@odoo/o-spreadsheet 16.3.0-alpha.8 → 16.3.1

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.
@@ -50,7 +50,7 @@
50
50
  }
51
51
  }
52
52
  }
53
- `;class Oi extends t.Component{static template="o-spreadsheet-ScorecardChart";ctx=document.createElement("canvas").getContext("2d");get runtime(){return this.env.model.getters.getChartRuntime(this.props.figure.id)}get title(){return this.runtime.title}get keyValue(){return this.runtime.keyValue}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){const e=this.runtime.baselineDescr||"";return this.baseline&&e?" "+e:e}get baselineArrowDirection(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get primaryFontColor(){return this.runtime.fontColor}get secondaryFontColor(){return Nt(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return Ti({padding:`${this.chartPadding}px`,background:this.backgroundColor})}get chartContentStyle(){return Ti({height:`${this.getDrawableHeight()}px`})}get chartPadding(){return.02*this.props.figure.width}getTextStyles(){const e=.96*this.props.figure.width,t=this.getWidestElement(),o=t.getElementMaxFontSize(this.getDrawableHeight(),this);let i=function(e,t,o,i=.25){let s=1;if(o(s)>e)return s;if(o(t)<e)return t;let r=(s+t)/2,n=o(r),a=0;for(;Math.abs(n-e)>i&&a<20;)n>=e?t=(s+t)/2:s=(s+t)/2,r=(s+t)/2,n=o(r),a++;return r}(e,o,(e=>t.getElementWidth(e,this.ctx,this)))/o;const s=(new Ni).getElementMaxFontSize(this.getDrawableHeight(),this)*i,r=(new Mi).getElementMaxFontSize(this.getDrawableHeight(),this)*i;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:s,cellStyle:this.runtime.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:r}),baselineValueStyle:this.getTextStyle({fontSize:r,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*r,color:this.secondaryFontColor})}}getTextStyle(e){const t=Ri(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),Ti(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*Ai:0,t}getWidestElement(){const e=new Mi,t=new Ni;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}class Mi{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.baseline,s="neutral"!==o.baselineArrowDirection?"A "+i:i;t.font=`${e}px ${Z}`;let r=t.measureText(s).width;return t.font=`${.9*e}px ${Z}`,r+=t.measureText(o.baselineDescr).width,r}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/Ai}}class Ni{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.keyValue||"";return t.font=`${e}px ${Z}`,t.measureText(i).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/Ai}}Oi.props={figure:Object};class _i{content={};add(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}}function Fi(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const Di=new _i;function Li(e,t){return{url:e=Fi(e),label:t||e,isExternal:!0,isUrlEditable:!0}}Di.add("sheet_URL",{match:e=>rt(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const o=at(e);return t.tryGetSheetName(o)||r("Invalid sheet")},open(e,t){const o=at(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:o})},sequence:0});const Pi={createLink:Li,match:e=>tt(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function ki(e){return Di.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||Pi}function Ui(e,t){return ki(e.url).urlRepresentation(e.url,t)}function Vi(e,t){ki(e.url).open(e.url,t)}function zi(e){if("string"==typeof e){if(et(e)){const{label:t,url:o}=it(e);return ki(o).createLink(o,t)}return tt(e)?Li(e):void 0}}const Bi=["number","string","boolean","undefined"];function Hi(e,t){if(!e())throw new Error(t)}const $i=e=>r("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Wi(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(Jt(e)||""===e)return to(e);const t=ye(e);if(t)return t.value;throw new Error($i(e));default:return 0}}function Gi(e){if(""===e)throw new Error($i(e));return Wi(e)}function qi(e){return Math.trunc(Gi(e))}function Zi(e){Hi((()=>e>=1),r("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e.toString()))}function ji(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}function Yi(e){return"string"==typeof e?e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):e}const Xi=e=>r("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function Ki(e){switch(typeof e){case"boolean":return e;case"string":if(e){let t=e.toUpperCase();if("TRUE"===t)return!0;if("FALSE"===t)return!1;throw new Error(Xi(e))}return!1;case"number":return!!e;default:return!1}}function Qi(e){return Re(Wi(e))}function Ji(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let s=0;s<o;s++)for(let o=0;o<e;o++)t(i[o][s])}else o(i)}function es(e,t){Ji(e,t,t)}function ts(e,t){Ji(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Gi(e))}))}function os(e,t,o,i){let s=i;for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let r=0;r<o;r++)for(let o=0;o<e;o++)s=t(s,i[o][r])}else s=o(s,i);return s}function is(e,t,o){return os(e,t,t,o)}function ss(e,t,o){return os(e,((e,o)=>"number"==typeof o?t(e,o):e),((e,o)=>t(e,Gi(o))),o)}function rs(e,t,o){return os(e,((e,o)=>null!=o?t(e,"number"==typeof o?o:"boolean"==typeof o?Wi(o):0):e),((e,o)=>t(e,Wi(o))),o)}function ns(e,t){return function(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let s=0;s<o;s++)for(let o=0;o<e;o++)if(!t(i[o][s]))return}else if(!o(i))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(Xi(e));return Ki(e)}(e))))}function as(e,t){let o,i,s=e.substring(0,2);"<="===s||">="===s||"<>"===s?(o=s,i=e.substring(2)):(s=e.substring(0,1),"<"===s||">"===s||"="===s?(o=s,i=e.substring(1)):(o="=",i=e)),Jt(i)?i=Wi(i):"TRUE"!==i&&"FALSE"!==i||(i=Ki(i));const r={operator:o,operand:i};return"string"==typeof i&&(t&&(i+="*"),r.regexp=function(e){let t="",o="";for(let i of e)"?"===i&&"~"!==o?t+=".":"*"===i&&"~"!==o?t+=".*":("*"!==i&&"?"!==i||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(i)&&(t+="\\"),t+=i),o=i;return new RegExp("^"+t+"$","i")}(i)),r}function ls(e,t){const{operator:o,operand:i}=t;if(void 0===e||void 0===i)return!1;if("number"==typeof i&&"="===o)return ji(e)===ji(i);if("<>"===o||"="===o){let s;return s=typeof e==typeof i&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===i),"="===o?s:!s}if(typeof e==typeof i)switch(o){case"<":return e<i;case">":return e>i;case"<=":return e<=i;case">=":return e>=i}return!1}function cs(e,t,o=!1){const i=e.length;if(i%2==1)throw new Error(r("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const s=e[0].length,n=e[0][0].length;let a=[];for(let t=0;t<i-1;t+=2){const i=e[t];if(!Array.isArray(i)||i.length!==s||i[0].length!==n)throw new Error(r("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=ji(e[t+1]);a.push(as(l,o))}for(let o=0;o<s;o++)for(let s=0;s<n;s++){let r=!0;for(let t=0;t<i-1;t+=2){if(r=ls(e[t][o][s],a[t/2]),!r)break}r&&t(o,s)}}function hs(e,t){return Yi(e[0][t])}function ds(e,t){return Yi(e[t][0])}function us(e,t,o,i,s,r){if(null==t)return-1;const n=typeof t;let a,l,c,h,d,u,g=0,p=s-1;for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=r(e,h),u=typeof d;g<h&&n!==u;)h--,d=r(e,h),u=typeof d;u===n&&void 0!==d?("strict"===o&&d===t?(a=d,l=h):"nextSmaller"===o&&d<=t?(void 0===a||a<d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h):"nextGreater"===o&&d>=t&&(void 0===a||a>d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h),"asc"===i&&d>t||"desc"===i&&d<=t?p=h-1:g=c+1):g=c+1}return void 0!==l?l:-1}function gs(e,t,o,i,s,r=!1){if(null==t)return-1;const n=r?(e,t)=>s(e,i-t-1):s;let a,l=-1;for(let s=0;s<i;s++){const c=n(e,s);if(c===t)return r?i-s-1:s;"nextSmaller"===o?(!a&&ps(t,c)>=0||ps(t,c)>=0&&ps(c,a)>0)&&(a=c,l=s):"nextGreater"===o&&(!a&&ps(t,c)<=0||ps(t,c)<=0&&ps(c,a)<0)&&(a=c,l=s)}return r?i-l-1:l}function ps(e,t){let o=Bi.indexOf(typeof e)-Bi.indexOf(typeof t);return 0===o&&("string"==typeof e&&"string"==typeof t?o=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?o=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(o=Number(e)-Number(t))),o}var ms,fs;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(ms||(ms={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(fs||(fs={}));const bs=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),vs=new Set([...bs,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),Ss=new Set(["START","ACTIVATE_SHEET","COPY","PREPARE_SELECTION_INPUT_EXPANSION","STOP_SELECTION_INPUT","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","SELECT_SEARCH_NEXT_MATCH","SELECT_SEARCH_PREVIOUS_MATCH","REFRESH_SEARCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY","OPEN_CELL_POPOVER","CLOSE_CELL_POPOVER","UPDATE_FILTER"]),Cs=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","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","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","SET_ZONE_BORDERS","CREATE_CHART","UPDATE_CHART","CREATE_FILTER_TABLE","REMOVE_FILTER_TABLE","CREATE_IMAGE"]);function Es(e){return Cs.has(e.type)}class ws{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new ws}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var xs;e.CommandResult=void 0,(xs=e.CommandResult||(e.CommandResult={}))[xs.Success=0]="Success",xs[xs.CancelledForUnknownReason=1]="CancelledForUnknownReason",xs[xs.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",xs[xs.MergeIsDestructive=3]="MergeIsDestructive",xs[xs.CellIsMerged=4]="CellIsMerged",xs[xs.InvalidTarget=5]="InvalidTarget",xs[xs.EmptyUndoStack=6]="EmptyUndoStack",xs[xs.EmptyRedoStack=7]="EmptyRedoStack",xs[xs.NotEnoughElements=8]="NotEnoughElements",xs[xs.NotEnoughSheets=9]="NotEnoughSheets",xs[xs.MissingSheetName=10]="MissingSheetName",xs[xs.DuplicatedSheetName=11]="DuplicatedSheetName",xs[xs.DuplicatedSheetId=12]="DuplicatedSheetId",xs[xs.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",xs[xs.WrongSheetMove=14]="WrongSheetMove",xs[xs.WrongSheetPosition=15]="WrongSheetPosition",xs[xs.InvalidAnchorZone=16]="InvalidAnchorZone",xs[xs.SelectionOutOfBound=17]="SelectionOutOfBound",xs[xs.TargetOutOfSheet=18]="TargetOutOfSheet",xs[xs.WrongCutSelection=19]="WrongCutSelection",xs[xs.WrongPasteSelection=20]="WrongPasteSelection",xs[xs.WrongPasteOption=21]="WrongPasteOption",xs[xs.WrongFigurePasteOption=22]="WrongFigurePasteOption",xs[xs.EmptyClipboard=23]="EmptyClipboard",xs[xs.EmptyRange=24]="EmptyRange",xs[xs.InvalidRange=25]="InvalidRange",xs[xs.InvalidZones=26]="InvalidZones",xs[xs.InvalidSheetId=27]="InvalidSheetId",xs[xs.InvalidFigureId=28]="InvalidFigureId",xs[xs.InputAlreadyFocused=29]="InputAlreadyFocused",xs[xs.MaximumRangesReached=30]="MaximumRangesReached",xs[xs.InvalidChartDefinition=31]="InvalidChartDefinition",xs[xs.InvalidDataSet=32]="InvalidDataSet",xs[xs.InvalidLabelRange=33]="InvalidLabelRange",xs[xs.InvalidScorecardKeyValue=34]="InvalidScorecardKeyValue",xs[xs.InvalidScorecardBaseline=35]="InvalidScorecardBaseline",xs[xs.InvalidGaugeDataRange=36]="InvalidGaugeDataRange",xs[xs.EmptyGaugeRangeMin=37]="EmptyGaugeRangeMin",xs[xs.GaugeRangeMinNaN=38]="GaugeRangeMinNaN",xs[xs.EmptyGaugeRangeMax=39]="EmptyGaugeRangeMax",xs[xs.GaugeRangeMaxNaN=40]="GaugeRangeMaxNaN",xs[xs.GaugeRangeMinBiggerThanRangeMax=41]="GaugeRangeMinBiggerThanRangeMax",xs[xs.GaugeLowerInflectionPointNaN=42]="GaugeLowerInflectionPointNaN",xs[xs.GaugeUpperInflectionPointNaN=43]="GaugeUpperInflectionPointNaN",xs[xs.GaugeLowerBiggerThanUpper=44]="GaugeLowerBiggerThanUpper",xs[xs.InvalidAutofillSelection=45]="InvalidAutofillSelection",xs[xs.WrongComposerSelection=46]="WrongComposerSelection",xs[xs.MinBiggerThanMax=47]="MinBiggerThanMax",xs[xs.LowerBiggerThanUpper=48]="LowerBiggerThanUpper",xs[xs.MidBiggerThanMax=49]="MidBiggerThanMax",xs[xs.MinBiggerThanMid=50]="MinBiggerThanMid",xs[xs.FirstArgMissing=51]="FirstArgMissing",xs[xs.SecondArgMissing=52]="SecondArgMissing",xs[xs.MinNaN=53]="MinNaN",xs[xs.MidNaN=54]="MidNaN",xs[xs.MaxNaN=55]="MaxNaN",xs[xs.ValueUpperInflectionNaN=56]="ValueUpperInflectionNaN",xs[xs.ValueLowerInflectionNaN=57]="ValueLowerInflectionNaN",xs[xs.MinInvalidFormula=58]="MinInvalidFormula",xs[xs.MidInvalidFormula=59]="MidInvalidFormula",xs[xs.MaxInvalidFormula=60]="MaxInvalidFormula",xs[xs.ValueUpperInvalidFormula=61]="ValueUpperInvalidFormula",xs[xs.ValueLowerInvalidFormula=62]="ValueLowerInvalidFormula",xs[xs.InvalidSortZone=63]="InvalidSortZone",xs[xs.WaitingSessionConfirmation=64]="WaitingSessionConfirmation",xs[xs.MergeOverlap=65]="MergeOverlap",xs[xs.TooManyHiddenElements=66]="TooManyHiddenElements",xs[xs.Readonly=67]="Readonly",xs[xs.InvalidViewportSize=68]="InvalidViewportSize",xs[xs.InvalidScrollingDirection=69]="InvalidScrollingDirection",xs[xs.FigureDoesNotExist=70]="FigureDoesNotExist",xs[xs.InvalidConditionalFormatId=71]="InvalidConditionalFormatId",xs[xs.InvalidCellPopover=72]="InvalidCellPopover",xs[xs.EmptyTarget=73]="EmptyTarget",xs[xs.InvalidFreezeQuantity=74]="InvalidFreezeQuantity",xs[xs.FrozenPaneOverlap=75]="FrozenPaneOverlap",xs[xs.ValuesNotChanged=76]="ValuesNotChanged",xs[xs.InvalidFilterZone=77]="InvalidFilterZone",xs[xs.FilterOverlap=78]="FilterOverlap",xs[xs.FilterNotFound=79]="FilterNotFound",xs[xs.MergeInFilter=80]="MergeInFilter",xs[xs.NonContinuousTargets=81]="NonContinuousTargets",xs[xs.DuplicatedFigureId=82]="DuplicatedFigureId",xs[xs.InvalidSelectionStep=83]="InvalidSelectionStep",xs[xs.DuplicatedChartId=84]="DuplicatedChartId",xs[xs.ChartDoesNotExist=85]="ChartDoesNotExist",xs[xs.InvalidHeaderIndex=86]="InvalidHeaderIndex",xs[xs.InvalidQuantity=87]="InvalidQuantity",xs[xs.MoreThanOneColumnSelected=88]="MoreThanOneColumnSelected",xs[xs.EmptySplitSeparator=89]="EmptySplitSeparator",xs[xs.SplitWillOverwriteContent=90]="SplitWillOverwriteContent",xs[xs.NoSplitSeparatorInSelection=91]="NoSplitSeparatorInSelection";const ys=["thin","medium","thick","dashed","dotted"];var Is,Rs;function Ts(e,t){return Os(As(e||""),t)}function As(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return Jt(e)||Ke(e)?Wi(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function Os(e,t){const o=zi(e);return o?{...Ms(As(o.label),t||xo(o.label)),link:o}:Ms(e,t)}function Ms(e,t){try{for(const o of Ds){const i=o(e,t);if(i)return i}return function(e,t){return{type:ms.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:uo(e,t)}}((e||"").toString(),t)}catch(t){return Fs((e||"").toString(),new c(a.GenericError,t.message||he))}}function Ns(e,t){return{type:ms.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:uo(e,t)}}!function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(Is||(Is={})),function(e){e[e.Background=0]="Background",e[e.Highlights=1]="Highlights",e[e.Clipboard=2]="Clipboard",e[e.Search=3]="Search",e[e.Chart=4]="Chart",e[e.Autofill=5]="Autofill",e[e.Selection=6]="Selection",e[e.Headers=7]="Headers"}(Rs||(Rs={}));const _s={type:ms.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function Fs(e,t){return{type:ms.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const Ds=[function(e,t){if(""===e)return function(e){return void 0===e?_s:{type:ms.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&bo(t))return function(e,t){const o=uo(e,t);return{type:ms.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:o}}(e,t)},function(e,t){return"number"==typeof e?Ns(e,t):null===e?Ns(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const o=e?"TRUE":"FALSE";return{type:ms.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:o}}(e,t)}],Ls=new _i;Ls.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const o=`${e.prefix}${e.current.toString().padStart(e.numberPostfixLength||0,"0")}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:{props:{content:o}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const o=e.current.toString(),i=uo(e.current,t.cell?.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,o)=>{const i=t.cell?.content||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i},tooltip:i?{props:{content:Ts(t.cell?.content,t.cell?.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,o,i)=>{e.current+=e.increment;let s=0,r=0;switch(i){case"up":s=0,r=-e.current;break;case"down":s=0,r=e.current;break;case"left":s=-e.current,r=0;break;case"right":s=e.current,r=0}const n=t.cell;if(!n||!n.isFormula)return{cellData:{}};const a=t.sheetId,l=o.createAdaptedRanges(n.dependencies,s,r,a),c=o.buildFormulaContent(a,n,l);return{cellData:{border:t.border,style:n.style,format:n.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});const Ps=new _i,ks=/(\d+)$/,Us=/^(.*\D+)/,Vs=/^(.*\D+)(\d+)$/;function zs(e,t,o){let i=[],s=!1;for(let r of t){r===e&&(s=!0);const t=Ts(r?.content);if(o(t))i.push(t);else{if(s)return i;i=[]}}return i}function Bs(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let o=e[0];for(let i=1;i<e.length;i++){const s=e[i];t.push(s-o),o=s}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}Ps.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&bo(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Ts(e.content).type===ms.text&&Vs.test(e.content),generateRule:(e,t)=>{const o=parseInt(e.content.match(ks)[0]),i=e.content.match(Us)[0],s=e.content.length-i.length,r=zs(e,t,(e=>e.type===ms.text&&Vs.test(e.value))).filter((e=>i===e.value.toString().match(Us)[0])).map((e=>parseInt(e.value.toString().match(ks)[0]))),n=Bs(r);return{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:i,current:o,increment:n,numberPostfixLength:s}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Ts(e.content).type===ms.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_number",{condition:e=>!e.isFormula&&Ts(e.content).type===ms.number,generateRule:(e,t)=>{const o=Bs(zs(e,t,(e=>e.type===ms.number)).map((e=>Number(e.value)))),i=Ts(e.content);return{type:"INCREMENT_MODIFIER",increment:o,current:i.type===ms.number?i.value:0}},sequence:40});xi`
53
+ `;class Oi extends t.Component{static template="o-spreadsheet-ScorecardChart";ctx=document.createElement("canvas").getContext("2d");get runtime(){return this.env.model.getters.getChartRuntime(this.props.figure.id)}get title(){return this.runtime.title}get keyValue(){return this.runtime.keyValue}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){const e=this.runtime.baselineDescr||"";return this.baseline&&e?" "+e:e}get baselineArrowDirection(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get primaryFontColor(){return this.runtime.fontColor}get secondaryFontColor(){return Nt(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return Ti({padding:`${this.chartPadding}px`,background:this.backgroundColor})}get chartContentStyle(){return Ti({height:`${this.getDrawableHeight()}px`})}get chartPadding(){return.02*this.props.figure.width}getTextStyles(){const e=.96*this.props.figure.width,t=this.getWidestElement(),o=t.getElementMaxFontSize(this.getDrawableHeight(),this);let i=function(e,t,o,i=.25){let s=1;if(o(s)>e)return s;if(o(t)<e)return t;let r=(s+t)/2,n=o(r),a=0;for(;Math.abs(n-e)>i&&a<20;)n>=e?t=(s+t)/2:s=(s+t)/2,r=(s+t)/2,n=o(r),a++;return r}(e,o,(e=>t.getElementWidth(e,this.ctx,this)))/o;const s=(new Ni).getElementMaxFontSize(this.getDrawableHeight(),this)*i,r=(new Mi).getElementMaxFontSize(this.getDrawableHeight(),this)*i;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:s,cellStyle:this.runtime.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:r}),baselineValueStyle:this.getTextStyle({fontSize:r,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*r,color:this.secondaryFontColor})}}getTextStyle(e){const t=Ri(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),Ti(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*Ai:0,t}getWidestElement(){const e=new Mi,t=new Ni;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}class Mi{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.baseline,s="neutral"!==o.baselineArrowDirection?"A "+i:i;t.font=`${e}px ${Z}`;let r=t.measureText(s).width;return t.font=`${.9*e}px ${Z}`,r+=t.measureText(o.baselineDescr).width,r}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/Ai}}class Ni{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.keyValue||"";return t.font=`${e}px ${Z}`,t.measureText(i).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/Ai}}Oi.props={figure:Object};class _i{content={};add(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}}function Fi(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const Di=new _i;function Li(e,t){return{url:e=Fi(e),label:t||e,isExternal:!0,isUrlEditable:!0}}Di.add("sheet_URL",{match:e=>rt(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const o=at(e);return t.tryGetSheetName(o)||r("Invalid sheet")},open(e,t){const o=at(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:o})},sequence:0});const Pi={createLink:Li,match:e=>tt(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function ki(e){return Di.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||Pi}function Ui(e,t){return ki(e.url).urlRepresentation(e.url,t)}function Vi(e,t){ki(e.url).open(e.url,t)}function zi(e){if("string"==typeof e){if(et(e)){const{label:t,url:o}=it(e);return ki(o).createLink(o,t)}return tt(e)?Li(e):void 0}}const Bi=["number","string","boolean","undefined"];function Hi(e,t){if(!e())throw new Error(t)}const $i=e=>r("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Wi(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(Jt(e)||""===e)return to(e);const t=ye(e);if(t)return t.value;throw new Error($i(e));default:return 0}}function Gi(e){if(""===e)throw new Error($i(e));return Wi(e)}function qi(e){return Math.trunc(Gi(e))}function Zi(e){Hi((()=>e>=1),r("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e.toString()))}function ji(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}function Yi(e){return"string"==typeof e?e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):e}const Xi=e=>r("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function Ki(e){switch(typeof e){case"boolean":return e;case"string":if(e){let t=e.toUpperCase();if("TRUE"===t)return!0;if("FALSE"===t)return!1;throw new Error(Xi(e))}return!1;case"number":return!!e;default:return!1}}function Qi(e){return Re(Wi(e))}function Ji(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let s=0;s<o;s++)for(let o=0;o<e;o++)t(i[o][s])}else o(i)}function es(e,t){Ji(e,t,t)}function ts(e,t){Ji(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Gi(e))}))}function os(e,t,o,i){let s=i;for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let r=0;r<o;r++)for(let o=0;o<e;o++)s=t(s,i[o][r])}else s=o(s,i);return s}function is(e,t,o){return os(e,t,t,o)}function ss(e,t,o){return os(e,((e,o)=>"number"==typeof o?t(e,o):e),((e,o)=>t(e,Gi(o))),o)}function rs(e,t,o){return os(e,((e,o)=>null!=o?t(e,"number"==typeof o?o:"boolean"==typeof o?Wi(o):0):e),((e,o)=>t(e,Wi(o))),o)}function ns(e,t){return function(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let s=0;s<o;s++)for(let o=0;o<e;o++)if(!t(i[o][s]))return}else if(!o(i))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(Xi(e));return Ki(e)}(e))))}function as(e,t){let o,i,s=e.substring(0,2);"<="===s||">="===s||"<>"===s?(o=s,i=e.substring(2)):(s=e.substring(0,1),"<"===s||">"===s||"="===s?(o=s,i=e.substring(1)):(o="=",i=e)),Jt(i)?i=Wi(i):"TRUE"!==i&&"FALSE"!==i||(i=Ki(i));const r={operator:o,operand:i};return"string"==typeof i&&(t&&(i+="*"),r.regexp=function(e){let t="",o="";for(let i of e)"?"===i&&"~"!==o?t+=".":"*"===i&&"~"!==o?t+=".*":("*"!==i&&"?"!==i||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(i)&&(t+="\\"),t+=i),o=i;return new RegExp("^"+t+"$","i")}(i)),r}function ls(e,t){const{operator:o,operand:i}=t;if(void 0===e||void 0===i)return!1;if("number"==typeof i&&"="===o)return ji(e)===ji(i);if("<>"===o||"="===o){let s;return s=typeof e==typeof i&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===i),"="===o?s:!s}if(typeof e==typeof i)switch(o){case"<":return e<i;case">":return e>i;case"<=":return e<=i;case">=":return e>=i}return!1}function cs(e,t,o=!1){const i=e.length;if(i%2==1)throw new Error(r("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const s=e[0].length,n=e[0][0].length;let a=[];for(let t=0;t<i-1;t+=2){const i=e[t];if(!Array.isArray(i)||i.length!==s||i[0].length!==n)throw new Error(r("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=ji(e[t+1]);a.push(as(l,o))}for(let o=0;o<s;o++)for(let s=0;s<n;s++){let r=!0;for(let t=0;t<i-1;t+=2){if(r=ls(e[t][o][s],a[t/2]),!r)break}r&&t(o,s)}}function hs(e,t){return Yi(e[0][t])}function ds(e,t){return Yi(e[t][0])}function us(e,t,o,i,s,r){if(null==t)return-1;const n=typeof t;let a,l,c,h,d,u,g=0,p=s-1;for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=r(e,h),u=typeof d;g<h&&n!==u;)h--,d=r(e,h),u=typeof d;u===n&&void 0!==d?("strict"===o&&d===t?(a=d,l=h):"nextSmaller"===o&&d<=t?(void 0===a||a<d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h):"nextGreater"===o&&d>=t&&(void 0===a||a>d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h),"asc"===i&&d>t||"desc"===i&&d<=t?p=h-1:g=c+1):g=c+1}return void 0!==l?l:-1}function gs(e,t,o,i,s,r=!1){if(null==t)return-1;const n=r?(e,t)=>s(e,i-t-1):s;let a,l=-1;for(let s=0;s<i;s++){const c=n(e,s);if(c===t)return r?i-s-1:s;"nextSmaller"===o?(!a&&ps(t,c)>=0||ps(t,c)>=0&&ps(c,a)>0)&&(a=c,l=s):"nextGreater"===o&&(!a&&ps(t,c)<=0||ps(t,c)<=0&&ps(c,a)<0)&&(a=c,l=s)}return r?i-l-1:l}function ps(e,t){let o=Bi.indexOf(typeof e)-Bi.indexOf(typeof t);return 0===o&&("string"==typeof e&&"string"==typeof t?o=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?o=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(o=Number(e)-Number(t))),o}var ms,fs;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(ms||(ms={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(fs||(fs={}));const bs=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),vs=new Set([...bs,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),Ss=new Set(["START","ACTIVATE_SHEET","COPY","PREPARE_SELECTION_INPUT_EXPANSION","STOP_SELECTION_INPUT","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","SELECT_SEARCH_NEXT_MATCH","SELECT_SEARCH_PREVIOUS_MATCH","REFRESH_SEARCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY","OPEN_CELL_POPOVER","CLOSE_CELL_POPOVER","UPDATE_FILTER"]),Cs=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","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","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","SET_ZONE_BORDERS","CREATE_CHART","UPDATE_CHART","CREATE_FILTER_TABLE","REMOVE_FILTER_TABLE","CREATE_IMAGE"]);function Es(e){return Cs.has(e.type)}class ws{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new ws}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var xs;e.CommandResult=void 0,(xs=e.CommandResult||(e.CommandResult={}))[xs.Success=0]="Success",xs[xs.CancelledForUnknownReason=1]="CancelledForUnknownReason",xs[xs.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",xs[xs.MergeIsDestructive=3]="MergeIsDestructive",xs[xs.CellIsMerged=4]="CellIsMerged",xs[xs.InvalidTarget=5]="InvalidTarget",xs[xs.EmptyUndoStack=6]="EmptyUndoStack",xs[xs.EmptyRedoStack=7]="EmptyRedoStack",xs[xs.NotEnoughElements=8]="NotEnoughElements",xs[xs.NotEnoughSheets=9]="NotEnoughSheets",xs[xs.MissingSheetName=10]="MissingSheetName",xs[xs.DuplicatedSheetName=11]="DuplicatedSheetName",xs[xs.DuplicatedSheetId=12]="DuplicatedSheetId",xs[xs.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",xs[xs.WrongSheetMove=14]="WrongSheetMove",xs[xs.WrongSheetPosition=15]="WrongSheetPosition",xs[xs.InvalidAnchorZone=16]="InvalidAnchorZone",xs[xs.SelectionOutOfBound=17]="SelectionOutOfBound",xs[xs.TargetOutOfSheet=18]="TargetOutOfSheet",xs[xs.WrongCutSelection=19]="WrongCutSelection",xs[xs.WrongPasteSelection=20]="WrongPasteSelection",xs[xs.WrongPasteOption=21]="WrongPasteOption",xs[xs.WrongFigurePasteOption=22]="WrongFigurePasteOption",xs[xs.EmptyClipboard=23]="EmptyClipboard",xs[xs.EmptyRange=24]="EmptyRange",xs[xs.InvalidRange=25]="InvalidRange",xs[xs.InvalidZones=26]="InvalidZones",xs[xs.InvalidSheetId=27]="InvalidSheetId",xs[xs.InvalidFigureId=28]="InvalidFigureId",xs[xs.InputAlreadyFocused=29]="InputAlreadyFocused",xs[xs.MaximumRangesReached=30]="MaximumRangesReached",xs[xs.InvalidChartDefinition=31]="InvalidChartDefinition",xs[xs.InvalidDataSet=32]="InvalidDataSet",xs[xs.InvalidLabelRange=33]="InvalidLabelRange",xs[xs.InvalidScorecardKeyValue=34]="InvalidScorecardKeyValue",xs[xs.InvalidScorecardBaseline=35]="InvalidScorecardBaseline",xs[xs.InvalidGaugeDataRange=36]="InvalidGaugeDataRange",xs[xs.EmptyGaugeRangeMin=37]="EmptyGaugeRangeMin",xs[xs.GaugeRangeMinNaN=38]="GaugeRangeMinNaN",xs[xs.EmptyGaugeRangeMax=39]="EmptyGaugeRangeMax",xs[xs.GaugeRangeMaxNaN=40]="GaugeRangeMaxNaN",xs[xs.GaugeRangeMinBiggerThanRangeMax=41]="GaugeRangeMinBiggerThanRangeMax",xs[xs.GaugeLowerInflectionPointNaN=42]="GaugeLowerInflectionPointNaN",xs[xs.GaugeUpperInflectionPointNaN=43]="GaugeUpperInflectionPointNaN",xs[xs.GaugeLowerBiggerThanUpper=44]="GaugeLowerBiggerThanUpper",xs[xs.InvalidAutofillSelection=45]="InvalidAutofillSelection",xs[xs.WrongComposerSelection=46]="WrongComposerSelection",xs[xs.MinBiggerThanMax=47]="MinBiggerThanMax",xs[xs.LowerBiggerThanUpper=48]="LowerBiggerThanUpper",xs[xs.MidBiggerThanMax=49]="MidBiggerThanMax",xs[xs.MinBiggerThanMid=50]="MinBiggerThanMid",xs[xs.FirstArgMissing=51]="FirstArgMissing",xs[xs.SecondArgMissing=52]="SecondArgMissing",xs[xs.MinNaN=53]="MinNaN",xs[xs.MidNaN=54]="MidNaN",xs[xs.MaxNaN=55]="MaxNaN",xs[xs.ValueUpperInflectionNaN=56]="ValueUpperInflectionNaN",xs[xs.ValueLowerInflectionNaN=57]="ValueLowerInflectionNaN",xs[xs.MinInvalidFormula=58]="MinInvalidFormula",xs[xs.MidInvalidFormula=59]="MidInvalidFormula",xs[xs.MaxInvalidFormula=60]="MaxInvalidFormula",xs[xs.ValueUpperInvalidFormula=61]="ValueUpperInvalidFormula",xs[xs.ValueLowerInvalidFormula=62]="ValueLowerInvalidFormula",xs[xs.InvalidSortZone=63]="InvalidSortZone",xs[xs.WaitingSessionConfirmation=64]="WaitingSessionConfirmation",xs[xs.MergeOverlap=65]="MergeOverlap",xs[xs.TooManyHiddenElements=66]="TooManyHiddenElements",xs[xs.Readonly=67]="Readonly",xs[xs.InvalidViewportSize=68]="InvalidViewportSize",xs[xs.InvalidScrollingDirection=69]="InvalidScrollingDirection",xs[xs.FigureDoesNotExist=70]="FigureDoesNotExist",xs[xs.InvalidConditionalFormatId=71]="InvalidConditionalFormatId",xs[xs.InvalidCellPopover=72]="InvalidCellPopover",xs[xs.EmptyTarget=73]="EmptyTarget",xs[xs.InvalidFreezeQuantity=74]="InvalidFreezeQuantity",xs[xs.FrozenPaneOverlap=75]="FrozenPaneOverlap",xs[xs.ValuesNotChanged=76]="ValuesNotChanged",xs[xs.InvalidFilterZone=77]="InvalidFilterZone",xs[xs.FilterOverlap=78]="FilterOverlap",xs[xs.FilterNotFound=79]="FilterNotFound",xs[xs.MergeInFilter=80]="MergeInFilter",xs[xs.NonContinuousTargets=81]="NonContinuousTargets",xs[xs.DuplicatedFigureId=82]="DuplicatedFigureId",xs[xs.InvalidSelectionStep=83]="InvalidSelectionStep",xs[xs.DuplicatedChartId=84]="DuplicatedChartId",xs[xs.ChartDoesNotExist=85]="ChartDoesNotExist",xs[xs.InvalidHeaderIndex=86]="InvalidHeaderIndex",xs[xs.InvalidQuantity=87]="InvalidQuantity",xs[xs.MoreThanOneColumnSelected=88]="MoreThanOneColumnSelected",xs[xs.EmptySplitSeparator=89]="EmptySplitSeparator",xs[xs.SplitWillOverwriteContent=90]="SplitWillOverwriteContent",xs[xs.NoSplitSeparatorInSelection=91]="NoSplitSeparatorInSelection",xs[xs.NoActiveSheet=92]="NoActiveSheet";const ys=["thin","medium","thick","dashed","dotted"];var Is,Rs;function Ts(e,t){return Os(As(e||""),t)}function As(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return Jt(e)||Ke(e)?Wi(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function Os(e,t){const o=zi(e);return o?{...Ms(As(o.label),t||xo(o.label)),link:o}:Ms(e,t)}function Ms(e,t){try{for(const o of Ds){const i=o(e,t);if(i)return i}return function(e,t){return{type:ms.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:uo(e,t)}}((e||"").toString(),t)}catch(t){return Fs((e||"").toString(),new c(a.GenericError,t.message||he))}}function Ns(e,t){return{type:ms.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:uo(e,t)}}!function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(Is||(Is={})),function(e){e[e.Background=0]="Background",e[e.Highlights=1]="Highlights",e[e.Clipboard=2]="Clipboard",e[e.Search=3]="Search",e[e.Chart=4]="Chart",e[e.Autofill=5]="Autofill",e[e.Selection=6]="Selection",e[e.Headers=7]="Headers"}(Rs||(Rs={}));const _s={type:ms.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function Fs(e,t){return{type:ms.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const Ds=[function(e,t){if(""===e)return function(e){return void 0===e?_s:{type:ms.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&bo(t))return function(e,t){const o=uo(e,t);return{type:ms.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:o}}(e,t)},function(e,t){return"number"==typeof e?Ns(e,t):null===e?Ns(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const o=e?"TRUE":"FALSE";return{type:ms.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:o}}(e,t)}],Ls=new _i;Ls.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const o=`${e.prefix}${e.current.toString().padStart(e.numberPostfixLength||0,"0")}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:{props:{content:o}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const o=e.current.toString(),i=uo(e.current,t.cell?.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,o)=>{const i=t.cell?.content||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i},tooltip:i?{props:{content:Ts(t.cell?.content,t.cell?.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,o,i)=>{e.current+=e.increment;let s=0,r=0;switch(i){case"up":s=0,r=-e.current;break;case"down":s=0,r=e.current;break;case"left":s=-e.current,r=0;break;case"right":s=e.current,r=0}const n=t.cell;if(!n||!n.isFormula)return{cellData:{}};const a=t.sheetId,l=o.createAdaptedRanges(n.dependencies,s,r,a),c=o.buildFormulaContent(a,n,l);return{cellData:{border:t.border,style:n.style,format:n.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});const Ps=new _i,ks=/(\d+)$/,Us=/^(.*\D+)/,Vs=/^(.*\D+)(\d+)$/;function zs(e,t,o){let i=[],s=!1;for(let r of t){r===e&&(s=!0);const t=Ts(r?.content);if(o(t))i.push(t);else{if(s)return i;i=[]}}return i}function Bs(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let o=e[0];for(let i=1;i<e.length;i++){const s=e[i];t.push(s-o),o=s}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}Ps.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&bo(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Ts(e.content).type===ms.text&&Vs.test(e.content),generateRule:(e,t)=>{const o=parseInt(e.content.match(ks)[0]),i=e.content.match(Us)[0],s=e.content.length-i.length,r=zs(e,t,(e=>e.type===ms.text&&Vs.test(e.value))).filter((e=>i===e.value.toString().match(Us)[0])).map((e=>parseInt(e.value.toString().match(ks)[0]))),n=Bs(r);return{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:i,current:o,increment:n,numberPostfixLength:s}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Ts(e.content).type===ms.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_number",{condition:e=>!e.isFormula&&Ts(e.content).type===ms.number,generateRule:(e,t)=>{const o=Bs(zs(e,t,(e=>e.type===ms.number)).map((e=>Number(e.value)))),i=Ts(e.content);return{type:"INCREMENT_MODIFIER",increment:o,current:i.type===ms.number?i.value:0}},sequence:40});xi`
54
54
  .o-error-tooltip {
55
55
  font-size: 13px;
56
56
  background-color: white;
@@ -349,7 +349,7 @@
349
349
  height: 100%;
350
350
  position: relative;
351
351
  }
352
- `;class _n extends t.Component{static template="o-spreadsheet-ChartFigure";static components={};onDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.openSidePanel("ChartPanel")}get chartType(){return this.env.model.getters.getChartType(this.props.figure.id)}get chartComponent(){const e=this.chartType,t=Mn.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}_n.props={figure:Object,onFigureDeleted:Function};class Fn extends t.Component{static template="o-spreadsheet-ImageFigure";static components={};get figureId(){return this.props.figure.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}function Dn(e,t){const o=Ve(t),i=e.getSheetViewDimension(),s=i.width,r=i.height;if(o.width>s){const e=s/o.width;o.width=s,o.height=o.height*e}if(o.height>r){const e=r/o.height;o.height=r,o.width=o.width*e}return o}Fn.props={figure:Object,onFigureDeleted:Function};const Ln=new _i;function Pn(e,t){return{id:"copy",name:r("Copy"),sequence:2,description:"Ctrl+C",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("COPY"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function kn(e,t){return{id:"cut",name:r("Cut"),sequence:3,description:"Ctrl+X",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("CUT"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function Un(e,t,o){return{id:"delete",name:r("Delete"),sequence:10,execute:()=>{o.model.dispatch("DELETE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e}),t()}}}Ln.add("chart",{Component:_n,SidePanelComponent:"ChartPanel",menuBuilder:function(e,t,o){return br([{id:"edit",name:r("Edit"),sequence:1,execute:()=>{o.model.dispatch("SELECT_FIGURE",{id:e}),o.openSidePanel("ChartPanel")}},Pn(e,o),kn(e,o),Un(e,t,o)])}}),Ln.add("image",{Component:Fn,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,o){return br([Pn(e,o),kn(e,o),{id:"reset_size",name:r("Reset size"),sequence:4,execute:()=>{const t=o.model.getters.getImageSize(e),{height:i,width:s}=Dn(o.model.getters,t);o.model.dispatch("UPDATE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e,height:i,width:s})}},Un(e,t,o)])}});const Vn=(new _i).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let o=e.base;"after"===e.position&&o++;for(let i=0;i<e.quantity;i++)t.push(i+o);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],o=[...e.elements].sort(((e,t)=>e-t));for(let i of Ye(o)){const o=0===i[0]?0:i[0]-1,s=0===i[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:i.length,base:o,sheetId:e.sheetId,position:s})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of Cs.values())Vn.contains(e)||Vn.add(e,zn);function zn(e){return[e]}const Bn={MergeIsDestructive:r("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:r("You can't merge cells inside of an existing filter.")};function Hn(e,t){const o=On.getAll().find((t=>t.match(e.type)));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t)}function $n(e,t){let o=e;e.left!==e.right&&(o={...e,left:e.left+1});const i=[Ko(o)],r=t.getActiveSheetId(),n=t.getCell({sheetId:r,col:e.left,row:e.top});if(1===vi(e)&&n?.content)return{type:"scorecard",title:"",background:n.style?.fillColor||void 0,keyValue:Ko(e),baselineMode:ie,baselineColorUp:se,baselineColorDown:re};let a="";const l=t.getEvaluatedCellsInZone(r,{...o,bottom:o.top}),c=!!l.find((e=>e.type!==ms.empty&&e.type!==ms.number));if(c){const e=l.filter((e=>e.type!==ms.error&&e.type!==ms.empty)).map((e=>e.formattedValue)),t=e.splice(-1)[0];a=e.join(", "),t&&(a+=(a?" "+s("and")+" ":"")+t)}let h;e.left!==e.right&&(h=Ko({...e,right:e.left}));const d=o.right===o.left?"none":"top";return Cn(h?t.getRangeFromSheetXC(r,h):void 0,t)?{title:a,dataSets:i,labelsAsText:!1,stacked:!1,aggregated:!1,labelRange:h,type:"line",dataSetsHaveTitle:c,verticalAxisPosition:"left",legendPosition:d}:{title:a,dataSets:i,labelRange:h,type:"bar",stacked:!1,aggregated:!1,dataSetsHaveTitle:c,verticalAxisPosition:"left",legendPosition:d}}const Wn=[ms.number,ms.error,ms.text,ms.boolean];function Gn(e,t,o,i,s){let n=ws.Success,a=i.right>i.left;if(e.model.getters.doesIntersectMerge(t,i)){let o;a=!1;for(let s=i.top;s<=i.bottom;s++){o=[];for(let r=i.left;r<=i.right;r++){let i=e.model.getters.getMerge({sheetId:t,col:r,row:s});i&&!o.includes(i.id.toString())&&o.push(i.id.toString())}if(o.length>=2){a=!0;break}}}const{col:l,row:c}=o;if(a)n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s});else{const o=e.model.getters.getContiguousZone(t,i);si(o,i)?n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s}):e.askConfirmation(r("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{i=o,n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s})}),(()=>{n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s})}))}if(n.isCancelledBecause(63)){const{col:t,row:s}=o;e.model.selection.selectZone({cell:{col:t,row:s},zone:i}),e.raiseError(r("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function qn(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(r("This operation is not allowed with multiple selections."))}const Zn={filterOverlap:r("You cannot create overlapping filters."),nonContinuousTargets:r("A filter can only be created on a continuous selection."),mergeInFilter:r("You can't create a filter over a range that contains a merge.")};function jn(e,t,o){const i=e.model.dispatch("CREATE_FILTER_TABLE",{target:o,sheetId:t});i.isCancelledBecause(78)?e.raiseError(Zn.filterOverlap):i.isCancelledBecause(80)?e.raiseError(Zn.mergeInFilter):i.isCancelledBecause(81)&&e.raiseError(Zn.nonContinuousTargets)}const Yn={wrongPasteSelection:r("This operation is not allowed with multiple selections."),willRemoveExistingMerge:r("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:r("Cannot do a special paste of a figure."),frozenPaneOverlap:r("Cannot paste merged cells over a frozen pane.")};function Xn(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(Yn.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(Yn.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(Yn.wrongFigurePasteOption):t.reasons.includes(75)&&e.raiseError(Yn.frozenPaneOverlap))}function Kn(e,t,o){const i=e.model.dispatch("PASTE",{target:t,pasteOption:o});Xn(e,i)}function Qn(e,t,o){const i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:o});Xn(e,i)}function Jn(e){const t=e.model.getters.getActiveCols();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}function ea(e){const t=e.model.getters.getActiveRows();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function ta(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function oa(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const ia=async e=>sa(e,"onlyValue");async function sa(e,t){const o=e.model.getters.getClipboardTextContent(),i=await e.clipboard.readText();switch(i.status){case"ok":const s=e.model.getters.getSelectedZones();i&&i.content!==o?Qn(e,s,i.content):Kn(e,s,t);break;case"notImplemented":e.raiseError(r("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(r("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const ra=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("ROW");return e.model.getters.canRemoveHeaders(t,"ROW",o)},na=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("COL");return e.model.getters.canRemoveHeaders(t,"COL",o)},aa=e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.min(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.top,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:o,quantity:i,dimension:"ROW"})},la=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.min(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.left,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:o,quantity:i})},ca=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.max(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.right,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:o,quantity:i})};const ha=async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),o=e.model.uuidGenerator.uuidv4(),i=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(r("An unexpected error occurred during the image transfer"))}}(e);if(!i)throw new Error("No image provider was given to the environment");const s=Dn(e.model.getters,i.size),n=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:s,scrollY:r}=e.getActiveSheetScrollInfo(),n=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,n.width-o),c=Math.min(a.height,n.height-i);return{x:o+s+Math.max(0,(l-t.width)/2),y:i+r+Math.max(0,(c-t.height)/2)}}(e.model.getters,s);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:o,position:n,size:s,definition:i})}},da=e=>ta(e,"0.00%"),ua=e=>{let{col:t,row:o}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:o,popoverType:"LinkEditor"})},ga=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)},pa=e=>1===e.model.getters.getSelectedZones().length,ma={name:r("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},fa={name:r("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},ba={name:r("Copy"),description:"Ctrl+C",isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch("COPY"),await e.clipboard.write(e.model.getters.getClipboardContent())},icon:"o-spreadsheet-Icon.COPY"},va={name:r("Cut"),description:"Ctrl+X",execute:async e=>{qn(e),await e.clipboard.write(e.model.getters.getClipboardContent())},icon:"o-spreadsheet-Icon.CUT"},Sa={name:r("Paste"),description:"Ctrl+V",execute:async e=>sa(e),icon:"o-spreadsheet-Icon.PASTE"},Ca={name:r("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},Ea={name:r("Paste value only"),description:"Ctrl+Shift+V",execute:ia},wa={name:r("Paste format only"),execute:e=>Kn(e,e.model.getters.getSelectedZones(),"onlyFormat")},xa={name:r("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},icon:"o-spreadsheet-Icon.FIND_AND_REPLACE"},ya={name:r("Delete values"),execute:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},Ia={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Delete rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?r("Delete row %s",(t+1).toString()):r("Delete rows %s - %s",(t+1).toString(),(o+1).toString())},execute:e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.top;e<=o.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:ra},Ra={...Ia,isVisible:pa},Ta={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Clear rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?r("Clear row %s",(t+1).toString()):r("Clear rows %s - %s",(t+1).toString(),(o+1).toString())},execute:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveRows()].map((o=>e.model.getters.getRowsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}},Aa={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Delete columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?r("Delete column %s",Pt(t)):r("Delete columns %s - %s",Pt(t),Pt(o))},execute:e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.left;e<=o.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:na},Oa={...Aa,isVisible:pa},Ma={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Clear columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?r("Clear column %s",Pt(t)):r("Clear columns %s - %s",Pt(t),Pt(o))},execute:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveCols()].map((o=>e.model.getters.getColsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}},Na={name:r("Delete cells"),isVisible:pa},_a={name:r("Delete cell and shift up"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});Xn(e,o)}},Fa={name:r("Delete cell and shift left"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});Xn(e,o)}},Da={name:r("Merge cells"),isEnabled:e=>!La(e),isActive:e=>Pa(e),execute:e=>function(e){if(La(e))return;const t=e.model.getters.getSelectedZones(),o=[t[t.length-1]],i=e.model.getters.getActiveSheetId();Pa(e)?e.model.dispatch("REMOVE_MERGE",{sheetId:i,target:o}):function(e,t,o){const i=e.model.dispatch("ADD_MERGE",{sheetId:t,target:o});i.isCancelledBecause(80)?e.raiseError(Bn.MergeInFilter):i.isCancelledBecause(3)&&e.askConfirmation(Bn.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:o,force:!0})}))}(e,i,o)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"};function La(e){const t=e.model.getters.getSelectedZones(),{top:o,left:i,right:s,bottom:r}=e.model.getters.getSelectedZone(),{sheetId:n}=e.model.getters.getActivePosition(),{xSplit:a,ySplit:l}=e.model.getters.getPaneDivisions(n);return t.length>1||o===r&&i===s||i<a&&a<=s||o<l&&l<=r}function Pa(e){if(!La(e)){const t=e.model.getters.getSelectedZones(),{col:o,row:i,sheetId:s}=e.model.getters.getActivePosition(),r=e.model.getters.expandZone(s,fi({col:o,row:i}));return si(t[0],r)}return!1}var ka=Object.freeze({__proto__:null,undo:ma,redo:fa,copy:ba,cut:va,paste:Sa,pasteSpecial:Ca,pasteSpecialValue:Ea,pasteSpecialFormat:wa,findAndReplace:xa,deleteValues:ya,deleteRows:Ia,deleteRow:Ra,clearRows:Ta,deleteCols:Aa,deleteCol:Oa,clearCols:Ma,deleteCells:Na,deleteCellShiftUp:_a,deleteCellShiftLeft:Fa,mergeCells:Da});const Ua=/(.*?)\((.*?)\)(.*)/,Va=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function za(e,t=""){return function(e){let t,o=e.match(Ua),i=o[1].trim(),s=[],r=!1,n=!1,a=!1;for(let e of o[2].split(",")){const o=e.trim().toUpperCase();let i=Va.find((e=>o===e));i?s.push(i):"RANGE<ANY>"===o?s.push("RANGE"):"OPTIONAL"===o?r=!0:"REPEATING"===o?n=!0:"LAZY"===o?a=!0:o.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}let l=o[3].trim();const c={name:i,description:l,type:s};r&&(c.optional=!0);n&&(c.repeating=!0);a&&(c.lazy=!0);void 0!==t&&(c.default=!0,c.defaultValue=t);return c}(`${e} ${t}`)}function Ba(e){let t=0,o=0,i=0;for(let s of e.args)t++,s.optional||s.repeating||s.default||o++,s.repeating&&i++;const s=e;return s.minArgRequired=o,s.maxArgPossible=i?1/0:t,s.nbrArgRepeating=i,s.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const o=e-t;return e=>{if(e<=o)return e;return o+((e-o)%t||t)}}(t,i),s.hidden=e.hidden||!1,s}const Ha={description:r("Apply a large number format"),args:[za("value (number)",r("The number.")),za("unit (string, optional)",r("The formatting unit. Use 'k', 'm', or 'b' to force the unit"))],returns:["NUMBER"],computeFormat:(e,t)=>{const o=Math.abs(Wi(e.value)),i=e.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return yo(i,1e3,"k");case"m":return yo(i,1e6,"m");case"b":return yo(i,1e9,"b");default:throw new Error(r("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?yo(i,0,""):o<1e8?yo(i,1e3,"k"):o<1e11?yo(i,1e6,"m"):yo(i,1e9,"b")},compute:function(e){return Wi(e)}};var $a=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Ha});const Wa=/^-?[a-z0-9]+$/i,Ga={description:r("Absolute value of a number."),args:[za("value (number)",r("The number of which to return the absolute value."))],returns:["NUMBER"],compute:function(e){return Math.abs(Wi(e))},isExported:!0},qa={description:r("Inverse cosine of a value, in radians."),args:[za("value (number)",r("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>Math.abs(t)<=1),r("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},Za={description:r("Inverse hyperbolic cosine of a number."),args:[za("value (number)",r("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>t>=1),r("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},ja={description:r("Inverse cotangent of a value."),args:[za("value (number)",r("The value for which to calculate the inverse cotangent."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Ya={description:r("Inverse hyperbolic cotangent of a value."),args:[za("value (number)",r("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>Math.abs(t)>1),r("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},Xa={description:r("Inverse sine of a value, in radians."),args:[za("value (number)",r("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>Math.abs(t)<=1),r("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Ka={description:r("Inverse hyperbolic sine of a number."),args:[za("value (number)",r("The value for which to calculate the inverse hyperbolic sine."))],returns:["NUMBER"],compute:function(e){return Math.asinh(Wi(e))},isExported:!0},Qa={description:r("Inverse tangent of a value, in radians."),args:[za("value (number)",r("The value for which to calculate the inverse tangent."))],returns:["NUMBER"],compute:function(e){return Math.atan(Wi(e))},isExported:!0},Ja={description:r("Angle from the X axis to a point (x,y), in radians."),args:[za("x (number)",r("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),za("y (number)",r("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],returns:["NUMBER"],compute:function(e,t){const o=Wi(e),i=Wi(t);return Hi((()=>0!==o||0!==i),r("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(i,o)},isExported:!0},el={description:r("Inverse hyperbolic tangent of a number."),args:[za("value (number)",r("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>Math.abs(t)<1),r("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},tl={description:r("Rounds number up to nearest multiple of factor."),args:[za("value (number)",r("The value to round up to the nearest integer multiple of factor.")),za("factor (number, default=1)",r("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){const o=Wi(e),i=Wi(t);return Hi((()=>i>=0||o<=0),r("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.ceil(o/i)*i:0},isExported:!0},ol={description:r("Rounds number up to nearest multiple of factor."),args:[za("number (number)",r("The value to round up to the nearest integer multiple of significance.")),za("significance (number, default=1)",r("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),za("mode (number, default=0)",r("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1,o=0){let i=Wi(t);if(0===i)return 0;const s=Wi(e);if(i=Math.abs(i),s>=0)return Math.ceil(s/i)*i;return 0===Wi(o)?-Math.floor(Math.abs(s)/i)*i:-Math.ceil(Math.abs(s)/i)*i},isExported:!0},il={description:r("Rounds number up to nearest multiple of factor."),args:[za("number (number)",r("The value to round up to the nearest integer multiple of significance.")),za("significance (number, default=1)",r("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){return ol.compute(e,t,0)},isExported:!0},sl={description:r("Cosine of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the cosine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.cos(Wi(e))},isExported:!0},rl={description:r("Hyperbolic cosine of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic cosine of."))],returns:["NUMBER"],compute:function(e){return Math.cosh(Wi(e))},isExported:!0},nl={description:r("Cotangent of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the cotangent of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},al={description:r("Hyperbolic cotangent of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic cotangent of."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},ll={description:r("Number of empty values."),args:[za("value1 (any, range)",r("The first value or range in which to count the number of blanks.")),za("value2 (any, range, repeating)",r("Additional values or ranges in which to count the number of blanks."))],returns:["NUMBER"],compute:function(...e){return is(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},cl={description:r("A conditional count across a range."),args:[za("range (range)",r("The range that is tested against criterion.")),za("criterion (string)",r("The pattern or test to apply to range."))],returns:["NUMBER"],compute:function(...e){let t=0;return cs(e,((e,o)=>{t+=1})),t},isExported:!0},hl={description:r("Count values depending on multiple criteria."),args:[za("criteria_range1 (range)",r("The range to check against criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1.")),za("criteria_range2 (any, range, repeating)",r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),za("criterion2 (string, repeating)",r("Additional criteria to check."))],returns:["NUMBER"],compute:function(...e){let t=0;return cs(e,((e,o)=>{t+=1})),t},isExported:!0};function dl(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const ul={description:r("Counts number of unique values in a range."),args:[za("value1 (any, range)",r("The first value or range to consider for uniqueness.")),za("value2 (any, range, repeating)",r("Additional values or ranges to consider for uniqueness."))],returns:["NUMBER"],compute:function(...e){return is(e,((e,t)=>dl(t)?e.add(t):e),new Set).size}},gl={description:r("Counts number of unique values in a range, filtered by a set of criteria."),args:[za("range (range)",r("The range of cells from which the number of unique values will be counted.")),za("criteria_range1 (range)",r("The range of cells over which to evaluate criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),za("criteria_range2 (any, range, repeating)",r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),za("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=new Set;return cs(t,((t,i)=>{const s=e[t][i];dl(s)&&o.add(s)})),o.size}},pl={description:r("Cosecant of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the cosecant of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},ml={description:r("Hyperbolic cosecant of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic cosecant of."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},fl={description:r("Converts from another base to decimal."),args:[za("value (string)",r("The number to convert.")),za(",base (number)",r("The base to convert the value from."))],returns:["NUMBER"],compute:function(e,t){let o=Wi(t);o=Math.floor(o),Hi((()=>2<=o&&o<=36),r("The base (%s) must be between 2 and 36 inclusive.",o.toString()));const i=ji(e);if(""===i)return 0;Hi((()=>!!Wa.test(i)),r("The value (%s) must be a valid base %s representation.",i,o.toString()));const s=parseInt(i,o);return Hi((()=>!isNaN(s)),r("The value (%s) must be a valid base %s representation.",i,o.toString())),s},isExported:!0},bl={description:r("Converts an angle value in radians to degrees."),args:[za("angle (number)",r("The angle to convert from radians to degrees."))],returns:["NUMBER"],compute:function(e){return 180*Wi(e)/Math.PI},isExported:!0},vl={description:r("Euler's number, e (~2.718) raised to a power."),args:[za("value (number)",r("The exponent to raise e."))],returns:["NUMBER"],compute:function(e){return Math.exp(Wi(e))},isExported:!0},Sl={description:r("Rounds number down to nearest multiple of factor."),args:[za("value (number)",r("The value to round down to the nearest integer multiple of factor.")),za("factor (number, default=1)",r("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){const o=Wi(e),i=Wi(t);return Hi((()=>i>=0||o<=0),r("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.floor(o/i)*i:0},isExported:!0},Cl={description:r("Rounds number down to nearest multiple of factor."),args:[za("number (number)",r("The value to round down to the nearest integer multiple of significance.")),za("significance (number, default=1)",r("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),za("mode (number, default=0)",r("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1,o=0){let i=Wi(t);if(0===i)return 0;const s=Wi(e);if(i=Math.abs(i),s>=0)return Math.floor(s/i)*i;return 0===Wi(o)?-Math.ceil(Math.abs(s)/i)*i:-Math.floor(Math.abs(s)/i)*i},isExported:!0},El={description:r("Rounds number down to nearest multiple of factor."),args:[za("number (number)",r("The value to round down to the nearest integer multiple of significance.")),za("significance (number, default=1)",r("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){return Cl.compute(e,t,0)},isExported:!0},wl={description:r("Whether the provided value is even."),args:[za("value (number)",r("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Gi(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},xl={description:r("Rounds number up to nearest multiple of factor."),args:[za("number (number)",r("The value to round up to the nearest integer multiple of significance.")),za("significance (number, default=1)",r("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){return ol.compute(e,t,0)},isExported:!0},yl={description:r("Whether the provided value is even."),args:[za("value (number)",r("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Gi(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Il={description:r("The logarithm of a number, base e (euler's number)."),args:[za("value (number)",r("The value for which to calculate the logarithm, base e."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>t>0),r("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},Rl={description:r("Modulo (remainder) operator."),args:[za("dividend (number)",r("The number to be divided to find the remainder.")),za("divisor (number)",r("The number to divide by."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Wi(t);Hi((()=>0!==o),r("The divisor must be different from 0."));const i=Wi(e)%o;return i>0&&o<0||i<0&&o>0?i+o:i},isExported:!0},Tl={description:r("Rounds a number up to the nearest odd integer."),args:[za("value (number)",r("The value to round to the next greatest odd number."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Wi(e);let o=Math.ceil(Math.abs(t));return o=1&o?o:o+1,t<0?-o:o},isExported:!0},Al={description:r("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Ol={description:r("A number raised to a power."),args:[za("base (number)",r("The number to raise to the exponent power.")),za("exponent (number)",r("The exponent to raise base to."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Wi(e),i=Wi(t);return Hi((()=>o>=0||Number.isInteger(i)),r("The exponent (%s) must be an integer when the base is negative.",i.toString())),Math.pow(o,i)},isExported:!0},Ml={description:r("Result of multiplying a series of numbers together."),args:[za("factor1 (number, range<number>)",r("The first number or range to calculate for the product.")),za("factor2 (number, range<number>, repeating)",r("More numbers or ranges to calculate for the product."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0,o=1;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(o*=i,t+=1);else null!=i&&(o*=Gi(i),t+=1);return 0===t?0:o},isExported:!0},Nl={description:r("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},_l={description:r("Random integer between two values, inclusive."),args:[za("low (number)",r("The low end of the random range.")),za("high (number)",r("The high end of the random range."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){let o=Wi(e);Number.isInteger(o)||(o=Math.ceil(o));let i=Wi(t);return Number.isInteger(i)||(i=Math.floor(i)),Hi((()=>o<=i),r("The high (%s) must be greater than or equal to the low (%s).",i.toString(),o.toString())),o+Math.ceil((i-o+1)*Math.random())-1},isExported:!0},Fl={description:r("Rounds a number according to standard rules."),args:[za("value (number)",r("The value to round to places number of places.")),za("places (number, default=0)",r("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Wi(e);let i=Wi(t);const s=Math.abs(o);let r;return 0===i?r=Math.round(s):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.round(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},Dl={description:r("Rounds down a number."),args:[za("value (number)",r("The value to round to places number of places, always rounding down.")),za("places (number, default=0)",r("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Wi(e);let i=Wi(t);const s=Math.abs(o);let r;return 0===i?r=Math.floor(s):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.floor(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},Ll={description:r("Rounds up a number."),args:[za("value (number)",r("The value to round to places number of places, always rounding up.")),za("places (number, default=0)",r("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Wi(e);let i=Wi(t);const s=Math.abs(o);let r;return 0===i?r=Math.ceil(s):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.ceil(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},Pl={description:r("Secant of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the secant of, in radians."))],returns:["NUMBER"],compute:function(e){return 1/Math.cos(Wi(e))},isExported:!0},kl={description:r("Hyperbolic secant of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic secant of."))],returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Wi(e))},isExported:!0},Ul={description:r("Sine of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the sine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.sin(Wi(e))},isExported:!0},Vl={description:r("Hyperbolic sine of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic sine of."))],returns:["NUMBER"],compute:function(e){return Math.sinh(Wi(e))},isExported:!0},zl={description:r("Positive square root of a positive number."),args:[za("value (number)",r("The number for which to calculate the positive square root."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Wi(e);return Hi((()=>t>=0),r("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},Bl={description:r("Sum of a series of numbers and/or cells."),args:[za("value1 (number, range<number>)",r("The first number or range to add together.")),za("value2 (number, range<number>, repeating)",r("Additional numbers or ranges to add to value1."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){return ss(e,((e,t)=>e+t),0)},isExported:!0},Hl={description:r("A conditional sum across a range."),args:[za("criteria_range (range)",r("The range which is tested against criterion.")),za("criterion (string)",r("The pattern or test to apply to range.")),za("sum_range (range, default=criteria_range)",r("The range to be summed, if different from range."))],returns:["NUMBER"],compute:function(e,t,o){void 0===o&&(o=e);let i=0;return cs([e,t],((e,t)=>{const s=o[e][t];"number"==typeof s&&(i+=s)})),i},isExported:!0},$l={description:r("Sums a range depending on multiple criteria."),args:[za("sum_range (range)",r("The range to sum.")),za("criteria_range1 (range)",r("The range to check against criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1.")),za("criteria_range2 (any, range, repeating)",r("Additional ranges to check.")),za("criterion2 (string, repeating)",r("Additional criteria to check."))],returns:["NUMBER"],compute:function(e,...t){let o=0;return cs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o+=s)})),o},isExported:!0},Wl={description:r("Tangent of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the tangent of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.tan(Wi(e))},isExported:!0},Gl={description:r("Hyperbolic tangent of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic tangent of."))],returns:["NUMBER"],compute:function(e){return Math.tanh(Wi(e))},isExported:!0},ql={description:r("Truncates a number."),args:[za("value (number)",r("The value to be truncated.")),za("places (number, default=0)",r("The number of significant digits to the right of the decimal point to retain."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Wi(e);let i=Wi(t);return 0===i?Math.trunc(o):(Number.isInteger(i)||(i=Math.trunc(i)),Math.trunc(o*Math.pow(10,i))/Math.pow(10,i))},isExported:!0};var Zl=Object.freeze({__proto__:null,ABS:Ga,ACOS:qa,ACOSH:Za,ACOT:ja,ACOTH:Ya,ASIN:Xa,ASINH:Ka,ATAN:Qa,ATAN2:Ja,ATANH:el,CEILING:tl,CEILING_MATH:ol,CEILING_PRECISE:il,COS:sl,COSH:rl,COT:nl,COTH:al,COUNTBLANK:ll,COUNTIF:cl,COUNTIFS:hl,COUNTUNIQUE:ul,COUNTUNIQUEIFS:gl,CSC:pl,CSCH:ml,DECIMAL:fl,DEGREES:bl,EXP:vl,FLOOR:Sl,FLOOR_MATH:Cl,FLOOR_PRECISE:El,ISEVEN:wl,ISO_CEILING:xl,ISODD:yl,LN:Il,MOD:Rl,ODD:Tl,PI:Al,POWER:Ol,PRODUCT:Ml,RAND:Nl,RANDBETWEEN:_l,ROUND:Fl,ROUNDDOWN:Dl,ROUNDUP:Ll,SEC:Pl,SECH:kl,SIN:Ul,SINH:Vl,SQRT:zl,SUM:Bl,SUMIF:Hl,SUMIFS:$l,TAN:Wl,TANH:Gl,TRUNC:ql});function jl(e,t,o){let i=[],s=[],n=0,a=0;es([e],(e=>{i.push(e),n+=1})),es([t],(e=>{s.push(e),a+=1})),Hi((()=>n===a),r("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",n.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<n;e++){const t=i[e],o=s[e];"number"==typeof t&&"number"==typeof o&&(l+=1,c+=t,h+=o)}Hi((()=>0!==l&&(!o||1!==l)),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let g=0;for(let e=0;e<n;e++){const t=i[e],o=s[e];"number"==typeof t&&"number"==typeof o&&(g+=(t-d)*(o-u))}return g/(l-(o?1:0))}function Yl(e,t,o){let i=0,s=0;const n=o?rs:ss;s=n(e,((e,t)=>(i+=1,e+t)),0),Hi((()=>0!==i&&(!t||1!==i)),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=s/i;return n(e,((e,t)=>e+Math.pow(t-a,2)),0)/(i-(t?1:0))}function Xl(e,t,o){const i=Wi(t);Hi((()=>o?0<=i&&i<=1:0<i&&i<1),r("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let s,n=[],a=0;return es(e,(e=>{"number"==typeof e&&(s=us(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(s+1,0,e),a++)})),Hi((()=>0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),o||Hi((()=>1/(a+1)<=i&&i<=a/(a+1)),r("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),oo(n,i,o)}const Kl={description:r("Average magnitude of deviations from mean."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){let t=0;const o=ss(e,((e,o)=>(t+=1,e+o)),0);Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const i=o/t;return ss(e,((e,t)=>e+Math.abs(i-t)),0)/t},isExported:!0},Ql={description:r("Numerical average value in a dataset, ignoring text."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when calculating the average value.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0;const o=ss(e,((e,o)=>(t+=1,e+o)),0);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},Jl=r("[[FUNCTION_NAME]] has mismatched range sizes."),ec=r("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),tc={description:r("Weighted average."),args:[za("values (number, range<number>)",r("Values to average.")),za("weights (number, range<number>)",r("Weights for each corresponding value.")),za("additional_values (number, range<number>, repeating)",r("Additional values to average.")),za("additional_weights (number, range<number>, repeating)",r("Additional weights."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t,o,i=0,s=0;Hi((()=>e.length%2==0),r("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let n=0;n<e.length-1;n+=2)if(t=e[n],o=e[n+1],Array.isArray(t)){Hi((()=>Array.isArray(o)),Jl);let e=t.length,n=t[0].length;Hi((()=>e===o.length&&n===o[0].length),Jl);for(let a=0;a<e;a++)for(let e=0;e<n;e++){let n=t[a][e],l=o[a][e],c="number"==typeof n,h="number"==typeof l;Hi((()=>c===h),r("[[FUNCTION_NAME]] expects number values.")),h&&(Hi((()=>l>=0),ec),i+=n*l,s+=l)}}else o=Wi(o),t=Wi(t),Hi((()=>o>=0),ec),i+=t*o,s+=o;return Hi((()=>0!==s),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/s}},oc={description:r("Numerical average value in a dataset."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when calculating the average value.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0;const o=rs(e,((e,o)=>(t+=1,e+o)),0);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},ic={description:r("Average of values depending on criteria."),args:[za("criteria_range (range)",r("The range to check against criterion.")),za("criterion (string)",r("The pattern or test to apply to criteria_range.")),za("average_range (range, default=criteria_range)",r("The range to average. If not included, criteria_range is used for the average instead."))],returns:["NUMBER"],compute:function(e,t,o){null==o&&(o=e);let i=0,s=0;return cs([e,t],((t,r)=>{const n=(o||e)[t][r];"number"==typeof n&&(i+=1,s+=n)})),Hi((()=>0!==i),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/i},isExported:!0},sc={description:r("Average of values depending on multiple criteria."),args:[za("average_range (range)",r("The range to average.")),za("criteria_range1 (range)",r("The range to check against criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1.")),za("criteria_range2 (any, range, repeating)",r("Additional criteria_range and criterion to check.")),za("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=0,i=0;return cs(t,((t,s)=>{const r=e[t][s];"number"==typeof r&&(o+=1,i+=r)})),Hi((()=>0!==o),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},rc={description:r("The number of numeric values in dataset."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when counting.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){let t=0;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(t+=1);else("string"!=typeof o||Jt(o)||ye(o))&&(t+=1);return t},isExported:!0},nc={description:r("The number of values in a dataset."),args:[za("value1 (any, range)",r("The first value or range to consider when counting.")),za("value2 (any, range, repeating)",r("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){return is(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},ac={description:r("The covariance of a dataset."),args:[za("data_y (any, range)",r("The range representing the array or matrix of dependent data.")),za("data_x (any, range)",r("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return jl(e,t,!1)},isExported:!0},lc={description:r("The covariance of a dataset."),args:[za("data_y (any, range)",r("The range representing the array or matrix of dependent data.")),za("data_x (any, range)",r("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return jl(e,t,!1)},isExported:!0},cc={description:r("The sample covariance of a dataset."),args:[za("data_y (any, range)",r("The range representing the array or matrix of dependent data.")),za("data_x (any, range)",r("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return jl(e,t,!0)},isExported:!0},hc={description:r("Nth largest element from a data set."),args:[za("data (any, range)",r("Array or range containing the dataset to consider.")),za("n (number)",r("The rank from largest to smallest of the element to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){const o=Math.trunc(Wi(t));let i,s=[],n=0;es([e],(e=>{"number"==typeof e&&(i=us(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(i+1,0,e),n++,n>o&&(s.shift(),n--))}));const a=s.shift();return Hi((()=>void 0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),Hi((()=>n>=o),r("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},dc={description:r("Maximum value in a numeric dataset."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when calculating the maximum value.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=ss(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},uc={description:r("Maximum numeric value in a dataset."),args:[za("value1 (any, range)",r("The first value or range to consider when calculating the maximum value.")),za("value2 (any, range, repeating)",r("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=rs(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},gc={description:r("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[za("range (range)",r("The range of cells from which the maximum will be determined.")),za("criteria_range1 (range)",r("The range of cells over which to evaluate criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),za("criteria_range2 (any, range, repeating)",r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),za("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=-1/0;return cs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o=o<s?s:o)})),o===-1/0?0:o},isExported:!0},pc={description:r("Median value in a numeric dataset."),args:[za("value1 (any, range)",r("The first value or range to consider when calculating the median value.")),za("value2 (any, range, repeating)",r("Additional values or ranges to consider when calculating the median value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=[];return ts(e,(e=>{t.push(e)})),Xl(t,.5,!0)},isExported:!0},mc={description:r("Minimum value in a numeric dataset."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when calculating the minimum value.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=ss(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},fc={description:r("Minimum numeric value in a dataset."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when calculating the minimum value.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=rs(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},bc={description:r("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[za("range (range)",r("The range of cells from which the minimum will be determined.")),za("criteria_range1 (range)",r("The range of cells over which to evaluate criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),za("criteria_range2 (any, range, repeating)",r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),za("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=1/0;return cs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o=o>s?s:o)})),o===1/0?0:o},isExported:!0},vc={description:r("Value at a given percentile of a dataset."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("percentile (number)",r("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Cc.compute(e,t)},isExported:!0},Sc={description:r("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("percentile (number)",r("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Xl([e],t,!1)},isExported:!0},Cc={description:r("Value at a given percentile of a dataset."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("percentile (number)",r("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Xl([e],t,!0)},isExported:!0},Ec={description:r("Value nearest to a specific quartile of a dataset."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("quartile_number (number)",r("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return xc.compute(e,t)},isExported:!0},wc={description:r("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("quartile_number (number)",r("Which quartile value, exclusive of 0 and 4, to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Xl([e],.25*Math.trunc(Wi(t)),!1)},isExported:!0},xc={description:r("Value nearest to a specific quartile of a dataset."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("quartile_number (number)",r("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Xl([e],.25*Math.trunc(Wi(t)),!0)},isExported:!0},yc={description:r("Nth smallest element in a data set."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("n (number)",r("The rank from smallest to largest of the element to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){const o=Math.trunc(Wi(t));let i,s=[],n=0;es([e],(e=>{"number"==typeof e&&(i=us(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(i+1,0,e),n++,n>o&&(s.pop(),n--))}));const a=s.pop();return Hi((()=>void 0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),Hi((()=>n>=o),r("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Ic={description:r("Standard deviation."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Nc.compute(...e))},isExported:!0},Rc={description:r("Standard deviation of entire population."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(_c.compute(...e))},isExported:!0},Tc={description:r("Standard deviation."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Fc.compute(...e))},isExported:!0},Ac={description:r("Standard deviation of sample (text as 0)."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Dc.compute(...e))},isExported:!0},Oc={description:r("Standard deviation of entire population."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Lc.compute(...e))},isExported:!0},Mc={description:r("Standard deviation of entire population (text as 0)."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Pc.compute(...e))},isExported:!0},Nc={description:r("Variance."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!0,!1)},isExported:!0},_c={description:r("Variance of entire population."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!1,!1)},isExported:!0},Fc={description:r("Variance."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!0,!1)},isExported:!0},Dc={description:r("Variance of sample (text as 0)."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!0,!0)},isExported:!0},Lc={description:r("Variance of entire population."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!1,!1)},isExported:!0},Pc={description:r("Variance of entire population (text as 0)."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!1,!0)},isExported:!0};var kc=Object.freeze({__proto__:null,AVEDEV:Kl,AVERAGE:Ql,AVERAGE_WEIGHTED:tc,AVERAGEA:oc,AVERAGEIF:ic,AVERAGEIFS:sc,COUNT:rc,COUNTA:nc,COVAR:ac,COVARIANCE_P:lc,COVARIANCE_S:cc,LARGE:hc,MAX:dc,MAXA:uc,MAXIFS:gc,MEDIAN:pc,MIN:mc,MINA:fc,MINIFS:bc,PERCENTILE:vc,PERCENTILE_EXC:Sc,PERCENTILE_INC:Cc,QUARTILE:Ec,QUARTILE_EXC:wc,QUARTILE_INC:xc,SMALL:yc,STDEV:Ic,STDEV_P:Rc,STDEV_S:Tc,STDEVA:Ac,STDEVP:Oc,STDEVPA:Mc,VAR:Nc,VAR_P:_c,VAR_S:Fc,VARA:Dc,VARP:Lc,VARPA:Pc});function Uc(e,t,o){const i=new Map,s=e.length;for(let t=s-1;t>=0;t--)i.set(ji(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(r("The field must be a number or a string"));let n;if("number"==typeof t){if(n=Math.trunc(t)-1,n<0||s-1<n)throw new Error(r("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),s.toString()))}else{const e=ji(t).toUpperCase();if(n=i.get(e)??-1,-1===n)throw new Error(r("The field (%s) must be one of %s.",ji(t),[...i.keys()].toString()))}const a=o[0].length;if(a<2)throw new Error(r("The criteria range contains %s row, it must be at least 2 rows.",a.toString()));let l=new Set;const c=e[0].length;for(let t=1;t<a;t++){let s=[],r=!0;for(let n=0;n<o.length;n++){const a=ji(o[n][0]).toUpperCase(),l=i.get(a),h=o[n][t];if(void 0!==h){if(void 0===l){r=!1;break}s.push([e[l].slice(1,c)]),s.push(h)}}if(r){if(!(s.length>0)){l=new Set(Array(c-1).keys());break}cs(s,((e,t)=>{l.add(t)}),!0)}}const h=e[n];return[...l].map((e=>h[e+1]))}const Vc=[za("database (range)",r("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.")),za("field (any)",r("Indicates which column in database contains the values to be extracted and operated on.")),za("criteria (range)",r("An array or range containing zero or more criteria to filter the database values by before operating."))],zc={description:r("Average of a set of values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Ql.compute([i])},isExported:!0},Bc={description:r("Counts values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return rc.compute([i])},isExported:!0},Hc={description:r("Counts values and text from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return nc.compute([i])},isExported:!0},$c={description:r("Single value from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Hi((()=>1===i.length),r("More than one match found in DGET evaluation.")),i[0]},isExported:!0},Wc={description:r("Maximum of values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return dc.compute([i])},isExported:!0},Gc={description:r("Minimum of values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return mc.compute([i])},isExported:!0},qc={description:r("Product of values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Ml.compute([i])},isExported:!0},Zc={description:r("Standard deviation of population sample from table."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Ic.compute([i])},isExported:!0},jc={description:r("Standard deviation of entire population from table."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Oc.compute([i])},isExported:!0},Yc={description:r("Sum of values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Bl.compute([i])},isExported:!0},Xc={description:r("Variance of population sample from table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Nc.compute([i])},isExported:!0},Kc={description:r("Variance of a population from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Lc.compute([i])},isExported:!0};var Qc=Object.freeze({__proto__:null,DAVERAGE:zc,DCOUNT:Bc,DCOUNTA:Hc,DGET:$c,DMAX:Wc,DMIN:Gc,DPRODUCT:qc,DSTDEV:Zc,DSTDEVP:jc,DSUM:Yc,DVAR:Xc,DVARP:Kc});var Jc;!function(e){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"}(Jc||(Jc={}));const eh={description:r("Converts year/month/day into a date."),args:[za("year (number)",r("The year component of the date.")),za("month (number)",r("The month component of the date.")),za("day (number)",r("The day component of the date."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){let i=Math.trunc(Wi(e));const s=Math.trunc(Wi(t)),n=Math.trunc(Wi(o));Hi((()=>0<=i&&i<=9999),r("The year (%s) must be between 0 and 9999 inclusive.",i.toString())),i<1900&&(i+=1900);const a=Te(new Date(i,s-1,n));return Hi((()=>a>=0),r("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},th={description:r("Calculates the number of days, months, or years between two dates."),args:[za("start_date (date)",r("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.")),za("end_date (date)",r("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.")),za("unit (string)",r('A text abbreviation for unit of time. Accepted values are "Y" (the number of whole years between start_date and end_date), "M" (the number of whole months between start_date and end_date), "D" (the number of days between start_date and end_date), "MD" (the number of days between start_date and end_date after subtracting whole months), "YM" (the number of whole months between start_date and end_date after subtracting whole years), "YD" (the number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart).'))],returns:["NUMBER"],compute:function(e,t,o){const i=ji(o).toUpperCase();Hi((()=>Object.values(Jc).includes(i)),((e,t)=>{const o=e.map((e=>`'${e}'`)).join(", ");return r("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,o)})(Object.values(Jc),ji(o)));const s=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Re(s),l=Re(n);switch(Hi((()=>n>=s),r("start_date (%s) should be on or before end_date (%s).",a.toLocaleDateString(),l.toLocaleDateString())),i){case Jc.WHOLE_YEARS:return Le(a,l);case Jc.WHOLE_MONTHS:return Fe(a,l);case Jc.WHOLE_DAYS:return De(a,l);case Jc.MONTH_WITHOUT_WHOLE_YEARS:return Fe(a,l)-12*Le(a,l);case Jc.DAYS_WITHOUT_WHOLE_MONTHS:let e=l.getDate()-a.getDate();if(e<0){e=Ae(new Date(l.getFullYear(),l.getMonth()-1,1))-Math.abs(e)}return e;case Jc.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return _e(e,t,1)<1}(s,n))return De(a,l);const e=new Date(a.getFullYear(),l.getMonth(),l.getDate());let t=De(a,e);return t<0&&(e.setFullYear(a.getFullYear()+1),t=De(a,e)),t}}},isExported:!0},oh={description:r("Converts a date string to a date value."),args:[za("date_string (string)",r("The string representing the date."))],returns:["NUMBER"],compute:function(e){const t=ji(e),o=ye(t);return Hi((()=>null!==o),r("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(o.value)},isExported:!0},ih={description:r("Day of the month that a specific date falls on."),args:[za("date (string)",r("The date from which to extract the day."))],returns:["NUMBER"],compute:function(e){return Qi(e).getDate()},isExported:!0},sh={description:r("Number of days between two dates."),args:[za("end_date (date)",r("The end of the date range.")),za("start_date (date)",r("The start of the date range."))],returns:["NUMBER"],compute:function(e,t){const o=Qi(e),i=Qi(t),s=o.getTime()-i.getTime();return Math.round(s/be)},isExported:!0},rh={description:r("Number of days between two dates on a 360-day year (months of 30 days)."),args:[za("start_date (date)",r("The start date to consider in the calculation.")),za("end_date (date)",r("The end date to consider in the calculation.")),za("method (number, default=0)",r("An indicator of what day count method to use. (0) US NASD method (1) European method"))],returns:["NUMBER"],compute:function(e,t,o=0){const i=Wi(e),s=Wi(t),r=Ki(o)?4:0,n=Ih.compute(e,t,r);return Math.sign(s-i)*Math.round(360*n)},isExported:!0},nh={description:r("Date a number of months before/after another date."),args:[za("start_date (date)",r("The date from which to calculate the result.")),za("months (number)",r("The number of months before (negative) or after (positive) 'start_date' to calculate."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){return Te(Me(Qi(e),Math.trunc(Wi(t)),!1))},isExported:!0},ah={description:r("Last day of a month before or after a date."),args:[za("start_date (date)",r("The date from which to calculate the result.")),za("months (number)",r("The number of months before (negative) or after (positive) 'start_date' to consider."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){const o=Qi(e),i=Math.trunc(Wi(t)),s=o.getFullYear(),r=o.getMonth();return Te(new Date(s,r+i+1,0))},isExported:!0},lh={description:r("Hour component of a specific time."),args:[za("time (date)",r("The time from which to calculate the hour component."))],returns:["NUMBER"],compute:function(e){return Qi(e).getHours()},isExported:!0},ch={description:r("ISO week number of the year."),args:[za("date (date)",r("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."))],returns:["NUMBER"],compute:function(e){const t=Qi(e),o=t.getFullYear();let i=1;for(;4!==new Date(o,0,i).getDay();)i+=1;const s=new Date(o,0,i-3);let r=31;for(;4!==new Date(o,11,r).getDay();)r-=1;const n=new Date(o,11,r+3);let a,l;switch(a=s.getTime()<=t.getTime()?t.getTime()<=n.getTime()?0:1:-1,a){case 0:l=s;break;case 1:l=new Date(o,11,r+3+1);break;case-1:let e=1;for(;4!==new Date(o-1,0,e).getDay();)e+=1;l=new Date(o-1,0,e-3)}const c=(t.getTime()-l.getTime())/be;return Math.floor(c/7)+1},isExported:!0},hh={description:r("Minute component of a specific time."),args:[za("time (date)",r("The time from which to calculate the minute component."))],returns:["NUMBER"],compute:function(e){return Qi(e).getMinutes()},isExported:!0},dh={description:r("Month of the year a specific date falls in"),args:[za("date (date)",r("The date from which to extract the month."))],returns:["NUMBER"],compute:function(e){return Qi(e).getMonth()+1},isExported:!0},uh={description:r("Net working days between two provided days."),args:[za("start_date (date)",r("The start date of the period from which to calculate the number of net working days.")),za("end_date (date)",r("The end date of the period from which to calculate the number of net working days.")),za("holidays (date, range<date>, optional)",r("A range or array constant containing the date serial numbers to consider holidays."))],returns:["NUMBER"],compute:function(e,t,o){return ph.compute(e,t,1,o)},isExported:!0};function gh(e){if("string"==typeof e){Hi((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),r('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let o=0;o<7;o++)"1"===e[o]&&t.push((o+1)%7);return t}if("number"==typeof e)return Hi((()=>1<=e&&e<=7||11<=e&&e<=17),r("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(r("The weekend must be a number or a string."))}const ph={description:r("Net working days between two dates (specifying weekends)."),args:[za("start_date (date)",r("The start date of the period from which to calculate the number of net working days.")),za("end_date (date)",r("The end date of the period from which to calculate the number of net working days.")),za("weekend (any, default=1)",r("A number or string representing which days of the week are considered weekends.")),za("holidays (date, range<date>, optional)",r("A range or array constant containing the dates to consider as holidays."))],returns:["NUMBER"],compute:function(e,t,o=1,i){const s=Qi(e),r=Qi(t),n=gh(o);let a=new Set;void 0!==i&&es([i],(e=>{const t=Qi(e);a.add(t.getTime())}));const l=s.getTime()>r.getTime(),c=new Date((l?s:r).getTime());let h=new Date((l?r:s).getTime());const d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)n.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},mh={description:r("Current date and time as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy hh:mm:ss",compute:function(){let e=new Date;e.setMilliseconds(0);const t=e.getTime()-fe.getTime(),o=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/be)+o},isExported:!0},fh={description:r("Minute component of a specific time."),args:[za("time (date)",r("The time from which to calculate the second component."))],returns:["NUMBER"],compute:function(e){return Qi(e).getSeconds()},isExported:!0},bh={description:r("Converts hour/minute/second into a time."),args:[za("hour (number)",r("The hour component of the time.")),za("minute (number)",r("The minute component of the time.")),za("second (number)",r("The second component of the time."))],returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,o){let i=Math.trunc(Wi(e)),s=Math.trunc(Wi(t)),n=Math.trunc(Wi(o));return s+=Math.floor(n/60),n=n%60+(n<0?60:0),i+=Math.floor(s/60),s=s%60+(s<0?60:0),i%=24,Hi((()=>i>=0),r("The function [[FUNCTION_NAME]] result cannot be negative")),i/24+s/1440+n/86400},isExported:!0},vh={description:r("Converts a time string into its serial number representation."),args:[za("time_string (string)",r("The string that holds the time representation."))],returns:["NUMBER"],compute:function(e){const t=ji(e),o=ye(t);Hi((()=>null!==o),r("The time_string (%s) cannot be parsed to date/time.",t));const i=o.value-Math.trunc(o.value);return i<0?1+i:i},isExported:!0},Sh={description:r("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=new Date;return Te(new Date(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Ch={description:r("Day of the week of the date provided (as number)."),args:[za("date (date)",r("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.")),za("type (number, default=1)",r("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const o=Qi(e),i=Math.round(Wi(t)),s=o.getDay();return Hi((()=>[1,2,3].includes(i)),r("The type (%s) must be 1, 2 or 3.",i.toString())),1===i?s+1:2===i?0===s?7:s:0===s?6:s-1},isExported:!0},Eh={description:r("Week number of the year."),args:[za("date (date)",r("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.")),za("type (number, default=1)",r("A number representing the day that a week starts on. Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const o=Qi(e),i=Math.round(Wi(t));if(Hi((()=>1===i||2===i||11<=i&&i<=17||21===i),r("The type (%s) is out of range.",i.toString())),21===i)return ch.compute(e);let s;s=1===i||2===i?i-1:i-10==7?0:i-10;const n=o.getFullYear();let a=1,l=new Date(n,0,a);for(;l.getDay()!==s;)a+=1,l=new Date(n,0,a);const c=(o.getTime()-l.getTime())/be;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},wh={description:r("Date after a number of workdays."),args:[za("start_date (date)",r("The date from which to begin counting.")),za("num_days (number)",r("The number of working days to advance from start_date. If negative, counts backwards.")),za("holidays (date, range<date>, optional)",r("A range or array constant containing the dates to consider holidays."))],returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){return xh.compute(e,t,1,o)},isExported:!0},xh={description:r("Date after a number of workdays (specifying weekends)."),args:[za("start_date (date)",r("The date from which to begin counting.")),za("num_days (number)",r("The number of working days to advance from start_date. If negative, counts backwards.")),za("weekend (any, default=1)",r("A number or string representing which days of the week are considered weekends.")),za("holidays (date, range<date>, optional)",r("A range or array constant containing the dates to consider holidays."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o=1,i){let s=Qi(e),n=Math.trunc(Wi(t));"string"==typeof o&&Hi((()=>"1111111"!==o),r("The weekend (%s) must be different from '1111111'.",o));const a=gh(o);let l=new Set;void 0!==i&&es([i],(e=>{const t=Qi(e);l.add(t.getTime())}));let c=new Date(s.getTime()),h=c.getTime();const d=Math.sign(n);let u=Math.abs(n);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),a.includes(c.getDay())||l.has(h)||(u-=1);const g=h-fe.getTime();return Math.round(g/be)},isExported:!0},yh={description:r("Year specified by a given date."),args:[za("date (date)",r("The date from which to extract the year."))],returns:["NUMBER"],compute:function(e){return Qi(e).getFullYear()},isExported:!0},Ih={description:r("Exact number of years between two dates."),args:[za("start_date (date)",r("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.")),za("end_date (date)",r("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.")),za("day_count_convention (number, default=0)",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o=0){let i=Math.trunc(Wi(e)),s=Math.trunc(Wi(t));const n=Math.trunc(Wi(o));return Hi((()=>i>=0),r("The start_date (%s) must be positive or null.",i.toString())),Hi((()=>s>=0),r("The end_date (%s) must be positive or null.",s.toString())),Hi((()=>0<=n&&n<=4),r("The day_count_convention (%s) must be between 0 and 4 inclusive.",n.toString())),_e(i,s,n)}},Rh={description:r("First day of the month preceding a date."),args:[za("date (date)",r("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Qi(e),o=t.getFullYear(),i=t.getMonth();return Te(new Date(o,i,1))}},Th={description:r("Last day of the month following a date."),args:[za("date (date)",r("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return ah.compute(e,0)}},Ah={description:r("Quarter of the year a specific date falls in"),args:[za("date (date)",r("The date from which to extract the quarter."))],returns:["NUMBER"],compute:function(e){return Math.ceil((Qi(e).getMonth()+1)/3)}},Oh={description:r("First day of the quarter of the year a specific date falls in."),args:[za("date (date)",r("The date from which to calculate the start of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Ah.compute(e),o=yh.compute(e);return Te(new Date(o,3*(t-1),1))}},Mh={description:r("Last day of the quarter of the year a specific date falls in."),args:[za("date (date)",r("The date from which to calculate the end of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Ah.compute(e),o=yh.compute(e);return Te(new Date(o,3*t,0))}},Nh={description:r("First day of the year a specific date falls in."),args:[za("date (date)",r("The date from which to calculate the start of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=yh.compute(e);return Te(new Date(t,0,1))}},_h={description:r("Last day of the year a specific date falls in."),args:[za("date (date)",r("The date from which to calculate the end of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=yh.compute(e);return Te(new Date(t+1,0,0))}};var Fh=Object.freeze({__proto__:null,DATE:eh,DATEDIF:th,DATEVALUE:oh,DAY:ih,DAYS:sh,DAYS360:rh,EDATE:nh,EOMONTH:ah,HOUR:lh,ISOWEEKNUM:ch,MINUTE:hh,MONTH:dh,NETWORKDAYS:uh,NETWORKDAYS_INTL:ph,NOW:mh,SECOND:fh,TIME:bh,TIMEVALUE:vh,TODAY:Sh,WEEKDAY:Ch,WEEKNUM:Eh,WORKDAY:wh,WORKDAY_INTL:xh,YEAR:yh,YEARFRAC:Ih,MONTH_START:Rh,MONTH_END:Th,QUARTER:Ah,QUARTER_START:Oh,QUARTER_END:Mh,YEAR_START:Nh,YEAR_END:_h});const Dh={description:r("Compare two numeric values, returning 1 if they're equal."),args:[za(" (number)",r("The first number to compare.")),za(" (number, default=0)",r("The second number to compare."))],returns:["NUMBER"],compute:function(e,t=0){return Wi(e)===Wi(t)?1:0},isExported:!0};var Lh=Object.freeze({__proto__:null,DELTA:Dh});function Ph(e,t){Hi((()=>e<t),r("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function kh(e,t){Hi((()=>t<e),r("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function Uh(e){Hi((()=>[1,2,4].includes(e)),r("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function Vh(e){Hi((()=>0<=e&&e<=4),r("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function zh(e){Hi((()=>e>0),r("The redemption (%s) must be strictly positive.",e.toString()))}function Bh(e){Hi((()=>e>0),r("The price (%s) must be strictly positive.",e.toString()))}function Hh(e){Hi((()=>e>0),r("The number_of_periods (%s) must be greater than 0.",e.toString()))}function $h(e){Hi((()=>e>0),r("The rate (%s) must be strictly positive.",e.toString()))}function Wh(e){Hi((()=>e>0),r("The life (%s) must be strictly positive.",e.toString()))}function Gh(e){Hi((()=>e>=0),r("The cost (%s) must be positive or null.",e.toString()))}function qh(e){Hi((()=>e>0),r("The period (%s) must be strictly positive.",e.toString()))}function Zh(e){Hi((()=>e>=0),r("The salvage (%s) must be positive or null.",e.toString()))}function jh(e){Hi((()=>e>0),r("The present value (%s) must be strictly positive.",e.toString()))}function Yh(e,t){Hi((()=>e<=t),r("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function Xh(e){Hi((()=>e>0),r("The investment (%s) must be strictly positive.",e.toString()))}function Kh(e){Hi((()=>e>0),r("The discount (%s) must be strictly positive.",e.toString()))}function Qh(e){Hi((()=>e<1),r("The discount (%s) must be smaller than 1.",e.toString()))}function Jh(e){Hi((()=>e>0),r("The depreciation factor (%s) must be strictly positive.",e.toString()))}function ed(e,t){const o=Qi(e),i=Qi(t),s=new Date(o);s.setFullYear(o.getFullYear()+1),Hi((()=>i.getTime()<=s.getTime()),r("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function td(e,t,o){Hh(o),Hi((()=>e>0),r("The first_period (%s) must be strictly positive.",e.toString())),Hi((()=>t>0),r("The last_period (%s) must be strictly positive.",t.toString())),Hi((()=>e<=t),r("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),Hi((()=>t<=o),r("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),o.toString()))}function od(e){Hi((()=>e>-1),r("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function id(e,t){Hi((()=>e.length===t.length&&e[0].length===t[0].length),r("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function sd(e){Hi((()=>e.every((t=>t>=e[0]))),r("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const rd=[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))];function nd(e,t,o,i,s=1e-10,n){let a,l,c,h,d=o,u=!1,g=0;do{c=e(d),isNaN(c)?(Hi((()=>g<i&&void 0!==n),r("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=n(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<s||Math.abs(c)<s,Hi((()=>g<i),r("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const ad={description:r("Accrued interest of security paying at maturity."),args:[za("issue (date)",r("The date the security was initially issued.")),za("maturity (date)",r("The maturity date of the security.")),za("rate (number)",r("The annualized rate of interest.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(i),l=Wi(o),c=Math.trunc(Wi(s));kh(n,r),Vh(c),zh(a),$h(l);return a*l*Ih.compute(r,n,s)},isExported:!0},ld={description:r("Depreciation for an accounting period."),args:[za("cost (number)",r("The initial cost of the asset.")),za("purchase_date (date)",r("The date the asset was purchased.")),za("first_period_end (date)",r("The date the first period ended.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("period (number)",r("The single period within life for which to calculate depreciation.")),za("rate (number)",r("The deprecation rate.")),za(" (number, optional)",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n,a=0){a=a||0;const l=Wi(e),c=Math.trunc(Wi(t)),h=Math.trunc(Wi(o)),d=Wi(i),u=Wi(s),g=Wi(n),p=Math.trunc(Wi(a));!function(e){Hi((()=>e>0),r("The cost (%s) must be strictly positive.",e.toString()))}(l),Zh(d),function(e,t){Hi((()=>e<=t),r("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){Hi((()=>e>=0),r("The period (%s) must be positive or null.",e.toString()))}(u),$h(g),Vh(p),Hi((()=>c<=h),r("The purchase_date (%s) must be before the first_period_end (%s).",c.toString(),h.toString()));const m=u<1&&u>0?1:Math.trunc(u),f=l*g,b=Ih.compute(c,h,p),v=c===h?f:f*b,S=l-v-f*m;return S>=d?0===m?v:f:d-S<f?f-(d-S):0},isExported:!0},cd={description:r("Days in coupon period containing settlement date."),args:rd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));if(Ph(s,r),Uh(n),Vh(a),1===a){const s=pd.compute(e,t,o,i);return ud.compute(e,t,o,i)-s}return(3===a?365:360)/n},isExported:!0},hd={description:r("Days from settlement until next coupon."),args:rd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));Ph(s,r),Uh(n),Vh(a);const l=pd.compute(s,r,o,i);if([1,2,3].includes(a))return s-l;if(4===a){const e=_e(l,s,a);return Math.round(360*e)}const c=Qi(s),h=Qi(l),d=h.getFullYear(),u=c.getFullYear(),g=h.getMonth()+1,p=c.getMonth()+1;let m=h.getDate(),f=c.getDate();return 2===g&&2===p&&Oe(h)&&Oe(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&Oe(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},dd={description:r("Days from settlement until next coupon."),args:rd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));Ph(s,r),Uh(n),Vh(a);const l=ud.compute(s,r,o,i);if([1,2,3].includes(a))return l-s;if(4===a){const e=_e(s,l,a);return Math.round(360*e)}const c=hd.compute(e,t,o,a);return cd.compute(e,t,o,a)-c},isExported:!0},ud={description:r("Next coupon date after the settlement date."),args:rd,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));Ph(s,r),Uh(n),Vh(a);const l=12/n,c=gd.compute(e,t,o,i);return Te(Me(Qi(r),-(c-1)*l,!0))},isExported:!0},gd={description:r("Number of coupons between settlement and maturity."),args:rd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));Ph(s,r),Uh(n),Vh(a);let l=1,c=r;const h=12/n;for(;c>s;)c=Te(Me(Qi(c),-h,!1)),l++;return l-1},isExported:!0},pd={description:r("Last coupon date prior to or on the settlement date."),args:rd,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));Ph(s,r),Uh(n),Vh(a);const l=12/n,c=gd.compute(e,t,o,i);return Te(Me(Qi(r),-c*l,!0))},isExported:!0},md={description:r("Cumulative interest paid over a set of periods."),args:[za("rate (number)",r("The interest rate.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity.")),za("first_period (number)",r("The number of the payment period to begin the cumulative calculation.")),za("last_period (number)",r("The number of the payment period to end the cumulative calculation.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){const n=Wi(i),a=Wi(s),l=Wi(e),c=Wi(o),h=Wi(t);td(n,a,h),$h(l),jh(c);let d=0;for(let t=n;t<=a;t++){d+=Td.compute(e,t,h,o,0,r)}return d},isExported:!0},fd={description:r("Cumulative principal paid over a set of periods."),args:[za("rate (number)",r("The interest rate.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity.")),za("first_period (number)",r("The number of the payment period to begin the cumulative calculation.")),za("last_period (number)",r("The number of the payment period to end the cumulative calculation.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){const n=Wi(i),a=Wi(s),l=Wi(e),c=Wi(o),h=Wi(t);td(n,a,h),$h(l),jh(c);let d=0;for(let t=n;t<=a;t++){d+=kd.compute(e,t,h,o,0,r)}return d},isExported:!0},bd={description:r("Depreciation via declining balance method."),args:[za("cost (number)",r("The initial cost of the asset.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("life (number)",r("The number of periods over which the asset is depreciated.")),za("period (number)",r("The single period within life for which to calculate depreciation.")),za("month (number, optional)",r("The number of months in the first year of depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,...s){const n=Wi(e),a=Wi(t),l=Wi(o),c=Math.trunc(Wi(i)),h=s.length?Math.trunc(Wi(s[0])):12,d=l+(12===h?0:1);Gh(n),Zh(a),qh(c),Wh(l),Hi((()=>1<=h&&h<=12),r("The month (%s) must be between 1 and 12 inclusive.",h.toString())),Hi((()=>c<=d),r("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let g=1-Math.pow(a/n,1/l);g=Math.round(1e3*g)/1e3;let p=n,m=n*(1-g*u);for(let e=1;e<c;e++)p=m,m=p*(1-g),e===l&&(m=p*(1-g*(1-u)));return p-m},isExported:!0},vd={description:r("Depreciation via double-declining balance method."),args:[za("cost (number)",r("The initial cost of the asset.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("life (number)",r("The number of periods over which the asset is depreciated.")),za("period (number)",r("The single period within life for which to calculate depreciation.")),za("factor (number, default=2)",r("The factor by which depreciation decreases."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=2){s=s||0;const r=Wi(e),n=Wi(t),a=Wi(o),l=Wi(i),c=Wi(s);if(Gh(r),Zh(n),qh(l),Wh(a),Yh(l,a),Jh(c),0===r||n>=r)return 0;const h=c/a;if(h>1)return 1===i?r-n:0;if(l<=1)return r*h;const d=r*Math.pow(1-h,l-1),u=r*Math.pow(1-h,l),g=u<n?d-n:d-u;return Math.max(g,0)},isExported:!0},Sd={description:r("Discount rate of a security based on price."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("price (number)",r("The price at which the security is bought per 100 face value.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(o),l=Wi(i),c=Math.trunc(Wi(s));Ph(r,n),Vh(c),Bh(a),zh(l);return(l-a)/l/Ih.compute(r,n,c)},isExported:!0},Cd={description:r("Convert a decimal fraction to decimal value."),args:[za("fractional_price (number)",r("The price quotation given using fractional decimal conventions.")),za("unit (number)",r("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const o=Wi(e),i=Math.trunc(Wi(t));Hi((()=>i>0),r("The unit (%s) must be strictly positive.",i.toString()));const s=Math.trunc(o);return s+(o-s)*(10**Math.ceil(Math.log10(i))/i)},isExported:!0},Ed={description:r("Convert a decimal value to decimal fraction."),args:[za("decimal_price (number)",r("The price quotation given as a decimal value.")),za("unit (number)",r("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const o=Wi(e),i=Math.trunc(Wi(t));Hi((()=>i>0),r("The unit (%s) must be strictly positive.",i.toString()));const s=Math.trunc(o);return s+(o-s)*(i/10**Math.ceil(Math.log10(i)))},isExported:!0},wd={description:r("Number of periods for an investment to reach a value."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("rate (number)",r("The annualized rate of interest.")),za("yield (number)",r("The expected annual yield of the security.")),za("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){n=n||0;const a=Math.trunc(Wi(e)),l=Math.trunc(Wi(t)),c=Wi(o),h=Wi(i),d=Math.trunc(Wi(s)),u=Math.trunc(Wi(n));Ph(a,l),Uh(d),Vh(u),Hi((()=>c>=0),r("The rate (%s) must be positive or null.",c.toString())),Hi((()=>h>=0),r("The yield (%s) must be positive or null.",h.toString()));const g=Ih.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,b=h/d;let v=0,S=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+b)**e;S+=(p+(e-1)/d)*t,v+=t}return 0===v?0:S/v},isExported:!0},xd={description:r("Annual effective interest rate."),args:[za("nominal_rate (number)",r("The nominal interest rate per year.")),za("periods_per_year (number)",r("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Wi(e),i=Math.trunc(Wi(t));return Hi((()=>o>0),r("The nominal rate (%s) must be strictly greater than 0.",o.toString())),Hi((()=>i>0),r("The number of periods by year (%s) must strictly greater than 0.",i.toString())),Math.pow(1+o/i,i)-1},isExported:!0},yd={description:r("Future value of an annuity investment."),args:[za("rate (number)",r("The interest rate.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("payment_amount (number)",r("The amount per period to be paid.")),za("present_value (number, default=0)",r("The current value of the annuity.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const r=Wi(e),n=Wi(t),a=Wi(o),l=Wi(i),c=Ki(s)?1:0;return r?-l*(1+r)**n-a*(1+r*c)*((1+r)**n-1)/r:-(l+a*n)},isExported:!0},Id={description:r("Future value of principal from series of rates."),args:[za("principal (number)",r("The amount of initial capital or value to compound against.")),za("rate_schedule (number, range<number>)",r("A series of interest rates to compound against the principal."))],returns:["NUMBER"],compute:function(e,t){return is([t],((e,t)=>e*(1+Wi(t))),Wi(e))},isExported:!0},Rd={description:r("Calculates effective interest rate."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("investment (number)",r("The amount invested in the security.")),za("redemption (number)",r("The amount to be received at maturity.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(i),l=Wi(o);Ph(r,n),Xh(l),zh(a);return(a-l)/l/Ih.compute(r,n,s)},isExported:!0},Td={description:r("Payment on the principal of an investment."),args:[za("rate (number)",r("The annualized rate of interest.")),za("period (number)",r("The amortization period, in terms of number of periods.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=0,r=0){return Pd.compute(e,o,i,s,r)-kd.compute(e,t,o,i,s,r)},isExported:!0},Ad={description:r("Internal rate of return given periodic cashflows."),args:[za("cashflow_amounts (number, range<number>)",r("An array or range containing the income or payments associated with the investment.")),za("rate_guess (number, default=0.1)",r("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const o=Wi(t);od(o);let i=!1,s=!1,n=[];ts([e],(e=>{e>0&&(i=!0),e<0&&(s=!0),n.push(e)})),Hi((()=>i&&s),r("The cashflow_amounts must include negative and positive values."));const a=n.shift();return nd((function(e){return function(e,t,o){const i=o.length;let s=0;return o.reduce(((t,o)=>(s++,t+o*e**(i-s))),t*e**i)}(e,a,n)}),(function(e){return function(e,t,o){const i=o.length;let s=0;return o.reduce(((t,o)=>(s++,t+o*(i-s)*e**(i-s-1))),t*i*e**(i-1))}(e,a,n)}),o+1,20,1e-5)-1},isExported:!0},Od={description:r("Returns the interest paid at a particular period of an investment."),args:[za("rate (number)",r("The interest rate.")),za("period (number)",r("The period for which you want to view the interest payment.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity."))],returns:["NUMBER"],compute:function(e,t,o,i){const s=Wi(e),n=Wi(t),a=Wi(o),l=Wi(i);Hi((()=>0!==a),r("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(n/a))*s},isExported:!0},Md={description:r("Modified Macaulay duration."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("rate (number)",r("The annualized rate of interest.")),za("yield (number)",r("The expected annual yield of the security.")),za("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){return wd.compute(e,t,o,i,s,r)/(1+Wi(i)/Math.trunc(Wi(s)))},isExported:!0},Nd={description:r("Modified internal rate of return."),args:[za("cashflow_amounts (range<number>)",r("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),za("financing_rate (number)",r("The interest rate paid on funds invested.")),za("reinvestment_return_rate (number)",r("The return (as a percentage) earned on reinvestment of income received from the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Wi(t),s=Wi(o),n=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(lt).map(Wi);var a;const l=n.length;let c=0,h=0;for(const e of je(0,l)){const t=n[e];t>=0?c+=t*(s+1)**(l-e-1):h+=t/(i+1)**e}Hi((()=>0!==h&&0!==c),r("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},_d={description:r("Annual nominal interest rate."),args:[za("effective_rate (number)",r("The effective interest rate per year.")),za("periods_per_year (number)",r("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Wi(e),i=Math.trunc(Wi(t));return Hi((()=>o>0),r("The effective rate (%s) must must strictly greater than 0.",o.toString())),Hi((()=>i>0),r("The number of periods by year (%s) must strictly greater than 0.",i.toString())),(Math.pow(o+1,1/i)-1)*i},isExported:!0},Fd={description:r("Number of payment periods for an investment."),args:[za("rate (number)",r("The interest rate.")),za("payment_amount (number)",r("The amount of each payment made.")),za("present_value (number)",r("The current value of the annuity.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const r=Wi(e),n=Wi(t),a=Wi(o),l=Wi(i),c=Ki(s)?1:0;if(0===r)return-(l+a)/n;const h=n*(1+r*c)/r;return Math.log((h-l)/(a+h))/Math.log(1+r)},isExported:!0};const Dd={description:r("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[za("discount (number)",r("The discount rate of the investment over one period.")),za("cashflow1 (number, range<number>)",r("The first future cash flow.")),za("cashflow2 (number, range<number>, repeating)",r("Additional future cash flows."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const o=Wi(e);return Hi((()=>-1!==o),r("The discount (%s) must be different from -1.",o.toString())),function(e,t,o){let i=0;return ss(o,((t,o)=>(i++,t+o/(1+e)**i)),t)}(o,0,t)},isExported:!0},Ld={description:r("Computes the number of periods needed for an investment to reach a value."),args:[za("rate (number)",r("The rate at which the investment grows each period.")),za("present_value (number)",r("The investment's current value.")),za("future_value (number)",r("The investment's desired future value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Wi(e),s=Wi(t),n=Wi(o);return $h(i),Hi((()=>s>0),r("The present_value (%s) must be strictly positive.",s.toString())),Hi((()=>n>0),r("The future_value (%s) must be strictly positive.",n.toString())),(Math.log(n)-Math.log(s))/Math.log(1+i)},isExported:!0},Pd={description:r("Periodic payment for an annuity investment."),args:[za("rate (number)",r("The annualized rate of interest.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const r=Wi(t),n=Wi(e),a=Ki(s)?1:0;let l=Wi(i),c=Wi(o);if(Hh(r),0===n)return-(l+c)/r;let h=-(c*(1+n)**r+l);return h=h*n/((1+n*a)*((1+n)**r-1)),h},isExported:!0},kd={description:r("Payment on the principal of an investment."),args:[za("rate (number)",r("The annualized rate of interest.")),za("period (number)",r("The amortization period, in terms of number of periods.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=0,n=0){s=s||0,n=n||0;const a=Wi(o),l=Wi(e),c=Wi(t),h=Ki(n)?1:0,d=Wi(s),u=Wi(i);Hh(a),Hi((()=>c>0&&c<=a),r("The period must be between 1 and number_of_periods",a.toString()));const g=Pd.compute(l,a,u,d,n);if(1===h&&1===c)return g;return g+-yd.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},Ud={description:r("Present value of an annuity investment."),args:[za("rate (number)",r("The interest rate.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("payment_amount (number)",r("The amount per period to be paid.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const r=Wi(e),n=Wi(t),a=Wi(o),l=Wi(i),c=Ki(s)?1:0;return r?-(a*(1+r*c)*((1+r)**n-1)/r+l)/(1+r)**n:-(l+a*n)},isExported:!0},Vd={description:r("Price of a security paying periodic interest."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("rate (number)",r("The annualized rate of interest.")),za("yield (number)",r("The expected annual yield of the security.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n,a=0){a=a||0;const l=Math.trunc(Wi(e)),c=Math.trunc(Wi(t)),h=Wi(o),d=Wi(i),u=Wi(s),g=Math.trunc(Wi(n)),p=Math.trunc(Wi(a));Ph(l,c),Uh(g),Vh(p),Hi((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Hi((()=>d>=0),r("The yield (%s) must be positive or null.",d.toString())),zh(u);const m=Ih.compute(l,c,p)*g,f=Math.ceil(m),b=m-Math.floor(m)||1,v=1+d/g,S=100*h/g;if(1===f)return(S+u)/(b*d/g+1)-S*(1-b);let C=0;for(let e=1;e<=f;e++)C+=S/v**(e-1+b);return u/v**(f-1+b)+C-S*(1-b)},isExported:!0},zd={description:r("Price of a discount security."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("discount (number)",r("The discount rate of the security at time of purchase.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(o),l=Wi(i),c=Math.trunc(Wi(s));Ph(r,n),Vh(c),Kh(a),zh(l);return l-a*l*Ih.compute(r,n,c)},isExported:!0},Bd={description:r("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("issue (date)",r("The date the security was initially issued.")),za("rate (number)",r("The annualized rate of interest.")),za("yield (number)",r("The expected annual yield of the security.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){n=n||0;const a=Math.trunc(Wi(e)),l=Math.trunc(Wi(t)),c=Math.trunc(Wi(o)),h=Wi(i),d=Wi(s),u=Math.trunc(Wi(n));kh(a,c),Ph(a,l),Vh(u),Hi((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Hi((()=>d>=0),r("The yield (%s) must be positive or null.",d.toString()));const g=Ih.compute(a,l,u),p=Ih.compute(a,c,u);return(100+Ih.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},Hd=.1,$d={description:r("Interest rate of an annuity investment."),args:[za("number_of_periods (number)",r("The number of payments to be made.")),za("payment_per_period (number)",r("The amount per period to be paid.")),za("present_value (number)",r("The current value of the annuity.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period.")),za("rate_guess (number, default=0.1)",r("An estimate for what the interest rate will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,o,i=0,s=0,n=.1){i=i||0,s=s||0,n=n||Hd;const a=Wi(e),l=Wi(t),c=Ki(s)?1:0,h=Wi(n);let d=Wi(i),u=Wi(o);Hh(a),Hi((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),r("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),od(h),d-=l*c,u+=l*c;return nd((e=>{const t=Math.pow(1+e,a);return d+u*t+l*((t-1)/e)}),(e=>{const t=Math.pow(1+e,a-1),o=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(o-1)/e/e)}),h,40,1e-5)},isExported:!0},Wd={description:r("Amount received at maturity for a security."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("investment (number)",r("The amount invested (irrespective of face value of each security).")),za("discount (number)",r("The discount rate of the security invested in.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(o),l=Wi(i),c=Math.trunc(Wi(s));Ph(r,n),Vh(c),Xh(a),Kh(l);return a/(1-l*Ih.compute(r,n,c))},isExported:!0},Gd={description:r("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[za("number_of_periods (number)",r("The number of periods.")),za("present_value (number)",r("The present value of the investment.")),za("future_value (number)",r("The future value of the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Wi(e),s=Wi(t),r=Wi(o);return Hh(i),(r/s)**(1/i)-1},isExported:!0},qd={description:r("Depreciation of an asset using the straight-line method."),args:[za("cost (number)",r("The initial cost of the asset.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("life (number)",r("The number of periods over which the asset is depreciated."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o){return(Wi(e)-Wi(t))/Wi(o)},isExported:!0},Zd={description:r("Depreciation via sum of years digit method."),args:[za("cost (number)",r("The initial cost of the asset.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("life (number)",r("The number of periods over which the asset is depreciated.")),za("period (number)",r("The single period within life for which to calculate depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i){const s=Wi(e),r=Wi(t),n=Wi(o),a=Wi(i);qh(a),Wh(n),Yh(a,n);return(n-a+1)/(n*(n+1)/2)*(s-r)},isExported:!0},jd={description:r("Price of a US Treasury bill."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("discount (number)",r("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Wi(e)),s=Math.trunc(Wi(t)),r=Wi(o);Ph(i,s),ed(i,s),Kh(r),Qh(r);return 100*(1-r*Ih.compute(i,s,2))},isExported:!0},Yd={description:r("Equivalent rate of return for a US Treasury bill."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("discount (number)",r("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Wi(e)),s=Math.trunc(Wi(t)),r=Wi(o);Ph(i,s),ed(i,s),Kh(r),Qh(r);const n=sh.compute(s,i);if(n<=182)return 365*r/(360-r*n);const a=jd.compute(i,s,r)/100,l=n/(366===n?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},Xd={description:r("The yield of a US Treasury bill based on price."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("price (number)",r("The price at which the security is bought per 100 face value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Wi(e)),s=Math.trunc(Wi(t)),r=Wi(o);Ph(i,s),ed(i,s),Bh(r);return(100-r)/r*(1/Ih.compute(i,s,2))},isExported:!0},Kd={description:r("Variable declining balance. WARNING : does not handle decimal periods."),args:[za("cost (number)",r("The initial cost of the asset.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("life (number)",r("The number of periods over which the asset is depreciated.")),za("start (number)",r("Starting period to calculate depreciation.")),za("end (number)",r("Ending period to calculate depreciation.")),za("factor (number, default=2)",r("The number of months in the first year of depreciation.")),za("no_switch (number, default=false)",r("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=2,a=false){n=n||0;const l=Wi(e),c=Wi(t),h=Wi(o),d=Math.trunc(Wi(i)),u=Math.trunc(Wi(s)),g=Wi(n),p=Ki(a);if(Gh(l),Zh(c),function(e,t,o){Wh(o),Hi((()=>e>=0),r("The start_period (%s) must be greater or equal than 0.",e.toString())),Hi((()=>t>=0),r("The end_period (%s) must be greater or equal than 0.",t.toString())),Hi((()=>e<=t),r("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),Hi((()=>t<=o),r("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),o.toString()))}(d,u,h),Jh(g),0===l)return 0;if(c>=l)return d<1?l-c:0;const m=g/h;if(m>=1)return d<1?l-c:0;let f=l,b=0,v=0,S=!1;for(let e=0;e<u;e++){if(!S||p){const t=f*m,o=(f-c)/(h-e);!p&&o>t?(S=!0,b=o):b=t}const t=Math.max(f-b,c);e>=d&&(v+=f-t),f=t}return v},isExported:!0},Qd={description:r("Internal rate of return given non-periodic cash flows."),args:[za("cashflow_amounts (range<number>)",r("An range containing the income or payments associated with the investment.")),za("cashflow_dates (range<number>)",r("An range with dates corresponding to the cash flows in cashflow_amounts.")),za("rate_guess (number, default=0.1)",r("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],compute:function(e,t,o=.1){const i=Wi(o=o||0),s=e.flat().map(Wi),n=t.flat().map(Wi);var a;id(e,t),a=s,Hi((()=>a.some((e=>e>0))&&a.some((e=>e<0))),r("There must be both positive and negative values in cashflow_amounts.")),sd(n),od(i);const l=new Map;for(const e of je(0,n.length)){const t=n[e];l.has(t)?l.set(t,l.get(t)+s[e]):l.set(t,s[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return nd((e=>{let t=h[0];for(const o of je(1,h.length)){const i=(c[0]-c[o])/365;t+=h[o]*(1+e)**i}return t}),(e=>{let t=0;for(const o of je(1,h.length)){const i=(c[0]-c[o])/365;t+=i*h[o]*(1+e)**(i-1)}return t}),i,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},Jd={description:r("Net present value given to non-periodic cash flows.."),args:[za("discount (number)",r("The discount rate of the investment over one period.")),za("cashflow_amounts (number, range<number>)",r("An range containing the income or payments associated with the investment.")),za("cashflow_dates (number, range<number>)",r("An range with dates corresponding to the cash flows in cashflow_amounts."))],returns:["NUMBER"],compute:function(e,t,o){const i=Wi(e),s=Array.isArray(t)?t.flat().map(Gi):[Gi(t)],n=Array.isArray(o)?o.flat().map(Gi):[Gi(o)];if(Array.isArray(o)&&Array.isArray(t)?id(t,o):Hi((()=>s.length===n.length),r("There must be the same number of values in cashflow_amounts and cashflow_dates.")),sd(n),$h(i),1===s.length)return s[0];const a=new Map;for(const e of je(0,n.length)){const t=n[e];a.has(t)?a.set(t,a.get(t)+s[e]):a.set(t,s[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of je(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+i)**t}return h},isExported:!0},eu={description:r("Annual yield of a security paying periodic interest."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("rate (number)",r("The annualized rate of interest.")),za("price (number)",r("The price at which the security is bought per 100 face value.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n,a=0){a=a||0;const l=Math.trunc(Wi(e)),c=Math.trunc(Wi(t)),h=Wi(o),d=Wi(i),u=Wi(s),g=Math.trunc(Wi(n)),p=Math.trunc(Wi(a));Ph(l,c),Uh(g),Vh(p),Hi((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Bh(d),zh(u);const m=Ih.compute(l,c,p)*g,f=Math.ceil(m),b=m-Math.floor(m)||1,v=100*h/g;if(1===f){const e=d+v*(1-b);return(u+v-e)*g*(1/b)/e}const S=nd((function(e){return function(e,t,o,i,s,r){let n=r-(e+s*(1-t))*i**(o-1+t);for(let e=1;e<=o;e++)n+=s*i**(e-1);return n}(d,b,f,e,v,u)}),(function(e){return function(e,t,o,i,s){let r=-(e+s*(1-t))*(o-1+t)*i**(o-2+t);for(let e=1;e<=o;e++)r+=s*(e-1)*i**(e-2);return r}(d,b,f,e,v)}),1+(h+1)/g,100,1e-5);return(S-1)*g},isExported:!0},tu={description:r("Annual yield of a discount security."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("price (number)",r("The price at which the security is bought per 100 face value.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(o),l=Wi(i),c=Math.trunc(Wi(s));Ph(r,n),Vh(c),Bh(a),zh(l);return(l/a-1)/Ih.compute(e,t,s)},isExported:!0},ou={description:r("Annual yield of a security paying interest at maturity."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("issue (date)",r("The date the security was initially issued.")),za("rate (number)",r("The annualized rate of interest.")),za("price (number)",r("The price at which the security is bought.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){n=n||0;const a=Math.trunc(Wi(e)),l=Math.trunc(Wi(t)),c=Math.trunc(Wi(o)),h=Wi(i),d=Wi(s),u=Math.trunc(Wi(n));Ph(a,l),Vh(u),Hi((()=>a>=c),r("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),Hi((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Bh(d);const g=Ih.compute(c,l,u),p=Ih.compute(c,a,u),m=Ih.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var iu=Object.freeze({__proto__:null,ACCRINTM:ad,AMORLINC:ld,COUPDAYS:cd,COUPDAYBS:hd,COUPDAYSNC:dd,COUPNCD:ud,COUPNUM:gd,COUPPCD:pd,CUMIPMT:md,CUMPRINC:fd,DB:bd,DDB:vd,DISC:Sd,DOLLARDE:Cd,DOLLARFR:Ed,DURATION:wd,EFFECT:xd,FV:yd,FVSCHEDULE:Id,INTRATE:Rd,IPMT:Td,IRR:Ad,ISPMT:Od,MDURATION:Md,MIRR:Nd,NOMINAL:_d,NPER:Fd,NPV:Dd,PDURATION:Ld,PMT:Pd,PPMT:kd,PV:Ud,PRICE:Vd,PRICEDISC:zd,PRICEMAT:Bd,RATE:$d,RECEIVED:Wd,RRI:Gd,SLN:qd,SYD:Zd,TBILLPRICE:jd,TBILLEQ:Yd,TBILLYIELD:Xd,VDB:Kd,XIRR:Qd,XNPV:Jd,YIELD:eu,YIELDDISC:tu,YIELDMAT:ou});const su={description:r("Whether a value is an error other than #N/A."),args:[za("value (any, lazy)",r("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return e?.errorType!=a.NotAvailable}},isExported:!0},ru={description:r("Whether a value is an error."),args:[za("value (any, lazy)",r("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},nu={description:r("Whether a value is `true` or `false`."),args:[za("value (any, lazy)",r("The value to be verified as a logical TRUE or FALSE."))],returns:["BOOLEAN"],compute:function(e){try{return"boolean"==typeof e()}catch(e){return!1}},isExported:!0},au={description:r("Whether a value is the error #N/A."),args:[za("value (any, lazy)",r("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return e?.errorType==a.NotAvailable}},isExported:!0},lu={description:r("Whether a value is non-textual."),args:[za("value (any, lazy)",r("The value to be checked."))],returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},cu={description:r("Whether a value is a number."),args:[za("value (any, lazy)",r("The value to be verified as a number."))],returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},hu={description:r("Whether a value is text."),args:[za("value (any, lazy)",r("The value to be verified as text."))],returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},du={description:r("Whether the referenced cell is empty"),args:[za("value (any, lazy)",r("Reference to the cell that will be checked for emptiness."))],returns:["BOOLEAN"],compute:function(e){try{return null===e()}catch(e){return!1}},isExported:!0},uu={description:r("Returns the error value #N/A."),args:[],returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var gu=Object.freeze({__proto__:null,ISERR:su,ISERROR:ru,ISLOGICAL:nu,ISNA:au,ISNONTEXT:lu,ISNUMBER:cu,ISTEXT:hu,ISBLANK:du,NA:uu});const pu={description:r("Logical `and` operator."),args:[za("logical_expression1 (boolean, range<boolean>)",r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),za("logical_expression2 (boolean, range<boolean>, repeating)",r("More expressions that represent logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!0;return ns(e,(e=>(t=!0,o=o&&e,o))),Hi((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},mu={description:r("Returns value depending on logical expression."),args:[za("logical_expression (boolean)",r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),za("value_if_true (any, lazy)",r("The value the function returns if logical_expression is TRUE.")),za("value_if_false (any, lazy, default=FALSE)",r("The value the function returns if logical_expression is FALSE."))],returns:["ANY"],compute:function(e,t,o=(()=>!1)){const i=Ki(e)?t():o();return null==i?"":i},isExported:!0},fu={description:r("Value if it is not an error, otherwise 2nd argument."),args:[za("value (any, lazy)",r("The value to return if value itself is not an error.")),za('value_if_error (any, lazy, default="empty")',r("The value the function returns if value is an error."))],returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{try{return e().format}catch(e){return t()?.format}},compute:function(e,t=(()=>"")){let o;try{o=e()}catch(e){o=t()}return null==o?"":o},isExported:!0},bu={description:r("Value if it is not an #N/A error, otherwise 2nd argument."),args:[za("value (any, lazy)",r("The value to return if value itself is not #N/A an error.")),za('value_if_error (any, lazy, default="empty")',r("The value the function returns if value is an #N/A error."))],returns:["ANY"],compute:function(e,t=(()=>"")){let o;try{o=e()}catch(i){o=i.errorType===a.NotAvailable?t():e()}return null==o?"":o},isExported:!0},vu={description:r("Returns a value depending on multiple logical expressions."),args:[za("condition1 (boolean, lazy)",r("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),za("value1 (any, lazy)",r("The returned value if condition1 is TRUE.")),za("condition2 (boolean, lazy, repeating)",r("Additional conditions to be evaluated if the previous ones are FALSE.")),za("value2 (any, lazy, repeating)",r("Additional values to be returned if their corresponding conditions are TRUE."))],returns:["ANY"],compute:function(...e){Hi((()=>e.length%2==0),r("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(Ki(e[t]())){const o=e[t+1]();return null!==o?o:""}throw new Error(r("No match."))},isExported:!0},Su={description:r("Returns opposite of provided logical value."),args:[za("logical_expression (boolean)",r("An expression or reference to a cell holding an expression that represents some logical value."))],returns:["BOOLEAN"],compute:function(e){return!Ki(e)},isExported:!0},Cu={description:r("Logical `or` operator."),args:[za("logical_expression1 (boolean, range<boolean>)",r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),za("logical_expression2 (boolean, range<boolean>, repeating)",r("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return ns(e,(e=>(t=!0,o=o||e,!o))),Hi((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Eu={description:r("Logical `xor` operator."),args:[za("logical_expression1 (boolean, range<boolean>)",r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),za("logical_expression2 (boolean, range<boolean>, repeating)",r("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return ns(e,(e=>(t=!0,o=o?!e:e,!0))),Hi((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0};var wu=Object.freeze({__proto__:null,AND:pu,IF:mu,IFERROR:fu,IFNA:bu,IFS:vu,NOT:Su,OR:Cu,XOR:Eu});function xu(e,t){if(void 0===e)throw new g(r("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",ji(t)))}const yu={description:r("Returns a cell reference as a string. "),args:[za("row (number)",r("The row number of the cell reference. ")),za("column (number)",r("The column number (not name) of the cell reference. A is column number 1. ")),za("absolute_relative_mode (number, default=1)",r("An indicator of whether the reference is row/column absolute. 1 is row and column absolute (e.g. $A$1), 2 is row absolute and column relative (e.g. A$1), 3 is row relative and column absolute (e.g. $A1), and 4 is row and column relative (e.g. A1).")),za("use_a1_notation (boolean, default=TRUE)",r("A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).")),za("sheet (string, optional)",r("A string indicating the name of the sheet into which the address points."))],returns:["STRING"],compute:function(e,t,o=1,i=!0,s){const n=qi(e),a=qi(t);Zi(n),Zi(a);const l=qi(o);var c,h;Hi((()=>[1,2,3,4].includes(l)),(c=4,h=l,r("The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.",1..toString(),c.toString(),h.toString())));let d;if(Ki(i)){d=Ht(a-1,n-1,{rowFixed:!![1,2].includes(l),colFixed:!![1,3].includes(l)})}else{d=([1,2].includes(l)?`R${n}`:`R[${n}]`)+([1,3].includes(l)?`C${a}`:`C[${a}]`)}return void 0!==s?`${Be(ji(s))}!${d}`:d},isExported:!0},Iu={description:r("Column number of a specified cell."),args:[za("cell_reference (meta, default='this cell')",r("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."))],returns:["NUMBER"],compute:function(e){const t=e||this.__originCellXC?.();Hi((()=>!!t),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Yo(t).left+1},isExported:!0},Ru={description:r("Number of columns in a specified array or range."),args:[za("range (meta)",r("The range whose column count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Yo(e);return t.right-t.left+1},isExported:!0},Tu={description:r("Horizontal lookup"),args:[za("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),za("range (range)",r("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),za("index (number)",r("The row index of the value to be returned, where the first row in range is numbered 1.")),za("is_sorted (boolean, default=true)",r("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."))],returns:["ANY"],compute:function(e,t,o,i=true){const s=Math.trunc(Wi(o)),n=Yi(e);Hi((()=>1<=s&&s<=t[0].length),r("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Ki(i)?us(t,n,"nextSmaller","asc",t.length,ds):gs(t,n,"strict",t.length,ds);const l=t[a];return xu(l,e),l[s-1]},isExported:!0},Au={description:r("Look up a value."),args:[za("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),za("search_array (range)",r("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.")),za("result_range (range, optional)",r("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."))],returns:["ANY"],compute:function(e,t,o){let i=t.length,s=t[0].length;const n=Yi(e),a=s>=i,l=us(t,n,"nextSmaller","asc",a?s:i,a?hs:ds);return-1===l&&xu(void 0,e),xu(a?t[0][l]:t[l][s-1],e),void 0===o?a?t[i-1][l]:t[l][s-1]:(i=o.length,s=o[0].length,Hi((()=>1===i||1===s),r("The result_range must be a single row or a single column.")),i>1?(Hi((()=>l<=i-1),r("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),o[l][0]):(Hi((()=>l<=s-1),r("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),o[0][l]))},isExported:!0},Ou={description:r("Position of item in range that matches value."),args:[za("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),za("range (any, range)",r("The one-dimensional array to be searched.")),za("search_type (number, default=1)",r("The search method. 1 (default) 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."))],returns:["NUMBER"],compute:function(e,t,o=1){let i=Wi(o);const s=Yi(e),n=t.length,a=t[0].length;Hi((()=>1===n||1===a),r("The range must be a single row or a single column."));let l=-1;const c=1===n?hs:ds,h=1===n?t[0].length:t.length;switch(i=Math.sign(i),i){case 1:l=us(t,s,"nextSmaller","asc",h,c);break;case 0:l=gs(t,s,"strict",h,c);break;case-1:l=us(t,s,"nextGreater","desc",h,c)}return xu(1===n?t[0][l]:t[l],e),l+1},isExported:!0},Mu={description:r("Row number of a specified cell."),args:[za("cell_reference (meta, default='this cell')",r("The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered."))],returns:["NUMBER"],compute:function(e){e=e||this.__originCellXC?.(),Hi((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Yo(e).top+1},isExported:!0},Nu={description:r("Number of rows in a specified array or range."),args:[za("range (meta)",r("The range whose row count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Yo(e);return t.bottom-t.top+1},isExported:!0},_u={description:r("Vertical lookup."),args:[za("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),za("range (any, range)",r("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),za("index (number)",r("The column index of the value to be returned, where the first column in range is numbered 1.")),za("is_sorted (boolean, default=true)",r("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."))],returns:["ANY"],compute:function(e,t,o,i=true){const s=Math.trunc(Wi(o)),n=Yi(e);Hi((()=>1<=s&&s<=t.length),r("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Ki(i)?us(t,n,"nextSmaller","asc",t[0].length,hs):gs(t,n,"strict",t[0].length,hs);const l=t[s-1][a];return xu(l,e),l},isExported:!0},Fu={description:r("Search a range for a match and return the corresponding item from a second range."),args:[za("search_key (any)",r("The value to search for.")),za("lookup_range (any, range)",r("The range to consider for the search. Should be a single column or a single row.")),za("return_range (any, range)",r("The range containing the return value. Should have the same dimensions as lookup_range.")),za("if_not_found (any, lazy, optional)",r("If a valid match is not found, return this value.")),za("match_mode (any, default=0)",r("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")),za("search_mode (any, default=1)",r("(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. "))],returns:["ANY"],compute:function(e,t,o,i,s=0,n=1){const a=Math.trunc(Wi(s)),l=Math.trunc(Wi(n)),c=Yi(e);Hi((()=>1===t.length||1===t[0].length),r("lookup_range should be either a single row or single column.")),Hi((()=>1===o.length||1===o[0].length),r("return_range should be either a single row or single column.")),Hi((()=>o.length===t.length&&o[0].length===t[0].length),r("return_range should have the same dimensions as lookup_range.")),Hi((()=>[-1,1,-2,2].includes(l)),r("searchMode should be a value in [-1, 1, -2, 2].")),Hi((()=>[-1,0,1].includes(a)),r("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?hs:ds,d=1===t.length?t[0].length:t.length,u=0===a?"strict":1===a?"nextGreater":"nextSmaller",g=-1===l;let p;if(2===l||-2===l){p=us(t,c,u,2===l?"asc":"desc",d,h)}else p=gs(t,c,u,d,h,g);if(-1!==p)return 1===t.length?o[0][p]:o[p][0];const m=i?.();return xu(m,e),m},isExported:!0};var Du=Object.freeze({__proto__:null,ADDRESS:yu,COLUMN:Iu,COLUMNS:Ru,HLOOKUP:Tu,LOOKUP:Au,MATCH:Ou,ROW:Mu,ROWS:Nu,VLOOKUP:_u,XLOOKUP:Fu});const Lu={description:r("Sum of two numbers."),args:[za("value1 (number)",r("The first addend.")),za("value2 (number)",r("The second addend."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Wi(e)+Wi(t)}},Pu={description:r("Concatenation of two values."),args:[za("value1 (string)",r("The value to which value2 will be appended.")),za("value2 (string)",r("The value to append to value1."))],returns:["STRING"],compute:function(e,t){return ji(e)+ji(t)},isExported:!0},ku={description:r("One number divided by another."),args:[za("dividend (number)",r("The number to be divided.")),za("divisor (number)",r("The number to divide by."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){const o=Wi(t);return Hi((()=>0!==o),r("The divisor must be different from zero.")),Wi(e)/o}};function Uu(e){return null==e}const Vu={number:0,string:"",boolean:!1},zu={description:r("Equal."),args:[za("value1 (any)",r("The first value.")),za("value2 (any)",r("The value to test against value1 for equality."))],returns:["BOOLEAN"],compute:function(e,t){return e=Uu(e)?Vu[typeof t]:e,t=Uu(t)?Vu[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function Bu(e,t,o){e=Uu(e)?Vu[typeof t]:e,t=Uu(t)?Vu[typeof e]:t,"number"!=typeof e&&(e=ji(e).toUpperCase()),"number"!=typeof t&&(t=ji(t).toUpperCase());const i=typeof e,s=typeof t;return"string"===i&&"number"===s||("string"!==s||"number"!==i)&&o(e,t)}const Hu={description:r("Strictly greater than."),args:[za("value1 (any)",r("The value to test as being greater than value2.")),za("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return Bu(e,t,((e,t)=>e>t))}},$u={description:r("Greater than or equal to."),args:[za("value1 (any)",r("The value to test as being greater than or equal to value2.")),za("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return Bu(e,t,((e,t)=>e>=t))}},Wu={description:r("Less than."),args:[za("value1 (any)",r("The value to test as being less than value2.")),za("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!$u.compute(e,t)}},Gu={description:r("Less than or equal to."),args:[za("value1 (any)",r("The value to test as being less than or equal to value2.")),za("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!Hu.compute(e,t)}},qu={description:r("Difference of two numbers."),args:[za("value1 (number)",r("The minuend, or number to be subtracted from.")),za("value2 (number)",r("The subtrahend, or number to subtract from value1."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Wi(e)-Wi(t)}},Zu={description:r("Product of two numbers"),args:[za("factor1 (number)",r("The first multiplicand.")),za("factor2 (number)",r("The second multiplicand."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Wi(e)*Wi(t)}},ju={description:r("Not equal."),args:[za("value1 (any)",r("The first value.")),za("value2 (any)",r("The value to test against value1 for inequality."))],returns:["BOOLEAN"],compute:function(e,t){return!zu.compute(e,t)}},Yu={description:r("A number raised to a power."),args:[za("base (number)",r("The number to raise to the exponent power.")),za("exponent (number)",r("The exponent to raise base to."))],returns:["NUMBER"],compute:function(e,t){return Ol.compute(e,t)}},Xu={description:r("A number with the sign reversed."),args:[za("value (number)",r("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],computeFormat:e=>e?.format,returns:["NUMBER"],compute:function(e){return-Wi(e)}},Ku={description:r("Value interpreted as a percentage."),args:[za("percentage (number)",r("The value to interpret as a percentage."))],returns:["NUMBER"],compute:function(e){return Wi(e)/100}},Qu={description:r("A specified number, unchanged."),args:[za("value (any)",r("The number to return."))],returns:["ANY"],computeFormat:e=>e?.format,compute:function(e){return null===e?"":e}};var Ju=Object.freeze({__proto__:null,ADD:Lu,CONCAT:Pu,DIVIDE:ku,EQ:zu,GT:Hu,GTE:$u,LT:Wu,LTE:Gu,MINUS:qu,MULTIPLY:Zu,NE:ju,POW:Yu,UMINUS:Xu,UNARY_PERCENT:Ku,UPLUS:Qu});const eg=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,tg={description:r("Gets character associated with number."),args:[za("table_number (number)",r("The number of the character to look up from the current Unicode table in decimal format."))],returns:["STRING"],compute:function(e){const t=Math.trunc(Wi(e));return Hi((()=>t>=1),r("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},og={description:r("Remove non-printable characters from a piece of text."),args:[za("text (string)",r("The text whose non-printable characters are to be removed."))],returns:["STRING"],compute:function(e){const t=ji(e);let o="";for(const e of t)e&&e.charCodeAt(0)>31&&(o+=e);return o},isExported:!0},ig={description:r("Appends strings to one another."),args:[za("string1 (string, range<string>)",r("The initial string.")),za("string2 (string, range<string>, repeating)",r("More strings to append in sequence."))],returns:["STRING"],compute:function(...e){return is(e,((e,t)=>e+ji(t)),"")},isExported:!0},sg={description:r("Tests whether two strings are identical."),args:[za("string1 (string)",r("The first string to compare.")),za("string2 (string)",r("The second string to compare."))],returns:["BOOLEAN"],compute:function(e,t){return ji(e)===ji(t)},isExported:!0},rg={description:r("First position of string found in text, case-sensitive."),args:[za("search_for (string)",r("The string to look for within text_to_search.")),za("text_to_search (string)",r("The text to search for the first occurrence of search_for.")),za("starting_at (number, default=1)",r("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,o=1){const i=ji(e),s=ji(t),n=Wi(o);Hi((()=>""!==s),r("The text_to_search must be non-empty.")),Hi((()=>n>=1),r("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const a=s.indexOf(i,n-1);return Hi((()=>a>=0),r("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i.toString(),s)),a+1},isExported:!0},ng={description:r("Concatenates elements of arrays with delimiter."),args:[za("delimiter (string)",r("The character or string to place between each concatenated value.")),za("value_or_array1 (string, range<string>)",r("The value or values to be appended using delimiter.")),za("value_or_array2 (string, range<string>, repeating)",r("More values to be appended using delimiter."))],returns:["STRING"],compute:function(e,...t){const o=ji(e);return is(t,((e,t)=>(e?e+o:"")+ji(t)),"")}},ag={description:r("Substring from beginning of specified string."),args:[za("text (string)",r("The string from which the left portion will be returned.")),za("number_of_characters (number, optional)",r("The number of characters to return from the left side of string."))],returns:["STRING"],compute:function(e,...t){const o=t.length?Wi(t[0]):1;return Hi((()=>o>=0),r("The number_of_characters (%s) must be positive or null.",o.toString())),ji(e).substring(0,o)},isExported:!0},lg={description:r("Length of a string."),args:[za("text (string)",r("The string whose length will be returned."))],returns:["NUMBER"],compute:function(e){return ji(e).length},isExported:!0},cg={description:r("Converts a specified string to lowercase."),args:[za("text (string)",r("The string to convert to lowercase."))],returns:["STRING"],compute:function(e){return ji(e).toLowerCase()},isExported:!0},hg={description:r("A segment of a string."),args:[za("text (string)",r("The string to extract a segment from.")),za(" (number)",r("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),za(" (number)",r("The length of the segment to extract."))],returns:["STRING"],compute:function(e,t,o){const i=ji(e),s=Wi(t),n=Wi(o);return Hi((()=>s>=1),r("The starting_at argument (%s) must be positive greater than one.",s.toString())),Hi((()=>n>=0),r("The extract_length argument (%s) must be positive or null.",n.toString())),i.slice(s-1,s+n-1)},isExported:!0},dg={description:r("Capitalizes each word in a specified string."),args:[za("text_to_capitalize (string)",r("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase."))],returns:["STRING"],compute:function(e){return ji(e).replace(eg,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},ug={description:r("Replaces part of a text string with different text."),args:[za("text (string)",r("The text, a part of which will be replaced.")),za("position (number)",r("The position where the replacement will begin (starting from 1).")),za("length (number)",r("The number of characters in the text to be replaced.")),za("new_text (string)",r("The text which will be inserted into the original text."))],returns:["STRING"],compute:function(e,t,o,i){const s=Wi(t);Hi((()=>s>=1),r("The position (%s) must be greater than or equal to 1.",s.toString()));const n=ji(e),a=Wi(o),l=ji(i);return n.substring(0,s-1)+l+n.substring(s-1+a)},isExported:!0},gg={description:r("A substring from the end of a specified string."),args:[za("text (string)",r("The string from which the right portion will be returned.")),za("number_of_characters (number, optional)",r("The number of characters to return from the right side of string."))],returns:["STRING"],compute:function(e,...t){const o=t.length?Wi(t[0]):1;Hi((()=>o>=0),r("The number_of_characters (%s) must be positive or null.",o.toString()));const i=ji(e),s=i.length;return i.substring(s-o,s)},isExported:!0},pg={description:r("First position of string found in text, ignoring case."),args:[za("search_for (string)",r("The string to look for within text_to_search.")),za("text_to_search (string)",r("The text to search for the first occurrence of search_for.")),za("starting_at (number, default=1)",r("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,o=1){const i=ji(e).toLowerCase(),s=ji(t).toLowerCase(),n=Wi(o);Hi((()=>""!==s),r("The text_to_search must be non-empty.")),Hi((()=>n>=1),r("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const a=s.indexOf(i,n-1);return Hi((()=>a>=0),r("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i,s)),a+1},isExported:!0},mg={description:r("Replaces existing text with new text in a string."),args:[za("text_to_search (string)",r("The text within which to search and replace.")),za("search_for (string)",r("The string to search for within text_to_search.")),za("replace_with (string)",r("The string that will replace search_for.")),za("occurrence_number (number, optional)",r("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."))],returns:["NUMBER"],compute:function(e,t,o,i){const s=Wi(i);Hi((()=>s>=0),r("The occurrenceNumber (%s) must be positive or null.",s.toString()));const n=ji(e),a=ji(t);if(""===a)return n;const l=ji(o),c=new RegExp(Ue(a),"g");if(0===s)return n.replace(c,l);let h=0;return n.replace(c,(e=>++h===s?l:e))},isExported:!0},fg={description:r("Combines text from multiple strings and/or arrays."),args:[za("delimiter (string)",r(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),za("ignore_empty (boolean)",r("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")),za("text1 (string, range<string>)",r("Any text item. This could be a string, or an array of strings in a range.")),za("text2 (string, range<string>, repeating)",r("Additional text item(s)."))],returns:["STRING"],compute:function(e,t,...o){const i=ji(e),s=Ki(t);let r=0;return is(o,((e,t)=>s&&""===ji(t)?e:(r++?e+i:"")+ji(t)),"")},isExported:!0},bg={description:r("Removes space characters."),args:[za("text (string)",r("The text or reference to a cell containing text to be trimmed."))],returns:["STRING"],compute:function(e){return ji(e).trim()},isExported:!0},vg={description:r("Converts a specified string to uppercase."),args:[za("text (string)",r("The string to convert to uppercase."))],returns:["STRING"],compute:function(e){return ji(e).toUpperCase()},isExported:!0},Sg={description:r("Converts a number to text according to a specified format."),args:[za("number (number)",r("The number, date or time to format.")),za("format (string)",r("The pattern by which to format the number, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){return uo(Wi(e),ji(t))},isExported:!0};var Cg=Object.freeze({__proto__:null,CHAR:tg,CLEAN:og,CONCATENATE:ig,EXACT:sg,FIND:rg,JOIN:ng,LEFT:ag,LEN:lg,LOWER:cg,MID:hg,PROPER:dg,REPLACE:ug,RIGHT:gg,SEARCH:pg,SUBSTITUTE:mg,TEXTJOIN:fg,TRIM:bg,UPPER:vg,TEXT:Sg});const Eg={description:r("Creates a hyperlink in a cell."),args:[za("url (string)",r("The full URL of the link enclosed in quotation marks.")),za("link_label (string, optional)",r("The text to display in the cell, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){const o=ji(e).trim(),i=ji(t)||o;return""===o?i:ot(i,o)},isExported:!0};var wg=Object.freeze({__proto__:null,HYPERLINK:Eg});const xg=[{name:r("Database"),functions:Qc},{name:r("Date"),functions:Fh},{name:r("Financial"),functions:iu},{name:r("Info"),functions:gu},{name:r("Lookup"),functions:Du},{name:r("Logical"),functions:wu},{name:r("Math"),functions:Zl},{name:r("Misc"),functions:$a},{name:r("Operator"),functions:Ju},{name:r("Statistical"),functions:kc},{name:r("Text"),functions:Cg},{name:r("Engineering"),functions:Lh},{name:r("Web"),functions:wg}],yg=/^[A-Z0-9\_\.]+$/;function Ig(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Rg(e()):Rg(e)}))}function Rg(e){return Array.isArray(e)?e.map((e=>e.map((e=>e?.value)))):e?.value}const Tg=new class extends _i{mapping={};add(e,t){if(e=e.toUpperCase(),!yg.test(e))throw new Error(r("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const o=Ba(t);return function(e){let t=!1,o=!1,i=!1;for(let s of e){if(s.type.includes("META")&&s.type.length>1)throw new Error(r("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!s.repeating)throw new Error(r("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=o||t||i,n=!(s.optional||s.repeating||s.default);if(e&&n)throw new Error(r("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=s.repeating,o=s.optional,i=s.default}}(o.args),this.mapping[e]=function(...e){const t=o.compute.bind(this),i=o.computeFormat?o.computeFormat.bind(this):()=>{};return{value:t(...Ig(e)),format:i(...e)}},super.add(e,o),this}};for(let e of xg){const t=e.functions;for(let o in t){const i=t[o];i.category=i.category||e.name,o=o.replace(/_/g,"."),Tg.add(o,{isExported:!1,...i})}}const Ag={name:e=>{const t=ea(e);return 1===t?r("Insert row"):r("Insert %s rows",t.toString())},isVisible:e=>wt(e.model.getters.getActiveRows())&&pa(e)&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_ROW"},Og={name:e=>{const t=ea(e);return 1===t?r("Insert row above"):r("Insert %s rows above",t.toString())},execute:aa,isVisible:e=>wt(e.model.getters.getActiveRows())&&pa(e)&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},Mg={...Og,name:e=>{const t=ea(e);return 1===t?r("Row above"):r("%s Rows above",t.toString())}},Ng={...Og,name:e=>{const t=ea(e);return 1===t?r("Insert row"):r("Insert %s rows",t.toString())},isVisible:pa,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},_g={execute:e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.max(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.bottom,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:o,quantity:i,dimension:"ROW"})},name:e=>{const t=ea(e);return 1===t?r("Insert row below"):r("Insert %s rows below",t.toString())},isVisible:e=>wt(e.model.getters.getActiveRows())&&pa(e)&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},Fg={..._g,name:e=>{const t=ea(e);return 1===t?r("Row below"):r("%s Rows below",t.toString())}},Dg={name:e=>{const t=Jn(e);return 1===t?r("Insert column"):r("Insert %s columns",t.toString())},isVisible:e=>wt(e.model.getters.getActiveCols())&&pa(e)&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_COL"},Lg={name:e=>{const t=Jn(e);return 1===t?r("Insert column left"):r("Insert %s columns left",t.toString())},execute:la,isVisible:e=>wt(e.model.getters.getActiveCols())&&pa(e)&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Pg={...Lg,name:e=>{const t=Jn(e);return 1===t?r("Column left"):r("%s Columns left",t.toString())}},kg={...Lg,name:e=>{const t=Jn(e);return 1===t?r("Insert column"):r("Insert %s columns",t.toString())},isVisible:pa,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Ug={name:e=>{const t=Jn(e);return 1===t?r("Insert column right"):r("Insert %s columns right",t.toString())},execute:ca,isVisible:e=>wt(e.model.getters.getActiveCols())&&pa(e)&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},Vg={...Ug,name:e=>{const t=Jn(e);return 1===t?r("Column right"):r("%s Columns right",t.toString())},execute:ca},zg={name:r("Insert cells"),isVisible:e=>pa(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},Bg={name:r("Insert cells and shift down"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});Xn(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},Hg={name:r("Insert cells and shift right"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});Xn(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},$g={name:r("Chart"),execute:e=>{const t=e.model.getters,o=e.model.uuidGenerator.uuidv4(),i=t.getActiveSheetId();1===vi(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const s={width:536,height:335},r=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:s,scrollY:r}=e.getActiveSheetScrollInfo(),{width:n,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:o+s+Math.max(0,(n-t.width)/2),y:i+r+Math.max(0,(a-t.height)/2)}}(t,s);e.model.dispatch("CREATE_CHART",{sheetId:i,id:o,position:r,size:s,definition:$n(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:o}),e.openSidePanel("ChartPanel"))},icon:"o-spreadsheet-Icon.INSERT_CHART"},Wg={name:r("Image"),description:"Ctrl+O",execute:ha,isVisible:e=>void 0!==e.imageProvider,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},Gg={name:r("Function"),icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},qg={name:r("SUM"),execute:e=>e.startCellEdition("=SUM(")},Zg={name:r("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},jg={name:r("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},Yg={name:r("MAX"),execute:e=>e.startCellEdition("=MAX(")},Xg={name:r("MIN"),execute:e=>e.startCellEdition("=MIN(")},Kg={name:r("All"),children:ep(Tg.getKeys())};const Qg={name:r("Link"),execute:ua,icon:"o-spreadsheet-Icon.INSERT_LINK"},Jg={name:r("Insert sheet"),execute:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSheetIds().indexOf(t)+1,i=e.model.uuidGenerator.uuidv4();e.model.dispatch("CREATE_SHEET",{sheetId:i,position:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})},icon:"o-spreadsheet-Icon.INSERT_SHEET"};function ep(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)})))}const tp=new Cr;tp.add("cut",{...va,sequence:10}).add("copy",{...ba,sequence:20}).add("paste",{...Sa,sequence:30}).add("paste_special",{...Ca,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Ea,sequence:10}).addChild("paste_format_only",["paste_special"],{...wa,sequence:20}).add("add_row_before",{...Ng,sequence:70}).add("add_column_before",{...kg,sequence:90}).add("insert_cell",{...zg,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...Bg,name:r("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...Hg,name:r("Shift right"),sequence:20}).add("delete_row",{...Ra,sequence:110,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_column",{...Oa,sequence:120,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_cell",{...Na,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.DELETE"}).addChild("delete_cell_up",["delete_cell"],{..._a,name:r("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...Fa,name:r("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("insert_link",{...Qg,name:r("Insert link"),sequence:150,separator:!0});const op={name:r("Sort range"),isVisible:pa,icon:"o-spreadsheet-Icon.SORT_RANGE"},ip={name:r("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();Gn(e,i,t.cell,o[0],"ascending")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},sp={name:r("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();Gn(e,i,t.cell,o[0],"descending")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},rp={name:r("Create filter"),execute:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelection().zones;jn(e,t,o)},isVisible:e=>!ga(e),isEnabled:e=>(e=>Si(...e.model.getters.getSelectedZones()))(e),icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},np={name:r("Remove filter"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:ga,icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},ap={name:r("Split text to columns"),sequence:1,execute:e=>e.openSidePanel("SplitToColumns",{}),isEnabled:e=>e.model.getters.isSingleColSelected(),icon:"o-spreadsheet-Icon.SPLIT_TEXT"},lp={name:r("Automatic"),execute:e=>ta(e,""),isActive:e=>function(e){const t=e.model.getters.getCell(e.model.getters.getActivePosition());return!t||!t.format}(e)},cp={name:r("Number"),description:"1,000.12",execute:e=>ta(e,"#,##0.00"),isActive:e=>Wp(e,"#,##0.00")},hp={name:r("Format as percent"),execute:da,icon:"o-spreadsheet-Icon.PERCENT"},dp={name:r("Percent"),description:"10.12%",execute:da,isActive:e=>Wp(e,"0.00%")},up={name:r("Currency"),description:"$1,000.12",execute:e=>ta(e,"[$$]#,##0.00"),isActive:e=>Wp(e,"[$$]#,##0.00")},gp={name:r("Currency rounded"),description:"$1,000",execute:e=>ta(e,"[$$]#,##0"),isActive:e=>Wp(e,"[$$]#,##0")},pp={name:r("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies,execute:e=>{e.openSidePanel("CustomCurrency",{})}},mp={name:r("Date"),description:"9/26/2008",execute:e=>ta(e,"m/d/yyyy"),isActive:e=>Wp(e,"m/d/yyyy")},fp={name:r("Time"),description:"10:43:00 PM",execute:e=>ta(e,"hh:mm:ss a"),isActive:e=>Wp(e,"hh:mm:ss a")},bp={name:r("Date time"),description:"9/26/2008 22:43:00",execute:e=>ta(e,"m/d/yyyy hh:mm:ss"),isActive:e=>Wp(e,"m/d/yyyy hh:mm:ss")},vp={name:r("Duration"),description:"27:51:38",execute:e=>ta(e,"hhhh:mm:ss"),isActive:e=>Wp(e,"hhhh:mm:ss")},Sp={name:r("Increase decimal places"),icon:"o-spreadsheet-Icon.INCREASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:1})},Cp={name:r("Decrease decimal places"),icon:"o-spreadsheet-Icon.DECRASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:-1})},Ep={name:r("Bold"),description:"Ctrl+B",execute:e=>oa(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},wp={name:r("Italic"),description:"Ctrl+I",execute:e=>oa(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},xp={name:r("Underline"),description:"Ctrl+U",execute:e=>oa(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},yp={name:r("Strikethrough"),execute:e=>oa(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},Ip={name:r("Font size"),children:me.map((e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>oa(t,{fontSize:e}),isActive:t=>function(e,t){const o=e.model.getters.getCurrentStyle().fontSize||q;return o===t}(t,e)}))),icon:"o-spreadsheet-Icon.FONT_SIZE"},Rp={name:r("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Tp={name:r("Horizontal align"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Ap={name:r("Left"),description:"Ctrl+Shift+L",execute:e=>oa(e,{align:"left"}),isActive:e=>"left"===Gp(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Op={name:r("Center"),description:"Ctrl+Shift+E",execute:e=>oa(e,{align:"center"}),isActive:e=>"center"===Gp(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},Mp={name:r("Right"),description:"Ctrl+Shift+R",execute:e=>oa(e,{align:"right"}),isActive:e=>"right"===Gp(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},Np={name:r("Vertical align"),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},_p={name:r("Top"),execute:e=>oa(e,{verticalAlign:"top"}),isActive:e=>"top"===(e.model.getters.getCurrentStyle().verticalAlign||j),icon:"o-spreadsheet-Icon.ALIGN_TOP"},Fp={name:r("Middle"),execute:e=>oa(e,{verticalAlign:"middle"}),isActive:e=>"middle"===(e.model.getters.getCurrentStyle().verticalAlign||j),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},Dp={name:r("Bottom"),execute:e=>oa(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===(e.model.getters.getCurrentStyle().verticalAlign||j),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},Lp={name:r("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},Pp={name:r("Overflow"),execute:e=>oa(e,{wrapping:"overflow"}),isActive:e=>"overflow"===(e.model.getters.getCurrentStyle().wrapping||"overflow"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},kp={name:r("Wrap"),execute:e=>oa(e,{wrapping:"wrap"}),isActive:e=>"wrap"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},Up={name:r("Clip"),execute:e=>oa(e,{wrapping:"clip"}),isActive:e=>"clip"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_CLIP"},Vp={name:r("Text Color"),icon:"o-spreadsheet-Icon.TEXT_COLOR"},zp={name:r("Fill Color"),icon:"o-spreadsheet-Icon.FILL_COLOR"},Bp={name:r("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},Hp={name:r("Paint Format"),execute:e=>e.model.dispatch("ACTIVATE_PAINT_FORMAT",{target:e.model.getters.getSelectedZones()}),icon:"o-spreadsheet-Icon.PAINT_FORMAT",isActive:e=>e.model.getters.isPaintingFormat()},$p={name:r("Clear formatting"),description:"Ctrl+<",execute:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},icon:"o-spreadsheet-Icon.CLEAR_FORMAT"};function Wp(e,t){return e.model.getters.getCell(e.model.getters.getActivePosition())?.format===t}function Gp(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}var qp=Object.freeze({__proto__:null,formatNumberAutomatic:lp,formatNumberNumber:cp,formatPercent:hp,formatNumberPercent:dp,formatNumberCurrency:up,formatNumberCurrencyRounded:gp,formatCustomCurrency:pp,formatNumberDate:mp,formatNumberTime:fp,formatNumberDateTime:bp,formatNumberDuration:vp,incraseDecimalPlaces:Sp,decraseDecimalPlaces:Cp,formatBold:Ep,formatItalic:wp,formatUnderline:xp,formatStrikethrough:yp,formatFontSize:Ip,formatAlignment:Rp,formatAlignmentHorizontal:Tp,formatAlignmentLeft:Ap,formatAlignmentCenter:Op,formatAlignmentRight:Mp,formatAlignmentVertical:Np,formatAlignmentTop:_p,formatAlignmentMiddle:Fp,formatAlignmentBottom:Dp,formatWrapping:Lp,formatWrappingOverflow:Pp,formatWrappingWrap:kp,formatWrappingClip:Up,textColor:Vp,fillColor:zp,formatCF:Bp,paintFormat:Hp,clearFormat:$p});function Zp(e,t,o){const i=e.model.getters.getActiveSheetId(),s="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(s,{sheetId:i,quantity:o}).isCancelledBecause(65)&&e.raiseError(Xr)}const jp={name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let o=t[0],i=t[t.length-1];return 1===t.length?r("Hide column %s",Pt(o).toString()):i-o+1===t.length?r("Hide columns %s - %s",Pt(o).toString(),Pt(i).toString()):r("Hide columns")},execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:na,icon:"o-spreadsheet-Icon.HIDE_COL"},Yp={name:r("Unhide columns"),execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))}},Xp={name:r("Unhide all columns"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0},Kp={name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let o=t[0],i=t[t.length-1];return 1===t.length?r("Hide row %s",(o+1).toString()):i-o+1===t.length?r("Hide rows %s - %s",(o+1).toString(),(i+1).toString()):r("Hide rows")},execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:ra,icon:"o-spreadsheet-Icon.HIDE_ROW"},Qp={name:r("Unhide rows"),execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))}},Jp={name:r("Unhide all rows"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0},em={name:r("Unfreeze"),isVisible:e=>{const{xSplit:t,ySplit:o}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+o>0},execute:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()})},tm={name:r("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},om={name:r("No rows"),execute:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},im={name:r("1 row"),execute:e=>Zp(e,"ROW",1),isReadonlyAllowed:!0},sm={name:r("2 rows"),execute:e=>Zp(e,"ROW",2),isReadonlyAllowed:!0},rm={name:r("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();Zp(e,"ROW",t+1)},isReadonlyAllowed:!0},nm={name:r("No columns"),execute:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},am={name:r("1 column"),execute:e=>Zp(e,"COL",1),isReadonlyAllowed:!0},lm={name:r("2 columns"),execute:e=>Zp(e,"COL",2),isReadonlyAllowed:!0},cm={name:r("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();Zp(e,"COL",t+1)},isReadonlyAllowed:!0},hm={name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?r("Hide gridlines"):r("Show gridlines"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},icon:"o-spreadsheet-Icon.SHOW_HIDE_GRID"},dm={name:e=>e.model.getters.shouldShowFormulas()?r("Hide formulas"):r("Show formulas"),execute:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},um={name:e=>gm(e)?r("Remove selected filters"):r("Create filter"),isActive:e=>gm(e),isEnabled:e=>!pm(e),execute:e=>function(e){if(gm(e))return void e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()});if(pm(e))return;e.model.selection.selectTableAroundSelection();const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();jn(e,t,o)}(e),icon:"o-spreadsheet-Icon.FILTER_ICON_INACTIVE"};function gm(e){const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)}function pm(e){return!Si(...e.model.getters.getSelectedZones())}var mm=Object.freeze({__proto__:null,hideCols:jp,unhideCols:Yp,unhideAllCols:Xp,hideRows:Kp,unhideRows:Qp,unhideAllRows:Jp,unFreezePane:em,freezePane:tm,unFreezeRows:om,freezeFirstRow:im,freezeSecondRow:sm,freezeCurrentRow:rm,unFreezeCols:nm,freezeFirstCol:am,freezeSecondCol:lm,freezeCurrentCol:cm,viewGridlines:hm,viewFormulas:dm,createRemoveFilter:um});const fm=new Cr;fm.add("cut",{...va,sequence:10}).add("copy",{...ba,sequence:20}).add("paste",{...Sa,sequence:30}).add("paste_special",{...Ca,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Ea,sequence:10}).addChild("paste_format_only",["paste_special"],{...wa,sequence:20}).add("sort_columns",{...op,name:e=>e.model.getters.getActiveCols().size>1?r("Sort columns"):r("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...ip,sequence:10}).addChild("sort_descending",["sort_columns"],{...sp,sequence:20}).add("add_column_before",{...Lg,sequence:70}).add("add_column_after",{...Ug,sequence:80}).add("delete_column",{...Aa,sequence:90,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_column",{...Ma,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...jp,sequence:105,separator:!0}).add("unhide_columns",{...Yp,sequence:106,separator:!0}).add("conditional_formatting",{...Bp,sequence:110});const bm=new Cr;bm.add("format_number_automatic",{...lp,sequence:10,separator:!0}).add("format_number_number",{...cp,sequence:20}).add("format_number_percent",{...dp,sequence:30,separator:!0}).add("format_number_currency",{...up,sequence:40}).add("format_number_currency_rounded",{...gp,sequence:50}).add("format_custom_currency",{...pp,sequence:60,separator:!0}).add("format_number_date",{...mp,sequence:70}).add("format_number_time",{...fp,sequence:80}).add("format_number_date_time",{...bp,sequence:90}).add("format_number_duration",{...vp,sequence:100,separator:!0});const vm={name:r("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[()=>bm.getAll()]},Sm=new Cr;Sm.add("cut",{...va,sequence:10}).add("copy",{...ba,sequence:20}).add("paste",{...Sa,sequence:30}).add("paste_special",{...Ca,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Ea,sequence:10}).addChild("paste_format_only",["paste_special"],{...wa,sequence:20}).add("add_row_before",{...Og,sequence:50}).add("add_row_after",{..._g,sequence:60}).add("delete_row",{...Ia,sequence:70,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_row",{...Ta,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...Kp,sequence:85,separator:!0}).add("unhide_rows",{...Qp,sequence:86,separator:!0}).add("conditional_formatting",{...Bp,sequence:90});const Cm=new Cr;Cm.add("file",{name:r("File"),sequence:10}).add("edit",{name:r("Edit"),sequence:20}).addChild("undo",["edit"],{...ma,sequence:10}).addChild("redo",["edit"],{...fa,sequence:20,separator:!0}).addChild("copy",["edit"],{...ba,sequence:30}).addChild("cut",["edit"],{...va,sequence:40}).addChild("paste",["edit"],{...Sa,sequence:50}).addChild("paste_special",["edit"],{...Ca,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...Ea,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...wa,sequence:20}).addChild("find_and_replace",["edit"],{...xa,sequence:65,separator:!0}).addChild("delete",["edit"],{name:r("Delete"),icon:"o-spreadsheet-Icon.DELETE",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...ya,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...Ia,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...Aa,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{..._a,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...Fa,sequence:50}).addChild("edit_unhide_columns",["edit"],{...Xp,sequence:80}).addChild("edit_unhide_rows",["edit"],{...Jp,sequence:80}).add("view",{name:r("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...em,sequence:4}).addChild("freeze_panes",["view"],{...tm,sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{...om,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...im,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...sm,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...rm,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...nm,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...am,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...lm,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...cm,sequence:40}).addChild("view_gridlines",["view"],{...hm,sequence:10}).addChild("view_formulas",["view"],{...dm,sequence:15}).add("insert",{name:r("Insert"),sequence:40}).addChild("insert_row",["insert"],{...Ag,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...Mg,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...Fg,sequence:20}).addChild("insert_column",["insert"],{...Dg,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...Pg,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...Vg,sequence:20}).addChild("insert_cell",["insert"],{...zg,sequence:43}).addChild("insert_cell_down",["insert","insert_cell"],{...Bg,name:r("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...Hg,name:r("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...Jg,sequence:80,separator:!0}).addChild("insert_chart",["insert"],{...$g,sequence:50}).addChild("insert_image",["insert"],{...Wg,sequence:55}).addChild("insert_function",["insert"],{...Gg,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...qg,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...Zg,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...jg,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...Yg,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...Xg,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...Kg,sequence:50}).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=Tg.content;return[...new Set(Tg.getAll().map((e=>e.category)))].filter(lt).sort().map(((t,o)=>{const i=Object.keys(e).filter((o=>e[o].category===t));return{name:t,children:ep(i)}}))})).addChild("insert_link",["insert"],{...Qg,separator:!0,sequence:70}).add("format",{name:r("Format"),sequence:50}).addChild("format_number",["format"],{...vm,name:r("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...Ep,sequence:20}).addChild("format_italic",["format"],{...wp,sequence:30}).addChild("format_underline",["format"],{...xp,sequence:40}).addChild("format_strikethrough",["format"],{...yp,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...Ip,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...Rp,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...Ap,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...Op,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...Mp,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{..._p,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...Fp,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...Dp,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...Lp,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...Pp,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...kp,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...Up,sequence:30}).addChild("format_cf",["format"],{...Bp,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...$p,sequence:100,separator:!0}).add("data",{name:r("Data"),sequence:60}).addChild("sort_range",["data"],{...op,sequence:20,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...ip,sequence:10}).addChild("sort_descending",["data","sort_range"],{...sp,sequence:20}).addChild("split_to_columns",["data"],{...ap,sequence:10,separator:!0}).addChild("add_data_filter",["data"],{...rp,sequence:10}).addChild("remove_data_filter",["data"],{...np,sequence:10});const Em=new class extends _i{addTransformation(e,t,o){for(let i of t)this.content[i]||(this.content[i]=new Map),this.content[i].set(e,o);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},wm={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function xm(e,t){const o=wm[e.key];e.shiftKey?t.resizeAnchorZone(o,e.ctrlKey?"end":1):t.moveAnchorCell(o,e.ctrlKey?"end":1)}const ym=new Zo;xi`
352
+ `;class _n extends t.Component{static template="o-spreadsheet-ChartFigure";static components={};onDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.openSidePanel("ChartPanel")}get chartType(){return this.env.model.getters.getChartType(this.props.figure.id)}get chartComponent(){const e=this.chartType,t=Mn.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}_n.props={figure:Object,onFigureDeleted:Function};class Fn extends t.Component{static template="o-spreadsheet-ImageFigure";static components={};get figureId(){return this.props.figure.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}function Dn(e,t){const o=Ve(t),i=e.getSheetViewDimension(),s=i.width,r=i.height;if(o.width>s){const e=s/o.width;o.width=s,o.height=o.height*e}if(o.height>r){const e=r/o.height;o.height=r,o.width=o.width*e}return o}Fn.props={figure:Object,onFigureDeleted:Function};const Ln=new _i;function Pn(e,t){return{id:"copy",name:r("Copy"),sequence:2,description:"Ctrl+C",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("COPY"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function kn(e,t){return{id:"cut",name:r("Cut"),sequence:3,description:"Ctrl+X",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("CUT"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function Un(e,t,o){return{id:"delete",name:r("Delete"),sequence:10,execute:()=>{o.model.dispatch("DELETE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e}),t()}}}Ln.add("chart",{Component:_n,SidePanelComponent:"ChartPanel",menuBuilder:function(e,t,o){return br([{id:"edit",name:r("Edit"),sequence:1,execute:()=>{o.model.dispatch("SELECT_FIGURE",{id:e}),o.openSidePanel("ChartPanel")}},Pn(e,o),kn(e,o),Un(e,t,o)])}}),Ln.add("image",{Component:Fn,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,o){return br([Pn(e,o),kn(e,o),{id:"reset_size",name:r("Reset size"),sequence:4,execute:()=>{const t=o.model.getters.getImageSize(e),{height:i,width:s}=Dn(o.model.getters,t);o.model.dispatch("UPDATE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e,height:i,width:s})}},Un(e,t,o)])}});const Vn=(new _i).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let o=e.base;"after"===e.position&&o++;for(let i=0;i<e.quantity;i++)t.push(i+o);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],o=[...e.elements].sort(((e,t)=>e-t));for(let i of Ye(o)){const o=0===i[0]?0:i[0]-1,s=0===i[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:i.length,base:o,sheetId:e.sheetId,position:s})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of Cs.values())Vn.contains(e)||Vn.add(e,zn);function zn(e){return[e]}const Bn={MergeIsDestructive:r("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:r("You can't merge cells inside of an existing filter.")};function Hn(e,t){const o=On.getAll().find((t=>t.match(e.type)));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t)}function $n(e,t){let o=e;e.left!==e.right&&(o={...e,left:e.left+1});const i=[Ko(o)],r=t.getActiveSheetId(),n=t.getCell({sheetId:r,col:e.left,row:e.top});if(1===vi(e)&&n?.content)return{type:"scorecard",title:"",background:n.style?.fillColor||void 0,keyValue:Ko(e),baselineMode:ie,baselineColorUp:se,baselineColorDown:re};let a="";const l=t.getEvaluatedCellsInZone(r,{...o,bottom:o.top}),c=!!l.find((e=>e.type!==ms.empty&&e.type!==ms.number));if(c){const e=l.filter((e=>e.type!==ms.error&&e.type!==ms.empty)).map((e=>e.formattedValue)),t=e.splice(-1)[0];a=e.join(", "),t&&(a+=(a?" "+s("and")+" ":"")+t)}let h;e.left!==e.right&&(h=Ko({...e,right:e.left}));const d=o.right===o.left?"none":"top";return Cn(h?t.getRangeFromSheetXC(r,h):void 0,t)?{title:a,dataSets:i,labelsAsText:!1,stacked:!1,aggregated:!1,labelRange:h,type:"line",dataSetsHaveTitle:c,verticalAxisPosition:"left",legendPosition:d}:{title:a,dataSets:i,labelRange:h,type:"bar",stacked:!1,aggregated:!1,dataSetsHaveTitle:c,verticalAxisPosition:"left",legendPosition:d}}const Wn=[ms.number,ms.error,ms.text,ms.boolean];function Gn(e,t,o,i,s){let n=ws.Success,a=i.right>i.left;if(e.model.getters.doesIntersectMerge(t,i)){let o;a=!1;for(let s=i.top;s<=i.bottom;s++){o=[];for(let r=i.left;r<=i.right;r++){let i=e.model.getters.getMerge({sheetId:t,col:r,row:s});i&&!o.includes(i.id.toString())&&o.push(i.id.toString())}if(o.length>=2){a=!0;break}}}const{col:l,row:c}=o;if(a)n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s});else{const o=e.model.getters.getContiguousZone(t,i);si(o,i)?n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s}):e.askConfirmation(r("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{i=o,n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s})}),(()=>{n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s})}))}if(n.isCancelledBecause(63)){const{col:t,row:s}=o;e.model.selection.selectZone({cell:{col:t,row:s},zone:i}),e.raiseError(r("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function qn(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(r("This operation is not allowed with multiple selections."))}const Zn={filterOverlap:r("You cannot create overlapping filters."),nonContinuousTargets:r("A filter can only be created on a continuous selection."),mergeInFilter:r("You can't create a filter over a range that contains a merge.")};function jn(e,t,o){const i=e.model.dispatch("CREATE_FILTER_TABLE",{target:o,sheetId:t});i.isCancelledBecause(78)?e.raiseError(Zn.filterOverlap):i.isCancelledBecause(80)?e.raiseError(Zn.mergeInFilter):i.isCancelledBecause(81)&&e.raiseError(Zn.nonContinuousTargets)}const Yn={wrongPasteSelection:r("This operation is not allowed with multiple selections."),willRemoveExistingMerge:r("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:r("Cannot do a special paste of a figure."),frozenPaneOverlap:r("Cannot paste merged cells over a frozen pane.")};function Xn(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(Yn.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(Yn.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(Yn.wrongFigurePasteOption):t.reasons.includes(75)&&e.raiseError(Yn.frozenPaneOverlap))}function Kn(e,t,o){const i=e.model.dispatch("PASTE",{target:t,pasteOption:o});Xn(e,i)}function Qn(e,t,o){const i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:o});Xn(e,i)}function Jn(e){const t=e.model.getters.getActiveCols();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}function ea(e){const t=e.model.getters.getActiveRows();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function ta(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function oa(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const ia=async e=>sa(e,"onlyValue");async function sa(e,t){const o=e.model.getters.getClipboardTextContent(),i=await e.clipboard.readText();switch(i.status){case"ok":const s=e.model.getters.getSelectedZones();i&&i.content!==o?Qn(e,s,i.content):Kn(e,s,t);break;case"notImplemented":e.raiseError(r("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(r("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const ra=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("ROW");return e.model.getters.canRemoveHeaders(t,"ROW",o)},na=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("COL");return e.model.getters.canRemoveHeaders(t,"COL",o)},aa=e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.min(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.top,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:o,quantity:i,dimension:"ROW"})},la=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.min(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.left,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:o,quantity:i})},ca=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.max(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.right,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:o,quantity:i})};const ha=async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),o=e.model.uuidGenerator.uuidv4(),i=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(r("An unexpected error occurred during the image transfer"))}}(e);if(!i)throw new Error("No image provider was given to the environment");const s=Dn(e.model.getters,i.size),n=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:s,scrollY:r}=e.getActiveSheetScrollInfo(),n=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,n.width-o),c=Math.min(a.height,n.height-i);return{x:o+s+Math.max(0,(l-t.width)/2),y:i+r+Math.max(0,(c-t.height)/2)}}(e.model.getters,s);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:o,position:n,size:s,definition:i})}},da=e=>ta(e,"0.00%"),ua=e=>{let{col:t,row:o}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:o,popoverType:"LinkEditor"})},ga=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)},pa=e=>1===e.model.getters.getSelectedZones().length,ma={name:r("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},fa={name:r("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},ba={name:r("Copy"),description:"Ctrl+C",isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch("COPY"),await e.clipboard.write(e.model.getters.getClipboardContent())},icon:"o-spreadsheet-Icon.COPY"},va={name:r("Cut"),description:"Ctrl+X",execute:async e=>{qn(e),await e.clipboard.write(e.model.getters.getClipboardContent())},icon:"o-spreadsheet-Icon.CUT"},Sa={name:r("Paste"),description:"Ctrl+V",execute:async e=>sa(e),icon:"o-spreadsheet-Icon.PASTE"},Ca={name:r("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},Ea={name:r("Paste value only"),description:"Ctrl+Shift+V",execute:ia},wa={name:r("Paste format only"),execute:e=>Kn(e,e.model.getters.getSelectedZones(),"onlyFormat")},xa={name:r("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},icon:"o-spreadsheet-Icon.FIND_AND_REPLACE"},ya={name:r("Delete values"),execute:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},Ia={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Delete rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?r("Delete row %s",(t+1).toString()):r("Delete rows %s - %s",(t+1).toString(),(o+1).toString())},execute:e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.top;e<=o.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:ra},Ra={...Ia,isVisible:pa},Ta={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Clear rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?r("Clear row %s",(t+1).toString()):r("Clear rows %s - %s",(t+1).toString(),(o+1).toString())},execute:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveRows()].map((o=>e.model.getters.getRowsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}},Aa={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Delete columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?r("Delete column %s",Pt(t)):r("Delete columns %s - %s",Pt(t),Pt(o))},execute:e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.left;e<=o.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:na},Oa={...Aa,isVisible:pa},Ma={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Clear columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?r("Clear column %s",Pt(t)):r("Clear columns %s - %s",Pt(t),Pt(o))},execute:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveCols()].map((o=>e.model.getters.getColsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}},Na={name:r("Delete cells"),isVisible:pa},_a={name:r("Delete cell and shift up"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});Xn(e,o)}},Fa={name:r("Delete cell and shift left"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});Xn(e,o)}},Da={name:r("Merge cells"),isEnabled:e=>!La(e),isActive:e=>Pa(e),execute:e=>function(e){if(La(e))return;const t=e.model.getters.getSelectedZones(),o=[t[t.length-1]],i=e.model.getters.getActiveSheetId();Pa(e)?e.model.dispatch("REMOVE_MERGE",{sheetId:i,target:o}):function(e,t,o){const i=e.model.dispatch("ADD_MERGE",{sheetId:t,target:o});i.isCancelledBecause(80)?e.raiseError(Bn.MergeInFilter):i.isCancelledBecause(3)&&e.askConfirmation(Bn.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:o,force:!0})}))}(e,i,o)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"};function La(e){const t=e.model.getters.getSelectedZones(),{top:o,left:i,right:s,bottom:r}=e.model.getters.getSelectedZone(),{sheetId:n}=e.model.getters.getActivePosition(),{xSplit:a,ySplit:l}=e.model.getters.getPaneDivisions(n);return t.length>1||o===r&&i===s||i<a&&a<=s||o<l&&l<=r}function Pa(e){if(!La(e)){const t=e.model.getters.getSelectedZones(),{col:o,row:i,sheetId:s}=e.model.getters.getActivePosition(),r=e.model.getters.expandZone(s,fi({col:o,row:i}));return si(t[0],r)}return!1}var ka=Object.freeze({__proto__:null,undo:ma,redo:fa,copy:ba,cut:va,paste:Sa,pasteSpecial:Ca,pasteSpecialValue:Ea,pasteSpecialFormat:wa,findAndReplace:xa,deleteValues:ya,deleteRows:Ia,deleteRow:Ra,clearRows:Ta,deleteCols:Aa,deleteCol:Oa,clearCols:Ma,deleteCells:Na,deleteCellShiftUp:_a,deleteCellShiftLeft:Fa,mergeCells:Da});const Ua=/(.*?)\((.*?)\)(.*)/,Va=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function za(e,t=""){return function(e){let t,o=e.match(Ua),i=o[1].trim(),s=[],r=!1,n=!1,a=!1;for(let e of o[2].split(",")){const o=e.trim().toUpperCase();let i=Va.find((e=>o===e));i?s.push(i):"RANGE<ANY>"===o?s.push("RANGE"):"OPTIONAL"===o?r=!0:"REPEATING"===o?n=!0:"LAZY"===o?a=!0:o.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}let l=o[3].trim();const c={name:i,description:l,type:s};r&&(c.optional=!0);n&&(c.repeating=!0);a&&(c.lazy=!0);void 0!==t&&(c.default=!0,c.defaultValue=t);return c}(`${e} ${t}`)}function Ba(e){let t=0,o=0,i=0;for(let s of e.args)t++,s.optional||s.repeating||s.default||o++,s.repeating&&i++;const s=e;return s.minArgRequired=o,s.maxArgPossible=i?1/0:t,s.nbrArgRepeating=i,s.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const o=e-t;return e=>{if(e<=o)return e;return o+((e-o)%t||t)}}(t,i),s.hidden=e.hidden||!1,s}const Ha={description:r("Apply a large number format"),args:[za("value (number)",r("The number.")),za("unit (string, optional)",r("The formatting unit. Use 'k', 'm', or 'b' to force the unit"))],returns:["NUMBER"],computeFormat:(e,t)=>{const o=Math.abs(Wi(e.value)),i=e.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return yo(i,1e3,"k");case"m":return yo(i,1e6,"m");case"b":return yo(i,1e9,"b");default:throw new Error(r("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?yo(i,0,""):o<1e8?yo(i,1e3,"k"):o<1e11?yo(i,1e6,"m"):yo(i,1e9,"b")},compute:function(e){return Wi(e)}};var $a=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Ha});const Wa=/^-?[a-z0-9]+$/i,Ga={description:r("Absolute value of a number."),args:[za("value (number)",r("The number of which to return the absolute value."))],returns:["NUMBER"],compute:function(e){return Math.abs(Wi(e))},isExported:!0},qa={description:r("Inverse cosine of a value, in radians."),args:[za("value (number)",r("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>Math.abs(t)<=1),r("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},Za={description:r("Inverse hyperbolic cosine of a number."),args:[za("value (number)",r("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>t>=1),r("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},ja={description:r("Inverse cotangent of a value."),args:[za("value (number)",r("The value for which to calculate the inverse cotangent."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Ya={description:r("Inverse hyperbolic cotangent of a value."),args:[za("value (number)",r("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>Math.abs(t)>1),r("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},Xa={description:r("Inverse sine of a value, in radians."),args:[za("value (number)",r("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>Math.abs(t)<=1),r("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Ka={description:r("Inverse hyperbolic sine of a number."),args:[za("value (number)",r("The value for which to calculate the inverse hyperbolic sine."))],returns:["NUMBER"],compute:function(e){return Math.asinh(Wi(e))},isExported:!0},Qa={description:r("Inverse tangent of a value, in radians."),args:[za("value (number)",r("The value for which to calculate the inverse tangent."))],returns:["NUMBER"],compute:function(e){return Math.atan(Wi(e))},isExported:!0},Ja={description:r("Angle from the X axis to a point (x,y), in radians."),args:[za("x (number)",r("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),za("y (number)",r("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],returns:["NUMBER"],compute:function(e,t){const o=Wi(e),i=Wi(t);return Hi((()=>0!==o||0!==i),r("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(i,o)},isExported:!0},el={description:r("Inverse hyperbolic tangent of a number."),args:[za("value (number)",r("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>Math.abs(t)<1),r("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},tl={description:r("Rounds number up to nearest multiple of factor."),args:[za("value (number)",r("The value to round up to the nearest integer multiple of factor.")),za("factor (number, default=1)",r("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){const o=Wi(e),i=Wi(t);return Hi((()=>i>=0||o<=0),r("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.ceil(o/i)*i:0},isExported:!0},ol={description:r("Rounds number up to nearest multiple of factor."),args:[za("number (number)",r("The value to round up to the nearest integer multiple of significance.")),za("significance (number, default=1)",r("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),za("mode (number, default=0)",r("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1,o=0){let i=Wi(t);if(0===i)return 0;const s=Wi(e);if(i=Math.abs(i),s>=0)return Math.ceil(s/i)*i;return 0===Wi(o)?-Math.floor(Math.abs(s)/i)*i:-Math.ceil(Math.abs(s)/i)*i},isExported:!0},il={description:r("Rounds number up to nearest multiple of factor."),args:[za("number (number)",r("The value to round up to the nearest integer multiple of significance.")),za("significance (number, default=1)",r("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){return ol.compute(e,t,0)},isExported:!0},sl={description:r("Cosine of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the cosine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.cos(Wi(e))},isExported:!0},rl={description:r("Hyperbolic cosine of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic cosine of."))],returns:["NUMBER"],compute:function(e){return Math.cosh(Wi(e))},isExported:!0},nl={description:r("Cotangent of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the cotangent of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},al={description:r("Hyperbolic cotangent of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic cotangent of."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},ll={description:r("Number of empty values."),args:[za("value1 (any, range)",r("The first value or range in which to count the number of blanks.")),za("value2 (any, range, repeating)",r("Additional values or ranges in which to count the number of blanks."))],returns:["NUMBER"],compute:function(...e){return is(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},cl={description:r("A conditional count across a range."),args:[za("range (range)",r("The range that is tested against criterion.")),za("criterion (string)",r("The pattern or test to apply to range."))],returns:["NUMBER"],compute:function(...e){let t=0;return cs(e,((e,o)=>{t+=1})),t},isExported:!0},hl={description:r("Count values depending on multiple criteria."),args:[za("criteria_range1 (range)",r("The range to check against criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1.")),za("criteria_range2 (any, range, repeating)",r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),za("criterion2 (string, repeating)",r("Additional criteria to check."))],returns:["NUMBER"],compute:function(...e){let t=0;return cs(e,((e,o)=>{t+=1})),t},isExported:!0};function dl(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const ul={description:r("Counts number of unique values in a range."),args:[za("value1 (any, range)",r("The first value or range to consider for uniqueness.")),za("value2 (any, range, repeating)",r("Additional values or ranges to consider for uniqueness."))],returns:["NUMBER"],compute:function(...e){return is(e,((e,t)=>dl(t)?e.add(t):e),new Set).size}},gl={description:r("Counts number of unique values in a range, filtered by a set of criteria."),args:[za("range (range)",r("The range of cells from which the number of unique values will be counted.")),za("criteria_range1 (range)",r("The range of cells over which to evaluate criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),za("criteria_range2 (any, range, repeating)",r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),za("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=new Set;return cs(t,((t,i)=>{const s=e[t][i];dl(s)&&o.add(s)})),o.size}},pl={description:r("Cosecant of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the cosecant of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},ml={description:r("Hyperbolic cosecant of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic cosecant of."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},fl={description:r("Converts from another base to decimal."),args:[za("value (string)",r("The number to convert.")),za(",base (number)",r("The base to convert the value from."))],returns:["NUMBER"],compute:function(e,t){let o=Wi(t);o=Math.floor(o),Hi((()=>2<=o&&o<=36),r("The base (%s) must be between 2 and 36 inclusive.",o.toString()));const i=ji(e);if(""===i)return 0;Hi((()=>!!Wa.test(i)),r("The value (%s) must be a valid base %s representation.",i,o.toString()));const s=parseInt(i,o);return Hi((()=>!isNaN(s)),r("The value (%s) must be a valid base %s representation.",i,o.toString())),s},isExported:!0},bl={description:r("Converts an angle value in radians to degrees."),args:[za("angle (number)",r("The angle to convert from radians to degrees."))],returns:["NUMBER"],compute:function(e){return 180*Wi(e)/Math.PI},isExported:!0},vl={description:r("Euler's number, e (~2.718) raised to a power."),args:[za("value (number)",r("The exponent to raise e."))],returns:["NUMBER"],compute:function(e){return Math.exp(Wi(e))},isExported:!0},Sl={description:r("Rounds number down to nearest multiple of factor."),args:[za("value (number)",r("The value to round down to the nearest integer multiple of factor.")),za("factor (number, default=1)",r("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){const o=Wi(e),i=Wi(t);return Hi((()=>i>=0||o<=0),r("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.floor(o/i)*i:0},isExported:!0},Cl={description:r("Rounds number down to nearest multiple of factor."),args:[za("number (number)",r("The value to round down to the nearest integer multiple of significance.")),za("significance (number, default=1)",r("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),za("mode (number, default=0)",r("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1,o=0){let i=Wi(t);if(0===i)return 0;const s=Wi(e);if(i=Math.abs(i),s>=0)return Math.floor(s/i)*i;return 0===Wi(o)?-Math.ceil(Math.abs(s)/i)*i:-Math.floor(Math.abs(s)/i)*i},isExported:!0},El={description:r("Rounds number down to nearest multiple of factor."),args:[za("number (number)",r("The value to round down to the nearest integer multiple of significance.")),za("significance (number, default=1)",r("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){return Cl.compute(e,t,0)},isExported:!0},wl={description:r("Whether the provided value is even."),args:[za("value (number)",r("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Gi(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},xl={description:r("Rounds number up to nearest multiple of factor."),args:[za("number (number)",r("The value to round up to the nearest integer multiple of significance.")),za("significance (number, default=1)",r("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){return ol.compute(e,t,0)},isExported:!0},yl={description:r("Whether the provided value is even."),args:[za("value (number)",r("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Gi(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Il={description:r("The logarithm of a number, base e (euler's number)."),args:[za("value (number)",r("The value for which to calculate the logarithm, base e."))],returns:["NUMBER"],compute:function(e){const t=Wi(e);return Hi((()=>t>0),r("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},Rl={description:r("Modulo (remainder) operator."),args:[za("dividend (number)",r("The number to be divided to find the remainder.")),za("divisor (number)",r("The number to divide by."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Wi(t);Hi((()=>0!==o),r("The divisor must be different from 0."));const i=Wi(e)%o;return i>0&&o<0||i<0&&o>0?i+o:i},isExported:!0},Tl={description:r("Rounds a number up to the nearest odd integer."),args:[za("value (number)",r("The value to round to the next greatest odd number."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Wi(e);let o=Math.ceil(Math.abs(t));return o=1&o?o:o+1,t<0?-o:o},isExported:!0},Al={description:r("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Ol={description:r("A number raised to a power."),args:[za("base (number)",r("The number to raise to the exponent power.")),za("exponent (number)",r("The exponent to raise base to."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Wi(e),i=Wi(t);return Hi((()=>o>=0||Number.isInteger(i)),r("The exponent (%s) must be an integer when the base is negative.",i.toString())),Math.pow(o,i)},isExported:!0},Ml={description:r("Result of multiplying a series of numbers together."),args:[za("factor1 (number, range<number>)",r("The first number or range to calculate for the product.")),za("factor2 (number, range<number>, repeating)",r("More numbers or ranges to calculate for the product."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0,o=1;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(o*=i,t+=1);else null!=i&&(o*=Gi(i),t+=1);return 0===t?0:o},isExported:!0},Nl={description:r("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},_l={description:r("Random integer between two values, inclusive."),args:[za("low (number)",r("The low end of the random range.")),za("high (number)",r("The high end of the random range."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){let o=Wi(e);Number.isInteger(o)||(o=Math.ceil(o));let i=Wi(t);return Number.isInteger(i)||(i=Math.floor(i)),Hi((()=>o<=i),r("The high (%s) must be greater than or equal to the low (%s).",i.toString(),o.toString())),o+Math.ceil((i-o+1)*Math.random())-1},isExported:!0},Fl={description:r("Rounds a number according to standard rules."),args:[za("value (number)",r("The value to round to places number of places.")),za("places (number, default=0)",r("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Wi(e);let i=Wi(t);const s=Math.abs(o);let r;return 0===i?r=Math.round(s):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.round(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},Dl={description:r("Rounds down a number."),args:[za("value (number)",r("The value to round to places number of places, always rounding down.")),za("places (number, default=0)",r("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Wi(e);let i=Wi(t);const s=Math.abs(o);let r;return 0===i?r=Math.floor(s):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.floor(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},Ll={description:r("Rounds up a number."),args:[za("value (number)",r("The value to round to places number of places, always rounding up.")),za("places (number, default=0)",r("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Wi(e);let i=Wi(t);const s=Math.abs(o);let r;return 0===i?r=Math.ceil(s):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.ceil(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},Pl={description:r("Secant of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the secant of, in radians."))],returns:["NUMBER"],compute:function(e){return 1/Math.cos(Wi(e))},isExported:!0},kl={description:r("Hyperbolic secant of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic secant of."))],returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Wi(e))},isExported:!0},Ul={description:r("Sine of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the sine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.sin(Wi(e))},isExported:!0},Vl={description:r("Hyperbolic sine of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic sine of."))],returns:["NUMBER"],compute:function(e){return Math.sinh(Wi(e))},isExported:!0},zl={description:r("Positive square root of a positive number."),args:[za("value (number)",r("The number for which to calculate the positive square root."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Wi(e);return Hi((()=>t>=0),r("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},Bl={description:r("Sum of a series of numbers and/or cells."),args:[za("value1 (number, range<number>)",r("The first number or range to add together.")),za("value2 (number, range<number>, repeating)",r("Additional numbers or ranges to add to value1."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){return ss(e,((e,t)=>e+t),0)},isExported:!0},Hl={description:r("A conditional sum across a range."),args:[za("criteria_range (range)",r("The range which is tested against criterion.")),za("criterion (string)",r("The pattern or test to apply to range.")),za("sum_range (range, default=criteria_range)",r("The range to be summed, if different from range."))],returns:["NUMBER"],compute:function(e,t,o){void 0===o&&(o=e);let i=0;return cs([e,t],((e,t)=>{const s=o[e][t];"number"==typeof s&&(i+=s)})),i},isExported:!0},$l={description:r("Sums a range depending on multiple criteria."),args:[za("sum_range (range)",r("The range to sum.")),za("criteria_range1 (range)",r("The range to check against criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1.")),za("criteria_range2 (any, range, repeating)",r("Additional ranges to check.")),za("criterion2 (string, repeating)",r("Additional criteria to check."))],returns:["NUMBER"],compute:function(e,...t){let o=0;return cs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o+=s)})),o},isExported:!0},Wl={description:r("Tangent of an angle provided in radians."),args:[za("angle (number)",r("The angle to find the tangent of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.tan(Wi(e))},isExported:!0},Gl={description:r("Hyperbolic tangent of any real number."),args:[za("value (number)",r("Any real value to calculate the hyperbolic tangent of."))],returns:["NUMBER"],compute:function(e){return Math.tanh(Wi(e))},isExported:!0},ql={description:r("Truncates a number."),args:[za("value (number)",r("The value to be truncated.")),za("places (number, default=0)",r("The number of significant digits to the right of the decimal point to retain."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Wi(e);let i=Wi(t);return 0===i?Math.trunc(o):(Number.isInteger(i)||(i=Math.trunc(i)),Math.trunc(o*Math.pow(10,i))/Math.pow(10,i))},isExported:!0};var Zl=Object.freeze({__proto__:null,ABS:Ga,ACOS:qa,ACOSH:Za,ACOT:ja,ACOTH:Ya,ASIN:Xa,ASINH:Ka,ATAN:Qa,ATAN2:Ja,ATANH:el,CEILING:tl,CEILING_MATH:ol,CEILING_PRECISE:il,COS:sl,COSH:rl,COT:nl,COTH:al,COUNTBLANK:ll,COUNTIF:cl,COUNTIFS:hl,COUNTUNIQUE:ul,COUNTUNIQUEIFS:gl,CSC:pl,CSCH:ml,DECIMAL:fl,DEGREES:bl,EXP:vl,FLOOR:Sl,FLOOR_MATH:Cl,FLOOR_PRECISE:El,ISEVEN:wl,ISO_CEILING:xl,ISODD:yl,LN:Il,MOD:Rl,ODD:Tl,PI:Al,POWER:Ol,PRODUCT:Ml,RAND:Nl,RANDBETWEEN:_l,ROUND:Fl,ROUNDDOWN:Dl,ROUNDUP:Ll,SEC:Pl,SECH:kl,SIN:Ul,SINH:Vl,SQRT:zl,SUM:Bl,SUMIF:Hl,SUMIFS:$l,TAN:Wl,TANH:Gl,TRUNC:ql});function jl(e,t,o){let i=[],s=[],n=0,a=0;es([e],(e=>{i.push(e),n+=1})),es([t],(e=>{s.push(e),a+=1})),Hi((()=>n===a),r("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",n.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<n;e++){const t=i[e],o=s[e];"number"==typeof t&&"number"==typeof o&&(l+=1,c+=t,h+=o)}Hi((()=>0!==l&&(!o||1!==l)),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let g=0;for(let e=0;e<n;e++){const t=i[e],o=s[e];"number"==typeof t&&"number"==typeof o&&(g+=(t-d)*(o-u))}return g/(l-(o?1:0))}function Yl(e,t,o){let i=0,s=0;const n=o?rs:ss;s=n(e,((e,t)=>(i+=1,e+t)),0),Hi((()=>0!==i&&(!t||1!==i)),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=s/i;return n(e,((e,t)=>e+Math.pow(t-a,2)),0)/(i-(t?1:0))}function Xl(e,t,o){const i=Wi(t);Hi((()=>o?0<=i&&i<=1:0<i&&i<1),r("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let s,n=[],a=0;return es(e,(e=>{"number"==typeof e&&(s=us(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(s+1,0,e),a++)})),Hi((()=>0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),o||Hi((()=>1/(a+1)<=i&&i<=a/(a+1)),r("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),oo(n,i,o)}const Kl={description:r("Average magnitude of deviations from mean."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){let t=0;const o=ss(e,((e,o)=>(t+=1,e+o)),0);Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const i=o/t;return ss(e,((e,t)=>e+Math.abs(i-t)),0)/t},isExported:!0},Ql={description:r("Numerical average value in a dataset, ignoring text."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when calculating the average value.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0;const o=ss(e,((e,o)=>(t+=1,e+o)),0);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},Jl=r("[[FUNCTION_NAME]] has mismatched range sizes."),ec=r("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),tc={description:r("Weighted average."),args:[za("values (number, range<number>)",r("Values to average.")),za("weights (number, range<number>)",r("Weights for each corresponding value.")),za("additional_values (number, range<number>, repeating)",r("Additional values to average.")),za("additional_weights (number, range<number>, repeating)",r("Additional weights."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t,o,i=0,s=0;Hi((()=>e.length%2==0),r("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let n=0;n<e.length-1;n+=2)if(t=e[n],o=e[n+1],Array.isArray(t)){Hi((()=>Array.isArray(o)),Jl);let e=t.length,n=t[0].length;Hi((()=>e===o.length&&n===o[0].length),Jl);for(let a=0;a<e;a++)for(let e=0;e<n;e++){let n=t[a][e],l=o[a][e],c="number"==typeof n,h="number"==typeof l;Hi((()=>c===h),r("[[FUNCTION_NAME]] expects number values.")),h&&(Hi((()=>l>=0),ec),i+=n*l,s+=l)}}else o=Wi(o),t=Wi(t),Hi((()=>o>=0),ec),i+=t*o,s+=o;return Hi((()=>0!==s),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/s}},oc={description:r("Numerical average value in a dataset."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when calculating the average value.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0;const o=rs(e,((e,o)=>(t+=1,e+o)),0);return Hi((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},ic={description:r("Average of values depending on criteria."),args:[za("criteria_range (range)",r("The range to check against criterion.")),za("criterion (string)",r("The pattern or test to apply to criteria_range.")),za("average_range (range, default=criteria_range)",r("The range to average. If not included, criteria_range is used for the average instead."))],returns:["NUMBER"],compute:function(e,t,o){null==o&&(o=e);let i=0,s=0;return cs([e,t],((t,r)=>{const n=(o||e)[t][r];"number"==typeof n&&(i+=1,s+=n)})),Hi((()=>0!==i),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/i},isExported:!0},sc={description:r("Average of values depending on multiple criteria."),args:[za("average_range (range)",r("The range to average.")),za("criteria_range1 (range)",r("The range to check against criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1.")),za("criteria_range2 (any, range, repeating)",r("Additional criteria_range and criterion to check.")),za("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=0,i=0;return cs(t,((t,s)=>{const r=e[t][s];"number"==typeof r&&(o+=1,i+=r)})),Hi((()=>0!==o),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},rc={description:r("The number of numeric values in dataset."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when counting.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){let t=0;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(t+=1);else("string"!=typeof o||Jt(o)||ye(o))&&(t+=1);return t},isExported:!0},nc={description:r("The number of values in a dataset."),args:[za("value1 (any, range)",r("The first value or range to consider when counting.")),za("value2 (any, range, repeating)",r("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){return is(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},ac={description:r("The covariance of a dataset."),args:[za("data_y (any, range)",r("The range representing the array or matrix of dependent data.")),za("data_x (any, range)",r("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return jl(e,t,!1)},isExported:!0},lc={description:r("The covariance of a dataset."),args:[za("data_y (any, range)",r("The range representing the array or matrix of dependent data.")),za("data_x (any, range)",r("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return jl(e,t,!1)},isExported:!0},cc={description:r("The sample covariance of a dataset."),args:[za("data_y (any, range)",r("The range representing the array or matrix of dependent data.")),za("data_x (any, range)",r("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return jl(e,t,!0)},isExported:!0},hc={description:r("Nth largest element from a data set."),args:[za("data (any, range)",r("Array or range containing the dataset to consider.")),za("n (number)",r("The rank from largest to smallest of the element to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){const o=Math.trunc(Wi(t));let i,s=[],n=0;es([e],(e=>{"number"==typeof e&&(i=us(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(i+1,0,e),n++,n>o&&(s.shift(),n--))}));const a=s.shift();return Hi((()=>void 0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),Hi((()=>n>=o),r("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},dc={description:r("Maximum value in a numeric dataset."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when calculating the maximum value.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=ss(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},uc={description:r("Maximum numeric value in a dataset."),args:[za("value1 (any, range)",r("The first value or range to consider when calculating the maximum value.")),za("value2 (any, range, repeating)",r("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=rs(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},gc={description:r("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[za("range (range)",r("The range of cells from which the maximum will be determined.")),za("criteria_range1 (range)",r("The range of cells over which to evaluate criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),za("criteria_range2 (any, range, repeating)",r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),za("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=-1/0;return cs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o=o<s?s:o)})),o===-1/0?0:o},isExported:!0},pc={description:r("Median value in a numeric dataset."),args:[za("value1 (any, range)",r("The first value or range to consider when calculating the median value.")),za("value2 (any, range, repeating)",r("Additional values or ranges to consider when calculating the median value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=[];return ts(e,(e=>{t.push(e)})),Xl(t,.5,!0)},isExported:!0},mc={description:r("Minimum value in a numeric dataset."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when calculating the minimum value.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=ss(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},fc={description:r("Minimum numeric value in a dataset."),args:[za("value1 (number, range<number>)",r("The first value or range to consider when calculating the minimum value.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=rs(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},bc={description:r("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[za("range (range)",r("The range of cells from which the minimum will be determined.")),za("criteria_range1 (range)",r("The range of cells over which to evaluate criterion1.")),za("criterion1 (string)",r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),za("criteria_range2 (any, range, repeating)",r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),za("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=1/0;return cs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o=o>s?s:o)})),o===1/0?0:o},isExported:!0},vc={description:r("Value at a given percentile of a dataset."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("percentile (number)",r("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Cc.compute(e,t)},isExported:!0},Sc={description:r("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("percentile (number)",r("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Xl([e],t,!1)},isExported:!0},Cc={description:r("Value at a given percentile of a dataset."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("percentile (number)",r("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Xl([e],t,!0)},isExported:!0},Ec={description:r("Value nearest to a specific quartile of a dataset."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("quartile_number (number)",r("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return xc.compute(e,t)},isExported:!0},wc={description:r("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("quartile_number (number)",r("Which quartile value, exclusive of 0 and 4, to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Xl([e],.25*Math.trunc(Wi(t)),!1)},isExported:!0},xc={description:r("Value nearest to a specific quartile of a dataset."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("quartile_number (number)",r("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Xl([e],.25*Math.trunc(Wi(t)),!0)},isExported:!0},yc={description:r("Nth smallest element in a data set."),args:[za("data (any, range)",r("The array or range containing the dataset to consider.")),za("n (number)",r("The rank from smallest to largest of the element to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){const o=Math.trunc(Wi(t));let i,s=[],n=0;es([e],(e=>{"number"==typeof e&&(i=us(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(i+1,0,e),n++,n>o&&(s.pop(),n--))}));const a=s.pop();return Hi((()=>void 0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),Hi((()=>n>=o),r("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Ic={description:r("Standard deviation."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Nc.compute(...e))},isExported:!0},Rc={description:r("Standard deviation of entire population."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(_c.compute(...e))},isExported:!0},Tc={description:r("Standard deviation."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Fc.compute(...e))},isExported:!0},Ac={description:r("Standard deviation of sample (text as 0)."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Dc.compute(...e))},isExported:!0},Oc={description:r("Standard deviation of entire population."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Lc.compute(...e))},isExported:!0},Mc={description:r("Standard deviation of entire population (text as 0)."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Pc.compute(...e))},isExported:!0},Nc={description:r("Variance."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!0,!1)},isExported:!0},_c={description:r("Variance of entire population."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!1,!1)},isExported:!0},Fc={description:r("Variance."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!0,!1)},isExported:!0},Dc={description:r("Variance of sample (text as 0)."),args:[za("value1 (number, range<number>)",r("The first value or range of the sample.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!0,!0)},isExported:!0},Lc={description:r("Variance of entire population."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!1,!1)},isExported:!0},Pc={description:r("Variance of entire population (text as 0)."),args:[za("value1 (number, range<number>)",r("The first value or range of the population.")),za("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Yl(e,!1,!0)},isExported:!0};var kc=Object.freeze({__proto__:null,AVEDEV:Kl,AVERAGE:Ql,AVERAGE_WEIGHTED:tc,AVERAGEA:oc,AVERAGEIF:ic,AVERAGEIFS:sc,COUNT:rc,COUNTA:nc,COVAR:ac,COVARIANCE_P:lc,COVARIANCE_S:cc,LARGE:hc,MAX:dc,MAXA:uc,MAXIFS:gc,MEDIAN:pc,MIN:mc,MINA:fc,MINIFS:bc,PERCENTILE:vc,PERCENTILE_EXC:Sc,PERCENTILE_INC:Cc,QUARTILE:Ec,QUARTILE_EXC:wc,QUARTILE_INC:xc,SMALL:yc,STDEV:Ic,STDEV_P:Rc,STDEV_S:Tc,STDEVA:Ac,STDEVP:Oc,STDEVPA:Mc,VAR:Nc,VAR_P:_c,VAR_S:Fc,VARA:Dc,VARP:Lc,VARPA:Pc});function Uc(e,t,o){const i=new Map,s=e.length;for(let t=s-1;t>=0;t--)i.set(ji(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(r("The field must be a number or a string"));let n;if("number"==typeof t){if(n=Math.trunc(t)-1,n<0||s-1<n)throw new Error(r("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),s.toString()))}else{const e=ji(t).toUpperCase();if(n=i.get(e)??-1,-1===n)throw new Error(r("The field (%s) must be one of %s.",ji(t),[...i.keys()].toString()))}const a=o[0].length;if(a<2)throw new Error(r("The criteria range contains %s row, it must be at least 2 rows.",a.toString()));let l=new Set;const c=e[0].length;for(let t=1;t<a;t++){let s=[],r=!0;for(let n=0;n<o.length;n++){const a=ji(o[n][0]).toUpperCase(),l=i.get(a),h=o[n][t];if(void 0!==h){if(void 0===l){r=!1;break}s.push([e[l].slice(1,c)]),s.push(h)}}if(r){if(!(s.length>0)){l=new Set(Array(c-1).keys());break}cs(s,((e,t)=>{l.add(t)}),!0)}}const h=e[n];return[...l].map((e=>h[e+1]))}const Vc=[za("database (range)",r("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.")),za("field (any)",r("Indicates which column in database contains the values to be extracted and operated on.")),za("criteria (range)",r("An array or range containing zero or more criteria to filter the database values by before operating."))],zc={description:r("Average of a set of values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Ql.compute([i])},isExported:!0},Bc={description:r("Counts values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return rc.compute([i])},isExported:!0},Hc={description:r("Counts values and text from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return nc.compute([i])},isExported:!0},$c={description:r("Single value from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Hi((()=>1===i.length),r("More than one match found in DGET evaluation.")),i[0]},isExported:!0},Wc={description:r("Maximum of values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return dc.compute([i])},isExported:!0},Gc={description:r("Minimum of values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return mc.compute([i])},isExported:!0},qc={description:r("Product of values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Ml.compute([i])},isExported:!0},Zc={description:r("Standard deviation of population sample from table."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Ic.compute([i])},isExported:!0},jc={description:r("Standard deviation of entire population from table."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Oc.compute([i])},isExported:!0},Yc={description:r("Sum of values from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Bl.compute([i])},isExported:!0},Xc={description:r("Variance of population sample from table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Nc.compute([i])},isExported:!0},Kc={description:r("Variance of a population from a table-like range."),args:Vc,returns:["NUMBER"],compute:function(e,t,o){const i=Uc(e,t,o);return Lc.compute([i])},isExported:!0};var Qc=Object.freeze({__proto__:null,DAVERAGE:zc,DCOUNT:Bc,DCOUNTA:Hc,DGET:$c,DMAX:Wc,DMIN:Gc,DPRODUCT:qc,DSTDEV:Zc,DSTDEVP:jc,DSUM:Yc,DVAR:Xc,DVARP:Kc});var Jc;!function(e){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"}(Jc||(Jc={}));const eh={description:r("Converts year/month/day into a date."),args:[za("year (number)",r("The year component of the date.")),za("month (number)",r("The month component of the date.")),za("day (number)",r("The day component of the date."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){let i=Math.trunc(Wi(e));const s=Math.trunc(Wi(t)),n=Math.trunc(Wi(o));Hi((()=>0<=i&&i<=9999),r("The year (%s) must be between 0 and 9999 inclusive.",i.toString())),i<1900&&(i+=1900);const a=Te(new Date(i,s-1,n));return Hi((()=>a>=0),r("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},th={description:r("Calculates the number of days, months, or years between two dates."),args:[za("start_date (date)",r("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.")),za("end_date (date)",r("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.")),za("unit (string)",r('A text abbreviation for unit of time. Accepted values are "Y" (the number of whole years between start_date and end_date), "M" (the number of whole months between start_date and end_date), "D" (the number of days between start_date and end_date), "MD" (the number of days between start_date and end_date after subtracting whole months), "YM" (the number of whole months between start_date and end_date after subtracting whole years), "YD" (the number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart).'))],returns:["NUMBER"],compute:function(e,t,o){const i=ji(o).toUpperCase();Hi((()=>Object.values(Jc).includes(i)),((e,t)=>{const o=e.map((e=>`'${e}'`)).join(", ");return r("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,o)})(Object.values(Jc),ji(o)));const s=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Re(s),l=Re(n);switch(Hi((()=>n>=s),r("start_date (%s) should be on or before end_date (%s).",a.toLocaleDateString(),l.toLocaleDateString())),i){case Jc.WHOLE_YEARS:return Le(a,l);case Jc.WHOLE_MONTHS:return Fe(a,l);case Jc.WHOLE_DAYS:return De(a,l);case Jc.MONTH_WITHOUT_WHOLE_YEARS:return Fe(a,l)-12*Le(a,l);case Jc.DAYS_WITHOUT_WHOLE_MONTHS:let e=l.getDate()-a.getDate();if(e<0){e=Ae(new Date(l.getFullYear(),l.getMonth()-1,1))-Math.abs(e)}return e;case Jc.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return _e(e,t,1)<1}(s,n))return De(a,l);const e=new Date(a.getFullYear(),l.getMonth(),l.getDate());let t=De(a,e);return t<0&&(e.setFullYear(a.getFullYear()+1),t=De(a,e)),t}}},isExported:!0},oh={description:r("Converts a date string to a date value."),args:[za("date_string (string)",r("The string representing the date."))],returns:["NUMBER"],compute:function(e){const t=ji(e),o=ye(t);return Hi((()=>null!==o),r("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(o.value)},isExported:!0},ih={description:r("Day of the month that a specific date falls on."),args:[za("date (string)",r("The date from which to extract the day."))],returns:["NUMBER"],compute:function(e){return Qi(e).getDate()},isExported:!0},sh={description:r("Number of days between two dates."),args:[za("end_date (date)",r("The end of the date range.")),za("start_date (date)",r("The start of the date range."))],returns:["NUMBER"],compute:function(e,t){const o=Qi(e),i=Qi(t),s=o.getTime()-i.getTime();return Math.round(s/be)},isExported:!0},rh={description:r("Number of days between two dates on a 360-day year (months of 30 days)."),args:[za("start_date (date)",r("The start date to consider in the calculation.")),za("end_date (date)",r("The end date to consider in the calculation.")),za("method (number, default=0)",r("An indicator of what day count method to use. (0) US NASD method (1) European method"))],returns:["NUMBER"],compute:function(e,t,o=0){const i=Wi(e),s=Wi(t),r=Ki(o)?4:0,n=Ih.compute(e,t,r);return Math.sign(s-i)*Math.round(360*n)},isExported:!0},nh={description:r("Date a number of months before/after another date."),args:[za("start_date (date)",r("The date from which to calculate the result.")),za("months (number)",r("The number of months before (negative) or after (positive) 'start_date' to calculate."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){return Te(Me(Qi(e),Math.trunc(Wi(t)),!1))},isExported:!0},ah={description:r("Last day of a month before or after a date."),args:[za("start_date (date)",r("The date from which to calculate the result.")),za("months (number)",r("The number of months before (negative) or after (positive) 'start_date' to consider."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){const o=Qi(e),i=Math.trunc(Wi(t)),s=o.getFullYear(),r=o.getMonth();return Te(new Date(s,r+i+1,0))},isExported:!0},lh={description:r("Hour component of a specific time."),args:[za("time (date)",r("The time from which to calculate the hour component."))],returns:["NUMBER"],compute:function(e){return Qi(e).getHours()},isExported:!0},ch={description:r("ISO week number of the year."),args:[za("date (date)",r("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."))],returns:["NUMBER"],compute:function(e){const t=Qi(e),o=t.getFullYear();let i=1;for(;4!==new Date(o,0,i).getDay();)i+=1;const s=new Date(o,0,i-3);let r=31;for(;4!==new Date(o,11,r).getDay();)r-=1;const n=new Date(o,11,r+3);let a,l;switch(a=s.getTime()<=t.getTime()?t.getTime()<=n.getTime()?0:1:-1,a){case 0:l=s;break;case 1:l=new Date(o,11,r+3+1);break;case-1:let e=1;for(;4!==new Date(o-1,0,e).getDay();)e+=1;l=new Date(o-1,0,e-3)}const c=(t.getTime()-l.getTime())/be;return Math.floor(c/7)+1},isExported:!0},hh={description:r("Minute component of a specific time."),args:[za("time (date)",r("The time from which to calculate the minute component."))],returns:["NUMBER"],compute:function(e){return Qi(e).getMinutes()},isExported:!0},dh={description:r("Month of the year a specific date falls in"),args:[za("date (date)",r("The date from which to extract the month."))],returns:["NUMBER"],compute:function(e){return Qi(e).getMonth()+1},isExported:!0},uh={description:r("Net working days between two provided days."),args:[za("start_date (date)",r("The start date of the period from which to calculate the number of net working days.")),za("end_date (date)",r("The end date of the period from which to calculate the number of net working days.")),za("holidays (date, range<date>, optional)",r("A range or array constant containing the date serial numbers to consider holidays."))],returns:["NUMBER"],compute:function(e,t,o){return ph.compute(e,t,1,o)},isExported:!0};function gh(e){if("string"==typeof e){Hi((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),r('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let o=0;o<7;o++)"1"===e[o]&&t.push((o+1)%7);return t}if("number"==typeof e)return Hi((()=>1<=e&&e<=7||11<=e&&e<=17),r("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(r("The weekend must be a number or a string."))}const ph={description:r("Net working days between two dates (specifying weekends)."),args:[za("start_date (date)",r("The start date of the period from which to calculate the number of net working days.")),za("end_date (date)",r("The end date of the period from which to calculate the number of net working days.")),za("weekend (any, default=1)",r("A number or string representing which days of the week are considered weekends.")),za("holidays (date, range<date>, optional)",r("A range or array constant containing the dates to consider as holidays."))],returns:["NUMBER"],compute:function(e,t,o=1,i){const s=Qi(e),r=Qi(t),n=gh(o);let a=new Set;void 0!==i&&es([i],(e=>{const t=Qi(e);a.add(t.getTime())}));const l=s.getTime()>r.getTime(),c=new Date((l?s:r).getTime());let h=new Date((l?r:s).getTime());const d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)n.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},mh={description:r("Current date and time as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy hh:mm:ss",compute:function(){let e=new Date;e.setMilliseconds(0);const t=e.getTime()-fe.getTime(),o=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/be)+o},isExported:!0},fh={description:r("Minute component of a specific time."),args:[za("time (date)",r("The time from which to calculate the second component."))],returns:["NUMBER"],compute:function(e){return Qi(e).getSeconds()},isExported:!0},bh={description:r("Converts hour/minute/second into a time."),args:[za("hour (number)",r("The hour component of the time.")),za("minute (number)",r("The minute component of the time.")),za("second (number)",r("The second component of the time."))],returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,o){let i=Math.trunc(Wi(e)),s=Math.trunc(Wi(t)),n=Math.trunc(Wi(o));return s+=Math.floor(n/60),n=n%60+(n<0?60:0),i+=Math.floor(s/60),s=s%60+(s<0?60:0),i%=24,Hi((()=>i>=0),r("The function [[FUNCTION_NAME]] result cannot be negative")),i/24+s/1440+n/86400},isExported:!0},vh={description:r("Converts a time string into its serial number representation."),args:[za("time_string (string)",r("The string that holds the time representation."))],returns:["NUMBER"],compute:function(e){const t=ji(e),o=ye(t);Hi((()=>null!==o),r("The time_string (%s) cannot be parsed to date/time.",t));const i=o.value-Math.trunc(o.value);return i<0?1+i:i},isExported:!0},Sh={description:r("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=new Date;return Te(new Date(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Ch={description:r("Day of the week of the date provided (as number)."),args:[za("date (date)",r("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.")),za("type (number, default=1)",r("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const o=Qi(e),i=Math.round(Wi(t)),s=o.getDay();return Hi((()=>[1,2,3].includes(i)),r("The type (%s) must be 1, 2 or 3.",i.toString())),1===i?s+1:2===i?0===s?7:s:0===s?6:s-1},isExported:!0},Eh={description:r("Week number of the year."),args:[za("date (date)",r("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.")),za("type (number, default=1)",r("A number representing the day that a week starts on. Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const o=Qi(e),i=Math.round(Wi(t));if(Hi((()=>1===i||2===i||11<=i&&i<=17||21===i),r("The type (%s) is out of range.",i.toString())),21===i)return ch.compute(e);let s;s=1===i||2===i?i-1:i-10==7?0:i-10;const n=o.getFullYear();let a=1,l=new Date(n,0,a);for(;l.getDay()!==s;)a+=1,l=new Date(n,0,a);const c=(o.getTime()-l.getTime())/be;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},wh={description:r("Date after a number of workdays."),args:[za("start_date (date)",r("The date from which to begin counting.")),za("num_days (number)",r("The number of working days to advance from start_date. If negative, counts backwards.")),za("holidays (date, range<date>, optional)",r("A range or array constant containing the dates to consider holidays."))],returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){return xh.compute(e,t,1,o)},isExported:!0},xh={description:r("Date after a number of workdays (specifying weekends)."),args:[za("start_date (date)",r("The date from which to begin counting.")),za("num_days (number)",r("The number of working days to advance from start_date. If negative, counts backwards.")),za("weekend (any, default=1)",r("A number or string representing which days of the week are considered weekends.")),za("holidays (date, range<date>, optional)",r("A range or array constant containing the dates to consider holidays."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o=1,i){let s=Qi(e),n=Math.trunc(Wi(t));"string"==typeof o&&Hi((()=>"1111111"!==o),r("The weekend (%s) must be different from '1111111'.",o));const a=gh(o);let l=new Set;void 0!==i&&es([i],(e=>{const t=Qi(e);l.add(t.getTime())}));let c=new Date(s.getTime()),h=c.getTime();const d=Math.sign(n);let u=Math.abs(n);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),a.includes(c.getDay())||l.has(h)||(u-=1);const g=h-fe.getTime();return Math.round(g/be)},isExported:!0},yh={description:r("Year specified by a given date."),args:[za("date (date)",r("The date from which to extract the year."))],returns:["NUMBER"],compute:function(e){return Qi(e).getFullYear()},isExported:!0},Ih={description:r("Exact number of years between two dates."),args:[za("start_date (date)",r("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.")),za("end_date (date)",r("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.")),za("day_count_convention (number, default=0)",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o=0){let i=Math.trunc(Wi(e)),s=Math.trunc(Wi(t));const n=Math.trunc(Wi(o));return Hi((()=>i>=0),r("The start_date (%s) must be positive or null.",i.toString())),Hi((()=>s>=0),r("The end_date (%s) must be positive or null.",s.toString())),Hi((()=>0<=n&&n<=4),r("The day_count_convention (%s) must be between 0 and 4 inclusive.",n.toString())),_e(i,s,n)}},Rh={description:r("First day of the month preceding a date."),args:[za("date (date)",r("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Qi(e),o=t.getFullYear(),i=t.getMonth();return Te(new Date(o,i,1))}},Th={description:r("Last day of the month following a date."),args:[za("date (date)",r("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return ah.compute(e,0)}},Ah={description:r("Quarter of the year a specific date falls in"),args:[za("date (date)",r("The date from which to extract the quarter."))],returns:["NUMBER"],compute:function(e){return Math.ceil((Qi(e).getMonth()+1)/3)}},Oh={description:r("First day of the quarter of the year a specific date falls in."),args:[za("date (date)",r("The date from which to calculate the start of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Ah.compute(e),o=yh.compute(e);return Te(new Date(o,3*(t-1),1))}},Mh={description:r("Last day of the quarter of the year a specific date falls in."),args:[za("date (date)",r("The date from which to calculate the end of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Ah.compute(e),o=yh.compute(e);return Te(new Date(o,3*t,0))}},Nh={description:r("First day of the year a specific date falls in."),args:[za("date (date)",r("The date from which to calculate the start of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=yh.compute(e);return Te(new Date(t,0,1))}},_h={description:r("Last day of the year a specific date falls in."),args:[za("date (date)",r("The date from which to calculate the end of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=yh.compute(e);return Te(new Date(t+1,0,0))}};var Fh=Object.freeze({__proto__:null,DATE:eh,DATEDIF:th,DATEVALUE:oh,DAY:ih,DAYS:sh,DAYS360:rh,EDATE:nh,EOMONTH:ah,HOUR:lh,ISOWEEKNUM:ch,MINUTE:hh,MONTH:dh,NETWORKDAYS:uh,NETWORKDAYS_INTL:ph,NOW:mh,SECOND:fh,TIME:bh,TIMEVALUE:vh,TODAY:Sh,WEEKDAY:Ch,WEEKNUM:Eh,WORKDAY:wh,WORKDAY_INTL:xh,YEAR:yh,YEARFRAC:Ih,MONTH_START:Rh,MONTH_END:Th,QUARTER:Ah,QUARTER_START:Oh,QUARTER_END:Mh,YEAR_START:Nh,YEAR_END:_h});const Dh={description:r("Compare two numeric values, returning 1 if they're equal."),args:[za(" (number)",r("The first number to compare.")),za(" (number, default=0)",r("The second number to compare."))],returns:["NUMBER"],compute:function(e,t=0){return Wi(e)===Wi(t)?1:0},isExported:!0};var Lh=Object.freeze({__proto__:null,DELTA:Dh});function Ph(e,t){Hi((()=>e<t),r("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function kh(e,t){Hi((()=>t<e),r("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function Uh(e){Hi((()=>[1,2,4].includes(e)),r("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function Vh(e){Hi((()=>0<=e&&e<=4),r("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function zh(e){Hi((()=>e>0),r("The redemption (%s) must be strictly positive.",e.toString()))}function Bh(e){Hi((()=>e>0),r("The price (%s) must be strictly positive.",e.toString()))}function Hh(e){Hi((()=>e>0),r("The number_of_periods (%s) must be greater than 0.",e.toString()))}function $h(e){Hi((()=>e>0),r("The rate (%s) must be strictly positive.",e.toString()))}function Wh(e){Hi((()=>e>0),r("The life (%s) must be strictly positive.",e.toString()))}function Gh(e){Hi((()=>e>=0),r("The cost (%s) must be positive or null.",e.toString()))}function qh(e){Hi((()=>e>0),r("The period (%s) must be strictly positive.",e.toString()))}function Zh(e){Hi((()=>e>=0),r("The salvage (%s) must be positive or null.",e.toString()))}function jh(e){Hi((()=>e>0),r("The present value (%s) must be strictly positive.",e.toString()))}function Yh(e,t){Hi((()=>e<=t),r("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function Xh(e){Hi((()=>e>0),r("The investment (%s) must be strictly positive.",e.toString()))}function Kh(e){Hi((()=>e>0),r("The discount (%s) must be strictly positive.",e.toString()))}function Qh(e){Hi((()=>e<1),r("The discount (%s) must be smaller than 1.",e.toString()))}function Jh(e){Hi((()=>e>0),r("The depreciation factor (%s) must be strictly positive.",e.toString()))}function ed(e,t){const o=Qi(e),i=Qi(t),s=new Date(o);s.setFullYear(o.getFullYear()+1),Hi((()=>i.getTime()<=s.getTime()),r("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function td(e,t,o){Hh(o),Hi((()=>e>0),r("The first_period (%s) must be strictly positive.",e.toString())),Hi((()=>t>0),r("The last_period (%s) must be strictly positive.",t.toString())),Hi((()=>e<=t),r("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),Hi((()=>t<=o),r("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),o.toString()))}function od(e){Hi((()=>e>-1),r("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function id(e,t){Hi((()=>e.length===t.length&&e[0].length===t[0].length),r("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function sd(e){Hi((()=>e.every((t=>t>=e[0]))),r("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const rd=[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))];function nd(e,t,o,i,s=1e-10,n){let a,l,c,h,d=o,u=!1,g=0;do{c=e(d),isNaN(c)?(Hi((()=>g<i&&void 0!==n),r("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=n(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<s||Math.abs(c)<s,Hi((()=>g<i),r("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const ad={description:r("Accrued interest of security paying at maturity."),args:[za("issue (date)",r("The date the security was initially issued.")),za("maturity (date)",r("The maturity date of the security.")),za("rate (number)",r("The annualized rate of interest.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(i),l=Wi(o),c=Math.trunc(Wi(s));kh(n,r),Vh(c),zh(a),$h(l);return a*l*Ih.compute(r,n,s)},isExported:!0},ld={description:r("Depreciation for an accounting period."),args:[za("cost (number)",r("The initial cost of the asset.")),za("purchase_date (date)",r("The date the asset was purchased.")),za("first_period_end (date)",r("The date the first period ended.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("period (number)",r("The single period within life for which to calculate depreciation.")),za("rate (number)",r("The deprecation rate.")),za(" (number, optional)",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n,a=0){a=a||0;const l=Wi(e),c=Math.trunc(Wi(t)),h=Math.trunc(Wi(o)),d=Wi(i),u=Wi(s),g=Wi(n),p=Math.trunc(Wi(a));!function(e){Hi((()=>e>0),r("The cost (%s) must be strictly positive.",e.toString()))}(l),Zh(d),function(e,t){Hi((()=>e<=t),r("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){Hi((()=>e>=0),r("The period (%s) must be positive or null.",e.toString()))}(u),$h(g),Vh(p),Hi((()=>c<=h),r("The purchase_date (%s) must be before the first_period_end (%s).",c.toString(),h.toString()));const m=u<1&&u>0?1:Math.trunc(u),f=l*g,b=Ih.compute(c,h,p),v=c===h?f:f*b,S=l-v-f*m;return S>=d?0===m?v:f:d-S<f?f-(d-S):0},isExported:!0},cd={description:r("Days in coupon period containing settlement date."),args:rd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));if(Ph(s,r),Uh(n),Vh(a),1===a){const s=pd.compute(e,t,o,i);return ud.compute(e,t,o,i)-s}return(3===a?365:360)/n},isExported:!0},hd={description:r("Days from settlement until next coupon."),args:rd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));Ph(s,r),Uh(n),Vh(a);const l=pd.compute(s,r,o,i);if([1,2,3].includes(a))return s-l;if(4===a){const e=_e(l,s,a);return Math.round(360*e)}const c=Qi(s),h=Qi(l),d=h.getFullYear(),u=c.getFullYear(),g=h.getMonth()+1,p=c.getMonth()+1;let m=h.getDate(),f=c.getDate();return 2===g&&2===p&&Oe(h)&&Oe(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&Oe(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},dd={description:r("Days from settlement until next coupon."),args:rd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));Ph(s,r),Uh(n),Vh(a);const l=ud.compute(s,r,o,i);if([1,2,3].includes(a))return l-s;if(4===a){const e=_e(s,l,a);return Math.round(360*e)}const c=hd.compute(e,t,o,a);return cd.compute(e,t,o,a)-c},isExported:!0},ud={description:r("Next coupon date after the settlement date."),args:rd,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));Ph(s,r),Uh(n),Vh(a);const l=12/n,c=gd.compute(e,t,o,i);return Te(Me(Qi(r),-(c-1)*l,!0))},isExported:!0},gd={description:r("Number of coupons between settlement and maturity."),args:rd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));Ph(s,r),Uh(n),Vh(a);let l=1,c=r;const h=12/n;for(;c>s;)c=Te(Me(Qi(c),-h,!1)),l++;return l-1},isExported:!0},pd={description:r("Last coupon date prior to or on the settlement date."),args:rd,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Wi(e)),r=Math.trunc(Wi(t)),n=Math.trunc(Wi(o)),a=Math.trunc(Wi(i));Ph(s,r),Uh(n),Vh(a);const l=12/n,c=gd.compute(e,t,o,i);return Te(Me(Qi(r),-c*l,!0))},isExported:!0},md={description:r("Cumulative interest paid over a set of periods."),args:[za("rate (number)",r("The interest rate.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity.")),za("first_period (number)",r("The number of the payment period to begin the cumulative calculation.")),za("last_period (number)",r("The number of the payment period to end the cumulative calculation.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){const n=Wi(i),a=Wi(s),l=Wi(e),c=Wi(o),h=Wi(t);td(n,a,h),$h(l),jh(c);let d=0;for(let t=n;t<=a;t++){d+=Td.compute(e,t,h,o,0,r)}return d},isExported:!0},fd={description:r("Cumulative principal paid over a set of periods."),args:[za("rate (number)",r("The interest rate.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity.")),za("first_period (number)",r("The number of the payment period to begin the cumulative calculation.")),za("last_period (number)",r("The number of the payment period to end the cumulative calculation.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){const n=Wi(i),a=Wi(s),l=Wi(e),c=Wi(o),h=Wi(t);td(n,a,h),$h(l),jh(c);let d=0;for(let t=n;t<=a;t++){d+=kd.compute(e,t,h,o,0,r)}return d},isExported:!0},bd={description:r("Depreciation via declining balance method."),args:[za("cost (number)",r("The initial cost of the asset.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("life (number)",r("The number of periods over which the asset is depreciated.")),za("period (number)",r("The single period within life for which to calculate depreciation.")),za("month (number, optional)",r("The number of months in the first year of depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,...s){const n=Wi(e),a=Wi(t),l=Wi(o),c=Math.trunc(Wi(i)),h=s.length?Math.trunc(Wi(s[0])):12,d=l+(12===h?0:1);Gh(n),Zh(a),qh(c),Wh(l),Hi((()=>1<=h&&h<=12),r("The month (%s) must be between 1 and 12 inclusive.",h.toString())),Hi((()=>c<=d),r("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let g=1-Math.pow(a/n,1/l);g=Math.round(1e3*g)/1e3;let p=n,m=n*(1-g*u);for(let e=1;e<c;e++)p=m,m=p*(1-g),e===l&&(m=p*(1-g*(1-u)));return p-m},isExported:!0},vd={description:r("Depreciation via double-declining balance method."),args:[za("cost (number)",r("The initial cost of the asset.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("life (number)",r("The number of periods over which the asset is depreciated.")),za("period (number)",r("The single period within life for which to calculate depreciation.")),za("factor (number, default=2)",r("The factor by which depreciation decreases."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=2){s=s||0;const r=Wi(e),n=Wi(t),a=Wi(o),l=Wi(i),c=Wi(s);if(Gh(r),Zh(n),qh(l),Wh(a),Yh(l,a),Jh(c),0===r||n>=r)return 0;const h=c/a;if(h>1)return 1===i?r-n:0;if(l<=1)return r*h;const d=r*Math.pow(1-h,l-1),u=r*Math.pow(1-h,l),g=u<n?d-n:d-u;return Math.max(g,0)},isExported:!0},Sd={description:r("Discount rate of a security based on price."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("price (number)",r("The price at which the security is bought per 100 face value.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(o),l=Wi(i),c=Math.trunc(Wi(s));Ph(r,n),Vh(c),Bh(a),zh(l);return(l-a)/l/Ih.compute(r,n,c)},isExported:!0},Cd={description:r("Convert a decimal fraction to decimal value."),args:[za("fractional_price (number)",r("The price quotation given using fractional decimal conventions.")),za("unit (number)",r("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const o=Wi(e),i=Math.trunc(Wi(t));Hi((()=>i>0),r("The unit (%s) must be strictly positive.",i.toString()));const s=Math.trunc(o);return s+(o-s)*(10**Math.ceil(Math.log10(i))/i)},isExported:!0},Ed={description:r("Convert a decimal value to decimal fraction."),args:[za("decimal_price (number)",r("The price quotation given as a decimal value.")),za("unit (number)",r("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const o=Wi(e),i=Math.trunc(Wi(t));Hi((()=>i>0),r("The unit (%s) must be strictly positive.",i.toString()));const s=Math.trunc(o);return s+(o-s)*(i/10**Math.ceil(Math.log10(i)))},isExported:!0},wd={description:r("Number of periods for an investment to reach a value."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("rate (number)",r("The annualized rate of interest.")),za("yield (number)",r("The expected annual yield of the security.")),za("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){n=n||0;const a=Math.trunc(Wi(e)),l=Math.trunc(Wi(t)),c=Wi(o),h=Wi(i),d=Math.trunc(Wi(s)),u=Math.trunc(Wi(n));Ph(a,l),Uh(d),Vh(u),Hi((()=>c>=0),r("The rate (%s) must be positive or null.",c.toString())),Hi((()=>h>=0),r("The yield (%s) must be positive or null.",h.toString()));const g=Ih.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,b=h/d;let v=0,S=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+b)**e;S+=(p+(e-1)/d)*t,v+=t}return 0===v?0:S/v},isExported:!0},xd={description:r("Annual effective interest rate."),args:[za("nominal_rate (number)",r("The nominal interest rate per year.")),za("periods_per_year (number)",r("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Wi(e),i=Math.trunc(Wi(t));return Hi((()=>o>0),r("The nominal rate (%s) must be strictly greater than 0.",o.toString())),Hi((()=>i>0),r("The number of periods by year (%s) must strictly greater than 0.",i.toString())),Math.pow(1+o/i,i)-1},isExported:!0},yd={description:r("Future value of an annuity investment."),args:[za("rate (number)",r("The interest rate.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("payment_amount (number)",r("The amount per period to be paid.")),za("present_value (number, default=0)",r("The current value of the annuity.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const r=Wi(e),n=Wi(t),a=Wi(o),l=Wi(i),c=Ki(s)?1:0;return r?-l*(1+r)**n-a*(1+r*c)*((1+r)**n-1)/r:-(l+a*n)},isExported:!0},Id={description:r("Future value of principal from series of rates."),args:[za("principal (number)",r("The amount of initial capital or value to compound against.")),za("rate_schedule (number, range<number>)",r("A series of interest rates to compound against the principal."))],returns:["NUMBER"],compute:function(e,t){return is([t],((e,t)=>e*(1+Wi(t))),Wi(e))},isExported:!0},Rd={description:r("Calculates effective interest rate."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("investment (number)",r("The amount invested in the security.")),za("redemption (number)",r("The amount to be received at maturity.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(i),l=Wi(o);Ph(r,n),Xh(l),zh(a);return(a-l)/l/Ih.compute(r,n,s)},isExported:!0},Td={description:r("Payment on the principal of an investment."),args:[za("rate (number)",r("The annualized rate of interest.")),za("period (number)",r("The amortization period, in terms of number of periods.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=0,r=0){return Pd.compute(e,o,i,s,r)-kd.compute(e,t,o,i,s,r)},isExported:!0},Ad={description:r("Internal rate of return given periodic cashflows."),args:[za("cashflow_amounts (number, range<number>)",r("An array or range containing the income or payments associated with the investment.")),za("rate_guess (number, default=0.1)",r("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const o=Wi(t);od(o);let i=!1,s=!1,n=[];ts([e],(e=>{e>0&&(i=!0),e<0&&(s=!0),n.push(e)})),Hi((()=>i&&s),r("The cashflow_amounts must include negative and positive values."));const a=n.shift();return nd((function(e){return function(e,t,o){const i=o.length;let s=0;return o.reduce(((t,o)=>(s++,t+o*e**(i-s))),t*e**i)}(e,a,n)}),(function(e){return function(e,t,o){const i=o.length;let s=0;return o.reduce(((t,o)=>(s++,t+o*(i-s)*e**(i-s-1))),t*i*e**(i-1))}(e,a,n)}),o+1,20,1e-5)-1},isExported:!0},Od={description:r("Returns the interest paid at a particular period of an investment."),args:[za("rate (number)",r("The interest rate.")),za("period (number)",r("The period for which you want to view the interest payment.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity."))],returns:["NUMBER"],compute:function(e,t,o,i){const s=Wi(e),n=Wi(t),a=Wi(o),l=Wi(i);Hi((()=>0!==a),r("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(n/a))*s},isExported:!0},Md={description:r("Modified Macaulay duration."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("rate (number)",r("The annualized rate of interest.")),za("yield (number)",r("The expected annual yield of the security.")),za("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){return wd.compute(e,t,o,i,s,r)/(1+Wi(i)/Math.trunc(Wi(s)))},isExported:!0},Nd={description:r("Modified internal rate of return."),args:[za("cashflow_amounts (range<number>)",r("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),za("financing_rate (number)",r("The interest rate paid on funds invested.")),za("reinvestment_return_rate (number)",r("The return (as a percentage) earned on reinvestment of income received from the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Wi(t),s=Wi(o),n=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(lt).map(Wi);var a;const l=n.length;let c=0,h=0;for(const e of je(0,l)){const t=n[e];t>=0?c+=t*(s+1)**(l-e-1):h+=t/(i+1)**e}Hi((()=>0!==h&&0!==c),r("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},_d={description:r("Annual nominal interest rate."),args:[za("effective_rate (number)",r("The effective interest rate per year.")),za("periods_per_year (number)",r("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Wi(e),i=Math.trunc(Wi(t));return Hi((()=>o>0),r("The effective rate (%s) must must strictly greater than 0.",o.toString())),Hi((()=>i>0),r("The number of periods by year (%s) must strictly greater than 0.",i.toString())),(Math.pow(o+1,1/i)-1)*i},isExported:!0},Fd={description:r("Number of payment periods for an investment."),args:[za("rate (number)",r("The interest rate.")),za("payment_amount (number)",r("The amount of each payment made.")),za("present_value (number)",r("The current value of the annuity.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const r=Wi(e),n=Wi(t),a=Wi(o),l=Wi(i),c=Ki(s)?1:0;if(0===r)return-(l+a)/n;const h=n*(1+r*c)/r;return Math.log((h-l)/(a+h))/Math.log(1+r)},isExported:!0};const Dd={description:r("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[za("discount (number)",r("The discount rate of the investment over one period.")),za("cashflow1 (number, range<number>)",r("The first future cash flow.")),za("cashflow2 (number, range<number>, repeating)",r("Additional future cash flows."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const o=Wi(e);return Hi((()=>-1!==o),r("The discount (%s) must be different from -1.",o.toString())),function(e,t,o){let i=0;return ss(o,((t,o)=>(i++,t+o/(1+e)**i)),t)}(o,0,t)},isExported:!0},Ld={description:r("Computes the number of periods needed for an investment to reach a value."),args:[za("rate (number)",r("The rate at which the investment grows each period.")),za("present_value (number)",r("The investment's current value.")),za("future_value (number)",r("The investment's desired future value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Wi(e),s=Wi(t),n=Wi(o);return $h(i),Hi((()=>s>0),r("The present_value (%s) must be strictly positive.",s.toString())),Hi((()=>n>0),r("The future_value (%s) must be strictly positive.",n.toString())),(Math.log(n)-Math.log(s))/Math.log(1+i)},isExported:!0},Pd={description:r("Periodic payment for an annuity investment."),args:[za("rate (number)",r("The annualized rate of interest.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const r=Wi(t),n=Wi(e),a=Ki(s)?1:0;let l=Wi(i),c=Wi(o);if(Hh(r),0===n)return-(l+c)/r;let h=-(c*(1+n)**r+l);return h=h*n/((1+n*a)*((1+n)**r-1)),h},isExported:!0},kd={description:r("Payment on the principal of an investment."),args:[za("rate (number)",r("The annualized rate of interest.")),za("period (number)",r("The amortization period, in terms of number of periods.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("present_value (number)",r("The current value of the annuity.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=0,n=0){s=s||0,n=n||0;const a=Wi(o),l=Wi(e),c=Wi(t),h=Ki(n)?1:0,d=Wi(s),u=Wi(i);Hh(a),Hi((()=>c>0&&c<=a),r("The period must be between 1 and number_of_periods",a.toString()));const g=Pd.compute(l,a,u,d,n);if(1===h&&1===c)return g;return g+-yd.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},Ud={description:r("Present value of an annuity investment."),args:[za("rate (number)",r("The interest rate.")),za("number_of_periods (number)",r("The number of payments to be made.")),za("payment_amount (number)",r("The amount per period to be paid.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const r=Wi(e),n=Wi(t),a=Wi(o),l=Wi(i),c=Ki(s)?1:0;return r?-(a*(1+r*c)*((1+r)**n-1)/r+l)/(1+r)**n:-(l+a*n)},isExported:!0},Vd={description:r("Price of a security paying periodic interest."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("rate (number)",r("The annualized rate of interest.")),za("yield (number)",r("The expected annual yield of the security.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n,a=0){a=a||0;const l=Math.trunc(Wi(e)),c=Math.trunc(Wi(t)),h=Wi(o),d=Wi(i),u=Wi(s),g=Math.trunc(Wi(n)),p=Math.trunc(Wi(a));Ph(l,c),Uh(g),Vh(p),Hi((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Hi((()=>d>=0),r("The yield (%s) must be positive or null.",d.toString())),zh(u);const m=Ih.compute(l,c,p)*g,f=Math.ceil(m),b=m-Math.floor(m)||1,v=1+d/g,S=100*h/g;if(1===f)return(S+u)/(b*d/g+1)-S*(1-b);let C=0;for(let e=1;e<=f;e++)C+=S/v**(e-1+b);return u/v**(f-1+b)+C-S*(1-b)},isExported:!0},zd={description:r("Price of a discount security."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("discount (number)",r("The discount rate of the security at time of purchase.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(o),l=Wi(i),c=Math.trunc(Wi(s));Ph(r,n),Vh(c),Kh(a),zh(l);return l-a*l*Ih.compute(r,n,c)},isExported:!0},Bd={description:r("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("issue (date)",r("The date the security was initially issued.")),za("rate (number)",r("The annualized rate of interest.")),za("yield (number)",r("The expected annual yield of the security.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){n=n||0;const a=Math.trunc(Wi(e)),l=Math.trunc(Wi(t)),c=Math.trunc(Wi(o)),h=Wi(i),d=Wi(s),u=Math.trunc(Wi(n));kh(a,c),Ph(a,l),Vh(u),Hi((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Hi((()=>d>=0),r("The yield (%s) must be positive or null.",d.toString()));const g=Ih.compute(a,l,u),p=Ih.compute(a,c,u);return(100+Ih.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},Hd=.1,$d={description:r("Interest rate of an annuity investment."),args:[za("number_of_periods (number)",r("The number of payments to be made.")),za("payment_per_period (number)",r("The amount per period to be paid.")),za("present_value (number)",r("The current value of the annuity.")),za("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),za("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period.")),za("rate_guess (number, default=0.1)",r("An estimate for what the interest rate will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,o,i=0,s=0,n=.1){i=i||0,s=s||0,n=n||Hd;const a=Wi(e),l=Wi(t),c=Ki(s)?1:0,h=Wi(n);let d=Wi(i),u=Wi(o);Hh(a),Hi((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),r("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),od(h),d-=l*c,u+=l*c;return nd((e=>{const t=Math.pow(1+e,a);return d+u*t+l*((t-1)/e)}),(e=>{const t=Math.pow(1+e,a-1),o=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(o-1)/e/e)}),h,40,1e-5)},isExported:!0},Wd={description:r("Amount received at maturity for a security."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("investment (number)",r("The amount invested (irrespective of face value of each security).")),za("discount (number)",r("The discount rate of the security invested in.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(o),l=Wi(i),c=Math.trunc(Wi(s));Ph(r,n),Vh(c),Xh(a),Kh(l);return a/(1-l*Ih.compute(r,n,c))},isExported:!0},Gd={description:r("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[za("number_of_periods (number)",r("The number of periods.")),za("present_value (number)",r("The present value of the investment.")),za("future_value (number)",r("The future value of the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Wi(e),s=Wi(t),r=Wi(o);return Hh(i),(r/s)**(1/i)-1},isExported:!0},qd={description:r("Depreciation of an asset using the straight-line method."),args:[za("cost (number)",r("The initial cost of the asset.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("life (number)",r("The number of periods over which the asset is depreciated."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o){return(Wi(e)-Wi(t))/Wi(o)},isExported:!0},Zd={description:r("Depreciation via sum of years digit method."),args:[za("cost (number)",r("The initial cost of the asset.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("life (number)",r("The number of periods over which the asset is depreciated.")),za("period (number)",r("The single period within life for which to calculate depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i){const s=Wi(e),r=Wi(t),n=Wi(o),a=Wi(i);qh(a),Wh(n),Yh(a,n);return(n-a+1)/(n*(n+1)/2)*(s-r)},isExported:!0},jd={description:r("Price of a US Treasury bill."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("discount (number)",r("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Wi(e)),s=Math.trunc(Wi(t)),r=Wi(o);Ph(i,s),ed(i,s),Kh(r),Qh(r);return 100*(1-r*Ih.compute(i,s,2))},isExported:!0},Yd={description:r("Equivalent rate of return for a US Treasury bill."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("discount (number)",r("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Wi(e)),s=Math.trunc(Wi(t)),r=Wi(o);Ph(i,s),ed(i,s),Kh(r),Qh(r);const n=sh.compute(s,i);if(n<=182)return 365*r/(360-r*n);const a=jd.compute(i,s,r)/100,l=n/(366===n?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},Xd={description:r("The yield of a US Treasury bill based on price."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("price (number)",r("The price at which the security is bought per 100 face value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Wi(e)),s=Math.trunc(Wi(t)),r=Wi(o);Ph(i,s),ed(i,s),Bh(r);return(100-r)/r*(1/Ih.compute(i,s,2))},isExported:!0},Kd={description:r("Variable declining balance. WARNING : does not handle decimal periods."),args:[za("cost (number)",r("The initial cost of the asset.")),za("salvage (number)",r("The value of the asset at the end of depreciation.")),za("life (number)",r("The number of periods over which the asset is depreciated.")),za("start (number)",r("Starting period to calculate depreciation.")),za("end (number)",r("Ending period to calculate depreciation.")),za("factor (number, default=2)",r("The number of months in the first year of depreciation.")),za("no_switch (number, default=false)",r("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=2,a=false){n=n||0;const l=Wi(e),c=Wi(t),h=Wi(o),d=Math.trunc(Wi(i)),u=Math.trunc(Wi(s)),g=Wi(n),p=Ki(a);if(Gh(l),Zh(c),function(e,t,o){Wh(o),Hi((()=>e>=0),r("The start_period (%s) must be greater or equal than 0.",e.toString())),Hi((()=>t>=0),r("The end_period (%s) must be greater or equal than 0.",t.toString())),Hi((()=>e<=t),r("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),Hi((()=>t<=o),r("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),o.toString()))}(d,u,h),Jh(g),0===l)return 0;if(c>=l)return d<1?l-c:0;const m=g/h;if(m>=1)return d<1?l-c:0;let f=l,b=0,v=0,S=!1;for(let e=0;e<u;e++){if(!S||p){const t=f*m,o=(f-c)/(h-e);!p&&o>t?(S=!0,b=o):b=t}const t=Math.max(f-b,c);e>=d&&(v+=f-t),f=t}return v},isExported:!0},Qd={description:r("Internal rate of return given non-periodic cash flows."),args:[za("cashflow_amounts (range<number>)",r("An range containing the income or payments associated with the investment.")),za("cashflow_dates (range<number>)",r("An range with dates corresponding to the cash flows in cashflow_amounts.")),za("rate_guess (number, default=0.1)",r("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],compute:function(e,t,o=.1){const i=Wi(o=o||0),s=e.flat().map(Wi),n=t.flat().map(Wi);var a;id(e,t),a=s,Hi((()=>a.some((e=>e>0))&&a.some((e=>e<0))),r("There must be both positive and negative values in cashflow_amounts.")),sd(n),od(i);const l=new Map;for(const e of je(0,n.length)){const t=n[e];l.has(t)?l.set(t,l.get(t)+s[e]):l.set(t,s[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return nd((e=>{let t=h[0];for(const o of je(1,h.length)){const i=(c[0]-c[o])/365;t+=h[o]*(1+e)**i}return t}),(e=>{let t=0;for(const o of je(1,h.length)){const i=(c[0]-c[o])/365;t+=i*h[o]*(1+e)**(i-1)}return t}),i,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},Jd={description:r("Net present value given to non-periodic cash flows.."),args:[za("discount (number)",r("The discount rate of the investment over one period.")),za("cashflow_amounts (number, range<number>)",r("An range containing the income or payments associated with the investment.")),za("cashflow_dates (number, range<number>)",r("An range with dates corresponding to the cash flows in cashflow_amounts."))],returns:["NUMBER"],compute:function(e,t,o){const i=Wi(e),s=Array.isArray(t)?t.flat().map(Gi):[Gi(t)],n=Array.isArray(o)?o.flat().map(Gi):[Gi(o)];if(Array.isArray(o)&&Array.isArray(t)?id(t,o):Hi((()=>s.length===n.length),r("There must be the same number of values in cashflow_amounts and cashflow_dates.")),sd(n),$h(i),1===s.length)return s[0];const a=new Map;for(const e of je(0,n.length)){const t=n[e];a.has(t)?a.set(t,a.get(t)+s[e]):a.set(t,s[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of je(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+i)**t}return h},isExported:!0},eu={description:r("Annual yield of a security paying periodic interest."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("rate (number)",r("The annualized rate of interest.")),za("price (number)",r("The price at which the security is bought per 100 face value.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n,a=0){a=a||0;const l=Math.trunc(Wi(e)),c=Math.trunc(Wi(t)),h=Wi(o),d=Wi(i),u=Wi(s),g=Math.trunc(Wi(n)),p=Math.trunc(Wi(a));Ph(l,c),Uh(g),Vh(p),Hi((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Bh(d),zh(u);const m=Ih.compute(l,c,p)*g,f=Math.ceil(m),b=m-Math.floor(m)||1,v=100*h/g;if(1===f){const e=d+v*(1-b);return(u+v-e)*g*(1/b)/e}const S=nd((function(e){return function(e,t,o,i,s,r){let n=r-(e+s*(1-t))*i**(o-1+t);for(let e=1;e<=o;e++)n+=s*i**(e-1);return n}(d,b,f,e,v,u)}),(function(e){return function(e,t,o,i,s){let r=-(e+s*(1-t))*(o-1+t)*i**(o-2+t);for(let e=1;e<=o;e++)r+=s*(e-1)*i**(e-2);return r}(d,b,f,e,v)}),1+(h+1)/g,100,1e-5);return(S-1)*g},isExported:!0},tu={description:r("Annual yield of a discount security."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("price (number)",r("The price at which the security is bought per 100 face value.")),za("redemption (number)",r("The redemption amount per 100 face value, or par.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Wi(e)),n=Math.trunc(Wi(t)),a=Wi(o),l=Wi(i),c=Math.trunc(Wi(s));Ph(r,n),Vh(c),Bh(a),zh(l);return(l/a-1)/Ih.compute(e,t,s)},isExported:!0},ou={description:r("Annual yield of a security paying interest at maturity."),args:[za("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),za("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),za("issue (date)",r("The date the security was initially issued.")),za("rate (number)",r("The annualized rate of interest.")),za("price (number)",r("The price at which the security is bought.")),za("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){n=n||0;const a=Math.trunc(Wi(e)),l=Math.trunc(Wi(t)),c=Math.trunc(Wi(o)),h=Wi(i),d=Wi(s),u=Math.trunc(Wi(n));Ph(a,l),Vh(u),Hi((()=>a>=c),r("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),Hi((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Bh(d);const g=Ih.compute(c,l,u),p=Ih.compute(c,a,u),m=Ih.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var iu=Object.freeze({__proto__:null,ACCRINTM:ad,AMORLINC:ld,COUPDAYS:cd,COUPDAYBS:hd,COUPDAYSNC:dd,COUPNCD:ud,COUPNUM:gd,COUPPCD:pd,CUMIPMT:md,CUMPRINC:fd,DB:bd,DDB:vd,DISC:Sd,DOLLARDE:Cd,DOLLARFR:Ed,DURATION:wd,EFFECT:xd,FV:yd,FVSCHEDULE:Id,INTRATE:Rd,IPMT:Td,IRR:Ad,ISPMT:Od,MDURATION:Md,MIRR:Nd,NOMINAL:_d,NPER:Fd,NPV:Dd,PDURATION:Ld,PMT:Pd,PPMT:kd,PV:Ud,PRICE:Vd,PRICEDISC:zd,PRICEMAT:Bd,RATE:$d,RECEIVED:Wd,RRI:Gd,SLN:qd,SYD:Zd,TBILLPRICE:jd,TBILLEQ:Yd,TBILLYIELD:Xd,VDB:Kd,XIRR:Qd,XNPV:Jd,YIELD:eu,YIELDDISC:tu,YIELDMAT:ou});const su={description:r("Whether a value is an error other than #N/A."),args:[za("value (any, lazy)",r("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return e?.errorType!=a.NotAvailable}},isExported:!0},ru={description:r("Whether a value is an error."),args:[za("value (any, lazy)",r("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},nu={description:r("Whether a value is `true` or `false`."),args:[za("value (any, lazy)",r("The value to be verified as a logical TRUE or FALSE."))],returns:["BOOLEAN"],compute:function(e){try{return"boolean"==typeof e()}catch(e){return!1}},isExported:!0},au={description:r("Whether a value is the error #N/A."),args:[za("value (any, lazy)",r("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return e?.errorType==a.NotAvailable}},isExported:!0},lu={description:r("Whether a value is non-textual."),args:[za("value (any, lazy)",r("The value to be checked."))],returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},cu={description:r("Whether a value is a number."),args:[za("value (any, lazy)",r("The value to be verified as a number."))],returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},hu={description:r("Whether a value is text."),args:[za("value (any, lazy)",r("The value to be verified as text."))],returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},du={description:r("Whether the referenced cell is empty"),args:[za("value (any, lazy)",r("Reference to the cell that will be checked for emptiness."))],returns:["BOOLEAN"],compute:function(e){try{return null===e()}catch(e){return!1}},isExported:!0},uu={description:r("Returns the error value #N/A."),args:[],returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var gu=Object.freeze({__proto__:null,ISERR:su,ISERROR:ru,ISLOGICAL:nu,ISNA:au,ISNONTEXT:lu,ISNUMBER:cu,ISTEXT:hu,ISBLANK:du,NA:uu});const pu={description:r("Logical `and` operator."),args:[za("logical_expression1 (boolean, range<boolean>)",r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),za("logical_expression2 (boolean, range<boolean>, repeating)",r("More expressions that represent logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!0;return ns(e,(e=>(t=!0,o=o&&e,o))),Hi((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},mu={description:r("Returns value depending on logical expression."),args:[za("logical_expression (boolean)",r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),za("value_if_true (any, lazy)",r("The value the function returns if logical_expression is TRUE.")),za("value_if_false (any, lazy, default=FALSE)",r("The value the function returns if logical_expression is FALSE."))],returns:["ANY"],compute:function(e,t,o=(()=>!1)){const i=Ki(e)?t():o();return null==i?"":i},isExported:!0},fu={description:r("Value if it is not an error, otherwise 2nd argument."),args:[za("value (any, lazy)",r("The value to return if value itself is not an error.")),za('value_if_error (any, lazy, default="empty")',r("The value the function returns if value is an error."))],returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{try{return e().format}catch(e){return t()?.format}},compute:function(e,t=(()=>"")){let o;try{o=e()}catch(e){o=t()}return null==o?"":o},isExported:!0},bu={description:r("Value if it is not an #N/A error, otherwise 2nd argument."),args:[za("value (any, lazy)",r("The value to return if value itself is not #N/A an error.")),za('value_if_error (any, lazy, default="empty")',r("The value the function returns if value is an #N/A error."))],returns:["ANY"],compute:function(e,t=(()=>"")){let o;try{o=e()}catch(i){o=i.errorType===a.NotAvailable?t():e()}return null==o?"":o},isExported:!0},vu={description:r("Returns a value depending on multiple logical expressions."),args:[za("condition1 (boolean, lazy)",r("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),za("value1 (any, lazy)",r("The returned value if condition1 is TRUE.")),za("condition2 (boolean, lazy, repeating)",r("Additional conditions to be evaluated if the previous ones are FALSE.")),za("value2 (any, lazy, repeating)",r("Additional values to be returned if their corresponding conditions are TRUE."))],returns:["ANY"],compute:function(...e){Hi((()=>e.length%2==0),r("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(Ki(e[t]())){const o=e[t+1]();return null!==o?o:""}throw new Error(r("No match."))},isExported:!0},Su={description:r("Returns opposite of provided logical value."),args:[za("logical_expression (boolean)",r("An expression or reference to a cell holding an expression that represents some logical value."))],returns:["BOOLEAN"],compute:function(e){return!Ki(e)},isExported:!0},Cu={description:r("Logical `or` operator."),args:[za("logical_expression1 (boolean, range<boolean>)",r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),za("logical_expression2 (boolean, range<boolean>, repeating)",r("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return ns(e,(e=>(t=!0,o=o||e,!o))),Hi((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Eu={description:r("Logical `xor` operator."),args:[za("logical_expression1 (boolean, range<boolean>)",r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),za("logical_expression2 (boolean, range<boolean>, repeating)",r("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return ns(e,(e=>(t=!0,o=o?!e:e,!0))),Hi((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0};var wu=Object.freeze({__proto__:null,AND:pu,IF:mu,IFERROR:fu,IFNA:bu,IFS:vu,NOT:Su,OR:Cu,XOR:Eu});function xu(e,t){if(void 0===e)throw new g(r("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",ji(t)))}const yu={description:r("Returns a cell reference as a string. "),args:[za("row (number)",r("The row number of the cell reference. ")),za("column (number)",r("The column number (not name) of the cell reference. A is column number 1. ")),za("absolute_relative_mode (number, default=1)",r("An indicator of whether the reference is row/column absolute. 1 is row and column absolute (e.g. $A$1), 2 is row absolute and column relative (e.g. A$1), 3 is row relative and column absolute (e.g. $A1), and 4 is row and column relative (e.g. A1).")),za("use_a1_notation (boolean, default=TRUE)",r("A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).")),za("sheet (string, optional)",r("A string indicating the name of the sheet into which the address points."))],returns:["STRING"],compute:function(e,t,o=1,i=!0,s){const n=qi(e),a=qi(t);Zi(n),Zi(a);const l=qi(o);var c,h;Hi((()=>[1,2,3,4].includes(l)),(c=4,h=l,r("The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.",1..toString(),c.toString(),h.toString())));let d;if(Ki(i)){d=Ht(a-1,n-1,{rowFixed:!![1,2].includes(l),colFixed:!![1,3].includes(l)})}else{d=([1,2].includes(l)?`R${n}`:`R[${n}]`)+([1,3].includes(l)?`C${a}`:`C[${a}]`)}return void 0!==s?`${Be(ji(s))}!${d}`:d},isExported:!0},Iu={description:r("Column number of a specified cell."),args:[za("cell_reference (meta, default='this cell')",r("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."))],returns:["NUMBER"],compute:function(e){const t=e||this.__originCellXC?.();Hi((()=>!!t),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Yo(t).left+1},isExported:!0},Ru={description:r("Number of columns in a specified array or range."),args:[za("range (meta)",r("The range whose column count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Yo(e);return t.right-t.left+1},isExported:!0},Tu={description:r("Horizontal lookup"),args:[za("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),za("range (range)",r("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),za("index (number)",r("The row index of the value to be returned, where the first row in range is numbered 1.")),za("is_sorted (boolean, default=true)",r("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."))],returns:["ANY"],compute:function(e,t,o,i=true){const s=Math.trunc(Wi(o)),n=Yi(e);Hi((()=>1<=s&&s<=t[0].length),r("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Ki(i)?us(t,n,"nextSmaller","asc",t.length,ds):gs(t,n,"strict",t.length,ds);const l=t[a];return xu(l,e),l[s-1]},isExported:!0},Au={description:r("Look up a value."),args:[za("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),za("search_array (range)",r("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.")),za("result_range (range, optional)",r("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."))],returns:["ANY"],compute:function(e,t,o){let i=t.length,s=t[0].length;const n=Yi(e),a=s>=i,l=us(t,n,"nextSmaller","asc",a?s:i,a?hs:ds);return-1===l&&xu(void 0,e),xu(a?t[0][l]:t[l][s-1],e),void 0===o?a?t[i-1][l]:t[l][s-1]:(i=o.length,s=o[0].length,Hi((()=>1===i||1===s),r("The result_range must be a single row or a single column.")),i>1?(Hi((()=>l<=i-1),r("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),o[l][0]):(Hi((()=>l<=s-1),r("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),o[0][l]))},isExported:!0},Ou={description:r("Position of item in range that matches value."),args:[za("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),za("range (any, range)",r("The one-dimensional array to be searched.")),za("search_type (number, default=1)",r("The search method. 1 (default) 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."))],returns:["NUMBER"],compute:function(e,t,o=1){let i=Wi(o);const s=Yi(e),n=t.length,a=t[0].length;Hi((()=>1===n||1===a),r("The range must be a single row or a single column."));let l=-1;const c=1===n?hs:ds,h=1===n?t[0].length:t.length;switch(i=Math.sign(i),i){case 1:l=us(t,s,"nextSmaller","asc",h,c);break;case 0:l=gs(t,s,"strict",h,c);break;case-1:l=us(t,s,"nextGreater","desc",h,c)}return xu(1===n?t[0][l]:t[l],e),l+1},isExported:!0},Mu={description:r("Row number of a specified cell."),args:[za("cell_reference (meta, default='this cell')",r("The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered."))],returns:["NUMBER"],compute:function(e){e=e||this.__originCellXC?.(),Hi((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Yo(e).top+1},isExported:!0},Nu={description:r("Number of rows in a specified array or range."),args:[za("range (meta)",r("The range whose row count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Yo(e);return t.bottom-t.top+1},isExported:!0},_u={description:r("Vertical lookup."),args:[za("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),za("range (any, range)",r("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),za("index (number)",r("The column index of the value to be returned, where the first column in range is numbered 1.")),za("is_sorted (boolean, default=true)",r("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."))],returns:["ANY"],compute:function(e,t,o,i=true){const s=Math.trunc(Wi(o)),n=Yi(e);Hi((()=>1<=s&&s<=t.length),r("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Ki(i)?us(t,n,"nextSmaller","asc",t[0].length,hs):gs(t,n,"strict",t[0].length,hs);const l=t[s-1][a];return xu(l,e),l},isExported:!0},Fu={description:r("Search a range for a match and return the corresponding item from a second range."),args:[za("search_key (any)",r("The value to search for.")),za("lookup_range (any, range)",r("The range to consider for the search. Should be a single column or a single row.")),za("return_range (any, range)",r("The range containing the return value. Should have the same dimensions as lookup_range.")),za("if_not_found (any, lazy, optional)",r("If a valid match is not found, return this value.")),za("match_mode (any, default=0)",r("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")),za("search_mode (any, default=1)",r("(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. "))],returns:["ANY"],compute:function(e,t,o,i,s=0,n=1){const a=Math.trunc(Wi(s)),l=Math.trunc(Wi(n)),c=Yi(e);Hi((()=>1===t.length||1===t[0].length),r("lookup_range should be either a single row or single column.")),Hi((()=>1===o.length||1===o[0].length),r("return_range should be either a single row or single column.")),Hi((()=>o.length===t.length&&o[0].length===t[0].length),r("return_range should have the same dimensions as lookup_range.")),Hi((()=>[-1,1,-2,2].includes(l)),r("searchMode should be a value in [-1, 1, -2, 2].")),Hi((()=>[-1,0,1].includes(a)),r("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?hs:ds,d=1===t.length?t[0].length:t.length,u=0===a?"strict":1===a?"nextGreater":"nextSmaller",g=-1===l;let p;if(2===l||-2===l){p=us(t,c,u,2===l?"asc":"desc",d,h)}else p=gs(t,c,u,d,h,g);if(-1!==p)return 1===t.length?o[0][p]:o[p][0];const m=i?.();return xu(m,e),m},isExported:!0};var Du=Object.freeze({__proto__:null,ADDRESS:yu,COLUMN:Iu,COLUMNS:Ru,HLOOKUP:Tu,LOOKUP:Au,MATCH:Ou,ROW:Mu,ROWS:Nu,VLOOKUP:_u,XLOOKUP:Fu});const Lu={description:r("Sum of two numbers."),args:[za("value1 (number)",r("The first addend.")),za("value2 (number)",r("The second addend."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Wi(e)+Wi(t)}},Pu={description:r("Concatenation of two values."),args:[za("value1 (string)",r("The value to which value2 will be appended.")),za("value2 (string)",r("The value to append to value1."))],returns:["STRING"],compute:function(e,t){return ji(e)+ji(t)},isExported:!0},ku={description:r("One number divided by another."),args:[za("dividend (number)",r("The number to be divided.")),za("divisor (number)",r("The number to divide by."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){const o=Wi(t);return Hi((()=>0!==o),r("The divisor must be different from zero.")),Wi(e)/o}};function Uu(e){return null==e}const Vu={number:0,string:"",boolean:!1},zu={description:r("Equal."),args:[za("value1 (any)",r("The first value.")),za("value2 (any)",r("The value to test against value1 for equality."))],returns:["BOOLEAN"],compute:function(e,t){return e=Uu(e)?Vu[typeof t]:e,t=Uu(t)?Vu[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function Bu(e,t,o){e=Uu(e)?Vu[typeof t]:e,t=Uu(t)?Vu[typeof e]:t,"number"!=typeof e&&(e=ji(e).toUpperCase()),"number"!=typeof t&&(t=ji(t).toUpperCase());const i=typeof e,s=typeof t;return"string"===i&&"number"===s||("string"!==s||"number"!==i)&&o(e,t)}const Hu={description:r("Strictly greater than."),args:[za("value1 (any)",r("The value to test as being greater than value2.")),za("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return Bu(e,t,((e,t)=>e>t))}},$u={description:r("Greater than or equal to."),args:[za("value1 (any)",r("The value to test as being greater than or equal to value2.")),za("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return Bu(e,t,((e,t)=>e>=t))}},Wu={description:r("Less than."),args:[za("value1 (any)",r("The value to test as being less than value2.")),za("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!$u.compute(e,t)}},Gu={description:r("Less than or equal to."),args:[za("value1 (any)",r("The value to test as being less than or equal to value2.")),za("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!Hu.compute(e,t)}},qu={description:r("Difference of two numbers."),args:[za("value1 (number)",r("The minuend, or number to be subtracted from.")),za("value2 (number)",r("The subtrahend, or number to subtract from value1."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Wi(e)-Wi(t)}},Zu={description:r("Product of two numbers"),args:[za("factor1 (number)",r("The first multiplicand.")),za("factor2 (number)",r("The second multiplicand."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Wi(e)*Wi(t)}},ju={description:r("Not equal."),args:[za("value1 (any)",r("The first value.")),za("value2 (any)",r("The value to test against value1 for inequality."))],returns:["BOOLEAN"],compute:function(e,t){return!zu.compute(e,t)}},Yu={description:r("A number raised to a power."),args:[za("base (number)",r("The number to raise to the exponent power.")),za("exponent (number)",r("The exponent to raise base to."))],returns:["NUMBER"],compute:function(e,t){return Ol.compute(e,t)}},Xu={description:r("A number with the sign reversed."),args:[za("value (number)",r("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],computeFormat:e=>e?.format,returns:["NUMBER"],compute:function(e){return-Wi(e)}},Ku={description:r("Value interpreted as a percentage."),args:[za("percentage (number)",r("The value to interpret as a percentage."))],returns:["NUMBER"],compute:function(e){return Wi(e)/100}},Qu={description:r("A specified number, unchanged."),args:[za("value (any)",r("The number to return."))],returns:["ANY"],computeFormat:e=>e?.format,compute:function(e){return null===e?"":e}};var Ju=Object.freeze({__proto__:null,ADD:Lu,CONCAT:Pu,DIVIDE:ku,EQ:zu,GT:Hu,GTE:$u,LT:Wu,LTE:Gu,MINUS:qu,MULTIPLY:Zu,NE:ju,POW:Yu,UMINUS:Xu,UNARY_PERCENT:Ku,UPLUS:Qu});const eg=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,tg={description:r("Gets character associated with number."),args:[za("table_number (number)",r("The number of the character to look up from the current Unicode table in decimal format."))],returns:["STRING"],compute:function(e){const t=Math.trunc(Wi(e));return Hi((()=>t>=1),r("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},og={description:r("Remove non-printable characters from a piece of text."),args:[za("text (string)",r("The text whose non-printable characters are to be removed."))],returns:["STRING"],compute:function(e){const t=ji(e);let o="";for(const e of t)e&&e.charCodeAt(0)>31&&(o+=e);return o},isExported:!0},ig={description:r("Appends strings to one another."),args:[za("string1 (string, range<string>)",r("The initial string.")),za("string2 (string, range<string>, repeating)",r("More strings to append in sequence."))],returns:["STRING"],compute:function(...e){return is(e,((e,t)=>e+ji(t)),"")},isExported:!0},sg={description:r("Tests whether two strings are identical."),args:[za("string1 (string)",r("The first string to compare.")),za("string2 (string)",r("The second string to compare."))],returns:["BOOLEAN"],compute:function(e,t){return ji(e)===ji(t)},isExported:!0},rg={description:r("First position of string found in text, case-sensitive."),args:[za("search_for (string)",r("The string to look for within text_to_search.")),za("text_to_search (string)",r("The text to search for the first occurrence of search_for.")),za("starting_at (number, default=1)",r("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,o=1){const i=ji(e),s=ji(t),n=Wi(o);Hi((()=>""!==s),r("The text_to_search must be non-empty.")),Hi((()=>n>=1),r("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const a=s.indexOf(i,n-1);return Hi((()=>a>=0),r("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i.toString(),s)),a+1},isExported:!0},ng={description:r("Concatenates elements of arrays with delimiter."),args:[za("delimiter (string)",r("The character or string to place between each concatenated value.")),za("value_or_array1 (string, range<string>)",r("The value or values to be appended using delimiter.")),za("value_or_array2 (string, range<string>, repeating)",r("More values to be appended using delimiter."))],returns:["STRING"],compute:function(e,...t){const o=ji(e);return is(t,((e,t)=>(e?e+o:"")+ji(t)),"")}},ag={description:r("Substring from beginning of specified string."),args:[za("text (string)",r("The string from which the left portion will be returned.")),za("number_of_characters (number, optional)",r("The number of characters to return from the left side of string."))],returns:["STRING"],compute:function(e,...t){const o=t.length?Wi(t[0]):1;return Hi((()=>o>=0),r("The number_of_characters (%s) must be positive or null.",o.toString())),ji(e).substring(0,o)},isExported:!0},lg={description:r("Length of a string."),args:[za("text (string)",r("The string whose length will be returned."))],returns:["NUMBER"],compute:function(e){return ji(e).length},isExported:!0},cg={description:r("Converts a specified string to lowercase."),args:[za("text (string)",r("The string to convert to lowercase."))],returns:["STRING"],compute:function(e){return ji(e).toLowerCase()},isExported:!0},hg={description:r("A segment of a string."),args:[za("text (string)",r("The string to extract a segment from.")),za(" (number)",r("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),za(" (number)",r("The length of the segment to extract."))],returns:["STRING"],compute:function(e,t,o){const i=ji(e),s=Wi(t),n=Wi(o);return Hi((()=>s>=1),r("The starting_at argument (%s) must be positive greater than one.",s.toString())),Hi((()=>n>=0),r("The extract_length argument (%s) must be positive or null.",n.toString())),i.slice(s-1,s+n-1)},isExported:!0},dg={description:r("Capitalizes each word in a specified string."),args:[za("text_to_capitalize (string)",r("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase."))],returns:["STRING"],compute:function(e){return ji(e).replace(eg,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},ug={description:r("Replaces part of a text string with different text."),args:[za("text (string)",r("The text, a part of which will be replaced.")),za("position (number)",r("The position where the replacement will begin (starting from 1).")),za("length (number)",r("The number of characters in the text to be replaced.")),za("new_text (string)",r("The text which will be inserted into the original text."))],returns:["STRING"],compute:function(e,t,o,i){const s=Wi(t);Hi((()=>s>=1),r("The position (%s) must be greater than or equal to 1.",s.toString()));const n=ji(e),a=Wi(o),l=ji(i);return n.substring(0,s-1)+l+n.substring(s-1+a)},isExported:!0},gg={description:r("A substring from the end of a specified string."),args:[za("text (string)",r("The string from which the right portion will be returned.")),za("number_of_characters (number, optional)",r("The number of characters to return from the right side of string."))],returns:["STRING"],compute:function(e,...t){const o=t.length?Wi(t[0]):1;Hi((()=>o>=0),r("The number_of_characters (%s) must be positive or null.",o.toString()));const i=ji(e),s=i.length;return i.substring(s-o,s)},isExported:!0},pg={description:r("First position of string found in text, ignoring case."),args:[za("search_for (string)",r("The string to look for within text_to_search.")),za("text_to_search (string)",r("The text to search for the first occurrence of search_for.")),za("starting_at (number, default=1)",r("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,o=1){const i=ji(e).toLowerCase(),s=ji(t).toLowerCase(),n=Wi(o);Hi((()=>""!==s),r("The text_to_search must be non-empty.")),Hi((()=>n>=1),r("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const a=s.indexOf(i,n-1);return Hi((()=>a>=0),r("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i,s)),a+1},isExported:!0},mg={description:r("Replaces existing text with new text in a string."),args:[za("text_to_search (string)",r("The text within which to search and replace.")),za("search_for (string)",r("The string to search for within text_to_search.")),za("replace_with (string)",r("The string that will replace search_for.")),za("occurrence_number (number, optional)",r("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."))],returns:["NUMBER"],compute:function(e,t,o,i){const s=Wi(i);Hi((()=>s>=0),r("The occurrenceNumber (%s) must be positive or null.",s.toString()));const n=ji(e),a=ji(t);if(""===a)return n;const l=ji(o),c=new RegExp(Ue(a),"g");if(0===s)return n.replace(c,l);let h=0;return n.replace(c,(e=>++h===s?l:e))},isExported:!0},fg={description:r("Combines text from multiple strings and/or arrays."),args:[za("delimiter (string)",r(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),za("ignore_empty (boolean)",r("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")),za("text1 (string, range<string>)",r("Any text item. This could be a string, or an array of strings in a range.")),za("text2 (string, range<string>, repeating)",r("Additional text item(s)."))],returns:["STRING"],compute:function(e,t,...o){const i=ji(e),s=Ki(t);let r=0;return is(o,((e,t)=>s&&""===ji(t)?e:(r++?e+i:"")+ji(t)),"")},isExported:!0},bg={description:r("Removes space characters."),args:[za("text (string)",r("The text or reference to a cell containing text to be trimmed."))],returns:["STRING"],compute:function(e){return ji(e).trim()},isExported:!0},vg={description:r("Converts a specified string to uppercase."),args:[za("text (string)",r("The string to convert to uppercase."))],returns:["STRING"],compute:function(e){return ji(e).toUpperCase()},isExported:!0},Sg={description:r("Converts a number to text according to a specified format."),args:[za("number (number)",r("The number, date or time to format.")),za("format (string)",r("The pattern by which to format the number, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){return uo(Wi(e),ji(t))},isExported:!0};var Cg=Object.freeze({__proto__:null,CHAR:tg,CLEAN:og,CONCATENATE:ig,EXACT:sg,FIND:rg,JOIN:ng,LEFT:ag,LEN:lg,LOWER:cg,MID:hg,PROPER:dg,REPLACE:ug,RIGHT:gg,SEARCH:pg,SUBSTITUTE:mg,TEXTJOIN:fg,TRIM:bg,UPPER:vg,TEXT:Sg});const Eg={description:r("Creates a hyperlink in a cell."),args:[za("url (string)",r("The full URL of the link enclosed in quotation marks.")),za("link_label (string, optional)",r("The text to display in the cell, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){const o=ji(e).trim(),i=ji(t)||o;return""===o?i:ot(i,o)},isExported:!0};var wg=Object.freeze({__proto__:null,HYPERLINK:Eg});const xg=[{name:r("Database"),functions:Qc},{name:r("Date"),functions:Fh},{name:r("Financial"),functions:iu},{name:r("Info"),functions:gu},{name:r("Lookup"),functions:Du},{name:r("Logical"),functions:wu},{name:r("Math"),functions:Zl},{name:r("Misc"),functions:$a},{name:r("Operator"),functions:Ju},{name:r("Statistical"),functions:kc},{name:r("Text"),functions:Cg},{name:r("Engineering"),functions:Lh},{name:r("Web"),functions:wg}],yg=/^[A-Z0-9\_\.]+$/;function Ig(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Rg(e()):Rg(e)}))}function Rg(e){return Array.isArray(e)?e.map((e=>e.map((e=>e?.value)))):e?.value}const Tg=new class extends _i{mapping={};add(e,t){if(e=e.toUpperCase(),!yg.test(e))throw new Error(r("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const o=Ba(t);return function(e){let t=!1,o=!1,i=!1;for(let s of e){if(s.type.includes("META")&&s.type.length>1)throw new Error(r("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!s.repeating)throw new Error(r("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=o||t||i,n=!(s.optional||s.repeating||s.default);if(e&&n)throw new Error(r("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=s.repeating,o=s.optional,i=s.default}}(o.args),this.mapping[e]=function(...e){const t=o.compute.bind(this),i=o.computeFormat?o.computeFormat.bind(this):()=>{};return{value:t(...Ig(e)),format:i(...e)}},super.add(e,o),this}};for(let e of xg){const t=e.functions;for(let o in t){const i=t[o];i.category=i.category||e.name,o=o.replace(/_/g,"."),Tg.add(o,{isExported:!1,...i})}}const Ag={name:e=>{const t=ea(e);return 1===t?r("Insert row"):r("Insert %s rows",t.toString())},isVisible:e=>wt(e.model.getters.getActiveRows())&&pa(e)&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_ROW"},Og={name:e=>{const t=ea(e);return 1===t?r("Insert row above"):r("Insert %s rows above",t.toString())},execute:aa,isVisible:e=>wt(e.model.getters.getActiveRows())&&pa(e)&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},Mg={...Og,name:e=>{const t=ea(e);return 1===t?r("Row above"):r("%s Rows above",t.toString())}},Ng={...Og,name:e=>{const t=ea(e);return 1===t?r("Insert row"):r("Insert %s rows",t.toString())},isVisible:pa,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},_g={execute:e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.max(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.bottom,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:o,quantity:i,dimension:"ROW"})},name:e=>{const t=ea(e);return 1===t?r("Insert row below"):r("Insert %s rows below",t.toString())},isVisible:e=>wt(e.model.getters.getActiveRows())&&pa(e)&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},Fg={..._g,name:e=>{const t=ea(e);return 1===t?r("Row below"):r("%s Rows below",t.toString())}},Dg={name:e=>{const t=Jn(e);return 1===t?r("Insert column"):r("Insert %s columns",t.toString())},isVisible:e=>wt(e.model.getters.getActiveCols())&&pa(e)&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_COL"},Lg={name:e=>{const t=Jn(e);return 1===t?r("Insert column left"):r("Insert %s columns left",t.toString())},execute:la,isVisible:e=>wt(e.model.getters.getActiveCols())&&pa(e)&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Pg={...Lg,name:e=>{const t=Jn(e);return 1===t?r("Column left"):r("%s Columns left",t.toString())}},kg={...Lg,name:e=>{const t=Jn(e);return 1===t?r("Insert column"):r("Insert %s columns",t.toString())},isVisible:pa,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Ug={name:e=>{const t=Jn(e);return 1===t?r("Insert column right"):r("Insert %s columns right",t.toString())},execute:ca,isVisible:e=>wt(e.model.getters.getActiveCols())&&pa(e)&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},Vg={...Ug,name:e=>{const t=Jn(e);return 1===t?r("Column right"):r("%s Columns right",t.toString())},execute:ca},zg={name:r("Insert cells"),isVisible:e=>pa(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},Bg={name:r("Insert cells and shift down"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});Xn(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},Hg={name:r("Insert cells and shift right"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});Xn(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},$g={name:r("Chart"),execute:e=>{const t=e.model.getters,o=e.model.uuidGenerator.uuidv4(),i=t.getActiveSheetId();1===vi(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const s={width:536,height:335},r=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:s,scrollY:r}=e.getActiveSheetScrollInfo(),{width:n,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:o+s+Math.max(0,(n-t.width)/2),y:i+r+Math.max(0,(a-t.height)/2)}}(t,s);e.model.dispatch("CREATE_CHART",{sheetId:i,id:o,position:r,size:s,definition:$n(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:o}),e.openSidePanel("ChartPanel"))},icon:"o-spreadsheet-Icon.INSERT_CHART"},Wg={name:r("Image"),description:"Ctrl+O",execute:ha,isVisible:e=>void 0!==e.imageProvider,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},Gg={name:r("Function"),icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},qg={name:r("SUM"),execute:e=>e.startCellEdition("=SUM(")},Zg={name:r("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},jg={name:r("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},Yg={name:r("MAX"),execute:e=>e.startCellEdition("=MAX(")},Xg={name:r("MIN"),execute:e=>e.startCellEdition("=MIN(")},Kg={name:r("All"),children:ep(Tg.getKeys())};const Qg={name:r("Link"),execute:ua,icon:"o-spreadsheet-Icon.INSERT_LINK"},Jg={name:r("Insert sheet"),execute:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSheetIds().indexOf(t)+1,i=e.model.uuidGenerator.uuidv4();e.model.dispatch("CREATE_SHEET",{sheetId:i,position:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})},icon:"o-spreadsheet-Icon.INSERT_SHEET"};function ep(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)})))}const tp=new Cr;tp.add("cut",{...va,sequence:10}).add("copy",{...ba,sequence:20}).add("paste",{...Sa,sequence:30}).add("paste_special",{...Ca,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Ea,sequence:10}).addChild("paste_format_only",["paste_special"],{...wa,sequence:20}).add("add_row_before",{...Ng,sequence:70}).add("add_column_before",{...kg,sequence:90}).add("insert_cell",{...zg,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...Bg,name:r("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...Hg,name:r("Shift right"),sequence:20}).add("delete_row",{...Ra,sequence:110,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_column",{...Oa,sequence:120,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_cell",{...Na,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.DELETE"}).addChild("delete_cell_up",["delete_cell"],{..._a,name:r("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...Fa,name:r("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("insert_link",{...Qg,name:r("Insert link"),sequence:150,separator:!0});const op={name:r("Sort range"),isVisible:pa,icon:"o-spreadsheet-Icon.SORT_RANGE"},ip={name:r("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();Gn(e,i,t.cell,o[0],"ascending")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},sp={name:r("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();Gn(e,i,t.cell,o[0],"descending")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},rp={name:r("Create filter"),execute:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelection().zones;jn(e,t,o)},isVisible:e=>!ga(e),isEnabled:e=>(e=>Si(...e.model.getters.getSelectedZones()))(e),icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},np={name:r("Remove filter"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:ga,icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},ap={name:r("Split text to columns"),sequence:1,execute:e=>e.openSidePanel("SplitToColumns",{}),isEnabled:e=>e.model.getters.isSingleColSelected(),icon:"o-spreadsheet-Icon.SPLIT_TEXT"},lp={name:r("Automatic"),execute:e=>ta(e,""),isActive:e=>function(e){const t=e.model.getters.getCell(e.model.getters.getActivePosition());return!t||!t.format}(e)},cp={name:r("Number"),description:"1,000.12",execute:e=>ta(e,"#,##0.00"),isActive:e=>Wp(e,"#,##0.00")},hp={name:r("Format as percent"),execute:da,icon:"o-spreadsheet-Icon.PERCENT"},dp={name:r("Percent"),description:"10.12%",execute:da,isActive:e=>Wp(e,"0.00%")},up={name:r("Currency"),description:"$1,000.12",execute:e=>ta(e,"[$$]#,##0.00"),isActive:e=>Wp(e,"[$$]#,##0.00")},gp={name:r("Currency rounded"),description:"$1,000",execute:e=>ta(e,"[$$]#,##0"),isActive:e=>Wp(e,"[$$]#,##0")},pp={name:r("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies,execute:e=>{e.openSidePanel("CustomCurrency",{})}},mp={name:r("Date"),description:"9/26/2008",execute:e=>ta(e,"m/d/yyyy"),isActive:e=>Wp(e,"m/d/yyyy")},fp={name:r("Time"),description:"10:43:00 PM",execute:e=>ta(e,"hh:mm:ss a"),isActive:e=>Wp(e,"hh:mm:ss a")},bp={name:r("Date time"),description:"9/26/2008 22:43:00",execute:e=>ta(e,"m/d/yyyy hh:mm:ss"),isActive:e=>Wp(e,"m/d/yyyy hh:mm:ss")},vp={name:r("Duration"),description:"27:51:38",execute:e=>ta(e,"hhhh:mm:ss"),isActive:e=>Wp(e,"hhhh:mm:ss")},Sp={name:r("Increase decimal places"),icon:"o-spreadsheet-Icon.INCREASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:1})},Cp={name:r("Decrease decimal places"),icon:"o-spreadsheet-Icon.DECRASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:-1})},Ep={name:r("Bold"),description:"Ctrl+B",execute:e=>oa(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},wp={name:r("Italic"),description:"Ctrl+I",execute:e=>oa(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},xp={name:r("Underline"),description:"Ctrl+U",execute:e=>oa(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},yp={name:r("Strikethrough"),execute:e=>oa(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},Ip={name:r("Font size"),children:me.map((e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>oa(t,{fontSize:e}),isActive:t=>function(e,t){const o=e.model.getters.getCurrentStyle().fontSize||q;return o===t}(t,e)}))),icon:"o-spreadsheet-Icon.FONT_SIZE"},Rp={name:r("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Tp={name:r("Horizontal align"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Ap={name:r("Left"),description:"Ctrl+Shift+L",execute:e=>oa(e,{align:"left"}),isActive:e=>"left"===Gp(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Op={name:r("Center"),description:"Ctrl+Shift+E",execute:e=>oa(e,{align:"center"}),isActive:e=>"center"===Gp(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},Mp={name:r("Right"),description:"Ctrl+Shift+R",execute:e=>oa(e,{align:"right"}),isActive:e=>"right"===Gp(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},Np={name:r("Vertical align"),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},_p={name:r("Top"),execute:e=>oa(e,{verticalAlign:"top"}),isActive:e=>"top"===(e.model.getters.getCurrentStyle().verticalAlign||j),icon:"o-spreadsheet-Icon.ALIGN_TOP"},Fp={name:r("Middle"),execute:e=>oa(e,{verticalAlign:"middle"}),isActive:e=>"middle"===(e.model.getters.getCurrentStyle().verticalAlign||j),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},Dp={name:r("Bottom"),execute:e=>oa(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===(e.model.getters.getCurrentStyle().verticalAlign||j),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},Lp={name:r("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},Pp={name:r("Overflow"),execute:e=>oa(e,{wrapping:"overflow"}),isActive:e=>"overflow"===(e.model.getters.getCurrentStyle().wrapping||"overflow"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},kp={name:r("Wrap"),execute:e=>oa(e,{wrapping:"wrap"}),isActive:e=>"wrap"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},Up={name:r("Clip"),execute:e=>oa(e,{wrapping:"clip"}),isActive:e=>"clip"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_CLIP"},Vp={name:r("Text Color"),icon:"o-spreadsheet-Icon.TEXT_COLOR"},zp={name:r("Fill Color"),icon:"o-spreadsheet-Icon.FILL_COLOR"},Bp={name:r("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},Hp={name:r("Paint Format"),execute:e=>e.model.dispatch("ACTIVATE_PAINT_FORMAT",{target:e.model.getters.getSelectedZones()}),icon:"o-spreadsheet-Icon.PAINT_FORMAT",isActive:e=>e.model.getters.isPaintingFormat()},$p={name:r("Clear formatting"),description:"Ctrl+<",execute:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},icon:"o-spreadsheet-Icon.CLEAR_FORMAT"};function Wp(e,t){return e.model.getters.getCell(e.model.getters.getActivePosition())?.format===t}function Gp(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}var qp=Object.freeze({__proto__:null,formatNumberAutomatic:lp,formatNumberNumber:cp,formatPercent:hp,formatNumberPercent:dp,formatNumberCurrency:up,formatNumberCurrencyRounded:gp,formatCustomCurrency:pp,formatNumberDate:mp,formatNumberTime:fp,formatNumberDateTime:bp,formatNumberDuration:vp,incraseDecimalPlaces:Sp,decraseDecimalPlaces:Cp,formatBold:Ep,formatItalic:wp,formatUnderline:xp,formatStrikethrough:yp,formatFontSize:Ip,formatAlignment:Rp,formatAlignmentHorizontal:Tp,formatAlignmentLeft:Ap,formatAlignmentCenter:Op,formatAlignmentRight:Mp,formatAlignmentVertical:Np,formatAlignmentTop:_p,formatAlignmentMiddle:Fp,formatAlignmentBottom:Dp,formatWrapping:Lp,formatWrappingOverflow:Pp,formatWrappingWrap:kp,formatWrappingClip:Up,textColor:Vp,fillColor:zp,formatCF:Bp,paintFormat:Hp,clearFormat:$p});function Zp(e,t,o){const i=e.model.getters.getActiveSheetId(),s="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(s,{sheetId:i,quantity:o}).isCancelledBecause(65)&&e.raiseError(Xr)}const jp={name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let o=t[0],i=t[t.length-1];return 1===t.length?r("Hide column %s",Pt(o).toString()):i-o+1===t.length?r("Hide columns %s - %s",Pt(o).toString(),Pt(i).toString()):r("Hide columns")},execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:na,icon:"o-spreadsheet-Icon.HIDE_COL"},Yp={name:r("Unhide columns"),execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))}},Xp={name:r("Unhide all columns"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0},Kp={name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let o=t[0],i=t[t.length-1];return 1===t.length?r("Hide row %s",(o+1).toString()):i-o+1===t.length?r("Hide rows %s - %s",(o+1).toString(),(i+1).toString()):r("Hide rows")},execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:ra,icon:"o-spreadsheet-Icon.HIDE_ROW"},Qp={name:r("Unhide rows"),execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))}},Jp={name:r("Unhide all rows"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0},em={name:r("Unfreeze"),isVisible:e=>{const{xSplit:t,ySplit:o}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+o>0},execute:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.UNFREEZE"},tm={name:r("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},om={name:r("No rows"),execute:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},im={name:r("1 row"),execute:e=>Zp(e,"ROW",1),isReadonlyAllowed:!0},sm={name:r("2 rows"),execute:e=>Zp(e,"ROW",2),isReadonlyAllowed:!0},rm={name:r("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();Zp(e,"ROW",t+1)},isReadonlyAllowed:!0},nm={name:r("No columns"),execute:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},am={name:r("1 column"),execute:e=>Zp(e,"COL",1),isReadonlyAllowed:!0},lm={name:r("2 columns"),execute:e=>Zp(e,"COL",2),isReadonlyAllowed:!0},cm={name:r("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();Zp(e,"COL",t+1)},isReadonlyAllowed:!0},hm={name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?r("Hide gridlines"):r("Show gridlines"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},icon:"o-spreadsheet-Icon.SHOW_HIDE_GRID"},dm={name:e=>e.model.getters.shouldShowFormulas()?r("Hide formulas"):r("Show formulas"),execute:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},um={name:e=>gm(e)?r("Remove selected filters"):r("Create filter"),isActive:e=>gm(e),isEnabled:e=>!pm(e),execute:e=>function(e){if(gm(e))return void e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()});if(pm(e))return;e.model.selection.selectTableAroundSelection();const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();jn(e,t,o)}(e),icon:"o-spreadsheet-Icon.FILTER_ICON_INACTIVE"};function gm(e){const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)}function pm(e){return!Si(...e.model.getters.getSelectedZones())}var mm=Object.freeze({__proto__:null,hideCols:jp,unhideCols:Yp,unhideAllCols:Xp,hideRows:Kp,unhideRows:Qp,unhideAllRows:Jp,unFreezePane:em,freezePane:tm,unFreezeRows:om,freezeFirstRow:im,freezeSecondRow:sm,freezeCurrentRow:rm,unFreezeCols:nm,freezeFirstCol:am,freezeSecondCol:lm,freezeCurrentCol:cm,viewGridlines:hm,viewFormulas:dm,createRemoveFilter:um});const fm=new Cr;fm.add("cut",{...va,sequence:10}).add("copy",{...ba,sequence:20}).add("paste",{...Sa,sequence:30}).add("paste_special",{...Ca,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Ea,sequence:10}).addChild("paste_format_only",["paste_special"],{...wa,sequence:20}).add("sort_columns",{...op,name:e=>e.model.getters.getActiveCols().size>1?r("Sort columns"):r("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...ip,sequence:10}).addChild("sort_descending",["sort_columns"],{...sp,sequence:20}).add("add_column_before",{...Lg,sequence:70}).add("add_column_after",{...Ug,sequence:80}).add("delete_column",{...Aa,sequence:90,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_column",{...Ma,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...jp,sequence:105,separator:!0}).add("unhide_columns",{...Yp,sequence:106,separator:!0}).add("conditional_formatting",{...Bp,sequence:110});const bm=new Cr;bm.add("format_number_automatic",{...lp,sequence:10,separator:!0}).add("format_number_number",{...cp,sequence:20}).add("format_number_percent",{...dp,sequence:30,separator:!0}).add("format_number_currency",{...up,sequence:40}).add("format_number_currency_rounded",{...gp,sequence:50}).add("format_custom_currency",{...pp,sequence:60,separator:!0}).add("format_number_date",{...mp,sequence:70}).add("format_number_time",{...fp,sequence:80}).add("format_number_date_time",{...bp,sequence:90}).add("format_number_duration",{...vp,sequence:100,separator:!0});const vm={name:r("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[()=>bm.getAll()]},Sm=new Cr;Sm.add("cut",{...va,sequence:10}).add("copy",{...ba,sequence:20}).add("paste",{...Sa,sequence:30}).add("paste_special",{...Ca,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Ea,sequence:10}).addChild("paste_format_only",["paste_special"],{...wa,sequence:20}).add("add_row_before",{...Og,sequence:50}).add("add_row_after",{..._g,sequence:60}).add("delete_row",{...Ia,sequence:70,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_row",{...Ta,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...Kp,sequence:85,separator:!0}).add("unhide_rows",{...Qp,sequence:86,separator:!0}).add("conditional_formatting",{...Bp,sequence:90});const Cm=new Cr;Cm.add("file",{name:r("File"),sequence:10}).add("edit",{name:r("Edit"),sequence:20}).addChild("undo",["edit"],{...ma,sequence:10}).addChild("redo",["edit"],{...fa,sequence:20,separator:!0}).addChild("copy",["edit"],{...ba,sequence:30}).addChild("cut",["edit"],{...va,sequence:40}).addChild("paste",["edit"],{...Sa,sequence:50}).addChild("paste_special",["edit"],{...Ca,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...Ea,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...wa,sequence:20}).addChild("find_and_replace",["edit"],{...xa,sequence:65,separator:!0}).addChild("delete",["edit"],{name:r("Delete"),icon:"o-spreadsheet-Icon.DELETE",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...ya,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...Ia,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...Aa,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{..._a,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...Fa,sequence:50}).addChild("edit_unhide_columns",["edit"],{...Xp,sequence:80}).addChild("edit_unhide_rows",["edit"],{...Jp,sequence:80}).add("view",{name:r("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...em,sequence:4}).addChild("freeze_panes",["view"],{...tm,sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{...om,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...im,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...sm,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...rm,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...nm,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...am,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...lm,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...cm,sequence:40}).addChild("view_gridlines",["view"],{...hm,sequence:10}).addChild("view_formulas",["view"],{...dm,sequence:15}).add("insert",{name:r("Insert"),sequence:40}).addChild("insert_row",["insert"],{...Ag,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...Mg,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...Fg,sequence:20}).addChild("insert_column",["insert"],{...Dg,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...Pg,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...Vg,sequence:20}).addChild("insert_cell",["insert"],{...zg,sequence:43}).addChild("insert_cell_down",["insert","insert_cell"],{...Bg,name:r("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...Hg,name:r("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...Jg,sequence:80,separator:!0}).addChild("insert_chart",["insert"],{...$g,sequence:50}).addChild("insert_image",["insert"],{...Wg,sequence:55}).addChild("insert_function",["insert"],{...Gg,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...qg,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...Zg,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...jg,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...Yg,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...Xg,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...Kg,sequence:50}).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=Tg.content;return[...new Set(Tg.getAll().map((e=>e.category)))].filter(lt).sort().map(((t,o)=>{const i=Object.keys(e).filter((o=>e[o].category===t));return{name:t,children:ep(i)}}))})).addChild("insert_link",["insert"],{...Qg,separator:!0,sequence:70}).add("format",{name:r("Format"),sequence:50}).addChild("format_number",["format"],{...vm,name:r("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...Ep,sequence:20}).addChild("format_italic",["format"],{...wp,sequence:30}).addChild("format_underline",["format"],{...xp,sequence:40}).addChild("format_strikethrough",["format"],{...yp,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...Ip,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...Rp,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...Ap,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...Op,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...Mp,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{..._p,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...Fp,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...Dp,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...Lp,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...Pp,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...kp,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...Up,sequence:30}).addChild("format_cf",["format"],{...Bp,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...$p,sequence:100,separator:!0}).add("data",{name:r("Data"),sequence:60}).addChild("sort_range",["data"],{...op,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...ip,sequence:10}).addChild("sort_descending",["data","sort_range"],{...sp,sequence:20}).addChild("split_to_columns",["data"],{...ap,sequence:20,separator:!0}).addChild("add_data_filter",["data"],{...rp,sequence:30}).addChild("remove_data_filter",["data"],{...np,sequence:30});const Em=new class extends _i{addTransformation(e,t,o){for(let i of t)this.content[i]||(this.content[i]=new Map),this.content[i].set(e,o);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},wm={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function xm(e,t){const o=wm[e.key];e.shiftKey?t.resizeAnchorZone(o,e.ctrlKey?"end":1):t.moveAnchorCell(o,e.ctrlKey?"end":1)}const ym=new Zo;xi`
353
353
  .o-selection {
354
354
  .o-selection-input {
355
355
  display: flex;
@@ -419,6 +419,18 @@
419
419
  grid-template-columns: repeat(${10}, 1fr);
420
420
  grid-gap: ${2}px;
421
421
  }
422
+ .o-color-picker-toggler-button {
423
+ display: flex;
424
+ .o-color-picker-toggler-sign {
425
+ margin: auto auto;
426
+ width: 55%;
427
+ height: 55%;
428
+ .o-icon {
429
+ width: 100%;
430
+ height: 100%;
431
+ }
432
+ }
433
+ }
422
434
  .o-color-picker-line-item {
423
435
  width: ${18}px;
424
436
  height: ${18}px;
@@ -609,7 +621,18 @@
609
621
  }
610
622
  }
611
623
  }
612
- `;class zm extends t.Component{static template="o-spreadsheet-ChartPanel";state;shouldUpdateChart=!0;get figureId(){return this.state.figureId}get sheetId(){return this.state.sheetId}setup(){const e=this.env.model.getters.getSelectedFigureId();e?(this.state=t.useState({panel:"configuration",figureId:e,sheetId:this.env.model.getters.getActiveSheetId()}),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getSelectedFigureId();e&&e!==this.state.figureId?(this.state.figureId=e,this.state.sheetId=this.env.model.getters.getActiveSheetId(),this.shouldUpdateChart=!1):this.shouldUpdateChart=!0,this.env.model.getters.isChartDefined(this.figureId)||this.props.onCloseSidePanel()}))):this.props.onCloseSidePanel()}updateChart(e){if(!this.shouldUpdateChart)return;const t={...this.getChartDefinition(),...e};return this.env.model.dispatch("UPDATE_CHART",{definition:t,id:this.figureId,sheetId:this.sheetId})}onTypeChange(e){const t=this.env.model.getters.getContextCreationChart(this.figureId);if(!t)throw new Error("Chart not defined.");const o=function(e,t){return On.get(t).getChartDefinitionFromContextCreation(e)}(t,e);this.env.model.dispatch("UPDATE_CHART",{definition:o,id:this.figureId,sheetId:this.sheetId})}get chartPanel(){const e=this.env.model.getters.getChartType(this.figureId);if(!e)throw new Error("Chart not defined.");const t=Vm.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e=this.figureId){return this.env.model.getters.getChartDefinition(e)}get chartTypes(){return function(){const e={};for(const t of On.getKeys())e[t]=On.get(t).name;return e}()}activatePanel(e){this.state.panel=e}}zm.props={onCloseSidePanel:Function};function Bm(e){e=`<svg xmlns="http://www.w3.org/2000/svg" ${e.slice(4)}`;const t=new Image;return t.src="data:image/svg+xml; charset=utf8, "+encodeURIComponent(e),t}const Hm={arrowGood:{template:"ARROW_UP",img:Bm('<svg class="o-cf-icon arrow-up" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#00A04A" d="M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"></path></svg>')},arrowNeutral:{template:"ARROW_RIGHT",img:Bm('<svg class="o-cf-icon arrow-right" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#F0AD4E" d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"></path></svg>')},arrowBad:{template:"ARROW_DOWN",img:Bm('<svg class="o-cf-icon arrow-down" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#DC6965" d="M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"></path></svg>')},smileyGood:{template:"SMILE",img:Bm('<svg class="o-cf-icon smile" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#00A04A" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z"></path></svg>')},smileyNeutral:{template:"MEH",img:Bm('<svg class="o-cf-icon meh" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#F0AD4E" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm8 144H160c-13.2 0-24 10.8-24 24s10.8 24 24 24h176c13.2 0 24-10.8 24-24s-10.8-24-24-24z"></path></svg>')},smileyBad:{template:"FROWN",img:Bm('<svg class="o-cf-icon frown" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#DC6965" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm-80 128c-40.2 0-78 17.7-103.8 48.6-8.5 10.2-7.1 25.3 3.1 33.8 10.2 8.4 25.3 7.1 33.8-3.1 16.6-19.9 41-31.4 66.9-31.4s50.3 11.4 66.9 31.4c8.1 9.7 23.1 11.9 33.8 3.1 10.2-8.5 11.5-23.6 3.1-33.8C326 321.7 288.2 304 248 304z"></path></svg>')},dotGood:{template:"GREEN_DOT",img:Bm('<svg class="o-cf-icon green-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#00A04A" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')},dotNeutral:{template:"YELLOW_DOT",img:Bm('<svg class="o-cf-icon yellow-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#F0AD4E" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')},dotBad:{template:"RED_DOT",img:Bm('<svg class="o-cf-icon red-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#DC6965" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')}},$m={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}};xi`
624
+ `;class zm extends t.Component{static template="o-spreadsheet-ChartPanel";state;shouldUpdateChart=!0;get figureId(){return this.state.figureId}get sheetId(){return this.state.sheetId}setup(){const e=this.env.model.getters.getSelectedFigureId();e?(this.state=t.useState({panel:"configuration",figureId:e,sheetId:this.env.model.getters.getActiveSheetId()}),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getSelectedFigureId();e&&e!==this.state.figureId?(this.state.figureId=e,this.state.sheetId=this.env.model.getters.getActiveSheetId(),this.shouldUpdateChart=!1):this.shouldUpdateChart=!0,this.env.model.getters.isChartDefined(this.figureId)||this.props.onCloseSidePanel()}))):this.props.onCloseSidePanel()}updateChart(e){if(!this.shouldUpdateChart)return;const t={...this.getChartDefinition(),...e};return this.env.model.dispatch("UPDATE_CHART",{definition:t,id:this.figureId,sheetId:this.sheetId})}onTypeChange(e){const t=this.env.model.getters.getContextCreationChart(this.figureId);if(!t)throw new Error("Chart not defined.");const o=function(e,t){return On.get(t).getChartDefinitionFromContextCreation(e)}(t,e);this.env.model.dispatch("UPDATE_CHART",{definition:o,id:this.figureId,sheetId:this.sheetId})}get chartPanel(){const e=this.env.model.getters.getChartType(this.figureId);if(!e)throw new Error("Chart not defined.");const t=Vm.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e=this.figureId){return this.env.model.getters.getChartDefinition(e)}get chartTypes(){return function(){const e={};for(const t of On.getKeys())e[t]=On.get(t).name;return e}()}activatePanel(e){this.state.panel=e}}zm.props={onCloseSidePanel:Function},xi`
625
+ .o-spreadsheet {
626
+ .o-icon {
627
+ .small-text {
628
+ font: bold 9px sans-serif;
629
+ }
630
+ .heavy-text {
631
+ font: bold 16px sans-serif;
632
+ }
633
+ }
634
+ }
635
+ `;function Bm(e){e=`<svg xmlns="http://www.w3.org/2000/svg" ${e.slice(4)}`;const t=new Image;return t.src="data:image/svg+xml; charset=utf8, "+encodeURIComponent(e),t}const Hm={arrowGood:{template:"ARROW_UP",img:Bm('<svg class="o-cf-icon arrow-up" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#00A04A" d="M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"></path></svg>')},arrowNeutral:{template:"ARROW_RIGHT",img:Bm('<svg class="o-cf-icon arrow-right" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#F0AD4E" d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"></path></svg>')},arrowBad:{template:"ARROW_DOWN",img:Bm('<svg class="o-cf-icon arrow-down" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#DC6965" d="M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"></path></svg>')},smileyGood:{template:"SMILE",img:Bm('<svg class="o-cf-icon smile" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#00A04A" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z"></path></svg>')},smileyNeutral:{template:"MEH",img:Bm('<svg class="o-cf-icon meh" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#F0AD4E" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm8 144H160c-13.2 0-24 10.8-24 24s10.8 24 24 24h176c13.2 0 24-10.8 24-24s-10.8-24-24-24z"></path></svg>')},smileyBad:{template:"FROWN",img:Bm('<svg class="o-cf-icon frown" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#DC6965" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm-80 128c-40.2 0-78 17.7-103.8 48.6-8.5 10.2-7.1 25.3 3.1 33.8 10.2 8.4 25.3 7.1 33.8-3.1 16.6-19.9 41-31.4 66.9-31.4s50.3 11.4 66.9 31.4c8.1 9.7 23.1 11.9 33.8 3.1 10.2-8.5 11.5-23.6 3.1-33.8C326 321.7 288.2 304 248 304z"></path></svg>')},dotGood:{template:"GREEN_DOT",img:Bm('<svg class="o-cf-icon green-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#00A04A" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')},dotNeutral:{template:"YELLOW_DOT",img:Bm('<svg class="o-cf-icon yellow-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#F0AD4E" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')},dotBad:{template:"RED_DOT",img:Bm('<svg class="o-cf-icon red-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#DC6965" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')}},$m={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}};xi`
613
636
  .o-icon-picker {
614
637
  position: absolute;
615
638
  z-index: ${de.IconPicker};
@@ -1069,7 +1092,7 @@
1069
1092
  }
1070
1093
  }
1071
1094
  }
1072
- `;class nf extends t.Component{static template="o-spreadsheet-TextValueProvider"}nf.props={values:Array,selectedIndex:Number,onValueSelected:Function};class af{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let o=window.getSelection();this.removeSelection();let i=document.createRange();if(e==t&&0===e)i.setStart(this.el,0),i.setEnd(this.el,0),o.addRange(i);else{const s=this.getText().length;(e<0||t>s)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${s}`),e<0&&(e=0),t>s&&(t=s),e>s&&(e=s));let r=this.findChildAtCharacterIndex(e),n=this.findChildAtCharacterIndex(t);i.setStart(r.node,r.offset),o.addRange(i),o.extend(n.node,n.offset)}}findChildAtCharacterIndex(e){let t,o,i=Ks(this.el),s=e,r=!0;do{t=i.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<s?s-=t.value.textContent.length:t.value.textContent&&t.value.textContent.length>=s&&i.return(t.value),o=t.value),t.done||"P"!==t.value.nodeName||(r?r=!1:s--)}while(!t.done&&s);return t.value?{node:t.value,offset:s}:{node:o,offset:s}}setText(e){if(this.el.innerHTML="",0!==e.length)for(const t of e){const e=document.createElement("p");if(0===t.length||t.every((e=>!e.value&&!e.class)))e.appendChild(document.createElement("br")),this.el.appendChild(e);else{for(const o of t){if(!o.value&&!o.class)continue;const t=document.createElement("span");t.innerText=o.value,t.style.color=o.color||"",o.class&&t.classList.add(o.class),e.appendChild(t)}this.el.appendChild(e)}}}scrollSelectionIntoView(){const e=document.getSelection()?.focusNode;if(!e||!this.el.contains(e))return;(e instanceof HTMLElement?e:e.parentElement)?.scrollIntoView({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){let{startElement:e,endElement:t,startSelectionOffset:o,endSelectionOffset:i}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,o),end:this.findSelectionIndex(t,i)}}findSelectionIndex(e,t){let o=0,i=Ks(this.el),s=i.next(),r=!0;for(;!s.done&&s.value!==e;)s.value.hasChildNodes()||s.value.textContent&&(o+=s.value.textContent.length),("P"===s.value.nodeName||"DIV"===s.value.nodeName&&s.value!==this.el)&&(r?r=!1:o++),s=i.next();if(s.value!==e)throw new Error("Cannot find the node in the children of the element");if(s.value.hasChildNodes()){const e=[...s.value.childNodes].slice(0,t);o+=e.reduce(((t,o,i)=>{if(null!==o.textContent){let s=o.textContent.length;return"P"===o.nodeName&&i!==e.length-1&&s++,t+s}return t}),0)}else o+=t;return"P"!==e.nodeName||r||""!=e.textContent||o++,o}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}getText(){let e="",t=Ks(this.el),o=t.next(),i=!0;for(;!o.done;)o.value.hasChildNodes()||(e+=o.value.textContent),("P"===o.value.nodeName||"DIV"===o.value.nodeName&&o.value!==this.el)&&(i?i=!1:e+=pe),o=t.next();return e}}xi`
1095
+ `;class nf extends t.Component{static template="o-spreadsheet-TextValueProvider"}nf.props={values:Array,selectedIndex:Number,onValueSelected:Function};class af{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let o=window.getSelection();this.removeSelection();let i=document.createRange();if(e==t&&0===e)i.setStart(this.el,0),i.setEnd(this.el,0),o.addRange(i);else{const s=this.getText().length;(e<0||t>s)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${s}`),e<0&&(e=0),t>s&&(t=s),e>s&&(e=s));let r=this.findChildAtCharacterIndex(e),n=this.findChildAtCharacterIndex(t);i.setStart(r.node,r.offset),o.addRange(i),o.extend(n.node,n.offset)}}findChildAtCharacterIndex(e){let t,o,i=Ks(this.el),s=e,r=!0;do{t=i.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<s?s-=t.value.textContent.length:t.value.textContent&&t.value.textContent.length>=s&&i.return(t.value),o=t.value),t.done||"P"!==t.value.nodeName||(r?r=!1:s--)}while(!t.done&&s);return t.value?{node:t.value,offset:s}:{node:o,offset:s}}setText(e){if(this.el.innerHTML="",0!==e.length)for(const t of e){const e=document.createElement("p");if(0===t.length||t.every((e=>!e.value&&!e.class)))e.appendChild(document.createElement("br")),this.el.appendChild(e);else{for(const o of t){if(!o.value&&!o.class)continue;const t=document.createElement("span");t.innerText=o.value,t.style.color=o.color||"",o.class&&t.classList.add(o.class),e.appendChild(t)}this.el.appendChild(e)}}}scrollSelectionIntoView(){const e=document.getSelection()?.focusNode;if(!e||!this.el.contains(e))return;(e instanceof HTMLElement?e:e.parentElement)?.scrollIntoView({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){let{startElement:e,endElement:t,startSelectionOffset:o,endSelectionOffset:i}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,o),end:this.findSelectionIndex(t,i)}}findSelectionIndex(e,t){let o=0,i=Ks(this.el),s=i.next(),r=!0;for(;!s.done&&s.value!==e;)s.value.hasChildNodes()||s.value.textContent&&(o+=s.value.textContent.length),("P"===s.value.nodeName||"DIV"===s.value.nodeName&&s.value!==this.el)&&(r?r=!1:o++),s=i.next();if(s.value!==e)return 0;if(s.value.hasChildNodes()){const e=[...s.value.childNodes].slice(0,t);o+=e.reduce(((t,o,i)=>{if(null!==o.textContent){let s=o.textContent.length;return"P"===o.nodeName&&i!==e.length-1&&s++,t+s}return t}),0)}else o+=t;return"P"!==e.nodeName||r||""!=e.textContent||o++,o}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}getText(){let e="",t=Ks(this.el),o=t.next(),i=!0;for(;!o.done;)o.value.hasChildNodes()||(e+=o.value.textContent),("P"===o.value.nodeName||"DIV"===o.value.nodeName&&o.value!==this.el)&&(i?i=!1:e+=pe),o=t.next();return e}}xi`
1073
1096
  .o-formula-assistant {
1074
1097
  .o-formula-assistant-head {
1075
1098
  background-color: #f2f2f2;
@@ -1391,7 +1414,7 @@
1391
1414
  onScroll.bind="onScroll"
1392
1415
  />`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetDOMScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){const{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{y:e}=this.env.model.getters.getMainViewportRect();return{top:`${this.props.topOffset+e}px`,right:"0px",width:"15px",bottom:"0px"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}qf.props={topOffset:{type:Number,optional:!0}};const Zf={ROW:Sm,COL:fm,CELL:tp};class jf extends t.Component{static template="o-spreadsheet-Grid";static components={GridComposer:ff,GridOverlay:_f,GridPopover:Ff,HeadersOverlay:kf,Menu:ar,Autofill:of,ClientTag:rf,Highlight:Hf,Popover:ir,VerticalScrollBar:qf,HorizontalScrollBar:Gf,FilterIconsOverlay:Cf};HEADER_HEIGHT=_;HEADER_WIDTH=F;menuState;gridRef;hiddenInput;onMouseWheel;canvasPosition;hoveredCell;setup(){this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hiddenInput=t.useRef("hiddenInput"),this.canvasPosition=Js(this.gridRef),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted((()=>this.focus())),this.props.exposeFocus((()=>this.focus())),Uf("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focus()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=Vf(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.col=void 0,this.hoveredCell.row=void 0}))}onCellHovered({col:e,row:t}){this.hoveredCell.col=e,this.hoveredCell.row=t}get gridOverlayDimensions(){return Ti({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.focus()}keyDownMapping={ENTER:()=>{this.env.model.getters.getActiveCell().type===ms.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},TAB:()=>this.env.model.selection.moveAnchorCell("right",1),"SHIFT+TAB":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===ms.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},DELETE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},BACKSPACE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},ESCAPE:()=>{this.env.model.getters.hasOpenedPopover()?this.closeOpenedPopover():this.menuState.isOpen?this.closeMenu():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":()=>ha(this.env),"ALT+=":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:o}=this.env.model.getters.getSelection(),i=this.env.model.getters.getAutomaticSums(e,t,o.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&i.length<=1){const t=i[0]?.zone,o=t?this.env.model.getters.zoneToXC(e,i[0].zone):"",s=`=SUM(${o})`;this.props.onGridComposerCellFocused(s,{start:5,end:5+o.length})}else this.env.model.dispatch("SUM_SELECTION")},"ALT+ENTER":()=>{const e=this.env.model.getters.getActiveCell();e.link&&Vi(e.link,this.env)},"CTRL+HOME":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,o)},"CTRL+END":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),o=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,o)},"SHIFT+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"CTRL+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"CTRL+SHIFT+E":()=>this.setHorizontalAlign("center"),"CTRL+SHIFT+L":()=>this.setHorizontalAlign("left"),"CTRL+SHIFT+R":()=>this.setHorizontalAlign("right"),"CTRL+SHIFT+V":()=>ia(this.env),"CTRL+SHIFT+<":()=>this.clearFormatting(),"CTRL+<":()=>this.clearFormatting(),"CTRL+SHIFT+ ":()=>{this.env.model.selection.selectAll()},"CTRL+ALT+=":()=>{const e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),o=1===this.env.model.getters.getSelectedZones().length,i=e.size>0&&o,s=t.size>0&&o;i&&!s?la(this.env):s&&!i&&aa(this.env)},"CTRL+ALT+-":()=>{const e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&0===t.length?this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",elements:e}):t.length>0&&0===e.length&&this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},"SHIFT+PAGEDOWN":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"CTRL+K":()=>ua(this.env)};focus(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.env.model.getters.getEditionMode()||this.hiddenInput.el?.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}get isAutofillVisible(){const 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!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:F,gridOffsetY:_})}moveCanvas(e,t){const{scrollX:o,scrollY:i}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o+e,offsetY:i+t})}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}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,{ctrlKey:o,shiftKey:i}){o&&this.env.model.dispatch("PREPARE_SELECTION_INPUT_EXPANSION"),this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),"editing"===this.env.model.getters.getEditionMode()&&this.env.model.dispatch("STOP_EDITION"),i?this.env.model.selection.setAnchorCorner(e,t):o?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let s=e,r=t;tf(this.env,((e,t)=>{(e!==s&&-1!=e||t!==r&&-1!=t)&&(s=-1===e?s:e,r=-1===t?r:t,this.env.model.selection.setAnchorCorner(s,r))}),(()=>{this.env.model.dispatch("STOP_SELECTION_INPUT"),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}))}onCellDoubleClicked(e,t){const o=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:o,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t}).type===ms.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()}closeOpenedPopover(){this.env.model.dispatch("CLOSE_CELL_POPOVER")}processArrows(e){e.preventDefault(),e.stopPropagation(),this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),xm(e,this.env.model.selection),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}onKeydown(e){if(e.key.startsWith("Arrow"))return void this.processArrows(e);let t="";e.ctrlKey&&(t+="CTRL+"),e.metaKey&&(t+="CTRL+"),e.altKey&&(t+="ALT+"),e.shiftKey&&(t+="SHIFT+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];return o?(e.preventDefault(),e.stopPropagation(),void o()):void 0}onInput(e){(e.isComposing||"insertFromPaste"!==e.inputType)&&e.data&&(e.preventDefault(),e.stopPropagation(),this.props.onGridComposerCellFocused(e.data))}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:o,top:i}=t;let s="CELL";this.env.model.dispatch("STOP_EDITION"),this.env.model.getters.getActiveCols().has(o)?s="COL":this.env.model.getters.getActiveRows().has(i)&&(s="ROW");const{x:r,y:n,width:a,height:l}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(s,r+a,n+l)}onCellRightClicked(e,t,{x:o,y:i}){const s=this.env.model.getters.getSelectedZones();let r="CELL";ni(e,t,s[s.length-1])?this.env.model.getters.getActiveCols().has(e)?r="COL":this.env.model.getters.getActiveRows().has(t)&&(r="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(r,o,i)}toggleContextMenu(e,t,o){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:o},this.menuState.menuItems=Zf[e].getMenuItems()}copy(e,t){if(!this.gridEl.contains(document.activeElement))return;const o=t.clipboardData;if(!o)return void this.displayWarningCopyPasteNotSupported();if("inactive"!==this.env.model.getters.getEditionMode())return;e?qn(this.env):this.env.model.dispatch("COPY");const i=this.env.model.getters.getClipboardContent();for(const e in i)o.setData(e,i[e]);t.preventDefault()}paste(e){if(!this.gridEl.contains(document.activeElement))return;const t=e.clipboardData;if(t){if(t.types.indexOf(fs.PlainText)>-1){const e=t.getData(fs.PlainText),o=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardTextContent()===e?Kn(this.env,o):Qn(this.env,o,e)}}else this.displayWarningCopyPasteNotSupported()}displayWarningCopyPasteNotSupported(){this.env.raiseError(r("Copy/Paste is not supported in this browser."))}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.focus()}}jf.props={sidePanelIsOpen:Boolean,exposeFocus:Function,focusComposer:String,onComposerContentFocused:Function,onGridComposerCellFocused:Function};class Yf{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const Xf=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],Kf="000000",Qf={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},Jf={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"},eb="http://schemas.openxmlformats.org/drawingml/2006/main",tb="http://schemas.openxmlformats.org/drawingml/2006/chart",ob={workbook:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",sheet:"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+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"},ib={document:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",sheet:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",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"},sb="http://schemas.openxmlformats.org/officeDocument/2006/relationships",rb=.75,nb=.1317,ab=8.43,lb=12.75,cb=30,hb=100,db=164,ub={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}]},gb=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","ERF.PRECISE","ERFC.PRECISE","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","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","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOWEEKNUM","LOGNORM.DIST","LOGNORM.INV","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","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANK.AVG","RANK.EQ","RRI","SEC","SECH","SHEET","SHEETS","SKEW.P","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TEXTJOIN","UNICHAR","UNICODE","VAR.P","VAR.S","WEBSERVICE","WEIBULL.DIST","XOR","Z.TEST"],pb="[Content_Types].xml";var mb;!function(e){e.DiagonalBorderNotSupported="Diagonal Borders",e.BorderStyleNotSupported="Border style",e.FillStyleNotSupported="Fill Style",e.FontNotSupported="Font",e.HorizontalAlignmentNotSupported="Horizontal Alignment",e.VerticalAlignmentNotSupported="Vertical Alignments",e.MultipleRulesCfNotSupported="Multiple rules conditional formats",e.CfTypeNotSupported="Conditional format type",e.CfFormatBorderNotSupported="Borders in conditional formats",e.CfFormatAlignmentNotSupported="Alignment in conditional formats",e.CfFormatNumFmtNotSupported="Num formats in conditional formats",e.CfIconSetEmptyIconNotSupported="IconSets with empty icons",e.BadlyFormattedHyperlink="Badly formatted hyperlink",e.NumFmtIdNotSupported="Number format"}(mb||(mb={}));class fb{_parsingWarnings=new Set;_conversionWarnings=new Set;addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,o){let i=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;o&&(i+=`Only ${o.join(", ")} are currently supported.`),this._conversionWarnings.has(i)||this._conversionWarnings.add(i)}}const bb=["thin"],vb=["general","left","center","right"],Sb=["top","center","bottom"],Cb=["Arial"],Eb=["solid"],wb=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],xb={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},yb={dashDot:"thin",dashDotDot:"thin",dashed:"dashed",dotted:"dotted",double:"thin",hair:"thin",medium:"medium",mediumDashDot:"thin",mediumDashDotDot:"thin",mediumDashed:"thin",none:void 0,slantDashDot:"thin",thick:"thick",thin:"thin"},Ib={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},Rb={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},Tb={top:"top",middle:"center",bottom:"bottom"};const Ab={aboveAverage:void 0,expression:void 0,cellIs:void 0,colorScale:void 0,dataBar:void 0,iconSet:void 0,top10:void 0,uniqueValues:void 0,duplicateValues:void 0,containsText:"ContainsText",notContainsText:"NotContains",beginsWith:"BeginsWith",endsWith:"EndsWith",containsBlanks:"IsEmpty",notContainsBlanks:"IsNotEmpty",containsErrors:void 0,notContainsErrors:void 0,timePeriod:void 0},Ob={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},Mb={NoIcons:void 0,"3Arrows":"arrows","3ArrowsGray":"arrows","3Symbols":"smiley","3Symbols2":"smiley","3Signs":"dots","3Flags":"dots","3TrafficLights1":"dots","3TrafficLights2":"dots","4Arrows":"arrows","4ArrowsGray":"arrows","4RedToBlack":"dots","4Rating":"smiley","4TrafficLights":"dots","5Arrows":"arrows","5ArrowsGray":"arrows","5Rating":"smiley","5Quarters":"dots","3Stars":"smiley","3Triangles":"arrows","5Boxes":"dots"},Nb={b:"bottom",t:"top",l:"left",r:"right",tr:"right"},_b={areaChart:void 0,area3DChart:void 0,lineChart:"line",line3DChart:void 0,stockChart:void 0,radarChart:void 0,scatterChart:void 0,pieChart:"pie",pie3DChart:void 0,doughnutChart:"pie",barChart:"bar",bar3DChart:void 0,ofPieChart:void 0,surfaceChart:void 0,surface3DChart:void 0,bubbleChart:void 0},Fb={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP",101:"AVERAGE",102:"COUNT",103:"COUNTA",104:"MAX",105:"MIN",106:"PRODUCT",107:"STDEV",108:"STDEVP",109:"SUM",110:"VAR",111:"VARP"},Db={0:"",1:"0",2:"0.00",3:"#,#00",4:"#,##0.00",9:"0%",10:"0.00%",11:void 0,12:void 0,13:void 0,14:"m/d/yyyy",15:"m/d/yyyy",16:"m/d/yyyy",17:"m/d/yyyy",18:"hh:mm:ss a",19:"hh:mm:ss a",20:"hhhh:mm:ss",21:"hhhh:mm:ss",22:"m/d/yy h:mm",37:void 0,38:void 0,39:void 0,40:void 0,45:"hhhh:mm:ss",46:"hhhh:mm:ss",47:"hhhh:mm:ss",48:void 0,49:void 0},Lb={0:1,"0.00":2,"#,#00":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mm-yy":15,"mm-yy":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"#,##0 ;(#,##0)":37,"#,##0 ;[Red](#,##0)":38,"#,##0.00;(#,##0.00)":39,"#,##0.00;[Red](#,##0.00)":40,"mm:ss":45,"[h]:mm:ss":46,"mmss.0":47,"##0.0E+0":48,"@":49,"hh:mm:ss a":19},Pb={0:"000000",1:"FFFFFF",2:"FF0000",3:"00FF00",4:"0000FF",5:"FFFF00",6:"FF00FF",7:"00FFFF",8:"000000",9:"FFFFFF",10:"FF0000",11:"00FF00",12:"0000FF",13:"FFFF00",14:"FF00FF",15:"00FFFF",16:"800000",17:"008000",18:"000080",19:"808000",20:"800080",21:"008080",22:"C0C0C0",23:"808080",24:"9999FF",25:"993366",26:"FFFFCC",27:"CCFFFF",28:"660066",29:"FF8080",30:"0066CC",31:"CCCCFF",32:"000080",33:"FF00FF",34:"FFFF00",35:"00FFFF",36:"800080",37:"800000",38:"008080",39:"0000FF",40:"00CCFF",41:"CCFFFF",42:"CCFFCC",43:"FFFF99",44:"99CCFF",45:"FF99CC",46:"CC99FF",47:"FFCC99",48:"3366FF",49:"33CCCC",50:"99CC00",51:"FFCC00",52:"FF9900",53:"FF6600",54:"666699",55:"969696",56:"003366",57:"339966",58:"003300",59:"333300",60:"993300",61:"993366",62:"333399",63:"333333",64:"000000",65:"FFFFFF"};function kb(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=Kf;else{if(!e.indexed)return;t=Pb[e.indexed]}var o;return t=6===(o=t).length?"#"+o+"FF":"#"+o.slice(2)+o.slice(0,2),e.tint&&(t=function(e,t){const o=Ft(e),i=Lt(o);t<0&&(i.l=i.l*(1+t));t>0&&(i.l=i.l*(1-t)+(100-100*(1-t)));return _t(Dt(i))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function Ub(e,t){const o=e.split("/"),i=t.split("/");let s="",r=0;for(let e=0;e<o.length-1;e++)o[e]===i[e]?r++:s+="../";return s+=i.slice(r).join("/"),s}function Vb(e,t=0){const o={};for(let i=0;i<e.length;i++)e[i]&&(o[i+t]=e[i]);return o}function zb(e){const t=[];for(let o of Object.keys(e).map(Number))t[o]=e[o];return t}function Bb(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const Hb=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function $b(e,t,o){if(0===e)return;let i=Db[e]||t.find((t=>t.id===e))?.format;if(i)try{let e=i.replace(/(.*?);.*/,"$1");e=e.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]"),e=e.replace(/\[\$\]/g,"");const t=e.match(/"/g)?.length||0;if(t/2+(e.match(/\[/g)?.length||0)>1)throw new Error("Multiple escaped blocks in format");if(e=e.replace(/"(.*)"/g,"[$$$1]"),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),e=e.replace(/\\ /g," "),e=e.replace(/\\./g,(e=>e[1])),function(e){return Hb.test(e)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm/g,"mmm"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return uo(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}o.generateNotSupportedWarning(mb.NumFmtIdNotSupported,i||`nmFmtId ${e}`)}function Wb(e,t){const o=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(mb.DiagonalBorderNotSupported)}(e,t);const o={top:Gb(e.top,t),bottom:Gb(e.bottom,t),left:Gb(e.left,t),right:Gb(e.right,t)};return Object.keys(o).forEach((e=>void 0===o[e]&&delete o[e])),o}));return Vb(o,1)}function Gb(e,t){if(!e)return;!function(e,t){bb.includes(e.style)||t.generateNotSupportedWarning(mb.BorderStyleNotSupported,e.style,bb)}(e,t);const o=yb[e.style];return o?{style:o,color:kb(e.color)}:void 0}function qb(e,t){return Vb(e.styles.map((o=>Zb({fontStyle:e.fonts[o.fontId],fillStyle:e.fills[o.fillId],alignment:o.alignment},t))),1)}function Zb(e,t){return function(e,t,o){e&&e.name&&!Cb.includes(e.name)&&o.generateNotSupportedWarning(mb.FontNotSupported,e.name,Cb);t&&t.patternType&&!Eb.includes(t.patternType)&&o.generateNotSupportedWarning(mb.FillStyleNotSupported,t.patternType,Eb)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!vb.includes(e)&&t.generateNotSupportedWarning(mb.HorizontalAlignmentNotSupported,e,vb)}(e?.alignment?.horizontal,t),function(e,t){e&&!Sb.includes(e)&&t.generateNotSupportedWarning(mb.VerticalAlignmentNotSupported,e,Sb)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?Rb[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?Ib[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?kb(e.fillStyle?.fgColor):kb(e.fillStyle?.bgColor),textColor:kb(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function jb(e,t){const o=[];for(let i of e.styles){const s=$b(i.numFmtId,e.numFmts,t);s&&(o[i.numFmtId]=s)}return Vb(o,1)}function Yb(e,t,o){const i=[];let s=1;for(let n of e){if(0===n.cfRules.length)continue;Jb(n,t,o);const e=n.cfRules[0];let a;const l=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"dataBar":case"duplicateValues":case"expression":case"top10":case"uniqueValues":case"timePeriod":continue;case"colorScale":const t=Xb(s++,n);t&&i.push(t);continue;case"iconSet":const c=Kb(s++,n,o);c&&i.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=Ab[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=Ab[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(r=e.operator).slice(0,1).toUpperCase()+r.slice(1),l.push(e.formula[0]),2===e.formula.length&&l.push(e.formula[1])}a&&void 0!==e.dxfId&&i.push({id:(s++).toString(),ranges:n.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:Zb({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},o)}})}}var r;return i}function Xb(e,t){const o=t.cfRules[0].colorScale;if(!o||o.cfvos.length!==o.colors.length||o.cfvos.length<2||o.cfvos.length>3)return;const i=[];for(let e=0;e<o.cfvos.length;e++)i.push({color:(s=kb(o.colors[e])||"#FFFFFF",9===s.length&&(s=s.slice(0,7)),parseInt(s.replace("#",""),16)),type:Ob[o.cfvos[e].type],value:o.cfvos[e].value});var s;const r=i[0],n=2===i.length?i[1]:i[2],a=3===i.length?i[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:r,midpoint:a,maximum:n}}}function Kb(e,t,o){const i=t.cfRules[0].iconSet;if(!i)return;let s=i.cfvos,r=i.cfIcons;if(s.length<3||r&&r.length<3)return;s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]),r&&r.length>3&&(r=[r[0],r[Math.floor(r.length/2)],r[r.length-1]]);const n=[];for(let e=1;e<=2;e++){const t=Ob[s[e].type];if("value"===t)return;n.push({value:s[e].value||"",operator:s[e].gte?"ge":"gt",type:t})}let a={lower:r?Qb(r[0].iconSet,r[0].iconId):Qb(i.iconSet,0),middle:r?Qb(r[1].iconSet,r[1].iconId):Qb(i.iconSet,1),upper:r?Qb(r[2].iconSet,r[2].iconId):Qb(i.iconSet,2)};i.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(let e of Object.keys(a))if(!a[e])switch(o.generateNotSupportedWarning(mb.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=$m.dots.good;break;case"middle":a[e]=$m.dots.neutral;break;case"lower":a[e]=$m.dots.bad}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"IconSetRule",icons:a,upperInflectionPoint:n[1],lowerInflectionPoint:n[0]}}}function Qb(e,t){const o=Mb[e];return o?0===t?$m[o].bad:1===t?$m[o].neutral:$m[o].good:""}function Jb(e,t,o){if(e.cfRules.length>1&&o.generateNotSupportedWarning(mb.MultipleRulesCfNotSupported),wb.includes(e.cfRules[0].type)||o.generateNotSupportedWarning(mb.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const i=t[e.cfRules[0].dxfId];i.border&&o.generateNotSupportedWarning(mb.CfFormatBorderNotSupported),i.alignment&&o.generateNotSupportedWarning(mb.CfFormatAlignmentNotSupported),i.numFmt&&o.generateNotSupportedWarning(mb.CfFormatNumFmtNotSupported)}}class ev{scope;code="";constructor(e=new ov){this.scope=e}append(...e){this.code+=e.map((e=>e.toString())).join("\n")+"\n"}return(e){return new tv(this.scope,this.code,e)}toString(){return iv(this.code)}}class tv{scope;returnExpression;code;constructor(e,t,o){this.scope=e,this.returnExpression=o,this.code=iv(t)}toString(){return this.code}wrapInClosure(){const e=this.scope.nextVariableName(),t=new ev(this.scope);return t.append(`const ${e} = () => {`),t.append(this.code),t.append(`return ${this.returnExpression};`),t.append("}"),t.return(e)}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;const e=this.scope.nextVariableName(),t=new ev(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class ov{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function iv(e){let t="",o=0;const i=e.split("\n").map((e=>e.trim())).filter((e=>""!==e));for(const e of i)e.startsWith("}")&&o--,t+="\t".repeat(o)+e+"\n",e.endsWith("{")&&o++;return t.trim()}const sv=Tg.content,rv=["%"],nv="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(rv);function av(e){e=Et(e);const t=new vv(e),o=[];for(;!t.isOver();){let e=fv(t)||hv(t)||dv(t)||gv(t)||lv(t)||bv(t)||uv(t)||mv(t);e||(e={type:"UNKNOWN",value:t.shift()}),o.push(e)}return o}function lv(e){return"?"===e.current()?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const cv={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function hv(e){if(e.current()in cv){const t=e.shift();return{type:cv[t],value:t}}return null}function dv(e){for(let t of nv)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}function uv(e){const t=e.remaining().match(Zt);return t?(e.advanceBy(t[0].length),{type:"NUMBER",value:t[0]}):null}function gv(e){if('"'===e.current()){const t=e.shift();let o=t;for(;e.current()&&(e.current()!==t||"\\"===o[o.length-1]);)o+=e.shift();return'"'===e.current()&&(o+=e.shift()),{type:"STRING",value:o}}return null}const pv=/\w|\.|!|\$/;function mv(e){let t="";if("'"===e.current()){let o=e.shift();for(t+=o;e.current();)if(o=e.shift(),t+=o,"'"===o){if(!e.current()||"'"!==e.current())break;o=e.shift(),t+=o}if("'"!==o)return{type:"UNKNOWN",value:t}}for(;e.current()&&pv.test(e.current());)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in sv)return{type:"FUNCTION",value:e};return Po.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function fv(e){let t=0;for(;e.current()===pe;)t++,e.shift();if(t)return{type:"SPACE",value:pe.repeat(t)};for(;" "===e.current();)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function bv(e){return e.currentStartsWith(Q)?(e.advanceBy(Q.length),{type:"INVALID_REFERENCE",value:Q}):null}class vv{text;currentIndex=0;constructor(e){this.text=e}current(){return this.text[this.currentIndex]}shift(){return this.text[this.currentIndex++]}advanceBy(e){this.currentIndex+=e}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){for(let t=0;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}}const Sv=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,Cv=["-","+"],Ev=["%"],wv=["*","+","&"],xv={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function yv(e){const t=e.shift();if(!t)throw new h(he);switch(t.type){case"DEBUGGER":const o=Tv(e,1e3);return o.debug=!0,o;case"NUMBER":return{type:"NUMBER",value:to(t.value)};case"STRING":return{type:"STRING",value:ke(t.value)};case"FUNCTION":const i=function(e){Rv(e,"LEFT_PAREN",r("Missing opening parenthesis"));const t=e[0];if("RIGHT_PAREN"===t?.type)return Rv(e,"RIGHT_PAREN"),[];const o=[];o.push(Iv(e));for(;"RIGHT_PAREN"!==e[0]?.type;)Rv(e,"COMMA",r("Wrong function call")),o.push(Iv(e));return Rv(e,"RIGHT_PAREN"),o}(e);return{type:"FUNCALL",value:t.value,args:i};case"INVALID_REFERENCE":throw new u;case"REFERENCE":if(":"===e[0]?.value&&"REFERENCE"===e[1]?.type){e.shift();const o=e.shift();return{type:"REFERENCE",value:`${t.value}:${o?.value}`}}return{type:"REFERENCE",value:t.value};case"SYMBOL":if(["TRUE","FALSE"].includes(t.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===t.value.toUpperCase()};if(t.value&&Sv.test(t.value)&&"LEFT_PAREN"===e[0]?.type)throw new p(t.value);throw new h(r("Invalid formula"));case"LEFT_PAREN":const s=Tv(e);return Rv(e,"RIGHT_PAREN",r("Missing closing parenthesis")),s;case"OPERATOR":const n=t.value;if(Cv.includes(n))return{type:"UNARY_OPERATION",value:n,operand:Tv(e,xv[n])};throw new h(r("Unexpected token: %s",t.value));default:throw new h(r("Unexpected token: %s",t.value))}}function Iv(e){const t=e[0];return"COMMA"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:""}:Tv(e)}function Rv(e,t,o=he){const i=e.shift();if(!i||i.type!==t)throw new h(o)}function Tv(e,t=0){if(0===e.length)throw new h(he);let o=yv(e);for(;"OPERATOR"===e[0]?.type&&xv[e[0].value]>t;){const t=e.shift().value;if(Ev.includes(t))o={type:"UNARY_OPERATION",value:t,operand:o,postfix:!0};else{o={type:"BIN_OPERATION",value:t,left:o,right:Tv(e,xv[t])}}}return o}function Av(e){return Ov(av(e))}function Ov(e){"="===(e=e.filter((e=>"SPACE"!==e.type)))[0].value&&e.splice(0,1);const t=Tv(e);if(e.length)throw new h(he);return t}function Mv(e,t,o){switch(t===e.type&&(e=o(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Mv(e,t,o)))};case"UNARY_OPERATION":return{...e,operand:Mv(e.operand,t,o)};case"BIN_OPERATION":return{...e,right:Mv(e.right,t,o),left:Mv(e.left,t,o)};default:return e}}function Nv(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>Nv(e)));return`${e.value}(${t.join(",")})`;case"NUMBER":return e.value.toString();case"REFERENCE":default:return e.value;case"STRING":return`"${e.value}"`;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"UNARY_OPERATION":return e.postfix?_v(e)+e.value:e.value+Fv(e);case"BIN_OPERATION":return _v(e)+e.value+Fv(e)}}function _v(e){const t=e.value,o="left"in e?e.left:e.operand,i=o.value;return"BIN_OPERATION"===o.type&&xv[i]<xv[t]?`(${Nv(o)})`:Nv(o)}function Fv(e){const t=e.value,o="right"in e?e.right:e.operand,i=xv[o.value],s=xv[t];let r=!1;return"BIN_OPERATION"!==o.type?r=!1:i<s?r=!0:i!==s||wv.includes(t)||(r=!0),r?`(${Nv(o)})`:Nv(o)}var Dv;!function(e){e[e.LeftRef=0]="LeftRef",e[e.RightRef=1]="RightRef",e[e.Separator=2]="Separator",e[e.FullColumnSeparator=3]="FullColumnSeparator",e[e.FullRowSeparator=4]="FullRowSeparator",e[e.RightColumnRef=5]="RightColumnRef",e[e.RightRowRef=6]="RightRowRef",e[e.Found=7]="Found"}(Dv||(Dv={}));const Lv=(e,t=(()=>!0))=>[{goTo:e,guard:t}],Pv=(e,t=(()=>!0))=>({goTo:e,guard:t}),kv={[Dv.LeftRef]:{REFERENCE:Lv(Dv.Separator),NUMBER:Lv(Dv.FullRowSeparator),SYMBOL:[Pv(Dv.FullColumnSeparator,(e=>ko(e.value))),Pv(Dv.FullRowSeparator,(e=>Uo(e.value)))]},[Dv.FullColumnSeparator]:{SPACE:Lv(Dv.FullColumnSeparator),OPERATOR:Lv(Dv.RightColumnRef,(e=>":"===e.value))},[Dv.FullRowSeparator]:{SPACE:Lv(Dv.FullRowSeparator),OPERATOR:Lv(Dv.RightRowRef,(e=>":"===e.value))},[Dv.Separator]:{SPACE:Lv(Dv.Separator),OPERATOR:Lv(Dv.RightRef,(e=>":"===e.value))},[Dv.RightRef]:{SPACE:Lv(Dv.RightRef),NUMBER:Lv(Dv.Found),REFERENCE:Lv(Dv.Found,(e=>zo(e.value))),SYMBOL:Lv(Dv.Found,(e=>Vo(e.value)))},[Dv.RightColumnRef]:{SPACE:Lv(Dv.RightColumnRef),SYMBOL:Lv(Dv.Found,(e=>Vo(e.value))),REFERENCE:Lv(Dv.Found,(e=>zo(e.value)))},[Dv.RightRowRef]:{SPACE:Lv(Dv.RightRowRef),NUMBER:Lv(Dv.Found),REFERENCE:Lv(Dv.Found,(e=>zo(e.value)))},[Dv.Found]:{}};function Uv(e){let t=0,o=kv[Dv.LeftRef];const i=[];for(;void 0!==o;){const s=e[t++];if(!s)return null;const r=o[s.type]?.find((e=>e.guard(s))),n=r?r.goTo:void 0;switch(n){case void 0:return null;case Dv.Found:return i.push(s),e.splice(0,t),{type:"REFERENCE",value:dt(i.map((e=>e.value)))};default:o=kv[n],i.push(s)}}return null}function Vv(e){const t=av(e),o=[];for(;t.length;)o.push(Uv(t)||t.shift());return o}const zv=Tg.content,Bv={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},Hv={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},$v={};function Wv(e){const t=Vv(e),{dependencies:o,constantValues:i}=function(e){const t={numbers:[],strings:[]},o=[];for(const i of e)switch(i.type){case"INVALID_REFERENCE":case"REFERENCE":o.push(i.value);break;case"STRING":const e=ke(i.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=to(i.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:o,constantValues:t}}(t),s=function(e,t,o){return dt(e.map((e=>{switch(e.type){case"STRING":const i=ke(e.value);return`|S${o.strings.indexOf(i)}|`;case"NUMBER":return`|N${o.numbers.indexOf(to(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,o,i);if(!$v[s]){const n=Ov([...t]),a=new ov;if("BIN_OPERATION"===n.type&&":"===n.value)throw new h(r("Invalid formula"));if("EMPTY"===n.type)throw new h(r("Invalid formula"));const l=g(n),c=new ev;c.append(`// ${s}`),c.append(l),c.append(`return ${l.returnExpression};`);let d=new Function("deps","ref","range","ctx",c.toString());function u(e){const t=zv[e.value.toUpperCase()],o=e.args,i=o.length;if(i<t.minArgRequired)throw new h(r("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),i.toString()));if(i>t.maxArgPossible)throw new h(r("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),i.toString()));const s=t.nbrArgRepeating;if(s>1){const o=t.args.length-s;if((i-o)%s!=0)throw new h(r("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),o.toString(),s.toString()))}let n=[];for(let s=0;s<i;s++){const i=t.getArgToFocus(s+1)-1;if(0<=i&&i<t.args.length){const a=o[s],l=t.args[i],c=l.type||[],d=c.includes("META"),u=l.lazy,p=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),m=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(m&&"REFERENCE"!==a.type)throw new h(r("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(s+1).toString(),a.type.toLowerCase()));const f=g(a,d,p,{functionName:e.value.toUpperCase(),paramIndex:s+1});n.push(u?f.wrapInClosure():f)}}return n}function g(e,t=!1,s=!1,n={}){const l=new ev(a);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&t)throw new h(r("Argument must be a reference to a cell or range."));switch(e.debug&&l.append("debugger;"),e.type){case"BOOLEAN":return l.return(`{ value: ${e.value} }`);case"NUMBER":return l.return(`{ value: this.constantValues.numbers[${i.numbers.indexOf(e.value)}] }`);case"STRING":return l.return(`{ value: this.constantValues.strings[${i.strings.indexOf(e.value)}] }`);case"REFERENCE":const r=o.indexOf(e.value);return s?l.return(`range(deps[${r}])`):l.return(`ref(deps[${r}], ${t?"true":"false"}, "${n.functionName||Bv["="]}", ${n.paramIndex})`);case"FUNCALL":const a=u(e).map((e=>e.assignResultToVariable()));l.append(...a);const c=e.value.toUpperCase();return l.append(`ctx.__lastFnCalled = '${c}';`),l.return(`ctx['${c}'](${a.map((e=>e.returnExpression))})`);case"UNARY_OPERATION":{const t=Hv[e.value],o=g(e.operand,!1,!1,{functionName:t}).assignResultToVariable();return l.append(o),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${o.returnExpression})`)}case"BIN_OPERATION":{const t=Bv[e.value],o=g(e.left,!1,!1,{functionName:t}).assignResultToVariable(),i=g(e.right,!1,!1,{functionName:t}).assignResultToVariable();return l.append(o),l.append(i),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${o.returnExpression}, ${i.returnExpression})`)}case"EMPTY":return l.return("undefined")}}$v[s]={execute:d}}return{execute:$v[s].execute,dependencies:o,constantValues:i,tokens:t}}function Gv(e){return function(e){let t=[],o="";return e.map(((e,i)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(o=""),e.type){case"FUNCTION":o=e.value;break;case"LEFT_PAREN":t.push({parent:o,argPosition:0}),o="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const o=t[t.length-1];o.parent&&(e.functionContext=Object.assign({},o))}return e}))}(function(e){let t=1;const o=[];return e.map((e=>("LEFT_PAREN"===e.type?(o.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=o.pop()),e)))}(function(e){let t=0;return e.map((e=>{const o=e.value.toString().length,i=Object.assign({},e,{start:t,end:t+o,length:o});return t=i.end,i}))}(Vv(e))))}function qv(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function Zv(e){return Math.round(rb*e*100)/100}function jv(e){return Math.round(nb*e*100)/100}function Yv(e){if(e)return{style:e.style,color:{rgb:e.color}}}function Xv(e,t){let o={};e.style&&(o=t.styles[e.style]);const i=function(e,t){if(e.format)return t.formats[e.format];if(e.isFormula){const t=av(e.content||""),o=Tg.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),s={};if(e.border){const o=t.borders[e.border];s.left=Yv(o.left),s.right=Yv(o.right),s.bottom=Yv(o.bottom),s.top=Yv(o.top)}const r={font:{size:o?.fontSize||q,color:{rgb:o?.textColor?o.textColor:"000000"},family:2,name:"Arial"},fill:o?.fillColor?{fgColor:{rgb:o.fillColor}}:{reservedAttribute:"none"},numFmt:i?{format:i,id:0}:void 0,border:s||{},alignment:{horizontal:o.align,vertical:o.verticalAlign?Tb[o.verticalAlign]:void 0,wrapText:"wrap"===o.wrapping}};return r.font.strike=!!o?.strikethrough||void 0,r.font.underline=!!o?.underline||void 0,r.font.bold=!!o?.bold||void 0,r.font.italic=!!o?.italic||void 0,r}function Kv(e,t){const{id:o}=Jv(t.font,e.fonts),{id:i}=Jv(t.fill,e.fills),{id:s}=Jv(t.border,e.borders),r=function(e,t){if(!e)return 0;let o=Lb[e.format];if(!o){const{id:i}=Jv(e,t);o=i+db}return o}(t.numFmt,e.numFmts),n={fontId:o,fillId:i,borderId:s,numFmtId:r,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText}},{id:a}=Jv(n,e.styles);return a}function Qv(e,t,o){let i,s=e.find((e=>e.path===t));return s?(i=`rId${(s.rels.length+1).toString()}`,s.rels.push({...o,id:i})):(i="rId1",e.push({path:t,rels:[{...o,id:i}]})),i}function Jv(e,t){for(let[o,i]of Object.entries(t))if(JSON.stringify(i)===JSON.stringify(e))return{id:parseInt(o,10),list:t};let o=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===o&&(t.push(e),o=t.length-1),{id:o,list:t}}const eS=[];function tS(e){const t=eS.findIndex((t=>t===e));return-1===t?(eS.push(e),eS.length):t+1}const oS=[];function iS(e){const t=oS.findIndex((t=>t===e));return-1===t?(oS.push(e),oS.length):t+1}function sS(e){return Math.round(914400*e/96)}function rS(e,t,o){let i,s,r=e;if(({xc:r,sheetName:i}=Bo(e)),i){const e=o.sheets.findIndex((e=>e.name===i));if(e<0)throw new Error("Unable to find a sheet with the name "+i);s=e}else s=Number(t);const n=jo(r);return void 0===n.right&&(n.right=o.sheets[s].colNumber),void 0===n.bottom&&(n.bottom=o.sheets[s].rowNumber),(n.right-n.left+1)*(n.bottom-n.top+1)}function nS(e){return Math.round(96*e/914400)}function aS(e,t){let o=0;for(let i=0;i<e;i++){const e=t.cols.find((e=>i>=e.min&&i<=e.max));e?.width?o+=e.width:t.sheetFormat?.defaultColWidth?o+=t.sheetFormat.defaultColWidth:o+=ab}return o/nb}function lS(e,t){let o=0;for(let i=0;i<e;i++){const e=t.rows[i];e?.height?o+=e.height:t.sheetFormat?.defaultRowHeight?o+=t.sheetFormat.defaultRowHeight:o+=lb}return o/rb}function cS(e){let t=1;return e.figures.map((o=>function(e,t,o){const i=aS(e.anchors[0].col,o)+nS(e.anchors[0].colOffset),s=aS(e.anchors[1].col,o)+nS(e.anchors[1].colOffset),r=lS(e.anchors[0].row,o)+nS(e.anchors[0].rowOffset),n=lS(e.anchors[1].row,o)+nS(e.anchors[1].rowOffset),a=s-i,l=n-r,c=hS(e.data);return c?{id:t,x:i,y:r,width:a,height:l,tag:"chart",data:hS(e.data)}:void 0}(o,(t++).toString(),e))).filter(lt)}function hS(e){const t=void 0!==e.dataSets[0].label,o=e.labelRange?dS(e.labelRange,t):void 0;let i=e.dataSets.map((e=>dS(e.range,t)));return"pie"===e.type&&i.reverse(),{dataSets:i,dataSetsHaveTitle:t,labelRange:o,title:e.title||"",type:e.type,background:kb({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,labelsAsText:!1}}function dS(e,t){let{sheetName:o,xc:i}=Bo(e);o=o?Be(o)+"!":"";let s=jo(i);if(t&&void 0!==s.bottom&&void 0!==s.right){const e=s.bottom-s.top+1,t=s.right-s.left+1;1===e?s={...s,left:s.left-1}:1===t&&(s={...s,top:s.top-1})}return o+Ko(s)}const uS=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),gS=new RegExp(/SUBTOTAL\(([0-9]*),/g),pS=new RegExp(No.source,"ig");function mS(e,t){const o=function(e){const t={};for(let o of e.rows)for(let e of o.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(let i of e.rows.map((e=>e.cells)).flat())i?.formula&&(i.formula.content=void 0===i.formula.sharedIndex||i.formula.content?"="+i.formula.content:"="+bS(i.xc,o[i.formula.sharedIndex]),i.formula.content=fS(i.formula.content,t))}function fS(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(gS,((e,t)=>{const o=Fb[t];return o?o+"(":e}))).replace(uS,((e,o,i,s)=>{o=Number(o)-1,s=s.replace(/\$/g,"");const r=t.externalBooks[o].sheetNames.findIndex((e=>e===i));if(-1===r)return e;const n=t.externalBooks[o].datasets.find((e=>e.sheetId===r))?.data;if(!n)return e;const a=n&&n[s];return(Number(a)?a:`"${a}"`)||e}))}function bS(e,t){const o=Bt(t.refCellXc);let i,s=t.formula.slice();do{if(i=pS.exec(s),i){const t=Bt(i[0].replace("$","")),r=Bt(e),n={colFixed:i[0].startsWith("$"),rowFixed:i[0].includes("$",1)},a={col:r.col-o.col,row:r.row-o.row},l={col:n.colFixed?t.col:t.col+a.col,row:n.rowFixed?t.row:t.row+a.row};s=s.slice(0,i.index)+Ht(l.col,l.row,n)+s.slice(i.index+i[0].length)}}while(i);return s}function vS(e,t){return e.sheets.map((o=>{mS(o,e);const i=function(e){const t=[0,0];for(let o of e.rows)t[0]=Math.max(t[0],...o.cells.map((e=>Bt(e.xc).col))),t[1]=Math.max(t[1],o.index);return t[0]=Math.max(t[0],cb),t[1]=Math.max(t[1],hb),t}(o),s=o.sheetViews[0];return{id:o.sheetName,areGridLinesVisible:!s||s.showGridLines,name:o.sheetName,colNumber:i[0],rowNumber:i[1],cells:ES(o,e,i,t),merges:o.merges,cols:SS(o,i[0]),rows:CS(o,i[1]),conditionalFormats:Yb(o.cfs,e.dxfs,t),figures:cS(o),isVisible:o.isVisible,panes:s?{xSplit:s.pane.xSplit,ySplit:s.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function SS(e,t){const o={};for(let s=1;s<t+1;s++){const t=e.cols.find((e=>e.min<=s&&s<=e.max));let r;r=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:ab,o[s-1]={size:(i=r,i?Math.round(i/nb*100)/100:i),isHidden:t?.hidden}}var i;return o}function CS(e,t){const o={};for(let s=1;s<t+1;s++){const t=e.rows.find((e=>e.index===s));let r;r=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:lb,o[s-1]={size:(i=r,i?Math.round(i/rb*100)/100:i),isHidden:t?.hidden}}var i;return o}function ES(e,t,o,i){const s={},r=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const n=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(let o of e.rows)for(let e of o.cells)s[e.xc]={content:wS(e,n,r,i),style:e.styleIndex?e.styleIndex+1:void 0,border:e.styleIndex?t.styles[e.styleIndex].borderId+1:void 0,format:e.styleIndex?t.styles[e.styleIndex].numFmtId+1:void 0};for(let i of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=o[0];e++){const o=Ht(e-1,i.index-1);let r=s[o];r||(r={},s[o]=r),r.style=r.style?r.style:i.styleIndex+1,r.border=r.border?r.border:t.styles[i.styleIndex].borderId+1,r.format=r.format?r.format:t.styles[i.styleIndex].numFmtId+1}for(let i of e.cols.filter((e=>e.styleIndex)))for(let e=i.min;e<=Math.min(i.max,o[0]);e++)for(let r=1;r<=o[1];r++){const o=Ht(e-1,r-1);let n=s[o];n||(n={},s[o]=n),n.style=n.style?n.style:i.styleIndex+1,n.border=n.border?n.border:t.styles[i.styleIndex].borderId+1,n.format=n.format?n.format:t.styles[i.styleIndex].numFmtId+1}return s}function wS(e,t,o,i){let s;switch(e.type){case"sharedString":s=o[parseInt(e.value,10)];break;case"boolean":s=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":s=e.value}return s&&t[e.xc]&&(s=function(e,t,o){const i=e.display||t;e.relTarget||e.location||o.generateNotSupportedWarning(mb.BadlyFormattedHyperlink);const s=e.relTarget?e.relTarget:nt(Bo(e.location).sheetName);return ot(i,s)}(t[e.xc],s,i)),e.formula&&(s=e.formula.content),s}const xS={fillColor:"#000000",textColor:"#ffffff",bold:!0},yS={bold:!0},IS={style:"thin",color:"#000000FF"};function RS(e,t){for(const o of t.sheets)for(const t of o.tables){const i=e.sheets.find((e=>e.name===o.sheetName));i&&t.autoFilter&&(i.filterTables||(i.filterTables=[]),i.filterTables.push({range:t.ref}))}!function(e,t){const o=zb(e.styles),i=zb(e.borders);for(let s of t.sheets)for(let t of s.tables){const r=e.sheets.find((e=>e.name===s.sheetName));if(!r)continue;const n=Yo(t.ref);for(let e=0;e<t.headerRowCount;e++)TS(xS,{...n,bottom:n.top+e},r.cells,o);for(let e=0;e<t.totalsRowCount;e++)TS(yS,{...n,top:n.bottom-e},r.cells,o);t.style?.showFirstColumn&&TS(yS,{...n,right:n.left},r.cells,o),t.style?.showLastColumn&&TS(yS,{...n,left:n.right},r.cells,o);for(let e=n.left;e<=n.right;e++)for(let o=n.top;o<=n.bottom;o++){const s=Ht(e,o),a=r.cells[s],l={left:e===n.left||t.style?.showColumnStripes?IS:void 0,right:e===n.right?IS:void 0,top:o===n.top||t.style?.showRowStripes||o>n.bottom-t.totalsRowCount?IS:void 0,bottom:o===n.bottom?IS:void 0},c=a?.border?{...i[a.border],...l}:l;let h=i.findIndex((e=>mt(e,c)));-1===h&&(h=i.length,i.push(c)),a?a.border=h:r.cells[s]={border:h}}}e.styles=Vb(o),e.borders=Vb(i)}(e,t),function(e,t){for(let o of e){const e=t.find((e=>e.sheetName===o.name)).tables;for(let t of e){const e=t.name+"[";for(let i of ui(Yo(t.ref))){const s=Ht(i.col,i.row),r=o.cells[s];if(r&&r.content&&r.content.startsWith("=")){let o;for(;-1!==(o=r.content.indexOf(e));){let i=r.content.slice(o+e.length),n=i.indexOf("]");i.startsWith("[")&&(n=i.indexOf("]",n+1),n=i.indexOf("]",n+1)),i=i.slice(0,n);const a=AS(i,t,s);r.content=r.content.slice(0,o)+a+r.content.slice(e.length+o+n+1)}}}}}}(e.sheets,t.sheets)}function TS(e,t,o,i){for(let s=t.left;s<=t.right;s++)for(let r=t.top;r<=t.bottom;r++){const t=Ht(s,r),n=o[t],a=n?.style?{...i[n.style],...e}:e;let l=i.findIndex((e=>mt(e,a)));-1===l&&(l=i.length,i.push(a)),n?n.style=l:o[t]={style:l}}}function AS(e,t,o){const i=e.split(","),s=Yo(t.ref),r={...s};let n=!0;if(1===i.length){const e=t.cols.findIndex((e=>e.name===i[0]));r.left=r.right=e+s.left,t.headerRowCount&&(r.top+=t.headerRowCount),t.totalsRowCount&&(r.bottom-=1)}else{switch(i[0].slice(1,i[0].length-1)){case"#All":r.top=t.headerRowCount?s.top+t.headerRowCount:s.top,r.bottom=s.bottom;break;case"#Data":r.top=t.headerRowCount?s.top+t.headerRowCount:s.top,r.bottom=t.totalsRowCount?s.bottom+1:s.bottom;break;case"#This Row":r.top=r.bottom=Bt(o).row;break;case"#Headers":r.top=r.bottom=s.top,t.headerRowCount||(n=!1);break;case"#Totals":r.top=r.bottom=s.bottom,t.totalsRowCount||(n=!1)}const e=i[1].slice(1,i[1].length-1),a=t.cols.findIndex((t=>t.name===e));r.left=r.right=a+s.left}return n?r.top!==r.bottom?Ko(r):Ht(r.left,r.top):Q}function OS(e,t,o){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:o}}function MS(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;")}function NS(e){return new Yf(e.map((([e,t])=>`${e}="${MS(t)}"`)).join(" "))}function _S(e,t="text/xml"){const o=(new DOMParser).parseFromString(e.toString(),t),i=o.querySelector("parsererror");if(i){const t=i.innerHTML,o=parseInt(t.split(":")[0],10),s=e.toString().trim().split("\n"),r=s.slice(Math.max(o-3,0),Math.min(o+2,s.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${r}`)}return o}function FS(e,t){return LS`
1393
1416
  <Override ContentType="${t}" PartName="${e}" />
1394
- `}function DS(e){return new Yf(e.join("\n"))}function LS(e,...t){let o=[e[0]];for(let i=0;i<t.length;i++){const s=t[i]instanceof Yf?t[i]:MS(t[i]);o.push(s+e[i+1])}return new Yf(dt(o))}function PS(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function kS(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class US{value;constructor(e){this.value=e}asString(){return Bb(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class VS{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;areNamespaceIgnored;constructor(e,t,o){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=o,this.areNamespaceIgnored=null!==(new DOMParser).parseFromString("<t:test xmlns:t='a'/>","text/xml").querySelector("test"),this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfFiles(){return Object.values(this.xlsxFileStructure).flat().filter(lt)}mapOnElements(e,t){const o=[],i=this.currentFile;let s;if(e.children){const t=this.querySelector(e.parent,e.query)?.children;s=t||[]}else s=this.querySelectorAll(e.parent,e.query);if(s)for(let e of s)try{o.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=i,o}catchErrorOnElement(e,t){const o=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([o,e.message].join("\n"))}extractAttr(e,t,o){const i=e.attributes[t];i||this.handleMissingValue(e,`attribute "${t}"`,o);const s=i?.value?i.value:o?.default;return void 0===s?void 0:new US(s)}extractTextContent(e,t){if(void 0!==t?.default&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const o="preserve"===e?.attributes["xml:space"]?.value;let i=e?.textContent;return e&&null!==i||this.handleMissingValue(e,"text content",t),i&&(i=o?i:i.trim()),i?Bb(i):t?.default}extractChildAttr(e,t,o,i){let s;s="number"==typeof t?e.children[t]:this.querySelector(e,t),s||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,i);const r=s?this.extractAttr(s,o,i)?.asString():i?.default;return void 0!==r?new US(r):void 0}extractChildTextContent(e,t,o){if(void 0!==o?.default&&"string"!=typeof o.default)throw new Error("extractTextContent default value should be a string");let i=this.querySelector(e,t);return i||this.handleMissingValue(e,`child <${t}>`,o),i?this.extractTextContent(i,o):o?.default}handleMissingValue(e,t,o){if(o?.required){if(!o?.default)throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${o.default}`)}}extractColor(e,t,o){if(!e)return o?{rgb:o}:void 0;const i=this.extractAttr(e,"theme")?.asString();let s;if(void 0!==i){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");s=this.getThemeColor(i,t.clrScheme)}else s=this.extractAttr(e,"rgb")?.asString();return{rgb:s,auto:this.extractAttr(e,"auto")?.asBool(),indexed:this.extractAttr(e,"indexed")?.asNum(),tint:this.extractAttr(e,"tint")?.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");let t=e.target;t=t.replace("../",""),t=t.replace("./","");const o=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!o||!o.file)throw new Error("Cannot find target file");return o}querySelector(e,t){return t=this.areNamespaceIgnored?PS(t):kS(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?PS(t):kS(t),e.querySelectorAll(t)}getThemeColor(e,t){switch(e){case"0":return"FFFFFF";case"1":return"000000";case"2":return t[3].value;case"3":return t[2].value;default:return t[e].value}}}class zS extends VS{getTheme(){return{clrScheme:this.mapOnElements({query:"a:clrScheme",parent:this.rootFile.file.xml,children:!0},(e=>({name:e.tagName,value:this.extractChildAttr(e,0,"val",{required:!0,default:Kf}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:Kf}).asString()})))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"si"},(e=>"t"===e.children[0].tagName?this.extractTextContent(e)||"":this.mapOnElements({parent:e,query:"t"},(e=>this.extractTextContent(e)||"")).join("")))}}class BS extends VS{theme;constructor(e,t,o,i){super(e,t,o),this.theme=i}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>({sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:this.extractAttr(e,"pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)})));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>({sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:this.extractAttr(e,"xm:pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)})))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>{const o=this.extractAttr(e,"type",{required:!0}).asString();if("dataBar"===o)throw new Error("Databars conditional formats are not supported.");return{type:o,priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,"dxfId")?.asNum(),stopIfTrue:this.extractAttr(e,"stopIfTrue")?.asBool(),aboveAverage:this.extractAttr(e,"aboveAverage")?.asBool(),percent:this.extractAttr(e,"percent")?.asBool(),bottom:this.extractAttr(e,"bottom")?.asBool(),operator:this.extractAttr(e,"operator")?.asString(),text:this.extractAttr(e,"text")?.asString(),timePeriod:this.extractAttr(e,"timePeriod")?.asString(),rank:this.extractAttr(e,"rank")?.asNum(),stdDev:this.extractAttr(e,"stdDev")?.asNum(),equalAverage:this.extractAttr(e,"equalAverage")?.asBool()}}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const o=this.querySelector(e,"colorScale");if(o)return{colors:this.mapOnElements({parent:o,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(o)}}extractCfIconSet(e){const t=this.querySelector(e,"iconSet, x14:iconSet");if(t)return{iconSet:this.extractAttr(t,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(t,"showValue",{default:!0}).asBool(),percent:this.extractAttr(t,"percent",{default:!0}).asBool(),reverse:this.extractAttr(t,"reverse")?.asBool(),custom:this.extractAttr(t,"custom")?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),gte:this.extractAttr(e,"gte",{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,"val")?.asString():this.extractChildTextContent(e,"f, xm:f")})))}}class HS extends VS{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!_b[t])throw new Error(`Unsupported chart type ${t}`);const o=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),i=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:o,type:_b[t],dataSets:this.extractChartDatasets(this.querySelector(e,`c:${t}`)),labelRange:this.extractChildTextContent(e,"c:ser c:cat c:f"),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),verticalAxisPosition:"r"===this.extractChildAttr(e,"c:valAx > c:axPos","val",{default:"l"}).asString()?"right":"left",legendPosition:Nb[this.extractChildAttr(e,"c:legendPos","val",{default:"b"}).asString()],stacked:"stacked"===i,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c:tx c:f"),range:this.extractChildTextContent(e,"c:val c:f",{required:!0})})))}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");for(let e of t.children){const t=PS(e.tagName);if(Xf.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class $S extends VS{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==PS(e.tagName))throw new Error("Only twoCellAnchor are supported for xlsx drawings.");const t=this.querySelector(e,"c:chart");if(!t)throw new Error("Only chart figures are currently supported.");return{anchors:[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)],data:this.extractChart(t)}}))}extractFigureAnchor(e,t){const o=this.querySelector(t,e);if(!o)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(o,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(o,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(o,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(o,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),o=this.getTargetXmlFile(this.relationships[t]),i=new HS(o,this.xlsxFileStructure,this.warningManager).extractChart();if(!i)throw new Error("Unable to extract chart definition");return i}}class WS extends VS{getPivotTable(){return this.mapOnElements({query:":root",parent:this.rootFile.file.xml},(e=>({displayName:this.extractAttr(e,"name",{required:!0}).asString(),id:this.extractAttr(e,"name",{required:!0}).asString(),ref:this.extractChildAttr(e,"location","ref",{required:!0}).asString(),headerRowCount:this.extractChildAttr(e,"location","firstDataRow",{default:0}).asNum(),totalsRowCount:1,cols:[],style:{showFirstColumn:!0,showRowStripes:!0}})))[0]}}class GS extends VS{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>({displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:this.extractAttr(e,"name")?.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)})))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>({name:this.extractAttr(e,"name")?.asString(),showFirstColumn:this.extractAttr(e,"showFirstColumn")?.asBool(),showLastColumn:this.extractAttr(e,"showLastColumn")?.asBool(),showRowStripes:this.extractAttr(e,"showRowStripes")?.asBool(),showColumnStripes:this.extractAttr(e,"showColumnStripes")?.asBool()})))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class qS extends VS{theme;constructor(e,t,o,i){super(e,t,o),this.theme=i}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},(e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:[...this.extractTables(e),...this.extractPivotTables()],isVisible:"visible"===t.state}}))[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},(e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}}))}extractSheetName(){const e=Ub(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id;for(let e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,"sheet"))if(e.attributes["r:id"].value===t)return e.attributes.name.value;throw new Error("Missing sheet name")}getSheetWorkbookInfo(){const e=Ub(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,o=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!o)throw new Error("Cannot find corresponding workbook sheet");return o}extractConditionalFormats(){return new BS(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),o=this.getTargetXmlFile(this.relationships[t]);return new $S(o,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),o=this.getTargetXmlFile(this.relationships[t]);return new GS(o,this.xlsxFileStructure,this.warningManager).getTable()}))}extractPivotTables(){try{return Object.values(this.relationships).filter((e=>e.type.endsWith("pivotTable"))).map((e=>{const t=this.getTargetXmlFile(e);return new WS(t,this.xlsxFileStructure,this.warningManager).getPivotTable()}))}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:"mergeCell"},(e=>this.extractAttr(e,"ref",{required:!0}).asString()))}extractSheetFormat(e){const t=this.querySelector(e,"sheetFormatPr");if(t)return{defaultColWidth:this.extractAttr(t,"defaultColWidth",{default:ab.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:lb.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>({width:this.extractAttr(e,"width")?.asNum(),customWidth:this.extractAttr(e,"customWidth")?.asBool(),bestFit:this.extractAttr(e,"bestFit")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),min:this.extractAttr(e,"min",{required:!0})?.asNum(),max:this.extractAttr(e,"max",{required:!0})?.asNum(),styleIndex:this.extractAttr(e,"style")?.asNum()})))}extractRows(e){return this.mapOnElements({parent:e,query:"sheetData row"},(e=>({index:this.extractAttr(e,"r",{required:!0})?.asNum(),cells:this.extractCells(e),height:this.extractAttr(e,"ht")?.asNum(),customHeight:this.extractAttr(e,"customHeight")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),styleIndex:this.extractAttr(e,"s")?.asNum()})))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>({xc:this.extractAttr(e,"r",{required:!0})?.asString(),styleIndex:this.extractAttr(e,"s")?.asNum(),type:xb[this.extractAttr(e,"t",{default:"n"})?.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)})))}extractCellFormula(e){const t=this.querySelector(e,"f");if(t)return{content:this.extractTextContent(t),sharedIndex:this.extractAttr(t,"si")?.asNum(),ref:this.extractAttr(t,"ref")?.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{const t=this.extractAttr(e,"r:id")?.asString();return{xc:this.extractAttr(e,"ref",{required:!0})?.asString(),location:this.extractAttr(e,"location")?.asString(),display:this.extractAttr(e,"display")?.asString(),relTarget:t?this.relationships[t].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),o={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),i=this.extractTextContent(e,{required:!0});o[t]=i}const i=[];for(let e=0;e<Object.keys(o).length;e++)o[e]?i.push(o[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),i.push(""));return i}}class ZS extends VS{theme;constructor(e,t,o){super(e.styles,e,t),this.theme=o}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){const t=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),o=this.extractChildAttr(e,"sz","val",{default:q.toString()}).asNum(),i=this.extractColor(this.querySelector(e,"color"),this.theme),s=this.querySelector(e,"i")||void 0,r=s&&"0"!==s.attributes.val?.value,n=this.querySelector(e,"b")||void 0,a=n&&"0"!==n.attributes.val?.value,l=this.querySelector(e,"strike")||void 0,c=l&&"0"!==l.attributes.val?.value,h=this.querySelector(e,"u")||void 0;return{name:t,size:o,color:i,italic:r,bold:a,underline:h&&"none"!==h.attributes.val?.value,strike:c}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){const t=e.children[0];return"patternFill"===t.tagName?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(t,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(t,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){const t={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,"diagonalUp")?.asBool(),t.diagonalDown=this.extractAttr(e,"diagonalDown")?.asBool()),t}extractSingleBorder(e,t,o){const i=this.querySelector(e,t);if(i&&i.attributes.style)return{style:this.extractAttr(i,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(i.children[0],o,"000000")}}extractAlignment(e){return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"bottom"}).asString(),textRotation:this.extractAttr(e,"textRotation")?.asNum(),wrapText:this.extractAttr(e,"wrapText")?.asBool(),indent:this.extractAttr(e,"indent")?.asNum(),relativeIndent:this.extractAttr(e,"relativeIndent")?.asNum(),justifyLastLine:this.extractAttr(e,"justifyLastLine")?.asBool(),shrinkToFit:this.extractAttr(e,"shrinkToFit")?.asBool(),readingOrder:this.extractAttr(e,"readingOrder")?.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),o=this.querySelector(e,"fill"),i=this.querySelector(e,"border"),s=this.querySelector(e,"numFmt"),r=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:o?this.extractFill(o):void 0,numFmt:s?this.extractNumFormats(s):void 0,alignment:r?this.extractAlignment(r):void 0,border:i?this.extractBorder(i):void 0}}))}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}}))}}class jS extends VS{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),o={};for(let e of t)o[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:o}}))}}function YS(e,t){const o=function(e,t){const o=t[pb],i=o.querySelectorAll(`Override[ContentType="${e}"]`),s=[];for(let e of i){const t=e?.attributes.PartName.value;s.push(t.substring(1))}return s}(e,t);return function(e,t){const o=[];for(let i of e){const e=XS(i,t);o.push({file:{fileName:i,xml:t[i]},rels:e?{fileName:e,xml:t[e]}:void 0})}return o}(o,t)}function XS(e,t){if(e===pb)return"_rels/.rels";let o="";const i=e.split("/");for(let e=0;e<i.length-1;e++)o+=i[e]+"/";return o+="_rels/",o+=i[i.length-1]+".rels",t[o]||(o=void 0),o}class KS{warningManager;xmls;constructor(e){this.warningManager=new fb,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=_S(new Yf(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new zS(e.theme,e,this.warningManager).getTheme():void 0,o=e.sharedStrings?new zS(e.sharedStrings,e,this.warningManager).getSharedStrings():[],i=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((o=>new qS(o,e,this.warningManager,t).getSheet())),s=e.externalLinks.map((t=>new jS(t,e,this.warningManager).getExternalBook())),r=new ZS(e,this.warningManager,t);return{fonts:r.getFonts(),fills:r.getFills(),borders:r.getBorders(),dxfs:r.getDxfs(),numFmts:r.getNumFormats(),styles:r.getStyles(),sheets:i,sharedStrings:o,externalBooks:s}}buildXlsxFileStructure(){const e={sheets:YS(ob.sheet,this.xmls),workbook:YS(ob.workbook,this.xmls)[0],styles:YS(ob.styles,this.xmls)[0],sharedStrings:YS(ob.sharedStrings,this.xmls)[0],theme:YS(ob.themes,this.xmls)[0],charts:YS(ob.chart,this.xmls),figures:YS(ob.drawing,this.xmls),tables:YS(ob.table,this.xmls),pivots:YS(ob.pivot,this.xmls),externalLinks:YS(ob.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(r("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:vS(e,this.warningManager),styles:qb(e,this.warningManager),formats:jb(e,this.warningManager),borders:Wb(e,this.warningManager),entities:{},revisionId:J};return RS(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=ft(e.styles[t])})),t}}function QS(e){const t=Vv(e);let o=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&No.test(e.value)){const t=e.value.trim();return o.includes(t)||o.push(t),`${ce}${o.indexOf(t)}${ce}`}return e.value}))),dependencies:o}}const JS=13,eC="Sheet1";function tC(e,t){if(!e)return nC();if(e["[Content_Types].xml"]){const o=new KS(e);if(e=o.convertXlsx(),t)for(let e of o.warningManager.warnings.sort())console.warn(e)}return"version"in e&&e.version<JS&&(e=function(e){for(let t=oC.findIndex((t=>t.from===e.version));t<oC.length;t++)e=oC[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,o=new Zo;for(const i of e.sheets||[])for(const e of i.figures||[])t.has(e.id)&&(e.id+=o.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(nC(),e,{version:JS}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(rC(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(rC(eC,"Sheet1"));return e}(e),e}(e),e}const oC=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const o=t.cells[e];o.content&&o.content.startsWith("=")&&(o.formula=QS(o.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:o,...i}=t.figures[e].data,s=[];for(let e of o)if(e.labelCell){const t=Yo(e.dataRange),o=e.labelCell+":"+Ht(t.right,t.bottom);s.push(o)}else s.push(e.dataRange);i.dataSetsHaveTitle=Boolean(o[0].labelCell),i.dataSets=s,t.figures[e].data=i}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){const t=[],o=new RegExp(le,"g");for(let i of e.sheets||[]){if(!i.name)continue;const e=i.name,s=e.replace(o,"_");let r=1,n=s;for(;t.includes(n);)n=`${s}${r}`,r++;i.name=n,t.push(n);const a=t=>{if(void 0===t)return t;let o=t.replace(e,n),i=t;for(;i!==o;)i=o,o=i.replace(e,n);return i};for(let e in i.cells){const t=i.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(a))}for(let e of i.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(a),o=a(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:o}}for(let e of i.conditionalFormats||[]){e.ranges=e.ranges.map(a);for(const t of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===e.rule[t]?.type&&(e.rule[t].value=a(e.rule[t].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=w,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const o=t.cells[e];if(o.formula){let{text:e,dependencies:t}=o.formula;for(let[o,i]of Object.entries(t)){const t=`\\${ce}${o}\\${ce}`;e=e.replace(new RegExp(t,"g"),i)}o.content=e,delete o.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let o of e.sheets||[])for(let e in o.cells||[]){const i=o.cells[e];i.format&&(i.format=ht(i.format,t))}return e.formats=t,e}},{description:"Add isVisible to sheets",from:11,to:12,applyMigration(e){for(let t of e.sheets||[])t.isVisible=!0;return e}},{description:"Change Border description structure",from:12,to:13,applyMigration(e){for(const t in e.borders){const o=e.borders[t];for(const e in o)Array.isArray(o[e])&&(o[e]={style:o[e][0],color:o[e][1]})}return e}}];function iC(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const o=[],i=[],s=e=>{if("CREATE_SHEET"===e.type)o.push(e.sheetId);else if("sheetId"in e&&!o.includes(e.sheetId))return{...e,sheetId:eC};return e};for(const e of t)"REMOTE_REVISION"===e.type?i.push({...e,commands:e.commands.map(s)}):i.push(e);return i}(e,t),t=sC(t,"SORT_CELLS"),t=function(e,t){const o=[],i={};for(const t of e.sheets||[])t.figures?.forEach((e=>{"chart"===e.tag&&(i[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const o of e.commands){let e=o;switch(o.type){case"CREATE_CHART":i[o.id]=o.definition;break;case"UPDATE_CHART":if(!i[o.id]){console.log(`Fix chart definition: chart with id ${o.id} not found.`);continue}const t={...i[o.id],...o.definition};e={...o,definition:t},i[o.id]=t}t.push(e)}o.push({...e,commands:t})}else o.push(e);return o}(e,t=sC(t,"SET_DECIMAL")),t}function sC(e,t){const o=[];for(const i of e)"REMOTE_REVISION"===i.type?o.push({...i,commands:i.commands.filter((e=>e.type!==t))}):o.push(i);return o}function rC(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function nC(e="Sheet1"){return{version:JS,sheets:[rC(eC,e)],entities:{},styles:{},formats:{},borders:{},revisionId:J,uniqueFigureIds:!0}}function aC(e,t){return{...rC(e,t),charts:[],images:[]}}class lC{static getters=[];history;dispatch;constructor(e,t){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t}exportForExcel(e){}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const o of e){let e=o.call(this,t);Array.isArray(e)||(e=[e]);const i=e.filter((e=>0!==e));if(i.length)return i}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class cC extends lC{getters;range;uuidGenerator;constructor({getters:e,stateObserver:t,range:o,dispatch:i,uuidGenerator:s}){super(t,i),this.range=o,o.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=s}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}}function hC(e){return""===e?NaN:Number(e)}class dC{id;zone;filters;constructor(e){this.filters=[],this.zone=e;const t=new Zo;this.id=t.uuidv4();for(const o of je(e.left,e.right+1)){const e={...this.zone,left:o,right:o};this.filters.push(new uC(t.uuidv4(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){return this.filters.find((t=>t.col===e))?.id}clone(){return new dC(this.zone)}}class uC{id;zoneWithHeaders;constructor(e,t){if(t.left!==t.right)throw new Error("Can only define a filter on a single column");this.id=e,this.zoneWithHeaders=t}get col(){return this.zoneWithHeaders.left}get filteredZone(){const e=this.zoneWithHeaders;if(e.bottom!==e.top)return{...e,top:e.top+1}}}function gC(e){return Object.entries(e).map((([e,t])=>t?pC(parseInt(e,10),t):void 0)).filter(lt).map((e=>Ht(e.left,e.top)+":"+Ht(e.right,e.bottom)))}function pC(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}class mC{getters;providers=[];constructor(e){this.getters=e}static getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?0:26:0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";const s=[...e.elements];s.sort(((e,t)=>t-e));const r=Ye(s);this.executeOnAllRanges((s=>{if(s.sheetId!==e.sheetId)return{changeType:"NONE"};let n=s,a="NONE";for(let e of r){const r=Math.min(...e),l=Math.max(...e);if(s.zone[t]<=r&&r<=s.zone[o]){const e=Math.min(s.zone[o],l)-r+1;a="RESIZE",n=this.createAdaptedRange(n,i,a,-e)}else if(s.zone[t]>=r&&s.zone[o]<=l)a="REMOVE",n=s.clone({...this.getInvalidRange()});else if(s.zone[t]<=l&&s.zone[o]>=l){const e=l-s.zone[t]+1;a="RESIZE",n=this.createAdaptedRange(n,i,a,-e),n=this.createAdaptedRange(n,i,"MOVE",-(s.zone[t]-r))}else r<s.zone[t]&&(a="MOVE",n=this.createAdaptedRange(n,i,a,-(l-r+1)))}return"NONE"!==a?{changeType:a,range:n}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((s=>{if(s.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(s.zone[t]<=e.base&&e.base<s.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(s,i,"RESIZE",e.quantity)};if(e.base<s.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(s,i,"MOVE",e.quantity)}}else{if(s.zone[t]<e.base&&e.base<=s.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(s,i,"RESIZE",e.quantity)};if(e.base<=s.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(s,i,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const o=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:o})}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const o=void 0,i=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:i,invalidSheetName:o})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId||!ai(o.zone,t))return{changeType:"NONE"};const i=e.targetSheetId,s=e.col-t.left,r=e.row-t.top,n=this.createAdaptedRange(o,"both","MOVE",[s,r]),a=e.sheetId!==i||n.prefixSheet;return{changeType:"MOVE",range:n.clone({sheetId:i,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||Xo(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,o,i){const s=gi(e.unboundedZone,t,o,i);return e.clone({zone:s})}executeOnAllRanges(e,t){const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,o,i){const s=e.map((e=>Ho.fromRange(e,this.getters)));return s.map((e=>{if(!Xo(e.zone))return e;const s=e.prefixSheet?e.sheetId:i,r={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:o),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:o)};return e.clone({sheetId:s,zone:r}).orderZone()}))}getRangeFromSheetXC(e,t){if(!Po.test(t))return new Ho({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let o,i=t,s=!1;t.includes("!")&&(({xc:i,sheetName:o}=Bo(t)),o&&(s=!0));const r=jo(i),n=Ho.getRangeParts(i,r),a=o&&!this.getters.getSheetIdByName(o)?o:void 0,l=this.getters.getSheetIdByName(o)||e;return new Ho({prefixSheet:s,zone:r,sheetId:l,invalidSheetName:a,parts:n},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const o=Ho.fromRange(e,this.getters),i=this.getters.expandZone(o.sheetId,o.zone),s=o.clone({zone:{...i,bottom:o.isFullCol?void 0:i.bottom,right:o.isFullRow?void 0:i.right}});return this.getRangeString(s,t)}getRangeString(e,t){if(!e)return Q;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return Q;if(e.zone.left<0||e.zone.top<0)return Q;const o=Ho.fromRange(e,this.getters);let i=o.sheetId!==t||o.invalidSheetName||o.prefixSheet,s="";if(i&&(s=o.invalidSheetName?o.invalidSheetName:Be(this.getters.getSheetName(o.sheetId))),i&&!s)return Q;let r=this.getRangePartString(o,0);return o.parts&&2===o.parts.length&&(o.zone.top!==o.zone.bottom||o.zone.left!==o.zone.right||o.parts[0].rowFixed||o.parts[0].colFixed||o.parts[1].rowFixed||o.parts[1].colFixed)&&(r+=":",r+=this.getRangePartString(o,1)),`${i?s+"!":""}${r}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t}}getRangeFromRangeData(e){const t={prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]};return new Ho(t,this.getters.getSheetSize)}getRangePartString(e,t){const o=e.parts&&e.parts[t].colFixed?"$":"",i=Pt(0===t?e.zone.left:e.zone.right),s=e.parts&&e.parts[t].rowFixed?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let n="";return n=e.isFullCol?0===t&&e.unboundedZone.hasHeader?o+i+s+r:o+i:e.isFullRow?0===t&&e.unboundedZone.hasHeader?o+i+s+r:s+r:o+i+s+r,n}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:Q}}}class fC extends lC{static layers=[];getters;ui;selection;constructor({getters:e,stateObserver:t,dispatch:o,uiActions:i,selection:s}){super(t,o),this.getters=e,this.ui=i,this.selection=s}drawGrid(e,t){}}const bC=Tg.mapping;class vC{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;offsetScrollbarX;offsetScrollbarY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,o,i,s,r){this.getters=e,this.sheetId=t,this.boundaries=o,this.viewportWidth=i.width,this.viewportHeight=i.height,this.offsetScrollbarX=r.x,this.offsetScrollbarY=r.y,this.canScrollVertically=s.canScrollVertically,this.canScrollHorizontally=s.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:o,size:i}=this.getters.getColDimensions(this.sheetId,e),{end:s,size:r}=this.getters.getRowDimensions(this.sheetId,t),n=this.searchHeaderIndex("COL",o-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,n),l=this.searchHeaderIndex("ROW",s-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=o-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(D,Math.min(a,this.viewportWidth-i)),h=Math.max(h,this.viewportWidth));let d=s-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(L+5,Math.min(c,this.viewportHeight-r)),d=Math.max(d,this.viewportHeight)),{width:h,height:d}}getColIndex(e,t=!1){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX,this.left,t)}getRowIndex(e,t=!1){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY,this.top,t)}adjustPosition(e){const t=this.sheetId;e||(e=this.getters.getSheetPosition(t));const o=this.getters.getMainCellPosition({sheetId:t,...e}),{col:i,row:s}=this.getters.getNextVisibleCellPosition(o);ni(i,this.boundaries.top,this.boundaries)&&this.adjustPositionX(i),ni(this.boundaries.left,s,this.boundaries)&&this.adjustPositionY(s)}adjustPositionX(e){const t=this.sheetId,{end:o}=this.getters.getColDimensions(t,e),i=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<o)for(let e=this.left;this.offsetX+this.offsetCorrectionX+this.viewportWidth<o&&!(e>i);e++)this.getters.isColHidden(t,e)||(this.offsetX=this.getters.getColDimensions(t,e).end-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX());else if(this.left>e)for(let o=this.left;o>=e&&!(o<0);o--)this.getters.isColHidden(t,o)||(this.offsetX=this.getters.getColDimensions(t,o).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX())}adjustPositionY(e){const t=this.sheetId,{end:o}=this.getters.getRowDimensions(t,e),i=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<o)for(let e=this.top;this.offsetY+this.viewportHeight+this.offsetCorrectionY<o&&!(e>i);e++)this.getters.isRowHidden(t,e)||(this.offsetY=this.getters.getRowDimensions(t,e).end-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY());else if(this.top>e)for(let o=this.top;o>=e&&!(o<0);o--)this.getters.isRowHidden(t,o)||(this.offsetY=this.getters.getRowDimensions(t,o).start-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY())}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getRect(e){const t=ii(e,this.zone);if(t){return{x:this.getters.getColRowOffset("COL",this.zone.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset("ROW",this.zone.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1),this.viewportHeight)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,o=0,i=!1){let s=0;const r=this.sheetId,n=this.getters.getNumberHeaders(r,e);for(let a=o;a<=n-1;a++){const o=i||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(r,e,a)&&!o&&(s+="COL"===e?this.getters.getColSize(r,a):this.getters.getRowSize(r,a),s>t))return a}return-1}get zone(){return{left:this.left,right:this.right,top:this.top,bottom:this.bottom}}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.left=this.getColIndex(this.offsetScrollbarX,!0),this.right=this.getColIndex(this.offsetScrollbarX+this.viewportWidth,!0),-1===this.right&&(this.right=this.boundaries.right),this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.top=this.getRowIndex(this.offsetScrollbarY,!0),this.bottom=this.getRowIndex(this.offsetScrollbarY+this.viewportWidth,!0),-1===this.bottom&&(this.bottom=this.boundaries.bottom),this.adjustViewportZoneY()}adjustViewportZoneX(){const e=this.sheetId;this.left=this.searchHeaderIndex("COL",this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",this.viewportWidth,this.left)),-1===this.right&&(this.right=this.getters.getNumberCols(e)-1),this.offsetX=this.getters.getColDimensions(e,this.left).start-this.getters.getColDimensions(e,this.boundaries.left).start}adjustViewportZoneY(){const e=this.sheetId;this.top=this.searchHeaderIndex("ROW",this.offsetScrollbarY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",this.viewportHeight,this.top)),-1===this.bottom&&(this.bottom=this.getters.getNumberRows(e)-1),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start}}class SC{cells;getters;index=0;direction;constructor(e,t,o){this.cells=e,this.getters=t,this.direction=o}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:o,tooltip:i}=Ls.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:o,tooltip:i,origin:{col:e.data.col,row:e.data.row}}}}class CC{subscriptions={};on(e,t,o){if(!o)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:o})}trigger(e,t){const o=this.subscriptions[e]||[];for(let e=0,i=o.length;e<i;e++){const i=o[e];i.callback.call(i.owner,t)}}off(e,t){const o=this.subscriptions[e];o&&(this.subscriptions[e]=o.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function EC(e,t){return{...e,definition:Hn(e.definition,t)}}function wC(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let o=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)o>t&&o--}if("ADD_COLUMNS_ROWS"===t.type){o=o>("before"===t.position?t.base-1:t.base)?o+t.quantity:o}return o>0?{...e,quantity:o}:void 0}Em.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],EC),Em.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],EC),Em.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),Em.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),Em.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){if(e.name===t.name)return{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),Em.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const o=[];for(const i of e.target)for(const e of t.target)ri(i,e)||o.push({...i});if(o.length)return{...e,target:o};return})),Em.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],wC),Em.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],wC),Em.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const o of e.target)for(const e of t.target)if(ri(e,o))return;return e}));const xC=[{match:function(e){return"sheetId"in e},fn:RC},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=RC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const i=[];for(const o of e.target){const e=Tr(o,t);e&&i.push(e)}if(!i.length)return"IGNORE_COMMAND";return{...e,target:i}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const o=RC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const o="COL"===t.dimension?"col":"row";let i=e[o];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(i))return"IGNORE_COMMAND";for(let t of e)i>=t&&i--}"ADD_COLUMNS_ROWS"===t.type&&(i>t.base||i===t.base&&"before"===t.position)&&(i+=t.quantity);return{...e,[o]:i}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const o of t.target){if(!(e.col===o.left&&e.row===o.top)&&ni(e.col,e.row,o))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e},fn:function(e,t){const o=RC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const o="ADD_COLUMNS_ROWS"===e.type,i=o?"base":"elements";let s=o?[e[i]]:e[i];if("REMOVE_COLUMNS_ROWS"===t.type&&(s=s.map((e=>{if(t.elements.includes(e))return;const o=t.elements.sort(((e,t)=>t-e));for(let t of o)e>t&&e--;return e})).filter(lt)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;s=s.map((o=>o>e?o+t.quantity:o))}if(s.length){let t=s;return o&&(t=s[0]),{...e,[i]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const o=[],i="DELETE_SHEET"===t.type&&t.sheetId;for(const s of e.ranges)if(s._sheetId!==t.sheetId)o.push({...s,_zone:s._zone});else{const e=Tr(s._zone,t);e&&i!==s._sheetId&&o.push({...s,_zone:e})}if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function yC(e,t){const o=Em.getTransformation(e.type,t.type);return o?o(e,t):function(e,t){for(const{match:o,fn:i}of xC)if(o(e)){const o=i(e,t);if("SKIP_TRANSFORMATION"===o)continue;if("IGNORE_COMMAND"===o)return;e=o}return e}(e,t)}function IC(e,t){let o=[...e];for(const e of t)o=o.map((t=>yC(t,e))).filter(lt);return o}function RC(e,t){const o="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===o?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class TC{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,o,i,s,r){this.rootCommand=i,this.timestamp=r,this.id=e,this.clientId=t,this._commands=[...o],this._changes=s?[...s]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class AC extends Error{}class OC extends CC{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;uuidGenerator=new Zo;constructor(e,t,o=J){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=o,this.debouncedMove=function(e,t,o){let i;return function(){const s=this,r=arguments,n=o&&!i;clearTimeout(i),i=setTimeout((function(){i=null,o||e.apply(s,r)}),t),n&&e.apply(s,r)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,o){if(!t.length||!o.length||!this.canApplyOptimisticUpdate())return;const i=new TC(this.uuidGenerator.uuidv4(),this.clientId,t,e,o,Date.now());this.revisions.append(i.id,i),this.trigger("new-local-state-update",{id:i.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:i.id,clientId:i.clientId,commands:i.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})}move(e){this.debouncedMove(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))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new AC("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(lt))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(e){const t=this.revisions.getRevertedExecution();for(const o of t){if("SNAPSHOT"===o.rootCommand)return;if(o.rootCommand&&"REMOTE"!==o.rootCommand&&(!e.includes(o.rootCommand?.type)&&o.commands.length))return o}}_move(e){if(!this.clients[this.clientId])return;const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const o=t?"CLIENT_MOVED":"CLIENT_JOINED",i=this.getClient();this.clients[this.clientId]={...i,position:e},this.transportService.sendMessage({type:o,version:1,client:{...i,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{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":const{clientId:t,commands:o,timestamp:i}=e,s=new TC(e.nextRevisionId,t,o,"REMOTE",void 0,i);if(s.clientId!==this.clientId){this.revisions.insert(s.id,s,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:IC(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new TC(e.nextRevisionId,"server",[],"SNAPSHOT",void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot");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;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({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.waitingAck=!0,this.sendPendingMessage())}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){const t=this.revisions.get(e.nextRevisionId);if(0===t.commands.length){this.revisions.drop(t.id);const e=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.nextRevisionId));return this.trigger("pending-revisions-dropped",{revisionIds:e}),this.waitingAck=!1,this.waitingUndoRedoAck=!1,void(this.pendingMessages=[])}e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":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.sendPendingMessage()}}isAlreadyProcessed(e){if("CLIENT_MOVED"===e.type&&e.client.id===this.clientId)return!0;switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":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})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const MC=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];var NC;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(NC||(NC={}));class _C extends fC{inputHasSingleRange;static layers=[1];static getters=[];ranges=[];focusedRangeIndex=null;activeSheet;willAddNewRange=!1;constructor(e,t,o){if(o&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e),this.inputHasSingleRange=o,this.insertNewRange(0,t),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}allowDispatch(e){switch(e.type){case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange&&1===this.ranges.length)return 30;break;case"CHANGE_RANGE":if(this.inputHasSingleRange&&e.value.split(",").length>1)return 30}return 0}handleEvent(e){const t=Ko(e.anchor.zone),o=this.activeSheet,i=this.getters.getActiveSheetId(),s=this.getters.getSheetName(i);this.add([i===o?t:`${Be(s)}!${t}`])}handle(e){switch(e.type){case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(this.getIndex(e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.rangeId);if(null!==t&&this.focusedRangeIndex!==t&&this.focus(t),null!==t){const o=e.value.replace(/^,+/,"").split(",").map((e=>e.trim()));this.setRange(t,o)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(this.ranges.length,[""]),this.focusLast();break;case"REMOVE_RANGE":const t=this.getIndex(e.rangeId);null!==t&&this.removeRange(t);break;case"STOP_SELECTION_INPUT":this.willAddNewRange=!1;break;case"PREPARE_SELECTION_INPUT_EXPANSION":{const e=this.focusedRangeIndex;null===e||this.inputHasSingleRange||(this.willAddNewRange=""!==this.ranges[e].xc.trim());break}case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),i=this.getters.expandZone(e.sheetIdTo,fi({col:t,row:o}));this.selection.resetAnchor(this,{cell:{col:t,row:o},zone:i})}}}getSelectionInputValue(){return this.cleanInputs(this.ranges.map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.ranges.map((e=>this.inputToHighlights(e))).flat()}focus(e){this.focusedRangeIndex=e}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null}add(e){null!==this.focusedRangeIndex&&0!==e.length&&(this.willAddNewRange?(this.insertNewRange(this.ranges.length,e),this.focusLast(),this.willAddNewRange=!1):this.setRange(this.focusedRangeIndex,e))}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){const o=Math.max(0,...this.ranges.map((e=>Number(e.id))));this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:o+t+1,color:It[(o+t)%It.length]}))))}setRange(e,t){const[,...o]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,o),o.length&&this.focus(e+o.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const o=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return o.map((e=>{const{sheetName:o}=Bo(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:o&&this.getters.getSheetIdByName(o)||this.activeSheet,color:t}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:o}=Bo(t),i=this.getters.getSheetIdByName(o),s=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(i===s||void 0===i&&s===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}const FC=[DC,function(e,t){return"target"in t&&Array.isArray(t.target)?{...Ve(t),target:e.getSelectedZones()}:t},function(e,t){if(!("row"in t)||!("col"in t))return t;const{col:o,row:i}=e.getActivePosition();return{...Ve(t),col:o,row:i}}];function DC(e,t){return"sheetId"in t?{...Ve(t),sheetId:e.getActiveSheetId()}:t}const LC=new Zo;function PC(e,t){const o=e.getSelectedZone();return{...DC(e,t),elements:"COL"===t.dimension?je(o.left,o.right+1):je(o.top,o.bottom+1)}}function kC(e,t){const o=e.getSelectedZone();return{...Ve(t),zone:o}}function UC(e,t){const o=Ve(t),i=e.getSelectedZone(),{top:s,bottom:r,left:n,right:a}=i;return"cols"in o?o.cols=je(n,a+1):"rows"in o&&(o.rows=je(s,r+1)),o}const VC=new _i;VC.add("UPDATE_CELL",BC),VC.add("CLEAR_CELL",BC),VC.add("DELETE_CONTENT",BC),VC.add("ADD_MERGE",BC),VC.add("REMOVE_MERGE",BC),VC.add("SET_FORMATTING",BC),VC.add("CLEAR_FORMATTING",BC),VC.add("SET_BORDER",BC),VC.add("CREATE_FILTER_TABLE",BC),VC.add("REMOVE_FILTER_TABLE",BC),VC.add("HIDE_SHEET",BC),VC.add("ADD_COLUMNS_ROWS",(function(e,t){const o=e.getActivePosition();return{...DC(e,t),base:"COL"===t.dimension?o.col:o.row}})),VC.add("REMOVE_COLUMNS_ROWS",PC),VC.add("HIDE_COLUMNS_ROWS",PC),VC.add("RESIZE_COLUMNS_ROWS",PC),VC.add("CREATE_SHEET",(function(e,t){const o=Ve(t);o.sheetId=LC.uuidv4();const i=t.name||e.getSheet(e.getActiveSheetId()).name,s=i.match(/(.+?)\d*$/)?.[1]||i;return o.name=e.getNextSheetName(s),o})),VC.add("CREATE_FIGURE",(function(e,t){const o=DC(e,t);return o.figure.id=LC.uuidv4(),o})),VC.add("CREATE_CHART",(function(e,t){return{...DC(e,t),id:LC.uuidv4()}})),VC.add("CREATE_IMAGE",(function(e,t){return{...DC(e,t),figureId:LC.uuidv4()}}));const zC=new _i;function BC(e,t){let o=Ve(t);for(const t of FC)o=t(e,o);return o}function HC(e,t){if(!t)return;if(!VC.contains(t.type))return;return VC.get(t.type)(e,t)}function $C(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return Es(e.rootCommand)?HC(t,e.rootCommand):function(e,t,o){if(!zC.contains(t.type))return;return zC.get(t.type)(e,t,o)}(t,e.rootCommand,e.commands)}zC.add("STOP_EDITION",(function(e,t,o){return o.map((t=>HC(e,t))).filter(lt)})),zC.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:Ve(t.pasteOption),target:e.getSelectedZones()}})),zC.add("INSERT_CELL",kC),zC.add("DELETE_CELL",kC),zC.add("AUTORESIZE_COLUMNS",UC),zC.add("AUTORESIZE_ROWS",UC),zC.add("SORT_CELLS",(function(e,t){const o=e.getSelectedZone();return{...DC(e,t),col:o.left,row:o.top,zone:o}})),zC.add("SUM_SELECTION",BC),zC.add("SET_DECIMAL",BC);class WC{getters;dispatch;selection;operation;sheetId;constructor(e,t,o,i){this.getters=t,this.dispatch=o,this.selection=i,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,o,i){const s=this.getters.getActiveSheetId(),r=t+i-this.getters.getNumberRows(s);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(s)-1,sheetId:s,quantity:r,position:"after"});const n=e+o-this.getters.getNumberCols(s);n>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(s)-1,sheetId:s,quantity:n,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class GC extends WC{cells;copiedTables;zones;constructor(e,t,o,i,s){if(super(t,o,i,s),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const r=new Set(e.map((e=>e.left))),n=new Set(e.map((e=>e.right))),a=new Set(e.map((e=>e.top))),l=new Set(e.map((e=>e.bottom))),c=1===a.size&&1===l.size||1===r.size&&1===n.size?function(e){return e.reduce(((e,t)=>{const o=e.length;for(let i=0;i<o;i++)if(ri(e[i],t))return e[i]=oi(e[i],t),e;return e[o]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>ui(e))).flat(),d=[...new Set(h.map((e=>e.col)))].sort(((e,t)=>e-t)),u=[...new Set(h.map((e=>e.row)))].sort(((e,t)=>e-t)),g=[],p=o.getActiveSheetId();for(let e of u){let t=[];for(let i of d){const s={col:i,row:e,sheetId:p};t.push({cell:o.getCell(s),style:o.getCellComputedStyle(s),evaluatedCell:o.getEvaluatedCell(s),border:o.getCellBorder(s)||void 0,position:s})}g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const o of je(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues({sheetId:p,col:o,row:e.zone.top}));m.push({filtersValues:t,zone:e.zone})}this.cells=g,this.zones=c,this.copiedTables=m}isCutAllowed(e){return 1!==e.length?19:0}isPasteAllowed(e,t){const o=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==t?.pasteOption)return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const i=this.cells.length,s=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(o,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(o,e[0])||i*s!=1))return 2;const{xSplit:r,ySplit:n}=this.getters.getPaneDivisions(o);for(const t of this.getPasteZones(e))if(t.left<r&&t.right>=r||t.top<n&&t.bottom>=n)return 75;return 0}paste(e,t){"COPY"===this.operation?this.pasteFromCopy(e,t):this.pasteFromCut(e,t);const o=this.cells.length,i=this.cells[0].length,s="CUT"===this.operation;t?.selectTarget&&this.selectPastedZone(i,o,s,e)}pasteFromCopy(e,t){if(1===e.length){const o=this.cells.length,i=this.cells[0].length,s=this.pastedZones(e,i,o);for(const e of s)this.pasteZone(e.left,e.top,t)}else for(const o of e)for(let e=o.left;e<=o.right;e++)for(let i=o.top;i<=o.bottom;i++)this.pasteZone(e,i,t);void 0===t?.pasteOption&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const o=e[0];this.pasteZone(o.left,o.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:o.left,row:o.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.getters.getActiveSheetId(),target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,o){const i=e[0],s=Math.max(1,Math.floor((i.right+1-i.left)/t)),r=Math.max(1,Math.floor((i.bottom+1-i.top)/o)),n=[];for(let e=0;e<s;e++)for(let s=0;s<r;s++){const r=i.top+s*o,a=i.left+e*t;n.push({left:a,top:r,bottom:r+o-1,right:a+t-1})}return n}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const o=[],i=t.length,s=t[0].length,r=e[e.length-1],n=r.left,a=r.top,l=Math.max(1,Math.floor((r.right+1-n)/s)),c=Math.max(1,Math.floor((r.bottom+1-a)/i));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)o.push({left:n,top:a,right:n-1+e*s,bottom:a-1+t*i});return o}selectPastedZone(e,t,o,i){const s=i[0],r=s.left,n=s.top;if(t>1||e>1||o){const s=this.pastedZones(i,e,t),a=o?s[0]:oi(...s);this.selection.selectZone({cell:{col:r,row:n},zone:a})}}clearClippedZones(){for(const e of this.cells)for(const t of e)t.cell&&this.dispatch("CLEAR_CELL",t.position);this.dispatch("CLEAR_FORMATTING",{sheetId:this.sheetId,target:this.zones})}pasteZone(e,t,o){const i=this.cells.length,s=this.cells[0].length,r="onlyValue"!==o?.pasteOption&&o?.shouldPasteCF,n=this.getters.getActiveSheetId();this.addMissingDimensions(s,i,e,t);for(let a=0;a<i;a++){const i=this.cells[a];for(let l=0;l<s;l++){const s=i[l],c={col:e+l,row:t+a,sheetId:n};"CUT"!==this.operation&&this.pasteMergeIfExist(s.position,c),this.pasteCell(s,c,this.operation,o),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:s.position,target:c,operation:this.operation})}}}pasteCell(e,t,o,i){const{sheetId:s,col:r,row:n}=t,a=this.getters.getEvaluatedCell(t);if("onlyValue"!==i?.pasteOption){const o=this.getters.getCellBorder(t),i=e.border,a={top:o?.top||i?.top,bottom:o?.bottom||i?.bottom,left:o?.left||i?.left,right:o?.right||i?.right};this.dispatch("SET_BORDER",{sheetId:s,col:r,row:n,border:a})}if(e.cell){if("onlyFormat"===i?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.evaluatedCell.format});if("onlyValue"===i?.pasteOption){const o=uo(e.evaluatedCell.value);return void this.dispatch("UPDATE_CELL",{...t,content:o})}let a=e.cell.content;if(e.cell.isFormula&&"COPY"===o){const t=r-e.position.col,i=n-e.position.row;a=this.getUpdatedContent(s,e.cell,t,i,o)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===i?.pasteOption?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===i?.pasteOption?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,o,i,s){const r=this.getters.createAdaptedRanges(t.dependencies,o,i,e);return this.getters.buildFormulaContent(e,t,r)}pasteMergeIfExist(e,t){let{sheetId:o,col:i,row:s}=e;const{col:r,row:n}=this.getters.getMainCellPosition(e);if(r===i&&n===s){const r=this.getters.getMerge(e);if(!r)return;({sheetId:o,col:i,row:s}=t),this.dispatch("ADD_MERGE",{sheetId:o,force:!0,target:[{left:i,top:s,right:i+r.right-r.left,bottom:s+r.bottom-r.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),o=e[0],i=this.zones[0],s=[o.left-i.left,o.top-i.top];for(const e of this.copiedTables){const o=gi(e.zone,"both","MOVE",s);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[o]});for(const i of je(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:o.left+i,row:o.top,values:e.filtersValues[i]})}}getClipboardContent(){return{[fs.PlainText]:this.getPlainTextContent(),[fs.Html]:this.getHTMLContent()}}getPlainTextContent(){return this.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.position,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}getHTMLContent(){if(1==this.cells.length&&1==this.cells[0].length)return this.getters.getCellText(this.cells[0][0].position);let e='<table border="1" style="border-collapse:collapse">';for(const t of this.cells){e+="<tr>";for(const o of t){e+=`<td style="${Ti(Ii(o.style))}">`+MS(this.getters.getCellText(o.position))+"</td>"}e+="</tr>"}return e+="</table>",e}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let o of this.zones){if("COL"===t&&e<=o.right)return!0;if("ROW"===t&&e<=o.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:o}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*o;for(const e of this.zones){const{x:o,y:i,width:s,height:r}=this.getters.getVisibleRect(e);s>0&&r>0&&t.strokeRect(o,i,s,r)}}}}class qC{operation;getters;dispatch;sheetId;copiedFigure;copiedFigureContent;constructor(e,t,o){this.operation=e,this.getters=t,this.dispatch=o,this.sheetId=t.getActiveSheetId();const i=t.getSelectedFigureId();if(!i)throw new Error("No figure selected");const s=t.getFigure(this.sheetId,i);if(!s)throw new Error(`No figure for the given id: ${i}`);switch(this.copiedFigure={...s},s.tag){case"chart":this.copiedFigureContent=new ZC(o,t,this.sheetId,i);break;case"image":this.copiedFigureContent=new jC(o,t,this.sheetId,i);break;default:throw new Error(`Unknow tag '${s.tag}' for the given figure id: ${i}`)}}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?73:void 0!==t?.pasteOption?22:0}paste(e){const t=this.getters.getActiveSheetId(),{width:o,height:i}=this.copiedFigure,s=this.getters.getNumberCols(t),r=this.getters.getNumberRows(t),n=this.getters.getColDimensions(t,e[0].left).start,a=this.getters.getRowDimensions(t,e[0].top).start,l=this.getters.getColDimensions(t,s-1).end,c=this.getters.getRowDimensions(t,r-1).end,h={x:l<o?0:Math.min(n,l-o),y:c<i?0:Math.min(a,c-i)},d=(new Zo).uuidv4();this.copiedFigureContent.paste(t,d,h,{height:i,width:o}),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedFigureContent.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:d})}getClipboardContent(){return{[fs.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class ZC{dispatch;sheetId;copiedChart;constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const s=t.getChart(i);if(!s)throw new Error(`No chart for the given id: ${i}`);this.copiedChart=s.copyInSheetId(o)}paste(e,t,o,i){const s=this.copiedChart.copyInSheetId(e);this.dispatch("CREATE_CHART",{id:t,sheetId:e,position:o,size:i,definition:s.getDefinition()})}}class jC{dispatch;sheetId;copiedImage;constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const s=t.getImage(i);this.copiedImage=Ve(s)}paste(e,t,o,i){const s=Ve(this.copiedImage);this.dispatch("CREATE_IMAGE",{figureId:t,sheetId:e,position:o,size:i,definition:s})}}class YC extends WC{values;constructor(e,t,o,i){super("COPY",t,o,i),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const o=this.getters.getActiveSheetId(),i=this.getPasteZone(e);return this.getters.doesIntersectMerge(o,i)?2:0}paste(e){const t=this.values,o=this.getPasteZone(e),{left:i,top:s}=o,{numberOfCols:r,numberOfRows:n}=hi(o),a=this.getters.getActiveSheetId();this.addMissingDimensions(r,n,i,s);for(let e=0;e<t.length;e++)for(let o=0;o<t[e].length;o++)this.dispatch("UPDATE_CELL",{row:s+e,col:i+o,content:t[e][o],sheetId:a});const l={left:i,top:s,right:i+r-1,bottom:s+n-1};this.selection.selectZone({cell:{col:i,row:s},zone:l})}getClipboardContent(){return{[fs.PlainText]:this.values.map((e=>e.join("\t"))).join("\n")}}getPasteZone(e){const t=this.values.length,o=Math.max(...this.values.map((e=>e.length))),{left:i,top:s}=e[0];return{top:s,left:i,bottom:s+t-1,right:i+o-1}}}function XC(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:o}=Bo(e.value),[i,s]=t.split(":"),r=o?`${Be(o)}!`:"",n=KC(i),a=s?`:${KC(s)}`:"";return{...e,value:r+n+a}}function KC(e){switch(function(e){if(function(e){return e.startsWith("$")&&e.length>1&&e.slice(1).includes("$")}(e))return"colrow";if(function(e){return e.startsWith("$")}(e))return"col";if(function(e){return e.includes("$",1)}(e))return"row";return"none"}(e)){case"none":e=QC(e,"colrow");break;case"colrow":e=QC(e,"row");break;case"row":e=QC(e,"col");break;case"col":e=QC(e,"none")}return e}function QC(e,t){let o;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return o=e.search(/[0-9]/),e.slice(0,o)+"$"+e.slice(o);case"colrow":return o=e.search(/[0-9]/),"$"+(e=e.slice(0,o)+"$"+e.slice(o));case"none":return e}}const JC=r("The cell you are trying to edit has been deleted.");const eE=[{name:r("Sum"),types:[ms.number],compute:e=>Bl.compute([e])},{name:r("Avg"),types:[ms.number],compute:e=>Ql.compute([e])},{name:r("Min"),types:[ms.number],compute:e=>mc.compute([e])},{name:r("Max"),types:[ms.number],compute:e=>dc.compute([e])},{name:r("Count"),types:[ms.number,ms.text,ms.boolean,ms.error],compute:e=>nc.compute([e])},{name:r("Count Numbers"),types:[ms.number,ms.text,ms.boolean,ms.error],compute:e=>rc.compute([e])}];const tE=(new _i).add("sheet",class extends cC{static getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","getEvaluationSheets","doesHeaderExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","isEmpty","getSheetSize","getSheetZone","getPaneDivisions"];sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?9:0;case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex((t=>t===e.sheetId));return this.findIndexOfTargetSheet(t,e.delta),0}catch(e){return 14}case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.orderedSheetIds.length>1?0:9;case"ADD_COLUMNS_ROWS":const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return e.base<0||e.base>t?86:e.quantity<=0?87:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return Math.min(...e.elements)<0||Math.max(...e.elements)>t?86:0}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return 0}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIdsMapName",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.name);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);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?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")}}import(e){for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let t of e.sheets){const e=t.name||s("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:o,rowNumber:i}=this.getImportedSheetSize(t),r={id:t.id,name:e,numberOfCols:o,rows:qo(i),areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0}};this.orderedSheetIds.push(r.id),this.sheets[r.id]=r}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(lt).map((e=>{const t=this.sheets[e],o={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},conditionalFormats:[],figures:[],filterTables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible};return(t.panes.xSplit||t.panes.ySplit)&&(o.panes=t.panes),o}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new 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){const t=ze(e);for(const e in this.sheetIdsMapName)if(e.toUpperCase()===t.toUpperCase())return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getEvaluationSheets(){return this.sheets}doesHeaderExist(e,t,o){return"COL"===t?o>=0&&o<this.getNumberCols(e):o>=0&&o<this.getNumberRows(e)}getRow(e,t){const o=this.getSheet(e).rows[t];if(!o)throw new Error(`Row ${o} not found.`);return o}getCell({sheetId:e,col:t,row:o}){const i=this.tryGetSheet(e)?.rows[o]?.cells[t];if(void 0!==i)return this.getters.getCellById(i)}getColsZone(e,t,o){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:o}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(lt)}getRowsZone(e,t,o){return{top:t,bottom:o,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){let t=1;const o=this.orderedSheetIds.map(this.getSheetName.bind(this));let i=`${e}${t}`;for(;o.includes(i);)i=`${e}${t}`,t++;return i}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}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,o){const i={...this.getPaneDivisions(e)};"COL"===o?i.xSplit=t:"ROW"===o&&(i.ySplit=t),this.history.update("sheets",e,"panes",i)}isEmpty(e,t){return ui(t).map((({col:t,row:o})=>this.getCell({sheetId:e,col:t,row:o}))).every((e=>!e||""===e.content))}updateCellPosition(e){const{sheetId:t,cellId:o,col:i,row:s}=e;o?this.setNewPosition(o,t,i,s):this.clearPosition(t,i,s)}setNewPosition(e,t,o,i){const s=this.cellPosition[e];s&&this.clearPosition(t,s.col,s.row),this.history.update("cellPosition",e,{row:i,col:o,sheetId:t}),this.history.update("sheets",t,"rows",i,"cells",o,e)}clearPosition(e,t,o){const i=this.sheets[e]?.rows[o].cells[t];i&&(this.history.update("cellPosition",i,void 0),this.history.update("sheets",e,"rows",o,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){this.sheets[e].rows[i].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:i})}}createSheet(e,t,o,i,s){const r={id:e,name:t,numberOfCols:o,rows:qo(i),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},n=this.orderedSheetIds.slice();n.splice(s,0,r.id);const a=this.sheets;return this.history.update("orderedSheetIds",n),this.history.update("sheets",Object.assign({},a,{[r.id]:r})),r}moveSheet(e,t){const o=this.orderedSheetIds.slice(),i=o.findIndex((t=>t===e)),s=o.splice(i,1);let r=this.findIndexOfTargetSheet(i,t);o.splice(r,0,s[0]),this.history.update("orderedSheetIds",o)}findIndexOfTargetSheet(e,t){for(;0!=t&&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(0===t)return e;throw new Error(r("There is not enough visible sheets"))}checkSheetName(e){const{orderedSheetIds:t,sheets:o}=this,i=e.name&&e.name.trim().toLowerCase();return t.find((e=>o[e]?.name.toLowerCase()===i))?11:le.test(i)?13:0}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?15:0}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?0:74}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:74}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.top<e.quantity&&e.quantity<=o.bottom)return 65;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.left<e.quantity&&e.quantity<=o.right)return 65;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const o=e.name;this.history.update("sheets",e.id,"name",t.trim());const i=Object.assign({},this.sheetIdsMapName);i[t]=e.id,delete i[o],this.history.update("sheetIdsMapName",i)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const o=this.getSheet(e),i=this.getDuplicateSheetName(o.name),s=Ve(o);s.id=t,s.name=i;for(let e=0;e<=s.numberOfCols;e++)for(let t=0;t<=s.rows.length;t++)s.rows[t]&&(s.rows[t].cells[e]=void 0);const r=this.orderedSheetIds.slice(),n=r.indexOf(e);r.splice(n+1,0,s.id),this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},this.sheets,{[s.id]:s}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:o}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:s.id,col:e,row:o,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[s.name]=s.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const o=this.orderedSheetIds.map(this.getSheetName.bind(this)),i=r("Copy of %s",e);let s=i.toString();for(;o.includes(s);)s=`${i} (${t})`,t++;return s}deleteSheet(e){const t=e.name,o=Object.assign({},this.sheets);delete o[e.id],this.history.update("sheets",o);const i=this.orderedSheetIds.slice(),s=i.indexOf(e.id);i.splice(s,1),this.history.update("orderedSheetIds",i);const r=Object.assign({},this.sheetIdsMapName);delete r[t],this.history.update("sheetIdsMapName",r)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let o of t)this.moveCellOnColumnsDeletion(e,o);const o=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",o-t.length);const i=t.filter((t=>t<e.panes.xSplit)).length;i&&this.setPaneDivisions(e.id,e.panes.xSplit-i,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let o of Ye(t))this.moveCellOnRowsDeletion(e,o[o.length-1],o[0]),o.map((t=>this.updateRowsStructureOnDeletion(t,e)));const o=t.filter((t=>t<e.panes.ySplit)).length;o&&this.setPaneDivisions(e.id,e.panes.ySplit-o,"ROW")}addColumns(e,t,o,i){const s="before"===o?t:t+1;this.moveCellsOnAddition(e,s,i,"columns");const r=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",r+i),s<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+i,"COL")}addRows(e,t,o,i){const s="before"===o?t:t+1;this.addEmptyRows(e,i),this.moveCellsOnAddition(e,s,i,"rows"),this.updateRowsStructureOnAddition(e,t,i),s<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+i,"ROW")}moveCellOnColumnsDeletion(e,t){for(let o=0;o<e.rows.length;o++){const i=e.rows[o];for(let s in i.cells){const r=Number(s),n=i.cells[s];n&&(r===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:r,row:o}),r>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:n,col:r-1,row:o}))}}}moveCellsOnAddition(e,t,o,i){const s=[];for(let r=0;r<e.rows.length;r++){const n=e.rows[r];if("rows"!==i||r>=t)for(let a in n.cells){const l=Number(a),c=n.cells[a];c&&("rows"===i||l>=t)&&s.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===i?o:0),row:r+("rows"===i?o:0)})}}for(let e of s.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,o){const i=o-t+1;for(let s=0;s<e.rows.length;s++){const r=e.rows[s];if(s>=t&&s<=o)for(let t in r.cells){const o=Number(t);r.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:o,row:s})}if(s>o)for(let t in r.cells){const o=Number(t),n=r.cells[t];n&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:n,col:o,row:s-i})}}}updateRowsStructureOnDeletion(e,t){const o=[],i=t.rows.map((e=>e.cells));for(let s in t.rows)Number(s)!==e&&o.push({cells:i.shift()});this.history.update("sheets",t.id,"rows",o)}updateRowsStructureOnAddition(e,t,o){const i=[],s=e.rows.map((e=>e.cells));e.rows.forEach((()=>i.push({cells:s.shift()}))),this.history.update("sheets",e.id,"rows",i)}addEmptyRows(e,t){const o=e.rows.slice();for(let e=0;e<t;e++)o.push({cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(Bt);let o=e.rowNumber,i=e.colNumber;for(let{col:e,row:s}of t)o=Math.max(o,s+1),i=Math.max(i,e+1);return{rowNumber:o,colNumber:i}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?27:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),"ranges"in e&&Array.isArray(e.ranges)&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),!t.every(Xo))return 25;if(t.length&&"sheetId"in e){const o=this.getSheetZone(e.sheetId);return t.every((e=>ai(e,o)))?0:18}return 0}}).add("header visibility",class extends cC{static getters=["canRemoveHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];hiddenHeaders={};allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return 27;const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),o="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=o?66:Math.min(...e.elements)<0||Math.max(...e.elements)>o?86:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.canRemoveHeaders(e.sheetId,e.dimension,e.elements)?0:8:27}return 0}handle(e){switch(e.type){case"CREATE_SHEET":const 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,Ve(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],o=pt(e.position,e.base);t.splice(o,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);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)}}canRemoveHeaders(e,t,o){const i=this.getAllVisibleHeaders(e,t);return s=o,!i.every((e=>s.includes(e)));var s}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]}getHiddenColsGroups(e){const t=[[]],o=this.hiddenHeaders[e].COL;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],o=this.hiddenHeaders[e].ROW;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){return je(0,this.hiddenHeaders[e][t].length).filter((o=>!this.hiddenHeaders[e][t][o]))}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]=Boolean(t.rows[e]?.isHidden);for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=Boolean(t.cols[e]?.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e=0;e<this.getters.getNumberRows(o.id);e++)(t||this.hiddenHeaders[o.id].ROW[e])&&(void 0===o.rows[e]&&(o.rows[e]={}),o.rows[e].isHidden=this.hiddenHeaders[o.id].ROW[e]);void 0===o.cols&&(o.cols={});for(let e=0;e<this.getters.getNumberCols(o.id);e++)(t||this.hiddenHeaders[o.id].COL[e])&&(void 0===o.cols[e]&&(o.cols[e]={}),o.cols[e].isHidden=this.hiddenHeaders[o.id].COL[e])}}}).add("filters",class extends cC{static getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];tables={};allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!Si(...e.target))return 81;const t=oi(...e.target),o=()=>this.getFilterTables(e.sheetId).some((e=>ri(e.zone,t)))?78:0,i=()=>{const o=this.getters.getMergesInZone(e.sheetId,t);for(let e of o)if(ri(t,e))return 80;return 0};return this.checkValidations(e,o,i);case"ADD_MERGE":for(let t of e.target)for(let o of this.getFilterTables(e.sheetId))if(ri(o.zone,t))return 80}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":this.history.update("tables",e.sheetIdTo,Ve(this.tables[e.sheetId]));break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=oi(...e.target),o=this.createFilterTable(t);this.history.update("tables",e.sheetId,o.id,o);break}case"REMOVE_FILTER_TABLE":{const t={};for(const o of this.getFilterTables(e.sheetId))e.target.every((e=>!ii(e,o.zone)))&&(t[o.id]=o);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let o of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,o)&&this.extendTableDown(t,o);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(lt):[]}getFilter(e){return this.getFilterTable(e)?.filters.find((t=>t.col===e.col))}getFilterId(e){return this.getFilter(e)?.id}getFilterTable({sheetId:e,col:t,row:o}){return this.getFilterTables(e).find((e=>ni(t,o,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>ai(e.zone,t)))}doesZonesContainFilter(e,t){for(const o of t)for(const t of this.getFilterTables(e))if(ii(o,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=Qo(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i=[];for(const o of t.filters){const t=Qo(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);i.push(new uC(o.id,t))}if(i.length<hi(o).numberOfCols){for(let e=o.left;e<=o.right;e++)i.find((t=>t.col===e))||i.push(new uC(this.uuidGenerator.uuidv4(),{...o,left:e,right:e}));i.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=ti(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(o){if(Ko(o)!==Ko(t.zone)){const i=[];for(const o of t.filters){const t=ti(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&i.push(new uC(o.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}else{const o={...this.tables[e.sheetId]};delete o[t.id],this.history.update("tables",e.sheetId,o)}}}createFilterTable(e){return new dC(e)}extendTableDown(e,t){const o={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",o);for(let o=0;o<t.filters.length;o++){const i=t.filters[o],s={...i.zoneWithHeaders,bottom:i.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",o,"zoneWithHeaders",s)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:o,row:i},s){if(!e)return;const r=s.zone;if(!(r.bottom+1===i&&o>=r.left&&o<=r.right))return!1;for(const e of je(r.left,r.right+1)){const o={sheetId:t,col:e,row:i},s=this.getters.getCell(o)?.content;if(s)return!1;if(this.getters.getFilter(o))return!1;if(this.getters.isInMerge(o))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const o=this.createFilterTable(Yo(e.range));this.history.update("tables",t.id,o.id,o)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:Ko(e.zone)})}exportForExcel(e){this.export(e)}}).add("cell",class extends cC{static getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];nextId=1;cells={};adaptRanges(e,t){for(const o of Object.keys(this.cells))for(const i of Object.values(this.cells[o]||{}))if(i.isFormula)for(const s of i.dependencies)if(!t||s.sheetId===t){const t=e(s);"NONE"!==t.changeType&&this.history.update("cells",o,i.id,"dependencies",i.dependencies.indexOf(s),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":case"CLEAR_CELL":return this.checkCellOutOfSheet(e.sheetId,e.col,e.row);default:return 0}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?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:""})}}setFormatter(e,t,o){for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let s=i.left;s<=i.right;s++)this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,format:o})}clearFormatting(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:null,format:""})}handleAddColumnsRows(e,t){let o,i;"before"===e.position?(o=je(e.base,e.base+e.quantity),i=e.base+e.quantity):(o=je(e.base+1,e.base+e.quantity+1),i=e.base),t(e.sheetId,i,o)}import(e){for(let t of e.sheets)for(let o in t.cells){const i=t.cells[o],{col:s,row:r}=Bt(o);if(i?.content||i?.format||i?.style){const o=this.importCell(t.id,i,e.styles,e.formats);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,col:s,row:r,sheetId:t.id})}}}export(e){const t={},o={};for(let i of e.sheets){const e={},s=Object.keys(this.cells[i.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const i of s){const s=this.getters.getCell(i);e[Ht(i.col,i.row)]={style:s.style?ht(s.style,t):void 0,format:s.format?ht(s.format,o):void 0,content:s.content||void 0}}i.cells=e}e.styles=t,e.formats=o}importCell(e,t,o,i){const s=t.style&&o[t.style]||void 0,r=t.format&&i[t.format]||void 0,n=this.getNextUid();return this.createCell(n,t?.content||"",r,s,e)}exportForExcel(e){this.export(e)}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t in this.cells){const o=this.cells[t][e];if(o)return o}}buildFormulaContent(e,t,o){const i=o||[...t.dependencies];return dt(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=i.shift();return this.getters.getRangeString(t,e)}return t.value})))}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,o=[{colFixed:!1,rowFixed:!1}]){const i=Ht((t=this.getters.expandZone(e,t)).left,t.top,o[0]),s=Ht(t.right,t.bottom,o.length>1?o[1]:o[0]),r=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),n=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=r.col===n.col&&r.row===n.row;return i==s||a?i:i+":"+s}setStyle(e,t,o){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let s=i.top;s<=i.bottom;s++){const i=this.getters.getCell({sheetId:e,col:t,row:s});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,style:o?{...i?.style,...o}:void 0})}}copyColumnStyle(e,t,o){for(let i=0;i<this.getters.getNumberRows(e);i++){const s=this.getFormat(e,t,i);if(s.style||s.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,...s})}}copyRowStyle(e,t,o){for(let i=0;i<this.getters.getNumberCols(e);i++){const s=this.getFormat(e,i,t);if(s.style||s.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,...s})}}getFormat(e,t,o){const i={},s=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),r=this.getters.getCell(s);return r&&(r.style&&(i.style=r.style),r.format&&(i.format=r.format)),i}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,o,i){const s=this.getters.getCell({sheetId:e,col:t,row:o}),r="content"in i||"formula"in i,n=r?Et(i?.content):s?.content||"";let a;a=void 0!==i.style?i.style||void 0:s?s.style:void 0;let l=("format"in i?i.format:s&&s.format)||xo(n);if((r&&!n&&!i.formula||!r&&(!s||""===s.content))&&!a&&!l)return void(s&&(this.history.update("cells",e,s.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:o,sheetId:e})));const c=s?.id||this.getNextUid(),h=this.createCell(c,n,l,a,e);this.history.update("cells",e,h.id,h),this.dispatch("UPDATE_CELL_POSITION",{cellId:h.id,col:t,row:o,sheetId:e})}createCell(e,t,o,i,s){if(!t.startsWith("="))return this.createLiteralCell(e,t,o,i);try{return this.createFormulaCell(e,t,o,i,s)}catch(s){return this.createErrorFormula(e,t,o,i,s)}}createLiteralCell(e,t,o,i){return{id:e,content:t,style:i,format:o,isFormula:!1}}createFormulaCell(e,t,o,i,s){const r=Wv(t);return r.dependencies.length?this.createFormulaCellWithDependencies(e,r,o,i,s):{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:r,dependencies:[]}}createFormulaCellWithDependencies(e,t,o,i,s){const r=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(s,e))),n=this.buildFormulaContent.bind(this);return{id:e,get content(){return n(s,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:i,format:o,isFormula:!0,compiledFormula:t,dependencies:r}}createErrorFormula(e,t,o,i,s){return{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:{dependencies:[],tokens:av(t),execute:function(){throw s}},dependencies:[]}}checkCellOutOfSheet(e,t,o){if(!this.getters.tryGetSheet(e))return 27;return ni(t,o,this.getters.getSheetZone(e))?0:18}}).add("merge",class extends cC{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];nextId=1;merges={};mergeCellMap={};allowDispatch(e){const t="force"in e&&!!e.force;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 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const o of Object.values(t).filter(lt))this.addMerge(e.sheetIdTo,o.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const o=t?[t]:Object.keys(this.merges);for(const t of o)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(lt)}getMerge({sheetId:e,col:t,row:o}){const i=this.mergeCellMap[e],s=i?t in i&&i[t]?.[o]:void 0;return s?this.getMergeById(e,s):void 0}getMergesInZone(e,t){const o=this.mergeCellMap[e];if(!o)return[];const i=new Set;for(const{col:e,row:s}of ui(t)){const t=o[e]?.[s];t&&i.add(t)}return Array.from(i).map((t=>this.getMergeById(e,t))).filter(lt)}doesIntersectMerge(e,t){return ui(t).some((({col:t,row:o})=>void 0!==this.getMerge({sheetId:e,col:t,row:o})))}doesColumnsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let s=0;s<this.getters.getNumberRows(e);s++)if(this.isInSameMerge(i.id,t,s,o,s))return!0;return!1}doesRowsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let s=0;s<=this.getters.getNumberCols(e);s++)if(this.isInSameMerge(i.id,s,t,s,o))return!0;return!1}expandZone(e,t){let{left:o,right:i,top:s,bottom:r}=t,n={left:o,right:i,top:s,bottom:r};for(let t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&ri(o,n)&&(n=oi(o,n))}return si(n,t)?n:this.expandZone(e,n)}isInSameMerge(e,t,o,i,s){const r=this.getMerge({sheetId:e,col:t,row:o}),n=this.getMerge({sheetId:e,col:i,row:s});return!(!r||!n)&&si(r,n)}isInMerge({sheetId:e,col:t,row:o}){const i=this.mergeCellMap[e];return!!i&&(t in i&&Boolean(i[t]?.[o]))}getMainCellPosition(e){if(!this.isInMerge(e))return e;const t=this.getMerge(e).topLeft;return{sheetId:e.sheetId,col:t.col,row:t.row}}getBottomLeftCell(e){if(!this.isInMerge(e))return e;const{bottom:t,left:o}=this.getMerge(e);return{sheetId:e.sheetId,col:o,row:t}}isMergeHidden(e,t){const o=this.getters.getHiddenColsGroups(e),i=this.getters.getHiddenRowsGroups(e);for(let e of o)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of i)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const o=this.getMerge({sheetId:e,col:t.left,row:t.top});if(o)return si(t,o);const{numberOfCols:i,numberOfRows:s}=hi(t);return 1===i&&1===s}isMergeDestructive(e,t){let{left:o,right:i,top:s,bottom:r}=t;i=He(i,0,this.getters.getNumberCols(e)-1),r=He(r,0,this.getters.getNumberRows(e)-1);for(let t=s;t<=r;t++)for(let r=o;r<=i;r++)if(r!==o||t!==s){const o=this.getters.getCell({sheetId:e,col:r,row:t});if(o&&""!==o.content)return!0}return!1}getMergeById(e,t){const o=this.merges[e]?.[t];return void 0!==o?pC(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;return t.some((t=>this.isMergeDestructive(e,t)))?3:0}checkOverlap({target:e}){for(const t of e)for(const o of e)if(t!==o&&ri(t,o))return 65;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:o,ySplit:i}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<o&&e.right>=o||e.top<i&&e.bottom>=i)return 75;return 0}checkMergedContentUpdate(e){const{col:t,row:o,content:i}=e;if(void 0===i)return 0;const{col:s,row:r}=this.getMainCellPosition(e);return s===t&&r===o?0:4}checkMergeExists(e){const{sheetId:t,target:o}=e;for(const e of o){const{left:o,top:i}=e,s=this.getMerge({sheetId:t,col:o,row:i});if(void 0===s||!si(e,s))return 5}return 0}addMerge(e,t){let{left:o,right:i,top:s,bottom:r}=t;i=He(i,0,this.getters.getNumberCols(e)-1),r=He(r,0,this.getters.getNumberRows(e)-1);if(Ht(o,s)===Ht(i,r))return;const n=this.getters.getCell({sheetId:e,col:o,row:s});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Ko({left:o,top:s,right:i,bottom:r})));let l=new Set;for(let t=s;t<=r;t++)for(let r=o;r<=i;r++){r===o&&t===s||this.dispatch("UPDATE_CELL",{sheetId:e,col:r,row:t,style:n?n.style:null,content:""});const i=this.getMerge({sheetId:e,col:r,row:t});i&&l.add(i.id),this.history.update("mergeCellMap",e,r,t,a)}for(let t of l){const{top:o,bottom:i,left:s,right:r}=this.getMergeById(e,t);for(let t=o;t<=i;t++)for(let o=s;o<=r;o++){const i={sheetId:e,col:o,row:t},s=this.getMerge(i);s&&s.id===a||(this.history.update("mergeCellMap",e,o,t,void 0),this.dispatch("CLEAR_CELL",i))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:o,top:i,bottom:s,right:r}=t,n=this.getMerge({sheetId:e,col:o,row:i});if(void 0!==n&&si(t,n)){this.history.update("merges",e,n.id,void 0);for(let t=i;t<=s;t++)for(let i=o;i<=r;i++)this.history.update("mergeCellMap",e,i,t,void 0)}}applyRangeChangeOnSheet(e,t){const o=Object.entries(this.merges[e]||{});for(const[i,s]of o)if(s){const o=s.zone,r=t(s);switch(r.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,o);break;default:const{numberOfCols:t,numberOfRows:s}=hi(r.range.zone);1===t&&1===s?this.removeMerge(e,o):this.history.update("merges",e,parseInt(i,10),r.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:o,row:i}of ui(t))this.history.update("mergeCellMap",e,o,i,t.id)}import(e){const 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 o of t)this.addMerge(e,Yo(o))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...gC(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends cC{static getters=["getRowSize","getColSize"];sizes={};handle(e){switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),o={COL:t.COL.map((e=>({manualSize:void 0,computedSize:ut(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:ut(e)})))};this.history.update("sizes",e.sheetId,o);break}case"DUPLICATE_SHEET":for(const t of this.sizes[e.sheetId].ROW)t.computedSize();for(const t of this.sizes[e.sheetId].COL)t.computedSize();this.history.update("sizes",e.sheetIdTo,Ve(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const 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]];for(let o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);const o=Math.min(...e.elements);t=t.map(((t,i)=>"ROW"===e.dimension&&i>=o?{manualSize:t.manualSize,computedSize:ut((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const o=pt(e.position,e.base),i=t[e.base];t.splice(o,0,...Array(e.quantity).fill(i)),t=t.map(((t,o)=>"ROW"===e.dimension&&o>e.base+e.quantity?{manualSize:t.manualSize,computedSize:ut((()=>this.getRowTallestCellSize(e.sheetId,o)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":for(let t of e.elements)if("ROW"===e.dimension){const o=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:ut(o)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:ut(e.size||D)});break;case"UPDATE_CELL":if(!this.sizes[e.sheetId]?.ROW?.[e.row]?.manualSize){const{sheetId:t,row:o}=e;this.history.update("sizes",t,"ROW",o,"computedSize",ut((()=>this.getRowTallestCellSize(t,o))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let o of je(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,o);t!==this.getRowSize(e.sheetId,o)&&this.history.update("sizes",e.sheetId,"ROW",o,"computedSize",ut(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,o){return Math.round(this.sizes[e]?.[t][o]?.manualSize||this.sizes[e]?.[t][o]?.computedSize()||this.getDefaultHeaderSize(t))}computeSheetSizes(e){const t={COL:[],ROW:[]};for(let o of je(0,this.getters.getNumberCols(e)))t.COL.push(this.getHeaderSize(e,"COL",o));for(let o of je(0,this.getters.getNumberRows(e))){let i=this.sizes[e]?.ROW?.[o].manualSize;if(!i){i=this.getRowTallestCellSize(e,o)}t.ROW.push(i)}return t}getDefaultHeaderSize(e){return"COL"===e?D:L}getCellHeight(e){const t=this.getters.getMerge(e);if(t&&t.bottom!==t.top)return L;return function(e){return e&&e.content?$e(Ze(e.style),e.isFormula?1:e.content.split(pe).length)+2*B:L}(this.getters.getCell(e))}getRowTallestCellSize(e,t){const o=this.getters.getRowCells(e,t);let i=0;for(let e=0;e<o.length;e++){const t=this.getters.getCellById(o[e]);if(!t)continue;const s=this.getters.getCellPosition(t.id),r=this.getCellHeight(s);r>i&&r>L&&(i=r)}return i<=L?L:i}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[o,i]of Object.entries(t.rows))i.size&&(e.ROW[o]=i.size);for(let[o,i]of Object.entries(t.cols))i.size&&(e.COL[o]=i.size);const o=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:o.COL.map(((t,o)=>({manualSize:e.COL[o],computedSize:ut(t)}))),ROW:o.ROW.map(((t,o)=>({manualSize:e.ROW[o],computedSize:ut(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e of je(0,this.getters.getNumberRows(o.id)))(t||this.sizes[o.id].ROW[e]?.manualSize)&&(o.rows[e]={...o.rows[e],size:this.getRowSize(o.id,e)});void 0===o.cols&&(o.cols={});for(let e of je(0,this.getters.getNumberCols(o.id)))(t||this.sizes[o.id].COL[e]?.manualSize)&&(o.cols[e]={...o.cols[e],size:this.getColSize(o.id,e)})}}}).add("borders",class extends cC{static getters=["getCellBorder","getBordersColors"];borders={};handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const o=t.slice().map((e=>e?.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,o)}break;case"DELETE_SHEET":const o={...this.borders};delete o[e.sheetId],this.history.update("borders",o);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_ZONE_BORDERS":if(e.border){const 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||Y,color:e.border.color||X})}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of e.elements)"COL"===e.dimension?this.shiftBordersHorizontally(e.sheetId,t+1,-1):this.shiftBordersVertically(e.sheetId,t+1,-1);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){let t,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,o)}handleAddRows(e){let t,o;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,o)}getCellBorder({sheetId:e,col:t,row:o}){const i={top:this.borders[e]?.[t]?.[o]?.horizontal,bottom:this.borders[e]?.[t]?.[o+1]?.horizontal,left:this.borders[e]?.[t]?.[o]?.vertical,right:this.borders[e]?.[t+1]?.[o]?.vertical};return i.bottom||i.left||i.right||i.top?i:null}getBordersColors(e){const t=[],o=this.borders[e];if(o)for(const e of o.filter(lt))for(const o of e)o?.horizontal&&t.push(o.horizontal.color),o?.vertical&&t.push(o.vertical.color);return t}ensureColumnBorderContinuity(e,t,o){const i=je(t+1,o);for(let s=0;s<this.getters.getNumberRows(e);s++){const r=this.getCellBorder({sheetId:e,col:t,row:s}),n=this.getCellBorder({sheetId:e,col:o,row:s});if(r&&n){const t=this.getCommonSides(r,n);for(let o of i)this.addBorder(e,o,s,t)}}}ensureRowBorderContinuity(e,t,o){const i=je(t+1,o);for(let s=0;s<this.getters.getNumberCols(e);s++){const r=this.getCellBorder({sheetId:e,col:s,row:t}),n=this.getCellBorder({sheetId:e,col:s,row:o});if(r&&n){const t=this.getCommonSides(r,n);for(let o of i)this.addBorder(e,s,o,t)}}}getCommonSides(e,t){const o={};for(let i of["top","bottom","left","right"])e[i]&&e[i]===t[i]&&(o[i]=e[i]);return o}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){return this.borders[e]?je(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,o,{moveFirstLeftBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfColumn(e,t,o,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((s=>{(s===t&&i||s!==t)&&this.moveBordersOfColumn(e,s,o,"vertical"),this.moveBordersOfColumn(e,s,o,"horizontal")})))}shiftBordersVertically(e,t,o,{moveFirstTopBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfRow(e,t,o,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((s=>{(s===t&&i||s!==t)&&this.moveBordersOfRow(e,s,o,"horizontal"),this.moveBordersOfRow(e,s,o,"vertical")})))}moveBordersOfRow(e,t,o,i,{destructive:s}={destructive:!0}){const r=this.borders[e];r&&this.getColumnsWithBorders(e).forEach((n=>{const a=r[n]?.[t+o]?.[i],l=r[n]?.[t]?.[i];this.history.update("borders",e,n,t+o,i,s?l:l||a),this.history.update("borders",e,n,t,i,void 0)}))}moveBordersOfColumn(e,t,o,i,{destructive:s}={destructive:!0}){const r=this.borders[e];r&&this.getRowsRange(e).forEach((n=>{const a=r[t+o]?.[n]?.[i],l=r[t]?.[n]?.[i];this.history.update("borders",e,t+o,n,i,s?l:l||a),this.history.update("borders",e,t,n,i,void 0)}))}setBorder(e,t,o,i,s=!0){!s&&this.borders?.[e]?.[t]?.[o]?.vertical||this.history.update("borders",e,t,o,"vertical",i?.left),!s&&this.borders?.[e]?.[t]?.[o]?.horizontal||this.history.update("borders",e,t,o,"horizontal",i?.top),!s&&this.borders?.[e]?.[t+1]?.[o]?.vertical||this.history.update("borders",e,t+1,o,"vertical",i?.right),!s&&this.borders?.[e]?.[t]?.[o+1]?.horizontal||this.history.update("borders",e,t,o+1,"horizontal",i?.bottom)}clearBorders(e,t){for(let o of t){for(let t=o.top;t<=o.bottom;t++){this.history.update("borders",e,o.right+1,t,"vertical",void 0);for(let i=o.left;i<=o.right;i++)this.history.update("borders",e,i,t,void 0)}for(let t=o.left;t<=o.right;t++)this.history.update("borders",e,t,o.bottom+1,"horizontal",void 0)}}addBorder(e,t,o,i){this.setBorder(e,t,o,{...this.getCellBorder({sheetId:e,col:t,row:o}),...i})}setBorders(e,t,o,i){if("clear"===o)return this.clearBorders(e,t);for(let s of t){if("h"===o||"hv"===o||"all"===o)for(let t=s.top+1;t<=s.bottom;t++)for(let o=s.left;o<=s.right;o++)this.addBorder(e,o,t,{top:i});if("v"===o||"hv"===o||"all"===o)for(let t=s.top;t<=s.bottom;t++)for(let o=s.left+1;o<=s.right;o++)this.addBorder(e,o,t,{left:i});if("left"===o||"all"===o||"external"===o)for(let t=s.top;t<=s.bottom;t++)this.addBorder(e,s.left,t,{left:i});if("right"===o||"all"===o||"external"===o)for(let t=s.top;t<=s.bottom;t++)this.addBorder(e,s.right+1,t,{left:i});if("top"===o||"all"===o||"external"===o)for(let t=s.left;t<=s.right;t++)this.addBorder(e,t,s.top,{top:i});if("bottom"===o||"all"===o||"external"===o)for(let t=s.left;t<=s.right;t++)this.addBorder(e,t,s.bottom+1,{top:i})}}addBordersToMerge(e,t){const{left:o,right:i,top:s,bottom:r}=t,n=this.getCellBorder({sheetId:e,col:o,row:s}),a=this.getCellBorder({sheetId:e,col:i,row:r});this.clearBorders(e,[t]),n?.top&&this.setBorders(e,[{...t,bottom:s}],"top",n.top),n?.left&&this.setBorders(e,[{...t,right:o}],"left",n.left),a?.bottom?this.setBorders(e,[{...t,top:r}],"bottom",a.bottom):n?.bottom&&this.setBorders(e,[{...t,top:r}],"bottom",n.bottom),a?.right?this.setBorders(e,[{...t,left:i}],"right",a.right):n?.right&&this.setBorders(e,[{...t,left:i}],"right",n.right)}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(const o in t.cells){const i=t.cells[o];if(i?.border){const s=e.borders[i.border],{col:r,row:n}=Bt(o);this.setBorder(t.id,r,n,s,!1)}}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Yo(e))}export(e){let t=0;const o={};function i(e){for(let[t,i]of Object.entries(o))if(Pe(i)===Pe(e))return parseInt(t,10);return o[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let o=0;o<t.rowNumber;o++){const s=this.getCellBorder({sheetId:t.id,col:e,row:o});if(s){const r=Ht(e,o),n=t.cells[r],a=i(s);n?n.border=a:t.cells[r]={border:a}}}e.borders=o}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends cC{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];cfRules={};loopThroughRangesOfSheet(e,t){for(const o of this.cfRules[e])for(const i of o.ranges){const s=t(i);switch(s.changeType){case"REMOVE":let t=o.ranges.slice();t.splice(o.ranges.indexOf(i),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",t):this.removeConditionalFormatting(o.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",o.ranges.indexOf(i),s.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case"MOVE_CONDITIONAL_FORMAT":return this.checkValidReordering(e.cfId,e.direction,e.sheetId)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const o={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(o,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"MOVE_CONDITIONAL_FORMAT":this.reorderConditionalFormatting(e.cfId,e.direction,e.sheetId)}}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){this.export(e)}getConditionalFormats(e){return this.cfRules[e]?.map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const o=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{o.add(e)}))})),Array.from(o)}getRulesByZone(e,t){const o=new Set;for(let i=t.top;i<=t.bottom;i++)for(let s=t.left;s<=t.right;s++){this.getRulesByCell(e,s,i).forEach((e=>{o.add(e.id)}))}return o}getRulesByCell(e,t,o){const i=[];for(let s of this.cfRules[e])for(let e of s.ranges)ni(t,o,e.zone)&&i.push(s);return new Set(i.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const o={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return o}addConditionalFormatting(e,t){const o=this.cfRules[t].slice(),i=o.findIndex((t=>t.id===e.id)),s=this.mapToConditionalFormatInternal(t,e);i>-1?o.splice(i,1,s):o.push(s),this.history.update("cfRules",t,o)}checkValidReordering(e,t,o){if(!this.cfRules[o])return 27;const i=this.cfRules[o].findIndex((t=>t.id===e));if(-1===i)return 71;const s="up"===t?i-1:i+1;return s<0||s>=this.cfRules[o].length?71:0}checkEmptyRange(e){return e.ranges.length?0:24}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));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)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return o=>{if(t.includes(o.operator)){const t=[],i=e=>void 0===e||""===e;return e>=1&&i(o.values[0])&&t.push(51),e>=2&&i(o.values[1])&&t.push(52),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 53;case"max":return 55;case"mid":return 54;case"upperInflectionPoint":return 56;case"lowerInflectionPoint":return 57}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{Wv(e.value||"")}catch(e){switch(t){case"min":return 58;case"max":return 60;case"mid":return 59;case"upperInflectionPoint":return 61;case"lowerInflectionPoint":return 62}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,o=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(o)?48:0}checkMinBiggerThanMax(e){const t=e.minimum.value,o=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&hC(t)>=hC(o)?47:0}checkMidBiggerThanMax(e){const t=e.midpoint?.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&hC(t)>=hC(o)?49:0}checkMinBiggerThanMid(e){const t=e.minimum.value,o=e.midpoint?.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&hC(t)>=hC(o)?50:0}removeConditionalFormatting(e,t){const o=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==o){const e=this.cfRules[t].slice();e.splice(o,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,o){const i=this.cfRules[o].findIndex((t=>t.id===e)),s="up"===t?i-1:i+1;if(!(s<0||s>=this.cfRules[o].length)&&-1!==i&&-1!==s){const e=[...this.cfRules[o]],t=e[i];e[i]=e[s],e[s]=t,this.history.update("cfRules",o,e)}}}).add("figures",class extends cC{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:o,...i}=e,s=i;this.updateFigure(o,s);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":this.onRowColDelete(e.sheetId,e.dimension)}}onRowColDelete(e,t){"ROW"===t?this.onRowDeletion(e):this.onColDeletion(e)}onRowDeletion(e){const t=this.getters.getNumberRows(e);let o=0;for(let i=0;i<t;i++)o+=this.getters.getRowSize(e,i);const i=this.getters.getFigures(e);for(const t of i){const i=Math.min(t.y,o-t.height);i!==t.y&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,y:i})}}onColDeletion(e){const t=this.getters.getNumberCols(e);let o=0;for(let i=0;i<t;i++)o+=this.getters.getColSize(e,i);const i=this.getters.getFigures(e);for(const t of i){const i=Math.min(t.x,o-t.width);i!==t.x&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,x:i})}}updateFigure(e,t){if("id"in t)for(const[o,i]of Object.entries(t))switch(o){case"x":case"y":void 0!==i&&this.history.update("figures",e,t.id,o,Math.max(i,0));break;case"width":case"height":void 0!==i&&this.history.update("figures",e,t.id,o,i)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){return void 0===this.figures[e]?.[t]?70:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>t?.[e]))?82:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(lt)}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>void 0!==this.figures[t]?.[e]))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const o=void 0;t.figures.push({...e,data:o})}}exportForExcel(e){this.export(e)}}).add("chart",class extends cC{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];charts={};createChart=function(e){const t=On.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(o,i,s){const r=t.find((e=>e.match(i.type)));if(!r)throw new Error(`No builder for this chart: ${i.type}`);return r.createChart(i,s,e)}}(this.getters);validateChartDefinition=e=>function(e,t){const o=On.getAll().find((e=>e.match(t.type)));if(!o)throw new Error("Unknown chart type.");return o.validateChartDefinition(e,t)}(this,e.definition);adaptRanges(e){for(const[t,o]of Object.entries(this.charts))this.history.update("charts",t,o?.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return 0}}handle(e){switch(e.type){case"CREATE_CHART":this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case"UPDATE_CHART":this.addChart(e.id,e.definition);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const o of t)if("chart"===o.tag){const t=o.id.split(oe).pop(),i=`${e.sheetIdTo}${oe}${t}`,s=this.charts[o.id]?.copyForSheetId(e.sheetIdTo);s&&this.dispatch("CREATE_CHART",{id:i,position:{x:o.x,y:o.y},size:{width:o.width,height:o.height},definition:s.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.id,void 0);break;case"DELETE_SHEET":for(let t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){const t=this.charts[e]?.type;if(!t)throw new Error("Chart not defined.");return t}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>t?.sheetId===e)).map((([e])=>e))}getChartDefinition(e){const t=this.charts[e]?.getDefinition();if(!t)throw new Error(`There is no chart with the given figureId: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)"chart"===e.tag&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){if(e.sheets)for(let t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(let t of e){const e=t;if(e&&"chart"===e.tag){const t=this.charts[e.id]?.getDefinition();t&&(e.data=t,o.push(e))}else o.push(e)}t.figures=o}}exportForExcel(e){for(let t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(let t of e)if(t&&"chart"===t.tag){const e=this.charts[t.id]?.getDefinitionForExcel();e&&o.push({...t,data:e})}t.charts=o}}addFigure(e,t,o={x:0,y:0},i={width:536,height:335}){if(this.getters.getFigure(t,e))return;const s={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:s})}addChart(e,t){const o=this.getters.getFigureSheetId(e);o&&this.history.update("charts",e,this.createChart(e,t,o))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?84:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:85}}).add("image",class extends cC{static getters=["getImage","getImagePath","getImageSize"];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?28:0}handle(e){switch(e.type){case"CREATE_IMAGE":this.addFigure(e.figureId,e.sheetId,e.position,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const o of t)if("image"===o.tag){const t=o.id.split(oe).pop(),i=`${e.sheetIdTo}${oe}${t}`,s=this.getImage(o.id);if(s){const t={width:o.width,height:o.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:i,position:{x:o.x,y:o.y},size:t,definition:Ve(s)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.id,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){const e=new Set(this.getAllImages().map((e=>e.path)));for(const t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new 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,o,i){const s={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:s})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const o of e)this.history.update("images",t.id,o.id,o.data),this.syncedImages.add(o.data.path)}}export(e){for(const t of e.sheets){const e=t.figures.filter((e=>"image"===e.tag));for(const o of e)o.data=this.images[t.id]?.[o.id]}}exportForExcel(e){for(const t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(const t of e)if("image"===t?.tag){const e=this.getImage(t.id);e&&o.push({...t,data:Ve(e)})}t.images=o}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(lt));return e}}),oE=(new _i).add("ui_sheet",class extends fC{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];ctx=document.createElement("canvas").getContext("2d");allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 27}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const o=this.getColMaxWidth(e.sheetId,t);0!==o&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:o,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e){const t=this.getCellText(e),o=this.getters.getCellComputedStyle(e);let i=this.getTextWidth(t,o);this.getters.getConditionalIcon(e)&&(i+=function(e){return Ze(e)+2*V}(this.getters.getCellStyle(e)));if(this.getters.isFilterHeader(e)&&(i+=20),i>0&&(i+=2*H,"wrap"===this.getters.getCellStyle(e).wrapping)){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,i)}return i}getTextWidth(e,t){return We(this.ctx,e,t)}getCellText(e,t=!1){const o=this.getters.getCell(e);return t&&o?.isFormula?o.content:this.getters.getEvaluatedCell(e).formattedValue}getCellMultiLineText(e,t){const o=this.getters.getCellStyle(e),i=this.getters.getCellText(e,this.getters.shouldShowFormulas()),s=[];for(const e of i.split("\n")){const i=e.split(" ");if(!t){s.push(e);continue}let r="",n=t;for(let e of i){const i=this.splitWordToSpecificWidth(this.ctx,e,t,o),a=i.pop(),l=We(this.ctx,a,o);if(i.length)""!==r&&(s.push(r),r="",n=t),i.forEach((e=>{s.push(e)})),r=a,n=t-l;else{const e=""===r?a:" "+a,i=We(this.ctx,e,o);i<=n?(r+=e,n-=i):(s.push(r),r=a,n=t-l)}}""!==r&&s.push(r)}return s}getColDimensions(e,t){const o=this.getColRowOffset("COL",0,t,e),i=this.getters.getColSize(e,t);return{start:o,size:i,end:o+(this.getters.isColHidden(e,t)?0:i)}}getRowDimensions(e,t){const o=this.getColRowOffset("ROW",0,t,e),i=this.getters.getRowSize(e,t);return{start:o,size:i,end:o+(this.getters.isRowHidden(e,t)?0:i)}}getColRowOffset(e,t,o,i=this.getters.getActiveSheetId()){if(o<t)return-this.getColRowOffset(e,o,t);let s=0;for(let r=t;r<o;r++)this.getters.isHeaderHidden(i,e,r)||(s+="COL"===e?this.getters.getColSize(i,r):this.getters.getRowSize(i,r));return s}getColMaxWidth(e,t){const o=ui(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,...o)}splitWordToSpecificWidth(e,t,o,i){if(We(e,t,i)<=o)return[t];const s=[];let r="";for(let n of t){We(e,r+n,i)>o?(s.push(r),r=n):r+=n}return s.push(r),s}}).add("header_visibility_ui",class extends fC{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,o){return"COL"===t?this.isColHidden(e,o):this.isRowHidden(e,o)}getNextVisibleCellPosition({sheetId:e,col:t,row:o}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",o,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,o,i){if(o<=i)for(let s=o;s<=i;s++)if(this.getters.doesHeaderExist(e,t,s)&&!this.isHeaderHidden(e,t,s))return s;if(o>i)for(let s=o;s>=i;s--)if(this.getters.doesHeaderExist(e,t,s)&&!this.isHeaderHidden(e,t,s))return s}findLastVisibleColRowIndex(e,t,{last:o,first:i}){return je(o,i,-1).find((o=>!this.isHeaderHidden(e,t,o)))||i}findFirstVisibleColRowIndex(e,t){const o=this.getters.getNumberHeaders(e,t);for(let i=0;i<o;i++){if("COL"===t&&!this.isColHidden(e,i))return i;if("ROW"===t&&!this.isRowHidden(e,i))return i}}exportForExcel(e){for(const t of e.sheets)for(const[e,o]of Object.entries(t.rows)){const i=this.isRowHidden(t.id,Number(e));o.isHidden=i}}}).add("ui_options",class extends fC{static getters=["shouldShowFormulas"];showFormulas=!1;handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}).add("selectionInputManager",class extends fC{config;static layers=[1];static getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];inputs={};focusedInputId=null;get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}constructor(e){super(e),this.config=e}allowDispatch(e){if("FOCUS_RANGE"===e.type){const t=this.currentInput?.getIndex(e.rangeId);if(this.focusedInputId===e.id&&this.currentInput?.focusedRangeIndex===t)return 29}return this.currentInput?this.currentInput.allowDispatch(e):0}handle(e){switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id];this.selection.capture(t,{cell:{col:0,row:0},zone:fi({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id],o=t.ranges.find((t=>t.id===e.rangeId)),i=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(i,o?.xc||"A1").zone;this.selection.capture(t,{cell:{col:s.left,row:s.top},zone:s},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}this.currentInput?.handle(e)}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,o)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.inputs[e].focusedRangeIndex&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.inputs[e].focusedRangeIndex===o}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:o}=Bo(e);return null!==t.match(Po)&&(!o||void 0!==this.getters.getSheetIdByName(o))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,o=!1){if(this.inputs[e]=new _C(this.config,t,o),0===t.length){const t=this.inputs[e],o={zone:fi({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,o,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}).add("highlight",class extends fC{static layers=[1];static getters=["getHighlights"];getHighlights(){return this.prepareHighlights(this.getters.getComposerHighlights().concat(this.getters.getSelectionInputHighlights()))}prepareHighlights(e){return e.filter((e=>e.zone.top>=0&&e.zone.left>=0&&e.zone.bottom<this.getters.getNumberRows(e.sheetId)&&e.zone.right<this.getters.getNumberCols(e.sheetId))).map((e=>{const{numberOfRows:t,numberOfCols:o}=hi(e.zone),i=t*o==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:i}}))}drawGrid(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId(),s=3*o;t.lineWidth=s;const r=this.getHighlights();for(let e of r.filter(((e,t)=>r.findIndex((t=>si(t.zone,e.zone)&&t.sheetId===i))===t))){const{x:o,y:i,width:r,height:n}=this.getters.getVisibleRect(e.zone);r>0&&n>0&&(t.strokeStyle=e.color,t.strokeRect(o+s/2,i+s/2,r-s,n-s),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+s,i+s,r-2*s,n-2*s))}}}).add("grid renderer",class extends fC{static layers=[0,7];static getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];boxes=[];getColDimensionsInViewport(e,t){const o=Math.min(...this.getters.getSheetViewVisibleCols()),i=this.getters.getColRowOffsetInViewport("COL",o,t),s=this.getters.getColSize(e,t);return{start:i,size:s,end:i+(this.getters.isColHidden(e,t)?0:s)}}getRowDimensionsInViewport(e,t){const o=Math.min(...this.getters.getSheetViewVisibleRows()),i=this.getters.getColRowOffsetInViewport("ROW",o,t),s=this.getters.getRowSize(e,t);return{start:i,size:s,end:i+(this.getters.isRowHidden(e,t)?0:s)}}getHeaderOffset(e,t,o){let i=this.getters.getColRowOffsetInViewport(e,t,o);return this.getters.isDashboard()||(i+="ROW"===e?_:F),i}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(),this.drawBackground(e),this.drawOverflowingCellBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e),this.drawFrozenPanes(e);break;case 7:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawBackground(e){const{ctx:t,thinLineWidth:o}=e,{width:i,height:s}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,i+m,s+m);const r=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),n=r?.1*o:0;if(r)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=o,t.strokeRect(e.x+n,e.y+n,e.width-2*n,e.height-2*n)}drawCellBackground(e){const{ctx:t}=e;for(const e of this.boxes){let o=e.style;o.fillColor&&"#ffffff"!==o.fillColor&&(t.fillStyle=o.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawOverflowingCellBackground(e){const{ctx:t,thinLineWidth:o}=e;for(const e of this.boxes)if(e.content&&e.isOverflow){const i=e.content.align||"left";let s,r;const n=e.y+o/2,a=e.height-o,l=Math.min(e.clipRect?.width||1/0,e.content.width);"left"===i?(s=e.x+o/2,r=l-2*o):"right"===i?(s=e.x+e.width-o/2,r=2*o-l):(s=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+o/2,r=l-2*o),t.fillStyle="#ffffff",t.fillRect(s,n,r,a)}}drawBorders(e){const{ctx:t}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:i,y:s,width:r,height:n}=e;t.left&&o(t.left,i,s,i,s+n),t.top&&o(t.top,i,s,i+r,s),t.right&&o(t.right,i+r,s,i+r,s+n),t.bottom&&o(t.bottom,i,s+n,i+r,s+n)}}function o({style:e,color:o},i,s,r,n){switch(t.strokeStyle=o,e){case"medium":t.lineWidth=2,s+=(i+=s===n?-.5:.5)===(r+=s===n?1.5:.5)?-.5:.5,n+=i===r?1.5:.5;break;case"thick":t.lineWidth=3,s===n&&(i--,r++),i===r&&(s--,n++);break;case"dashed":t.lineWidth=1,t.setLineDash([1,3]);break;case"dotted":t.lineWidth=1,s===n&&(i+=.5,r+=.5),i===r&&(s+=.5,n+=.5),t.setLineDash([1,1]);break;default:t.lineWidth=1}t.beginPath(),t.moveTo(i,s),t.lineTo(r,n),t.stroke(),t.lineWidth=1,t.setLineDash([])}}drawTexts(e){const{ctx:t,thinLineWidth:o}=e;let i;t.textBaseline="top";for(let e of this.boxes)if(e.content){const s=e.style||{},r=e.content.align||"left",n=qe(s);n!==i&&(i=n,t.font=n),t.fillStyle=s.textColor||"#000";let a=e.x;if(a+="left"===r?z+(e.image?e.image.size+V:0):"right"===r?e.width-z-(e.isFilterHeader?20:0):e.width/2,t.textAlign=r,e.clipRect){t.save(),t.beginPath();const{x:o,y:i,width:s,height:r}=e.clipRect;t.rect(o,i,s,r),t.clip()}const l=Ze(s),c=e.content.textLines.length;let h=this.computeTextYCoordinate(e,l,c);for(let i of e.content.textLines){if(t.fillText(i,Math.round(a),Math.round(h)),s.strikethrough||s.underline){const e=We(t,i,s);let n=a;"right"===r?n-=e:"center"===r&&(n-=e/2),s.strikethrough&&t.fillRect(n,h+l/2,e,2.6*o),s.underline&&t.fillRect(n,h+l+1,e,1.3*o)}h+=z+l}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const o=e.image.image;if(e.image.clipIcon){t.save(),t.beginPath();const{x:o,y:i,width:s,height:r}=e.image.clipIcon;t.rect(o,i,s,r),t.clip()}const i=e.image.size,s=this.computeTextYCoordinate(e,i);t.drawImage(o,e.x+V,s,i,i),e.image.clipIcon&&t.restore()}}computeTextYCoordinate(e,t,o=1){const i=e.y+1,s=$e(t,o),r=e.height>s+2*z,n=e.verticalAlign||j;if(r){if("middle"===n)return i+(e.height-s)/2;if("bottom"===n)return i+e.height-s-z}return i+z}drawHeaders(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getSheetViewVisibleCols(),s=i[0],r=i[i.length-1],n=this.getters.getSheetViewVisibleRows(),a=n[0],l=n[n.length-1],{width:c,height:h}=this.getters.getSheetViewDimensionWithHeaders(),d=this.getters.getSelectedZones(),u=function(e){const t=new Set;for(let o of e)for(let e of je(o.left,o.right+1))t.add(e);return t}(d),g=function(e){const t=new Set;for(let o of e)for(let e of je(o.top,o.bottom+1))t.add(e);return t}(d),p=this.getters.getActiveSheetId(),m=this.getters.getNumberCols(p),f=this.getters.getNumberRows(p),E=this.getters.getActiveCols(),w=this.getters.getActiveRows();t.font=`400 11px ${Z}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=o,t.strokeStyle="#333";for(let e=s;e<=r;e++){const o={left:e,right:e,top:0,bottom:f-1},{x:i,width:s}=this.getters.getVisibleRect(o),r=this.getters.doesZonesContainFilter(p,[o]),n=E.has(e),a=u.has(e);t.fillStyle=n?r?R:S:a?r?A:v:r?T:b,t.fillRect(i,0,s,_)}for(let e=a;e<=l;e++){const o={top:e,bottom:e,left:0,right:m-1},{y:i,height:s}=this.getters.getVisibleRect(o),r=this.getters.doesZonesContainFilter(p,[o]),n=w.has(e),a=g.has(e);t.fillStyle=n?r?R:S:a?r?A:v:r?T:b,t.fillRect(0,i,F,s)}t.beginPath(),t.moveTo(F,0),t.lineTo(F,h),t.moveTo(0,_),t.lineTo(c,_),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of i){const o=this.getters.getColSize(p,e),i=Pt(e);t.fillStyle=E.has(e)?"#fff":C;let r=this.getHeaderOffset("COL",s,e);t.fillText(i,r+o/2,13),t.moveTo(r+o,0),t.lineTo(r+o,_)}for(const e of n){const o=this.getters.getRowSize(p,e);t.fillStyle=w.has(e)?"#fff":C;let i=this.getHeaderOffset("ROW",a,e);t.fillText(String(e+1),24,i+o/2),t.moveTo(0,i+o),t.lineTo(F,i+o)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:s}=this.getters.getMainViewportCoordinates(),r=this.getters.isDashboard()?0:F,n=this.getters.isDashboard()?0:_;t.lineWidth=6*o,t.strokeStyle="#BCBCBC",t.beginPath(),i&&(t.moveTo(r+i,0),t.lineTo(r+i,n)),s&&(t.moveTo(0,n+s),t.lineTo(r,n+s)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:s}=this.getters.getMainViewportCoordinates(),r=this.getters.getSheetViewVisibleCols(),n=r[0],a=r[r.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:n,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:F,u=this.getters.isDashboard()?0:_;t.lineWidth=6*o,t.strokeStyle="#DADFE8",t.beginPath(),i&&(t.moveTo(d+i,u),t.lineTo(d+i,h.height+u)),s&&(t.moveTo(d,u+s),t.lineTo(h.width+d,u+s)),t.stroke()}findNextEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let s=e;for(;s<t;){const e={sheetId:i,col:s+1,row:o},t=this.getters.getEvaluatedCell(e),r=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==ms.empty||this.getters.isInMerge(e)||r?.left)return s;s++}return s}findPreviousEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let s=e;for(;s>t;){const e={sheetId:i,col:s-1,row:o},t=this.getters.getEvaluatedCell(e),r=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==ms.empty||this.getters.isInMerge(e)||r?.right)return s;s--}return s}computeCellAlignment(e,t){if(this.getters.getCell(e)?.isFormula&&this.getters.shouldShowFormulas())return"left";const{align:o}=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e);return t&&i.type===ms.number?"center"!==o?"left":o:o||i.defaultAlign}createZoneBox(e,t,o){const{left:i,right:s}=o,r=t.left,n=t.top,a={sheetId:e,col:r,row:n},c=this.getters.getEvaluatedCell(a),h=this.getters.shouldShowFormulas(),{x:d,y:u,width:g,height:p}=this.getters.getVisibleRect(t),{verticalAlign:m}=this.getters.getCellStyle(a),f={x:d,y:u,width:g,height:p,border:this.getters.getCellBorderWithFilterBorder(a)||void 0,style:this.getters.getCellComputedStyle(a),verticalAlign:m};if(c.type===ms.empty)return f;const b=this.getters.getConditionalIcon(a),v=Ze(f.style),S=b?V+v:0;b&&(f.image={type:"icon",size:v,clipIcon:{x:f.x,y:f.y,width:Math.min(S,g),height:p},image:Hm[b].img}),f.isFilterHeader=this.getters.isFilterHeader(a);const C=f.isFilterHeader?19:0,E=this.getters.getCellComputedStyle(a),w=E.wrapping||"overflow",x="wrap"!==w||h?void 0:g-2*z,y=this.getters.getCellMultiLineText(a,x),I=Math.max(...y.map((e=>this.getters.getTextWidth(e,E)+z))),R=S+I+C,T=this.computeCellAlignment(a,R>g);f.content={textLines:y,width:"overflow"===w?I:g,align:T},c.type===ms.error&&c.error.logLevel>l.silent&&(f.error=c.error.message);const A=R>g||v>p;if(b||f.isFilterHeader)f.clipRect={x:f.x+S,y:f.y,width:Math.max(0,g-S-C),height:p};else if(A&&"overflow"===w){let e,o;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,o=r):(e=this.findNextEmptyCol(r,s,n),o=this.findPreviousEmptyCol(r,i,n),f.isOverflow=!0),T){case"left":{const o=fi({col:e,row:n}),{x:i,y:s,width:r,height:a}=this.getters.getVisibleRect(oi(t,o));(r<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:r,height:a});break}case"right":{const e=fi({col:o,row:n}),{x:i,y:s,width:r,height:a}=this.getters.getVisibleRect(oi(t,e));(r<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:r,height:a});break}case"center":{const i={...t,left:o,right:e},{x:s,y:r,height:n,width:a}=this.getters.getVisibleRect(i),l=R/2,c=f.x+f.width/2;if(s+a<c+l||s>c-l||v>n||y.length>1){const e=s>c-l?s:c-l,t=s+a-e;f.clipRect={x:e,y:r,width:t,height:n}}break}}}else("clip"===w||"wrap"===w||y.length>1)&&(f.clipRect={x:f.x,y:f.y,width:g,height:p});return f}getGridBoxes(){const e=[],t=this.getters.getSheetViewVisibleCols(),o=t[0],i=t[t.length-1],s=this.getters.getSheetViewVisibleRows(),r={left:o,right:i,top:s[0],bottom:s[s.length-1]},n=this.getters.getActiveSheetId();for(const o of s)for(const i of t){const t={sheetId:n,col:i,row:o};this.getters.isInMerge(t)||e.push(this.createZoneBox(n,fi(t),r))}for(const t of this.getters.getMerges(n))if(!this.getters.isMergeHidden(n,t)&&ri(t,r)){const o=this.createZoneBox(n,t,r),i=this.getters.getCellBorder({sheetId:n,col:t.right,row:t.bottom});o.border={...o.border,bottom:i?i.bottom:void 0,right:i?i.right:void 0},o.isMerge=!0,e.push(o)}return e}}).add("autofill",class extends fC{static layers=[5];static getters=["getAutofillTooltip"];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case"AUTOFILL_SELECT":const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:He(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:He(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:45;case"AUTOFILL_AUTO":const o=this.getters.getSelectedZone();return o.top===o.bottom?0:1}return 0}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;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),o=this.autofillZone;switch(this.direction){case"down":for(let i=t.left;i<=t.right;i++){const s=[];for(let e=t.top;e<=t.bottom;e++)s.push(Ht(i,e));const r=this.createGenerator(s);for(let t=o.top;t<=o.bottom;t++)this.computeNewCell(r,i,t,e)}break;case"up":for(let i=t.left;i<=t.right;i++){const s=[];for(let e=t.bottom;e>=t.top;e--)s.push(Ht(i,e));const r=this.createGenerator(s);for(let t=o.bottom;t>=o.top;t--)this.computeNewCell(r,i,t,e)}break;case"left":for(let i=t.top;i<=t.bottom;i++){const s=[];for(let e=t.right;e>=t.left;e--)s.push(Ht(e,i));const r=this.createGenerator(s);for(let t=o.right;t>=o.left;t--)this.computeNewCell(r,t,i,e)}break;case"right":for(let i=t.top;i<=t.bottom;i++){const s=[];for(let e=t.left;e<=t.right;e++)s.push(Ht(e,i));const r=this.createGenerator(s);for(let t=o.left;t<=o.right;t++)this.computeNewCell(r,t,i,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const o=this.getters.getSelectedZone();if(ni(e,t,o))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,o.top-1,o.left,o.right),this.steps=o.top-t;break;case"down":this.saveZone(o.bottom+1,t,o.left,o.right),this.steps=t-o.bottom;break;case"left":this.saveZone(o.top,o.bottom,e,o.left-1),this.steps=o.left-e;break;case"right":this.saveZone(o.top,o.bottom,o.right+1,e),this.steps=e-o.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let o=e.left,i=e.bottom;if(o>0){let e=this.getters.getEvaluatedCell({sheetId:t,col:o-1,row:i});for(;e.type!==ms.empty;)i+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:o-1,row:i})}if(i===e.bottom&&(o=e.right,o<=this.getters.getNumberCols(t))){let e=this.getters.getEvaluatedCell({sheetId:t,col:o+1,row:i});for(;e.type!==ms.empty;)i+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:o+1,row:i})}i!==e.bottom&&(this.select(e.left,i-1),this.autofill(!0))}computeNewCell(e,t,o,i){const{cellData:s,tooltip:r,origin:n}=e.next(),{content:a,style:l,border:c,format:h}=s;this.tooltip=r,i&&this.dispatch("AUTOFILL_CELL",{originCol:n.col,originRow:n.row,col:t,row:o,content:a,style:l,border:c,format:h})}getRule(e,t){const o=Ps.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((o=>o.condition(e,t)));return o&&o.generateRule(e,t)}createGenerator(e){const t=[],o=[],i=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:s}=Bt(t),r=this.getters.getCell({sheetId:i,col:e,row:s});o.push({col:e,row:s,cell:r,sheetId:i})}const s=o.map((e=>e.cell));for(let e of o){let o={type:"COPY_MODIFIER"};if(e&&e.cell){o=this.getRule(e.cell,s)||o}const i=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:i},rule:o})}return new SC(t,this.getters,this.direction)}saveZone(e,t,o,i){this.autofillZone={top:e,bottom:t,left:o,right:i}}getDirection(e,t){const o=this.getters.getSelectedZone(),i={up:{number:o.top-t,value:"up"},down:{number:t-o.bottom,value:"down"},left:{number:o.left-e,value:"left"},right:{number:e-o.right,value:"right"}};if(1===Object.values(i).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(i).find((e=>e.number>0?1:0)).value;const s=i.up.number>0?"up":"down",r=i.left.number>0?"left":"right";return Math.abs(i[s].number)>=Math.abs(i[r].number)?i[s].value:i[r].value}autoFillMerge(e,t,o,i){const s=this.getters.getActiveSheetId(),r={sheetId:s,col:o,row:i},n={sheetId:s,col:e,row:t};if(this.getters.isInMerge(r)&&!this.getters.isInMerge(n)){const e=this.getters.getMerge(r);e&&this.dispatch("REMOVE_MERGE",{sheetId:s,target:[e]})}const a=this.getters.getMerge(n);a?.topLeft.col===e&&a?.topLeft.row===t&&this.dispatch("ADD_MERGE",{sheetId:s,target:[{top:i,bottom:i+a.bottom-a.top,left:o,right:o+a.right-a.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:o}=e,{x:i,y:s,width:r,height:n}=this.getters.getVisibleRect(this.autofillZone);r>0&&n>0&&(t.strokeStyle="black",t.lineWidth=o,t.setLineDash([3]),t.strokeRect(i,s,r,n),t.setLineDash([]))}}).add("find_and_replace",class extends fC{static layers=[3];static getters=["getSearchMatches","getCurrentSelectedMatchIndex"];searchMatches=[];selectedMatchIndex=null;currentSearchRegex=null;searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1};toSearch="";handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":case"UNDO":case"REDO":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(NC.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(NC.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith);break;case"ACTIVATE_SHEET":case"REFRESH_SEARCH":this.refreshSearch()}}getSearchMatches(){return this.searchMatches}getCurrentSelectedMatchIndex(){return this.selectedMatchIndex}updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.updateRegex(),this.refreshSearch()}refreshSearch(){const e=this.findMatches();this.searchMatches=e,this.selectNextCell(NC.current)}updateRegex(){let e=Ue(this.toSearch);const t=this.searchOptions.matchCase?"":"i";this.searchOptions.exactMatch&&(e=`^${e}$`),this.currentSearchRegex=RegExp(e,t)}findMatches(){const e=this.getters.getActiveSheetId(),t=this.getters.getCells(e),o=[];if(this.toSearch)for(const i of Object.values(t)){const{col:t,row:s}=this.getters.getCellPosition(i.id);if(i&&this.currentSearchRegex&&this.currentSearchRegex.test(this.getSearchableString({sheetId:e,col:t,row:s}))){const e={col:t,row:s,selected:!1};o.push(e)}}return o.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let o;o=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,o=(o%t.length+t.length)%t.length,this.selectedMatchIndex=o,this.selection.selectCell(t[o].col,t[o].row);for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1}}replace(e){if(null===this.selectedMatchIndex||!this.currentSearchRegex)return;const t=this.searchMatches[this.selectedMatchIndex],o=this.getters.getActiveSheetId();if(this.getters.getCell({sheetId:o,...t})?.isFormula&&!this.searchOptions.searchFormulas)this.selectNextCell(NC.next);else{const i=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),s=this.getSearchableString({sheetId:o,col:t.col,row:t.row}).replace(i,e);this.dispatch("UPDATE_CELL",{sheetId:this.getters.getActiveSheetId(),col:t.col,row:t.row,content:s}),this.searchMatches.splice(this.selectedMatchIndex,1),this.selectNextCell(NC.current)}}replaceAll(e){const t=this.searchMatches.length;for(let o=0;o<t;o++)this.replace(e)}getSearchableString(e){const t=this.getters.getCell(e);return this.searchOptions.searchFormulas&&t?.isFormula?t.content:this.getters.getEvaluatedCell(e).formattedValue}drawGrid(e){const{ctx:t}=e,o=this.getters.getActiveSheetId();for(const e of this.searchMatches){const i=this.getters.getMerge({sheetId:o,col:e.col,row:e.row}),s=i?i.left:e.col,r=i?i.right:e.col,n=i?i.top:e.row,a=i?i.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:n,left:s,right:r,bottom:a});h>0&&d>0&&(t.fillStyle="#8B008B33",t.fillRect(l,c,h,d),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(l,c,h,d)))}}}).add("sort",class extends fC{static getters=["getContiguousZone"];allowDispatch(e){if("SORT_CELLS"===e.type){if(!ni(e.col,e.row,e.zone))throw new Error(r("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;return ui(t).some((({col:t,row:o})=>!this.getters.isInMerge({sheetId:e,col:t,row:o})))?63:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const o=this.getters.getMerges(e).filter((e=>ri(e,t))),i=hi(o[0]);let[s,r]=[i.numberOfCols,i.numberOfRows];return o.every((e=>{let[t,o]=[e.right-e.left+1,e.bottom-e.top+1];return t===s&&o===r}))?0:63}expand(e,t){const{left:o,right:i,top:s,bottom:r}=this.getters.expandZone(e,t);return{left:Math.max(0,o),right:Math.min(this.getters.getNumberCols(e)-1,i),top:Math.max(0,s),bottom:Math.min(this.getters.getNumberRows(e)-1,r)}}checkExpandedValues(e,t){const o=this.expand(e,t);let i;if(this.getters.doesIntersectMerge(e,o)){const{left:t,right:s,top:r,bottom:n}=o;for(let o=t;o<=s;o++)for(let t=r;t<=n;t++){const{col:s,row:r}=this.getters.getMainCellPosition({sheetId:e,col:o,row:t});if(i=this.getters.getEvaluatedCell({sheetId:e,col:s,row:r}),i.formattedValue)return!0}}else for(let t of this.getters.getEvaluatedCellsInZone(e,o))if(t.formattedValue)return!0;return!1}getContiguousZone(e,t){let o,{top:i,bottom:s,left:r,right:n}=t,a=!1;for(;!a;)a=!0,i>0&&(o=this.checkExpandedValues(e,{left:r-1,right:n+1,top:i-1,bottom:i-1}),o&&(a=!1,i--)),r>0&&(o=this.checkExpandedValues(e,{left:r-1,right:r-1,top:i-1,bottom:s+1}),o&&(a=!1,r--)),n<this.getters.getNumberCols(e)-1&&(o=this.checkExpandedValues(e,{left:n+1,right:n+1,top:i-1,bottom:s+1}),o&&(a=!1,n++)),s<this.getters.getNumberRows(e)-1&&(o=this.checkExpandedValues(e,{left:r-1,right:n+1,top:s+1,bottom:s+1}),o&&(a=!1,s++));return{left:r,right:n,top:i,bottom:s}}hasHeader(e,t){if(1===t[0].length)return!1;let o=t.map((t=>t.map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).type))));return o[0][0]===ms.empty&&(o=o.slice(1)),!o.some((e=>e[0]===ms.empty))&&!!o.some((e=>e[1]!==ms.empty&&e[0]!==e[1]))}sortZone(e,t,o,i,s){const[r,n]=this.mainCellsSteps(e,o);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},o),c=this.mainCells(e,o);!s.sortHeaders&&this.hasHeader(e,c)&&(l.top+=n),c=this.mainCells(e,l);const h=function(e,t,o){const i=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));let s=i.filter((e=>e.type===ms.empty)),r=i.filter((e=>e.type!==ms.empty));o&&(r.push(...s.map((e=>({...e,type:ms.number,value:0})))),s=[]);const n="descending"===t?-1:1;return r.sort(((e,t)=>{let o=Wn.indexOf(e.type)-Wn.indexOf(t.type);return 0===o&&(o=e.type===ms.text||e.type===ms.error?e.value.localeCompare(t.value):e.value-t.value),n*o})).concat(s)}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),i,Boolean(s.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++){for(let t=0;t<g;t++){let{col:o,row:i,sheetId:s}=c[e][d[t]];const a=this.getters.getCell({sheetId:s,col:o,row:i});let h=l.left+e*r,u=l.top+t*n,g={sheetId:s,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=u-this.getters.getCellPosition(a.id).row,o=this.getters.createAdaptedRanges(a.dependencies,0,t,s);e=this.getters.buildFormulaContent(s,a,o)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}for(const e of p)this.dispatch("UPDATE_CELL",e)}}mainCellsSteps(e,t){const o=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[o?o.right-o.left+1:1,o?o.bottom-o.top+1:1]}mainCells(e,t){const[o,i]=this.mainCellsSteps(e,t),s=[],r=je(t.left,t.right+1,o),n=je(t.top,t.bottom+1,i);for(const t of r){const o=[];s.push(o);for(const i of n)o.push({sheetId:e,col:t,row:i})}return s}}).add("automatic_sum",class extends fC{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:o}=this.getters.getSelection();for(const i of t){const t=this.getAutomaticSums(e,i,o.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,o){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,o):this.sumData(e,t)}sumData(e,t){const o=this.dimensionsToSum(e,t),i=this.sumDimensions(e,t,o).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return o.has("ROW")&&o.has("COL")&&i.push(this.sumTotal(t)),i}sumAdjacentData(e,t,o){const{col:i,row:s}=ni(o.col,o.row,t)?o:{col:t.left,row:t.top},r=this.findAdjacentData(e,i,s);return r?this.getters.isSingleCellOrMerge(e,t)||di(oi(r,t))?[{position:{col:i,row:s},zone:r}]:this.sumDimensions(e,oi(r,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,o){const i=this.getters.getSheet(e),s=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),r=this.findSuitableZoneToSum(i,s.col,s.row);if(r)return this.getters.expandZone(e,r)}findSuitableZoneToSum(e,t,o){const i=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:o-1}),s=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:o});if(this.isNumber(s)&&!this.isNumber(i))return this.findHorizontalZone(e,t,o);const r=this.findVerticalZone(e,t,o);if(this.isZoneValid(r))return r;const n=this.findHorizontalZone(e,t,o);return this.isZoneValid(n)?n:void 0}findVerticalZone(e,t,o){const i={top:0,bottom:o-1,left:t,right:t},s=this.reduceZoneStart(e,i,i.bottom);return{...i,top:s}}findHorizontalZone(e,t,o){const i={top:o,bottom:o,left:0,right:t-1},s=this.reduceZoneStart(e,i,i.right);return{...i,left:s}}reduceZoneStart(e,t,o){const i=this.getters.getEvaluatedCellsInZone(e.id,t),s=je(o,-1,-1),r=s.filter((e=>i[e]&&!i[e].isAutoSummable)),n=Math.max(...r),a=Ye(s.filter((e=>this.isNumber(i[e]))))[0]||[];return Math.max(...a)<n?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===ms.number&&!(e.format&&bo(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){const o=new Set;return di(t)?(o.add(1===hi(t).numberOfCols?"COL":"ROW"),o):(this.lastColIsEmpty(e,t)&&o.add("ROW"),this.lastRowIsEmpty(e,t)&&o.add("COL"),0===o.size&&o.add("COL"),o)}sumDimensions(e,t,o){return[...o.has("COL")?this.sumColumns(t,e):[],...o.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:o}=e;return{position:{col:o,row:t},zone:{...e,top:t,right:o-1}}}sumColumns(e,t){const o=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,o.bottom-1)},ui(o).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const o=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,o.right-1)},ui(o).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const o of t){const{col:t,row:i}=o.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,content:`=SUM(${this.getters.zoneToXC(e,o.zone)})`})}}nextEmptyRow(e,t){let o=t.bottom+1;const{left:i,right:s}=t;for(;!this.getters.isEmpty(e,{bottom:o,top:o,left:i,right:s});)o++;return{...t,top:o,bottom:o}}nextEmptyCol(e,t){let o=t.right+1;const{top:i,bottom:s}=t;for(;!this.getters.isEmpty(e,{left:o,right:o,top:i,bottom:s});)o++;return{...t,left:o,right:o}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}).add("format",class extends fC{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,o){for(const i of t)for(const t of ui(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const s=Io(i,o);this.dispatch("SET_FORMATTING",{sheetId:e,target:[fi(t)],format:s})}}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==ms.number||e.format&&bo(e.format)))return e.format||wo(e.value)}}}).add("split_to_columns",class extends fC{static getters=["getAutomaticSeparator"];allowDispatch(e){return"SPLIT_TEXT_INTO_COLUMNS"===e.type?this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e):0}handle(e){if("SPLIT_TEXT_INTO_COLUMNS"===e.type)this.splitIntoColumns(e)}getAutomaticSeparator(){const e=this.getters.getSelectedCells();for(const t of e)if(t.value&&t.type===ms.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[pe,";",","," ","."];for(const o of t)if(e.includes(o))return o}splitIntoColumns({separator:e,addNewColumns:t}){const o=this.getters.getSelectedZone(),i=this.getters.getActiveSheetId(),s=this.getSplittedCols(o,e);t&&this.addColsToAvoidCollisions(o,s),this.removeMergesInSplitZone(o,s),this.addColumnsToNotOverflowSheet(o,s);for(let e=0;e<s.length;e++){const t=o.top+e,r=s[e],n=o.left,a=this.getters.getCell({sheetId:i,col:n,row:t});if(1!==r.length||r[0]!==a?.content)for(const[e,o]of r.entries())this.dispatch("UPDATE_CELL",{sheetId:i,col:n+e,row:t,content:o,format:"",style:a?.style||null})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const o=this.getters.getActiveSheetId(),i=[];for(const s of je(e.top,e.bottom+1)){const r=this.getters.getEvaluatedCell({sheetId:o,col:e.left,row:s}).formattedValue;i.push(this.splitAndRemoveTrailingEmpty(r,t))}return i}splitAndRemoveTrailingEmpty(e,t){const o=e.split(t);for(;o.length>1&&""===o[o.length-1];)o.pop();return o}willSplittedColsOverwriteContent(e,t){const o=this.getters.getActiveSheetId();for(const i of je(e.top,e.bottom+1)){const s=t[i-e.top];for(let t=1;t<s.length;t++){const s=this.getters.getCell({sheetId:o,col:e.left+t,row:i});if(s&&s.content)return!0}}return!1}removeMergesInSplitZone(e,t){const o=this.getters.getActiveSheetId(),i=Math.max(...t.map((e=>e.length))),s={...e,right:e.left+i-1},r=this.getters.getMergesInZone(o,s);this.dispatch("REMOVE_MERGE",{sheetId:o,target:r})}addColsToAvoidCollisions(e,t){const o=this.getters.getActiveSheetId();let i=0;for(const s of je(e.top,e.bottom+1)){const r={sheetId:o,col:e.left,row:s},n=t[s-e.top],a=this.getColsToAddToAvoidCollision(r,n);i=Math.max(i,a)}i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:o,quantity:i,position:"after"})}getColsToAddToAvoidCollision(e,t){const o=t.length;for(let t=1;t<o;t++){const i=e.col+t,s=this.getters.getCell({...e,col:i});if(s&&s.content)return o-t}return 0}addColumnsToNotOverflowSheet(e,t){const o=this.getters.getActiveSheetId(),i=Math.max(...t.map((e=>e.length-1))),s=this.getters.getNumberCols(o)-1;e.left+i>s&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:s,sheetId:o,quantity:e.left+i-s,position:"after"})}checkSingleColSelected(){return this.getters.isSingleColSelected()?0:88}checkNonEmptySelector(e){return""===e.separator?89:0}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return 0;const t=this.getters.getSelectedZones()[0],o=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,o)?90:0}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const o of t)if(o.formattedValue.includes(e))return 0;return 91}}).add("cell_popovers",class extends fC{static getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];persistentPopover;allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{yr.get(e.popoverType)}catch(e){return 72}return 0}return 0}handle(e){switch(e.type){case"ACTIVATE_SHEET":case"CLOSE_CELL_POPOVER":this.persistentPopover=void 0;break;case"OPEN_CELL_POPOVER":this.persistentPopover={col:e.col,row:e.row,sheetId:this.getters.getActiveSheetId(),type:e.popoverType}}}getCellPopover({col:e,row:t}){const o=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=yr.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport({sheetId:o,col:e,row:t}))return{isOpen:!1};const i=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}),s=yr.getAll().map((e=>e.onHover?.(i,this.getters))).find((e=>e?.isOpen));return s?.isOpen?{...s,anchorRect:this.computePopoverAnchorRect(i)}:{isOpen:!1}}hasOpenedPopover(){return void 0!==this.persistentPopover}getPersistentPopoverTypeAtPosition({col:e,row:t}){if(this.persistentPopover&&this.persistentPopover.col===e&&this.persistentPopover.row===t)return this.persistentPopover.type}computePopoverAnchorRect({col:e,row:t}){const o=this.getters.getActiveSheetId(),i=this.getters.getMerge({sheetId:o,col:e,row:t});return i?this.getters.getVisibleRect(i):this.getters.getVisibleRect(fi({col:e,row:t}))}}).add("collaborative",class extends fC{static getters=["getClientsToDisplay","getClient","getConnectedClients","isFullySynchronized"];static layers=[6];availableColors=new Set(MC);colors={};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)}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(MC));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClient(){return this.session.getClient()}getConnectedClients(){return this.session.getConnectedClients()}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof AC)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const o of this.getters.getConnectedClients())if(o.id!==this.getters.getClient().id&&o.position&&o.position.sheetId===e&&this.isPositionValid(o.position)){const e=o.position;this.colors[o.id]||(this.colors[o.id]=this.chooseNewColor());const i=this.colors[o.id];t.push({...o,position:e,color:i})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:s,col:r}=e.position,n=this.getters.expandZone(i,{top:s,bottom:s,left:r,right:r}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(n);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*o,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${q+1}px ${Z}`}}}).add("history",class extends fC{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("pending-revisions-dropped",this,(({revisionIds:e})=>this.drop(e))),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return 6;break;case"REQUEST_REDO":if(!this.canRedo())return 7}return 0}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();if(t)"UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t));else{const e=this.getPossibleRevisionToRepeat();if(!e)return;const t=$C(e,this.getters);if(!t)return;if(!Array.isArray(t))return void this.dispatch(t.type,t);for(const e of t)this.dispatch(e.type,e)}}canUndo(){return this.undoStack.length>0}canRedo(){if(this.redoStack.length>0)return!0;const e=this.getPossibleRevisionToRepeat();return!(!(t=e)||!t.rootCommand||"object"!=typeof t.rootCommand)&&(Es(t.rootCommand)?VC.contains(t.rootCommand.type):zC.contains(t.rootCommand.type));var t}drop(e){this.undoStack=this.undoStack.filter((t=>!e.includes(t))),this.redoStack=[]}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision(["REQUEST_REDO"])}}),iE=(new _i).add("selection",class extends fC{static layers=[6];static getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSelected","isSingleColSelected","getElementsFromSelection"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 27}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handleEvent(e){const t=e.anchor;let o=[];switch(e.mode){case"overrideSelection":o=[t.zone];break;case"updateAnchor":o=[...this.gridSelection.zones];const i=o.findIndex((t=>si(t,e.previousAnchor.zone)));i>=0&&(o[i]=t.zone);break;case"newAnchor":o=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,o),this.selection.resetDefaultAnchor(this,Ve(this.gridSelection.anchor));const{col:i,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:i,row:s}),this.selectedFigureId=null}handle(e){switch(e.type){case"START_EDITION":case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.dispatch("ACTIVATE_SHEET",{sheetIdTo:t,sheetIdFrom:t});const{col:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(o,i),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":if(this.getters.isSheetVisible(e.sheetIdTo)||this.dispatch("SHOW_SHEET",{sheetId:e.sheetIdTo}),this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={gridSelection:Ve(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Ve(this.gridSelection.anchor));else{const{col:t,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0});this.selectCell(t,o)}break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const s=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of s)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Ve(t)}}if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:o})}const r=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(r,e))),this.gridSelection.anchor.zone=this.getters.expandZone(r,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones)}this.selection.resetDefaultAnchor(this,Ve(this.gridSelection.anchor))}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(let t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let o=t.left;o<=t.right;o++)e.add(o);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let o of this.gridSelection.zones)if(0===o.left&&o.right===this.getters.getNumberCols(t)-1)for(let t=o.top;t<=o.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return Ve(this.gridSelection.zones)}getSelectedZone(){return Ve(this.gridSelection.anchor.zone)}getSelection(){return Ve(this.gridSelection)}getSelectedCells(){const e=this.getters.getActiveSheetId(),t=[];for(const o of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,o));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}getStatisticFnResults(){const e=new Set(this.gridSelection.zones.map((e=>this.getters.getEvaluatedCellsInZone(this.getters.getActiveSheetId(),e))).flat().filter((e=>e.type!==ms.empty)));let t=new Set,o=[];for(let i of e)t.add(i.type),o.push(i.value);let i={};for(let e of eE){let s;e.types.some((e=>t.has(e)))&&(s=e.compute(o)),i[e.name]=s}return i}getAggregate(){let e=0,t=0;const o=this.getters.getActiveSheetId(),i=this.gridSelection.zones.map(ui).flat();for(const{col:s,row:r}of i){const i=this.getters.getEvaluatedCell({sheetId:o,col:s,row:r});i.type===ms.number&&(t++,e+=i.value)}return t<2?null:uo(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>si(t,e)))}isSingleColSelected(){const e=this.getters.getSelectedZones();return 1===e.length&&e[0].left===e[0].right}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let o=[];const i="COL"===e?"left":"top",s="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[s]-e[i]+1},((t,o)=>e[i]+o));o=o.concat(t)}return[...new Set(o)].sort()}setSelectionMixin(e,t){const{anchor:o,zones:i}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=o,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,o)=>t===o.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(i)}selectCell(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.expandZone(o,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:i,cell:{col:e,row:t}},[i])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),o=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[o]})}onColumnsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=ei(o,"left",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=ei(s,"left",[...e.elements]);const r={cell:{col:s.left,row:s.top},zone:i},n=this.gridSelection.zones.map((t=>ei(t,"left",[...e.elements])));this.setSelectionMixin(r,n)}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=ei(o,"top",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=ei(s,"top",[...e.elements]);const r={cell:{col:s.left,row:s.top},zone:i},n=this.gridSelection.zones.map((t=>ei(t,"top",[...e.elements])));this.setSelectionMixin(r,n)}onAddElements(e){const t="COL"===e.dimension?"left":"top",o=Jo(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),i=this.gridSelection.zones.map((o=>Jo(o,t,e.base,e.position,e.quantity))),s={cell:{col:o.left,row:o.top},zone:o};this.setSelectionMixin(s,i)}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:"before"});const o="COL"===e.dimension,i=e.elements[0],s=e.elements[t-1],r=e.base<i,n=r&&o?t:0,a=r&&!o?t:0;this.dispatch("CUT",{target:[{left:o?i+n:0,right:o?s+n:this.getters.getNumberCols(e.sheetId)-1,top:o?0:i+a,bottom:o?this.getters.getNumberRows(e.sheetId)-1:s+a}]}),this.dispatch("PASTE",{target:[{left:o?e.base:0,right:o?e.base+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:e.base,bottom:o?this.getters.getNumberRows(e.sheetId)-1:e.base+t-1}]});const l=r?e.elements.map((e=>e+t)):e.elements;let c=e.base;for(const t of l){const o="COL"===e.dimension?this.getters.getColSize(e.sheetId,t):this.getters.getRowSize(e.sheetId,t);this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:o,elements:[c]}),c+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:l})}isMoveElementAllowed(e){const t="COL"===e.dimension,o=e.elements[0],i=e.elements[e.elements.length-1],s=e.sheetId,r=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return r(s,o-1,o)||r(s,i,i+1)||r(s,e.base-1,e.base)?2:0}clipSelection(e,t){const o=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:He(e.left,0,o),right:He(e.right,0,o),top:He(e.top,0,i),bottom:He(e.bottom,0,i)}))),anchor:{cell:{col:He(t.anchor.cell.col,0,o),row:He(t.anchor.cell.row,0,i)},zone:{left:He(t.anchor.zone.left,0,o),right:He(t.anchor.zone.right,0,o),top:He(t.anchor.zone.top,0,i),bottom:He(t.anchor.zone.bottom,0,i)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getSelectedZones();t.fillStyle="#f3f7fe";const s=1===i.length&&i[0].left===i[0].right&&i[0].top===i[0].bottom;t.fillStyle=s?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*o;for(const e of i){const{x:o,y:i,width:s,height:r}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(o,i,s,r),t.globalCompositeOperation="source-over",t.strokeRect(o,i,s,r)}t.globalCompositeOperation="source-over";const r=this.getActivePosition();let n;t.strokeStyle=E,t.lineWidth=3*o,n=this.getters.isInMerge(r)?this.getters.getMerge(r):fi(r);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(n);c>0&&h>0&&t.strokeRect(a,l,c,h)}}).add("clipboard",class extends fC{static layers=[2];static getters=["getClipboardContent","getClipboardTextContent","isCutOperation","isPaintingFormat"];status="invisible";state;lastPasteState;_isPaintingFormat=!1;allowDispatch(e){switch(e.type){case"CUT":const t=e.target||this.getters.getSelectedZones();return this.getClipboardState(t,e.type).isCutAllowed(t);case"PASTE":if(!this.state)return 23;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:o});case"PASTE_FROM_OS_CLIPBOARD":return new YC(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}}return 0}handle(e){switch(e.type){case"COPY":case"CUT":const t="target"in e&&e.target||this.getters.getSelectedZones();this.state=this.getClipboardState(t,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:o,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.lastPasteState=this.state,this.status="invisible";break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Xo(t[0])){for(const{col:t,row:o}of ui(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:o,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==this.state?.operation)return;this.state.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==this.state?.operation)return;for(let t of e.elements){if(this.state.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":this.state=new YC(e.text,this.getters,this.dispatch,this.selection),this.state.paste(e.target),this.lastPasteState=this.state,this.status="invisible";break;case"REPEAT_PASTE":this.lastPasteState?.paste(e.target,{pasteOption:e.pasteOption,shouldPasteCF:!0,selectTarget:!0});break;case"ACTIVATE_PAINT_FORMAT":{const e=this.getters.getSelectedZones();this.state=this.getClipboardStateForCopyCells(e,"COPY"),this._isPaintingFormat=!0,this.status="visible";break}default:Es(e)&&(this.status="invisible")}}getClipboardContent(){return this.state?.getClipboardContent()||{[fs.PlainText]:"\t"}}getClipboardTextContent(){return this.state?.getClipboardContent()[fs.PlainText]||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i;return i="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(o)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1},{cut:[i],paste:[e]}}getInsertCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i,s;return"COL"===t?(i={...e,right:this.getters.getNumberCols(o)-1},s={...e,left:e.right+1,right:e.right+1}):(i={...e,bottom:this.getters.getNumberRows(o)-1},s={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1}),{cut:[i],paste:[s]}}getClipboardStateForCopyCells(e,t){return new GC(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new qC(t,this.getters,this.dispatch):new GC(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}).add("edition",class extends fC{static getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights","getCurrentEditedCell"];col=0;row=0;mode="inactive";sheetId="";currentContent="";currentTokens=[];selectionStart=0;selectionEnd=0;selectionInitialStart=0;initialContent="";previousRef="";previousRange=void 0;colorIndexByRange={};allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=e.text||this.getComposerContent(this.getters.getActivePosition());return this.validateSelection(t.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handleEvent(e){if("selecting"===this.mode)if("newAnchor"===e.mode)this.insertSelectedRange(e.anchor.zone);else this.replaceSelectedRanges(e.anchor.zone)}handle(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":this.selectionStart=e.start,this.selectionEnd=e.end;break;case"STOP_COMPOSER_RANGE_SELECTION":this.isSelectingForComposer()&&(this.mode="editing");break;case"START_EDITION":"inactive"!==this.mode&&e.text?this.setContent(e.text,e.selection):this.startEdition(e.text,e.selection),this.updateRangeColor();break;case"STOP_EDITION":e.cancel?(this.cancelEditionAndActivateSheet(),this.resetContent()):this.stopEdition(),this.colorIndexByRange={};break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0),this.updateRangeColor();break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEditionAndActivateSheet(),this.resetContent();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.getters.getRangeFromRangeData(e.range),o=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:o,sheetName:i}=Bo(e.value),s=i||this.getters.getSheetName(this.sheetId),r=this.getters.getActiveSheetId();if(this.getters.getSheetName(r)!==s)return!1;const n=this.getters.getRangeFromSheetXC(r,o);return si(this.getters.expandZone(r,n.zone),t.zone)}));this.previousRef=o.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=o.start;break;case"CHANGE_HIGHLIGHT":const i=this.getters.getRangeFromRangeData(e.range),s=this.getRangeReference(i,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(s),this.previousRef=s,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"ACTIVATE_SHEET":if(this.currentContent.startsWith("=")||(this.cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),s=this.getters.expandZone(e.sheetIdTo,fi({col:o,row:i}));this.selection.resetAnchor(this,{cell:{col:o,row:i},zone:s})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.mode||(this.sheetId=this.getters.getActiveSheetId(),this.cancelEditionAndActivateSheet(),this.resetContent(),this.ui.notifyUI({type:"ERROR",text:JC}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}getEditionMode(){return this.mode}getCurrentContent(){return"inactive"===this.mode?this.getComposerContent(this.getters.getActivePosition()):this.currentContent}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}getCurrentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}isSelectingForComposer(){return"selecting"===this.mode}showSelectionIndicator(){return this.isSelectingForComposer()&&this.canStartComposerRangeSelection()}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((o=>o.start<=e&&o.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const o=e.map(XC).map((e=>e.value)).join(""),i=this.currentContent,s=e[0].start,r=e[e.length-1].end,n=i.slice(0,s)+o+i.slice(r),a=n.length-i.length,l={start:t[0].start,end:t[t.length-1].end+a};1===t.length&&this.selectionStart===this.selectionEnd&&(l.start=l.end),this.dispatch("SET_CURRENT_CONTENT",{content:n,selection:l})}validateSelection(e,t,o){return t>=0&&t<=e&&o>=0&&o<=e?0:46}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:JC});const{top:t,left:o}=ei({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=o,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:JC});const{top:t,left:o}=ei({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=o,this.row=t}onAddElements(e){const{top:t,left:o}=Jo({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=o,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=fi({col:this.col,row:this.row});this.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.mode="selecting",this.selectionInitialStart=this.selectionStart}startEdition(e,t){const o=this.getters.getActiveCell();e&&o.format?.includes("%")&&Jt(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:i,row:s,sheetId:r}=this.getters.getActivePosition();this.col=i,this.sheetId=r,this.row=s,this.initialContent=this.getComposerContent({sheetId:r,col:i,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const n=fi({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:n},{handleEvent:this.handleEvent.bind(this),release:()=>{this.stopEdition()}})}stopEdition(){if("inactive"!==this.mode){this.cancelEditionAndActivateSheet();const e=this.col,t=this.row;let o=this.currentContent;if(!(this.initialContent!==o))return;if(o){const i=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCell({sheetId:i,col:this.col,row:this.row});if(o.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,i=e-t;i>0&&(o+=dt(new Array(i).fill(")")))}else s.link&&(o=ot(o,s.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:e,row:t,content:o})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,content:"",col:e,row:t});this.setContent("")}}cancelEditionAndActivateSheet(){if("inactive"===this.mode)return;this.cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}getComposerContent(e){const t=this.getters.getCell(e);if(t?.isFormula)return t.content;const{format:o,value:i,type:s,formattedValue:r}=this.getters.getEvaluatedCell(e);switch(s){case ms.text:case ms.empty:return i;case ms.boolean:return r;case ms.error:return t?.content||"";case ms.number:return o&&bo(o)?r:this.numberComposerContent(i,o)}}numberComposerContent(e,t){return t?.includes("%")?100*e+"%":function(e){const{integerDigits:t,decimalDigits:o}=mo(e,20);return o?`${t}.${o}`:t}(e)}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,o){const i=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(i||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Gv(e):[],this.currentTokens.length>100&&o&&this.ui.notifyUI({type:"ERROR",text:r("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),o=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(o,t),this.selectionInitialStart=t):(this.insertText(","+o,t),this.selectionInitialStart=t+1)}replaceSelectedRanges(e){const t=this.getZoneReference(e);this.replaceText(t,this.selectionInitialStart,this.selectionEnd)}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const o=this.getters.getActiveSheetId();let i=this.getters.zoneToXC(o,e,t);if(this.getters.getCurrentEditedCell().sheetId!==this.getters.getActiveSheetId()){i=`${Be(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${i}`}return i}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){let o=[...t];1===t.length&&vi(e.zone)>1?o.push({...t[0]}):2===t.length&&1===vi(e.zone)&&o.pop();const i=e.clone({parts:o});return this.getters.getSelectionRangeString(i,this.getters.getCurrentEditedCell().sheetId)}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),o=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,o)}replaceText(e,t,o){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(o,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const o=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),i=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:o,selection:{start:i,end:i}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getCurrentEditedCell().sheetId,t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),o={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(o[e]=this.colorIndexByRange[e]);const i=new Set(Object.values(o));let s=0;const r=()=>{for(;i.has(s);)s++;return i.add(s),s};for(const e of t){const t=e in o?o[e]:r();o[e]=t}this.colorIndexByRange=o}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getCurrentEditedCell().sheetId,t=e=>{const t=this.colorIndexByRange[e];return It[t%It.length]};return this.getReferencedRanges().map((o=>{const i=this.getters.getRangeString(o,e);return{zone:o.zone,color:t(i),sheetId:o.sheetId}}))}getReferencedRanges(){const e=this.getters.getCurrentEditedCell().sheetId;return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value)))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let o=t,i=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(i.type)||rv.includes(i.value);){if("SPACE"!==i.type||o<1)return!1;o--,i=this.currentTokens[o]}for(o=t+1,i=this.currentTokens[o];i&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(i.type);){if("SPACE"!==i.type)return!1;o++,i=this.currentTokens[o]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((o=>o.start<=e&&o.end>=e||o.start>=e&&o.start<t))}}),sE=(new _i).add("evaluation",class extends fC{static getters=["evaluateFormula","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getColEvaluatedCells","getEvaluatedCellsInZone"];isUpToDate=!1;evaluatedCells={};evalContext;lazyEvaluation;constructor(e){super(e),this.evalContext=e.custom,this.lazyEvaluation=e.lazyEvaluation}handle(e){switch(bs.has(e.type)&&(this.isUpToDate=!1),e.type){case"UPDATE_CELL":("content"in e||"format"in e)&&(this.isUpToDate=!1);break;case"EVALUATE_CELLS":this.evaluate()}}finalize(){this.isUpToDate||(this.evaluate(),this.isUpToDate=!0)}evaluateFormula(e,t=this.getters.getActiveSheetId()){const o=Wv(e),i=this.getCompilationParameters((e=>this.getEvaluatedCell(this.getters.getCellPosition(e.id)))),s=[];for(let e of o.dependencies)s.push(this.getters.getRangeFromSheetXC(t,e));return o.execute(s,...i).value}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.formattedValue))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.value))}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.format))}getEvaluatedCell({sheetId:e,col:t,row:o}){return void 0===this.getters.getCell({sheetId:e,col:t,row:o})?Os(""):this.evaluatedCells[e]?.[t]?.[o]?.()||Os("")}getEvaluatedCells(e){const t=this.getters.getCells(e)||{},o={};for(let e of Object.keys(t)){const t=this.getters.getCellPosition(e);o[e]=this.getEvaluatedCell(t)}return o}getColEvaluatedCells(e,t){return Object.values(this.evaluatedCells[e]?.[t]||[]).filter(lt).map((e=>e()))}getEvaluatedCellsInZone(e,t){return ui(t).map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o})))}setEvaluatedCell(e,t){const{col:o,row:i,sheetId:s}=this.getters.getCellPosition(e);this.evaluatedCells[s]||(this.evaluatedCells[s]={}),this.evaluatedCells[s][o]||(this.evaluatedCells[s][o]={}),this.evaluatedCells[s][o][i]=t,this.lazyEvaluation||this.evaluatedCells[s][o][i]()}*getAllCells(){for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t)yield t[e]}}evaluate(){this.evaluatedCells={};const e=new Set,t=e=>{const t=e.id,{col:s,row:r,sheetId:n}=this.getters.getCellPosition(t),a=this.evaluatedCells[n]?.[s]?.[r];return a||ut((()=>{try{switch(e.isFormula){case!0:return i(e);case!1:return Ts(e.content,e.format)}}catch(t){return o(t,e)}}))},o=(e,t)=>{e instanceof Error||(e=new Error(e));const o=e?.errorType||a.GenericError,i=s[2].__lastFnCalled||"",r=new c(o,e.message.replace("[[FUNCTION_NAME]]",i),void 0!==e.logLevel?e.logLevel:l.error);return Fs(t.content,r)},i=t=>{const o=t.id;if(e.has(o))throw new d;s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(o);return Ht(e.col,e.row)},e.add(o);const i=t.compiledFormula.execute(t.dependencies,...s);if(e.delete(o),Array.isArray(i.value))throw new Error(r("This formula depends on invalid values"));return Os(i.value,t.format||i.format)},s=this.getCompilationParameters((e=>t(e)()));for(const e of this.getAllCells())this.setEvaluatedCell(e.id,t(e))}getCompilationParameters(e){const t=Object.assign(Object.create(bC),this.evalContext,{getters:this.getters}),o=this.getters;const i=t=>{const o=e(t);if(o.type===ms.error)throw o.error;return o};return[function(e,t,s,n){if(t)return{value:Ko(e.zone)};if(!Xo(e.zone))throw new u;if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(n?r("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",s.toString(),n.toString()):r("Function %s expects its parameters to be single values or single cell references, not ranges.",s.toString()));if(e.invalidSheetName)throw new Error(r("Invalid sheet name: %s",e.invalidSheetName));return function(e){let t;if(!o.tryGetSheet(e.sheetId))throw new Error(r("Invalid sheet name"));return t=o.getCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}),t&&""!==t.content?i(t):{value:null,format:t?.format}}(e)},function(e){const s=e.sheetId;if(!Xo(e.zone))throw new u;const r=o.getSheetZone(s),n=[],a=ii(e.zone,r);if(!a)return n.push([]),n;for(let o=a.left;o<=a.right;o++){const s=[];for(let r=a.top;r<=a.bottom;r++){const n=t.getters.getCell({sheetId:e.sheetId,col:o,row:r});s.push(n?i(n):void 0)}n.push(s)}return n},t]}exportForExcel(e){for(let t of e.sheets)for(const e in t.cells){const o={sheetId:t.id,...Bt(e)},i=this.getters.getCell(o);if(i){const s=t.cells[e],r=this.getEvaluatedCell(o);s.value=r.value,s.isFormula=i.isFormula&&!this.isBadExpression(i.content),i.format!==r.format&&(s.computedFormat=r.format)}}}isBadExpression(e){try{return Wv(e),!1}catch(e){return!0}}}).add("evaluation_filter",class extends fC{static getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];filterValues={};hiddenRows=new Set;isEvaluationDirty=!1;allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return 79;return 0}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_FILTER_TABLE":this.isEvaluationDirty=!0;break;case"START":for(const e of this.getters.getSheetIds()){this.filterValues[e]={};for(const t of this.getters.getFilters(e))this.filterValues[e][t.id]=[]}break;case"CREATE_SHEET":this.filterValues[e.sheetId]={};break;case"HIDE_COLUMNS_ROWS":this.updateHiddenRows();break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows();break;case"DUPLICATE_SHEET":const t={};for(const o of this.getters.getFilters(e.sheetIdTo)){const i=o.zoneWithHeaders;t[o.id]=this.getFilterValues({sheetId:e.sheetId,col:i.left,row:i.top})}this.filterValues[e.sheetIdTo]=t}}finalize(){this.isEvaluationDirty&&(this.updateHiddenRows(),this.isEvaluationDirty=!1)}isRowFiltered(e,t){return e===this.getters.getActiveSheetId()&&this.hiddenRows.has(t)}getCellBorderWithFilterBorder(e){const{sheetId:t,col:o,row:i}=e;let s;for(let e of this.getters.getFilterTables(t)){const r=e.zone;if(ni(o,i,r)){const e=this.intersectZoneWithViewport(t,r);s={top:i===e.top?K:void 0,bottom:i===e.bottom?K:void 0,left:o===e.left?K:void 0,right:o===e.right?K:void 0}}}const r=this.getters.getCellBorder(e),n={...s,...ft(r||{})};return ct(n)?null:n}getFilterHeaders(e){const t=[];for(let o of this.getters.getFilterTables(e)){const i=o.zone;if(!i)continue;const s=i.top;for(let o=i.left;o<=i.right;o++)this.getters.isColHidden(e,o)||this.getters.isRowHidden(e,s)||t.push({col:o,row:s})}return t}getFilterValues(e){const t=this.getters.getFilterId(e),o=e.sheetId;return t&&this.filterValues[o]&&this.filterValues[o][t]||[]}isFilterHeader({sheetId:e,col:t,row:o}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===o))}isFilterActive(e){const t=this.getters.getFilterId(e),o=e.sheetId;return Boolean(t&&this.filterValues[o]?.[t]?.length)}intersectZoneWithViewport(e,t){return{left:this.getters.findVisibleHeader(e,"COL",t.left,t.right),right:this.getters.findVisibleHeader(e,"COL",t.right,t.left),top:this.getters.findVisibleHeader(e,"ROW",t.top,t.bottom),bottom:this.getters.findVisibleHeader(e,"ROW",t.bottom,t.top)}}updateFilter({col:e,row:t,values:o,sheetId:i}){const s=this.getters.getFilterId({sheetId:i,col:e,row:t});s&&(this.filterValues[i]||(this.filterValues[i]={}),this.filterValues[i][s]=o)}updateHiddenRows(){const e=this.getters.getActiveSheetId(),t=this.getters.getFilters(e).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),o=new Set;for(let i of t){if(this.getters.isRowHiddenByUser(e,i.zoneWithHeaders.top))continue;if(o.has(i.zoneWithHeaders.top))continue;const t=this.filterValues[e]?.[i.id]?.map(bt);if(t&&i.filteredZone)for(let s=i.filteredZone.top;s<=i.filteredZone.bottom;s++){const r=this.getCellValueAsString(e,i.col,s);t.includes(r)&&o.add(s)}}this.hiddenRows=o}getCellValueAsString(e,t,o){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets)for(const e of t.filterTables){const o=Yo(e.range),i=[],s=[];for(const e of je(0,hi(o).numberOfCols)){const r={sheetId:t.id,col:o.left+e,row:o.top},n=this.getFilterValues(r),a=this.getters.getFilter(r);if(!a)continue;const l=(a.filteredZone?ui(a.filteredZone).map((({col:e,row:o})=>this.getters.getEvaluatedCell({sheetId:t.id,col:e,row:o}))).filter((e=>e.type!==ms.empty)).map((e=>e.formattedValue)):[]).filter((e=>!n.includes(e)));i.push({colId:e,filteredValues:[...new Set(l)]});const c={col:a.col,row:a.zoneWithHeaders.top,sheetId:t.id},h=this.getters.getEvaluatedCell(c).formattedValue,d=this.getUniqueColNameForExcel(e,h,s);s.push(d),t.cells[Ht(c.col,c.row)]={...t.cells[Ht(c.col,c.row)],content:d,value:d,isFormula:!1}}e.filters=i}}getUniqueColNameForExcel(e,t,o){t||(t=`Column${e}`);let i=t,s=2;for(;o.includes(i);)i=t+String(s),s++;return i}}).add("evaluation_chart",class extends fC{static getters=["getChartRuntime","getBackgroundOfSingleCellChart"];charts={};createRuntimeChart=function(e){const t=On.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(o){const i=t.find((e=>e.match(o.type)));if(!i)throw new Error("No runtime builder for this chart.");return i.getChartRuntime(o,e)}}(this.getters);handle(e){if(bs.has(e.type)||vs.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type)for(const e in this.charts)this.charts[e]=void 0;switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":case"DELETE_FIGURE":this.charts[e.id]=void 0;break;case"DELETE_SHEET":for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0)}}getChartRuntime(e){if(!this.charts[e]){const t=this.getters.getChart(e);if(!t)throw new Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getBackgroundOfSingleCellChart(e,t){if(e)return e;if(!t)return w;const o=t.zone.left,i=t.zone.top,s=t.sheetId;return this.getters.getCellComputedStyle({sheetId:s,col:o,row:i}).fillColor||w}}).add("evaluation_cf",class extends fC{static getters=["getConditionalIcon","getCellComputedStyle"];isStale=!0;computedStyles={};computedIcons={};handle(e){switch((vs.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isStale=!0),e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const o=this.getters.getActiveSheetId(),i=this.getters.getRulesByCell(o,e.originCol,e.originRow);for(const t of i)this.adaptRules(o,t,[Ht(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e){const{sheetId:t,col:o,row:i}=e,s=this.getters.getCell(e),r=this.computedStyles[t],n=r&&r[o]?.[i],a={...s?.style,...n};return this.getters.getEvaluatedCell(e).link&&!a.textColor&&(a.textColor=I),this.getters.isFilterHeader(e)&&(a.bold=!0),a}getConditionalIcon({col:e,row:t}){const o=this.getters.getActiveSheetId(),i=this.computedIcons[o];return i&&i[e]?.[t]}computeStyles(){const e=this.getters.getActiveSheetId();this.computedStyles[e]={},this.computedIcons[e]={};const t=this.computedStyles[e];for(let o of this.getters.getConditionalFormats(e).reverse())try{switch(o.rule.type){case"ColorScaleRule":for(let e of o.ranges)this.applyColorScale(e,o.rule);break;case"IconSetRule":for(let e of o.ranges)this.applyIcon(e,o.rule);break;default:for(let i of o.ranges){const s=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=s.top;i<=s.bottom;i++)for(let r=s.left;r<=s.right;r++){const s=this.rulePredicate[o.rule.type];let n=this.getters.getEvaluatedCell({sheetId:e,col:r,row:i});s&&s(n,o.rule)&&(t[r]||(t[r]=[]),t[r][i]=Object.assign(t[r]?.[i]||{},o.rule.style))}}}}catch(e){}}parsePoint(e,t,o){const i=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCellsInZone(i,this.getters.getRangeFromSheetXC(i,e).zone).filter((e=>e.type===ms.number)).map((e=>e.value));switch(t.type){case"value":return"max"===o?Math.max(...s):Math.min(...s);case"number":return Number(t.value);case"percentage":const e=Math.min(...s);return e+(Math.max(...s)-e)*Number(t.value)/100;case"percentile":return oo(s,Number(t.value)/100,!0);case"formula":const i=t.value&&this.getters.evaluateFormula(t.value);return i instanceof Promise?null:i;default:return null}}applyIcon(e,t){const o=this.parsePoint(e,t.lowerInflectionPoint),i=this.parsePoint(e,t.upperInflectionPoint);if(null===o||null===i||o>i)return;const s=this.getters.getActiveSheetId(),r=this.getters.getRangeFromSheetXC(s,e).zone,n=this.computedIcons[s],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=r.top;e<=r.bottom;e++)for(let l=r.left;l<=r.right;l++){const r=this.getters.getEvaluatedCell({sheetId:s,col:l,row:e});if(r.type!==ms.number)continue;const c=this.computeIcon(r.value,i,t.upperInflectionPoint.operator,o,t.lowerInflectionPoint.operator,a);n[l]||(n[l]=[]),n[l][e]=c}}computeIcon(e,t,o,i,s,r){return"ge"===o&&e>=t||"gt"===o&&e>t?r[0]:"ge"===s&&e>=i||"gt"===s&&e>i?r[1]:r[2]}applyColorScale(e,t){const o=this.parsePoint(e,t.minimum,"min"),i=t.midpoint?this.parsePoint(e,t.midpoint):null,s=this.parsePoint(e,t.maximum,"max");if(null===o||null===s||o>=s||i&&(o>=i||i>=s))return;const r=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(r,e).zone,a=this.computedStyles[r],l=[];t.midpoint&&i?(l.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,i,t.minimum.color,t.midpoint.color)}),l.push({minValue:i,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(i,s,t.midpoint.color,t.maximum.color)})):l.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,s,t.minimum.color,t.maximum.color)});for(let e=n.top;e<=n.bottom;e++)for(let t=n.left;t<=n.right;t++){const n=this.getters.getEvaluatedCell({sheetId:r,col:t,row:e});if(n.type===ms.number){const r=He(n.value,o,s);let c;c=2===l.length&&i?r<=i?this.colorCell(r,l[0].minValue,l[0].minColor,l[0].colorDiffUnit):this.colorCell(r,l[1].minValue,l[1].minColor,l[1].colorDiffUnit):this.colorCell(r,l[0].minValue,l[0].minColor,l[0].colorDiffUnit),a[t]||(a[t]=[]),a[t][e]=a[t]?.[e]||{},a[t][e].fillColor=Rt(c)}}}computeColorDiffUnits(e,t,o,i){const s=t-e;return[((o>>16)%256-(i>>16)%256)/s,((o>>8)%256-(i>>8)%256)/s,(o%256-i%256)/s]}colorCell(e,t,o,i){const[s,r,n]=i;return Math.round((o>>16)%256-s*(e-t))<<16|Math.round((o>>8)%256-r*(e-t))<<8|Math.round(o%256-n*(e-t))}rulePredicate={CellIsRule:(e,t)=>{if(e.type===ms.error)return!1;const o=t.values.map(As);switch(t.operator){case"IsEmpty":return""===e.value.toString().trim();case"IsNotEmpty":return""!==e.value.toString().trim();case"BeginsWith":return""!==o[0]&&e.value.toString().startsWith(o[0].toString());case"EndsWith":return""!==o[0]&&e.value.toString().endsWith(o[0].toString());case"Between":return e.value>=o[0]&&e.value<=o[1];case"NotBetween":return!(e.value>=o[0]&&e.value<=o[1]);case"ContainsText":return e.value.toString().indexOf(o[0].toString())>-1;case"NotContains":return!e.value||-1==e.value.toString().indexOf(o[0].toString());case"GreaterThan":return e.value>o[0];case"GreaterThanOrEqual":return e.value>=o[0];case"LessThan":return e.value<o[0];case"LessThanOrEqual":return e.value<=o[0];case"NotEqual":return""!==o[0]&&e.value!==o[0];case"Equal":return""===o[0]||e.value===o[0];default:console.warn(r("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}};adaptRules(e,t,o,i){if(0===o.length&&0===i.length)return;const s=this.getters.getConditionalFormats(e),r=s.findIndex((e=>e.id===t.id));let n=[];r>-1&&(n=s[r].ranges),n=n.concat(o);const a=li(n,i);this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},ranges:a.map((t=>this.getters.getRangeDataFromXc(e,t))),sheetId:e})}pasteCf(e,t,o){const i=Ht(t.col,t.row);for(let s of this.getters.getConditionalFormats(e.sheetId))for(let r of s.ranges)if(ni(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,r).zone)){const r=s,n=[];"CUT"===o&&n.push(Ht(e.col,e.row)),e.sheetId===t.sheetId?this.adaptRules(e.sheetId,r,[i],n):(this.adaptRules(t.sheetId,r,[i],[]),this.adaptRules(e.sheetId,r,[],n))}}}).add("viewport",class extends fC{static getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","isPositionVisible"];viewports={};sheetViewWidth=ge();sheetViewHeight=ge();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkScrollingDirection(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return 0}}handleEvent(e){switch(e.type){case"HeadersSelected":case"AlterZone":break;case"ZonesSelected":let{col:t,row:o}=pi(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const i=e.previousAnchor.zone,s=e.anchor.zone,{top:r,bottom:n,left:a,right:l}=this.getters.getActiveMainViewport();i.left===s.left&&i.right===s.right&&(t=a>t||t>l?a:t),i.top===s.top&&i.bottom===s.bottom&&(o=r>o||o>n?r:o)}const i=this.getters.getActiveSheetId();t=Math.min(t,this.getters.getNumberCols(i)-1),o=Math.min(o,this.getters.getNumberRows(i)-1),this.refreshViewport(this.getters.getActiveSheetId(),{col:t,row:o})}}handle(e){switch(this.cleanViewports(),e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.resetSheetViews();break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const{top:t}=this.getActiveMainViewport(),o=this.getters.getActiveSheetId(),i=this.clipOffsetY(this.getters.getRowDimensions(o,t).start+this.sheetViewHeight);this.shiftVertically(i);break;case"SHIFT_VIEWPORT_UP":{const{top:e}=this.getActiveMainViewport(),t=this.getters.getActiveSheetId(),o=this.clipOffsetY(this.getters.getRowDimensions(t,e).end-this.sheetViewHeight);this.shiftVertically(o);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UPDATE_FILTER":this.resetViewports(e.sheetId);break;case"UPDATE_CELL":("content"in e||"format"in e||void 0!==e.style?.fontSize)&&this.sheetsWithDirtyViewports.add(e.sheetId);break;case"ACTIVATE_SHEET":this.setViewports(),this.refreshViewport(e.sheetIdTo);break;case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":this.resetViewports(this.getters.getActiveSheetId());break;case"DELETE_SHEET":this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"START_EDITION":const{col:s,row:r}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:s,row:r})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){const e=this.getters.getSheetIds();for(const t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>je(e.left,e.right+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>je(e.top,e.bottom+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"ROW",t)))}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:o,ySplit:i}=this.getters.getPaneDivisions(e);let{width:s,height:r}=t.getMaxSize();return{x:this.getters.getColDimensions(e,o).start,y:this.getters.getRowDimensions(e,i).start,width:s,height:r}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:o}=this.getMainViewportRect(),i=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-i.viewportWidth+1),maxOffsetY:Math.max(0,o-i.viewportHeight+1)}}getColRowOffsetInViewport(e,t,o){const i=this.getters.getActiveSheetId(),s=this.getters.getSheetViewVisibleCols(),r=this.getters.getSheetViewVisibleRows();if(o<t)return-this.getColRowOffsetInViewport(e,o,t);let n=0;const a="COL"===e?s:r;for(let s=t;s<o;s++)a.includes(s)&&(n+="COL"===e?this.getters.getColSize(i,s):this.getters.getRowSize(i,s));return n}isVisibleInViewport({sheetId:e,col:t,row:o}){return this.getSubViewports(e).some((e=>e.isVisible(t,o)))}getEdgeScrollCol(e,t,o){let i=!1,s=0,r=0;const{xSplit:n}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(i=!0,r=qt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,r=qt(l-e),s=-1):n&&t<l&&e>l&&(i=!0,r=qt(e),s="reset"),{canEdgeScroll:i,direction:s,delay:r}}getEdgeScrollRow(e,t,o){let i=!1,s=0,r=0;const{ySplit:n}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(i=!0,r=qt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,r=qt(l-e),s=-1):n&&t<l&&e>l&&(i=!0,r=qt(e),s="reset"),{canEdgeScroll:i,direction:s,delay:r}}getVisibleRect(e){const t=this.getters.getActiveSheetId(),o=this.getSubViewports(t).map((t=>t.getRect(e))).filter(lt);if(0===o.length)return{x:0,y:0,width:0,height:0};const i=Math.min(...o.map((e=>e.x))),s=Math.min(...o.map((e=>e.y))),r=Math.max(...o.map((e=>e.x+e.width)))-i,n=Math.max(...o.map((e=>e.y+e.height)))-s;return{x:i+this.gridOffsetX,y:s+this.gridOffsetY,width:r,height:n}}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,o).start}}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(lt)}checkPositiveDimension(e){return e.width<0||e.height<0?68:0}checkValuesAreDifferent(e){const{height:t,width:o}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===o&&e.height===t?76:0}checkScrollingDirection({offsetX:e,offsetY:t}){const o=this.getMainInternalViewport(this.getters.getActiveSheetId());return!o.canScrollHorizontally&&e>0||!o.canScrollVertically&&t>0?69:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e=this.getters.getSheetIds();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetSheetViews(){for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const o=this.getSubViewports(e);Object.values(o).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,o=0,i=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=o,this.gridOffsetY=i,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.resetViewports(e)}setSheetViewOffset(e,t){const o=this.getters.getActiveSheetId(),{maxOffsetX:i,maxOffsetY:s}=this.getMaximumSheetOffset();Object.values(this.getSubViewports(o)).forEach((o=>o.setViewportOffset(He(e,0,i),He(t,0,s))))}clipOffsetY(e){const{height:t}=this.getMainViewportRect(),o=t-this.sheetViewHeight;return e=Math.min(e,o),e=Math.max(e,0)}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetScrollbarX||0,y:this.viewports[e]?.bottomRight.offsetScrollbarY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getNumberCols(e),s=this.getters.getNumberRows(e),r=this.getters.getColRowOffset("COL",0,t,e),n=this.getters.getColRowOffset("ROW",0,o,e),{xRatio:a,yRatio:l}=this.getFrozenSheetViewRatio(e),c=a<1,h=l<1,d=this.getViewportOffset(e),u={topLeft:o&&t&&new vC(this.getters,e,{left:0,right:t-1,top:0,bottom:o-1},{width:r,height:n},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:o&&new vC(this.getters,e,{left:t,right:i-1,top:0,bottom:o-1},{width:this.sheetViewWidth-r,height:n},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new vC(this.getters,e,{left:0,right:t-1,top:o,bottom:s-1},{width:r,height:this.sheetViewHeight-n},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new vC(this.getters,e,{left:t,right:i-1,top:o,bottom:s-1},{width:this.sheetViewWidth-r,height:this.sheetViewHeight-n},{canScrollHorizontally:c,canScrollVertically:h},{x:c?d.x:0,y:h?d.y:0})};this.viewports[e]=u}refreshViewport(e,t){Object.values(this.getSubViewports(e)).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const{top:t}=this.getActiveMainViewport(),{scrollX:o}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(o,e);const{anchor:i}=this.getters.getSelection(),s=this.getActiveMainViewport().top-t;this.selection.selectCell(i.cell.col,i.cell.row+s)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:i,scrollY:s}=this.getActiveSheetScrollInfo(),{x:r,y:n}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of o)e.x>=r&&(e.x+e.width<=r+i||e.x>=a+i+r)||e.y>=n&&(e.y+e.height<=n+s||e.y>=l+s+n)||t.push(e);return t}isPositionVisible(e){const{scrollX:t,scrollY:o}=this.getters.getActiveSheetScrollInfo(),{x:i,y:s}=this.getters.getMainViewportCoordinates(),{width:r,height:n}=this.getters.getSheetViewDimension();return!(e.x>=i&&(e.x<i+t||e.x>r+t+i))&&!(e.y>=s&&(e.y<s+o||e.y>n+o+s))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getColDimensions(e,t).start,s=this.getters.getRowDimensions(e,o).start;return{xRatio:i/(this.sheetViewWidth+this.gridOffsetX),yRatio:s/(this.sheetViewHeight+this.gridOffsetY)}}}).add("custom_colors",class extends fC{customColors=new Set;shouldUpdateColors=!1;static getters=["getCustomColors"];handle(e){switch(e.type){case"UPDATE_CELL":case"UPDATE_CHART":case"CREATE_CHART":case"ADD_CONDITIONAL_FORMAT":case"SET_BORDER":case"SET_ZONE_BORDERS":case"SET_FORMATTING":this.shouldUpdateColors=!0}}finalize(){if(this.shouldUpdateColors){this.shouldUpdateColors=!1;for(const e of this.getCustomColors())this.tryToAddColor(e)}}getCustomColors(){let e=[];for(const t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getChartColors(t));return function(e){const t=[{leadColor:Mt(255,0,0),colors:[]},{leadColor:Mt(255,128,0),colors:[]},{leadColor:Mt(128,128,0),colors:[]},{leadColor:Mt(128,255,0),colors:[]},{leadColor:Mt(0,255,0),colors:[]},{leadColor:Mt(0,255,128),colors:[]},{leadColor:Mt(0,255,255),colors:[]},{leadColor:Mt(0,127,255),colors:[]},{leadColor:Mt(0,0,255),colors:[]},{leadColor:Mt(127,0,255),colors:[]},{leadColor:Mt(128,0,128),colors:[]},{leadColor:Mt(255,0,128),colors:[]}];for(const o of e.map(Ft)){let e=500,i=0;t.forEach(((t,s)=>{const r=(n=o,a=t.leadColor,Math.sqrt(Math.pow(n.r-a.r,2)+Math.pow(n.g-a.g,2)+Math.pow(n.b-a.b,2)));var n,a;e>r&&(e=r,i=s)})),t[i].colors.push(o)}return t.map((e=>e.colors.sort(((e,t)=>Lt(e).s-Lt(t).s)))).flat().map(_t)}([...new Set([...new Set([...e,...this.customColors])].filter(At).map(Tt))]).filter((e=>!N.includes(e)))}getColorsFromCells(e){const t=Object.values(this.getters.getCells(e)),o=new Set;for(const e of t)e.style?.textColor&&o.add(e.style.textColor),e.style?.fillColor&&o.add(e.style.fillColor);for(const t of this.getters.getBordersColors(e))o.add(t);return[...o]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),o=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(o.push(t.style.textColor),o.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(o.push(Rt(t.minimum.color)),o.push(t.midpoint?Rt(t.midpoint.color):void 0),o.push(Rt(t.maximum.color)))}return o.filter(lt)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let o=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&o.add(t),e.type){case"gauge":const t=e.sectionRule.colors;o.add(t.lowerColor),o.add(t.middleColor),o.add(t.upperColor);break;case"scorecard":const i=e;o.add(i.baselineColorDown),o.add(i.baselineColorUp)}}return[...o]}tryToAddColor(e){const t=Tt(e);e&&!N.includes(t)&&this.customColors.add(t)}}),rE=new _i;rE.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,execute:(e,t)=>Vi(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class nE{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageSize(t)}}getImageFromUser(){return new Promise(((e,t)=>{const o=document.createElement("input");o.setAttribute("type","file"),o.setAttribute("accept","image/*"),o.addEventListener("change",(async()=>{null===o.files||1!=o.files.length?t():e(o.files[0])})),o.click()}))}getImageSize(e){return new Promise(((t,o)=>{const i=new Image;i.src=e,i.addEventListener("load",(()=>{const e={width:i.width,height:i.height};t(e)})),i.addEventListener("error",o)}))}}const aE=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];xi`
1417
+ `}function DS(e){return new Yf(e.join("\n"))}function LS(e,...t){let o=[e[0]];for(let i=0;i<t.length;i++){const s=t[i]instanceof Yf?t[i]:MS(t[i]);o.push(s+e[i+1])}return new Yf(dt(o))}function PS(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function kS(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class US{value;constructor(e){this.value=e}asString(){return Bb(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class VS{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;areNamespaceIgnored;constructor(e,t,o){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=o,this.areNamespaceIgnored=null!==(new DOMParser).parseFromString("<t:test xmlns:t='a'/>","text/xml").querySelector("test"),this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfFiles(){return Object.values(this.xlsxFileStructure).flat().filter(lt)}mapOnElements(e,t){const o=[],i=this.currentFile;let s;if(e.children){const t=this.querySelector(e.parent,e.query)?.children;s=t||[]}else s=this.querySelectorAll(e.parent,e.query);if(s)for(let e of s)try{o.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=i,o}catchErrorOnElement(e,t){const o=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([o,e.message].join("\n"))}extractAttr(e,t,o){const i=e.attributes[t];i||this.handleMissingValue(e,`attribute "${t}"`,o);const s=i?.value?i.value:o?.default;return void 0===s?void 0:new US(s)}extractTextContent(e,t){if(void 0!==t?.default&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const o="preserve"===e?.attributes["xml:space"]?.value;let i=e?.textContent;return e&&null!==i||this.handleMissingValue(e,"text content",t),i&&(i=o?i:i.trim()),i?Bb(i):t?.default}extractChildAttr(e,t,o,i){let s;s="number"==typeof t?e.children[t]:this.querySelector(e,t),s||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,i);const r=s?this.extractAttr(s,o,i)?.asString():i?.default;return void 0!==r?new US(r):void 0}extractChildTextContent(e,t,o){if(void 0!==o?.default&&"string"!=typeof o.default)throw new Error("extractTextContent default value should be a string");let i=this.querySelector(e,t);return i||this.handleMissingValue(e,`child <${t}>`,o),i?this.extractTextContent(i,o):o?.default}handleMissingValue(e,t,o){if(o?.required){if(!o?.default)throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${o.default}`)}}extractColor(e,t,o){if(!e)return o?{rgb:o}:void 0;const i=this.extractAttr(e,"theme")?.asString();let s;if(void 0!==i){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");s=this.getThemeColor(i,t.clrScheme)}else s=this.extractAttr(e,"rgb")?.asString();return{rgb:s,auto:this.extractAttr(e,"auto")?.asBool(),indexed:this.extractAttr(e,"indexed")?.asNum(),tint:this.extractAttr(e,"tint")?.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");let t=e.target;t=t.replace("../",""),t=t.replace("./","");const o=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!o||!o.file)throw new Error("Cannot find target file");return o}querySelector(e,t){return t=this.areNamespaceIgnored?PS(t):kS(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?PS(t):kS(t),e.querySelectorAll(t)}getThemeColor(e,t){switch(e){case"0":return"FFFFFF";case"1":return"000000";case"2":return t[3].value;case"3":return t[2].value;default:return t[e].value}}}class zS extends VS{getTheme(){return{clrScheme:this.mapOnElements({query:"a:clrScheme",parent:this.rootFile.file.xml,children:!0},(e=>({name:e.tagName,value:this.extractChildAttr(e,0,"val",{required:!0,default:Kf}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:Kf}).asString()})))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"si"},(e=>"t"===e.children[0].tagName?this.extractTextContent(e)||"":this.mapOnElements({parent:e,query:"t"},(e=>this.extractTextContent(e)||"")).join("")))}}class BS extends VS{theme;constructor(e,t,o,i){super(e,t,o),this.theme=i}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>({sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:this.extractAttr(e,"pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)})));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>({sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:this.extractAttr(e,"xm:pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)})))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>{const o=this.extractAttr(e,"type",{required:!0}).asString();if("dataBar"===o)throw new Error("Databars conditional formats are not supported.");return{type:o,priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,"dxfId")?.asNum(),stopIfTrue:this.extractAttr(e,"stopIfTrue")?.asBool(),aboveAverage:this.extractAttr(e,"aboveAverage")?.asBool(),percent:this.extractAttr(e,"percent")?.asBool(),bottom:this.extractAttr(e,"bottom")?.asBool(),operator:this.extractAttr(e,"operator")?.asString(),text:this.extractAttr(e,"text")?.asString(),timePeriod:this.extractAttr(e,"timePeriod")?.asString(),rank:this.extractAttr(e,"rank")?.asNum(),stdDev:this.extractAttr(e,"stdDev")?.asNum(),equalAverage:this.extractAttr(e,"equalAverage")?.asBool()}}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const o=this.querySelector(e,"colorScale");if(o)return{colors:this.mapOnElements({parent:o,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(o)}}extractCfIconSet(e){const t=this.querySelector(e,"iconSet, x14:iconSet");if(t)return{iconSet:this.extractAttr(t,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(t,"showValue",{default:!0}).asBool(),percent:this.extractAttr(t,"percent",{default:!0}).asBool(),reverse:this.extractAttr(t,"reverse")?.asBool(),custom:this.extractAttr(t,"custom")?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),gte:this.extractAttr(e,"gte",{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,"val")?.asString():this.extractChildTextContent(e,"f, xm:f")})))}}class HS extends VS{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!_b[t])throw new Error(`Unsupported chart type ${t}`);const o=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),i=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:o,type:_b[t],dataSets:this.extractChartDatasets(this.querySelector(e,`c:${t}`)),labelRange:this.extractChildTextContent(e,"c:ser c:cat c:f"),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),verticalAxisPosition:"r"===this.extractChildAttr(e,"c:valAx > c:axPos","val",{default:"l"}).asString()?"right":"left",legendPosition:Nb[this.extractChildAttr(e,"c:legendPos","val",{default:"b"}).asString()],stacked:"stacked"===i,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c:tx c:f"),range:this.extractChildTextContent(e,"c:val c:f",{required:!0})})))}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");for(let e of t.children){const t=PS(e.tagName);if(Xf.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class $S extends VS{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==PS(e.tagName))throw new Error("Only twoCellAnchor are supported for xlsx drawings.");const t=this.querySelector(e,"c:chart");if(!t)throw new Error("Only chart figures are currently supported.");return{anchors:[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)],data:this.extractChart(t)}}))}extractFigureAnchor(e,t){const o=this.querySelector(t,e);if(!o)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(o,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(o,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(o,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(o,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),o=this.getTargetXmlFile(this.relationships[t]),i=new HS(o,this.xlsxFileStructure,this.warningManager).extractChart();if(!i)throw new Error("Unable to extract chart definition");return i}}class WS extends VS{getPivotTable(){return this.mapOnElements({query:":root",parent:this.rootFile.file.xml},(e=>({displayName:this.extractAttr(e,"name",{required:!0}).asString(),id:this.extractAttr(e,"name",{required:!0}).asString(),ref:this.extractChildAttr(e,"location","ref",{required:!0}).asString(),headerRowCount:this.extractChildAttr(e,"location","firstDataRow",{default:0}).asNum(),totalsRowCount:1,cols:[],style:{showFirstColumn:!0,showRowStripes:!0}})))[0]}}class GS extends VS{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>({displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:this.extractAttr(e,"name")?.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)})))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>({name:this.extractAttr(e,"name")?.asString(),showFirstColumn:this.extractAttr(e,"showFirstColumn")?.asBool(),showLastColumn:this.extractAttr(e,"showLastColumn")?.asBool(),showRowStripes:this.extractAttr(e,"showRowStripes")?.asBool(),showColumnStripes:this.extractAttr(e,"showColumnStripes")?.asBool()})))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class qS extends VS{theme;constructor(e,t,o,i){super(e,t,o),this.theme=i}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},(e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:[...this.extractTables(e),...this.extractPivotTables()],isVisible:"visible"===t.state}}))[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},(e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}}))}extractSheetName(){const e=Ub(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id;for(let e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,"sheet"))if(e.attributes["r:id"].value===t)return e.attributes.name.value;throw new Error("Missing sheet name")}getSheetWorkbookInfo(){const e=Ub(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,o=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!o)throw new Error("Cannot find corresponding workbook sheet");return o}extractConditionalFormats(){return new BS(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),o=this.getTargetXmlFile(this.relationships[t]);return new $S(o,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),o=this.getTargetXmlFile(this.relationships[t]);return new GS(o,this.xlsxFileStructure,this.warningManager).getTable()}))}extractPivotTables(){try{return Object.values(this.relationships).filter((e=>e.type.endsWith("pivotTable"))).map((e=>{const t=this.getTargetXmlFile(e);return new WS(t,this.xlsxFileStructure,this.warningManager).getPivotTable()}))}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:"mergeCell"},(e=>this.extractAttr(e,"ref",{required:!0}).asString()))}extractSheetFormat(e){const t=this.querySelector(e,"sheetFormatPr");if(t)return{defaultColWidth:this.extractAttr(t,"defaultColWidth",{default:ab.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:lb.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>({width:this.extractAttr(e,"width")?.asNum(),customWidth:this.extractAttr(e,"customWidth")?.asBool(),bestFit:this.extractAttr(e,"bestFit")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),min:this.extractAttr(e,"min",{required:!0})?.asNum(),max:this.extractAttr(e,"max",{required:!0})?.asNum(),styleIndex:this.extractAttr(e,"style")?.asNum()})))}extractRows(e){return this.mapOnElements({parent:e,query:"sheetData row"},(e=>({index:this.extractAttr(e,"r",{required:!0})?.asNum(),cells:this.extractCells(e),height:this.extractAttr(e,"ht")?.asNum(),customHeight:this.extractAttr(e,"customHeight")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),styleIndex:this.extractAttr(e,"s")?.asNum()})))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>({xc:this.extractAttr(e,"r",{required:!0})?.asString(),styleIndex:this.extractAttr(e,"s")?.asNum(),type:xb[this.extractAttr(e,"t",{default:"n"})?.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)})))}extractCellFormula(e){const t=this.querySelector(e,"f");if(t)return{content:this.extractTextContent(t),sharedIndex:this.extractAttr(t,"si")?.asNum(),ref:this.extractAttr(t,"ref")?.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{const t=this.extractAttr(e,"r:id")?.asString();return{xc:this.extractAttr(e,"ref",{required:!0})?.asString(),location:this.extractAttr(e,"location")?.asString(),display:this.extractAttr(e,"display")?.asString(),relTarget:t?this.relationships[t].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),o={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),i=this.extractTextContent(e,{required:!0});o[t]=i}const i=[];for(let e=0;e<Object.keys(o).length;e++)o[e]?i.push(o[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),i.push(""));return i}}class ZS extends VS{theme;constructor(e,t,o){super(e.styles,e,t),this.theme=o}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){const t=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),o=this.extractChildAttr(e,"sz","val",{default:q.toString()}).asNum(),i=this.extractColor(this.querySelector(e,"color"),this.theme),s=this.querySelector(e,"i")||void 0,r=s&&"0"!==s.attributes.val?.value,n=this.querySelector(e,"b")||void 0,a=n&&"0"!==n.attributes.val?.value,l=this.querySelector(e,"strike")||void 0,c=l&&"0"!==l.attributes.val?.value,h=this.querySelector(e,"u")||void 0;return{name:t,size:o,color:i,italic:r,bold:a,underline:h&&"none"!==h.attributes.val?.value,strike:c}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){const t=e.children[0];return"patternFill"===t.tagName?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(t,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(t,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){const t={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,"diagonalUp")?.asBool(),t.diagonalDown=this.extractAttr(e,"diagonalDown")?.asBool()),t}extractSingleBorder(e,t,o){const i=this.querySelector(e,t);if(i&&i.attributes.style)return{style:this.extractAttr(i,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(i.children[0],o,"000000")}}extractAlignment(e){return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"bottom"}).asString(),textRotation:this.extractAttr(e,"textRotation")?.asNum(),wrapText:this.extractAttr(e,"wrapText")?.asBool(),indent:this.extractAttr(e,"indent")?.asNum(),relativeIndent:this.extractAttr(e,"relativeIndent")?.asNum(),justifyLastLine:this.extractAttr(e,"justifyLastLine")?.asBool(),shrinkToFit:this.extractAttr(e,"shrinkToFit")?.asBool(),readingOrder:this.extractAttr(e,"readingOrder")?.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),o=this.querySelector(e,"fill"),i=this.querySelector(e,"border"),s=this.querySelector(e,"numFmt"),r=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:o?this.extractFill(o):void 0,numFmt:s?this.extractNumFormats(s):void 0,alignment:r?this.extractAlignment(r):void 0,border:i?this.extractBorder(i):void 0}}))}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}}))}}class jS extends VS{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),o={};for(let e of t)o[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:o}}))}}function YS(e,t){const o=function(e,t){const o=t[pb],i=o.querySelectorAll(`Override[ContentType="${e}"]`),s=[];for(let e of i){const t=e?.attributes.PartName.value;s.push(t.substring(1))}return s}(e,t);return function(e,t){const o=[];for(let i of e){const e=XS(i,t);o.push({file:{fileName:i,xml:t[i]},rels:e?{fileName:e,xml:t[e]}:void 0})}return o}(o,t)}function XS(e,t){if(e===pb)return"_rels/.rels";let o="";const i=e.split("/");for(let e=0;e<i.length-1;e++)o+=i[e]+"/";return o+="_rels/",o+=i[i.length-1]+".rels",t[o]||(o=void 0),o}class KS{warningManager;xmls;constructor(e){this.warningManager=new fb,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=_S(new Yf(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new zS(e.theme,e,this.warningManager).getTheme():void 0,o=e.sharedStrings?new zS(e.sharedStrings,e,this.warningManager).getSharedStrings():[],i=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((o=>new qS(o,e,this.warningManager,t).getSheet())),s=e.externalLinks.map((t=>new jS(t,e,this.warningManager).getExternalBook())),r=new ZS(e,this.warningManager,t);return{fonts:r.getFonts(),fills:r.getFills(),borders:r.getBorders(),dxfs:r.getDxfs(),numFmts:r.getNumFormats(),styles:r.getStyles(),sheets:i,sharedStrings:o,externalBooks:s}}buildXlsxFileStructure(){const e={sheets:YS(ob.sheet,this.xmls),workbook:YS(ob.workbook,this.xmls)[0],styles:YS(ob.styles,this.xmls)[0],sharedStrings:YS(ob.sharedStrings,this.xmls)[0],theme:YS(ob.themes,this.xmls)[0],charts:YS(ob.chart,this.xmls),figures:YS(ob.drawing,this.xmls),tables:YS(ob.table,this.xmls),pivots:YS(ob.pivot,this.xmls),externalLinks:YS(ob.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(r("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:vS(e,this.warningManager),styles:qb(e,this.warningManager),formats:jb(e,this.warningManager),borders:Wb(e,this.warningManager),entities:{},revisionId:J};return RS(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=ft(e.styles[t])})),t}}function QS(e){const t=Vv(e);let o=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&No.test(e.value)){const t=e.value.trim();return o.includes(t)||o.push(t),`${ce}${o.indexOf(t)}${ce}`}return e.value}))),dependencies:o}}const JS=13,eC="Sheet1";function tC(e,t){if(!e)return nC();if(e["[Content_Types].xml"]){const o=new KS(e);if(e=o.convertXlsx(),t)for(let e of o.warningManager.warnings.sort())console.warn(e)}return"version"in e&&e.version<JS&&(e=function(e){for(let t=oC.findIndex((t=>t.from===e.version));t<oC.length;t++)e=oC[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,o=new Zo;for(const i of e.sheets||[])for(const e of i.figures||[])t.has(e.id)&&(e.id+=o.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(nC(),e,{version:JS}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(rC(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(rC(eC,"Sheet1"));return e}(e),e}(e),e}const oC=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const o=t.cells[e];o.content&&o.content.startsWith("=")&&(o.formula=QS(o.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:o,...i}=t.figures[e].data,s=[];for(let e of o)if(e.labelCell){const t=Yo(e.dataRange),o=e.labelCell+":"+Ht(t.right,t.bottom);s.push(o)}else s.push(e.dataRange);i.dataSetsHaveTitle=Boolean(o[0].labelCell),i.dataSets=s,t.figures[e].data=i}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){const t=[],o=new RegExp(le,"g");for(let i of e.sheets||[]){if(!i.name)continue;const e=i.name,s=e.replace(o,"_");let r=1,n=s;for(;t.includes(n);)n=`${s}${r}`,r++;i.name=n,t.push(n);const a=t=>{if(void 0===t)return t;let o=t.replace(e,n),i=t;for(;i!==o;)i=o,o=i.replace(e,n);return i};for(let e in i.cells){const t=i.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(a))}for(let e of i.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(a),o=a(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:o}}for(let e of i.conditionalFormats||[]){e.ranges=e.ranges.map(a);for(const t of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===e.rule[t]?.type&&(e.rule[t].value=a(e.rule[t].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=w,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const o=t.cells[e];if(o.formula){let{text:e,dependencies:t}=o.formula;for(let[o,i]of Object.entries(t)){const t=`\\${ce}${o}\\${ce}`;e=e.replace(new RegExp(t,"g"),i)}o.content=e,delete o.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let o of e.sheets||[])for(let e in o.cells||[]){const i=o.cells[e];i.format&&(i.format=ht(i.format,t))}return e.formats=t,e}},{description:"Add isVisible to sheets",from:11,to:12,applyMigration(e){for(let t of e.sheets||[])t.isVisible=!0;return e}},{description:"Change Border description structure",from:12,to:13,applyMigration(e){for(const t in e.borders){const o=e.borders[t];for(const e in o)Array.isArray(o[e])&&(o[e]={style:o[e][0],color:o[e][1]})}return e}}];function iC(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const o=[],i=[],s=e=>{if("CREATE_SHEET"===e.type)o.push(e.sheetId);else if("sheetId"in e&&!o.includes(e.sheetId))return{...e,sheetId:eC};return e};for(const e of t)"REMOTE_REVISION"===e.type?i.push({...e,commands:e.commands.map(s)}):i.push(e);return i}(e,t),t=sC(t,"SORT_CELLS"),t=function(e,t){const o=[],i={};for(const t of e.sheets||[])t.figures?.forEach((e=>{"chart"===e.tag&&(i[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const o of e.commands){let e=o;switch(o.type){case"CREATE_CHART":i[o.id]=o.definition;break;case"UPDATE_CHART":if(!i[o.id]){console.log(`Fix chart definition: chart with id ${o.id} not found.`);continue}const t={...i[o.id],...o.definition};e={...o,definition:t},i[o.id]=t}t.push(e)}o.push({...e,commands:t})}else o.push(e);return o}(e,t=sC(t,"SET_DECIMAL")),t}function sC(e,t){const o=[];for(const i of e)"REMOTE_REVISION"===i.type?o.push({...i,commands:i.commands.filter((e=>e.type!==t))}):o.push(i);return o}function rC(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function nC(e="Sheet1"){return{version:JS,sheets:[rC(eC,e)],entities:{},styles:{},formats:{},borders:{},revisionId:J,uniqueFigureIds:!0}}function aC(e,t){return{...rC(e,t),charts:[],images:[]}}class lC{static getters=[];history;dispatch;constructor(e,t){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t}exportForExcel(e){}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const o of e){let e=o.call(this,t);Array.isArray(e)||(e=[e]);const i=e.filter((e=>0!==e));if(i.length)return i}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class cC extends lC{getters;range;uuidGenerator;constructor({getters:e,stateObserver:t,range:o,dispatch:i,uuidGenerator:s}){super(t,i),this.range=o,o.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=s}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}}function hC(e){return""===e?NaN:Number(e)}class dC{id;zone;filters;constructor(e){this.filters=[],this.zone=e;const t=new Zo;this.id=t.uuidv4();for(const o of je(e.left,e.right+1)){const e={...this.zone,left:o,right:o};this.filters.push(new uC(t.uuidv4(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){return this.filters.find((t=>t.col===e))?.id}clone(){return new dC(this.zone)}}class uC{id;zoneWithHeaders;constructor(e,t){if(t.left!==t.right)throw new Error("Can only define a filter on a single column");this.id=e,this.zoneWithHeaders=t}get col(){return this.zoneWithHeaders.left}get filteredZone(){const e=this.zoneWithHeaders;if(e.bottom!==e.top)return{...e,top:e.top+1}}}function gC(e){return Object.entries(e).map((([e,t])=>t?pC(parseInt(e,10),t):void 0)).filter(lt).map((e=>Ht(e.left,e.top)+":"+Ht(e.right,e.bottom)))}function pC(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}class mC{getters;providers=[];constructor(e){this.getters=e}static getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?0:26:0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";const s=[...e.elements];s.sort(((e,t)=>t-e));const r=Ye(s);this.executeOnAllRanges((s=>{if(s.sheetId!==e.sheetId)return{changeType:"NONE"};let n=s,a="NONE";for(let e of r){const r=Math.min(...e),l=Math.max(...e);if(s.zone[t]<=r&&r<=s.zone[o]){const e=Math.min(s.zone[o],l)-r+1;a="RESIZE",n=this.createAdaptedRange(n,i,a,-e)}else if(s.zone[t]>=r&&s.zone[o]<=l)a="REMOVE",n=s.clone({...this.getInvalidRange()});else if(s.zone[t]<=l&&s.zone[o]>=l){const e=l-s.zone[t]+1;a="RESIZE",n=this.createAdaptedRange(n,i,a,-e),n=this.createAdaptedRange(n,i,"MOVE",-(s.zone[t]-r))}else r<s.zone[t]&&(a="MOVE",n=this.createAdaptedRange(n,i,a,-(l-r+1)))}return"NONE"!==a?{changeType:a,range:n}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((s=>{if(s.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(s.zone[t]<=e.base&&e.base<s.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(s,i,"RESIZE",e.quantity)};if(e.base<s.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(s,i,"MOVE",e.quantity)}}else{if(s.zone[t]<e.base&&e.base<=s.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(s,i,"RESIZE",e.quantity)};if(e.base<=s.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(s,i,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const o=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:o})}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const o=void 0,i=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:i,invalidSheetName:o})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId||!ai(o.zone,t))return{changeType:"NONE"};const i=e.targetSheetId,s=e.col-t.left,r=e.row-t.top,n=this.createAdaptedRange(o,"both","MOVE",[s,r]),a=e.sheetId!==i||n.prefixSheet;return{changeType:"MOVE",range:n.clone({sheetId:i,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||Xo(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,o,i){const s=gi(e.unboundedZone,t,o,i);return e.clone({zone:s})}executeOnAllRanges(e,t){const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,o,i){const s=e.map((e=>Ho.fromRange(e,this.getters)));return s.map((e=>{if(!Xo(e.zone))return e;const s=e.prefixSheet?e.sheetId:i,r={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:o),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:o)};return e.clone({sheetId:s,zone:r}).orderZone()}))}getRangeFromSheetXC(e,t){if(!Po.test(t))return new Ho({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let o,i=t,s=!1;t.includes("!")&&(({xc:i,sheetName:o}=Bo(t)),o&&(s=!0));const r=jo(i),n=Ho.getRangeParts(i,r),a=o&&!this.getters.getSheetIdByName(o)?o:void 0,l=this.getters.getSheetIdByName(o)||e;return new Ho({prefixSheet:s,zone:r,sheetId:l,invalidSheetName:a,parts:n},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const o=Ho.fromRange(e,this.getters),i=this.getters.expandZone(o.sheetId,o.zone),s=o.clone({zone:{...i,bottom:o.isFullCol?void 0:i.bottom,right:o.isFullRow?void 0:i.right}});return this.getRangeString(s,t)}getRangeString(e,t){if(!e)return Q;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return Q;if(e.zone.left<0||e.zone.top<0)return Q;const o=Ho.fromRange(e,this.getters);let i=o.sheetId!==t||o.invalidSheetName||o.prefixSheet,s="";if(i&&(s=o.invalidSheetName?o.invalidSheetName:Be(this.getters.getSheetName(o.sheetId))),i&&!s)return Q;let r=this.getRangePartString(o,0);return o.parts&&2===o.parts.length&&(o.zone.top!==o.zone.bottom||o.zone.left!==o.zone.right||o.parts[0].rowFixed||o.parts[0].colFixed||o.parts[1].rowFixed||o.parts[1].colFixed)&&(r+=":",r+=this.getRangePartString(o,1)),`${i?s+"!":""}${r}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t}}getRangeFromRangeData(e){const t={prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]};return new Ho(t,this.getters.getSheetSize)}getRangePartString(e,t){const o=e.parts&&e.parts[t].colFixed?"$":"",i=Pt(0===t?e.zone.left:e.zone.right),s=e.parts&&e.parts[t].rowFixed?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let n="";return n=e.isFullCol?0===t&&e.unboundedZone.hasHeader?o+i+s+r:o+i:e.isFullRow?0===t&&e.unboundedZone.hasHeader?o+i+s+r:s+r:o+i+s+r,n}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:Q}}}class fC extends lC{static layers=[];getters;ui;selection;constructor({getters:e,stateObserver:t,dispatch:o,uiActions:i,selection:s}){super(t,o),this.getters=e,this.ui=i,this.selection=s}drawGrid(e,t){}}const bC=Tg.mapping;class vC{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;offsetScrollbarX;offsetScrollbarY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,o,i,s,r){this.getters=e,this.sheetId=t,this.boundaries=o,this.viewportWidth=i.width,this.viewportHeight=i.height,this.offsetScrollbarX=r.x,this.offsetScrollbarY=r.y,this.canScrollVertically=s.canScrollVertically,this.canScrollHorizontally=s.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:o,size:i}=this.getters.getColDimensions(this.sheetId,e),{end:s,size:r}=this.getters.getRowDimensions(this.sheetId,t),n=this.searchHeaderIndex("COL",o-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,n),l=this.searchHeaderIndex("ROW",s-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=o-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(D,Math.min(a,this.viewportWidth-i)),h=Math.max(h,this.viewportWidth));let d=s-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(L+5,Math.min(c,this.viewportHeight-r)),d=Math.max(d,this.viewportHeight)),{width:h,height:d}}getColIndex(e,t=!1){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX,this.left,t)}getRowIndex(e,t=!1){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY,this.top,t)}adjustPosition(e){const t=this.sheetId;e||(e=this.getters.getSheetPosition(t));const o=this.getters.getMainCellPosition({sheetId:t,...e}),{col:i,row:s}=this.getters.getNextVisibleCellPosition(o);ni(i,this.boundaries.top,this.boundaries)&&this.adjustPositionX(i),ni(this.boundaries.left,s,this.boundaries)&&this.adjustPositionY(s)}adjustPositionX(e){const t=this.sheetId,{end:o}=this.getters.getColDimensions(t,e),i=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<o)for(let e=this.left;this.offsetX+this.offsetCorrectionX+this.viewportWidth<o&&!(e>i);e++)this.getters.isColHidden(t,e)||(this.offsetX=this.getters.getColDimensions(t,e).end-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX());else if(this.left>e)for(let o=this.left;o>=e&&!(o<0);o--)this.getters.isColHidden(t,o)||(this.offsetX=this.getters.getColDimensions(t,o).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX())}adjustPositionY(e){const t=this.sheetId,{end:o}=this.getters.getRowDimensions(t,e),i=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<o)for(let e=this.top;this.offsetY+this.viewportHeight+this.offsetCorrectionY<o&&!(e>i);e++)this.getters.isRowHidden(t,e)||(this.offsetY=this.getters.getRowDimensions(t,e).end-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY());else if(this.top>e)for(let o=this.top;o>=e&&!(o<0);o--)this.getters.isRowHidden(t,o)||(this.offsetY=this.getters.getRowDimensions(t,o).start-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY())}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getRect(e){const t=ii(e,this.zone);if(t){return{x:this.getters.getColRowOffset("COL",this.zone.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset("ROW",this.zone.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1),this.viewportHeight)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,o=0,i=!1){let s=0;const r=this.sheetId,n=this.getters.getNumberHeaders(r,e);for(let a=o;a<=n-1;a++){const o=i||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(r,e,a)&&!o&&(s+="COL"===e?this.getters.getColSize(r,a):this.getters.getRowSize(r,a),s>t))return a}return-1}get zone(){return{left:this.left,right:this.right,top:this.top,bottom:this.bottom}}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.left=this.getColIndex(this.offsetScrollbarX,!0),this.right=this.getColIndex(this.offsetScrollbarX+this.viewportWidth,!0),-1===this.right&&(this.right=this.boundaries.right),this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.top=this.getRowIndex(this.offsetScrollbarY,!0),this.bottom=this.getRowIndex(this.offsetScrollbarY+this.viewportWidth,!0),-1===this.bottom&&(this.bottom=this.boundaries.bottom),this.adjustViewportZoneY()}adjustViewportZoneX(){const e=this.sheetId;this.left=this.searchHeaderIndex("COL",this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",this.viewportWidth,this.left)),-1===this.right&&(this.right=this.getters.getNumberCols(e)-1),this.offsetX=this.getters.getColDimensions(e,this.left).start-this.getters.getColDimensions(e,this.boundaries.left).start}adjustViewportZoneY(){const e=this.sheetId;this.top=this.searchHeaderIndex("ROW",this.offsetScrollbarY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",this.viewportHeight,this.top)),-1===this.bottom&&(this.bottom=this.getters.getNumberRows(e)-1),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start}}class SC{cells;getters;index=0;direction;constructor(e,t,o){this.cells=e,this.getters=t,this.direction=o}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:o,tooltip:i}=Ls.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:o,tooltip:i,origin:{col:e.data.col,row:e.data.row}}}}class CC{subscriptions={};on(e,t,o){if(!o)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:o})}trigger(e,t){const o=this.subscriptions[e]||[];for(let e=0,i=o.length;e<i;e++){const i=o[e];i.callback.call(i.owner,t)}}off(e,t){const o=this.subscriptions[e];o&&(this.subscriptions[e]=o.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function EC(e,t){return{...e,definition:Hn(e.definition,t)}}function wC(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let o=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)o>t&&o--}if("ADD_COLUMNS_ROWS"===t.type){o=o>("before"===t.position?t.base-1:t.base)?o+t.quantity:o}return o>0?{...e,quantity:o}:void 0}Em.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],EC),Em.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],EC),Em.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),Em.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),Em.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){if(e.name===t.name)return{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),Em.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const o=[];for(const i of e.target)for(const e of t.target)ri(i,e)||o.push({...i});if(o.length)return{...e,target:o};return})),Em.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],wC),Em.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],wC),Em.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const o of e.target)for(const e of t.target)if(ri(e,o))return;return e}));const xC=[{match:function(e){return"sheetId"in e},fn:RC},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=RC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const i=[];for(const o of e.target){const e=Tr(o,t);e&&i.push(e)}if(!i.length)return"IGNORE_COMMAND";return{...e,target:i}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const o=RC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const o="COL"===t.dimension?"col":"row";let i=e[o];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(i))return"IGNORE_COMMAND";for(let t of e)i>=t&&i--}"ADD_COLUMNS_ROWS"===t.type&&(i>t.base||i===t.base&&"before"===t.position)&&(i+=t.quantity);return{...e,[o]:i}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const o of t.target){if(!(e.col===o.left&&e.row===o.top)&&ni(e.col,e.row,o))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e},fn:function(e,t){const o=RC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const o="ADD_COLUMNS_ROWS"===e.type,i=o?"base":"elements";let s=o?[e[i]]:e[i];if("REMOVE_COLUMNS_ROWS"===t.type&&(s=s.map((e=>{if(t.elements.includes(e))return;const o=t.elements.sort(((e,t)=>t-e));for(let t of o)e>t&&e--;return e})).filter(lt)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;s=s.map((o=>o>e?o+t.quantity:o))}if(s.length){let t=s;return o&&(t=s[0]),{...e,[i]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const o=[],i="DELETE_SHEET"===t.type&&t.sheetId;for(const s of e.ranges)if(s._sheetId!==t.sheetId)o.push({...s,_zone:s._zone});else{const e=Tr(s._zone,t);e&&i!==s._sheetId&&o.push({...s,_zone:e})}if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function yC(e,t){const o=Em.getTransformation(e.type,t.type);return o?o(e,t):function(e,t){for(const{match:o,fn:i}of xC)if(o(e)){const o=i(e,t);if("SKIP_TRANSFORMATION"===o)continue;if("IGNORE_COMMAND"===o)return;e=o}return e}(e,t)}function IC(e,t){let o=[...e];for(const e of t)o=o.map((t=>yC(t,e))).filter(lt);return o}function RC(e,t){const o="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===o?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class TC{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,o,i,s,r){this.rootCommand=i,this.timestamp=r,this.id=e,this.clientId=t,this._commands=[...o],this._changes=s?[...s]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class AC extends Error{}class OC extends CC{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;uuidGenerator=new Zo;constructor(e,t,o=J){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=o,this.debouncedMove=function(e,t,o){let i;return function(){const s=this,r=arguments,n=o&&!i;clearTimeout(i),i=setTimeout((function(){i=null,o||e.apply(s,r)}),t),n&&e.apply(s,r)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,o){if(!t.length||!o.length||!this.canApplyOptimisticUpdate())return;const i=new TC(this.uuidGenerator.uuidv4(),this.clientId,t,e,o,Date.now());this.revisions.append(i.id,i),this.trigger("new-local-state-update",{id:i.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:i.id,clientId:i.clientId,commands:i.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})}move(e){this.debouncedMove(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))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new AC("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(lt))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(e){const t=this.revisions.getRevertedExecution();for(const o of t){if("SNAPSHOT"===o.rootCommand)return;if(o.rootCommand&&"REMOTE"!==o.rootCommand&&(!e.includes(o.rootCommand?.type)&&o.commands.length))return o}}_move(e){if(!this.clients[this.clientId])return;const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const o=t?"CLIENT_MOVED":"CLIENT_JOINED",i=this.getClient();this.clients[this.clientId]={...i,position:e},this.transportService.sendMessage({type:o,version:1,client:{...i,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{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":const{clientId:t,commands:o,timestamp:i}=e,s=new TC(e.nextRevisionId,t,o,"REMOTE",void 0,i);if(s.clientId!==this.clientId){this.revisions.insert(s.id,s,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:IC(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new TC(e.nextRevisionId,"server",[],"SNAPSHOT",void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot");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;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({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.waitingAck=!0,this.sendPendingMessage())}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){const t=this.revisions.get(e.nextRevisionId);if(0===t.commands.length){this.revisions.drop(t.id);const e=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.nextRevisionId));return this.trigger("pending-revisions-dropped",{revisionIds:e}),this.waitingAck=!1,this.waitingUndoRedoAck=!1,void(this.pendingMessages=[])}e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":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.sendPendingMessage()}}isAlreadyProcessed(e){if("CLIENT_MOVED"===e.type&&e.client.id===this.clientId)return!0;switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":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})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const MC=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];var NC;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(NC||(NC={}));class _C extends fC{inputHasSingleRange;static layers=[1];static getters=[];ranges=[];focusedRangeIndex=null;activeSheet;willAddNewRange=!1;constructor(e,t,o){if(o&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e),this.inputHasSingleRange=o,this.insertNewRange(0,t),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}allowDispatch(e){switch(e.type){case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange&&1===this.ranges.length)return 30;break;case"CHANGE_RANGE":if(this.inputHasSingleRange&&e.value.split(",").length>1)return 30}return 0}handleEvent(e){const t=Ko(e.anchor.zone),o=this.activeSheet,i=this.getters.getActiveSheetId(),s=this.getters.getSheetName(i);this.add([i===o?t:`${Be(s)}!${t}`])}handle(e){switch(e.type){case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(this.getIndex(e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.rangeId);if(null!==t&&this.focusedRangeIndex!==t&&this.focus(t),null!==t){const o=e.value.replace(/^,+/,"").split(",").map((e=>e.trim()));this.setRange(t,o)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(this.ranges.length,[""]),this.focusLast();break;case"REMOVE_RANGE":const t=this.getIndex(e.rangeId);null!==t&&this.removeRange(t);break;case"STOP_SELECTION_INPUT":this.willAddNewRange=!1;break;case"PREPARE_SELECTION_INPUT_EXPANSION":{const e=this.focusedRangeIndex;null===e||this.inputHasSingleRange||(this.willAddNewRange=""!==this.ranges[e].xc.trim());break}case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),i=this.getters.expandZone(e.sheetIdTo,fi({col:t,row:o}));this.selection.resetAnchor(this,{cell:{col:t,row:o},zone:i})}}}getSelectionInputValue(){return this.cleanInputs(this.ranges.map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.ranges.map((e=>this.inputToHighlights(e))).flat()}focus(e){this.focusedRangeIndex=e}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null}add(e){null!==this.focusedRangeIndex&&0!==e.length&&(this.willAddNewRange?(this.insertNewRange(this.ranges.length,e),this.focusLast(),this.willAddNewRange=!1):this.setRange(this.focusedRangeIndex,e))}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){const o=Math.max(0,...this.ranges.map((e=>Number(e.id))));this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:o+t+1,color:It[(o+t)%It.length]}))))}setRange(e,t){const[,...o]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,o),o.length&&this.focus(e+o.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const o=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return o.map((e=>{const{sheetName:o}=Bo(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:o&&this.getters.getSheetIdByName(o)||this.activeSheet,color:t}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:o}=Bo(t),i=this.getters.getSheetIdByName(o),s=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(i===s||void 0===i&&s===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}const FC=[DC,function(e,t){return"target"in t&&Array.isArray(t.target)?{...Ve(t),target:e.getSelectedZones()}:t},function(e,t){if(!("row"in t)||!("col"in t))return t;const{col:o,row:i}=e.getActivePosition();return{...Ve(t),col:o,row:i}}];function DC(e,t){return"sheetId"in t?{...Ve(t),sheetId:e.getActiveSheetId()}:t}const LC=new Zo;function PC(e,t){const o=e.getSelectedZone();return{...DC(e,t),elements:"COL"===t.dimension?je(o.left,o.right+1):je(o.top,o.bottom+1)}}function kC(e,t){const o=e.getSelectedZone();return{...Ve(t),zone:o}}function UC(e,t){const o=Ve(t),i=e.getSelectedZone(),{top:s,bottom:r,left:n,right:a}=i;return"cols"in o?o.cols=je(n,a+1):"rows"in o&&(o.rows=je(s,r+1)),o}const VC=new _i;VC.add("UPDATE_CELL",BC),VC.add("CLEAR_CELL",BC),VC.add("DELETE_CONTENT",BC),VC.add("ADD_MERGE",BC),VC.add("REMOVE_MERGE",BC),VC.add("SET_FORMATTING",BC),VC.add("CLEAR_FORMATTING",BC),VC.add("SET_BORDER",BC),VC.add("CREATE_FILTER_TABLE",BC),VC.add("REMOVE_FILTER_TABLE",BC),VC.add("HIDE_SHEET",BC),VC.add("ADD_COLUMNS_ROWS",(function(e,t){const o=e.getActivePosition();return{...DC(e,t),base:"COL"===t.dimension?o.col:o.row}})),VC.add("REMOVE_COLUMNS_ROWS",PC),VC.add("HIDE_COLUMNS_ROWS",PC),VC.add("RESIZE_COLUMNS_ROWS",PC),VC.add("CREATE_SHEET",(function(e,t){const o=Ve(t);o.sheetId=LC.uuidv4();const i=t.name||e.getSheet(e.getActiveSheetId()).name,s=i.match(/(.+?)\d*$/)?.[1]||i;return o.name=e.getNextSheetName(s),o})),VC.add("CREATE_FIGURE",(function(e,t){const o=DC(e,t);return o.figure.id=LC.uuidv4(),o})),VC.add("CREATE_CHART",(function(e,t){return{...DC(e,t),id:LC.uuidv4()}})),VC.add("CREATE_IMAGE",(function(e,t){return{...DC(e,t),figureId:LC.uuidv4()}}));const zC=new _i;function BC(e,t){let o=Ve(t);for(const t of FC)o=t(e,o);return o}function HC(e,t){if(!t)return;if(!VC.contains(t.type))return;return VC.get(t.type)(e,t)}function $C(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return Es(e.rootCommand)?HC(t,e.rootCommand):function(e,t,o){if(!zC.contains(t.type))return;return zC.get(t.type)(e,t,o)}(t,e.rootCommand,e.commands)}zC.add("STOP_EDITION",(function(e,t,o){return o.map((t=>HC(e,t))).filter(lt)})),zC.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:Ve(t.pasteOption),target:e.getSelectedZones()}})),zC.add("INSERT_CELL",kC),zC.add("DELETE_CELL",kC),zC.add("AUTORESIZE_COLUMNS",UC),zC.add("AUTORESIZE_ROWS",UC),zC.add("SORT_CELLS",(function(e,t){const o=e.getSelectedZone();return{...DC(e,t),col:o.left,row:o.top,zone:o}})),zC.add("SUM_SELECTION",BC),zC.add("SET_DECIMAL",BC);class WC{getters;dispatch;selection;operation;sheetId;constructor(e,t,o,i){this.getters=t,this.dispatch=o,this.selection=i,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,o,i){const s=this.getters.getActiveSheetId(),r=t+i-this.getters.getNumberRows(s);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(s)-1,sheetId:s,quantity:r,position:"after"});const n=e+o-this.getters.getNumberCols(s);n>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(s)-1,sheetId:s,quantity:n,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class GC extends WC{cells;copiedTables;zones;constructor(e,t,o,i,s){if(super(t,o,i,s),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const r=new Set(e.map((e=>e.left))),n=new Set(e.map((e=>e.right))),a=new Set(e.map((e=>e.top))),l=new Set(e.map((e=>e.bottom))),c=1===a.size&&1===l.size||1===r.size&&1===n.size?function(e){return e.reduce(((e,t)=>{const o=e.length;for(let i=0;i<o;i++)if(ri(e[i],t))return e[i]=oi(e[i],t),e;return e[o]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>ui(e))).flat(),d=[...new Set(h.map((e=>e.col)))].sort(((e,t)=>e-t)),u=[...new Set(h.map((e=>e.row)))].sort(((e,t)=>e-t)),g=[],p=o.getActiveSheetId();for(let e of u){let t=[];for(let i of d){const s={col:i,row:e,sheetId:p};t.push({cell:o.getCell(s),style:o.getCellComputedStyle(s),evaluatedCell:o.getEvaluatedCell(s),border:o.getCellBorder(s)||void 0,position:s})}g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const o of je(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues({sheetId:p,col:o,row:e.zone.top}));m.push({filtersValues:t,zone:e.zone})}this.cells=g,this.zones=c,this.copiedTables=m}isCutAllowed(e){return 1!==e.length?19:0}isPasteAllowed(e,t){const o=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==t?.pasteOption)return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const i=this.cells.length,s=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(o,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(o,e[0])||i*s!=1))return 2;const{xSplit:r,ySplit:n}=this.getters.getPaneDivisions(o);for(const t of this.getPasteZones(e))if(t.left<r&&t.right>=r||t.top<n&&t.bottom>=n)return 75;return 0}paste(e,t){"COPY"===this.operation?this.pasteFromCopy(e,t):this.pasteFromCut(e,t);const o=this.cells.length,i=this.cells[0].length,s="CUT"===this.operation;t?.selectTarget&&this.selectPastedZone(i,o,s,e)}pasteFromCopy(e,t){if(1===e.length){const o=this.cells.length,i=this.cells[0].length,s=this.pastedZones(e,i,o);for(const e of s)this.pasteZone(e.left,e.top,t)}else for(const o of e)for(let e=o.left;e<=o.right;e++)for(let i=o.top;i<=o.bottom;i++)this.pasteZone(e,i,t);void 0===t?.pasteOption&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const o=e[0];this.pasteZone(o.left,o.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:o.left,row:o.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.getters.getActiveSheetId(),target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,o){const i=e[0],s=Math.max(1,Math.floor((i.right+1-i.left)/t)),r=Math.max(1,Math.floor((i.bottom+1-i.top)/o)),n=[];for(let e=0;e<s;e++)for(let s=0;s<r;s++){const r=i.top+s*o,a=i.left+e*t;n.push({left:a,top:r,bottom:r+o-1,right:a+t-1})}return n}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const o=[],i=t.length,s=t[0].length,r=e[e.length-1],n=r.left,a=r.top,l=Math.max(1,Math.floor((r.right+1-n)/s)),c=Math.max(1,Math.floor((r.bottom+1-a)/i));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)o.push({left:n,top:a,right:n-1+e*s,bottom:a-1+t*i});return o}selectPastedZone(e,t,o,i){const s=i[0],r=s.left,n=s.top;if(t>1||e>1||o){const s=this.pastedZones(i,e,t),a=o?s[0]:oi(...s);this.selection.selectZone({cell:{col:r,row:n},zone:a})}}clearClippedZones(){for(const e of this.cells)for(const t of e)t.cell&&this.dispatch("CLEAR_CELL",t.position);this.dispatch("CLEAR_FORMATTING",{sheetId:this.sheetId,target:this.zones})}pasteZone(e,t,o){const i=this.cells.length,s=this.cells[0].length,r="onlyValue"!==o?.pasteOption&&o?.shouldPasteCF,n=this.getters.getActiveSheetId();this.addMissingDimensions(s,i,e,t);for(let a=0;a<i;a++){const i=this.cells[a];for(let l=0;l<s;l++){const s=i[l],c={col:e+l,row:t+a,sheetId:n};"CUT"!==this.operation&&this.pasteMergeIfExist(s.position,c),this.pasteCell(s,c,this.operation,o),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{originPosition:s.position,targetPosition:c,operation:this.operation})}}}pasteCell(e,t,o,i){const{sheetId:s,col:r,row:n}=t,a=this.getters.getEvaluatedCell(t);if("onlyValue"!==i?.pasteOption){const o=this.getters.getCellBorder(t),i=e.border,a={top:o?.top||i?.top,bottom:o?.bottom||i?.bottom,left:o?.left||i?.left,right:o?.right||i?.right};this.dispatch("SET_BORDER",{sheetId:s,col:r,row:n,border:a})}if(e.cell){if("onlyFormat"===i?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.evaluatedCell.format});if("onlyValue"===i?.pasteOption){const o=uo(e.evaluatedCell.value);return void this.dispatch("UPDATE_CELL",{...t,content:o})}let a=e.cell.content;if(e.cell.isFormula&&"COPY"===o){const t=r-e.position.col,i=n-e.position.row;a=this.getUpdatedContent(s,e.cell,t,i,o)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===i?.pasteOption?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===i?.pasteOption?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,o,i,s){const r=this.getters.createAdaptedRanges(t.dependencies,o,i,e);return this.getters.buildFormulaContent(e,t,r)}pasteMergeIfExist(e,t){let{sheetId:o,col:i,row:s}=e;const{col:r,row:n}=this.getters.getMainCellPosition(e);if(r===i&&n===s){const r=this.getters.getMerge(e);if(!r)return;({sheetId:o,col:i,row:s}=t),this.dispatch("ADD_MERGE",{sheetId:o,force:!0,target:[{left:i,top:s,right:i+r.right-r.left,bottom:s+r.bottom-r.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),o=e[0],i=this.zones[0],s=[o.left-i.left,o.top-i.top];for(const e of this.copiedTables){const o=gi(e.zone,"both","MOVE",s);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[o]});for(const i of je(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:o.left+i,row:o.top,values:e.filtersValues[i]})}}getClipboardContent(){return{[fs.PlainText]:this.getPlainTextContent(),[fs.Html]:this.getHTMLContent()}}getPlainTextContent(){return this.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.position,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}getHTMLContent(){if(1==this.cells.length&&1==this.cells[0].length)return this.getters.getCellText(this.cells[0][0].position);let e='<table border="1" style="border-collapse:collapse">';for(const t of this.cells){e+="<tr>";for(const o of t){e+=`<td style="${Ti(Ii(o.style))}">`+MS(this.getters.getCellText(o.position))+"</td>"}e+="</tr>"}return e+="</table>",e}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let o of this.zones){if("COL"===t&&e<=o.right)return!0;if("ROW"===t&&e<=o.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:o}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*o;for(const e of this.zones){const{x:o,y:i,width:s,height:r}=this.getters.getVisibleRect(e);s>0&&r>0&&t.strokeRect(o,i,s,r)}}}}class qC{operation;getters;dispatch;sheetId;copiedFigure;copiedFigureContent;constructor(e,t,o){this.operation=e,this.getters=t,this.dispatch=o,this.sheetId=t.getActiveSheetId();const i=t.getSelectedFigureId();if(!i)throw new Error("No figure selected");const s=t.getFigure(this.sheetId,i);if(!s)throw new Error(`No figure for the given id: ${i}`);switch(this.copiedFigure={...s},s.tag){case"chart":this.copiedFigureContent=new ZC(o,t,this.sheetId,i);break;case"image":this.copiedFigureContent=new jC(o,t,this.sheetId,i);break;default:throw new Error(`Unknow tag '${s.tag}' for the given figure id: ${i}`)}}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?73:void 0!==t?.pasteOption?22:0}paste(e){const t=this.getters.getActiveSheetId(),{width:o,height:i}=this.copiedFigure,s=this.getters.getNumberCols(t),r=this.getters.getNumberRows(t),n=this.getters.getColDimensions(t,e[0].left).start,a=this.getters.getRowDimensions(t,e[0].top).start,l=this.getters.getColDimensions(t,s-1).end,c=this.getters.getRowDimensions(t,r-1).end,h={x:l<o?0:Math.min(n,l-o),y:c<i?0:Math.min(a,c-i)},d=(new Zo).uuidv4();this.copiedFigureContent.paste(t,d,h,{height:i,width:o}),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedFigureContent.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:d})}getClipboardContent(){return{[fs.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class ZC{dispatch;sheetId;copiedChart;constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const s=t.getChart(i);if(!s)throw new Error(`No chart for the given id: ${i}`);this.copiedChart=s.copyInSheetId(o)}paste(e,t,o,i){const s=this.copiedChart.copyInSheetId(e);this.dispatch("CREATE_CHART",{id:t,sheetId:e,position:o,size:i,definition:s.getDefinition()})}}class jC{dispatch;sheetId;copiedImage;constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const s=t.getImage(i);this.copiedImage=Ve(s)}paste(e,t,o,i){const s=Ve(this.copiedImage);this.dispatch("CREATE_IMAGE",{figureId:t,sheetId:e,position:o,size:i,definition:s})}}class YC extends WC{values;constructor(e,t,o,i){super("COPY",t,o,i),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const o=this.getters.getActiveSheetId(),i=this.getPasteZone(e);return this.getters.doesIntersectMerge(o,i)?2:0}paste(e){const t=this.values,o=this.getPasteZone(e),{left:i,top:s}=o,{numberOfCols:r,numberOfRows:n}=hi(o),a=this.getters.getActiveSheetId();this.addMissingDimensions(r,n,i,s);for(let e=0;e<t.length;e++)for(let o=0;o<t[e].length;o++)this.dispatch("UPDATE_CELL",{row:s+e,col:i+o,content:t[e][o],sheetId:a});const l={left:i,top:s,right:i+r-1,bottom:s+n-1};this.selection.selectZone({cell:{col:i,row:s},zone:l})}getClipboardContent(){return{[fs.PlainText]:this.values.map((e=>e.join("\t"))).join("\n")}}getPasteZone(e){const t=this.values.length,o=Math.max(...this.values.map((e=>e.length))),{left:i,top:s}=e[0];return{top:s,left:i,bottom:s+t-1,right:i+o-1}}}function XC(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:o}=Bo(e.value),[i,s]=t.split(":"),r=o?`${Be(o)}!`:"",n=KC(i),a=s?`:${KC(s)}`:"";return{...e,value:r+n+a}}function KC(e){switch(function(e){if(function(e){return e.startsWith("$")&&e.length>1&&e.slice(1).includes("$")}(e))return"colrow";if(function(e){return e.startsWith("$")}(e))return"col";if(function(e){return e.includes("$",1)}(e))return"row";return"none"}(e)){case"none":e=QC(e,"colrow");break;case"colrow":e=QC(e,"row");break;case"row":e=QC(e,"col");break;case"col":e=QC(e,"none")}return e}function QC(e,t){let o;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return o=e.search(/[0-9]/),e.slice(0,o)+"$"+e.slice(o);case"colrow":return o=e.search(/[0-9]/),"$"+(e=e.slice(0,o)+"$"+e.slice(o));case"none":return e}}const JC=r("The cell you are trying to edit has been deleted.");const eE=[{name:r("Sum"),types:[ms.number],compute:e=>Bl.compute([e])},{name:r("Avg"),types:[ms.number],compute:e=>Ql.compute([e])},{name:r("Min"),types:[ms.number],compute:e=>mc.compute([e])},{name:r("Max"),types:[ms.number],compute:e=>dc.compute([e])},{name:r("Count"),types:[ms.number,ms.text,ms.boolean,ms.error],compute:e=>nc.compute([e])},{name:r("Count Numbers"),types:[ms.number,ms.text,ms.boolean,ms.error],compute:e=>rc.compute([e])}];const tE=(new _i).add("sheet",class extends cC{static getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","getEvaluationSheets","doesHeaderExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","isEmpty","getSheetSize","getSheetZone","getPaneDivisions","checkZonesExistInSheet","getCommandZones"];sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(0!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?9:0;case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex((t=>t===e.sheetId));return this.findIndexOfTargetSheet(t,e.delta),0}catch(e){return 14}case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.orderedSheetIds.length>1?0:9;case"ADD_COLUMNS_ROWS":const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return e.base<0||e.base>t?86:e.quantity<=0?87:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return Math.min(...e.elements)<0||Math.max(...e.elements)>t?86:0}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return 0}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIdsMapName",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.name);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);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?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")}}import(e){for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let t of e.sheets){const e=t.name||s("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:o,rowNumber:i}=this.getImportedSheetSize(t),r={id:t.id,name:e,numberOfCols:o,rows:qo(i),areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0}};this.orderedSheetIds.push(r.id),this.sheets[r.id]=r}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(lt).map((e=>{const t=this.sheets[e],o={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},conditionalFormats:[],figures:[],filterTables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible};return(t.panes.xSplit||t.panes.ySplit)&&(o.panes=t.panes),o}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new 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){const t=ze(e);for(const e in this.sheetIdsMapName)if(e.toUpperCase()===t.toUpperCase())return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getEvaluationSheets(){return this.sheets}doesHeaderExist(e,t,o){return"COL"===t?o>=0&&o<this.getNumberCols(e):o>=0&&o<this.getNumberRows(e)}getRow(e,t){const o=this.getSheet(e).rows[t];if(!o)throw new Error(`Row ${o} not found.`);return o}getCell({sheetId:e,col:t,row:o}){const i=this.tryGetSheet(e)?.rows[o]?.cells[t];if(void 0!==i)return this.getters.getCellById(i)}getColsZone(e,t,o){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:o}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(lt)}getRowsZone(e,t,o){return{top:t,bottom:o,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){let t=1;const o=this.orderedSheetIds.map(this.getSheetName.bind(this));let i=`${e}${t}`;for(;o.includes(i);)i=`${e}${t}`,t++;return i}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}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,o){const i={...this.getPaneDivisions(e)};"COL"===o?i.xSplit=t:"ROW"===o&&(i.ySplit=t),this.history.update("sheets",e,"panes",i)}isEmpty(e,t){return ui(t).map((({col:t,row:o})=>this.getCell({sheetId:e,col:t,row:o}))).every((e=>!e||""===e.content))}getCommandZones(e){const 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&&"row"in e&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Xo))return 25;if(t.length){const o=this.getSheetZone(e);return t.every((e=>ai(e,o)))?0:18}return 0}updateCellPosition(e){const{sheetId:t,cellId:o,col:i,row:s}=e;o?this.setNewPosition(o,t,i,s):this.clearPosition(t,i,s)}setNewPosition(e,t,o,i){const s=this.cellPosition[e];s&&this.clearPosition(t,s.col,s.row),this.history.update("cellPosition",e,{row:i,col:o,sheetId:t}),this.history.update("sheets",t,"rows",i,"cells",o,e)}clearPosition(e,t,o){const i=this.sheets[e]?.rows[o].cells[t];i&&(this.history.update("cellPosition",i,void 0),this.history.update("sheets",e,"rows",o,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){this.sheets[e].rows[i].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:i})}}createSheet(e,t,o,i,s){const r={id:e,name:t,numberOfCols:o,rows:qo(i),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},n=this.orderedSheetIds.slice();n.splice(s,0,r.id);const a=this.sheets;return this.history.update("orderedSheetIds",n),this.history.update("sheets",Object.assign({},a,{[r.id]:r})),r}moveSheet(e,t){const o=this.orderedSheetIds.slice(),i=o.findIndex((t=>t===e)),s=o.splice(i,1);let r=this.findIndexOfTargetSheet(i,t);o.splice(r,0,s[0]),this.history.update("orderedSheetIds",o)}findIndexOfTargetSheet(e,t){for(;0!=t&&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(0===t)return e;throw new Error(r("There is not enough visible sheets"))}checkSheetName(e){const{orderedSheetIds:t,sheets:o}=this,i=e.name&&e.name.trim().toLowerCase();return t.find((e=>o[e]?.name.toLowerCase()===i))?11:le.test(i)?13:0}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?15:0}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?0:74}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:74}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.top<e.quantity&&e.quantity<=o.bottom)return 65;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.left<e.quantity&&e.quantity<=o.right)return 65;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const o=e.name;this.history.update("sheets",e.id,"name",t.trim());const i=Object.assign({},this.sheetIdsMapName);i[t]=e.id,delete i[o],this.history.update("sheetIdsMapName",i)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const o=this.getSheet(e),i=this.getDuplicateSheetName(o.name),s=Ve(o);s.id=t,s.name=i;for(let e=0;e<=s.numberOfCols;e++)for(let t=0;t<=s.rows.length;t++)s.rows[t]&&(s.rows[t].cells[e]=void 0);const r=this.orderedSheetIds.slice(),n=r.indexOf(e);r.splice(n+1,0,s.id),this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},this.sheets,{[s.id]:s}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:o}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:s.id,col:e,row:o,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[s.name]=s.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const o=this.orderedSheetIds.map(this.getSheetName.bind(this)),i=r("Copy of %s",e);let s=i.toString();for(;o.includes(s);)s=`${i} (${t})`,t++;return s}deleteSheet(e){const t=e.name,o=Object.assign({},this.sheets);delete o[e.id],this.history.update("sheets",o);const i=this.orderedSheetIds.slice(),s=i.indexOf(e.id);i.splice(s,1),this.history.update("orderedSheetIds",i);const r=Object.assign({},this.sheetIdsMapName);delete r[t],this.history.update("sheetIdsMapName",r)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let o of t)this.moveCellOnColumnsDeletion(e,o);const o=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",o-t.length);const i=t.filter((t=>t<e.panes.xSplit)).length;i&&this.setPaneDivisions(e.id,e.panes.xSplit-i,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let o of Ye(t))this.moveCellOnRowsDeletion(e,o[o.length-1],o[0]),o.map((t=>this.updateRowsStructureOnDeletion(t,e)));const o=t.filter((t=>t<e.panes.ySplit)).length;o&&this.setPaneDivisions(e.id,e.panes.ySplit-o,"ROW")}addColumns(e,t,o,i){const s="before"===o?t:t+1;this.moveCellsOnAddition(e,s,i,"columns");const r=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",r+i),s<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+i,"COL")}addRows(e,t,o,i){const s="before"===o?t:t+1;this.addEmptyRows(e,i),this.moveCellsOnAddition(e,s,i,"rows"),this.updateRowsStructureOnAddition(e,t,i),s<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+i,"ROW")}moveCellOnColumnsDeletion(e,t){for(let o=0;o<e.rows.length;o++){const i=e.rows[o];for(let s in i.cells){const r=Number(s),n=i.cells[s];n&&(r===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:r,row:o}),r>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:n,col:r-1,row:o}))}}}moveCellsOnAddition(e,t,o,i){const s=[];for(let r=0;r<e.rows.length;r++){const n=e.rows[r];if("rows"!==i||r>=t)for(let a in n.cells){const l=Number(a),c=n.cells[a];c&&("rows"===i||l>=t)&&s.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===i?o:0),row:r+("rows"===i?o:0)})}}for(let e of s.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,o){const i=o-t+1;for(let s=0;s<e.rows.length;s++){const r=e.rows[s];if(s>=t&&s<=o)for(let t in r.cells){const o=Number(t);r.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:o,row:s})}if(s>o)for(let t in r.cells){const o=Number(t),n=r.cells[t];n&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:n,col:o,row:s-i})}}}updateRowsStructureOnDeletion(e,t){const o=[],i=t.rows.map((e=>e.cells));for(let s in t.rows)Number(s)!==e&&o.push({cells:i.shift()});this.history.update("sheets",t.id,"rows",o)}updateRowsStructureOnAddition(e,t,o){const i=[],s=e.rows.map((e=>e.cells));e.rows.forEach((()=>i.push({cells:s.shift()}))),this.history.update("sheets",e.id,"rows",i)}addEmptyRows(e,t){const o=e.rows.slice();for(let e=0;e<t;e++)o.push({cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(Bt);let o=e.rowNumber,i=e.colNumber;for(let{col:e,row:s}of t)o=Math.max(o,s+1),i=Math.max(i,e+1);return{rowNumber:o,colNumber:i}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?27:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZonesAreInSheet(e){return"sheetId"in e?this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):0}}).add("header visibility",class extends cC{static getters=["canRemoveHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];hiddenHeaders={};allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return 27;const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),o="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=o?66:Math.min(...e.elements)<0||Math.max(...e.elements)>o?86:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.canRemoveHeaders(e.sheetId,e.dimension,e.elements)?0:8:27}return 0}handle(e){switch(e.type){case"CREATE_SHEET":const 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,Ve(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],o=pt(e.position,e.base);t.splice(o,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);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)}}canRemoveHeaders(e,t,o){const i=this.getAllVisibleHeaders(e,t);return s=o,!i.every((e=>s.includes(e)));var s}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]}getHiddenColsGroups(e){const t=[[]],o=this.hiddenHeaders[e].COL;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],o=this.hiddenHeaders[e].ROW;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){return je(0,this.hiddenHeaders[e][t].length).filter((o=>!this.hiddenHeaders[e][t][o]))}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]=Boolean(t.rows[e]?.isHidden);for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=Boolean(t.cols[e]?.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e=0;e<this.getters.getNumberRows(o.id);e++)(t||this.hiddenHeaders[o.id].ROW[e])&&(void 0===o.rows[e]&&(o.rows[e]={}),o.rows[e].isHidden=this.hiddenHeaders[o.id].ROW[e]);void 0===o.cols&&(o.cols={});for(let e=0;e<this.getters.getNumberCols(o.id);e++)(t||this.hiddenHeaders[o.id].COL[e])&&(void 0===o.cols[e]&&(o.cols[e]={}),o.cols[e].isHidden=this.hiddenHeaders[o.id].COL[e])}}}).add("filters",class extends cC{static getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];tables={};allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!Si(...e.target))return 81;const t=oi(...e.target),o=()=>this.getFilterTables(e.sheetId).some((e=>ri(e.zone,t)))?78:0,i=()=>{const o=this.getters.getMergesInZone(e.sheetId,t);for(let e of o)if(ri(t,e))return 80;return 0};return this.checkValidations(e,o,i);case"ADD_MERGE":for(let t of e.target)for(let o of this.getFilterTables(e.sheetId))if(ri(o.zone,t))return 80}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":this.history.update("tables",e.sheetIdTo,Ve(this.tables[e.sheetId]));break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=oi(...e.target),o=this.createFilterTable(t);this.history.update("tables",e.sheetId,o.id,o);break}case"REMOVE_FILTER_TABLE":{const t={};for(const o of this.getFilterTables(e.sheetId))e.target.every((e=>!ii(e,o.zone)))&&(t[o.id]=o);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let o of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,o)&&this.extendTableDown(t,o);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(lt):[]}getFilter(e){return this.getFilterTable(e)?.filters.find((t=>t.col===e.col))}getFilterId(e){return this.getFilter(e)?.id}getFilterTable({sheetId:e,col:t,row:o}){return this.getFilterTables(e).find((e=>ni(t,o,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>ai(e.zone,t)))}doesZonesContainFilter(e,t){for(const o of t)for(const t of this.getFilterTables(e))if(ii(o,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=Qo(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i=[];for(const o of t.filters){const t=Qo(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);i.push(new uC(o.id,t))}if(i.length<hi(o).numberOfCols){for(let e=o.left;e<=o.right;e++)i.find((t=>t.col===e))||i.push(new uC(this.uuidGenerator.uuidv4(),{...o,left:e,right:e}));i.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=ti(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(o){if(Ko(o)!==Ko(t.zone)){const i=[];for(const o of t.filters){const t=ti(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&i.push(new uC(o.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}else{const o={...this.tables[e.sheetId]};delete o[t.id],this.history.update("tables",e.sheetId,o)}}}createFilterTable(e){return new dC(e)}extendTableDown(e,t){const o={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",o);for(let o=0;o<t.filters.length;o++){const i=t.filters[o],s={...i.zoneWithHeaders,bottom:i.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",o,"zoneWithHeaders",s)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:o,row:i},s){if(!e)return;const r=s.zone;if(!(r.bottom+1===i&&o>=r.left&&o<=r.right))return!1;for(const e of je(r.left,r.right+1)){const o={sheetId:t,col:e,row:i},s=this.getters.getCell(o)?.content;if(s)return!1;if(this.getters.getFilter(o))return!1;if(this.getters.isInMerge(o))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const o=this.createFilterTable(Yo(e.range));this.history.update("tables",t.id,o.id,o)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:Ko(e.zone)})}exportForExcel(e){this.export(e)}}).add("cell",class extends cC{static getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];nextId=1;cells={};adaptRanges(e,t){for(const o of Object.keys(this.cells))for(const i of Object.values(this.cells[o]||{}))if(i.isFormula)for(const s of i.dependencies)if(!t||s.sheetId===t){const t=e(s);"NONE"!==t.changeType&&this.history.update("cells",o,i.id,"dependencies",i.dependencies.indexOf(s),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":case"CLEAR_CELL":return this.checkCellOutOfSheet(e.sheetId,e.col,e.row);default:return 0}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?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:""})}}setFormatter(e,t,o){for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let s=i.left;s<=i.right;s++)this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,format:o})}clearFormatting(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:null,format:""})}handleAddColumnsRows(e,t){let o,i;"before"===e.position?(o=je(e.base,e.base+e.quantity),i=e.base+e.quantity):(o=je(e.base+1,e.base+e.quantity+1),i=e.base),t(e.sheetId,i,o)}import(e){for(let t of e.sheets)for(let o in t.cells){const i=t.cells[o],{col:s,row:r}=Bt(o);if(i?.content||i?.format||i?.style){const o=this.importCell(t.id,i,e.styles,e.formats);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,col:s,row:r,sheetId:t.id})}}}export(e){const t={},o={};for(let i of e.sheets){const e={},s=Object.keys(this.cells[i.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const i of s){const s=this.getters.getCell(i);e[Ht(i.col,i.row)]={style:s.style?ht(s.style,t):void 0,format:s.format?ht(s.format,o):void 0,content:s.content||void 0}}i.cells=e}e.styles=t,e.formats=o}importCell(e,t,o,i){const s=t.style&&o[t.style]||void 0,r=t.format&&i[t.format]||void 0,n=this.getNextUid();return this.createCell(n,t?.content||"",r,s,e)}exportForExcel(e){this.export(e)}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t in this.cells){const o=this.cells[t][e];if(o)return o}}buildFormulaContent(e,t,o){const i=o||[...t.dependencies];return dt(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=i.shift();return this.getters.getRangeString(t,e)}return t.value})))}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,o=[{colFixed:!1,rowFixed:!1}]){const i=Ht((t=this.getters.expandZone(e,t)).left,t.top,o[0]),s=Ht(t.right,t.bottom,o.length>1?o[1]:o[0]),r=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),n=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=r.col===n.col&&r.row===n.row;return i==s||a?i:i+":"+s}setStyle(e,t,o){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let s=i.top;s<=i.bottom;s++){const i=this.getters.getCell({sheetId:e,col:t,row:s});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,style:o?{...i?.style,...o}:void 0})}}copyColumnStyle(e,t,o){for(let i=0;i<this.getters.getNumberRows(e);i++){const s=this.getFormat(e,t,i);if(s.style||s.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,...s})}}copyRowStyle(e,t,o){for(let i=0;i<this.getters.getNumberCols(e);i++){const s=this.getFormat(e,i,t);if(s.style||s.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,...s})}}getFormat(e,t,o){const i={},s=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),r=this.getters.getCell(s);return r&&(r.style&&(i.style=r.style),r.format&&(i.format=r.format)),i}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,o,i){const s=this.getters.getCell({sheetId:e,col:t,row:o}),r="content"in i||"formula"in i,n=r?Et(i?.content):s?.content||"";let a;a=void 0!==i.style?i.style||void 0:s?s.style:void 0;let l=("format"in i?i.format:s&&s.format)||xo(n);if((r&&!n&&!i.formula||!r&&(!s||""===s.content))&&!a&&!l)return void(s&&(this.history.update("cells",e,s.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:o,sheetId:e})));const c=s?.id||this.getNextUid(),h=this.createCell(c,n,l,a,e);this.history.update("cells",e,h.id,h),this.dispatch("UPDATE_CELL_POSITION",{cellId:h.id,col:t,row:o,sheetId:e})}createCell(e,t,o,i,s){if(!t.startsWith("="))return this.createLiteralCell(e,t,o,i);try{return this.createFormulaCell(e,t,o,i,s)}catch(s){return this.createErrorFormula(e,t,o,i,s)}}createLiteralCell(e,t,o,i){return{id:e,content:t,style:i,format:o,isFormula:!1}}createFormulaCell(e,t,o,i,s){const r=Wv(t);return r.dependencies.length?this.createFormulaCellWithDependencies(e,r,o,i,s):{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:r,dependencies:[]}}createFormulaCellWithDependencies(e,t,o,i,s){const r=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(s,e))),n=this.buildFormulaContent.bind(this);return{id:e,get content(){return n(s,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:i,format:o,isFormula:!0,compiledFormula:t,dependencies:r}}createErrorFormula(e,t,o,i,s){return{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:{dependencies:[],tokens:av(t),execute:function(){throw s}},dependencies:[]}}checkCellOutOfSheet(e,t,o){if(!this.getters.tryGetSheet(e))return 27;return ni(t,o,this.getters.getSheetZone(e))?0:18}}).add("merge",class extends cC{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];nextId=1;merges={};mergeCellMap={};allowDispatch(e){const t="force"in e&&!!e.force;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 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const o of Object.values(t).filter(lt))this.addMerge(e.sheetIdTo,o.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const o=t?[t]:Object.keys(this.merges);for(const t of o)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(lt)}getMerge({sheetId:e,col:t,row:o}){const i=this.mergeCellMap[e],s=i?t in i&&i[t]?.[o]:void 0;return s?this.getMergeById(e,s):void 0}getMergesInZone(e,t){const o=this.mergeCellMap[e];if(!o)return[];const i=new Set;for(const{col:e,row:s}of ui(t)){const t=o[e]?.[s];t&&i.add(t)}return Array.from(i).map((t=>this.getMergeById(e,t))).filter(lt)}doesIntersectMerge(e,t){return ui(t).some((({col:t,row:o})=>void 0!==this.getMerge({sheetId:e,col:t,row:o})))}doesColumnsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let s=0;s<this.getters.getNumberRows(e);s++)if(this.isInSameMerge(i.id,t,s,o,s))return!0;return!1}doesRowsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let s=0;s<=this.getters.getNumberCols(e);s++)if(this.isInSameMerge(i.id,s,t,s,o))return!0;return!1}expandZone(e,t){let{left:o,right:i,top:s,bottom:r}=t,n={left:o,right:i,top:s,bottom:r};for(let t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&ri(o,n)&&(n=oi(o,n))}return si(n,t)?n:this.expandZone(e,n)}isInSameMerge(e,t,o,i,s){const r=this.getMerge({sheetId:e,col:t,row:o}),n=this.getMerge({sheetId:e,col:i,row:s});return!(!r||!n)&&si(r,n)}isInMerge({sheetId:e,col:t,row:o}){const i=this.mergeCellMap[e];return!!i&&(t in i&&Boolean(i[t]?.[o]))}getMainCellPosition(e){if(!this.isInMerge(e))return e;const t=this.getMerge(e).topLeft;return{sheetId:e.sheetId,col:t.col,row:t.row}}getBottomLeftCell(e){if(!this.isInMerge(e))return e;const{bottom:t,left:o}=this.getMerge(e);return{sheetId:e.sheetId,col:o,row:t}}isMergeHidden(e,t){const o=this.getters.getHiddenColsGroups(e),i=this.getters.getHiddenRowsGroups(e);for(let e of o)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of i)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const o=this.getMerge({sheetId:e,col:t.left,row:t.top});if(o)return si(t,o);const{numberOfCols:i,numberOfRows:s}=hi(t);return 1===i&&1===s}isMergeDestructive(e,t){let{left:o,right:i,top:s,bottom:r}=t;i=He(i,0,this.getters.getNumberCols(e)-1),r=He(r,0,this.getters.getNumberRows(e)-1);for(let t=s;t<=r;t++)for(let r=o;r<=i;r++)if(r!==o||t!==s){const o=this.getters.getCell({sheetId:e,col:r,row:t});if(o&&""!==o.content)return!0}return!1}getMergeById(e,t){const o=this.merges[e]?.[t];return void 0!==o?pC(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;return t.some((t=>this.isMergeDestructive(e,t)))?3:0}checkOverlap({target:e}){for(const t of e)for(const o of e)if(t!==o&&ri(t,o))return 65;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:o,ySplit:i}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<o&&e.right>=o||e.top<i&&e.bottom>=i)return 75;return 0}checkMergedContentUpdate(e){const{col:t,row:o,content:i}=e;if(void 0===i)return 0;const{col:s,row:r}=this.getMainCellPosition(e);return s===t&&r===o?0:4}checkMergeExists(e){const{sheetId:t,target:o}=e;for(const e of o){const{left:o,top:i}=e,s=this.getMerge({sheetId:t,col:o,row:i});if(void 0===s||!si(e,s))return 5}return 0}addMerge(e,t){let{left:o,right:i,top:s,bottom:r}=t;i=He(i,0,this.getters.getNumberCols(e)-1),r=He(r,0,this.getters.getNumberRows(e)-1);if(Ht(o,s)===Ht(i,r))return;const n=this.getters.getCell({sheetId:e,col:o,row:s});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Ko({left:o,top:s,right:i,bottom:r})));let l=new Set;for(let t=s;t<=r;t++)for(let r=o;r<=i;r++){r===o&&t===s||this.dispatch("UPDATE_CELL",{sheetId:e,col:r,row:t,style:n?n.style:null,content:""});const i=this.getMerge({sheetId:e,col:r,row:t});i&&l.add(i.id),this.history.update("mergeCellMap",e,r,t,a)}for(let t of l){const{top:o,bottom:i,left:s,right:r}=this.getMergeById(e,t);for(let t=o;t<=i;t++)for(let o=s;o<=r;o++){const i={sheetId:e,col:o,row:t},s=this.getMerge(i);s&&s.id===a||(this.history.update("mergeCellMap",e,o,t,void 0),this.dispatch("CLEAR_CELL",i))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:o,top:i,bottom:s,right:r}=t,n=this.getMerge({sheetId:e,col:o,row:i});if(void 0!==n&&si(t,n)){this.history.update("merges",e,n.id,void 0);for(let t=i;t<=s;t++)for(let i=o;i<=r;i++)this.history.update("mergeCellMap",e,i,t,void 0)}}applyRangeChangeOnSheet(e,t){const o=Object.entries(this.merges[e]||{});for(const[i,s]of o)if(s){const o=s.zone,r=t(s);switch(r.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,o);break;default:const{numberOfCols:t,numberOfRows:s}=hi(r.range.zone);1===t&&1===s?this.removeMerge(e,o):this.history.update("merges",e,parseInt(i,10),r.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:o,row:i}of ui(t))this.history.update("mergeCellMap",e,o,i,t.id)}import(e){const 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 o of t)this.addMerge(e,Yo(o))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...gC(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends cC{static getters=["getRowSize","getColSize"];sizes={};handle(e){switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),o={COL:t.COL.map((e=>({manualSize:void 0,computedSize:ut(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:ut(e)})))};this.history.update("sizes",e.sheetId,o);break}case"DUPLICATE_SHEET":for(const t of this.sizes[e.sheetId].ROW)t.computedSize();for(const t of this.sizes[e.sheetId].COL)t.computedSize();this.history.update("sizes",e.sheetIdTo,Ve(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const 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]];for(let o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);const o=Math.min(...e.elements);t=t.map(((t,i)=>"ROW"===e.dimension&&i>=o?{manualSize:t.manualSize,computedSize:ut((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const o=pt(e.position,e.base),i=t[e.base];t.splice(o,0,...Array(e.quantity).fill(i)),t=t.map(((t,o)=>"ROW"===e.dimension&&o>e.base+e.quantity?{manualSize:t.manualSize,computedSize:ut((()=>this.getRowTallestCellSize(e.sheetId,o)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":for(let t of e.elements)if("ROW"===e.dimension){const o=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:ut(o)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:ut(e.size||D)});break;case"UPDATE_CELL":if(!this.sizes[e.sheetId]?.ROW?.[e.row]?.manualSize){const{sheetId:t,row:o}=e;this.history.update("sizes",t,"ROW",o,"computedSize",ut((()=>this.getRowTallestCellSize(t,o))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let o of je(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,o);t!==this.getRowSize(e.sheetId,o)&&this.history.update("sizes",e.sheetId,"ROW",o,"computedSize",ut(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,o){return Math.round(this.sizes[e]?.[t][o]?.manualSize||this.sizes[e]?.[t][o]?.computedSize()||this.getDefaultHeaderSize(t))}computeSheetSizes(e){const t={COL:[],ROW:[]};for(let o of je(0,this.getters.getNumberCols(e)))t.COL.push(this.getHeaderSize(e,"COL",o));for(let o of je(0,this.getters.getNumberRows(e))){let i=this.sizes[e]?.ROW?.[o].manualSize;if(!i){i=this.getRowTallestCellSize(e,o)}t.ROW.push(i)}return t}getDefaultHeaderSize(e){return"COL"===e?D:L}getCellHeight(e){const t=this.getters.getMerge(e);if(t&&t.bottom!==t.top)return L;return function(e){return e&&e.content?$e(Ze(e.style),e.isFormula?1:e.content.split(pe).length)+2*B:L}(this.getters.getCell(e))}getRowTallestCellSize(e,t){const o=this.getters.getRowCells(e,t);let i=0;for(let e=0;e<o.length;e++){const t=this.getters.getCellById(o[e]);if(!t)continue;const s=this.getters.getCellPosition(t.id),r=this.getCellHeight(s);r>i&&r>L&&(i=r)}return i<=L?L:i}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[o,i]of Object.entries(t.rows))i.size&&(e.ROW[o]=i.size);for(let[o,i]of Object.entries(t.cols))i.size&&(e.COL[o]=i.size);const o=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:o.COL.map(((t,o)=>({manualSize:e.COL[o],computedSize:ut(t)}))),ROW:o.ROW.map(((t,o)=>({manualSize:e.ROW[o],computedSize:ut(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e of je(0,this.getters.getNumberRows(o.id)))(t||this.sizes[o.id].ROW[e]?.manualSize)&&(o.rows[e]={...o.rows[e],size:this.getRowSize(o.id,e)});void 0===o.cols&&(o.cols={});for(let e of je(0,this.getters.getNumberCols(o.id)))(t||this.sizes[o.id].COL[e]?.manualSize)&&(o.cols[e]={...o.cols[e],size:this.getColSize(o.id,e)})}}}).add("borders",class extends cC{static getters=["getCellBorder","getBordersColors"];borders={};handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const o=t.slice().map((e=>e?.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,o)}break;case"DELETE_SHEET":const o={...this.borders};delete o[e.sheetId],this.history.update("borders",o);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_ZONE_BORDERS":if(e.border){const 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||Y,color:e.border.color||X})}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of e.elements)"COL"===e.dimension?this.shiftBordersHorizontally(e.sheetId,t+1,-1):this.shiftBordersVertically(e.sheetId,t+1,-1);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){let t,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,o)}handleAddRows(e){let t,o;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,o)}getCellBorder({sheetId:e,col:t,row:o}){const i={top:this.borders[e]?.[t]?.[o]?.horizontal,bottom:this.borders[e]?.[t]?.[o+1]?.horizontal,left:this.borders[e]?.[t]?.[o]?.vertical,right:this.borders[e]?.[t+1]?.[o]?.vertical};return i.bottom||i.left||i.right||i.top?i:null}getBordersColors(e){const t=[],o=this.borders[e];if(o)for(const e of o.filter(lt))for(const o of e)o?.horizontal&&t.push(o.horizontal.color),o?.vertical&&t.push(o.vertical.color);return t}ensureColumnBorderContinuity(e,t,o){const i=je(t+1,o);for(let s=0;s<this.getters.getNumberRows(e);s++){const r=this.getCellBorder({sheetId:e,col:t,row:s}),n=this.getCellBorder({sheetId:e,col:o,row:s});if(r&&n){const t=this.getCommonSides(r,n);for(let o of i)this.addBorder(e,o,s,t)}}}ensureRowBorderContinuity(e,t,o){const i=je(t+1,o);for(let s=0;s<this.getters.getNumberCols(e);s++){const r=this.getCellBorder({sheetId:e,col:s,row:t}),n=this.getCellBorder({sheetId:e,col:s,row:o});if(r&&n){const t=this.getCommonSides(r,n);for(let o of i)this.addBorder(e,s,o,t)}}}getCommonSides(e,t){const o={};for(let i of["top","bottom","left","right"])e[i]&&e[i]===t[i]&&(o[i]=e[i]);return o}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){return this.borders[e]?je(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,o,{moveFirstLeftBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfColumn(e,t,o,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((s=>{(s===t&&i||s!==t)&&this.moveBordersOfColumn(e,s,o,"vertical"),this.moveBordersOfColumn(e,s,o,"horizontal")})))}shiftBordersVertically(e,t,o,{moveFirstTopBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfRow(e,t,o,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((s=>{(s===t&&i||s!==t)&&this.moveBordersOfRow(e,s,o,"horizontal"),this.moveBordersOfRow(e,s,o,"vertical")})))}moveBordersOfRow(e,t,o,i,{destructive:s}={destructive:!0}){const r=this.borders[e];r&&this.getColumnsWithBorders(e).forEach((n=>{const a=r[n]?.[t+o]?.[i],l=r[n]?.[t]?.[i];this.history.update("borders",e,n,t+o,i,s?l:l||a),this.history.update("borders",e,n,t,i,void 0)}))}moveBordersOfColumn(e,t,o,i,{destructive:s}={destructive:!0}){const r=this.borders[e];r&&this.getRowsRange(e).forEach((n=>{const a=r[t+o]?.[n]?.[i],l=r[t]?.[n]?.[i];this.history.update("borders",e,t+o,n,i,s?l:l||a),this.history.update("borders",e,t,n,i,void 0)}))}setBorder(e,t,o,i,s=!0){!s&&this.borders?.[e]?.[t]?.[o]?.vertical||this.history.update("borders",e,t,o,"vertical",i?.left),!s&&this.borders?.[e]?.[t]?.[o]?.horizontal||this.history.update("borders",e,t,o,"horizontal",i?.top),!s&&this.borders?.[e]?.[t+1]?.[o]?.vertical||this.history.update("borders",e,t+1,o,"vertical",i?.right),!s&&this.borders?.[e]?.[t]?.[o+1]?.horizontal||this.history.update("borders",e,t,o+1,"horizontal",i?.bottom)}clearBorders(e,t){for(let o of t){for(let t=o.top;t<=o.bottom;t++){this.history.update("borders",e,o.right+1,t,"vertical",void 0);for(let i=o.left;i<=o.right;i++)this.history.update("borders",e,i,t,void 0)}for(let t=o.left;t<=o.right;t++)this.history.update("borders",e,t,o.bottom+1,"horizontal",void 0)}}addBorder(e,t,o,i){this.setBorder(e,t,o,{...this.getCellBorder({sheetId:e,col:t,row:o}),...i})}setBorders(e,t,o,i){if("clear"===o)return this.clearBorders(e,t);for(let s of t){if("h"===o||"hv"===o||"all"===o)for(let t=s.top+1;t<=s.bottom;t++)for(let o=s.left;o<=s.right;o++)this.addBorder(e,o,t,{top:i});if("v"===o||"hv"===o||"all"===o)for(let t=s.top;t<=s.bottom;t++)for(let o=s.left+1;o<=s.right;o++)this.addBorder(e,o,t,{left:i});if("left"===o||"all"===o||"external"===o)for(let t=s.top;t<=s.bottom;t++)this.addBorder(e,s.left,t,{left:i});if("right"===o||"all"===o||"external"===o)for(let t=s.top;t<=s.bottom;t++)this.addBorder(e,s.right+1,t,{left:i});if("top"===o||"all"===o||"external"===o)for(let t=s.left;t<=s.right;t++)this.addBorder(e,t,s.top,{top:i});if("bottom"===o||"all"===o||"external"===o)for(let t=s.left;t<=s.right;t++)this.addBorder(e,t,s.bottom+1,{top:i})}}addBordersToMerge(e,t){const{left:o,right:i,top:s,bottom:r}=t,n=this.getCellBorder({sheetId:e,col:o,row:s}),a=this.getCellBorder({sheetId:e,col:i,row:r});this.clearBorders(e,[t]),n?.top&&this.setBorders(e,[{...t,bottom:s}],"top",n.top),n?.left&&this.setBorders(e,[{...t,right:o}],"left",n.left),a?.bottom?this.setBorders(e,[{...t,top:r}],"bottom",a.bottom):n?.bottom&&this.setBorders(e,[{...t,top:r}],"bottom",n.bottom),a?.right?this.setBorders(e,[{...t,left:i}],"right",a.right):n?.right&&this.setBorders(e,[{...t,left:i}],"right",n.right)}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(const o in t.cells){const i=t.cells[o];if(i?.border){const s=e.borders[i.border],{col:r,row:n}=Bt(o);this.setBorder(t.id,r,n,s,!1)}}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Yo(e))}export(e){let t=0;const o={};function i(e){for(let[t,i]of Object.entries(o))if(Pe(i)===Pe(e))return parseInt(t,10);return o[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let o=0;o<t.rowNumber;o++){const s=this.getCellBorder({sheetId:t.id,col:e,row:o});if(s){const r=Ht(e,o),n=t.cells[r],a=i(s);n?n.border=a:t.cells[r]={border:a}}}e.borders=o}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends cC{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];cfRules={};loopThroughRangesOfSheet(e,t){for(const o of this.cfRules[e])for(const i of o.ranges){const s=t(i);switch(s.changeType){case"REMOVE":let t=o.ranges.slice();t.splice(o.ranges.indexOf(i),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",t):this.removeConditionalFormatting(o.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",o.ranges.indexOf(i),s.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case"MOVE_CONDITIONAL_FORMAT":return this.checkValidReordering(e.cfId,e.direction,e.sheetId)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const o={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(o,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"MOVE_CONDITIONAL_FORMAT":this.reorderConditionalFormatting(e.cfId,e.direction,e.sheetId)}}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){this.export(e)}getConditionalFormats(e){return this.cfRules[e]?.map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const o=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{o.add(e)}))})),Array.from(o)}getRulesByZone(e,t){const o=new Set;for(let i=t.top;i<=t.bottom;i++)for(let s=t.left;s<=t.right;s++){this.getRulesByCell(e,s,i).forEach((e=>{o.add(e.id)}))}return o}getRulesByCell(e,t,o){const i=[];for(let s of this.cfRules[e])for(let e of s.ranges)ni(t,o,e.zone)&&i.push(s);return new Set(i.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const o={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return o}addConditionalFormatting(e,t){const o=this.cfRules[t].slice(),i=o.findIndex((t=>t.id===e.id)),s=this.mapToConditionalFormatInternal(t,e);i>-1?o.splice(i,1,s):o.push(s),this.history.update("cfRules",t,o)}checkValidReordering(e,t,o){if(!this.cfRules[o])return 27;const i=this.cfRules[o].findIndex((t=>t.id===e));if(-1===i)return 71;const s="up"===t?i-1:i+1;return s<0||s>=this.cfRules[o].length?71:0}checkEmptyRange(e){return e.ranges.length?0:24}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));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)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return o=>{if(t.includes(o.operator)){const t=[],i=e=>void 0===e||""===e;return e>=1&&i(o.values[0])&&t.push(51),e>=2&&i(o.values[1])&&t.push(52),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 53;case"max":return 55;case"mid":return 54;case"upperInflectionPoint":return 56;case"lowerInflectionPoint":return 57}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{Wv(e.value||"")}catch(e){switch(t){case"min":return 58;case"max":return 60;case"mid":return 59;case"upperInflectionPoint":return 61;case"lowerInflectionPoint":return 62}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,o=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(o)?48:0}checkMinBiggerThanMax(e){const t=e.minimum.value,o=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&hC(t)>=hC(o)?47:0}checkMidBiggerThanMax(e){const t=e.midpoint?.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&hC(t)>=hC(o)?49:0}checkMinBiggerThanMid(e){const t=e.minimum.value,o=e.midpoint?.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&hC(t)>=hC(o)?50:0}removeConditionalFormatting(e,t){const o=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==o){const e=this.cfRules[t].slice();e.splice(o,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,o){const i=this.cfRules[o].findIndex((t=>t.id===e)),s="up"===t?i-1:i+1;if(!(s<0||s>=this.cfRules[o].length)&&-1!==i&&-1!==s){const e=[...this.cfRules[o]],t=e[i];e[i]=e[s],e[s]=t,this.history.update("cfRules",o,e)}}}).add("figures",class extends cC{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:o,...i}=e,s=i;this.updateFigure(o,s);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":this.onRowColDelete(e.sheetId,e.dimension)}}onRowColDelete(e,t){"ROW"===t?this.onRowDeletion(e):this.onColDeletion(e)}onRowDeletion(e){const t=this.getters.getNumberRows(e);let o=0;for(let i=0;i<t;i++)o+=this.getters.getRowSize(e,i);const i=this.getters.getFigures(e);for(const t of i){const i=Math.min(t.y,o-t.height);i!==t.y&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,y:i})}}onColDeletion(e){const t=this.getters.getNumberCols(e);let o=0;for(let i=0;i<t;i++)o+=this.getters.getColSize(e,i);const i=this.getters.getFigures(e);for(const t of i){const i=Math.min(t.x,o-t.width);i!==t.x&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,x:i})}}updateFigure(e,t){if("id"in t)for(const[o,i]of Object.entries(t))switch(o){case"x":case"y":void 0!==i&&this.history.update("figures",e,t.id,o,Math.max(i,0));break;case"width":case"height":void 0!==i&&this.history.update("figures",e,t.id,o,i)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){return void 0===this.figures[e]?.[t]?70:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>t?.[e]))?82:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(lt)}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>void 0!==this.figures[t]?.[e]))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const o=void 0;t.figures.push({...e,data:o})}}exportForExcel(e){this.export(e)}}).add("chart",class extends cC{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];charts={};createChart=function(e){const t=On.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(o,i,s){const r=t.find((e=>e.match(i.type)));if(!r)throw new Error(`No builder for this chart: ${i.type}`);return r.createChart(i,s,e)}}(this.getters);validateChartDefinition=e=>function(e,t){const o=On.getAll().find((e=>e.match(t.type)));if(!o)throw new Error("Unknown chart type.");return o.validateChartDefinition(e,t)}(this,e.definition);adaptRanges(e){for(const[t,o]of Object.entries(this.charts))this.history.update("charts",t,o?.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return 0}}handle(e){switch(e.type){case"CREATE_CHART":this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case"UPDATE_CHART":this.addChart(e.id,e.definition);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const o of t)if("chart"===o.tag){const t=o.id.split(oe).pop(),i=`${e.sheetIdTo}${oe}${t}`,s=this.charts[o.id]?.copyForSheetId(e.sheetIdTo);s&&this.dispatch("CREATE_CHART",{id:i,position:{x:o.x,y:o.y},size:{width:o.width,height:o.height},definition:s.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.id,void 0);break;case"DELETE_SHEET":for(let t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){const t=this.charts[e]?.type;if(!t)throw new Error("Chart not defined.");return t}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>t?.sheetId===e)).map((([e])=>e))}getChartDefinition(e){const t=this.charts[e]?.getDefinition();if(!t)throw new Error(`There is no chart with the given figureId: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)"chart"===e.tag&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){if(e.sheets)for(let t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(let t of e){const e=t;if(e&&"chart"===e.tag){const t=this.charts[e.id]?.getDefinition();t&&(e.data=t,o.push(e))}else o.push(e)}t.figures=o}}exportForExcel(e){for(let t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(let t of e)if(t&&"chart"===t.tag){const e=this.charts[t.id]?.getDefinitionForExcel();e&&o.push({...t,data:e})}t.charts=o}}addFigure(e,t,o={x:0,y:0},i={width:536,height:335}){if(this.getters.getFigure(t,e))return;const s={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:s})}addChart(e,t){const o=this.getters.getFigureSheetId(e);o&&this.history.update("charts",e,this.createChart(e,t,o))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?84:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:85}}).add("image",class extends cC{static getters=["getImage","getImagePath","getImageSize"];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?28:0}handle(e){switch(e.type){case"CREATE_IMAGE":this.addFigure(e.figureId,e.sheetId,e.position,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const o of t)if("image"===o.tag){const t=o.id.split(oe).pop(),i=`${e.sheetIdTo}${oe}${t}`,s=this.getImage(o.id);if(s){const t={width:o.width,height:o.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:i,position:{x:o.x,y:o.y},size:t,definition:Ve(s)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.id,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){const e=new Set(this.getAllImages().map((e=>e.path)));for(const t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new 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,o,i){const s={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:s})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const o of e)this.history.update("images",t.id,o.id,o.data),this.syncedImages.add(o.data.path)}}export(e){for(const t of e.sheets){const e=t.figures.filter((e=>"image"===e.tag));for(const o of e)o.data=this.images[t.id]?.[o.id]}}exportForExcel(e){for(const t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(const t of e)if("image"===t?.tag){const e=this.getImage(t.id);e&&o.push({...t,data:Ve(e)})}t.images=o}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(lt));return e}}),oE=(new _i).add("ui_sheet",class extends fC{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];ctx=document.createElement("canvas").getContext("2d");allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const o=this.getColMaxWidth(e.sheetId,t);0!==o&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:o,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e){const t=this.getCellText(e),o=this.getters.getCellComputedStyle(e),i=t.split(pe);let s=Math.max(...i.map((e=>this.getTextWidth(e,o))));this.getters.getConditionalIcon(e)&&(s+=function(e){return Ze(e)+2*V}(this.getters.getCellStyle(e)));if(this.getters.isFilterHeader(e)&&(s+=20),s>0&&(s+=2*H,"wrap"===this.getters.getCellStyle(e).wrapping)){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,s)}return s}getTextWidth(e,t){return We(this.ctx,e,t)}getCellText(e,t=!1){const o=this.getters.getCell(e);return t&&o?.isFormula?o.content:this.getters.getEvaluatedCell(e).formattedValue}getCellMultiLineText(e,t){const o=this.getters.getCellStyle(e),i=this.getters.getCellText(e,this.getters.shouldShowFormulas()),s=[];for(const e of i.split("\n")){const i=e.split(" ");if(!t){s.push(e);continue}let r="",n=t;for(let e of i){const i=this.splitWordToSpecificWidth(this.ctx,e,t,o),a=i.pop(),l=We(this.ctx,a,o);if(i.length)""!==r&&(s.push(r),r="",n=t),i.forEach((e=>{s.push(e)})),r=a,n=t-l;else{const e=""===r?a:" "+a,i=We(this.ctx,e,o);i<=n?(r+=e,n-=i):(s.push(r),r=a,n=t-l)}}""!==r&&s.push(r)}return s}getColDimensions(e,t){const o=this.getColRowOffset("COL",0,t,e),i=this.getters.getColSize(e,t);return{start:o,size:i,end:o+(this.getters.isColHidden(e,t)?0:i)}}getRowDimensions(e,t){const o=this.getColRowOffset("ROW",0,t,e),i=this.getters.getRowSize(e,t);return{start:o,size:i,end:o+(this.getters.isRowHidden(e,t)?0:i)}}getColRowOffset(e,t,o,i=this.getters.getActiveSheetId()){if(o<t)return-this.getColRowOffset(e,o,t);let s=0;for(let r=t;r<o;r++)this.getters.isHeaderHidden(i,e,r)||(s+="COL"===e?this.getters.getColSize(i,r):this.getters.getRowSize(i,r));return s}getColMaxWidth(e,t){const o=ui(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,...o)}splitWordToSpecificWidth(e,t,o,i){if(We(e,t,i)<=o)return[t];const s=[];let r="";for(let n of t){We(e,r+n,i)>o?(s.push(r),r=n):r+=n}return s.push(r),s}checkSheetExists(e){return"sheetId"in e&&void 0===this.getters.tryGetSheet(e.sheetId)?27:0}checkZonesAreInSheet(e){const t="sheetId"in e?e.sheetId:this.getters.tryGetActiveSheetId(),o=this.getters.getCommandZones(e);return!t&&o.length>0?92:t&&o.length>0?this.getters.checkZonesExistInSheet(t,o):0}}).add("header_visibility_ui",class extends fC{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,o){return"COL"===t?this.isColHidden(e,o):this.isRowHidden(e,o)}getNextVisibleCellPosition({sheetId:e,col:t,row:o}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",o,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,o,i){if(o<=i)for(let s=o;s<=i;s++)if(this.getters.doesHeaderExist(e,t,s)&&!this.isHeaderHidden(e,t,s))return s;if(o>i)for(let s=o;s>=i;s--)if(this.getters.doesHeaderExist(e,t,s)&&!this.isHeaderHidden(e,t,s))return s}findLastVisibleColRowIndex(e,t,{last:o,first:i}){return je(o,i,-1).find((o=>!this.isHeaderHidden(e,t,o)))||i}findFirstVisibleColRowIndex(e,t){const o=this.getters.getNumberHeaders(e,t);for(let i=0;i<o;i++){if("COL"===t&&!this.isColHidden(e,i))return i;if("ROW"===t&&!this.isRowHidden(e,i))return i}}exportForExcel(e){for(const t of e.sheets)for(const[e,o]of Object.entries(t.rows)){const i=this.isRowHidden(t.id,Number(e));o.isHidden=i}}}).add("ui_options",class extends fC{static getters=["shouldShowFormulas"];showFormulas=!1;handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}).add("selectionInputManager",class extends fC{config;static layers=[1];static getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];inputs={};focusedInputId=null;get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}constructor(e){super(e),this.config=e}allowDispatch(e){if("FOCUS_RANGE"===e.type){const t=this.currentInput?.getIndex(e.rangeId);if(this.focusedInputId===e.id&&this.currentInput?.focusedRangeIndex===t)return 29}return this.currentInput?this.currentInput.allowDispatch(e):0}handle(e){switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id];this.selection.capture(t,{cell:{col:0,row:0},zone:fi({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id],o=t.ranges.find((t=>t.id===e.rangeId)),i=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(i,o?.xc||"A1").zone;this.selection.capture(t,{cell:{col:s.left,row:s.top},zone:s},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}this.currentInput?.handle(e)}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,o)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.inputs[e].focusedRangeIndex&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.inputs[e].focusedRangeIndex===o}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:o}=Bo(e);return null!==t.match(Po)&&(!o||void 0!==this.getters.getSheetIdByName(o))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,o=!1){if(this.inputs[e]=new _C(this.config,t,o),0===t.length){const t=this.inputs[e],o={zone:fi({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,o,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}).add("highlight",class extends fC{static layers=[1];static getters=["getHighlights"];getHighlights(){return this.prepareHighlights(this.getters.getComposerHighlights().concat(this.getters.getSelectionInputHighlights()))}prepareHighlights(e){return e.filter((e=>e.zone.top>=0&&e.zone.left>=0&&e.zone.bottom<this.getters.getNumberRows(e.sheetId)&&e.zone.right<this.getters.getNumberCols(e.sheetId))).map((e=>{const{numberOfRows:t,numberOfCols:o}=hi(e.zone),i=t*o==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:i}}))}drawGrid(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId(),s=3*o;t.lineWidth=s;const r=this.getHighlights();for(let e of r.filter(((e,t)=>r.findIndex((t=>si(t.zone,e.zone)&&t.sheetId===i))===t))){const{x:o,y:i,width:r,height:n}=this.getters.getVisibleRect(e.zone);r>0&&n>0&&(t.strokeStyle=e.color,t.strokeRect(o+s/2,i+s/2,r-s,n-s),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+s,i+s,r-2*s,n-2*s))}}}).add("grid renderer",class extends fC{static layers=[0,7];static getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];boxes=[];getColDimensionsInViewport(e,t){const o=Math.min(...this.getters.getSheetViewVisibleCols()),i=this.getters.getColRowOffsetInViewport("COL",o,t),s=this.getters.getColSize(e,t);return{start:i,size:s,end:i+(this.getters.isColHidden(e,t)?0:s)}}getRowDimensionsInViewport(e,t){const o=Math.min(...this.getters.getSheetViewVisibleRows()),i=this.getters.getColRowOffsetInViewport("ROW",o,t),s=this.getters.getRowSize(e,t);return{start:i,size:s,end:i+(this.getters.isRowHidden(e,t)?0:s)}}getHeaderOffset(e,t,o){let i=this.getters.getColRowOffsetInViewport(e,t,o);return this.getters.isDashboard()||(i+="ROW"===e?_:F),i}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(),this.drawBackground(e),this.drawOverflowingCellBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e),this.drawFrozenPanes(e);break;case 7:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawBackground(e){const{ctx:t,thinLineWidth:o}=e,{width:i,height:s}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,i+m,s+m);const r=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),n=r?.1*o:0;if(r)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=o,t.strokeRect(e.x+n,e.y+n,e.width-2*n,e.height-2*n)}drawCellBackground(e){const{ctx:t}=e;for(const e of this.boxes){let o=e.style;o.fillColor&&"#ffffff"!==o.fillColor&&(t.fillStyle=o.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawOverflowingCellBackground(e){const{ctx:t,thinLineWidth:o}=e;for(const e of this.boxes)if(e.content&&e.isOverflow){const i=e.content.align||"left";let s,r;const n=e.y+o/2,a=e.height-o,l=Math.min(e.clipRect?.width||1/0,e.content.width);"left"===i?(s=e.x+o/2,r=l-2*o):"right"===i?(s=e.x+e.width-o/2,r=2*o-l):(s=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+o/2,r=l-2*o),t.fillStyle="#ffffff",t.fillRect(s,n,r,a)}}drawBorders(e){const{ctx:t}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:i,y:s,width:r,height:n}=e;t.left&&o(t.left,i,s,i,s+n),t.top&&o(t.top,i,s,i+r,s),t.right&&o(t.right,i+r,s,i+r,s+n),t.bottom&&o(t.bottom,i,s+n,i+r,s+n)}}function o({style:e,color:o},i,s,r,n){switch(t.strokeStyle=o,e){case"medium":t.lineWidth=2,s+=(i+=s===n?-.5:.5)===(r+=s===n?1.5:.5)?-.5:.5,n+=i===r?1.5:.5;break;case"thick":t.lineWidth=3,s===n&&(i--,r++),i===r&&(s--,n++);break;case"dashed":t.lineWidth=1,t.setLineDash([1,3]);break;case"dotted":t.lineWidth=1,s===n&&(i+=.5,r+=.5),i===r&&(s+=.5,n+=.5),t.setLineDash([1,1]);break;default:t.lineWidth=1}t.beginPath(),t.moveTo(i,s),t.lineTo(r,n),t.stroke(),t.lineWidth=1,t.setLineDash([])}}drawTexts(e){const{ctx:t,thinLineWidth:o}=e;let i;t.textBaseline="top";for(let e of this.boxes)if(e.content){const s=e.style||{},r=e.content.align||"left",n=qe(s);n!==i&&(i=n,t.font=n),t.fillStyle=s.textColor||"#000";let a=e.x;if(a+="left"===r?z+(e.image?e.image.size+V:0):"right"===r?e.width-z-(e.isFilterHeader?20:0):e.width/2,t.textAlign=r,e.clipRect){t.save(),t.beginPath();const{x:o,y:i,width:s,height:r}=e.clipRect;t.rect(o,i,s,r),t.clip()}const l=Ze(s),c=e.content.textLines.length;let h=this.computeTextYCoordinate(e,l,c);for(let i of e.content.textLines){if(t.fillText(i,Math.round(a),Math.round(h)),s.strikethrough||s.underline){const e=We(t,i,s);let n=a;"right"===r?n-=e:"center"===r&&(n-=e/2),s.strikethrough&&t.fillRect(n,h+l/2,e,2.6*o),s.underline&&t.fillRect(n,h+l+1,e,1.3*o)}h+=z+l}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const o=e.image.image;if(e.image.clipIcon){t.save(),t.beginPath();const{x:o,y:i,width:s,height:r}=e.image.clipIcon;t.rect(o,i,s,r),t.clip()}const i=e.image.size,s=this.computeTextYCoordinate(e,i);t.drawImage(o,e.x+V,s,i,i),e.image.clipIcon&&t.restore()}}computeTextYCoordinate(e,t,o=1){const i=e.y+1,s=$e(t,o),r=e.height>s+2*z,n=e.verticalAlign||j;if(r){if("middle"===n)return i+(e.height-s)/2;if("bottom"===n)return i+e.height-s-z}return i+z}drawHeaders(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getSheetViewVisibleCols(),s=i[0],r=i[i.length-1],n=this.getters.getSheetViewVisibleRows(),a=n[0],l=n[n.length-1],{width:c,height:h}=this.getters.getSheetViewDimensionWithHeaders(),d=this.getters.getSelectedZones(),u=function(e){const t=new Set;for(let o of e)for(let e of je(o.left,o.right+1))t.add(e);return t}(d),g=function(e){const t=new Set;for(let o of e)for(let e of je(o.top,o.bottom+1))t.add(e);return t}(d),p=this.getters.getActiveSheetId(),m=this.getters.getNumberCols(p),f=this.getters.getNumberRows(p),E=this.getters.getActiveCols(),w=this.getters.getActiveRows();t.font=`400 11px ${Z}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=o,t.strokeStyle="#333";for(let e=s;e<=r;e++){const o={left:e,right:e,top:0,bottom:f-1},{x:i,width:s}=this.getters.getVisibleRect(o),r=this.getters.doesZonesContainFilter(p,[o]),n=E.has(e),a=u.has(e);t.fillStyle=n?r?R:S:a?r?A:v:r?T:b,t.fillRect(i,0,s,_)}for(let e=a;e<=l;e++){const o={top:e,bottom:e,left:0,right:m-1},{y:i,height:s}=this.getters.getVisibleRect(o),r=this.getters.doesZonesContainFilter(p,[o]),n=w.has(e),a=g.has(e);t.fillStyle=n?r?R:S:a?r?A:v:r?T:b,t.fillRect(0,i,F,s)}t.beginPath(),t.moveTo(F,0),t.lineTo(F,h),t.moveTo(0,_),t.lineTo(c,_),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of i){const o=this.getters.getColSize(p,e),i=Pt(e);t.fillStyle=E.has(e)?"#fff":C;let r=this.getHeaderOffset("COL",s,e);t.fillText(i,r+o/2,13),t.moveTo(r+o,0),t.lineTo(r+o,_)}for(const e of n){const o=this.getters.getRowSize(p,e);t.fillStyle=w.has(e)?"#fff":C;let i=this.getHeaderOffset("ROW",a,e);t.fillText(String(e+1),24,i+o/2),t.moveTo(0,i+o),t.lineTo(F,i+o)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:s}=this.getters.getMainViewportCoordinates(),r=this.getters.isDashboard()?0:F,n=this.getters.isDashboard()?0:_;t.lineWidth=6*o,t.strokeStyle="#BCBCBC",t.beginPath(),i&&(t.moveTo(r+i,0),t.lineTo(r+i,n)),s&&(t.moveTo(0,n+s),t.lineTo(r,n+s)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:s}=this.getters.getMainViewportCoordinates(),r=this.getters.getSheetViewVisibleCols(),n=r[0],a=r[r.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:n,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:F,u=this.getters.isDashboard()?0:_;t.lineWidth=6*o,t.strokeStyle="#DADFE8",t.beginPath(),i&&(t.moveTo(d+i,u),t.lineTo(d+i,h.height+u)),s&&(t.moveTo(d,u+s),t.lineTo(h.width+d,u+s)),t.stroke()}findNextEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let s=e;for(;s<t;){const e={sheetId:i,col:s+1,row:o},t=this.getters.getEvaluatedCell(e),r=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==ms.empty||this.getters.isInMerge(e)||r?.left)return s;s++}return s}findPreviousEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let s=e;for(;s>t;){const e={sheetId:i,col:s-1,row:o},t=this.getters.getEvaluatedCell(e),r=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==ms.empty||this.getters.isInMerge(e)||r?.right)return s;s--}return s}computeCellAlignment(e,t){if(this.getters.getCell(e)?.isFormula&&this.getters.shouldShowFormulas())return"left";const{align:o}=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e);return t&&i.type===ms.number?"center"!==o?"left":o:o||i.defaultAlign}createZoneBox(e,t,o){const{left:i,right:s}=o,r=t.left,n=t.top,a={sheetId:e,col:r,row:n},c=this.getters.getEvaluatedCell(a),h=this.getters.shouldShowFormulas(),{x:d,y:u,width:g,height:p}=this.getters.getVisibleRect(t),{verticalAlign:m}=this.getters.getCellStyle(a),f={x:d,y:u,width:g,height:p,border:this.getters.getCellBorderWithFilterBorder(a)||void 0,style:this.getters.getCellComputedStyle(a),verticalAlign:m};if(c.type===ms.empty)return f;const b=this.getters.getConditionalIcon(a),v=Ze(f.style),S=b?V+v:0;b&&(f.image={type:"icon",size:v,clipIcon:{x:f.x,y:f.y,width:Math.min(S,g),height:p},image:Hm[b].img}),f.isFilterHeader=this.getters.isFilterHeader(a);const C=f.isFilterHeader?19:0,E=this.getters.getCellComputedStyle(a),w=E.wrapping||"overflow",x="wrap"!==w||h?void 0:g-2*z,y=this.getters.getCellMultiLineText(a,x),I=Math.max(...y.map((e=>this.getters.getTextWidth(e,E)+z))),R=S+I+C,T=this.computeCellAlignment(a,R>g);f.content={textLines:y,width:"overflow"===w?I:g,align:T},c.type===ms.error&&c.error.logLevel>l.silent&&(f.error=c.error.message);const A=R>g||v>p;if(b||f.isFilterHeader)f.clipRect={x:f.x+S,y:f.y,width:Math.max(0,g-S-C),height:p};else if(A&&"overflow"===w){let e,o;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,o=r):(e=this.findNextEmptyCol(r,s,n),o=this.findPreviousEmptyCol(r,i,n),f.isOverflow=!0),T){case"left":{const o=fi({col:e,row:n}),{x:i,y:s,width:r,height:a}=this.getters.getVisibleRect(oi(t,o));(r<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:r,height:a});break}case"right":{const e=fi({col:o,row:n}),{x:i,y:s,width:r,height:a}=this.getters.getVisibleRect(oi(t,e));(r<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:r,height:a});break}case"center":{const i={...t,left:o,right:e},{x:s,y:r,height:n,width:a}=this.getters.getVisibleRect(i),l=R/2,c=f.x+f.width/2;if(s+a<c+l||s>c-l||v>n||y.length>1){const e=s>c-l?s:c-l,t=s+a-e;f.clipRect={x:e,y:r,width:t,height:n}}break}}}else("clip"===w||"wrap"===w||y.length>1)&&(f.clipRect={x:f.x,y:f.y,width:g,height:p});return f}getGridBoxes(){const e=[],t=this.getters.getSheetViewVisibleCols(),o=t[0],i=t[t.length-1],s=this.getters.getSheetViewVisibleRows(),r={left:o,right:i,top:s[0],bottom:s[s.length-1]},n=this.getters.getActiveSheetId();for(const o of s)for(const i of t){const t={sheetId:n,col:i,row:o};this.getters.isInMerge(t)||e.push(this.createZoneBox(n,fi(t),r))}for(const t of this.getters.getMerges(n))if(!this.getters.isMergeHidden(n,t)&&ri(t,r)){const o=this.createZoneBox(n,t,r),i=this.getters.getCellBorder({sheetId:n,col:t.right,row:t.bottom});o.border={...o.border,bottom:i?i.bottom:void 0,right:i?i.right:void 0},o.isMerge=!0,e.push(o)}return e}}).add("autofill",class extends fC{static layers=[5];static getters=["getAutofillTooltip"];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case"AUTOFILL_SELECT":const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:He(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:He(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:45;case"AUTOFILL_AUTO":const o=this.getters.getSelectedZone();return o.top===o.bottom?0:1}return 0}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;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),o=this.autofillZone;switch(this.direction){case"down":for(let i=t.left;i<=t.right;i++){const s=[];for(let e=t.top;e<=t.bottom;e++)s.push(Ht(i,e));const r=this.createGenerator(s);for(let t=o.top;t<=o.bottom;t++)this.computeNewCell(r,i,t,e)}break;case"up":for(let i=t.left;i<=t.right;i++){const s=[];for(let e=t.bottom;e>=t.top;e--)s.push(Ht(i,e));const r=this.createGenerator(s);for(let t=o.bottom;t>=o.top;t--)this.computeNewCell(r,i,t,e)}break;case"left":for(let i=t.top;i<=t.bottom;i++){const s=[];for(let e=t.right;e>=t.left;e--)s.push(Ht(e,i));const r=this.createGenerator(s);for(let t=o.right;t>=o.left;t--)this.computeNewCell(r,t,i,e)}break;case"right":for(let i=t.top;i<=t.bottom;i++){const s=[];for(let e=t.left;e<=t.right;e++)s.push(Ht(e,i));const r=this.createGenerator(s);for(let t=o.left;t<=o.right;t++)this.computeNewCell(r,t,i,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const o=this.getters.getSelectedZone();if(ni(e,t,o))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,o.top-1,o.left,o.right),this.steps=o.top-t;break;case"down":this.saveZone(o.bottom+1,t,o.left,o.right),this.steps=t-o.bottom;break;case"left":this.saveZone(o.top,o.bottom,e,o.left-1),this.steps=o.left-e;break;case"right":this.saveZone(o.top,o.bottom,o.right+1,e),this.steps=e-o.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let o=e.left,i=e.bottom;if(o>0){let e=this.getters.getEvaluatedCell({sheetId:t,col:o-1,row:i});for(;e.type!==ms.empty;)i+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:o-1,row:i})}if(i===e.bottom&&(o=e.right,o<=this.getters.getNumberCols(t))){let e=this.getters.getEvaluatedCell({sheetId:t,col:o+1,row:i});for(;e.type!==ms.empty;)i+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:o+1,row:i})}i!==e.bottom&&(this.select(e.left,i-1),this.autofill(!0))}computeNewCell(e,t,o,i){const{cellData:s,tooltip:r,origin:n}=e.next(),{content:a,style:l,border:c,format:h}=s;this.tooltip=r,i&&this.dispatch("AUTOFILL_CELL",{originCol:n.col,originRow:n.row,col:t,row:o,content:a,style:l,border:c,format:h})}getRule(e,t){const o=Ps.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((o=>o.condition(e,t)));return o&&o.generateRule(e,t)}createGenerator(e){const t=[],o=[],i=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:s}=Bt(t),r=this.getters.getCell({sheetId:i,col:e,row:s});o.push({col:e,row:s,cell:r,sheetId:i})}const s=o.map((e=>e.cell));for(let e of o){let o={type:"COPY_MODIFIER"};if(e&&e.cell){o=this.getRule(e.cell,s)||o}const i=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:i},rule:o})}return new SC(t,this.getters,this.direction)}saveZone(e,t,o,i){this.autofillZone={top:e,bottom:t,left:o,right:i}}getDirection(e,t){const o=this.getters.getSelectedZone(),i={up:{number:o.top-t,value:"up"},down:{number:t-o.bottom,value:"down"},left:{number:o.left-e,value:"left"},right:{number:e-o.right,value:"right"}};if(1===Object.values(i).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(i).find((e=>e.number>0?1:0)).value;const s=i.up.number>0?"up":"down",r=i.left.number>0?"left":"right";return Math.abs(i[s].number)>=Math.abs(i[r].number)?i[s].value:i[r].value}autoFillMerge(e,t,o,i){const s=this.getters.getActiveSheetId(),r={sheetId:s,col:o,row:i},n={sheetId:s,col:e,row:t};if(this.getters.isInMerge(r)&&!this.getters.isInMerge(n)){const e=this.getters.getMerge(r);e&&this.dispatch("REMOVE_MERGE",{sheetId:s,target:[e]})}const a=this.getters.getMerge(n);a?.topLeft.col===e&&a?.topLeft.row===t&&this.dispatch("ADD_MERGE",{sheetId:s,target:[{top:i,bottom:i+a.bottom-a.top,left:o,right:o+a.right-a.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:o}=e,{x:i,y:s,width:r,height:n}=this.getters.getVisibleRect(this.autofillZone);r>0&&n>0&&(t.strokeStyle="black",t.lineWidth=o,t.setLineDash([3]),t.strokeRect(i,s,r,n),t.setLineDash([]))}}).add("find_and_replace",class extends fC{static layers=[3];static getters=["getSearchMatches","getCurrentSelectedMatchIndex"];searchMatches=[];selectedMatchIndex=null;currentSearchRegex=null;searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1};toSearch="";handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":case"UNDO":case"REDO":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(NC.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(NC.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith);break;case"ACTIVATE_SHEET":case"REFRESH_SEARCH":this.refreshSearch()}}getSearchMatches(){return this.searchMatches}getCurrentSelectedMatchIndex(){return this.selectedMatchIndex}updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.updateRegex(),this.refreshSearch()}refreshSearch(){const e=this.findMatches();this.searchMatches=e,this.selectNextCell(NC.current)}updateRegex(){let e=Ue(this.toSearch);const t=this.searchOptions.matchCase?"":"i";this.searchOptions.exactMatch&&(e=`^${e}$`),this.currentSearchRegex=RegExp(e,t)}findMatches(){const e=this.getters.getActiveSheetId(),t=this.getters.getCells(e),o=[];if(this.toSearch)for(const i of Object.values(t)){const{col:t,row:s}=this.getters.getCellPosition(i.id);if(i&&this.currentSearchRegex&&this.currentSearchRegex.test(this.getSearchableString({sheetId:e,col:t,row:s}))){const e={col:t,row:s,selected:!1};o.push(e)}}return o.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let o;o=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,o=(o%t.length+t.length)%t.length,this.selectedMatchIndex=o,this.selection.selectCell(t[o].col,t[o].row);for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1}}replace(e){if(null===this.selectedMatchIndex||!this.currentSearchRegex)return;const t=this.searchMatches[this.selectedMatchIndex],o=this.getters.getActiveSheetId();if(this.getters.getCell({sheetId:o,...t})?.isFormula&&!this.searchOptions.searchFormulas)this.selectNextCell(NC.next);else{const i=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),s=this.getSearchableString({sheetId:o,col:t.col,row:t.row}).replace(i,e);this.dispatch("UPDATE_CELL",{sheetId:this.getters.getActiveSheetId(),col:t.col,row:t.row,content:s}),this.searchMatches.splice(this.selectedMatchIndex,1),this.selectNextCell(NC.current)}}replaceAll(e){const t=this.searchMatches.length;for(let o=0;o<t;o++)this.replace(e)}getSearchableString(e){const t=this.getters.getCell(e);return this.searchOptions.searchFormulas&&t?.isFormula?t.content:this.getters.getEvaluatedCell(e).formattedValue}drawGrid(e){const{ctx:t}=e,o=this.getters.getActiveSheetId();for(const e of this.searchMatches){const i=this.getters.getMerge({sheetId:o,col:e.col,row:e.row}),s=i?i.left:e.col,r=i?i.right:e.col,n=i?i.top:e.row,a=i?i.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:n,left:s,right:r,bottom:a});h>0&&d>0&&(t.fillStyle="#8B008B33",t.fillRect(l,c,h,d),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(l,c,h,d)))}}}).add("sort",class extends fC{static getters=["getContiguousZone"];allowDispatch(e){if("SORT_CELLS"===e.type){if(!ni(e.col,e.row,e.zone))throw new Error(r("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;return ui(t).some((({col:t,row:o})=>!this.getters.isInMerge({sheetId:e,col:t,row:o})))?63:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const o=this.getters.getMerges(e).filter((e=>ri(e,t))),i=hi(o[0]);let[s,r]=[i.numberOfCols,i.numberOfRows];return o.every((e=>{let[t,o]=[e.right-e.left+1,e.bottom-e.top+1];return t===s&&o===r}))?0:63}expand(e,t){const{left:o,right:i,top:s,bottom:r}=this.getters.expandZone(e,t);return{left:Math.max(0,o),right:Math.min(this.getters.getNumberCols(e)-1,i),top:Math.max(0,s),bottom:Math.min(this.getters.getNumberRows(e)-1,r)}}checkExpandedValues(e,t){const o=this.expand(e,t);let i;if(this.getters.doesIntersectMerge(e,o)){const{left:t,right:s,top:r,bottom:n}=o;for(let o=t;o<=s;o++)for(let t=r;t<=n;t++){const{col:s,row:r}=this.getters.getMainCellPosition({sheetId:e,col:o,row:t});if(i=this.getters.getEvaluatedCell({sheetId:e,col:s,row:r}),i.formattedValue)return!0}}else for(let t of this.getters.getEvaluatedCellsInZone(e,o))if(t.formattedValue)return!0;return!1}getContiguousZone(e,t){let o,{top:i,bottom:s,left:r,right:n}=t,a=!1;for(;!a;)a=!0,i>0&&(o=this.checkExpandedValues(e,{left:r-1,right:n+1,top:i-1,bottom:i-1}),o&&(a=!1,i--)),r>0&&(o=this.checkExpandedValues(e,{left:r-1,right:r-1,top:i-1,bottom:s+1}),o&&(a=!1,r--)),n<this.getters.getNumberCols(e)-1&&(o=this.checkExpandedValues(e,{left:n+1,right:n+1,top:i-1,bottom:s+1}),o&&(a=!1,n++)),s<this.getters.getNumberRows(e)-1&&(o=this.checkExpandedValues(e,{left:r-1,right:n+1,top:s+1,bottom:s+1}),o&&(a=!1,s++));return{left:r,right:n,top:i,bottom:s}}hasHeader(e,t){if(1===t[0].length)return!1;let o=t.map((t=>t.map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).type))));return o[0][0]===ms.empty&&(o=o.slice(1)),!o.some((e=>e[0]===ms.empty))&&!!o.some((e=>e[1]!==ms.empty&&e[0]!==e[1]))}sortZone(e,t,o,i,s){const[r,n]=this.mainCellsSteps(e,o);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},o),c=this.mainCells(e,o);!s.sortHeaders&&this.hasHeader(e,c)&&(l.top+=n),c=this.mainCells(e,l);const h=function(e,t,o){const i=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));let s=i.filter((e=>e.type===ms.empty)),r=i.filter((e=>e.type!==ms.empty));o&&(r.push(...s.map((e=>({...e,type:ms.number,value:0})))),s=[]);const n="descending"===t?-1:1;return r.sort(((e,t)=>{let o=Wn.indexOf(e.type)-Wn.indexOf(t.type);return 0===o&&(o=e.type===ms.text||e.type===ms.error?e.value.localeCompare(t.value):e.value-t.value),n*o})).concat(s)}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),i,Boolean(s.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++){for(let t=0;t<g;t++){let{col:o,row:i,sheetId:s}=c[e][d[t]];const a=this.getters.getCell({sheetId:s,col:o,row:i});let h=l.left+e*r,u=l.top+t*n,g={sheetId:s,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=u-this.getters.getCellPosition(a.id).row,o=this.getters.createAdaptedRanges(a.dependencies,0,t,s);e=this.getters.buildFormulaContent(s,a,o)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}for(const e of p)this.dispatch("UPDATE_CELL",e)}}mainCellsSteps(e,t){const o=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[o?o.right-o.left+1:1,o?o.bottom-o.top+1:1]}mainCells(e,t){const[o,i]=this.mainCellsSteps(e,t),s=[],r=je(t.left,t.right+1,o),n=je(t.top,t.bottom+1,i);for(const t of r){const o=[];s.push(o);for(const i of n)o.push({sheetId:e,col:t,row:i})}return s}}).add("automatic_sum",class extends fC{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:o}=this.getters.getSelection();for(const i of t){const t=this.getAutomaticSums(e,i,o.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,o){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,o):this.sumData(e,t)}sumData(e,t){const o=this.dimensionsToSum(e,t),i=this.sumDimensions(e,t,o).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return o.has("ROW")&&o.has("COL")&&i.push(this.sumTotal(t)),i}sumAdjacentData(e,t,o){const{col:i,row:s}=ni(o.col,o.row,t)?o:{col:t.left,row:t.top},r=this.findAdjacentData(e,i,s);return r?this.getters.isSingleCellOrMerge(e,t)||di(oi(r,t))?[{position:{col:i,row:s},zone:r}]:this.sumDimensions(e,oi(r,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,o){const i=this.getters.getSheet(e),s=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),r=this.findSuitableZoneToSum(i,s.col,s.row);if(r)return this.getters.expandZone(e,r)}findSuitableZoneToSum(e,t,o){const i=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:o-1}),s=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:o});if(this.isNumber(s)&&!this.isNumber(i))return this.findHorizontalZone(e,t,o);const r=this.findVerticalZone(e,t,o);if(this.isZoneValid(r))return r;const n=this.findHorizontalZone(e,t,o);return this.isZoneValid(n)?n:void 0}findVerticalZone(e,t,o){const i={top:0,bottom:o-1,left:t,right:t},s=this.reduceZoneStart(e,i,i.bottom);return{...i,top:s}}findHorizontalZone(e,t,o){const i={top:o,bottom:o,left:0,right:t-1},s=this.reduceZoneStart(e,i,i.right);return{...i,left:s}}reduceZoneStart(e,t,o){const i=this.getters.getEvaluatedCellsInZone(e.id,t),s=je(o,-1,-1),r=s.filter((e=>i[e]&&!i[e].isAutoSummable)),n=Math.max(...r),a=Ye(s.filter((e=>this.isNumber(i[e]))))[0]||[];return Math.max(...a)<n?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===ms.number&&!(e.format&&bo(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){const o=new Set;return di(t)?(o.add(1===hi(t).numberOfCols?"COL":"ROW"),o):(this.lastColIsEmpty(e,t)&&o.add("ROW"),this.lastRowIsEmpty(e,t)&&o.add("COL"),0===o.size&&o.add("COL"),o)}sumDimensions(e,t,o){return[...o.has("COL")?this.sumColumns(t,e):[],...o.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:o}=e;return{position:{col:o,row:t},zone:{...e,top:t,right:o-1}}}sumColumns(e,t){const o=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,o.bottom-1)},ui(o).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const o=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,o.right-1)},ui(o).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const o of t){const{col:t,row:i}=o.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,content:`=SUM(${this.getters.zoneToXC(e,o.zone)})`})}}nextEmptyRow(e,t){let o=t.bottom+1;const{left:i,right:s}=t;for(;!this.getters.isEmpty(e,{bottom:o,top:o,left:i,right:s});)o++;return{...t,top:o,bottom:o}}nextEmptyCol(e,t){let o=t.right+1;const{top:i,bottom:s}=t;for(;!this.getters.isEmpty(e,{left:o,right:o,top:i,bottom:s});)o++;return{...t,left:o,right:o}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}).add("format",class extends fC{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,o){for(const i of t)for(const t of ui(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const s=Io(i,o);this.dispatch("SET_FORMATTING",{sheetId:e,target:[fi(t)],format:s})}}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==ms.number||e.format&&bo(e.format)))return e.format||wo(e.value)}}}).add("split_to_columns",class extends fC{static getters=["getAutomaticSeparator"];allowDispatch(e){return"SPLIT_TEXT_INTO_COLUMNS"===e.type?this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e):0}handle(e){if("SPLIT_TEXT_INTO_COLUMNS"===e.type)this.splitIntoColumns(e)}getAutomaticSeparator(){const e=this.getters.getSelectedCells();for(const t of e)if(t.value&&t.type===ms.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[pe,";",","," ","."];for(const o of t)if(e.includes(o))return o}splitIntoColumns({separator:e,addNewColumns:t}){const o=this.getters.getSelectedZone(),i=this.getters.getActiveSheetId(),s=this.getSplittedCols(o,e);t&&this.addColsToAvoidCollisions(o,s),this.removeMergesInSplitZone(o,s),this.addColumnsToNotOverflowSheet(o,s);for(let e=0;e<s.length;e++){const t=o.top+e,r=s[e],n=o.left,a=this.getters.getCell({sheetId:i,col:n,row:t});if(1!==r.length||r[0]!==a?.content)for(const[e,o]of r.entries())this.dispatch("UPDATE_CELL",{sheetId:i,col:n+e,row:t,content:o,format:"",style:a?.style||null})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const o=this.getters.getActiveSheetId(),i=[];for(const s of je(e.top,e.bottom+1)){const r=this.getters.getEvaluatedCell({sheetId:o,col:e.left,row:s}).formattedValue;i.push(this.splitAndRemoveTrailingEmpty(r,t))}return i}splitAndRemoveTrailingEmpty(e,t){const o=e.split(t);for(;o.length>1&&""===o[o.length-1];)o.pop();return o}willSplittedColsOverwriteContent(e,t){const o=this.getters.getActiveSheetId();for(const i of je(e.top,e.bottom+1)){const s=t[i-e.top];for(let t=1;t<s.length;t++){const s=this.getters.getCell({sheetId:o,col:e.left+t,row:i});if(s&&s.content)return!0}}return!1}removeMergesInSplitZone(e,t){const o=this.getters.getActiveSheetId(),i=Math.max(...t.map((e=>e.length))),s={...e,right:e.left+i-1},r=this.getters.getMergesInZone(o,s);this.dispatch("REMOVE_MERGE",{sheetId:o,target:r})}addColsToAvoidCollisions(e,t){const o=this.getters.getActiveSheetId();let i=0;for(const s of je(e.top,e.bottom+1)){const r={sheetId:o,col:e.left,row:s},n=t[s-e.top],a=this.getColsToAddToAvoidCollision(r,n);i=Math.max(i,a)}i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:o,quantity:i,position:"after"})}getColsToAddToAvoidCollision(e,t){const o=t.length;for(let t=1;t<o;t++){const i=e.col+t,s=this.getters.getCell({...e,col:i});if(s&&s.content)return o-t}return 0}addColumnsToNotOverflowSheet(e,t){const o=this.getters.getActiveSheetId(),i=Math.max(...t.map((e=>e.length-1))),s=this.getters.getNumberCols(o)-1;e.left+i>s&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:s,sheetId:o,quantity:e.left+i-s,position:"after"})}checkSingleColSelected(){return this.getters.isSingleColSelected()?0:88}checkNonEmptySelector(e){return""===e.separator?89:0}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return 0;const t=this.getters.getSelectedZones()[0],o=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,o)?90:0}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const o of t)if(o.formattedValue.includes(e))return 0;return 91}}).add("cell_popovers",class extends fC{static getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];persistentPopover;allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{yr.get(e.popoverType)}catch(e){return 72}return 0}return 0}handle(e){switch(e.type){case"ACTIVATE_SHEET":case"CLOSE_CELL_POPOVER":this.persistentPopover=void 0;break;case"OPEN_CELL_POPOVER":this.persistentPopover={col:e.col,row:e.row,sheetId:this.getters.getActiveSheetId(),type:e.popoverType}}}getCellPopover({col:e,row:t}){const o=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=yr.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport({sheetId:o,col:e,row:t}))return{isOpen:!1};const i=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}),s=yr.getAll().map((e=>e.onHover?.(i,this.getters))).find((e=>e?.isOpen));return s?.isOpen?{...s,anchorRect:this.computePopoverAnchorRect(i)}:{isOpen:!1}}hasOpenedPopover(){return void 0!==this.persistentPopover}getPersistentPopoverTypeAtPosition({col:e,row:t}){if(this.persistentPopover&&this.persistentPopover.col===e&&this.persistentPopover.row===t)return this.persistentPopover.type}computePopoverAnchorRect({col:e,row:t}){const o=this.getters.getActiveSheetId(),i=this.getters.getMerge({sheetId:o,col:e,row:t});return i?this.getters.getVisibleRect(i):this.getters.getVisibleRect(fi({col:e,row:t}))}}).add("collaborative",class extends fC{static getters=["getClientsToDisplay","getClient","getConnectedClients","isFullySynchronized"];static layers=[6];availableColors=new Set(MC);colors={};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)}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(MC));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClient(){return this.session.getClient()}getConnectedClients(){return this.session.getConnectedClients()}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof AC)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const o of this.getters.getConnectedClients())if(o.id!==this.getters.getClient().id&&o.position&&o.position.sheetId===e&&this.isPositionValid(o.position)){const e=o.position;this.colors[o.id]||(this.colors[o.id]=this.chooseNewColor());const i=this.colors[o.id];t.push({...o,position:e,color:i})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:s,col:r}=e.position,n=this.getters.expandZone(i,{top:s,bottom:s,left:r,right:r}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(n);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*o,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${q+1}px ${Z}`}}}).add("history",class extends fC{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("pending-revisions-dropped",this,(({revisionIds:e})=>this.drop(e))),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return 6;break;case"REQUEST_REDO":if(!this.canRedo())return 7}return 0}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();if(t)"UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t));else{const e=this.getPossibleRevisionToRepeat();if(!e)return;const t=$C(e,this.getters);if(!t)return;if(!Array.isArray(t))return void this.dispatch(t.type,t);for(const e of t)this.dispatch(e.type,e)}}canUndo(){return this.undoStack.length>0}canRedo(){if(this.redoStack.length>0)return!0;const e=this.getPossibleRevisionToRepeat();return!(!(t=e)||!t.rootCommand||"object"!=typeof t.rootCommand)&&(Es(t.rootCommand)?VC.contains(t.rootCommand.type):zC.contains(t.rootCommand.type));var t}drop(e){this.undoStack=this.undoStack.filter((t=>!e.includes(t))),this.redoStack=[]}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision(["REQUEST_REDO"])}}),iE=(new _i).add("selection",class extends fC{static layers=[6];static getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSelected","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 27}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handleEvent(e){const t=e.anchor;let o=[];switch(e.mode){case"overrideSelection":o=[t.zone];break;case"updateAnchor":o=[...this.gridSelection.zones];const i=o.findIndex((t=>si(t,e.previousAnchor.zone)));i>=0&&(o[i]=t.zone);break;case"newAnchor":o=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,o),this.selection.resetDefaultAnchor(this,Ve(this.gridSelection.anchor));const{col:i,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:i,row:s}),this.selectedFigureId=null}handle(e){switch(e.type){case"START_EDITION":case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.dispatch("ACTIVATE_SHEET",{sheetIdTo:t,sheetIdFrom:t});const{col:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(o,i),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":if(this.getters.isSheetVisible(e.sheetIdTo)||this.dispatch("SHOW_SHEET",{sheetId:e.sheetIdTo}),this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={gridSelection:Ve(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Ve(this.gridSelection.anchor));else{const{col:t,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0});this.selectCell(t,o)}break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const s=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of s)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Ve(t)}}if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:o})}const r=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(r,e))),this.gridSelection.anchor.zone=this.getters.expandZone(r,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones)}this.selection.resetDefaultAnchor(this,Ve(this.gridSelection.anchor))}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(let t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let o=t.left;o<=t.right;o++)e.add(o);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let o of this.gridSelection.zones)if(0===o.left&&o.right===this.getters.getNumberCols(t)-1)for(let t=o.top;t<=o.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return Ve(this.gridSelection.zones)}getSelectedZone(){return Ve(this.gridSelection.anchor.zone)}getSelection(){return Ve(this.gridSelection)}getSelectedCells(){const e=this.getters.getActiveSheetId(),t=[];for(const o of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,o));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}getStatisticFnResults(){const e=new Set(this.gridSelection.zones.map((e=>this.getters.getEvaluatedCellsInZone(this.getters.getActiveSheetId(),e))).flat().filter((e=>e.type!==ms.empty)));let t=new Set,o=[];for(let i of e)t.add(i.type),o.push(i.value);let i={};for(let e of eE){let s;e.types.some((e=>t.has(e)))&&(s=e.compute(o)),i[e.name]=s}return i}getAggregate(){let e=0,t=0;const o=this.getters.getActiveSheetId(),i=this.gridSelection.zones.map(ui).flat();for(const{col:s,row:r}of i){const i=this.getters.getEvaluatedCell({sheetId:o,col:s,row:r});i.type===ms.number&&(t++,e+=i.value)}return t<2?null:uo(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>si(t,e)))}isSingleColSelected(){const e=this.getters.getSelectedZones();return 1===e.length&&e[0].left===e[0].right}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let o=[];const i="COL"===e?"left":"top",s="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[s]-e[i]+1},((t,o)=>e[i]+o));o=o.concat(t)}return[...new Set(o)].sort()}setSelectionMixin(e,t){const{anchor:o,zones:i}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=o,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,o)=>t===o.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(i)}selectCell(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.expandZone(o,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:i,cell:{col:e,row:t}},[i])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),o=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[o]})}onColumnsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=ei(o,"left",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=ei(s,"left",[...e.elements]);const r={cell:{col:s.left,row:s.top},zone:i},n=this.gridSelection.zones.map((t=>ei(t,"left",[...e.elements])));this.setSelectionMixin(r,n)}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=ei(o,"top",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=ei(s,"top",[...e.elements]);const r={cell:{col:s.left,row:s.top},zone:i},n=this.gridSelection.zones.map((t=>ei(t,"top",[...e.elements])));this.setSelectionMixin(r,n)}onAddElements(e){const t="COL"===e.dimension?"left":"top",o=Jo(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),i=this.gridSelection.zones.map((o=>Jo(o,t,e.base,e.position,e.quantity))),s={cell:{col:o.left,row:o.top},zone:o};this.setSelectionMixin(s,i)}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:"before"});const o="COL"===e.dimension,i=e.elements[0],s=e.elements[t-1],r=e.base<i,n=r&&o?t:0,a=r&&!o?t:0;this.dispatch("CUT",{cutTarget:[{left:o?i+n:0,right:o?s+n:this.getters.getNumberCols(e.sheetId)-1,top:o?0:i+a,bottom:o?this.getters.getNumberRows(e.sheetId)-1:s+a}]}),this.dispatch("PASTE",{target:[{left:o?e.base:0,right:o?e.base+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:e.base,bottom:o?this.getters.getNumberRows(e.sheetId)-1:e.base+t-1}]});const l=r?e.elements.map((e=>e+t)):e.elements;let c=e.base;for(const t of l){const o="COL"===e.dimension?this.getters.getColSize(e.sheetId,t):this.getters.getRowSize(e.sheetId,t);this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:o,elements:[c]}),c+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:l})}isMoveElementAllowed(e){const t="COL"===e.dimension,o=e.elements[0],i=e.elements[e.elements.length-1],s=e.sheetId,r=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return r(s,o-1,o)||r(s,i,i+1)||r(s,e.base-1,e.base)?2:0}clipSelection(e,t){const o=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:He(e.left,0,o),right:He(e.right,0,o),top:He(e.top,0,i),bottom:He(e.bottom,0,i)}))),anchor:{cell:{col:He(t.anchor.cell.col,0,o),row:He(t.anchor.cell.row,0,i)},zone:{left:He(t.anchor.zone.left,0,o),right:He(t.anchor.zone.right,0,o),top:He(t.anchor.zone.top,0,i),bottom:He(t.anchor.zone.bottom,0,i)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getSelectedZones();t.fillStyle="#f3f7fe";const s=1===i.length&&i[0].left===i[0].right&&i[0].top===i[0].bottom;t.fillStyle=s?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*o;for(const e of i){const{x:o,y:i,width:s,height:r}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(o,i,s,r),t.globalCompositeOperation="source-over",t.strokeRect(o,i,s,r)}t.globalCompositeOperation="source-over";const r=this.getActivePosition();let n;t.strokeStyle=E,t.lineWidth=3*o,n=this.getters.isInMerge(r)?this.getters.getMerge(r):fi(r);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(n);c>0&&h>0&&t.strokeRect(a,l,c,h)}}).add("clipboard",class extends fC{static layers=[2];static getters=["getClipboardContent","getClipboardTextContent","isCutOperation","isPaintingFormat"];status="invisible";state;lastPasteState;_isPaintingFormat=!1;allowDispatch(e){switch(e.type){case"CUT":const t=e.cutTarget||this.getters.getSelectedZones();return this.getClipboardState(t,e.type).isCutAllowed(t);case"PASTE":if(!this.state)return 23;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:o});case"PASTE_FROM_OS_CLIPBOARD":return new YC(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}}return 0}handle(e){switch(e.type){case"COPY":case"CUT":const t="cutTarget"in e&&e.cutTarget||this.getters.getSelectedZones();this.state=this.getClipboardState(t,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:o,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.lastPasteState=this.state,this.status="invisible";break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Xo(t[0])){for(const{col:t,row:o}of ui(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:o,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==this.state?.operation)return;this.state.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==this.state?.operation)return;for(let t of e.elements){if(this.state.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":this.state=new YC(e.text,this.getters,this.dispatch,this.selection),this.state.paste(e.target),this.lastPasteState=this.state,this.status="invisible";break;case"REPEAT_PASTE":this.lastPasteState?.paste(e.target,{pasteOption:e.pasteOption,shouldPasteCF:!0,selectTarget:!0});break;case"ACTIVATE_PAINT_FORMAT":{const e=this.getters.getSelectedZones();this.state=this.getClipboardStateForCopyCells(e,"COPY"),this._isPaintingFormat=!0,this.status="visible";break}default:Es(e)&&(this.status="invisible")}}getClipboardContent(){return this.state?.getClipboardContent()||{[fs.PlainText]:"\t"}}getClipboardTextContent(){return this.state?.getClipboardContent()[fs.PlainText]||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i;return i="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(o)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1},{cut:[i],paste:[e]}}getInsertCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i,s;return"COL"===t?(i={...e,right:this.getters.getNumberCols(o)-1},s={...e,left:e.right+1,right:e.right+1}):(i={...e,bottom:this.getters.getNumberRows(o)-1},s={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1}),{cut:[i],paste:[s]}}getClipboardStateForCopyCells(e,t){return new GC(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new qC(t,this.getters,this.dispatch):new GC(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}).add("edition",class extends fC{static getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights","getCurrentEditedCell"];col=0;row=0;mode="inactive";sheetId="";currentContent="";currentTokens=[];selectionStart=0;selectionEnd=0;selectionInitialStart=0;initialContent="";previousRef="";previousRange=void 0;colorIndexByRange={};allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=e.text||this.getComposerContent(this.getters.getActivePosition());return this.validateSelection(t.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handleEvent(e){if("selecting"===this.mode)if("newAnchor"===e.mode)this.insertSelectedRange(e.anchor.zone);else this.replaceSelectedRanges(e.anchor.zone)}handle(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":this.selectionStart=e.start,this.selectionEnd=e.end;break;case"STOP_COMPOSER_RANGE_SELECTION":this.isSelectingForComposer()&&(this.mode="editing");break;case"START_EDITION":"inactive"!==this.mode&&e.text?this.setContent(e.text,e.selection):this.startEdition(e.text,e.selection),this.updateRangeColor();break;case"STOP_EDITION":e.cancel?(this.cancelEditionAndActivateSheet(),this.resetContent()):this.stopEdition(),this.colorIndexByRange={};break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0),this.updateRangeColor();break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEditionAndActivateSheet(),this.resetContent();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.getters.getRangeFromRangeData(e.range),o=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:o,sheetName:i}=Bo(e.value),s=i||this.getters.getSheetName(this.sheetId),r=this.getters.getActiveSheetId();if(this.getters.getSheetName(r)!==s)return!1;const n=this.getters.getRangeFromSheetXC(r,o);return si(this.getters.expandZone(r,n.zone),t.zone)}));this.previousRef=o.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=o.start;break;case"CHANGE_HIGHLIGHT":const i=this.getters.getRangeFromRangeData(e.range),s=this.getRangeReference(i,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(s),this.previousRef=s,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"ACTIVATE_SHEET":if(this.currentContent.startsWith("=")||(this.cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),s=this.getters.expandZone(e.sheetIdTo,fi({col:o,row:i}));this.selection.resetAnchor(this,{cell:{col:o,row:i},zone:s})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.mode||(this.sheetId=this.getters.getActiveSheetId(),this.cancelEditionAndActivateSheet(),this.resetContent(),this.ui.notifyUI({type:"ERROR",text:JC}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}getEditionMode(){return this.mode}getCurrentContent(){return"inactive"===this.mode?this.getComposerContent(this.getters.getActivePosition()):this.currentContent}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}getCurrentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}isSelectingForComposer(){return"selecting"===this.mode}showSelectionIndicator(){return this.isSelectingForComposer()&&this.canStartComposerRangeSelection()}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((o=>o.start<=e&&o.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const o=e.map(XC).map((e=>e.value)).join(""),i=this.currentContent,s=e[0].start,r=e[e.length-1].end,n=i.slice(0,s)+o+i.slice(r),a=n.length-i.length,l={start:t[0].start,end:t[t.length-1].end+a};1===t.length&&this.selectionStart===this.selectionEnd&&(l.start=l.end),this.dispatch("SET_CURRENT_CONTENT",{content:n,selection:l})}validateSelection(e,t,o){return t>=0&&t<=e&&o>=0&&o<=e?0:46}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:JC});const{top:t,left:o}=ei({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=o,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:JC});const{top:t,left:o}=ei({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=o,this.row=t}onAddElements(e){const{top:t,left:o}=Jo({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=o,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=fi({col:this.col,row:this.row});this.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.mode="selecting",this.selectionInitialStart=this.selectionStart}startEdition(e,t){const o=this.getters.getActiveCell();e&&o.format?.includes("%")&&Jt(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:i,row:s,sheetId:r}=this.getters.getActivePosition();this.col=i,this.sheetId=r,this.row=s,this.initialContent=this.getComposerContent({sheetId:r,col:i,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const n=fi({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:n},{handleEvent:this.handleEvent.bind(this),release:()=>{this.stopEdition()}})}stopEdition(){if("inactive"!==this.mode){this.cancelEditionAndActivateSheet();const e=this.col,t=this.row;let o=this.currentContent;if(!(this.initialContent!==o))return;if(o){const i=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCell({sheetId:i,col:this.col,row:this.row});if(o.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,i=e-t;i>0&&(o+=dt(new Array(i).fill(")")))}else s.link&&(o=ot(o,s.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:e,row:t,content:o})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,content:"",col:e,row:t});this.setContent("")}}cancelEditionAndActivateSheet(){if("inactive"===this.mode)return;this.cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}getComposerContent(e){const t=this.getters.getCell(e);if(t?.isFormula)return t.content;const{format:o,value:i,type:s,formattedValue:r}=this.getters.getEvaluatedCell(e);switch(s){case ms.text:case ms.empty:return i;case ms.boolean:return r;case ms.error:return t?.content||"";case ms.number:return o&&bo(o)?r:this.numberComposerContent(i,o)}}numberComposerContent(e,t){return t?.includes("%")?100*e+"%":function(e){const{integerDigits:t,decimalDigits:o}=mo(e,20);return o?`${t}.${o}`:t}(e)}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,o){const i=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(i||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Gv(e):[],this.currentTokens.length>100&&o&&this.ui.notifyUI({type:"ERROR",text:r("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),o=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(o,t),this.selectionInitialStart=t):(this.insertText(","+o,t),this.selectionInitialStart=t+1)}replaceSelectedRanges(e){const t=this.getZoneReference(e);this.replaceText(t,this.selectionInitialStart,this.selectionEnd)}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const o=this.getters.getActiveSheetId();let i=this.getters.zoneToXC(o,e,t);if(this.getters.getCurrentEditedCell().sheetId!==this.getters.getActiveSheetId()){i=`${Be(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${i}`}return i}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){let o=[...t];1===t.length&&vi(e.zone)>1?o.push({...t[0]}):2===t.length&&1===vi(e.zone)&&o.pop();const i=e.clone({parts:o});return this.getters.getSelectionRangeString(i,this.getters.getCurrentEditedCell().sheetId)}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),o=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,o)}replaceText(e,t,o){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(o,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const o=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),i=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:o,selection:{start:i,end:i}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getCurrentEditedCell().sheetId,t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),o={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(o[e]=this.colorIndexByRange[e]);const i=new Set(Object.values(o));let s=0;const r=()=>{for(;i.has(s);)s++;return i.add(s),s};for(const e of t){const t=e in o?o[e]:r();o[e]=t}this.colorIndexByRange=o}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getCurrentEditedCell().sheetId,t=e=>{const t=this.colorIndexByRange[e];return It[t%It.length]};return this.getReferencedRanges().map((o=>{const i=this.getters.getRangeString(o,e);return{zone:o.zone,color:t(i),sheetId:o.sheetId}}))}getReferencedRanges(){const e=this.getters.getCurrentEditedCell().sheetId;return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value)))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let o=t,i=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(i.type)||rv.includes(i.value);){if("SPACE"!==i.type||o<1)return!1;o--,i=this.currentTokens[o]}for(o=t+1,i=this.currentTokens[o];i&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(i.type);){if("SPACE"!==i.type)return!1;o++,i=this.currentTokens[o]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((o=>o.start<=e&&o.end>=e||o.start>=e&&o.start<t))}}),sE=(new _i).add("evaluation",class extends fC{static getters=["evaluateFormula","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getColEvaluatedCells","getEvaluatedCellsInZone"];isUpToDate=!1;evaluatedCells={};evalContext;lazyEvaluation;constructor(e){super(e),this.evalContext=e.custom,this.lazyEvaluation=e.lazyEvaluation}handle(e){switch(bs.has(e.type)&&(this.isUpToDate=!1),e.type){case"UPDATE_CELL":("content"in e||"format"in e)&&(this.isUpToDate=!1);break;case"EVALUATE_CELLS":this.evaluate()}}finalize(){this.isUpToDate||(this.evaluate(),this.isUpToDate=!0)}evaluateFormula(e,t=this.getters.getActiveSheetId()){const o=Wv(e),i=this.getCompilationParameters((e=>this.getEvaluatedCell(this.getters.getCellPosition(e.id)))),s=[];for(let e of o.dependencies)s.push(this.getters.getRangeFromSheetXC(t,e));return o.execute(s,...i).value}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.formattedValue))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.value))}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.format))}getEvaluatedCell({sheetId:e,col:t,row:o}){return void 0===this.getters.getCell({sheetId:e,col:t,row:o})?Os(""):this.evaluatedCells[e]?.[t]?.[o]?.()||Os("")}getEvaluatedCells(e){const t=this.getters.getCells(e)||{},o={};for(let e of Object.keys(t)){const t=this.getters.getCellPosition(e);o[e]=this.getEvaluatedCell(t)}return o}getColEvaluatedCells(e,t){return Object.values(this.evaluatedCells[e]?.[t]||[]).filter(lt).map((e=>e()))}getEvaluatedCellsInZone(e,t){return ui(t).map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o})))}setEvaluatedCell(e,t){const{col:o,row:i,sheetId:s}=this.getters.getCellPosition(e);this.evaluatedCells[s]||(this.evaluatedCells[s]={}),this.evaluatedCells[s][o]||(this.evaluatedCells[s][o]={}),this.evaluatedCells[s][o][i]=t,this.lazyEvaluation||this.evaluatedCells[s][o][i]()}*getAllCells(){for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t)yield t[e]}}evaluate(){this.evaluatedCells={};const e=new Set,t=e=>{const t=e.id,{col:s,row:r,sheetId:n}=this.getters.getCellPosition(t),a=this.evaluatedCells[n]?.[s]?.[r];return a||ut((()=>{try{switch(e.isFormula){case!0:return i(e);case!1:return Ts(e.content,e.format)}}catch(t){return o(t,e)}}))},o=(e,t)=>{e instanceof Error||(e=new Error(e));const o=e?.errorType||a.GenericError,i=s[2].__lastFnCalled||"",r=new c(o,e.message.replace("[[FUNCTION_NAME]]",i),void 0!==e.logLevel?e.logLevel:l.error);return Fs(t.content,r)},i=t=>{const o=t.id;if(e.has(o))throw new d;s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(o);return Ht(e.col,e.row)},e.add(o);const i=t.compiledFormula.execute(t.dependencies,...s);if(e.delete(o),Array.isArray(i.value))throw new Error(r("This formula depends on invalid values"));return Os(i.value,t.format||i.format)},s=this.getCompilationParameters((e=>t(e)()));for(const e of this.getAllCells())this.setEvaluatedCell(e.id,t(e))}getCompilationParameters(e){const t=Object.assign(Object.create(bC),this.evalContext,{getters:this.getters}),o=this.getters;const i=t=>{const o=e(t);if(o.type===ms.error)throw o.error;return o};return[function(e,t,s,n){if(t)return{value:Ko(e.zone)};if(!Xo(e.zone))throw new u;if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(n?r("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",s.toString(),n.toString()):r("Function %s expects its parameters to be single values or single cell references, not ranges.",s.toString()));if(e.invalidSheetName)throw new Error(r("Invalid sheet name: %s",e.invalidSheetName));return function(e){let t;if(!o.tryGetSheet(e.sheetId))throw new Error(r("Invalid sheet name"));return t=o.getCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}),t&&""!==t.content?i(t):{value:null,format:t?.format}}(e)},function(e){const s=e.sheetId;if(!Xo(e.zone))throw new u;const r=o.getSheetZone(s),n=[],a=ii(e.zone,r);if(!a)return n.push([]),n;for(let o=a.left;o<=a.right;o++){const s=[];for(let r=a.top;r<=a.bottom;r++){const n=t.getters.getCell({sheetId:e.sheetId,col:o,row:r});s.push(n?i(n):void 0)}n.push(s)}return n},t]}exportForExcel(e){for(let t of e.sheets)for(const e in t.cells){const o={sheetId:t.id,...Bt(e)},i=this.getters.getCell(o);if(i){const s=t.cells[e],r=this.getEvaluatedCell(o);s.value=r.value,s.isFormula=i.isFormula&&!this.isBadExpression(i.content),i.format!==r.format&&(s.computedFormat=r.format)}}}isBadExpression(e){try{return Wv(e),!1}catch(e){return!0}}}).add("evaluation_filter",class extends fC{static getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];filterValues={};hiddenRows=new Set;isEvaluationDirty=!1;allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return 79;return 0}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_FILTER_TABLE":this.isEvaluationDirty=!0;break;case"START":for(const e of this.getters.getSheetIds()){this.filterValues[e]={};for(const t of this.getters.getFilters(e))this.filterValues[e][t.id]=[]}break;case"CREATE_SHEET":this.filterValues[e.sheetId]={};break;case"HIDE_COLUMNS_ROWS":this.updateHiddenRows();break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows();break;case"DUPLICATE_SHEET":const t={};for(const o of this.getters.getFilters(e.sheetIdTo)){const i=o.zoneWithHeaders;t[o.id]=this.getFilterValues({sheetId:e.sheetId,col:i.left,row:i.top})}this.filterValues[e.sheetIdTo]=t}}finalize(){this.isEvaluationDirty&&(this.updateHiddenRows(),this.isEvaluationDirty=!1)}isRowFiltered(e,t){return e===this.getters.getActiveSheetId()&&this.hiddenRows.has(t)}getCellBorderWithFilterBorder(e){const{sheetId:t,col:o,row:i}=e;let s;for(let e of this.getters.getFilterTables(t)){const r=e.zone;if(ni(o,i,r)){const e=this.intersectZoneWithViewport(t,r);s={top:i===e.top?K:void 0,bottom:i===e.bottom?K:void 0,left:o===e.left?K:void 0,right:o===e.right?K:void 0}}}const r=this.getters.getCellBorder(e),n={...s,...ft(r||{})};return ct(n)?null:n}getFilterHeaders(e){const t=[];for(let o of this.getters.getFilterTables(e)){const i=o.zone;if(!i)continue;const s=i.top;for(let o=i.left;o<=i.right;o++)this.getters.isColHidden(e,o)||this.getters.isRowHidden(e,s)||t.push({col:o,row:s})}return t}getFilterValues(e){const t=this.getters.getFilterId(e),o=e.sheetId;return t&&this.filterValues[o]&&this.filterValues[o][t]||[]}isFilterHeader({sheetId:e,col:t,row:o}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===o))}isFilterActive(e){const t=this.getters.getFilterId(e),o=e.sheetId;return Boolean(t&&this.filterValues[o]?.[t]?.length)}intersectZoneWithViewport(e,t){return{left:this.getters.findVisibleHeader(e,"COL",t.left,t.right),right:this.getters.findVisibleHeader(e,"COL",t.right,t.left),top:this.getters.findVisibleHeader(e,"ROW",t.top,t.bottom),bottom:this.getters.findVisibleHeader(e,"ROW",t.bottom,t.top)}}updateFilter({col:e,row:t,values:o,sheetId:i}){const s=this.getters.getFilterId({sheetId:i,col:e,row:t});s&&(this.filterValues[i]||(this.filterValues[i]={}),this.filterValues[i][s]=o)}updateHiddenRows(){const e=this.getters.getActiveSheetId(),t=this.getters.getFilters(e).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),o=new Set;for(let i of t){if(this.getters.isRowHiddenByUser(e,i.zoneWithHeaders.top))continue;if(o.has(i.zoneWithHeaders.top))continue;const t=this.filterValues[e]?.[i.id]?.map(bt);if(t&&i.filteredZone)for(let s=i.filteredZone.top;s<=i.filteredZone.bottom;s++){const r=this.getCellValueAsString(e,i.col,s);t.includes(r)&&o.add(s)}}this.hiddenRows=o}getCellValueAsString(e,t,o){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets)for(const e of t.filterTables){const o=Yo(e.range),i=[],s=[];for(const e of je(0,hi(o).numberOfCols)){const r={sheetId:t.id,col:o.left+e,row:o.top},n=this.getFilterValues(r),a=this.getters.getFilter(r);if(!a)continue;const l=(a.filteredZone?ui(a.filteredZone).map((({col:e,row:o})=>this.getters.getEvaluatedCell({sheetId:t.id,col:e,row:o}))).filter((e=>e.type!==ms.empty)).map((e=>e.formattedValue)):[]).filter((e=>!n.includes(e)));i.push({colId:e,filteredValues:[...new Set(l)]});const c={col:a.col,row:a.zoneWithHeaders.top,sheetId:t.id},h=this.getters.getEvaluatedCell(c).formattedValue,d=this.getUniqueColNameForExcel(e,h,s);s.push(d),t.cells[Ht(c.col,c.row)]={...t.cells[Ht(c.col,c.row)],content:d,value:d,isFormula:!1}}e.filters=i}}getUniqueColNameForExcel(e,t,o){t||(t=`Column${e}`);let i=t,s=2;for(;o.includes(i);)i=t+String(s),s++;return i}}).add("evaluation_chart",class extends fC{static getters=["getChartRuntime","getBackgroundOfSingleCellChart"];charts={};createRuntimeChart=function(e){const t=On.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(o){const i=t.find((e=>e.match(o.type)));if(!i)throw new Error("No runtime builder for this chart.");return i.getChartRuntime(o,e)}}(this.getters);handle(e){if(bs.has(e.type)||vs.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type)for(const e in this.charts)this.charts[e]=void 0;switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":case"DELETE_FIGURE":this.charts[e.id]=void 0;break;case"DELETE_SHEET":for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0)}}getChartRuntime(e){if(!this.charts[e]){const t=this.getters.getChart(e);if(!t)throw new Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getBackgroundOfSingleCellChart(e,t){if(e)return e;if(!t)return w;const o=t.zone.left,i=t.zone.top,s=t.sheetId;return this.getters.getCellComputedStyle({sheetId:s,col:o,row:i}).fillColor||w}}).add("evaluation_cf",class extends fC{static getters=["getConditionalIcon","getCellComputedStyle"];isStale=!0;computedStyles={};computedIcons={};handle(e){switch((vs.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isStale=!0),e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const o=this.getters.getActiveSheetId(),i=this.getters.getRulesByCell(o,e.originCol,e.originRow);for(const t of i)this.adaptRules(o,t,[Ht(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.originPosition,e.targetPosition,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e){const{sheetId:t,col:o,row:i}=e,s=this.getters.getCell(e),r=this.computedStyles[t],n=r&&r[o]?.[i],a={...s?.style,...n};return this.getters.getEvaluatedCell(e).link&&!a.textColor&&(a.textColor=I),this.getters.isFilterHeader(e)&&(a.bold=!0),a}getConditionalIcon({col:e,row:t}){const o=this.getters.getActiveSheetId(),i=this.computedIcons[o];return i&&i[e]?.[t]}computeStyles(){const e=this.getters.getActiveSheetId();this.computedStyles[e]={},this.computedIcons[e]={};const t=this.computedStyles[e];for(let o of this.getters.getConditionalFormats(e).reverse())try{switch(o.rule.type){case"ColorScaleRule":for(let e of o.ranges)this.applyColorScale(e,o.rule);break;case"IconSetRule":for(let e of o.ranges)this.applyIcon(e,o.rule);break;default:for(let i of o.ranges){const s=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=s.top;i<=s.bottom;i++)for(let r=s.left;r<=s.right;r++){const s=this.rulePredicate[o.rule.type];let n=this.getters.getEvaluatedCell({sheetId:e,col:r,row:i});s&&s(n,o.rule)&&(t[r]||(t[r]=[]),t[r][i]=Object.assign(t[r]?.[i]||{},o.rule.style))}}}}catch(e){}}parsePoint(e,t,o){const i=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCellsInZone(i,this.getters.getRangeFromSheetXC(i,e).zone).filter((e=>e.type===ms.number)).map((e=>e.value));switch(t.type){case"value":return"max"===o?Math.max(...s):Math.min(...s);case"number":return Number(t.value);case"percentage":const e=Math.min(...s);return e+(Math.max(...s)-e)*Number(t.value)/100;case"percentile":return oo(s,Number(t.value)/100,!0);case"formula":const i=t.value&&this.getters.evaluateFormula(t.value);return i instanceof Promise?null:i;default:return null}}applyIcon(e,t){const o=this.parsePoint(e,t.lowerInflectionPoint),i=this.parsePoint(e,t.upperInflectionPoint);if(null===o||null===i||o>i)return;const s=this.getters.getActiveSheetId(),r=this.getters.getRangeFromSheetXC(s,e).zone,n=this.computedIcons[s],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=r.top;e<=r.bottom;e++)for(let l=r.left;l<=r.right;l++){const r=this.getters.getEvaluatedCell({sheetId:s,col:l,row:e});if(r.type!==ms.number)continue;const c=this.computeIcon(r.value,i,t.upperInflectionPoint.operator,o,t.lowerInflectionPoint.operator,a);n[l]||(n[l]=[]),n[l][e]=c}}computeIcon(e,t,o,i,s,r){return"ge"===o&&e>=t||"gt"===o&&e>t?r[0]:"ge"===s&&e>=i||"gt"===s&&e>i?r[1]:r[2]}applyColorScale(e,t){const o=this.parsePoint(e,t.minimum,"min"),i=t.midpoint?this.parsePoint(e,t.midpoint):null,s=this.parsePoint(e,t.maximum,"max");if(null===o||null===s||o>=s||i&&(o>=i||i>=s))return;const r=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(r,e).zone,a=this.computedStyles[r],l=[];t.midpoint&&i?(l.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,i,t.minimum.color,t.midpoint.color)}),l.push({minValue:i,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(i,s,t.midpoint.color,t.maximum.color)})):l.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,s,t.minimum.color,t.maximum.color)});for(let e=n.top;e<=n.bottom;e++)for(let t=n.left;t<=n.right;t++){const n=this.getters.getEvaluatedCell({sheetId:r,col:t,row:e});if(n.type===ms.number){const r=He(n.value,o,s);let c;c=2===l.length&&i?r<=i?this.colorCell(r,l[0].minValue,l[0].minColor,l[0].colorDiffUnit):this.colorCell(r,l[1].minValue,l[1].minColor,l[1].colorDiffUnit):this.colorCell(r,l[0].minValue,l[0].minColor,l[0].colorDiffUnit),a[t]||(a[t]=[]),a[t][e]=a[t]?.[e]||{},a[t][e].fillColor=Rt(c)}}}computeColorDiffUnits(e,t,o,i){const s=t-e;return[((o>>16)%256-(i>>16)%256)/s,((o>>8)%256-(i>>8)%256)/s,(o%256-i%256)/s]}colorCell(e,t,o,i){const[s,r,n]=i;return Math.round((o>>16)%256-s*(e-t))<<16|Math.round((o>>8)%256-r*(e-t))<<8|Math.round(o%256-n*(e-t))}rulePredicate={CellIsRule:(e,t)=>{if(e.type===ms.error)return!1;const o=t.values.map(As);switch(t.operator){case"IsEmpty":return""===e.value.toString().trim();case"IsNotEmpty":return""!==e.value.toString().trim();case"BeginsWith":return""!==o[0]&&e.value.toString().startsWith(o[0].toString());case"EndsWith":return""!==o[0]&&e.value.toString().endsWith(o[0].toString());case"Between":return e.value>=o[0]&&e.value<=o[1];case"NotBetween":return!(e.value>=o[0]&&e.value<=o[1]);case"ContainsText":return e.value.toString().indexOf(o[0].toString())>-1;case"NotContains":return!e.value||-1==e.value.toString().indexOf(o[0].toString());case"GreaterThan":return e.value>o[0];case"GreaterThanOrEqual":return e.value>=o[0];case"LessThan":return e.value<o[0];case"LessThanOrEqual":return e.value<=o[0];case"NotEqual":return""!==o[0]&&e.value!==o[0];case"Equal":return""===o[0]||e.value===o[0];default:console.warn(r("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}};adaptRules(e,t,o,i){if(0===o.length&&0===i.length)return;const s=this.getters.getConditionalFormats(e),r=s.findIndex((e=>e.id===t.id));let n=[];r>-1&&(n=s[r].ranges),n=n.concat(o);const a=li(n,i);this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},ranges:a.map((t=>this.getters.getRangeDataFromXc(e,t))),sheetId:e})}pasteCf(e,t,o){const i=Ht(t.col,t.row);for(let s of this.getters.getConditionalFormats(e.sheetId))for(let r of s.ranges)if(ni(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,r).zone)){const r=s,n=[];"CUT"===o&&n.push(Ht(e.col,e.row)),e.sheetId===t.sheetId?this.adaptRules(e.sheetId,r,[i],n):(this.adaptRules(t.sheetId,r,[i],[]),this.adaptRules(e.sheetId,r,[],n))}}}).add("viewport",class extends fC{static getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","isPositionVisible"];viewports={};sheetViewWidth=ge();sheetViewHeight=ge();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkScrollingDirection(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return 0}}handleEvent(e){switch(e.type){case"HeadersSelected":case"AlterZone":break;case"ZonesSelected":let{col:t,row:o}=pi(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const i=e.previousAnchor.zone,s=e.anchor.zone,{top:r,bottom:n,left:a,right:l}=this.getters.getActiveMainViewport();i.left===s.left&&i.right===s.right&&(t=a>t||t>l?a:t),i.top===s.top&&i.bottom===s.bottom&&(o=r>o||o>n?r:o)}const i=this.getters.getActiveSheetId();t=Math.min(t,this.getters.getNumberCols(i)-1),o=Math.min(o,this.getters.getNumberRows(i)-1),this.refreshViewport(this.getters.getActiveSheetId(),{col:t,row:o})}}handle(e){switch(this.cleanViewports(),e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.resetSheetViews();break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const{top:t}=this.getActiveMainViewport(),o=this.getters.getActiveSheetId(),i=this.clipOffsetY(this.getters.getRowDimensions(o,t).start+this.sheetViewHeight);this.shiftVertically(i);break;case"SHIFT_VIEWPORT_UP":{const{top:e}=this.getActiveMainViewport(),t=this.getters.getActiveSheetId(),o=this.clipOffsetY(this.getters.getRowDimensions(t,e).end-this.sheetViewHeight);this.shiftVertically(o);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UPDATE_FILTER":this.resetViewports(e.sheetId);break;case"UPDATE_CELL":("content"in e||"format"in e||void 0!==e.style?.fontSize)&&this.sheetsWithDirtyViewports.add(e.sheetId);break;case"ACTIVATE_SHEET":this.setViewports(),this.refreshViewport(e.sheetIdTo);break;case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":this.resetViewports(this.getters.getActiveSheetId());break;case"DELETE_SHEET":this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"START_EDITION":const{col:s,row:r}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:s,row:r})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){const e=this.getters.getSheetIds();for(const t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>je(e.left,e.right+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>je(e.top,e.bottom+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"ROW",t)))}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:o,ySplit:i}=this.getters.getPaneDivisions(e);let{width:s,height:r}=t.getMaxSize();return{x:this.getters.getColDimensions(e,o).start,y:this.getters.getRowDimensions(e,i).start,width:s,height:r}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:o}=this.getMainViewportRect(),i=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-i.viewportWidth+1),maxOffsetY:Math.max(0,o-i.viewportHeight+1)}}getColRowOffsetInViewport(e,t,o){const i=this.getters.getActiveSheetId(),s=this.getters.getSheetViewVisibleCols(),r=this.getters.getSheetViewVisibleRows();if(o<t)return-this.getColRowOffsetInViewport(e,o,t);let n=0;const a="COL"===e?s:r;for(let s=t;s<o;s++)a.includes(s)&&(n+="COL"===e?this.getters.getColSize(i,s):this.getters.getRowSize(i,s));return n}isVisibleInViewport({sheetId:e,col:t,row:o}){return this.getSubViewports(e).some((e=>e.isVisible(t,o)))}getEdgeScrollCol(e,t,o){let i=!1,s=0,r=0;const{xSplit:n}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(i=!0,r=qt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,r=qt(l-e),s=-1):n&&t<l&&e>l&&(i=!0,r=qt(e),s="reset"),{canEdgeScroll:i,direction:s,delay:r}}getEdgeScrollRow(e,t,o){let i=!1,s=0,r=0;const{ySplit:n}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(i=!0,r=qt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,r=qt(l-e),s=-1):n&&t<l&&e>l&&(i=!0,r=qt(e),s="reset"),{canEdgeScroll:i,direction:s,delay:r}}getVisibleRect(e){const t=this.getters.getActiveSheetId(),o=this.getSubViewports(t).map((t=>t.getRect(e))).filter(lt);if(0===o.length)return{x:0,y:0,width:0,height:0};const i=Math.min(...o.map((e=>e.x))),s=Math.min(...o.map((e=>e.y))),r=Math.max(...o.map((e=>e.x+e.width)))-i,n=Math.max(...o.map((e=>e.y+e.height)))-s;return{x:i+this.gridOffsetX,y:s+this.gridOffsetY,width:r,height:n}}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,o).start}}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(lt)}checkPositiveDimension(e){return e.width<0||e.height<0?68:0}checkValuesAreDifferent(e){const{height:t,width:o}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===o&&e.height===t?76:0}checkScrollingDirection({offsetX:e,offsetY:t}){const o=this.getMainInternalViewport(this.getters.getActiveSheetId());return!o.canScrollHorizontally&&e>0||!o.canScrollVertically&&t>0?69:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e=this.getters.getSheetIds();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetSheetViews(){for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const o=this.getSubViewports(e);Object.values(o).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,o=0,i=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=o,this.gridOffsetY=i,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.resetViewports(e)}setSheetViewOffset(e,t){const o=this.getters.getActiveSheetId(),{maxOffsetX:i,maxOffsetY:s}=this.getMaximumSheetOffset();Object.values(this.getSubViewports(o)).forEach((o=>o.setViewportOffset(He(e,0,i),He(t,0,s))))}clipOffsetY(e){const{height:t}=this.getMainViewportRect(),o=t-this.sheetViewHeight;return e=Math.min(e,o),e=Math.max(e,0)}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetScrollbarX||0,y:this.viewports[e]?.bottomRight.offsetScrollbarY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getNumberCols(e),s=this.getters.getNumberRows(e),r=this.getters.getColRowOffset("COL",0,t,e),n=this.getters.getColRowOffset("ROW",0,o,e),{xRatio:a,yRatio:l}=this.getFrozenSheetViewRatio(e),c=a<1,h=l<1,d=this.getViewportOffset(e),u={topLeft:o&&t&&new vC(this.getters,e,{left:0,right:t-1,top:0,bottom:o-1},{width:r,height:n},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:o&&new vC(this.getters,e,{left:t,right:i-1,top:0,bottom:o-1},{width:this.sheetViewWidth-r,height:n},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new vC(this.getters,e,{left:0,right:t-1,top:o,bottom:s-1},{width:r,height:this.sheetViewHeight-n},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new vC(this.getters,e,{left:t,right:i-1,top:o,bottom:s-1},{width:this.sheetViewWidth-r,height:this.sheetViewHeight-n},{canScrollHorizontally:c,canScrollVertically:h},{x:c?d.x:0,y:h?d.y:0})};this.viewports[e]=u}refreshViewport(e,t){Object.values(this.getSubViewports(e)).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const{top:t}=this.getActiveMainViewport(),{scrollX:o}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(o,e);const{anchor:i}=this.getters.getSelection(),s=this.getActiveMainViewport().top-t;this.selection.selectCell(i.cell.col,i.cell.row+s)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:i,scrollY:s}=this.getActiveSheetScrollInfo(),{x:r,y:n}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of o)e.x>=r&&(e.x+e.width<=r+i||e.x>=a+i+r)||e.y>=n&&(e.y+e.height<=n+s||e.y>=l+s+n)||t.push(e);return t}isPositionVisible(e){const{scrollX:t,scrollY:o}=this.getters.getActiveSheetScrollInfo(),{x:i,y:s}=this.getters.getMainViewportCoordinates(),{width:r,height:n}=this.getters.getSheetViewDimension();return!(e.x>=i&&(e.x<i+t||e.x>r+t+i))&&!(e.y>=s&&(e.y<s+o||e.y>n+o+s))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getColDimensions(e,t).start,s=this.getters.getRowDimensions(e,o).start;return{xRatio:i/(this.sheetViewWidth+this.gridOffsetX),yRatio:s/(this.sheetViewHeight+this.gridOffsetY)}}}).add("custom_colors",class extends fC{customColors=new Set;shouldUpdateColors=!1;static getters=["getCustomColors"];handle(e){switch(e.type){case"UPDATE_CELL":case"UPDATE_CHART":case"CREATE_CHART":case"ADD_CONDITIONAL_FORMAT":case"SET_BORDER":case"SET_ZONE_BORDERS":case"SET_FORMATTING":this.shouldUpdateColors=!0}}finalize(){if(this.shouldUpdateColors){this.shouldUpdateColors=!1;for(const e of this.getCustomColors())this.tryToAddColor(e)}}getCustomColors(){let e=[];for(const t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getChartColors(t));return function(e){const t=[{leadColor:Mt(255,0,0),colors:[]},{leadColor:Mt(255,128,0),colors:[]},{leadColor:Mt(128,128,0),colors:[]},{leadColor:Mt(128,255,0),colors:[]},{leadColor:Mt(0,255,0),colors:[]},{leadColor:Mt(0,255,128),colors:[]},{leadColor:Mt(0,255,255),colors:[]},{leadColor:Mt(0,127,255),colors:[]},{leadColor:Mt(0,0,255),colors:[]},{leadColor:Mt(127,0,255),colors:[]},{leadColor:Mt(128,0,128),colors:[]},{leadColor:Mt(255,0,128),colors:[]}];for(const o of e.map(Ft)){let e=500,i=0;t.forEach(((t,s)=>{const r=(n=o,a=t.leadColor,Math.sqrt(Math.pow(n.r-a.r,2)+Math.pow(n.g-a.g,2)+Math.pow(n.b-a.b,2)));var n,a;e>r&&(e=r,i=s)})),t[i].colors.push(o)}return t.map((e=>e.colors.sort(((e,t)=>Lt(e).s-Lt(t).s)))).flat().map(_t)}([...new Set([...new Set([...e,...this.customColors])].filter(At).map(Tt))]).filter((e=>!N.includes(e)))}getColorsFromCells(e){const t=Object.values(this.getters.getCells(e)),o=new Set;for(const e of t)e.style?.textColor&&o.add(e.style.textColor),e.style?.fillColor&&o.add(e.style.fillColor);for(const t of this.getters.getBordersColors(e))o.add(t);return[...o]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),o=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(o.push(t.style.textColor),o.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(o.push(Rt(t.minimum.color)),o.push(t.midpoint?Rt(t.midpoint.color):void 0),o.push(Rt(t.maximum.color)))}return o.filter(lt)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let o=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&o.add(t),e.type){case"gauge":const t=e.sectionRule.colors;o.add(t.lowerColor),o.add(t.middleColor),o.add(t.upperColor);break;case"scorecard":const i=e;o.add(i.baselineColorDown),o.add(i.baselineColorUp)}}return[...o]}tryToAddColor(e){const t=Tt(e);e&&!N.includes(t)&&this.customColors.add(t)}}),rE=new _i;rE.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,execute:(e,t)=>Vi(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class nE{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageSize(t)}}getImageFromUser(){return new Promise(((e,t)=>{const o=document.createElement("input");o.setAttribute("type","file"),o.setAttribute("accept","image/*"),o.addEventListener("change",(async()=>{null===o.files||1!=o.files.length?t():e(o.files[0])})),o.click()}))}getImageSize(e){return new Promise(((t,o)=>{const i=new Image;i.src=e,i.addEventListener("load",(()=>{const e={width:i.width,height:i.height};t(e)})),i.addEventListener("error",o)}))}}const aE=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];xi`
1395
1418
  .o-ripple {
1396
1419
  z-index: 1;
1397
1420
  }
@@ -1975,7 +1998,7 @@
1975
1998
  outline: none;
1976
1999
  }
1977
2000
  }
1978
- `;const RE=e=>e;class TE extends t.Component{static template="o-spreadsheet-Spreadsheet";static components={TopBar:xE,Grid:jf,BottomBar:gE,SidePanel:fE,SpreadsheetDashboard:mE};static _t=RE;sidePanel;composer;_focusGrid;keyDownMapping;isViewportTooSmall=!1;get model(){return this.props.model}getStyle(){return this.env.isDashboard()?"grid-template-rows: auto;":"grid-template-rows: 63px auto 37px"}setup(){this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})};const e=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:e?new nE(e):void 0,loadCurrencies:this.model.config.external.loadCurrencies,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.openSidePanel.bind(this),toggleSidePanel:this.toggleSidePanel.bind(this),_t:TE._t,clipboard:this.env.clipboard||new yE(navigator.clipboard),startCellEdition:e=>this.onGridComposerCellFocused(e)}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:r("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.isOpen&&e!==this.sidePanel.component&&this.sidePanel.panelProps?.onCloseSidePanel?.(),this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid(),this.sidePanel.panelProps?.onCloseSidePanel?.()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}onKeydown(e){let t="";(e.ctrlKey||e.metaKey)&&(t+="CTRL+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];if(o)return e.preventDefault(),e.stopPropagation(),void o()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}}TE.props={model:Object};class AE{listeners=[];sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}function OE(e){return Vn.get(e.type)(e)}function ME(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class NE{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const o of this.operations){if(o.id===e)return e;if(o.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const o=this.buildTransformation.with(e.data),{before:i,operation:s,after:r}=this.locateOperation(t);this.operations=[...i,s,e,...r.map((e=>e.transformed(o)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new NE(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:o}=this.locateOperation(e);this.operations=t.concat([o])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class _E{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new FE(this.id,ut((()=>e(this.data))))}}class FE{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new FE(this.id,this.lazyData.map(e))}}class DE{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new DE(function*(e,t){for(const o of e)if(yield o,o.operation.id===t)return}(this.operations,e))}stopBefore(e){return new DE(function*(e,t){for(const o of e){if(o.operation.id===t)return;yield o}}(this.operations,e))}startAfter(e){return new DE(function*(e,t){let o=!0;for(const i of e)o||(yield i),i.operation.id===t&&(o=!1)}(this.operations,e))}}class LE{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new DE(Xe(this._execution(e),this._execution(e)))}revertedExecution(e){return new DE(Xe(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const o=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,o){e.insert(t,o),this.updateNextWith(e,t,o),this.insertPrevious(e,t,o)}undo(e,t){const o=this.buildTransformation.without(t.data),i=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const s=e.fork(t.id);i&&this.branchingOperationIds.set(s,i),this.insertBranchAfter(e,s),this.transform(s,o)}redo(e){const t=this.nextBranch(e);if(!t)return;const o=this.nextBranch(t);this.removeBranchFromTree(t);const i=this.branchingOperationIds.get(t);i?this.branchingOperationIds.set(e,i):this.branchingOperationIds.delete(e),o&&this.rebaseUp(o)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const o of this.revertedExecution(e))if(o.operation.id===t)return o;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!t||!o)return;const i=this.buildTransformation.without(o.data),s=t.fork(o.id);this.branchingOperationIds.set(s,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,s),s.transform(i);const r=this.nextBranch(s);r&&this.rebaseUp(r)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const o=this.branches.findIndex((t=>t===e));this.branches.splice(o+1,0,t)}updateNextWith(e,t,o){const i=this.branchingOperationIds.get(e),s=this.nextBranch(e);if(i&&s)if(e.getFirstOperationAmong(o,i)===i){const r=this.addToNextBranch(e,s,i,t,o);this.updateNextWith(s,r,o)}else{const e=this.buildTransformation.with(t.data);this.transform(s,e)}}addToNextBranch(e,t,o,i,s){let r=i;return s===o?(r=this.getTransformedOperation(e,o,i),t.prepend(r)):t.contains(s)?(r=this.getTransformedOperation(e,o,i),t.insert(r,s)):t.append(i),r}getTransformedOperation(e,t,o){const i=e.getOperation(t),s=this.buildTransformation.without(i.data);return o.transformed(s)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const o=this.nextBranch(e);o&&this.transform(o,t)}insertPrevious(e,t,o){const{previousBranch:i,branchingOperation:s}=this.findPreviousBranchingOperation(e);if(!i||!s)return;const r=this.buildTransformation.with(s.data),n=e.fork(o);n.transform(r),i.cutAfter(o),i.appendBranch(n);const a=t.transformed(r);this.insertPrevious(i,a,o)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const o=this.branchingOperationIds.get(t);return o?{previousBranch:t,branchingOperation:t.getOperation(o)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let o=!!t;const i=e.getOperations();for(let s=i.length-1;s>=0;s--){const r=i[s];r.id===t&&(o=!1),o||(yield{operation:r,branch:e,isCancelled:!this.shouldExecute(e,r)})}const s=this.previousBranch(e);yield*s?this._revertedExecution(s):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class PE{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new NE(this.buildTransformation),this.tree=new LE(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,o=new _E(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,o),this.HEAD_OPERATION=o}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const o=new _E(e,t),i=this.tree.getLastBranch();this.tree.insertOperationLast(i,o),this.HEAD_BRANCH=i,this.HEAD_OPERATION=o}insert(e,t,o){const i=new _E(e,t);this.revertTo(o),this.tree.insertOperationAfter(this.HEAD_BRANCH,i,o),this.fastForward()}undo(e,t,o){const{branch:i,operation:s}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(i,s),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}redo(e,t,o){const{branch:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(i),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}drop(e){this.revertBefore(e),this.tree.drop(e)}getRevertedExecution(){const e=[],t=this.tree.revertedExecution(this.HEAD_BRANCH);for(const{operation:o}of t)e.push(o.data);return e}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:o,isCancelled:i}of e)i||this.revertOperation(o.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:o,isCancelled:i}of e)i||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=o}}function kE(e){return new PE({initialOperationId:e.initialRevisionId,applyOperation:t=>{const o=t.commands.slice(),{changes:i}=e.recordChanges((()=>{for(const t of o)e.dispatch(t)}));t.setChanges(i)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){UE(t.changes[e],"before")}}([e]),buildEmpty:e=>new TC(e,"empty",[]),buildTransformation:{with:e=>t=>new TC(t.id,t.clientId,IC(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new TC(t.id,t.clientId,IC(t.commands,e.commands.map(OE).flat()),t.rootCommand,void 0,t.timestamp)}})}function UE(e,t){let o=e.root,i=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const i=e.path[t];if(void 0===o[i]){const s=e.path[t+1];o[i]=ME(s)}o=o[i]}void 0===e[t]?delete o[i]:o[i]=e[t]}class VE{observers=[];defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.push({owner:e,callbacks:t})}capture(e,t){if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.find((t=>t.owner===e))||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),[...this.observers].forEach((t=>t.callbacks.handleEvent(e)))}}class zE{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new VE,this.anchor={cell:{col:0,row:0},zone:fi({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,o){this.stream.capture(e,o),this.anchor=t}registerAsDefault(e,t,o){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,o),this.defaultAnchor=t,this.capture(e,t,o)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e){return this.modifyAnchor(e,"overrideSelection","ZonesSelected")}modifyAnchor(e,t,o){const i=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(i,e.zone)},this.processEvent({type:o,anchor:e,mode:t})}selectCell(e,t){const o=fi({col:e,row:t});return this.selectZone({zone:o,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new ws(83);const{col:o,row:i}=this.getNextAvailablePosition(e,t);return this.selectCell(o,i)}setAnchorCorner(e,t){const o=this.getters.getActiveSheetId(),{col:i,row:s}=this.anchor.cell,r={left:Math.min(i,e),top:Math.min(s,t),right:Math.max(i,e),bottom:Math.max(s,t)},n={zone:this.getters.expandZone(o,r),cell:{col:i,row:s}};return this.processEvent({type:"AlterZone",mode:"updateAnchor",anchor:n})}addCellToSelection(e,t){const o=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}));const i=this.getters.expandZone(o,fi({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:i,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new ws(83);const o=this.getters.getActiveSheetId(),i=this.anchor,{col:s,row:r}=i.cell,{left:n,right:a,top:l,bottom:c}=i.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return ws.Success;let g=i.zone;const p=e=>{e=mi(e);const{left:t,right:i,top:s,bottom:r}=this.getters.expandZone(o,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(o)-1,i),top:Math.max(0,s),bottom:Math.min(this.getters.getNumberRows(o)-1,r)}},{col:m,row:f}=this.getReferencePosition();let b=0;for(;null!==g;){if(b++,d<0){const e=this.getNextAvailableCol(d,a-(b-1),f);g=m<=a-b?p({top:l,left:n,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,n+(b-1),f);g=n+b<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(b-1));g=f<=c-b?p({top:l,left:n,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(b-1));g=l+b<=f?p({top:e,left:n,bottom:c,right:a}):null}if(g=g?mi(g):g,g&&!si(g,i.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:s,row:r}}})}g=p(oi({top:r,bottom:r,left:s,right:s},mi({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,n,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const v={zone:g,cell:{col:s,row:r}};return this.processEvent({type:"ZonesSelected",anchor:v,mode:"updateAnchor"})}selectColumn(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberRows(o)-1;let s={left:e,right:e,top:0,bottom:i};const r=this.getters.findFirstVisibleColRowIndex(o,"ROW");let n,a;switch(t){case"overrideSelection":case"newAnchor":n=e,a=r;break;case"updateAnchor":({col:n,row:a}=this.anchor.cell),s=oi(s,{left:n,right:n,top:r,bottom:i})}return this.processEvent({type:"HeadersSelected",anchor:{zone:s,cell:{col:n,row:a}},mode:t})}selectRow(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberCols(o)-1;let s={top:e,bottom:e,left:0,right:i};const r=this.getters.findFirstVisibleColRowIndex(o,"COL");let n,a;switch(t){case"overrideSelection":case"newAnchor":n=r,a=e;break;case"updateAnchor":({col:n,row:a}=this.anchor.cell),s=oi(s,{left:r,right:i,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:s,cell:{col:n,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(si(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:fi(t.cell)},"updateAnchor","AlterZone");const o=this.expandZoneToTable(t.zone);return mt(o,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:o},"updateAnchor","AlterZone")}selectTableAroundSelection(){const e=this.expandZoneToTable(this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:e},"updateAnchor","AlterZone")}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({type:"HeadersSelected",mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell}})}processEvent(e){const t={...e,previousAnchor:Ve(this.anchor)},o=this.checkEventAnchorZone(t);return 0!==o?new ws(o):(this.anchor=t.anchor,this.stream.send(t),ws.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:o}=e;if(!ni(t.col,t.row,o))return 16;const{left:i,right:s,top:r,bottom:n}=o,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",i,s);return void 0===this.getters.findVisibleHeader(a,"ROW",r,n)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(s("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:o,row:i}=this.anchor.cell,s=this.deltaToTarget({col:o,row:i},e,t);return{col:this.getNextAvailableCol(s[0],o,i),row:this.getNextAvailableRow(s[1],o,i)}}getNextAvailableCol(e,t,o){const i=this.getters.getActiveSheetId(),s={col:t,row:o};return this.getNextAvailableHeader(e,"COL",t,s,(e=>this.getters.isInSameMerge(i,t,o,e,o)))}getNextAvailableRow(e,t,o){const i=this.getters.getActiveSheetId(),s={col:t,row:o};return this.getNextAvailableHeader(e,"ROW",o,s,(e=>this.getters.isInSameMerge(i,t,o,t,e)))}getNextAvailableHeader(e,t,o,i,s){const r=this.getters.getActiveSheetId();if(0===e)return o;const n=Math.sign(e);let a=o+e;for(;s(a);)a+=n;for(;this.getters.isHeaderHidden(r,t,a);)a+=n;return a<0||a>this.getters.getNumberHeaders(r,t)-1?this.getters.isHeaderHidden(r,t,o)?this.getNextAvailableHeader(-n,t,o,i,s):o:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:o,right:i,top:s,bottom:r}=t.zone,{col:n,row:a}=t.cell;return{col:this.getters.isColHidden(e,n)&&this.getters.findVisibleHeader(e,"COL",o,i)||n,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",s,r)||a}}deltaToTarget(e,t,o){switch(t){case"up":return"end"!==o?[0,-o]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==o?[0,o]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==o?[-o,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==o?[o,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:o}=this.getPosition();const i=this.anchor.zone;switch(e){case"down":case"up":o=o===i.top?i.bottom:i.top;break;case"left":case"right":t=t===i.right?i.left:i.right}return{col:t,row:o}}getEndOfCluster(e,t,o){const i=this.getters.getActiveSheet();let s=e;const r=this.getNextCellPosition(e,t,o);let n=this.isCellEmpty(s,i.id)||this.isCellEmpty(r,i.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(s,t,o);if(s.col===e.col&&s.row===e.row)break;const r=this.isCellEmpty(e,i.id);if("endOfCluster"===n&&r)break;if("nextCluster"===n&&!r){s=e;break}s=e}return"cols"===t?s.col:s.row}isCellEmpty({col:e,row:t},o=this.getters.getActiveSheetId()){const i=this.getters.getMainCellPosition({sheetId:o,col:e,row:t});return this.getters.getEvaluatedCell(i).type===ms.empty}getNextCellPosition(e,t,o){const i="cols"===t?"col":"row",s={...e},r="cols"===t?this.getNextAvailableCol(o,s.col,s.row):this.getNextAvailableRow(o,s.col,s.row);return s[i]=r,{col:s.col,row:s.row}}getPosition(){return{...this.anchor.cell}}expandZoneToTable(e){const t=e=>{for(const t of je(e.left,e.right+1)){if(!this.isCellEmpty({col:t,row:e.top-1}))return{...e,top:e.top-1};if(!this.isCellEmpty({col:t,row:e.bottom+1}))return{...e,bottom:e.bottom+1}}for(const t of je(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};let o=!1,i=e;do{o=!1;const e=t(i);si(i,e)||(o=!0,i=e)}while(o);return i}}class BE{changes=[];commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop(),[o,...i]=e;let s=o,r=i[i.length-1];for(let e=0;e<=i.length-2;e++){const t=i[e];if(void 0===s[t]){const o=i[e+1];s[t]=ME(o)}s=s[t]}s[r]!==t&&(this.changes.push({root:o,path:i,before:s[r],after:t}),void 0===t?delete s[r]:s[r]=t)}}const HE=17781237,$E=88853993;function WE(e,t,o){const i=[["xmlns:r",sb],["xmlns:a",eb],["xmlns:c",tb]],s=GE({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let r=LS``;e.data.title&&(r=LS`
2001
+ `;const RE=e=>e;class TE extends t.Component{static template="o-spreadsheet-Spreadsheet";static components={TopBar:xE,Grid:jf,BottomBar:gE,SidePanel:fE,SpreadsheetDashboard:mE};static _t=RE;sidePanel;composer;_focusGrid;keyDownMapping;isViewportTooSmall=!1;get model(){return this.props.model}getStyle(){return this.env.isDashboard()?"grid-template-rows: auto;":"grid-template-rows: 63px auto 37px"}setup(){this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})};const e=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:e?new nE(e):void 0,loadCurrencies:this.model.config.external.loadCurrencies,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.openSidePanel.bind(this),toggleSidePanel:this.toggleSidePanel.bind(this),_t:TE._t,clipboard:this.env.clipboard||new yE(navigator.clipboard),startCellEdition:e=>this.onGridComposerCellFocused(e)}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(isFinite(e)&&isFinite(t))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:r("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.isOpen&&e!==this.sidePanel.component&&this.sidePanel.panelProps?.onCloseSidePanel?.(),this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid(),this.sidePanel.panelProps?.onCloseSidePanel?.()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}onKeydown(e){let t="";(e.ctrlKey||e.metaKey)&&(t+="CTRL+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];if(o)return e.preventDefault(),e.stopPropagation(),void o()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}}TE.props={model:Object};class AE{listeners=[];sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}function OE(e){return Vn.get(e.type)(e)}function ME(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class NE{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const o of this.operations){if(o.id===e)return e;if(o.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const o=this.buildTransformation.with(e.data),{before:i,operation:s,after:r}=this.locateOperation(t);this.operations=[...i,s,e,...r.map((e=>e.transformed(o)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new NE(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:o}=this.locateOperation(e);this.operations=t.concat([o])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class _E{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new FE(this.id,ut((()=>e(this.data))))}}class FE{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new FE(this.id,this.lazyData.map(e))}}class DE{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new DE(function*(e,t){for(const o of e)if(yield o,o.operation.id===t)return}(this.operations,e))}stopBefore(e){return new DE(function*(e,t){for(const o of e){if(o.operation.id===t)return;yield o}}(this.operations,e))}startAfter(e){return new DE(function*(e,t){let o=!0;for(const i of e)o||(yield i),i.operation.id===t&&(o=!1)}(this.operations,e))}}class LE{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new DE(Xe(this._execution(e),this._execution(e)))}revertedExecution(e){return new DE(Xe(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const o=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,o){e.insert(t,o),this.updateNextWith(e,t,o),this.insertPrevious(e,t,o)}undo(e,t){const o=this.buildTransformation.without(t.data),i=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const s=e.fork(t.id);i&&this.branchingOperationIds.set(s,i),this.insertBranchAfter(e,s),this.transform(s,o)}redo(e){const t=this.nextBranch(e);if(!t)return;const o=this.nextBranch(t);this.removeBranchFromTree(t);const i=this.branchingOperationIds.get(t);i?this.branchingOperationIds.set(e,i):this.branchingOperationIds.delete(e),o&&this.rebaseUp(o)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const o of this.revertedExecution(e))if(o.operation.id===t)return o;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!t||!o)return;const i=this.buildTransformation.without(o.data),s=t.fork(o.id);this.branchingOperationIds.set(s,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,s),s.transform(i);const r=this.nextBranch(s);r&&this.rebaseUp(r)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const o=this.branches.findIndex((t=>t===e));this.branches.splice(o+1,0,t)}updateNextWith(e,t,o){const i=this.branchingOperationIds.get(e),s=this.nextBranch(e);if(i&&s)if(e.getFirstOperationAmong(o,i)===i){const r=this.addToNextBranch(e,s,i,t,o);this.updateNextWith(s,r,o)}else{const e=this.buildTransformation.with(t.data);this.transform(s,e)}}addToNextBranch(e,t,o,i,s){let r=i;return s===o?(r=this.getTransformedOperation(e,o,i),t.prepend(r)):t.contains(s)?(r=this.getTransformedOperation(e,o,i),t.insert(r,s)):t.append(i),r}getTransformedOperation(e,t,o){const i=e.getOperation(t),s=this.buildTransformation.without(i.data);return o.transformed(s)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const o=this.nextBranch(e);o&&this.transform(o,t)}insertPrevious(e,t,o){const{previousBranch:i,branchingOperation:s}=this.findPreviousBranchingOperation(e);if(!i||!s)return;const r=this.buildTransformation.with(s.data),n=e.fork(o);n.transform(r),i.cutAfter(o),i.appendBranch(n);const a=t.transformed(r);this.insertPrevious(i,a,o)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const o=this.branchingOperationIds.get(t);return o?{previousBranch:t,branchingOperation:t.getOperation(o)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let o=!!t;const i=e.getOperations();for(let s=i.length-1;s>=0;s--){const r=i[s];r.id===t&&(o=!1),o||(yield{operation:r,branch:e,isCancelled:!this.shouldExecute(e,r)})}const s=this.previousBranch(e);yield*s?this._revertedExecution(s):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class PE{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new NE(this.buildTransformation),this.tree=new LE(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,o=new _E(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,o),this.HEAD_OPERATION=o}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const o=new _E(e,t),i=this.tree.getLastBranch();this.tree.insertOperationLast(i,o),this.HEAD_BRANCH=i,this.HEAD_OPERATION=o}insert(e,t,o){const i=new _E(e,t);this.revertTo(o),this.tree.insertOperationAfter(this.HEAD_BRANCH,i,o),this.fastForward()}undo(e,t,o){const{branch:i,operation:s}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(i,s),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}redo(e,t,o){const{branch:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(i),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}drop(e){this.revertBefore(e),this.tree.drop(e)}getRevertedExecution(){const e=[],t=this.tree.revertedExecution(this.HEAD_BRANCH);for(const{operation:o}of t)e.push(o.data);return e}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:o,isCancelled:i}of e)i||this.revertOperation(o.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:o,isCancelled:i}of e)i||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=o}}function kE(e){return new PE({initialOperationId:e.initialRevisionId,applyOperation:t=>{const o=t.commands.slice(),{changes:i}=e.recordChanges((()=>{for(const t of o)e.dispatch(t)}));t.setChanges(i)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){UE(t.changes[e],"before")}}([e]),buildEmpty:e=>new TC(e,"empty",[]),buildTransformation:{with:e=>t=>new TC(t.id,t.clientId,IC(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new TC(t.id,t.clientId,IC(t.commands,e.commands.map(OE).flat()),t.rootCommand,void 0,t.timestamp)}})}function UE(e,t){let o=e.root,i=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const i=e.path[t];if(void 0===o[i]){const s=e.path[t+1];o[i]=ME(s)}o=o[i]}void 0===e[t]?delete o[i]:o[i]=e[t]}class VE{observers=[];defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.push({owner:e,callbacks:t})}capture(e,t){if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.find((t=>t.owner===e))||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),[...this.observers].forEach((t=>t.callbacks.handleEvent(e)))}}class zE{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new VE,this.anchor={cell:{col:0,row:0},zone:fi({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,o){this.stream.capture(e,o),this.anchor=t}registerAsDefault(e,t,o){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,o),this.defaultAnchor=t,this.capture(e,t,o)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e){return this.modifyAnchor(e,"overrideSelection","ZonesSelected")}modifyAnchor(e,t,o){const i=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(i,e.zone)},this.processEvent({type:o,anchor:e,mode:t})}selectCell(e,t){const o=fi({col:e,row:t});return this.selectZone({zone:o,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new ws(83);const{col:o,row:i}=this.getNextAvailablePosition(e,t);return this.selectCell(o,i)}setAnchorCorner(e,t){const o=this.getters.getActiveSheetId(),{col:i,row:s}=this.anchor.cell,r={left:Math.min(i,e),top:Math.min(s,t),right:Math.max(i,e),bottom:Math.max(s,t)},n={zone:this.getters.expandZone(o,r),cell:{col:i,row:s}};return this.processEvent({type:"AlterZone",mode:"updateAnchor",anchor:n})}addCellToSelection(e,t){const o=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}));const i=this.getters.expandZone(o,fi({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:i,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new ws(83);const o=this.getters.getActiveSheetId(),i=this.anchor,{col:s,row:r}=i.cell,{left:n,right:a,top:l,bottom:c}=i.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return ws.Success;let g=i.zone;const p=e=>{e=mi(e);const{left:t,right:i,top:s,bottom:r}=this.getters.expandZone(o,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(o)-1,i),top:Math.max(0,s),bottom:Math.min(this.getters.getNumberRows(o)-1,r)}},{col:m,row:f}=this.getReferencePosition();let b=0;for(;null!==g;){if(b++,d<0){const e=this.getNextAvailableCol(d,a-(b-1),f);g=m<=a-b?p({top:l,left:n,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,n+(b-1),f);g=n+b<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(b-1));g=f<=c-b?p({top:l,left:n,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(b-1));g=l+b<=f?p({top:e,left:n,bottom:c,right:a}):null}if(g=g?mi(g):g,g&&!si(g,i.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:s,row:r}}})}g=p(oi({top:r,bottom:r,left:s,right:s},mi({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,n,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const v={zone:g,cell:{col:s,row:r}};return this.processEvent({type:"ZonesSelected",anchor:v,mode:"updateAnchor"})}selectColumn(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberRows(o)-1;let s={left:e,right:e,top:0,bottom:i};const r=this.getters.findFirstVisibleColRowIndex(o,"ROW");let n,a;switch(t){case"overrideSelection":case"newAnchor":n=e,a=r;break;case"updateAnchor":({col:n,row:a}=this.anchor.cell),s=oi(s,{left:n,right:n,top:r,bottom:i})}return this.processEvent({type:"HeadersSelected",anchor:{zone:s,cell:{col:n,row:a}},mode:t})}selectRow(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberCols(o)-1;let s={top:e,bottom:e,left:0,right:i};const r=this.getters.findFirstVisibleColRowIndex(o,"COL");let n,a;switch(t){case"overrideSelection":case"newAnchor":n=r,a=e;break;case"updateAnchor":({col:n,row:a}=this.anchor.cell),s=oi(s,{left:r,right:i,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:s,cell:{col:n,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(si(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:fi(t.cell)},"updateAnchor","AlterZone");const o=this.expandZoneToTable(t.zone);return mt(o,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:o},"updateAnchor","AlterZone")}selectTableAroundSelection(){const e=this.expandZoneToTable(this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:e},"updateAnchor","AlterZone")}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({type:"HeadersSelected",mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell}})}processEvent(e){const t={...e,previousAnchor:Ve(this.anchor)},o=this.checkEventAnchorZone(t);return 0!==o?new ws(o):(this.anchor=t.anchor,this.stream.send(t),ws.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:o}=e;if(!ni(t.col,t.row,o))return 16;const{left:i,right:s,top:r,bottom:n}=o,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",i,s);return void 0===this.getters.findVisibleHeader(a,"ROW",r,n)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(s("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:o,row:i}=this.anchor.cell,s=this.deltaToTarget({col:o,row:i},e,t);return{col:this.getNextAvailableCol(s[0],o,i),row:this.getNextAvailableRow(s[1],o,i)}}getNextAvailableCol(e,t,o){const i=this.getters.getActiveSheetId(),s={col:t,row:o};return this.getNextAvailableHeader(e,"COL",t,s,(e=>this.getters.isInSameMerge(i,t,o,e,o)))}getNextAvailableRow(e,t,o){const i=this.getters.getActiveSheetId(),s={col:t,row:o};return this.getNextAvailableHeader(e,"ROW",o,s,(e=>this.getters.isInSameMerge(i,t,o,t,e)))}getNextAvailableHeader(e,t,o,i,s){const r=this.getters.getActiveSheetId();if(0===e)return o;const n=Math.sign(e);let a=o+e;for(;s(a);)a+=n;for(;this.getters.isHeaderHidden(r,t,a);)a+=n;return a<0||a>this.getters.getNumberHeaders(r,t)-1?this.getters.isHeaderHidden(r,t,o)?this.getNextAvailableHeader(-n,t,o,i,s):o:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:o,right:i,top:s,bottom:r}=t.zone,{col:n,row:a}=t.cell;return{col:this.getters.isColHidden(e,n)&&this.getters.findVisibleHeader(e,"COL",o,i)||n,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",s,r)||a}}deltaToTarget(e,t,o){switch(t){case"up":return"end"!==o?[0,-o]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==o?[0,o]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==o?[-o,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==o?[o,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:o}=this.getPosition();const i=this.anchor.zone;switch(e){case"down":case"up":o=o===i.top?i.bottom:i.top;break;case"left":case"right":t=t===i.right?i.left:i.right}return{col:t,row:o}}getEndOfCluster(e,t,o){const i=this.getters.getActiveSheet();let s=e;const r=this.getNextCellPosition(e,t,o);let n=this.isCellEmpty(s,i.id)||this.isCellEmpty(r,i.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(s,t,o);if(s.col===e.col&&s.row===e.row)break;const r=this.isCellEmpty(e,i.id);if("endOfCluster"===n&&r)break;if("nextCluster"===n&&!r){s=e;break}s=e}return"cols"===t?s.col:s.row}isCellEmpty({col:e,row:t},o=this.getters.getActiveSheetId()){const i=this.getters.getMainCellPosition({sheetId:o,col:e,row:t});return this.getters.getEvaluatedCell(i).type===ms.empty}getNextCellPosition(e,t,o){const i="cols"===t?"col":"row",s={...e},r="cols"===t?this.getNextAvailableCol(o,s.col,s.row):this.getNextAvailableRow(o,s.col,s.row);return s[i]=r,{col:s.col,row:s.row}}getPosition(){return{...this.anchor.cell}}expandZoneToTable(e){const t=e=>{for(const t of je(e.left,e.right+1)){if(!this.isCellEmpty({col:t,row:e.top-1}))return{...e,top:e.top-1};if(!this.isCellEmpty({col:t,row:e.bottom+1}))return{...e,bottom:e.bottom+1}}for(const t of je(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};let o=!1,i=e;do{o=!1;const e=t(i);si(i,e)||(o=!0,i=e)}while(o);return i}}class BE{changes=[];commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop(),[o,...i]=e;let s=o,r=i[i.length-1];for(let e=0;e<=i.length-2;e++){const t=i[e];if(void 0===s[t]){const o=i[e+1];s[t]=ME(o)}s=s[t]}s[r]!==t&&(this.changes.push({root:o,path:i,before:s[r],after:t}),void 0===t?delete s[r]:s[r]=t)}}const HE=17781237,$E=88853993;function WE(e,t,o){const i=[["xmlns:r",sb],["xmlns:a",eb],["xmlns:c",tb]],s=GE({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let r=LS``;e.data.title&&(r=LS`
1979
2002
  <c:title>
1980
2003
  ${ZE(e.data.title,e.data.fontColor)}
1981
2004
  <c:overlay val="0" />
@@ -2463,4 +2486,4 @@
2463
2486
  <tableParts count="${e.filterTables.length}">
2464
2487
  ${DS(a)}
2465
2488
  </tableParts>
2466
- `}var Ow;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(Ow||(Ow={}));function Mw(e,t={}){const o=Ve(t);return o.type=e,o}const Nw={},_w={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:_,HEADER_WIDTH:F,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:D,DEFAULT_CELL_HEIGHT:L,SCROLLBAR_WIDTH:P},Fw={autofillModifiersRegistry:Ls,autofillRulesRegistry:Ps,cellMenuRegistry:tp,colMenuRegistry:fm,linkMenuRegistry:Er,functionRegistry:Tg,featurePluginRegistry:oE,statefulUIPluginRegistry:iE,coreViewsPluginRegistry:sE,corePluginRegistry:tE,rowMenuRegistry:Sm,sidePanelRegistry:Km,figureRegistry:Ln,chartSidePanelComponentRegistry:Vm,chartComponentRegistry:Mn,chartRegistry:On,topbarMenuRegistry:Cm,topbarComponentRegistry:Qm,clickableCellRegistry:rE,otRegistry:Em,inverseCommandRegistry:Vn,urlRegistry:Di,cellPopoverRegistry:yr,numberFormatMenuRegistry:bm,repeatLocalCommandTransformRegistry:zC,repeatCommandTransformRegistry:VC},Dw={arg:za,toBoolean:Ki,toJsDate:Qi,toNumber:Wi,toString:ji,toXC:Ht,toZone:Yo,toCartesian:Bt,numberToLetters:Pt,UuidGenerator:Zo,formatValue:uo,computeTextWidth:We,createEmptyWorkbookData:nC,createEmptySheet:rC,createEmptyExcelSheet:aC,getDefaultChartJsRuntime:on,chartFontColor:Vr,ChartColors:Ur,EvaluationError:c,CellErrorLevel:l,getFillingMode:an,rgbaToHex:_t,colorToRGBA:Ft,positionToZone:fi,isDefined:lt,lazy:ut,genericRepeat:BC},Lw={isMarkdownLink:et,parseMarkdownLink:it,markdownLink:ot,openLink:Vi,urlRepresentation:Ui},Pw={ChartPanel:zm,ChartFigure:_n,ChartJsComponent:Ci,Grid:jf,GridOverlay:_f,ScorecardChart:Oi,LineConfigPanel:Pm,LineBarPieDesignPanel:Fm,BarConfigPanel:Tm,LineBarPieConfigPanel:Rm,GaugeChartConfigPanel:Dm,GaugeChartDesignPanel:Lm,ScorecardChartConfigPanel:km,ScorecardChartDesignPanel:Um,FigureComponent:Jm};e.AbstractChart=Rr,e.CorePlugin=cC,e.DispatchResult=ws,e.EvaluationError=c,e.Model=class extends CC{corePlugins=[];featurePlugins=[];statefulUIPlugins=[];coreViewsPlugins=[];range;session;isReplayingCommand=!1;renderers=[];status=0;config;corePluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];coreHandlers=[];constructor(e={},o={},i=[],s=new Zo,r=!0){super(),i=iC(e,i);const n=tC(e,r);this.state=new BE,this.uuidGenerator=s,this.config=this.setupConfig(o),this.session=this.setupSession(n.revisionId),this.coreGetters={},this.range=new mC(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.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.getSelectionRangeString=this.range.getSelectionRangeString.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode},this.uuidGenerator.setIsFastStrategy(!0),this.selection=new zE(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of tE.getAll())this.setupCorePlugin(e,n);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(i);for(let e of iE.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t)}for(let e of sE.getAll()){const t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.coreHandlers.push(t)}for(let e of oE.getAll()){const t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t)}this.uuidGenerator.setIsFastStrategy(!1),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.joinSession(),o.snapshotRequested&&(this.session.snapshot(this.exportData()),this.garbageCollectExternalResources()),t.markRaw(this)}joinSession(){this.session.join(this.config.client)}leaveSession(){this.session.leave()}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(let o of e.getters){if(!(o in t))throw new Error(`Invalid getter name: ${o} for plugin ${t.constructor}`);if(o in this.getters)throw new Error(`Getter "${o}" is already defined.`);this.getters[o]=t[o].bind(t)}const o=e.layers.map((e=>[t,e]));return this.renderers.push(...o),this.renderers.sort(((e,t)=>e[1]-t[1])),t}setupCorePlugin(e,t){const o=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in o))throw new Error(`Invalid getter name: ${t} for plugin ${o.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=o[t].bind(o)}o.import(t),this.corePlugins.push(o),this.coreHandlers.push(o),this.handlers.push(o)}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new OC(kE({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1)}}),this.config.transportService,e)}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){const t=e.client||{id:this.uuidGenerator.uuidv4(),name:r("Anonymous").toString()},o=e.transportService||new AE;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:e.external||{},transportService:o,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),lazyEvaluation:!("lazyEvaluation"in e)||e.lazyEvaluation}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,uuidGenerator:this.uuidGenerator,custom:this.config.custom,external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,lazyEvaluation:this.config.lazyEvaluation,session:this.session}}checkDispatchAllowed(e){return Es(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e)}checkDispatchAllowedCoreCommand(e){const t=this.corePlugins.map((t=>t.allowDispatch(e)));return t.push(this.range.allowDispatch(e)),new ws(t.flat())}checkDispatchAllowedLocalCommand(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return new ws(t.flat())}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}canDispatch=(e,t)=>this.checkDispatchAllowed(Mw(e,t));dispatch=(e,t)=>{const o=Mw(e,t);let i=this.status;if(this.getters.isReadonly()&&(s=o,!Ss.has(s.type)))return new ws(67);var s;if(!this.session.canApplyOptimisticUpdate())return new ws(64);switch(i){case 0:const t=this.checkDispatchAllowed(o);if(!t.isSuccessful)return t;this.status=1;const{changes:i,commands:s}=this.state.recordChanges((()=>{Es(o)&&this.state.addCommand(o),this.dispatchToHandlers(this.handlers,o),this.finalize()}));this.session.save(o,s,i),this.status=0,this.trigger("update");break;case 1:if(Es(o)){const e=this.checkDispatchAllowed(o);if(!e.isSuccessful)return e;this.state.addCommand(o)}this.dispatchToHandlers(this.handlers,o);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(Es(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return ws.Success};dispatchFromCorePlugin=(e,t)=>{const o=Mw(e,t),i=this.status;this.status=2;const s=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(s,o),this.status=i,ws.Success};dispatchToHandlers(e,t){for(const o of e)o.beforeHandle(t);for(const o of e)o.handle(t)}drawGrid(e){for(let[t,o]of this.renderers)e.ctx.save(),t.drawGrid(e,o),e.ctx.restore()}exportData(){let e=nC();for(let t of this.handlers)t instanceof cC&&t.export(e);return e.revisionId=this.session.getRevisionId()||J,e=Ve(e),e}updateMode(e){"normal"!==e&&this.dispatch("STOP_EDITION",{cancel:!0}),this.config.mode=e,this.trigger("update")}exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...nC(),sheets:[aC(eC,"Sheet1")]};for(let t of this.handlers)t instanceof lC&&t.exportForExcel(e);return e=Ve(e),Tw(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=_i,e.Revision=TC,e.SPREADSHEET_DIMENSIONS=_w,e.Spreadsheet=TE,e.UIPlugin=fC,e.__info__=Nw,e.addFunction=function(e,t){Tg.add(e,t)},e.astToFormula=Nv,e.compile=Wv,e.components=Pw,e.convertAstNodes=Mv,e.coreTypes=Cs,e.findCellInNewZone=pi,e.functionCache=$v,e.helpers=Dw,e.invalidateEvaluationCommands=bs,e.links=Lw,e.load=tC,e.parse=Av,e.readonlyAllowedCommands=Ss,e.registries=Fw,e.setDefaultSheetViewSize=function(e){ue=e},e.setTranslationMethod=function(e){o=e},e.tokenize=av,Object.defineProperty(e,"__esModule",{value:!0}),Nw.version="16.3.0-alpha.8",Nw.date="2023-05-12T10:59:42.550Z",Nw.hash="afee7d5"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
2489
+ `}var Ow;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(Ow||(Ow={}));function Mw(e,t={}){const o=Ve(t);return o.type=e,o}const Nw={},_w={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:_,HEADER_WIDTH:F,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:D,DEFAULT_CELL_HEIGHT:L,SCROLLBAR_WIDTH:P},Fw={autofillModifiersRegistry:Ls,autofillRulesRegistry:Ps,cellMenuRegistry:tp,colMenuRegistry:fm,linkMenuRegistry:Er,functionRegistry:Tg,featurePluginRegistry:oE,statefulUIPluginRegistry:iE,coreViewsPluginRegistry:sE,corePluginRegistry:tE,rowMenuRegistry:Sm,sidePanelRegistry:Km,figureRegistry:Ln,chartSidePanelComponentRegistry:Vm,chartComponentRegistry:Mn,chartRegistry:On,topbarMenuRegistry:Cm,topbarComponentRegistry:Qm,clickableCellRegistry:rE,otRegistry:Em,inverseCommandRegistry:Vn,urlRegistry:Di,cellPopoverRegistry:yr,numberFormatMenuRegistry:bm,repeatLocalCommandTransformRegistry:zC,repeatCommandTransformRegistry:VC},Dw={arg:za,toBoolean:Ki,toJsDate:Qi,toNumber:Wi,toString:ji,toXC:Ht,toZone:Yo,toCartesian:Bt,numberToLetters:Pt,UuidGenerator:Zo,formatValue:uo,computeTextWidth:We,createEmptyWorkbookData:nC,createEmptySheet:rC,createEmptyExcelSheet:aC,getDefaultChartJsRuntime:on,chartFontColor:Vr,ChartColors:Ur,EvaluationError:c,CellErrorLevel:l,getFillingMode:an,rgbaToHex:_t,colorToRGBA:Ft,positionToZone:fi,isDefined:lt,lazy:ut,genericRepeat:BC},Lw={isMarkdownLink:et,parseMarkdownLink:it,markdownLink:ot,openLink:Vi,urlRepresentation:Ui},Pw={ChartPanel:zm,ChartFigure:_n,ChartJsComponent:Ci,Grid:jf,GridOverlay:_f,ScorecardChart:Oi,LineConfigPanel:Pm,LineBarPieDesignPanel:Fm,BarConfigPanel:Tm,LineBarPieConfigPanel:Rm,GaugeChartConfigPanel:Dm,GaugeChartDesignPanel:Lm,ScorecardChartConfigPanel:km,ScorecardChartDesignPanel:Um,FigureComponent:Jm};e.AbstractChart=Rr,e.CorePlugin=cC,e.DispatchResult=ws,e.EvaluationError=c,e.Model=class extends CC{corePlugins=[];featurePlugins=[];statefulUIPlugins=[];coreViewsPlugins=[];range;session;isReplayingCommand=!1;renderers=[];status=0;config;corePluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},o={},i=[],s=new Zo,r=!0){super(),i=iC(e,i);const n=tC(e,r);this.state=new BE,this.uuidGenerator=s,this.config=this.setupConfig(o),this.session=this.setupSession(n.revisionId),this.coreGetters={},this.range=new mC(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.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.getSelectionRangeString=this.range.getSelectionRangeString.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode},this.uuidGenerator.setIsFastStrategy(!0),this.selection=new zE(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of tE.getAll())this.setupCorePlugin(e,n);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(i);for(let e of iE.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of sE.getAll()){const t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of oE.getAll()){const t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}this.uuidGenerator.setIsFastStrategy(!1),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.joinSession(),o.snapshotRequested&&(this.session.snapshot(this.exportData()),this.garbageCollectExternalResources()),t.markRaw(this)}joinSession(){this.session.join(this.config.client)}leaveSession(){this.session.leave()}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(let o of e.getters){if(!(o in t))throw new Error(`Invalid getter name: ${o} for plugin ${t.constructor}`);if(o in this.getters)throw new Error(`Getter "${o}" is already defined.`);this.getters[o]=t[o].bind(t)}const o=e.layers.map((e=>[t,e]));return this.renderers.push(...o),this.renderers.sort(((e,t)=>e[1]-t[1])),t}setupCorePlugin(e,t){const o=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in o))throw new Error(`Invalid getter name: ${t} for plugin ${o.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=o[t].bind(o)}o.import(t),this.corePlugins.push(o),this.coreHandlers.push(o),this.handlers.push(o)}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new OC(kE({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1)}}),this.config.transportService,e)}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){const t=e.client||{id:this.uuidGenerator.uuidv4(),name:r("Anonymous").toString()},o=e.transportService||new AE;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:e.external||{},transportService:o,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),lazyEvaluation:!("lazyEvaluation"in e)||e.lazyEvaluation}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,uuidGenerator:this.uuidGenerator,custom:this.config.custom,external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,lazyEvaluation:this.config.lazyEvaluation,session:this.session}}checkDispatchAllowed(e){return Es(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e)}checkDispatchAllowedCoreCommand(e){const t=this.corePlugins.map((t=>t.allowDispatch(e)));return t.push(this.range.allowDispatch(e)),new ws(t.flat())}checkDispatchAllowedLocalCommand(e){const t=this.uiHandlers.map((t=>t.allowDispatch(e)));return new ws(t.flat())}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}canDispatch=(e,t)=>this.checkDispatchAllowed(Mw(e,t));dispatch=(e,t)=>{const o=Mw(e,t);let i=this.status;if(this.getters.isReadonly()&&(s=o,!Ss.has(s.type)))return new ws(67);var s;if(!this.session.canApplyOptimisticUpdate())return new ws(64);switch(i){case 0:const t=this.checkDispatchAllowed(o);if(!t.isSuccessful)return t;this.status=1;const{changes:i,commands:s}=this.state.recordChanges((()=>{Es(o)&&this.state.addCommand(o),this.dispatchToHandlers(this.handlers,o),this.finalize()}));this.session.save(o,s,i),this.status=0,this.trigger("update");break;case 1:if(Es(o)){const e=this.checkDispatchAllowed(o);if(!e.isSuccessful)return e;this.state.addCommand(o)}this.dispatchToHandlers(this.handlers,o);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(Es(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return ws.Success};dispatchFromCorePlugin=(e,t)=>{const o=Mw(e,t),i=this.status;this.status=2;const s=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(s,o),this.status=i,ws.Success};dispatchToHandlers(e,t){for(const o of e)o.beforeHandle(t);for(const o of e)o.handle(t)}drawGrid(e){for(let[t,o]of this.renderers)e.ctx.save(),t.drawGrid(e,o),e.ctx.restore()}exportData(){let e=nC();for(let t of this.handlers)t instanceof cC&&t.export(e);return e.revisionId=this.session.getRevisionId()||J,e=Ve(e),e}updateMode(e){"normal"!==e&&this.dispatch("STOP_EDITION",{cancel:!0}),this.config.mode=e,this.trigger("update")}exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...nC(),sheets:[aC(eC,"Sheet1")]};for(let t of this.handlers)t instanceof lC&&t.exportForExcel(e);return e=Ve(e),Tw(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=_i,e.Revision=TC,e.SPREADSHEET_DIMENSIONS=_w,e.Spreadsheet=TE,e.UIPlugin=fC,e.__info__=Nw,e.addFunction=function(e,t){Tg.add(e,t)},e.astToFormula=Nv,e.compile=Wv,e.components=Pw,e.convertAstNodes=Mv,e.coreTypes=Cs,e.findCellInNewZone=pi,e.functionCache=$v,e.helpers=Dw,e.invalidateEvaluationCommands=bs,e.links=Lw,e.load=tC,e.parse=Av,e.readonlyAllowedCommands=Ss,e.registries=Fw,e.setDefaultSheetViewSize=function(e){ue=e},e.setTranslationMethod=function(e){o=e},e.tokenize=av,Object.defineProperty(e,"__esModule",{value:!0}),Nw.version="16.3.1",Nw.date="2023-05-25T13:00:27.320Z",Nw.hash="b3cfd2c"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);