@odoo/o-spreadsheet 19.3.17 → 19.3.18
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/o_spreadsheet.cjs +45 -14
- package/dist/o_spreadsheet.css +9 -3
- package/dist/o_spreadsheet.esm.js +45 -14
- package/dist/o_spreadsheet.iife.js +45 -14
- package/dist/o_spreadsheet.min.iife.js +4 -4
- package/dist/o_spreadsheet.xml +3 -3
- package/dist/types/collaborative/session.d.ts +3 -1
- package/dist/types/plugins/core/squisher.d.ts +3 -0
- package/dist/types/types/collaborative/transport_service.d.ts +1 -0
- package/package.json +1 -1
|
@@ -15,7 +15,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
15
15
|
`,e.endsWith(`{`)&&n++;return t.trim()}let Fc=Io.content,Ic={"=":`EQ`,"+":`ADD`,"-":`MINUS`,"*":`MULTIPLY`,"/":`DIVIDE`,">=":`GTE`,"<>":`NE`,">":`GT`,"<=":`LTE`,"<":`LT`,"^":`POWER`,"&":`CONCATENATE`},Lc={"-":`UMINUS`,"+":`UPLUS`,"%":`UNARY.PERCENT`,"#":`SPILLED.RANGE`},Rc={},zc=new Intl.Collator(`en`,{sensitivity:`accent`});var Bc=class e{sheetId;tokens;literalValues;symbols;isBadExpression;normalizedFormula;execute;rangeDependencies;hasDependencies;constructor(e,t,n,r,i,a,o,s){this.sheetId=e,this.tokens=t,this.literalValues=n,this.symbols=r,this.isBadExpression=a,this.normalizedFormula=o,this.execute=s,this.hasDependencies=i?.length>0,this.tokens.forEach(e=>{[`REFERENCE`,`NUMBER`,`STRING`,`INVALID_REFERENCE`].includes(e.type)&&(e.value=`__NO_REAL_VALUE__`)}),this.rangeDependencies=i}getTokens(e,t){let n=0,r=0,i=0;return this.isBadExpression||this.tokens.forEach(a=>{switch(a.type){case`REFERENCE`:case`INVALID_REFERENCE`:a.value=e.getRangeString(this.rangeDependencies[n++],this.sheetId,t);break;case`NUMBER`:a.value=this.literalValues.numbers[r++].value.toString();break;case`STRING`:a.value=`"${this.literalValues.strings[i++].value}"`;break}}),this.tokens}getAst(e){return Gs(this.getTokens(e))}toFormulaString(e,t){return this.isBadExpression?this.normalizedFormula:bt(this.getTokens(e,t).filter(e=>e.type!==`SPACE`).map(e=>e.value))}getNamedRangesInFormula(e){let t=[];for(let n=0;n<this.tokens.length;n++)if(Tc(this.tokens,n)){let r=e.getNamedRange(this.tokens[n].value);r&&t.push(r)}return t}usesSymbol(e){return this.symbols.some(t=>zc.compare(t,e)===0)}areAllFunctionsExportableToExcel(){return this.isBadExpression?!1:!qs(Gs(this.tokens)).some(e=>e.type===`FUNCALL`&&!Fc[e.value.toUpperCase()]?.isExported)}getFunctionsFromTokens(e,t){return this.isBadExpression||!e.some(e=>this.usesSymbol(e))?[]:qs(this.getAst(t)).filter(t=>t.type===`FUNCALL`&&e.includes(t.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}isFirstNonWhitespaceSymbol(e){let t=this.tokens.find((e,t)=>t>0&&e.type!==`SPACE`);return t?.type===`SYMBOL`&&t.value.toUpperCase()===e}adaptCompiledFormula(t,n){let r=[],i=!1;for(let e of this.rangeDependencies){let n=t(e);r.push(n.range),n.changeType!==`NONE`&&(i=!0)}let a=this.renameNamedRangeTokens(n);return i||a?new e(this.sheetId,a?.newTokens||this.tokens,this.literalValues,a?.newSymbols||this.symbols,r,this.isBadExpression,Uc(a?.newTokens||this.tokens),this.execute):this}renameNamedRangeTokens(e){let t=!1,n=[],r=[];for(let i=0;i<this.tokens.length;i++){let a=this.tokens[i];if(Tc(this.tokens,i)){let n=e(this.tokens[i].value);n!==this.tokens[i].value&&(t=!0,a={...this.tokens[i],value:n})}n.push(a),a.type===`SYMBOL`&&r.push(a.value)}return t?{newSymbols:r,newTokens:n}:void 0}static IsBadExpression(e){return Vc(Ms(e)).isBadExpression}static CopyWithDependencies(t,n,r){return new e(n,t.tokens,t.literalValues,t.symbols,r,t.isBadExpression,t.normalizedFormula,t.execute)}static CopyWithDependenciesAndLiteral(t,n,r,i,a){return new e(n,t.tokens,{numbers:i,strings:a},t.symbols,r,t.isBadExpression,t.normalizedFormula,t.execute)}static CompileForSerializedFormula(t,n){let r=Vc(n.tokens);return new e(t,n.tokens,n.literalValues,n.symbols,n.rangeDependencies,n.isBadExpression,n.normalizedFormula,r.execute)}static Compile(t,n,r){let i=Vc(Ms(t));return new e(n,i.tokens,i.literalValues,i.symbols,i.dependencies.map(e=>r.getRangeFromSheetXC(n,e)),i.isBadExpression,i.normalizedFormula,i.execute)}areRangeShapesInLineWithNormalizedFormula(){return Array.from(this.normalizedFormula.matchAll(/\|C\||\|R\|/g)).every((e,t)=>this.rangeDependencies[t].parts.length===1&&e[0]===`|C|`||this.rangeDependencies[t].parts.length===2&&e[0]===`|R|`||this.rangeDependencies[t].invalidXc||this.rangeDependencies[t].invalidSheetName)}};function Vc(e){try{return Hc(e)}catch(t){return{tokens:e,literalValues:{numbers:[],strings:[]},symbols:[],dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map(e=>e.value).join(``)}}}function Hc(e){let{dependencies:t,literalValues:n,symbols:r}=Wc(e),i=Uc(e);if(!Rc[i]){let t=Gs([...e]),n=new Mc,s=0,c=0,l=0;if(t.type===`BIN_OPERATION`&&t.value===`:`||t.type===`EMPTY`)throw new Fi(j(`Invalid formula`));let u=o(t),d=new Ac;d.append(u),d.append(`return ${u.returnExpression};`),Rc[i]=Function(`deps`,`ref`,`range`,`getSymbolValue`,`ctx`,d.toString());function a(e){let{args:t}=e,n=Fc[e.value.toUpperCase()];if(!n)throw new zi(j(`Unknown function: "%s"`,e.value));Gc(e);let r=[],i=Ci(n,t.length);for(let e=0;e<t.length;e++){let a=n.args[i[e].index],s=t[e],c=(a.type||[]).some(e=>Kc(e));r.push(o(s,c))}return r}function o(e,t=!1){let i=new Ac(n);switch(e.debug&&(i.append(`debugger;`),i.append(`ctx["debug"] = true;`)),e.type){case`BOOLEAN`:return i.return(`{ value: ${e.value} }`);case`NUMBER`:return i.return(`this.literalValues.numbers[${c++}]`);case`STRING`:return i.return(`this.literalValues.strings[${s++}]`);case`REFERENCE`:return i.return(`${e.value.includes(`:`)||t?`range`:`ref`}(deps[${l++}])`);case`FUNCALL`:let n=a(e).map(e=>e.assignResultToVariable());i.append(...n);let u=e.value.toUpperCase();return i.return(`ctx['${u}'](${n.map(e=>e.returnExpression)})`);case`ARRAY`:return o({type:`FUNCALL`,value:`ARRAY.LITERAL`,args:e.value.map(e=>({type:`FUNCALL`,value:`ARRAY.ROW`,args:e,tokenStartIndex:0,tokenEndIndex:0})),tokenStartIndex:0,tokenEndIndex:0});case`UNARY_OPERATION`:{let t=Lc[e.value],n=o(e.operand,e.value===`#`).assignResultToVariable();return i.append(n),i.return(`ctx['${t}'](${n.returnExpression})`)}case`BIN_OPERATION`:{let t=Ic[e.value],n=o(e.left,!1).assignResultToVariable(),r=o(e.right,!1).assignResultToVariable();return i.append(n),i.append(r),i.return(`ctx['${t}'](${n.returnExpression}, ${r.returnExpression})`)}case`SYMBOL`:let d=r.indexOf(e.value);return i.return(`getSymbolValue(this.symbols[${d}], ${t})`);case`EMPTY`:return i.return(`undefined`)}}}return{execute:Rc[i],dependencies:t,literalValues:n,symbols:r,tokens:e,isBadExpression:!1,normalizedFormula:i}}function Uc(e){let t=``;for(let n of e)switch(n.type){case`STRING`:t+=`|S|`;break;case`NUMBER`:t+=`|N|`;break;case`REFERENCE`:case`INVALID_REFERENCE`:n.value.includes(`:`)?t+=`|R|`:t+=`|C|`;break;case`SPACE`:break;default:t+=n.value;break}return t}function Wc(e){let t={numbers:[],strings:[]},n=[],r=[];for(let i of e)switch(i.type){case`INVALID_REFERENCE`:case`REFERENCE`:n.push(i.value);break;case`STRING`:let e=et(i.value);t.strings.push({value:e});break;case`NUMBER`:{let e=Ia(i.value,V);t.numbers.push({value:e});break}case`SYMBOL`:r.push(et(i.value,`'`))}return{dependencies:n,literalValues:t,symbols:r}}function Gc(e){let t=e.args.length,n=e.value.toUpperCase(),r=Fc[n],{nbrArgRepeating:i,minArgRequired:a}=r;if(t<a)throw new Fi(j(`Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.`,{functionName:n,minArgRequired:a,nbrArgSupplied:t}));if(t>r.maxArgPossible)throw new Fi(j(`Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.`,{functionName:n,maxArgPossible:r.maxArgPossible,nbrArgSupplied:t}));if(i>1){let e=i*Math.floor((t-a)/i),o=t-a-e-r.nbrOptionalNonRepeatingArgs;if(o>0)throw new Fi(j(`Invalid number of arguments for the %(functionName)s function. Repeatable arguments should be supplied in groups of %(nbrArgRepeating)s, with up to %(nbrArgOptional)s optional. Got %(nbrValueRemaining)s too many.`,{functionName:n,nbrArgRepeating:i,nbrArgOptional:r.nbrOptionalNonRepeatingArgs,nbrValueRemaining:o}))}}function Kc(e){return e.startsWith(`RANGE`)}let qc=function(e){return e.boolean=`boolean`,e.number=`number`,e.text=`text`,e.empty=`empty`,e.error=`error`,e}({});function Jc(e){e=e.replace(/\s/g,` `);let t=new Ut(e),n=[],r=[];for(n.push(r);!t.isOver();){if(t.current===`;`){r=[],n.push(r),t.shift();continue}let e=rl(t)||Yc(t)||Zc(t)||Qc(t)||el(t)||tl(t)||nl(t)||al(t)||$c(t)||ol(t);if(!e)throw Error(`Unknown token at `+t.remaining());r.push(e)}return n}function Yc(e){let t;if(e.current===`"`?(e.shift(),t=`"`):e.currentStartsWith(`[$`)&&(e.advanceBy(2),t=`]`),!t)return null;let n=``;for(;e.current&&e.current!==t;)n+=e.shift();if(e.current===t)e.shift();else throw Error(`Unterminated string in format`);return{type:`STRING`,value:n}}let Xc=new Set(`$+-/():!^&~{}<>= `);function Zc(e){if(e.current===`\\`){e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`CHAR`,value:t}}return Xc.has(e.current)?{type:`CHAR`,value:e.shift()}:null}function Qc(e){return e.current===`,`?(e.shift(),{type:`THOUSANDS_SEPARATOR`,value:`,`}):null}function $c(e){return e.current===`@`?(e.shift(),{type:`TEXT_PLACEHOLDER`,value:`@`}):null}function el(e){return e.current===`.`?(e.shift(),{type:`DECIMAL_POINT`,value:`.`}):null}function tl(e){return e.current===`%`?(e.shift(),{type:`PERCENT`,value:`%`}):null}function nl(e){return e.current===`e`?(e.shift(),{type:`SCIENTIFIC`,value:`e`}):null}function rl(e){if(e.current===`0`||e.current===`#`){let t=e.current;return e.shift(),{type:`DIGIT`,value:t}}return null}let il=new Set(`dmqyhsa`);function al(e){if(!il.has(e.current))return null;let t=e.current,n=``;for(;e.current===t;)n+=e.shift();return{type:`DATE_PART`,value:n}}function ol(e){if(e.current!==`*`)return null;e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`REPEATED_CHAR`,value:t}}let sl={};function cl(e){let t=sl[e];return t===void 0&&(t=ll(e),sl[e]=t),t}function ll(e){let t=Jc(e);for(let e of t){let t=e.filter(e=>e.type===`REPEATED_CHAR`);for(let e of t.slice(1))e.type=`CHAR`}let n=ml(t[0])||pl(t[0])||hl(t[0]);if(!n)throw Error(`Invalid first format part of: `+e);if(t.length>1&&n.type===`text`)throw Error(`The first format in a multi-part format must be a number format: `+e);let r=ml(t[1])||pl(t[1]);if(t[1]?.length&&!r)throw Error(`Invalid second format part of: `+e);let i=ml(t[2])||pl(t[2]);if(t[2]?.length&&!i)throw Error(`Invalid third format part of: `+e);let a=hl(t[3]);if(t[3]?.length&&!a)throw Error(`Invalid fourth format part of: `+e);return{positive:n,negative:r,zero:i,text:a}}function ul(e){return e.every(e=>e.type===`DATE_PART`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function dl(e){return e.every(e=>e.type===`DIGIT`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`PERCENT`||e.type===`SCIENTIFIC`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function fl(e){return e.every(e=>e.type===`STRING`||e.type===`TEXT_PLACEHOLDER`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function pl(e){if(!e||!dl(e))return;let t=[],n,r=t,i=0,a=!1,o=0,s=e.findLastIndex(e=>e.type===`DIGIT`),c=!1,l=0;for(let u=0;u<e.length;u++){let d=e[u];switch(d.type){case`DIGIT`:r===t?r.push(d):l<20&&(r.push(d),l++);break;case`DECIMAL_POINT`:if(r===t)n=[],r=n;else throw Error(`Multiple decimal points in a number format`);break;case`SCIENTIFIC`:a=!0;break;case`REPEATED_CHAR`:case`CHAR`:case`STRING`:r.push(d);break;case`PERCENT`:i++,r.push(d);break;case`THOUSANDS_SEPARATOR`:u-1===s?(o+=1,s++,r.push(d)):e[u+1]?.type===`DIGIT`&&e[u-1]?.type===`DIGIT`?(r===t&&(c=!0),r.push(d)):r.push({type:`CHAR`,value:`,`});break}}return{type:`number`,integerPart:t,decimalPart:n,percentSymbols:i,scientific:a,thousandsSeparator:c,magnitude:o}}function ml(e){let t=e&&ul(e)?{type:`date`,tokens:e}:void 0;if(!(!t||!e?.some(e=>e.type===`DATE_PART`))){if(t.tokens.length&&t.tokens.every(e=>e.type===`DATE_PART`&&e.value===`a`))throw Error(`Invalid date format`);return{type:`date`,tokens:gl(t.tokens.map(e=>e.type===`THOUSANDS_SEPARATOR`||e.type===`DECIMAL_POINT`?{type:`CHAR`,value:e.value}:e))}}}function hl(e){return e&&fl(e)?{type:`text`,tokens:e}:void 0}function gl(e){let t=e.filter(e=>e.type===`DATE_PART`);for(let e=0;e<t.length;e++)!t[e].value.startsWith(`m`)||t[e].value.length>2||(t[e-1]?.value.startsWith(`h`)||t[e+1]?.value.startsWith(`s`))&&(t[e].value=t[e].value.replaceAll(`m`,`M`));return e}function _l(e){return[vl(e.positive),vl(e.negative),vl(e.zero),vl(e.text)].filter(w).join(`;`)}function vl(e){if(!e)return;let t=``,n=e.type===`number`?yl(e):e.tokens;for(let e of n)switch(e.type){case`STRING`:t+=`[$${e.value}]`;break;case`CHAR`:t+=bl(e.value)?`\\${e.value}`:e.value;break;case`REPEATED_CHAR`:t+=`*`+e.value;break;case`DATE_PART`:t+=e.value===`MM`?`mm`:e.value;break;default:t+=e.value}return t}function yl(e){let t=[...e.integerPart];return e.decimalPart&&(t.push({type:`DECIMAL_POINT`,value:`.`}),t.push(...e.decimalPart)),e.scientific&&t.push({type:`SCIENTIFIC`,value:`e`}),t}function bl(e){return!Xc.has(e)}let xl=`REPEATED_CHAR_PLACEHOLDER_`,Sl={0:j(`January`),1:j(`February`),2:j(`March`),3:j(`April`),4:j(`May`),5:j(`June`),6:j(`July`),7:j(`August`),8:j(`September`),9:j(`October`),10:j(`November`),11:j(`December`)},Cl={0:j(`Sunday`),1:j(`Monday`),2:j(`Tuesday`),3:j(`Wednesday`),4:j(`Thursday`),5:j(`Friday`),6:j(`Saturday`)};function wl(e,t,n,r=!1){return r?Zl({value:e,format:t},n):H(e,{format:t,locale:n})}function H(e,{format:t,locale:n,formatWidth:r}){switch(typeof e==`boolean`&&(e=e?`TRUE`:`FALSE`),typeof e){case`string`:{if(e.includes(`\\"`)&&(e=e.replaceAll(/\\"/g,`"`)),!t)return e;let n=cl(t),i=Tl(e,n).format;return!i||i.type!==`text`?e:El(e,i,r)}case`number`:t||=Hl(e);let i=cl(t),{format:a,isNegativeFormat:o}=Tl(e,i);if(!a)return e.toString();if(a.type===`text`)return El(e.toString(),a,r);if(o&&(e=Math.abs(e)),a.type===`date`)return Dl(zl(e,a),r);let s=e<0,c=Dl(Ol(Math.abs(e),a,n),r);return s?`-`+c:c;case`object`:return``}}function Tl(e,t){let n,r=!1;switch(typeof e){case`number`:e<0&&t.negative?(n=t.negative,r=!0):n=e===0&&t.zero?t.zero:t.positive;break;case`string`:let i=t.text||t.positive;i.type===`text`&&(n=i);break}return{format:n,isNegativeFormat:r}}function El(e,t,n){let r=``;for(let n of t.tokens)switch(n.type){case`TEXT_PLACEHOLDER`:r+=e;break;case`CHAR`:case`STRING`:r+=n.value;break;case`REPEATED_CHAR`:r+=xl+n.value;break}return Dl(r,n)}function Dl(e,t){let n=e.indexOf(xl);if(n===-1)return e;let r=e.slice(0,n),i=e.slice(n+26+1),a=e[n+26];function o(){if(!t)return{timesToRepeat:0,padding:``};let e=t.measureText(r+i),n=t.measureText(a),o=t.availableWidth-e;if(o<=0)return{timesToRepeat:0,padding:``};let s=Math.floor(o/n),c=o-s*n,l=t.measureText(` `);return{timesToRepeat:s,padding:` `.repeat(Math.floor(c/l))}}let{timesToRepeat:s,padding:c}=o();return r+a.repeat(s)+c+i}function Ol(e,t,n){if(!t.integerPart.length&&!t.decimalPart?.length)return``;if(e===1/0)return`∞`+(t.percentSymbols?`%`:``);let r=Math.floor(Math.log10(Math.abs(e)));r===-1/0&&(r=0),t.scientific&&(e/=10**r);let i=t.percentSymbols*2-t.magnitude*3;e*=10**i;let a=0;t.decimalPart!==void 0&&(a=t.decimalPart.filter(e=>e.type===`DIGIT`).length);let{integerDigits:o,decimalDigits:s}=Ml(Math.abs(e),a),c=!!t.decimalPart?.some(e=>e.type===`DIGIT`),l=kl(o,t,t.thousandsSeparator?n.thousandsSeparator:void 0,c,n);if(t.decimalPart!==void 0&&(l+=n.decimalSeparator+Al(s||``,t)),t.scientific){let e=Math.abs(r).toString().padStart(2,`0`);l+=`e`+(r>=0?`+`:`-`)+e}return l}function kl(e,t,n,r,i){let a=t.integerPart;r&&!a.some(e=>e.type===`DIGIT`)&&(a=[...a,{type:`DIGIT`,value:`#`}]),e===`0`&&(e=``);let o=``,s=a.findIndex(e=>e.type===`DIGIT`),c=e.length-1;function l(t,r){if(r===`0`&&(t||=`0`),!t)return;let a=e.length-1-c,s=uu(i.digitGrouping||`[3,0]`);o=n&&s.has(a-1)?t+n+o:t+o}for(let t=a.length-1;t>=0;t--){let n=a[t];switch(n.type){case`DIGIT`:let r=e[c];if(l(r,n.value),c--,s===t)for(;c>=0;)l(e[c],`0`),c--;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:o=xl+n.value+o;break;default:o=n.value+o;break}}return o}function Al(e,t){if(!t.decimalPart)return``;let n=``,r=0;for(let i of t.decimalPart)switch(i.type){case`DIGIT`:let t=i.value===`#`?e[r]||``:e[r]||`0`;n+=t,r++;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:n+=xl+i.value;break;default:n+=i.value;break}return n}let jl=[];function Ml(e,t=20){let n=e.toString();if(n.includes(`e`))return Il(e,t);if(Number.isInteger(e))return{integerDigits:n,decimalDigits:void 0};let r=n.indexOf(`.`),i=n.substring(0,r),a=n.substring(r+1);if(t===0)return Number(a[0])>=5&&(i=(Number(i)+1).toString()),{integerDigits:i,decimalDigits:void 0};if(a.length>t){let{integerDigits:e,decimalDigits:n}=Fl(a,t);a=n,e!==`0`&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:Nl(a||``)}}function Nl(e){let t=e.length-1;for(;t>=0&&e[t]===`0`;)t--;return e.slice(0,t+1)||void 0}let Pl=/^0+/;function Fl(e,t){let n=`0`,r=e,i=e.slice(0,t);if(Number(e[t])<5)return{integerDigits:n,decimalDigits:i};let a=i.match(Pl)?.[0]||``,o=(Number(i)+1).toString(),s=i.slice(a.length),c=o.length>s.length;return c&&!a?(n=`1`,r=void 0):r=c?a.slice(0,-1)+o:a+o,{integerDigits:n,decimalDigits:r}}function Il(e,t=20){let n=jl[t];n||(n=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:t,useGrouping:!1}),jl[t]=n);let[r,i]=n.format(e).split(`.`);return{integerDigits:r,decimalDigits:i}}function Ll(e,t){let{integerDigits:n,decimalDigits:r}=Ml(e,20);return r?n+t+r:n}let Rl=Pt(function(e){if(!e)return!1;try{return cl(e).positive.type===`date`}catch{return!1}});function zl(e,t){let n=ma(e);if(isNaN(n.getTime()))return e.toString();let r=t.tokens.some(e=>e.type===`DATE_PART`&&e.value===`a`),i=``;for(let e of t.tokens)switch(e.type){case`DATE_PART`:i+=Bl(n,e.value,r);break;case`REPEATED_CHAR`:i+=xl+e.value;break;default:i+=e.value;break}return i}function Bl(e,t,n){switch(t){case`d`:return e.getDate();case`dd`:return e.getDate().toString().padStart(2,`0`);case`ddd`:return Cl[e.getDay()].slice(0,3);case`dddd`:return Cl[e.getDay()].toString();case`m`:return e.getMonth()+1;case`mm`:return String(e.getMonth()+1).padStart(2,`0`);case`mmm`:return Sl[e.getMonth()].slice(0,3);case`mmmm`:return Sl[e.getMonth()].toString();case`mmmmm`:return Sl[e.getMonth()].slice(0,1);case`qq`:return j(`Q%(quarter)s`,{quarter:e.getQuarter()}).toString();case`qqqq`:return j(`Quarter %(quarter)s`,{quarter:e.getQuarter()}).toString();case`yy`:let r=String(e.getFullYear()).replace(`-`,``).padStart(2,`0`);return r.slice(r.length-2);case`yyyy`:return String(e.getFullYear()).replace(`-`,``).padStart(4,`0`);case`hhhh`:return Math.floor((e.getTime()-Ui.getTime())/(3600*1e3)).toString();case`hh`:let i=e.getHours();return n&&(i=i===0?12:i>12?i-12:i),i.toString().padStart(2,`0`);case`MM`:return e.getMinutes().toString().padStart(2,`0`);case`ss`:return e.getSeconds().toString().padStart(2,`0`);case`a`:return e.getHours()>=12?`PM`:`AM`;default:throw Error(`invalid date format token: ${t}`)}}let Vl=Pt(function(e){return RegExp(`[0-9]+${Ze(e.decimalSeparator)}[0-9]`)});function Hl(e){let{integerDigits:t,decimalDigits:n}=Ml(e);if(!n)return`0`;let r=t.replace(`-`,``).length;if(r+2>11)return`0`;let i=11-r-1;return{decimalDigits:n}=Ml(e,Math.min(i,n.length)),n?`0.`+`0`.repeat(n.length):`0`}function Ul(e,t){if(na(e,t))return ia(e,t).format}function Wl(e){let t=e.includes(`.`)?`0.00`:`0`,n=e.match(/[\$€]/);if(n){let r=e.match(/[\d]/),i=`[$`+n.values().next().value+`]`;return r.index<n.index?`#,##`+t+i:i+`#,##`+t}if(e.includes(`%`))return t+`%`}function Gl(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),Jl(o,n,a)}function Kl(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),[ql(o,n,` ${a} `),ql(o,n,`(${a})`),ql(o,n,` - `)].join(`;`)}function ql(e,t,n){let r=`[$${e}]`;return t===`before`?r+`* `+n:n+`* `+r}function Jl(e,t,n){let r=`[$${e}]`;return t===`before`?r+n:n+r}function Yl(e){let t=cl(e);return _l({positive:Xl(t.positive),negative:t.negative?Xl(t.negative):void 0,zero:t.zero?Xl(t.zero):void 0,text:t.text})}function Xl(e){if(e.type!==`number`||!e.decimalPart)return e;let t=e.decimalPart.filter(e=>e.type!==`DIGIT`);return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...t]}}function Zl({value:e,format:t},n){let r=Ga(e,n);if(r===void 0)return``;let i=t;if(Math.abs(r)<1e3){let e=r%1!=0;i=!t&&e?Math.abs(r)<.01?`0.00e`:`0.##`:t}else i=Ql({value:e,format:t},void 0,n);return H(e,{format:i,locale:n})}function Ql(e,t,n){let r=0;try{r=Math.abs(I(e?.value,n))}catch{return``}let i=e?.format;if(t!==void 0)switch(t?.value){case`k`:return $l(i,1,`k`);case`m`:return $l(i,2,`m`);case`b`:return $l(i,3,`b`);default:throw new N(j(`The formatting unit should be 'k', 'm' or 'b'.`))}return r<1e5?$l(i,0,``):r<1e8?$l(i,1,`k`):r<1e11?$l(i,2,`m`):r<0x5af3107a4000?$l(i,3,`b`):`0.00e`}function $l(e,t,n){let r=cl(e||`#,##0`);return _l({positive:eu(r.positive,t,n),negative:r.negative?eu(r.negative,t,n):void 0,zero:r.zero?eu(r.zero,t,n):void 0,text:r.text})}function eu(e,t,n){if(e.type!==`number`||e.scientific)return e;let r=Xl(e),i={type:`STRING`,value:n},a=[...r.integerPart],o=a.findLastIndex(e=>e.type===`DIGIT`);if(o===-1)return e;for(;a[o+1]?.type===`THOUSANDS_SEPARATOR`;)a=Ft(a,[o+1]);let s=a[o+1];a=s?.type===`STRING`&&[`m`,`k`,`b`].includes(s.value)?Lt(a,i,o+1):It(a,[i],o+1),t>0&&(a=It(a,Array(t).fill({type:`THOUSANDS_SEPARATOR`,value:`,`}),o+1));let c=r.percentSymbols-a.filter(e=>e.type===`PERCENT`).length;return a.push(...Array(c).fill({type:`PERCENT`,value:`%`})),{...r,integerPart:a,magnitude:t}}function tu(e,t){let n=cl(e);return _l(cl(_l({positive:nu(n.positive,t),negative:n.negative?nu(n.negative,t):void 0,zero:n.zero?nu(n.zero,t):void 0,text:n.text})))}function nu(e,t){return e.type===`number`?t>0?iu(e,t):ru(e,Math.abs(t)):e}function ru(e,t){let n=e.decimalPart;if(!n)return e;let r=[],i=0;for(let e=n.length-1;e>=0&&!(i>=Math.abs(t));e--)n[e].type===`DIGIT`&&(i++,r.push(e));return n=Ft(n,r),n.some(e=>e.type===`DIGIT`)?{...e,decimalPart:n}:{...e,decimalPart:void 0,integerPart:[...e.integerPart,...n]}}function iu(e,t){let n=e.integerPart,r=e.decimalPart;if(!r){let e=n.findLastIndex(e=>e.type===`DIGIT`);r=n.slice(e+1),n=n.slice(0,e+1)}let i=C(0,t).map(()=>({type:`DIGIT`,value:`0`})),a=r.findLastIndex(e=>e.type===`DIGIT`);return r=a===-1?[...i,...r]:It(r,i,a+1),{...e,decimalPart:r,integerPart:n}}function au(e){let t=cl(e);for(let e of[t.positive,t.negative,t.zero])if(e&&e.type===`date`&&e.tokens.some(e=>e.type===`DATE_PART`&&e.value.includes(`q`)))return!1;return!0}function ou(e){if(!e)return!1;try{return cl(e).positive.type===`text`}catch{return!1}}function su(e,t){if(!t)return!1;try{let{format:n}=Tl(e,cl(t));if(n?.type===`text`||n?.type===`date`)return n.tokens.some(e=>e.type===`REPEATED_CHAR`);if(n?.type===`number`)return n.integerPart.some(e=>e.type===`REPEATED_CHAR`)||(n.decimalPart?n.decimalPart.some(e=>e.type===`REPEATED_CHAR`):!1)}catch{}return!1}function cu(e){try{return H(0,{format:e,locale:V}),!0}catch{return!1}}function lu(e){return Jc(e).length}let uu=Pt(function(e){let t=e.trim();if(!t.startsWith(`[`)||!t.endsWith(`]`))throw Error(`Invalid digit grouping: "${e}"`);let n=t.slice(1,-1).split(`,`).map(e=>Number(e));if(n.length===0||n.some(e=>isNaN(e)||e<0)||n[0]===0)throw Error(`Invalid digit grouping: "${e}"`);let r=new Set,i=0,a=-1;do a+=n[i],r.add(a),i=n[i+1]===0?i:i+1;while(a<=30&&n[i]!==void 0);return r});function du(e){return`sheetId`in e}function fu(e){return`dimension`in e&&`sheetId`in e&&`elements`in e}function pu(e){return`target`in e&&`sheetId`in e}function mu(e){return`ranges`in e}function hu(e){return`col`in e&&`row`in e&&`sheetId`in e}function gu(e){return`sheetId`in e&&`zone`in e}let _u=new Set([`RENAME_SHEET`,`DELETE_SHEET`,`CREATE_SHEET`,`DUPLICATE_SHEET`,`ADD_COLUMNS_ROWS`,`REMOVE_COLUMNS_ROWS`,`UNDO`,`REDO`,`ADD_MERGE`,`REMOVE_MERGE`,`UPDATE_LOCALE`,`ADD_PIVOT`,`UPDATE_PIVOT`,`INSERT_PIVOT`,`RENAME_PIVOT`,`REMOVE_PIVOT`,`DUPLICATE_PIVOT`,`CREATE_NAMED_RANGE`,`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`]),vu=new Set([`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`UPDATE_CELL`,`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`UNDO`,`REDO`]),yu=new Set([`MOVE_RANGES`]),bu=new Set([`EVALUATE_CELLS`,`ADD_CONDITIONAL_FORMAT`,`REMOVE_CONDITIONAL_FORMAT`,`CHANGE_CONDITIONAL_FORMAT_PRIORITY`]),xu=new Set([`AUTOFILL_CELL`,`SET_BORDER`,`SET_ZONE_BORDERS`,`SET_BORDERS_ON_TARGET`]),Su=new Set([`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`]),Cu=new Set([`START`,`ACTIVATE_SHEET`,`COPY`,`RESIZE_SHEETVIEW`,`SET_VIEWPORT_OFFSET`,`SET_ZOOM`,`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`SET_FORMULA_VISIBILITY`,`UPDATE_FILTER`,`UPDATE_CHART`,`UPDATE_CHART_REGION`,`UPDATE_CAROUSEL_ACTIVE_ITEM`,`UPDATE_PIVOT`]),wu=new Set(`LOCK_SHEET.UNLOCK_SHEET.MOVE_SHEET.DUPLICATE_SHEET.CREATE_SHEET.HIDE_SHEET.SHOW_SHEET.COPY.START.SCROLL_TO_CELL.ACTIVATE_SHEET.RESIZE_SHEETVIEW.SET_VIEWPORT_OFFSET.SET_FORMULA_VISIBILITY.SELECT_FIGURE.EVALUATE_CHARTS.EVALUATE_CELLS.REQUEST_UNDO.REQUEST_REDO.REPLACE_SEARCH.SET_ZOOM.UPDATE_CAROUSEL_ACTIVE_ITEM.DUPLICATE_PIVOT_IN_NEW_SHEET.UPDATE_FILTER.ACTIVATE_NEXT_SHEET.ACTIVATE_PREVIOUS_SHEET.SCROLL_TO_CELL.SHIFT_VIEWPORT_DOWN.SHIFT_VIEWPORT_UP`.split(`.`)),Tu=new Set(`UPDATE_CELL.UPDATE_CELL_POSITION.CLEAR_CELL.CLEAR_CELLS.DELETE_CONTENT.ADD_COLUMNS_ROWS.REMOVE_COLUMNS_ROWS.RESIZE_COLUMNS_ROWS.HIDE_COLUMNS_ROWS.UNHIDE_COLUMNS_ROWS.SET_GRID_LINES_VISIBILITY.UNFREEZE_COLUMNS.UNFREEZE_ROWS.FREEZE_COLUMNS.FREEZE_ROWS.UNFREEZE_COLUMNS_ROWS.ADD_MERGE.REMOVE_MERGE.CREATE_SHEET.DELETE_SHEET.DUPLICATE_SHEET.MOVE_SHEET.RENAME_SHEET.COLOR_SHEET.HIDE_SHEET.SHOW_SHEET.LOCK_SHEET.UNLOCK_SHEET.MOVE_RANGES.ADD_CONDITIONAL_FORMAT.REMOVE_CONDITIONAL_FORMAT.CHANGE_CONDITIONAL_FORMAT_PRIORITY.CREATE_FIGURE.DELETE_FIGURE.UPDATE_FIGURE.CREATE_CAROUSEL.UPDATE_CAROUSEL.SET_FORMATTING.CLEAR_FORMATTING.SET_BORDER.SET_ZONE_BORDERS.SET_BORDERS_ON_TARGET.CREATE_CHART.UPDATE_CHART.DELETE_CHART.CREATE_TABLE.REMOVE_TABLE.UPDATE_TABLE.CREATE_TABLE_STYLE.REMOVE_TABLE_STYLE.CREATE_IMAGE.GROUP_HEADERS.UNGROUP_HEADERS.UNFOLD_HEADER_GROUP.FOLD_HEADER_GROUP.FOLD_ALL_HEADER_GROUPS.UNFOLD_ALL_HEADER_GROUPS.UNFOLD_HEADER_GROUPS_IN_ZONE.FOLD_HEADER_GROUPS_IN_ZONE.ADD_DATA_VALIDATION_RULE.REMOVE_DATA_VALIDATION_RULE.UPDATE_LOCALE.CREATE_NAMED_RANGE.UPDATE_NAMED_RANGE.DELETE_NAMED_RANGE.ADD_PIVOT.UPDATE_PIVOT.INSERT_PIVOT.RENAME_PIVOT.REMOVE_PIVOT.DUPLICATE_PIVOT`.split(`.`));function Eu(e){return Tu.has(e.type)}function Du(e){return Cu.has(e.type)}var Ou=class{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>e!==`Success`)}static get Success(){return ku}get isSuccessful(){return this.reasons.length===0}isCancelledBecause(e){return this.reasons.includes(e)}};let ku=new Ou,Au=function(e){return e.Success=`Success`,e.CancelledForUnknownReason=`CancelledForUnknownReason`,e.WillRemoveExistingMerge=`WillRemoveExistingMerge`,e.CannotMoveTableHeader=`CannotMoveTableHeader`,e.MergeIsDestructive=`MergeIsDestructive`,e.CellIsMerged=`CellIsMerged`,e.InvalidTarget=`InvalidTarget`,e.EmptyUndoStack=`EmptyUndoStack`,e.EmptyRedoStack=`EmptyRedoStack`,e.NotEnoughElements=`NotEnoughElements`,e.NotEnoughSheets=`NotEnoughSheets`,e.MissingSheetName=`MissingSheetName`,e.UnchangedSheetName=`UnchangedSheetName`,e.DuplicatedSheetName=`DuplicatedSheetName`,e.DuplicatedSheetId=`DuplicatedSheetId`,e.ForbiddenCharactersInSheetName=`ForbiddenCharactersInSheetName`,e.WrongSheetMove=`WrongSheetMove`,e.WrongSheetPosition=`WrongSheetPosition`,e.InvalidAnchorZone=`InvalidAnchorZone`,e.SelectionOutOfBound=`SelectionOutOfBound`,e.TargetOutOfSheet=`TargetOutOfSheet`,e.WrongCutSelection=`WrongCutSelection`,e.WrongPasteSelection=`WrongPasteSelection`,e.WrongPasteOption=`WrongPasteOption`,e.WrongFigurePasteOption=`WrongFigurePasteOption`,e.EmptyClipboard=`EmptyClipboard`,e.EmptyRange=`EmptyRange`,e.EmptyTarget=`EmptyTarget`,e.InvalidRange=`InvalidRange`,e.InvalidZones=`InvalidZones`,e.InvalidSheetId=`InvalidSheetId`,e.InvalidCellId=`InvalidCellId`,e.InvalidFigureId=`InvalidFigureId`,e.InputAlreadyFocused=`InputAlreadyFocused`,e.MaximumRangesReached=`MaximumRangesReached`,e.MinimumRangesReached=`MinimumRangesReached`,e.InvalidChartDefinition=`InvalidChartDefinition`,e.InvalidDataSet=`InvalidDataSet`,e.InvalidLabelRange=`InvalidLabelRange`,e.InvalidScorecardKeyValue=`InvalidScorecardKeyValue`,e.InvalidScorecardBaseline=`InvalidScorecardBaseline`,e.InvalidGaugeDataRange=`InvalidGaugeDataRange`,e.EmptyGaugeRangeMin=`EmptyGaugeRangeMin`,e.GaugeRangeMinNaN=`GaugeRangeMinNaN`,e.EmptyGaugeRangeMax=`EmptyGaugeRangeMax`,e.GaugeRangeMaxNaN=`GaugeRangeMaxNaN`,e.GaugeLowerInflectionPointNaN=`GaugeLowerInflectionPointNaN`,e.GaugeUpperInflectionPointNaN=`GaugeUpperInflectionPointNaN`,e.InvalidAutofillSelection=`InvalidAutofillSelection`,e.MinBiggerThanMax=`MinBiggerThanMax`,e.LowerBiggerThanUpper=`LowerBiggerThanUpper`,e.MidBiggerThanMax=`MidBiggerThanMax`,e.MinBiggerThanMid=`MinBiggerThanMid`,e.FirstArgMissing=`FirstArgMissing`,e.SecondArgMissing=`SecondArgMissing`,e.MinNaN=`MinNaN`,e.MidNaN=`MidNaN`,e.MaxNaN=`MaxNaN`,e.ValueUpperInflectionNaN=`ValueUpperInflectionNaN`,e.ValueLowerInflectionNaN=`ValueLowerInflectionNaN`,e.MinInvalidFormula=`MinInvalidFormula`,e.MidInvalidFormula=`MidInvalidFormula`,e.MaxInvalidFormula=`MaxInvalidFormula`,e.ValueUpperInvalidFormula=`ValueUpperInvalidFormula`,e.ValueLowerInvalidFormula=`ValueLowerInvalidFormula`,e.InvalidSortAnchor=`InvalidSortAnchor`,e.InvalidSortZone=`InvalidSortZone`,e.SortZoneWithArrayFormulas=`SortZoneWithArrayFormulas`,e.WaitingSessionConfirmation=`WaitingSessionConfirmation`,e.MergeOverlap=`MergeOverlap`,e.TooManyHiddenElements=`TooManyHiddenElements`,e.Readonly=`Readonly`,e.InvalidViewportSize=`InvalidViewportSize`,e.InvalidScrollingDirection=`InvalidScrollingDirection`,e.ViewportScrollLimitsReached=`ViewportScrollLimitsReached`,e.FigureDoesNotExist=`FigureDoesNotExist`,e.InvalidConditionalFormatId=`InvalidConditionalFormatId`,e.InvalidConditionalFormatType=`InvalidConditionalFormatType`,e.InvalidCellPopover=`InvalidCellPopover`,e.EmptySelectedRange=`EmptySelectedRange`,e.InvalidFreezeQuantity=`InvalidFreezeQuantity`,e.FrozenPaneOverlap=`FrozenPaneOverlap`,e.ValuesNotChanged=`ValuesNotChanged`,e.InvalidFilterZone=`InvalidFilterZone`,e.TableNotFound=`TableNotFound`,e.TableOverlap=`TableOverlap`,e.InvalidTableConfig=`InvalidTableConfig`,e.InvalidTableStyle=`InvalidTableStyle`,e.FilterNotFound=`FilterNotFound`,e.MergeInTable=`MergeInTable`,e.NonContinuousTargets=`NonContinuousTargets`,e.DuplicatedFigureId=`DuplicatedFigureId`,e.InvalidSelectionStep=`InvalidSelectionStep`,e.DuplicatedChartId=`DuplicatedChartId`,e.ChartDoesNotExist=`ChartDoesNotExist`,e.InvalidHeaderIndex=`InvalidHeaderIndex`,e.InvalidQuantity=`InvalidQuantity`,e.MoreThanOneColumnSelected=`MoreThanOneColumnSelected`,e.EmptySplitSeparator=`EmptySplitSeparator`,e.SplitWillOverwriteContent=`SplitWillOverwriteContent`,e.NoSplitSeparatorInSelection=`NoSplitSeparatorInSelection`,e.NoActiveSheet=`NoActiveSheet`,e.InvalidLocale=`InvalidLocale`,e.MoreThanOneRangeSelected=`MoreThanOneRangeSelected`,e.NoColumnsProvided=`NoColumnsProvided`,e.ColumnsNotIncludedInZone=`ColumnsNotIncludedInZone`,e.DuplicatesColumnsSelected=`DuplicatesColumnsSelected`,e.InvalidHeaderGroupStartEnd=`InvalidHeaderGroupStartEnd`,e.HeaderGroupAlreadyExists=`HeaderGroupAlreadyExists`,e.UnknownHeaderGroup=`UnknownHeaderGroup`,e.UnknownDataValidationRule=`UnknownDataValidationRule`,e.UnknownDataValidationCriterionType=`UnknownDataValidationCriterionType`,e.InvalidDataValidationCriterionValue=`InvalidDataValidationCriterionValue`,e.InvalidNumberOfCriterionValues=`InvalidNumberOfCriterionValues`,e.InvalidCopyPasteSelection=`InvalidCopyPasteSelection`,e.NoChanges=`NoChanges`,e.InvalidInputId=`InvalidInputId`,e.SheetIsHidden=`SheetIsHidden`,e.InvalidTableResize=`InvalidTableResize`,e.PivotIdNotFound=`PivotIdNotFound`,e.PivotIdTaken=`PivotIdTaken`,e.PivotInError=`PivotInError`,e.EmptyName=`EmptyName`,e.ValueCellIsInvalidFormula=`ValueCellIsInvalidFormula`,e.InvalidDefinition=`InvalidDefinition`,e.InvalidColor=`InvalidColor`,e.InvalidPivotDataSet=`InvalidPivotDataSet`,e.InvalidPivotCustomField=`InvalidPivotCustomField`,e.MissingFigureArguments=`MissingFigureArguments`,e.InvalidCarouselItem=`InvalidCarouselItem`,e.SheetLocked=`SheetLocked`,e.InvalidZoomLevel=`InvalidZoomLevel`,e.NamedRangeNameAlreadyExists=`NamedRangeNameAlreadyExists`,e.NamedRangeInvalidName=`NamedRangeInvalidName`,e.NamedRangeNameLooksLikeCellReference=`NamedRangeNameLooksLikeCellReference`,e.NamedRangeNotFound=`NamedRangeNotFound`,e.SubCommandOnly=`SubCommandOnly`,e}({});function ju(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}let Mu=new A;function Nu(e,t){return e=ju(e),{url:e,label:t||e,isExternal:!0,isUrlEditable:!0}}Mu.add(`sheet_URL`,{match:e=>pt(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){let n=ht(e);return t.tryGetSheetName(n)||j(`Invalid sheet`)},open(e,t){let n=ht(e);t.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:n}).isCancelledBecause(`SheetIsHidden`)&&t.notifyUser({type:`warning`,sticky:!1,text:j(`Cannot open the link because the linked sheet is hidden.`)})},sequence:0,title:j(`Sheets`),getLinkProposals(e){return e.model.getters.getSheetIds().map(t=>{let n=e.model.getters.getSheet(t);return{...this.createLink(mt(t),n.name),icon:`o-spreadsheet-Icon.INSERT_SHEET`}})}});let Pu={createLink:Nu,match:e=>lt(e),open:e=>window.open(e,`_blank`),urlRepresentation:e=>e,sequence:0,title:j(`Web`)};function Fu(e){return Mu.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||Pu}function Iu(e,t){return Fu(e.url).urlRepresentation(e.url,t)}function Lu(e,t,n){Fu(e.url).open(e.url,t,n)}function Ru(e){if(typeof e==`string`){if(ct(e)){let{label:t,url:n}=dt(e);return Fu(n).createLink(n,t)}else if(lt(e))return Nu(e)}}function zu(e,t,n){return Gu({value:ou(t.format)&&e.parsedValue!==null?e.content:e.parsedValue,format:t.format,origin:n},t.locale,n)}function Bu(e,t,n,r,i,a,o){return n.startsWith(`=`)?Hu(e,t,n,r,i,a):Vu(e,t,n,r,i,o)}function Vu(e,t,n,r,i,a){let o=e.getLocale(),s=Wu(n,o);if(!r&&typeof s==`number`){let e=Ul(n,o);if(a?.avoidAutomaticDateFormat&&e)return{id:t,content:n,style:i,format:r,isFormula:!1,parsedValue:n};r=e||Wl(n)}else r||=void 0;return!ou(r)&&!n.startsWith(`'`)&&!F(n)&&(n=L(s)),{id:t,content:n,style:i,format:r,isFormula:!1,parsedValue:s}}function Hu(e,t,n,r,i,a){return Uu(t,Bc.Compile(n,a,e),r,i)}function Uu(e,t,n,r){return{id:e,format:n,style:r,isFormula:!0,compiledFormula:t}}function Wu(e,t){if(e.startsWith(`=`))throw Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e.startsWith(`'`))return e.slice(1);if(e===``)return null;if(e.includes(`
|
|
16
16
|
`))return e;if(Pa(e,V))return Ia(e,V);let n=ia(e,t);return n?n.value:at(e)?e.toUpperCase()===`TRUE`:e}function Gu(e,t=V,n,r){let i=Ru(e.value);if(!i)return nd(Ku(e,t,n,r),e.origin??n);let a=Wu(i.label,t);return nd({...Ku({value:a,format:e.format||(typeof a==`number`?Ul(i.label,t)||Wl(i.label):void 0)},t,n,r),link:i},e.origin??n)}function Ku(e,t,n,r){let{value:i,format:a,message:o,errorOriginPosition:s}=e;a=r?.format||a;let c=H(i,{format:a,locale:t});return F(i)?td(i,o,n,s):i===null?Qu(a):ou(a)?Xu(L(i),a,c,n):typeof i==`number`?Rl(a||``)?$u(i,a,c,n):Zu(i,a,c,n):typeof i==`boolean`?ed(i,a,c,n):Xu(i,a,c,n)}function U(e){return!!e&&Yu(e)===`number`}function qu(e){return!!e&&Yu(e)===`text`}function Ju(e){return!!e&&Yu(e)===`error`}function Yu({value:e,format:t}){if(e===null)return`empty`;if(F(e))return`error`;if(ou(t))return`text`;switch(typeof e){case`number`:return`number`;case`boolean`:return`boolean`;case`string`:return`text`}}function Xu(e,t,n,r){return{value:e,format:t,formattedValue:n,position:r,type:`text`,isAutoSummable:!0,defaultAlign:`left`}}function Zu(e,t,n,r){return{value:e||0,format:t,formattedValue:n,position:r,type:`number`,isAutoSummable:!0,defaultAlign:`right`}}let Qu=Pt(function(e){return{value:null,format:e,formattedValue:``,type:`empty`,isAutoSummable:!0,defaultAlign:`left`}});function $u(e,t,n,r){return{value:e,format:t,formattedValue:n,position:r,type:`number`,isAutoSummable:!1,defaultAlign:`right`}}function ed(e,t,n,r){return{value:e,format:t,formattedValue:n,position:r,type:`boolean`,isAutoSummable:!1,defaultAlign:`center`}}function td(e,t,n,r){return{value:e,formattedValue:e,message:t,position:n,type:`error`,isAutoSummable:!1,defaultAlign:`center`,errorOriginPosition:r}}function nd(e,t){return e.value===null||`origin`in e||(e.origin=t),e}function rd(e){let t=P.now();switch(e){case`today`:return Math.floor(ga(t));case`yesterday`:return t.setDate(t.getDate()-1),Math.floor(ga(t));case`tomorrow`:return t.setDate(t.getDate()+1),Math.floor(ga(t));case`lastWeek`:return t.setDate(t.getDate()-6),Math.floor(ga(t));case`lastMonth`:{let e=t.getMonth()===0?11:t.getMonth()-1,n=new P(t.getFullYear(),e,1);return t.getDate()>_a(n)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(ga(t))}case`lastYear`:return t.getMonth()===1&&t.getDate()===29?(t.setDate(28),t.setFullYear(t.getFullYear()-1)):(t.setDate(t.getDate()+1),t.setFullYear(t.getFullYear()-1)),Math.floor(ga(t))}}function id(e,t){return`dateValue`in e&&e.dateValue!==`exactDate`?[rd(e.dateValue)]:e.values.map(e=>ta(e,t))}function ad(e,t){return e.map(e=>{if(e.startsWith(`=`))return e;let n=Wu(e,t);return typeof n==`number`?H(n,{format:t.dateFormat,locale:t}):``})}let od=new WeakMap,sd=new WeakMap;function cd(e,t){od.has(t)||(od.set(t,new Map),sd.set(t,0));let n=od.get(t),r=dd(e);if(n.has(r)){let i=n.get(r);return t[i]=e,i}let i=sd.get(t)+1;return n.set(r,i),sd.set(t,i),t[i]=e,i}function ld(e){let t={};for(let n in e){let r=cn(e[n].map(D));for(let e of r)t[wn(e)]=Number(n)}return t}function*ud(e,t){for(let n in t){let r=yn(n),i=t[n];for(let t=r.top;t<=r.bottom;t++)for(let n=r.left;n<=r.right;n++)yield[{sheetId:e,col:n,row:t},i]}}function dd(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(typeof e!=`object`)return String(e);if(Array.isArray(e)){let t=e.length,n=`[`;for(let r=0;r<t;r++)r>0&&(n+=`,`),n+=dd(e[r]);return n+`]`}let t=Object.keys(e).sort(),n=`{`;for(let r of t)e[r]!==void 0&&(n+=`"${r}":${dd(e[r])},`);return n+=`}`,n}function fd(e){return 20+120*Math.exp(-.035*(e-1))}function pd(e,t){e=e.toLocaleLowerCase(),t=t.toLocaleLowerCase();let n=0,r=0,i=t.length,a=0;for(let o=0;o<i;o++)t[o]===e[a]?(a++,r+=100+r-o/200):r=0,n+=r;return a===e.length?n:0}function md(e,t,n){let r=[];return t.forEach(t=>{let i=pd(e,n(t));i>0&&r.push({score:i,elem:t})}),r.sort((e,t)=>t.score-e.score),r.map(e=>e.elem)}function hd(e){if(typeof e==`string`)return{};if(typeof e==`number`)return[];throw Error(`Cannot create new node`)}function gd(e,t=1){return t*(e+4)-4}function _d(e=100,t=100){return new OffscreenCanvas(e,t).getContext(`2d`)}function vd(e,t,n,r){if(!t||!t.isFormula&&!t.content)return 23;let i=``;try{if(!t.isFormula){let e={format:t.format,locale:n};i=H(Wu(t.content,n),e)}}catch{i=M.GenericError}return yd(e,i,t.style,r)}function yd(e,t,n,r){return xd(e,jd(e,t,n,n?.wrapping===`wrap`?r-8:void 0),n).height+6}function bd(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${De}`}function xd(e,t,n={},r=`pt`){if(!t.length)return{width:0,height:0};let i=Od(n,r),a=t.map(t=>Ed(e,t,i)),o=gd(a[0].height,t.length),s=Math.max(...a.map(e=>e.width));if(!n.rotation)return{height:o,width:s};let c=Math.abs(Math.cos(n.rotation)),l=Math.abs(Math.sin(n.rotation));return{width:s*c+o*l,height:l*s+c*o}}function Sd(e,t,n={},r=`pt`){return Cd(e,t,Od(n,r),n.rotation)}function Cd(e,t,n,r){let i=Ed(e,t,n);if(!r)return i.width;let a=Math.abs(Math.cos(r)),o=Math.abs(Math.sin(r));return i.width*a+i.height*o}let wd={};function Td(e,t,n,r=`pt`){let i=Ed(e,t,Od(n,r));if(!n.rotation)return i;let a=Math.abs(Math.cos(n.rotation)),o=Math.abs(Math.sin(n.rotation));return{width:i.width*a+i.height*o,height:i.height*a+i.width*o}}function Ed(e,t,n){if(wd[n]||(wd[n]={}),wd[n][t]===void 0){e.save(),e.font=n;let r=e.measureText(t);e.restore();let i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;wd[n][t]={width:i,height:a}}return wd[n][t]}function Dd(e){return Math.round(e*96/72)}function Od(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?kd(e):e.fontSize)??Ee}px ${De}`}function kd(e){return Dd(e?.fontSize||Ee)}function Ad(e,t,n,r){if(Sd(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)Sd(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function jd(e,t,n,r){n||={},ct(t)&&(t=dt(t).label);let i=[],a=t.includes(`
|
|
17
17
|
`)?t.split(`
|
|
18
|
-
`):[t];for(let t of a){let a=t.includes(` `)?t.split(` `):[t];if(!r){i.push(t);continue}let o=``,s=r;for(let t of a){let a=Ad(e,t,r,n),c=a.pop(),l=Sd(e,c,n);if(a.length)o!==``&&(i.push(o),o=``,s=r),a.forEach(e=>{i.push(e)}),o=c,s=r-l;else{let t=o===``?c:` `+c,a=Sd(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function Md(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function Nd(e){return e?e.toLowerCase().trim():``}let Pd=/([0-9\.]*)px/;function Fd(e){return Number(e.match(Pd)?.[1])}function Id(e,t,n){let r=Cd(e,t,e.font);if(r<=n)return t;let i=Cd(e,`…`,e.font);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-->0;)t=t.substring(0,a),r=Cd(e,t,e.font);return t+`…`}function Ld(e,t,n,r=!1,i=!1,a=Fd(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}function Rd(e,t,n,r,i=`pt`){if(Sd(e,n,r,i)<=t)return n;let a=Sd(e,`...`,r,i);if(a>=t)return``;let o=1,s=n.length,c;for(;o<=s;){let l=Math.floor((o+s)/2);c=Sd(e,n.slice(0,l),r,i),c+a>t?s=l-1:o=l+1}let l=n.slice(0,Math.max(0,o-1));return l?l+`...`:``}function zd(e,t){if(!t.rotation||t.rotation%(Math.PI*2)==0)return e;let{x:n,y:r}=e,i=Math.cos(-t.rotation),a=Math.sin(-t.rotation),o=e.textWidth-8,s=e.textHeight,c=t.align===`center`,l=t.align===`left`==a<0,u=a*s,d=Math.abs(a*o),f=i*s;return t.verticalAlign===`top`?c?(r+=d/2,n-=u/2):l?n-=u:r+=d:!t.verticalAlign||t.verticalAlign===`bottom`?(r+=s-f,c?(r-=d/2,n-=u/2):l&&(n-=u,r-=d)):c?(n-=u/2,r-=s/2,l?r+=u:r-=u):l?(n-=u,r-=d/2):r+=d/2+f/4,{x:i*n-a*r,y:i*r+a*n}}var Bd=class{getCrypto(){if(typeof globalThis<`u`&&globalThis.crypto)return globalThis.crypto}smallUuid(){let e=this.getCrypto();return e?`10000000-1000`.replace(/[01]/g,t=>{let n=Number(t);return(n^e.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16)}):`xxxxxxxx-xxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}uuidv4(){let e=this.getCrypto();return e?`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,t=>{let n=Number(t);return(n^e.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16)}):`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}};let Vd=new A;function Hd(){return globalThis.Chart?!!globalThis.Chart.registry.plugins.get(`chartShowValuesPlugin`):!0}function Ud(){if(!(!globalThis.Chart||Hd()))for(let e of Vd.getAll())e.register(globalThis.Chart)}function Wd(){if(globalThis.Chart)for(let e of Vd.getAll())e.unregister(globalThis.Chart)}var Gd=class extends wr{mutators=[`disableAnimationForChart`,`enableAnimationForChart`];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,`noStateChange`}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,`noStateChange`}};let Kd={id:`background`,beforeDraw(e,t,n){let{ctx:r}=e;r.save(),r.globalCompositeOperation=`destination-over`,r.fillStyle=n.color||`#FFFFFF`,r.fillRect(0,0,e.width,e.height),r.restore()}};function qd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`calendar`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`bar`,animations:{numbers:{type:`number`,properties:[]}}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);let i=this.chart.config.options?.plugins?.background?.color||`#FFFFFF`;for(let a=t;a<t+n;a++)r===`reset`&&this.updateElement(e[a],a,{options:{backgroundColor:i}},r)}}}let Jd={id:`chartColorScalePlugin`,afterDatasetsDraw(e,t,n){if(!n.position||n.position===`none`||!n.colorScale.length)return;let r=e.ctx;r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1;let i=(e.chartArea.bottom-e.chartArea.top)/2,a=n.position===`left`?20:r.canvas.width-70,o=e.chartArea.top,s=r.createLinearGradient(0,o+i,0,o),c=1/(n.colorScale.length-1);n.colorScale.forEach((e,t)=>{s.addColorStop(t*c,e)}),r.fillStyle=s,r.fillRect(a,o,10,i),r.fillStyle=n.fontColor??`black`,r.font=bd(12),r.textAlign=`left`;let l=Math.round(n.minValue*100)/100,u=Math.round(n.maxValue*100)/100;n.minValue===n.maxValue&&(--l,u+=1);let d=Zl({value:u,format:void 0},n.locale),f=Zl({value:l,format:void 0},n.locale);r.fillText(f,a+10+5,o+i-6),r.fillText(d,a+10+5,o+6),r.restore()}};function Yd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`funnel`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function Xd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=Zd(this),c=(s-(i?Zd(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=Zd(this),c=a?Zd(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function Zd(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let Qd=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},$d={id:`geoProjection`,beforeUpdate(e){e.options?.scales?.projection?.projection===`conicConformal`&&e.scales?.projection?.projection?.rotate([100,0])}},ef={id:`o-spreadsheet-minor-gridlines`,beforeDatasetsDraw(e){let t=e.ctx,n=e.chartArea;if(n)for(let r in e.scales){let i=e.scales[r],a=i.options,o=a?.grid?.minor;if(!o?.display)continue;let s=a?.grid?.display,c=i.ticks;if(!(!c||c.length<2)){t.save(),t.lineWidth=1,t.strokeStyle=o.color??a?.grid?.color??`#e6e6e6`;for(let e=0;e<c.length-1;e++){let r=i.getPixelForTick(e),a=i.getPixelForTick(e+1);if(!(!isFinite(r)||!isFinite(a)))for(let e=+!!s;e<4;e++){let o=e/4,s=Math.round(r+(a-r)*o)+.5;t.beginPath(),i.isHorizontal()?(t.moveTo(s,n.top),t.lineTo(s,n.bottom)):(t.moveTo(n.left,s),t.lineTo(n.right,s)),t.stroke()}}t.restore()}}}},tf=`000000`,nf={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},rf={styleSheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,sst:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,Relationships:`http://schemas.openxmlformats.org/package/2006/relationships`,Types:`http://schemas.openxmlformats.org/package/2006/content-types`,worksheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,workbook:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,drawing:`http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing`,table:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,revision:`http://schemas.microsoft.com/office/spreadsheetml/2014/revision`,revision3:`http://schemas.microsoft.com/office/spreadsheetml/2016/revision3`,markupCompatibility:`http://schemas.openxmlformats.org/markup-compatibility/2006`},af=`http://schemas.openxmlformats.org/drawingml/2006/main`,of=`http://schemas.openxmlformats.org/drawingml/2006/chart`,sf={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml`,macroEnabledWorkbook:`application/vnd.ms-excel.sheet.macroEnabled.main+xml`,templateWorkbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml`,macroEnabledTemplateWorkbook:`application/vnd.ms-excel.template.macroEnabled.main+xml`,excelAddInWorkbook:`application/vnd.ms-excel.addin.macroEnabled.main+xml`,sheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml`,metadata:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml`,sharedStrings:`application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml`,styles:`application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml`,drawing:`application/vnd.openxmlformats-officedocument.drawing+xml`,chart:`application/vnd.openxmlformats-officedocument.drawingml.chart+xml`,themes:`application/vnd.openxmlformats-officedocument.theme+xml`,table:`application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml`,pivot:`application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml`,externalLink:`application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml`},cf={document:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument`,sheet:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,metadata:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata`,sharedStrings:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings`,styles:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles`,drawing:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing`,chart:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart`,theme:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme`,table:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/table`,hyperlink:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink`,image:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/image`},lf=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,uf=.75,df=.143,ff=8.43,pf=12.75,mf={FLOOR:[{type:`NUMBER`,value:1}],CEILING:[{type:`NUMBER`,value:1}],ROUND:[{type:`NUMBER`,value:0}],ROUNDUP:[{type:`NUMBER`,value:0}],ROUNDDOWN:[{type:`NUMBER`,value:0}],IFERROR:[{type:`NUMBER`,value:0}]},hf=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),gf=`xMovingAverage`,_f={exponential:`exp`,logarithmic:`log`,polynomial:`poly`,trailingMovingAverage:`movingAvg`};function vf(e,t,n){return n?rc(e,t,n):void 0}function yf(e,{applyChange:t}){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}function bf(e,t,n){let r=[];for(let i of n.dataSets){let{unboundedZone:a,sheetId:o,invalidSheetName:s,invalidXc:c}=e.getRangeFromSheetXC(t,i.dataRange);if(!(s||c))if(a.left!==a.right&&a.top!==a.bottom){if(a.right===void 0)continue;let t=i.dataSetId;for(let i=a.left;i<=a.right;i++){let s={...a,left:i,right:i};r.push({...xf(e,o,s,n.dataSetsHaveTitle?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0),dataSetId:t}),t=`${t}_${i}`}}else r.push({...xf(e,o,a,n.dataSetsHaveTitle?{top:a.top,bottom:a.top,left:a.left,right:a.left}:void 0),dataSetId:i.dataSetId})}return r}function xf(e,t,n,r){if(n.left!==n.right&&n.top!==n.bottom)throw Error(`Zone should be a single column or row: ${wn(n)}`);if(r){let i=wn(n),a=wn(r);return{labelCell:e.getRangeFromSheetXC(t,a),dataRange:e.getRangeFromSheetXC(t,i)}}else return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,wn(n))}}function Sf(e,t,n){let r=n.labelCell?.zone,i=n.dataRange.zone;if(r){let{numberOfRows:e,numberOfCols:t}=Ln(i);e===1?i={...i,left:i.left+1}:t===1&&(i={...i,top:i.top+1})}let a=t[n.dataSetId]??{},o=Zs({...n.dataRange,zone:i},e.getSheetSize),s={};a.label?s={text:a.label}:n.labelCell&&(s={reference:e.getRangeString(n.labelCell,`forceSheetReference`,{useBoundedReference:!0})});let c;return a.trend?.type&&(c={type:a.trend.type===`polynomial`&&a.trend.order===1?`linear`:_f[a.trend.type],color:a.trend.color,order:a.trend.order?Math.min(a.trend.order,6):void 0,window:a.trend.window||2}),{label:s,range:e.getRangeString(o,`forceSheetReference`,{useBoundedReference:!0}),backgroundColor:a.backgroundColor,rightYAxis:a.yAxisId===`y1`,trend:c}}function Cf(e,t,n){if(!t)return;let r={...t.zone};n&&t.zone.bottom>t.zone.top&&(r.top+=1);let i=Zs({...t,zone:r},e.getSheetSize);return e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0})}function wf(e){return e&&Rr(e)<.3?`#FFFFFF`:`#000000`}function Tf(e){return e&&Rr(e)<.3?`#C8C8C8`:`#666666`}function Ef(e){return e.dataSets.find(e=>!Go.test(e.dataRange))!==void 0||e.dataSets.map(e=>vn(e.dataRange)).some(e=>e.top!==e.bottom&&Jn(e))?`InvalidDataSet`:`Success`}function Df(e){return e.labelRange&&!Go.test(e.labelRange||``)?`InvalidLabelRange`:`Success`}function Of(e,t,n){return n&&!!t&&e>=t}function kf(e,t){let{x:n,y:r}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:a}=e.getActiveSheetScrollInfo(),{width:o,height:s}=e.getVisibleRect(e.getActiveMainViewport());return{x:n+i+Math.max(0,(o-t.width)/2),y:r+a+Math.max(0,(s-t.height)/2)}}function Af(e){let t=!1,n=!1;if(`horizontal`in e&&e.horizontal)return{useLeftAxis:!0,useRightAxis:!1};for(let r of Object.values(e.dataSetStyles??{}))r?.yAxisId===`y1`?n=!0:t=!0;return t||=!n,{useLeftAxis:t,useRightAxis:n}}function jf(e,t,n=!1){return(r,i)=>{let a=e?.[i];return Mf({format:a,locale:t},n)(r)}}function Mf(e,t=!1){return n=>{if(n=Number(n),isNaN(n))return n;let{locale:r,format:i}=e;return Ff(t?Zl({value:n,format:i},r):H(n,{locale:r,format:!i&&Math.abs(n)>=1e3?`#,##`:i}))}}let Nf=[{value:`left`,label:j(`Left`)},{value:`right`,label:j(`Right`)}];function Pf(e,t){let n=[],r=Vt(t.map(e=>e.data.length));for(let t=0;t<=r;t++)n.push(e.next());return n}function Ff(e,t=20){return e?e.length>t?e.substring(0,t)+`…`:e:``}function If(e){return e===`x1`||e===`xMovingAverage`}let Lf={id:`chartShowValuesPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues||!e._metasets?.[0]?.data)return;let r=e.ctx;switch(r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1,n.type){case`pie`:Hf(e,n,r);break;case`line`:case`scatter`:case`combo`:case`waterfall`:case`radar`:zf(e,n,r);break;case`bar`:n.horizontal?Vf(e,n,r):zf(e,n,r);break;case`pyramid`:Vf(e,n,r);break;case`calendar`:Bf(e,n,r);break;case`funnel`:Vf(e,n,r);break}r.restore()}};function Rf(e,t,n,r){r.lineWidth=3,r.strokeText(e,t,n),r.lineWidth=1,r.fillText(e,t,n)}function zf(e,t,n){let r={};for(let i of e._metasets){if(If(i.xAxisID)||i.hidden)continue;let a=e.scales[i.yAxisID];for(let o=0;o<i._parsed.length;o++){let s=i._parsed[o],c=Number(e.config.type===`radar`?s.r:s.y);if(isNaN(c))continue;let l=i.data[o],u=l.x,d=0;if(e.config.type===`line`||e.config.type===`radar`)d=c<0?l.y+10:l.y-10;else{let e=a.getPixelForValue(0),t=Math.abs(e-l.y),n=globalThis.Chart?.defaults.font.size??12;d=t<n?c<0?e+n/2:e-n/2:c<0?l.y-l.height/2:l.y+l.height/2}r[u]||(r[u]=[]);for(let e of r[u]||[])Math.abs(e-d)<13&&(d=c<0?e+13:e-13);r[u].push(d),n.fillStyle=l.options.backgroundColor,n.strokeStyle=t.background(Number(c),i,o)||`#ffffff`,Rf(t.callback(Number(c),i,o),u,d,n)}}}function Bf(e,t,n){let r=e.chartArea.bottom,i=e.chartArea.top;for(let a of e._metasets){if(If(a.xAxisID)||a.hidden)continue;let o=e.scales[a.yAxisID];for(let s=0;s<a._parsed.length;s++){let c=a._parsed[s],l=Number(e.config.type===`radar`?c.r:c.y);if(isNaN(l))continue;let u=a.data[s],d=u.x,f=0,p=o.getPixelForValue(0),m=Math.abs(p-u.y),h=globalThis.Chart?.defaults.font.size??12;f=m<h?l<0?p+h/2:p-h/2:l<0?u.y-u.height/2:u.y+u.height/2,f=Math.min(f,r),f=Math.max(f,i),n.strokeStyle=u.options.backgroundColor,n.fillStyle=t.background(Number(l),a,s)||`#ffffff`;let g=t.callback(Number(l),a,s),_=n.measureText(g);_.actualBoundingBoxAscent+_.actualBoundingBoxDescent+2>Math.abs(u.height)-2||Rf(g,d,f,n)}}}function Vf(e,t,n){let r={};for(let i of e._metasets){if(If(i.xAxisID))return;let a=e.scales[i.xAxisID].getPixelForValue(0);for(let e=0;e<i._parsed.length;e++){let o=Number(i._parsed[e].x);if(isNaN(o))continue;let s=t.callback(o,i,e),c=i.data[e],l=c.y,u=Sd(n,s,{fontSize:globalThis.Chart?.defaults.font.size??12},`px`),d=Math.abs(c.x-a),f;f=d<u?o<0?a-u/2-3:a+u/2+3:o<0?c.x+c.width/2:c.x-c.width/2,r[l]||(r[l]=[]);for(let e of r[l])Math.abs(e-f)<u&&(f=o<0?e-u-3:e+u+3);r[l].push(f),n.strokeStyle=c.options.backgroundColor,n.fillStyle=t.background(Number(o),i,e)||`#ffffff`,Rf(s,f,l,n)}}}function Hf(e,t,n){for(let r of e._metasets)for(let e=0;e<r._parsed.length;e++){let i=Number(r._parsed[e]);if(isNaN(i)||i===0)continue;let a=r.data[e],{startAngle:o,endAngle:s,innerRadius:c,outerRadius:l}=a,u=(o+s)/2,d=(c+l)/2,f=a.x+d*Math.cos(u),p=a.y+d*Math.sin(u),m=t.callback(i,r,e),h=globalThis.Chart?.defaults.font.size??12,g=Sd(n,m,{fontSize:h},`px`),_=l-c;if(g>=_||_<h)continue;let v=s-o,y=2*d*Math.tan(v/2);if(v<Math.PI/2&&(g>=y||y<h))continue;let b=t.background(Number(i),r,e);n.fillStyle=wf(b),n.strokeStyle=b||`#ffffff`,Rf(m,f,p,n)}}let Uf={showHeaders:!0,headerDesign:{align:`center`,fillColor:`#808080`,bold:!0,fontSize:15},showValues:!0,showLabels:!0,valuesDesign:{align:`left`,verticalAlign:`bottom`,fontSize:12},coloringOptions:{type:`categoryColor`,colors:[],useValueBasedGradient:!0}},Wf={second:1e3,minute:1e3*60,hour:1e3*3600,day:1e3*3600*24,month:1e3*3600*24*30,year:1e3*3600*24*365},Gf={inSeconds:function(e){return Math.floor(e/Wf.second)},inMinutes:function(e){return Math.floor(e/Wf.minute)},inHours:function(e){return Math.floor(e/Wf.hour)},inDays:function(e){return Math.floor(e/Wf.day)},inMonths:function(e){return Math.floor(e/Wf.month)},inYears:function(e){return Math.floor(e/Wf.year)}},Kf=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function qf(e,t,n){let r=Jf(t),i=Xf(e,r,n),a={};return i&&(a[i]=r),{parser:r,displayFormats:a,unit:i??!1,tooltipFormat:r}}function Jf(e){let t=e.indexOf(`h`);return e=t>=0?e.slice(0,t).replace(/m/g,`M`)+e.slice(t):e.replace(/m/g,`M`),e.includes(`a`)||(e=e.replace(/h/g,`H`)),e}function Yf(e){return e.includes(`s`)?`second`:e.includes(`m`)?`minute`:e.includes(`h`)||e.includes(`H`)?`hour`:e.includes(`d`)?`day`:e.includes(`M`)?`month`:`year`}function Xf(e,t,n){let r=e.map(e=>ia(e,n)?.jsDate);if(r.some(e=>e===void 0)||e.length<2)return;let i=r.map(e=>e.getTime()),a=Vt(i)-Ht(i),o=Yf(t);return Wf.second>=Wf[o]&&Gf.inSeconds(a)<180?`second`:Wf.minute>=Wf[o]&&Gf.inMinutes(a)<180?`minute`:Wf.hour>=Wf[o]&&Gf.inHours(a)<96?`hour`:Wf.day>=Wf[o]&&Gf.inDays(a)<90?`day`:Wf.month>=Wf[o]&&Gf.inMonths(a)<36?`month`:`year`}function Zf(e,t){let n={},{trendDataSetsValues:r,locale:i,axisFormats:a,axisType:o}=t,s={stacked:e.stacked,locale:i};if(e.horizontal)n.x=up(e,`bottom`,`values`,o,{...s,format:a?.x}),n.y={...up(e,`left`,`labels`,`linear`,s),grid:{display:!1}};else{n.x={...up(e,`bottom`,`labels`,o,s),grid:{display:!1}};let t={...s,format:a?.y};n.y=up(e,`left`,`values`,`linear`,t);let r={...s,format:a?.y1};n.y1=up(e,`right`,`values`,`linear`,r)}if(n=Dt(n),r&&r.length&&r.some(w)){let e=Math.max(...r.map(e=>e?.length||0));n.x1={...n.x,labels:Array(e).fill(``),offset:!1,display:!1},n[gf]={...n.x,offset:!0,display:!1}}return n}function Qf(e,t){let n=t.map(e=>e.label||``),r=wf(e.background);return{y:{title:lp(e.axesDesign?.y),stacked:!0,min:0,max:n.length,ticks:{stepSize:.5,color:r,callback:function(e,t,r){if(t%2!=0)return n[Math.floor((t-1)/2)]}},grid:{display:!1},border:{display:!1}},x:{title:lp(e.axesDesign?.x),stacked:!0,grid:{display:!1},position:`top`,ticks:{color:r},border:{display:!1}}}}function $f(e,t){let{dataSetsValues:n}=t;if(!n.length||e.legendPosition===`none`)return;let r=n.flatMap(e=>e.data).filter(U).map(e=>e.value),i=Math.min(...r),a=Math.max(...r),o=[];return o=typeof e.colorScale==`object`?[e.colorScale.minColor,e.colorScale.midColor,e.colorScale.maxColor].filter(w):[...pi[e.colorScale??`oranges`]],{position:e.legendPosition===`right`?`right`:`left`,colorScale:o,fontColor:wf(e.background),minValue:i,maxValue:a,locale:t.locale}}function ep(e,t){let{locale:n,axisType:r,trendDataSetsValues:i,labels:a,axisFormats:o}=t,s=o?.x,c=e.stacked,l={x:up(e,`bottom`,`labels`,r,{locale:n}),y:up(e,`left`,`values`,`linear`,{locale:n,stacked:c,format:o?.y}),y1:up(e,`right`,`values`,`linear`,{locale:n,stacked:c,format:o?.y1})};if(l=Dt(l),r===`time`&&a&&s){let t={type:`time`,time:qf(a,s,n),min:H(e.axesDesign?.x?.min??``,{format:s,locale:n}),max:H(e.axesDesign?.x?.max??``,{format:s,locale:n})};Object.assign(l.x,t),l.x.ticks.maxTicksLimit=15,delete l?.x?.ticks?.callback}else r===`linear`&&(l.x.type=`linear`,l.x.ticks.callback=e.humanize?e=>Zl({value:e,format:s},n):e=>H(e,{format:s,locale:n}));if(i&&i.length&&i.some(w)&&(l.x1={...l.x,display:!1},l[gf]={...l.x,display:!1},r===`category`||r===`time`)){let e=Math.max(...i.map(e=>e?.length||0));l.x1.type=`category`,l.x1.labels=C(0,e).map(e=>e.toString()),l.x1.offset=!1,l[gf].type=`category`,l[gf].offset=!1}return l}function tp(e){return Rr(e||`#ffffff`)>.5?`#cccccc`:`#999999`}function np(e){return Rr(e||`#ffffff`)>.5?`#e6e6e6`:`#333333`}function rp(e,t){let n=ep(e,t),r=n?.x??{},i=e.axesDesign?.x,a=i?.gridLines!==`none`&&i?.gridLines!==`minor`;return{...n,x:{...r,grid:{...r.grid,color:tp(e.background),display:a}}}}function ip(e,t){let{locale:n,axisFormats:r,axisType:i}=t,a=r?.y||r?.y1,o=e.axesDesign?.y,s={x:{...up(e,`bottom`,`labels`,i,{locale:n}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:wf(e.background),callback:Mf({locale:n,format:a},e.humanize)},title:lp(e.axesDesign?.y),min:o?.min,max:o?.max,grid:{lineWidth:e=>e.tick.value===0?2:1,display:o?.gridLines!==`none`&&o?.gridLines!==`minor`,color:tp(e.background)}}};return(o?.gridLines===`minor`||o?.gridLines===`both`)&&(s.y.grid.minor={display:!0,color:np(e.background)}),s}function ap(e,t){let{dataSetsValues:n}=t,r=Zf(e,t),i=r.x.ticks.callback;r.x.ticks.callback=e=>i(Math.abs(e));let a=Math.max(...n.map(e=>Math.max(...e.data.filter(U).map(e=>Math.abs(e.value)))));return r.x.suggestedMin=-a,r.x.suggestedMax=a,r}function op(e,t){let{locale:n,axisFormats:r,dataSetsValues:i}=t,a=Math.min(...i.map(e=>Math.min(...e.data.filter(U).map(e=>e.value))));return{r:{beginAtZero:!0,ticks:{callback:Mf({format:r?.r,locale:n},e.humanize),backdropColor:e.background||`#FFFFFF`},pointLabels:{color:wf(e.background),callback:e=>Ff(e)},suggestedMin:a<0?a-1:0}}}function sp(e,t){let{locale:n,axisFormats:r,availableRegions:i}=t,a=pp(e.legendPosition),o=e.region?i.find(t=>t.id===e.region):i[0],s=r?.y||r?.y1;return{projection:{projection:o?.defaultProjection||`mercator`,axis:`x`},color:{axis:`x`,display:e.legendPosition!==`none`,border:{color:me},grid:{color:me},ticks:{color:wf(e.background),callback:Mf({locale:n,format:s},e.humanize)},legend:{position:a,align:a.includes(`right`)?`left`:`right`,margin:fp(e)},interpolate:dp(e.colorScale??_e),missing:e.missingValueColor||`#ffffff`}}}function cp(e,t){let n=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return Ff(this.getLabelForValue(e))}},border:{display:!1}},percentages:{position:`right`,border:{display:!1},ticks:{callback:function(e,r,i){let a=n.data?.[r],o=n.data?.[0];return!o?.value||a?.value===null||!U(a)||!U(o)?``:H(a.value/o.value,{format:`0%`,locale:t.locale})}},grid:{display:!1}}}}function lp(e){if(e?.title?.text){let{text:t,color:n,align:r,italic:i,bold:a}=e.title;return{display:!0,text:t,color:n,font:{style:i?`italic`:`normal`,weight:a?`bold`:`normal`,size:e.title.fontSize??12},align:r===`left`?`start`:r===`right`?`end`:`center`}}}function up(e,t,n,r,i){let{useLeftAxis:a,useRightAxis:o}=Af(e);if(t===`left`&&!a||t===`right`&&!o)return;let s=wf(e.background),c;if(c=t===`bottom`?e.axesDesign?.x:t===`left`?e.axesDesign?.y:e.axesDesign?.y1,n===`values`){let n=!(t===`right`&&a),o=c?.gridLines?c?.gridLines===`major`||c?.gridLines===`both`:n,l=!(r===`category`||r===void 0)&&(c?.gridLines===`minor`||c?.gridLines===`both`),u=Mf(i,e.humanize),d={position:t,title:lp(c),beginAtZero:!c?.min,stacked:i?.stacked,ticks:{color:s,callback:u},min:c?.min,max:c?.max,grid:{display:o,color:tp(e.background)}};return l&&(d.grid.minor={display:!0,color:np(e.background)}),d}else{let t={ticks:{padding:5,color:s,callback:function(e,t,n){return Ff(this.getLabelForValue(e))}},min:c?.min,max:c?.max,grid:{display:c?.gridLines===`major`||c?.gridLines===`both`,color:tp(e.background)},stacked:i?.stacked,title:lp(c)};return(c?.gridLines===`minor`||c?.gridLines===`both`)&&(t.grid.minor={display:!0,color:np(e.background)}),t}}function dp(e,t=0,n=1){if(t===n){let t=e.midColor??e.minColor;return e=>t}let r=[{value:t,color:e.minColor}];return e.midColor&&r.push({value:(t+n)/2,color:e.midColor}),r.push({value:n,color:e.maxColor}),hi(r)}function fp(e){switch(e.legendPosition){case`top`:case`right`:return{top:e.title.text?45:15,left:20,right:20};case`bottom`:case`left`:case`none`:return{left:20,right:20,bottom:10}}}function pp(e){switch(e){case`top`:return`top-left`;case`right`:return`top-right`;case`bottom`:return`bottom-right`;case`left`:return`bottom-left`;case`none`:return`bottom-left`}}let mp=`nullValue`;function hp(e,t){let{dataSetsValues:n}=t,r=[],i=Fp(e.dataSetStyles,n),a=[];for(let o in n){let{label:s,data:c,hidden:l,dataSetId:u}=n[o];s=e.dataSetStyles?.[u]?.label??s;let d=i.next(),f={label:s,data:c.map(e=>U(e)?e.value:NaN),hidden:l,borderColor:e.background||`#FFFFFF`,borderWidth:+!!e.stacked,backgroundColor:d,yAxisID:e.horizontal?`y`:e.dataSetStyles?.[u]?.yAxisId??`y`,xAxisID:`x`,barPercentage:.9,categoryPercentage:n.length>1?.8:1,borderRadius:2};r.push(f);let p=e.dataSetStyles?.[u]?.trend,m=t.trendDataSetsValues?.[o];!p?.display||e.horizontal||!m||a.push(Np(f,p,m))}return r.push(...a),r}function gp(e,t){let{labels:n,dataSetsValues:r}=t,i=r.map(e=>e.data).flat().filter(U).map(e=>e.value),a=Math.max(...i),o=Math.min(...i),s=dp(e.colorScale??_e,o,a),c=[];for(let t of r)c.push({label:t.label,data:t.data.map(e=>1),backgroundColor:t.data.map(t=>U(t)?s(t.value):e.missingValueColor||`#00000000`),borderColor:e.background||`#FFFFFF`,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1,values:t.data.map(e=>U(e)?e.value:void 0)});return{labels:n,datasets:c}}function _p(e,t){let{dataSetsValues:n,labels:r}=t,i=e.negativeValuesColor||`#EA6175`,a=e.positiveValuesColor||`#4EA7F2`,o=e.subTotalValuesColor||`#AAAAAA`,s=[],c=[],l={label:``,data:c,backgroundColor:s},u=[],d=0;for(let t of n)if(!t.hidden){for(let l=0;l<t.data.length;l++){let f=t.data[l];if(u.push(r[l]),!U(f)){c.push([d,d]),s.push(``);continue}c.push([d,f.value+d]);let p=f.value>=0?a:i;l===0&&t===n[0]&&e.firstValueAsSubtotal&&(p=o),s.push(p),d+=f.value}e.showSubTotals&&(u.push(j(`Subtotal`)),c.push([0,d]),s.push(o))}return{datasets:[l],labels:u}}function vp(e,t){let{dataSetsValues:n,axisType:r,labels:i}=t,a=[],o=!!e.fillArea,s=!!e.stacked,c=[],l=Fp(e.dataSetStyles,n);for(let u=0;u<n.length;u++){let{label:d,data:f,hidden:p,dataSetId:m}=n[u];d=e.dataSetStyles?.[m]?.label??d;let h=[],g=l.next();h=r&&[`linear`,`time`].includes(r)?f.map((e,t)=>({x:i[t]===``?NaN:i[t]??NaN,y:U(e)?e.value:NaN})):f.map(e=>U(e)?e.value:NaN);let _=e.dataSetStyles?.[m],v={label:d,data:h,hidden:p,tension:0,borderColor:g,backgroundColor:o?Yr(g,Ne):g,pointBackgroundColor:g,fill:o?Pp(u,s):!1,pointRadius:e.hideDataMarkers?0:3,yAxisID:_?.yAxisId||`y`};a.push(v);let y=_?.trend,b=t.trendDataSetsValues?.[u];!y?.display||!b||c.push(Np(v,y,b))}return a.push(...c),a}function yp(e,t){let n=vp(e,t);for(let e of n)If(e.xAxisID)||(e.showLine=!1);return n}function bp(e,t){let{dataSetsValues:n}=t,r=[],i=Pf(new ui(Math.max(0,...n.map(e=>e?.data?.length??0)),e.slicesColors),n);for(let{label:t,data:a,hidden:o}of n){if(o)continue;let n={label:t,data:a.map(e=>U(e)?e.value:NaN),borderColor:e.background||`#FFFFFF`,backgroundColor:i,hoverOffset:10};r.push(n)}return r}function xp(e,t){let{dataSetsValues:n}=t,r=[],i=Fp(e.dataSetStyles,n),a=[],o=n.filter(({dataSetId:t})=>(e.dataSetStyles?.[t]?.type??`line`)===`bar`);for(let s=0;s<n.length;s++){let{label:c,data:l,hidden:u,dataSetId:d}=n[s];c=e.dataSetStyles?.[d]?.label||c;let f=e.dataSetStyles?.[d],p=i.next(),m=s===0?`bar`:`line`,h=f?.type??m,g={label:c,data:l.map(e=>U(e)?e.value:null),hidden:u,borderColor:p,backgroundColor:p,yAxisID:e.dataSetStyles?.[d]?.yAxisId||`y`,xAxisID:`x`,type:h,order:h===`bar`?n.length+s:s,pointRadius:e.hideDataMarkers?0:3};g.type===`bar`&&(g.barPercentage=.9,g.categoryPercentage=o.length>1?.8:1,g.borderRadius=2),r.push(g);let _=e.dataSetStyles?.[d]?.trend,v=t.trendDataSetsValues?.[s];!_?.display||!v||a.push(Np(g,_,v))}return r.push(...a),r}function Sp(e,t){let{dataSetsValues:n}=t,r=[],i=e.fillArea??!1,a=Fp(e.dataSetStyles,n);for(let t=0;t<n.length;t++){let{label:o,data:s,hidden:c}=n[t];e.dataSetStyles?.[t]?.label&&(o=e.dataSetStyles[t].label);let l=a.next(),u={label:o,data:s.map(e=>U(e)?e.value:null),hidden:c,borderColor:l,backgroundColor:l,pointRadius:e.hideDataMarkers?0:3};i&&(u.backgroundColor=Yr(l,Ne),u.fill=`start`),r.push(u)}return r}function Cp(e,t){let{availableRegions:n,dataSetsValues:r,labels:i}=t,a=e.region||n[0]?.id,o=a?t.getGeoJsonFeatures(a):void 0,s={outline:o,showOutline:!!o,data:[]};if(o&&a){let e={};if(r[0])for(let n=0;n<r[0].data.length;n++){let o=r[0].data[n];if(!i[n]||o===void 0)continue;let s=t.geoFeatureNameToId(a,i[n]);s&&(e[s]={value:U(o)?o.value:0,label:i[n]})}for(let t of o)t.id&&s.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[s]}function wp(e,t){let n=t.dataSetsValues[0],r=t.labels;if(!n)return[];let{label:i,data:a}=n;return i=e.dataSetStyles?.[0]?.label||i,[{label:i,data:a.map(e=>{if(!U(e))return 0;let t=e.value;return t<=0?[0,0]:[-t,t]}),backgroundColor:Tp(r,e.funnelColors),yAxisID:`y`,xAxisID:`x`,barPercentage:1,categoryPercentage:1,borderColor:e.background||`#FFFFFF`,borderWidth:3}]}function Tp(e,t){let n=new ui(e.length,t);return e.map(()=>n.next())}function Ep(e,t){let{dataSetsValues:n,labels:r}=t,i=Ap(Op(n,r)),a=i[0]||[],o=new ui(a.length,e.groupColors||[]),s=a.map(e=>({label:e.label,color:o.next()})),c=[];for(let t=i.length-1;t>=0;t--){let n={groupColors:s,parsing:{key:`value`},data:i[t],borderColor:t=>{let n=t.type===`data`?t.raw:void 0;return!n||n.label===`nullValue`?de:e.background||`#FFFFFF`},backgroundColor:e=>{let t=e.type===`data`?e.raw:void 0;if(!t||t.label===`nullValue`)return de;let n=t.groups[0];return s.find(e=>e.label===n)?.color},hoverOffset:10};c.push(n)}return c}function Dp(e,t){let n=[],r=Math.max(...e.map(e=>e.data.length));for(let i=0;i<r;i++){n[i]={};for(let t=0;t<e.length;t++){let r=e[t].data[i]?.value,a=r===null?mp:String(r);n[i][t]=a}n[i].value=Number(t[i])}return n}function Op(e,t){return kp(Dp(e,t),0,e.length,[])}function kp(e,t,n,r){if(t>=n)return[];let i=Object.groupBy(e,e=>e[t]);return Object.keys(i).map(e=>{let a=i[e]?.reduce((e,t)=>e+Number(t.value),0)||0,o=[...r,e];return{label:e,value:a,children:kp(i[e]||[],t+1,n,[...r,e]),groups:o,depth:t}}).sort((e,t)=>t.value-e.value)}function Ap(e){let t=[],n=[...e];for(;n.length>0;){let e=n.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&n.push(...e.children))}return t}function jp(e,t){let{dataSetsValues:n,labels:r,locale:i,axisFormats:a}=t,o={locale:i,format:a?.y};if(n.length===0)return[];let s=Op(n,r).sort((e,t)=>t.value-e.value),c=Ip(e,s),l=[],u=Math.max(...n.map(e=>e.data.length));for(let e=0;e<u;e++){l[e]={};for(let t=0;t<n.length;t++)l[e][t]=n[t].data[e].value?String(n[t].data[e].value):void 0;l[e].value=Number(r[e])}let d=e.showLabels??Uf.showLabels,f=e.showValues??Uf.showValues,p=e.coloringOptions||Uf.coloringOptions,m;return p?.type===`colorScale`&&(m=Lp(s,p)),[{data:[],tree:l,labels:{display:d||f,overflow:`hidden`,...Mp(e.valuesDesign,Uf.valuesDesign),formatter:e=>[d?e.raw.g:void 0,f?H(e.raw.v,o):void 0].filter(w)},captions:{display:e.showHeaders??Uf.showHeaders,padding:6,...Mp(e.headerDesign,Uf.headerDesign)},key:`value`,groups:C(0,n.length).map(e=>String(e)),borderWidth:0,spacing:1,displayMode:`headerBoxes`,groupColors:c,backgroundColor:t=>{if(t.type!==`data`)return`transparent`;if(!t.raw.isLeaf)return e.headerDesign?.fillColor||Uf.headerDesign?.fillColor;if(p.type===`colorScale`)return m?.(t.raw.v)||`#FF0000`;if(p.type===`categoryColor`)return Rp(t,s,p,c);throw Error(`Unsupported coloring option type}`)}}]}function Mp(e,t){let n=e=>{let t=e.element.options.backgroundColor;return Rr(t)>.7?`#666666`:`#FFFFFF`};return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||n,hoverColor:e?.color||n,font:{weight:e?.bold??t?.bold?`bold`:`normal`,style:e?.italic??t?.italic?`italic`:`normal`,size:e?.fontSize??t?.fontSize}}}function Np(e,t,n){let r=Vr(e.backgroundColor);r.a=1;let i=t.color||Xr(Br(r),.5);return{type:`line`,xAxisID:t.type===`trailingMovingAverage`?gf:`x1`,yAxisID:e.yAxisID,label:e.label?j(`Trend line for %s`,e.label):``,data:n,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function Pp(e,t){return t?e===0?`origin`:`-1`:`origin`}function Fp(e,t){let n=t.map(t=>e?.[t.dataSetId]?.backgroundColor),r=t.length;return new ui(r,n)}function Ip(e,t){let n=e.coloringOptions?.type===`categoryColor`?e.coloringOptions.colors:[],r=new ui(t.length,n);return t.map(e=>({label:e.label,color:r.next()}))}function Lp(e,t){if(e.length===0)return;let n=Ap(e),r=n[n.length-1],i=Math.min(...r.map(e=>e.value)),a=Math.max(...r.map(e=>e.value));if(Number.isFinite(i)&&Number.isFinite(a)){let e=[{value:i,color:t.minColor}];if(t.midColor){let n=(i+a)/2;e.push({value:n,color:t.midColor})}return e.push({value:a,color:t.maxColor}),hi(e)}}function Rp(e,t,n,r){let i=e.raw._data.children[0][0],a=r.find(e=>e.label===i)?.color;if(!a||!n.useValueBasedGradient)return a||`#FF0000`;let o=t.find(e=>e.label===i);if(!o||!o.children.length)return a;let s=Ap(o.children),c=s[s.length-1],l=Math.max(...c.map(e=>e.value)),u=Math.min(...c.map(e=>e.value));return u===l||!isFinite(u)||!isFinite(l)?a:Xr(a,((Number(e.raw.v)||0)-l)/(u-l)*.5)}let zp={id:`sunburstHoverPlugin`,afterEvent(e,t,n){if(!n.enabled)return;let r=e.getActiveElements(),i=r.map(e=>({datasetIndex:e.datasetIndex,index:e.index}));for(let t of r){let n=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){let r=e.data.datasets[t];for(let e=0;e<r.data.length;e++){let a=r.data[e];Bp(n.groups,a.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter(t=>{let{datasetIndex:n,index:r}=t;return e.data.datasets[n].data[r].label!==mp}),e.setActiveElements(i);for(let t of e.getSortedVisibleDatasetMetas())for(let e of t.data){let t=e.$context,{datasetIndex:n,index:r,dataset:a,raw:o}=t;if(o.label===`nullValue`)continue;let s=typeof a.backgroundColor==`function`?a.backgroundColor(t):a.backgroundColor;i.length&&!i.some(e=>e.datasetIndex===n&&e.index===r)?e.options.backgroundColor=Xr(s,.5):e.options.backgroundColor=s}}};function Bp(e,t){return t.length>e.length&&e.every((e,n)=>e===t[n])}let Vp={id:`sunburstLabelsPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues&&!n.showLabels||e.config.type!==`doughnut`)return;let r=e.ctx;Hp(e,n,r)}};function Hp(e,t,n){let r=t.style,i=r.fontSize||13,a=i+3;for(let o of e._metasets)for(let s=0;s<o._dataset.data.length;s++){let c=o._dataset.data[s];if(c.label===`nullValue`)continue;let l=[t.showLabels?c.label:void 0,t.showValues?t.callback(c.value,`y`):void 0].filter(w),u=o.data[s],{startAngle:d,endAngle:f,innerRadius:p,outerRadius:m,circumference:h}=u,g=u.options.offset/4,_=g*(1-Math.sin(Math.min(Math.PI,h||0)));p+=_,m+=_;let v=(d+f)/2,y=(p+m)/2,b=(m-p)*.9,ee=f-d;if((ee>=Math.PI?m:Math.sin(ee/2)*p*2)<l.length*a)continue;n.save();let te={x:Math.cos(v)*g,y:Math.sin(v)*g},ne=e.chartArea.left+e.chartArea.width/2+te.x,re=e.chartArea.top+e.chartArea.height/2+te.y;n.translate(ne,re);let ie;v>Math.PI/2?(n.rotate(v-Math.PI),ie=-y):(ie=y,n.rotate(v));let ae=u.options.backgroundColor,oe=Rr(ae)>.7?`#666666`:`#FFFFFF`;n.fillStyle=r.textColor||oe,n.textAlign=`center`,n.textBaseline=`middle`,n.font=bd(i,r.bold,r.italic);let se=-((l.length-1)*a)/2;for(let e=0;e<l.length;e++){let t=Rd(n,b,l[e],r,`px`);n.fillText(t,ie,se+e*a)}n.restore()}}let Up={id:`waterfallLinesPlugin`,beforeDraw(e,t,n){if(!n.showConnectorLines)return;let r=e._metasets?.[0]?.data;if(!r)return;let i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<r.length;e++){let t=r[e];if(t.height===0)continue;let n=Gp(r,e);if(!n)break;let a=Wp(t),o=Wp(n),s=t.$context.raw,c=s[1]-s[0],l=Math.round(c<0?a.bottom-1:a.top),u=Math.round(a.right),d=Math.round(o.left);i.strokeStyle=`#999`,i.beginPath(),i.moveTo(u+1,l+.5),i.lineTo(d,l+.5),i.stroke()}i.restore()}};function Wp(e){let t=e.base<e.y;return{left:e.x-e.width/2,right:e.x+e.width/2,bottom:t?e.base+e.height:e.y+e.height,top:t?e.base:e.y}}function Gp(e,t){return e.find((e,n)=>n>t&&e.height!==0)}let Kp={id:`zoomWindowPlugin`,afterDatasetsDraw:function(e,t,n){if(!n.getLowerBound||!n.getUpperBound)return;let{ctx:r,chartArea:{left:i,right:a,top:o,bottom:s}}=e,c=n.getLowerBound()??i,l=n.getUpperBound()??a;c>l&&([c,l]=[l,c]),c=Math.max(i,c),l=Math.min(a,l),c===i&&--c,l===a&&(l+=1),r.save(),r.fillStyle=`rgba(255,255,255,0.5)`,r.beginPath(),r.rect(i,s,c-i,o-s),r.rect(l,s,a-l,o-s),r.fill(),r.beginPath(),r.strokeStyle=`#bbb`,r.rect(c,s,l-c,o-s),r.stroke(),r.lineWidth=2,r.beginPath(),r.moveTo(c-3,(o+s)/2-7),r.lineTo(c-3,(o+s)/2+7),r.stroke(),r.beginPath(),r.moveTo(l+3,(o+s)/2-7),r.lineTo(l+3,(o+s)/2+7),r.stroke(),r.restore()}};Vd.add(`chartShowValuesPlugin`,{register:e=>e.register(Lf),unregister:e=>e.unregister(Lf)}),Vd.add(`chartMinorGridPlugin`,{register:e=>e.register(ef),unregister:e=>e.unregister(ef)}),Vd.add(`waterfallLinesPlugin`,{register:e=>e.register(Up),unregister:e=>e.unregister(Up)}),Vd.add(`funnelController`,{register:e=>e.register(Yd()),unregister:e=>e.unregister(Yd())}),Vd.add(`funnelElement`,{register:e=>e.register(Xd()),unregister:e=>e.unregister(Xd())}),Vd.add(`funnelTooltipPositioner`,{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=Qd,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),Vd.add(`sunburstLabelsPlugin`,{register:e=>e.register(Vp),unregister:e=>e.unregister(Vp)}),Vd.add(`sunburstHoverPlugin`,{register:e=>e.register(zp),unregister:e=>e.unregister(zp)}),Vd.add(`chartColorScalePlugin`,{register:e=>e.register(Jd),unregister:e=>e.unregister(Jd)}),Vd.add(`calendarController`,{register:e=>e.register(qd()),unregister:e=>e.unregister(qd())}),Vd.add(`zoomWindowPlugin`,{register:e=>e.register(Kp),unregister:e=>e.unregister(Kp)}),Vd.add(`chartBackgroundPlugin`,{register:e=>e.register(Kd),unregister:e=>e.unregister(Kd)}),Vd.add(`geoProjectionPlugin`,{register:e=>e.register($d),unregister:e=>e.unregister($d)});var qp=class extends t.Component{static template=`o-spreadsheet-ChartJsComponent`;static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`graphContainer`);chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get chartRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!(`chartJsConfig`in e))throw Error(`Unsupported chart runtime`);return e}setup(){this.shouldAnimate&&(this.animationStore=O(Gd)),(0,t.onMounted)(()=>{Ud();let e=this.chartRuntime;this.currentRuntime=e,this.createChart(x(e))}),(0,t.onWillUnmount)(this.unmount.bind(this)),(0,t.useEffect)(()=>{let e=this.chartRuntime;e===this.currentRuntime?this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(x(this.currentRuntime))):(e.chartJsConfig.type===this.currentRuntime.chartJsConfig.type?this.updateChartJs(x(e)):(this.chart?.destroy(),this.createChart(x(e))),this.currentRuntime=e)})}unmount(){this.chart?.destroy()}get shouldAnimate(){return this.env.model.getters.isDashboard()}createChart(e){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let t=e.chartJsConfig;if(this.shouldAnimate&&this.animationStore){let e=this.env.model.getters.getChartDefinition(this.props.chartId)?.type;e&&this.animationStore.animationPlayed[this.animationChartId]!==e&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}let n=this.canvas.el.getContext(`2d`);this.chart=new globalThis.Chart(n,t)}updateChartJs(e){let t=e.chartJsConfig;if(this.shouldAnimate){let e=this.env.model.getters.getChartDefinition(this.props.chartId)?.type;e&&this.hasChartDataChanged()&&this.animationStore&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.plugins?.title&&(this.chart.config.options.plugins.title=t.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=t.options,this.chart.update()}hasChartDataChanged(){return!T(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}getChartDataInRuntime(e){let t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}get animationChartId(){return this.props.isFullScreen?this.props.chartId+`-fullscreen`:this.props.chartId}},Jp=class{static commonKeys=[`type`,`title`,`background`,`humanize`]};function Yp(e,t,n,r,i){if(!e)return``;if(n===`text`||t?.type!==`number`||e.type!==`number`)return r?Zl(e,i):e.formattedValue;let{value:a,format:o}=e;return n===`progress`?(a=t.value/a,o=`0.0%`):(a=Math.abs(t.value-a),n===`percentage`&&a!==0&&(a/=e.value),n===`percentage`&&(o=`0.0%`),o||(a=Math.round(a*100)/100)),r?Zl({value:a,format:o},i):H(a,{format:o,locale:i})}function Xp(e,t,n){return e?t?Zl(e,n):e.formattedValue??String(e.value??``):``}function Zp(e,t,n,r,i){if(t===`text`||t===`progress`||e?.type!==`number`||n?.type!==`number`)return;let a=n.value-e.value;if(a>0)return r;if(a<0)return i}function Qp(e,t,n){if(n===`text`||e?.type!==`number`||t?.type!==`number`)return`neutral`;let r=t.value-e.value;return r>0?`up`:r<0?`down`:`neutral`}function $p(e){return e.keyValue&&!Go.test(e.keyValue)?`InvalidScorecardKeyValue`:`Success`}function em(e){return e.baseline&&!Go.test(e.baseline)?`InvalidScorecardBaseline`:`Success`}let tm=globalThis.Path2D,nm=tm&&new tm(`M8.6 4.8a.5.5 0 0 1 0 .75l-3.9 3.9a.5 .5 0 0 1 -.75 0l-3.8 -3.9a.5 .5 0 0 1 0 -.75l.4-.4a.5.5 0 0 1 .75 0l2.3 2.4v-5.7c0-.25.25-.5.5-.5h.6c.25 0 .5.25.5.5v5.8l2.3 -2.4a.5.5 0 0 1 .75 0z`),rm=tm&&new tm(`M8.7 5.5a.5.5 0 0 0 0-.75l-3.8-4a.5.5 0 0 0-.75 0l-3.8 4a.5.5 0 0 0 0 .75l.4.4a.5.5 0 0 0 .75 0l2.3-2.4v5.8c0 .25.25.5.5.5h.6c.25 0 .5-.25.5-.5v-5.8l2.2 2.4a.5.5 0 0 0 .75 0z`),im={sequence:40,allowedDefinitionKeys:[...Jp.commonKeys,`keyValue`,`keyDescr`,`baseline`,`baselineMode`,`baselineDescr`,`baselineColorUp`,`baselineColorDown`],fromStrDefinition(e,t,n){let r=ic(n,t,e.baseline),i=ic(n,t,e.keyValue);return{...e,baseline:r,keyValue:i}},validateDefinition(e,t){return e.checkValidations(t,$p,em)},copyInSheetId:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,type:`scorecard`,keyValue:e.dataSource?.type===`range`?e.dataSource?.dataSets?.[0]?.dataRange:void 0,title:e.title||{text:``},baselineMode:Ae,baselineColorUp:je,baselineColorDown:Me,baseline:e.auxiliaryRange||``,humanize:e.humanize}},transformDefinition(e,t,{adaptRangeString:n}){let r,i;if(e.baseline){let{changeType:i,range:a}=n(t,e.baseline);i!==`REMOVE`&&(r=a)}if(e.keyValue){let{changeType:r,range:a}=n(t,e.keyValue);r!==`REMOVE`&&(i=a)}return{...e,baseline:r,keyValue:i}},duplicateInDuplicatedSheet(e,t,n){let r=vf(t,n,e.baseline),i=vf(t,n,e.keyValue);return{...e,baseline:r,keyValue:i}},toStrDefinition(e,t,n){return{...e,keyValue:e.keyValue?n.getRangeString(e.keyValue,t):void 0,baseline:e.baseline?n.getRangeString(e.baseline,t):void 0}},getContextCreation(e,t){return{...e,dataSource:{type:`range`,dataSets:e.keyValue?[{dataRange:e.keyValue,dataSetId:`0`}]:[]},auxiliaryRange:e.baseline}},getDefinitionForExcel:()=>void 0,updateRanges(e,t){let n=yf(e.baseline,t),r=yf(e.keyValue,t);return e.baseline===n&&e.keyValue===r?e:{...e,baseline:n,keyValue:r}},getRuntime(e,t){let n=``,r,i=e.getLocale();if(t.keyValue){let a={sheetId:t.keyValue.sheetId,col:t.keyValue.zone.left,row:t.keyValue.zone.top};r=e.getEvaluatedCell(a),n=Xp(r,t.humanize??!0,i)}let a,o=t.baseline;if(o){let t={sheetId:o.sheetId,col:o.zone.left,row:o.zone.top};a=e.getEvaluatedCell(t)}let{background:s,fontColor:c}=e.getStyleOfSingleCellChart(t.background,t.keyValue),l=Yp(a,r,t.baselineMode,t.humanize??!0,i),u=t.baselineMode===`progress`&&Pa(l,i)?I(l,i):0,d=t.title;return{title:{...d,text:d.text?e.dynamicTranslate(d.text):``},keyValue:n,keyDescr:t.keyDescr?.text?e.dynamicTranslate(t.keyDescr.text):``,baselineDisplay:l,baselineArrow:Qp(a,r,t.baselineMode),baselineColor:Zp(a,t.baselineMode,r,t.baselineColorUp,t.baselineColorDown),baselineDescr:t.baselineMode!==`progress`&&t.baselineDescr?.text?e.dynamicTranslate(t.baselineDescr.text):``,fontColor:c,background:s,baselineStyle:{...t.baselineMode!==`percentage`&&t.baselineMode!==`progress`&&o?e.getCellComputedStyle({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0,fontSize:t.baselineDescr?.fontSize,align:t.baselineDescr?.align},baselineDescrStyle:{textColor:t.baselineDescr?.color,...t.baselineDescr},keyValueStyle:{...t.keyValue?e.getCellComputedStyle({sheetId:t.keyValue.sheetId,col:t.keyValue.zone.left,row:t.keyValue.zone.top}):void 0,fontSize:t.keyDescr?.fontSize,align:t.keyDescr?.align},keyValueDescrStyle:{textColor:t.keyDescr?.color,...t.keyDescr},progressBar:t.baselineMode===`progress`?{value:u,color:u>0?t.baselineColorUp:t.baselineColorDown}:void 0}}};function am(e,t,n=1){let r=t.getContext(`2d`);if(!r)throw Error(`Unable to retrieve 2D context from canvas`);let i=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;t.width=i*e.canvas.width*n,t.height=i*e.canvas.height*n,r.scale(i*n,i*n);let a=e.canvas.width-20;if(r.fillStyle=e.canvas.backgroundColor,r.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){r.font=e.title.style.font,r.fillStyle=e.title.style.color;let t=r.textBaseline;r.textBaseline=`middle`,r.fillText(Id(r,e.title.text,a-e.title.position.x),e.title.position.x,e.title.position.y),r.textBaseline=t}if(e.baseline&&(r.font=e.baseline.style.font,r.fillStyle=e.baseline.style.color,Ld(r,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&tm){r.save(),r.fillStyle=e.baselineArrow.style.color,r.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);let t=e.baselineArrow.style.size/10;switch(r.scale(t,t),e.baselineArrow.direction){case`down`:r.fill(nm);break;case`up`:r.fill(rm);break}r.restore()}if(e.baselineDescr){let t=e.baselineDescr;r.font=t.style.font,r.fillStyle=t.style.color,r.fillText(Id(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.key&&(r.font=e.key.style.font,r.fillStyle=e.key.style.color,Ld(r,Id(r,e.key.text,a-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){let t=e.keyDescr;r.font=e.keyDescr?.style.font??t.style.font,r.fillStyle=t.style.color,r.fillText(Id(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(r.fillStyle=e.progressBar.style.backgroundColor,r.beginPath(),r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),r.fill(),r.fillStyle=e.progressBar.style.color,r.beginPath(),e.progressBar.value>0)r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{let t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));r.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}r.fill()}}let om=.05;function sm(e,t){let n=e||``;return t&&n?` `+n:n}function cm({width:e,height:t},n){return new lm({width:e,height:t},n).computeDesign()}var lm=class{runtime;context;width;height;constructor({width:e,height:t},n){if(this.runtime=n,this.width=e,this.height=t,typeof OffscreenCanvas>`u`)throw Error(`OffscreenCanvas is not supported in this environment`);let r=new globalThis.OffscreenCanvas(e,t).getContext(`2d`);if(!r)throw Error(`Unable to create scorecard measurement context`);this.context=r}computeDesign(){let e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles(),n=0;if(this.title){let r,i;switch({height:n,width:i}=this.getFullTextDimensions(this.title,t.title.font),this.runtime.title.align){case`center`:r=(this.width-i)/2;break;case`right`:r=this.width-i-20;break;default:r=20}e.title={text:this.title,style:t.title,position:{x:r,y:10+n/2}}}let r=t.baselineArrow?.size??0,{height:i,width:a}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);let o=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width,s;switch(this.runtime.baselineStyle?.align){case`right`:s=this.width-20-o-a;break;case`left`:s=20+r;break;default:s=(this.width-a-o+r)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:s,y:this.keyValue?this.height*(1-om*(this.runtime.progressBar?1:2)):this.height-(this.height-n-i)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-r,y:e.baseline.position.y-(i+r)/2}})),e.baseline&&this.baselineDescr){let n={x:e.baseline.position.x+a,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:n}}let c=0;this.runtime.progressBar&&(c=this.height*.05,e.progressBar={position:{x:40,y:this.height*(1-2*om)-i-c},dimension:{height:c,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});let{width:l,height:u}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),d=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width,f;switch(this.runtime.keyValueStyle?.align){case`right`:f=this.width-20-d-l;break;case`left`:f=20;break;default:f=(this.width-l-d)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(20,f),y:this.height*(.5-om*2)+10/2+(n+u/2)/2}}),e.key&&this.keyDescr){let n={x:e.key.position.x+l,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:n}}return e}get title(){return this.runtime.title.text??``}get keyValue(){return this.runtime.keyValue}get keyDescr(){return sm(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return sm(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return Tf(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.actualBoundingBoxAscent+n.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.fontBoundingBoxAscent+n.fontBoundingBoxDescent}}getTextStyles(){let e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e),n=this.runtime.baselineStyle?.fontSize??16,r=Math.floor(.9*n);return this.runtime.progressBar&&(n/=1.5),{title:{font:bd(this.runtime.title.fontSize??14,this.runtime.title.bold,this.runtime.title.italic),color:this.runtime.title.color??this.secondaryFontColor},keyValue:{color:this.runtime.keyValueStyle?.textColor||this.runtime.fontColor,font:bd(e,this.runtime.keyValueStyle?.bold,this.runtime.keyValueStyle?.italic),strikethrough:this.runtime.keyValueStyle?.strikethrough,underline:this.runtime.keyValueStyle?.underline},keyDescr:{color:this.runtime.keyValueDescrStyle?.textColor||this.runtime.fontColor,font:bd(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:bd(n,this.runtime.baselineStyle?.bold,this.runtime.baselineStyle?.italic),strikethrough:this.runtime.baselineStyle?.strikethrough,underline:this.runtime.baselineStyle?.underline,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor},baselineDescr:{font:bd(r,this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:this.baselineArrow===`neutral`||this.runtime.progressBar?void 0:{size:this.keyValue?.8*n:0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}};let um=/Mac/i,dm=!1;function fm(){let e=document.createElement(`div`);e.setAttribute(`style`,`width:10px;height:1px;zoom:2;position:absolute;z-index:-10000`),document.body.appendChild(e),dm=e.getBoundingClientRect().width!==20,document.body.removeChild(e)}(0,t.whenReady)(fm);let pm=[`Shift`,`Control`,`Alt`,`Meta`];function mm(e,t){return e?!!t.target&&e.contains(t.target):!1}function hm(e=1){let t=document.querySelector(`.o-grid-overlay`),n=t&&gm(t,e);if(!n)throw Error(`Can't find spreadsheet position`);return n}function gm(e,t){let n=e.closest(`.o-zoomable`),r,i=1;n?(r=n,i=dm?t:1):r=e;let a=r.getBoundingClientRect();return{x:a.x*i,y:a.y*i,width:a.width*i,height:a.height*i}}function _m(e){return e.el?vm(e.el):{x:0,y:0,width:0,height:0}}function vm(e){let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*ym(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*ym(t)}function bm(){return Array.from(document.querySelectorAll(`.o-spreadsheet .o-menu`))}function xm(e){let{startElement:t,endElement:n,startSelectionOffset:r,endSelectionOffset:i}=Sm(e);return{start:Cm(e,t,r),end:Cm(e,n,i)}}function Sm(e){let t=document.getSelection();return{startElement:t.anchorNode||e,startSelectionOffset:t.anchorOffset,endElement:t.focusNode||e,endSelectionOffset:t.focusOffset}}function Cm(e,t,n){let r=0,i=ym(e),a=i.next(),o=!0;for(;!a.done&&a.value!==t;)a.value.hasChildNodes()||a.value.textContent&&(r+=a.value.textContent.length),(a.value.nodeName===`P`||a.value.nodeName===`DIV`&&a.value!==e)&&(o?o=!1:r++),a=i.next();if(a.value!==t)return 0;if(!a.value.hasChildNodes())r+=n;else{let e=[...a.value.childNodes].slice(0,n);r+=e.reduce((t,n,r)=>{if(n.textContent!==null){let i=n.textContent.length;return n.nodeName===`P`&&r!==e.length-1&&i++,t+i}else return t},0)}return t.nodeName===`P`&&!o&&t.textContent===``&&r++,r}let wm=/^[a-zA-Z]$/;function Tm(e,t=`key`){let n=``;pm.includes(e.key)||(Dm(e)&&(n+=`Ctrl+`),e.altKey&&(n+=`Alt+`),e.shiftKey&&(n+=`Shift+`));let r=t===`key`?e.key:e.code;return n+=wm.test(r)?r.toUpperCase():r,n}function Em(){return!!um.test(navigator.userAgent)}function Dm(e){return Em()||Nm()?e.metaKey:e.ctrlKey}function Om(e){return e.button===1||Dm(e)&&e.button===0}function km(e,t){let n=document.createElement(`a`);n.href=e,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function Am(){return/Firefox/i.test(navigator.userAgent)}function jm(){return navigator.maxTouchPoints||1}function Mm(){return/Android/i.test(navigator.userAgent)}function Nm(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||navigator.platform===`MacIntel`&&jm()>1}function Pm(){return/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}function Fm(){return Mm()||Nm()||Pm()}let Im=`select, input, textarea, button, .o-select, .os-input, .o-input, .o-button, .o-button-icon, .o-button-link, .o-composer`;function Lm(e){let t=e.target,n=e.currentTarget;if(!n||!t||!n.contains(t))return!1;let r=t;for(;r&&r!==n;){if(r.matches(Im))return!0;r=r.parentElement}return n.matches(Im)}function Rm(e,t,n){let r=e.model.getters.getViewportZoomLevel();if(n===void 0&&(n=Vm(t,r)),!n)return zm(t);let i=t.clientX-n.x,a=t.clientY-n.y,o=i/r,s=a/r;return{ev:t,clientX:t.clientX-i+o,clientY:t.clientY-a+s,offsetX:o,offsetY:s}}function zm(e){return{ev:e,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY}}function Bm(e,t){return{height:t.height*e,width:t.width*e,x:t.x*e,y:t.y*e}}function Vm(e,t){let n=e.target;return!n||!(`classList`in n)||!(n instanceof Element)?null:gm(n,t)}var Hm=class extends t.Component{static template=`o-spreadsheet-ScorecardChart`;static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`chartContainer`);get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get title(){let e=this.env.model.getters.getChartDefinition(this.props.chartId).title.text;return e?this.env.model.getters.dynamicTranslate(e):``}setup(){(0,t.useEffect)(this.createChart.bind(this),()=>{let e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}createChart(){let e=this.canvas.el,t=this.env.model.getters.getViewportZoomLevel();am(cm(Bm(1/t,e.getBoundingClientRect()),this.runtime),e,t)}};function Um(e){return e=Nr(e).replace(`#`,``),e.length===8?e.slice(6)+e.slice(0,6):e}let Wm=`#F3F2F1`;function Gm(e,t,n=1,r){let i=r??Km(e),a=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;e.width=i.width*a,e.height=i.height*a;let o=e.getContext(`2d`);if(!o)throw Error(`Unable to retrieve 2D context from canvas`);o.scale(a*n,a*n);let s=Qm({width:i.width/n,height:i.height/n,x:0,y:0},t,o);Jm(o,s),qm(o,s),Xm(o,s),Ym(o,s),Zm(o,s)}function Km(e){if(e instanceof HTMLCanvasElement){let t=e.getBoundingClientRect();return{width:t.width,height:t.height}}return{width:e.width,height:e.height}}function qm(e,t){e.save();let n=t.gauge,r=n.rect.x+n.rect.width/2,i=n.rect.y+n.rect.height,a=n.rect.height-n.arcWidth/2;if(a<0)return;let o=n.percentage===1?0:Math.PI*(1+n.percentage);e.strokeStyle=Wm,e.beginPath(),e.lineWidth=n.arcWidth,e.arc(r,i,a,o,0),e.stroke(),e.strokeStyle=n.color,e.beginPath(),e.arc(r,i,a,Math.PI,o),e.stroke(),e.restore()}function Jm(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}function Ym(e,t){for(let n of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign=`center`,e.fillStyle=n.color,e.font=`${n.fontSize}px ${De}`,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Xm(e,t){let{x:n,y:r,width:i,height:a}=t.gauge.rect;for(let o of t.inflectionValues){e.save(),e.translate(n+i/2-.5,r+a-.5),e.rotate(Math.PI/2-o.rotation),e.lineWidth=2,e.strokeStyle=Tf(t.backgroundColor)+`aa`,e.beginPath(),e.moveTo(0,-(a-t.gauge.arcWidth)),e.lineTo(0,-a-3),e.stroke(),e.textAlign=`center`,e.font=`${o.fontSize}px ${De}`,e.fillStyle=o.color;let s=-a-6-o.offset;e.fillText(o.label,0,s),e.restore()}}function Zm(e,t){e.save();let n=t.title;e.font=bd(n.fontSize,n.bold,n.italic),e.textBaseline=`middle`,e.fillStyle=n.color,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Qm(e,t,n){let r=t.maxValue,i=t.minValue,a=oh(t,`animated`),o=$m(e,t.title.text),s=o.width/6,c=a?(a-i.value)/(r.value-i.value):0,l={x:e.width/2,y:o.y+o.height-o.height/12},u=80;o.height<300&&(u*=o.height/300);let d=o.width/2,f=t.gaugeValue?.label||`-`;Sd(n,f,{fontSize:u},`px`)>d&&(u=Md(d,u,e=>Sd(n,f,{fontSize:e},`px`)));let p={x:o.x+s/2,y:o.y+o.height+12},m={x:o.x+o.width-s/2,y:o.y+o.height+12},h=Tf(t.background),g=eh(t,o,h,n),_=0,v=0,y=0;switch(t.title.text&&({width:v,height:y}=Td(n,t.title.text,{fontSize:16,...t.title},`px`)),t.title.align){case`right`:_=e.width-v-20;break;case`center`:_=(e.width-v)/2;break;default:_=20;break}return{width:e.width,height:e.height,title:{label:t.title.text??``,fontSize:t.title.fontSize??16,textPosition:{x:_,y:15+y/2},color:t.title.color??h,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:o,arcWidth:s,percentage:S(c,0,1),color:th(t)},inflectionValues:g,gaugeValue:{label:f,textPosition:l,fontSize:u,color:h},minLabel:{label:t.minValue.label,textPosition:p,fontSize:12,color:h},maxLabel:{label:t.maxValue.label,textPosition:m,fontSize:12,color:h}}}function $m(e,t){let n=t?25:0,r=e.height-20-n-10,i=e.width-60,a,o;return i>2*r?(a=2*r,o=r):(a=i,o=i/2),{x:30+(i-a)/2,y:n+10+(r-o)/2,width:a,height:o}}function eh(e,t,n,r){let i=e.maxValue,a=e.minValue,o={x:t.x+t.width/2,y:t.y+t.height},s={fontSize:12},c=[],l=[];for(let u of e.inflectionValues){let e=(u.value-a.value)/(i.value-a.value),d=Sd(r,u.label,s,`px`),f=Math.PI-Math.PI*e,p=ah(f,t.height+6,o.x,o.y,d+2,12),m=l.some(e=>ih(e,p))?12:0;l.push(p),c.push({rotation:f,label:u.label,fontSize:12,color:n,offset:m})}return c}function th(e){let t=oh(e,`final`);if(t===void 0)return Wm;for(let n=0;n<e.inflectionValues.length;n++){let r=e.inflectionValues[n];if(r.operator===`<`&&t<r.value||r.operator===`<=`&&t<=r.value)return e.colors[n]}return e.colors.at(-1)}function nh(e){return[{start:e.topLeft,end:e.topRight},{start:e.topRight,end:e.bottomRight},{start:e.bottomRight,end:e.bottomLeft},{start:e.bottomLeft,end:e.topLeft}]}function rh(e,t){let n=e.start,r=e.end,i=t.start,a=t.end;function o(e,t,n){return(n.y-e.y)*(t.x-e.x)>(t.y-e.y)*(n.x-e.x)}return o(n,i,a)!==o(r,i,a)&&o(n,r,i)!==o(n,r,a)}function ih(e,t){let n=nh(e),r=nh(t);for(let e of n)for(let t of r)if(rh(e,t))return!0;return!1}function ah(e,t,n,r,i,a){let o=Math.cos(e),s=Math.sin(e),c=o*t,l=s*t,u=i/2*s,d=i/2*o,f={x:c+u+n,y:r-(l-d)},p={x:c-u+n,y:r-(l+d)},m=o*(t+a),h=s*(t+a),g={x:m-u+n,y:r-(h+d)};return{bottomLeft:p,bottomRight:f,topRight:{x:m+u+n,y:r-(h-d)},topLeft:g}}function oh(e,t){return t===`animated`&&e.animationValue!==void 0?e.animationValue:e.gaugeValue?.value}let sh={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:[`mousemove`,`mouseout`,`click`,`touchstart`,`touchmove`,`mouseup`]};async function ch(e,t,n){try{let r=uh(t.width,t.height),i=ph(r,e,t,n),a=await fh(r);return i(),a}catch(e){console.log(`Error exporting chart to image URL: `+e.message)}}async function lh(e,t,n){try{let r=uh(t.width,t.height),i=ph(r,e,t,n),a=await dh(r);return i(),a}catch(e){console.log(`Error exporting chart to image file: `+e.message)}return null}function uh(e,t){if(!globalThis.OffscreenCanvas)throw Error(`converting a chart to an image using OffscreenCanvas is not supported in this environment`);return new OffscreenCanvas(e,t)}async function dh(e){return`convertToBlob`in e?e.convertToBlob({type:`image/png`}):new Promise(t=>e.toBlob(t,`image/png`))}async function fh(e){let t=await dh(e);if(t)return new Promise(e=>{let n=new FileReader;n.addEventListener(`load`,()=>{e(n.result)}),n.readAsDataURL(t)})}function ph(e,t,n,r){if(`chartJsConfig`in t){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let n=Hd();n||Ud();let r=x(t.chartJsConfig);if(!globalThis.Chart.registry.controllers.get(r.type))throw console.log(`Chart of type "${r.type}" is not registered in Chart.js library.`),n||Wd(),Error(`Chart of type "${r.type}" is not registered in Chart.js library.`);let i=new globalThis.Chart(e,r);return()=>{i.destroy(),n||Wd()}}else r===`scorecard`?am(cm(n,t),e):r===`gauge`&&Gm(e,t,1,n);return()=>{}}function mh(e,t){if(!e)throw new N(t)}function hh(e,t=j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)){if(e===0)throw new Vi(t)}function gh(e){return e.length===1||e[0].length===1}function _h(...e){if(e.every(Je)){let t=e[0].length,n=e[0][0].length;for(let r of e)if(r.length!==t||r[0].length!==n)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(e.length!==1||e[0].length!==1))}function vh(e){return e.length===e[0].length}let yh=e=>j(`The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.`,e);function bh(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Array(e).fill(0),t[n][n]=1;return t}function xh(e){if(e.length<1||e[0].length<1)throw Error(`invertMatrix: an empty matrix cannot be inverted.`);if(e.length!==e[0].length)throw Error(`invertMatrix: only square matrices are invertible`);let t=1,n=e.length,r=bh(n),i=e.map(e=>e.slice());for(let e=0;e<n;e++){let a=i[e][e];if(a===0){for(let a=e+1;a<n;a++)if(i[e][a]!==0){Sh(i,e,a),Sh(r,e,a),t*=-1;break}if(a=i[e][e],a===0)return{determinant:0}}for(let t=0;t<n;t++)i[t][e]=i[t][e]/a,r[t][e]=r[t][e]/a;t*=a;for(let t=0;t<n;t++){if(t===e)continue;let a=i[e][t];for(let o=0;o<n;o++)i[o][t]-=a*i[o][e],r[o][t]-=a*r[o][e]}}return{inverted:r,determinant:t}}function Sh(e,t,n){for(let r=0;r<e.length;r++){let i=e[r][t];e[r][t]=e[r][n],e[r][n]=i}}function Ch(e,t){if(e.length<1||t.length<1)throw Error(`multiplyMatrices: empty matrices cannot be multiplied.`);if(e.length!==t[0].length)throw Error(`multiplyMatrices: incompatible matrices size.`);let n=e[0].length,r=t.length,i=e.length,a=Array(r);for(let o=0;o<r;o++){a[o]=Array(n);for(let r=0;r<n;r++){let n=0;for(let a=0;a<i;a++)n+=e[a][r]*t[o][a];a[o][r]=n}}return a}function wh(e){if(!Je(e))return e;if(!Th(e))throw Error(`The value should be a scalar or a 1x1 matrix`);return e[0][0]}function Th(e){return e.length===1&&e[0].length===1}function Eh(e){return Je(e)&&!Th(e)}function Dh(...e){let t=e[0].length;e.forEach((e,n)=>mh(e.length===t,j(`[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).`,n.toString(),t.toString(),e.length.toString())))}function Oh(e,t){let n=0,r=oo(e,(e,t)=>(n+=1,e+t),0,t);return hh(n),r/n}function kh(e,t){let n=[];ro(e,e=>{n.push(e.value)},t),n.sort((e,t)=>e-t);let r=n.length;if(r===0)return;let i=Math.floor(r/2);return r%2==0?(n[i-1]+n[i])/2:n[i]}function Ah(e,t){let n=0;for(let r of e)if(Je(r))for(let e of r)for(let t of e)typeof t.value==`number`&&(n+=1);else{let e=r?.value;!F(e)&&(typeof e!=`string`||Pa(e,t)||ia(e,t))&&(n+=1)}return n}function jh(e){return ao(e,(e,t)=>t!==void 0&&t.value!==null?e+1:e,0)}function Mh(e,t){let n={value:-1/0};return ro(e,e=>{e.value>=n.value&&(n=e)},t),n.value===-1/0?{value:0}:n}function Nh(e,t){let n={value:1/0};return ro(e,e=>{e.value<=n.value&&(n=e)},t),n.value===1/0?{value:0}:n}function Ph(e,t,n){let r=e[0].length?e:[C(1,t.flat().length+1)],i=r.length,a=n[0].length?n:r;return a=a.length===i?fo(a):a,{_X:r,_newX:a}}function Fh(e,t,n=!0,r=!1){let i=t.flat(),a=i.length,{_X:o}=Ph(e,t,[[]]);o=o.length===a?fo(o):o.slice(),Dh(o[0],i);let s=o.length,c=a-s-+!!n,l=[i],u=fo(o.reverse()),d=[];for(let e=0;e<s;e++)if(d.push(0),n){for(let t of o[e])d[e]+=t;d[e]/=a}let f=0;if(n){for(let e of i)f+=e;f/=a}let p=u.map(e=>e.map((e,t)=>e-d[t]));n&&u.forEach(e=>e.push(1));let m=Lh(u,l);if(n||m.push([0]),!r)return m;let{inverted:h}=xh(Ch(p,fo(p)));if(h===void 0)throw new N(j(`Matrix is not invertible`));let g=0,_=0;for(let e=0;e<a;e++){let t=i[e]-f,n=0;for(let t=0;t<s;t++){let r=p[e][t];n+=r*m[t][0]}let r=t-n;g+=r*r,_+=n*n}let v=Math.sqrt(g/c),y=_/(_+g),b=_/s/(g/c),ee=[];for(let e=0;e<s;e++)ee.push(v*Math.sqrt(h[e][e]));if(n){let e=Ch(h,[d]),t=Ch(fo([d]),e);ee.push(v*Math.sqrt(t[0][0]+1/i.length))}let te=[[m[0][0],ee[0],y,b,_],[m[1][0],ee[1],v,c,g]];for(let e=2;e<s;e++)te.push([m[e][0],ee[e],``,``,``]);return n?te.push([m[s][0],ee[s],``,``,``]):te.push([0,``,``,``,``]),te}function Ih(e,t,n,r){Dh(t,e),mh(n>=1,j(`Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible.`));let i=[e],a=t.map(e=>C(0,n).map(t=>e**+(n-t)));r&&a.forEach(e=>e.push(1));let o=Lh(a,i);return r||o.push([0]),o}function Lh(e,t){let{inverted:n}=xh(Ch(e,fo(e)));if(n===void 0)throw new N(j(`Matrix is not invertible`));return fo(Ch(n,Ch(e,t)))}function Rh(e,t,n){return e.reduce((e,r,i)=>e+r*t**+(n-i),0)}function zh(e){return e.map(e=>e.map(e=>Math.exp(e)))}function Bh(e){return e.map(e=>e.map(e=>Math.log(e)))}function Vh(e,t,n,r){let{_X:i,_newX:a}=Ph(t,e,n),o=Fh(i,e,r,!1),s=o.length-1,c=a.map(e=>{let t=0;for(let n=0;n<s;n++)t+=o[n][0]*e[s-n-1];return t+=o[s][0],[t]});return c.length===n.length?c:fo(c)}function Hh(e,t,n=2){let r=[];for(let e=0;e<n-1;e++)r.push({x:t[e],y:NaN});for(let i=0;i<=e.length-n;i++){let a=0;for(let t=i;t<i+n;t++)a+=e[t];r.push({x:t[i+n-1],y:a/n})}return r}let Uh=[`line`,`bar`,`pie`,`scorecard`,`gauge`,`scatter`,`combo`,`waterfall`,`pyramid`,`radar`,`geo`,`funnel`,`sunburst`,`treemap`,`calendar`];function Wh(e){let t=pi[e];return t===void 0?void 0:{minColor:t[0],midColor:t.length===3?t[1]:void 0,maxColor:t[t.length-1]}}let Gh=new Set([`containsText`,`notContainsText`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`beginsWithText`,`endsWithText`,`isNotEmpty`,`isEmpty`,`isNotEqual`,`isEqual`,`customFormula`,`dateIs`,`dateIsBefore`,`dateIsAfter`,`dateIsOnOrBefore`,`dateIsOnOrAfter`,`top10`,`uniqueValues`,`duplicateValues`]),Kh=new Set([`containsText`,`notContainsText`,`isEqualText`,`isEmail`,`isLink`,`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`dateIsValid`,`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isBoolean`,`isValueInList`,`isValueInRange`,`customFormula`]),qh=`(previous)`,Jh=`(next)`,Yh=[`containsText`,`notContainsText`,`isEqualText`,`isEmpty`,`isNotEmpty`,`beginsWithText`,`endsWithText`],Xh=[`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isEmpty`,`isNotEmpty`],Zh=[`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`isEmpty`,`isNotEmpty`];function Qh(e){let t=!1,n=!0;return ho(e,e=>(t=!0,n&&=e,n)),{foundBoolean:t,result:n}}function $h(e){let t=!1,n=!1;return ho(e,e=>(t=!0,n||=e,!n)),{foundBoolean:t,result:n}}function eg(e,t){return oo(e,(e,t)=>e+t,0,t)}function tg(e){return ao(e,(e,t)=>Eo(t)?e.add(t?.value):e,new Set).size}function ng(e){let[t,n]=e.split(`/`);return Number(n)*100+Number(t)}let rg=new A;function ig(e){return rg.get(e)}let ag={normalizeFunctionValue(e){return I(e,V)},toValueAndFormat(e,t){return{value:I(e,V),format:`dd mmm yyyy`}},toFunctionValue(e){let t=z(e,V);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},og={normalizeFunctionValue(e){let t=I(e,V);if(t<1||t>31)throw new N(j(`%s is not a valid day of month (it should be a number between 1 and 31)`,t));return t},toValueAndFormat(e){return{value:I(e,V),format:`0`}},toFunctionValue(e){return`${e}`}},sg={normalizeFunctionValue(e){let t=I(e,V);if(t<1||t>7)throw new N(j(`%s is not a valid day of week (it should be a number between 1 and 7)`,t));return t},toValueAndFormat(e,t){return{value:Cl[(e-1+(t||V).weekStart)%7].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},cg={normalizeFunctionValue(e){let t=I(e,V);if(t<0||t>53)throw new N(j(`%s is not a valid week (it should be a number between 0 and 53)`,t));return t},toValueAndFormat(e){return{value:I(e,V),format:`0`}},toFunctionValue(e){return`${e}`}},lg={normalizeFunctionValue(e){let t=I(e,V);if(t<1||t>12)throw new N(j(`%s is not a valid month (it should be a number between 1 and 12)`,t));return t},toValueAndFormat(e){return{value:Sl[I(e,V)-1].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},ug={normalizeFunctionValue(e){return H(I(e,V),{locale:V,format:`mm/yyyy`})},toValueAndFormat(e){return{value:I(e,V),format:`mmmm yyyy`}},toFunctionValue(e){let t=z(e,V);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`},toComparableValue(e){return ng(e)}},dg={normalizeFunctionValue(e){let t=I(e,V);if(t<1||t>4)throw new N(j(`%s is not a valid quarter (it should be a number between 1 and 4)`,t));return t},toValueAndFormat(e){return{value:j(`Q%(quarter_number)s`,{quarter_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},fg={normalizeFunctionValue(e){let t=I(e,V);return t>3e3?z(t,V).getFullYear():t},toValueAndFormat(e){return{value:I(e,V),format:`0`}},toFunctionValue(e){return`${e}`}},pg={normalizeFunctionValue(e){let t=I(e,V);if(t<0||t>23)throw new N(j(`%s is not a valid hour (it should be a number between 0 and 23)`,t));return t},toValueAndFormat(e){return{value:j(`%(hour_number)sh`,{hour_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},mg={normalizeFunctionValue(e){let t=I(e,V);if(t<0||t>59)throw new N(j(`%s is not a valid minute (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:j(`%(minute_number)s'`,{minute_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},hg={normalizeFunctionValue(e){let t=I(e,V);if(t<0||t>59)throw new N(j(`%s is not a valid second (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:j(`%(second_number)s''`,{second_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}};function gg(e){return{normalizeFunctionValue(t){return t===null?null:e.normalizeFunctionValue(t)},toValueAndFormat(t,n){return t===null?{value:j(`(Undefined)`)}:e.toValueAndFormat(t,n)},toFunctionValue(t){return t===null?`false`:e.toFunctionValue(t)},toComparableValue(t){if(t!==null)return e.toComparableValue?.(t)}}}rg.add(`day`,gg(ag)).add(`year`,gg(fg)).add(`day_of_month`,gg(og)).add(`iso_week_number`,gg(cg)).add(`month_number`,gg(lg)).add(`month`,gg(ug)).add(`quarter_number`,gg(dg)).add(`day_of_week`,gg(sg)).add(`hour_number`,gg(pg)).add(`minute_number`,gg(mg)).add(`second_number`,gg(hg));let _g={displayTotals:!0,displayColumnHeaders:!0,displayMeasuresRow:!0,numberOfRows:Number.MAX_VALUE,numberOfColumns:Number.MAX_VALUE,tableStyleId:`None`,bandedRows:!1,bandedColumns:!1,hasFilters:!1,tabularForm:!1},vg={count:j(`Count`),count_distinct:j(`Count Distinct`),bool_and:j(`Boolean And`),bool_or:j(`Boolean Or`),max:j(`Maximum`),min:j(`Minimum`),avg:j(`Average`),sum:j(`Sum`)},yg=[`max`,`min`,`avg`,`sum`,`count_distinct`,`count`],bg={integer:yg,char:yg,datetime:yg,boolean:[`count_distinct`,`count`,`bool_and`,`bool_or`]},xg={};for(let e in bg){xg[e]={};for(let t of bg[e])xg[e][t]=vg[t]}let Sg={count:e=>({value:jh([e]),format:`0`}),count_distinct:e=>({value:tg([e]),format:`0`}),bool_and:e=>({value:Qh([e]).result}),bool_or:e=>({value:$h([e]).result}),max:(e,t)=>Mh([e],t),min:(e,t)=>Nh([e],t),avg:(e,t)=>({value:Oh([e],t),format:za(e)}),sum:(e,t)=>({value:eg([e],t),format:za(e)})};function Cg(e){let t=Object.keys(e);if(!t.length)return 0;let n=t.map(e=>parseInt(e,10));return Math.max(...n)}let wg={year:j(`Year`),quarter:j(`Quarter & Year`),month:j(`Month & Year`),week:j(`Week & Year`),day:j(`Day`),quarter_number:j(`Quarter`),month_number:j(`Month`),iso_week_number:j(`Week`),day_of_month:j(`Day of Month`),day_of_week:j(`Day of Week`),hour_number:j(`Hour`),minute_number:j(`Minute`),second_number:j(`Second`)},Tg=[`date`,`datetime`];function Eg(e){let[t,n]=e.split(`:`);return n?{fieldName:t,granularity:n}:{fieldName:t}}function Dg(e){return Tg.includes(e.type)}function Og(e,t,n){let r=[e];n&&r.push(`"${n}"`);for(let{field:e,value:n,type:i}of t){if(e===`measure`){r.push(`"measure"`,`"${n}"`);continue}let{granularity:t}=Eg(e),a=Ng(n,{type:i,granularity:t});r.push(`"${e}"`,a)}return r}function kg(e,t){let n=0,r=0,i=t.columns.map(e=>e.nameWithGranularity),a=t.rows.map(e=>e.nameWithGranularity);for(;e[n]!==void 0&&e[n]===a[r];)n++,r++;for(r=0;e[n]!==void 0&&e[n]===i[r];)n++,r++;return e.length===n}function Ag(e,t){switch(t.type){case`HEADER`:return`=PIVOT.HEADER(${Og(e,t.domain).join(`,`)})`;case`VALUE`:return`=PIVOT.VALUE(${Og(e,t.domain,t.measure).join(`,`)})`;case`MEASURE_HEADER`:return`=PIVOT.HEADER(${Og(e,[...t.domain,{field:`measure`,value:t.measure,type:`char`}]).join(`,`)})`}return``}function jg(e,t){if(t===null||t===`null`)return null;let n=typeof t==`object`?t.value:t;if(F(n))return n;if(e.type===`custom`)return eo(t)??null;let r=typeof t==`boolean`?L(t).toLocaleLowerCase():L(t);if(r===`null`)return null;if(!Fg.contains(e.type))throw new N(j(`Field %(field)s is not supported because of its type (%(type)s)`,{field:e.displayName,type:e.type}));return r.toLowerCase()===`false`?!1:Fg.get(e.type)(r,e)}function Mg(e,t){return ig(t.granularity??`month`).normalizeFunctionValue(e)}function Ng(e,t){return e===null?`"null"`:Ig.contains(t.type)?Ig.get(t.type)(e,t.granularity):`"${e}"`}function Pg(e,t){return ig(t??`month`).toFunctionValue(e)}let Fg=new A;Fg.add(`date`,Mg).add(`datetime`,Mg).add(`integer`,e=>I(e,V)).add(`boolean`,e=>R(e)).add(`char`,e=>L(e)).add(`custom`,e=>e);let Ig=new A;Ig.add(`date`,Pg).add(`datetime`,Pg).add(`integer`,e=>`${I(e,V)}`).add(`boolean`,e=>R(e)?`TRUE`:`FALSE`).add(`char`,e=>`"${L(e).replace(/"/g,`\\"`)}"`).add(`custom`,e=>typeof e==`string`?`"${e}"`:String(e));function Lg(e){return e.displayName+(e.granularity?` (${wg[e.granularity]})`:``)}function Rg(e,t){return e.length===0?t:{...t,format:(t.format||`@`)+`* `}}function zg(e,t){try{if(!t.getMeasure(e.measure))return!1;let n=t.definition.columns;for(let r=0;r<e.domain.length;r++){if(n[r].nameWithGranularity!==e.domain[r].field)return!1;let i=t.getPossibleFieldValues(n[r]).map(e=>e.value);if(!i.includes(e.domain[r].value)&&!(e.domain[r].value===null&&i.includes(``)))return!1}return!0}catch{return!1}}function Bg(e,t){return Kt(e,t.groups.map(e=>e.name),{compute:(e,t)=>`${e}${t}`,start:2})}function Vg(e,t){return Kt(e,Object.values(t).map(e=>[e?.name,e?.string]).flat().filter(w),{compute:(e,t)=>`${e}${t}`,start:2})}function Hg(e,t){let n={};for(let r of Object.values(e.customFields||{}))t[r.parentField]&&(n[r.name]={type:`custom`,isCustomField:!0,name:r.name,string:r.name,customGroups:r.groups,parentField:r.parentField});return n}function Ug(e,t){t.groups=t.groups.filter(t=>!t.values.some(t=>e.includes(t)))}function Wg(e,t,n){let r=e.rows.some(e=>e.fieldName===t)?e.rows:e.columns,i=r.findIndex(e=>e.fieldName===t);return i===-1||r.some(e=>e.fieldName===n)||r.splice(i,0,{fieldName:n}),e}function Gg(e,t,n){return Object.values(e.customFields||{}).find(e=>e.parentField===t.name)||{parentField:t.name,name:Vg(t.string,n),groups:[]}}function Kg(e,t){let n=t.model.getters.getPivotCellFromPosition(e),r=t.model.getters.getPivotIdFromPosition(e);if(!r||n.type!==`HEADER`)return;let i=t.model.getters.getPivotCoreDefinition(r),a=i.collapsedDomains?.[n.dimension]?[...i.collapsedDomains[n.dimension]]:[],o=a.findIndex(e=>T(e,n.domain));o===-1?a.push(n.domain):a.splice(o,1);let s=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};s[n.dimension]=a,t.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...i,collapsedDomains:s}})}function qg(e,t,n,r,i,a,o){let s=e.style;return{numberOfRows:t===void 0?s?.numberOfRows??_g.numberOfRows:I(t,o),numberOfColumns:i===void 0?s?.numberOfColumns??_g.numberOfColumns:I(i,o),displayTotals:n===void 0?s?.displayTotals??_g.displayTotals:R(n),displayColumnHeaders:r===void 0?s?.displayColumnHeaders??_g.displayColumnHeaders:R(r),displayMeasuresRow:a===void 0?s?.displayMeasuresRow??_g.displayMeasuresRow:R(a),tableStyleId:s?.tableStyleId||_g.tableStyleId,bandedRows:s?.bandedRows??_g.bandedRows,bandedColumns:s?.bandedColumns??_g.bandedColumns,hasFilters:s?.hasFilters??_g.hasFilters,tabularForm:s?.tabularForm??_g.tabularForm}}function Jg(e,t=`>`){let n=e.indexOf(t),r=e.lastIndexOf(t);return!e||!n||n===r?e:`${e.slice(0,n+1)} … ${e.slice(r)}`}function Yg(e,t,n){return n.map(n=>{if(n.id===e.id)return t;if(!n.computedBy||e.id===t.id)return n;let r=ls(n.computedBy.formula).map(n=>n.type===`SYMBOL`&&n.value===tt(e.id)?tt(t.id):n.value).join(``);return{...n,computedBy:{...n.computedBy,formula:r}}})}let Xg=Symbol(`NULL`);function Zg(e,t,n){let r=e.granularity||`month`;if(!(r in Qg))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:Xg;if(!Qg[r].set.has(t)){Qg[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=z(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(I(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(I(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}Qg[r].values[i]=jg(e,a)}return Qg[r].values[i]}let Qg={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function $g(){for(let e in Qg)Qg[e].set.clear(),Qg[e].values={}}let e_=Object.freeze({value:null}),t_=Object.freeze({value:0});function n_(e,{labelValues:t,dataSetsValues:n},r){let i=r.getLocale(),a=t.map(({value:e,format:t})=>H(e,{format:t,locale:i}));({labels:a,dataSetsValues:n}=D_(a,n)),e.aggregated&&({labels:a,dataSetsValues:n}=j_(a,n));let o=N_(e.dataSetStyles,n,`left`),s=N_(e.dataSetStyles,n,`right`),c=e.horizontal?{x:o||s}:{y:o,y1:s},l=[];for(let t in n){let{data:r,dataSetId:i}=n[t],a=e.dataSetStyles?.[i]?.trend;if(!a?.display||e.horizontal){l.push(void 0);continue}let o=p_(a,r);l.push(o)}return{dataSetsValues:n,trendDataSetsValues:l,axisFormats:c,labels:a,locale:r.getLocale(),topPadding:F_(e,r)}}function r_(e,t){switch(t){case`day_of_week`:return Cl[e-1].toString();case`hour_number`:{let t=String(e%12).padStart(2,`0`);return j(e<12?`%(hour)s AM`:`%(hour)s PM`,{hour:t})}case`month_number`:return Sl[e-1].toString();case`iso_week_number`:return j(`W%(weekNumber)s`,{weekNumber:String(e).padStart(2,`0`)});case`quarter_number`:return j(`Q%(value)s`,{value:e});default:return e.toString()}}function i_(e,t,n,r,i){let a={},o=[],s=[],c=[];for(let l=0;l<e?.length;l++){let u=I(Zg({granularity:n,type:`date`,displayName:`date`},e[l].value,V),i);u in a||(o.push(u),a[u]={});let d=I(Zg({granularity:r,type:`date`,displayName:`date`},e[l].value,V),i);c.includes(d)||(s.push(d),c.push(d)),d in a[u]||(a[u][d]={value:0});let f=t[l];U(f)&&(a[u][d].value+=f.value)}return o.sort((e,t)=>e-t),s.sort((e,t)=>t-e),{dataSetsValues:s.map(e=>({data:o.map(t=>a?.[t]?.[e]),label:r_(e,r),hidden:!1,dataSetId:`0`})),labels:o.map(e=>({value:r_(e,n)}))}}function a_(e,{labelValues:t,dataSetsValues:n},r){let i=t,a=r.getLocale();({labels:i,dataSetsValues:n}=O_(i,n));let o={y:N_(e.dataSetStyles,n,`left`)};return{labels:i,dataSetsValues:n}=i_(i,n[0]?.data??[],e.horizontalGroupBy??`day_of_week`,e.verticalGroupBy??`hour_number`,a),{dataSetsValues:n,axisFormats:o,labels:i.map(({value:e})=>String(e??``)),locale:r.getLocale(),topPadding:F_(e,r)}}function o_(e,{labelValues:t,dataSetsValues:n},r){let i=n_(e,{labelValues:t,dataSetsValues:n.slice(0,2)},r),a=i.dataSetsValues.filter(e=>!e.hidden),o=[];if(a[0]){let e=a[0].data.map(e=>U(e)&&e.value>0?e:t_);o.push({...a[0],data:e})}if(a[1]){let e=a[1].data.map(e=>U(e)&&e.value>0?{value:-e.value}:t_);o.push({...a[1],data:e})}return{...i,dataSetsValues:o}}function s_(e,{labelValues:t,dataSetsValues:n},r){let i=__(e,{labelValues:t,dataSetsValues:n}),a=i===`linear`?t.map(({value:e})=>String(e??``)):t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:a,dataSetsValues:n}=D_(a,n)),i===`time`&&({labels:a,dataSetsValues:n}=E_(a,n)),e.aggregated&&({labels:a,dataSetsValues:n}=j_(a,n)),e.cumulative&&(n=P_(n,`asc`));let o={y:N_(e.dataSetStyles,n,`left`),y1:N_(e.dataSetStyles,n,`right`),x:M_(t)},s=[];for(let t in n){let{data:o,dataSetId:c}=n[t],l=e.dataSetStyles?.[c]?.trend;if(!l?.display){s.push(void 0);continue}s.push(m_(l,o,a,i,r.getLocale()))}return{dataSetsValues:n,axisFormats:o,labels:a,locale:r.getLocale(),trendDataSetsValues:s,axisType:i,topPadding:F_(e,r)}}function c_(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=D_(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=j_(i,n)),{dataSetsValues:n,labels:i}=T_(i,n);let a=N_(e.dataSetStyles,n,`left`);return{dataSetsValues:n,axisFormats:{y:a},labels:i,locale:r.getLocale(),topPadding:F_(e,r)}}function l_(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=D_(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=j_(i,n));let a={r:N_(e.dataSetStyles,n,`left`)||N_(e.dataSetStyles,n,`right`)};return{dataSetsValues:n,axisFormats:a,labels:i,locale:r.getLocale()}}function u_(e,{labelValues:t,dataSetsValues:n},r){n=n.slice(0,1);let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=j_(i,n));let a=N_(e.dataSetStyles,n,`left`)||N_(e.dataSetStyles,n,`right`);return{dataSetsValues:n,axisFormats:{y:a},labels:i,locale:r.getLocale(),availableRegions:r.getGeoChartAvailableRegions(),geoFeatureNameToId:r.geoFeatureNameToId,getGeoJsonFeatures:r.getGeoJsonFeatures}}function d_(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=D_(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=j_(i,n)),e.cumulative&&(n=P_(n,`desc`));let a=N_(e.dataSetStyles,n,`left`)||N_(e.dataSetStyles,n,`right`);return{dataSetsValues:n,axisFormats:{x:a},labels:i,locale:r.getLocale()}}function f_(e,{labelValues:t,dataSetsValues:n},r){let i=t;return{labels:i,dataSetsValues:n}=A_(i,n),{labels:i,dataSetsValues:n}=k_(i,n),{dataSetsValues:n,axisFormats:{y:M_(i)},labels:i.map(({value:e})=>String(e??``)),locale:r.getLocale()}}function p_(e,t){let n=[],r=[],i=[];for(let e=0;e<t.length;e++){let a=t[e];U(a)&&(n.push(a.value),r.push(e+1)),i.push(e+1)}let a=h_(e,n,r,C(.5,i.length+.55,.2));return a.length?a:void 0}function m_(e,t,n,r,i){let a=[],o=[],s=[],c=t.length;if(c<2)return;switch(r){case`category`:for(let e=0;e<c;e++){let n=t[e];U(n)&&(a.push(n.value),o.push(e+1)),s.push(e+1)}break;case`linear`:for(let e=0;e<t.length;e++){let r=Number(n[e]);if(isNaN(r))continue;let i=t[e];U(i)&&(a.push(i.value),o.push(r)),s.push(r)}break;case`time`:for(let e=0;e<t.length;e++){let r=I({value:n[e]},i),c=t[e];U(c)&&(a.push(c.value),o.push(r)),s.push(r)}break}let l=Math.min(...s),u=Math.max(...s);if(u===l)return;let d=5*s.length,f=(u-l)/d,p=h_(e,a,o,C(l,u+f/2,f));if(p.length)return p}function h_(e,t,n,r){if(t.length<2||n.length<2||r.length===0)return[];let{normalizedLabels:i,normalizedNewLabels:a}=g_(n,r,e);try{switch(e.type){case`polynomial`:{let n=e.order;if(!n)return r.map(e=>({x:e,y:NaN}));if(n===1)return Vh([t],[i],[a],!0)[0].map((e,t)=>({x:r[t],y:e}));let o=Ih(t,i,n,!0).flat();return a.map((e,t)=>({x:r[t],y:Rh(o,e,n)}))}case`exponential`:{let e=[],n=[];for(let r=0;r<t.length;r++)t[r]>0&&(e.push(Math.log(t[r])),n.push(i[r]));return n.length?zh(Vh([e],[n],[a],!0))[0].map((e,t)=>({x:r[t],y:e})):r.map(e=>({x:e,y:NaN}))}case`logarithmic`:return Vh([t],Bh([i]),Bh([a]),!0)[0].map((e,t)=>({x:r[t],y:e}));case`trailingMovingAverage`:return Hh(t,n,e.window);default:return r.map(e=>({x:e,y:NaN}))}}catch{return r.map(e=>({x:e,y:NaN}))}}function g_(e,t,n){let r=[],i=[];if(n.type===`logarithmic`){let n=Math.max(...e.map(Math.abs));r=e.map(e=>e/n),i=t.map(e=>e/n)}else{let n=Math.max(...e),a=n-Math.min(...e);r=e.map(e=>(e-n)/a),i=t.map(e=>(e-n)/a)}return{normalizedLabels:r,normalizedNewLabels:i}}function __(e,t){return v_(e,t)&&w_()?`time`:y_(e,t)?`linear`:`category`}function v_(e,t){return!e.labelsAsText&&x_(t)}function y_(e,t){return!e.labelsAsText&&S_(t)}function b_(e){return x_(e)||S_(e)}function x_(e){if(!S_(e))return!1;let t=M_(e.labelValues);return!!(t&&Kf.test(t))}function S_(e){let t=e.labelValues;return!(t.some(e=>!U(e)&&e.value)||t.every(e=>!e.value))}let C_=!1;function w_(){if(!window.Chart)return!1;let e=new window.Chart._adapters._date({})._id===`luxon`;return!e&&!C_&&(C_=!0,console.warn(`'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled.`)),e}function T_(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(e=>t.some(t=>U(t.data[e])&&t.data[e].value>0));return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>U(e.data[t])&&e.data[t].value>0?e.data[t]:e_)}))}}function E_(e,t){if(e.length===0||e.every(e=>!e))return{labels:e,dataSetsValues:t};let n=[...e],r=x(t);for(let e=0;e<n.length;e++)if(!n[e]){n[e]=St(n,e);for(let t of r)t.data[e]=e_}return{labels:n,dataSetsValues:r}}function D_(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(n=>{let r=e[n],i=t.map(e=>e.data?.[n]);return r||i.some(U)});return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>U(e.data[t])?e.data[t]:e_)}))}}function O_(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(n=>{let r=e[n],i=t.map(e=>e.data?.[n]);return U(r)&&U(i[0])});return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>U(e.data[t])?e.data[t]:e_)}))}}function k_(e,t){let n=Math.max(e.length,...t.map(e=>e.data?.length||0)),r=e=>e==null||e===``,i=C(0,n).filter(n=>{let i=t.map(e=>e.data?.[n]);if(r(i[0]?.value))return!1;let a=!1;for(let e of i)if(a||=r(e?.value),a&&!r(e?.value))return!1;return e[n]&&U(e[n])});return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}function A_(e,t){let n=[],r=[];for(let t=0;t<e.length;t++)Number(e[t].value)<=0?r.push(t):Number(e[t].value)>0&&n.push(t);let i=n.length?n:r;return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}function j_(e,t){let n=e=>typeof e==`number`?e:0,r=new Set(e),i={};r.forEach(e=>{i[e]=Array(t.length)});for(let r of C(0,e.length)){let a=e[r];for(let e of C(0,t.length)){let o=t[e].data[r];i[a][e]?i[a][e].value+=n(o?.value):i[a][e]={...o,value:n(o?.value)}}}return{labels:Array.from(r),dataSetsValues:t.map((e,t)=>({...e,data:Array.from(r).map(e=>i[e][t])}))}}function M_(e){return e.find(({format:e})=>e!==void 0)?.format}function N_(e,t,n){let r=t.filter(t=>n===`right`==(e?.[t.dataSetId]?.yAxisId===`y1`));for(let e of r){let t=e.data.find(({format:e})=>e!==void 0&&!Rl(e));if(t)return t.format}}function P_(e,t){return e.map(e=>{let n=[],r=0,i=t===`asc`?C(0,e.data.length):C(0,e.data.length).reverse();for(let t of i){let i=e.data[t];U(i)?(r+=i.value,n[t]={...i,value:r}):n[t]=e_}return{...e,data:n}})}function F_(e,t){let{title:n,legendPosition:r}=e,i=n&&n.text||r===`top`;return t.isDashboard()&&!i?30:0}function I_(e,t){return{padding:{left:20,right:20,top:Math.max(15,t.topPadding||0),bottom:10}}}function L_(e,t){let n=e.legendPosition;return{padding:{left:20+(n===`left`?70:0),right:20+(n===`right`?70:0),top:Math.max(15,t.topPadding||0),bottom:10}}}function R_(e,t){return{display:e.legendPosition!==`none`,position:e.legendPosition===`none`?void 0:e.legendPosition}}function z_(e,t){return{...q_,...R_(e,t),...J_(wf(e.background),{pointStyle:`rect`,lineWidth:3})}}function B_(e,t){let n=e.fillArea,r=n?`rect`:`line`,i=n?2:3;return{...q_,...R_(e,t),...J_(wf(e.background),{pointStyle:r,lineWidth:i})}}function V_(e,t){let{dataSetsValues:n}=t,r=Pf(new ui(Math.max(0,...n.map(e=>e?.data?.length??0)),e.slicesColors),n),i=wf(e.background);return{...R_(e,t),labels:{usePointStyle:!0,generateLabels:e=>(e.data.labels?.map((e,t)=>({text:Ff(String(e)),strokeStyle:r[t],fillStyle:r[t],pointStyle:`rect`,lineWidth:2,fontColor:i}))||[]).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}function H_(e,t){return{...q_,...R_(e,t),...J_(wf(e.background),{pointStyle:`circle`,strokeStyle:e.background||`#ffffff`,lineWidth:8})}}function U_(e,t){return{...q_,...R_(e,t),...J_(wf(e.background),{lineWidth:3})}}function W_(e,t){let n=wf(e.background),r=e.negativeValuesColor||`#EA6175`,i=e.positiveValuesColor||`#4EA7F2`,a=e.subTotalValuesColor||`#AAAAAA`;return{...R_(e,t),labels:{usePointStyle:!0,generateLabels:()=>{let t=[{text:j(`Positive values`),fontColor:n,fillStyle:i,strokeStyle:i,pointStyle:`rect`},{text:j(`Negative values`),fontColor:n,fillStyle:r,strokeStyle:r,pointStyle:`rect`}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:j(`Subtotals`),fontColor:n,fillStyle:a,strokeStyle:a,pointStyle:`rect`}),t},filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0},onClick:()=>{}}}function G_(e,t){let n=e.fillArea??!1,r=n?`rect`:`line`,i=n?2:3;return{...q_,...R_(e,t),...J_(wf(e.background),{pointStyle:r,lineWidth:i})}}function K_(e,t){let n=wf(e.background);return{...R_(e,t),labels:{usePointStyle:!0,generateLabels:e=>{let t=e.data.datasets.at(-1);return t?t.groupColors.map(({color:e,label:t})=>({text:Ff(t),fontColor:n,fillStyle:e,strokeStyle:e,pointStyle:`rect`})):[]}}}}let q_={onHover:e=>{let t=e.native?.target;t&&(t.style.cursor=`pointer`)},onLeave:e=>{let t=e.native?.target;t&&(t.style.cursor=`default`)},onClick:(e,t,n)=>{if(e.type!==`click`)return;let r=t.datasetIndex;!n.legendItems||r===void 0||(n.chart.isDatasetVisible(r)?n.chart.hide(r):n.chart.show(r),e.native.preventDefault(),e.native.stopPropagation())}};function J_(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:n=>n.data.datasets.map((r,i)=>If(r.xAxisID)?{text:Ff(r.label),fontColor:e,strokeStyle:r.borderColor,hidden:!n.isDatasetVisible(i),pointStyle:`line`,datasetIndex:i,lineWidth:3}:{text:Ff(r.label),fontColor:e,strokeStyle:r.borderColor,fillStyle:r.backgroundColor,hidden:!n.isDatasetVisible(i),pointStyle:r.type===`line`?`line`:`rect`,datasetIndex:i,...t}).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}let Y_={showValues:!1,showLabels:!0,valuesDesign:{align:`center`,fontSize:13}};function X_(e,t){let{axisFormats:n,locale:r}=t;return{type:e.type,horizontal:`horizontal`in e&&e.horizontal,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(t,i)=>{let a=tv(e,i);return jf(n,r,e.humanize)(t,a)}}}function Z_(e,t){let{locale:n,axisFormats:r}=t,i=(t,n,r)=>e.background,a=t.dataSetsValues.flat().flatMap(e=>e?.data.filter(U)).map(e=>e.value);if(a.length){let t=Math.min(...a),n=Math.max(...a),r=dp(e.colorScale??Wh(`oranges`),t,n);i=(t,n,i)=>{let a=n._dataset.values[i];return a===void 0?e.background:wf(r(a))}}return{type:`calendar`,horizontal:!1,showValues:`showValues`in e?!!e.showValues:!1,background:i,callback:(e,t,i)=>{let a=t._dataset.values[i];return a===void 0?``:Zl({value:a,format:r?.y},n)}}}function Q_(e,t){let{axisFormats:n,locale:r}=t;return{callback:jf(n,r,e.humanize),showLabels:e.showLabels??Y_.showLabels,showValues:e.showValues??Y_.showValues,style:{fontSize:e.valuesDesign?.fontSize??Y_.valuesDesign.fontSize,align:e.valuesDesign?.align??Y_.valuesDesign.align,bold:e.valuesDesign?.bold??Y_.valuesDesign.bold,italic:e.valuesDesign?.italic??Y_.valuesDesign.italic,textColor:e.valuesDesign?.color??Y_.valuesDesign.color}}}function $_(e,t){let{axisFormats:n,locale:r}=t;return{type:`pyramid`,horizontal:!0,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(e,t)=>(e=Math.abs(Number(e)),e===0?``:jf(n,r)(e,t.xAxisID||`x`))}}function ev(e,t){let{axisFormats:n,locale:r,dataSetsValues:i}=t,a=i.reduce((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e),[]);return{type:`waterfall`,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(t,i,o)=>{let s=i._dataset.data[o],c=s[1]-s[0],l=c>=0?`+`:``;return e.showSubTotals&&a.includes(o)&&l===`+`&&(l=``),`${l}${jf(n,r,e.humanize)(c,i.yAxisID)}`}}}function tv(e,t){return t.rAxisID?t.rAxisID:(`horizontal`in e&&e.horizontal?t.xAxisID:t.yAxisID)||`y`}function nv(e,t){let n=e.title,r=Tf(e.background);return{display:!!n.text,text:n.text?t.dynamicTranslate(n.text):``,color:n?.color??r,align:n.align===`center`?`center`:n.align===`right`?`end`:`start`,font:{size:e.title.fontSize??16,weight:n.bold?`bold`:`normal`,style:n.italic?`italic`:`normal`},padding:{bottom:e.legendPosition===`top`?0:20}}}let rv;function iv(e,t={}){return av(e,t).innerHTML}function av(e,n={}){rv||=new t.App(t.Component,{templates:`
|
|
18
|
+
`):[t];for(let t of a){let a=t.includes(` `)?t.split(` `):[t];if(!r){i.push(t);continue}let o=``,s=r;for(let t of a){let a=Ad(e,t,r,n),c=a.pop(),l=Sd(e,c,n);if(a.length)o!==``&&(i.push(o),o=``,s=r),a.forEach(e=>{i.push(e)}),o=c,s=r-l;else{let t=o===``?c:` `+c,a=Sd(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function Md(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function Nd(e){return e?e.toLowerCase().trim():``}let Pd=/([0-9\.]*)px/;function Fd(e){return Number(e.match(Pd)?.[1])}function Id(e,t,n){let r=Cd(e,t,e.font);if(r<=n)return t;let i=Cd(e,`…`,e.font);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-->0;)t=t.substring(0,a),r=Cd(e,t,e.font);return t+`…`}function Ld(e,t,n,r=!1,i=!1,a=Fd(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}function Rd(e,t,n,r,i=`pt`){if(Sd(e,n,r,i)<=t)return n;let a=Sd(e,`...`,r,i);if(a>=t)return``;let o=1,s=n.length,c;for(;o<=s;){let l=Math.floor((o+s)/2);c=Sd(e,n.slice(0,l),r,i),c+a>t?s=l-1:o=l+1}let l=n.slice(0,Math.max(0,o-1));return l?l+`...`:``}function zd(e,t){if(!t.rotation||t.rotation%(Math.PI*2)==0)return e;let{x:n,y:r}=e,i=Math.cos(-t.rotation),a=Math.sin(-t.rotation),o=e.textWidth-8,s=e.textHeight,c=t.align===`center`,l=t.align===`left`==a<0,u=a*s,d=Math.abs(a*o),f=i*s;return t.verticalAlign===`top`?c?(r+=d/2,n-=u/2):l?n-=u:r+=d:!t.verticalAlign||t.verticalAlign===`bottom`?(r+=s-f,c?(r-=d/2,n-=u/2):l&&(n-=u,r-=d)):c?(n-=u/2,r-=s/2,l?r+=u:r-=u):l?(n-=u,r-=d/2):r+=d/2+f/4,{x:i*n-a*r,y:i*r+a*n}}var Bd=class{getCrypto(){if(typeof globalThis<`u`&&globalThis.crypto)return globalThis.crypto}smallUuid(){let e=this.getCrypto();return e?`10000000-1000`.replace(/[01]/g,t=>{let n=Number(t);return(n^e.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16)}):`xxxxxxxx-xxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}uuidv4(){let e=this.getCrypto();return e?`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,t=>{let n=Number(t);return(n^e.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16)}):`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}};let Vd=new A;function Hd(){return globalThis.Chart?!!globalThis.Chart.registry.plugins.get(`chartShowValuesPlugin`):!0}function Ud(){if(!(!globalThis.Chart||Hd()))for(let e of Vd.getAll())e.register(globalThis.Chart)}function Wd(){if(globalThis.Chart)for(let e of Vd.getAll())e.unregister(globalThis.Chart)}var Gd=class extends wr{mutators=[`disableAnimationForChart`,`enableAnimationForChart`];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,`noStateChange`}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,`noStateChange`}};let Kd={id:`background`,beforeDraw(e,t,n){let{ctx:r}=e;r.save(),r.globalCompositeOperation=`destination-over`,r.fillStyle=n.color||`#FFFFFF`,r.fillRect(0,0,e.width,e.height),r.restore()}};function qd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`calendar`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`bar`,animations:{numbers:{type:`number`,properties:[]}}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);let i=this.chart.config.options?.plugins?.background?.color||`#FFFFFF`;for(let a=t;a<t+n;a++)r===`reset`&&this.updateElement(e[a],a,{options:{backgroundColor:i}},r)}}}let Jd={id:`chartColorScalePlugin`,afterDatasetsDraw(e,t,n){if(!n.position||n.position===`none`||!n.colorScale.length)return;let r=e.ctx;r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1;let i=(e.chartArea.bottom-e.chartArea.top)/2,a=n.position===`left`?20:r.canvas.width-70,o=e.chartArea.top,s=r.createLinearGradient(0,o+i,0,o),c=1/(n.colorScale.length-1);n.colorScale.forEach((e,t)=>{s.addColorStop(t*c,e)}),r.fillStyle=s,r.fillRect(a,o,10,i),r.fillStyle=n.fontColor??`black`,r.font=bd(12),r.textAlign=`left`;let l=Math.round(n.minValue*100)/100,u=Math.round(n.maxValue*100)/100;n.minValue===n.maxValue&&(--l,u+=1);let d=Zl({value:u,format:void 0},n.locale),f=Zl({value:l,format:void 0},n.locale);r.fillText(f,a+10+5,o+i-6),r.fillText(d,a+10+5,o+6),r.restore()}};function Yd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`funnel`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function Xd(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=Zd(this),c=(s-(i?Zd(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=Zd(this),c=a?Zd(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function Zd(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let Qd=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},$d={id:`geoProjection`,beforeUpdate(e){e.options?.scales?.projection?.projection===`conicConformal`&&e.scales?.projection?.projection?.rotate([100,0])}},ef={id:`o-spreadsheet-minor-gridlines`,beforeDatasetsDraw(e){let t=e.ctx,n=e.chartArea;if(n)for(let r in e.scales){let i=e.scales[r],a=i.options,o=a?.grid?.minor;if(!o?.display)continue;let s=a?.grid?.display,c=i.ticks;if(!(!c||c.length<2)){t.save(),t.lineWidth=1,t.strokeStyle=o.color??a?.grid?.color??`#e6e6e6`;for(let e=0;e<c.length-1;e++){let r=i.getPixelForTick(e),a=i.getPixelForTick(e+1);if(!(!isFinite(r)||!isFinite(a)))for(let e=+!!s;e<4;e++){let o=e/4,s=Math.round(r+(a-r)*o)+.5;t.beginPath(),i.isHorizontal()?(t.moveTo(s,n.top),t.lineTo(s,n.bottom)):(t.moveTo(n.left,s),t.lineTo(n.right,s)),t.stroke()}}t.restore()}}}},tf=`000000`,nf={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},rf={styleSheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,sst:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,Relationships:`http://schemas.openxmlformats.org/package/2006/relationships`,Types:`http://schemas.openxmlformats.org/package/2006/content-types`,worksheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,workbook:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,drawing:`http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing`,table:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,revision:`http://schemas.microsoft.com/office/spreadsheetml/2014/revision`,revision3:`http://schemas.microsoft.com/office/spreadsheetml/2016/revision3`,markupCompatibility:`http://schemas.openxmlformats.org/markup-compatibility/2006`},af=`http://schemas.openxmlformats.org/drawingml/2006/main`,of=`http://schemas.openxmlformats.org/drawingml/2006/chart`,sf={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml`,macroEnabledWorkbook:`application/vnd.ms-excel.sheet.macroEnabled.main+xml`,templateWorkbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml`,macroEnabledTemplateWorkbook:`application/vnd.ms-excel.template.macroEnabled.main+xml`,excelAddInWorkbook:`application/vnd.ms-excel.addin.macroEnabled.main+xml`,sheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml`,metadata:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml`,sharedStrings:`application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml`,styles:`application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml`,drawing:`application/vnd.openxmlformats-officedocument.drawing+xml`,chart:`application/vnd.openxmlformats-officedocument.drawingml.chart+xml`,themes:`application/vnd.openxmlformats-officedocument.theme+xml`,table:`application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml`,pivot:`application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml`,externalLink:`application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml`},cf={document:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument`,sheet:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,metadata:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata`,sharedStrings:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings`,styles:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles`,drawing:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing`,chart:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart`,theme:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme`,table:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/table`,hyperlink:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink`,image:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/image`},lf=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,uf=.75,df=.143,ff=8.43,pf=12.75,mf={FLOOR:[{type:`NUMBER`,value:1}],CEILING:[{type:`NUMBER`,value:1}],ROUND:[{type:`NUMBER`,value:0}],ROUNDUP:[{type:`NUMBER`,value:0}],ROUNDDOWN:[{type:`NUMBER`,value:0}],IFERROR:[{type:`NUMBER`,value:0}]},hf=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),gf=`xMovingAverage`,_f={exponential:`exp`,logarithmic:`log`,polynomial:`poly`,trailingMovingAverage:`movingAvg`};function vf(e,t,n){return n?rc(e,t,n):void 0}function yf(e,{applyChange:t}){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}function bf(e,t,n){let r=[];for(let i of n.dataSets){let{unboundedZone:a,sheetId:o,invalidSheetName:s,invalidXc:c}=e.getRangeFromSheetXC(t,i.dataRange);if(!(s||c))if(a.left!==a.right&&a.top!==a.bottom){if(a.right===void 0)continue;let t=i.dataSetId;for(let i=a.left;i<=a.right;i++){let s={...a,left:i,right:i};r.push({...xf(e,o,s,n.dataSetsHaveTitle?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0),dataSetId:t}),t=`${t}_${i}`}}else r.push({...xf(e,o,a,n.dataSetsHaveTitle?{top:a.top,bottom:a.top,left:a.left,right:a.left}:void 0),dataSetId:i.dataSetId})}return r}function xf(e,t,n,r){if(n.left!==n.right&&n.top!==n.bottom)throw Error(`Zone should be a single column or row: ${wn(n)}`);if(r){let i=wn(n),a=wn(r);return{labelCell:e.getRangeFromSheetXC(t,a),dataRange:e.getRangeFromSheetXC(t,i)}}else return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,wn(n))}}function Sf(e,t,n){let r=n.labelCell?.zone,i=n.dataRange.zone;if(r){let{numberOfRows:e,numberOfCols:t}=Ln(i);e===1?i={...i,left:i.left+1}:t===1&&(i={...i,top:i.top+1})}let a=t[n.dataSetId]??{},o=Zs({...n.dataRange,zone:i},e.getSheetSize),s={};a.label?s={text:a.label}:n.labelCell&&(s={reference:e.getRangeString(n.labelCell,`forceSheetReference`,{useBoundedReference:!0})});let c;return a.trend?.type&&(c={type:a.trend.type===`polynomial`&&a.trend.order===1?`linear`:_f[a.trend.type],color:a.trend.color,order:a.trend.order?Math.min(a.trend.order,6):void 0,window:a.trend.window||2}),{label:s,range:e.getRangeString(o,`forceSheetReference`,{useBoundedReference:!0}),backgroundColor:a.backgroundColor,rightYAxis:a.yAxisId===`y1`,trend:c}}function Cf(e,t,n){if(!t)return;let r={...t.zone};n&&t.zone.bottom>t.zone.top&&(r.top+=1);let i=Zs({...t,zone:r},e.getSheetSize);return e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0})}function wf(e){return e&&Rr(e)<.3?`#FFFFFF`:`#000000`}function Tf(e){return e&&Rr(e)<.3?`#C8C8C8`:`#666666`}function Ef(e){return e.dataSets.find(e=>!Go.test(e.dataRange))!==void 0||e.dataSets.map(e=>vn(e.dataRange)).some(e=>e.top!==e.bottom&&Jn(e))?`InvalidDataSet`:`Success`}function Df(e){return e.labelRange&&!Go.test(e.labelRange||``)?`InvalidLabelRange`:`Success`}function Of(e,t,n){return n&&!!t&&e>=t}function kf(e,t){let{x:n,y:r}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:a}=e.getActiveSheetScrollInfo(),{width:o,height:s}=e.getVisibleRect(e.getActiveMainViewport());return{x:n+i+Math.max(0,(o-t.width)/2),y:r+a+Math.max(0,(s-t.height)/2)}}function Af(e){let t=!1,n=!1;if(`horizontal`in e&&e.horizontal)return{useLeftAxis:!0,useRightAxis:!1};for(let r of Object.values(e.dataSetStyles??{}))r?.yAxisId===`y1`?n=!0:t=!0;return t||=!n,{useLeftAxis:t,useRightAxis:n}}function jf(e,t,n=!1){return(r,i)=>{let a=e?.[i];return Mf({format:a,locale:t},n)(r)}}function Mf(e,t=!1){return n=>{if(n=Number(n),isNaN(n))return n;let{locale:r,format:i}=e;return Ff(t?Zl({value:n,format:i},r):H(n,{locale:r,format:!i&&Math.abs(n)>=1e3?`#,##`:i}))}}let Nf=[{value:`left`,label:j(`Left`)},{value:`right`,label:j(`Right`)}];function Pf(e,t){let n=[],r=Vt(t.map(e=>e.data.length));for(let t=0;t<=r;t++)n.push(e.next());return n}function Ff(e,t=20){return e?e.length>t?e.substring(0,t)+`…`:e:``}function If(e){return e===`x1`||e===`xMovingAverage`}let Lf={id:`chartShowValuesPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues||!e._metasets?.[0]?.data)return;let r=e.ctx;switch(r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1,n.type){case`pie`:Hf(e,n,r);break;case`line`:case`scatter`:case`combo`:case`waterfall`:case`radar`:zf(e,n,r);break;case`bar`:n.horizontal?Vf(e,n,r):zf(e,n,r);break;case`pyramid`:Vf(e,n,r);break;case`calendar`:Bf(e,n,r);break;case`funnel`:Vf(e,n,r);break}r.restore()}};function Rf(e,t,n,r){r.lineWidth=3,r.strokeText(e,t,n),r.lineWidth=1,r.fillText(e,t,n)}function zf(e,t,n){let r={};for(let i of e._metasets){if(If(i.xAxisID)||i.hidden)continue;let a=e.scales[i.yAxisID];for(let o=0;o<i._parsed.length;o++){let s=i._parsed[o],c=Number(e.config.type===`radar`?s.r:s.y);if(isNaN(c))continue;let l=i.data[o],u=l.x,d=0;if(e.config.type===`line`||e.config.type===`radar`)d=c<0?l.y+10:l.y-10;else{let e=a.getPixelForValue(0),t=Math.abs(e-l.y),n=globalThis.Chart?.defaults.font.size??12;d=t<n?c<0?e+n/2:e-n/2:c<0?l.y-l.height/2:l.y+l.height/2}r[u]||(r[u]=[]);for(let e of r[u]||[])Math.abs(e-d)<13&&(d=c<0?e+13:e-13);r[u].push(d),n.fillStyle=l.options.backgroundColor,n.strokeStyle=t.background(Number(c),i,o)||`#ffffff`,Rf(t.callback(Number(c),i,o),u,d,n)}}}function Bf(e,t,n){let r=e.chartArea.bottom,i=e.chartArea.top;for(let a of e._metasets){if(If(a.xAxisID)||a.hidden)continue;let o=e.scales[a.yAxisID];for(let s=0;s<a._parsed.length;s++){let c=a._parsed[s],l=Number(e.config.type===`radar`?c.r:c.y);if(isNaN(l))continue;let u=a.data[s],d=u.x,f=0,p=o.getPixelForValue(0),m=Math.abs(p-u.y),h=globalThis.Chart?.defaults.font.size??12;f=m<h?l<0?p+h/2:p-h/2:l<0?u.y-u.height/2:u.y+u.height/2,f=Math.min(f,r),f=Math.max(f,i),n.strokeStyle=u.options.backgroundColor,n.fillStyle=t.background(Number(l),a,s)||`#ffffff`;let g=t.callback(Number(l),a,s),_=n.measureText(g);_.actualBoundingBoxAscent+_.actualBoundingBoxDescent+2>Math.abs(u.height)-2||Rf(g,d,f,n)}}}function Vf(e,t,n){let r={};for(let i of e._metasets){if(If(i.xAxisID))return;let a=e.scales[i.xAxisID].getPixelForValue(0);for(let e=0;e<i._parsed.length;e++){let o=Number(i._parsed[e].x);if(isNaN(o))continue;let s=t.callback(o,i,e),c=i.data[e],l=c.y,u=Sd(n,s,{fontSize:globalThis.Chart?.defaults.font.size??12},`px`),d=Math.abs(c.x-a),f;f=d<u?o<0?a-u/2-3:a+u/2+3:o<0?c.x+c.width/2:c.x-c.width/2,r[l]||(r[l]=[]);for(let e of r[l])Math.abs(e-f)<u&&(f=o<0?e-u-3:e+u+3);r[l].push(f),n.strokeStyle=c.options.backgroundColor,n.fillStyle=t.background(Number(o),i,e)||`#ffffff`,Rf(s,f,l,n)}}}function Hf(e,t,n){for(let r of e._metasets)for(let e=0;e<r._parsed.length;e++){let i=Number(r._parsed[e]);if(isNaN(i)||i===0)continue;let a=r.data[e],{startAngle:o,endAngle:s,innerRadius:c,outerRadius:l}=a,u=(o+s)/2,d=(c+l)/2,f=a.x+d*Math.cos(u),p=a.y+d*Math.sin(u),m=t.callback(i,r,e),h=globalThis.Chart?.defaults.font.size??12,g=Sd(n,m,{fontSize:h},`px`),_=l-c;if(g>=_||_<h)continue;let v=s-o,y=2*d*Math.tan(v/2);if(v<Math.PI/2&&(g>=y||y<h))continue;let b=t.background(Number(i),r,e);n.fillStyle=wf(b),n.strokeStyle=b||`#ffffff`,Rf(m,f,p,n)}}let Uf={showHeaders:!0,headerDesign:{align:`center`,fillColor:`#808080`,bold:!0,fontSize:15},showValues:!0,showLabels:!0,valuesDesign:{align:`left`,verticalAlign:`bottom`,fontSize:12},coloringOptions:{type:`categoryColor`,colors:[],useValueBasedGradient:!0}},Wf={second:1e3,minute:1e3*60,hour:1e3*3600,day:1e3*3600*24,month:1e3*3600*24*30,year:1e3*3600*24*365},Gf={inSeconds:function(e){return Math.floor(e/Wf.second)},inMinutes:function(e){return Math.floor(e/Wf.minute)},inHours:function(e){return Math.floor(e/Wf.hour)},inDays:function(e){return Math.floor(e/Wf.day)},inMonths:function(e){return Math.floor(e/Wf.month)},inYears:function(e){return Math.floor(e/Wf.year)}},Kf=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function qf(e,t,n){let r=Jf(t),i=Xf(e,r,n),a={};return i&&(a[i]=r),{parser:r,displayFormats:a,unit:i??!1,tooltipFormat:r}}function Jf(e){let t=e.indexOf(`h`);return e=t>=0?e.slice(0,t).replace(/m/g,`M`)+e.slice(t):e.replace(/m/g,`M`),e.includes(`a`)||(e=e.replace(/h/g,`H`)),e}function Yf(e){return e.includes(`s`)?`second`:e.includes(`m`)?`minute`:e.includes(`h`)||e.includes(`H`)?`hour`:e.includes(`d`)?`day`:e.includes(`M`)?`month`:`year`}function Xf(e,t,n){let r=e.map(e=>ia(e,n)?.jsDate);if(r.some(e=>e===void 0)||e.length<2)return;let i=r.map(e=>e.getTime()),a=Vt(i)-Ht(i),o=Yf(t);return Wf.second>=Wf[o]&&Gf.inSeconds(a)<180?`second`:Wf.minute>=Wf[o]&&Gf.inMinutes(a)<180?`minute`:Wf.hour>=Wf[o]&&Gf.inHours(a)<96?`hour`:Wf.day>=Wf[o]&&Gf.inDays(a)<90?`day`:Wf.month>=Wf[o]&&Gf.inMonths(a)<36?`month`:`year`}function Zf(e,t){let n={},{trendDataSetsValues:r,locale:i,axisFormats:a,axisType:o}=t,s={stacked:e.stacked,locale:i};if(e.horizontal)n.x=up(e,`bottom`,`values`,o,{...s,format:a?.x}),n.y={...up(e,`left`,`labels`,`linear`,s),grid:{display:!1}};else{n.x={...up(e,`bottom`,`labels`,o,s),grid:{display:!1}};let t={...s,format:a?.y};n.y=up(e,`left`,`values`,`linear`,t);let r={...s,format:a?.y1};n.y1=up(e,`right`,`values`,`linear`,r)}if(n=Dt(n),r&&r.length&&r.some(w)){let e=Math.max(...r.map(e=>e?.length||0));n.x1={...n.x,labels:Array(e).fill(``),offset:!1,display:!1},n[gf]={...n.x,offset:!0,display:!1}}return n}function Qf(e,t){let n=t.map(e=>e.label||``),r=wf(e.background);return{y:{title:lp(e.axesDesign?.y),stacked:!0,min:0,max:n.length,ticks:{stepSize:.5,color:r,callback:function(e,t,r){if(t%2!=0)return n[Math.floor((t-1)/2)]}},grid:{display:!1},border:{display:!1}},x:{title:lp(e.axesDesign?.x),stacked:!0,grid:{display:!1},position:`top`,ticks:{color:r},border:{display:!1}}}}function $f(e,t){let{dataSetsValues:n}=t;if(!n.length||e.legendPosition===`none`)return;let r=n.flatMap(e=>e.data).filter(U).map(e=>e.value),i=Math.min(...r),a=Math.max(...r),o=[];return o=typeof e.colorScale==`object`?[e.colorScale.minColor,e.colorScale.midColor,e.colorScale.maxColor].filter(w):[...pi[e.colorScale??`oranges`]],{position:e.legendPosition===`right`?`right`:`left`,colorScale:o,fontColor:wf(e.background),minValue:i,maxValue:a,locale:t.locale}}function ep(e,t){let{locale:n,axisType:r,trendDataSetsValues:i,labels:a,axisFormats:o}=t,s=o?.x,c=e.stacked,l={x:up(e,`bottom`,`labels`,r,{locale:n}),y:up(e,`left`,`values`,`linear`,{locale:n,stacked:c,format:o?.y}),y1:up(e,`right`,`values`,`linear`,{locale:n,stacked:c,format:o?.y1})};if(l=Dt(l),r===`time`&&a&&s){let t={type:`time`,time:qf(a,s,n),min:H(e.axesDesign?.x?.min??``,{format:s,locale:n}),max:H(e.axesDesign?.x?.max??``,{format:s,locale:n})};Object.assign(l.x,t),l.x.ticks.maxTicksLimit=15,delete l?.x?.ticks?.callback}else r===`linear`&&(l.x.type=`linear`,l.x.ticks.callback=e.humanize?e=>Zl({value:e,format:s},n):e=>H(e,{format:s,locale:n}));if(i&&i.length&&i.some(w)&&(l.x1={...l.x,display:!1},l[gf]={...l.x,display:!1},r===`category`||r===`time`)){let e=Math.max(...i.map(e=>e?.length||0));l.x1.type=`category`,l.x1.labels=C(0,e).map(e=>e.toString()),l.x1.offset=!1,l[gf].type=`category`,l[gf].offset=!1}return l}function tp(e){return Rr(e||`#ffffff`)>.5?`#cccccc`:`#999999`}function np(e){return Rr(e||`#ffffff`)>.5?`#e6e6e6`:`#333333`}function rp(e,t){let n=ep(e,t),r=n?.x??{},i=e.axesDesign?.x,a=i?.gridLines!==`none`&&i?.gridLines!==`minor`;return{...n,x:{...r,grid:{...r.grid,color:tp(e.background),display:a}}}}function ip(e,t){let{locale:n,axisFormats:r,axisType:i}=t,a=r?.y||r?.y1,o=e.axesDesign?.y,s={x:{...up(e,`bottom`,`labels`,i,{locale:n}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:wf(e.background),callback:Mf({locale:n,format:a},e.humanize)},title:lp(e.axesDesign?.y),min:o?.min,max:o?.max,grid:{lineWidth:e=>e.tick.value===0?2:1,display:o?.gridLines!==`none`&&o?.gridLines!==`minor`,color:tp(e.background)}}};return(o?.gridLines===`minor`||o?.gridLines===`both`)&&(s.y.grid.minor={display:!0,color:np(e.background)}),s}function ap(e,t){let{dataSetsValues:n}=t,r=Zf(e,t),i=r.x.ticks.callback;r.x.ticks.callback=e=>i(Math.abs(e));let a=Math.max(...n.map(e=>Math.max(...e.data.filter(U).map(e=>Math.abs(e.value)))));return r.x.suggestedMin=-a,r.x.suggestedMax=a,r}function op(e,t){let{locale:n,axisFormats:r,dataSetsValues:i}=t,a=Math.min(...i.map(e=>Math.min(...e.data.filter(U).map(e=>e.value))));return{r:{beginAtZero:!0,ticks:{callback:Mf({format:r?.r,locale:n},e.humanize),backdropColor:e.background||`#FFFFFF`},pointLabels:{color:wf(e.background),callback:e=>Ff(e)},suggestedMin:a<0?a-1:0}}}function sp(e,t){let{locale:n,axisFormats:r,availableRegions:i}=t,a=pp(e.legendPosition),o=e.region?i.find(t=>t.id===e.region):i[0],s=r?.y||r?.y1;return{projection:{projection:o?.defaultProjection||`mercator`,axis:`x`},color:{axis:`x`,display:e.legendPosition!==`none`,border:{color:me},grid:{color:me},ticks:{color:wf(e.background),callback:Mf({locale:n,format:s},e.humanize)},legend:{position:a,align:a.includes(`right`)?`left`:`right`,margin:fp(e)},interpolate:dp(e.colorScale??_e),missing:e.missingValueColor||`#ffffff`}}}function cp(e,t){let n=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return Ff(this.getLabelForValue(e))}},border:{display:!1}},percentages:{position:`right`,border:{display:!1},ticks:{callback:function(e,r,i){let a=n.data?.[r],o=n.data?.[0];return!o?.value||a?.value===null||!U(a)||!U(o)?``:H(a.value/o.value,{format:`0%`,locale:t.locale})}},grid:{display:!1}}}}function lp(e){if(e?.title?.text){let{text:t,color:n,align:r,italic:i,bold:a}=e.title;return{display:!0,text:t,color:n,font:{style:i?`italic`:`normal`,weight:a?`bold`:`normal`,size:e.title.fontSize??12},align:r===`left`?`start`:r===`right`?`end`:`center`}}}function up(e,t,n,r,i){let{useLeftAxis:a,useRightAxis:o}=Af(e);if(t===`left`&&!a||t===`right`&&!o)return;let s=wf(e.background),c;if(c=t===`bottom`?e.axesDesign?.x:t===`left`?e.axesDesign?.y:e.axesDesign?.y1,n===`values`){let n=!(t===`right`&&a),o=c?.gridLines?c?.gridLines===`major`||c?.gridLines===`both`:n,l=!(r===`category`||r===void 0)&&(c?.gridLines===`minor`||c?.gridLines===`both`),u=Mf(i,e.humanize),d={position:t,title:lp(c),beginAtZero:!c?.min,stacked:i?.stacked,ticks:{color:s,callback:u},min:c?.min,max:c?.max,grid:{display:o,color:tp(e.background)}};return l&&(d.grid.minor={display:!0,color:np(e.background)}),d}else{let t={ticks:{padding:5,color:s,callback:function(e,t,n){return Ff(this.getLabelForValue(e))}},min:c?.min,max:c?.max,grid:{display:c?.gridLines===`major`||c?.gridLines===`both`,color:tp(e.background)},stacked:i?.stacked,title:lp(c)};return(c?.gridLines===`minor`||c?.gridLines===`both`)&&(t.grid.minor={display:!0,color:np(e.background)}),t}}function dp(e,t=0,n=1){if(t===n){let t=e.midColor??e.minColor;return e=>t}let r=[{value:t,color:e.minColor}];return e.midColor&&r.push({value:(t+n)/2,color:e.midColor}),r.push({value:n,color:e.maxColor}),hi(r)}function fp(e){switch(e.legendPosition){case`top`:case`right`:return{top:e.title.text?45:15,left:20,right:20};case`bottom`:case`left`:case`none`:return{left:20,right:20,bottom:10}}}function pp(e){switch(e){case`top`:return`top-left`;case`right`:return`top-right`;case`bottom`:return`bottom-right`;case`left`:return`bottom-left`;case`none`:return`bottom-left`}}let mp=`nullValue`;function hp(e,t){let{dataSetsValues:n}=t,r=[],i=Fp(e.dataSetStyles,n),a=[];for(let o in n){let{label:s,data:c,hidden:l,dataSetId:u}=n[o];s=e.dataSetStyles?.[u]?.label??s;let d=i.next(),f={label:s,data:c.map(e=>U(e)?e.value:NaN),hidden:l,borderColor:e.background||`#FFFFFF`,borderWidth:+!!e.stacked,backgroundColor:d,yAxisID:e.horizontal?`y`:e.dataSetStyles?.[u]?.yAxisId??`y`,xAxisID:`x`,barPercentage:.9,categoryPercentage:n.length>1?.8:1,borderRadius:2};r.push(f);let p=e.dataSetStyles?.[u]?.trend,m=t.trendDataSetsValues?.[o];!p?.display||e.horizontal||!m||a.push(Np(f,p,m))}return r.push(...a),r}function gp(e,t){let{labels:n,dataSetsValues:r}=t,i=r.map(e=>e.data).flat().filter(U).map(e=>e.value),a=Math.max(...i),o=Math.min(...i),s=dp(e.colorScale??_e,o,a),c=[];for(let t of r)c.push({label:t.label,data:t.data.map(e=>1),backgroundColor:t.data.map(t=>U(t)?s(t.value):e.missingValueColor||`#00000000`),borderColor:e.background||`#FFFFFF`,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1,values:t.data.map(e=>U(e)?e.value:void 0)});return{labels:n,datasets:c}}function _p(e,t){let{dataSetsValues:n,labels:r}=t,i=e.negativeValuesColor||`#EA6175`,a=e.positiveValuesColor||`#4EA7F2`,o=e.subTotalValuesColor||`#AAAAAA`,s=[],c=[],l={label:``,data:c,backgroundColor:s},u=[],d=0;for(let t of n)if(!t.hidden){for(let l=0;l<t.data.length;l++){let f=t.data[l];if(u.push(r[l]),!U(f)){c.push([d,d]),s.push(``);continue}c.push([d,f.value+d]);let p=f.value>=0?a:i;l===0&&t===n[0]&&e.firstValueAsSubtotal&&(p=o),s.push(p),d+=f.value}e.showSubTotals&&(u.push(j(`Subtotal`)),c.push([0,d]),s.push(o))}return{datasets:[l],labels:u}}function vp(e,t){let{dataSetsValues:n,axisType:r,labels:i}=t,a=[],o=!!e.fillArea,s=!!e.stacked,c=[],l=Fp(e.dataSetStyles,n);for(let u=0;u<n.length;u++){let{label:d,data:f,hidden:p,dataSetId:m}=n[u];d=e.dataSetStyles?.[m]?.label??d;let h=[],g=l.next();h=r&&[`linear`,`time`].includes(r)?f.map((e,t)=>({x:i[t]===``?NaN:i[t]??NaN,y:U(e)?e.value:NaN})):f.map(e=>U(e)?e.value:NaN);let _=e.dataSetStyles?.[m],v={label:d,data:h,hidden:p,tension:0,borderColor:g,backgroundColor:o?Yr(g,Ne):g,pointBackgroundColor:g,fill:o?Pp(u,s):!1,pointRadius:e.hideDataMarkers?0:3,yAxisID:_?.yAxisId||`y`};a.push(v);let y=_?.trend,b=t.trendDataSetsValues?.[u];!y?.display||!b||c.push(Np(v,y,b))}return a.push(...c),a}function yp(e,t){let n=vp(e,t);for(let e of n)If(e.xAxisID)||(e.showLine=!1);return n}function bp(e,t){let{dataSetsValues:n}=t,r=[],i=Pf(new ui(Math.max(0,...n.map(e=>e?.data?.length??0)),e.slicesColors),n);for(let{label:t,data:a,hidden:o}of n){if(o)continue;let n={label:t,data:a.map(e=>U(e)?e.value:NaN),borderColor:e.background||`#FFFFFF`,backgroundColor:i,hoverOffset:10};r.push(n)}return r}function xp(e,t){let{dataSetsValues:n}=t,r=[],i=Fp(e.dataSetStyles,n),a=[],o=n.filter(({dataSetId:t})=>(e.dataSetStyles?.[t]?.type??`line`)===`bar`);for(let s=0;s<n.length;s++){let{label:c,data:l,hidden:u,dataSetId:d}=n[s];c=e.dataSetStyles?.[d]?.label||c;let f=e.dataSetStyles?.[d],p=i.next(),m=s===0?`bar`:`line`,h=f?.type??m,g={label:c,data:l.map(e=>U(e)?e.value:null),hidden:u,borderColor:p,backgroundColor:p,yAxisID:e.dataSetStyles?.[d]?.yAxisId||`y`,xAxisID:`x`,type:h,order:h===`bar`?n.length+s:s,pointRadius:e.hideDataMarkers?0:3};g.type===`bar`&&(g.barPercentage=.9,g.categoryPercentage=o.length>1?.8:1,g.borderRadius=2),r.push(g);let _=e.dataSetStyles?.[d]?.trend,v=t.trendDataSetsValues?.[s];!_?.display||!v||a.push(Np(g,_,v))}return r.push(...a),r}function Sp(e,t){let{dataSetsValues:n}=t,r=[],i=e.fillArea??!1,a=Fp(e.dataSetStyles,n);for(let t=0;t<n.length;t++){let{label:o,data:s,hidden:c}=n[t];e.dataSetStyles?.[t]?.label&&(o=e.dataSetStyles[t].label);let l=a.next(),u={label:o,data:s.map(e=>U(e)?e.value:null),hidden:c,borderColor:l,backgroundColor:l,pointBackgroundColor:l,pointRadius:e.hideDataMarkers?0:3};i&&(u.backgroundColor=Yr(l,Ne),u.fill=`start`),r.push(u)}return r}function Cp(e,t){let{availableRegions:n,dataSetsValues:r,labels:i}=t,a=e.region||n[0]?.id,o=a?t.getGeoJsonFeatures(a):void 0,s={outline:o,showOutline:!!o,data:[]};if(o&&a){let e={};if(r[0])for(let n=0;n<r[0].data.length;n++){let o=r[0].data[n];if(!i[n]||o===void 0)continue;let s=t.geoFeatureNameToId(a,i[n]);s&&(e[s]={value:U(o)?o.value:0,label:i[n]})}for(let t of o)t.id&&s.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[s]}function wp(e,t){let n=t.dataSetsValues[0],r=t.labels;if(!n)return[];let{label:i,data:a}=n;return i=e.dataSetStyles?.[0]?.label||i,[{label:i,data:a.map(e=>{if(!U(e))return 0;let t=e.value;return t<=0?[0,0]:[-t,t]}),backgroundColor:Tp(r,e.funnelColors),yAxisID:`y`,xAxisID:`x`,barPercentage:1,categoryPercentage:1,borderColor:e.background||`#FFFFFF`,borderWidth:3}]}function Tp(e,t){let n=new ui(e.length,t);return e.map(()=>n.next())}function Ep(e,t){let{dataSetsValues:n,labels:r}=t,i=Ap(Op(n,r)),a=i[0]||[],o=new ui(a.length,e.groupColors||[]),s=a.map(e=>({label:e.label,color:o.next()})),c=[];for(let t=i.length-1;t>=0;t--){let n={groupColors:s,parsing:{key:`value`},data:i[t],borderColor:t=>{let n=t.type===`data`?t.raw:void 0;return!n||n.label===`nullValue`?de:e.background||`#FFFFFF`},backgroundColor:e=>{let t=e.type===`data`?e.raw:void 0;if(!t||t.label===`nullValue`)return de;let n=t.groups[0];return s.find(e=>e.label===n)?.color},hoverOffset:10};c.push(n)}return c}function Dp(e,t){let n=[],r=Math.max(...e.map(e=>e.data.length));for(let i=0;i<r;i++){n[i]={};for(let t=0;t<e.length;t++){let r=e[t].data[i]?.value,a=r===null?mp:String(r);n[i][t]=a}n[i].value=Number(t[i])}return n}function Op(e,t){return kp(Dp(e,t),0,e.length,[])}function kp(e,t,n,r){if(t>=n)return[];let i=Object.groupBy(e,e=>e[t]);return Object.keys(i).map(e=>{let a=i[e]?.reduce((e,t)=>e+Number(t.value),0)||0,o=[...r,e];return{label:e,value:a,children:kp(i[e]||[],t+1,n,[...r,e]),groups:o,depth:t}}).sort((e,t)=>t.value-e.value)}function Ap(e){let t=[],n=[...e];for(;n.length>0;){let e=n.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&n.push(...e.children))}return t}function jp(e,t){let{dataSetsValues:n,labels:r,locale:i,axisFormats:a}=t,o={locale:i,format:a?.y};if(n.length===0)return[];let s=Op(n,r).sort((e,t)=>t.value-e.value),c=Ip(e,s),l=[],u=Math.max(...n.map(e=>e.data.length));for(let e=0;e<u;e++){l[e]={};for(let t=0;t<n.length;t++)l[e][t]=n[t].data[e].value?String(n[t].data[e].value):void 0;l[e].value=Number(r[e])}let d=e.showLabels??Uf.showLabels,f=e.showValues??Uf.showValues,p=e.coloringOptions||Uf.coloringOptions,m;return p?.type===`colorScale`&&(m=Lp(s,p)),[{data:[],tree:l,labels:{display:d||f,overflow:`hidden`,...Mp(e.valuesDesign,Uf.valuesDesign),formatter:e=>[d?e.raw.g:void 0,f?H(e.raw.v,o):void 0].filter(w)},captions:{display:e.showHeaders??Uf.showHeaders,padding:6,...Mp(e.headerDesign,Uf.headerDesign)},key:`value`,groups:C(0,n.length).map(e=>String(e)),borderWidth:0,spacing:1,displayMode:`headerBoxes`,groupColors:c,backgroundColor:t=>{if(t.type!==`data`)return`transparent`;if(!t.raw.isLeaf)return e.headerDesign?.fillColor||Uf.headerDesign?.fillColor;if(p.type===`colorScale`)return m?.(t.raw.v)||`#FF0000`;if(p.type===`categoryColor`)return Rp(t,s,p,c);throw Error(`Unsupported coloring option type}`)}}]}function Mp(e,t){let n=e=>{let t=e.element.options.backgroundColor;return Rr(t)>.7?`#666666`:`#FFFFFF`};return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||n,hoverColor:e?.color||n,font:{weight:e?.bold??t?.bold?`bold`:`normal`,style:e?.italic??t?.italic?`italic`:`normal`,size:e?.fontSize??t?.fontSize}}}function Np(e,t,n){let r=Vr(e.backgroundColor);r.a=1;let i=t.color||Xr(Br(r),.5);return{type:`line`,xAxisID:t.type===`trailingMovingAverage`?gf:`x1`,yAxisID:e.yAxisID,label:e.label?j(`Trend line for %s`,e.label):``,data:n,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function Pp(e,t){return t?e===0?`origin`:`-1`:`origin`}function Fp(e,t){let n=t.map(t=>e?.[t.dataSetId]?.backgroundColor),r=t.length;return new ui(r,n)}function Ip(e,t){let n=e.coloringOptions?.type===`categoryColor`?e.coloringOptions.colors:[],r=new ui(t.length,n);return t.map(e=>({label:e.label,color:r.next()}))}function Lp(e,t){if(e.length===0)return;let n=Ap(e),r=n[n.length-1],i=Math.min(...r.map(e=>e.value)),a=Math.max(...r.map(e=>e.value));if(Number.isFinite(i)&&Number.isFinite(a)){let e=[{value:i,color:t.minColor}];if(t.midColor){let n=(i+a)/2;e.push({value:n,color:t.midColor})}return e.push({value:a,color:t.maxColor}),hi(e)}}function Rp(e,t,n,r){let i=e.raw._data.children[0][0],a=r.find(e=>e.label===i)?.color;if(!a||!n.useValueBasedGradient)return a||`#FF0000`;let o=t.find(e=>e.label===i);if(!o||!o.children.length)return a;let s=Ap(o.children),c=s[s.length-1],l=Math.max(...c.map(e=>e.value)),u=Math.min(...c.map(e=>e.value));return u===l||!isFinite(u)||!isFinite(l)?a:Xr(a,((Number(e.raw.v)||0)-l)/(u-l)*.5)}let zp={id:`sunburstHoverPlugin`,afterEvent(e,t,n){if(!n.enabled)return;let r=e.getActiveElements(),i=r.map(e=>({datasetIndex:e.datasetIndex,index:e.index}));for(let t of r){let n=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){let r=e.data.datasets[t];for(let e=0;e<r.data.length;e++){let a=r.data[e];Bp(n.groups,a.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter(t=>{let{datasetIndex:n,index:r}=t;return e.data.datasets[n].data[r].label!==mp}),e.setActiveElements(i);for(let t of e.getSortedVisibleDatasetMetas())for(let e of t.data){let t=e.$context,{datasetIndex:n,index:r,dataset:a,raw:o}=t;if(o.label===`nullValue`)continue;let s=typeof a.backgroundColor==`function`?a.backgroundColor(t):a.backgroundColor;i.length&&!i.some(e=>e.datasetIndex===n&&e.index===r)?e.options.backgroundColor=Xr(s,.5):e.options.backgroundColor=s}}};function Bp(e,t){return t.length>e.length&&e.every((e,n)=>e===t[n])}let Vp={id:`sunburstLabelsPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues&&!n.showLabels||e.config.type!==`doughnut`)return;let r=e.ctx;Hp(e,n,r)}};function Hp(e,t,n){let r=t.style,i=r.fontSize||13,a=i+3;for(let o of e._metasets)for(let s=0;s<o._dataset.data.length;s++){let c=o._dataset.data[s];if(c.label===`nullValue`)continue;let l=[t.showLabels?c.label:void 0,t.showValues?t.callback(c.value,`y`):void 0].filter(w),u=o.data[s],{startAngle:d,endAngle:f,innerRadius:p,outerRadius:m,circumference:h}=u,g=u.options.offset/4,_=g*(1-Math.sin(Math.min(Math.PI,h||0)));p+=_,m+=_;let v=(d+f)/2,y=(p+m)/2,b=(m-p)*.9,ee=f-d;if((ee>=Math.PI?m:Math.sin(ee/2)*p*2)<l.length*a)continue;n.save();let te={x:Math.cos(v)*g,y:Math.sin(v)*g},ne=e.chartArea.left+e.chartArea.width/2+te.x,re=e.chartArea.top+e.chartArea.height/2+te.y;n.translate(ne,re);let ie;v>Math.PI/2?(n.rotate(v-Math.PI),ie=-y):(ie=y,n.rotate(v));let ae=u.options.backgroundColor,oe=Rr(ae)>.7?`#666666`:`#FFFFFF`;n.fillStyle=r.textColor||oe,n.textAlign=`center`,n.textBaseline=`middle`,n.font=bd(i,r.bold,r.italic);let se=-((l.length-1)*a)/2;for(let e=0;e<l.length;e++){let t=Rd(n,b,l[e],r,`px`);n.fillText(t,ie,se+e*a)}n.restore()}}let Up={id:`waterfallLinesPlugin`,beforeDraw(e,t,n){if(!n.showConnectorLines)return;let r=e._metasets?.[0]?.data;if(!r)return;let i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<r.length;e++){let t=r[e];if(t.height===0)continue;let n=Gp(r,e);if(!n)break;let a=Wp(t),o=Wp(n),s=t.$context.raw,c=s[1]-s[0],l=Math.round(c<0?a.bottom-1:a.top),u=Math.round(a.right),d=Math.round(o.left);i.strokeStyle=`#999`,i.beginPath(),i.moveTo(u+1,l+.5),i.lineTo(d,l+.5),i.stroke()}i.restore()}};function Wp(e){let t=e.base<e.y;return{left:e.x-e.width/2,right:e.x+e.width/2,bottom:t?e.base+e.height:e.y+e.height,top:t?e.base:e.y}}function Gp(e,t){return e.find((e,n)=>n>t&&e.height!==0)}let Kp={id:`zoomWindowPlugin`,afterDatasetsDraw:function(e,t,n){if(!n.getLowerBound||!n.getUpperBound)return;let{ctx:r,chartArea:{left:i,right:a,top:o,bottom:s}}=e,c=n.getLowerBound()??i,l=n.getUpperBound()??a;c>l&&([c,l]=[l,c]),c=Math.max(i,c),l=Math.min(a,l),c===i&&--c,l===a&&(l+=1),r.save(),r.fillStyle=`rgba(255,255,255,0.5)`,r.beginPath(),r.rect(i,s,c-i,o-s),r.rect(l,s,a-l,o-s),r.fill(),r.beginPath(),r.strokeStyle=`#bbb`,r.rect(c,s,l-c,o-s),r.stroke(),r.lineWidth=2,r.beginPath(),r.moveTo(c-3,(o+s)/2-7),r.lineTo(c-3,(o+s)/2+7),r.stroke(),r.beginPath(),r.moveTo(l+3,(o+s)/2-7),r.lineTo(l+3,(o+s)/2+7),r.stroke(),r.restore()}};Vd.add(`chartShowValuesPlugin`,{register:e=>e.register(Lf),unregister:e=>e.unregister(Lf)}),Vd.add(`chartMinorGridPlugin`,{register:e=>e.register(ef),unregister:e=>e.unregister(ef)}),Vd.add(`waterfallLinesPlugin`,{register:e=>e.register(Up),unregister:e=>e.unregister(Up)}),Vd.add(`funnelController`,{register:e=>e.register(Yd()),unregister:e=>e.unregister(Yd())}),Vd.add(`funnelElement`,{register:e=>e.register(Xd()),unregister:e=>e.unregister(Xd())}),Vd.add(`funnelTooltipPositioner`,{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=Qd,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),Vd.add(`sunburstLabelsPlugin`,{register:e=>e.register(Vp),unregister:e=>e.unregister(Vp)}),Vd.add(`sunburstHoverPlugin`,{register:e=>e.register(zp),unregister:e=>e.unregister(zp)}),Vd.add(`chartColorScalePlugin`,{register:e=>e.register(Jd),unregister:e=>e.unregister(Jd)}),Vd.add(`calendarController`,{register:e=>e.register(qd()),unregister:e=>e.unregister(qd())}),Vd.add(`zoomWindowPlugin`,{register:e=>e.register(Kp),unregister:e=>e.unregister(Kp)}),Vd.add(`chartBackgroundPlugin`,{register:e=>e.register(Kd),unregister:e=>e.unregister(Kd)}),Vd.add(`geoProjectionPlugin`,{register:e=>e.register($d),unregister:e=>e.unregister($d)});var qp=class extends t.Component{static template=`o-spreadsheet-ChartJsComponent`;static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`graphContainer`);chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get chartRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!(`chartJsConfig`in e))throw Error(`Unsupported chart runtime`);return e}setup(){this.shouldAnimate&&(this.animationStore=O(Gd)),(0,t.onMounted)(()=>{Ud();let e=this.chartRuntime;this.currentRuntime=e,this.createChart(x(e))}),(0,t.onWillUnmount)(this.unmount.bind(this)),(0,t.useEffect)(()=>{let e=this.chartRuntime;e===this.currentRuntime?this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(x(this.currentRuntime))):(e.chartJsConfig.type===this.currentRuntime.chartJsConfig.type?this.updateChartJs(x(e)):(this.chart?.destroy(),this.createChart(x(e))),this.currentRuntime=e)})}unmount(){this.chart?.destroy()}get shouldAnimate(){return this.env.model.getters.isDashboard()}createChart(e){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let t=e.chartJsConfig;if(this.shouldAnimate&&this.animationStore){let e=this.env.model.getters.getChartDefinition(this.props.chartId)?.type;e&&this.animationStore.animationPlayed[this.animationChartId]!==e&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}let n=this.canvas.el.getContext(`2d`);this.chart=new globalThis.Chart(n,t)}updateChartJs(e){let t=e.chartJsConfig;if(this.shouldAnimate){let e=this.env.model.getters.getChartDefinition(this.props.chartId)?.type;e&&this.hasChartDataChanged()&&this.animationStore&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.plugins?.title&&(this.chart.config.options.plugins.title=t.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=t.options,this.chart.update()}hasChartDataChanged(){return!T(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}getChartDataInRuntime(e){let t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}get animationChartId(){return this.props.isFullScreen?this.props.chartId+`-fullscreen`:this.props.chartId}},Jp=class{static commonKeys=[`type`,`title`,`background`,`humanize`]};function Yp(e,t,n,r,i){if(!e)return``;if(n===`text`||t?.type!==`number`||e.type!==`number`)return r?Zl(e,i):e.formattedValue;let{value:a,format:o}=e;return n===`progress`?(a=t.value/a,o=`0.0%`):(a=Math.abs(t.value-a),n===`percentage`&&a!==0&&(a/=e.value),n===`percentage`&&(o=`0.0%`),o||(a=Math.round(a*100)/100)),r?Zl({value:a,format:o},i):H(a,{format:o,locale:i})}function Xp(e,t,n){return e?t?Zl(e,n):e.formattedValue??String(e.value??``):``}function Zp(e,t,n,r,i){if(t===`text`||t===`progress`||e?.type!==`number`||n?.type!==`number`)return;let a=n.value-e.value;if(a>0)return r;if(a<0)return i}function Qp(e,t,n){if(n===`text`||e?.type!==`number`||t?.type!==`number`)return`neutral`;let r=t.value-e.value;return r>0?`up`:r<0?`down`:`neutral`}function $p(e){return e.keyValue&&!Go.test(e.keyValue)?`InvalidScorecardKeyValue`:`Success`}function em(e){return e.baseline&&!Go.test(e.baseline)?`InvalidScorecardBaseline`:`Success`}let tm=globalThis.Path2D,nm=tm&&new tm(`M8.6 4.8a.5.5 0 0 1 0 .75l-3.9 3.9a.5 .5 0 0 1 -.75 0l-3.8 -3.9a.5 .5 0 0 1 0 -.75l.4-.4a.5.5 0 0 1 .75 0l2.3 2.4v-5.7c0-.25.25-.5.5-.5h.6c.25 0 .5.25.5.5v5.8l2.3 -2.4a.5.5 0 0 1 .75 0z`),rm=tm&&new tm(`M8.7 5.5a.5.5 0 0 0 0-.75l-3.8-4a.5.5 0 0 0-.75 0l-3.8 4a.5.5 0 0 0 0 .75l.4.4a.5.5 0 0 0 .75 0l2.3-2.4v5.8c0 .25.25.5.5.5h.6c.25 0 .5-.25.5-.5v-5.8l2.2 2.4a.5.5 0 0 0 .75 0z`),im={sequence:40,allowedDefinitionKeys:[...Jp.commonKeys,`keyValue`,`keyDescr`,`baseline`,`baselineMode`,`baselineDescr`,`baselineColorUp`,`baselineColorDown`],fromStrDefinition(e,t,n){let r=ic(n,t,e.baseline),i=ic(n,t,e.keyValue);return{...e,baseline:r,keyValue:i}},validateDefinition(e,t){return e.checkValidations(t,$p,em)},copyInSheetId:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,type:`scorecard`,keyValue:e.dataSource?.type===`range`?e.dataSource?.dataSets?.[0]?.dataRange:void 0,title:e.title||{text:``},baselineMode:Ae,baselineColorUp:je,baselineColorDown:Me,baseline:e.auxiliaryRange||``,humanize:e.humanize}},transformDefinition(e,t,{adaptRangeString:n}){let r,i;if(e.baseline){let{changeType:i,range:a}=n(t,e.baseline);i!==`REMOVE`&&(r=a)}if(e.keyValue){let{changeType:r,range:a}=n(t,e.keyValue);r!==`REMOVE`&&(i=a)}return{...e,baseline:r,keyValue:i}},duplicateInDuplicatedSheet(e,t,n){let r=vf(t,n,e.baseline),i=vf(t,n,e.keyValue);return{...e,baseline:r,keyValue:i}},toStrDefinition(e,t,n){return{...e,keyValue:e.keyValue?n.getRangeString(e.keyValue,t):void 0,baseline:e.baseline?n.getRangeString(e.baseline,t):void 0}},getContextCreation(e,t){return{...e,dataSource:{type:`range`,dataSets:e.keyValue?[{dataRange:e.keyValue,dataSetId:`0`}]:[]},auxiliaryRange:e.baseline}},getDefinitionForExcel:()=>void 0,updateRanges(e,t){let n=yf(e.baseline,t),r=yf(e.keyValue,t);return e.baseline===n&&e.keyValue===r?e:{...e,baseline:n,keyValue:r}},getRuntime(e,t){let n=``,r,i=e.getLocale();if(t.keyValue){let a={sheetId:t.keyValue.sheetId,col:t.keyValue.zone.left,row:t.keyValue.zone.top};r=e.getEvaluatedCell(a),n=Xp(r,t.humanize??!0,i)}let a,o=t.baseline;if(o){let t={sheetId:o.sheetId,col:o.zone.left,row:o.zone.top};a=e.getEvaluatedCell(t)}let{background:s,fontColor:c}=e.getStyleOfSingleCellChart(t.background,t.keyValue),l=Yp(a,r,t.baselineMode,t.humanize??!0,i),u=t.baselineMode===`progress`&&Pa(l,i)?I(l,i):0,d=t.title;return{title:{...d,text:d.text?e.dynamicTranslate(d.text):``},keyValue:n,keyDescr:t.keyDescr?.text?e.dynamicTranslate(t.keyDescr.text):``,baselineDisplay:l,baselineArrow:Qp(a,r,t.baselineMode),baselineColor:Zp(a,t.baselineMode,r,t.baselineColorUp,t.baselineColorDown),baselineDescr:t.baselineMode!==`progress`&&t.baselineDescr?.text?e.dynamicTranslate(t.baselineDescr.text):``,fontColor:c,background:s,baselineStyle:{...t.baselineMode!==`percentage`&&t.baselineMode!==`progress`&&o?e.getCellComputedStyle({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0,fontSize:t.baselineDescr?.fontSize,align:t.baselineDescr?.align},baselineDescrStyle:{textColor:t.baselineDescr?.color,...t.baselineDescr},keyValueStyle:{...t.keyValue?e.getCellComputedStyle({sheetId:t.keyValue.sheetId,col:t.keyValue.zone.left,row:t.keyValue.zone.top}):void 0,fontSize:t.keyDescr?.fontSize,align:t.keyDescr?.align},keyValueDescrStyle:{textColor:t.keyDescr?.color,...t.keyDescr},progressBar:t.baselineMode===`progress`?{value:u,color:u>0?t.baselineColorUp:t.baselineColorDown}:void 0}}};function am(e,t,n=1){let r=t.getContext(`2d`);if(!r)throw Error(`Unable to retrieve 2D context from canvas`);let i=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;t.width=i*e.canvas.width*n,t.height=i*e.canvas.height*n,r.scale(i*n,i*n);let a=e.canvas.width-20;if(r.fillStyle=e.canvas.backgroundColor,r.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){r.font=e.title.style.font,r.fillStyle=e.title.style.color;let t=r.textBaseline;r.textBaseline=`middle`,r.fillText(Id(r,e.title.text,a-e.title.position.x),e.title.position.x,e.title.position.y),r.textBaseline=t}if(e.baseline&&(r.font=e.baseline.style.font,r.fillStyle=e.baseline.style.color,Ld(r,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&tm){r.save(),r.fillStyle=e.baselineArrow.style.color,r.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);let t=e.baselineArrow.style.size/10;switch(r.scale(t,t),e.baselineArrow.direction){case`down`:r.fill(nm);break;case`up`:r.fill(rm);break}r.restore()}if(e.baselineDescr){let t=e.baselineDescr;r.font=t.style.font,r.fillStyle=t.style.color,r.fillText(Id(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.key&&(r.font=e.key.style.font,r.fillStyle=e.key.style.color,Ld(r,Id(r,e.key.text,a-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){let t=e.keyDescr;r.font=e.keyDescr?.style.font??t.style.font,r.fillStyle=t.style.color,r.fillText(Id(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(r.fillStyle=e.progressBar.style.backgroundColor,r.beginPath(),r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),r.fill(),r.fillStyle=e.progressBar.style.color,r.beginPath(),e.progressBar.value>0)r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{let t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));r.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}r.fill()}}let om=.05;function sm(e,t){let n=e||``;return t&&n?` `+n:n}function cm({width:e,height:t},n){return new lm({width:e,height:t},n).computeDesign()}var lm=class{runtime;context;width;height;constructor({width:e,height:t},n){if(this.runtime=n,this.width=e,this.height=t,typeof OffscreenCanvas>`u`)throw Error(`OffscreenCanvas is not supported in this environment`);let r=new globalThis.OffscreenCanvas(e,t).getContext(`2d`);if(!r)throw Error(`Unable to create scorecard measurement context`);this.context=r}computeDesign(){let e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles(),n=0;if(this.title){let r,i;switch({height:n,width:i}=this.getFullTextDimensions(this.title,t.title.font),this.runtime.title.align){case`center`:r=(this.width-i)/2;break;case`right`:r=this.width-i-20;break;default:r=20}e.title={text:this.title,style:t.title,position:{x:r,y:10+n/2}}}let r=t.baselineArrow?.size??0,{height:i,width:a}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);let o=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width,s;switch(this.runtime.baselineStyle?.align){case`right`:s=this.width-20-o-a;break;case`left`:s=20+r;break;default:s=(this.width-a-o+r)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:s,y:this.keyValue?this.height*(1-om*(this.runtime.progressBar?1:2)):this.height-(this.height-n-i)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-r,y:e.baseline.position.y-(i+r)/2}})),e.baseline&&this.baselineDescr){let n={x:e.baseline.position.x+a,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:n}}let c=0;this.runtime.progressBar&&(c=this.height*.05,e.progressBar={position:{x:40,y:this.height*(1-2*om)-i-c},dimension:{height:c,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});let{width:l,height:u}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),d=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width,f;switch(this.runtime.keyValueStyle?.align){case`right`:f=this.width-20-d-l;break;case`left`:f=20;break;default:f=(this.width-l-d)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(20,f),y:this.height*(.5-om*2)+10/2+(n+u/2)/2}}),e.key&&this.keyDescr){let n={x:e.key.position.x+l,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:n}}return e}get title(){return this.runtime.title.text??``}get keyValue(){return this.runtime.keyValue}get keyDescr(){return sm(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return sm(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return Tf(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.actualBoundingBoxAscent+n.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.fontBoundingBoxAscent+n.fontBoundingBoxDescent}}getTextStyles(){let e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e),n=this.runtime.baselineStyle?.fontSize??16,r=Math.floor(.9*n);return this.runtime.progressBar&&(n/=1.5),{title:{font:bd(this.runtime.title.fontSize??14,this.runtime.title.bold,this.runtime.title.italic),color:this.runtime.title.color??this.secondaryFontColor},keyValue:{color:this.runtime.keyValueStyle?.textColor||this.runtime.fontColor,font:bd(e,this.runtime.keyValueStyle?.bold,this.runtime.keyValueStyle?.italic),strikethrough:this.runtime.keyValueStyle?.strikethrough,underline:this.runtime.keyValueStyle?.underline},keyDescr:{color:this.runtime.keyValueDescrStyle?.textColor||this.runtime.fontColor,font:bd(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:bd(n,this.runtime.baselineStyle?.bold,this.runtime.baselineStyle?.italic),strikethrough:this.runtime.baselineStyle?.strikethrough,underline:this.runtime.baselineStyle?.underline,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor},baselineDescr:{font:bd(r,this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:this.baselineArrow===`neutral`||this.runtime.progressBar?void 0:{size:this.keyValue?.8*n:0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}};let um=/Mac/i,dm=!1;function fm(){let e=document.createElement(`div`);e.setAttribute(`style`,`width:10px;height:1px;zoom:2;position:absolute;z-index:-10000`),document.body.appendChild(e),dm=e.getBoundingClientRect().width!==20,document.body.removeChild(e)}(0,t.whenReady)(fm);let pm=[`Shift`,`Control`,`Alt`,`Meta`];function mm(e,t){return e?!!t.target&&e.contains(t.target):!1}function hm(e=1){let t=document.querySelector(`.o-grid-overlay`),n=t&&gm(t,e);if(!n)throw Error(`Can't find spreadsheet position`);return n}function gm(e,t){let n=e.closest(`.o-zoomable`),r,i=1;n?(r=n,i=dm?t:1):r=e;let a=r.getBoundingClientRect();return{x:a.x*i,y:a.y*i,width:a.width*i,height:a.height*i}}function _m(e){return e.el?vm(e.el):{x:0,y:0,width:0,height:0}}function vm(e){let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*ym(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*ym(t)}function bm(){return Array.from(document.querySelectorAll(`.o-spreadsheet .o-menu`))}function xm(e){let{startElement:t,endElement:n,startSelectionOffset:r,endSelectionOffset:i}=Sm(e);return{start:Cm(e,t,r),end:Cm(e,n,i)}}function Sm(e){let t=document.getSelection();return{startElement:t.anchorNode||e,startSelectionOffset:t.anchorOffset,endElement:t.focusNode||e,endSelectionOffset:t.focusOffset}}function Cm(e,t,n){let r=0,i=ym(e),a=i.next(),o=!0;for(;!a.done&&a.value!==t;)a.value.hasChildNodes()||a.value.textContent&&(r+=a.value.textContent.length),(a.value.nodeName===`P`||a.value.nodeName===`DIV`&&a.value!==e)&&(o?o=!1:r++),a=i.next();if(a.value!==t)return 0;if(!a.value.hasChildNodes())r+=n;else{let e=[...a.value.childNodes].slice(0,n);r+=e.reduce((t,n,r)=>{if(n.textContent!==null){let i=n.textContent.length;return n.nodeName===`P`&&r!==e.length-1&&i++,t+i}else return t},0)}return t.nodeName===`P`&&!o&&t.textContent===``&&r++,r}let wm=/^[a-zA-Z]$/;function Tm(e,t=`key`){let n=``;pm.includes(e.key)||(Dm(e)&&(n+=`Ctrl+`),e.altKey&&(n+=`Alt+`),e.shiftKey&&(n+=`Shift+`));let r=t===`key`?e.key:e.code;return n+=wm.test(r)?r.toUpperCase():r,n}function Em(){return!!um.test(navigator.userAgent)}function Dm(e){return Em()||Nm()?e.metaKey:e.ctrlKey}function Om(e){return e.button===1||Dm(e)&&e.button===0}function km(e,t){let n=document.createElement(`a`);n.href=e,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function Am(){return/Firefox/i.test(navigator.userAgent)}function jm(){return navigator.maxTouchPoints||1}function Mm(){return/Android/i.test(navigator.userAgent)}function Nm(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||navigator.platform===`MacIntel`&&jm()>1}function Pm(){return/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}function Fm(){return Mm()||Nm()||Pm()}let Im=`select, input, textarea, button, .o-select, .os-input, .o-input, .o-button, .o-button-icon, .o-button-link, .o-composer`;function Lm(e){let t=e.target,n=e.currentTarget;if(!n||!t||!n.contains(t))return!1;let r=t;for(;r&&r!==n;){if(r.matches(Im))return!0;r=r.parentElement}return n.matches(Im)}function Rm(e,t,n){let r=e.model.getters.getViewportZoomLevel();if(n===void 0&&(n=Vm(t,r)),!n)return zm(t);let i=t.clientX-n.x,a=t.clientY-n.y,o=i/r,s=a/r;return{ev:t,clientX:t.clientX-i+o,clientY:t.clientY-a+s,offsetX:o,offsetY:s}}function zm(e){return{ev:e,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY}}function Bm(e,t){return{height:t.height*e,width:t.width*e,x:t.x*e,y:t.y*e}}function Vm(e,t){let n=e.target;return!n||!(`classList`in n)||!(n instanceof Element)?null:gm(n,t)}var Hm=class extends t.Component{static template=`o-spreadsheet-ScorecardChart`;static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`chartContainer`);get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get title(){let e=this.env.model.getters.getChartDefinition(this.props.chartId).title.text;return e?this.env.model.getters.dynamicTranslate(e):``}setup(){(0,t.useEffect)(this.createChart.bind(this),()=>{let e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}createChart(){let e=this.canvas.el,t=this.env.model.getters.getViewportZoomLevel();am(cm(Bm(1/t,e.getBoundingClientRect()),this.runtime),e,t)}};function Um(e){return e=Nr(e).replace(`#`,``),e.length===8?e.slice(6)+e.slice(0,6):e}let Wm=`#F3F2F1`;function Gm(e,t,n=1,r){let i=r??Km(e),a=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;e.width=i.width*a,e.height=i.height*a;let o=e.getContext(`2d`);if(!o)throw Error(`Unable to retrieve 2D context from canvas`);o.scale(a*n,a*n);let s=Qm({width:i.width/n,height:i.height/n,x:0,y:0},t,o);Jm(o,s),qm(o,s),Xm(o,s),Ym(o,s),Zm(o,s)}function Km(e){if(e instanceof HTMLCanvasElement){let t=e.getBoundingClientRect();return{width:t.width,height:t.height}}return{width:e.width,height:e.height}}function qm(e,t){e.save();let n=t.gauge,r=n.rect.x+n.rect.width/2,i=n.rect.y+n.rect.height,a=n.rect.height-n.arcWidth/2;if(a<0)return;let o=n.percentage===1?0:Math.PI*(1+n.percentage);e.strokeStyle=Wm,e.beginPath(),e.lineWidth=n.arcWidth,e.arc(r,i,a,o,0),e.stroke(),e.strokeStyle=n.color,e.beginPath(),e.arc(r,i,a,Math.PI,o),e.stroke(),e.restore()}function Jm(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}function Ym(e,t){for(let n of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign=`center`,e.fillStyle=n.color,e.font=`${n.fontSize}px ${De}`,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Xm(e,t){let{x:n,y:r,width:i,height:a}=t.gauge.rect;for(let o of t.inflectionValues){e.save(),e.translate(n+i/2-.5,r+a-.5),e.rotate(Math.PI/2-o.rotation),e.lineWidth=2,e.strokeStyle=Tf(t.backgroundColor)+`aa`,e.beginPath(),e.moveTo(0,-(a-t.gauge.arcWidth)),e.lineTo(0,-a-3),e.stroke(),e.textAlign=`center`,e.font=`${o.fontSize}px ${De}`,e.fillStyle=o.color;let s=-a-6-o.offset;e.fillText(o.label,0,s),e.restore()}}function Zm(e,t){e.save();let n=t.title;e.font=bd(n.fontSize,n.bold,n.italic),e.textBaseline=`middle`,e.fillStyle=n.color,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Qm(e,t,n){let r=t.maxValue,i=t.minValue,a=oh(t,`animated`),o=$m(e,t.title.text),s=o.width/6,c=a?(a-i.value)/(r.value-i.value):0,l={x:e.width/2,y:o.y+o.height-o.height/12},u=80;o.height<300&&(u*=o.height/300);let d=o.width/2,f=t.gaugeValue?.label||`-`;Sd(n,f,{fontSize:u},`px`)>d&&(u=Md(d,u,e=>Sd(n,f,{fontSize:e},`px`)));let p={x:o.x+s/2,y:o.y+o.height+12},m={x:o.x+o.width-s/2,y:o.y+o.height+12},h=Tf(t.background),g=eh(t,o,h,n),_=0,v=0,y=0;switch(t.title.text&&({width:v,height:y}=Td(n,t.title.text,{fontSize:16,...t.title},`px`)),t.title.align){case`right`:_=e.width-v-20;break;case`center`:_=(e.width-v)/2;break;default:_=20;break}return{width:e.width,height:e.height,title:{label:t.title.text??``,fontSize:t.title.fontSize??16,textPosition:{x:_,y:15+y/2},color:t.title.color??h,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:o,arcWidth:s,percentage:S(c,0,1),color:th(t)},inflectionValues:g,gaugeValue:{label:f,textPosition:l,fontSize:u,color:h},minLabel:{label:t.minValue.label,textPosition:p,fontSize:12,color:h},maxLabel:{label:t.maxValue.label,textPosition:m,fontSize:12,color:h}}}function $m(e,t){let n=t?25:0,r=e.height-20-n-10,i=e.width-60,a,o;return i>2*r?(a=2*r,o=r):(a=i,o=i/2),{x:30+(i-a)/2,y:n+10+(r-o)/2,width:a,height:o}}function eh(e,t,n,r){let i=e.maxValue,a=e.minValue,o={x:t.x+t.width/2,y:t.y+t.height},s={fontSize:12},c=[],l=[];for(let u of e.inflectionValues){let e=(u.value-a.value)/(i.value-a.value),d=Sd(r,u.label,s,`px`),f=Math.PI-Math.PI*e,p=ah(f,t.height+6,o.x,o.y,d+2,12),m=l.some(e=>ih(e,p))?12:0;l.push(p),c.push({rotation:f,label:u.label,fontSize:12,color:n,offset:m})}return c}function th(e){let t=oh(e,`final`);if(t===void 0)return Wm;for(let n=0;n<e.inflectionValues.length;n++){let r=e.inflectionValues[n];if(r.operator===`<`&&t<r.value||r.operator===`<=`&&t<=r.value)return e.colors[n]}return e.colors.at(-1)}function nh(e){return[{start:e.topLeft,end:e.topRight},{start:e.topRight,end:e.bottomRight},{start:e.bottomRight,end:e.bottomLeft},{start:e.bottomLeft,end:e.topLeft}]}function rh(e,t){let n=e.start,r=e.end,i=t.start,a=t.end;function o(e,t,n){return(n.y-e.y)*(t.x-e.x)>(t.y-e.y)*(n.x-e.x)}return o(n,i,a)!==o(r,i,a)&&o(n,r,i)!==o(n,r,a)}function ih(e,t){let n=nh(e),r=nh(t);for(let e of n)for(let t of r)if(rh(e,t))return!0;return!1}function ah(e,t,n,r,i,a){let o=Math.cos(e),s=Math.sin(e),c=o*t,l=s*t,u=i/2*s,d=i/2*o,f={x:c+u+n,y:r-(l-d)},p={x:c-u+n,y:r-(l+d)},m=o*(t+a),h=s*(t+a),g={x:m-u+n,y:r-(h+d)};return{bottomLeft:p,bottomRight:f,topRight:{x:m+u+n,y:r-(h-d)},topLeft:g}}function oh(e,t){return t===`animated`&&e.animationValue!==void 0?e.animationValue:e.gaugeValue?.value}let sh={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:[`mousemove`,`mouseout`,`click`,`touchstart`,`touchmove`,`mouseup`]};async function ch(e,t,n){try{let r=uh(t.width,t.height),i=ph(r,e,t,n),a=await fh(r);return i(),a}catch(e){console.log(`Error exporting chart to image URL: `+e.message)}}async function lh(e,t,n){try{let r=uh(t.width,t.height),i=ph(r,e,t,n),a=await dh(r);return i(),a}catch(e){console.log(`Error exporting chart to image file: `+e.message)}return null}function uh(e,t){if(!globalThis.OffscreenCanvas)throw Error(`converting a chart to an image using OffscreenCanvas is not supported in this environment`);return new OffscreenCanvas(e,t)}async function dh(e){return`convertToBlob`in e?e.convertToBlob({type:`image/png`}):new Promise(t=>e.toBlob(t,`image/png`))}async function fh(e){let t=await dh(e);if(t)return new Promise(e=>{let n=new FileReader;n.addEventListener(`load`,()=>{e(n.result)}),n.readAsDataURL(t)})}function ph(e,t,n,r){if(`chartJsConfig`in t){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let n=Hd();n||Ud();let r=x(t.chartJsConfig);if(!globalThis.Chart.registry.controllers.get(r.type))throw console.log(`Chart of type "${r.type}" is not registered in Chart.js library.`),n||Wd(),Error(`Chart of type "${r.type}" is not registered in Chart.js library.`);let i=new globalThis.Chart(e,r);return()=>{i.destroy(),n||Wd()}}else r===`scorecard`?am(cm(n,t),e):r===`gauge`&&Gm(e,t,1,n);return()=>{}}function mh(e,t){if(!e)throw new N(t)}function hh(e,t=j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)){if(e===0)throw new Vi(t)}function gh(e){return e.length===1||e[0].length===1}function _h(...e){if(e.every(Je)){let t=e[0].length,n=e[0][0].length;for(let r of e)if(r.length!==t||r[0].length!==n)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(e.length!==1||e[0].length!==1))}function vh(e){return e.length===e[0].length}let yh=e=>j(`The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.`,e);function bh(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=Array(e).fill(0),t[n][n]=1;return t}function xh(e){if(e.length<1||e[0].length<1)throw Error(`invertMatrix: an empty matrix cannot be inverted.`);if(e.length!==e[0].length)throw Error(`invertMatrix: only square matrices are invertible`);let t=1,n=e.length,r=bh(n),i=e.map(e=>e.slice());for(let e=0;e<n;e++){let a=i[e][e];if(a===0){for(let a=e+1;a<n;a++)if(i[e][a]!==0){Sh(i,e,a),Sh(r,e,a),t*=-1;break}if(a=i[e][e],a===0)return{determinant:0}}for(let t=0;t<n;t++)i[t][e]=i[t][e]/a,r[t][e]=r[t][e]/a;t*=a;for(let t=0;t<n;t++){if(t===e)continue;let a=i[e][t];for(let o=0;o<n;o++)i[o][t]-=a*i[o][e],r[o][t]-=a*r[o][e]}}return{inverted:r,determinant:t}}function Sh(e,t,n){for(let r=0;r<e.length;r++){let i=e[r][t];e[r][t]=e[r][n],e[r][n]=i}}function Ch(e,t){if(e.length<1||t.length<1)throw Error(`multiplyMatrices: empty matrices cannot be multiplied.`);if(e.length!==t[0].length)throw Error(`multiplyMatrices: incompatible matrices size.`);let n=e[0].length,r=t.length,i=e.length,a=Array(r);for(let o=0;o<r;o++){a[o]=Array(n);for(let r=0;r<n;r++){let n=0;for(let a=0;a<i;a++)n+=e[a][r]*t[o][a];a[o][r]=n}}return a}function wh(e){if(!Je(e))return e;if(!Th(e))throw Error(`The value should be a scalar or a 1x1 matrix`);return e[0][0]}function Th(e){return e.length===1&&e[0].length===1}function Eh(e){return Je(e)&&!Th(e)}function Dh(...e){let t=e[0].length;e.forEach((e,n)=>mh(e.length===t,j(`[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).`,n.toString(),t.toString(),e.length.toString())))}function Oh(e,t){let n=0,r=oo(e,(e,t)=>(n+=1,e+t),0,t);return hh(n),r/n}function kh(e,t){let n=[];ro(e,e=>{n.push(e.value)},t),n.sort((e,t)=>e-t);let r=n.length;if(r===0)return;let i=Math.floor(r/2);return r%2==0?(n[i-1]+n[i])/2:n[i]}function Ah(e,t){let n=0;for(let r of e)if(Je(r))for(let e of r)for(let t of e)typeof t.value==`number`&&(n+=1);else{let e=r?.value;!F(e)&&(typeof e!=`string`||Pa(e,t)||ia(e,t))&&(n+=1)}return n}function jh(e){return ao(e,(e,t)=>t!==void 0&&t.value!==null?e+1:e,0)}function Mh(e,t){let n={value:-1/0};return ro(e,e=>{e.value>=n.value&&(n=e)},t),n.value===-1/0?{value:0}:n}function Nh(e,t){let n={value:1/0};return ro(e,e=>{e.value<=n.value&&(n=e)},t),n.value===1/0?{value:0}:n}function Ph(e,t,n){let r=e[0].length?e:[C(1,t.flat().length+1)],i=r.length,a=n[0].length?n:r;return a=a.length===i?fo(a):a,{_X:r,_newX:a}}function Fh(e,t,n=!0,r=!1){let i=t.flat(),a=i.length,{_X:o}=Ph(e,t,[[]]);o=o.length===a?fo(o):o.slice(),Dh(o[0],i);let s=o.length,c=a-s-+!!n,l=[i],u=fo(o.reverse()),d=[];for(let e=0;e<s;e++)if(d.push(0),n){for(let t of o[e])d[e]+=t;d[e]/=a}let f=0;if(n){for(let e of i)f+=e;f/=a}let p=u.map(e=>e.map((e,t)=>e-d[t]));n&&u.forEach(e=>e.push(1));let m=Lh(u,l);if(n||m.push([0]),!r)return m;let{inverted:h}=xh(Ch(p,fo(p)));if(h===void 0)throw new N(j(`Matrix is not invertible`));let g=0,_=0;for(let e=0;e<a;e++){let t=i[e]-f,n=0;for(let t=0;t<s;t++){let r=p[e][t];n+=r*m[t][0]}let r=t-n;g+=r*r,_+=n*n}let v=Math.sqrt(g/c),y=_/(_+g),b=_/s/(g/c),ee=[];for(let e=0;e<s;e++)ee.push(v*Math.sqrt(h[e][e]));if(n){let e=Ch(h,[d]),t=Ch(fo([d]),e);ee.push(v*Math.sqrt(t[0][0]+1/i.length))}let te=[[m[0][0],ee[0],y,b,_],[m[1][0],ee[1],v,c,g]];for(let e=2;e<s;e++)te.push([m[e][0],ee[e],``,``,``]);return n?te.push([m[s][0],ee[s],``,``,``]):te.push([0,``,``,``,``]),te}function Ih(e,t,n,r){Dh(t,e),mh(n>=1,j(`Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible.`));let i=[e],a=t.map(e=>C(0,n).map(t=>e**+(n-t)));r&&a.forEach(e=>e.push(1));let o=Lh(a,i);return r||o.push([0]),o}function Lh(e,t){let{inverted:n}=xh(Ch(e,fo(e)));if(n===void 0)throw new N(j(`Matrix is not invertible`));return fo(Ch(n,Ch(e,t)))}function Rh(e,t,n){return e.reduce((e,r,i)=>e+r*t**+(n-i),0)}function zh(e){return e.map(e=>e.map(e=>Math.exp(e)))}function Bh(e){return e.map(e=>e.map(e=>Math.log(e)))}function Vh(e,t,n,r){let{_X:i,_newX:a}=Ph(t,e,n),o=Fh(i,e,r,!1),s=o.length-1,c=a.map(e=>{let t=0;for(let n=0;n<s;n++)t+=o[n][0]*e[s-n-1];return t+=o[s][0],[t]});return c.length===n.length?c:fo(c)}function Hh(e,t,n=2){let r=[];for(let e=0;e<n-1;e++)r.push({x:t[e],y:NaN});for(let i=0;i<=e.length-n;i++){let a=0;for(let t=i;t<i+n;t++)a+=e[t];r.push({x:t[i+n-1],y:a/n})}return r}let Uh=[`line`,`bar`,`pie`,`scorecard`,`gauge`,`scatter`,`combo`,`waterfall`,`pyramid`,`radar`,`geo`,`funnel`,`sunburst`,`treemap`,`calendar`];function Wh(e){let t=pi[e];return t===void 0?void 0:{minColor:t[0],midColor:t.length===3?t[1]:void 0,maxColor:t[t.length-1]}}let Gh=new Set([`containsText`,`notContainsText`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`beginsWithText`,`endsWithText`,`isNotEmpty`,`isEmpty`,`isNotEqual`,`isEqual`,`customFormula`,`dateIs`,`dateIsBefore`,`dateIsAfter`,`dateIsOnOrBefore`,`dateIsOnOrAfter`,`top10`,`uniqueValues`,`duplicateValues`]),Kh=new Set([`containsText`,`notContainsText`,`isEqualText`,`isEmail`,`isLink`,`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`dateIsValid`,`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isBoolean`,`isValueInList`,`isValueInRange`,`customFormula`]),qh=`(previous)`,Jh=`(next)`,Yh=[`containsText`,`notContainsText`,`isEqualText`,`isEmpty`,`isNotEmpty`,`beginsWithText`,`endsWithText`],Xh=[`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isEmpty`,`isNotEmpty`],Zh=[`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`isEmpty`,`isNotEmpty`];function Qh(e){let t=!1,n=!0;return ho(e,e=>(t=!0,n&&=e,n)),{foundBoolean:t,result:n}}function $h(e){let t=!1,n=!1;return ho(e,e=>(t=!0,n||=e,!n)),{foundBoolean:t,result:n}}function eg(e,t){return oo(e,(e,t)=>e+t,0,t)}function tg(e){return ao(e,(e,t)=>Eo(t)?e.add(t?.value):e,new Set).size}function ng(e){let[t,n]=e.split(`/`);return Number(n)*100+Number(t)}let rg=new A;function ig(e){return rg.get(e)}let ag={normalizeFunctionValue(e){return I(e,V)},toValueAndFormat(e,t){return{value:I(e,V),format:`dd mmm yyyy`}},toFunctionValue(e){let t=z(e,V);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},og={normalizeFunctionValue(e){let t=I(e,V);if(t<1||t>31)throw new N(j(`%s is not a valid day of month (it should be a number between 1 and 31)`,t));return t},toValueAndFormat(e){return{value:I(e,V),format:`0`}},toFunctionValue(e){return`${e}`}},sg={normalizeFunctionValue(e){let t=I(e,V);if(t<1||t>7)throw new N(j(`%s is not a valid day of week (it should be a number between 1 and 7)`,t));return t},toValueAndFormat(e,t){return{value:Cl[(e-1+(t||V).weekStart)%7].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},cg={normalizeFunctionValue(e){let t=I(e,V);if(t<0||t>53)throw new N(j(`%s is not a valid week (it should be a number between 0 and 53)`,t));return t},toValueAndFormat(e){return{value:I(e,V),format:`0`}},toFunctionValue(e){return`${e}`}},lg={normalizeFunctionValue(e){let t=I(e,V);if(t<1||t>12)throw new N(j(`%s is not a valid month (it should be a number between 1 and 12)`,t));return t},toValueAndFormat(e){return{value:Sl[I(e,V)-1].toString(),format:`@`}},toFunctionValue(e){return`${e}`}},ug={normalizeFunctionValue(e){return H(I(e,V),{locale:V,format:`mm/yyyy`})},toValueAndFormat(e){return{value:I(e,V),format:`mmmm yyyy`}},toFunctionValue(e){let t=z(e,V);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`},toComparableValue(e){return ng(e)}},dg={normalizeFunctionValue(e){let t=I(e,V);if(t<1||t>4)throw new N(j(`%s is not a valid quarter (it should be a number between 1 and 4)`,t));return t},toValueAndFormat(e){return{value:j(`Q%(quarter_number)s`,{quarter_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},fg={normalizeFunctionValue(e){let t=I(e,V);return t>3e3?z(t,V).getFullYear():t},toValueAndFormat(e){return{value:I(e,V),format:`0`}},toFunctionValue(e){return`${e}`}},pg={normalizeFunctionValue(e){let t=I(e,V);if(t<0||t>23)throw new N(j(`%s is not a valid hour (it should be a number between 0 and 23)`,t));return t},toValueAndFormat(e){return{value:j(`%(hour_number)sh`,{hour_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},mg={normalizeFunctionValue(e){let t=I(e,V);if(t<0||t>59)throw new N(j(`%s is not a valid minute (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:j(`%(minute_number)s'`,{minute_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}},hg={normalizeFunctionValue(e){let t=I(e,V);if(t<0||t>59)throw new N(j(`%s is not a valid second (it should be a number between 0 and 59)`,t));return t},toValueAndFormat(e){return{value:j(`%(second_number)s''`,{second_number:e}),format:`@`}},toFunctionValue(e){return`${e}`}};function gg(e){return{normalizeFunctionValue(t){return t===null?null:e.normalizeFunctionValue(t)},toValueAndFormat(t,n){return t===null?{value:j(`(Undefined)`)}:e.toValueAndFormat(t,n)},toFunctionValue(t){return t===null?`false`:e.toFunctionValue(t)},toComparableValue(t){if(t!==null)return e.toComparableValue?.(t)}}}rg.add(`day`,gg(ag)).add(`year`,gg(fg)).add(`day_of_month`,gg(og)).add(`iso_week_number`,gg(cg)).add(`month_number`,gg(lg)).add(`month`,gg(ug)).add(`quarter_number`,gg(dg)).add(`day_of_week`,gg(sg)).add(`hour_number`,gg(pg)).add(`minute_number`,gg(mg)).add(`second_number`,gg(hg));let _g={displayTotals:!0,displayColumnHeaders:!0,displayMeasuresRow:!0,numberOfRows:Number.MAX_VALUE,numberOfColumns:Number.MAX_VALUE,tableStyleId:`None`,bandedRows:!1,bandedColumns:!1,hasFilters:!1,tabularForm:!1},vg={count:j(`Count`),count_distinct:j(`Count Distinct`),bool_and:j(`Boolean And`),bool_or:j(`Boolean Or`),max:j(`Maximum`),min:j(`Minimum`),avg:j(`Average`),sum:j(`Sum`)},yg=[`max`,`min`,`avg`,`sum`,`count_distinct`,`count`],bg={integer:yg,char:yg,datetime:yg,boolean:[`count_distinct`,`count`,`bool_and`,`bool_or`]},xg={};for(let e in bg){xg[e]={};for(let t of bg[e])xg[e][t]=vg[t]}let Sg={count:e=>({value:jh([e]),format:`0`}),count_distinct:e=>({value:tg([e]),format:`0`}),bool_and:e=>({value:Qh([e]).result}),bool_or:e=>({value:$h([e]).result}),max:(e,t)=>Mh([e],t),min:(e,t)=>Nh([e],t),avg:(e,t)=>({value:Oh([e],t),format:za(e)}),sum:(e,t)=>({value:eg([e],t),format:za(e)})};function Cg(e){let t=Object.keys(e);if(!t.length)return 0;let n=t.map(e=>parseInt(e,10));return Math.max(...n)}let wg={year:j(`Year`),quarter:j(`Quarter & Year`),month:j(`Month & Year`),week:j(`Week & Year`),day:j(`Day`),quarter_number:j(`Quarter`),month_number:j(`Month`),iso_week_number:j(`Week`),day_of_month:j(`Day of Month`),day_of_week:j(`Day of Week`),hour_number:j(`Hour`),minute_number:j(`Minute`),second_number:j(`Second`)},Tg=[`date`,`datetime`];function Eg(e){let[t,n]=e.split(`:`);return n?{fieldName:t,granularity:n}:{fieldName:t}}function Dg(e){return Tg.includes(e.type)}function Og(e,t,n){let r=[e];n&&r.push(`"${n}"`);for(let{field:e,value:n,type:i}of t){if(e===`measure`){r.push(`"measure"`,`"${n}"`);continue}let{granularity:t}=Eg(e),a=Ng(n,{type:i,granularity:t});r.push(`"${e}"`,a)}return r}function kg(e,t){let n=0,r=0,i=t.columns.map(e=>e.nameWithGranularity),a=t.rows.map(e=>e.nameWithGranularity);for(;e[n]!==void 0&&e[n]===a[r];)n++,r++;for(r=0;e[n]!==void 0&&e[n]===i[r];)n++,r++;return e.length===n}function Ag(e,t){switch(t.type){case`HEADER`:return`=PIVOT.HEADER(${Og(e,t.domain).join(`,`)})`;case`VALUE`:return`=PIVOT.VALUE(${Og(e,t.domain,t.measure).join(`,`)})`;case`MEASURE_HEADER`:return`=PIVOT.HEADER(${Og(e,[...t.domain,{field:`measure`,value:t.measure,type:`char`}]).join(`,`)})`}return``}function jg(e,t){if(t===null||t===`null`)return null;let n=typeof t==`object`?t.value:t;if(F(n))return n;if(e.type===`custom`)return eo(t)??null;let r=typeof t==`boolean`?L(t).toLocaleLowerCase():L(t);if(r===`null`)return null;if(!Fg.contains(e.type))throw new N(j(`Field %(field)s is not supported because of its type (%(type)s)`,{field:e.displayName,type:e.type}));return r.toLowerCase()===`false`?!1:Fg.get(e.type)(r,e)}function Mg(e,t){return ig(t.granularity??`month`).normalizeFunctionValue(e)}function Ng(e,t){return e===null?`"null"`:Ig.contains(t.type)?Ig.get(t.type)(e,t.granularity):`"${e}"`}function Pg(e,t){return ig(t??`month`).toFunctionValue(e)}let Fg=new A;Fg.add(`date`,Mg).add(`datetime`,Mg).add(`integer`,e=>I(e,V)).add(`boolean`,e=>R(e)).add(`char`,e=>L(e)).add(`custom`,e=>e);let Ig=new A;Ig.add(`date`,Pg).add(`datetime`,Pg).add(`integer`,e=>`${I(e,V)}`).add(`boolean`,e=>R(e)?`TRUE`:`FALSE`).add(`char`,e=>`"${L(e).replace(/"/g,`\\"`)}"`).add(`custom`,e=>typeof e==`string`?`"${e}"`:String(e));function Lg(e){return e.displayName+(e.granularity?` (${wg[e.granularity]})`:``)}function Rg(e,t){return e.length===0?t:{...t,format:(t.format||`@`)+`* `}}function zg(e,t){try{if(!t.getMeasure(e.measure))return!1;let n=t.definition.columns;for(let r=0;r<e.domain.length;r++){if(n[r].nameWithGranularity!==e.domain[r].field)return!1;let i=t.getPossibleFieldValues(n[r]).map(e=>e.value);if(!i.includes(e.domain[r].value)&&!(e.domain[r].value===null&&i.includes(``)))return!1}return!0}catch{return!1}}function Bg(e,t){return Kt(e,t.groups.map(e=>e.name),{compute:(e,t)=>`${e}${t}`,start:2})}function Vg(e,t){return Kt(e,Object.values(t).map(e=>[e?.name,e?.string]).flat().filter(w),{compute:(e,t)=>`${e}${t}`,start:2})}function Hg(e,t){let n={};for(let r of Object.values(e.customFields||{}))t[r.parentField]&&(n[r.name]={type:`custom`,isCustomField:!0,name:r.name,string:r.name,customGroups:r.groups,parentField:r.parentField});return n}function Ug(e,t){t.groups=t.groups.filter(t=>!t.values.some(t=>e.includes(t)))}function Wg(e,t,n){let r=e.rows.some(e=>e.fieldName===t)?e.rows:e.columns,i=r.findIndex(e=>e.fieldName===t);return i===-1||r.some(e=>e.fieldName===n)||r.splice(i,0,{fieldName:n}),e}function Gg(e,t,n){return Object.values(e.customFields||{}).find(e=>e.parentField===t.name)||{parentField:t.name,name:Vg(t.string,n),groups:[]}}function Kg(e,t){let n=t.model.getters.getPivotCellFromPosition(e),r=t.model.getters.getPivotIdFromPosition(e);if(!r||n.type!==`HEADER`)return;let i=t.model.getters.getPivotCoreDefinition(r),a=i.collapsedDomains?.[n.dimension]?[...i.collapsedDomains[n.dimension]]:[],o=a.findIndex(e=>T(e,n.domain));o===-1?a.push(n.domain):a.splice(o,1);let s=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};s[n.dimension]=a,t.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...i,collapsedDomains:s}})}function qg(e,t,n,r,i,a,o){let s=e.style;return{numberOfRows:t===void 0?s?.numberOfRows??_g.numberOfRows:I(t,o),numberOfColumns:i===void 0?s?.numberOfColumns??_g.numberOfColumns:I(i,o),displayTotals:n===void 0?s?.displayTotals??_g.displayTotals:R(n),displayColumnHeaders:r===void 0?s?.displayColumnHeaders??_g.displayColumnHeaders:R(r),displayMeasuresRow:a===void 0?s?.displayMeasuresRow??_g.displayMeasuresRow:R(a),tableStyleId:s?.tableStyleId||_g.tableStyleId,bandedRows:s?.bandedRows??_g.bandedRows,bandedColumns:s?.bandedColumns??_g.bandedColumns,hasFilters:s?.hasFilters??_g.hasFilters,tabularForm:s?.tabularForm??_g.tabularForm}}function Jg(e,t=`>`){let n=e.indexOf(t),r=e.lastIndexOf(t);return!e||!n||n===r?e:`${e.slice(0,n+1)} … ${e.slice(r)}`}function Yg(e,t,n){return n.map(n=>{if(n.id===e.id)return t;if(!n.computedBy||e.id===t.id)return n;let r=ls(n.computedBy.formula).map(n=>n.type===`SYMBOL`&&n.value===tt(e.id)?tt(t.id):n.value).join(``);return{...n,computedBy:{...n.computedBy,formula:r}}})}let Xg=Symbol(`NULL`);function Zg(e,t,n){let r=e.granularity||`month`;if(!(r in Qg))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:Xg;if(!Qg[r].set.has(t)){Qg[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=z(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(I(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(I(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}Qg[r].values[i]=jg(e,a)}return Qg[r].values[i]}let Qg={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function $g(){for(let e in Qg)Qg[e].set.clear(),Qg[e].values={}}let e_=Object.freeze({value:null}),t_=Object.freeze({value:0});function n_(e,{labelValues:t,dataSetsValues:n},r){let i=r.getLocale(),a=t.map(({value:e,format:t})=>H(e,{format:t,locale:i}));({labels:a,dataSetsValues:n}=D_(a,n)),e.aggregated&&({labels:a,dataSetsValues:n}=j_(a,n));let o=N_(e.dataSetStyles,n,`left`),s=N_(e.dataSetStyles,n,`right`),c=e.horizontal?{x:o||s}:{y:o,y1:s},l=[];for(let t in n){let{data:r,dataSetId:i}=n[t],a=e.dataSetStyles?.[i]?.trend;if(!a?.display||e.horizontal){l.push(void 0);continue}let o=p_(a,r);l.push(o)}return{dataSetsValues:n,trendDataSetsValues:l,axisFormats:c,labels:a,locale:r.getLocale(),topPadding:F_(e,r)}}function r_(e,t){switch(t){case`day_of_week`:return Cl[e-1].toString();case`hour_number`:{let t=String(e%12).padStart(2,`0`);return j(e<12?`%(hour)s AM`:`%(hour)s PM`,{hour:t})}case`month_number`:return Sl[e-1].toString();case`iso_week_number`:return j(`W%(weekNumber)s`,{weekNumber:String(e).padStart(2,`0`)});case`quarter_number`:return j(`Q%(value)s`,{value:e});default:return e.toString()}}function i_(e,t,n,r,i){let a={},o=[],s=[],c=[];for(let l=0;l<e?.length;l++){let u=I(Zg({granularity:n,type:`date`,displayName:`date`},e[l].value,V),i);u in a||(o.push(u),a[u]={});let d=I(Zg({granularity:r,type:`date`,displayName:`date`},e[l].value,V),i);c.includes(d)||(s.push(d),c.push(d)),d in a[u]||(a[u][d]={value:0});let f=t[l];U(f)&&(a[u][d].value+=f.value)}return o.sort((e,t)=>e-t),s.sort((e,t)=>t-e),{dataSetsValues:s.map(e=>({data:o.map(t=>a?.[t]?.[e]),label:r_(e,r),hidden:!1,dataSetId:`0`})),labels:o.map(e=>({value:r_(e,n)}))}}function a_(e,{labelValues:t,dataSetsValues:n},r){let i=t,a=r.getLocale();({labels:i,dataSetsValues:n}=O_(i,n));let o={y:N_(e.dataSetStyles,n,`left`)};return{labels:i,dataSetsValues:n}=i_(i,n[0]?.data??[],e.horizontalGroupBy??`day_of_week`,e.verticalGroupBy??`hour_number`,a),{dataSetsValues:n,axisFormats:o,labels:i.map(({value:e})=>String(e??``)),locale:r.getLocale(),topPadding:F_(e,r)}}function o_(e,{labelValues:t,dataSetsValues:n},r){let i=n_(e,{labelValues:t,dataSetsValues:n.slice(0,2)},r),a=i.dataSetsValues.filter(e=>!e.hidden),o=[];if(a[0]){let e=a[0].data.map(e=>U(e)&&e.value>0?e:t_);o.push({...a[0],data:e})}if(a[1]){let e=a[1].data.map(e=>U(e)&&e.value>0?{value:-e.value}:t_);o.push({...a[1],data:e})}return{...i,dataSetsValues:o}}function s_(e,{labelValues:t,dataSetsValues:n},r){let i=__(e,{labelValues:t,dataSetsValues:n}),a=i===`linear`?t.map(({value:e})=>String(e??``)):t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:a,dataSetsValues:n}=D_(a,n)),i===`time`&&({labels:a,dataSetsValues:n}=E_(a,n)),e.aggregated&&({labels:a,dataSetsValues:n}=j_(a,n)),e.cumulative&&(n=P_(n,`asc`));let o={y:N_(e.dataSetStyles,n,`left`),y1:N_(e.dataSetStyles,n,`right`),x:M_(t)},s=[];for(let t in n){let{data:o,dataSetId:c}=n[t],l=e.dataSetStyles?.[c]?.trend;if(!l?.display){s.push(void 0);continue}s.push(m_(l,o,a,i,r.getLocale()))}return{dataSetsValues:n,axisFormats:o,labels:a,locale:r.getLocale(),trendDataSetsValues:s,axisType:i,topPadding:F_(e,r)}}function c_(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=D_(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=j_(i,n)),{dataSetsValues:n,labels:i}=T_(i,n);let a=N_(e.dataSetStyles,n,`left`);return{dataSetsValues:n,axisFormats:{y:a},labels:i,locale:r.getLocale(),topPadding:F_(e,r)}}function l_(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=D_(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=j_(i,n));let a={r:N_(e.dataSetStyles,n,`left`)||N_(e.dataSetStyles,n,`right`)};return{dataSetsValues:n,axisFormats:a,labels:i,locale:r.getLocale()}}function u_(e,{labelValues:t,dataSetsValues:n},r){n=n.slice(0,1);let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=j_(i,n));let a=N_(e.dataSetStyles,n,`left`)||N_(e.dataSetStyles,n,`right`);return{dataSetsValues:n,axisFormats:{y:a},labels:i,locale:r.getLocale(),availableRegions:r.getGeoChartAvailableRegions(),geoFeatureNameToId:r.geoFeatureNameToId,getGeoJsonFeatures:r.getGeoJsonFeatures}}function d_(e,{labelValues:t,dataSetsValues:n},r){let i=t.map(({value:e,format:t})=>H(e,{format:t,locale:r.getLocale()}));({labels:i,dataSetsValues:n}=D_(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=j_(i,n)),e.cumulative&&(n=P_(n,`desc`));let a=N_(e.dataSetStyles,n,`left`)||N_(e.dataSetStyles,n,`right`);return{dataSetsValues:n,axisFormats:{x:a},labels:i,locale:r.getLocale()}}function f_(e,{labelValues:t,dataSetsValues:n},r){let i=t;return{labels:i,dataSetsValues:n}=A_(i,n),{labels:i,dataSetsValues:n}=k_(i,n),{dataSetsValues:n,axisFormats:{y:M_(i)},labels:i.map(({value:e})=>String(e??``)),locale:r.getLocale()}}function p_(e,t){let n=[],r=[],i=[];for(let e=0;e<t.length;e++){let a=t[e];U(a)&&(n.push(a.value),r.push(e+1)),i.push(e+1)}let a=h_(e,n,r,C(.5,i.length+.55,.2));return a.length?a:void 0}function m_(e,t,n,r,i){let a=[],o=[],s=[],c=t.length;if(c<2)return;switch(r){case`category`:for(let e=0;e<c;e++){let n=t[e];U(n)&&(a.push(n.value),o.push(e+1)),s.push(e+1)}break;case`linear`:for(let e=0;e<t.length;e++){let r=Number(n[e]);if(isNaN(r))continue;let i=t[e];U(i)&&(a.push(i.value),o.push(r)),s.push(r)}break;case`time`:for(let e=0;e<t.length;e++){let r=I({value:n[e]},i),c=t[e];U(c)&&(a.push(c.value),o.push(r)),s.push(r)}break}let l=Math.min(...s),u=Math.max(...s);if(u===l)return;let d=5*s.length,f=(u-l)/d,p=h_(e,a,o,C(l,u+f/2,f));if(p.length)return p}function h_(e,t,n,r){if(t.length<2||n.length<2||r.length===0)return[];let{normalizedLabels:i,normalizedNewLabels:a}=g_(n,r,e);try{switch(e.type){case`polynomial`:{let n=e.order;if(!n)return r.map(e=>({x:e,y:NaN}));if(n===1)return Vh([t],[i],[a],!0)[0].map((e,t)=>({x:r[t],y:e}));let o=Ih(t,i,n,!0).flat();return a.map((e,t)=>({x:r[t],y:Rh(o,e,n)}))}case`exponential`:{let e=[],n=[];for(let r=0;r<t.length;r++)t[r]>0&&(e.push(Math.log(t[r])),n.push(i[r]));return n.length?zh(Vh([e],[n],[a],!0))[0].map((e,t)=>({x:r[t],y:e})):r.map(e=>({x:e,y:NaN}))}case`logarithmic`:return Vh([t],Bh([i]),Bh([a]),!0)[0].map((e,t)=>({x:r[t],y:e}));case`trailingMovingAverage`:return Hh(t,n,e.window);default:return r.map(e=>({x:e,y:NaN}))}}catch{return r.map(e=>({x:e,y:NaN}))}}function g_(e,t,n){let r=[],i=[];if(n.type===`logarithmic`){let n=Math.max(...e.map(Math.abs));r=e.map(e=>e/n),i=t.map(e=>e/n)}else{let n=Math.max(...e),a=n-Math.min(...e);r=e.map(e=>(e-n)/a),i=t.map(e=>(e-n)/a)}return{normalizedLabels:r,normalizedNewLabels:i}}function __(e,t){return v_(e,t)&&w_()?`time`:y_(e,t)?`linear`:`category`}function v_(e,t){return!e.labelsAsText&&x_(t)}function y_(e,t){return!e.labelsAsText&&S_(t)}function b_(e){return x_(e)||S_(e)}function x_(e){if(!S_(e))return!1;let t=M_(e.labelValues);return!!(t&&Kf.test(t))}function S_(e){let t=e.labelValues;return!(t.some(e=>!U(e)&&e.value)||t.every(e=>!e.value))}let C_=!1;function w_(){if(!window.Chart)return!1;let e=new window.Chart._adapters._date({})._id===`luxon`;return!e&&!C_&&(C_=!0,console.warn(`'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled.`)),e}function T_(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(e=>t.some(t=>U(t.data[e])&&t.data[e].value>0));return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>U(e.data[t])&&e.data[t].value>0?e.data[t]:e_)}))}}function E_(e,t){if(e.length===0||e.every(e=>!e))return{labels:e,dataSetsValues:t};let n=[...e],r=x(t);for(let e=0;e<n.length;e++)if(!n[e]){n[e]=St(n,e);for(let t of r)t.data[e]=e_}return{labels:n,dataSetsValues:r}}function D_(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(n=>{let r=e[n],i=t.map(e=>e.data?.[n]);return r||i.some(U)});return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>U(e.data[t])?e.data[t]:e_)}))}}function O_(e,t){let n=C(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(n=>{let r=e[n],i=t.map(e=>e.data?.[n]);return U(r)&&U(i[0])});return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>U(e.data[t])?e.data[t]:e_)}))}}function k_(e,t){let n=Math.max(e.length,...t.map(e=>e.data?.length||0)),r=e=>e==null||e===``,i=C(0,n).filter(n=>{let i=t.map(e=>e.data?.[n]);if(r(i[0]?.value))return!1;let a=!1;for(let e of i)if(a||=r(e?.value),a&&!r(e?.value))return!1;return e[n]&&U(e[n])});return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}function A_(e,t){let n=[],r=[];for(let t=0;t<e.length;t++)Number(e[t].value)<=0?r.push(t):Number(e[t].value)>0&&n.push(t);let i=n.length?n:r;return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}function j_(e,t){let n=e=>typeof e==`number`?e:0,r=new Set(e),i={};r.forEach(e=>{i[e]=Array(t.length)});for(let r of C(0,e.length)){let a=e[r];for(let e of C(0,t.length)){let o=t[e].data[r];i[a][e]?i[a][e].value+=n(o?.value):i[a][e]={...o,value:n(o?.value)}}}return{labels:Array.from(r),dataSetsValues:t.map((e,t)=>({...e,data:Array.from(r).map(e=>i[e][t])}))}}function M_(e){return e.find(({format:e})=>e!==void 0)?.format}function N_(e,t,n){let r=t.filter(t=>n===`right`==(e?.[t.dataSetId]?.yAxisId===`y1`));for(let e of r){let t=e.data.find(({format:e})=>e!==void 0&&!Rl(e));if(t)return t.format}}function P_(e,t){return e.map(e=>{let n=[],r=0,i=t===`asc`?C(0,e.data.length):C(0,e.data.length).reverse();for(let t of i){let i=e.data[t];U(i)?(r+=i.value,n[t]={...i,value:r}):n[t]=e_}return{...e,data:n}})}function F_(e,t){let{title:n,legendPosition:r}=e,i=n&&n.text||r===`top`;return t.isDashboard()&&!i?30:0}function I_(e,t){return{padding:{left:20,right:20,top:Math.max(15,t.topPadding||0),bottom:10}}}function L_(e,t){let n=e.legendPosition;return{padding:{left:20+(n===`left`?70:0),right:20+(n===`right`?70:0),top:Math.max(15,t.topPadding||0),bottom:10}}}function R_(e,t){return{display:e.legendPosition!==`none`,position:e.legendPosition===`none`?void 0:e.legendPosition}}function z_(e,t){return{...q_,...R_(e,t),...J_(wf(e.background),{pointStyle:`rect`,lineWidth:3})}}function B_(e,t){let n=e.fillArea,r=n?`rect`:`line`,i=n?2:3;return{...q_,...R_(e,t),...J_(wf(e.background),{pointStyle:r,lineWidth:i})}}function V_(e,t){let{dataSetsValues:n}=t,r=Pf(new ui(Math.max(0,...n.map(e=>e?.data?.length??0)),e.slicesColors),n),i=wf(e.background);return{...R_(e,t),labels:{usePointStyle:!0,generateLabels:e=>(e.data.labels?.map((e,t)=>({text:Ff(String(e)),strokeStyle:r[t],fillStyle:r[t],pointStyle:`rect`,lineWidth:2,fontColor:i}))||[]).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}function H_(e,t){return{...q_,...R_(e,t),...J_(wf(e.background),{pointStyle:`circle`,strokeStyle:e.background||`#ffffff`,lineWidth:8})}}function U_(e,t){return{...q_,...R_(e,t),...J_(wf(e.background),{lineWidth:3})}}function W_(e,t){let n=wf(e.background),r=e.negativeValuesColor||`#EA6175`,i=e.positiveValuesColor||`#4EA7F2`,a=e.subTotalValuesColor||`#AAAAAA`;return{...R_(e,t),labels:{usePointStyle:!0,generateLabels:()=>{let t=[{text:j(`Positive values`),fontColor:n,fillStyle:i,strokeStyle:i,pointStyle:`rect`},{text:j(`Negative values`),fontColor:n,fillStyle:r,strokeStyle:r,pointStyle:`rect`}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:j(`Subtotals`),fontColor:n,fillStyle:a,strokeStyle:a,pointStyle:`rect`}),t},filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0},onClick:()=>{}}}function G_(e,t){let n=e.fillArea??!1,r=n?`rect`:`line`,i=n?2:3;return{...q_,...R_(e,t),...J_(wf(e.background),{pointStyle:r,lineWidth:i})}}function K_(e,t){let n=wf(e.background);return{...R_(e,t),labels:{usePointStyle:!0,generateLabels:e=>{let t=e.data.datasets.at(-1);return t?t.groupColors.map(({color:e,label:t})=>({text:Ff(t),fontColor:n,fillStyle:e,strokeStyle:e,pointStyle:`rect`})):[]}}}}let q_={onHover:e=>{let t=e.native?.target;t&&(t.style.cursor=`pointer`)},onLeave:e=>{let t=e.native?.target;t&&(t.style.cursor=`default`)},onClick:(e,t,n)=>{if(e.type!==`click`)return;let r=t.datasetIndex;!n.legendItems||r===void 0||(n.chart.isDatasetVisible(r)?n.chart.hide(r):n.chart.show(r),e.native.preventDefault(),e.native.stopPropagation())}};function J_(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:n=>n.data.datasets.map((r,i)=>If(r.xAxisID)?{text:Ff(r.label),fontColor:e,strokeStyle:r.borderColor,hidden:!n.isDatasetVisible(i),pointStyle:`line`,datasetIndex:i,lineWidth:3}:{text:Ff(r.label),fontColor:e,strokeStyle:r.borderColor,fillStyle:r.backgroundColor,hidden:!n.isDatasetVisible(i),pointStyle:r.type===`line`?`line`:`rect`,datasetIndex:i,...t}).filter(e=>e.text),filter:(e,t)=>`datasetIndex`in e?!t.datasets[e.datasetIndex].hidden:!0}}}let Y_={showValues:!1,showLabels:!0,valuesDesign:{align:`center`,fontSize:13}};function X_(e,t){let{axisFormats:n,locale:r}=t;return{type:e.type,horizontal:`horizontal`in e&&e.horizontal,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(t,i)=>{let a=tv(e,i);return jf(n,r,e.humanize)(t,a)}}}function Z_(e,t){let{locale:n,axisFormats:r}=t,i=(t,n,r)=>e.background,a=t.dataSetsValues.flat().flatMap(e=>e?.data.filter(U)).map(e=>e.value);if(a.length){let t=Math.min(...a),n=Math.max(...a),r=dp(e.colorScale??Wh(`oranges`),t,n);i=(t,n,i)=>{let a=n._dataset.values[i];return a===void 0?e.background:wf(r(a))}}return{type:`calendar`,horizontal:!1,showValues:`showValues`in e?!!e.showValues:!1,background:i,callback:(e,t,i)=>{let a=t._dataset.values[i];return a===void 0?``:Zl({value:a,format:r?.y},n)}}}function Q_(e,t){let{axisFormats:n,locale:r}=t;return{callback:jf(n,r,e.humanize),showLabels:e.showLabels??Y_.showLabels,showValues:e.showValues??Y_.showValues,style:{fontSize:e.valuesDesign?.fontSize??Y_.valuesDesign.fontSize,align:e.valuesDesign?.align??Y_.valuesDesign.align,bold:e.valuesDesign?.bold??Y_.valuesDesign.bold,italic:e.valuesDesign?.italic??Y_.valuesDesign.italic,textColor:e.valuesDesign?.color??Y_.valuesDesign.color}}}function $_(e,t){let{axisFormats:n,locale:r}=t;return{type:`pyramid`,horizontal:!0,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(e,t)=>(e=Math.abs(Number(e)),e===0?``:jf(n,r)(e,t.xAxisID||`x`))}}function ev(e,t){let{axisFormats:n,locale:r,dataSetsValues:i}=t,a=i.reduce((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e),[]);return{type:`waterfall`,showValues:`showValues`in e?!!e.showValues:!1,background:()=>e.background,callback:(t,i,o)=>{let s=i._dataset.data[o],c=s[1]-s[0],l=c>=0?`+`:``;return e.showSubTotals&&a.includes(o)&&l===`+`&&(l=``),`${l}${jf(n,r,e.humanize)(c,i.yAxisID)}`}}}function tv(e,t){return t.rAxisID?t.rAxisID:(`horizontal`in e&&e.horizontal?t.xAxisID:t.yAxisID)||`y`}function nv(e,t){let n=e.title,r=Tf(e.background);return{display:!!n.text,text:n.text?t.dynamicTranslate(n.text):``,color:n?.color??r,align:n.align===`center`?`center`:n.align===`right`?`end`:`start`,font:{size:e.title.fontSize??16,weight:n.bold?`bold`:`normal`,style:n.italic?`italic`:`normal`},padding:{bottom:e.legendPosition===`top`?0:20}}}let rv;function iv(e,t={}){return av(e,t).innerHTML}function av(e,n={}){rv||=new t.App(t.Component,{templates:`
|
|
19
19
|
<templates>
|
|
20
20
|
<t t-name="o-spreadsheet-CustomTooltip">
|
|
21
21
|
<div
|
|
@@ -111,9 +111,9 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
111
111
|
offset="offset"
|
|
112
112
|
direction="'vertical'"
|
|
113
113
|
onScroll.bind="onScroll"
|
|
114
|
-
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){let{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{y:e}=this.env.model.getters.getMainViewportRect(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`${t}px`,bottom:Am()?`${t}px`:`0`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},_I=class extends t.Component{static template=`o-spreadsheet-Selection`;static props={};static components={Highlight:fI};get highlightProps(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:ae}}},vI=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=nF(this.env);setup(){hk(this)}get containerStyle(){let e=this.props.table.range.zone,t=this.props.table.range.sheetId;if(this.env.model.getters.isReadonly()||this.env.model.getters.isSheetLocked(t))return W({display:`none`});let n={...e,left:e.right,top:e.bottom},r=this.env.model.getters.getVisibleRect(n);return r.height===0||r.width===0?W({display:`none`}):W({top:`${r.y+r.height-6}px`,left:`${r.x+r.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`;let r=Rm(this.env,e);this.dragNDropGrid.start(r,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let t=this.props.table.range.sheetId;this.env.model.dispatch(`RESIZE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:`#777`,noFill:!0}]:[]}};let yI={ROW:$P,COL:KP,CELL:NP,GROUP_HEADERS:ZP,UNGROUP_HEADERS:QP};var bI=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:jF,GridOverlay:YF,GridPopover:XF,HeadersOverlay:nI,MenuPopover:Oy,Autofill:iF,ClientTag:oF,Highlight:fI,Popover:wy,VerticalScrollBar:gI,HorizontalScrollBar:hI,TableResizer:vI,Selection:_I};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=nF(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=O(fT),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=O(Iy),this.composerFocusStore=O(Er),this.DOMFocusableElementStore=O(py),this.sidePanel=O(rN),this.paintFormatStore=O(GF),this.clientFocusStore=O(tF),O(eF),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),iI({refName:`canvas`,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState()})}),this.onMouseWheel=cI((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=O(Sw),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),oI(this.gridRef,{updateScroll:this.moveCanvas.bind(this),canMoveUp:()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},canMoveDown:()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e},getZoom:()=>this.env.model.getters.getViewportZoomLevel(),setZoom:e=>this.env.model.dispatch(`SET_ZOOM`,{zoom:e})})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){let e=this.env.model.getters.getScrollBarWidth();return W({top:`26px`,left:`48px`,height:`calc(100% - ${26+e}px)`,width:`calc(100% - ${48+e}px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>this.editOrMoveInSelection(`down`),"Shift+Enter":()=>this.editOrMoveInSelection(`up`),Tab:()=>this.moveInSelection(`right`),"Shift+Tab":()=>this.moveInSelection(`left`),F2:()=>{this.focusComposerFromActiveCell()},Delete:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch(`CLEAN_CLIPBOARD_HIGHLIGHT`)},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch(`REQUEST_UNDO`),"Ctrl+Y":()=>this.env.model.dispatch(`REQUEST_REDO`),F4:()=>this.env.model.dispatch(`REQUEST_REDO`),"Ctrl+B":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>GE(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&Lu(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+D":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ABOVE`})},"Ctrl+R":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ON_LEFT`})},"Ctrl+Enter":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ON_ZONE`})},"Ctrl+H":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+F":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign(`center`),"Ctrl+Shift+L":()=>this.setHorizontalAlign(`left`),"Ctrl+Shift+R":()=>this.setHorizontalAlign(`right`),"Ctrl+Shift+V":()=>bE(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?IE(this.env):i&&!r&&PE(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},"Shift+F11":()=>{RD.execute?.(this.env)},"Alt+T":()=>{TD.execute?.(this.env)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>{this.closeMenu(),JE(this.env)},"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey(`right`),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey(`left`),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey(`up`),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey(`down`)};focusComposerFromActiveCell(){this.env.model.getters.getActiveCell().type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}editOrMoveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.focusComposerFromActiveCell();return}zw(this.env.model.getters,this.env.model.selection,e)}moveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.env.model.selection.moveAnchorCell(e,1);return}zw(this.env.model.getters,this.env.model.selection,e)}isSingleCellOrMergeSelection(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();return this.env.model.getters.isSingleCellOrMerge(e,t)}focusDefaultElement(){!this.env.model.getters.getSelectedFigureId()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{x:t.x+t.width-8/2,y:t.y+t.height-8/2}}get isAutofillVisible(){if(this.env.model.getters.isCurrentSheetLocked())return!1;let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(t.width===0||t.height===0)}onGridResized(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){let e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{..._m(this.gridRef),width:t*e,height:n*e}}onCellClicked(e,t,n,r){if(r.ev.preventDefault(),this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.env.model.selection.commitSelection(),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),Rw(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=Tm(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRectWithZoom(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;Fn(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=yI[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?LN(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files].find(e=>JT.includes(e.type)),r={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation();if(this.env.model.getters.getClipboardId()===$T(r.content[`text/html`]))yw(this.env,i);else{let e=QT(r.content);await bw(this.env,i,e)}a&&await this.env.clipboard.write({"text/plain":``})}clearFormatting(){this.env.model.dispatch(`CLEAR_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`}))}processHeaderGroupingEventOnGrid(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!FN(this.env,`COL`)&&!FN(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:`cellFocus`})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:`contentFocus`})}get staticTables(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(AM)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}get clientsToDisplay(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getClientsToDisplay(e)}};let xI=new A;xI.add(`SPREADSHEET`,!1);var SI=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=O(KF)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position),t=kd(e);return W({height:`${t}px`,width:`${t}px`,color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?Kr(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},CI=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:My};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=Sy();figureRegistry=Py;setup(){this.fullScreenFigureStore=O(fy);let e=O(Gd),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return Py.get(this.figureUI.tag).Component}},wI=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:BT};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(L(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=L(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Og(e,o,a).join(`,`)})`,value:H(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},TI=class{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},EI=class extends TI{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e,t){}adaptRanges(e){}},DI=class extends EI{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>x(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Oe.style,color:e.border.color||Oe.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of rt(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?x(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(w))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&T(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(w);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?C(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!T(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!T(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!T(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!T(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of cn(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of cn(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||T(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of ud(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,yn(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=cd(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=ld(e)}e.borders=t}exportForExcel(e){this.export(e)}},OI=class extends EI{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?`DuplicatedFigureId`:`Success`;case`UPDATE_CAROUSEL`:return this.carousels[e.sheetId]?.[e.figureId]?`Success`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},kI=class{getters;baseFormula;alreadyAppliedNumberOffsets=[];previousStrings=[];baseFormulaWasTransformed=!1;rangeToStringOptions={doNotSimplifyRange:!0};baseNumber=void 0;constructor(e){this.getters=e}buildResult(e,t,n){let r={};if(e.length&&(r.N=e.join(`|`)),t.length&&(r.S=t),n.length){let e;e=n.some(e=>e.includes(`|`))?n:n.join(`|`),r.R=e}return r}resetBaseTo(e){this.baseFormula=Bc.CopyWithDependenciesAndLiteral(e,e.sheetId,x(e.rangeDependencies),e.literalValues.numbers,e.literalValues.strings),this.alreadyAppliedNumberOffsets=e.literalValues.numbers.map(e=>0),this.previousStrings=e.literalValues.strings.map(e=>e.value),this.baseFormulaWasTransformed=!1,this.baseNumber=void 0}resetBaseFormula(){this.baseFormula&&(this.baseFormula=void 0,this.alreadyAppliedNumberOffsets=[],this.previousStrings=[],this.baseFormulaWasTransformed=!1)}squish(e,t){if(e.isFormula){if(Lo.getAll().some(t=>e.compiledFormula.usesSymbol(t)))return this.resetBaseFormula(),e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions);let n=[],r=[],i=[];return!this.baseFormula||this.baseFormula.normalizedFormula!==e.compiledFormula.normalizedFormula?(this.resetBaseTo(e.compiledFormula),e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions)):!this.baseFormulaWasTransformed&&T(e.compiledFormula.literalValues,this.baseFormula.literalValues)&&T(e.compiledFormula.rangeDependencies,this.baseFormula.rangeDependencies)?e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions):(n=this.squishNumbers(e.compiledFormula.literalValues.numbers),r=this.squishStrings(e.compiledFormula.literalValues.strings),i=this.squishReferences(e.compiledFormula.rangeDependencies,t),this.baseFormulaWasTransformed=!0,this.buildResult(n,r,i))}if(typeof e.parsedValue==`number`&&e.parsedValue%1==0){this.resetBaseFormula();let t=e.parsedValue;if(this.baseNumber===void 0)return this.baseNumber=t,e.content;let n=t-this.baseNumber;return n===0?e.content:(this.baseNumber=t,{N:(n>0?`+`:``)+n.toString()})}return this.resetBaseFormula(),this.baseNumber=void 0,e.content}squishCommand(e){if(e.content){let t=Bu(this.getters,-1,e.content,e.format,e.style??void 0,e.sheetId),n=this.squish(t,e.sheetId);return typeof n==`string`?e.content:n}return e.content}squishSheet(e,t){let n=Object.keys(e),r={};for(let i=0;i<n.length;i++){let a=sn(n[i]),o=0;for(o=0;o+i+1<n.length;o++){let t=sn(n[o+i+1]);if(t.col!==a.col||t.row!==a.row+o+1||!T(e[n[o+i+1]],e[n[i]]))break}if(o>0){let t=`${n[i]}:${E(a.col,a.row+o)}`;r[t]=e[n[i]],i+=o}else{let o=this.getters.getCell({sheetId:t,col:a.col,row:a.row});!o?.isFormula&&typeof o?.parsedValue==`number`?r[n[i]]=o.content:r[n[i]]=e[n[i]]}}return r}squishReferences(e,t){if(!this.baseFormula)throw Error(`No previous cell to squish against`);return e.map((e,n)=>this.squishOneReference(e,this.baseFormula.rangeDependencies,n,t))}squishOneReference(e,t,n,r){let i=t[n];if(T(i,e))return`=`;if(i.sheetId!==e.sheetId||i.prefixSheet!==e.prefixSheet||i.invalidSheetName!==e.invalidSheetName||i.invalidXc!==e.invalidXc||i.parts.length!==e.parts.length||i.unboundedZone.bottom===void 0||i.unboundedZone.right===void 0||e.unboundedZone.bottom===void 0||e.unboundedZone.right===void 0)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);for(let a=0;a<e.parts.length;a++)if(i.parts[a].colFixed!==e.parts[a].colFixed||i.parts[a].rowFixed!==e.parts[a].rowFixed)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);let a=e.zone,o=i.zone;if(a.top!==a.bottom||a.left!==a.right||o.top!==o.bottom||o.left!==o.right)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);let s=e.zone.left-i.zone.left,c=e.zone.top-i.zone.top;return i.zone=x(e.zone),i.unboundedZone=x(e.unboundedZone),s!==0&&c===0?`${s>0?`+`:`-`}C${Math.abs(s)}`:c!==0&&s===0?`${c>0?`+`:`-`}R${Math.abs(c)}`:nc(e,r,this.getters.getSheetName,this.rangeToStringOptions)}squishNumbers(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=this.baseFormula.literalValues.numbers[n].value,i=e[n].value,a=this.alreadyAppliedNumberOffsets[n]||0,o=i-(r+a);o!==0&&(t[n]=`+`+o.toString(),this.alreadyAppliedNumberOffsets[n]=a+o)}return t}squishStrings(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=e[n].value;r!==this.previousStrings[n]&&(t[n]=r,this.previousStrings[n]=r)}return t}};function AI(e){return[sn(e)]}function*jI(e,t){let n=sn(e),r=sn(t);for(let e=Math.min(n.col,r.col);e<=Math.max(n.col,r.col);e++)for(let t=Math.min(n.row,r.row);t<=Math.max(n.row,r.row);t++)yield{col:e,row:t}}var MI=class{previousFormula;alreadyAppliedNumberOffset=[];previousString=[];alreadyAppliedReferenceOffset=[];previousOffset=void 0;previousNumber=void 0;previousNumberFormat;rebase(){this.previousFormula=void 0,this.alreadyAppliedNumberOffset=[],this.previousString=[],this.alreadyAppliedReferenceOffset=[],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}*unsquishCommands(e,t){let n;for(let r of e){if(r.type!==`UPDATE_CELL`&&r.type!==`SQUISHED_UPDATE_CELL`){yield r;continue}let e=r.content;n=e==null||e===``?`NOT_A_FORMULA`:this.chooseStrategy(e,n,r.sheetId,t);let i;if(r.type===`SQUISHED_UPDATE_CELL`&&`targetRange`in r){let[e,t]=r.targetRange.split(`:`);i=jI(e,t)}else i=[{row:r.row,col:r.col}];for(let{position:a,compiled:o,content:s}of this.applyStrategy(n,i,e,r.sheetId,t)){let e=o?o.toFormulaString(t):s,n={type:`UPDATE_CELL`,sheetId:r.sheetId,row:a.row,col:a.col};(`content`in r||o)&&(n.content=e),`style`in r&&(n.style=r.style),`format`in r&&(n.format=r.format),yield n}}}*unsquishSheet(e,t,n){let r=Object.keys(e).map(e=>({cartesian:sn(e.split(`:`)[0]),key:e})).sort((e,t)=>e.cartesian.col===t.cartesian.col?e.cartesian.row-t.cartesian.row:e.cartesian.col-t.cartesian.col),i;for(let{key:a}of r){let r=e[a];if(r==null||r===``)continue;i=this.chooseStrategy(r,i,t,n);let o=a.split(`:`),s=o.length===1?AI(a):jI(o[0],o[1]);yield*this.applyStrategy(i,s,r,t,n)}}chooseStrategy(e,t,n,r){let i=t;if(typeof e==`string`)if(e.startsWith(`=`)){i=`NEW_FORMULA`;let t=Bc.Compile(e,n,r);this.previousFormula=t,this.alreadyAppliedNumberOffset=t.literalValues.numbers.map(e=>e.value),this.previousString=t.literalValues.strings.map(e=>e.value),this.alreadyAppliedReferenceOffset=[...t.rangeDependencies],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}else{let t=this.parseSquishableLiteral(e,r);t?(i=`NEW_NUMBER`,this.rebase(),this.previousNumber=t.value,this.previousNumberFormat=t.format):(this.rebase(),i=`NOT_A_FORMULA`)}else if(e.N||e.S||e.R){if(!i)throw Error(`Incorrect order of commands, cannot unsquish`);switch(i){case`NEW_FORMULA`:i=`FIRST_OFFSET`;break;case`NEW_NUMBER`:if(e.R||e.S)throw Error(`Invalid squished format: cannot have string or reference offsets for a number`);i=`OFFSET_NUMBER`;break;case`FIRST_OFFSET`:i=`COMBINE_OFFSET`;break}}return i}*applyStrategy(e,t,n,r,i){let a=n;switch(e){case`NEW_FORMULA`:for(let e of t)yield{position:e,compiled:this.previousFormula};break;case`NOT_A_FORMULA`:for(let e of t)yield{position:e,content:a};break;case`FIRST_OFFSET`:{let e=a;this.previousOffset=e;for(let n of t){let t=this.unsquishFormula(e,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:n,compiled:t};else{let e=t.toFormulaString(i);yield{position:n,compiled:Bc.Compile(e,r,i)}}}break}case`COMBINE_OFFSET`:{if(!this.previousOffset)throw Error(`No previous offset to combine with`);let e=a;this.previousOffset.N=e.N??this.previousOffset.N,this.previousOffset.S=e.S??this.previousOffset.S,this.previousOffset.R=e.R??this.previousOffset.R;for(let e of t){let t=this.unsquishFormula(this.previousOffset,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:e,compiled:t};else{let n=t.toFormulaString(i);yield{position:e,compiled:Bc.Compile(n,r,i)}}}break}case`NEW_NUMBER`:for(let e of t)yield{position:e,content:a};break;case`OFFSET_NUMBER`:{let e=a.N;if(e===void 0||this.previousNumber===void 0)throw Error(`No ${e} provided for OFFSET_NUMBER strategy, previous ${this.previousNumber} for ${r}!${JSON.stringify(a)} `);let n=parseFloat(e),o={format:this.previousNumberFormat,locale:i.getLocale()};for(let e of t)this.previousNumber+=n,yield{position:e,content:H(this.previousNumber,o)};break}}}parseSquishableLiteral(e,t){let n=Vu(t,-1,e,void 0,void 0);if(!(typeof n.parsedValue!=`number`||n.parsedValue%1!=0))return{value:n.parsedValue,format:n.format}}unsquishFormula(e,t,n){if(typeof e==`object`&&this.previousFormula){let r={numbers:[],strings:[],dependencies:[]};if(e.N!==void 0&&e.N.length>0?r.numbers=e.N.split(`|`).map(this.adjustNumbers):r.numbers=this.previousFormula.literalValues.numbers,e.S!==void 0&&e.S.length>0?r.strings=e.S.map(this.adjustStrings):r.strings=this.previousFormula.literalValues.strings,e.R!==void 0&&this.previousFormula){let i;i=typeof e.R==`string`?e.R.split(`|`):e.R,r.dependencies=i.map((e,r)=>{if(e===`=`)return{...this.alreadyAppliedReferenceOffset[r]};if(e.startsWith(`+`)||e.startsWith(`-`)){let t=parseInt(e.slice(2),10),n=e[0]===`+`?1:-1;if(e[1]===`R`){let e=this.alreadyAppliedReferenceOffset[r].zone.top+t*n,i={...this.alreadyAppliedReferenceOffset[r]};return i.zone=i.unboundedZone={...i.zone,top:e,bottom:e},this.alreadyAppliedReferenceOffset[r]=i,i}else if(e[1]===`C`){let e=this.alreadyAppliedReferenceOffset[r].zone.left+t*n,i=Object.assign({},this.alreadyAppliedReferenceOffset[r]);return i.zone=i.unboundedZone=Object.assign({},i.zone,{left:e,right:e}),this.alreadyAppliedReferenceOffset[r]=i,i}else throw Error(`Invalid reference offset format: ${e}`)}else{let i=n.getRangeFromSheetXC(t,e);return this.alreadyAppliedReferenceOffset[r]=i,i}})}else r.dependencies=this.previousFormula.rangeDependencies;return Bc.CopyWithDependenciesAndLiteral(this.previousFormula,t,r.dependencies,r.numbers,r.strings)}throw Error(`Invalid squished element or no previous cell to unsquish against`)}adjustStrings=(e,t)=>e===`=`?{value:this.previousString[t]}:(this.previousString[t]=e,{value:e});adjustNumbers=(e,t)=>{if(e===`=`)return{value:this.alreadyAppliedNumberOffset[t]};{let n=parseFloat(e.slice(1)),r=(this.alreadyAppliedNumberOffset[t]||0)+n;return this.alreadyAppliedNumberOffset[t]=r,{value:r}}}},NI=class extends EI{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e){for(let t of Object.keys(this.cells))for(let n of Object.values(this.cells[t]||{}))if(n.isFormula){let r=e.adaptCompiledFormula(n.compiledFormula);r!==n.compiledFormula&&this.history.update(`cells`,t,n.id,`compiledFormula`,r)}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;case`SET_FORMATTING`:return this.checkUselessSetFormatting(e);default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:this.setStyleFormat(e.sheetId,e.target,e.style,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}clearFormatting(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=C(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=C(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){let t=performance.now();for(let t of e.sheets){let n=t.id,r=new aN,i=new MI;for(let e of i.unsquishSheet(t.cells,t.id,this.getters))if(e.content||e.compiled){let n={sheetId:t.id,col:e.position.col,row:e.position.row};e.compiled?r.set(n,{compiledFormula:e.compiled}):r.set(n,{content:e.content})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of ud(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style||n?.compiledFormula){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0,n?.compiledFormula);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}console.debug(`cells imported in`,performance.now()-t,`ms`)}export(e,t){let n={},r={};for(let i of e.sheets){let e=new kI(this.getters),a=[],o=[],s={},c=Object.values(this.cells[i.id]||{}).map(e=>this.getters.getCellPosition(e.id)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let l of c){let c=this.getters.getCell(l),u=this.extractCustomStyle(c);if(Object.keys(u).length){let e=cd(u,n);a[e]??=[],a[e].push(l)}if(c.format){let e=cd(c.format,r);o[e]??=[],o[e].push(l)}let d=E(l.col,l.row);c.isFormula?s[d]=t?e.squish(c,i.id):c.compiledFormula.toFormulaString(this.getters):c.content&&(s[d]=t?e.squish(c,i.id):c.content)}i.styles=ld(a),i.formats=ld(o),i.cells=t?e.squishSheet(s,i.id):s}e.styles=n,e.formats=r}importCell(e,t,n,r,i){let a=this.getNextCellId();return i?Uu(a,i,r,n):Bu(this.getters,a,t||``,r,n,e,{avoidAutomaticDateFormat:!0})}exportForExcel(e){this.export(e,!1);let t=[];for(let n in e.formats||[])au(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=!e.isFormula&&Pa(e.content,V)?Ce:xe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return Object.values(this.cells[e]||{})}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){return Bc.CopyWithDependencies(t,e,n).toFormulaString(this.getters,{useBoundedReference:r})}getTranslatedCellFormula(e,t,n,r){r instanceof Bc||(r=Bc.CompileForSerializedFormula(e,r));let i=this.getters.createAdaptedRanges(r.rangeDependencies,t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t){let n=this.getters.removeRangesSheetPrefix(e,t.rangeDependencies);return Bc.CopyWithDependencies(t,e,n).toFormulaString(this.getters)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=E(t.left,t.top,n[0]),i=E(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyleFormat(e,t,n,r){if(!(n===void 0&&r===void 0))for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++){let i=this.getters.getCell({sheetId:e,col:t,row:a});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:a,style:n?{...i?.style,...n}:void 0,format:r})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextCellId(){let e=this.nextId;return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o;o=a?Mt(r?.content):i?.isFormula?i.compiledFormula.toFormulaString(this.getters):i?.content||``;let s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||!i.isFormula&&i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextCellId(),u=Bu(this.getters,l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?Fn(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.isFormula&&!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.isFormula&&t.compiledFormula.toFormulaString(this.getters)===e.content||!t?.isFormula&&t?.content===e.content)&&(!r||T(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}checkUselessSetFormatting(e){let{sheetId:t,target:n}=e,r=`style`in e,i=`format`in e;if(!r&&!i)return`NoChanges`;for(let a of cn(n))for(let n=a.left;n<=a.right;n++)for(let o=a.top;o<=a.bottom;o++){let a={sheetId:t,col:n,row:o},s=this.getters.getCell(a);if(r&&!T(s?.style,e.style)||i&&s?.format!==e.format)return`Success`}return`NoChanges`}},PI=class extends EI{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=CO.fromDefinition(this.getters,n.chart.sheetId,n.chart.updateRanges(e));this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.checkChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkChartDefinition,this.checkChartExists,this.checkChartChanged));case`DELETE_CHART`:return`SubCommandOnly`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetId,e.sheetIdTo);this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l,sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.getRangeDefinition().type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r={...e.data};delete r.chartId;let i=CO.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=CO.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}}}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=CO.fromStrDefinition(this.getters,r,n);this.history.update(`charts`,t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?`DuplicatedChartId`:`Success`}checkChartDefinition(e){return CO.validate(this,e.definition)}checkChartExists(e){return this.isChartDefined(e.chartId)?`Success`:`ChartDoesNotExist`}checkChartChanged(e){return e.figureId===this.charts[e.chartId]?.figureId&&T(this.getChartDefinition(e.chartId),e.definition)?`NoChanges`:`Success`}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?`Success`:`MissingFigureArguments`}};function FI(e){return e===``?NaN:Number(e)}var II=class extends EI{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e){for(let t of Object.keys(this.cfRules))this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)Fn(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(vn));let s=cn(o,r);return cn([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return Gh.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&T(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=X.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(Bc.IsBadExpression(e.value||``))switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&FI(t)>=FI(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&FI(t)>=FI(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&FI(t)>=FI(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&Bc.IsBadExpression(t))return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},LI=class extends EI{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e){for(let t in this.rules)this.adaptDVRanges(t,e);this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=x(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>rc(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=cn(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(!e)continue;let i=this.getters.getCell({sheetId:n,col:r,row:t});if(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!i?.isFormula&&!i?.content){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,E(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(Fn(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=x(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of ac(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...x(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return X.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=X.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=X.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||Bc.IsBadExpression(e):!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},RI=class extends EI{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges(e){for(let t in this.figures)this.adaptRangesOnSheet(e,t)}adaptRangesOnSheet({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=S(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=S(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},zI=class extends EI{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(C(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=x(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ct(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&C(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Nt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=vc(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=yc(n,C(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=Bb(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Bb(t,e,n.end+1);r.collapsed=!0}}}}}},BI=class extends EI{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,x(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ft(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ct(e.position,e.base),r=t[e.base],i=It(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of C(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of C(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},VI=class extends EI{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Ht(e.elements)<0||Vt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,x(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ct(e.position,e.base),n=It([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Et(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=C(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...C(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},HI=class extends EI{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:x(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:x(e)})}t.images=[...t.images,...n]}}},UI=class extends EI{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(w))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e){for(let t in this.merges)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(w)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(w)}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(Nn(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&Nn(n,o)&&(o=kn(n,o))}return Mn(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Mn(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Mn(t,n);let{numberOfCols:r,numberOfRows:i}=Ln(t);return r===1&&i===1}isMainCellPosition(e){return T(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&(n.isFormula||n.content!==``))return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:GI(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&Nn(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return Qn(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Mn(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1),E(n,i)===E(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,wn({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Mn(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=Ln(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Bn(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,yn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...WI(e))}}exportForExcel(e){this.export(e)}};function WI(e){return Object.entries(e).map(([e,t])=>t?GI(parseInt(e,10),t):void 0).filter(w).map(e=>E(e.left,e.top)+`:`+E(e.right,e.bottom))}function GI(e,t){return{...t.zone,id:e}}let KI=/^[\p{L}\p{N}_.]+$/u;var qI=class extends EI{static getters=[`getNamedRange`,`getNamedRangeFromZone`,`getNamedRanges`];namedRanges=[];adaptRanges({applyChange:e}){let t=[],n=!1;for(let r of this.namedRanges){let i=e(r.range);switch(i.changeType){case`REMOVE`:n=!0;break;case`RESIZE`:case`MOVE`:case`CHANGE`:n=!0,t.push({...r,range:i.range});break;case`NONE`:t.push(r)}}n&&this.history.update(`namedRanges`,t)}allowDispatch(e){switch(e.type){case`CREATE_NAMED_RANGE`:return this.checkValidNewNamedRangeName(e.name);case`UPDATE_NAMED_RANGE`:return this.checkValidations(e,()=>this.checkNamedRangeExists(e.oldRangeName),()=>e.newRangeName===e.oldRangeName?`Success`:this.checkValidNewNamedRangeName(e.newRangeName));case`DELETE_NAMED_RANGE`:return this.checkNamedRangeExists(e.name)}return`Success`}handle(e){switch(e.type){case`CREATE_NAMED_RANGE`:{let t=this.getters.getRangeFromRangeData(e.ranges[0]),n=[...this.namedRanges,{name:e.name,range:t}];this.history.update(`namedRanges`,n);break}case`UPDATE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.oldRangeName);if(t!==-1){let n=this.getters.getRangeFromRangeData(e.ranges[0]);this.history.update(`namedRanges`,t,{name:e.newRangeName,range:n})}break}case`DELETE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.name);if(t!==-1){let e=[...this.namedRanges];e.splice(t,1),this.history.update(`namedRanges`,e)}break}}}getNamedRange(e){return this.namedRanges[this.getNamedRangeIndex(e)]}getNamedRangeFromZone(e,t){for(let n of this.namedRanges){let r=n.range;if(r.sheetId===e&&T(r.unboundedZone,t))return n}}getNamedRanges(){return this.namedRanges}getNamedRangeIndex(e){return this.namedRanges.findIndex(t=>t&&t.name.toLowerCase()===e.toLowerCase())}import(e){for(let t in e.namedRanges||{})this.namedRanges.push({name:t,range:this.getters.getRangeFromSheetXC(void 0,e.namedRanges[t])})}export(e){e.namedRanges={};for(let t of this.namedRanges){let n=this.getters.getRangeString(t.range);e.namedRanges[t.name]=n}}checkValidNewNamedRangeName(e){return this.getNamedRange(e)?`NamedRangeNameAlreadyExists`:!KI.test(e)||Pa(e,V)||[`TRUE`,`FALSE`].includes(e.toUpperCase())?`NamedRangeInvalidName`:Go.test(e)?`NamedRangeNameLooksLikeCellReference`:`Success`}checkNamedRangeExists(e){return this.getNamedRange(e)?`Success`:`NamedRangeNotFound`}},JI=class extends EI{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return e.pivotId in this.pivots?`PivotIdTaken`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?T(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new Fj(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=x(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,x(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break;case`CREATE_NAMED_RANGE`:case`UPDATE_NAMED_RANGE`:case`DELETE_NAMED_RANGE`:for(let e in this.pivots){let t=this.pivots[e];t&&this.compileCalculatedMeasures(e,t.definition.measures)}}}adaptRanges(e){let{applyChange:t,adaptFormulaString:n}=e;for(let e in this.pivots){let n=x(this.pivots[e]?.definition);if(!n)continue;let r=qj.get(n.type)?.adaptRanges?.(this.getters,n,t);r&&!T(n,r)&&this.history.update(`pivots`,e,`definition`,r)}for(let r in this.compiledMeasureFormulas)for(let i in this.compiledMeasureFormulas[r]){let a=this.pivots[r]?.definition.measures.find(e=>e.id===i);if(!a||!a.computedBy)continue;let o=a.computedBy.sheetId,{formula:s,dependencies:c}=this.compiledMeasureFormulas[r][i],l=e.adaptCompiledFormula(s);l!==s&&this.history.update(`compiledMeasureFormulas`,r,i,`formula`,l),this.history.update(`compiledMeasureFormulas`,r,a.id,`dependencies`,c.map(e=>t(e).range));let u=a.computedBy.formula,d=n(o,u);d!==u&&this.replaceMeasureFormula(r,a,d)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:x(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=Bc.Compile(n.computedBy.formula,n.computedBy.sheetId,this.getters);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.symbols){let a=i.measures.find(e=>tt(e.id)===o&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.rangeDependencies.filter(e=>!e.invalidXc)),r.push(...a.getNamedRangesInFormula(this.getters).map(e=>e.range)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Ag(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return`InvalidPivotCustomField`;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return`Success`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||Cg(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},YI=class extends EI{static getters=[`getLocale`];locale=V;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return Jy(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let r of this.getters.getCells(n)){let n;if(r.format===e.dateFormat&&(n=t.dateFormat),r.format===e.timeFormat&&(n=t.timeFormat),r.format===db(e)&&(n=db(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r.id);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??V}export(e){e.settings={locale:this.locale}}},XI=class extends EI{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCellIds.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName.tryGetCellPosition.isSheetLocked`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;let n=!1;switch(e.type){case`CREATE_SHEET`:e.name===void 0&&(n=!0);break;case`DELETE_SHEET`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`MOVE_RANGES`:e.sheetName===void 0&&(n=!0);break}switch(n&&console.warn(`Deprecation Warning: Sheet name is missing in the command %s payload.`,e.type),e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.createSheetHasName,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||Pr(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Ht(e.elements),n=Vt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,Sc(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`LOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!0);break;case`UNLOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!1);break}}import(e){for(let t of e.sheets)this.sheetIdsMapName[Sc(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:_c(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color,isLocked:t.isLocked};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(w).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,isLocked:t.isLocked,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}isSheetLocked(e){return this.tryGetSheet(e)?.isLocked||!1}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[Sc(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCellIds(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(w)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}tryGetCellPosition(e){return this.cellPosition[e]}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return bc(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Et(n,C(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Sn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>In(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:_c(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0},isLocked:!1},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}createSheetHasName(e){return e.name!==void 0&&!e.name.trim()?`MissingSheetName`:`Success`}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>Cc(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Fe.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[Sc(n)],r[Sc(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=x(this.getSheet(e));r.id=t,r.name=n,r.isLocked=!1;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.isFormula?t.compiledFormula.toFormulaString(this.getters):t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[Sc(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return xc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[Sc(t)],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of rt(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(yn),n=e.rowNumber,r=e.colNumber;for(let{right:e,bottom:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return mu(e)&&e.ranges.length===0?`EmptyRange`:`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:pu(e)&&e.target.length===0?`EmptyTarget`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},ZI=class extends EI{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!Sn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},QI=class extends EI{static getters=[`getNewCustomTableStyleName`,`getTableStyle`,`getTableStyles`,`isTableStyleEditable`];styles={};allowDispatch(e){switch(e.type){case`CREATE_TABLE`:case`UPDATE_TABLE`:if(e.config?.styleId&&!this.styles[e.config.styleId])return`InvalidTableConfig`;break;case`CREATE_TABLE_STYLE`:if(!oC[e.templateName])return`InvalidTableStyle`;try{Nr(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=sC(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:WS.styleId}});break}}getTableStyle(e){if(xM[e])return xM[e];if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Kt(j(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!aC[e]&&!xM[e]}import(e){for(let e in aC)this.styles[e]=aC[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=sC(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)aC[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},$I=class extends EI{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e}){for(let t in this.tables)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return er(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(Nn(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||WS,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!jn(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>In(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(w):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e||this.isPivotFormula(e,t))return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e},i=this.getters.getCell(r);if(i?.isFormula||i?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[D(r)]).length)return`none`}return o}isPivotFormula(e,t){return e.startsWith(`=`)?Qj(Bc.Compile(e,t,this.getters),this.getters)?.functionName===`PIVOT`:!1}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of C(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=qn(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of C(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,qn(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return kM(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return kM(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:x(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:x(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=kM(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<Ln(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||WS,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:wn(e.range.zone),type:e.type};T(e.config,WS)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=wn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},eL=class extends TI{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let tL=Io.mapping;function nL(e,t,n){return new rL(e,t,n).getParameters()}var rL=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(tL),e,{getters:this.getters,locale:this.getters.getLocale(),getFormulaResult:this.getFormulaResult.bind(this)})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e){let t=this.getRangeError(e);if(t)return t;let n={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top},r=this.computeCell(n);return r.position?r:{...r,position:n}}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=jn(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.getFormulaResult({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getFormulaResult(e){let t=this.computeCell(e);return t.position?t:{...t,position:e}}getRangeError(e){if(!Sn(e.zone))return new Li;if(e.invalidSheetName)return new Li(j(`Invalid sheet name: %s`,e.invalidSheetName))}},iL=class{interval;left;right;max;constructor(e,t=null,n=null){this.interval=e,this.left=t,this.right=n,this.max=e.bottom}},aL=class{root=null;buffer=[];insert(e){this.buffer.push(e)}query(e){this.buffer.length&&this.rebuild();let t=[];return this.searchTree(this.root,e,t),t}rebuild(){let e=[];this.inOrderTraversal(this.root,e);let t=this.buffer.sort(oL),n=this.mergeSortedIntervals(e,t);this.bulkLoad(n),this.buffer=[]}compactSortedIntervals(e){let t=e[0],n=[];for(let r=1;r<e.length;r++){let i=e[r];if(i.top===t.top&&i.bottom===t.bottom&&i.dependents.zone.left===t.dependents.zone.left&&i.dependents.zone.right===t.dependents.zone.right&&i.dependents.sheetId===t.dependents.sheetId)if(i.dependents.zone.top-1===t.dependents.zone.bottom)t.dependents.zone.bottom=i.dependents.zone.bottom;else if(i.dependents.zone.top===t.dependents.zone.top&&i.dependents.zone.bottom===t.dependents.zone.bottom)continue;else n.push(t),t=i;else n.push(t),t=i}return n.push(t),n}mergeSortedIntervals(e,t){let n=[],r=0,i=0;for(;r<e.length&&i<t.length;)oL(e[r],t[i])<=0?n.push(e[r++]):n.push(t[i++]);return n.concat(r<e.length?e.slice(r):t.slice(i))}bulkLoad(e){let t=this.compactSortedIntervals(e);this.root=this.buildBalancedTree(t)}buildBalancedTree(e,t=0,n=e.length){if(t>=n)return null;let r=t+(n-t>>1),i=new iL(e[r]);return i.left=this.buildBalancedTree(e,t,r),i.right=this.buildBalancedTree(e,r+1,n),i.max=Math.max(i.interval.bottom,i.left?i.left.max:-1,i.right?i.right.max:-1),i}searchTree(e,t,n){!e||t.top>e.max||(this.isOverlapping(e.interval,t)&&n.push(e.interval),e.left&&e.left.max>=t.top&&this.searchTree(e.left,t,n),e.right&&t.bottom>=e.interval.top&&this.searchTree(e.right,t,n))}inOrderTraversal(e,t){e&&(this.inOrderTraversal(e.left,t),t.push(e.interval),this.inOrderTraversal(e.right,t))}isOverlapping(e,t){return e.top<=t.bottom&&e.bottom>=t.top}};function oL(e,t){if(e.top!==t.top)return e.top-t.top;if(e.bottom!==t.bottom)return e.bottom-t.bottom;let{zone:n,sheetId:r}=e.dependents,{zone:i,sheetId:a}=t.dependents;return r===a?n.left-i.left||n.right-i.right||n.top-i.top||n.bottom-i.bottom:r>a?1:-1}var sL=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){ln(this.profilesStartingPosition,this.profiles,[e])}delete(e){ln(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return un(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return mn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},cL=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new sL),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(sc(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(sc(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(sc(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},lL=class{forest={};removeAllDependencies(e){}addDependencies(e,t){let n={zone:D(e),sheetId:e.sheetId};for(let e of t){if(e.invalidSheetName||e.invalidXc)continue;let{zone:t,sheetId:r}=e;for(let e=t.left;e<=t.right;e++)this.getOrCreateIntervalTree(r,e).insert({top:t.top,bottom:t.bottom,dependents:n})}}getCellsDependingOn(e,t=new cL){t=t.copy();let n=Array.from(e).reverse();for(;n.length>0;){let e=n.pop();t.add(e);let r=e.zone,i=this.forest[e.sheetId];if(!i)continue;let a=new cL;for(let e=r.left;e<=r.right;e++){let t=i[e];if(!t)continue;let n=t.query(r);for(let e of n)a.add(e.dependents)}n.push(...a.difference(t))}for(let n of e)t.delete(n);return t}getOrCreateIntervalTree(e,t){let n=this.forest[e]?.[t];return n||(this.forest[e]||(this.forest[e]={}),n=new aL,this.forest[e][t]=n),n}},uL=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=dL(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function dL(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var fL=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=uL.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},pL=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),mL=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new hL,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new hL),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&T(e.data,t.data)}},hL=class extends pL.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},gL=class{resultsToArrayFormulas=new mL;arrayFormulasToResults=new aN;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||_L}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let _L=[],vL=new A;vL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let yL=Object.freeze(Gu({value:null}));var bL=class{context;getters;compilationParams;evaluatedCells=new aN;formulaDependencies=xt(new lL);blockedArrayFormulas=new fL({});spreadingRelations=new gL;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=nL(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||yL}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===M.SpilledBlocked)?D(e):kn(D(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==`empty`)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,D(e)).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t),this.computeDependencies(t)}computeDependencies(e){for(let t of e)this.compilationParams.ensureRange(t)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=nL(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=nL(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new fL(e)}evaluateCells(e){let t=performance.now(),n=new cL;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new cL;for(let n of e){let e=this.getters.getCell(n),r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),!e?.isFormula&&!e?.content&&t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new gL,this.formulaDependencies=xt(()=>{let e=new lL;for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t))if(n.isFormula){let t=this.getters.getCellPosition(n.id);e.addDependencies(t,n.compiledFormula.rangeDependencies)}return e})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new aN;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=Bc.Compile(t,e,this.getters);return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,r)}evaluateCompiledFormula(e,t,n){try{let r=wL(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Je(r)?lo(r,SL):SL(r)}catch(e){return Ao(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new cL,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new cL;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new cL(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);(r.value!==null||r.format!==void 0)&&this.evaluatedCells.set(n,r)}}vL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return{...yL,position:e};let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?TL(e):(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):zu(n,i,e))}catch(t){return t.value=t?.value||M.GenericError,t.message=t?.message||No,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,Gu(t,i.locale,e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=wL(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Je(n)){let r=Gu(CL(n),this.getters.getLocale(),e,t);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return Gu({value:0},this.getters.getLocale(),e,t);if(i===1&&r===1)return Gu(CL(n[0][0]),this.getters.getLocale(),e,t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),xL(r,i,this.checkCollision(e)),xL(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),Gu(CL(n[0][0]),this.getters.getLocale(),e,t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(zn(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw new Bi(j(`Result couldn't be automatically expanded.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Bi(j(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r},s=this.getters.getCell(o);if(s?.isFormula||s?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new Bi(j(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=Gu(CL(r[i][a]),this.getters.getLocale(),o,s);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r},i=this.getters.getCell(t);i?.isFormula||i?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return(t,n)=>{if(this.symbolsBeingComputed.has(t))return TL(this.compilationParams.evalContext.__originCellPosition);this.symbolsBeingComputed.add(t);try{let r=this.getters.getNamedRange(t);if(r){let e=this.compilationParams.evalContext;return e.__originCellPosition?this.addDependencies(e.__originCellPosition,[r.range]):this.computeDependencies([r.range]),Xn(r.range.zone)>1||n?this.compilationParams.ensureRange(r.range):this.compilationParams.referenceDenormalizer(r.range)}return e?.(t,n)||new Fi(j(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.rangeDependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function xL(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function SL(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function CL(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new Hi:SL(e)}function wL(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.rangeDependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}function TL(e){return Gu({...new Ii,origin:void 0},void 0,e)}var EL=class extends eL{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getVisibleRangeValues`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new bL(e.custom,this.getters)}beforeHandle(e){(_u.has(e.type)||yu.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Je(r)?lo(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getVisibleRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e))}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return Bn(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Bn(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Bn(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=E(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=l.compiledFormula.areAllFunctionsExportableToExcel(),a=s&&(u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content)===l.compiledFormula.toFormulaString(this.getters),!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=cd(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l?.isFormula?l.compiledFormula.toFormulaString(this.getters,{useBoundedReference:!0}):s?u:o,c.cells[r]=d,c.cellValues[r]=i===M.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let DL=new A;DL.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?Ab:Ob,hoverSvg:n?Ab:kb,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),DL.add(`data_validation_list_chip_icon`,(e,t)=>{if(e.isReadonly())return;let n=e.getDataValidationChipStyle(t);if(!e.cellHasListDataValidationIcon(t)&&!n)return;let r=e.getCellComputedStyle(t),i=n||r;return{svg:Tb(i),hoverSvg:Db(i),priority:2,horizontalAlign:`right`,size:kd(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_chip_icon`}}),DL.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:Nb[n].svg,priority:1,horizontalAlign:`left`,size:kd(r),margin:4,position:t}}}),DL.add(`pivot_collapse`,(e,t)=>{let n=e.getPivotIdFromPosition(t);if(!e.isSpillPivotFormula(t)||!n)return;let r=e.getPivotCellFromPosition(t),i=e.getPivotCoreDefinition(n);if(!(i.style?.tabularForm??_g.tabularForm)&&r.type===`HEADER`&&n&&r.domain.length){let n=e.isDashboard(),a=r.dimension===`COL`?i.columns:i.rows,o=!n&&!e.shouldShowFormulas()&&r.domain.length!==a.length,s=(i.collapsedDomains?.[r.dimension]??[]).some(e=>T(e,r.domain)),c=r.dimension===`ROW`?(r.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:o||!n&&r.dimension===`ROW`&&i.rows.length>1?12:0,margin:o?4+c:c,svg:o?jb(s,!1):void 0,hoverSvg:o?jb(s,!0):void 0,position:t,onClick:Kg}}}),DL.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:kd(r),margin:0,svg:n===`asc`?Eb(r):Tb(r),position:t,onClick:void 0}});var OL=class extends eL{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=DL.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(w)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}};let kL=/"(#[0-9a-fA-F]{6})"/g;function AL(e){let t=[{leadColor:Lr(255,0,0),colors:[]},{leadColor:Lr(255,128,0),colors:[]},{leadColor:Lr(128,128,0),colors:[]},{leadColor:Lr(128,255,0),colors:[]},{leadColor:Lr(0,255,0),colors:[]},{leadColor:Lr(0,255,128),colors:[]},{leadColor:Lr(0,255,255),colors:[]},{leadColor:Lr(0,127,255),colors:[]},{leadColor:Lr(0,0,255),colors:[]},{leadColor:Lr(127,0,255),colors:[]},{leadColor:Lr(128,0,128),colors:[]},{leadColor:Lr(255,0,128),colors:[]}];for(let n of e.map(Vr)){let e=500,r=0;t.forEach((t,i)=>{let a=jL(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Ur(e).s-Ur(t).s)).flat().map(Br)}function jL(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var ML=class extends eL{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds()){for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));for(let t of this.getters.getFigures(e))this.tryToAddColors(this.getCarouselColors(e,t.id))}break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.chartId));break;case`CREATE_CAROUSEL`:case`UPDATE_CAROUSEL`:this.tryToAddColors(this.getCarouselColors(e.sheetId,e.figureId));break;case`COLOR_SHEET`:e.color&&this.tryToAddColors([e.color]);break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return AL(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getSheetColors(t),this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getSheetColors(e){let t=this.getters.getSheet(e);return t.color?[t.color]:[]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(jr(t.minimum.color)),n.push(t.midpoint?jr(t.midpoint.color):void 0),n.push(jr(t.maximum.color)))}return n.filter(w)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getRangeDefinition()).matchAll(kL)].map(e=>e[1])}getCarouselColors(e,t){if(this.getters.getFigure(e,t)?.tag!==`carousel`)return[];let n=this.getters.getCarousel(t).title?.color;return n?[n]:[]}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(w):[]}tryToAddColors(e){for(let t of e){if(!Pr(t))continue;let e=Nr(t);t&&!ye.includes(e)&&this.history.update(`customColors`,e,!0)}}},NL=class extends eL{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(_u.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:case`REFRESH_PIVOT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=[...this.getters.getCoreTables(e)].filter(e=>e.type!==`dynamic`);t.push(...n);for(let r of this.getDynamicTables(e)){let i=this.coreTableToTable(e,r),a=i.range.zone,o=a.left,s=a.top;if(!n.some(e=>Fn(o,s,e.range.zone))){for(let e of n){let t=e.range.zone;Nn(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...i,range:this.getters.getRangeFromZone(e,a)})}}return t}getDynamicTables(e){let t=this.getters.getCoreTables(e).filter(e=>e.type===`dynamic`),n=this.getTablesFromPivots(e),r=new Set(n.map(t=>this.getters.getRangeString(t.range,e))),i=t.filter(t=>!r.has(this.getters.getRangeString(t.range,e)));return[...n,...i]}getTablesFromPivots(e){let t=[];for(let{position:n,pivotStyle:r,pivotId:i}of this.getters.getAllPivotArrayFormulas()){if(!this.getters.getPivot(i).isValid())continue;let a=this.getters.getSpreadZone(n),o=this.getters.getCell(n);n.sheetId!==e||!a||!o||r.tableStyleId===`None`||t.push({type:`dynamic`,id:`pivot_table_`+i+`_`+o.id,range:this.getters.getRangeFromZone(e,D(n)),config:this.getTableConfigFromPivotStyle(i,r),isPivotTable:!0})}return t}getTableConfigFromPivotStyle(e,t){let n=this.getters.getPivot(e).getCollapsedTableStructure(),{numberOfRows:r,numberOfHeaderRows:i}=n.getPivotTableDimensions(t),a=n.getPivotCells(t)[0]?.[r-1],o=t.displayTotals&&a?.type===`HEADER`&&a.domain.length===0;return{hasFilters:t.hasFilters,totalRow:o,firstColumn:!0,lastColumn:!0,numberOfHeaders:i,bandedRows:t.bandedRows,bandedColumns:t.bandedColumns,styleId:t.tableStyleId}}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!er(t))return!1;let n=kn(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===M.SpilledBlocked&&!e.errorOriginPosition}else if(T(i,r)&&Xn(n)===1)return!0;return T(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config,isPivotTable:t.isPivotTable}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=kM(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Bn(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=yn(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Bn(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=E(n.col,n.row);if(!gt(i)){let n=cd(i,e.styles);t.styles[o]=n}if(a){let n=cd(a,e.borders);t.borders[o]=n}}}t.tables=n}}};function PL(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!If(e.xAxisID)).map(e=>({...e,pointRadius:e.showLine===!1?2:0}))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return Ff(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}var FL=class extends eL{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};handle(e){if(_u.has(e.type)||bu.has(e.type)||vu.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(e,t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:wf(e)};if(!t)return{background:oe,fontColor:wf(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||wf(o)}}async exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=await ch(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}createRuntimeChart(e,t){let n=t.getRangeDefinition(),r=t.getRuntime(this.getters,e);if(`chartJsConfig`in r&&/line|combo|bar|scatter|waterfall/.test(n.type)){let e=r.chartJsConfig;r.masterChartConfig=PL(e)}return r}},IL=class extends eL{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(_u.has(e.type)||bu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=xt(()=>this.getComputedStyles(e)),this.computedIcons[e]=xt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=xt(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]?.();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]?.();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]?.();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(t=>{if(t.startsWith(`=`))return Bc.Compile(t,e,this.getters)}),i=X.get(n.rule.operator),a={...n.rule,type:n.rule.operator},o=n.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t)),s=i.preComputeCriterion?.(a,o,this.getters);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s):t});this.getRuleResultForTarget(c,{...n.rule,values:l},s)&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Vt(a):Ht(a);case`number`:return Number(n.value);case`percentage`:let t=Ht(a);return t+(Vt(a)-t)*Number(n.value)/100;case`percentile`:return La(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Vt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!Fn(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:jr(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a!==null&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a!==null&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=hi(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=S(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t,n){let r=this.getters.getEvaluatedCell(e);if(r.type===`error`)return!1;let{sheetId:i}=e,a=X.get(t.operator),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(i,t,e)??``:Wu(t,V));if(o.some(Eh))return!1;let s={...t,type:t.operator,values:o.map(wh),dateValue:t.dateValue||`exactDate`};return a.isValueValid(r.value??``,s,n)}};let LL={isValid:!0};var RL=class extends eL{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};criterionPreComputeResult={};handle(e){if(_u.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={},this.criterionPreComputeResult={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId],delete this.criterionPreComputeResult[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=X.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?j(`The value must not be a formula`):this.isValidFormula(t)?void 0:Wy.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?j(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Bn(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return LL;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:LL}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Qr(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!Bc.IsBadExpression(e)}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||LL}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of ac(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=xt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?LL:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=X.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(Eh))return;let c={...i,values:s.map(wh)};this.criterionPreComputeResult[r]||(this.criterionPreComputeResult[r]={});let l=this.criterionPreComputeResult[r][n.id];if(l===void 0&&(l=a.preComputeCriterion?.(n.criterion,n.ranges,this.getters),this.criterionPreComputeResult[r][n.id]=l),!a.isValueValid(e,c,l))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>Fn(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n,r){return r.values.map(r=>{if(!r.startsWith(`=`))return Wu(r,V);let i=Bc.Compile(r,e,this.getters),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i);return this.getters.evaluateFormula(e,a,t)})}};let zL=[`SUBTOTAL`,`PIVOT`];var BL=class extends eL{static getters=[`getCellsWithTrackedFormula`];trackedCells={};handle(e){switch(e.type){case`START`:for(let e of zL)this.trackedCells[e]={};for(let e of this.getters.getSheetIds())for(let t of this.getters.getCells(e))for(let e of zL)Yt(t,e)&&this.history.update(`trackedCells`,e,t.id,t.id);break;case`UPDATE_CELL`:{if(!(`content`in e))return;let t=this.getters.getCell(e);if(!t)return;for(let e of zL)Yt(t,e)?this.history.update(`trackedCells`,e,t.id,t.id):this.trackedCells[e][t.id]&&this.history.update(`trackedCells`,e,t.id,void 0);break}}}getCellsWithTrackedFormula(e){return Object.values(this.trackedCells[e]||{}).filter(t=>t!==void 0&&this.trackedCells[e][t]&&this.getters.tryGetCellPosition(t))}},VL=class extends eL{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=_d();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ct(e.position,e.base),n=Array(e.quantity).fill(void 0),r=It(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=x(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=Ft(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of C(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`SET_FORMATTING`:if(e.style&&(`fontSize`in e.style||`wrapping`in e.style||`rotation`in e.style))for(let t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Bn(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForZoneChange(e,t){for(let n=t.top;n<=t.bottom;n++){let t=this.getRowTallestCell(e,n);this.history.update(`tallestCellInRow`,e,n,t)}}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return vd(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCellIds(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let HL=`0.00%`;function UL(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=Sg[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return Ao(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=vj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=vj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Je(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=vj(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=jg(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:M.NotAvailable,message:j(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return Ao(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:HL}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:HL}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:HL}}asPercentOfParentRowTotal(e,t,n){let r=gj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:HL}}asPercentOfParentColumnTotal(e,t,n){let r=_j(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:HL}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!Ej(i,n))return{value:``};let a=wj(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:HL}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:M.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=vj(this,n),u=kj(l),d=kj(c),f=s[u]?.[d];return f===void 0&&(f=this.getPreviousRunningTotalValue(a,n,s)),{value:f??``,format:i===`running_total`?e.format:HL}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Ej(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:M.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:HL}:s===void 0?{value:M.NullError}:{value:s/o,format:HL}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Ej(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Ej(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:M.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:M.NullError}:{value:(s-o)/o,format:HL}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!Ej(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=vj(this,n),u=kj(l),d=kj(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=Dj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=fo(o));for(let s of o){let o=kj(yj(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:yj(this,i,t.domain)})).filter(e=>Ej(t,e.rowDomain)),l=Object.groupBy(c,e=>jj(e.rowDomain,t));for(let e in l)l[e]=Wt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=kj(yj(this,i,e.domain)),a=l[jj(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Gt(r)}computeRunningTotal(e,t,n){let r={},i=Dj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=fo(o));for(let s of o){let o=kj(yj(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:yj(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>Ej(t,e.rowDomain));for(let e of l){let n=kj(e.rowDomain),i=Mj(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=kj(n),a=Mj(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Gt(r)}getPreviousRunningTotalValue(e,t,n){let r=this.definition.getDimension(e);if(r.type!==`date`&&r.type!==`datetime`)return;let i=Dj(this,e),{rowDomain:a,colDomain:o}=vj(this,t),s=i===`row`?a:o,c=i===`row`?o:a,l=s.find(t=>t.field===e)?.value;if(l===void 0)return;let u=kj(c),d=Mj(s,e),f,p,m=this.getCollapsedTableStructure(),h=i===`row`?m.getRowTree():m.getColTree(),g=(t,n=[])=>{for(let i of t){let t=[...n,{field:i.field,value:i.value,type:i.type}];i.children.length&&g(i.children,t);let a=t.find(t=>t.field===e)?.value,o=Mj(t,e);a===void 0||o!==d||this.compareRunningTotalValues(a,l,r)>=0||(p===void 0||this.compareRunningTotalValues(p,a,r)<0)&&(p=a,f=kj(t))}};if(g(h),f)return i===`row`?n[u]?.[f]:n[f]?.[u]}compareRunningTotalValues(e,t,n){let r=n.order??`asc`,i=e===null,a=t===null;if(i&&a)return 0;if(i)return r===`asc`?1:-1;if(a)return r===`asc`?-1:1;let o=this.getRunningTotalComparableValue(e,n)-this.getRunningTotalComparableValue(t,n);return r===`asc`?o:-o}getRunningTotalComparableValue(e,t){let n=t.granularity;if(n&&rg.contains(n)){let t=ig(n).toComparableValue?.(e);if(t!==void 0)return t}return I(e,V)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=vj(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=vj(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?Oj(this,t,n,r):Tj(t,n,r);if(T(i,t))return`sameValue`;if(!i||!xj(this,i))throw new Ri;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;zg(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let WL=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function GL(e){return WL.includes(e.type)}var KL=class extends eL{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`,`getAllPivotArrayFormulas`,`getPivotStyleAtPosition`];pivots={};unusedPivotsInFormulas;custom;pivotPositionCache=new aN;shouldInvalidateCache=!1;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(_u.has(e.type)){this.shouldInvalidateCache=!0;for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0})}switch(e.type===`UPDATE_CELL`&&(this.shouldInvalidateCache=!0),e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.unusedPivotsInFormulas?.push(e.pivotId),this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.unusedPivotsInFormulas?.push(e.newPivotId),this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivotsInFormulas=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivotsInFormulas=void 0;let t=e.commands.filter(GL);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:$g();break}}finalize(){this.shouldInvalidateCache&&=(this.pivotPositionCache=new aN,!1)}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){if(!this.pivotPositionCache.has(e)){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula);this.pivotPositionCache.set(e,n)}}return this.pivotPositionCache.get(e)||[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(w)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=$j(t,this.getters);if(!n.length)return[];let r=[];for(let t of n){let{functionName:n,args:i}=t,a=i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=TF(t);return this.getters.evaluateFormula(e,n)});r.push({functionName:n,args:a})}return r}getFirstPivotFunction(e,t){return this.getPivotFunctions(e,t)[0]}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||eM(t.compiledFormula,this.getters)===0)return Ij;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!r)return Ij;let{functionName:i,args:a}=r,o=a[0];if(!o)return Ij;let s=this.getters.getPivotId(o.toString());if(!s)return Ij;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!this.isMainFunctionPivotSpreadFunction(t))return Ij;try{if(i===`PIVOT`){let t=qg(this.getters.getPivotCoreDefinition(s),wh(a[1]),wh(a[2]),wh(a[3]),wh(a[4]),wh(a[5]),this.getters.getLocale()),r=c.getCollapsedTableStructure().getPivotCells(t),i=e.col-n.col,o=e.row-n.row;return r[i][o]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Je(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:vj(c,e).colDomain.length?`COL`:`ROW`}}let[o,...l]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(l.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return Ij}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return Kt(j(`Calculated measure 1`),t,{compute:(e,t)=>j(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){let{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&qj.get(t).isPivotUnused(this.getters,e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||n.type===`ROW_GROUP_NAME`||!t)return;let r=this.getters.getPivot(t),i=vj(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&T(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=x(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=UL(qj.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(this.unusedPivotsInFormulas!==void 0)return this.unusedPivotsInFormulas;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t)){let t=this.getters.getCellPosition(n.id),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivotCoreDefinition(t);for(let r of n.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}getAllPivotArrayFormulas(){let e=[];for(let t of this.getters.getCellsWithTrackedFormula(`PIVOT`)){let n=this.getters.getCellPosition(t);if(this.getters.getEvaluatedCell(n).type===`error`)continue;let r=this.getPivotStyleAtPosition(n);r&&e.push({position:n,...r})}return e}getPivotStyleAtPosition(e){e=this.getters.getArrayFormulaSpreadingOn(e)||e;let t=this.getters.getCell(e);if(!t||!t.isFormula||!this.isMainFunctionPivotSpreadFunction(t))return;let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!n||n.functionName!==`PIVOT`)return;let r=n.args[0];if(!r)return;let i=this.getters.getPivotId(r.toString());if(i)return{pivotStyle:qg(this.getters.getPivotCoreDefinition(i),wh(n.args[1]),wh(n.args[2]),wh(n.args[3]),wh(n.args[4]),wh(n.args[5]),this.getters.getLocale()),pivotId:i}}isMainFunctionPivotSpreadFunction(e){return e.compiledFormula.isFirstNonWhitespaceSymbol(`PIVOT`)}},qL=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},JL=class extends qL{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of ZT(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},YL=class extends JL{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t,n=`copyPaste`){let r=e.sheetId,{clippedZones:i,rowsIndexes:a,columnsIndexes:o}=e,s=[],c=a.length===1&&o.length===1;for(let t of a){let i=[];for(let s of o){let l={col:s,row:t,sheetId:r},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(n!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!T(p,l)||!c)&&t&&!e.zones.some(e=>In(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=Ag(this.getters.getPivotFormulaId(f),e);u={id:u?.id??0,style:u?.style,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(n!==`shiftCells`&&p&&!T(p,l)){let e=a.includes(p.row)&&o.includes(p.col)?``:H(d.value,{locale:this.getters.getLocale()});u={id:u?.id??0,style:u?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content??``,style:u?.style,format:u?.format,compiledFormula:u?.isFormula?u?.compiledFormula:void 0,border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}s.push(i)}return{cells:s,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of ZT(t,n.cells))if(this.getters.doesIntersectMerge(e,r)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*a!==1))return`WillRemoveExistingMerge`;return`Success`}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.cells,n)}getPasteTarget(e,t,n,r){let i=n.cells[0].length,a=n.cells.length;return r?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+a-1}]}:i===1&&a===1?{zones:[],sheetId:e}:{sheetId:e,zones:ZT(t,n.cells)}}pasteFromCut(e,t,n,r){this.clearClippedZones(n);let i=t[0];this.pasteZone(e,i.left,i.top,n.cells,r)}clearClippedZones(e){this.dispatch(`CLEAR_CELLS`,{sheetId:e.sheetId,target:e.zones}),this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){if(!s)continue;let o={col:t+r,row:n+a,sheetId:e};this.pasteCell(s,o,i)}}pasteCell(e,t,n){let{sheetId:r,col:i,row:a}=t,o=this.getters.getEvaluatedCell(t),s=e?.format||e.evaluatedCell.format;if(n?.pasteOption===`asValue`){this.dispatch(`UPDATE_CELL`,{...t,content:e.evaluatedCell.value?.toString()||``});return}if(n?.pasteOption===`onlyFormat`){this.dispatch(`UPDATE_CELL`,{...t,style:e?.style??null,format:s??o.format});return}let c=e?.content;e?.compiledFormula?.hasDependencies&&!n?.isCutOperation?c=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.compiledFormula):e?.compiledFormula?.hasDependencies&&(c=this.getters.getFormulaMovedInSheet(r,e.compiledFormula)),c!==``||e?.format||e?.style?this.dispatch(`UPDATE_CELL`,{...t,content:c,style:e?.style||null,format:e?.format}):o&&this.dispatch(`CLEAR_CELL`,t)}convertTextToClipboardData(e){let t=this.getters.getLocale(),n={cells:[]},r=[],i=0;for(let[t,n]of e.replace(/\r/g,``).split(`
|
|
114
|
+
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){let{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{y:e}=this.env.model.getters.getMainViewportRect(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`${t}px`,bottom:Am()?`${t}px`:`0`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},_I=class extends t.Component{static template=`o-spreadsheet-Selection`;static props={};static components={Highlight:fI};get highlightProps(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:ae}}},vI=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=nF(this.env);setup(){hk(this)}get containerStyle(){let e=this.props.table.range.zone,t=this.props.table.range.sheetId;if(this.env.model.getters.isReadonly()||this.env.model.getters.isSheetLocked(t))return W({display:`none`});let n={...e,left:e.right,top:e.bottom},r=this.env.model.getters.getVisibleRect(n);return r.height===0||r.width===0?W({display:`none`}):W({top:`${r.y+r.height-6}px`,left:`${r.x+r.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`;let r=Rm(this.env,e);this.dragNDropGrid.start(r,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let t=this.props.table.range.sheetId;this.env.model.dispatch(`RESIZE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:`#777`,noFill:!0}]:[]}};let yI={ROW:$P,COL:KP,CELL:NP,GROUP_HEADERS:ZP,UNGROUP_HEADERS:QP};var bI=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:jF,GridOverlay:YF,GridPopover:XF,HeadersOverlay:nI,MenuPopover:Oy,Autofill:iF,ClientTag:oF,Highlight:fI,Popover:wy,VerticalScrollBar:gI,HorizontalScrollBar:hI,TableResizer:vI,Selection:_I};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=nF(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=O(fT),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=O(Iy),this.composerFocusStore=O(Er),this.DOMFocusableElementStore=O(py),this.sidePanel=O(rN),this.paintFormatStore=O(GF),this.clientFocusStore=O(tF),O(eF),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),iI({refName:`canvas`,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState()})}),this.onMouseWheel=cI((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=O(Sw),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),oI(this.gridRef,{updateScroll:this.moveCanvas.bind(this),canMoveUp:()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},canMoveDown:()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e},getZoom:()=>this.env.model.getters.getViewportZoomLevel(),setZoom:e=>this.env.model.dispatch(`SET_ZOOM`,{zoom:e})})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){let e=this.env.model.getters.getScrollBarWidth();return W({top:`26px`,left:`48px`,height:`calc(100% - ${26+e}px)`,width:`calc(100% - ${48+e}px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>this.editOrMoveInSelection(`down`),"Shift+Enter":()=>this.editOrMoveInSelection(`up`),Tab:()=>this.moveInSelection(`right`),"Shift+Tab":()=>this.moveInSelection(`left`),F2:()=>{this.focusComposerFromActiveCell()},Delete:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch(`CLEAN_CLIPBOARD_HIGHLIGHT`)},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch(`REQUEST_UNDO`),"Ctrl+Y":()=>this.env.model.dispatch(`REQUEST_REDO`),F4:()=>this.env.model.dispatch(`REQUEST_REDO`),"Ctrl+B":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>GE(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&Lu(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+D":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ABOVE`})},"Ctrl+R":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ON_LEFT`})},"Ctrl+Enter":()=>{gw(this.env,{type:`COPY_PASTE_CELLS_ON_ZONE`})},"Ctrl+H":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+F":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign(`center`),"Ctrl+Shift+L":()=>this.setHorizontalAlign(`left`),"Ctrl+Shift+R":()=>this.setHorizontalAlign(`right`),"Ctrl+Shift+V":()=>bE(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?IE(this.env):i&&!r&&PE(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},"Shift+F11":()=>{RD.execute?.(this.env)},"Alt+T":()=>{TD.execute?.(this.env)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>{this.closeMenu(),JE(this.env)},"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey(`right`),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey(`left`),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey(`up`),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey(`down`)};focusComposerFromActiveCell(){this.env.model.getters.getActiveCell().type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}editOrMoveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.focusComposerFromActiveCell();return}zw(this.env.model.getters,this.env.model.selection,e)}moveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.env.model.selection.moveAnchorCell(e,1);return}zw(this.env.model.getters,this.env.model.selection,e)}isSingleCellOrMergeSelection(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();return this.env.model.getters.isSingleCellOrMerge(e,t)}focusDefaultElement(){!this.env.model.getters.getSelectedFigureId()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{x:t.x+t.width-8/2,y:t.y+t.height-8/2}}get isAutofillVisible(){if(this.env.model.getters.isCurrentSheetLocked())return!1;let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(t.width===0||t.height===0)}onGridResized(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){let e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{..._m(this.gridRef),width:t*e,height:n*e}}onCellClicked(e,t,n,r){if(r.ev.preventDefault(),this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.env.model.selection.commitSelection(),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),Rw(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=Tm(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRectWithZoom(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;Fn(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=yI[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?LN(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files].find(e=>JT.includes(e.type)),r={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation();if(this.env.model.getters.getClipboardId()===$T(r.content[`text/html`]))yw(this.env,i);else{let e=QT(r.content);await bw(this.env,i,e)}a&&await this.env.clipboard.write({"text/plain":``})}clearFormatting(){this.env.model.dispatch(`CLEAR_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`}))}processHeaderGroupingEventOnGrid(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!FN(this.env,`COL`)&&!FN(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:`cellFocus`})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:`contentFocus`})}get staticTables(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(AM)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}get clientsToDisplay(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getClientsToDisplay(e)}};let xI=new A;xI.add(`SPREADSHEET`,!1);var SI=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=O(KF)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position),t=kd(e);return W({height:`${t}px`,width:`${t}px`,color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?Kr(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},CI=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:My};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=Sy();figureRegistry=Py;setup(){this.fullScreenFigureStore=O(fy);let e=O(Gd),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return Py.get(this.figureUI.tag).Component}},wI=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:BT};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(L(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Og(e,i).join(`,`)})`,value:H(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=L(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Og(e,o,a).join(`,`)})`,value:H(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},TI=class{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},EI=class extends TI{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e,t){}adaptRanges(e){}},DI=class extends EI{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>x(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Oe.style,color:e.border.color||Oe.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of rt(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?x(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(w))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&T(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(w);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?C(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!T(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!T(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!T(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!T(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of cn(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of cn(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||T(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of ud(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,yn(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=cd(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=ld(e)}e.borders=t}exportForExcel(e){this.export(e)}},OI=class extends EI{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?`DuplicatedFigureId`:`Success`;case`UPDATE_CAROUSEL`:return this.carousels[e.sheetId]?.[e.figureId]?`Success`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},kI=class{getters;baseFormula;alreadyAppliedNumberOffsets=[];previousStrings=[];baseFormulaWasTransformed=!1;rangeToStringOptions={doNotSimplifyRange:!0};baseNumber=void 0;baseNumberFormat=void 0;constructor(e){this.getters=e}buildResult(e,t,n){let r={};if(e.length&&(r.N=e.join(`|`)),t.length&&(r.S=t),n.length){let e;e=n.some(e=>e.includes(`|`))?n:n.join(`|`),r.R=e}return r}resetBaseTo(e){this.baseFormula=Bc.CopyWithDependenciesAndLiteral(e,e.sheetId,x(e.rangeDependencies),e.literalValues.numbers,e.literalValues.strings),this.alreadyAppliedNumberOffsets=e.literalValues.numbers.map(e=>0),this.previousStrings=e.literalValues.strings.map(e=>e.value),this.baseFormulaWasTransformed=!1,this.baseNumber=void 0}resetBaseFormula(){this.baseFormula&&(this.baseFormula=void 0,this.alreadyAppliedNumberOffsets=[],this.previousStrings=[],this.baseFormulaWasTransformed=!1)}resetBaseNumber(){this.baseNumber=void 0,this.baseNumberFormat=void 0}squish(e,t){if(e.isFormula){if(Lo.getAll().some(t=>e.compiledFormula.usesSymbol(t)))return this.resetBaseFormula(),e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions);let n=[],r=[],i=[];return!this.baseFormula||this.baseFormula.normalizedFormula!==e.compiledFormula.normalizedFormula?(this.resetBaseTo(e.compiledFormula),e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions)):!this.baseFormulaWasTransformed&&T(e.compiledFormula.literalValues,this.baseFormula.literalValues)&&T(e.compiledFormula.rangeDependencies,this.baseFormula.rangeDependencies)?e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions):(n=this.squishNumbers(e.compiledFormula.literalValues.numbers),r=this.squishStrings(e.compiledFormula.literalValues.strings),i=this.squishReferences(e.compiledFormula.rangeDependencies,t),this.baseFormulaWasTransformed=!0,this.buildResult(n,r,i))}if(typeof e.parsedValue==`number`&&e.parsedValue%1==0){this.resetBaseFormula();let t=e.parsedValue;if(this.baseNumber===void 0||e.format!==this.baseNumberFormat)return this.baseNumber=t,this.baseNumberFormat=e.format,e.content;let n=t-this.baseNumber;return n===0?e.content:(this.baseNumber=t,{N:(n>0?`+`:``)+n.toString()})}return this.resetBaseFormula(),this.resetBaseNumber(),e.content}squishCommand(e){if(e.content){let t=Bu(this.getters,-1,e.content,e.format,e.style??void 0,e.sheetId),n=this.squish(t,e.sheetId);return typeof n==`string`?e.content:n}return this.resetBaseFormula(),this.resetBaseNumber(),e.content}squishSheet(e,t){let n=Object.keys(e),r={};for(let i=0;i<n.length;i++){let a=sn(n[i]),o=0;for(o=0;o+i+1<n.length;o++){let t=sn(n[o+i+1]);if(t.col!==a.col||t.row!==a.row+o+1||!T(e[n[o+i+1]],e[n[i]]))break}if(o>0){let t=`${n[i]}:${E(a.col,a.row+o)}`;r[t]=e[n[i]],i+=o}else{let o=this.getters.getCell({sheetId:t,col:a.col,row:a.row});!o?.isFormula&&typeof o?.parsedValue==`number`?r[n[i]]=o.content:r[n[i]]=e[n[i]]}}return r}squishReferences(e,t){if(!this.baseFormula)throw Error(`No previous cell to squish against`);return e.map((e,n)=>this.squishOneReference(e,this.baseFormula.rangeDependencies,n,t))}squishOneReference(e,t,n,r){let i=t[n];if(T(i,e))return`=`;if(i.sheetId!==e.sheetId||i.prefixSheet!==e.prefixSheet||i.invalidSheetName!==e.invalidSheetName||i.invalidXc!==e.invalidXc||i.parts.length!==e.parts.length||i.unboundedZone.bottom===void 0||i.unboundedZone.right===void 0||e.unboundedZone.bottom===void 0||e.unboundedZone.right===void 0)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);for(let a=0;a<e.parts.length;a++)if(i.parts[a].colFixed!==e.parts[a].colFixed||i.parts[a].rowFixed!==e.parts[a].rowFixed)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);let a=e.zone,o=i.zone;if(a.top!==a.bottom||a.left!==a.right||o.top!==o.bottom||o.left!==o.right)return t[n]=x(e),nc(e,r,this.getters.getSheetName,this.rangeToStringOptions);let s=e.zone.left-i.zone.left,c=e.zone.top-i.zone.top;return i.zone=x(e.zone),i.unboundedZone=x(e.unboundedZone),s!==0&&c===0?`${s>0?`+`:`-`}C${Math.abs(s)}`:c!==0&&s===0?`${c>0?`+`:`-`}R${Math.abs(c)}`:nc(e,r,this.getters.getSheetName,this.rangeToStringOptions)}squishNumbers(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=this.baseFormula.literalValues.numbers[n].value,i=e[n].value,a=this.alreadyAppliedNumberOffsets[n]||0,o=i-(r+a);o!==0&&(t[n]=`+`+o.toString(),this.alreadyAppliedNumberOffsets[n]=a+o)}return t}squishStrings(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=e[n].value;r!==this.previousStrings[n]&&(t[n]=r,this.previousStrings[n]=r)}return t}};function AI(e){return[sn(e)]}function*jI(e,t){let n=sn(e),r=sn(t);for(let e=Math.min(n.col,r.col);e<=Math.max(n.col,r.col);e++)for(let t=Math.min(n.row,r.row);t<=Math.max(n.row,r.row);t++)yield{col:e,row:t}}var MI=class{previousFormula;alreadyAppliedNumberOffset=[];previousString=[];alreadyAppliedReferenceOffset=[];previousOffset=void 0;previousNumber=void 0;previousNumberFormat;rebase(){this.previousFormula=void 0,this.alreadyAppliedNumberOffset=[],this.previousString=[],this.alreadyAppliedReferenceOffset=[],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}*unsquishCommands(e,t){let n;for(let r of e){if(r.type!==`UPDATE_CELL`&&r.type!==`SQUISHED_UPDATE_CELL`){yield r;continue}let e=r.content;e==null||e===``?(this.rebase(),n=`NOT_A_FORMULA`):n=this.chooseStrategy(e,n,r.sheetId,t);let i;if(r.type===`SQUISHED_UPDATE_CELL`&&`targetRange`in r){let[e,t]=r.targetRange.split(`:`);i=jI(e,t)}else i=[{row:r.row,col:r.col}];for(let{position:a,compiled:o,content:s}of this.applyStrategy(n,i,e,r.sheetId,t)){let e=o?o.toFormulaString(t):s,n={type:`UPDATE_CELL`,sheetId:r.sheetId,row:a.row,col:a.col};(`content`in r||o)&&(n.content=e),`style`in r&&(n.style=r.style),`format`in r&&(n.format=r.format),yield n}}}*unsquishSheet(e,t,n){let r=Object.keys(e).map(e=>({cartesian:sn(e.split(`:`)[0]),key:e})).sort((e,t)=>e.cartesian.col===t.cartesian.col?e.cartesian.row-t.cartesian.row:e.cartesian.col-t.cartesian.col),i;for(let{key:a}of r){let r=e[a];if(r==null||r===``){this.rebase(),i=void 0;continue}else i=this.chooseStrategy(r,i,t,n);let o=a.split(`:`),s=o.length===1?AI(a):jI(o[0],o[1]);yield*this.applyStrategy(i,s,r,t,n)}}chooseStrategy(e,t,n,r){let i=t;if(typeof e==`string`)if(e.startsWith(`=`)){i=`NEW_FORMULA`;let t=Bc.Compile(e,n,r);this.previousFormula=t,this.alreadyAppliedNumberOffset=t.literalValues.numbers.map(e=>e.value),this.previousString=t.literalValues.strings.map(e=>e.value),this.alreadyAppliedReferenceOffset=[...t.rangeDependencies],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}else{let t=this.parseSquishableLiteral(e,r);t?(i=`NEW_NUMBER`,this.rebase(),this.previousNumber=t.value,this.previousNumberFormat=t.format):(this.rebase(),i=`NOT_A_FORMULA`)}else if(e.N||e.S||e.R){if(!i)throw Error(`Incorrect order of commands, cannot unsquish`);switch(i){case`NEW_FORMULA`:i=`FIRST_OFFSET`;break;case`NEW_NUMBER`:if(e.R||e.S)throw Error(`Invalid squished format: cannot have string or reference offsets for a number`);i=`OFFSET_NUMBER`;break;case`FIRST_OFFSET`:i=`COMBINE_OFFSET`;break;case`COMBINE_OFFSET`:case`OFFSET_NUMBER`:break;default:throw Error(`Cannot unsquish an offset without a preceding base cell: ${i}`)}}return i}*applyStrategy(e,t,n,r,i){let a=n;switch(e){case`NEW_FORMULA`:for(let e of t)yield{position:e,compiled:this.previousFormula};break;case`NOT_A_FORMULA`:for(let e of t)yield{position:e,content:a};break;case`FIRST_OFFSET`:{let e=a;this.previousOffset=e;for(let n of t){let t=this.unsquishFormula(e,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:n,compiled:t};else{let e=t.toFormulaString(i);yield{position:n,compiled:Bc.Compile(e,r,i)}}}break}case`COMBINE_OFFSET`:{if(!this.previousOffset)throw Error(`No previous offset to combine with`);let e=a;this.previousOffset.N=e.N??this.previousOffset.N,this.previousOffset.S=e.S??this.previousOffset.S,this.previousOffset.R=e.R??this.previousOffset.R;for(let e of t){let t=this.unsquishFormula(this.previousOffset,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:e,compiled:t};else{let n=t.toFormulaString(i);yield{position:e,compiled:Bc.Compile(n,r,i)}}}break}case`NEW_NUMBER`:for(let e of t)yield{position:e,content:a};break;case`OFFSET_NUMBER`:{let e=a.N;if(e===void 0||this.previousNumber===void 0)throw Error(`No ${e} provided for OFFSET_NUMBER strategy, previous ${this.previousNumber} for ${r}!${JSON.stringify(a)} `);let n=parseFloat(e),o={format:this.previousNumberFormat,locale:i.getLocale()};for(let e of t)this.previousNumber+=n,yield{position:e,content:H(this.previousNumber,o)};break}}}parseSquishableLiteral(e,t){let n=Vu(t,-1,e,void 0,void 0);if(!(typeof n.parsedValue!=`number`||n.parsedValue%1!=0))return{value:n.parsedValue,format:n.format}}unsquishFormula(e,t,n){if(typeof e==`object`&&this.previousFormula){let r={numbers:[],strings:[],dependencies:[]};if(e.N!==void 0&&e.N.length>0?r.numbers=e.N.split(`|`).map(this.adjustNumbers):r.numbers=this.previousFormula.literalValues.numbers,e.S!==void 0&&e.S.length>0?r.strings=e.S.map(this.adjustStrings):r.strings=this.previousFormula.literalValues.strings,e.R!==void 0&&this.previousFormula){let i;i=typeof e.R==`string`?e.R.split(`|`):e.R,r.dependencies=i.map((e,r)=>{if(e===`=`)return{...this.alreadyAppliedReferenceOffset[r]};if(e.startsWith(`+`)||e.startsWith(`-`)){let t=parseInt(e.slice(2),10),n=e[0]===`+`?1:-1;if(e[1]===`R`){let e=this.alreadyAppliedReferenceOffset[r].zone.top+t*n,i={...this.alreadyAppliedReferenceOffset[r]};return i.zone=i.unboundedZone={...i.zone,top:e,bottom:e},this.alreadyAppliedReferenceOffset[r]=i,i}else if(e[1]===`C`){let e=this.alreadyAppliedReferenceOffset[r].zone.left+t*n,i=Object.assign({},this.alreadyAppliedReferenceOffset[r]);return i.zone=i.unboundedZone=Object.assign({},i.zone,{left:e,right:e}),this.alreadyAppliedReferenceOffset[r]=i,i}else throw Error(`Invalid reference offset format: ${e}`)}else{let i=n.getRangeFromSheetXC(t,e);return this.alreadyAppliedReferenceOffset[r]=i,i}})}else r.dependencies=this.previousFormula.rangeDependencies;return Bc.CopyWithDependenciesAndLiteral(this.previousFormula,t,r.dependencies,r.numbers,r.strings)}throw Error(`Invalid squished element or no previous cell to unsquish against`)}adjustStrings=(e,t)=>e===`=`?{value:this.previousString[t]}:(this.previousString[t]=e,{value:e});adjustNumbers=(e,t)=>{if(e===`=`)return{value:this.alreadyAppliedNumberOffset[t]};{let n=parseFloat(e.slice(1)),r=(this.alreadyAppliedNumberOffset[t]||0)+n;return this.alreadyAppliedNumberOffset[t]=r,{value:r}}}},NI=class extends EI{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e){for(let t of Object.keys(this.cells))for(let n of Object.values(this.cells[t]||{}))if(n.isFormula){let r=e.adaptCompiledFormula(n.compiledFormula);r!==n.compiledFormula&&this.history.update(`cells`,t,n.id,`compiledFormula`,r)}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;case`SET_FORMATTING`:return this.checkUselessSetFormatting(e);default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:this.setStyleFormat(e.sheetId,e.target,e.style,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}clearFormatting(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=C(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=C(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){let t=performance.now();for(let t of e.sheets){let n=t.id,r=new aN,i=new MI;for(let e of i.unsquishSheet(t.cells,t.id,this.getters))if(e.content||e.compiled){let n={sheetId:t.id,col:e.position.col,row:e.position.row};e.compiled?r.set(n,{compiledFormula:e.compiled}):r.set(n,{content:e.content})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of ud(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style||n?.compiledFormula){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0,n?.compiledFormula);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}console.debug(`cells imported in`,performance.now()-t,`ms`)}export(e,t){let n={},r={};for(let i of e.sheets){let e=new kI(this.getters),a=[],o=[],s={},c=Object.values(this.cells[i.id]||{}).map(e=>this.getters.getCellPosition(e.id)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let l of c){let c=this.getters.getCell(l),u=this.extractCustomStyle(c);if(Object.keys(u).length){let e=cd(u,n);a[e]??=[],a[e].push(l)}if(c.format){let e=cd(c.format,r);o[e]??=[],o[e].push(l)}let d=E(l.col,l.row);c.isFormula?s[d]=t?e.squish(c,i.id):c.compiledFormula.toFormulaString(this.getters):c.content&&(s[d]=t?e.squish(c,i.id):c.content)}i.styles=ld(a),i.formats=ld(o),i.cells=t?e.squishSheet(s,i.id):s}e.styles=n,e.formats=r}importCell(e,t,n,r,i){let a=this.getNextCellId();return i?Uu(a,i,r,n):Bu(this.getters,a,t||``,r,n,e,{avoidAutomaticDateFormat:!0})}exportForExcel(e){this.export(e,!1);let t=[];for(let n in e.formats||[])au(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=!e.isFormula&&Pa(e.content,V)?Ce:xe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return Object.values(this.cells[e]||{})}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){return Bc.CopyWithDependencies(t,e,n).toFormulaString(this.getters,{useBoundedReference:r})}getTranslatedCellFormula(e,t,n,r){r instanceof Bc||(r=Bc.CompileForSerializedFormula(e,r));let i=this.getters.createAdaptedRanges(r.rangeDependencies,t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t){let n=this.getters.removeRangesSheetPrefix(e,t.rangeDependencies);return Bc.CopyWithDependencies(t,e,n).toFormulaString(this.getters)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=E(t.left,t.top,n[0]),i=E(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyleFormat(e,t,n,r){if(!(n===void 0&&r===void 0))for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++){let i=this.getters.getCell({sheetId:e,col:t,row:a});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:a,style:n?{...i?.style,...n}:void 0,format:r})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextCellId(){let e=this.nextId;return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o;o=a?Mt(r?.content):i?.isFormula?i.compiledFormula.toFormulaString(this.getters):i?.content||``;let s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||!i.isFormula&&i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextCellId(),u=Bu(this.getters,l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?Fn(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.isFormula&&!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.isFormula&&t.compiledFormula.toFormulaString(this.getters)===e.content||!t?.isFormula&&t?.content===e.content)&&(!r||T(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}checkUselessSetFormatting(e){let{sheetId:t,target:n}=e,r=`style`in e,i=`format`in e;if(!r&&!i)return`NoChanges`;for(let a of cn(n))for(let n=a.left;n<=a.right;n++)for(let o=a.top;o<=a.bottom;o++){let a={sheetId:t,col:n,row:o},s=this.getters.getCell(a);if(r&&!T(s?.style,e.style)||i&&s?.format!==e.format)return`Success`}return`NoChanges`}},PI=class extends EI{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=CO.fromDefinition(this.getters,n.chart.sheetId,n.chart.updateRanges(e));this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.checkChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkChartDefinition,this.checkChartExists,this.checkChartChanged));case`DELETE_CHART`:return`SubCommandOnly`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetId,e.sheetIdTo);this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l,sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.getRangeDefinition().type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r={...e.data};delete r.chartId;let i=CO.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=CO.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}}}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=CO.fromStrDefinition(this.getters,r,n);this.history.update(`charts`,t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?`DuplicatedChartId`:`Success`}checkChartDefinition(e){return CO.validate(this,e.definition)}checkChartExists(e){return this.isChartDefined(e.chartId)?`Success`:`ChartDoesNotExist`}checkChartChanged(e){return e.figureId===this.charts[e.chartId]?.figureId&&T(this.getChartDefinition(e.chartId),e.definition)?`NoChanges`:`Success`}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?`Success`:`MissingFigureArguments`}};function FI(e){return e===``?NaN:Number(e)}var II=class extends EI{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e){for(let t of Object.keys(this.cfRules))this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)Fn(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(vn));let s=cn(o,r);return cn([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return Gh.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&T(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=X.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(Bc.IsBadExpression(e.value||``))switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&FI(t)>=FI(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&FI(t)>=FI(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&FI(t)>=FI(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&Bc.IsBadExpression(t))return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},LI=class extends EI{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e){for(let t in this.rules)this.adaptDVRanges(t,e);this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=x(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>rc(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=cn(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(!e)continue;let i=this.getters.getCell({sheetId:n,col:r,row:t});if(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!i?.isFormula&&!i?.content){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,E(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(Fn(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=x(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of ac(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...x(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return X.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=X.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=X.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||Bc.IsBadExpression(e):!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},RI=class extends EI{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges(e){for(let t in this.figures)this.adaptRangesOnSheet(e,t)}adaptRangesOnSheet({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=S(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=S(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},zI=class extends EI{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(C(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=x(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ct(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&C(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Nt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=vc(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=yc(n,C(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=Bb(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Bb(t,e,n.end+1);r.collapsed=!0}}}}}},BI=class extends EI{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,x(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ft(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ct(e.position,e.base),r=t[e.base],i=It(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of C(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of C(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},VI=class extends EI{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Ht(e.elements)<0||Vt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,x(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ct(e.position,e.base),n=It([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Et(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=C(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...C(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},HI=class extends EI{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:x(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:x(e)})}t.images=[...t.images,...n]}}},UI=class extends EI{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(w))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e){for(let t in this.merges)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(w)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(w)}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(Nn(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&Nn(n,o)&&(o=kn(n,o))}return Mn(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Mn(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Mn(t,n);let{numberOfCols:r,numberOfRows:i}=Ln(t);return r===1&&i===1}isMainCellPosition(e){return T(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&(n.isFormula||n.content!==``))return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:GI(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&Nn(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return Qn(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Mn(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1),E(n,i)===E(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,wn({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Mn(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=Ln(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Bn(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,yn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...WI(e))}}exportForExcel(e){this.export(e)}};function WI(e){return Object.entries(e).map(([e,t])=>t?GI(parseInt(e,10),t):void 0).filter(w).map(e=>E(e.left,e.top)+`:`+E(e.right,e.bottom))}function GI(e,t){return{...t.zone,id:e}}let KI=/^[\p{L}\p{N}_.]+$/u;var qI=class extends EI{static getters=[`getNamedRange`,`getNamedRangeFromZone`,`getNamedRanges`];namedRanges=[];adaptRanges({applyChange:e}){let t=[],n=!1;for(let r of this.namedRanges){let i=e(r.range);switch(i.changeType){case`REMOVE`:n=!0;break;case`RESIZE`:case`MOVE`:case`CHANGE`:n=!0,t.push({...r,range:i.range});break;case`NONE`:t.push(r)}}n&&this.history.update(`namedRanges`,t)}allowDispatch(e){switch(e.type){case`CREATE_NAMED_RANGE`:return this.checkValidNewNamedRangeName(e.name);case`UPDATE_NAMED_RANGE`:return this.checkValidations(e,()=>this.checkNamedRangeExists(e.oldRangeName),()=>e.newRangeName===e.oldRangeName?`Success`:this.checkValidNewNamedRangeName(e.newRangeName));case`DELETE_NAMED_RANGE`:return this.checkNamedRangeExists(e.name)}return`Success`}handle(e){switch(e.type){case`CREATE_NAMED_RANGE`:{let t=this.getters.getRangeFromRangeData(e.ranges[0]),n=[...this.namedRanges,{name:e.name,range:t}];this.history.update(`namedRanges`,n);break}case`UPDATE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.oldRangeName);if(t!==-1){let n=this.getters.getRangeFromRangeData(e.ranges[0]);this.history.update(`namedRanges`,t,{name:e.newRangeName,range:n})}break}case`DELETE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.name);if(t!==-1){let e=[...this.namedRanges];e.splice(t,1),this.history.update(`namedRanges`,e)}break}}}getNamedRange(e){return this.namedRanges[this.getNamedRangeIndex(e)]}getNamedRangeFromZone(e,t){for(let n of this.namedRanges){let r=n.range;if(r.sheetId===e&&T(r.unboundedZone,t))return n}}getNamedRanges(){return this.namedRanges}getNamedRangeIndex(e){return this.namedRanges.findIndex(t=>t&&t.name.toLowerCase()===e.toLowerCase())}import(e){for(let t in e.namedRanges||{})this.namedRanges.push({name:t,range:this.getters.getRangeFromSheetXC(void 0,e.namedRanges[t])})}export(e){e.namedRanges={};for(let t of this.namedRanges){let n=this.getters.getRangeString(t.range);e.namedRanges[t.name]=n}}checkValidNewNamedRangeName(e){return this.getNamedRange(e)?`NamedRangeNameAlreadyExists`:!KI.test(e)||Pa(e,V)||[`TRUE`,`FALSE`].includes(e.toUpperCase())?`NamedRangeInvalidName`:Go.test(e)?`NamedRangeNameLooksLikeCellReference`:`Success`}checkNamedRangeExists(e){return this.getNamedRange(e)?`Success`:`NamedRangeNotFound`}},JI=class extends EI{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return e.pivotId in this.pivots?`PivotIdTaken`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?T(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new Fj(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=x(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,x(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break;case`CREATE_NAMED_RANGE`:case`UPDATE_NAMED_RANGE`:case`DELETE_NAMED_RANGE`:for(let e in this.pivots){let t=this.pivots[e];t&&this.compileCalculatedMeasures(e,t.definition.measures)}}}adaptRanges(e){let{applyChange:t,adaptFormulaString:n}=e;for(let e in this.pivots){let n=x(this.pivots[e]?.definition);if(!n)continue;let r=qj.get(n.type)?.adaptRanges?.(this.getters,n,t);r&&!T(n,r)&&this.history.update(`pivots`,e,`definition`,r)}for(let r in this.compiledMeasureFormulas)for(let i in this.compiledMeasureFormulas[r]){let a=this.pivots[r]?.definition.measures.find(e=>e.id===i);if(!a||!a.computedBy)continue;let o=a.computedBy.sheetId,{formula:s,dependencies:c}=this.compiledMeasureFormulas[r][i],l=e.adaptCompiledFormula(s);l!==s&&this.history.update(`compiledMeasureFormulas`,r,i,`formula`,l),this.history.update(`compiledMeasureFormulas`,r,a.id,`dependencies`,c.map(e=>t(e).range));let u=a.computedBy.formula,d=n(o,u);d!==u&&this.replaceMeasureFormula(r,a,d)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:x(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=Bc.Compile(n.computedBy.formula,n.computedBy.sheetId,this.getters);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.symbols){let a=i.measures.find(e=>tt(e.id)===o&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.rangeDependencies.filter(e=>!e.invalidXc)),r.push(...a.getNamedRangesInFormula(this.getters).map(e=>e.range)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Ag(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return`InvalidPivotCustomField`;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return`Success`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||Cg(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},YI=class extends EI{static getters=[`getLocale`];locale=V;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return Jy(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let r of this.getters.getCells(n)){let n;if(r.format===e.dateFormat&&(n=t.dateFormat),r.format===e.timeFormat&&(n=t.timeFormat),r.format===db(e)&&(n=db(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r.id);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??V}export(e){e.settings={locale:this.locale}}},XI=class extends EI{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCellIds.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName.tryGetCellPosition.isSheetLocked`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;let n=!1;switch(e.type){case`CREATE_SHEET`:e.name===void 0&&(n=!0);break;case`DELETE_SHEET`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`MOVE_RANGES`:e.sheetName===void 0&&(n=!0);break}switch(n&&console.warn(`Deprecation Warning: Sheet name is missing in the command %s payload.`,e.type),e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.createSheetHasName,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||Pr(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Ht(e.elements),n=Vt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,Sc(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`LOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!0);break;case`UNLOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!1);break}}import(e){for(let t of e.sheets)this.sheetIdsMapName[Sc(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:_c(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color,isLocked:t.isLocked};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(w).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,isLocked:t.isLocked,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}isSheetLocked(e){return this.tryGetSheet(e)?.isLocked||!1}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[Sc(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCellIds(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(w)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}tryGetCellPosition(e){return this.cellPosition[e]}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return bc(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Et(n,C(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Sn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>In(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:_c(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0},isLocked:!1},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}createSheetHasName(e){return e.name!==void 0&&!e.name.trim()?`MissingSheetName`:`Success`}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>Cc(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Fe.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[Sc(n)],r[Sc(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=x(this.getSheet(e));r.id=t,r.name=n,r.isLocked=!1;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.isFormula?t.compiledFormula.toFormulaString(this.getters):t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[Sc(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return xc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[Sc(t)],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of rt(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(yn),n=e.rowNumber,r=e.colNumber;for(let{right:e,bottom:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return mu(e)&&e.ranges.length===0?`EmptyRange`:`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:pu(e)&&e.target.length===0?`EmptyTarget`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},ZI=class extends EI{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!Sn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},QI=class extends EI{static getters=[`getNewCustomTableStyleName`,`getTableStyle`,`getTableStyles`,`isTableStyleEditable`];styles={};allowDispatch(e){switch(e.type){case`CREATE_TABLE`:case`UPDATE_TABLE`:if(e.config?.styleId&&!this.styles[e.config.styleId])return`InvalidTableConfig`;break;case`CREATE_TABLE_STYLE`:if(!oC[e.templateName])return`InvalidTableStyle`;try{Nr(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=sC(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:WS.styleId}});break}}getTableStyle(e){if(xM[e])return xM[e];if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Kt(j(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!aC[e]&&!xM[e]}import(e){for(let e in aC)this.styles[e]=aC[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=sC(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)aC[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},$I=class extends EI{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e}){for(let t in this.tables)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return er(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(Nn(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||WS,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!jn(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>In(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(w):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e||this.isPivotFormula(e,t))return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e},i=this.getters.getCell(r);if(i?.isFormula||i?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[D(r)]).length)return`none`}return o}isPivotFormula(e,t){return e.startsWith(`=`)?Qj(Bc.Compile(e,t,this.getters),this.getters)?.functionName===`PIVOT`:!1}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of C(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=qn(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of C(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,qn(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return kM(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return kM(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:x(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:x(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=kM(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<Ln(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||WS,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:wn(e.range.zone),type:e.type};T(e.config,WS)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=wn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},eL=class extends TI{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let tL=Io.mapping;function nL(e,t,n){return new rL(e,t,n).getParameters()}var rL=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(tL),e,{getters:this.getters,locale:this.getters.getLocale(),getFormulaResult:this.getFormulaResult.bind(this)})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e){let t=this.getRangeError(e);if(t)return t;let n={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top},r=this.computeCell(n);return r.position?r:{...r,position:n}}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=jn(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.getFormulaResult({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getFormulaResult(e){let t=this.computeCell(e);return t.position?t:{...t,position:e}}getRangeError(e){if(!Sn(e.zone))return new Li;if(e.invalidSheetName)return new Li(j(`Invalid sheet name: %s`,e.invalidSheetName))}},iL=class{interval;left;right;max;constructor(e,t=null,n=null){this.interval=e,this.left=t,this.right=n,this.max=e.bottom}},aL=class{root=null;buffer=[];insert(e){this.buffer.push(e)}query(e){this.buffer.length&&this.rebuild();let t=[];return this.searchTree(this.root,e,t),t}rebuild(){let e=[];this.inOrderTraversal(this.root,e);let t=this.buffer.sort(oL),n=this.mergeSortedIntervals(e,t);this.bulkLoad(n),this.buffer=[]}compactSortedIntervals(e){let t=e[0],n=[];for(let r=1;r<e.length;r++){let i=e[r];if(i.top===t.top&&i.bottom===t.bottom&&i.dependents.zone.left===t.dependents.zone.left&&i.dependents.zone.right===t.dependents.zone.right&&i.dependents.sheetId===t.dependents.sheetId)if(i.dependents.zone.top-1===t.dependents.zone.bottom)t.dependents.zone.bottom=i.dependents.zone.bottom;else if(i.dependents.zone.top===t.dependents.zone.top&&i.dependents.zone.bottom===t.dependents.zone.bottom)continue;else n.push(t),t=i;else n.push(t),t=i}return n.push(t),n}mergeSortedIntervals(e,t){let n=[],r=0,i=0;for(;r<e.length&&i<t.length;)oL(e[r],t[i])<=0?n.push(e[r++]):n.push(t[i++]);return n.concat(r<e.length?e.slice(r):t.slice(i))}bulkLoad(e){let t=this.compactSortedIntervals(e);this.root=this.buildBalancedTree(t)}buildBalancedTree(e,t=0,n=e.length){if(t>=n)return null;let r=t+(n-t>>1),i=new iL(e[r]);return i.left=this.buildBalancedTree(e,t,r),i.right=this.buildBalancedTree(e,r+1,n),i.max=Math.max(i.interval.bottom,i.left?i.left.max:-1,i.right?i.right.max:-1),i}searchTree(e,t,n){!e||t.top>e.max||(this.isOverlapping(e.interval,t)&&n.push(e.interval),e.left&&e.left.max>=t.top&&this.searchTree(e.left,t,n),e.right&&t.bottom>=e.interval.top&&this.searchTree(e.right,t,n))}inOrderTraversal(e,t){e&&(this.inOrderTraversal(e.left,t),t.push(e.interval),this.inOrderTraversal(e.right,t))}isOverlapping(e,t){return e.top<=t.bottom&&e.bottom>=t.top}};function oL(e,t){if(e.top!==t.top)return e.top-t.top;if(e.bottom!==t.bottom)return e.bottom-t.bottom;let{zone:n,sheetId:r}=e.dependents,{zone:i,sheetId:a}=t.dependents;return r===a?n.left-i.left||n.right-i.right||n.top-i.top||n.bottom-i.bottom:r>a?1:-1}var sL=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){ln(this.profilesStartingPosition,this.profiles,[e])}delete(e){ln(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return un(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return mn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},cL=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new sL),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(sc(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(sc(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(sc(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},lL=class{forest={};removeAllDependencies(e){}addDependencies(e,t){let n={zone:D(e),sheetId:e.sheetId};for(let e of t){if(e.invalidSheetName||e.invalidXc)continue;let{zone:t,sheetId:r}=e;for(let e=t.left;e<=t.right;e++)this.getOrCreateIntervalTree(r,e).insert({top:t.top,bottom:t.bottom,dependents:n})}}getCellsDependingOn(e,t=new cL){t=t.copy();let n=Array.from(e).reverse();for(;n.length>0;){let e=n.pop();t.add(e);let r=e.zone,i=this.forest[e.sheetId];if(!i)continue;let a=new cL;for(let e=r.left;e<=r.right;e++){let t=i[e];if(!t)continue;let n=t.query(r);for(let e of n)a.add(e.dependents)}n.push(...a.difference(t))}for(let n of e)t.delete(n);return t}getOrCreateIntervalTree(e,t){let n=this.forest[e]?.[t];return n||(this.forest[e]||(this.forest[e]={}),n=new aL,this.forest[e][t]=n),n}},uL=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=dL(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function dL(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var fL=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=uL.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},pL=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),mL=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new hL,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new hL),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&T(e.data,t.data)}},hL=class extends pL.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},gL=class{resultsToArrayFormulas=new mL;arrayFormulasToResults=new aN;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||_L}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let _L=[],vL=new A;vL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let yL=Object.freeze(Gu({value:null}));var bL=class{context;getters;compilationParams;evaluatedCells=new aN;formulaDependencies=xt(new lL);blockedArrayFormulas=new fL({});spreadingRelations=new gL;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=nL(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||yL}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===M.SpilledBlocked)?D(e):kn(D(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==`empty`)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,D(e)).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t),this.computeDependencies(t)}computeDependencies(e){for(let t of e)this.compilationParams.ensureRange(t)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=nL(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=nL(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new fL(e)}evaluateCells(e){let t=performance.now(),n=new cL;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new cL;for(let n of e){let e=this.getters.getCell(n),r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),!e?.isFormula&&!e?.content&&t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new gL,this.formulaDependencies=xt(()=>{let e=new lL;for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t))if(n.isFormula){let t=this.getters.getCellPosition(n.id);e.addDependencies(t,n.compiledFormula.rangeDependencies)}return e})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new aN;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=Bc.Compile(t,e,this.getters);return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,r)}evaluateCompiledFormula(e,t,n){try{let r=wL(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Je(r)?lo(r,SL):SL(r)}catch(e){return Ao(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new cL,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new cL;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new cL(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);(r.value!==null||r.format!==void 0)&&this.evaluatedCells.set(n,r)}}vL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return{...yL,position:e};let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?TL(e):(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):zu(n,i,e))}catch(t){return t.value=t?.value||M.GenericError,t.message=t?.message||No,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,Gu(t,i.locale,e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=wL(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Je(n)){let r=Gu(CL(n),this.getters.getLocale(),e,t);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return Gu({value:0},this.getters.getLocale(),e,t);if(i===1&&r===1)return Gu(CL(n[0][0]),this.getters.getLocale(),e,t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),xL(r,i,this.checkCollision(e)),xL(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),Gu(CL(n[0][0]),this.getters.getLocale(),e,t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(zn(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw new Bi(j(`Result couldn't be automatically expanded.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Bi(j(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r},s=this.getters.getCell(o);if(s?.isFormula||s?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new Bi(j(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=Gu(CL(r[i][a]),this.getters.getLocale(),o,s);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r},i=this.getters.getCell(t);i?.isFormula||i?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return(t,n)=>{if(this.symbolsBeingComputed.has(t))return TL(this.compilationParams.evalContext.__originCellPosition);this.symbolsBeingComputed.add(t);try{let r=this.getters.getNamedRange(t);if(r){let e=this.compilationParams.evalContext;return e.__originCellPosition?this.addDependencies(e.__originCellPosition,[r.range]):this.computeDependencies([r.range]),Xn(r.range.zone)>1||n?this.compilationParams.ensureRange(r.range):this.compilationParams.referenceDenormalizer(r.range)}return e?.(t,n)||new Fi(j(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.rangeDependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function xL(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function SL(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function CL(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new Hi:SL(e)}function wL(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.rangeDependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}function TL(e){return Gu({...new Ii,origin:void 0},void 0,e)}var EL=class extends eL{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getVisibleRangeValues`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new bL(e.custom,this.getters)}beforeHandle(e){(_u.has(e.type)||yu.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Je(r)?lo(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getVisibleRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e))}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return Bn(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Bn(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Bn(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=E(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=l.compiledFormula.areAllFunctionsExportableToExcel(),a=s&&(u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content)===l.compiledFormula.toFormulaString(this.getters),!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=cd(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l?.isFormula?l.compiledFormula.toFormulaString(this.getters,{useBoundedReference:!0}):s?u:o,c.cells[r]=d,c.cellValues[r]=i===M.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let DL=new A;DL.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?Ab:Ob,hoverSvg:n?Ab:kb,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),DL.add(`data_validation_list_chip_icon`,(e,t)=>{if(e.isReadonly())return;let n=e.getDataValidationChipStyle(t);if(!e.cellHasListDataValidationIcon(t)&&!n)return;let r=e.getCellComputedStyle(t),i=n||r;return{svg:Tb(i),hoverSvg:Db(i),priority:2,horizontalAlign:`right`,size:kd(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_chip_icon`}}),DL.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:Nb[n].svg,priority:1,horizontalAlign:`left`,size:kd(r),margin:4,position:t}}}),DL.add(`pivot_collapse`,(e,t)=>{let n=e.getPivotIdFromPosition(t);if(!e.isSpillPivotFormula(t)||!n)return;let r=e.getPivotCellFromPosition(t),i=e.getPivotCoreDefinition(n);if(!(i.style?.tabularForm??_g.tabularForm)&&r.type===`HEADER`&&n&&r.domain.length){let n=e.isDashboard(),a=r.dimension===`COL`?i.columns:i.rows,o=!n&&!e.shouldShowFormulas()&&r.domain.length!==a.length,s=(i.collapsedDomains?.[r.dimension]??[]).some(e=>T(e,r.domain)),c=r.dimension===`ROW`?(r.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:o||!n&&r.dimension===`ROW`&&i.rows.length>1?12:0,margin:o?4+c:c,svg:o?jb(s,!1):void 0,hoverSvg:o?jb(s,!0):void 0,position:t,onClick:Kg}}}),DL.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:kd(r),margin:0,svg:n===`asc`?Eb(r):Tb(r),position:t,onClick:void 0}});var OL=class extends eL{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=DL.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(w)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}};let kL=/"(#[0-9a-fA-F]{6})"/g;function AL(e){let t=[{leadColor:Lr(255,0,0),colors:[]},{leadColor:Lr(255,128,0),colors:[]},{leadColor:Lr(128,128,0),colors:[]},{leadColor:Lr(128,255,0),colors:[]},{leadColor:Lr(0,255,0),colors:[]},{leadColor:Lr(0,255,128),colors:[]},{leadColor:Lr(0,255,255),colors:[]},{leadColor:Lr(0,127,255),colors:[]},{leadColor:Lr(0,0,255),colors:[]},{leadColor:Lr(127,0,255),colors:[]},{leadColor:Lr(128,0,128),colors:[]},{leadColor:Lr(255,0,128),colors:[]}];for(let n of e.map(Vr)){let e=500,r=0;t.forEach((t,i)=>{let a=jL(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Ur(e).s-Ur(t).s)).flat().map(Br)}function jL(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var ML=class extends eL{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds()){for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));for(let t of this.getters.getFigures(e))this.tryToAddColors(this.getCarouselColors(e,t.id))}break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.chartId));break;case`CREATE_CAROUSEL`:case`UPDATE_CAROUSEL`:this.tryToAddColors(this.getCarouselColors(e.sheetId,e.figureId));break;case`COLOR_SHEET`:e.color&&this.tryToAddColors([e.color]);break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return AL(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getSheetColors(t),this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getSheetColors(e){let t=this.getters.getSheet(e);return t.color?[t.color]:[]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(jr(t.minimum.color)),n.push(t.midpoint?jr(t.midpoint.color):void 0),n.push(jr(t.maximum.color)))}return n.filter(w)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getRangeDefinition()).matchAll(kL)].map(e=>e[1])}getCarouselColors(e,t){if(this.getters.getFigure(e,t)?.tag!==`carousel`)return[];let n=this.getters.getCarousel(t).title?.color;return n?[n]:[]}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(w):[]}tryToAddColors(e){for(let t of e){if(!Pr(t))continue;let e=Nr(t);t&&!ye.includes(e)&&this.history.update(`customColors`,e,!0)}}},NL=class extends eL{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(_u.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:case`REFRESH_PIVOT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=[...this.getters.getCoreTables(e)].filter(e=>e.type!==`dynamic`);t.push(...n);for(let r of this.getDynamicTables(e)){let i=this.coreTableToTable(e,r),a=i.range.zone,o=a.left,s=a.top;if(!n.some(e=>Fn(o,s,e.range.zone))){for(let e of n){let t=e.range.zone;Nn(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...i,range:this.getters.getRangeFromZone(e,a)})}}return t}getDynamicTables(e){let t=this.getters.getCoreTables(e).filter(e=>e.type===`dynamic`),n=this.getTablesFromPivots(e),r=new Set(n.map(t=>this.getters.getRangeString(t.range,e))),i=t.filter(t=>!r.has(this.getters.getRangeString(t.range,e)));return[...n,...i]}getTablesFromPivots(e){let t=[];for(let{position:n,pivotStyle:r,pivotId:i}of this.getters.getAllPivotArrayFormulas()){if(!this.getters.getPivot(i).isValid())continue;let a=this.getters.getSpreadZone(n),o=this.getters.getCell(n);n.sheetId!==e||!a||!o||r.tableStyleId===`None`||t.push({type:`dynamic`,id:`pivot_table_`+i+`_`+o.id,range:this.getters.getRangeFromZone(e,D(n)),config:this.getTableConfigFromPivotStyle(i,r),isPivotTable:!0})}return t}getTableConfigFromPivotStyle(e,t){let n=this.getters.getPivot(e).getCollapsedTableStructure(),{numberOfRows:r,numberOfHeaderRows:i}=n.getPivotTableDimensions(t),a=n.getPivotCells(t)[0]?.[r-1],o=t.displayTotals&&a?.type===`HEADER`&&a.domain.length===0;return{hasFilters:t.hasFilters,totalRow:o,firstColumn:!0,lastColumn:!0,numberOfHeaders:i,bandedRows:t.bandedRows,bandedColumns:t.bandedColumns,styleId:t.tableStyleId}}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!er(t))return!1;let n=kn(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===M.SpilledBlocked&&!e.errorOriginPosition}else if(T(i,r)&&Xn(n)===1)return!0;return T(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config,isPivotTable:t.isPivotTable}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=kM(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Bn(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=yn(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Bn(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=E(n.col,n.row);if(!gt(i)){let n=cd(i,e.styles);t.styles[o]=n}if(a){let n=cd(a,e.borders);t.borders[o]=n}}}t.tables=n}}};function PL(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!If(e.xAxisID)).map(e=>({...e,pointRadius:e.showLine===!1?2:0}))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return Ff(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}var FL=class extends eL{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};handle(e){if(_u.has(e.type)||bu.has(e.type)||vu.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(e,t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:wf(e)};if(!t)return{background:oe,fontColor:wf(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||wf(o)}}async exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=await ch(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}createRuntimeChart(e,t){let n=t.getRangeDefinition(),r=t.getRuntime(this.getters,e);if(`chartJsConfig`in r&&/line|combo|bar|scatter|waterfall/.test(n.type)){let e=r.chartJsConfig;r.masterChartConfig=PL(e)}return r}},IL=class extends eL{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(_u.has(e.type)||bu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=xt(()=>this.getComputedStyles(e)),this.computedIcons[e]=xt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=xt(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]?.();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]?.();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]?.();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(t=>{if(t.startsWith(`=`))return Bc.Compile(t,e,this.getters)}),i=X.get(n.rule.operator),a={...n.rule,type:n.rule.operator},o=n.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t)),s=i.preComputeCriterion?.(a,o,this.getters);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s):t});this.getRuleResultForTarget(c,{...n.rule,values:l},s)&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Vt(a):Ht(a);case`number`:return Number(n.value);case`percentage`:let t=Ht(a);return t+(Vt(a)-t)*Number(n.value)/100;case`percentile`:return La(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Vt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!Fn(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:jr(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a!==null&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a!==null&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=hi(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=S(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t,n){let r=this.getters.getEvaluatedCell(e);if(r.type===`error`)return!1;let{sheetId:i}=e,a=X.get(t.operator),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(i,t,e)??``:Wu(t,V));if(o.some(Eh))return!1;let s={...t,type:t.operator,values:o.map(wh),dateValue:t.dateValue||`exactDate`};return a.isValueValid(r.value??``,s,n)}};let LL={isValid:!0};var RL=class extends eL{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};criterionPreComputeResult={};handle(e){if(_u.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={},this.criterionPreComputeResult={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId],delete this.criterionPreComputeResult[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=X.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?j(`The value must not be a formula`):this.isValidFormula(t)?void 0:Wy.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?j(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Bn(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return LL;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:LL}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Qr(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!Bc.IsBadExpression(e)}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||LL}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of ac(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=xt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?LL:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=X.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(Eh))return;let c={...i,values:s.map(wh)};this.criterionPreComputeResult[r]||(this.criterionPreComputeResult[r]={});let l=this.criterionPreComputeResult[r][n.id];if(l===void 0&&(l=a.preComputeCriterion?.(n.criterion,n.ranges,this.getters),this.criterionPreComputeResult[r][n.id]=l),!a.isValueValid(e,c,l))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>Fn(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n,r){return r.values.map(r=>{if(!r.startsWith(`=`))return Wu(r,V);let i=Bc.Compile(r,e,this.getters),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i);return this.getters.evaluateFormula(e,a,t)})}};let zL=[`SUBTOTAL`,`PIVOT`];var BL=class extends eL{static getters=[`getCellsWithTrackedFormula`];trackedCells={};handle(e){switch(e.type){case`START`:for(let e of zL)this.trackedCells[e]={};for(let e of this.getters.getSheetIds())for(let t of this.getters.getCells(e))for(let e of zL)Yt(t,e)&&this.history.update(`trackedCells`,e,t.id,t.id);break;case`UPDATE_CELL`:{if(!(`content`in e))return;let t=this.getters.getCell(e);if(!t)return;for(let e of zL)Yt(t,e)?this.history.update(`trackedCells`,e,t.id,t.id):this.trackedCells[e][t.id]&&this.history.update(`trackedCells`,e,t.id,void 0);break}}}getCellsWithTrackedFormula(e){return Object.values(this.trackedCells[e]||{}).filter(t=>t!==void 0&&this.trackedCells[e][t]&&this.getters.tryGetCellPosition(t))}},VL=class extends eL{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=_d();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ct(e.position,e.base),n=Array(e.quantity).fill(void 0),r=It(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=x(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=Ft(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of C(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`SET_FORMATTING`:if(e.style&&(`fontSize`in e.style||`wrapping`in e.style||`rotation`in e.style))for(let t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Bn(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForZoneChange(e,t){for(let n=t.top;n<=t.bottom;n++){let t=this.getRowTallestCell(e,n);this.history.update(`tallestCellInRow`,e,n,t)}}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return vd(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCellIds(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let HL=`0.00%`;function UL(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=Sg[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return Ao(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=vj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=vj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Je(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=vj(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=jg(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:M.NotAvailable,message:j(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return Ao(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:HL}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:HL}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:HL}}asPercentOfParentRowTotal(e,t,n){let r=gj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:HL}}asPercentOfParentColumnTotal(e,t,n){let r=_j(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:HL}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!Ej(i,n))return{value:``};let a=wj(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:HL}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:M.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=vj(this,n),u=kj(l),d=kj(c),f=s[u]?.[d];return f===void 0&&(f=this.getPreviousRunningTotalValue(a,n,s)),{value:f??``,format:i===`running_total`?e.format:HL}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Ej(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:M.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:HL}:s===void 0?{value:M.NullError}:{value:s/o,format:HL}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Ej(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Ej(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:M.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:M.NullError}:{value:(s-o)/o,format:HL}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!Ej(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=vj(this,n),u=kj(l),d=kj(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=Dj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=fo(o));for(let s of o){let o=kj(yj(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:yj(this,i,t.domain)})).filter(e=>Ej(t,e.rowDomain)),l=Object.groupBy(c,e=>jj(e.rowDomain,t));for(let e in l)l[e]=Wt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=kj(yj(this,i,e.domain)),a=l[jj(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Gt(r)}computeRunningTotal(e,t,n){let r={},i=Dj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=fo(o));for(let s of o){let o=kj(yj(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:yj(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>Ej(t,e.rowDomain));for(let e of l){let n=kj(e.rowDomain),i=Mj(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=kj(n),a=Mj(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Gt(r)}getPreviousRunningTotalValue(e,t,n){let r=this.definition.getDimension(e);if(r.type!==`date`&&r.type!==`datetime`)return;let i=Dj(this,e),{rowDomain:a,colDomain:o}=vj(this,t),s=i===`row`?a:o,c=i===`row`?o:a,l=s.find(t=>t.field===e)?.value;if(l===void 0)return;let u=kj(c),d=Mj(s,e),f,p,m=this.getCollapsedTableStructure(),h=i===`row`?m.getRowTree():m.getColTree(),g=(t,n=[])=>{for(let i of t){let t=[...n,{field:i.field,value:i.value,type:i.type}];i.children.length&&g(i.children,t);let a=t.find(t=>t.field===e)?.value,o=Mj(t,e);a===void 0||o!==d||this.compareRunningTotalValues(a,l,r)>=0||(p===void 0||this.compareRunningTotalValues(p,a,r)<0)&&(p=a,f=kj(t))}};if(g(h),f)return i===`row`?n[u]?.[f]:n[f]?.[u]}compareRunningTotalValues(e,t,n){let r=n.order??`asc`,i=e===null,a=t===null;if(i&&a)return 0;if(i)return r===`asc`?1:-1;if(a)return r===`asc`?-1:1;let o=this.getRunningTotalComparableValue(e,n)-this.getRunningTotalComparableValue(t,n);return r===`asc`?o:-o}getRunningTotalComparableValue(e,t){let n=t.granularity;if(n&&rg.contains(n)){let t=ig(n).toComparableValue?.(e);if(t!==void 0)return t}return I(e,V)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=vj(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=vj(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?Oj(this,t,n,r):Tj(t,n,r);if(T(i,t))return`sameValue`;if(!i||!xj(this,i))throw new Ri;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;zg(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let WL=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function GL(e){return WL.includes(e.type)}var KL=class extends eL{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`,`getAllPivotArrayFormulas`,`getPivotStyleAtPosition`];pivots={};unusedPivotsInFormulas;custom;pivotPositionCache=new aN;shouldInvalidateCache=!1;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(_u.has(e.type)){this.shouldInvalidateCache=!0;for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0})}switch(e.type===`UPDATE_CELL`&&(this.shouldInvalidateCache=!0),e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.unusedPivotsInFormulas?.push(e.pivotId),this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.unusedPivotsInFormulas?.push(e.newPivotId),this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivotsInFormulas=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivotsInFormulas=void 0;let t=e.commands.filter(GL);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:$g();break}}finalize(){this.shouldInvalidateCache&&=(this.pivotPositionCache=new aN,!1)}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){if(!this.pivotPositionCache.has(e)){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula);this.pivotPositionCache.set(e,n)}}return this.pivotPositionCache.get(e)||[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(w)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=$j(t,this.getters);if(!n.length)return[];let r=[];for(let t of n){let{functionName:n,args:i}=t,a=i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=TF(t);return this.getters.evaluateFormula(e,n)});r.push({functionName:n,args:a})}return r}getFirstPivotFunction(e,t){return this.getPivotFunctions(e,t)[0]}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||eM(t.compiledFormula,this.getters)===0)return Ij;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!r)return Ij;let{functionName:i,args:a}=r,o=a[0];if(!o)return Ij;let s=this.getters.getPivotId(o.toString());if(!s)return Ij;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!this.isMainFunctionPivotSpreadFunction(t))return Ij;try{if(i===`PIVOT`){let t=qg(this.getters.getPivotCoreDefinition(s),wh(a[1]),wh(a[2]),wh(a[3]),wh(a[4]),wh(a[5]),this.getters.getLocale()),r=c.getCollapsedTableStructure().getPivotCells(t),i=e.col-n.col,o=e.row-n.row;return r[i][o]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Je(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:vj(c,e).colDomain.length?`COL`:`ROW`}}let[o,...l]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(l.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return Ij}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return Kt(j(`Calculated measure 1`),t,{compute:(e,t)=>j(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){let{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&qj.get(t).isPivotUnused(this.getters,e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||n.type===`ROW_GROUP_NAME`||!t)return;let r=this.getters.getPivot(t),i=vj(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&T(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=x(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=UL(qj.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(this.unusedPivotsInFormulas!==void 0)return this.unusedPivotsInFormulas;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t)){let t=this.getters.getCellPosition(n.id),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivotCoreDefinition(t);for(let r of n.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}getAllPivotArrayFormulas(){let e=[];for(let t of this.getters.getCellsWithTrackedFormula(`PIVOT`)){let n=this.getters.getCellPosition(t);if(this.getters.getEvaluatedCell(n).type===`error`)continue;let r=this.getPivotStyleAtPosition(n);r&&e.push({position:n,...r})}return e}getPivotStyleAtPosition(e){e=this.getters.getArrayFormulaSpreadingOn(e)||e;let t=this.getters.getCell(e);if(!t||!t.isFormula||!this.isMainFunctionPivotSpreadFunction(t))return;let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!n||n.functionName!==`PIVOT`)return;let r=n.args[0];if(!r)return;let i=this.getters.getPivotId(r.toString());if(i)return{pivotStyle:qg(this.getters.getPivotCoreDefinition(i),wh(n.args[1]),wh(n.args[2]),wh(n.args[3]),wh(n.args[4]),wh(n.args[5]),this.getters.getLocale()),pivotId:i}}isMainFunctionPivotSpreadFunction(e){return e.compiledFormula.isFirstNonWhitespaceSymbol(`PIVOT`)}},qL=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},JL=class extends qL{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of ZT(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},YL=class extends JL{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t,n=`copyPaste`){let r=e.sheetId,{clippedZones:i,rowsIndexes:a,columnsIndexes:o}=e,s=[],c=a.length===1&&o.length===1;for(let t of a){let i=[];for(let s of o){let l={col:s,row:t,sheetId:r},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(n!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!T(p,l)||!c)&&t&&!e.zones.some(e=>In(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=Ag(this.getters.getPivotFormulaId(f),e);u={id:u?.id??0,style:u?.style,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(n!==`shiftCells`&&p&&!T(p,l)){let e=a.includes(p.row)&&o.includes(p.col)?``:H(d.value,{locale:this.getters.getLocale()});u={id:u?.id??0,style:u?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content??``,style:u?.style,format:u?.format,compiledFormula:u?.isFormula?u?.compiledFormula:void 0,border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}s.push(i)}return{cells:s,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of ZT(t,n.cells))if(this.getters.doesIntersectMerge(e,r)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*a!==1))return`WillRemoveExistingMerge`;return`Success`}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.cells,n)}getPasteTarget(e,t,n,r){let i=n.cells[0].length,a=n.cells.length;return r?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+a-1}]}:i===1&&a===1?{zones:[],sheetId:e}:{sheetId:e,zones:ZT(t,n.cells)}}pasteFromCut(e,t,n,r){this.clearClippedZones(n);let i=t[0];this.pasteZone(e,i.left,i.top,n.cells,r)}clearClippedZones(e){this.dispatch(`CLEAR_CELLS`,{sheetId:e.sheetId,target:e.zones}),this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){if(!s)continue;let o={col:t+r,row:n+a,sheetId:e};this.pasteCell(s,o,i)}}pasteCell(e,t,n){let{sheetId:r,col:i,row:a}=t,o=this.getters.getEvaluatedCell(t),s=e?.format||e.evaluatedCell.format;if(n?.pasteOption===`asValue`){this.dispatch(`UPDATE_CELL`,{...t,content:e.evaluatedCell.value?.toString()||``});return}if(n?.pasteOption===`onlyFormat`){this.dispatch(`UPDATE_CELL`,{...t,style:e?.style??null,format:s??o.format});return}let c=e?.content;e?.compiledFormula?.hasDependencies&&!n?.isCutOperation?c=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.compiledFormula):e?.compiledFormula?.hasDependencies&&(c=this.getters.getFormulaMovedInSheet(r,e.compiledFormula)),c!==``||e?.format||e?.style?this.dispatch(`UPDATE_CELL`,{...t,content:c,style:e?.style||null,format:e?.format}):o&&this.dispatch(`CLEAR_CELL`,t)}convertTextToClipboardData(e){let t=this.getters.getLocale(),n={cells:[]},r=[],i=0;for(let[t,n]of e.replace(/\r/g,``).split(`
|
|
115
115
|
`).entries())r.push(n.split(` `)),r[t].length>i&&(i=r[t].length);for(let e of r){let r=[];for(let n=0;n<i;n++){let i=Qy(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},XL=class extends TI{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t),this.getters=e,this.ui=i,this.selection=a,this.dispatch=n,this.canDispatch=r}drawLayer(e,t){}},ZL=class extends XL{allowDispatch(e){switch(e.type){case`REMOVE_DUPLICATES`:return this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique))}return`Success`}handle(e){switch(e.type){case`REMOVE_DUPLICATES`:this.removeDuplicates(e.columns,e.hasHeader);break;case`TRIM_WHITESPACE`:this.trimWhitespace();break}}removeDuplicates(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getSelectedZone();t&&(r.top+=1);let i=this.getUniqueRowsIndexes(n,r.top,r.bottom,e),a=i.length;if(a===Ln(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new YL(this.getters,this.dispatch),c=s.copy(YT(n,o),!1);if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of C(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>T(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:j(`%s duplicate rows found and removed.
|
|
116
|
-
%s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?`Success`:`MoreThanOneRangeSelected`}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?`WillRemoveExistingMerge`:`Success`}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?`EmptySelectedRange`:`Success`}checkNoColumnProvided(e){return e.columns.length===0?`NoColumnsProvided`:`Success`}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?`ColumnsNotIncludedInZone`:`Success`}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?`Success`:`DuplicatesColumnsSelected`}trimWhitespace(){let e=cn(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(Bn).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=e.isFormula?e.compiledFormula.toFormulaString(this.getters):e.content,o=Rt(a);o!==a&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:o}))}let r=n?j(`Trimmed whitespace from %s cells.`,n):j(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}};let QL=new A;QL.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:{props:{content:r}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=H(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=z(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=ga(r);e.current=i;let a=n.getLocale(),o=H(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.isFormula?t.cell?.compiledFormula.toFormulaString(n):t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format},a={sheetId:t.sheetId,col:t.col,row:t.row};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?zu(t.cell,i,a).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let $L=new A,eR=/(\d+)$/,tR=/^(.*\D+)/,nR=/^(.*\D+)(\d+)$/,rR=/^0*/;function iR(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:zu(a,{locale:V,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function aR(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function oR(e){let t=1;return e.length>=2&&(t=aR(e)*e.length),t}function sR(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function cR(e){if(e.length<2)return 1;let t=e.map(e=>z(e,V)),n=sR(lR(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}$L.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&Rl(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&zu(e,{locale:V}).type===`text`&&nR.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(eR)[0]),i=e.content.match(tR)[0],a=iR(e,t,e=>e.type===`text`&&nR.test(e.value)).filter(e=>i===(e.value??``).toString().match(tR)[0]).map(e=>(e.value??``).toString().match(eR)[0]),o=a.reduce((e,t)=>{let n=t.match(rR)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=oR(a.map(e=>parseInt(e)));return[`up`,`left`].includes(n)&&a.length===1&&(c=-c),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:c,numberPostfixLength:s}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&zu(e,{locale:V}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&zu(e,{locale:V}).type===`number`&&!!e.format&&Rl(e.format),generateRule:(e,t)=>{let n=cR(iR(e,t,e=>e.type===`number`&&!!e.format&&Rl(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=zu(e,{locale:V});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&zu(e,{locale:V}).type===`number`,generateRule:(e,t,n)=>{let r=iR(e,t,e=>e.type===`number`&&!Rl(e.format||``)).map(e=>Number(e.value)),i=oR(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=zu(e,{locale:V});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function lR(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=P.fromTimestamp(e[n-1].getTime()),i=wa(r,t),a=Sa(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:Ca(r,t)}}).slice(1)}var uR=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=QL.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},dR=class extends XL{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:S(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:S(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(D({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=E(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(D({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:cn(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(yn),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=cn(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(Fn(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=$L.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=sn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)??void 0;t.push({data:{...e,border:r},rule:n})}return new uR(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e,{x:a,y:o,width:s,height:c}=r.getVisibleRect(i,this.autofillZone);s>0&&c>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(a,o,s,c),t.setLineDash([]))}},fR=class extends XL{static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=Fn(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||Rn(kn(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,kn(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=C(n,-1,-1),a=Vt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=rt(i.filter(e=>this.isNumber(r[e])))[0]||[];return Vt(o)<a?1/0:Ht(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&Rl(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return Rn(t)?(n.add(Ln(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},Bn(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},Bn(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}},pR=class extends XL{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(_u.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(hR(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)try{return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}catch(e){if(F(e)||e instanceof N)return;throw e}}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)try{return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}catch(e){if(F(e)||e instanceof N)return;throw e}}computeTableStyle(e,t){return xt(()=>{let n=this.getters.getTableStyle(t.config.styleId),r=this.getTableMetaData(e,t);if(!r)return{borders:{},styles:{}};let{tableMetaData:i,config:a}=r,o=jM(a,n,i),s=this.getTableMapping(e,t),c={borders:{},styles:{}};for(let e=0;e<i.numberOfCols;e++){let t=s.colMapping[e];c.borders[t]={},c.styles[t]={};for(let n=0;n<i.numberOfRows;n++){let r=s.rowMapping[n];c.borders[t][r]=o.borders[e][n],c.styles[t][r]=o.styles[e][n]}}return c})}getTableMetaData(e,t){let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t);if(!t.isPivotTable)return{tableMetaData:{numberOfCols:r,numberOfRows:i,mode:`table`},config:n};let a={sheetId:e,col:t.range.zone.left,row:t.range.zone.top},o=this.getters.getPivotStyleAtPosition(a);if(!o)throw Error(`No dynamic pivot info found at pivot table position`);let s=this.getters.getPivot(o.pivotId);if(!s.isValid())return;let c=o.pivotStyle,l=s.getExpandedTableStructure().getNumberOfRowGroupBys(),u=s.getCollapsedTableStructure(),d=u.getPivotCells(c),f=new Set,p=new Set,m=new Set,h=u.getNumberOfRowGroupBys();if(c.tabularForm){let n=0;for(let r=0;r<h;r++){if(this.getters.isColHidden(e,r+t.range.zone.left)){n++;continue}r===0&&l>1?f.add(0):r%2==1?p.add(r-n):r%2==0&&m.add(r-n)}}else{let n=0;for(let r=0;r<d[0].length;r++){if(this.getters.isRowHidden(e,r+t.range.zone.top)){n++;continue}let i=d[0][r];i.type!==`HEADER`||i.domain.length===0||(i.domain.length===1&&l>1?f.add(r-n):i.domain.length%2==0&&l>i.domain.length?p.add(r-n):i.domain.length%2==1&&l>i.domain.length&&m.add(r-n))}}return{tableMetaData:{mode:`pivot`,numberOfCols:r,numberOfRows:i,mainSubHeaderRows:f,firstAlternatingSubHeaderIndexes:p,secondAlternatingSubHeaderIndexes:m,measureRow:n.numberOfHeaders&&c.displayMeasuresRow&&!this.getters.isRowHidden(e,n.numberOfHeaders-1+t.range.zone.top)?n.numberOfHeaders-1:void 0,isTabular:c.tabularForm},config:n}}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let mR=new Set([`HIDE_COLUMNS_ROWS`,`UNHIDE_COLUMNS_ROWS`,`UNFOLD_HEADER_GROUP`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`FOLD_ALL_HEADER_GROUPS`,`UNFOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`CREATE_TABLE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`REMOVE_TABLE`,`RESIZE_TABLE`,`CREATE_TABLE_STYLE`,`REMOVE_TABLE_STYLE`,`DELETE_CONTENT`]);function hR(e){return mR.has(e.type)}var gR=class extends XL{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new aN;borders=new aN;handle(e){if(_u.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles=new aN,this.borders=new aN;return}if(hR(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new aN,this.borders=new aN);return}if(bu.has(e.type)){this.styles=new aN;return}if(xu.has(e.type)){this.borders=new aN;return}}getCellComputedBorder(e){let t=this.borders.get(e);return t===void 0&&(t=this.computeCellBorder(e),this.borders.set(e,t)),t}getCellComputedStyle(e){let t=this.styles.get(e);return t===void 0&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellStyle(e){let t=this.getters.getEvaluatedCell(e),n=this.getComputedStyle(e);return t.link&&!n.textColor&&(n.textColor=ce),n}getComputedStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e);return{...Dt(r),...Dt(i),...Dt(t?.style),...Dt(n)}}exportForExcel(e){for(let t of e.sheets){let n={},r=[];for(let e in t.cells){let i={sheetId:t.id,...sn(e)},a=this.getters.getEvaluatedCell(i),o=this.getComputedStyle(i);if(!a.link||o.textColor)continue;let s=Object.keys(t.styles).find(t=>In(yn(e),yn(t)));s?(n[s]||(n[s]=[]),n[s].push(e)):r.push(e)}for(let[r,i]of Object.entries(n)){let n=t.styles[r];if(e.styles[n].textColor)continue;let a=e.styles[n],o=i.map(yn),s=cn([yn(r)],o);delete t.styles[r];for(let e of s)t.styles[wn(e)]=n;let c=cd({...a,textColor:ce},e.styles);for(let e of i)t.styles[e]=c}for(let n of r){let r=this.getters.getCell({sheetId:t.id,...sn(n)});t.styles[n]=cd({...r?.style,textColor:ce},e.styles)}}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...Dt(this.getters.getCellTableBorder(e)||{}),...Dt(t)};return gt(n)?null:n}},_R=class extends XL{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}};function vR(e){let t=lc.get(e.type)?.(e),n=xR(e);if(!t&&!n)return;let r=t||bR(),i=n||(e=>e),a=yR(r.applyChange);return{applyChange:a,adaptRangeString:(e,t)=>Ec(e,t,r),adaptFormulaString:(e,t)=>wc(e,t,r,i),adaptCompiledFormula:e=>e.adaptCompiledFormula(a,i)}}function yR(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!Sn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}function bR(){return{applyChange:e=>({changeType:`NONE`,range:e}),sheetId:`ignoredSheetId`,sheetName:{old:`ignoredSheetName`,current:`ignoredSheetName`}}}function xR(e){if(e.type!==`UPDATE_NAMED_RANGE`)return;let t=e.oldRangeName.toLowerCase();return n=>n.toLowerCase()===t?e.newRangeName:n}let SR=new class extends A{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},CR=new class extends A{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};SR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],IR),SR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],IR),SR.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],DR),SR.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],OR),SR.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],kR),SR.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],AR),SR.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],jR),SR.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],MR),SR.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],NR),SR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],NR),SR.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],PR),SR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],PR),SR.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],FR),SR.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],LR),SR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],LR),SR.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],ER),SR.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],TR),SR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],wR),SR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],wR),SR.addTransformation(`UPDATE_NAMED_RANGE`,[`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`],RR);function wR(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=sr(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function TR(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function ER(e,t){if(e.pivotId!==t.pivotId)return e}function DR(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function OR(e,t){if(e.figureId!==t.figureId)return e}function kR(e,t){if(e.chartId!==t.chartId)return e}function AR(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function jR(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function MR(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!Nn(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function NR(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function PR(e,t){if(e.sheetId!==t.sheetId)return e;let n=sr(e.zone,t);if(!n)return;let r=e.newTableRange?cr(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function FR(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:WS.styleId}}:e}function IR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=yc(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=vc(Ct(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function LR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=C(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=yc(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=vc(Ct(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function RR(e,t){return t.newRangeName===t.oldRangeName?e:e.type===`DELETE_NAMED_RANGE`&&e.name===t.oldRangeName?{...e,name:t.newRangeName}:e.type===`UPDATE_NAMED_RANGE`&&e.oldRangeName===t.oldRangeName?{...e,oldRangeName:t.newRangeName}:e}function zR(e,{adaptFormulaString:t}){let n=e.content&&t(e.sheetId,e.content);return{...e,content:n}}CR.add(`UPDATE_CELL`,zR);function BR(e,{adaptRangeString:t,adaptFormulaString:n}){let r=e.cf.rule;if(e={...e,cf:{...e.cf}},r.type===`CellIsRule`)e.cf.rule={...r,values:r.values.map(t=>n(e.sheetId,t))};else if(r.type===`ColorScaleRule`){let{minimum:t,maximum:i,midpoint:a}=r;e.cf.rule={...r,minimum:{...t,value:t.value&&n(e.sheetId,t.value)},maximum:{...i,value:i.value&&n(e.sheetId,i.value)},midpoint:a?{...a,value:n(e.sheetId,a.value)}:void 0}}else if(r.type===`IconSetRule`){let{upperInflectionPoint:t,lowerInflectionPoint:i}=r;e.cf.rule={...r,upperInflectionPoint:{...t,value:n(e.sheetId,t.value)},lowerInflectionPoint:{...i,value:n(e.sheetId,i.value)}}}else r.type===`DataBarRule`&&(e.cf.rule={...r,rangeValues:r.rangeValues?t(e.sheetId,r.rangeValues).range:void 0});return e}CR.add(`ADD_CONDITIONAL_FORMAT`,BR);function VR(e,{adaptFormulaString:t}){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>t(e.sheetId,n)),e}CR.add(`ADD_DATA_VALIDATION_RULE`,VR);function HR(e,{adaptFormulaString:t}){return e=x(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=t(e.computedBy.sheetId,e.computedBy.formula))}),e}CR.add(`ADD_PIVOT`,HR),CR.add(`UPDATE_PIVOT`,HR),CR.add(`CREATE_CHART`,UR),CR.add(`UPDATE_CHART`,UR);function UR(e,t){return{...e,definition:CO.transformDefinition(e.sheetId,e.definition,t)}}let WR=[{match:du,fn:YR},{match:pu,fn:XR},{match:gu,fn:ZR},{match:hu,fn:ez},{match:fu,fn:$R},{match:mu,fn:QR}];function GR(e,t){let n=SR.getTransformation(e.type,t.type),r=n?n(e,t):JR(e,t);return r&&KR(r,t)}function KR(e,t){let n=CR.get(e.type);if(!n)return e;let r=vR(t);return r?n(e,r):e}function qR(e,t){let n=[...e],r=new Set(SR.getKeys());for(let e of t)(r.has(e.type)||lc.contains(e.type))&&(n=n.reduce((t,n)=>{let r=GR(n,e);return r&&t.push(r),t},[]));return n}function JR(e,t){for(let{match:n,fn:r}of WR)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function YR(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId,r=t.type===`LOCK_SHEET`&&t.sheetId;return e.sheetId===n||e.sheetId===r?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function XR(e,t){let n=YR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=sr(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function ZR(e,t){let n=YR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=sr(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function QR(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>cr(e,t)).filter(w);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function $R(e,t){let n=YR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=yc(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=vc(Ct(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function ez(e,t){let n=YR(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?tz(e,t):t.type===`ADD_MERGE`?nz(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function tz(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function nz(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&Fn(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var rz=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},iz=class extends Error{},az=class extends lr{revisions;transportService;serverRevisionId;commandSquisher;clients={};clientId=`local`;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Bd;lastLocalOperation;constructor(e,t,n=ke,r){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.commandSquisher=r}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new rz(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&=(this.move(this.awaitingClientPosition),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),await this.sendToTransport({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new iz(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(w))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.sendToTransport({type:n,version:1,client:{...r,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,timestamp:n}=e,r=this.commandSquisher.unsquish(e.commands),i=new rz(e.nextRevisionId,t,r,void 0,void 0,n);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:qR(r,t)})}break;case`SNAPSHOT_CREATED`:{let t=new rz(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.sendToTransport({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}async sendToTransport(e){return this.transportService.sendMessage(e)}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
|
|
116
|
+
%s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?`Success`:`MoreThanOneRangeSelected`}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?`WillRemoveExistingMerge`:`Success`}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?`EmptySelectedRange`:`Success`}checkNoColumnProvided(e){return e.columns.length===0?`NoColumnsProvided`:`Success`}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?`ColumnsNotIncludedInZone`:`Success`}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?`Success`:`DuplicatesColumnsSelected`}trimWhitespace(){let e=cn(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(Bn).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=e.isFormula?e.compiledFormula.toFormulaString(this.getters):e.content,o=Rt(a);o!==a&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:o}))}let r=n?j(`Trimmed whitespace from %s cells.`,n):j(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}};let QL=new A;QL.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:{props:{content:r}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=H(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=z(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=ga(r);e.current=i;let a=n.getLocale(),o=H(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.isFormula?t.cell?.compiledFormula.toFormulaString(n):t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format},a={sheetId:t.sheetId,col:t.col,row:t.row};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?zu(t.cell,i,a).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let $L=new A,eR=/(\d+)$/,tR=/^(.*\D+)/,nR=/^(.*\D+)(\d+)$/,rR=/^0*/;function iR(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:zu(a,{locale:V,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function aR(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function oR(e){let t=1;return e.length>=2&&(t=aR(e)*e.length),t}function sR(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function cR(e){if(e.length<2)return 1;let t=e.map(e=>z(e,V)),n=sR(lR(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}$L.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&Rl(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&zu(e,{locale:V}).type===`text`&&nR.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(eR)[0]),i=e.content.match(tR)[0],a=iR(e,t,e=>e.type===`text`&&nR.test(e.value)).filter(e=>i===(e.value??``).toString().match(tR)[0]).map(e=>(e.value??``).toString().match(eR)[0]),o=a.reduce((e,t)=>{let n=t.match(rR)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=oR(a.map(e=>parseInt(e)));return[`up`,`left`].includes(n)&&a.length===1&&(c=-c),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:c,numberPostfixLength:s}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&zu(e,{locale:V}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&zu(e,{locale:V}).type===`number`&&!!e.format&&Rl(e.format),generateRule:(e,t)=>{let n=cR(iR(e,t,e=>e.type===`number`&&!!e.format&&Rl(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=zu(e,{locale:V});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&zu(e,{locale:V}).type===`number`,generateRule:(e,t,n)=>{let r=iR(e,t,e=>e.type===`number`&&!Rl(e.format||``)).map(e=>Number(e.value)),i=oR(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=zu(e,{locale:V});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function lR(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=P.fromTimestamp(e[n-1].getTime()),i=wa(r,t),a=Sa(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:Ca(r,t)}}).slice(1)}var uR=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=QL.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},dR=class extends XL{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:S(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:S(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(D({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=E(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(D({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:cn(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(yn),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=cn(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(Fn(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=$L.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=sn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)??void 0;t.push({data:{...e,border:r},rule:n})}return new uR(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e,{x:a,y:o,width:s,height:c}=r.getVisibleRect(i,this.autofillZone);s>0&&c>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(a,o,s,c),t.setLineDash([]))}},fR=class extends XL{static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=Fn(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||Rn(kn(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,kn(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=C(n,-1,-1),a=Vt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=rt(i.filter(e=>this.isNumber(r[e])))[0]||[];return Vt(o)<a?1/0:Ht(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&Rl(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return Rn(t)?(n.add(Ln(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},Bn(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},Bn(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}},pR=class extends XL{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(_u.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(hR(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)try{return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}catch(e){if(F(e)||e instanceof N)return;throw e}}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)try{return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}catch(e){if(F(e)||e instanceof N)return;throw e}}computeTableStyle(e,t){return xt(()=>{let n=this.getters.getTableStyle(t.config.styleId),r=this.getTableMetaData(e,t);if(!r)return{borders:{},styles:{}};let{tableMetaData:i,config:a}=r,o=jM(a,n,i),s=this.getTableMapping(e,t),c={borders:{},styles:{}};for(let e=0;e<i.numberOfCols;e++){let t=s.colMapping[e];c.borders[t]={},c.styles[t]={};for(let n=0;n<i.numberOfRows;n++){let r=s.rowMapping[n];c.borders[t][r]=o.borders[e][n],c.styles[t][r]=o.styles[e][n]}}return c})}getTableMetaData(e,t){let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t);if(!t.isPivotTable)return{tableMetaData:{numberOfCols:r,numberOfRows:i,mode:`table`},config:n};let a={sheetId:e,col:t.range.zone.left,row:t.range.zone.top},o=this.getters.getPivotStyleAtPosition(a);if(!o)throw Error(`No dynamic pivot info found at pivot table position`);let s=this.getters.getPivot(o.pivotId);if(!s.isValid())return;let c=o.pivotStyle,l=s.getExpandedTableStructure().getNumberOfRowGroupBys(),u=s.getCollapsedTableStructure(),d=u.getPivotCells(c),f=new Set,p=new Set,m=new Set,h=u.getNumberOfRowGroupBys();if(c.tabularForm){let n=0;for(let r=0;r<h;r++){if(this.getters.isColHidden(e,r+t.range.zone.left)){n++;continue}r===0&&l>1?f.add(0):r%2==1?p.add(r-n):r%2==0&&m.add(r-n)}}else{let n=0;for(let r=0;r<d[0].length;r++){if(this.getters.isRowHidden(e,r+t.range.zone.top)){n++;continue}let i=d[0][r];i.type!==`HEADER`||i.domain.length===0||(i.domain.length===1&&l>1?f.add(r-n):i.domain.length%2==0&&l>i.domain.length?p.add(r-n):i.domain.length%2==1&&l>i.domain.length&&m.add(r-n))}}return{tableMetaData:{mode:`pivot`,numberOfCols:r,numberOfRows:i,mainSubHeaderRows:f,firstAlternatingSubHeaderIndexes:p,secondAlternatingSubHeaderIndexes:m,measureRow:n.numberOfHeaders&&c.displayMeasuresRow&&!this.getters.isRowHidden(e,n.numberOfHeaders-1+t.range.zone.top)?n.numberOfHeaders-1:void 0,isTabular:c.tabularForm},config:n}}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let mR=new Set([`HIDE_COLUMNS_ROWS`,`UNHIDE_COLUMNS_ROWS`,`UNFOLD_HEADER_GROUP`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`FOLD_ALL_HEADER_GROUPS`,`UNFOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`CREATE_TABLE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`REMOVE_TABLE`,`RESIZE_TABLE`,`CREATE_TABLE_STYLE`,`REMOVE_TABLE_STYLE`,`DELETE_CONTENT`]);function hR(e){return mR.has(e.type)}var gR=class extends XL{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new aN;borders=new aN;handle(e){if(_u.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles=new aN,this.borders=new aN;return}if(hR(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new aN,this.borders=new aN);return}if(bu.has(e.type)){this.styles=new aN;return}if(xu.has(e.type)){this.borders=new aN;return}}getCellComputedBorder(e){let t=this.borders.get(e);return t===void 0&&(t=this.computeCellBorder(e),this.borders.set(e,t)),t}getCellComputedStyle(e){let t=this.styles.get(e);return t===void 0&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellStyle(e){let t=this.getters.getEvaluatedCell(e),n=this.getComputedStyle(e);return t.link&&!n.textColor&&(n.textColor=ce),n}getComputedStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e);return{...Dt(r),...Dt(i),...Dt(t?.style),...Dt(n)}}exportForExcel(e){for(let t of e.sheets){let n={},r=[];for(let e in t.cells){let i={sheetId:t.id,...sn(e)},a=this.getters.getEvaluatedCell(i),o=this.getComputedStyle(i);if(!a.link||o.textColor)continue;let s=Object.keys(t.styles).find(t=>In(yn(e),yn(t)));s?(n[s]||(n[s]=[]),n[s].push(e)):r.push(e)}for(let[r,i]of Object.entries(n)){let n=t.styles[r];if(e.styles[n].textColor)continue;let a=e.styles[n],o=i.map(yn),s=cn([yn(r)],o);delete t.styles[r];for(let e of s)t.styles[wn(e)]=n;let c=cd({...a,textColor:ce},e.styles);for(let e of i)t.styles[e]=c}for(let n of r){let r=this.getters.getCell({sheetId:t.id,...sn(n)});t.styles[n]=cd({...r?.style,textColor:ce},e.styles)}}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...Dt(this.getters.getCellTableBorder(e)||{}),...Dt(t)};return gt(n)?null:n}},_R=class extends XL{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}};function vR(e){let t=lc.get(e.type)?.(e),n=xR(e);if(!t&&!n)return;let r=t||bR(),i=n||(e=>e),a=yR(r.applyChange);return{applyChange:a,adaptRangeString:(e,t)=>Ec(e,t,r),adaptFormulaString:(e,t)=>wc(e,t,r,i),adaptCompiledFormula:e=>e.adaptCompiledFormula(a,i)}}function yR(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!Sn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}function bR(){return{applyChange:e=>({changeType:`NONE`,range:e}),sheetId:`ignoredSheetId`,sheetName:{old:`ignoredSheetName`,current:`ignoredSheetName`}}}function xR(e){if(e.type!==`UPDATE_NAMED_RANGE`)return;let t=e.oldRangeName.toLowerCase();return n=>n.toLowerCase()===t?e.newRangeName:n}let SR=new class extends A{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},CR=new class extends A{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};SR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],IR),SR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],IR),SR.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],DR),SR.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],OR),SR.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],kR),SR.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],AR),SR.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],jR),SR.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],MR),SR.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],NR),SR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],NR),SR.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],PR),SR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],PR),SR.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],FR),SR.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],LR),SR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],LR),SR.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],ER),SR.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],TR),SR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],wR),SR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],wR),SR.addTransformation(`UPDATE_NAMED_RANGE`,[`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`],RR);function wR(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=sr(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function TR(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function ER(e,t){if(e.pivotId!==t.pivotId)return e}function DR(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function OR(e,t){if(e.figureId!==t.figureId)return e}function kR(e,t){if(e.chartId!==t.chartId)return e}function AR(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function jR(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function MR(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!Nn(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function NR(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function PR(e,t){if(e.sheetId!==t.sheetId)return e;let n=sr(e.zone,t);if(!n)return;let r=e.newTableRange?cr(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function FR(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:WS.styleId}}:e}function IR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=yc(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=vc(Ct(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function LR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=C(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=yc(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=vc(Ct(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function RR(e,t){return t.newRangeName===t.oldRangeName?e:e.type===`DELETE_NAMED_RANGE`&&e.name===t.oldRangeName?{...e,name:t.newRangeName}:e.type===`UPDATE_NAMED_RANGE`&&e.oldRangeName===t.oldRangeName?{...e,oldRangeName:t.newRangeName}:e}function zR(e,{adaptFormulaString:t}){let n=e.content&&t(e.sheetId,e.content);return{...e,content:n}}CR.add(`UPDATE_CELL`,zR);function BR(e,{adaptRangeString:t,adaptFormulaString:n}){let r=e.cf.rule;if(e={...e,cf:{...e.cf}},r.type===`CellIsRule`)e.cf.rule={...r,values:r.values.map(t=>n(e.sheetId,t))};else if(r.type===`ColorScaleRule`){let{minimum:t,maximum:i,midpoint:a}=r;e.cf.rule={...r,minimum:{...t,value:t.value&&n(e.sheetId,t.value)},maximum:{...i,value:i.value&&n(e.sheetId,i.value)},midpoint:a?{...a,value:n(e.sheetId,a.value)}:void 0}}else if(r.type===`IconSetRule`){let{upperInflectionPoint:t,lowerInflectionPoint:i}=r;e.cf.rule={...r,upperInflectionPoint:{...t,value:n(e.sheetId,t.value)},lowerInflectionPoint:{...i,value:n(e.sheetId,i.value)}}}else r.type===`DataBarRule`&&(e.cf.rule={...r,rangeValues:r.rangeValues?t(e.sheetId,r.rangeValues).range:void 0});return e}CR.add(`ADD_CONDITIONAL_FORMAT`,BR);function VR(e,{adaptFormulaString:t}){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>t(e.sheetId,n)),e}CR.add(`ADD_DATA_VALIDATION_RULE`,VR);function HR(e,{adaptFormulaString:t}){return e=x(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=t(e.computedBy.sheetId,e.computedBy.formula))}),e}CR.add(`ADD_PIVOT`,HR),CR.add(`UPDATE_PIVOT`,HR),CR.add(`CREATE_CHART`,UR),CR.add(`UPDATE_CHART`,UR);function UR(e,t){return{...e,definition:CO.transformDefinition(e.sheetId,e.definition,t)}}let WR=[{match:du,fn:YR},{match:pu,fn:XR},{match:gu,fn:ZR},{match:hu,fn:ez},{match:fu,fn:$R},{match:mu,fn:QR}];function GR(e,t){let n=SR.getTransformation(e.type,t.type),r=n?n(e,t):JR(e,t);return r&&KR(r,t)}function KR(e,t){let n=CR.get(e.type);if(!n)return e;let r=vR(t);return r?n(e,r):e}function qR(e,t){let n=[...e],r=new Set(SR.getKeys());for(let e of t)(r.has(e.type)||lc.contains(e.type))&&(n=n.reduce((t,n)=>{let r=GR(n,e);return r&&t.push(r),t},[]));return n}function JR(e,t){for(let{match:n,fn:r}of WR)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function YR(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId,r=t.type===`LOCK_SHEET`&&t.sheetId;return e.sheetId===n||e.sheetId===r?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function XR(e,t){let n=YR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=sr(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function ZR(e,t){let n=YR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=sr(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function QR(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>cr(e,t)).filter(w);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function $R(e,t){let n=YR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=yc(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=vc(Ct(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function ez(e,t){let n=YR(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?tz(e,t):t.type===`ADD_MERGE`?nz(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function tz(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function nz(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&Fn(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var rz=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},iz=class extends Error{},az=class extends lr{revisions;transportService;serverRevisionId;commandSquisher;shouldVerifySquish;clients={};clientId=`local`;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Bd;lastLocalOperation;constructor(e,t,n=ke,r,i=!0){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.commandSquisher=r,this.shouldVerifySquish=i}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new rz(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&=(this.move(this.awaitingClientPosition),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),await this.sendToTransport({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new iz(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(w))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.sendToTransport({type:n,version:1,client:{...r,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,timestamp:n}=e,r=this.commandSquisher.unsquish(e.commands),i=new rz(e.nextRevisionId,t,r,void 0,void 0,n);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:qR(r,t)})}break;case`SNAPSHOT_CREATED`:{let t=new rz(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.sendToTransport({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}async sendToTransport(e){return this.transportService.sendMessage(e)}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId));let n=this.commandSquisher.squish(t.commands);e=n.some(e=>e.type===`SQUISHED_UPDATE_CELL`)?this.shouldVerifySquish&&!T(t.commands,this.commandSquisher.unsquish(n))?{...e,commands:t.commands,squishedFailed:!0}:{...e,commands:n}:{...e,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
|
|
117
117
|
${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof iz))throw e.cause||e;this.waitingAck=!1})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}},oz=class extends XL{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new fi(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map(e=>({...e,color:this.colors.get(e.id)}))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(e){try{this.getters.getCurrentClient()}catch(e){if(e instanceof iz)return[];throw e}let t=[];for(let n of this.getters.getConnectedClients())n.id!==this.getters.getCurrentClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)&&t.push({...n,position:n.position});return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e;for(let e of this.getClientsToDisplay(i)){let{row:a,col:o}=e.position,s=this.getters.expandZone(i,{top:a,bottom:a,left:o,right:o}),{x:c,y:l,width:u,height:d}=r.getVisibleRect(i,s);if(u<=0||d<=0)continue;let f=e.color;t.fillStyle=`${f}10`,t.lineWidth=4*n,t.strokeStyle=f,t.globalCompositeOperation=`multiply`,t.fillRect(c,l,u,d),t.globalCompositeOperation=`source-over`,t.strokeRect(c,l,u,d),t.font=`bold ${Ee+1}px ${De}`}}},sz=class extends XL{handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of ac(t)){let t=this.getters.getCell(e),n=this.getters.getEvaluatedCell(e);if(!t?.isFormula&&!t?.content)this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`});else if((t?.isFormula||t?.content)&&n.type===`empty`){let n;if(t.isFormula){let r=this.getters.evaluateCompiledFormula(e.sheetId,t.compiledFormula);n=(Je(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!at(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},cz=class extends XL{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},lz=class extends XL{handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let a=n.top;a<=n.bottom;a++){let n={sheetId:e,col:t,row:a},o=this.getters.getPivotCellFromPosition(n);if(this.isSpilledPivotValueFormula(n,o)){r.push(n);let e=this.getters.getPivotIdFromPosition(n)||``;i[e]??=new Set,i[e].add(o.measure)}}let a=cn(r.map(D));for(let e in i){let t=i[e],r=this.getters.getPivotCoreDefinition(e);this.dispatch(`UPDATE_PIVOT`,{pivotId:e,pivot:{...r,measures:r.measures.map(e=>t.has(e.id)?{...e,format:n}:e)}})}this.dispatch(`SET_FORMATTING`,{sheetId:e,target:a,format:``}),this.dispatch(`SET_FORMATTING`,{sheetId:e,target:cn(t,a),format:n})}isSpilledPivotValueFormula(e,t){let n=this.getters.getCell(e);return t.type===`VALUE`&&!n?.isFormula}setDecimal(e,t,n){let r={};for(let i of cn(t))for(let t of Bn(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=tu(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=cn(r[t].map(e=>D(e)));this.setContextualFormat(e,n,t)}}getCellNumberFormat(e){for(let t of[e]){let e=this.getters.getEvaluatedCell(t);if(e.type===`number`&&!(e.format&&Rl(e.format)))return e.format||Hl(e.value)}}},uz=class extends XL{static getters=[`getGeoJsonFeatures`,`geoFeatureNameToId`,`getGeoChartAvailableRegions`,`getAvailableChartRegions`];geoJsonService;geoJsonCache={};initialRegions={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.trackInitialRegion(t);break;case`CREATE_CHART`:this.trackInitialRegion(e.chartId);break;case`UPDATE_CHART_REGION`:{let t=this.getters.getChart(e.chartId),n=this.getters.getChartDefinition(e.chartId);if(!t||n.type!==`geo`)break;this.dispatch(`UPDATE_CHART`,{chartId:e.chartId,sheetId:t.sheetId,figureId:this.getters.getFigureIdFromChartId(e.chartId),definition:{...n,region:e.region}});break}}}trackInitialRegion(e){let t=this.getters.getChartDefinition(e);if(t?.type===`geo`){let n=this.getGeoChartAvailableRegions();this.initialRegions[e]=t.region||n[0]?.id||``}}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error(`No geoJsonService provided to the model`),[])}getAvailableChartRegions(e){if(!this.geoJsonService)return[];let t=this.getters.getChartDefinition(e);if(!t||t.type!==`geo`)return[];let n=this.initialRegions[e];return n&&this.geoJsonService.getAlternativeRegions?.(n)||[]}getGeoJsonFeatures(e){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}let t=this.geoJsonCache[e];if(!(t instanceof Promise)){if(t!==void 0)return t??void 0;this.geoJsonCache[e]=new Promise(async t=>{let n=await this.geoJsonService?.getTopoJson(e);this.geoJsonCache[e]=this.convertToGeoJson(n),this.dispatch(`EVALUATE_CHARTS`),t()})}}geoFeatureNameToId(e,t){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}return this.geoJsonService.geoFeatureNameToId(e,t)}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){let t=globalThis.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return t.type===`FeatureCollection`?t.features:[t]}else if(e.type===`FeatureCollection`)return e.features;throw Error(`Invalid TopoJSON`)}},dz=class extends XL{static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1)||this.findVisibleHeader(e,`COL`,t,0)||0,row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)||this.findVisibleHeader(e,`ROW`,n,0)||0}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return C(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},fz=class extends XL{static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return`PivotIdNotFound`;if(!this.getters.getPivot(e.pivotId).isValid())return`PivotInError`;break}return`Success`}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){Xn(this.getters.getSelectedZone())===1&&this.selection.selectTableAroundSelection();let n=this.getters.getActiveSheetId();this.dispatch(`ADD_PIVOT`,{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:n},columns:[],rows:[],measures:[],name:j(`New pivot`),type:`SPREADSHEET`,style:{tableStyleId:Ve}}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:j(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getCollapsedTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:j(`%s (copy)`,this.getters.getPivotCoreDefinition(e).name)});let r=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(r)+1,a=this.getters.getPivotFormulaId(t),o=this.getters.getPivotName(t);if(this.dispatch(`CREATE_SHEET`,{sheetId:n,name:this.getPivotDuplicateSheetName(j(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getCollapsedTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return Kt(nt(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new Fj(o,s,c,l||{}),d=u.columns.length-1;if(this.resizeSheet(e,t,n,u),a===`dynamic`)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${this.getters.getPivotFormulaId(r)})`});else{this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()});let i={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length};this.dispatch(`CREATE_TABLE`,{tableType:`static`,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,i)],config:{...Be,numberOfHeaders:d}})}}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i={sheetId:e,col:t,row:n},a=this.getters.getSpreadZone(i),o=this.getters.getTable(i);if(!a)return;let s=this.getters.getPivotFormulaId(r),c=this.getters.getPivotStyleAtPosition(i);if(!c)return;let l={...c.pivotStyle,tabularForm:!1},u=this.getters.getPivot(r).getCollapsedTableStructure(),d=u.getPivotCells(l),{numberOfCols:f,numberOfRows:p}=u.getPivotTableDimensions(l);if(!(p===0||f===0)){for(let t of C(0,f))for(let n of C(0,p)){let r=d[t][n];if(r){let i={sheetId:e,col:a.left+t,row:a.top+n};this.dispatch(`UPDATE_CELL`,{...i,content:Ag(s,r)})}}if(this.getters.getCoreTable(i)&&this.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[D(i)]}),o?.isPivotTable){let t=this.getters.getRangeDataFromZone(e,{left:a.left,right:a.left+f-1,top:a.top,bottom:a.top+p-1});this.dispatch(`CREATE_TABLE`,{tableType:`static`,sheetId:e,ranges:[t],config:{...o.config,styleId:TM(o.config.styleId)}})}}}};let pz=new A,mz=new A;function hz(e,t){if(t&&pz.contains(t.type))return pz.get(t.type)(e,t)}function gz(e,t,n){if(mz.contains(t.type))return mz.get(t.type)(e,t,n)}function _z(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Eu(e.rootCommand)?pz.contains(e.rootCommand.type):mz.contains(e.rootCommand.type)}function vz(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Eu(e.rootCommand)?hz(t,e.rootCommand):gz(t,e.rootCommand,e.commands)}var yz=class extends XL{static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return`EmptyUndoStack`;break;case`REQUEST_REDO`:if(!this.canRedo())return`EmptyRedoStack`;break}return`Success`}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=vz(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:_z(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},bz=class extends XL{static getters=[`isCurrentSheetLocked`];allowDispatch(e){return wu.has(e.type)||this.getters.isDashboard()?`Success`:`sheetId`in e&&this.getters.isSheetLocked(e.sheetId)||!Eu(e)&&this.isCurrentSheetLocked()?`SheetLocked`:`Success`}isCurrentSheetLocked(){return this.getters.isSheetLocked(this.getters.getActiveSheetId())}},xz=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,L(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},Sz=class extends XL{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new xz,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}};let Cz=[`number`,`error`,`text`,`boolean`];function wz(e){let t=e===`asc`?1:-1;return(e,n)=>{if(e.type===`empty`)return n.type===`empty`?0:1;if(n.type===`empty`)return-1;let r=Cz.indexOf(e.type)-Cz.indexOf(n.type);return r===0&&(r=e.type===`text`||e.type===`error`?e.value.localeCompare(n.value):e.value-n.value),t*r}}function Tz(e,t,n){let r=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(n?r.map(e=>e.type===`empty`?{...e,type:`number`,value:0}:e):r).sort(wz(t))}var Ez=class extends XL{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return Fn(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):`InvalidSortAnchor`}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&Bn(t).some(({col:t,row:n})=>!this.getters.isInMerge({sheetId:e,col:t,row:n}))?`InvalidSortZone`:`Success`}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return`Success`;let n=this.getters.getMerges(e).filter(e=>Nn(e,t)),r=Ln(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return Bn(t).some(({col:t,row:n})=>{let r=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:n});return r&&!T(r,{sheetId:e,col:t,row:n})})?`SortZoneWithArrayFormulas`:`Success`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=Tz(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula)}else e=s.content;p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=C(t.left,t.right+1,n),o=C(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},Dz=class extends XL{static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return`Success`}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===`text`){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
|
|
118
118
|
`,`;`,`,`,` `,`.`])if(e.includes(t))return t}splitIntoColumns({separator:e,addNewColumns:t}){let n=this.getters.getSelectedZone(),r=this.getters.getActiveSheetId(),i=this.getSplittedCols(n,e);t&&this.addColsToAvoidCollisions(n,i),this.removeMergesInSplitZone(n,i),this.addColumnsToNotOverflowSheet(n,i);for(let e=0;e<i.length;e++){let t=n.top+e,a=i[e],o=n.left,s=this.getters.getCell({sheetId:r,col:o,row:t});if(!(a.length===1&&!s?.isFormula&&a[0]===s?.content))for(let[e,n]of a.entries())this.dispatch(`UPDATE_CELL`,{sheetId:r,col:o+e,row:t,content:Yy(n,this.getters.getLocale()),format:``,style:s?.style||null})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of C(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of C(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i?.isFormula||i?.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of C(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i?.isFormula||i?.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},Oz=class extends XL{handle(e){Su.has(e.type)&&this.dispatch(`EVALUATE_CELLS`,{cellIds:this.getters.getCellsWithTrackedFormula(`SUBTOTAL`)})}},kz=class extends XL{handle(e){switch(e.type){case`AUTOFILL_TABLE_COLUMN`:let t=this.getters.getCoreTable(e),n=this.getters.getCell(e);if(!t?.config.automaticAutofill||t.type===`dynamic`||!n?.isFormula)return;let{col:r,row:i}=e,a=DM(t.range.zone,t.config);if(a&&Fn(r,i,a)){let t=e.autofillRowStart??a.top,n=e.autofillRowEnd??a.bottom,r={...a,top:t,bottom:n};this.autofillTableZone(e,r)}break}}autofillTableZone(e,t){if(t.top===t.bottom)return;let{col:n,row:r,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==r&&this.getters.getEvaluatedCell({col:n,row:e,sheetId:i}).type!==`empty`)return;let a={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.bottom}),this.dispatch(`AUTOFILL`),this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.top}),this.dispatch(`AUTOFILL`),this.selection.selectZone(a)}},Az=class extends XL{allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t)return;let n=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(n.right,n.bottom),!t.config.automaticAutofill)return;let r=t.range.zone;if(n.bottom>=r.bottom){for(let t=n.left;t<=n.right;t++){let i={col:t,row:r.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.isFormula&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:r.bottom,autofillRowEnd:n.bottom})}break}}}}},jz=class extends XL{static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},Mz=class extends XL{static getters=[`getCellWidth`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getMultilineTextSize`,`getContiguousZone`,`computeTextYCoordinate`];ctx=_d();allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case`AUTORESIZE_COLUMNS`:for(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break;case`DELETE_UNFILTERED_CONTENT`:let t=[];for(let n of e.target){let r=rt(C(n.top,n.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(let e of r)t.push({...n,top:e[0],bottom:e[e.length-1]})}this.dispatch(`DELETE_CONTENT`,{sheetId:e.sheetId,target:t});break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=jd(this.ctx,r,t,void 0);n+=xd(this.ctx,e,t).width}for(let t of this.getters.getCellIcons(e))n+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(n+=10),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(e.sheetId,e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return Sd(this.ctx,e,t)}getMultilineTextSize(e,t){return xd(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula){if(n?.isFormula)return eb(n.compiledFormula.toFormulaString(this.getters),r);if(!n?.content)return``}let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>Sd(this.ctx,e,n?.style||{})}:void 0;return H(i.value,{format:i.format,locale:r,formatWidth:a})}getCellMultiLineText(e,t){let n=this.getters.getCellStyle(e),r=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return jd(this.ctx,r,n,t.wrapWidth)}computeTextYCoordinate(e,t,n=we,r=1){let i=e.y+1,a=gd(t,r);if(e.height>a+8){if(n===`middle`)return Math.ceil(i+(e.height-a)/2);if(n===`bottom`)return i+e.height-a-4}return i+4}getContiguousZone(e,t){let n=t=>{for(let n of C(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of C(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);Mn(i,e)||(r=!0,i=e)}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=Bn(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,Vt(n))}checkSheetExists(e){return`sheetId`in e&&this.getters.tryGetSheet(e.sheetId)===void 0&&e.type!==`CREATE_SHEET`?`InvalidSheetId`:`Success`}checkZonesAreInSheet(e){let t=`sheetId`in e?e.sheetId:this.getters.tryGetActiveSheetId();if(`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return`InvalidSheetId`;let n=this.getters.getCommandZones(e);return!t&&n.length>0?`NoActiveSheet`:t&&n.length>0?this.getters.checkZonesExistInSheet(t,n):`Success`}autoResizeRows(e,t){let n=[];for(let r of t){let t=0;for(let n of this.getters.getRowCellIds(e,r)){let r=this.getters.getCellById(n);if(!r)continue;let i=this.getters.getCellPosition(r.id),a=this.getters.getColSize(e,i.col);if(r.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){let e=this.getters.getEvaluatedCell(i).formattedValue,n=yd(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=yd(this.ctx,e,r?.style,a);n>=t&&n>23&&(t=0)}}n.push(t||null)}let r=new Map(n.map(e=>[e,[]]));for(let e=0;e<n.length;e++)r.get(n[e])?.push(t[e]);for(let[t,n]of r)this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:n,dimension:`ROW`,size:t,sheetId:e})}},Nz=class extends XL{static getters=[`getSelectedCarouselItem`,`getChartFromFigureId`,`getChartIdFromFigureId`];uuidGenerator=new Bd;carouselStates={};allowDispatch(e){switch(e.type){case`ADD_FIGURE_CHART_TO_CAROUSEL`:return!this.getters.doesCarouselExist(e.carouselFigureId)||this.getters.getFigure(e.sheetId,e.chartFigureId)?.tag!==`chart`?`InvalidFigureId`:`Success`;case`DUPLICATE_CAROUSEL_CHART`:return!this.getters.doesCarouselExist(e.carouselId)||!this.getters.getCarousel(e.carouselId).items.some(t=>t.type===`chart`&&t.chartId===e.chartId)||this.getters.getChart(e.duplicatedChartId)?`InvalidFigureId`:`Success`;case`ADD_NEW_CHART_TO_CAROUSEL`:return this.getters.doesCarouselExist(e.figureId)?`Success`:`InvalidFigureId`;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:return this.getters.doesCarouselExist(e.figureId)?this.getters.getCarousel(e.figureId).items.some(t=>T(t,e.item))?`Success`:`InvalidCarouselItem`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`ADD_NEW_CHART_TO_CAROUSEL`:this.addNewChartToCarousel(e.figureId,e.sheetId);break;case`ADD_FIGURE_CHART_TO_CAROUSEL`:this.addFigureChartToCarousel(e.carouselFigureId,e.chartFigureId,e.sheetId);break;case`DUPLICATE_CAROUSEL_CHART`:this.duplicateCarouselChart(e);break;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:this.carouselStates[e.figureId]=this.getCarouselItemId(e.item);break;case`POPOUT_CHART_FROM_CAROUSEL`:this.popOutChartFromCarousel(e.carouselId,e.chartId,e.sheetId);break;case`DELETE_FIGURE`:delete this.carouselStates[e.figureId];break;case`UPDATE_CAROUSEL`:this.fixWrongCarouselState(e.figureId);break;case`DELETE_CHART`:case`UNDO`:case`REDO`:case`DELETE_SHEET`:for(let e in this.carouselStates)this.fixWrongCarouselState(e);break}}popOutChartFromCarousel(e,t,n){let r=this.getters.getCarousel(e);if(!r)return;let i=this.getters.getFigure(n,e),a=this.getters.getChartDefinition(t);if(!a||!i)return;let o=this.getters.getFigureUI(n,i),s=this.getters.getPositionAnchorOffset({x:o.x+50,y:o.y+50}),c=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{...s,chartId:this.uuidGenerator.smallUuid(),figureId:c,sheetId:n,size:{width:i.width,height:i.height},definition:{...a}});let l=r.items.filter(e=>e.type!==`chart`||e.chartId!==t);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...r,items:l}}),this.dispatch(`SELECT_FIGURE`,{figureId:c})}getSelectedCarouselItem(e){let t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;let t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){let t=this.getters.getFigureSheetId(e);if(!t)return;let n=this.getters.getFigure(t,e);if(!(!n||n.tag!==`chart`&&n.tag!==`carousel`)){if(n.tag===`carousel`){let t=this.getSelectedCarouselItem(e);return t?.type===`chart`?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e)){delete this.carouselStates[e];return}let t=this.getters.getCarousel(e);t.items.length===0?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){let n=this.getters.getCarousel(e),r=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:t,definition:qv});let i={...n,items:[...n.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:t,figureId:e,definition:i})}addFigureChartToCarousel(e,t,n){let r=this.getChartIdFromFigureId(t);if(!r)return;let i=this.getters.getCarousel(e),a={...i,items:[...i.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:a}),this.dispatch(`UPDATE_CHART`,{sheetId:n,chartId:r,figureId:e,definition:this.getters.getChartDefinition(r)}),this.dispatch(`DELETE_FIGURE`,{sheetId:n,figureId:t})}duplicateCarouselChart({carouselId:e,chartId:t,sheetId:n,duplicatedChartId:r}){let i=this.getters.getChart(t);if(!i)return;let a=this.getters.getCarousel(e),o=a.items.findIndex(e=>e.type===`chart`&&e.chartId===t);if(o===-1)return;this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:n,definition:i.getDefinition()});let s=It(a.items,[{type:`chart`,chartId:r}],o+1);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...a,items:s}})}getCarouselItemId(e){return e.type===`chart`?e.chartId:`carouselDataView`}};async function Pz(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{let e=document.createElement(`canvas`);e.width=r.width,e.height=r.height,e.getContext(`2d`)?.drawImage(r,0,0),e.toBlob(t,`image/png`)}),r.addEventListener(`error`,n),r.src=e})}var Fz=class extends XL{static layers=[`Clipboard`];static getters=[`getClipboardTextAndImageContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new Bd().uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new Bd}allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;let t=this.getters.getSelectedZone(),n=this.getCopiedDataAbove(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;let t=this.getters.getSelectedZone(),n=this.getCopiedDataOnLeft(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`COPY_PASTE_CELLS_ON_ZONE`:{let e=this.getters.getSelectedZones();if(e.length>1)return`InvalidCopyPasteSelection`;let t=this.getters.getSelectedZone(),n=this.getCopiedDataOnLeft(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation=e.type===`CUT`,this.copiedData=this.copy(t);break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;if(t.data?.version!==YC()&&(t={...t},delete t.data),t.imageData){let n=this.getters.getActiveSheetId(),r=this.uuidGenerator.uuidv4(),i=t.imageData,a=Lv(this.getters,i.size);this.dispatch(`CREATE_IMAGE`,{definition:i,size:a,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:n,figureId:r})}t.data?this.copiedData=t.data:this.copiedData=this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`,this.copiedData=void 0;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataAbove(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataOnLeft(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_ZONE`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataAboveOnLeft(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Sn(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:Eu(e)&&(this.status=`invisible`)}}getCopiedDataAbove(e){let t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};return this.copy([n])}getCopiedDataOnLeft(e){let t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};return this.copy([n])}getCopiedDataAboveOnLeft(e){let t={...e,right:e.left,bottom:e.top};return this.copy([t])}convertTextToClipboardData(e){let t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),n={};for(let{handlerName:r,handler:i}of t){let t=i.convertTextToClipboardData(e);n[r]=t;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])t&&e in t&&(n[e]=t[e])}return n}selectClipboardHandlers(e){let t=`figureId`in e?UF.figureHandlers:UF.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,this._isCutOperation,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=nE(r,e,t,i,n);o!==void 0&&this.addMissingDimensions(r,o.right-o.left+1,o.bottom-o.top+1,o.left,o.top),tE(i,t,a,n),n?.selectTarget&&rE(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){let e=await this.getImageContent(),t=e?.type,n={"text/plain":``,"text/html":``};try{n[`text/plain`]=this.getPlainTextContent(),n[`text/html`]=await this.getHTMLContent()}catch{this.ui.notifyUI({type:`danger`,text:`Your selection was too large for the browser to copy it.
|
|
119
119
|
Please select a smaller zone.`,sticky:!0})}return t&&e&&(n[t]=e),n}getSheetData(){let e={version:YC()};return this.copiedData&&`figureId`in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map(e=>e.map(e=>this.getters.shouldShowFormulas()&&e?.compiledFormula?e?.content||``:e.evaluatedCell?.formattedValue||``).join(` `)).join(`
|
|
@@ -953,4 +953,4 @@ If you meant to create a named range, named range cannot have the same name as a
|
|
|
953
953
|
<Relationships xmlns="${rf.Relationships}">
|
|
954
954
|
<Relationship ${q(e)} />
|
|
955
955
|
</Relationships>
|
|
956
|
-
`),`_rels/.rels`)}function XU(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=Kt(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${Ze(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function ZU(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>Ln(yn(e.range)).numberOfRows>1);return e}var QU=class e extends lr{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=new Bd,i=!1){let a=performance.now();console.debug(`##### Model creation #####`),super(),Mi(),n=ow(e,n);let o=QC(e,i);this.state=new dH,this.uuidGenerator=r,this.config=this.setupConfig(t),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.session=this.setupSession(o.revisionId),this.coreGetters={},this.range=new cH(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.selection=new uH(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of Uz.getAll())this.setupCorePlugin(e,o);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of Kz.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of Gz.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of Wz.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.config.mode!==`export_verification`&&(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly())){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}console.debug(`Model created in`,performance.now()-a,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:xt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new az(aH({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowedRemoteCommand(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e,new XV(this.getters))}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:j(`Anonymous`).toString()},n=e.transportService||new tV,r=e.mode===`readonly`||e.mode===`dashboard`||e.mode===`export_verification`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new ZV(n):n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Ro));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=Eu(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==`Success`)?new Ou(e.flat()):Ou.Success}checkDispatchAllowedRemoteCommand(e){let t=this.coreHandlers.map(t=>t.allowDispatch(e));return this.processCommandResults(t)}checkDispatchAllowedCoreCommand(e){return this.handlers.map(t=>t.allowDispatch(e))}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed($U(e,t));dispatch=(e,t)=>{let n=$U(e,t),r=this.status;if(this.getters.isReadonly()&&!Du(n))return new Ou(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Ou(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),this.trigger(`command-rejected`,{command:n,result:t}),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();Eu(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(Eu(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(Eu(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Ou.Success};dispatchFromCorePlugin=(e,t)=>{let n=$U(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Ou.Success};dispatchToHandlers(e,t){let n=Eu(t);for(let r of e)!n&&r instanceof EI||r.beforeHandle(t);for(let r of e)!n&&r instanceof EI||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let t=this._exportData(!0),n=this._exportData(!1),r={...this.config,mode:`export_verification`,client:{id:`exporter`,name:`exporter`},snapshotRequested:!1,transportService:new tV};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=pw();for(let n of this.handlers)n instanceof EI&&n.export(t,e);return t.revisionId=this.session.getRevisionId()||`START_REVISION`,t=x(t),t}updateMode(e){this.config.mode=e,this.trigger(`update`)}async exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=hw();for(let t of this.handlers)t instanceof TI&&await t.exportForExcel(e);return e=x(e),VU(e)}};function $U(e,t={}){let n=x(t);return n.type=e,n}function eW(e){return!MO.includes(e.horizontalGroupBy)||!MO.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}let tW={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,eW)},fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){let n=`left`;return e.legendPosition===`right`&&(n=`right`),{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},title:e.title||{text:``},type:`calendar`,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:n,horizontalGroupBy:`day_of_week`,verticalGroupBy:`month_number`}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n}){let r=a_(t,n(),e),{labels:i,datasets:a}=gp(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...sh,indexAxis:`x`,layout:L_(t,r),scales:Qf(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:sv(t,r),chartShowValuesPlugin:Z_(t,r),chartColorScalePlugin:$f(t,r),background:{color:t.background}}}}}}},nW={sequence:15,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`aggregated`,`axesDesign`,`showValues`,`hideDataMarkers`,`zoomable`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t)}},getDefinitionFromContextCreation(e,t){let n=e.dataSetStyles??{};if(e.dataSource?.type===`range`){let t=e.dataSource?.dataSets?.[0]?.dataSetId;for(let r of e.dataSource?.dataSets||[])n[r.dataSetId]={...e.dataSetStyles?.[r.dataSetId]||{},type:r.dataSetId===t?`bar`:`line`}}return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:n,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}},getRuntime(e,t,{extractData:n},r,i){let a=n_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:xp(t,a)},options:{...sh,layout:I_(t,a),scales:Zf(t,a),plugins:{title:nv(t,e),legend:U_(t,a),tooltip:ov(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},rW={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`dataSetStyles`,`axesDesign`,`legendPosition`,`horizontal`,`aggregated`,`showValues`,`funnelColors`,`cumulative`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative??!0,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=d_(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:wp(t,a)},options:{...sh,indexAxis:`y`,layout:I_(t,a),scales:cp(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:mv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}}}}},iW={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`colorScale`,`missingValueColor`,`region`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=u_(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:Cp(t,a)},options:{...sh,layout:I_(t,a),scales:sp(t,a),plugins:{title:nv(t,e),tooltip:pv(t,a),legend:{display:!1},background:{color:t.background}},...i}}}}},aW={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`axesDesign`,`stacked`,`horizontal`],fromStrDefinition:e=>({...e,horizontal:!0,stacked:!0}),toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){if(t.dataSource.type!==`range`)return;let{dataSetsValues:i}=o_(t,DO(e,t.dataSource),e),a=Math.max(...i.map(e=>Math.max(...e.data.map(e=>U(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t),maxValue:a}},getRuntime(e,t,{extractData:n},r,i){let a=o_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:hp(t,a)},options:{...sh,indexAxis:`y`,layout:I_(t,a),scales:ap(t,a),plugins:{title:nv(t,e),legend:z_(t,a),tooltip:dv(t,a),chartShowValuesPlugin:$_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},oW={sequence:80,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`stacked`,`fillArea`,`hideDataMarkers`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=l_(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:Sp(t,a)},options:{...sh,layout:I_(t,a),scales:op(t,a),plugins:{title:nv(t,e),legend:G_(t,a),tooltip:fv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},sW={sequence:60,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`labelsAsText`,`aggregated`,`axesDesign`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t)}},getRuntime(e,t,{extractData:n},r,i){let a=s_(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:yp(t,a)},options:{...sh,layout:I_(t,a),scales:rp(t,a),plugins:{title:nv(t,e),legend:H_(t,a),tooltip:cv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},cW={sequence:30,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`showLabels`,`valuesDesign`,`groupColors`,`pieHolePercentage`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize,pieHolePercentage:e.pieHolePercentage}},getContextCreation(e,t,n){return{...e,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=f_(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:Ep(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...sh,layout:I_(t,a),plugins:{title:nv(t,e),legend:K_(t,a),tooltip:hv(t,a),sunburstLabelsPlugin:Q_(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:t.background}},...i}}}}},lW={sequence:100,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showHeaders`,`headerDesign`,`showLabels`,`valuesDesign`,`coloringOptions`,`showValues`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}},getContextCreation(e,t,n){return{...e,treemapColoringOptions:e.coloringOptions,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=f_(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:jp(t,a)},options:{...sh,layout:I_(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:gv(t,a),background:{color:t.background}},...i}}}}};dS.add(`bar`,xv),dS.add(`combo`,nW),dS.add(`line`,Mv),dS.add(`pie`,Nv),dS.add(`scorecard`,im),dS.add(`gauge`,Dv),dS.add(`scatter`,sW),dS.add(`waterfall`,Pv),dS.add(`pyramid`,aW),dS.add(`radar`,oW),dS.add(`geo`,iW),dS.add(`funnel`,rW),dS.add(`sunburst`,cW),dS.add(`treemap`,lW),dS.add(`calendar`,tW),Kv.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:j(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:j(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:j(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:j(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:j(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:j(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:j(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:j(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:j(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:j(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:j(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:j(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:j(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:j(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:j(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:j(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:j(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:j(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:j(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:j(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:j(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:j(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:j(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`});var uW=class extends JL{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(D(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=cn(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},dW=class extends qL{copy(e){}},fW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`carousel`)return;let r={...n},i=this.getters.getCarousel(e.figureId),a={};for(let e of i.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);a[e.chartId]=t}return{figureId:e.figureId,copiedFigure:r,copiedCarousel:i,copiedCharts:a,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:new Bd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=this.getters.getMaxAnchorOffset(a,s,o),{left:l,top:u}=r[0],d={x:0,y:0};l>c.col&&(l=c.col,d.x=c.offset.x),u>c.row&&(u=c.row,d.y=c.offset.y),this.dispatch(`CREATE_CAROUSEL`,{figureId:i,sheetId:a,definition:{items:[]},col:l,row:u,offset:d,size:{height:s,width:o}});let f=new Bd,p=x(t.copiedCarousel.items);for(let e of p){if(e.type!==`chart`)continue;let n=t.copiedCharts[e.chartId],r=f.smallUuid(),o=CO.fromDefinition(this.getters,a,n.copyInSheetId(a)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:i,chartId:r,sheetId:a,definition:o}),e.chartId=r}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:a,figureId:i,definition:{...t.copiedCarousel,items:p}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},pW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`chart`)return;let r={...n},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i;return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new Bd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart,l=CO.fromDefinition(this.getters,a,c.copyInSheetId(a)).getDefinition();l=CO.fromStrDefinition(this.getters,a,l).getDefinition();let u=this.getters.getMaxAnchorOffset(a,s,o),{left:d,top:f}=r[0],p={x:0,y:0};d>u.col&&(d=u.col,p.x=u.offset.x),f>u.row&&(f=u.row,p.y=u.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,chartId:new Bd().smallUuid(),sheetId:a,definition:l,col:d,row:f,offset:p,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},mW=class extends JL{uuidGenerator=new Bd;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=D(e.position),i=D(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&T(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&T(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},hW=class extends JL{uuidGenerator=new Bd;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=D(t),i=D(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>T(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>T(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=cn([...cn(r.ranges.map(e=>e.zone),n),...t],[]);if(i.length===0){this.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:r.id});continue}this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:{id:r.id,criterion:r.criterion,isBlocking:r.isBlocking},ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}},gW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=x(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new Bd().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=x(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},_W=class extends JL{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(w);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},vW=class extends JL{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},yW=class extends JL{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Qn(ZT(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},bW=class extends JL{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>In(f,e))){s.add(u.id);let{numberOfRows:e}=Ln(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}if(u.isPivotTable){let t=u.range.zone.top===e&&u.range.zone.left===c,n=o.some(e=>In(u.range.zone,e));(t||n)&&s.add(u.id)}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=Dt({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Dt(n)},border:{...r,...Dt(i)}}}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.tableCells,n)}pasteFromCut(e,t,n,r){for(let e of n.tableCells)for(let t of e)t.table&&this.dispatch(`REMOVE_TABLE`,{sheetId:n.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});let i=t[0];this.pasteZone(e,i.left,i.top,n.tableCells,r)}pasteZone(e,t,n,r,i){for(let a=0;a<r.length;a++){let o=r[a];for(let r=0;r<o.length;r++){let s=o[r];if(!s)continue;let c={col:t+r,row:n+a,sheetId:e};this.pasteTableCell(e,s,c,i)}}if(r.length===1)for(let i=0;i<r[0].length;i++)this.dispatch(`AUTOFILL_TABLE_COLUMN`,{col:t+i,row:n,sheetId:e})}pasteTableCell(e,t,n,r){if(t.table&&!r?.pasteOption){let{range:r}=t.table,i=Ln(this.getters.getRangeFromRangeData(r).zone),a={left:n.col,top:n.row,right:n.col+i.numberOfCols-1,bottom:n.row+i.numberOfRows-1};this.dispatch(`CREATE_TABLE`,{sheetId:n.sheetId,ranges:[this.getters.getRangeDataFromZone(e,a)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(n)||r?.pasteOption===`asValue`||(!r?.pasteOption&&!t.isWholeTableCopied||r?.pasteOption===`onlyFormat`)&&(t.style?.style&&this.dispatch(`UPDATE_CELL`,{...n,style:t.style.style}),t.style?.border&&this.dispatch(`SET_BORDER`,{...n,border:t.style.border}))}};UF.figureHandlers.add(`chart`,pW).add(`image`,gW).add(`carousel`,fW),UF.cellHandlers.add(`dataValidation`,hW).add(`cell`,YL).add(`sheet`,yW).add(`merge`,_W).add(`border`,uW).add(`table`,bW).add(`conditionalFormat`,mW).add(`references`,vW);var xW=l({ARRAYTOTEXT:()=>XW,ARRAY_CONSTRAIN:()=>wW,ARRAY_LITERAL:()=>TW,ARRAY_ROW:()=>EW,CHOOSECOLS:()=>DW,CHOOSEROWS:()=>OW,EXPAND:()=>kW,FLATTEN:()=>AW,FREQUENCY:()=>jW,HSTACK:()=>MW,MDETERM:()=>NW,MINVERSE:()=>PW,MMULT:()=>FW,SUMPRODUCT:()=>IW,SUMX2MY2:()=>RW,SUMX2PY2:()=>zW,SUMXMY2:()=>BW,TOCOL:()=>UW,TOROW:()=>WW,TRANSPOSE:()=>GW,VSTACK:()=>KW,WRAPCOLS:()=>qW,WRAPROWS:()=>JW});function SW(e,t){let n=e.map(B),r=n.map(e=>e?.[0]?.length??0),i=Math.max(...r);if(t?.requireSameRowCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=[];for(let e of n)for(let t=0;t<e.length;t++){let n=Array(i).fill({value:null});for(let r=0;r<e[t].length;r++)n[r]=e[t][r];a.push(n)}return a}function CW(e,t){let n=e.map(B),r=n.map(e=>e?.length??0),i=Math.max(...r);if(t?.requireSameColCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=co(i,n.reduce((e,t)=>e+(t?.[0]?.length??0),0),()=>({value:null})),o=0;for(let e of n){for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)a[t][o+n]=e[t][n];o+=e[0]?.length??0}return a}let wW={description:j(`Returns a result array constrained to a specific width and height.`),args:[k(`input_range (any, range<any>)`,j(`The range to constrain.`)),k(`rows (number)`,j(`The number of rows in the constrained array.`)),k(`columns (number)`,j(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=B(e),i=Ja(t?.value,this.locale),a=Ja(n?.value,this.locale);if(i<=0)return new N(j(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new N(j(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return co(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},TW={description:j(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return CW(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},EW={description:j(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return SW(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},DW={description:j(`Creates a new array from the selected columns in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the columns to be returned.`)),k(`col_num (number, range<number>, repeating)`,j(`The column index of the column to be returned.`))],compute:function(e,...t){let n=B(e),r=To(t,e=>Ja(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new N(j(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},OW={description:j(`Creates a new array from the selected rows in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the rows to be returned.`)),k(`row_num (number, range<number>, repeating)`,j(`The row index of the row to be returned.`))],compute:function(e,...t){let n=B(e),r=To(t,e=>Ja(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?co(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new N(j(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},kW={description:j(`Expands or pads an array to specified row and column dimensions.`),args:[k(`array (any, range<any>)`,j(`The array to expand.`)),k(`rows (number)`,j(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),k(`columns (number, optional)`,j(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),k(`pad_with (any, default=0)`,j(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=B(e),a=Ja(t?.value,this.locale),o=n===void 0?i.length:Ja(n.value,this.locale);return a<i[0].length?new N(j(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new N(j(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):co(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},AW={description:j(`Flattens all the values from one or more ranges into a single column.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to flatten.`))],compute:function(...e){return[To(e,e=>e===void 0?{value:``}:e)]},isExported:!1},jW={description:j(`Calculates the frequency distribution of a range.`),args:[k(`data (range<number>)`,j(`The array of ranges containing the values to be counted.`)),k(`classes (number, range<number>)`,j(`The range containing the set of classes.`))],compute:function(e,t){let n=To([e],e=>e.value).filter(e=>typeof e==`number`),r=To([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},MW={description:j(`Appends ranges horizontally and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return SW(e)},isExported:!0},NW={description:j(`Returns the matrix determinant of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);return vh(t)?xh(t).determinant:new N(j(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},PW={description:j(`Returns the multiplicative inverse of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);if(!vh(t))return new N(j(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=xh(t);return n||new N(j(`The matrix is not invertible.`))},isExported:!0},FW={description:j(`Calculates the matrix product of two matrices.`),args:[k(`matrix1 (number, range<number>)`,j(`The first matrix in the matrix multiplication operation.`)),k(`matrix2 (number, range<number>)`,j(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=Ka(e,`matrix1`),r=Ka(t,`matrix2`);return n.length===0||r.length===0?new N(j(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?Ch(n,r):new N(j(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},IW={description:j(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[k(`range (number, range<number>, repeating)`,j(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!_h(...e))return new N(j(`All the ranges must have the same dimensions.`));let t=e.map(B),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=I(n[e][r],this.locale);n+=i}return n},isExported:!0};function LW(e,t,n){if(!_h(e,t))return new N(j(`The arguments array_x and array_y must have the same dimensions.`));let r=B(e),i=B(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new N(j(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let RW={description:j(`Calculates the sum of the difference of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>e**2-t**2)},isExported:!0},zW={description:j(`Calculates the sum of the sum of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>e**2+t**2)},isExported:!0},BW={description:j(`Calculates the sum of squares of the differences of values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>(e-t)**2)},isExported:!0},VW=[k(`array (any, range<any>)`,j(`The array which will be transformed.`)),k(`ignore (number, default=0)`,j(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:j(`Keep all values (default)`)},{value:1,label:j(`Ignore blanks`)},{value:2,label:j(`Ignore errors`)},{value:3,label:j(`Ignore blanks and errors`)}]),k(`scan_by_column (number, default=false)`,j(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:j(`Scan by row (default)`)},{value:!0,label:j(`Scan by column`)}])];function HW(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!F(e.value);if(t===3)return e=>e.value!==null&&!F(e.value);throw new N(j(`Argument ignore must be between 0 and 3`))}let UW={description:j(`Transforms a range of cells into a single column.`),args:VW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:fo(r)).flat().filter(HW(i));return a.length===0?new Ri(j(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},WW={description:j(`Transforms a range of cells into a single row.`),args:VW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:fo(r)).flat().filter(HW(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Ri(j(`No results for the given arguments of TOROW.`)):a},isExported:!0},GW={description:j(`Transposes the rows and columns of a range.`),args:[k(`range (any, range<any>)`,j(`The range to be transposed.`))],compute:function(e){let t=B(e),n=t[0].length,r=t.length;return co(n,r,(e,n)=>t[n][e])},isExported:!0},KW={description:j(`Appends ranges vertically and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return CW(e)},isExported:!0},qW={description:j(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!gh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return co(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},JW={description:j(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!gh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return co(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},YW=[{value:0,label:j(`Concise format\xA0(default)`)},{value:1,label:j(`Strict format`)}],XW={description:j(`returns an array of text values from any specified range. It passes text values unchanged, and converts non-text values to text.`),args:[k(`array (range)`,j(`The array to convert into text`)),k(`format (number, default=0)`,j(`The format of the returned data.`),YW)],compute:function(e,t={value:0}){let n=I(t,this.locale),r=B(e);if(n===1)return sT(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return fo(r).flatMap(e=>e.map(e=>F(e.value)?e.value:Xa(e,this.locale))).join(e)}else return new N(j(`Format must be 0 or 1`))},isExported:!0};var ZW=l({ABS:()=>$W,ACOS:()=>eG,ACOSH:()=>tG,ACOT:()=>nG,ACOTH:()=>rG,ASIN:()=>iG,ASINH:()=>aG,ATAN:()=>oG,ATAN2:()=>sG,ATANH:()=>cG,CEILING:()=>lG,CEILING_MATH:()=>dG,CEILING_PRECISE:()=>fG,COS:()=>pG,COSH:()=>mG,COT:()=>hG,COTH:()=>gG,COUNTBLANK:()=>_G,COUNTIF:()=>vG,COUNTIFS:()=>yG,COUNTUNIQUE:()=>bG,COUNTUNIQUEIFS:()=>xG,CSC:()=>SG,CSCH:()=>CG,DECIMAL:()=>wG,DEGREES:()=>TG,EXP:()=>EG,FLOOR:()=>DG,FLOOR_MATH:()=>kG,FLOOR_PRECISE:()=>AG,INT:()=>fK,ISEVEN:()=>jG,ISODD:()=>NG,ISO_CEILING:()=>MG,LN:()=>PG,LOG:()=>FG,MOD:()=>LG,MUNIT:()=>RG,ODD:()=>zG,PI:()=>BG,POWER:()=>VG,PRODUCT:()=>HG,RAND:()=>UG,RANDARRAY:()=>WG,RANDBETWEEN:()=>GG,ROUND:()=>KG,ROUNDDOWN:()=>qG,ROUNDUP:()=>JG,SEC:()=>YG,SECH:()=>XG,SEQUENCE:()=>ZG,SIN:()=>QG,SINH:()=>$G,SQRT:()=>eK,SUBTOTAL:()=>iK,SUM:()=>aK,SUMIF:()=>oK,SUMIFS:()=>sK,TAN:()=>cK,TANH:()=>lK,TRUNC:()=>dK});let QW=/^-?[a-z0-9]+$/i,$W={description:j(`Absolute value of a number.`),args:[k(`value (number)`,j(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(I(e,this.locale))},isExported:!0},eG={description:j(`Inverse cosine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},tG={description:j(`Inverse hyperbolic cosine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=I(e,this.locale);return t<1?new N(j(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},nG={description:j(`Inverse cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=I(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},rG={description:j(`Inverse hyperbolic cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)<=1?new N(j(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},iG={description:j(`Inverse sine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},aG={description:j(`Inverse hyperbolic sine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(I(e,this.locale))},isExported:!0},oG={description:j(`Inverse tangent of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(I(e,this.locale))},isExported:!0},sG={description:j(`Angle from the X axis to a point (x,y), in radians.`),args:[k(`x (number)`,j(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),k(`y (number)`,j(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n===0&&r===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},cG={description:j(`Inverse hyperbolic tangent of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>=1?new N(j(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},lG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round up to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function uG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let dG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:uG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},fG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:uG(I(e,this.locale),n),format:e?.format}},isExported:!0},pG={description:j(`Cosine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(I(e,this.locale))},isExported:!0},mG={description:j(`Hyperbolic cosine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(I(e,this.locale))},isExported:!0},hG={description:j(`Cotangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},gG={description:j(`Hyperbolic cotangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},_G={description:j(`Number of empty values.`),args:[k(`value (any, range, repeating)`,j(`Value or range in which to count the number of blanks.`))],compute:function(...e){return ao(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},vG={description:j(`A conditional count across a range.`),args:[k(`range (range)`,j(`The range that is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return yo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},yG={description:j(`Count values depending on multiple criteria.`),args:[k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(...e){let t=0;return yo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},bG={description:j(`Counts number of unique values in a range.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider for uniqueness.`))],compute:function(...e){return tg(e)}},xG={description:j(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the number of unique values will be counted.`)),k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return yo(t,(t,r)=>{let i=e[t]?.[r];Eo(i)&&n.add(i.value)},this.locale),n.size}},SG={description:j(`Cosecant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},CG={description:j(`Hyperbolic cosecant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},wG={description:j(`Converts from another base to decimal.`),args:[k(`value (string)`,j(`The number to convert.`)),k(`base (number)`,j(`The base to convert the value from.`))],compute:function(e,t){let n=I(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new N(j(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=L(e);if(r===``)return 0;if(!QW.test(r))return new N(j(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new N(j(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},TG={description:j(`Converts an angle value in radians to degrees.`),args:[k(`angle (number)`,j(`The angle to convert from radians to degrees.`))],compute:function(e){return I(e,this.locale)*180/Math.PI},isExported:!0},EG={description:j(`Euler's number, e (~2.718) raised to a power.`),args:[k(`value (number)`,j(`The exponent to raise e.`))],compute:function(e){return Math.exp(I(e,this.locale))},isExported:!0},DG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round down to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function OG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let kG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:OG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},AG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:OG(I(e,this.locale),n),format:e?.format}},isExported:!0},jG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},MG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:uG(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},NG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},PG={description:j(`The logarithm of a number, base e (euler's number).`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=I(e,this.locale);return t<=0?new N(j(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},FG={description:j(`The logarithm of a number, for a given base.`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm.`)),k(`base (number, default=10)`,j(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=I(e,this.locale),r=I(t,this.locale);return n<=0?new N(j(`The value (%s) must be strictly positive.`,n)):r<=0?new N(j(`The base (%s) must be strictly positive.`,r)):r===1?new N(j(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function IG(e,t){hh(t,j(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let LG={description:j(`Modulo (remainder) operator.`),args:[k(`dividend (number)`,j(`The number to be divided to find the remainder.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return{value:IG(I(e,this.locale),n),format:e?.format}},isExported:!0},RG={description:j(`Returns a n x n unit matrix, where n is the input dimension.`),args:[k(`dimension (number)`,j(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=Ja(e,this.locale);return t<1?new N(j(`The argument dimension must be positive`)):bh(t)},isExported:!0},zG={description:j(`Rounds a number up to the nearest odd integer.`),args:[k(`value (number)`,j(`The value to round to the next greatest odd number.`))],compute:function(e){let t=I(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},BG={description:j(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},VG={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n<0&&!Number.isInteger(r)?new N(j(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},HG={description:j(`Result of multiplying a series of numbers together.`),args:[k(`factor (number, range<number>, repeating)`,j(`Number or range to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Je(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),F(e))return r}else r!==void 0&&r.value!==null&&(n*=qa(r,this.locale),t+=1);return{value:t===0?0:n,format:za(e[0])}},isExported:!0},UG={description:j(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},WG={description:j(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[k(`rows (number, default=1)`,j(`The number of rows to be returned.`)),k(`columns (number, default=1)`,j(`The number of columns to be returned.`)),k(`min (number, default=0)`,j(`The minimum number you would like returned.`)),k(`max (number, default=1)`,j(`The maximum number you would like returned.`)),k(`whole_number (boolean, default=FALSE)`,j(`Return a whole number or a decimal value.`),[{value:!1,label:j(`Decimal (default)`)},{value:!0,label:j(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=Ja(t,this.locale),o=Ja(e,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=R(i);if(a<1)return new N(j(`The number of columns (%s) must be positive.`,a));if(o<1)return new N(j(`The number of rows (%s) must be positive.`,o));if(s>c)return new N(j(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new N(j(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},GG={description:j(`Random integer between two values, inclusive.`),args:[k(`low (number)`,j(`The low end of the random range.`)),k(`high (number)`,j(`The high end of the random range.`))],compute:function(e,t){let n=I(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=I(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new N(j(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},KG={description:j(`Rounds a number according to standard rules.`),args:[k(`value (number)`,j(`The value to round to places number of places.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},qG={description:j(`Rounds down a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding down.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},JG={description:j(`Rounds up a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding up.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},YG={description:j(`Secant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(I(e,this.locale))},isExported:!0},XG={description:j(`Hyperbolic secant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(I(e,this.locale))},isExported:!0},ZG={description:j(`Returns a sequence of numbers.`),args:[k(`rows (number)`,j(`The number of rows to return`)),k(`columns (number, optional, default=1)`,j(`The number of columns to return`)),k(`start (number, optional, default=1)`,j(`The first number in the sequence`)),k(`step (number, optional, default=1)`,j(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=I(n,this.locale),a=I(r,this.locale),o=Ja(e,this.locale),s=Ja(t,this.locale);return s<1?new N(j(`The number of columns (%s) must be positive.`,s)):o<1?new N(j(`The number of rows (%s) must be positive.`,o)):co(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},QG={description:j(`Sine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(I(e,this.locale))},isExported:!0},$G={description:j(`Hyperbolic sine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(I(e,this.locale))},isExported:!0},eK={description:j(`Positive square root of a positive number.`),args:[k(`value (number)`,j(`The number for which to calculate the positive square root.`))],compute:function(e){let t=I(e,this.locale);return t<0?new N(j(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},tK={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},nK=Object.entries(tK).map(([e,t])=>({value:parseInt(e),label:j(`%s (include manually-hidden rows)`,t)})),rK=Object.entries(tK).map(([e,t])=>({value:parseInt(e)+100,label:j(`%s (exclude manually-hidden rows)`,t)})),iK={description:j(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[k(`function_code (number)`,j(`The function to use in subtotal aggregation.`),[...nK,...rK]),k(`ref (any, range<any>, repeating)`,j(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=Ja(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new N(j(`The function code (%s) must be between 1 to 11 or 101 to 111.`,n));let i=[];for(let e of t){let t=B(e),n=t[0][0]?.position;if(n===void 0)return new Li(Ha);let a=n.col+t.length-1,o=n.row+t[0].length-1,s=n.sheetId;for(let e=n.row;e<=o;e++)if(!this.getters.isRowFiltered(s,e)&&!(!r&&this.getters.isRowHiddenByUser(s,e)))for(let t=n.col;t<=a;t++){let n=this.getters.getCorrespondingFormulaCell({sheetId:s,col:t,row:e});(!n||!Yt(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[tK[n]].apply(this,[[i]])},isExported:!0},aK={description:j(`Sum of a series of numbers and/or cells.`),args:[k(`value (number, range<number>, repeating)`,j(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:eg(e,this.locale),format:za(t)}},isExported:!0},oK={description:j(`A conditional sum across a range.`),args:[k(`criteria_range (range)`,j(`The range which is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`)),k(`sum_range (range, default=criteria_range)`,j(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return yo([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},sK={description:j(`Sums a range depending on multiple criteria.`),args:[k(`sum_range (range)`,j(`The range to sum.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},cK={description:j(`Tangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(I(e,this.locale))},isExported:!0},lK={description:j(`Hyperbolic tangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(I(e,this.locale))},isExported:!0};function uK(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let dK={description:j(`Truncates a number.`),args:[k(`value (number)`,j(`The value to be truncated.`)),k(`places (number, default=0)`,j(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:uK(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},fK={description:j(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[k(`value (number)`,j(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(I(e,this.locale))},isExported:!0};var pK=l({AVEDEV:()=>CK,AVERAGE:()=>wK,AVERAGEA:()=>OK,AVERAGEIF:()=>kK,AVERAGEIFS:()=>AK,AVERAGE_WEIGHTED:()=>DK,CORREL:()=>QK,COUNT:()=>jK,COUNTA:()=>MK,COVAR:()=>NK,COVARIANCE_P:()=>PK,COVARIANCE_S:()=>FK,FORECAST:()=>IK,GROWTH:()=>LK,INTERCEPT:()=>RK,LARGE:()=>zK,LINEST:()=>BK,LOGEST:()=>VK,MATTHEWS:()=>HK,MAX:()=>UK,MAXA:()=>WK,MAXIFS:()=>GK,MEDIAN:()=>KK,MIN:()=>qK,MINA:()=>JK,MINIFS:()=>YK,PEARSON:()=>ZK,PERCENTILE:()=>$K,PERCENTILE_EXC:()=>eq,PERCENTILE_INC:()=>tq,POLYFIT_COEFFS:()=>nq,POLYFIT_FORECAST:()=>rq,QUARTILE:()=>iq,QUARTILE_EXC:()=>aq,QUARTILE_INC:()=>oq,RANK:()=>sq,RSQ:()=>cq,SLOPE:()=>lq,SMALL:()=>uq,SPEARMAN:()=>dq,STDEV:()=>fq,STDEVA:()=>hq,STDEVP:()=>gq,STDEVPA:()=>_q,STDEV_P:()=>pq,STDEV_S:()=>mq,STEYX:()=>vq,TREND:()=>yq,VAR:()=>bq,VARA:()=>Cq,VARP:()=>wq,VARPA:()=>Tq,VAR_P:()=>xq,VAR_S:()=>Sq});let mK=[{value:!0,label:j(`b is calculated normally`)},{value:!1,label:j(`b is forced to 1`)}],hK=[{value:!1,label:j(`do not return additional regression statistics`)},{value:!0,label:j(`return additional regression statistics`)}],gK=[{value:1,label:j(`order 1 (Linear)`)},{value:2,label:j(`order 2 (Quadratic)`)},{value:3,label:j(`order 3 (Cubic)`)},{value:4,label:j(`order 4 (Quartic)`)},{value:5,label:j(`order 5 (Quintic)`)},{value:6,label:j(`order 6 (Sextic)`)}],_K=[{value:!0,label:j(`Compute intercept`)},{value:!1,label:j(`Force intercept to 0`)}],vK=[{value:0,label:j(`Minimum value`)},{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)},{value:4,label:j(`Maximum value`)}];function yK(e,t){let n=[],r=[],i=0,a=0;no([e],e=>{n.push(e),i+=1}),no([t],e=>{r.push(e),a+=1}),mh(i===a,j(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function bK(e,t,n){let{flatDataX:r,flatDataY:i}=yK(e,t),a=i.length;hh(a),n&&hh(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function xK(e,t,n,r){let i=0,a=n?so:oo,o=a(e,(e,t)=>(i+=1,e+t),0,r);hh(i),t&&hh(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function SK(e,t,n,r){let i=I(t,r);mh(n?0<=i&&i<=1:0<i&&i<1,j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return no(e,e=>{let t=e?.value;typeof t==`number`&&(o=bo(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),mh(s!==0,Do),n||mh(1/(s+1)<=i&&i<=s/(s+1),j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),La(a,i,n)}let CK={description:j(`Average magnitude of deviations from mean.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=oo(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return oo(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},wK={description:j(`Numerical average value in a dataset, ignoring text.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:Oh(e,this.locale),format:za(e[0])}},isExported:!0},TK=j(`[[FUNCTION_NAME]] has mismatched range sizes.`),EK=j(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),DK={description:j(`Weighted average.`),args:[k(`values (number, range<number>, repeating)`,j(`Value to average.`)),k(`weights (number, range<number>, repeating)`,j(`Weight for each corresponding value.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!_h(i,a))return new N(TK);if(Je(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Je(a)?a?.[e][r].value:I(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new N(EK);t+=o*s,n+=s;continue}if(c!==l)return new N(j(`[[FUNCTION_NAME]] expects number values.`))}else{let e=I(i,this.locale),r=Je(a)?a?.[0][0].value:I(a,this.locale);if(typeof r==`number`){if(r<0)return new N(EK);t+=e*r,n+=r}}}return n===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:za(e[0])}}},OK={description:j(`Numerical average value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=so(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:za(e[0])}},isExported:!0},kK={description:j(`Average of values depending on criteria.`),args:[k(`criteria_range (number, range<number>)`,j(`The range to check against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to criteria_range.`)),k(`average_range (number, range<number>, default=criteria_range)`,j(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=B(n===void 0?e:n),i=0,a=0;return yo([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},AK={description:j(`Average of values depending on multiple criteria.`),args:[k(`average_range (range)`,j(`The range to average.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=B(e),r=0,i=0;return yo(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},jK={description:j(`The number of numeric values in dataset.`),args:[k(`value (number, any, range<number>, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return Ah(e,this.locale)},isExported:!0},MK={description:j(`The number of values in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return jh(e)},isExported:!0},NK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!1)},isExported:!0},PK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!1)},isExported:!0},FK={description:j(`The sample covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!0)},isExported:!0},IK={description:j(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=yK(t,n);return r.length===0||i.length===0?new Ri(Do):Vh([i],[r],lo(B(e),e=>I(e,this.locale)),!0)},isExported:!0},LK={description:j(`Fits points to exponential growth trend.`),args:[k(`known_data_y (range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),k(`known_data_x (range<number>, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (any, range, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, default=TRUE)`,j(`Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE.`),mK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Oo(`known_data_y`)):zh(Vh(Bh(Ka(e,`known_data_y`)),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r)))}},RK={description:j(`Compute the intercept of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let[[],[i]]=Fh([n],[r]);return i},isExported:!0},zK={description:j(`Nth largest element from a data set.`),args:[k(`data (any, range)`,j(`Array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;no([e],e=>{typeof e?.value==`number`&&(i=bo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new N(Do):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},BK={description:j(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),mK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),hK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new N(Oo(`data_y`)):Fh(Ka(t,`data_x`),Ka(e,`data_y`),R(n),R(r))},isExported:!0},VK={description:j(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, optional, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),mK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),hK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new N(Oo(`data_y`));let i=Fh(Ka(t,`data_x`),Bh(Ka(e,`data_y`)),R(n),R(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},HK={description:j(`Compute the Matthews correlation coefficient of a dataset.`),args:[k(`data_x (range)`,j(`The range representing the array or matrix of observed data.`)),k(`data_y (range)`,j(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Dh(n,r),n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=R(n[e]);t===R(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},UK={description:j(`Maximum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return Mh(e,this.locale)},isExported:!0},WK={description:j(`Maximum numeric value in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=so(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:za(e[0])}},isExported:!0},GK={description:j(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the maximum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},KK={description:j(`Median value in a numeric dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return ro(e,e=>{t.push(e)},this.locale),{value:SK(t,{value:.5},!0,this.locale),format:za(t[0])}},isExported:!0},qK={description:j(`Minimum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return Nh(e,this.locale)},isExported:!0},JK={description:j(`Minimum numeric value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=so(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:za(e[0])}},isExported:!0},YK={description:j(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the minimum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function XK(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let ZK={description:j(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return XK(e,t)},isExported:!0},QK=ZK,$K={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return tq.compute.bind(this)(e,t)},isExported:!0},eq={description:j(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:SK([e],t,!1,this.locale),format:za(e)}},isExported:!0},tq={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:SK([e],t,!0,this.locale),format:za(e)}},isExported:!0},nq={description:j(`Compute the coefficients of polynomial regression of the dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),gK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),_K)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=yK(e,t);return i.length===0||a.length===0?new Ri(Do):Ih(a,i,I(n,this.locale),R(r))},isExported:!1},rq={description:j(`Predict value by computing a polynomial regression of the dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),gK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),_K)],compute:function(e,t,n,r,i={value:!0}){let a=I(r,this.locale),{flatDataX:o,flatDataY:s}=yK(t,n);if(o.length===0||s.length===0)return new Ri(Do);let c=Ih(s,o,a,R(i)).flat();return lo(B(e),e=>Rh(c,I(e,this.locale),a))},isExported:!1},iq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),vK)],compute:function(e,t){return oq.compute.bind(this)(e,t)},isExported:!0},aq={description:j(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:SK([e],n,!1,this.locale),format:za(e)}},isExported:!0},oq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),vK)],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:SK([e],n,!0,this.locale),format:za(e)}},isExported:!0},sq={description:j(`Returns the rank of a specified value in a dataset.`),args:[k(`value (number)`,j(`The value whose rank will be determined.`)),k(`data (range)`,j(`The range containing the dataset to consider.`)),k(`is_ascending (boolean, default=FALSE)`,j(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:j(`Descending`)},{value:!0,label:j(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=R(n),i=I(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=I(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Ri(j(`Value not found in the given data.`))},isExported:!0},cq={description:j(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=XK(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},lq={description:j(`Compute the slope of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let[[i]]=Fh([n],[r]);return i},isExported:!0},uq={description:j(`Nth smallest element in a data set.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;no([e],e=>{typeof e?.value==`number`&&(i=bo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new N(Do):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},dq={description:j(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(t,e);if(n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},fq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(bq.compute.bind(this)(...e))},isExported:!0},pq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(xq.compute.bind(this)(...e))},isExported:!0},mq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Sq.compute.bind(this)(...e))},isExported:!0},hq={description:j(`Standard deviation of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Cq.compute.bind(this)(...e))},isExported:!0},gq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(wq.compute.bind(this)(...e))},isExported:!0},_q={description:j(`Standard deviation of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(Tq.compute.bind(this)(...e))},isExported:!0},vq={description:j(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);return n.length===0||r.length===0?new Ri(Do):Fh([n],[r],!0,!0)[1][2]},isExported:!0},yq={description:j(`Fits points to linear trend derived via least-squares.`),args:[k(`known_data_y (number, range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),k(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (number, range<number>, optional, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, optional, default=TRUE)`,j(`Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin.`),mK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Oo(`known_data_y`)):Vh(Ka(e,`known_data_y`),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r))}},bq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!1,this.locale)},isExported:!0},xq={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!1,this.locale)},isExported:!0},Sq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!1,this.locale)},isExported:!0},Cq={description:j(`Variance of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!0,this.locale)},isExported:!0},wq={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!1,this.locale)},isExported:!0},Tq={description:j(`Variance of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!0,this.locale)},isExported:!0};var Eq=l({DAVERAGE:()=>kq,DCOUNT:()=>Aq,DCOUNTA:()=>jq,DGET:()=>Mq,DMAX:()=>Nq,DMIN:()=>Pq,DPRODUCT:()=>Fq,DSTDEV:()=>Iq,DSTDEVP:()=>Lq,DSUM:()=>Rq,DVAR:()=>zq,DVARP:()=>Bq});function Dq(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(L(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new N(j(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new N(j(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=L(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new N(j(`The field (%s) must be one of %s.`,L(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new N(j(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=L(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)yo(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let Oq=[k(`database (range)`,j(`The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.`)),k(`field (number, string)`,j(`Indicates which column in database contains the values to be extracted and operated on.`)),k(`criteria (range)`,j(`An array or range containing zero or more criteria to filter the database values by before operating.`))],kq={description:j(`Average of a set of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return wK.compute.bind(this)([r])},isExported:!0},Aq={description:j(`Counts values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return jK.compute.bind(this)([r])},isExported:!0},jq={description:j(`Counts values and text from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return MK.compute.bind(this)([r])},isExported:!0},Mq={description:j(`Single value from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return r.length===1?r[0]:new N(j(`More than one match found in DGET evaluation.`))},isExported:!0},Nq={description:j(`Maximum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return UK.compute.bind(this)([r])},isExported:!0},Pq={description:j(`Minimum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return qK.compute.bind(this)([r])},isExported:!0},Fq={description:j(`Product of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return HG.compute.bind(this)([r])},isExported:!0},Iq={description:j(`Standard deviation of population sample from table.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return fq.compute.bind(this)([r])},isExported:!0},Lq={description:j(`Standard deviation of entire population from table.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return gq.compute.bind(this)([r])},isExported:!0},Rq={description:j(`Sum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return aK.compute.bind(this)([r])},isExported:!0},zq={description:j(`Variance of population sample from table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return bq.compute.bind(this)([r])},isExported:!0},Bq={description:j(`Variance of a population from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return wq.compute.bind(this)([r])},isExported:!0},Vq=j(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Hq=j(`There must be both positive and negative values in cashflow_amounts.`),Uq=e=>j(`The cost (%s) must be positive or null.`,e),Wq=e=>j(`The cost (%s) must be strictly positive.`,e),Gq=e=>j(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Kq=e=>j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),qq=e=>j(`The depreciation factor (%s) must be strictly positive.`,e),Jq=e=>j(`The discount (%s) must be different from -1.`,e),Yq=e=>j(`The discount (%s) must be strictly positive.`,e),Xq=e=>j(`The discount (%s) must be smaller than 1.`,e),Zq=e=>j(`The effective_rate (%s) must be strictly positive.`,e),Qq=e=>j(`The end_period (%s) must be positive or null.`,e),$q=(e,t)=>j(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),eJ=e=>j(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),tJ=(e,t)=>j(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),nJ=e=>j(`The first_period (%s) must be strictly positive.`,e),rJ=e=>j(`The future_value (%s) must be strictly positive.`,e),iJ=e=>j(`The investment (%s) must be strictly positive.`,e),aJ=e=>j(`The issue (%s) must be positive or null.`,e),oJ=(e,t)=>j(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),sJ=e=>j(`The last_period (%s) must be strictly positive.`,e),cJ=e=>j(`The life (%s) must be strictly positive.`,e),lJ=(e,t)=>j(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),uJ=e=>j(`The month (%s) must be between 1 and 12 inclusive.`,e),dJ=e=>j(`The nominal_rate (%s) must be strictly positive.`,e),fJ=e=>j(`The number_of_periods (%s) must be different from zero.`,e),pJ=e=>j(`The number_of_periods (%s) must be strictly positive.`,e),mJ=e=>j(`The period must be between 1 and number_of_periods (%s)`,e),hJ=(e,t)=>j(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),gJ=e=>j(`The period (%s) must be positive or null.`,e),_J=e=>j(`The periods_by_year (%s) must be strictly positive.`,e),vJ=(e,t)=>j(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),yJ=e=>j(`The period (%s) must be strictly positive.`,e),bJ=e=>j(`The present_value (%s) must be strictly positive.`,e),xJ=e=>j(`The price (%s) must be strictly positive.`,e),SJ=(e,t)=>j(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),CJ=e=>j(`The purchase_date (%s) must be positive or null.`,e),wJ=e=>j(`The rate_guess (%s) must be strictly greater than -1.`,e),TJ=e=>j(`The rate (%s) must be positive or null.`,e),EJ=e=>j(`The rate (%s) must be strictly positive.`,e),DJ=e=>j(`The redemption (%s) must be strictly positive.`,e),OJ=e=>j(`The salvage (%s) must be positive or null.`,e),kJ=(e,t)=>j(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),AJ=(e,t)=>j(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),jJ=(e,t)=>j(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),MJ=(e,t)=>j(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),NJ=e=>j(`The start_period (%s) must be positive or null.`,e),PJ=(e,t)=>j(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),FJ=e=>j(`The unit (%s) must be strictly positive.`,e),IJ=e=>j(`The yield (%s) must be positive or null.`,e);function LJ(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function RJ(e){return![0,1,2,3,4].includes(e)}function zJ(e){return![1,2,4].includes(e)}function BJ(e,t,n){let r=z(e,n),i=z(t,n),a=z(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let VJ=[{value:0,label:j(`US (NASD) 30/360`)},{value:1,label:j(`Actual/Actual`)},{value:2,label:j(`Actual/360`)},{value:3,label:j(`Actual/365`)},{value:4,label:j(`European 30/360`)}];var HJ=l({DATE:()=>WJ,DATEDIF:()=>GJ,DATEVALUE:()=>KJ,DAY:()=>qJ,DAYS:()=>JJ,DAYS360:()=>YJ,EDATE:()=>XJ,EOMONTH:()=>ZJ,HOUR:()=>QJ,ISOWEEKNUM:()=>$J,MINUTE:()=>eY,MONTH:()=>tY,MONTH_END:()=>vY,MONTH_START:()=>_Y,NETWORKDAYS:()=>nY,NETWORKDAYS_INTL:()=>aY,NOW:()=>oY,QUARTER:()=>yY,QUARTER_END:()=>xY,QUARTER_START:()=>bY,SECOND:()=>sY,TIME:()=>cY,TIMEVALUE:()=>lY,TODAY:()=>uY,WEEKDAY:()=>dY,WEEKNUM:()=>fY,WORKDAY:()=>pY,WORKDAY_INTL:()=>mY,YEAR:()=>hY,YEARFRAC:()=>gY,YEAR_END:()=>CY,YEAR_START:()=>SY}),UJ=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(UJ||{});let WJ={description:j(`Converts year/month/day into a date.`),args:[k(`year (number)`,j(`The year component of the date.`)),k(`month (number)`,j(`The month component of the date.`)),k(`day (number)`,j(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));if(r<0||r>9999)return new N(j(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=ha(new P(r,i-1,a));return o<0?new N(j(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},GJ={description:j(`Calculates the number of days, months, or years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`unit (string)`,j(`A text abbreviation for unit of time.`),[{value:`Y`,label:j(`The number of whole years between start_date and end_date`)},{value:`M`,label:j(`The number of whole months between start_date and end_date`)},{value:`D`,label:j(`The number of days between start_date and end_date`)},{value:`MD`,label:j(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:j(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:j(`The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart`)}])],compute:function(e,t,n){let r=L(n).toUpperCase();if(!Object.values(UJ).includes(r))return new N(Wa(Object.values(UJ),L(n)));let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=ma(i),s=ma(a);if(a<i)return new N(j(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return wa(o,s);case`M`:return Sa(o,s);case`D`:return Ca(o,s);case`YM`:return Sa(o,s)-wa(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=_a(new P(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(Ta(i,a))return Ca(o,s);let e=new P(o.getFullYear(),s.getMonth(),s.getDate()),t=Ca(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=Ca(o,e)),t}}},isExported:!0},KJ={description:j(`Converts a date string to a date value.`),args:[k(`date_string (string)`,j(`The string representing the date.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);return n===null?new N(j(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},qJ={description:j(`Day of the month that a specific date falls on.`),args:[k(`date (string)`,j(`The date from which to extract the day.`))],compute:function(e){return z(e,this.locale).getDate()},isExported:!0},JJ={description:j(`Number of days between two dates.`),args:[k(`end_date (date)`,j(`The end of the date range.`)),k(`start_date (date)`,j(`The start of the date range.`))],compute:function(e,t){let n=z(e,this.locale),r=z(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Wi)},isExported:!0},YJ={description:j(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation.`)),k(`end_date (date)`,j(`The end date to consider in the calculation.`)),k(`method (boolean, default=false)`,j(`An indicator of what day count method to use.`),[{value:!1,label:j(`U.S. NASD method (default)`)},{value:!0,label:j(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=xa(r,i,R(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},XJ={description:j(`Date a number of months before/after another date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:ha(ya(z(e,this.locale),Math.trunc(I(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},ZJ={description:j(`Last day of a month before or after a date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=z(e,this.locale),r=Math.trunc(I(t,this.locale));return{value:ha(new P(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},QJ={description:j(`Hour component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the hour component.`))],compute:function(e){return z(e,this.locale).getHours()},isExported:!0},$J={description:j(`ISO week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=z(e,this.locale),n=t.getFullYear(),r=1;for(;new P(n,0,r).getDay()!==4;)r+=1;let i=new P(n,0,r-3),a=31;for(;new P(n,11,a).getDay()!==4;)--a;let o=new P(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new P(n,11,a+3+1);break;case-1:let e=1;for(;new P(n-1,0,e).getDay()!==4;)e+=1;c=new P(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Wi;return Math.floor(l/7)+1},isExported:!0},eY={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the minute component.`))],compute:function(e){return z(e,this.locale).getMinutes()},isExported:!0},tY={description:j(`Month of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the month.`))],compute:function(e){return z(e,this.locale).getMonth()+1},isExported:!0},nY={description:j(`Net working days between two provided days.`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return aY.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function rY(e){let t=e?.value;if(typeof t==`string`){mh(t.length===7&&[...t].every(e=>e===`0`||e===`1`),j(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return mh(1<=t&&t<=7||11<=t&&t<=17,j(`The weekend (%s) must be a string or a number in the range 1-7 or 11-17.`,t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new N(j(`The weekend must be a number or a string.`))}let iY=[{value:1,label:j(`Saturday/Sunday are weekends`)},{value:2,label:j(`Sunday/Monday are weekends`)},{value:3,label:j(`Monday/Tuesday are weekends`)},{value:4,label:j(`Tuesday/Wednesday are weekends`)},{value:5,label:j(`Wednesday/Thursday are weekends`)},{value:6,label:j(`Thursday/Friday are weekends`)},{value:7,label:j(`Friday/Saturday are weekends`)},{value:11,label:j(`Sunday is the only weekend`)},{value:12,label:j(`Monday is the only weekend`)},{value:13,label:j(`Tuesday is the only weekend`)},{value:14,label:j(`Wednesday is the only weekend`)},{value:15,label:j(`Thursday is the only weekend`)},{value:16,label:j(`Friday is the only weekend`)},{value:17,label:j(`Saturday is the only weekend`)}],aY={description:j(`Net working days between two dates (specifying weekends).`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),iY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=z(t,this.locale),o=rY(n),s=new Set;r!==void 0&&no([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=P.fromTimestamp((c?i:a).getTime()),u=P.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},oY={description:j(`Current date and time as a date value.`),args:[],compute:function(){let e=P.now(),t=e.getTime()-Ui.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Wi)+n,format:db(this.locale)}},isExported:!0},sY={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the second component.`))],compute:function(e){return z(e,this.locale).getSeconds()},isExported:!0},cY={description:j(`Converts hour/minute/second into a time.`),args:[k(`hour (number)`,j(`The hour component of the time.`)),k(`minute (number)`,j(`The minute component of the time.`)),k(`second (number)`,j(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new N(j(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},lY={description:j(`Converts a time string into its serial number representation.`),args:[k(`time_string (string)`,j(`The string that holds the time representation.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);if(n===null)return new N(j(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},uY={description:j(`Current date as a date value.`),args:[],compute:function(){let e=P.now();return{value:ha(new P(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},dY={description:j(`Day of the week of the date provided (as number).`),args:[k(`date (date)`,j(`The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:j(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:j(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:j(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:j(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:j(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:j(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new N(j(`The type (%s) must be between 1 and 3 or between 11 and 17.`,r));switch(r){case 1:return i+1;case 2:return i===0?7:i;case 3:return i===0?6:i-1}let a=r-10,o=(i+1-a+7)%7;return o===0?7:o},isExported:!0},fY={description:j(`Week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:j(`Sunday`)},{value:2,label:j(`Monday`)},{value:11,label:j(`Monday`)},{value:12,label:j(`Tuesday`)},{value:13,label:j(`Wednesday`)},{value:14,label:j(`Thursday`)},{value:15,label:j(`Friday`)},{value:16,label:j(`Saturday`)},{value:17,label:j(`Sunday`)},{value:21,label:j(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new N(j(`The type (%s) is out of range.`,r.toString()));if(r===21)return $J.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new P(a,0,o);for(;s.getDay()!==i;)o+=1,s=new P(a,0,o);let c=(n.getTime()-s.getTime())/Wi;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},pY={description:j(`Date after a number of workdays.`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return mY.compute.bind(this)(e,t,{value:1},n)},isExported:!0},mY={description:j(`Date after a number of workdays (specifying weekends).`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),iY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=Math.trunc(I(t,this.locale));if(n.value===`1111111`)return new N(j(`The weekend must be different from '1111111'.`));let o=rY(n),s=new Set;r!==void 0&&no([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=P.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Ui.getTime();return{value:Math.round(f/Wi),format:this.locale.dateFormat}},isExported:!0},hY={description:j(`Year specified by a given date.`),args:[k(`date (date)`,j(`The date from which to extract the year.`))],compute:function(e){return z(e,this.locale).getFullYear()},isExported:!0},gY={description:j(`Exact number of years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`day_count_convention (number, default=0)`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n={value:0}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return r<0?new N(j(`The start_date (%s) must be positive or null.`,r)):i<0?new N(j(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new N(j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):xa(r,i,a)}},_Y={description:j(`First day of the month preceding a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){let t=z(e,this.locale);return{value:ha(new P(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},vY={description:j(`Last day of the month following a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){return ZJ.compute.bind(this)(e,{value:0})}},yY={description:j(`Quarter of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((z(e,this.locale).getMonth()+1)/3)}},bY={description:j(`First day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=yY.compute.bind(this)(e);return{value:ha(new P(hY.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},xY={description:j(`Last day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=yY.compute.bind(this)(e);return{value:ha(new P(hY.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},SY={description:j(`First day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:ha(new P(hY.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},CY={description:j(`Last day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:ha(new P(hY.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var wY=l({DELTA:()=>TY});let TY={description:j(`Compare two numeric values, returning 1 if they're equal.`),args:[k(`number1 (number)`,j(`The first number to compare.`)),k(`number2 (number, default=0)`,j(`The second number to compare.`))],compute:function(e,t={value:0}){return+(I(e,this.locale)===I(t,this.locale))},isExported:!0};var EY=l({FILTER:()=>OY,SORT:()=>kY,SORTN:()=>AY,UNIQUE:()=>jY});function DY(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;mh(n[e]!==void 0,j(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(R(wh(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Je(s)&&(s.length>1||s[0].length>1))mh(s.length===1&&s[0].length===a,j(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=I(wh(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:wz(`desc`),asc:wz(`asc`)},s=C(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?`empty`:typeof i==`string`?`text`:typeof i},l={value:s,type:s===null?`empty`:typeof s==`string`?`text`:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let OY={description:j(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[k(`range (any, range<any>)`,j(`The data to be filtered.`)),k(`condition (boolean, range<boolean>, repeating)`,j(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=B(e),r=t.map(e=>lo(B(e),e=>e.value));for(let e of r)if(!gh(e))return new N(j(`The arguments condition must be a single column or row.`));if(!_h(...t))return new N(j(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?fo(n):n,i.some(e=>e.length!==n.length))return new N(j(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?fo(o):o:new Ri(j(`No match found in FILTER evaluation`))},isExported:!1},kY={description:j(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`sort_column (any, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,...t){return fo(DY(fo(e),this.locale,...t))},isExported:!0},AY={description:j(`Returns the first n items in a data set after performing a sort.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`n (number)`,j(`The number of items to return.`)),k(`display_ties_mode (number, default=0)`,j(`A number representing the way to display ties.`)),k(`sort_column (number, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,t,...n){let r=I(t?.value??1,this.locale),i=n.length%2==0?0:I(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new N(j(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new N(j(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=DY(fo(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return fo(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return fo(o.slice(0,e));return fo(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return fo(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return fo(e)}}},isExported:!1},jY={description:j(`Unique rows in the provided source range.`),args:[k(`range (any, range<any>)`,j(`The data to filter by unique entries.`)),k(`by_column (boolean, default=FALSE)`,j(`Whether to filter the data by columns or by rows.`),[{value:!0,label:j(`Return unique columns`)},{value:!1,label:j(`Return unique rows`)}]),k(`exactly_once (boolean, default=FALSE)`,j(`Whether to return only entries with no duplicates.`),[{value:!0,label:j(`Return items that appear exactly once`)},{value:!1,label:j(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!Je(e))return[[e]];let r=R(t?.value)||!1,i=R(n?.value)||!1;r||(e=fo(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:fo(o):new N(j(`No unique values found`))},isExported:!0};var MY=l({ACCRINTM:()=>LY,AMORLINC:()=>RY,COUPDAYBS:()=>BY,COUPDAYS:()=>zY,COUPDAYSNC:()=>VY,COUPNCD:()=>HY,COUPNUM:()=>UY,COUPPCD:()=>WY,CUMIPMT:()=>GY,CUMPRINC:()=>KY,DB:()=>qY,DDB:()=>YY,DISC:()=>XY,DOLLARDE:()=>ZY,DOLLARFR:()=>QY,DURATION:()=>$Y,EFFECT:()=>eX,FV:()=>nX,FVSCHEDULE:()=>rX,INTRATE:()=>iX,IPMT:()=>oX,IRR:()=>cX,ISPMT:()=>lX,MDURATION:()=>uX,MIRR:()=>dX,NOMINAL:()=>fX,NPER:()=>pX,NPV:()=>hX,PDURATION:()=>gX,PMT:()=>vX,PPMT:()=>bX,PRICE:()=>SX,PRICEDISC:()=>CX,PRICEMAT:()=>wX,PV:()=>xX,RATE:()=>EX,RECEIVED:()=>DX,RRI:()=>OX,SLN:()=>kX,SYD:()=>AX,TBILLEQ:()=>NX,TBILLPRICE:()=>MX,TBILLYIELD:()=>PX,VDB:()=>FX,XIRR:()=>IX,XNPV:()=>LX,YIELD:()=>RX,YIELDDISC:()=>zX,YIELDMAT:()=>BX});let NY=[{value:1,label:j(`Annual`)},{value:2,label:j(`Semi-annual`)},{value:4,label:j(`Quarterly`)}],PY=[{value:0,label:j(`End of period (default)`)},{value:1,label:j(`Beginning of period`)}],FY=[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)];function IY(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){mh(d<r&&a!==void 0,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,mh(d<r,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let LY={description:j(`Accrued interest of security paying at maturity.`),args:[k(`issue (date)`,j(`The date the security was initially issued.`)),k(`maturity (date)`,j(`The maturity date of the security.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a<0)return new N(aJ(a));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(DJ(s));if(c<=0)return new N(EJ(c));let u=xa(a,o,l);return s*c*u},isExported:!0},RY={description:j(`Depreciation for an accounting period.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`purchase_date (date)`,j(`The date the asset was purchased.`)),k(`first_period_end (date)`,j(`The date the first period ended.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`rate (number)`,j(`The deprecation rate.`)),k(`day_count_convention (number, optional)`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=I(e,this.locale),c=Math.trunc(I(t,this.locale)),l=Math.trunc(I(n,this.locale)),u=I(r,this.locale),d=I(i,this.locale),f=I(a,this.locale),p=Math.trunc(I(o,this.locale));if(s<=0)return new N(Wq(s));if(c<0)return new N(CJ(c));if(u<0)return new N(OJ(u));if(u>s)return new N(kJ(u,s));if(d<0)return new N(gJ(d));if(f<=0)return new N(EJ(f));if(RJ(p))return new N(Kq(p));if(c>l)return new N(SJ(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=xa(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},zY={description:j(`Days in coupon period containing settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));if(s===1){let i=WY.compute.bind(this)(e,t,n,r).value,a=HY.compute.bind(this)(e,t,n,r).value;return I(a,this.locale)-I(i,this.locale)}return(s===3?365:360)/o},isExported:!0},BY={description:j(`Days from settlement until next coupon.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=WY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=xa(l,i,s);return Math.round(e*360)}let u=z(i,this.locale),d=z(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&va(d)&&va(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&va(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},VY={description:j(`Days from settlement until next coupon.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=HY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=xa(i,l,s);return Math.round(e*360)}let u=BY.compute.bind(this)(e,t,n,r);return I(zY.compute.bind(this)(e,t,n,r),this.locale)-I(u,this.locale)},isExported:!0},HY={description:j(`Next coupon date after the settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=12/o,l=UY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-(I(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},UY={description:j(`Number of coupons between settlement and maturity.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=1,l=a,u=12/o;for(;l>i;)l=ha(ya(z(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},WY={description:j(`Last coupon date prior to or on the settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=12/o,l=UY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},GY={description:j(`Cumulative interest paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(pJ(u));if(o<=0)return new N(nJ(o));if(s<=0)return new N(sJ(s));if(o>s)return new N(tJ(o,s));if(s>u)return new N(oJ(s,u));if(c<=0)return new N(EJ(c));if(l<=0)return new N(bJ(l));let f=0;for(let e=o;e<=s;e++)f+=aX(c,e,u,l,0,d);return f},isExported:!0},KY={description:j(`Cumulative principal paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(pJ(u));if(o<=0)return new N(nJ(o));if(s<=0)return new N(sJ(s));if(o>s)return new N(tJ(o,s));if(s>u)return new N(oJ(s,u));if(c<=0)return new N(EJ(c));if(l<=0)return new N(bJ(l));let f=0;for(let e=o;e<=s;e++)f+=yX(c,e,u,l,0,d);return f},isExported:!0},qY={description:j(`Depreciation via declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`month (number, optional)`,j(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=Math.trunc(I(r,this.locale)),l=i.length?Math.trunc(I(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new N(Uq(a));if(o<0)return new N(OJ(o));if(c<=0)return new N(yJ(c));if(s<=0)return new N(cJ(s));if(1>l||l>12)return new N(uJ(l));if(c>u)return new N(hJ(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},JY=`#,##0.00`,YY={description:j(`Depreciation via double-declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(a<0)return new N(Uq(a));if(o<0)return new N(OJ(o));if(c<=0)return new N(yJ(c));if(s<=0)return new N(cJ(s));if(c>s)return new N(vJ(c,s));if(l<=0)return new N(qq(l));if(a===0||o>=a)return{value:0,format:JY};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:JY};if(c<=1)return{value:a*u,format:JY};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:JY}},isExported:!0},XY={description:j(`Discount rate of a security based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(xJ(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return(c-s)/c/u},isExported:!0},ZY={description:j(`Convert a decimal fraction to decimal value.`),args:[k(`fractional_price (number)`,j(`The price quotation given using fractional decimal conventions.`)),k(`unit (number)`,j(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(FJ(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},QY={description:j(`Convert a decimal value to decimal fraction.`),args:[k(`decimal_price (number)`,j(`The price quotation given as a decimal value.`)),k(`unit (number)`,j(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(FJ(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},$Y={description:j(`Number of periods for an investment to reach a value.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=I(n,this.locale),l=I(r,this.locale),u=Math.trunc(I(i,this.locale)),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(lJ(o,s));if(zJ(u))return new N(Gq(u));if(RJ(d))return new N(Kq(d));if(c<0)return new N(TJ(c));if(l<0)return new N(IJ(l));let f=xa(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},eX={description:j(`Annual effective interest rate.`),args:[k(`nominal_rate (number)`,j(`The nominal interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(dJ(n)):r<=0?new N(_J(r)):(1+n/r)**+r-1},isExported:!0};function tX(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let nX={description:j(`Future value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`present_value (number, default=0)`,j(`The current value of the annuity.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:tX(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),+!!R(i)),format:`#,##0.00`}},isExported:!0},rX={description:j(`Future value of principal from series of rates.`),args:[k(`principal (number)`,j(`The amount of initial capital or value to compound against.`)),k(`rate_schedule (number, range<number>)`,j(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=I(e,this.locale);return ao([t],(e,t)=>e*(1+I(t,this.locale)),n)},isExported:!0},iX={description:j(`Calculates effective interest rate.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested in the security.`)),k(`redemption (number)`,j(`The amount to be received at maturity.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(c<=0)return new N(iJ(c));if(s<=0)return new N(DJ(s));if(RJ(l))return new N(Kq(l));let u=xa(a,o,l);return(s-c)/c/u},isExported:!0};function aX(e,t,n,r,i,a){return _X(e,n,r,i,a)-yX(e,t,n,r,i,a)}let oX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:aX(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),I(i,this.locale),+!!R(a)),format:`#,##0.00`}},isExported:!0},sX=.1,cX={description:j(`Internal rate of return given periodic cashflows.`),args:[k(`cashflow_amounts (number, range<number>)`,j(`An array or range containing the income or payments associated with the investment.`)),k(`rate_guess (number, default=${sX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:sX}){let n=I(t,this.locale);if(n<=-1)return new N(wJ(n));let r=!1,i=!1,a=[];if(ro([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new N(Hq);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:IY(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},lX={description:j(`Returns the interest paid at a particular period of an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`period (number)`,j(`The period for which you want to view the interest payment.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);return o===0?new N(fJ(o)):-1*(s-a/o*s)*i},isExported:!0},uX={description:j(`Modified Macaulay duration.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=$Y.compute.bind(this)(e,t,n,r,i,a),s=I(r,this.locale),c=Math.trunc(I(i,this.locale));return I(o,this.locale)/(1+s/c)},isExported:!0},dX={description:j(`Modified internal rate of return.`),args:[k(`cashflow_amounts (range<number>)`,j(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),k(`financing_rate (number)`,j(`The interest rate paid on funds invested.`)),k(`reinvestment_return_rate (number)`,j(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=fo(e).flat().filter(e=>e.value!==null).map(e=>I(e,this.locale)),o=a.length,s=0,c=0;for(let e of C(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new N(Hq);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},fX={description:j(`Annual nominal interest rate.`),args:[k(`effective_rate (number)`,j(`The effective interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(Zq(n)):r<=0?new N(_J(r)):((n+1)**(1/r)-1)*r},isExported:!0},pX={description:j(`Number of payment periods for an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`payment_amount (number)`,j(`The amount of each payment made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function mX(e,t,n,r){let i=0;return oo(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let hX={description:j(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow (number, range<number>, repeating)`,j(`The future cash flows.`))],compute:function(e,...t){let n=I(e,this.locale);return n===-1?new N(Jq(n)):{value:mX(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},gX={description:j(`Computes the number of periods needed for an investment to reach a value.`),args:[k(`rate (number)`,j(`The rate at which the investment grows each period.`)),k(`present_value (number)`,j(`The investment's current value.`)),k(`future_value (number)`,j(`The investment's desired future value.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(EJ(r)):i<=0?new N(bJ(i)):a<=0?new N(rJ(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function _X(e,t,n,r,i){if(t<=0)throw new N(pJ(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let vX={description:j(`Periodic payment for an annuity investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){let a=I(t,this.locale),o=I(e,this.locale),s=+!!R(i),c=I(r,this.locale);return{value:_X(o,a,I(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function yX(e,t,n,r,i,a){if(n<=0)throw new N(pJ(n));if(t<=0||t>n)throw new N(mJ(n));let o=_X(e,n,r,i,a);return a===1&&t===1?o:o+-tX(e,a===0?t-1:t-2,o,r+o*a,0)*e}let bX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=I(n,this.locale),s=I(e,this.locale),c=I(t,this.locale),l=+!!R(a),u=I(i,this.locale);return{value:yX(s,c,o,I(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},xX={description:j(`Present value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},SX={description:j(`Price of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(lJ(s,c));if(zJ(f))return new N(Gq(f));if(RJ(p))return new N(Kq(p));if(l<0)return new N(TJ(l));if(u<0)return new N(IJ(u));if(d<=0)return new N(DJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},CX={description:j(`Price of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the security at time of purchase.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(Yq(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return c-s*c*u},isExported:!0},wX={description:j(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o<=c)return new N(MJ(o,c));if(o>=s)return new N(lJ(o,s));if(RJ(d))return new N(Kq(d));if(l<0)return new N(TJ(l));if(u<0)return new N(IJ(u));let f=xa(o,s,d),p=xa(o,c,d),m=100+xa(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},TX=.1,EX={description:j(`Interest rate of an annuity investment.`),args:[k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_per_period (number)`,j(`The amount per period to be paid.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY),k(`rate_guess (number, default=${TX})`,j(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:TX}){let o=I(e,this.locale),s=I(t,this.locale),c=+!!R(i),l=I(a,this.locale)||TX,u=I(r,this.locale),d=I(n,this.locale);return o<=0?new N(pJ(o)):LJ([s,d,u])?l<=-1?new N(wJ(l)):(u-=s*c,d+=s*c,{value:IY(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new N(j(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},DX={description:j(`Amount received at maturity for a security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested (irrespective of face value of each security).`)),k(`discount (number)`,j(`The discount rate of the security invested in.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));return a>=o?new N(lJ(a,o)):RJ(l)?new N(Kq(l)):s<=0?new N(iJ(s)):c<=0?new N(Yq(c)):s/(1-c*xa(a,o,l))},isExported:!0},OX={description:j(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[k(`number_of_periods (number)`,j(`The number of periods.`)),k(`present_value (number)`,j(`The present value of the investment.`)),k(`future_value (number)`,j(`The future value of the investment.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(pJ(r)):(a/i)**(1/r)-1},isExported:!0},kX={description:j(`Depreciation of an asset using the straight-line method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},AX={description:j(`Depreciation via sum of years digit method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);if(s<=0)return new N(yJ(s));if(o<=0)return new N(cJ(o));if(s>o)return new N(vJ(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function jX(e,t,n){return 100*(1-n*xa(e,t,2))}let MX={description:j(`Price of a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);return r>=i?new N(lJ(r,i)):BJ(r,i,this.locale)?a<=0?new N(Yq(a)):a>=1?new N(Xq(a)):jX(r,i,a):new N(jJ(r,i))},isExported:!0},NX={description:j(`Equivalent rate of return for a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(lJ(r,i));if(!BJ(r,i,this.locale))return new N(jJ(r,i));if(a<=0)return new N(Yq(a));if(a>=1)return new N(Xq(a));let o=JJ.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=jX(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},PX={description:j(`The yield of a US Treasury bill based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(lJ(r,i));if(!BJ(r,i,this.locale))return new N(jJ(r,i));if(a<=0)return new N(xJ(a));let o=xa(r,i,2);return(100-a)/a*(1/o)},isExported:!0},FX={description:j(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`start (number)`,j(`Starting period to calculate depreciation.`)),k(`end (number)`,j(`Ending period to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The number of months in the first year of depreciation.`)),k(`no_switch (number, default=false)`,j(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:j(`Switch to straight-line depreciation`)},{value:!0,label:j(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=I(e,this.locale),c=I(t,this.locale),l=I(n,this.locale),u=Math.trunc(I(r,this.locale)),d=Math.trunc(I(i,this.locale)),f=I(a,this.locale),p=R(o);if(s<0)return new N(Uq(s));if(c<0)return new N(OJ(c));if(l<=0)return new N(cJ(l));if(u<0)return new N(NJ(u));if(d<0)return new N(Qq(d));if(u>d)return new N(PJ(u,d));if(d>l)return new N($q(d,l));if(f<=0)return new N(qq(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},IX={description:j(`Internal rate of return given non-periodic cash flows.`),args:[k(`cashflow_amounts (range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),k(`rate_guess (number, default=${TX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:TX}){let r=I(n,this.locale);if(!_h(e,t))return new N(Vq);let i=e.flat().map(e=>I(e,this.locale)),a=t.flat().map(e=>I(e,this.locale));if(!LJ(i))return new N(Hq);if(a.some(e=>e<a[0]))return new N(eJ(a[0]));if(r<=-1)return new N(wJ(r));let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return IY(e=>{let t=c[0];for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},LX={description:j(`Net present value given to non-periodic cash flows..`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow_amounts (number, range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (number, range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=I(e,this.locale);if(!_h(t,n))return new N(Vq);let i=B(t).flat().map(e=>qa(e,this.locale)),a=B(n).flat().map(e=>qa(e,this.locale));if(a.some(e=>e<a[0]))return new N(eJ(a[0]));if(r<=0)return new N(EJ(r));if(i.length===1)return i[0];let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of C(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},RX={description:j(`Annual yield of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(lJ(s,c));if(zJ(f))return new N(Gq(f));if(RJ(p))return new N(Kq(p));if(l<0)return new N(TJ(l));if(u<=0)return new N(xJ(u));if(d<=0)return new N(DJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function b(e){return v(u,g,h,e,_,d)}function ee(e){return y(u,g,h,e,_)}return(IY(b,ee,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},zX={description:j(`Annual yield of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(xJ(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return(c/s-1)/u},isExported:!0},BX={description:j(`Annual yield of a security paying interest at maturity.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(lJ(o,s));if(RJ(d))return new N(Kq(d));if(o<c)return new N(AJ(o,c));if(l<0)return new N(TJ(l));if(u<=0)return new N(xJ(u));let f=xa(c,s,d),p=xa(c,o,d),m=xa(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var VX=l({CELL:()=>UX,ISBLANK:()=>ZX,ISERR:()=>WX,ISERROR:()=>GX,ISFORMULA:()=>$X,ISLOGICAL:()=>KX,ISNA:()=>qX,ISNONTEXT:()=>JX,ISNUMBER:()=>YX,ISTEXT:()=>XX,NA:()=>QX});let HX=[{value:`address`,label:j(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:j(`Returns the column number of the cell in reference.`)},{value:`contents`,label:j(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:j(`Returns the format of the top left cell in reference.`)},{value:`row`,label:j(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:j(`Returns the type of data in the cell in reference. The following values are returned: "b" for a blank cell, "l" (for label) if the cell contains plain text, and "v" (for value) if the cell contains any other type of data.`)}],UX={description:j(`Gets information about a cell.`),args:[k(`info_type (string)`,j(`The type of information requested.`),HX),k(`reference (any, range<any>)`,j(`The reference to the cell.`))],compute:function(e,t){let n=L(e).toLowerCase();if(!HX.map(e=>e.value).includes(n))return new N(j(`The info_type should be one of %s.`,HX.join(`, `)));let r=B(t)[0][0],i=r.position;if(i===void 0)return new N(j(`The reference is invalid.`));switch(n){case`address`:return(this.__originSheetId===i.sheetId?``:this.getters.getSheetName(i.sheetId)+`!`)+E(i.col,i.row,{colFixed:!0,rowFixed:!0});case`col`:return i.col+1;case`contents`:return r.value;case`format`:return r.format||``;case`row`:return i.row+1;case`type`:return r.value===null?`b`:ou(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},WX={description:j(`Whether a value is an error other than #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)&&t!==M.NotAvailable},isExported:!0},GX={description:j(`Whether a value is an error.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)},isExported:!0},KX={description:j("Whether a value is `true` or `false`."),args:[k(`value (any)`,j(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},qX={description:j(`Whether a value is the error #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){return e?.value===M.NotAvailable},isExported:!0},JX={description:j(`Whether a value is non-textual.`),args:[k(`value (any)`,j(`The value to be checked.`))],compute:function(e){return!XX.compute.bind(this)(e)},isExported:!0},YX={description:j(`Whether a value is a number.`),args:[k(`value (any)`,j(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},XX={description:j(`Whether a value is text.`),args:[k(`value (any)`,j(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&F(e?.value)===!1},isExported:!0},ZX={description:j(`Whether the referenced cell is empty`),args:[k(`value (any)`,j(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},QX={description:j(`Returns the error value #N/A.`),args:[],compute:function(){return{value:M.NotAvailable}},isExported:!0},$X={description:j(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new Li(Ha):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var eZ=l({AND:()=>tZ,FALSE:()=>nZ,IF:()=>rZ,IFERROR:()=>iZ,IFNA:()=>aZ,IFS:()=>oZ,NOT:()=>sZ,OR:()=>cZ,SWITCH:()=>lZ,TRUE:()=>uZ,XOR:()=>dZ});let tZ={description:j("Logical `and` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=Qh(e);return n?t:new N(Do)},isExported:!0},nZ={description:j("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},rZ={description:j(`Returns value depending on logical expression.`),args:[k(`logical_expression (boolean, range<boolean>)`,j(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),k(`value_if_true (any, range)`,j(`The value the function returns if logical_expression is TRUE.`)),k(`value_if_false (any, range, default=FALSE)`,j(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Eh(e)?po(rZ.compute,[e,t,n]):(R(wh(e))?t:n)??{value:0}},isExported:!0},iZ={description:j(`Value if it is not an error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an error.`))],compute:function(e,t){return Eh(e)?po(iZ.compute,[e,t]):(F(wh(e)?.value)?t:e)??{value:0}},isExported:!0},aZ={description:j(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not #N/A an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return Eh(e)?po(aZ.compute,[e,t]):(wh(e)?.value===M.NotAvailable?t:e)??{value:0}},isExported:!0},oZ={description:j(`Returns a value depending on multiple logical expressions.`),args:[k(`condition (any, range, repeating)`,j(`The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.`)),k(`value (any, range, repeating)`,j(`The value to be returned if its corresponding condition is TRUE.`))],compute:function(...e){if(e.length%2!=0)return new N(j(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(Eh(e[0]))return po(oZ.compute,e);let t=R(wh(e.shift())),n=e.shift();if(t)return n??{value:0}}return new N(j(`No match.`))},isExported:!0},sZ={description:j(`Returns opposite of provided logical value.`),args:[k(`logical_expression (boolean)`,j(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!R(e)},isExported:!0},cZ={description:j("Logical `or` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=$h(e);return n?t:new N(Do)},isExported:!0},lZ={description:j(`Returns a value by comparing cases to an expression.`),args:[k(`expression (number, boolean, string)`,j(`The value to be checked.`)),k(`case (any, repeating)`,j(`Case to be checked against expression.`)),k(`value (any, repeating)`,j(`Value to be returned if its corresponding case matches expression.`)),k(`default (any, default="empty")`,j(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Ba(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&F(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},uZ={description:j("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},dZ={description:j("Logical `xor` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let t=!1,n=!1;return ho(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new N(Do)},isExported:!0};function fZ(e,t){let n=t.getPivotId(e);if(!n)throw new N(j(`There is no pivot with id "%s"`,e));return n}function pZ(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new N(j(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function mZ(e){if(e.length%2!=0)throw new N(j(`Function PIVOT takes an even number of arguments.`))}function hZ(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=wn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Li;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&In(D(e.__originCellPosition),n))throw new Ii;r.push(o)}for(let i of n)i.computedBy&&r.push(...e.getters.getMeasureFullDependencies(t,i));let a=e.__originCellPosition;a&&r.length&&(e.updateDependencies?.(a),e.addDependencies?.(a,r))}var gZ=l({ADDRESS:()=>yZ,CHOOSE:()=>IZ,COLUMN:()=>bZ,COLUMNS:()=>xZ,DROP:()=>LZ,FORMULATEXT:()=>zZ,HLOOKUP:()=>SZ,INDEX:()=>CZ,INDIRECT:()=>wZ,LOOKUP:()=>TZ,MATCH:()=>EZ,OFFSET:()=>FZ,PIVOT:()=>PZ,PIVOT_HEADER:()=>NZ,PIVOT_VALUE:()=>MZ,ROW:()=>DZ,ROWS:()=>OZ,TAKE:()=>RZ,VLOOKUP:()=>kZ,XLOOKUP:()=>jZ});let _Z=[{value:!0,label:j(`A1 style (default)`)},{value:!1,label:j(`R1C1 style`)}],vZ=[{value:!0,label:j(`Approximate match (default)`)},{value:!1,label:j(`Exact match`)}],yZ={description:j(`Returns a cell reference as a string. `),args:[k(`row (number)`,j(`The row number of the cell reference. `)),k(`column (number)`,j(`The column number (not name) of the cell reference. A is column number 1. `)),k(`absolute_relative_mode (number, default=1)`,j(`An indicator of whether the reference is row/column absolute.`),[{value:1,label:j(`Absolute row and column (e.g. $A$1)`)},{value:2,label:j(`Absolute row, relative column (e.g. A$1)`)},{value:3,label:j(`Relative row, absolute column (e.g. $A1)`)},{value:4,label:j(`Relative row and column (e.g. A1)`)}]),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),_Z),k(`sheet (string, optional)`,j(`A string indicating the name of the sheet into which the address points.`))],compute:function(e,t,n={value:1},r={value:!0},i){let a=Ya(e,this.locale),o=Ya(t,this.locale);if(a<1)return new N(yh(a));if(o<1)return new N(yh(o));let s=Ya(n,this.locale);if(![1,2,3,4].includes(s))return new N(Ua(1,4,s));let c=R(r),l;if(c){let e={rowFixed:[1,2].includes(s),colFixed:[1,3].includes(s)};l=E(o-1,a-1,e)}else l=([1,2].includes(s)?`R${a}`:`R[${a}]`)+([1,3].includes(s)?`C${o}`:`C[${o}]`);return i===void 0?l:Qo(L(i),l)},isExported:!0},bZ={description:j(`Column number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.col+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.col;return t.length===1?r+1:co(t.length,1,e=>({value:r+e+1}))},isExported:!0},xZ={description:j(`Number of columns in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose column count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t.length},isExported:!0},SZ={description:j(`Horizontal lookup`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The row index of the value to be returned, where the first row in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.`),vZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a[0].length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[R(r.value)?bo(a,e,`nextSmaller`,`asc`,a.length,o):xo(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ba(e):s[i-1]},isExported:!0},CZ={description:j(`Returns the content of a cell, specified by row and column offset.`),args:[k(`reference (any, range)`,j(`The range of cells from which the values are returned.`)),k(`row (number, default=0)`,j(`The index of the row to be returned from within the reference range of cells.`)),k(`column (number, default=0)`,j(`The index of the column to be returned from within the reference range of cells.`))],compute:function(e,t={value:0},n={value:0}){let r=B(e),i=I(t.value,this.locale),a=I(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new N(j(`Index out of range.`)):i===0&&a===0?r:i===0?[r[a-1]]:a===0?r.map(e=>[e[i-1]]):r[a-1][i-1]},isExported:!0},wZ={description:j(`Returns the content of a cell, specified by a string.`),args:[k(`reference (string)`,j(`The range of cells from which the values are returned.`)),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),_Z)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Li(j(`Reference should be defined.`));if(!R(t))return new N(j(`R1C1 notation is not supported.`));let r=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);let a=this.getters.getNamedRange(n),o=a?a.range:this.getters.getRangeFromSheetXC(r,n);if(o===void 0||o.invalidXc||o.invalidSheetName)return new Li;i&&this.addDependencies?.(i,[o]);let s=[];for(let e=o.zone.left;e<=o.zone.right;e++){let t=[];for(let n=o.zone.top;n<=o.zone.bottom;n++){let r={sheetId:o.sheetId,col:e,row:n};t.push(this.getFormulaResult(r))}s.push(t)}return s.length===1&&s[0].length===1?s[0][0]:s},isExported:!0},TZ={description:j(`Look up a value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`search_array (any, range)`,j(`One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.`)),k(`result_range (any, range, optional)`,j(`The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.`))],compute:function(e,t,n){let r=B(t),i=B(n),a=r.length,o=r[0].length,s=o>=a,c=bo(r,e,`nextSmaller`,`asc`,s?o:a,s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value);return c===-1||s&&r[0][c]===void 0||!s&&r[c][o-1]===void 0?Ba(e):i[0].length===0?s?r[a-1][c]:r[c][o-1]:(a=i.length,o=i[0].length,a!==1&&o!==1?new N(j(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},EZ={description:j(`Position of item in range that matches value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The one-dimensional array to be searched.`)),k(`search_type (number, default=1)`,j(`The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.`),[{value:1,label:j(`Ascending order (default)`)},{value:0,label:j(`Exact match`)},{value:-1,label:j(`Descending order`)}])],compute:function(e,t,n={value:1}){let r=I(n,this.locale),i=B(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new N(j(`The range must be a single row or a single column.`));let s=-1,c=a===1?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,l=a===1?i[0].length:i.length;switch(r=Math.sign(r),r){case 1:s=bo(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=xo(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=bo(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ba(e):s+1},isExported:!0},DZ={description:j(`Row number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition?.row===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.row+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.row;return t[0].length===1?r+1:co(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},OZ={description:j(`Number of rows in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose row count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t[0].length},isExported:!0},kZ={description:j(`Vertical lookup.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The column index of the value to be returned, where the first column in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.`),vZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a.length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=R(r.value)?bo(a,e,`nextSmaller`,`asc`,a[0].length,o):xo(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ba(e):c},isExported:!0},AZ={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},jZ={description:j(`Search a range for a match and return the corresponding item from a second range.`),args:[k(`search_key (string,number,boolean)`,j(`The value to search for.`)),k(`lookup_range (any, range)`,j(`The range to consider for the search. Should be a single column or a single row.`)),k(`return_range (any, range)`,j(`The range containing the return value. Should have the same dimensions as lookup_range.`)),k(`if_not_found (any, optional)`,j(`If a valid match is not found, return this value.`)),k(`match_mode (any, default=0)`,j(`Specifies how to match search_key with the items in lookup_range. `),[{value:0,label:j(`Exact match (default)`)},{value:-1,label:j(`Exact match or next smaller item`)},{value:1,label:j(`Exact match or next larger item`)},{value:2,label:j(`Wildcard character match`)}]),k(`search_mode (any, default=1)`,j(`Specifies the search mode to use. By default, a first to last search will be used.`),[{value:1,label:j(`Search first to last (default)`)},{value:-1,label:j(`Search last to first`)},{value:2,label:j(`Binary search (sorted ascending order)`)},{value:-2,label:j(`Binary search (sorted descending order)`)}])],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(I(i.value,this.locale)),s=Math.trunc(I(a.value,this.locale)),c=B(t),l=B(n);if(c.length!==1&&c[0].length!==1)return new N(j(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new N(j(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new N(j(`match_mode should be a value in [-1, 0, 1, 2].`));let u=c.length===1?`col`:`row`;if(o===2&&[-2,2].includes(s))return new N(j(`The search and match mode combination is not supported for XLOOKUP evaluation.`));if(u===`col`?l[0].length!==c[0].length:l.length!==c.length)return new N(j(`return_range should have the same dimensions as lookup_range.`));let d=u===`col`?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,f=u===`col`?c[0].length:c.length,p=AZ[o],m=s===-1,h=s===2||s===-2?bo(c,e,p,s===2?`asc`:`desc`,f,d):xo(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ba(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},MZ={description:j(`Get the value from a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`measure_name (string)`,j(`Name of the measure.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,boolean,repeating,optional)`,j(`Value.`))],compute:function(e,t,...n){let r=L(e),i=L(t),a=fZ(r,this.getters);pZ(a,i,this.getters),mZ(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);hZ(this,a,s.measures.filter(e=>e.id===i)),o.init({reload:o.needsReevaluation});let c=o.assertIsValid({throwOnError:!1});if(c)return c;if(!o.areDomainArgsFieldsValid(n)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let l=o.parseArgsToPivotDomain(n);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(a)?.trackValue(i,l),o.getPivotCellValueAndFormat(i,l)}},NZ={description:j(`Get the header of a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,value,repeating,optional)`,j(`Value.`))],compute:function(e,...t){let n=L(e),r=fZ(n,this.getters);mZ(t);let i=this.getters.getPivot(r);hZ(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let o=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(r)?.trackHeader(o);let s=o.at(-1);if(s?.field===`measure`)return i.getPivotMeasureValue(L(s.value),o);let{value:c,format:l}=i.getPivotHeaderValueAndFormat(o);return{value:c,format:!s||s.field===`measure`||s.value===`false`?void 0:l}}},PZ={description:j(`Get a pivot table.`),args:[k(`pivot_id (string)`,j(`ID of the pivot.`)),k(`row_count (number, optional)`,j(`number of rows`)),k(`include_total (boolean, default=TRUE)`,j(`Whether to include total/sub-totals or not.`)),k(`include_column_titles (boolean, default=TRUE)`,j(`Whether to include the column titles or not.`)),k(`column_count (number, optional)`,j(`number of columns`)),k(`include_measure_titles (boolean, default=TRUE)`,j(`Whether to include the measure titles row or not.`))],compute:function(e,t,n,r,i,a){let o=fZ(L(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=qg(c,t,n,r,i,a,this.locale);if(l.numberOfRows<0)return new N(j(`The number of rows must be positive.`));if(l.numberOfColumns<0)return new N(j(`The number of columns must be positive.`));hZ(this,o,c.measures),s.init({reload:s.needsReevaluation});let u=s.assertIsValid({throwOnError:!1});if(u)return u;let d=s.getCollapsedTableStructure();if(d.numberOfCells>5e5)return new N(qy(d.numberOfCells,this.locale));let f=d.getPivotCells(l),p=this.getters.getPivotName(o),{numberOfCols:m,numberOfRows:h}=d.getPivotTableDimensions(l);if(h===0)return[[{value:p}]];let g=[];for(let e of C(0,m)){g[e]=[];for(let t of C(0,h)){let n=f[e][t];switch(n.type){case`EMPTY`:g[e].push({value:``});break;case`HEADER`:let t=s.getPivotHeaderValueAndFormat(n.domain);g[e].push(Rg(n.domain,t));break;case`MEASURE_HEADER`:g[e].push(s.getPivotMeasureValue(n.measure,n.domain));break;case`VALUE`:g[e].push(s.getPivotCellValueAndFormat(n.measure,n.domain));break;case`ROW_GROUP_NAME`:let r=s.definition.rows.find(e=>e.nameWithGranularity===n.rowField)?.displayName;g[e].push({value:r||``});break}}}return(l.displayColumnHeaders||l.displayMeasuresRow)&&f[0][0].type===`EMPTY`&&(g[0][0]={value:p}),g}},FZ={description:j(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[k(`cell_reference (any, range<any>)`,j(`The starting point from which to count the offset rows and columns.`)),k(`offset_rows (number)`,j(`The number of rows to offset by.`)),k(`offset_columns (number)`,j(`The number of columns to offset by.`)),k(`height (number, default='height of cell_reference')`,j(`The number of rows of the range to return starting at the offset target.`)),k(`width (number, default='width of cell_reference')`,j(`The number of columns of the range to return starting at the offset target.`))],compute:function(e,t,n,r,i){if(e===void 0)return new Li(Ha);let a=B(e),o=a[0][0];if(o===void 0)return new N(j(`The range is out of bounds.`));if(o.position===void 0)return new Li(Ha);let s=a[0].length,c=a.length;if(r){let e=I(r,this.locale);if(e<1)return new N(j(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=I(i,this.locale);if(e<1)return new N(j(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let l=I(t,this.locale),u=I(n,this.locale),d=this.__originCellPosition;d&&this.updateDependencies?.(d);let f=o.position.col+u,p=o.position.row+l;if(f<0||p<0)return new Li(j(`OFFSET evaluates to an out of bounds range.`));let m={left:f,top:p,right:f+c-1,bottom:p+s-1},h=o.position.sheetId,g=this.getters.getRangeFromZone(h,m);return g.invalidXc||g.invalidSheetName?new Li:(d&&this.addDependencies?.(d,[g]),co(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},IZ={description:j(`Returns an element from a list of choices based on index.`),args:[k(`index (number)`,j(`Which choice to return.`)),k(`choice (any, range<any>, repeating)`,j(`A potential value to return. May be a reference to a cell or an individual value.`))],compute:function(e,...t){let n=Math.floor(I(e,this.locale))-1;return n<0||n>=t.length?new N(j(`Index for CHOOSE is invalid. Valid values are between 1 and %(choices)s inclusive.`,{choices:t.length})):t[n]??new N(j(`Choice is undefined.`))},isExported:!0},LZ={description:j(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to drop rows or columns`)),k(`rows (number)`,j(`The number of rows to drop. A negative value drops from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to exclude. A negative value drops from the end of the array.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=e;if(Math.abs(i)>=e.length||Math.abs(r)>=e[0].length)return new N(j(`The number of rows or column to exclude must be smaller than the number of elements in the array.`));a=i>=0?a.slice(i):a.slice(0,a.length+i);for(let e=0;e<a.length;e++)r>=0?a[e]=a[e].slice(r):a[e]=a[e].slice(0,a[e].length+r);return a},isExported:!0},RZ={description:j(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to take rows or columns.`)),k(`rows (number)`,j(`The number of rows to take. A negative value takes from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to take. A negative value takes from the end of the array.`))],compute:function(e,t,n){let r=t?I(t,this.locale):e[0].length,i=I(n,this.locale),a=e;if((Math.abs(i)>=e.length||i===0)&&(i=e.length),Math.abs(r)>=e[0].length&&(r=e[0].length),a=i>=0?a.slice(0,i):a.slice(a.length+i,a.length),r===0)return new N(j(`The number of rows can not be zero.`));for(let e=0;e<a.length;e++)r>0?a[e]=a[e].slice(0,r):a[e]=a[e].slice(a[e].length+r,a[e].length);return a},isExported:!0},zZ={description:j(`Returns a formula as a string.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new Li(Ha);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Ri(j(`The cell does not contain a formula.`))},isExported:!0};var BZ=l({ADD:()=>VZ,CONCAT:()=>HZ,DIVIDE:()=>UZ,EQ:()=>qZ,GT:()=>YZ,GTE:()=>XZ,LT:()=>ZZ,LTE:()=>QZ,MINUS:()=>$Z,MULTIPLY:()=>eQ,NE:()=>tQ,POW:()=>nQ,SPILLED_RANGE:()=>rQ,UMINUS:()=>iQ,UNARY_PERCENT:()=>aQ,UPLUS:()=>oQ});let VZ={description:j(`Sum of two numbers.`),args:[k(`value1 (number)`,j(`The first addend.`)),k(`value2 (number)`,j(`The second addend.`))],compute:function(e,t){return{value:I(e,this.locale)+I(t,this.locale),format:e?.format||t?.format}}},HZ={description:j(`Concatenation of two values.`),args:[k(`value1 (string)`,j(`The value to which value2 will be appended.`)),k(`value2 (string)`,j(`The value to append to value1.`))],compute:function(e,t){return Xa(e,this.locale)+Xa(t,this.locale)},isExported:!0},UZ={description:j(`One number divided by another.`),args:[k(`dividend (number)`,j(`The number to be divided.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return n===0?new Vi(j(`The divisor must be different from zero.`)):{value:I(e,this.locale)/n,format:e?.format||t?.format}}};function WZ(e){return e===void 0||e.value===null}let GZ={number:0,string:``,boolean:!1};function KZ(e,t,n=2e-16){return Math.abs(e-t)<n}let qZ={description:j(`Equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for equality.`))],compute:function(e,t){if(F(e?.value))return e;if(F(t?.value))return t;let n=WZ(e)?GZ[typeof t?.value]:e?.value,r=WZ(t)?GZ[typeof e?.value]:t?.value;return typeof n==`string`&&(n=n.toUpperCase()),typeof r==`string`&&(r=r.toUpperCase()),typeof n==`number`&&typeof r==`number`?{value:KZ(n,r)}:{value:n===r}}};function JZ(e,t,n){if(F(e?.value))return e;if(F(t?.value))return t;let r=WZ(e)?GZ[typeof t?.value]:e?.value,i=WZ(t)?GZ[typeof e?.value]:t?.value;typeof r!=`number`&&(r=L(r).toUpperCase()),typeof i!=`number`&&(i=L(i).toUpperCase());let a=typeof r,o=typeof i;return a===`string`&&o===`number`?{value:!0}:o===`string`&&a===`number`?{value:!1}:{value:n(r,i)}}let YZ={description:j(`Strictly greater than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return JZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!KZ(e,t)&&e>t:e>t)}},XZ={description:j(`Greater than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return JZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?KZ(e,t)||e>t:e>=t)}},ZZ={description:j(`Less than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=XZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},QZ={description:j(`Less than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=YZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},$Z={description:j(`Difference of two numbers.`),args:[k(`value1 (number)`,j(`The minuend, or number to be subtracted from.`)),k(`value2 (number)`,j(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:I(e,this.locale)-I(t,this.locale),format:e?.format||t?.format}}},eQ={description:j(`Product of two numbers`),args:[k(`factor1 (number)`,j(`The first multiplicand.`)),k(`factor2 (number)`,j(`The second multiplicand.`))],compute:function(e,t){return{value:I(e,this.locale)*I(t,this.locale),format:e?.format||t?.format}}},tQ={description:j(`Not equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=qZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},nQ={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){return VG.compute.bind(this)(e,t)}},rQ={description:j(`Gets the spilled range of an array formula.`),args:[k(`ref (any, range<any>)`,j(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new Li(Ha);let t=B(e);if(t.length!==1||t[0].length!==1)return new N(j(`Only single-cell references are allowed to get the spilled range.`));let n=t[0][0];if(F(n.value))return n;if(n.position===void 0)return new Li(Ha);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new Li;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),co(i.right-i.left+1,i.bottom-i.top+1,(e,t)=>this.getFormulaResult({sheetId:a.sheetId,col:i.left+e,row:i.top+t}))},hidden:!0},iQ={description:j(`A number with the sign reversed.`),args:[k(`value (number)`,j(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-I(e,this.locale),format:e?.format}}},aQ={description:j(`Value interpreted as a percentage.`),args:[k(`percentage (number)`,j(`The value to interpret as a percentage.`))],compute:function(e){return I(e,this.locale)/100}},oQ={description:j(`A specified number, unchanged.`),args:[k(`value (any)`,j(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),sQ={transform:e=>e,inverseTransform:e=>e},cQ=1e-10,lQ=.0254,uQ=lQ/72,dQ=.3048,fQ=.9144,pQ=1609.34,mQ=1852,hQ=946073047258e4,gQ={g:{...sQ,category:`weight`},u:{...$(166053e-29),category:`weight`},grain:{...$(.0647989),category:`weight`},ozm:{...$(28.3495),category:`weight`},lbm:{...$(453.592),category:`weight`},stone:{...$(6350.29),category:`weight`},sg:{...$(14593.90294),category:`weight`},cwt:{...$(45359.237),category:`weight`},uk_cwt:{...$(50802.3),category:`weight`},ton:{...$(907184.74),category:`weight`},uk_ton:{...$(1016046.9),category:`weight`},m:{...sQ,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(cQ),category:`distance`},Picapt:{...$(uQ),category:`distance`},pica:{...$(lQ/6),category:`distance`},in:{...$(lQ),category:`distance`},ft:{...$(dQ),category:`distance`},yd:{...$(fQ),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(pQ),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(mQ),category:`distance`},ly:{...$(hQ),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...sQ,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...sQ,category:`pressure`},bar:{...$(1e5),category:`pressure`},mmHg:{...$(133.322),category:`pressure`},Torr:{...$(133.322),category:`pressure`},psi:{...$(6894.76),category:`pressure`},atm:{...$(101325),category:`pressure`},N:{...sQ,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...sQ,category:`energy`},eV:{...$(160218e-24),category:`energy`},e:{...$(1e-7),category:`energy`},flb:{...$(1.3558179483),category:`energy`},c:{...$(4.184),category:`energy`},cal:{...$(4.1868),category:`energy`},BTU:{...$(1055.06),category:`energy`},Wh:{...$(3600),category:`energy`},HPh:{...$(2684520),category:`energy`},W:{...sQ,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...sQ,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...sQ,category:`temperature`},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:`temperature`},F:{transform:e=>(e-32)*5/9+273.15,inverseTransform:e=>(e-273.15)*9/5+32,category:`temperature`},Rank:{...$(5/9),category:`temperature`},Reau:{transform:e=>e*1.25+273.15,inverseTransform:e=>(e-273.15)/1.25,category:`temperature`},"m^3":{...sQ,category:`volume`,order:3},"ang^3":{...$(cQ**3),category:`volume`,order:3},"Picapt^3":{...$(uQ**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$(lQ**3),category:`volume`,order:3},oz:{...$(295735295625e-16),category:`volume`},cup:{...$(237e-6),category:`volume`},pt:{...$(.0004731765),category:`volume`},uk_pt:{...$(568261e-9),category:`volume`},qt:{...$(.0009463529),category:`volume`},l:{...$(.001),category:`volume`},uk_qt:{...$(.0011365225),category:`volume`},gal:{...$(.0037854118),category:`volume`},uk_gal:{...$(.00454609),category:`volume`},"ft^3":{...$(dQ**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(fQ**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(pQ**3),category:`volume`,order:3},"Nmi^3":{...$(mQ**3),category:`volume`,order:3},"ly^3":{...$(hQ**3),category:`volume`,order:3},"m^2":{...sQ,category:`area`,order:2},"ang^2":{...$(cQ**2),category:`area`,order:2},"Picapt^2":{...$(uQ**2),category:`area`,order:2},"in^2":{...$(lQ**2),category:`area`,order:2},"ft^2":{...$(dQ**2),category:`area`,order:2},"yd^2":{...$(fQ**2),category:`area`,order:2},ar:{...$(100),category:`area`},Morgen:{...$(2500),category:`area`},uk_acre:{...$(4046.8564224),category:`area`},us_acre:{...$(4046.8726098743),category:`area`},ha:{...$(1e4),category:`area`},"mi^2":{...$(pQ**2),category:`area`,order:2},"Nmi^2":{...$(mQ**2),category:`area`,order:2},"ly^2":{...$(hQ**2),category:`area`,order:2},bit:{...sQ,category:`information`},byte:{...$(8),category:`information`},"m/s":{...sQ,category:`speed`},"m/hr":{...$(1/3600),category:`speed`},"km/hr":{...$(1/3.6),category:`speed`},mph:{...$(.44704),category:`speed`},kn:{...$(.5144444444),category:`speed`},admkn:{...$(.5147733333),category:`speed`}},_Q={shweight:`cwt`,lcwt:`uk_cwt`,hweight:`uk_cwt`,LTON:`uk_ton`,brton:`uk_ton`,pc:`parsec`,Pica:`Picapt`,d:`day`,mn:`min`,s:`sec`,p:`Pa`,at:`atm`,dy:`dyn`,ev:`eV`,hh:`HPh`,wh:`Wh`,btu:`BTU`,h:`HP`,cel:`C`,fah:`F`,kel:`K`,us_pt:`pt`,L:`l`,lt:`l`,ang3:`ang^3`,ft3:`ft^3`,in3:`in^3`,ly3:`ly^3`,m3:`m^3`,mi3:`mi^3`,yd3:`yd^3`,Nmi3:`Nmi^3`,Picapt3:`Picapt^3`,"Pica^3":`Picapt^3`,Pica3:`Picapt^3`,regton:`GRT`,ang2:`ang^2`,ft2:`ft^2`,in2:`in^2`,ly2:`ly^2`,m2:`m^2`,mi2:`mi^2`,Nmi2:`Nmi^2`,Picapt2:`Picapt^2`,"Pica^2":`Picapt^2`,Pica2:`Picapt^2`,yd2:`yd^2`,"m/h":`m/hr`,"m/sec":`m/s`},vQ={"":1,Y:1e24,Z:1e21,E:0xde0b6b3a7640000,P:0x38d7ea4c68000,T:0xe8d4a51000,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:2**80,Zi:2**70,Ei:2**60,Pi:2**50,Ti:2**40,Gi:2**30,Mi:2**20,ki:2**10},yQ={weight:j(`Weight`),distance:j(`Distance`),time:j(`Time`),pressure:j(`Pressure`),force:j(`Force`),energy:j(`Energy`),power:j(`Power`),magnetism:j(`Magnetism`),temperature:j(`Temperature`),volume:j(`Volume`),area:j(`Area`),information:j(`Information`),speed:j(`Speed`)},bQ=Object.entries(gQ).map(([e,t])=>({value:e,label:xQ(t.category)}));function xQ(e){return yQ[e]??``}function SQ(e){for(let[t,n]of Object.entries(vQ)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=gQ[r];if(!i&&_Q[r]&&(i=gQ[_Q[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var CQ=l({CONVERT:()=>wQ});let wQ={description:j(`Converts a numeric value to a different unit of measure.`),args:[k(`value (number)`,j(`the numeric value in start_unit to convert to end_unit`)),k(`start_unit (string)`,j(`The starting unit, the unit currently assigned to value`),bQ),k(`end_unit (string)`,j(`The unit of measure into which to convert value`),bQ)],compute:function(e,t,n){let r=I(e,this.locale),i=L(t),a=L(n),o=SQ(i),s=SQ(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:M.GenericError,message:j(`Incompatible units of measure ('%s' vs '%s')`,xQ(o.category),xQ(s.category))}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,a)}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,i)}},isExported:!0};var TQ=l({CHAR:()=>kQ,CLEAN:()=>AQ,CONCATENATE:()=>jQ,EXACT:()=>MQ,FIND:()=>NQ,FORMAT_LARGE_NUMBER:()=>PQ,JOIN:()=>FQ,LEFT:()=>IQ,LEN:()=>LQ,LOWER:()=>RQ,MID:()=>zQ,PROPER:()=>BQ,REGEXEXTRACT:()=>HQ,REGEXREPLACE:()=>UQ,REGEXTEST:()=>VQ,REPLACE:()=>WQ,RIGHT:()=>GQ,SEARCH:()=>KQ,SPLIT:()=>qQ,SUBSTITUTE:()=>JQ,TEXT:()=>$Q,TEXTAFTER:()=>t$,TEXTBEFORE:()=>n$,TEXTJOIN:()=>YQ,TEXTSPLIT:()=>XQ,TRIM:()=>ZQ,UPPER:()=>QQ,VALUE:()=>e$});let EQ=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,DQ=[{value:0,label:j(`Case-sensitive (default)`)},{value:1,label:j(`Case-insensitive`)}],OQ=[{value:0,label:j(`Don't match to end (default)`)},{value:1,label:j(`Match to end`)}],kQ={description:j(`Gets character associated with number.`),args:[k(`table_number (number)`,j(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(I(e,this.locale));return t<1?new N(j(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},AQ={description:j(`Remove non-printable characters from a piece of text.`),args:[k(`text (string)`,j(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=Xa(e,this.locale),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},jQ={description:j(`Appends strings to one another.`),args:[k(`string (string, range<string>, repeating)`,j(`String to append in sequence.`))],compute:function(...e){return ao(e,(e,t)=>e+Xa(t,this.locale),``)},isExported:!0},MQ={description:j(`Tests whether two strings are identical.`),args:[k(`string1 (string)`,j(`The first string to compare.`)),k(`string2 (string)`,j(`The second string to compare.`))],compute:function(e,t){return Xa(e,this.locale)===Xa(t,this.locale)},isExported:!0},NQ={description:j(`First position of string found in text, case-sensitive.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=Xa(e,this.locale),i=Xa(t,this.locale),a=I(n,this.locale);if(i===``)return new N(j(`The text_to_search must be non-empty.`));if(a<1)return new N(j(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new N(j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},PQ={description:j(`Apply a large number format`),args:[k(`value (number)`,j(`The number.`)),k(`unit (string, optional)`,j(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:j(`Thousand`)},{value:`m`,label:j(`Million`)},{value:`b`,label:j(`Billion`)}])],compute:function(e,t){return{value:I(e,this.locale),format:Ql(e,t,this.locale)}}},FQ={description:j(`Concatenates elements of arrays with delimiter.`),args:[k(`delimiter (string)`,j(`The character or string to place between each concatenated value.`)),k(`value_or_array (string, range<string>, repeating)`,j(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=Xa(e,this.locale);return ao(t,(e,t)=>(e?e+n:``)+Xa(t,this.locale),``)}},IQ={description:j(`Substring from beginning of specified string.`),args:[k(`text (string)`,j(`The string from which the left portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;return n<0?new N(j(`The number_of_characters (%s) must be positive or null.`,n)):Xa(e,this.locale).substring(0,n)},isExported:!0},LQ={description:j(`Length of a string.`),args:[k(`text (string)`,j(`The string whose length will be returned.`))],compute:function(e){return Xa(e,this.locale).length},isExported:!0},RQ={description:j(`Converts a specified string to lowercase.`),args:[k(`text (string)`,j(`The string to convert to lowercase.`))],compute:function(e){return Xa(e,this.locale).toLowerCase()},isExported:!0},zQ={description:j(`A segment of a string.`),args:[k(`text (string)`,j(`The string to extract a segment from.`)),k(`starting_at (number)`,j(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),k(`extract_length (number)`,j(`The length of the segment to extract.`))],compute:function(e,t,n){let r=Xa(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return i<1?new N(j(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new N(j(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},BQ={description:j(`Capitalizes each word in a specified string.`),args:[k(`text_to_capitalize (string)`,j(`The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.`))],compute:function(e){return Xa(e,this.locale).replace(EQ,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},VQ={description:j(`Checks whether a string matches the supplied regular expression.`),args:[k(`text (string)`,j(`The string to test.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0}){let r=L(e),i=L(t),a=I(n,this.locale);if(i===``)return!0;if(r===``)return!1;if(a!==0&&a!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,a));let o=a===1?`gi`:`g`,s;try{s=new RegExp(i,o)}catch{return new N(j(`Invalid regular expression`))}return s.test(r)},isExported:!0},HQ={description:j(`Extract text from a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string on which you want to extract text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`return_mode (number, default=0)`,j(`0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array.`),[{value:0,label:j(`First match`)},{value:1,label:j(`All matches`)},{value:2,label:j(`Capture groups of first match`)}]),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0},r={value:0}){let i=L(e),a=L(t),o=I(n,this.locale),s=I(r,this.locale);if(i===``||a===``)return{value:``};if(o<0||o>2)return new N(j(`The return_mode (%s) must be 0, 1 or 2.`,o));if(s!==0&&s!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,s));let c=s===1?`gi`:`g`,l;try{l=new RegExp(a,c)}catch{return new N(j(`Invalid regular expression`))}let u=[...i.matchAll(l)];return u.length===0?{value:M.NotAvailable,message:j(`No matches found.`)}:o===0?u[0][0]:o===1?u.map(e=>[e[0]]):u[0].length<2?new N(j(`No capturing groups found.`)):u[0].slice(1).map(e=>[e])},isExported:!0},UQ={description:j(`Replace text in a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string in which you want to replace text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`replacement (string)`,j(`The text to use as the replacement.`)),k(`occurrence (number, default=0)`,j(`0 = replace all matches. A negative number counts from the end.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n,r={value:0},i={value:0}){let a=L(e),o=L(t),s=L(n),c=I(r,this.locale),l=I(i,this.locale);if(l!==0&&l!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,l));let u=l===1?`gi`:`g`,d;try{d=new RegExp(o,u)}catch{return new N(j(`Invalid regular expression`))}if(c!==0){let e=[...a.matchAll(d)];if(e.length===0||Math.abs(c)>e.length)return a;let t=c>0?c-1:e.length+c,n=e[t][0].length,r=e[t].index;return a.substring(0,r)+s+a.substring(r+n)}return a.replace(d,s)},isExported:!0},WQ={description:j(`Replaces part of a text string with different text.`),args:[k(`text (string)`,j(`The text, a part of which will be replaced.`)),k(`position (number)`,j(`The position where the replacement will begin (starting from 1).`)),k(`length (number)`,j(`The number of characters in the text to be replaced.`)),k(`new_text (string)`,j(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=I(t,this.locale);if(i<1)return new N(j(`The position (%s) must be greater than or equal to 1.`,i));let a=Xa(e,this.locale),o=I(n,this.locale),s=Xa(r,this.locale);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},GQ={description:j(`A substring from the end of a specified string.`),args:[k(`text (string)`,j(`The string from which the right portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;if(n<0)return new N(j(`The number_of_characters (%s) must be positive or null.`,n));let r=Xa(e,this.locale),i=r.length;return r.substring(i-n,i)},isExported:!0},KQ={description:j(`First position of string found in text, ignoring case.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=Xa(e,this.locale).toLowerCase(),i=Xa(t,this.locale).toLowerCase(),a=I(n,this.locale);if(i===``)return{value:M.GenericError,message:j(`The text_to_search must be non-empty.`)};if(a<1)return{value:M.GenericError,message:j(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:M.GenericError,message:j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},qQ={description:j(`Split text by specific character delimiter(s).`),args:[k(`text (string)`,j(`The text to divide.`)),k(`delimiter (string)`,j(`The character or characters to use to split text.`)),k(`split_by_each (boolean, default=true})`,j(`Whether or not to divide text around each character contained in delimiter.`)),k(`remove_empty_text (boolean, default=true)`,j(`Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters.`))],compute:function(e,t,n={value:!0},r={value:!0}){let i=Xa(e,this.locale),a=Ze(Xa(t,this.locale)),o=R(n),s=R(r);if(a.length<=0)return new N(j(`The delimiter (%s) must be not be empty.`,a));let c=o?RegExp(`[${a}]`,`g`):new RegExp(a,`g`),l=i.split(c);return s&&(l=l.filter(e=>e!==``)),fo([l])},isExported:!1},JQ={description:j(`Replaces existing text with new text in a string.`),args:[k(`text_to_search (string)`,j(`The text within which to search and replace.`)),k(`search_for (string)`,j(`The string to search for within text_to_search.`)),k(`replace_with (string)`,j(`The string that will replace search_for.`)),k(`occurrence_number (number, optional)`,j(`The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.`))],compute:function(e,t,n,r){let i=I(r,this.locale);if(i<0)return new N(j(`The occurrenceNumber (%s) must be positive or null.`,i));let a=Xa(e,this.locale),o=Xa(t,this.locale);if(o===``)return a;let s=Xa(n,this.locale),c=new RegExp(Ze(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},YQ={description:j(`Combines text from multiple strings and/or arrays.`),args:[k(`delimiter (string)`,j(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),k(`ignore_empty (boolean)`,j(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`),[{value:!0,label:j(`Ignore empty cells`)},{value:!1,label:j(`Include empty cells (default)`)}]),k(`texts (string, range<string>, repeating)`,j(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=Xa(e,this.locale),i=R(t),a=0;return ao(n,(e,t)=>i&&Xa(t,this.locale)===``?e:(a++?e+r:``)+Xa(t,this.locale),``)},isExported:!0},XQ={description:j(`Splits text into rows or columns using specified column and row delimiters.`),args:[k(`text (string)`,j(`The text to split.`)),k(`col_delimiter (string, range<string>)`,j(`Character or string to split columns by.`)),k(`row_delimiter (string, range<string>, optional)`,j(`Character or string to split rows by.`)),k(`ignore_empty (boolean, default=false)`,j(`Whether to ignore empty cells.`),[{value:!1,label:j(`Include empty cells (default)`)},{value:!0,label:j(`Ignore empty cells`)}]),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`pad_with (string, default="${M.NotAvailable}")`,j(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Ri){let o=L(e);if(o.length<=0)return new N(j(`No text to split.`));if(t===void 0&&n===void 0)return new N(j(`At least one delimiter must be provided.`));let s=B(t).flat().map(e=>Ze(L(e))),c=B(n).flat().map(e=>Ze(L(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new N(j(`The delimiters cannot be empty values.`));let l=R(r),u=I(i,this.locale);if(![0,1].includes(u))return new N(j(`match_mode should be a value of 0 or 1.`));let d=[],f=u===1?`gi`:`g`,p=c.filter(e=>!s.includes(e)),m=p.length?o.split(new RegExp(p.join(`|`),f)):[o];l&&(m=m.filter(e=>e!==``));let h=new RegExp(s.join(`|`),f);for(let e of m){let t=s.length?e.split(h):[e];l&&(t=t.filter(e=>e!==``)),d.push(t.map(e=>({value:e})))}let g=Math.max(...d.map(e=>e.length));for(let e of d)for(;e.length<g;)e.push(a);return fo(d)},isExported:!0},ZQ={description:j(`Removes space characters.`),args:[k(`text (string)`,j(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return Rt(Xa(e,this.locale))},isExported:!0},QQ={description:j(`Converts a specified string to uppercase.`),args:[k(`text (string)`,j(`The string to convert to uppercase.`))],compute:function(e){return Xa(e,this.locale).toUpperCase()},isExported:!0},$Q={description:j(`Converts a number to text according to a specified format.`),args:[k(`number (number)`,j(`The number, date or time to format.`)),k(`format (string)`,j(`The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.`))],compute:function(e,t){return H(I(e,this.locale),{format:L(t),locale:this.locale})},isExported:!0},e$={description:j(`Converts a string to a numeric value.`),args:[k(`value (number)`,j(`the string to be converted`))],compute:function(e){return I(e,this.locale)},isExported:!0},t$={description:j(`Returns text that occurs after a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter after which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`match_end (number, default=0))`,j(`Whether to treat the end of text as a delimiter.`),OQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:``}:{value:o};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(h)}},isExported:!0},n$={description:j(`Returns text that occurs before a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter before which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`match_end (number, default=0))`,j(`Whether to match a delimiter against the end of the text.`),OQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:o}:{value:``};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(0,h-u.length)}},isExported:!0};var r$=l({HYPERLINK:()=>i$});let i$={description:j(`Creates a hyperlink in a cell.`),args:[k(`url (string)`,j(`The full URL of the link enclosed in quotation marks.`)),k(`link_label (string, optional)`,j(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=L(e).trim(),r=Xa(t,this.locale)||n;return n===``?r:ut(r,n)},isExported:!0},a$=[{name:j(`Array`),functions:xW},{name:j(`Database`),functions:Eq},{name:j(`Date`),functions:HJ},{name:j(`Filter`),functions:EY},{name:j(`Financial`),functions:MY},{name:j(`Info`),functions:VX},{name:j(`Lookup`),functions:gZ},{name:j(`Logical`),functions:eZ},{name:j(`Math`),functions:ZW},{name:j(`Operator`),functions:BZ},{name:j(`Statistical`),functions:pK},{name:j(`Text`),functions:TQ},{name:j(`Engineering`),functions:wY},{name:j(`Web`),functions:r$},{name:j(`Parser`),functions:CQ}];for(let e of a$){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),Io.add(n,{isExported:!1,...r})}}let o$={},s$={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},c$={autoCompleteProviders:uT,autofillModifiersRegistry:QL,autofillRulesRegistry:$L,cellMenuRegistry:NP,colMenuRegistry:KP,errorTypes:Pi,functionRegistry:Io,featurePluginRegistry:Wz,iconsOnCellRegistry:DL,statefulUIPluginRegistry:Gz,coreViewsPluginRegistry:Kz,corePluginRegistry:Uz,rowMenuRegistry:$P,sidePanelRegistry:tN,figureRegistry:Py,chartSidePanelComponentRegistry:sk,chartDataSourceSidePanelComponentRegistry:QD,chartComponentRegistry:dy,chartTypeRegistry:dS,chartSubtypeRegistry:Kv,chartDataSourceRegistry:uS,topbarMenuRegistry:PB,topbarComponentRegistry:eV,clickableCellRegistry:$z,otRegistry:SR,inverseCommandRegistry:nB,urlRegistry:Mu,cellPopoverRegistry:xw,numberFormatMenuRegistry:bB,repeatLocalCommandTransformRegistry:mz,repeatCommandTransformRegistry:pz,clipboardHandlersRegistries:UF,pivotRegistry:qj,pivotTimeAdapterRegistry:rg,pivotSidePanelRegistry:cM,pivotNormalizationValueRegistry:Fg,supportedPivotPositionalFormulaRegistry:xI,pivotToFunctionValueRegistry:Ig,migrationStepRegistry:qC,chartJsExtensionRegistry:Vd,NonSquishableFunctionRegistry:Lo},l$={arg:k,isEvaluationError:F,toBoolean:R,toJsDate:z,toNumber:I,toString:L,toNormalizedPivotValue:jg,toFunctionPivotValue:Ng,toXC:E,toZone:yn,toUnboundedZone:vn,toCartesian:sn,numberToLetters:Zt,lettersToNumber:Qt,UuidGenerator:Bd,formatValue:H,createCurrencyFormat:Gl,ColorGenerator:ui,computeTextWidth:Sd,createEmptyWorkbookData:pw,createEmptySheet:fw,createEmptyExcelSheet:mw,rgbaToHex:Br,colorToRGBA:Vr,positionToZone:D,isDefined:w,isMatrix:Je,lazy:xt,genericRepeat:$B,createAction:h,createActions:p,transformRangeData:cr,deepEquals:T,overlap:Nn,union:kn,isInside:Fn,deepCopy:x,expandZoneOnInsertion:Tn,reduceZoneOnDeletion:On,unquote:et,getMaxObjectId:Cg,getFirstPivotFunction:Qj,getNumberOfPivotFunctions:eM,parseDimension:Eg,isDateOrDatetimeField:Dg,makeFieldProposal:tM,periodYearToComparable:ng,insertTokenAfterArgSeparator:rM,insertTokenAfterLeftParenthesis:iM,mergeContiguousZones:ar,getPivotHighlights:ej,pivotTimeAdapter:ig,UNDO_REDO_PIVOT_COMMANDS:WL,createPivotFormula:Ag,areDomainArgsFieldsValid:kg,splitReference:Zo,sanitizeSheetName:nt,getUniqueText:Kt,isNumber:Pa,isDateTime:na,createCustomFields:Hg,schemeToColorScale:Wh,isDateTimeFormat:Rl,jsDateToNumber:ga,numberToJsDate:ma,DateTime:P,parseFormat:cl,isFormula:qt,domainToColRowDomain:vj,collapseHierarchicalDisplayName:Jg,PositionMap:aN},u$={isMarkdownLink:ct,parseMarkdownLink:dt,markdownLink:ut,openLink:Lu,urlRepresentation:Iu},d$={Checkbox:BT,Section:Z,Select:ky,RoundColorPicker:ET,ChartDataSeries:eO,ChartErrorSection:iO,ChartLabelRange:tO,ChartRangeDataSourceComponent:SO,ChartTitle:uO,ChartPanel:dk,ChartFigure:My,ChartJsComponent:qp,ClickableCellSortIcon:SI,ZoomableChartJsComponent:ry,Grid:bI,GridOverlay:YF,ScorecardChart:Hm,GaugeChartComponent:ly,LineConfigPanel:KO,BarConfigPanel:oO,PieChartDesignPanel:YO,GenericChartConfigPanel:aO,ChartWithAxisDesignPanel:yO,GenericZoomableChartDesignPanel:bO,LineChartDesignPanel:qO,GaugeChartConfigPanel:BO,GaugeChartDesignPanel:VO,ScorecardChartConfigPanel:QO,ScorecardChartDesignPanel:$O,GeoChartDesignPanel:WO,RadarChartDesignPanel:XO,WaterfallChartDesignPanel:ok,ComboChartDesignPanel:LO,FunnelChartDesignPanel:zO,SunburstChartDesignPanel:ek,TreeMapChartDesignPanel:ak,ChartTypePicker:lk,FigureComponent:Fy,MenuPopover:Oy,Popover:wy,SelectionInput:FT,ValidationMessages:rO,AddDimensionButton:aj,PivotDimensionGranularity:sj,PivotDimensionOrder:cj,PivotDimension:oj,PivotLayoutConfigurator:fj,PivotHTMLRenderer:wI,PivotDeferUpdate:nj,PivotTitleSection:pj,CogWheelMenu:XD,TextInput:WD,SidePanelCollapsible:Ow,RadioSelection:fO,GeoChartRegionSelectSection:HO,ChartDashboardMenu:Ay,FullScreenFigure:CI,NumberInput:sO,TopBar:KV,Composer:Qw},f$={useDragAndDropListItems:OT,useHighlights:hk,useHighlightsOnHover:mk},p$={useStoreProvider:mr,DependencyContainer:ur,CellPopoverStore:Sw,ComposerFocusStore:Er,CellComposerStore:kF,FindAndReplaceStore:Fk,HighlightStore:fT,DelayedHoveredCellStore:Iy,HoveredTableStore:KF,ModelStore:yr,NotificationStore:pT,RendererStore:Cr,SelectionInputStore:PT,SpreadsheetStore:wr,useStore:O,useLocalStore:hr,SidePanelStore:rN,PivotSidePanelStore:oM,PivotMeasureDisplayPanelStore:QA,ClientFocusStore:tF,GridRenderer:rI};function m$(e,t){return Io.add(e,t),{addFunction:(e,t)=>m$(e,t)}}let h$={DEFAULT_LOCALE:V,HIGHLIGHT_COLOR:ee,PIVOT_STATIC_TABLE_CONFIG:Be,PIVOT_INSERT_TABLE_STYLE_ID:Ve,ChartTerms:Ry,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:Uh},g$={...Fv,...bv};e.AbstractCellClipboardHandler=JL,e.AbstractChart=Jp,e.AbstractFigureClipboardHandler=dW,e.CellErrorType=M,e.ClientDisconnectedError=iz,e.CommandResult=Au,e.CompiledFormula=Bc,e.CorePlugin=EI,e.CoreViewPlugin=eL,e.DEFAULT_LOCALE=V,e.DEFAULT_LOCALES=Ro,e.DispatchResult=Ou,e.EvaluationError=N,e.LocalTransportService=tV,e.Model=QU,e.PivotRuntimeDefinition=mj,e.Registry=A,e.Revision=rz,e.SPREADSHEET_DIMENSIONS=s$,e.Spreadsheet=YV,e.SpreadsheetPivotTable=Fj,e.UIPlugin=XL,e.__info__=o$,e.addFunction=m$,e.addRenderingLayer=Sr,e.astToFormula=TF,e.canExecuteInReadonly=Du,e.categories=a$,e.chartHelpers=g$,e.components=d$,e.constants=h$,e.convertAstNodes=Ks,e.coreTypes=Tu,e.createAutocompleteArgumentsProvider=qz,e.findCellInNewZone=Kn,e.functionCache=Rc,e.getCaretDownSvg=Tb,e.getCaretUpSvg=Eb,e.helpers=l$,e.hooks=f$,e.invalidateCFEvaluationCommands=bu,e.invalidateChartEvaluationCommands=vu,e.invalidateDependenciesCommands=yu,e.invalidateEvaluationCommands=_u,e.isCoreCommand=Eu,e.isSheetDependent=du,e.iterateAstNodes=qs,e.links=u$,e.load=QC,e.lockedSheetAllowedCommands=wu,e.parse=Ws,e.parseTokens=Gs,e.readonlyAllowedCommands=Cu,e.registries=c$,e.setDefaultSheetViewSize=Re,e.setTranslationMethod=ji,e.stores=p$,e.tokenColors=Ke,e.tokenize=ls,o$.version=`19.3.17`,o$.date=`2026-08-21T15:31:50.940Z`,o$.hash=`cf8c614`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|
|
956
|
+
`),`_rels/.rels`)}function XU(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=Kt(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${Ze(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function ZU(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>Ln(yn(e.range)).numberOfRows>1);return e}var QU=class e extends lr{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=new Bd,i=!1){let a=performance.now();console.debug(`##### Model creation #####`),super(),Mi(),n=ow(e,n);let o=QC(e,i);this.state=new dH,this.uuidGenerator=r,this.config=this.setupConfig(t),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.session=this.setupSession(o.revisionId),this.coreGetters={},this.range=new cH(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.selection=new uH(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of Uz.getAll())this.setupCorePlugin(e,o);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of Kz.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of Gz.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of Wz.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.config.mode!==`export_verification`&&(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly())){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}console.debug(`Model created in`,performance.now()-a,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:xt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new az(aH({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowedRemoteCommand(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e,new XV(this.getters))}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:j(`Anonymous`).toString()},n=e.transportService||new tV,r=e.mode===`readonly`||e.mode===`dashboard`||e.mode===`export_verification`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new ZV(n):n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Ro));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=Eu(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==`Success`)?new Ou(e.flat()):Ou.Success}checkDispatchAllowedRemoteCommand(e){let t=this.coreHandlers.map(t=>t.allowDispatch(e));return this.processCommandResults(t)}checkDispatchAllowedCoreCommand(e){return this.handlers.map(t=>t.allowDispatch(e))}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed($U(e,t));dispatch=(e,t)=>{let n=$U(e,t),r=this.status;if(this.getters.isReadonly()&&!Du(n))return new Ou(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Ou(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),this.trigger(`command-rejected`,{command:n,result:t}),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();Eu(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(Eu(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(Eu(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Ou.Success};dispatchFromCorePlugin=(e,t)=>{let n=$U(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Ou.Success};dispatchToHandlers(e,t){let n=Eu(t);for(let r of e)!n&&r instanceof EI||r.beforeHandle(t);for(let r of e)!n&&r instanceof EI||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let t=this._exportData(!0),n=this._exportData(!1),r={...this.config,mode:`export_verification`,client:{id:`exporter`,name:`exporter`},snapshotRequested:!1,transportService:new tV};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=pw();for(let n of this.handlers)n instanceof EI&&n.export(t,e);return t.revisionId=this.session.getRevisionId()||`START_REVISION`,t=x(t),t}updateMode(e){this.config.mode=e,this.trigger(`update`)}async exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=hw();for(let t of this.handlers)t instanceof TI&&await t.exportForExcel(e);return e=x(e),VU(e)}};function $U(e,t={}){let n=x(t);return n.type=e,n}function eW(e){return!MO.includes(e.horizontalGroupBy)||!MO.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}let tW={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,eW)},fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){let n=`left`;return e.legendPosition===`right`&&(n=`right`),{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},title:e.title||{text:``},type:`calendar`,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:n,horizontalGroupBy:`day_of_week`,verticalGroupBy:`month_number`}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n}){let r=a_(t,n(),e),{labels:i,datasets:a}=gp(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...sh,indexAxis:`x`,layout:L_(t,r),scales:Qf(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:sv(t,r),chartShowValuesPlugin:Z_(t,r),chartColorScalePlugin:$f(t,r),background:{color:t.background}}}}}}},nW={sequence:15,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`aggregated`,`axesDesign`,`showValues`,`hideDataMarkers`,`zoomable`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t)}},getDefinitionFromContextCreation(e,t){let n=e.dataSetStyles??{};if(e.dataSource?.type===`range`){let t=e.dataSource?.dataSets?.[0]?.dataSetId;for(let r of e.dataSource?.dataSets||[])n[r.dataSetId]={...e.dataSetStyles?.[r.dataSetId]||{},type:r.dataSetId===t?`bar`:`line`}}return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:n,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}},getRuntime(e,t,{extractData:n},r,i){let a=n_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:xp(t,a)},options:{...sh,layout:I_(t,a),scales:Zf(t,a),plugins:{title:nv(t,e),legend:U_(t,a),tooltip:ov(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},rW={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`dataSetStyles`,`axesDesign`,`legendPosition`,`horizontal`,`aggregated`,`showValues`,`funnelColors`,`cumulative`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative??!0,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=d_(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:wp(t,a)},options:{...sh,indexAxis:`y`,layout:I_(t,a),scales:cp(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:mv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}}}}},iW={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`colorScale`,`missingValueColor`,`region`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=u_(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:Cp(t,a)},options:{...sh,layout:I_(t,a),scales:sp(t,a),plugins:{title:nv(t,e),tooltip:pv(t,a),legend:{display:!1},background:{color:t.background}},...i}}}}},aW={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`axesDesign`,`stacked`,`horizontal`],fromStrDefinition:e=>({...e,horizontal:!0,stacked:!0}),toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){if(t.dataSource.type!==`range`)return;let{dataSetsValues:i}=o_(t,DO(e,t.dataSource),e),a=Math.max(...i.map(e=>Math.max(...e.data.map(e=>U(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t),maxValue:a}},getRuntime(e,t,{extractData:n},r,i){let a=o_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:hp(t,a)},options:{...sh,indexAxis:`y`,layout:I_(t,a),scales:ap(t,a),plugins:{title:nv(t,e),legend:z_(t,a),tooltip:dv(t,a),chartShowValuesPlugin:$_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},oW={sequence:80,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`stacked`,`fillArea`,`hideDataMarkers`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=l_(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:Sp(t,a)},options:{...sh,layout:I_(t,a),scales:op(t,a),plugins:{title:nv(t,e),legend:G_(t,a),tooltip:fv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},sW={sequence:60,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`labelsAsText`,`aggregated`,`axesDesign`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:Um(t.background||`#FFFFFF`),fontColor:Um(wf(t.background)),dataSets:n,labelRange:r,verticalAxis:Af(t)}},getRuntime(e,t,{extractData:n},r,i){let a=s_(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:yp(t,a)},options:{...sh,layout:I_(t,a),scales:rp(t,a),plugins:{title:nv(t,e),legend:H_(t,a),tooltip:cv(t,a),chartShowValuesPlugin:X_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},cW={sequence:30,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`showLabels`,`valuesDesign`,`groupColors`,`pieHolePercentage`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize,pieHolePercentage:e.pieHolePercentage}},getContextCreation(e,t,n){return{...e,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=f_(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:Ep(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...sh,layout:I_(t,a),plugins:{title:nv(t,e),legend:K_(t,a),tooltip:hv(t,a),sunburstLabelsPlugin:Q_(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:t.background}},...i}}}}},lW={sequence:100,allowedDefinitionKeys:[...Jp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showHeaders`,`headerDesign`,`showLabels`,`valuesDesign`,`coloringOptions`,`showValues`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}},getContextCreation(e,t,n){return{...e,treemapColoringOptions:e.coloringOptions,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=f_(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:jp(t,a)},options:{...sh,layout:I_(t,a),plugins:{title:nv(t,e),legend:{display:!1},tooltip:gv(t,a),background:{color:t.background}},...i}}}}};dS.add(`bar`,xv),dS.add(`combo`,nW),dS.add(`line`,Mv),dS.add(`pie`,Nv),dS.add(`scorecard`,im),dS.add(`gauge`,Dv),dS.add(`scatter`,sW),dS.add(`waterfall`,Pv),dS.add(`pyramid`,aW),dS.add(`radar`,oW),dS.add(`geo`,iW),dS.add(`funnel`,rW),dS.add(`sunburst`,cW),dS.add(`treemap`,lW),dS.add(`calendar`,tW),Kv.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:j(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:j(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:j(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:j(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:j(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:j(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:j(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:j(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:j(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:j(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:j(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:j(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:j(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:j(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:j(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:j(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:j(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:j(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:j(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:j(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:j(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:j(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:j(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`});var uW=class extends JL{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(D(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=cn(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},dW=class extends qL{copy(e){}},fW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`carousel`)return;let r={...n},i=this.getters.getCarousel(e.figureId),a={};for(let e of i.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);a[e.chartId]=t}return{figureId:e.figureId,copiedFigure:r,copiedCarousel:i,copiedCharts:a,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:new Bd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=this.getters.getMaxAnchorOffset(a,s,o),{left:l,top:u}=r[0],d={x:0,y:0};l>c.col&&(l=c.col,d.x=c.offset.x),u>c.row&&(u=c.row,d.y=c.offset.y),this.dispatch(`CREATE_CAROUSEL`,{figureId:i,sheetId:a,definition:{items:[]},col:l,row:u,offset:d,size:{height:s,width:o}});let f=new Bd,p=x(t.copiedCarousel.items);for(let e of p){if(e.type!==`chart`)continue;let n=t.copiedCharts[e.chartId],r=f.smallUuid(),o=CO.fromDefinition(this.getters,a,n.copyInSheetId(a)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:i,chartId:r,sheetId:a,definition:o}),e.chartId=r}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:a,figureId:i,definition:{...t.copiedCarousel,items:p}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},pW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`chart`)return;let r={...n},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i;return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new Bd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart,l=CO.fromDefinition(this.getters,a,c.copyInSheetId(a)).getDefinition();l=CO.fromStrDefinition(this.getters,a,l).getDefinition();let u=this.getters.getMaxAnchorOffset(a,s,o),{left:d,top:f}=r[0],p={x:0,y:0};d>u.col&&(d=u.col,p.x=u.offset.x),f>u.row&&(f=u.row,p.y=u.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,chartId:new Bd().smallUuid(),sheetId:a,definition:l,col:d,row:f,offset:p,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},mW=class extends JL{uuidGenerator=new Bd;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=D(e.position),i=D(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&T(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&T(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},hW=class extends JL{uuidGenerator=new Bd;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=D(t),i=D(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>T(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>T(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=cn([...cn(r.ranges.map(e=>e.zone),n),...t],[]);if(i.length===0){this.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:r.id});continue}this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:{id:r.id,criterion:r.criterion,isBlocking:r.isBlocking},ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}},gW=class extends dW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=x(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new Bd().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=x(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},_W=class extends JL{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(w);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},vW=class extends JL{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},yW=class extends JL{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Qn(ZT(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},bW=class extends JL{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>In(f,e))){s.add(u.id);let{numberOfRows:e}=Ln(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}if(u.isPivotTable){let t=u.range.zone.top===e&&u.range.zone.left===c,n=o.some(e=>In(u.range.zone,e));(t||n)&&s.add(u.id)}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=Dt({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Dt(n)},border:{...r,...Dt(i)}}}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.tableCells,n)}pasteFromCut(e,t,n,r){for(let e of n.tableCells)for(let t of e)t.table&&this.dispatch(`REMOVE_TABLE`,{sheetId:n.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});let i=t[0];this.pasteZone(e,i.left,i.top,n.tableCells,r)}pasteZone(e,t,n,r,i){for(let a=0;a<r.length;a++){let o=r[a];for(let r=0;r<o.length;r++){let s=o[r];if(!s)continue;let c={col:t+r,row:n+a,sheetId:e};this.pasteTableCell(e,s,c,i)}}if(r.length===1)for(let i=0;i<r[0].length;i++)this.dispatch(`AUTOFILL_TABLE_COLUMN`,{col:t+i,row:n,sheetId:e})}pasteTableCell(e,t,n,r){if(t.table&&!r?.pasteOption){let{range:r}=t.table,i=Ln(this.getters.getRangeFromRangeData(r).zone),a={left:n.col,top:n.row,right:n.col+i.numberOfCols-1,bottom:n.row+i.numberOfRows-1};this.dispatch(`CREATE_TABLE`,{sheetId:n.sheetId,ranges:[this.getters.getRangeDataFromZone(e,a)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(n)||r?.pasteOption===`asValue`||(!r?.pasteOption&&!t.isWholeTableCopied||r?.pasteOption===`onlyFormat`)&&(t.style?.style&&this.dispatch(`UPDATE_CELL`,{...n,style:t.style.style}),t.style?.border&&this.dispatch(`SET_BORDER`,{...n,border:t.style.border}))}};UF.figureHandlers.add(`chart`,pW).add(`image`,gW).add(`carousel`,fW),UF.cellHandlers.add(`dataValidation`,hW).add(`cell`,YL).add(`sheet`,yW).add(`merge`,_W).add(`border`,uW).add(`table`,bW).add(`conditionalFormat`,mW).add(`references`,vW);var xW=l({ARRAYTOTEXT:()=>XW,ARRAY_CONSTRAIN:()=>wW,ARRAY_LITERAL:()=>TW,ARRAY_ROW:()=>EW,CHOOSECOLS:()=>DW,CHOOSEROWS:()=>OW,EXPAND:()=>kW,FLATTEN:()=>AW,FREQUENCY:()=>jW,HSTACK:()=>MW,MDETERM:()=>NW,MINVERSE:()=>PW,MMULT:()=>FW,SUMPRODUCT:()=>IW,SUMX2MY2:()=>RW,SUMX2PY2:()=>zW,SUMXMY2:()=>BW,TOCOL:()=>UW,TOROW:()=>WW,TRANSPOSE:()=>GW,VSTACK:()=>KW,WRAPCOLS:()=>qW,WRAPROWS:()=>JW});function SW(e,t){let n=e.map(B),r=n.map(e=>e?.[0]?.length??0),i=Math.max(...r);if(t?.requireSameRowCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=[];for(let e of n)for(let t=0;t<e.length;t++){let n=Array(i).fill({value:null});for(let r=0;r<e[t].length;r++)n[r]=e[t][r];a.push(n)}return a}function CW(e,t){let n=e.map(B),r=n.map(e=>e?.length??0),i=Math.max(...r);if(t?.requireSameColCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=co(i,n.reduce((e,t)=>e+(t?.[0]?.length??0),0),()=>({value:null})),o=0;for(let e of n){for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)a[t][o+n]=e[t][n];o+=e[0]?.length??0}return a}let wW={description:j(`Returns a result array constrained to a specific width and height.`),args:[k(`input_range (any, range<any>)`,j(`The range to constrain.`)),k(`rows (number)`,j(`The number of rows in the constrained array.`)),k(`columns (number)`,j(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=B(e),i=Ja(t?.value,this.locale),a=Ja(n?.value,this.locale);if(i<=0)return new N(j(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new N(j(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return co(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},TW={description:j(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return CW(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},EW={description:j(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return SW(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},DW={description:j(`Creates a new array from the selected columns in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the columns to be returned.`)),k(`col_num (number, range<number>, repeating)`,j(`The column index of the column to be returned.`))],compute:function(e,...t){let n=B(e),r=To(t,e=>Ja(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new N(j(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},OW={description:j(`Creates a new array from the selected rows in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the rows to be returned.`)),k(`row_num (number, range<number>, repeating)`,j(`The row index of the row to be returned.`))],compute:function(e,...t){let n=B(e),r=To(t,e=>Ja(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?co(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new N(j(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},kW={description:j(`Expands or pads an array to specified row and column dimensions.`),args:[k(`array (any, range<any>)`,j(`The array to expand.`)),k(`rows (number)`,j(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),k(`columns (number, optional)`,j(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),k(`pad_with (any, default=0)`,j(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=B(e),a=Ja(t?.value,this.locale),o=n===void 0?i.length:Ja(n.value,this.locale);return a<i[0].length?new N(j(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new N(j(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):co(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},AW={description:j(`Flattens all the values from one or more ranges into a single column.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to flatten.`))],compute:function(...e){return[To(e,e=>e===void 0?{value:``}:e)]},isExported:!1},jW={description:j(`Calculates the frequency distribution of a range.`),args:[k(`data (range<number>)`,j(`The array of ranges containing the values to be counted.`)),k(`classes (number, range<number>)`,j(`The range containing the set of classes.`))],compute:function(e,t){let n=To([e],e=>e.value).filter(e=>typeof e==`number`),r=To([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},MW={description:j(`Appends ranges horizontally and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return SW(e)},isExported:!0},NW={description:j(`Returns the matrix determinant of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);return vh(t)?xh(t).determinant:new N(j(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},PW={description:j(`Returns the multiplicative inverse of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);if(!vh(t))return new N(j(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=xh(t);return n||new N(j(`The matrix is not invertible.`))},isExported:!0},FW={description:j(`Calculates the matrix product of two matrices.`),args:[k(`matrix1 (number, range<number>)`,j(`The first matrix in the matrix multiplication operation.`)),k(`matrix2 (number, range<number>)`,j(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=Ka(e,`matrix1`),r=Ka(t,`matrix2`);return n.length===0||r.length===0?new N(j(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?Ch(n,r):new N(j(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},IW={description:j(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[k(`range (number, range<number>, repeating)`,j(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!_h(...e))return new N(j(`All the ranges must have the same dimensions.`));let t=e.map(B),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=I(n[e][r],this.locale);n+=i}return n},isExported:!0};function LW(e,t,n){if(!_h(e,t))return new N(j(`The arguments array_x and array_y must have the same dimensions.`));let r=B(e),i=B(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new N(j(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let RW={description:j(`Calculates the sum of the difference of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>e**2-t**2)},isExported:!0},zW={description:j(`Calculates the sum of the sum of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>e**2+t**2)},isExported:!0},BW={description:j(`Calculates the sum of squares of the differences of values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together.`))],compute:function(e,t){return LW(e,t,(e,t)=>(e-t)**2)},isExported:!0},VW=[k(`array (any, range<any>)`,j(`The array which will be transformed.`)),k(`ignore (number, default=0)`,j(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:j(`Keep all values (default)`)},{value:1,label:j(`Ignore blanks`)},{value:2,label:j(`Ignore errors`)},{value:3,label:j(`Ignore blanks and errors`)}]),k(`scan_by_column (number, default=false)`,j(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:j(`Scan by row (default)`)},{value:!0,label:j(`Scan by column`)}])];function HW(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!F(e.value);if(t===3)return e=>e.value!==null&&!F(e.value);throw new N(j(`Argument ignore must be between 0 and 3`))}let UW={description:j(`Transforms a range of cells into a single column.`),args:VW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:fo(r)).flat().filter(HW(i));return a.length===0?new Ri(j(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},WW={description:j(`Transforms a range of cells into a single row.`),args:VW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:fo(r)).flat().filter(HW(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Ri(j(`No results for the given arguments of TOROW.`)):a},isExported:!0},GW={description:j(`Transposes the rows and columns of a range.`),args:[k(`range (any, range<any>)`,j(`The range to be transposed.`))],compute:function(e){let t=B(e),n=t[0].length,r=t.length;return co(n,r,(e,n)=>t[n][e])},isExported:!0},KW={description:j(`Appends ranges vertically and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return CW(e)},isExported:!0},qW={description:j(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!gh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return co(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},JW={description:j(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!gh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return co(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},YW=[{value:0,label:j(`Concise format\xA0(default)`)},{value:1,label:j(`Strict format`)}],XW={description:j(`returns an array of text values from any specified range. It passes text values unchanged, and converts non-text values to text.`),args:[k(`array (range)`,j(`The array to convert into text`)),k(`format (number, default=0)`,j(`The format of the returned data.`),YW)],compute:function(e,t={value:0}){let n=I(t,this.locale),r=B(e);if(n===1)return sT(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return fo(r).flatMap(e=>e.map(e=>F(e.value)?e.value:Xa(e,this.locale))).join(e)}else return new N(j(`Format must be 0 or 1`))},isExported:!0};var ZW=l({ABS:()=>$W,ACOS:()=>eG,ACOSH:()=>tG,ACOT:()=>nG,ACOTH:()=>rG,ASIN:()=>iG,ASINH:()=>aG,ATAN:()=>oG,ATAN2:()=>sG,ATANH:()=>cG,CEILING:()=>lG,CEILING_MATH:()=>dG,CEILING_PRECISE:()=>fG,COS:()=>pG,COSH:()=>mG,COT:()=>hG,COTH:()=>gG,COUNTBLANK:()=>_G,COUNTIF:()=>vG,COUNTIFS:()=>yG,COUNTUNIQUE:()=>bG,COUNTUNIQUEIFS:()=>xG,CSC:()=>SG,CSCH:()=>CG,DECIMAL:()=>wG,DEGREES:()=>TG,EXP:()=>EG,FLOOR:()=>DG,FLOOR_MATH:()=>kG,FLOOR_PRECISE:()=>AG,INT:()=>fK,ISEVEN:()=>jG,ISODD:()=>NG,ISO_CEILING:()=>MG,LN:()=>PG,LOG:()=>FG,MOD:()=>LG,MUNIT:()=>RG,ODD:()=>zG,PI:()=>BG,POWER:()=>VG,PRODUCT:()=>HG,RAND:()=>UG,RANDARRAY:()=>WG,RANDBETWEEN:()=>GG,ROUND:()=>KG,ROUNDDOWN:()=>qG,ROUNDUP:()=>JG,SEC:()=>YG,SECH:()=>XG,SEQUENCE:()=>ZG,SIN:()=>QG,SINH:()=>$G,SQRT:()=>eK,SUBTOTAL:()=>iK,SUM:()=>aK,SUMIF:()=>oK,SUMIFS:()=>sK,TAN:()=>cK,TANH:()=>lK,TRUNC:()=>dK});let QW=/^-?[a-z0-9]+$/i,$W={description:j(`Absolute value of a number.`),args:[k(`value (number)`,j(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(I(e,this.locale))},isExported:!0},eG={description:j(`Inverse cosine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},tG={description:j(`Inverse hyperbolic cosine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=I(e,this.locale);return t<1?new N(j(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},nG={description:j(`Inverse cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=I(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},rG={description:j(`Inverse hyperbolic cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)<=1?new N(j(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},iG={description:j(`Inverse sine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},aG={description:j(`Inverse hyperbolic sine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(I(e,this.locale))},isExported:!0},oG={description:j(`Inverse tangent of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(I(e,this.locale))},isExported:!0},sG={description:j(`Angle from the X axis to a point (x,y), in radians.`),args:[k(`x (number)`,j(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),k(`y (number)`,j(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n===0&&r===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},cG={description:j(`Inverse hyperbolic tangent of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>=1?new N(j(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},lG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round up to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function uG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let dG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:uG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},fG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:uG(I(e,this.locale),n),format:e?.format}},isExported:!0},pG={description:j(`Cosine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(I(e,this.locale))},isExported:!0},mG={description:j(`Hyperbolic cosine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(I(e,this.locale))},isExported:!0},hG={description:j(`Cotangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},gG={description:j(`Hyperbolic cotangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},_G={description:j(`Number of empty values.`),args:[k(`value (any, range, repeating)`,j(`Value or range in which to count the number of blanks.`))],compute:function(...e){return ao(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},vG={description:j(`A conditional count across a range.`),args:[k(`range (range)`,j(`The range that is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return yo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},yG={description:j(`Count values depending on multiple criteria.`),args:[k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(...e){let t=0;return yo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},bG={description:j(`Counts number of unique values in a range.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider for uniqueness.`))],compute:function(...e){return tg(e)}},xG={description:j(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the number of unique values will be counted.`)),k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return yo(t,(t,r)=>{let i=e[t]?.[r];Eo(i)&&n.add(i.value)},this.locale),n.size}},SG={description:j(`Cosecant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},CG={description:j(`Hyperbolic cosecant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},wG={description:j(`Converts from another base to decimal.`),args:[k(`value (string)`,j(`The number to convert.`)),k(`base (number)`,j(`The base to convert the value from.`))],compute:function(e,t){let n=I(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new N(j(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=L(e);if(r===``)return 0;if(!QW.test(r))return new N(j(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new N(j(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},TG={description:j(`Converts an angle value in radians to degrees.`),args:[k(`angle (number)`,j(`The angle to convert from radians to degrees.`))],compute:function(e){return I(e,this.locale)*180/Math.PI},isExported:!0},EG={description:j(`Euler's number, e (~2.718) raised to a power.`),args:[k(`value (number)`,j(`The exponent to raise e.`))],compute:function(e){return Math.exp(I(e,this.locale))},isExported:!0},DG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round down to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function OG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let kG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:OG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},AG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:OG(I(e,this.locale),n),format:e?.format}},isExported:!0},jG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},MG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:uG(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},NG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},PG={description:j(`The logarithm of a number, base e (euler's number).`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=I(e,this.locale);return t<=0?new N(j(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},FG={description:j(`The logarithm of a number, for a given base.`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm.`)),k(`base (number, default=10)`,j(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=I(e,this.locale),r=I(t,this.locale);return n<=0?new N(j(`The value (%s) must be strictly positive.`,n)):r<=0?new N(j(`The base (%s) must be strictly positive.`,r)):r===1?new N(j(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function IG(e,t){hh(t,j(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let LG={description:j(`Modulo (remainder) operator.`),args:[k(`dividend (number)`,j(`The number to be divided to find the remainder.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return{value:IG(I(e,this.locale),n),format:e?.format}},isExported:!0},RG={description:j(`Returns a n x n unit matrix, where n is the input dimension.`),args:[k(`dimension (number)`,j(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=Ja(e,this.locale);return t<1?new N(j(`The argument dimension must be positive`)):bh(t)},isExported:!0},zG={description:j(`Rounds a number up to the nearest odd integer.`),args:[k(`value (number)`,j(`The value to round to the next greatest odd number.`))],compute:function(e){let t=I(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},BG={description:j(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},VG={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n<0&&!Number.isInteger(r)?new N(j(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},HG={description:j(`Result of multiplying a series of numbers together.`),args:[k(`factor (number, range<number>, repeating)`,j(`Number or range to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Je(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),F(e))return r}else r!==void 0&&r.value!==null&&(n*=qa(r,this.locale),t+=1);return{value:t===0?0:n,format:za(e[0])}},isExported:!0},UG={description:j(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},WG={description:j(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[k(`rows (number, default=1)`,j(`The number of rows to be returned.`)),k(`columns (number, default=1)`,j(`The number of columns to be returned.`)),k(`min (number, default=0)`,j(`The minimum number you would like returned.`)),k(`max (number, default=1)`,j(`The maximum number you would like returned.`)),k(`whole_number (boolean, default=FALSE)`,j(`Return a whole number or a decimal value.`),[{value:!1,label:j(`Decimal (default)`)},{value:!0,label:j(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=Ja(t,this.locale),o=Ja(e,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=R(i);if(a<1)return new N(j(`The number of columns (%s) must be positive.`,a));if(o<1)return new N(j(`The number of rows (%s) must be positive.`,o));if(s>c)return new N(j(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new N(j(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},GG={description:j(`Random integer between two values, inclusive.`),args:[k(`low (number)`,j(`The low end of the random range.`)),k(`high (number)`,j(`The high end of the random range.`))],compute:function(e,t){let n=I(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=I(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new N(j(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},KG={description:j(`Rounds a number according to standard rules.`),args:[k(`value (number)`,j(`The value to round to places number of places.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},qG={description:j(`Rounds down a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding down.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},JG={description:j(`Rounds up a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding up.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},YG={description:j(`Secant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(I(e,this.locale))},isExported:!0},XG={description:j(`Hyperbolic secant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(I(e,this.locale))},isExported:!0},ZG={description:j(`Returns a sequence of numbers.`),args:[k(`rows (number)`,j(`The number of rows to return`)),k(`columns (number, optional, default=1)`,j(`The number of columns to return`)),k(`start (number, optional, default=1)`,j(`The first number in the sequence`)),k(`step (number, optional, default=1)`,j(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=I(n,this.locale),a=I(r,this.locale),o=Ja(e,this.locale),s=Ja(t,this.locale);return s<1?new N(j(`The number of columns (%s) must be positive.`,s)):o<1?new N(j(`The number of rows (%s) must be positive.`,o)):co(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},QG={description:j(`Sine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(I(e,this.locale))},isExported:!0},$G={description:j(`Hyperbolic sine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(I(e,this.locale))},isExported:!0},eK={description:j(`Positive square root of a positive number.`),args:[k(`value (number)`,j(`The number for which to calculate the positive square root.`))],compute:function(e){let t=I(e,this.locale);return t<0?new N(j(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},tK={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},nK=Object.entries(tK).map(([e,t])=>({value:parseInt(e),label:j(`%s (include manually-hidden rows)`,t)})),rK=Object.entries(tK).map(([e,t])=>({value:parseInt(e)+100,label:j(`%s (exclude manually-hidden rows)`,t)})),iK={description:j(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[k(`function_code (number)`,j(`The function to use in subtotal aggregation.`),[...nK,...rK]),k(`ref (any, range<any>, repeating)`,j(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=Ja(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new N(j(`The function code (%s) must be between 1 to 11 or 101 to 111.`,n));let i=[];for(let e of t){let t=B(e),n=t[0][0]?.position;if(n===void 0)return new Li(Ha);let a=n.col+t.length-1,o=n.row+t[0].length-1,s=n.sheetId;for(let e=n.row;e<=o;e++)if(!this.getters.isRowFiltered(s,e)&&!(!r&&this.getters.isRowHiddenByUser(s,e)))for(let t=n.col;t<=a;t++){let n=this.getters.getCorrespondingFormulaCell({sheetId:s,col:t,row:e});(!n||!Yt(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[tK[n]].apply(this,[[i]])},isExported:!0},aK={description:j(`Sum of a series of numbers and/or cells.`),args:[k(`value (number, range<number>, repeating)`,j(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:eg(e,this.locale),format:za(t)}},isExported:!0},oK={description:j(`A conditional sum across a range.`),args:[k(`criteria_range (range)`,j(`The range which is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`)),k(`sum_range (range, default=criteria_range)`,j(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return yo([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},sK={description:j(`Sums a range depending on multiple criteria.`),args:[k(`sum_range (range)`,j(`The range to sum.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},cK={description:j(`Tangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(I(e,this.locale))},isExported:!0},lK={description:j(`Hyperbolic tangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(I(e,this.locale))},isExported:!0};function uK(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let dK={description:j(`Truncates a number.`),args:[k(`value (number)`,j(`The value to be truncated.`)),k(`places (number, default=0)`,j(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:uK(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},fK={description:j(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[k(`value (number)`,j(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(I(e,this.locale))},isExported:!0};var pK=l({AVEDEV:()=>CK,AVERAGE:()=>wK,AVERAGEA:()=>OK,AVERAGEIF:()=>kK,AVERAGEIFS:()=>AK,AVERAGE_WEIGHTED:()=>DK,CORREL:()=>QK,COUNT:()=>jK,COUNTA:()=>MK,COVAR:()=>NK,COVARIANCE_P:()=>PK,COVARIANCE_S:()=>FK,FORECAST:()=>IK,GROWTH:()=>LK,INTERCEPT:()=>RK,LARGE:()=>zK,LINEST:()=>BK,LOGEST:()=>VK,MATTHEWS:()=>HK,MAX:()=>UK,MAXA:()=>WK,MAXIFS:()=>GK,MEDIAN:()=>KK,MIN:()=>qK,MINA:()=>JK,MINIFS:()=>YK,PEARSON:()=>ZK,PERCENTILE:()=>$K,PERCENTILE_EXC:()=>eq,PERCENTILE_INC:()=>tq,POLYFIT_COEFFS:()=>nq,POLYFIT_FORECAST:()=>rq,QUARTILE:()=>iq,QUARTILE_EXC:()=>aq,QUARTILE_INC:()=>oq,RANK:()=>sq,RSQ:()=>cq,SLOPE:()=>lq,SMALL:()=>uq,SPEARMAN:()=>dq,STDEV:()=>fq,STDEVA:()=>hq,STDEVP:()=>gq,STDEVPA:()=>_q,STDEV_P:()=>pq,STDEV_S:()=>mq,STEYX:()=>vq,TREND:()=>yq,VAR:()=>bq,VARA:()=>Cq,VARP:()=>wq,VARPA:()=>Tq,VAR_P:()=>xq,VAR_S:()=>Sq});let mK=[{value:!0,label:j(`b is calculated normally`)},{value:!1,label:j(`b is forced to 1`)}],hK=[{value:!1,label:j(`do not return additional regression statistics`)},{value:!0,label:j(`return additional regression statistics`)}],gK=[{value:1,label:j(`order 1 (Linear)`)},{value:2,label:j(`order 2 (Quadratic)`)},{value:3,label:j(`order 3 (Cubic)`)},{value:4,label:j(`order 4 (Quartic)`)},{value:5,label:j(`order 5 (Quintic)`)},{value:6,label:j(`order 6 (Sextic)`)}],_K=[{value:!0,label:j(`Compute intercept`)},{value:!1,label:j(`Force intercept to 0`)}],vK=[{value:0,label:j(`Minimum value`)},{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)},{value:4,label:j(`Maximum value`)}];function yK(e,t){let n=[],r=[],i=0,a=0;no([e],e=>{n.push(e),i+=1}),no([t],e=>{r.push(e),a+=1}),mh(i===a,j(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function bK(e,t,n){let{flatDataX:r,flatDataY:i}=yK(e,t),a=i.length;hh(a),n&&hh(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function xK(e,t,n,r){let i=0,a=n?so:oo,o=a(e,(e,t)=>(i+=1,e+t),0,r);hh(i),t&&hh(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function SK(e,t,n,r){let i=I(t,r);mh(n?0<=i&&i<=1:0<i&&i<1,j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return no(e,e=>{let t=e?.value;typeof t==`number`&&(o=bo(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),mh(s!==0,Do),n||mh(1/(s+1)<=i&&i<=s/(s+1),j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),La(a,i,n)}let CK={description:j(`Average magnitude of deviations from mean.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=oo(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return oo(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},wK={description:j(`Numerical average value in a dataset, ignoring text.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:Oh(e,this.locale),format:za(e[0])}},isExported:!0},TK=j(`[[FUNCTION_NAME]] has mismatched range sizes.`),EK=j(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),DK={description:j(`Weighted average.`),args:[k(`values (number, range<number>, repeating)`,j(`Value to average.`)),k(`weights (number, range<number>, repeating)`,j(`Weight for each corresponding value.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!_h(i,a))return new N(TK);if(Je(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Je(a)?a?.[e][r].value:I(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new N(EK);t+=o*s,n+=s;continue}if(c!==l)return new N(j(`[[FUNCTION_NAME]] expects number values.`))}else{let e=I(i,this.locale),r=Je(a)?a?.[0][0].value:I(a,this.locale);if(typeof r==`number`){if(r<0)return new N(EK);t+=e*r,n+=r}}}return n===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:za(e[0])}}},OK={description:j(`Numerical average value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=so(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:za(e[0])}},isExported:!0},kK={description:j(`Average of values depending on criteria.`),args:[k(`criteria_range (number, range<number>)`,j(`The range to check against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to criteria_range.`)),k(`average_range (number, range<number>, default=criteria_range)`,j(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=B(n===void 0?e:n),i=0,a=0;return yo([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},AK={description:j(`Average of values depending on multiple criteria.`),args:[k(`average_range (range)`,j(`The range to average.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=B(e),r=0,i=0;return yo(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},jK={description:j(`The number of numeric values in dataset.`),args:[k(`value (number, any, range<number>, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return Ah(e,this.locale)},isExported:!0},MK={description:j(`The number of values in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return jh(e)},isExported:!0},NK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!1)},isExported:!0},PK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!1)},isExported:!0},FK={description:j(`The sample covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return bK(e,t,!0)},isExported:!0},IK={description:j(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=yK(t,n);return r.length===0||i.length===0?new Ri(Do):Vh([i],[r],lo(B(e),e=>I(e,this.locale)),!0)},isExported:!0},LK={description:j(`Fits points to exponential growth trend.`),args:[k(`known_data_y (range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),k(`known_data_x (range<number>, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (any, range, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, default=TRUE)`,j(`Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE.`),mK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Oo(`known_data_y`)):zh(Vh(Bh(Ka(e,`known_data_y`)),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r)))}},RK={description:j(`Compute the intercept of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let[[],[i]]=Fh([n],[r]);return i},isExported:!0},zK={description:j(`Nth largest element from a data set.`),args:[k(`data (any, range)`,j(`Array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;no([e],e=>{typeof e?.value==`number`&&(i=bo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new N(Do):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},BK={description:j(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),mK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),hK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new N(Oo(`data_y`)):Fh(Ka(t,`data_x`),Ka(e,`data_y`),R(n),R(r))},isExported:!0},VK={description:j(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, optional, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),mK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),hK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new N(Oo(`data_y`));let i=Fh(Ka(t,`data_x`),Bh(Ka(e,`data_y`)),R(n),R(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},HK={description:j(`Compute the Matthews correlation coefficient of a dataset.`),args:[k(`data_x (range)`,j(`The range representing the array or matrix of observed data.`)),k(`data_y (range)`,j(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Dh(n,r),n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=R(n[e]);t===R(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},UK={description:j(`Maximum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return Mh(e,this.locale)},isExported:!0},WK={description:j(`Maximum numeric value in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=so(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:za(e[0])}},isExported:!0},GK={description:j(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the maximum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},KK={description:j(`Median value in a numeric dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return ro(e,e=>{t.push(e)},this.locale),{value:SK(t,{value:.5},!0,this.locale),format:za(t[0])}},isExported:!0},qK={description:j(`Minimum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return Nh(e,this.locale)},isExported:!0},JK={description:j(`Minimum numeric value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=so(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:za(e[0])}},isExported:!0},YK={description:j(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the minimum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return yo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function XK(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let ZK={description:j(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return XK(e,t)},isExported:!0},QK=ZK,$K={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return tq.compute.bind(this)(e,t)},isExported:!0},eq={description:j(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:SK([e],t,!1,this.locale),format:za(e)}},isExported:!0},tq={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:SK([e],t,!0,this.locale),format:za(e)}},isExported:!0},nq={description:j(`Compute the coefficients of polynomial regression of the dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),gK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),_K)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=yK(e,t);return i.length===0||a.length===0?new Ri(Do):Ih(a,i,I(n,this.locale),R(r))},isExported:!1},rq={description:j(`Predict value by computing a polynomial regression of the dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),gK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),_K)],compute:function(e,t,n,r,i={value:!0}){let a=I(r,this.locale),{flatDataX:o,flatDataY:s}=yK(t,n);if(o.length===0||s.length===0)return new Ri(Do);let c=Ih(s,o,a,R(i)).flat();return lo(B(e),e=>Rh(c,I(e,this.locale),a))},isExported:!1},iq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),vK)],compute:function(e,t){return oq.compute.bind(this)(e,t)},isExported:!0},aq={description:j(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:SK([e],n,!1,this.locale),format:za(e)}},isExported:!0},oq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),vK)],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:SK([e],n,!0,this.locale),format:za(e)}},isExported:!0},sq={description:j(`Returns the rank of a specified value in a dataset.`),args:[k(`value (number)`,j(`The value whose rank will be determined.`)),k(`data (range)`,j(`The range containing the dataset to consider.`)),k(`is_ascending (boolean, default=FALSE)`,j(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:j(`Descending`)},{value:!0,label:j(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=R(n),i=I(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=I(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Ri(j(`Value not found in the given data.`))},isExported:!0},cq={description:j(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=XK(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},lq={description:j(`Compute the slope of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);if(n.length===0||r.length===0)return new Ri(Do);let[[i]]=Fh([n],[r]);return i},isExported:!0},uq={description:j(`Nth smallest element in a data set.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;no([e],e=>{typeof e?.value==`number`&&(i=bo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new N(Do):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},dq={description:j(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(t,e);if(n.length===0||r.length===0)return new Ri(Do);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},fq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(bq.compute.bind(this)(...e))},isExported:!0},pq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(xq.compute.bind(this)(...e))},isExported:!0},mq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Sq.compute.bind(this)(...e))},isExported:!0},hq={description:j(`Standard deviation of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(Cq.compute.bind(this)(...e))},isExported:!0},gq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(wq.compute.bind(this)(...e))},isExported:!0},_q={description:j(`Standard deviation of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(Tq.compute.bind(this)(...e))},isExported:!0},vq={description:j(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=yK(e,t);return n.length===0||r.length===0?new Ri(Do):Fh([n],[r],!0,!0)[1][2]},isExported:!0},yq={description:j(`Fits points to linear trend derived via least-squares.`),args:[k(`known_data_y (number, range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),k(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (number, range<number>, optional, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, optional, default=TRUE)`,j(`Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin.`),mK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Oo(`known_data_y`)):Vh(Ka(e,`known_data_y`),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r))}},bq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!1,this.locale)},isExported:!0},xq={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!1,this.locale)},isExported:!0},Sq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!1,this.locale)},isExported:!0},Cq={description:j(`Variance of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return xK(e,!0,!0,this.locale)},isExported:!0},wq={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!1,this.locale)},isExported:!0},Tq={description:j(`Variance of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return xK(e,!1,!0,this.locale)},isExported:!0};var Eq=l({DAVERAGE:()=>kq,DCOUNT:()=>Aq,DCOUNTA:()=>jq,DGET:()=>Mq,DMAX:()=>Nq,DMIN:()=>Pq,DPRODUCT:()=>Fq,DSTDEV:()=>Iq,DSTDEVP:()=>Lq,DSUM:()=>Rq,DVAR:()=>zq,DVARP:()=>Bq});function Dq(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(L(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new N(j(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new N(j(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=L(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new N(j(`The field (%s) must be one of %s.`,L(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new N(j(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=L(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)yo(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let Oq=[k(`database (range)`,j(`The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.`)),k(`field (number, string)`,j(`Indicates which column in database contains the values to be extracted and operated on.`)),k(`criteria (range)`,j(`An array or range containing zero or more criteria to filter the database values by before operating.`))],kq={description:j(`Average of a set of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return wK.compute.bind(this)([r])},isExported:!0},Aq={description:j(`Counts values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return jK.compute.bind(this)([r])},isExported:!0},jq={description:j(`Counts values and text from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return MK.compute.bind(this)([r])},isExported:!0},Mq={description:j(`Single value from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return r.length===1?r[0]:new N(j(`More than one match found in DGET evaluation.`))},isExported:!0},Nq={description:j(`Maximum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return UK.compute.bind(this)([r])},isExported:!0},Pq={description:j(`Minimum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return qK.compute.bind(this)([r])},isExported:!0},Fq={description:j(`Product of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return HG.compute.bind(this)([r])},isExported:!0},Iq={description:j(`Standard deviation of population sample from table.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return fq.compute.bind(this)([r])},isExported:!0},Lq={description:j(`Standard deviation of entire population from table.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return gq.compute.bind(this)([r])},isExported:!0},Rq={description:j(`Sum of values from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return aK.compute.bind(this)([r])},isExported:!0},zq={description:j(`Variance of population sample from table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return bq.compute.bind(this)([r])},isExported:!0},Bq={description:j(`Variance of a population from a table-like range.`),args:Oq,compute:function(e,t,n){let r=Dq(e,t,n,this.locale);return wq.compute.bind(this)([r])},isExported:!0},Vq=j(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Hq=j(`There must be both positive and negative values in cashflow_amounts.`),Uq=e=>j(`The cost (%s) must be positive or null.`,e),Wq=e=>j(`The cost (%s) must be strictly positive.`,e),Gq=e=>j(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Kq=e=>j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),qq=e=>j(`The depreciation factor (%s) must be strictly positive.`,e),Jq=e=>j(`The discount (%s) must be different from -1.`,e),Yq=e=>j(`The discount (%s) must be strictly positive.`,e),Xq=e=>j(`The discount (%s) must be smaller than 1.`,e),Zq=e=>j(`The effective_rate (%s) must be strictly positive.`,e),Qq=e=>j(`The end_period (%s) must be positive or null.`,e),$q=(e,t)=>j(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),eJ=e=>j(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),tJ=(e,t)=>j(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),nJ=e=>j(`The first_period (%s) must be strictly positive.`,e),rJ=e=>j(`The future_value (%s) must be strictly positive.`,e),iJ=e=>j(`The investment (%s) must be strictly positive.`,e),aJ=e=>j(`The issue (%s) must be positive or null.`,e),oJ=(e,t)=>j(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),sJ=e=>j(`The last_period (%s) must be strictly positive.`,e),cJ=e=>j(`The life (%s) must be strictly positive.`,e),lJ=(e,t)=>j(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),uJ=e=>j(`The month (%s) must be between 1 and 12 inclusive.`,e),dJ=e=>j(`The nominal_rate (%s) must be strictly positive.`,e),fJ=e=>j(`The number_of_periods (%s) must be different from zero.`,e),pJ=e=>j(`The number_of_periods (%s) must be strictly positive.`,e),mJ=e=>j(`The period must be between 1 and number_of_periods (%s)`,e),hJ=(e,t)=>j(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),gJ=e=>j(`The period (%s) must be positive or null.`,e),_J=e=>j(`The periods_by_year (%s) must be strictly positive.`,e),vJ=(e,t)=>j(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),yJ=e=>j(`The period (%s) must be strictly positive.`,e),bJ=e=>j(`The present_value (%s) must be strictly positive.`,e),xJ=e=>j(`The price (%s) must be strictly positive.`,e),SJ=(e,t)=>j(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),CJ=e=>j(`The purchase_date (%s) must be positive or null.`,e),wJ=e=>j(`The rate_guess (%s) must be strictly greater than -1.`,e),TJ=e=>j(`The rate (%s) must be positive or null.`,e),EJ=e=>j(`The rate (%s) must be strictly positive.`,e),DJ=e=>j(`The redemption (%s) must be strictly positive.`,e),OJ=e=>j(`The salvage (%s) must be positive or null.`,e),kJ=(e,t)=>j(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),AJ=(e,t)=>j(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),jJ=(e,t)=>j(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),MJ=(e,t)=>j(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),NJ=e=>j(`The start_period (%s) must be positive or null.`,e),PJ=(e,t)=>j(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),FJ=e=>j(`The unit (%s) must be strictly positive.`,e),IJ=e=>j(`The yield (%s) must be positive or null.`,e);function LJ(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function RJ(e){return![0,1,2,3,4].includes(e)}function zJ(e){return![1,2,4].includes(e)}function BJ(e,t,n){let r=z(e,n),i=z(t,n),a=z(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let VJ=[{value:0,label:j(`US (NASD) 30/360`)},{value:1,label:j(`Actual/Actual`)},{value:2,label:j(`Actual/360`)},{value:3,label:j(`Actual/365`)},{value:4,label:j(`European 30/360`)}];var HJ=l({DATE:()=>WJ,DATEDIF:()=>GJ,DATEVALUE:()=>KJ,DAY:()=>qJ,DAYS:()=>JJ,DAYS360:()=>YJ,EDATE:()=>XJ,EOMONTH:()=>ZJ,HOUR:()=>QJ,ISOWEEKNUM:()=>$J,MINUTE:()=>eY,MONTH:()=>tY,MONTH_END:()=>vY,MONTH_START:()=>_Y,NETWORKDAYS:()=>nY,NETWORKDAYS_INTL:()=>aY,NOW:()=>oY,QUARTER:()=>yY,QUARTER_END:()=>xY,QUARTER_START:()=>bY,SECOND:()=>sY,TIME:()=>cY,TIMEVALUE:()=>lY,TODAY:()=>uY,WEEKDAY:()=>dY,WEEKNUM:()=>fY,WORKDAY:()=>pY,WORKDAY_INTL:()=>mY,YEAR:()=>hY,YEARFRAC:()=>gY,YEAR_END:()=>CY,YEAR_START:()=>SY}),UJ=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(UJ||{});let WJ={description:j(`Converts year/month/day into a date.`),args:[k(`year (number)`,j(`The year component of the date.`)),k(`month (number)`,j(`The month component of the date.`)),k(`day (number)`,j(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));if(r<0||r>9999)return new N(j(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=ha(new P(r,i-1,a));return o<0?new N(j(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},GJ={description:j(`Calculates the number of days, months, or years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`unit (string)`,j(`A text abbreviation for unit of time.`),[{value:`Y`,label:j(`The number of whole years between start_date and end_date`)},{value:`M`,label:j(`The number of whole months between start_date and end_date`)},{value:`D`,label:j(`The number of days between start_date and end_date`)},{value:`MD`,label:j(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:j(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:j(`The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart`)}])],compute:function(e,t,n){let r=L(n).toUpperCase();if(!Object.values(UJ).includes(r))return new N(Wa(Object.values(UJ),L(n)));let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=ma(i),s=ma(a);if(a<i)return new N(j(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return wa(o,s);case`M`:return Sa(o,s);case`D`:return Ca(o,s);case`YM`:return Sa(o,s)-wa(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=_a(new P(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(Ta(i,a))return Ca(o,s);let e=new P(o.getFullYear(),s.getMonth(),s.getDate()),t=Ca(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=Ca(o,e)),t}}},isExported:!0},KJ={description:j(`Converts a date string to a date value.`),args:[k(`date_string (string)`,j(`The string representing the date.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);return n===null?new N(j(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},qJ={description:j(`Day of the month that a specific date falls on.`),args:[k(`date (string)`,j(`The date from which to extract the day.`))],compute:function(e){return z(e,this.locale).getDate()},isExported:!0},JJ={description:j(`Number of days between two dates.`),args:[k(`end_date (date)`,j(`The end of the date range.`)),k(`start_date (date)`,j(`The start of the date range.`))],compute:function(e,t){let n=z(e,this.locale),r=z(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Wi)},isExported:!0},YJ={description:j(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation.`)),k(`end_date (date)`,j(`The end date to consider in the calculation.`)),k(`method (boolean, default=false)`,j(`An indicator of what day count method to use.`),[{value:!1,label:j(`U.S. NASD method (default)`)},{value:!0,label:j(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=xa(r,i,R(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},XJ={description:j(`Date a number of months before/after another date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:ha(ya(z(e,this.locale),Math.trunc(I(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},ZJ={description:j(`Last day of a month before or after a date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=z(e,this.locale),r=Math.trunc(I(t,this.locale));return{value:ha(new P(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},QJ={description:j(`Hour component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the hour component.`))],compute:function(e){return z(e,this.locale).getHours()},isExported:!0},$J={description:j(`ISO week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=z(e,this.locale),n=t.getFullYear(),r=1;for(;new P(n,0,r).getDay()!==4;)r+=1;let i=new P(n,0,r-3),a=31;for(;new P(n,11,a).getDay()!==4;)--a;let o=new P(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new P(n,11,a+3+1);break;case-1:let e=1;for(;new P(n-1,0,e).getDay()!==4;)e+=1;c=new P(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Wi;return Math.floor(l/7)+1},isExported:!0},eY={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the minute component.`))],compute:function(e){return z(e,this.locale).getMinutes()},isExported:!0},tY={description:j(`Month of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the month.`))],compute:function(e){return z(e,this.locale).getMonth()+1},isExported:!0},nY={description:j(`Net working days between two provided days.`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return aY.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function rY(e){let t=e?.value;if(typeof t==`string`){mh(t.length===7&&[...t].every(e=>e===`0`||e===`1`),j(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return mh(1<=t&&t<=7||11<=t&&t<=17,j(`The weekend (%s) must be a string or a number in the range 1-7 or 11-17.`,t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new N(j(`The weekend must be a number or a string.`))}let iY=[{value:1,label:j(`Saturday/Sunday are weekends`)},{value:2,label:j(`Sunday/Monday are weekends`)},{value:3,label:j(`Monday/Tuesday are weekends`)},{value:4,label:j(`Tuesday/Wednesday are weekends`)},{value:5,label:j(`Wednesday/Thursday are weekends`)},{value:6,label:j(`Thursday/Friday are weekends`)},{value:7,label:j(`Friday/Saturday are weekends`)},{value:11,label:j(`Sunday is the only weekend`)},{value:12,label:j(`Monday is the only weekend`)},{value:13,label:j(`Tuesday is the only weekend`)},{value:14,label:j(`Wednesday is the only weekend`)},{value:15,label:j(`Thursday is the only weekend`)},{value:16,label:j(`Friday is the only weekend`)},{value:17,label:j(`Saturday is the only weekend`)}],aY={description:j(`Net working days between two dates (specifying weekends).`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),iY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=z(t,this.locale),o=rY(n),s=new Set;r!==void 0&&no([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=P.fromTimestamp((c?i:a).getTime()),u=P.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},oY={description:j(`Current date and time as a date value.`),args:[],compute:function(){let e=P.now(),t=e.getTime()-Ui.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Wi)+n,format:db(this.locale)}},isExported:!0},sY={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the second component.`))],compute:function(e){return z(e,this.locale).getSeconds()},isExported:!0},cY={description:j(`Converts hour/minute/second into a time.`),args:[k(`hour (number)`,j(`The hour component of the time.`)),k(`minute (number)`,j(`The minute component of the time.`)),k(`second (number)`,j(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new N(j(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},lY={description:j(`Converts a time string into its serial number representation.`),args:[k(`time_string (string)`,j(`The string that holds the time representation.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);if(n===null)return new N(j(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},uY={description:j(`Current date as a date value.`),args:[],compute:function(){let e=P.now();return{value:ha(new P(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},dY={description:j(`Day of the week of the date provided (as number).`),args:[k(`date (date)`,j(`The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:j(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:j(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:j(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:j(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:j(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:j(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new N(j(`The type (%s) must be between 1 and 3 or between 11 and 17.`,r));switch(r){case 1:return i+1;case 2:return i===0?7:i;case 3:return i===0?6:i-1}let a=r-10,o=(i+1-a+7)%7;return o===0?7:o},isExported:!0},fY={description:j(`Week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:j(`Sunday`)},{value:2,label:j(`Monday`)},{value:11,label:j(`Monday`)},{value:12,label:j(`Tuesday`)},{value:13,label:j(`Wednesday`)},{value:14,label:j(`Thursday`)},{value:15,label:j(`Friday`)},{value:16,label:j(`Saturday`)},{value:17,label:j(`Sunday`)},{value:21,label:j(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new N(j(`The type (%s) is out of range.`,r.toString()));if(r===21)return $J.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new P(a,0,o);for(;s.getDay()!==i;)o+=1,s=new P(a,0,o);let c=(n.getTime()-s.getTime())/Wi;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},pY={description:j(`Date after a number of workdays.`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return mY.compute.bind(this)(e,t,{value:1},n)},isExported:!0},mY={description:j(`Date after a number of workdays (specifying weekends).`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),iY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=Math.trunc(I(t,this.locale));if(n.value===`1111111`)return new N(j(`The weekend must be different from '1111111'.`));let o=rY(n),s=new Set;r!==void 0&&no([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=P.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Ui.getTime();return{value:Math.round(f/Wi),format:this.locale.dateFormat}},isExported:!0},hY={description:j(`Year specified by a given date.`),args:[k(`date (date)`,j(`The date from which to extract the year.`))],compute:function(e){return z(e,this.locale).getFullYear()},isExported:!0},gY={description:j(`Exact number of years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`day_count_convention (number, default=0)`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n={value:0}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return r<0?new N(j(`The start_date (%s) must be positive or null.`,r)):i<0?new N(j(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new N(j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):xa(r,i,a)}},_Y={description:j(`First day of the month preceding a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){let t=z(e,this.locale);return{value:ha(new P(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},vY={description:j(`Last day of the month following a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){return ZJ.compute.bind(this)(e,{value:0})}},yY={description:j(`Quarter of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((z(e,this.locale).getMonth()+1)/3)}},bY={description:j(`First day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=yY.compute.bind(this)(e);return{value:ha(new P(hY.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},xY={description:j(`Last day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=yY.compute.bind(this)(e);return{value:ha(new P(hY.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},SY={description:j(`First day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:ha(new P(hY.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},CY={description:j(`Last day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:ha(new P(hY.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var wY=l({DELTA:()=>TY});let TY={description:j(`Compare two numeric values, returning 1 if they're equal.`),args:[k(`number1 (number)`,j(`The first number to compare.`)),k(`number2 (number, default=0)`,j(`The second number to compare.`))],compute:function(e,t={value:0}){return+(I(e,this.locale)===I(t,this.locale))},isExported:!0};var EY=l({FILTER:()=>OY,SORT:()=>kY,SORTN:()=>AY,UNIQUE:()=>jY});function DY(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;mh(n[e]!==void 0,j(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(R(wh(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Je(s)&&(s.length>1||s[0].length>1))mh(s.length===1&&s[0].length===a,j(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=I(wh(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:wz(`desc`),asc:wz(`asc`)},s=C(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?`empty`:typeof i==`string`?`text`:typeof i},l={value:s,type:s===null?`empty`:typeof s==`string`?`text`:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let OY={description:j(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[k(`range (any, range<any>)`,j(`The data to be filtered.`)),k(`condition (boolean, range<boolean>, repeating)`,j(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=B(e),r=t.map(e=>lo(B(e),e=>e.value));for(let e of r)if(!gh(e))return new N(j(`The arguments condition must be a single column or row.`));if(!_h(...t))return new N(j(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?fo(n):n,i.some(e=>e.length!==n.length))return new N(j(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?fo(o):o:new Ri(j(`No match found in FILTER evaluation`))},isExported:!1},kY={description:j(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`sort_column (any, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,...t){return fo(DY(fo(e),this.locale,...t))},isExported:!0},AY={description:j(`Returns the first n items in a data set after performing a sort.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`n (number)`,j(`The number of items to return.`)),k(`display_ties_mode (number, default=0)`,j(`A number representing the way to display ties.`)),k(`sort_column (number, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,t,...n){let r=I(t?.value??1,this.locale),i=n.length%2==0?0:I(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new N(j(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new N(j(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=DY(fo(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return fo(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return fo(o.slice(0,e));return fo(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return fo(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return fo(e)}}},isExported:!1},jY={description:j(`Unique rows in the provided source range.`),args:[k(`range (any, range<any>)`,j(`The data to filter by unique entries.`)),k(`by_column (boolean, default=FALSE)`,j(`Whether to filter the data by columns or by rows.`),[{value:!0,label:j(`Return unique columns`)},{value:!1,label:j(`Return unique rows`)}]),k(`exactly_once (boolean, default=FALSE)`,j(`Whether to return only entries with no duplicates.`),[{value:!0,label:j(`Return items that appear exactly once`)},{value:!1,label:j(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!Je(e))return[[e]];let r=R(t?.value)||!1,i=R(n?.value)||!1;r||(e=fo(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:fo(o):new N(j(`No unique values found`))},isExported:!0};var MY=l({ACCRINTM:()=>LY,AMORLINC:()=>RY,COUPDAYBS:()=>BY,COUPDAYS:()=>zY,COUPDAYSNC:()=>VY,COUPNCD:()=>HY,COUPNUM:()=>UY,COUPPCD:()=>WY,CUMIPMT:()=>GY,CUMPRINC:()=>KY,DB:()=>qY,DDB:()=>YY,DISC:()=>XY,DOLLARDE:()=>ZY,DOLLARFR:()=>QY,DURATION:()=>$Y,EFFECT:()=>eX,FV:()=>nX,FVSCHEDULE:()=>rX,INTRATE:()=>iX,IPMT:()=>oX,IRR:()=>cX,ISPMT:()=>lX,MDURATION:()=>uX,MIRR:()=>dX,NOMINAL:()=>fX,NPER:()=>pX,NPV:()=>hX,PDURATION:()=>gX,PMT:()=>vX,PPMT:()=>bX,PRICE:()=>SX,PRICEDISC:()=>CX,PRICEMAT:()=>wX,PV:()=>xX,RATE:()=>EX,RECEIVED:()=>DX,RRI:()=>OX,SLN:()=>kX,SYD:()=>AX,TBILLEQ:()=>NX,TBILLPRICE:()=>MX,TBILLYIELD:()=>PX,VDB:()=>FX,XIRR:()=>IX,XNPV:()=>LX,YIELD:()=>RX,YIELDDISC:()=>zX,YIELDMAT:()=>BX});let NY=[{value:1,label:j(`Annual`)},{value:2,label:j(`Semi-annual`)},{value:4,label:j(`Quarterly`)}],PY=[{value:0,label:j(`End of period (default)`)},{value:1,label:j(`Beginning of period`)}],FY=[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)];function IY(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){mh(d<r&&a!==void 0,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,mh(d<r,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let LY={description:j(`Accrued interest of security paying at maturity.`),args:[k(`issue (date)`,j(`The date the security was initially issued.`)),k(`maturity (date)`,j(`The maturity date of the security.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a<0)return new N(aJ(a));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(DJ(s));if(c<=0)return new N(EJ(c));let u=xa(a,o,l);return s*c*u},isExported:!0},RY={description:j(`Depreciation for an accounting period.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`purchase_date (date)`,j(`The date the asset was purchased.`)),k(`first_period_end (date)`,j(`The date the first period ended.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`rate (number)`,j(`The deprecation rate.`)),k(`day_count_convention (number, optional)`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=I(e,this.locale),c=Math.trunc(I(t,this.locale)),l=Math.trunc(I(n,this.locale)),u=I(r,this.locale),d=I(i,this.locale),f=I(a,this.locale),p=Math.trunc(I(o,this.locale));if(s<=0)return new N(Wq(s));if(c<0)return new N(CJ(c));if(u<0)return new N(OJ(u));if(u>s)return new N(kJ(u,s));if(d<0)return new N(gJ(d));if(f<=0)return new N(EJ(f));if(RJ(p))return new N(Kq(p));if(c>l)return new N(SJ(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=xa(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},zY={description:j(`Days in coupon period containing settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));if(s===1){let i=WY.compute.bind(this)(e,t,n,r).value,a=HY.compute.bind(this)(e,t,n,r).value;return I(a,this.locale)-I(i,this.locale)}return(s===3?365:360)/o},isExported:!0},BY={description:j(`Days from settlement until next coupon.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=WY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=xa(l,i,s);return Math.round(e*360)}let u=z(i,this.locale),d=z(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&va(d)&&va(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&va(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},VY={description:j(`Days from settlement until next coupon.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=HY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=xa(i,l,s);return Math.round(e*360)}let u=BY.compute.bind(this)(e,t,n,r);return I(zY.compute.bind(this)(e,t,n,r),this.locale)-I(u,this.locale)},isExported:!0},HY={description:j(`Next coupon date after the settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=12/o,l=UY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-(I(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},UY={description:j(`Number of coupons between settlement and maturity.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=1,l=a,u=12/o;for(;l>i;)l=ha(ya(z(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},WY={description:j(`Last coupon date prior to or on the settlement date.`),args:FY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(lJ(i,a));if(zJ(o))return new N(Gq(o));if(RJ(s))return new N(Kq(s));let c=12/o,l=UY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},GY={description:j(`Cumulative interest paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(pJ(u));if(o<=0)return new N(nJ(o));if(s<=0)return new N(sJ(s));if(o>s)return new N(tJ(o,s));if(s>u)return new N(oJ(s,u));if(c<=0)return new N(EJ(c));if(l<=0)return new N(bJ(l));let f=0;for(let e=o;e<=s;e++)f+=aX(c,e,u,l,0,d);return f},isExported:!0},KY={description:j(`Cumulative principal paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(pJ(u));if(o<=0)return new N(nJ(o));if(s<=0)return new N(sJ(s));if(o>s)return new N(tJ(o,s));if(s>u)return new N(oJ(s,u));if(c<=0)return new N(EJ(c));if(l<=0)return new N(bJ(l));let f=0;for(let e=o;e<=s;e++)f+=yX(c,e,u,l,0,d);return f},isExported:!0},qY={description:j(`Depreciation via declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`month (number, optional)`,j(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=Math.trunc(I(r,this.locale)),l=i.length?Math.trunc(I(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new N(Uq(a));if(o<0)return new N(OJ(o));if(c<=0)return new N(yJ(c));if(s<=0)return new N(cJ(s));if(1>l||l>12)return new N(uJ(l));if(c>u)return new N(hJ(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},JY=`#,##0.00`,YY={description:j(`Depreciation via double-declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(a<0)return new N(Uq(a));if(o<0)return new N(OJ(o));if(c<=0)return new N(yJ(c));if(s<=0)return new N(cJ(s));if(c>s)return new N(vJ(c,s));if(l<=0)return new N(qq(l));if(a===0||o>=a)return{value:0,format:JY};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:JY};if(c<=1)return{value:a*u,format:JY};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:JY}},isExported:!0},XY={description:j(`Discount rate of a security based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(xJ(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return(c-s)/c/u},isExported:!0},ZY={description:j(`Convert a decimal fraction to decimal value.`),args:[k(`fractional_price (number)`,j(`The price quotation given using fractional decimal conventions.`)),k(`unit (number)`,j(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(FJ(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},QY={description:j(`Convert a decimal value to decimal fraction.`),args:[k(`decimal_price (number)`,j(`The price quotation given as a decimal value.`)),k(`unit (number)`,j(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(FJ(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},$Y={description:j(`Number of periods for an investment to reach a value.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=I(n,this.locale),l=I(r,this.locale),u=Math.trunc(I(i,this.locale)),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(lJ(o,s));if(zJ(u))return new N(Gq(u));if(RJ(d))return new N(Kq(d));if(c<0)return new N(TJ(c));if(l<0)return new N(IJ(l));let f=xa(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},eX={description:j(`Annual effective interest rate.`),args:[k(`nominal_rate (number)`,j(`The nominal interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(dJ(n)):r<=0?new N(_J(r)):(1+n/r)**+r-1},isExported:!0};function tX(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let nX={description:j(`Future value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`present_value (number, default=0)`,j(`The current value of the annuity.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:tX(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),+!!R(i)),format:`#,##0.00`}},isExported:!0},rX={description:j(`Future value of principal from series of rates.`),args:[k(`principal (number)`,j(`The amount of initial capital or value to compound against.`)),k(`rate_schedule (number, range<number>)`,j(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=I(e,this.locale);return ao([t],(e,t)=>e*(1+I(t,this.locale)),n)},isExported:!0},iX={description:j(`Calculates effective interest rate.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested in the security.`)),k(`redemption (number)`,j(`The amount to be received at maturity.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(c<=0)return new N(iJ(c));if(s<=0)return new N(DJ(s));if(RJ(l))return new N(Kq(l));let u=xa(a,o,l);return(s-c)/c/u},isExported:!0};function aX(e,t,n,r,i,a){return _X(e,n,r,i,a)-yX(e,t,n,r,i,a)}let oX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:aX(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),I(i,this.locale),+!!R(a)),format:`#,##0.00`}},isExported:!0},sX=.1,cX={description:j(`Internal rate of return given periodic cashflows.`),args:[k(`cashflow_amounts (number, range<number>)`,j(`An array or range containing the income or payments associated with the investment.`)),k(`rate_guess (number, default=${sX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:sX}){let n=I(t,this.locale);if(n<=-1)return new N(wJ(n));let r=!1,i=!1,a=[];if(ro([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new N(Hq);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:IY(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},lX={description:j(`Returns the interest paid at a particular period of an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`period (number)`,j(`The period for which you want to view the interest payment.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);return o===0?new N(fJ(o)):-1*(s-a/o*s)*i},isExported:!0},uX={description:j(`Modified Macaulay duration.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=$Y.compute.bind(this)(e,t,n,r,i,a),s=I(r,this.locale),c=Math.trunc(I(i,this.locale));return I(o,this.locale)/(1+s/c)},isExported:!0},dX={description:j(`Modified internal rate of return.`),args:[k(`cashflow_amounts (range<number>)`,j(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),k(`financing_rate (number)`,j(`The interest rate paid on funds invested.`)),k(`reinvestment_return_rate (number)`,j(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=fo(e).flat().filter(e=>e.value!==null).map(e=>I(e,this.locale)),o=a.length,s=0,c=0;for(let e of C(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new N(Hq);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},fX={description:j(`Annual nominal interest rate.`),args:[k(`effective_rate (number)`,j(`The effective interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(Zq(n)):r<=0?new N(_J(r)):((n+1)**(1/r)-1)*r},isExported:!0},pX={description:j(`Number of payment periods for an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`payment_amount (number)`,j(`The amount of each payment made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function mX(e,t,n,r){let i=0;return oo(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let hX={description:j(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow (number, range<number>, repeating)`,j(`The future cash flows.`))],compute:function(e,...t){let n=I(e,this.locale);return n===-1?new N(Jq(n)):{value:mX(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},gX={description:j(`Computes the number of periods needed for an investment to reach a value.`),args:[k(`rate (number)`,j(`The rate at which the investment grows each period.`)),k(`present_value (number)`,j(`The investment's current value.`)),k(`future_value (number)`,j(`The investment's desired future value.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(EJ(r)):i<=0?new N(bJ(i)):a<=0?new N(rJ(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function _X(e,t,n,r,i){if(t<=0)throw new N(pJ(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let vX={description:j(`Periodic payment for an annuity investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){let a=I(t,this.locale),o=I(e,this.locale),s=+!!R(i),c=I(r,this.locale);return{value:_X(o,a,I(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function yX(e,t,n,r,i,a){if(n<=0)throw new N(pJ(n));if(t<=0||t>n)throw new N(mJ(n));let o=_X(e,n,r,i,a);return a===1&&t===1?o:o+-tX(e,a===0?t-1:t-2,o,r+o*a,0)*e}let bX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=I(n,this.locale),s=I(e,this.locale),c=I(t,this.locale),l=+!!R(a),u=I(i,this.locale);return{value:yX(s,c,o,I(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},xX={description:j(`Present value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},SX={description:j(`Price of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(lJ(s,c));if(zJ(f))return new N(Gq(f));if(RJ(p))return new N(Kq(p));if(l<0)return new N(TJ(l));if(u<0)return new N(IJ(u));if(d<=0)return new N(DJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},CX={description:j(`Price of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the security at time of purchase.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(Yq(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return c-s*c*u},isExported:!0},wX={description:j(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o<=c)return new N(MJ(o,c));if(o>=s)return new N(lJ(o,s));if(RJ(d))return new N(Kq(d));if(l<0)return new N(TJ(l));if(u<0)return new N(IJ(u));let f=xa(o,s,d),p=xa(o,c,d),m=100+xa(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},TX=.1,EX={description:j(`Interest rate of an annuity investment.`),args:[k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_per_period (number)`,j(`The amount per period to be paid.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),PY),k(`rate_guess (number, default=${TX})`,j(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:TX}){let o=I(e,this.locale),s=I(t,this.locale),c=+!!R(i),l=I(a,this.locale)||TX,u=I(r,this.locale),d=I(n,this.locale);return o<=0?new N(pJ(o)):LJ([s,d,u])?l<=-1?new N(wJ(l)):(u-=s*c,d+=s*c,{value:IY(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new N(j(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},DX={description:j(`Amount received at maturity for a security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested (irrespective of face value of each security).`)),k(`discount (number)`,j(`The discount rate of the security invested in.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));return a>=o?new N(lJ(a,o)):RJ(l)?new N(Kq(l)):s<=0?new N(iJ(s)):c<=0?new N(Yq(c)):s/(1-c*xa(a,o,l))},isExported:!0},OX={description:j(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[k(`number_of_periods (number)`,j(`The number of periods.`)),k(`present_value (number)`,j(`The present value of the investment.`)),k(`future_value (number)`,j(`The future value of the investment.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(pJ(r)):(a/i)**(1/r)-1},isExported:!0},kX={description:j(`Depreciation of an asset using the straight-line method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},AX={description:j(`Depreciation via sum of years digit method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);if(s<=0)return new N(yJ(s));if(o<=0)return new N(cJ(o));if(s>o)return new N(vJ(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function jX(e,t,n){return 100*(1-n*xa(e,t,2))}let MX={description:j(`Price of a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);return r>=i?new N(lJ(r,i)):BJ(r,i,this.locale)?a<=0?new N(Yq(a)):a>=1?new N(Xq(a)):jX(r,i,a):new N(jJ(r,i))},isExported:!0},NX={description:j(`Equivalent rate of return for a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(lJ(r,i));if(!BJ(r,i,this.locale))return new N(jJ(r,i));if(a<=0)return new N(Yq(a));if(a>=1)return new N(Xq(a));let o=JJ.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=jX(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},PX={description:j(`The yield of a US Treasury bill based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(lJ(r,i));if(!BJ(r,i,this.locale))return new N(jJ(r,i));if(a<=0)return new N(xJ(a));let o=xa(r,i,2);return(100-a)/a*(1/o)},isExported:!0},FX={description:j(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`start (number)`,j(`Starting period to calculate depreciation.`)),k(`end (number)`,j(`Ending period to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The number of months in the first year of depreciation.`)),k(`no_switch (number, default=false)`,j(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:j(`Switch to straight-line depreciation`)},{value:!0,label:j(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=I(e,this.locale),c=I(t,this.locale),l=I(n,this.locale),u=Math.trunc(I(r,this.locale)),d=Math.trunc(I(i,this.locale)),f=I(a,this.locale),p=R(o);if(s<0)return new N(Uq(s));if(c<0)return new N(OJ(c));if(l<=0)return new N(cJ(l));if(u<0)return new N(NJ(u));if(d<0)return new N(Qq(d));if(u>d)return new N(PJ(u,d));if(d>l)return new N($q(d,l));if(f<=0)return new N(qq(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},IX={description:j(`Internal rate of return given non-periodic cash flows.`),args:[k(`cashflow_amounts (range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),k(`rate_guess (number, default=${TX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:TX}){let r=I(n,this.locale);if(!_h(e,t))return new N(Vq);let i=e.flat().map(e=>I(e,this.locale)),a=t.flat().map(e=>I(e,this.locale));if(!LJ(i))return new N(Hq);if(a.some(e=>e<a[0]))return new N(eJ(a[0]));if(r<=-1)return new N(wJ(r));let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return IY(e=>{let t=c[0];for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},LX={description:j(`Net present value given to non-periodic cash flows..`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow_amounts (number, range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (number, range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=I(e,this.locale);if(!_h(t,n))return new N(Vq);let i=B(t).flat().map(e=>qa(e,this.locale)),a=B(n).flat().map(e=>qa(e,this.locale));if(a.some(e=>e<a[0]))return new N(eJ(a[0]));if(r<=0)return new N(EJ(r));if(i.length===1)return i[0];let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of C(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},RX={description:j(`Annual yield of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),NY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(lJ(s,c));if(zJ(f))return new N(Gq(f));if(RJ(p))return new N(Kq(p));if(l<0)return new N(TJ(l));if(u<=0)return new N(xJ(u));if(d<=0)return new N(DJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function b(e){return v(u,g,h,e,_,d)}function ee(e){return y(u,g,h,e,_)}return(IY(b,ee,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},zX={description:j(`Annual yield of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(lJ(a,o));if(RJ(l))return new N(Kq(l));if(s<=0)return new N(xJ(s));if(c<=0)return new N(DJ(c));let u=xa(a,o,l);return(c/s-1)/u},isExported:!0},BX={description:j(`Annual yield of a security paying interest at maturity.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),VJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(lJ(o,s));if(RJ(d))return new N(Kq(d));if(o<c)return new N(AJ(o,c));if(l<0)return new N(TJ(l));if(u<=0)return new N(xJ(u));let f=xa(c,s,d),p=xa(c,o,d),m=xa(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var VX=l({CELL:()=>UX,ISBLANK:()=>ZX,ISERR:()=>WX,ISERROR:()=>GX,ISFORMULA:()=>$X,ISLOGICAL:()=>KX,ISNA:()=>qX,ISNONTEXT:()=>JX,ISNUMBER:()=>YX,ISTEXT:()=>XX,NA:()=>QX});let HX=[{value:`address`,label:j(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:j(`Returns the column number of the cell in reference.`)},{value:`contents`,label:j(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:j(`Returns the format of the top left cell in reference.`)},{value:`row`,label:j(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:j(`Returns the type of data in the cell in reference. The following values are returned: "b" for a blank cell, "l" (for label) if the cell contains plain text, and "v" (for value) if the cell contains any other type of data.`)}],UX={description:j(`Gets information about a cell.`),args:[k(`info_type (string)`,j(`The type of information requested.`),HX),k(`reference (any, range<any>)`,j(`The reference to the cell.`))],compute:function(e,t){let n=L(e).toLowerCase();if(!HX.map(e=>e.value).includes(n))return new N(j(`The info_type should be one of %s.`,HX.join(`, `)));let r=B(t)[0][0],i=r.position;if(i===void 0)return new N(j(`The reference is invalid.`));switch(n){case`address`:return(this.__originSheetId===i.sheetId?``:this.getters.getSheetName(i.sheetId)+`!`)+E(i.col,i.row,{colFixed:!0,rowFixed:!0});case`col`:return i.col+1;case`contents`:return r.value;case`format`:return r.format||``;case`row`:return i.row+1;case`type`:return r.value===null?`b`:ou(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},WX={description:j(`Whether a value is an error other than #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)&&t!==M.NotAvailable},isExported:!0},GX={description:j(`Whether a value is an error.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)},isExported:!0},KX={description:j("Whether a value is `true` or `false`."),args:[k(`value (any)`,j(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},qX={description:j(`Whether a value is the error #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){return e?.value===M.NotAvailable},isExported:!0},JX={description:j(`Whether a value is non-textual.`),args:[k(`value (any)`,j(`The value to be checked.`))],compute:function(e){return!XX.compute.bind(this)(e)},isExported:!0},YX={description:j(`Whether a value is a number.`),args:[k(`value (any)`,j(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},XX={description:j(`Whether a value is text.`),args:[k(`value (any)`,j(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&F(e?.value)===!1},isExported:!0},ZX={description:j(`Whether the referenced cell is empty`),args:[k(`value (any)`,j(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},QX={description:j(`Returns the error value #N/A.`),args:[],compute:function(){return{value:M.NotAvailable}},isExported:!0},$X={description:j(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new Li(Ha):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var eZ=l({AND:()=>tZ,FALSE:()=>nZ,IF:()=>rZ,IFERROR:()=>iZ,IFNA:()=>aZ,IFS:()=>oZ,NOT:()=>sZ,OR:()=>cZ,SWITCH:()=>lZ,TRUE:()=>uZ,XOR:()=>dZ});let tZ={description:j("Logical `and` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=Qh(e);return n?t:new N(Do)},isExported:!0},nZ={description:j("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},rZ={description:j(`Returns value depending on logical expression.`),args:[k(`logical_expression (boolean, range<boolean>)`,j(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),k(`value_if_true (any, range)`,j(`The value the function returns if logical_expression is TRUE.`)),k(`value_if_false (any, range, default=FALSE)`,j(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Eh(e)?po(rZ.compute,[e,t,n]):(R(wh(e))?t:n)??{value:0}},isExported:!0},iZ={description:j(`Value if it is not an error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an error.`))],compute:function(e,t){return Eh(e)?po(iZ.compute,[e,t]):(F(wh(e)?.value)?t:e)??{value:0}},isExported:!0},aZ={description:j(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not #N/A an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return Eh(e)?po(aZ.compute,[e,t]):(wh(e)?.value===M.NotAvailable?t:e)??{value:0}},isExported:!0},oZ={description:j(`Returns a value depending on multiple logical expressions.`),args:[k(`condition (any, range, repeating)`,j(`The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.`)),k(`value (any, range, repeating)`,j(`The value to be returned if its corresponding condition is TRUE.`))],compute:function(...e){if(e.length%2!=0)return new N(j(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(Eh(e[0]))return po(oZ.compute,e);let t=R(wh(e.shift())),n=e.shift();if(t)return n??{value:0}}return new N(j(`No match.`))},isExported:!0},sZ={description:j(`Returns opposite of provided logical value.`),args:[k(`logical_expression (boolean)`,j(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!R(e)},isExported:!0},cZ={description:j("Logical `or` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=$h(e);return n?t:new N(Do)},isExported:!0},lZ={description:j(`Returns a value by comparing cases to an expression.`),args:[k(`expression (number, boolean, string)`,j(`The value to be checked.`)),k(`case (any, repeating)`,j(`Case to be checked against expression.`)),k(`value (any, repeating)`,j(`Value to be returned if its corresponding case matches expression.`)),k(`default (any, default="empty")`,j(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Ba(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&F(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},uZ={description:j("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},dZ={description:j("Logical `xor` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let t=!1,n=!1;return ho(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new N(Do)},isExported:!0};function fZ(e,t){let n=t.getPivotId(e);if(!n)throw new N(j(`There is no pivot with id "%s"`,e));return n}function pZ(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new N(j(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function mZ(e){if(e.length%2!=0)throw new N(j(`Function PIVOT takes an even number of arguments.`))}function hZ(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=wn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Li;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&In(D(e.__originCellPosition),n))throw new Ii;r.push(o)}for(let i of n)i.computedBy&&r.push(...e.getters.getMeasureFullDependencies(t,i));let a=e.__originCellPosition;a&&r.length&&(e.updateDependencies?.(a),e.addDependencies?.(a,r))}var gZ=l({ADDRESS:()=>yZ,CHOOSE:()=>IZ,COLUMN:()=>bZ,COLUMNS:()=>xZ,DROP:()=>LZ,FORMULATEXT:()=>zZ,HLOOKUP:()=>SZ,INDEX:()=>CZ,INDIRECT:()=>wZ,LOOKUP:()=>TZ,MATCH:()=>EZ,OFFSET:()=>FZ,PIVOT:()=>PZ,PIVOT_HEADER:()=>NZ,PIVOT_VALUE:()=>MZ,ROW:()=>DZ,ROWS:()=>OZ,TAKE:()=>RZ,VLOOKUP:()=>kZ,XLOOKUP:()=>jZ});let _Z=[{value:!0,label:j(`A1 style (default)`)},{value:!1,label:j(`R1C1 style`)}],vZ=[{value:!0,label:j(`Approximate match (default)`)},{value:!1,label:j(`Exact match`)}],yZ={description:j(`Returns a cell reference as a string. `),args:[k(`row (number)`,j(`The row number of the cell reference. `)),k(`column (number)`,j(`The column number (not name) of the cell reference. A is column number 1. `)),k(`absolute_relative_mode (number, default=1)`,j(`An indicator of whether the reference is row/column absolute.`),[{value:1,label:j(`Absolute row and column (e.g. $A$1)`)},{value:2,label:j(`Absolute row, relative column (e.g. A$1)`)},{value:3,label:j(`Relative row, absolute column (e.g. $A1)`)},{value:4,label:j(`Relative row and column (e.g. A1)`)}]),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),_Z),k(`sheet (string, optional)`,j(`A string indicating the name of the sheet into which the address points.`))],compute:function(e,t,n={value:1},r={value:!0},i){let a=Ya(e,this.locale),o=Ya(t,this.locale);if(a<1)return new N(yh(a));if(o<1)return new N(yh(o));let s=Ya(n,this.locale);if(![1,2,3,4].includes(s))return new N(Ua(1,4,s));let c=R(r),l;if(c){let e={rowFixed:[1,2].includes(s),colFixed:[1,3].includes(s)};l=E(o-1,a-1,e)}else l=([1,2].includes(s)?`R${a}`:`R[${a}]`)+([1,3].includes(s)?`C${o}`:`C[${o}]`);return i===void 0?l:Qo(L(i),l)},isExported:!0},bZ={description:j(`Column number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.col+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.col;return t.length===1?r+1:co(t.length,1,e=>({value:r+e+1}))},isExported:!0},xZ={description:j(`Number of columns in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose column count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t.length},isExported:!0},SZ={description:j(`Horizontal lookup`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The row index of the value to be returned, where the first row in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.`),vZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a[0].length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[R(r.value)?bo(a,e,`nextSmaller`,`asc`,a.length,o):xo(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ba(e):s[i-1]},isExported:!0},CZ={description:j(`Returns the content of a cell, specified by row and column offset.`),args:[k(`reference (any, range)`,j(`The range of cells from which the values are returned.`)),k(`row (number, default=0)`,j(`The index of the row to be returned from within the reference range of cells.`)),k(`column (number, default=0)`,j(`The index of the column to be returned from within the reference range of cells.`))],compute:function(e,t={value:0},n={value:0}){let r=B(e),i=I(t.value,this.locale),a=I(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new N(j(`Index out of range.`)):i===0&&a===0?r:i===0?[r[a-1]]:a===0?r.map(e=>[e[i-1]]):r[a-1][i-1]},isExported:!0},wZ={description:j(`Returns the content of a cell, specified by a string.`),args:[k(`reference (string)`,j(`The range of cells from which the values are returned.`)),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),_Z)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Li(j(`Reference should be defined.`));if(!R(t))return new N(j(`R1C1 notation is not supported.`));let r=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);let a=this.getters.getNamedRange(n),o=a?a.range:this.getters.getRangeFromSheetXC(r,n);if(o===void 0||o.invalidXc||o.invalidSheetName)return new Li;i&&this.addDependencies?.(i,[o]);let s=[];for(let e=o.zone.left;e<=o.zone.right;e++){let t=[];for(let n=o.zone.top;n<=o.zone.bottom;n++){let r={sheetId:o.sheetId,col:e,row:n};t.push(this.getFormulaResult(r))}s.push(t)}return s.length===1&&s[0].length===1?s[0][0]:s},isExported:!0},TZ={description:j(`Look up a value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`search_array (any, range)`,j(`One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.`)),k(`result_range (any, range, optional)`,j(`The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.`))],compute:function(e,t,n){let r=B(t),i=B(n),a=r.length,o=r[0].length,s=o>=a,c=bo(r,e,`nextSmaller`,`asc`,s?o:a,s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value);return c===-1||s&&r[0][c]===void 0||!s&&r[c][o-1]===void 0?Ba(e):i[0].length===0?s?r[a-1][c]:r[c][o-1]:(a=i.length,o=i[0].length,a!==1&&o!==1?new N(j(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},EZ={description:j(`Position of item in range that matches value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The one-dimensional array to be searched.`)),k(`search_type (number, default=1)`,j(`The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.`),[{value:1,label:j(`Ascending order (default)`)},{value:0,label:j(`Exact match`)},{value:-1,label:j(`Descending order`)}])],compute:function(e,t,n={value:1}){let r=I(n,this.locale),i=B(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new N(j(`The range must be a single row or a single column.`));let s=-1,c=a===1?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,l=a===1?i[0].length:i.length;switch(r=Math.sign(r),r){case 1:s=bo(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=xo(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=bo(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ba(e):s+1},isExported:!0},DZ={description:j(`Row number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition?.row===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.row+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.row;return t[0].length===1?r+1:co(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},OZ={description:j(`Number of rows in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose row count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t[0].length},isExported:!0},kZ={description:j(`Vertical lookup.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The column index of the value to be returned, where the first column in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.`),vZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a.length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=R(r.value)?bo(a,e,`nextSmaller`,`asc`,a[0].length,o):xo(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ba(e):c},isExported:!0},AZ={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},jZ={description:j(`Search a range for a match and return the corresponding item from a second range.`),args:[k(`search_key (string,number,boolean)`,j(`The value to search for.`)),k(`lookup_range (any, range)`,j(`The range to consider for the search. Should be a single column or a single row.`)),k(`return_range (any, range)`,j(`The range containing the return value. Should have the same dimensions as lookup_range.`)),k(`if_not_found (any, optional)`,j(`If a valid match is not found, return this value.`)),k(`match_mode (any, default=0)`,j(`Specifies how to match search_key with the items in lookup_range. `),[{value:0,label:j(`Exact match (default)`)},{value:-1,label:j(`Exact match or next smaller item`)},{value:1,label:j(`Exact match or next larger item`)},{value:2,label:j(`Wildcard character match`)}]),k(`search_mode (any, default=1)`,j(`Specifies the search mode to use. By default, a first to last search will be used.`),[{value:1,label:j(`Search first to last (default)`)},{value:-1,label:j(`Search last to first`)},{value:2,label:j(`Binary search (sorted ascending order)`)},{value:-2,label:j(`Binary search (sorted descending order)`)}])],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(I(i.value,this.locale)),s=Math.trunc(I(a.value,this.locale)),c=B(t),l=B(n);if(c.length!==1&&c[0].length!==1)return new N(j(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new N(j(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new N(j(`match_mode should be a value in [-1, 0, 1, 2].`));let u=c.length===1?`col`:`row`;if(o===2&&[-2,2].includes(s))return new N(j(`The search and match mode combination is not supported for XLOOKUP evaluation.`));if(u===`col`?l[0].length!==c[0].length:l.length!==c.length)return new N(j(`return_range should have the same dimensions as lookup_range.`));let d=u===`col`?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,f=u===`col`?c[0].length:c.length,p=AZ[o],m=s===-1,h=s===2||s===-2?bo(c,e,p,s===2?`asc`:`desc`,f,d):xo(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ba(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},MZ={description:j(`Get the value from a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`measure_name (string)`,j(`Name of the measure.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,boolean,repeating,optional)`,j(`Value.`))],compute:function(e,t,...n){let r=L(e),i=L(t),a=fZ(r,this.getters);pZ(a,i,this.getters),mZ(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);hZ(this,a,s.measures.filter(e=>e.id===i)),o.init({reload:o.needsReevaluation});let c=o.assertIsValid({throwOnError:!1});if(c)return c;if(!o.areDomainArgsFieldsValid(n)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let l=o.parseArgsToPivotDomain(n);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(a)?.trackValue(i,l),o.getPivotCellValueAndFormat(i,l)}},NZ={description:j(`Get the header of a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,value,repeating,optional)`,j(`Value.`))],compute:function(e,...t){let n=L(e),r=fZ(n,this.getters);mZ(t);let i=this.getters.getPivot(r);hZ(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let o=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(r)?.trackHeader(o);let s=o.at(-1);if(s?.field===`measure`)return i.getPivotMeasureValue(L(s.value),o);let{value:c,format:l}=i.getPivotHeaderValueAndFormat(o);return{value:c,format:!s||s.field===`measure`||s.value===`false`?void 0:l}}},PZ={description:j(`Get a pivot table.`),args:[k(`pivot_id (string)`,j(`ID of the pivot.`)),k(`row_count (number, optional)`,j(`number of rows`)),k(`include_total (boolean, default=TRUE)`,j(`Whether to include total/sub-totals or not.`)),k(`include_column_titles (boolean, default=TRUE)`,j(`Whether to include the column titles or not.`)),k(`column_count (number, optional)`,j(`number of columns`)),k(`include_measure_titles (boolean, default=TRUE)`,j(`Whether to include the measure titles row or not.`))],compute:function(e,t,n,r,i,a){let o=fZ(L(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=qg(c,t,n,r,i,a,this.locale);if(l.numberOfRows<0)return new N(j(`The number of rows must be positive.`));if(l.numberOfColumns<0)return new N(j(`The number of columns must be positive.`));hZ(this,o,c.measures),s.init({reload:s.needsReevaluation});let u=s.assertIsValid({throwOnError:!1});if(u)return u;let d=s.getCollapsedTableStructure();if(d.numberOfCells>5e5)return new N(qy(d.numberOfCells,this.locale));let f=d.getPivotCells(l),p=this.getters.getPivotName(o),{numberOfCols:m,numberOfRows:h}=d.getPivotTableDimensions(l);if(h===0)return[[{value:p}]];let g=[];for(let e of C(0,m)){g[e]=[];for(let t of C(0,h)){let n=f[e][t];switch(n.type){case`EMPTY`:g[e].push({value:``});break;case`HEADER`:let t=s.getPivotHeaderValueAndFormat(n.domain);g[e].push(Rg(n.domain,t));break;case`MEASURE_HEADER`:g[e].push(s.getPivotMeasureValue(n.measure,n.domain));break;case`VALUE`:g[e].push(s.getPivotCellValueAndFormat(n.measure,n.domain));break;case`ROW_GROUP_NAME`:let r=s.definition.rows.find(e=>e.nameWithGranularity===n.rowField)?.displayName;g[e].push({value:r||``});break}}}return(l.displayColumnHeaders||l.displayMeasuresRow)&&f[0][0].type===`EMPTY`&&(g[0][0]={value:p}),g}},FZ={description:j(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[k(`cell_reference (any, range<any>)`,j(`The starting point from which to count the offset rows and columns.`)),k(`offset_rows (number)`,j(`The number of rows to offset by.`)),k(`offset_columns (number)`,j(`The number of columns to offset by.`)),k(`height (number, default='height of cell_reference')`,j(`The number of rows of the range to return starting at the offset target.`)),k(`width (number, default='width of cell_reference')`,j(`The number of columns of the range to return starting at the offset target.`))],compute:function(e,t,n,r,i){if(e===void 0)return new Li(Ha);let a=B(e),o=a[0][0];if(o===void 0)return new N(j(`The range is out of bounds.`));if(o.position===void 0)return new Li(Ha);let s=a[0].length,c=a.length;if(r){let e=I(r,this.locale);if(e<1)return new N(j(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=I(i,this.locale);if(e<1)return new N(j(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let l=I(t,this.locale),u=I(n,this.locale),d=this.__originCellPosition;d&&this.updateDependencies?.(d);let f=o.position.col+u,p=o.position.row+l;if(f<0||p<0)return new Li(j(`OFFSET evaluates to an out of bounds range.`));let m={left:f,top:p,right:f+c-1,bottom:p+s-1},h=o.position.sheetId,g=this.getters.getRangeFromZone(h,m);return g.invalidXc||g.invalidSheetName?new Li:(d&&this.addDependencies?.(d,[g]),co(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},IZ={description:j(`Returns an element from a list of choices based on index.`),args:[k(`index (number)`,j(`Which choice to return.`)),k(`choice (any, range<any>, repeating)`,j(`A potential value to return. May be a reference to a cell or an individual value.`))],compute:function(e,...t){let n=Math.floor(I(e,this.locale))-1;return n<0||n>=t.length?new N(j(`Index for CHOOSE is invalid. Valid values are between 1 and %(choices)s inclusive.`,{choices:t.length})):t[n]??new N(j(`Choice is undefined.`))},isExported:!0},LZ={description:j(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to drop rows or columns`)),k(`rows (number)`,j(`The number of rows to drop. A negative value drops from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to exclude. A negative value drops from the end of the array.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=e;if(Math.abs(i)>=e.length||Math.abs(r)>=e[0].length)return new N(j(`The number of rows or column to exclude must be smaller than the number of elements in the array.`));a=i>=0?a.slice(i):a.slice(0,a.length+i);for(let e=0;e<a.length;e++)r>=0?a[e]=a[e].slice(r):a[e]=a[e].slice(0,a[e].length+r);return a},isExported:!0},RZ={description:j(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to take rows or columns.`)),k(`rows (number)`,j(`The number of rows to take. A negative value takes from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to take. A negative value takes from the end of the array.`))],compute:function(e,t,n){let r=t?I(t,this.locale):e[0].length,i=I(n,this.locale),a=e;if((Math.abs(i)>=e.length||i===0)&&(i=e.length),Math.abs(r)>=e[0].length&&(r=e[0].length),a=i>=0?a.slice(0,i):a.slice(a.length+i,a.length),r===0)return new N(j(`The number of rows can not be zero.`));for(let e=0;e<a.length;e++)r>0?a[e]=a[e].slice(0,r):a[e]=a[e].slice(a[e].length+r,a[e].length);return a},isExported:!0},zZ={description:j(`Returns a formula as a string.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new Li(Ha);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Ri(j(`The cell does not contain a formula.`))},isExported:!0};var BZ=l({ADD:()=>VZ,CONCAT:()=>HZ,DIVIDE:()=>UZ,EQ:()=>qZ,GT:()=>YZ,GTE:()=>XZ,LT:()=>ZZ,LTE:()=>QZ,MINUS:()=>$Z,MULTIPLY:()=>eQ,NE:()=>tQ,POW:()=>nQ,SPILLED_RANGE:()=>rQ,UMINUS:()=>iQ,UNARY_PERCENT:()=>aQ,UPLUS:()=>oQ});let VZ={description:j(`Sum of two numbers.`),args:[k(`value1 (number)`,j(`The first addend.`)),k(`value2 (number)`,j(`The second addend.`))],compute:function(e,t){return{value:I(e,this.locale)+I(t,this.locale),format:e?.format||t?.format}}},HZ={description:j(`Concatenation of two values.`),args:[k(`value1 (string)`,j(`The value to which value2 will be appended.`)),k(`value2 (string)`,j(`The value to append to value1.`))],compute:function(e,t){return Xa(e,this.locale)+Xa(t,this.locale)},isExported:!0},UZ={description:j(`One number divided by another.`),args:[k(`dividend (number)`,j(`The number to be divided.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return n===0?new Vi(j(`The divisor must be different from zero.`)):{value:I(e,this.locale)/n,format:e?.format||t?.format}}};function WZ(e){return e===void 0||e.value===null}let GZ={number:0,string:``,boolean:!1};function KZ(e,t,n=2e-16){return Math.abs(e-t)<n}let qZ={description:j(`Equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for equality.`))],compute:function(e,t){if(F(e?.value))return e;if(F(t?.value))return t;let n=WZ(e)?GZ[typeof t?.value]:e?.value,r=WZ(t)?GZ[typeof e?.value]:t?.value;return typeof n==`string`&&(n=n.toUpperCase()),typeof r==`string`&&(r=r.toUpperCase()),typeof n==`number`&&typeof r==`number`?{value:KZ(n,r)}:{value:n===r}}};function JZ(e,t,n){if(F(e?.value))return e;if(F(t?.value))return t;let r=WZ(e)?GZ[typeof t?.value]:e?.value,i=WZ(t)?GZ[typeof e?.value]:t?.value;typeof r!=`number`&&(r=L(r).toUpperCase()),typeof i!=`number`&&(i=L(i).toUpperCase());let a=typeof r,o=typeof i;return a===`string`&&o===`number`?{value:!0}:o===`string`&&a===`number`?{value:!1}:{value:n(r,i)}}let YZ={description:j(`Strictly greater than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return JZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!KZ(e,t)&&e>t:e>t)}},XZ={description:j(`Greater than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return JZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?KZ(e,t)||e>t:e>=t)}},ZZ={description:j(`Less than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=XZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},QZ={description:j(`Less than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=YZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},$Z={description:j(`Difference of two numbers.`),args:[k(`value1 (number)`,j(`The minuend, or number to be subtracted from.`)),k(`value2 (number)`,j(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:I(e,this.locale)-I(t,this.locale),format:e?.format||t?.format}}},eQ={description:j(`Product of two numbers`),args:[k(`factor1 (number)`,j(`The first multiplicand.`)),k(`factor2 (number)`,j(`The second multiplicand.`))],compute:function(e,t){return{value:I(e,this.locale)*I(t,this.locale),format:e?.format||t?.format}}},tQ={description:j(`Not equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=qZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},nQ={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){return VG.compute.bind(this)(e,t)}},rQ={description:j(`Gets the spilled range of an array formula.`),args:[k(`ref (any, range<any>)`,j(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new Li(Ha);let t=B(e);if(t.length!==1||t[0].length!==1)return new N(j(`Only single-cell references are allowed to get the spilled range.`));let n=t[0][0];if(F(n.value))return n;if(n.position===void 0)return new Li(Ha);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new Li;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),co(i.right-i.left+1,i.bottom-i.top+1,(e,t)=>this.getFormulaResult({sheetId:a.sheetId,col:i.left+e,row:i.top+t}))},hidden:!0},iQ={description:j(`A number with the sign reversed.`),args:[k(`value (number)`,j(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-I(e,this.locale),format:e?.format}}},aQ={description:j(`Value interpreted as a percentage.`),args:[k(`percentage (number)`,j(`The value to interpret as a percentage.`))],compute:function(e){return I(e,this.locale)/100}},oQ={description:j(`A specified number, unchanged.`),args:[k(`value (any)`,j(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),sQ={transform:e=>e,inverseTransform:e=>e},cQ=1e-10,lQ=.0254,uQ=lQ/72,dQ=.3048,fQ=.9144,pQ=1609.34,mQ=1852,hQ=946073047258e4,gQ={g:{...sQ,category:`weight`},u:{...$(166053e-29),category:`weight`},grain:{...$(.0647989),category:`weight`},ozm:{...$(28.3495),category:`weight`},lbm:{...$(453.592),category:`weight`},stone:{...$(6350.29),category:`weight`},sg:{...$(14593.90294),category:`weight`},cwt:{...$(45359.237),category:`weight`},uk_cwt:{...$(50802.3),category:`weight`},ton:{...$(907184.74),category:`weight`},uk_ton:{...$(1016046.9),category:`weight`},m:{...sQ,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(cQ),category:`distance`},Picapt:{...$(uQ),category:`distance`},pica:{...$(lQ/6),category:`distance`},in:{...$(lQ),category:`distance`},ft:{...$(dQ),category:`distance`},yd:{...$(fQ),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(pQ),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(mQ),category:`distance`},ly:{...$(hQ),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...sQ,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...sQ,category:`pressure`},bar:{...$(1e5),category:`pressure`},mmHg:{...$(133.322),category:`pressure`},Torr:{...$(133.322),category:`pressure`},psi:{...$(6894.76),category:`pressure`},atm:{...$(101325),category:`pressure`},N:{...sQ,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...sQ,category:`energy`},eV:{...$(160218e-24),category:`energy`},e:{...$(1e-7),category:`energy`},flb:{...$(1.3558179483),category:`energy`},c:{...$(4.184),category:`energy`},cal:{...$(4.1868),category:`energy`},BTU:{...$(1055.06),category:`energy`},Wh:{...$(3600),category:`energy`},HPh:{...$(2684520),category:`energy`},W:{...sQ,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...sQ,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...sQ,category:`temperature`},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:`temperature`},F:{transform:e=>(e-32)*5/9+273.15,inverseTransform:e=>(e-273.15)*9/5+32,category:`temperature`},Rank:{...$(5/9),category:`temperature`},Reau:{transform:e=>e*1.25+273.15,inverseTransform:e=>(e-273.15)/1.25,category:`temperature`},"m^3":{...sQ,category:`volume`,order:3},"ang^3":{...$(cQ**3),category:`volume`,order:3},"Picapt^3":{...$(uQ**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$(lQ**3),category:`volume`,order:3},oz:{...$(295735295625e-16),category:`volume`},cup:{...$(237e-6),category:`volume`},pt:{...$(.0004731765),category:`volume`},uk_pt:{...$(568261e-9),category:`volume`},qt:{...$(.0009463529),category:`volume`},l:{...$(.001),category:`volume`},uk_qt:{...$(.0011365225),category:`volume`},gal:{...$(.0037854118),category:`volume`},uk_gal:{...$(.00454609),category:`volume`},"ft^3":{...$(dQ**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(fQ**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(pQ**3),category:`volume`,order:3},"Nmi^3":{...$(mQ**3),category:`volume`,order:3},"ly^3":{...$(hQ**3),category:`volume`,order:3},"m^2":{...sQ,category:`area`,order:2},"ang^2":{...$(cQ**2),category:`area`,order:2},"Picapt^2":{...$(uQ**2),category:`area`,order:2},"in^2":{...$(lQ**2),category:`area`,order:2},"ft^2":{...$(dQ**2),category:`area`,order:2},"yd^2":{...$(fQ**2),category:`area`,order:2},ar:{...$(100),category:`area`},Morgen:{...$(2500),category:`area`},uk_acre:{...$(4046.8564224),category:`area`},us_acre:{...$(4046.8726098743),category:`area`},ha:{...$(1e4),category:`area`},"mi^2":{...$(pQ**2),category:`area`,order:2},"Nmi^2":{...$(mQ**2),category:`area`,order:2},"ly^2":{...$(hQ**2),category:`area`,order:2},bit:{...sQ,category:`information`},byte:{...$(8),category:`information`},"m/s":{...sQ,category:`speed`},"m/hr":{...$(1/3600),category:`speed`},"km/hr":{...$(1/3.6),category:`speed`},mph:{...$(.44704),category:`speed`},kn:{...$(.5144444444),category:`speed`},admkn:{...$(.5147733333),category:`speed`}},_Q={shweight:`cwt`,lcwt:`uk_cwt`,hweight:`uk_cwt`,LTON:`uk_ton`,brton:`uk_ton`,pc:`parsec`,Pica:`Picapt`,d:`day`,mn:`min`,s:`sec`,p:`Pa`,at:`atm`,dy:`dyn`,ev:`eV`,hh:`HPh`,wh:`Wh`,btu:`BTU`,h:`HP`,cel:`C`,fah:`F`,kel:`K`,us_pt:`pt`,L:`l`,lt:`l`,ang3:`ang^3`,ft3:`ft^3`,in3:`in^3`,ly3:`ly^3`,m3:`m^3`,mi3:`mi^3`,yd3:`yd^3`,Nmi3:`Nmi^3`,Picapt3:`Picapt^3`,"Pica^3":`Picapt^3`,Pica3:`Picapt^3`,regton:`GRT`,ang2:`ang^2`,ft2:`ft^2`,in2:`in^2`,ly2:`ly^2`,m2:`m^2`,mi2:`mi^2`,Nmi2:`Nmi^2`,Picapt2:`Picapt^2`,"Pica^2":`Picapt^2`,Pica2:`Picapt^2`,yd2:`yd^2`,"m/h":`m/hr`,"m/sec":`m/s`},vQ={"":1,Y:1e24,Z:1e21,E:0xde0b6b3a7640000,P:0x38d7ea4c68000,T:0xe8d4a51000,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:2**80,Zi:2**70,Ei:2**60,Pi:2**50,Ti:2**40,Gi:2**30,Mi:2**20,ki:2**10},yQ={weight:j(`Weight`),distance:j(`Distance`),time:j(`Time`),pressure:j(`Pressure`),force:j(`Force`),energy:j(`Energy`),power:j(`Power`),magnetism:j(`Magnetism`),temperature:j(`Temperature`),volume:j(`Volume`),area:j(`Area`),information:j(`Information`),speed:j(`Speed`)},bQ=Object.entries(gQ).map(([e,t])=>({value:e,label:xQ(t.category)}));function xQ(e){return yQ[e]??``}function SQ(e){for(let[t,n]of Object.entries(vQ)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=gQ[r];if(!i&&_Q[r]&&(i=gQ[_Q[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var CQ=l({CONVERT:()=>wQ});let wQ={description:j(`Converts a numeric value to a different unit of measure.`),args:[k(`value (number)`,j(`the numeric value in start_unit to convert to end_unit`)),k(`start_unit (string)`,j(`The starting unit, the unit currently assigned to value`),bQ),k(`end_unit (string)`,j(`The unit of measure into which to convert value`),bQ)],compute:function(e,t,n){let r=I(e,this.locale),i=L(t),a=L(n),o=SQ(i),s=SQ(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:M.GenericError,message:j(`Incompatible units of measure ('%s' vs '%s')`,xQ(o.category),xQ(s.category))}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,a)}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,i)}},isExported:!0};var TQ=l({CHAR:()=>kQ,CLEAN:()=>AQ,CONCATENATE:()=>jQ,EXACT:()=>MQ,FIND:()=>NQ,FORMAT_LARGE_NUMBER:()=>PQ,JOIN:()=>FQ,LEFT:()=>IQ,LEN:()=>LQ,LOWER:()=>RQ,MID:()=>zQ,PROPER:()=>BQ,REGEXEXTRACT:()=>HQ,REGEXREPLACE:()=>UQ,REGEXTEST:()=>VQ,REPLACE:()=>WQ,RIGHT:()=>GQ,SEARCH:()=>KQ,SPLIT:()=>qQ,SUBSTITUTE:()=>JQ,TEXT:()=>$Q,TEXTAFTER:()=>t$,TEXTBEFORE:()=>n$,TEXTJOIN:()=>YQ,TEXTSPLIT:()=>XQ,TRIM:()=>ZQ,UPPER:()=>QQ,VALUE:()=>e$});let EQ=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,DQ=[{value:0,label:j(`Case-sensitive (default)`)},{value:1,label:j(`Case-insensitive`)}],OQ=[{value:0,label:j(`Don't match to end (default)`)},{value:1,label:j(`Match to end`)}],kQ={description:j(`Gets character associated with number.`),args:[k(`table_number (number)`,j(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(I(e,this.locale));return t<1?new N(j(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},AQ={description:j(`Remove non-printable characters from a piece of text.`),args:[k(`text (string)`,j(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=Xa(e,this.locale),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},jQ={description:j(`Appends strings to one another.`),args:[k(`string (string, range<string>, repeating)`,j(`String to append in sequence.`))],compute:function(...e){return ao(e,(e,t)=>e+Xa(t,this.locale),``)},isExported:!0},MQ={description:j(`Tests whether two strings are identical.`),args:[k(`string1 (string)`,j(`The first string to compare.`)),k(`string2 (string)`,j(`The second string to compare.`))],compute:function(e,t){return Xa(e,this.locale)===Xa(t,this.locale)},isExported:!0},NQ={description:j(`First position of string found in text, case-sensitive.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=Xa(e,this.locale),i=Xa(t,this.locale),a=I(n,this.locale);if(i===``)return new N(j(`The text_to_search must be non-empty.`));if(a<1)return new N(j(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new N(j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},PQ={description:j(`Apply a large number format`),args:[k(`value (number)`,j(`The number.`)),k(`unit (string, optional)`,j(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:j(`Thousand`)},{value:`m`,label:j(`Million`)},{value:`b`,label:j(`Billion`)}])],compute:function(e,t){return{value:I(e,this.locale),format:Ql(e,t,this.locale)}}},FQ={description:j(`Concatenates elements of arrays with delimiter.`),args:[k(`delimiter (string)`,j(`The character or string to place between each concatenated value.`)),k(`value_or_array (string, range<string>, repeating)`,j(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=Xa(e,this.locale);return ao(t,(e,t)=>(e?e+n:``)+Xa(t,this.locale),``)}},IQ={description:j(`Substring from beginning of specified string.`),args:[k(`text (string)`,j(`The string from which the left portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;return n<0?new N(j(`The number_of_characters (%s) must be positive or null.`,n)):Xa(e,this.locale).substring(0,n)},isExported:!0},LQ={description:j(`Length of a string.`),args:[k(`text (string)`,j(`The string whose length will be returned.`))],compute:function(e){return Xa(e,this.locale).length},isExported:!0},RQ={description:j(`Converts a specified string to lowercase.`),args:[k(`text (string)`,j(`The string to convert to lowercase.`))],compute:function(e){return Xa(e,this.locale).toLowerCase()},isExported:!0},zQ={description:j(`A segment of a string.`),args:[k(`text (string)`,j(`The string to extract a segment from.`)),k(`starting_at (number)`,j(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),k(`extract_length (number)`,j(`The length of the segment to extract.`))],compute:function(e,t,n){let r=Xa(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return i<1?new N(j(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new N(j(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},BQ={description:j(`Capitalizes each word in a specified string.`),args:[k(`text_to_capitalize (string)`,j(`The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.`))],compute:function(e){return Xa(e,this.locale).replace(EQ,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},VQ={description:j(`Checks whether a string matches the supplied regular expression.`),args:[k(`text (string)`,j(`The string to test.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0}){let r=L(e),i=L(t),a=I(n,this.locale);if(i===``)return!0;if(r===``)return!1;if(a!==0&&a!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,a));let o=a===1?`gi`:`g`,s;try{s=new RegExp(i,o)}catch{return new N(j(`Invalid regular expression`))}return s.test(r)},isExported:!0},HQ={description:j(`Extract text from a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string on which you want to extract text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`return_mode (number, default=0)`,j(`0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array.`),[{value:0,label:j(`First match`)},{value:1,label:j(`All matches`)},{value:2,label:j(`Capture groups of first match`)}]),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0},r={value:0}){let i=L(e),a=L(t),o=I(n,this.locale),s=I(r,this.locale);if(i===``||a===``)return{value:``};if(o<0||o>2)return new N(j(`The return_mode (%s) must be 0, 1 or 2.`,o));if(s!==0&&s!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,s));let c=s===1?`gi`:`g`,l;try{l=new RegExp(a,c)}catch{return new N(j(`Invalid regular expression`))}let u=[...i.matchAll(l)];return u.length===0?{value:M.NotAvailable,message:j(`No matches found.`)}:o===0?u[0][0]:o===1?u.map(e=>[e[0]]):u[0].length<2?new N(j(`No capturing groups found.`)):u[0].slice(1).map(e=>[e])},isExported:!0},UQ={description:j(`Replace text in a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string in which you want to replace text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`replacement (string)`,j(`The text to use as the replacement.`)),k(`occurrence (number, default=0)`,j(`0 = replace all matches. A negative number counts from the end.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n,r={value:0},i={value:0}){let a=L(e),o=L(t),s=L(n),c=I(r,this.locale),l=I(i,this.locale);if(l!==0&&l!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,l));let u=l===1?`gi`:`g`,d;try{d=new RegExp(o,u)}catch{return new N(j(`Invalid regular expression`))}if(c!==0){let e=[...a.matchAll(d)];if(e.length===0||Math.abs(c)>e.length)return a;let t=c>0?c-1:e.length+c,n=e[t][0].length,r=e[t].index;return a.substring(0,r)+s+a.substring(r+n)}return a.replace(d,s)},isExported:!0},WQ={description:j(`Replaces part of a text string with different text.`),args:[k(`text (string)`,j(`The text, a part of which will be replaced.`)),k(`position (number)`,j(`The position where the replacement will begin (starting from 1).`)),k(`length (number)`,j(`The number of characters in the text to be replaced.`)),k(`new_text (string)`,j(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=I(t,this.locale);if(i<1)return new N(j(`The position (%s) must be greater than or equal to 1.`,i));let a=Xa(e,this.locale),o=I(n,this.locale),s=Xa(r,this.locale);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},GQ={description:j(`A substring from the end of a specified string.`),args:[k(`text (string)`,j(`The string from which the right portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;if(n<0)return new N(j(`The number_of_characters (%s) must be positive or null.`,n));let r=Xa(e,this.locale),i=r.length;return r.substring(i-n,i)},isExported:!0},KQ={description:j(`First position of string found in text, ignoring case.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=Xa(e,this.locale).toLowerCase(),i=Xa(t,this.locale).toLowerCase(),a=I(n,this.locale);if(i===``)return{value:M.GenericError,message:j(`The text_to_search must be non-empty.`)};if(a<1)return{value:M.GenericError,message:j(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:M.GenericError,message:j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},qQ={description:j(`Split text by specific character delimiter(s).`),args:[k(`text (string)`,j(`The text to divide.`)),k(`delimiter (string)`,j(`The character or characters to use to split text.`)),k(`split_by_each (boolean, default=true})`,j(`Whether or not to divide text around each character contained in delimiter.`)),k(`remove_empty_text (boolean, default=true)`,j(`Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters.`))],compute:function(e,t,n={value:!0},r={value:!0}){let i=Xa(e,this.locale),a=Ze(Xa(t,this.locale)),o=R(n),s=R(r);if(a.length<=0)return new N(j(`The delimiter (%s) must be not be empty.`,a));let c=o?RegExp(`[${a}]`,`g`):new RegExp(a,`g`),l=i.split(c);return s&&(l=l.filter(e=>e!==``)),fo([l])},isExported:!1},JQ={description:j(`Replaces existing text with new text in a string.`),args:[k(`text_to_search (string)`,j(`The text within which to search and replace.`)),k(`search_for (string)`,j(`The string to search for within text_to_search.`)),k(`replace_with (string)`,j(`The string that will replace search_for.`)),k(`occurrence_number (number, optional)`,j(`The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.`))],compute:function(e,t,n,r){let i=I(r,this.locale);if(i<0)return new N(j(`The occurrenceNumber (%s) must be positive or null.`,i));let a=Xa(e,this.locale),o=Xa(t,this.locale);if(o===``)return a;let s=Xa(n,this.locale),c=new RegExp(Ze(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},YQ={description:j(`Combines text from multiple strings and/or arrays.`),args:[k(`delimiter (string)`,j(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),k(`ignore_empty (boolean)`,j(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`),[{value:!0,label:j(`Ignore empty cells`)},{value:!1,label:j(`Include empty cells (default)`)}]),k(`texts (string, range<string>, repeating)`,j(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=Xa(e,this.locale),i=R(t),a=0;return ao(n,(e,t)=>i&&Xa(t,this.locale)===``?e:(a++?e+r:``)+Xa(t,this.locale),``)},isExported:!0},XQ={description:j(`Splits text into rows or columns using specified column and row delimiters.`),args:[k(`text (string)`,j(`The text to split.`)),k(`col_delimiter (string, range<string>)`,j(`Character or string to split columns by.`)),k(`row_delimiter (string, range<string>, optional)`,j(`Character or string to split rows by.`)),k(`ignore_empty (boolean, default=false)`,j(`Whether to ignore empty cells.`),[{value:!1,label:j(`Include empty cells (default)`)},{value:!0,label:j(`Ignore empty cells`)}]),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`pad_with (string, default="${M.NotAvailable}")`,j(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Ri){let o=L(e);if(o.length<=0)return new N(j(`No text to split.`));if(t===void 0&&n===void 0)return new N(j(`At least one delimiter must be provided.`));let s=B(t).flat().map(e=>Ze(L(e))),c=B(n).flat().map(e=>Ze(L(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new N(j(`The delimiters cannot be empty values.`));let l=R(r),u=I(i,this.locale);if(![0,1].includes(u))return new N(j(`match_mode should be a value of 0 or 1.`));let d=[],f=u===1?`gi`:`g`,p=c.filter(e=>!s.includes(e)),m=p.length?o.split(new RegExp(p.join(`|`),f)):[o];l&&(m=m.filter(e=>e!==``));let h=new RegExp(s.join(`|`),f);for(let e of m){let t=s.length?e.split(h):[e];l&&(t=t.filter(e=>e!==``)),d.push(t.map(e=>({value:e})))}let g=Math.max(...d.map(e=>e.length));for(let e of d)for(;e.length<g;)e.push(a);return fo(d)},isExported:!0},ZQ={description:j(`Removes space characters.`),args:[k(`text (string)`,j(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return Rt(Xa(e,this.locale))},isExported:!0},QQ={description:j(`Converts a specified string to uppercase.`),args:[k(`text (string)`,j(`The string to convert to uppercase.`))],compute:function(e){return Xa(e,this.locale).toUpperCase()},isExported:!0},$Q={description:j(`Converts a number to text according to a specified format.`),args:[k(`number (number)`,j(`The number, date or time to format.`)),k(`format (string)`,j(`The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.`))],compute:function(e,t){return H(I(e,this.locale),{format:L(t),locale:this.locale})},isExported:!0},e$={description:j(`Converts a string to a numeric value.`),args:[k(`value (number)`,j(`the string to be converted`))],compute:function(e){return I(e,this.locale)},isExported:!0},t$={description:j(`Returns text that occurs after a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter after which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`match_end (number, default=0))`,j(`Whether to treat the end of text as a delimiter.`),OQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:``}:{value:o};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(h)}},isExported:!0},n$={description:j(`Returns text that occurs before a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter before which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),DQ),k(`match_end (number, default=0))`,j(`Whether to match a delimiter against the end of the text.`),OQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:o}:{value:``};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(0,h-u.length)}},isExported:!0};var r$=l({HYPERLINK:()=>i$});let i$={description:j(`Creates a hyperlink in a cell.`),args:[k(`url (string)`,j(`The full URL of the link enclosed in quotation marks.`)),k(`link_label (string, optional)`,j(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=L(e).trim(),r=Xa(t,this.locale)||n;return n===``?r:ut(r,n)},isExported:!0},a$=[{name:j(`Array`),functions:xW},{name:j(`Database`),functions:Eq},{name:j(`Date`),functions:HJ},{name:j(`Filter`),functions:EY},{name:j(`Financial`),functions:MY},{name:j(`Info`),functions:VX},{name:j(`Lookup`),functions:gZ},{name:j(`Logical`),functions:eZ},{name:j(`Math`),functions:ZW},{name:j(`Operator`),functions:BZ},{name:j(`Statistical`),functions:pK},{name:j(`Text`),functions:TQ},{name:j(`Engineering`),functions:wY},{name:j(`Web`),functions:r$},{name:j(`Parser`),functions:CQ}];for(let e of a$){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),Io.add(n,{isExported:!1,...r})}}let o$={},s$={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},c$={autoCompleteProviders:uT,autofillModifiersRegistry:QL,autofillRulesRegistry:$L,cellMenuRegistry:NP,colMenuRegistry:KP,errorTypes:Pi,functionRegistry:Io,featurePluginRegistry:Wz,iconsOnCellRegistry:DL,statefulUIPluginRegistry:Gz,coreViewsPluginRegistry:Kz,corePluginRegistry:Uz,rowMenuRegistry:$P,sidePanelRegistry:tN,figureRegistry:Py,chartSidePanelComponentRegistry:sk,chartDataSourceSidePanelComponentRegistry:QD,chartComponentRegistry:dy,chartTypeRegistry:dS,chartSubtypeRegistry:Kv,chartDataSourceRegistry:uS,topbarMenuRegistry:PB,topbarComponentRegistry:eV,clickableCellRegistry:$z,otRegistry:SR,inverseCommandRegistry:nB,urlRegistry:Mu,cellPopoverRegistry:xw,numberFormatMenuRegistry:bB,repeatLocalCommandTransformRegistry:mz,repeatCommandTransformRegistry:pz,clipboardHandlersRegistries:UF,pivotRegistry:qj,pivotTimeAdapterRegistry:rg,pivotSidePanelRegistry:cM,pivotNormalizationValueRegistry:Fg,supportedPivotPositionalFormulaRegistry:xI,pivotToFunctionValueRegistry:Ig,migrationStepRegistry:qC,chartJsExtensionRegistry:Vd,NonSquishableFunctionRegistry:Lo},l$={arg:k,isEvaluationError:F,toBoolean:R,toJsDate:z,toNumber:I,toString:L,toNormalizedPivotValue:jg,toFunctionPivotValue:Ng,toXC:E,toZone:yn,toUnboundedZone:vn,toCartesian:sn,numberToLetters:Zt,lettersToNumber:Qt,UuidGenerator:Bd,formatValue:H,createCurrencyFormat:Gl,ColorGenerator:ui,computeTextWidth:Sd,createEmptyWorkbookData:pw,createEmptySheet:fw,createEmptyExcelSheet:mw,rgbaToHex:Br,colorToRGBA:Vr,positionToZone:D,isDefined:w,isMatrix:Je,lazy:xt,genericRepeat:$B,createAction:h,createActions:p,transformRangeData:cr,deepEquals:T,overlap:Nn,union:kn,isInside:Fn,deepCopy:x,expandZoneOnInsertion:Tn,reduceZoneOnDeletion:On,unquote:et,getMaxObjectId:Cg,getFirstPivotFunction:Qj,getNumberOfPivotFunctions:eM,parseDimension:Eg,isDateOrDatetimeField:Dg,makeFieldProposal:tM,periodYearToComparable:ng,insertTokenAfterArgSeparator:rM,insertTokenAfterLeftParenthesis:iM,mergeContiguousZones:ar,getPivotHighlights:ej,pivotTimeAdapter:ig,UNDO_REDO_PIVOT_COMMANDS:WL,createPivotFormula:Ag,areDomainArgsFieldsValid:kg,splitReference:Zo,sanitizeSheetName:nt,getUniqueText:Kt,isNumber:Pa,isDateTime:na,createCustomFields:Hg,schemeToColorScale:Wh,isDateTimeFormat:Rl,jsDateToNumber:ga,numberToJsDate:ma,DateTime:P,parseFormat:cl,isFormula:qt,domainToColRowDomain:vj,collapseHierarchicalDisplayName:Jg,PositionMap:aN},u$={isMarkdownLink:ct,parseMarkdownLink:dt,markdownLink:ut,openLink:Lu,urlRepresentation:Iu},d$={Checkbox:BT,Section:Z,Select:ky,RoundColorPicker:ET,ChartDataSeries:eO,ChartErrorSection:iO,ChartLabelRange:tO,ChartRangeDataSourceComponent:SO,ChartTitle:uO,ChartPanel:dk,ChartFigure:My,ChartJsComponent:qp,ClickableCellSortIcon:SI,ZoomableChartJsComponent:ry,Grid:bI,GridOverlay:YF,ScorecardChart:Hm,GaugeChartComponent:ly,LineConfigPanel:KO,BarConfigPanel:oO,PieChartDesignPanel:YO,GenericChartConfigPanel:aO,ChartWithAxisDesignPanel:yO,GenericZoomableChartDesignPanel:bO,LineChartDesignPanel:qO,GaugeChartConfigPanel:BO,GaugeChartDesignPanel:VO,ScorecardChartConfigPanel:QO,ScorecardChartDesignPanel:$O,GeoChartDesignPanel:WO,RadarChartDesignPanel:XO,WaterfallChartDesignPanel:ok,ComboChartDesignPanel:LO,FunnelChartDesignPanel:zO,SunburstChartDesignPanel:ek,TreeMapChartDesignPanel:ak,ChartTypePicker:lk,FigureComponent:Fy,MenuPopover:Oy,Popover:wy,SelectionInput:FT,ValidationMessages:rO,AddDimensionButton:aj,PivotDimensionGranularity:sj,PivotDimensionOrder:cj,PivotDimension:oj,PivotLayoutConfigurator:fj,PivotHTMLRenderer:wI,PivotDeferUpdate:nj,PivotTitleSection:pj,CogWheelMenu:XD,TextInput:WD,SidePanelCollapsible:Ow,RadioSelection:fO,GeoChartRegionSelectSection:HO,ChartDashboardMenu:Ay,FullScreenFigure:CI,NumberInput:sO,TopBar:KV,Composer:Qw},f$={useDragAndDropListItems:OT,useHighlights:hk,useHighlightsOnHover:mk},p$={useStoreProvider:mr,DependencyContainer:ur,CellPopoverStore:Sw,ComposerFocusStore:Er,CellComposerStore:kF,FindAndReplaceStore:Fk,HighlightStore:fT,DelayedHoveredCellStore:Iy,HoveredTableStore:KF,ModelStore:yr,NotificationStore:pT,RendererStore:Cr,SelectionInputStore:PT,SpreadsheetStore:wr,useStore:O,useLocalStore:hr,SidePanelStore:rN,PivotSidePanelStore:oM,PivotMeasureDisplayPanelStore:QA,ClientFocusStore:tF,GridRenderer:rI};function m$(e,t){return Io.add(e,t),{addFunction:(e,t)=>m$(e,t)}}let h$={DEFAULT_LOCALE:V,HIGHLIGHT_COLOR:ee,PIVOT_STATIC_TABLE_CONFIG:Be,PIVOT_INSERT_TABLE_STYLE_ID:Ve,ChartTerms:Ry,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:Uh},g$={...Fv,...bv};e.AbstractCellClipboardHandler=JL,e.AbstractChart=Jp,e.AbstractFigureClipboardHandler=dW,e.CellErrorType=M,e.ClientDisconnectedError=iz,e.CommandResult=Au,e.CompiledFormula=Bc,e.CorePlugin=EI,e.CoreViewPlugin=eL,e.DEFAULT_LOCALE=V,e.DEFAULT_LOCALES=Ro,e.DispatchResult=Ou,e.EvaluationError=N,e.LocalTransportService=tV,e.Model=QU,e.PivotRuntimeDefinition=mj,e.Registry=A,e.Revision=rz,e.SPREADSHEET_DIMENSIONS=s$,e.Spreadsheet=YV,e.SpreadsheetPivotTable=Fj,e.UIPlugin=XL,e.__info__=o$,e.addFunction=m$,e.addRenderingLayer=Sr,e.astToFormula=TF,e.canExecuteInReadonly=Du,e.categories=a$,e.chartHelpers=g$,e.components=d$,e.constants=h$,e.convertAstNodes=Ks,e.coreTypes=Tu,e.createAutocompleteArgumentsProvider=qz,e.findCellInNewZone=Kn,e.functionCache=Rc,e.getCaretDownSvg=Tb,e.getCaretUpSvg=Eb,e.helpers=l$,e.hooks=f$,e.invalidateCFEvaluationCommands=bu,e.invalidateChartEvaluationCommands=vu,e.invalidateDependenciesCommands=yu,e.invalidateEvaluationCommands=_u,e.isCoreCommand=Eu,e.isSheetDependent=du,e.iterateAstNodes=qs,e.links=u$,e.load=QC,e.lockedSheetAllowedCommands=wu,e.parse=Ws,e.parseTokens=Gs,e.readonlyAllowedCommands=Cu,e.registries=c$,e.setDefaultSheetViewSize=Re,e.setTranslationMethod=ji,e.stores=p$,e.tokenColors=Ke,e.tokenize=ls,o$.version=`19.3.18`,o$.date=`2026-08-29T09:16:28.272Z`,o$.hash=`1f4b1ae`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|