@univerjs/engine-formula 0.5.4 → 0.5.5-nightly.202501201336

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Bu=Object.defineProperty;var Iu=(i,o,e)=>o in i?Bu(i,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[o]=e;var A=(i,o,e)=>Iu(i,typeof o!="symbol"?o+"":o,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("@univerjs/core"),er=require("rxjs"),Fu=require("@univerjs/rpc");var Mt=(i=>(i.FALSE="FALSE",i.TRUE="TRUE",i))(Mt||{}),pt=(i=>(i[i.SUCCESS=0]="SUCCESS",i[i.ERROR=1]="ERROR",i))(pt||{}),Je=(i=>(i[i.FRONT=0]="FRONT",i[i.BACK=1]="BACK",i))(Je||{});function mi(i,o,e,t,r){for(let n=0,s=i.length;n<s;n++){const a=i[n];if(o!==a.unitId||e!==a.sheetId)continue;const{startRow:u,startColumn:c,endRow:l,endColumn:f}=a.range;if(t>=u&&t<=l&&r>=c&&r<=f)return!0}return!1}var h=(i=>(i.DIV_BY_ZERO="#DIV/0!",i.NAME="#NAME?",i.VALUE="#VALUE!",i.NUM="#NUM!",i.NA="#N/A",i.CYCLE="#CYCLE!",i.REF="#REF!",i.SPILL="#SPILL!",i.CALC="#CALC!",i.ERROR="#ERROR!",i.CONNECT="#GETTING_DATA",i.NULL="#NULL!",i))(h||{});const Kt=new Set(Object.values(h)),Ra=[...new Set(Object.values(h).map(i=>i.length))];var hi=(i=>(i[i.Financial=0]="Financial",i[i.Date=1]="Date",i[i.Math=2]="Math",i[i.Statistical=3]="Statistical",i[i.Lookup=4]="Lookup",i[i.Database=5]="Database",i[i.Text=6]="Text",i[i.Logical=7]="Logical",i[i.Information=8]="Information",i[i.Engineering=9]="Engineering",i[i.Cube=10]="Cube",i[i.Compatibility=11]="Compatibility",i[i.Web=12]="Web",i[i.Array=13]="Array",i[i.Univer=14]="Univer",i[i.User=15]="User",i[i.DefinedName=16]="DefinedName",i))(hi||{}),X=(i=>(i.PLUS="+",i.MINUS="-",i.MULTIPLY="*",i.DIVIDED="/",i.CONCATENATE="&",i.POWER="^",i.EQUALS="=",i.NOT_EQUAL="<>",i.GREATER_THAN=">",i.GREATER_THAN_OR_EQUAL=">=",i.LESS_THAN="<",i.LESS_THAN_OR_EQUAL="<=",i))(X||{}),Y=(i=>(i.EQUALS="=",i.NOT_EQUAL="<>",i.GREATER_THAN=">",i.GREATER_THAN_OR_EQUAL=">=",i.LESS_THAN="<",i.LESS_THAN_OR_EQUAL="<=",i))(Y||{});const Fr=new Map([["<>",4],["<",4],[">=",4],["=",4],[">",4],["<=",4],["&",3],["+",2],["-",2],["/",1],["*",1],["^",0]]),bt=new Set(Fr.keys()),ku=new Set(["=","<>",">",">=","<","<="]);var K=(i=>(i.OPEN_BRACKET="(",i.CLOSE_BRACKET=")",i.COMMA=",",i.SINGLE_QUOTATION="'",i.DOUBLE_QUOTATION='"',i.OPEN_BRACES="{",i.CLOSE_BRACES="}",i.COLON=":",i.OPEN_SQUARE_BRACKET="[",i.CLOSE_SQUARE_BRACKET="]",i))(K||{}),He=(i=>(i.PERCENTAGE="%",i.POUND="#",i))(He||{});const Wn=new Set(["%","#"]);var Ne=(i=>(i.AT="@",i.MINUS="-",i.PLUS="+",i))(Ne||{});const $u=" ",gi=[...Object.values(Y),...Object.values(X),...Object.values(K),...Object.values(He),...Object.values(Ne)];function hr(i){return gi.includes(i)}function di(i){for(const o of gi)if(i.indexOf(o)>-1)return!0;return!1}function Yu(i){return i[0]==="'"&&i[i.length-1]==="'"?i.substring(1,i.length-1):i}function Hu(i){return hr(i)&&i!==K.CLOSE_BRACES&&i!==K.CLOSE_BRACKET&&i!==K.SINGLE_QUOTATION&&i!==K.DOUBLE_QUOTATION||i===" "}const Gu=new Set([X.PLUS,X.MINUS,X.MULTIPLY,X.DIVIDED,X.CONCATENATE,X.POWER,X.EQUALS,X.NOT_EQUAL,X.GREATER_THAN,X.GREATER_THAN_OR_EQUAL,X.LESS_THAN,X.LESS_THAN_OR_EQUAL,K.OPEN_BRACKET,K.COMMA,K.COLON,K.OPEN_BRACES,K.OPEN_SQUARE_BRACKET]);function Wu(i){return Gu.has(i)}const Qu=new Set([X.PLUS,X.MINUS,X.MULTIPLY,X.DIVIDED,X.CONCATENATE,X.POWER,X.EQUALS,X.NOT_EQUAL,X.GREATER_THAN,X.GREATER_THAN_OR_EQUAL,X.LESS_THAN,X.LESS_THAN_OR_EQUAL,K.OPEN_BRACKET,K.COMMA,K.COLON,K.OPEN_BRACES,K.OPEN_SQUARE_BRACKET,He.PERCENTAGE,He.POUND]);function qu(i){return Qu.has(i)}function Ci(i){const o={};return Object.keys(i).forEach(e=>{const t=i[e];if(t==null)return!0;o[e]==null&&(o[e]={}),Object.keys(t).forEach(r=>{const n=t[r];o[e][r]=new S.ObjectMatrix(n)})}),o}function Ku(i){const o={};for(const e in i){const t=i[e];if(t!=null){o[e]==null&&(o[e]={});for(const r in t){const n=t[r],s={};n.forValue((a,u,c)=>{s[a]===void 0&&(s[a]={}),s[a][u]=c}),o[e][r]=s}}}return o}const _i='\\[([^\\[\\]\\/?:"<>|*\\\\]+)\\]',pa=new RegExp(_i),Xu="((?![\\[\\]\\/?*\\\\]).)*!",St="$",xs="\\s*?:\\s*?",qr="[A-Za-z]+",Kr="[1-9][0-9]*",cr=`'?(${_i})?(${Xu})?'?`,is=`\\${St}?${qr}\\${St}?${Kr}`,Zu=`^(${Ne.AT})?${cr}${is}${xs}${is}$`,Na=new RegExp(Zu),zu=`^${cr}\\s*?${is}(${He.POUND})?$`,Va=new RegExp(zu),Ju=`^${cr}\\${St}?${Kr}${xs}\\${St}?${Kr}$`,Oa=new RegExp(Ju),ec=`^${cr}\\${St}?${qr}${xs}\\${St}?${qr}$`,Ma=new RegExp(ec),tc=`^${cr}\\s*?\\${St}?${Kr}$`,Sa=new RegExp(tc),rc=`^${cr}\\s*?\\${St}?${qr}$`,Da=new RegExp(rc),nc="{.*?}",wa=new RegExp(nc,"g");function yr(i){return Va.lastIndex=0,Va.test(i)}function sc(i){return Na.lastIndex=0,Na.test(i)}function Ai(i){return Oa.lastIndex=0,Oa.test(i)}function Ei(i){return Ma.lastIndex=0,Ma.test(i)}function bi(i){return Sa.lastIndex=0,Sa.test(i)}function yi(i){return Da.lastIndex=0,Da.test(i)}function ac(i){return wa.lastIndex=0,wa.test(i)}function Ri(i){return yr(i)||sc(i)||Ai(i)||Ei(i)}const pi={id:"formula.mutation.register-function",type:S.CommandType.MUTATION,handler:()=>!0},Xr={id:"formula.mutation.set-array-formula-data",type:S.CommandType.MUTATION,handler:(i,o)=>!0},ic=/[^0-9]/g,oc=/[^A-Za-z]/g;function gr(i){let o=i[0]==="$";const e=i.substring(1);let t=e.indexOf("$")>-1;return S.Tools.isStringNumber(e)&&o&&!t&&(o=!1,t=!0),o&&t?S.AbsoluteRefType.ALL:o?S.AbsoluteRefType.COLUMN:t?S.AbsoluteRefType.ROW:S.AbsoluteRefType.NONE}function uc(i){const o=i.split("!");o.length>1&&(i=o[o.length-1]);const e=i.split(":");return e.length>1?{startAbsoluteRefType:gr(e[0]),endAbsoluteRefType:gr(e[1])}:{startAbsoluteRefType:gr(e[0])}}function Pa(i=S.AbsoluteRefType.NONE){let o="",e="";return i===S.AbsoluteRefType.ROW?o="$":i===S.AbsoluteRefType.COLUMN?e="$":i===S.AbsoluteRefType.ALL&&(o="$",e="$"),{rowAbsoluteString:o,columnAbsoluteString:e}}function Yt(i){const{startColumn:o,startRow:e,endColumn:t,endRow:r,startAbsoluteRefType:n,endAbsoluteRefType:s,rangeType:a=S.RANGE_TYPE.NORMAL}=i,u=Pa(n),c=Pa(s);if(a===S.RANGE_TYPE.ROW||a===S.RANGE_TYPE.ALL){const m=`${u.rowAbsoluteString}${e+1}`,d=`${c.rowAbsoluteString}${r+1}`;return`${m}:${d}`}if(a===S.RANGE_TYPE.COLUMN){const m=`${u.columnAbsoluteString}${S.Tools.chatAtABC(o)}`,d=`${c.columnAbsoluteString}${S.Tools.chatAtABC(t)}`;return`${m}:${d}`}const l=`${u.columnAbsoluteString}${S.Tools.chatAtABC(o)}${u.rowAbsoluteString}${e+1}`,f=`${c.columnAbsoluteString}${S.Tools.chatAtABC(t)}${c.rowAbsoluteString}${r+1}`;return l===f?l:`${l}:${f}`}function Ni(i,o){return`${Si(i)}!${Yt(o)}`}function Vi(i,o,e){return os(i)||os(o)?`'[${us(i)}]${us(o)}'!${Yt(e)}`:`[${i}]${o}!${Yt(e)}`}function Zr(i){const{unitId:o,sheetName:e,range:t}=i;return o!=null&&o.length>0&&e!=null&&e.length>0?Vi(o,e,t):e!=null&&e.length>0?Ni(e,t):Yt(t)}function kr(i){const o=Number.parseInt(i.replace(ic,""))-1,e=S.Tools.ABCatNum(i.replace(oc,"")),t=gr(i);return{row:o,column:e,absoluteRefType:t}}function _n(i){const o=pa.exec(i);let e="";o!=null&&(e=o[0].trim(),e=La(e.slice(1,e.length-1)),i=i.replace(pa,""));const t=i.indexOf("!");let r="",n="";return t>-1?(r=i.substring(0,t),r[0]==="'"&&r[r.length-1]==="'"&&(r=r.substring(1,r.length-1)),r=La(r),n=i.substring(t+1)):n=i,{refBody:n,sheetName:r,unitId:e}}function Cr(i){const{refBody:o,sheetName:e,unitId:t}=_n(i),r=o.indexOf(":");if(r===-1){const _=kr(o),C=_.row,E=_.column,b=_.absoluteRefType;return{unitId:t,sheetName:e,range:{startRow:C,startColumn:E,endRow:C,endColumn:E,startAbsoluteRefType:b,endAbsoluteRefType:b}}}const n=o.substring(0,r),s=o.substring(r+1),a=kr(n),u=kr(s),c=a.row>u.row?u.row:a.row,l=a.column>u.column?u.column:a.column,f=a.row>u.row?a.row:u.row,m=a.column>u.column?a.column:u.column;let d=S.RANGE_TYPE.NORMAL;return Number.isNaN(c)&&Number.isNaN(f)?d=S.RANGE_TYPE.COLUMN:Number.isNaN(l)&&Number.isNaN(m)&&(d=S.RANGE_TYPE.ROW),{unitId:t,sheetName:e,range:{startRow:c,startColumn:l,endRow:f,endColumn:m,startAbsoluteRefType:a.absoluteRefType,endAbsoluteRefType:u.absoluteRefType,rangeType:d}}}const cc=["LOG10"];function dr(i){const o=Oi(i);if(!Ri(o)||cc.includes(o.toUpperCase().trim()))return!1;const{range:e}=Cr(o);return!(e.endColumn>=16384)}function Oi(i){const o=[];let e=!1;for(let t=0,r=i.length;t<r;t++){const n=i[t];if(n===$u&&!e)o.push(n);else{if(!e&&(n===Ne.AT||n===Ne.MINUS||n===Ne.PLUS))continue;o.push(n),e=!0}}return o.join("")}function lc(i,o){const e=(i==null?void 0:i.split(","))||[];return i===""||e.length===0?[]:Mi(i)?e.map(n=>{const s=Cr(n);return{unitId:s.unitId,sheetId:o(s.sheetName),range:s.range,sheetName:s.sheetName}}):[]}function Mi(i){return((i==null?void 0:i.split(","))||[]).every(e=>dr(e.trim()))}function os(i){return i.length===0?!1:!!(di(i)||fc(i)||mc(i)||hc(i)||/[\s!$%^&*()+\-=\[\]{};':"\\|,.<>\/?()]/.test(i))}function Si(i){return os(i)?`'${us(i)}'`:i}function us(i){return i.replace(/'/g,"''")}function La(i){return i.replace(/''/g,"'")}function fc(i){const o=i.match(/[1-9][0-9]{0,6}/);return/^[A-Z]+[1-9][0-9]{0,6}$/.test(i)&&o!==null}function mc(i){return/^(R(-?[0-9]+)?C(-?[0-9]+)?|C(-?[0-9]+)?|R(-?[0-9]+)?)$/.test(i)}function hc(i){return!new RegExp("^\\p{Letter}","u").test(i.charAt(0))}var gc=Object.defineProperty,dc=Object.getOwnPropertyDescriptor,Cc=(i,o,e,t)=>{for(var r=t>1?void 0:t?dc(o,e):o,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(o,e,r):s(r))||r);return t&&r&&gc(o,e,r),r},_c=(i,o)=>(e,t)=>o(e,t,i);exports.DefinedNamesService=class extends S.Disposable{constructor(e){super();A(this,"_definedNameMap",{});A(this,"_update$",new er.Subject);A(this,"update$",this._update$.asObservable());A(this,"_currentRange",{unitId:"",sheetId:"",range:{startRow:0,endRow:0,startColumn:0,endColumn:0}});A(this,"_currentRange$",new er.Subject);A(this,"currentRange$",this._currentRange$.asObservable());A(this,"_focusRange$",new er.Subject);A(this,"focusRange$",this._focusRange$.asObservable());this._univerInstanceService=e}dispose(){this._definedNameMap={}}getWorksheetByRef(e,t){var n;const{sheetName:r}=_n(t);return(n=this._univerInstanceService.getUnit(e))==null?void 0:n.getSheetBySheetName(r)}focusRange(e,t){const r=this.getValueById(e,t);r!=null&&this._focusRange$.next({...r,unitId:e})}setCurrentRange(e){this._currentRange=e,this._currentRange$.next(e)}getCurrentRange(){return this._currentRange}getCurrentRangeForString(){return Yt(this._currentRange.range)}registerDefinedNames(e,t){this._definedNameMap[e]=t,this._update()}registerDefinedName(e,t){this._definedNameMap[e]==null&&(this._definedNameMap[e]={}),this._definedNameMap[e][t.id]=t,this._update()}removeDefinedName(e,t){var r;(r=this._definedNameMap[e])==null||delete r[t],this._update()}removeUnitDefinedName(e){delete this._definedNameMap[e],this._update()}getDefinedNameMap(e){return this._definedNameMap[e]}getValueByName(e,t){var n;const r=this._definedNameMap[e];return r==null?null:(n=Array.from(Object.values(r)).filter(s=>s.name===t))==null?void 0:n[0]}getValueById(e,t){var r;return(r=this._definedNameMap[e])==null?void 0:r[t]}hasDefinedName(e){return this._definedNameMap[e]==null?!1:(Array.from(Object.values(this._definedNameMap[e])).length||0)!==0}_update(){this._update$.next(null)}};exports.DefinedNamesService=Cc([_c(0,S.IUniverInstanceService)],exports.DefinedNamesService);const Xt=S.createIdentifier("univer.formula.defined-names.service"),Ac=(i,o)=>{const{unitId:e,id:t}=o;return{...i.get(Xt).getValueById(e,t),unitId:e}},An={id:"formula.mutation.set-defined-name",type:S.CommandType.MUTATION,handler:(i,o)=>{if(o==null)return!1;const e=i.get(Xt),{id:t,unitId:r,name:n,formulaOrRefString:s,comment:a,hidden:u,localSheetId:c}=o;return e.registerDefinedName(r,{id:t,name:n.trim(),formulaOrRefString:s.trim(),comment:a==null?void 0:a.trim(),hidden:u,localSheetId:c}),!0}},js={id:"formula.mutation.remove-defined-name",type:S.CommandType.MUTATION,handler:(i,o)=>{if(o==null)return!1;const e=i.get(Xt),{unitId:t,id:r}=o;return e.removeDefinedName(t,r),!0}},En={id:"formula.mutation.set-feature-calculation",type:S.CommandType.MUTATION,handler:()=>!0},bn={id:"formula.mutation.remove-feature-calculation",type:S.CommandType.MUTATION,handler:()=>!0},Us={id:"formula.mutation.set-formula-calculation-start",type:S.CommandType.MUTATION,handler:()=>!0},Ts={id:"formula.mutation.set-formula-calculation-stop",type:S.CommandType.MUTATION,handler:()=>!0},zr={id:"formula.mutation.set-formula-calculation-notification",type:S.CommandType.MUTATION,handler:()=>!0},vs={id:"formula.mutation.set-formula-calculation-result",type:S.CommandType.MUTATION,handler:()=>!0},Bs={id:"formula.mutation.set-formula-data",type:S.CommandType.MUTATION,handler:(i,o)=>!0},yn={id:"formula.mutation.set-other-formula",type:S.CommandType.MUTATION,handler:()=>!0},Rn={id:"formula.mutation.remove-other-formula",type:S.CommandType.MUTATION,handler:()=>!0},Di={id:"formula.mutation.set-super-table",type:S.CommandType.MUTATION,handler:()=>!0},wi={id:"formula.mutation.remove-super-table",type:S.CommandType.MUTATION,handler:()=>!0},Is={id:"formula.mutation.set-super-table-option",type:S.CommandType.MUTATION,handler:()=>!0};class ht{constructor(o){A(this,"_cache");this._cache=new S.LRUMap(o)}set(o,e){const t=this._hash(o);this._cache.set(t,e)}get(o){const e=this._hash(o);return this._cache.get(e)}clear(){this._cache.clear()}_hash(o){return o.length<=64?o:S.hashAlgorithm(o).toString()}}const nt="P_1",Vt="R_1",nr="L_1",Rr="LR_1",Pi="LO_1",Ec="LET",_r="LAMBDA",bc="CUBE",yc=new Set(["RAND","RANDBETWEEN","NOW","TODAY"]),cs=new ht(1e5);function Ht(i){const o=cs.get(i);if(o)return o;const e=Cr(i);return cs.set(i,e),Cr(i)}function Rc(){cs.clear()}var Te=(i=>(i[i.NORMAL=0]="NORMAL",i[i.NUMBER=1]="NUMBER",i[i.STRING=2]="STRING",i[i.FUNCTION=3]="FUNCTION",i[i.REFERENCE=4]="REFERENCE",i[i.ARRAY=5]="ARRAY",i[i.DEFINED_NAME=6]="DEFINED_NAME",i))(Te||{});function ls(i){let o="";for(const e of i)typeof e=="string"?o+=e:o+=e.token;return o}class ae{constructor(){A(this,"_parent");A(this,"_token",Vt);A(this,"_children",[]);A(this,"_lambdaId");A(this,"_functionDefinitionPrivacyVar");A(this,"_lambdaParameter","");A(this,"_startIndex",-1);A(this,"_endIndex",-1);A(this,"_definedNames",[])}dispose(){var o;this._children.forEach(e=>{typeof e!="string"&&e.dispose()}),(o=this._functionDefinitionPrivacyVar)==null||o.clear(),this._functionDefinitionPrivacyVar=null,this._children=[],this._parent=null,this._definedNames=[]}getDefinedNames(){return this._definedNames}getStartIndex(){return this._startIndex}getLambdaId(){return this._lambdaId}setLambdaId(o){this._lambdaId=o}getFunctionDefinitionPrivacyVar(){return this._functionDefinitionPrivacyVar}setLambdaPrivacyVar(o){this._functionDefinitionPrivacyVar=o}getLambdaParameter(){return this._lambdaParameter}setLambdaParameter(o){this._lambdaParameter=o}getParent(){return this._parent}setParent(o){this._parent=o}getChildren(){return this._children}setChildren(o){this._children=o}addChildren(o){this._children.push(o)}addChildrenFirst(o){this._children.unshift(o)}getToken(){return this._token}setToken(o){this._token=o}setIndex(o,e){this._startIndex=o,this._endIndex=e}setDefinedNames(o){this._definedNames=o}hasDefinedNames(){return this._definedNames.length>0}replaceChild(o,e){const t=this._getIndexInParent(o);t!=null&&(this.getChildren().splice(t,1,e),e.setParent(this))}changeToParent(o){const e=this.getParent();e&&e.removeChild(this),this.setParent(o),o.getChildren().push(this)}removeChild(o){const e=this._getIndexInParent(o);e!=null&&this.getChildren().splice(e,1)}serialize(){const o=this.getToken(),e=this.getChildren(),t=[],r=e.length;for(let n=0;n<r;n++){const s=e[n];s instanceof ae?t.push(s.serialize()):t.push(s)}return{token:o,st:this._startIndex,ed:this._endIndex,children:t}}_getIndexInParent(o){const e=this.getChildren(),t=e.length;for(let r=0;r<t;r++)if(e[r]===o)return r}}const Li=2e3,Qn=new ht(Li),qn=new ht(Li);class pn extends S.Disposable{constructor(){super(...arguments);A(this,"_currentLexerNode",new ae);A(this,"_upLevel",0);A(this,"_segment","");A(this,"_bracketState",[]);A(this,"_squareBracketState",0);A(this,"_bracesState",0);A(this,"_singleQuotationState",0);A(this,"_doubleQuotationState",0);A(this,"_lambdaState",!1);A(this,"_colonState",!1);A(this,"_formulaErrorCount",0);A(this,"_tableBracketState",!1)}dispose(){this._resetTemp(),this._currentLexerNode.dispose(),Qn.clear(),qn.clear()}getUpLevel(){return this._upLevel}isColonClose(){return this._colonState===!1}isColonOpen(){return this._colonState===!0}isDoubleQuotationClose(){return this._doubleQuotationState===0}isLambdaOpen(){return this._lambdaState===!0}isLambdaClose(){return this._lambdaState===!1}isSingleQuotationClose(){return this._singleQuotationState===0}isBracesClose(){return this._bracesState===0}isBracketClose(){return this._bracketState.length===0}isSquareBracketClose(){return this._squareBracketState===0}getCurrentLexerNode(){return this._currentLexerNode}getFunctionAndParameter(e,t){const r=this._getCurrentParamIndex(e,t);if(r==null||r===h.VALUE)return;const n=r[0];if(typeof n=="string")return;let s=n.getParent(),a=n;for(;s;){const u=s.getToken();if(u!==nt&&!hr(u)&&s.getStartIndex()!==-1){const c=s.getChildren().indexOf(a);return{functionName:u,paramIndex:c}}a=s,s=s.getParent()}}checkIfAddBracket(e){let t=0,r=e.length-1,n=e[r];for(;(n===K.CLOSE_BRACKET||n===" ")&&r>=0;)n===K.CLOSE_BRACKET&&t++,n=e[--r];const s=this._getCurrentParamIndex(e,e.length-2);if(s==null||s===h.VALUE)return 0;const a=s[0];if(typeof a=="string")return 0;let u=a.getParent(),c=0;for(s[1]===K.OPEN_BRACKET&&c++;u;){const l=u.getToken();l!==nt&&l!==K.COLON&&u.getStartIndex()!==-1&&l.toUpperCase()!==_r&&(t===0?c+=1:t--),u=u.getParent()}return c}sequenceNodesBuilder(e){const t=qn.get(e);if(t)return[...t];const r=this._getSequenceArray(e);if(r.length===0)return;const n=this.getSequenceNode(r);return qn.set(e,[...n]),n}convertRefersToAbsolute(e,t,r,n=""){const s=this.sequenceNodesBuilder(e);if(s==null)return e;let a="";e.substring(0,1)===X.EQUALS&&(a=X.EQUALS);for(let u=0,c=s.length;u<c;u++){const l=s[u];if(typeof l!="string"&&l.nodeType===Te.REFERENCE){const{token:f,endIndex:m}=l,d=Ht(f);if(d==null)continue;const{range:_,sheetName:C,unitId:E}=d,b={..._,startAbsoluteRefType:t,endAbsoluteRefType:r},R=Zr({range:b,unitId:E,sheetName:C||n}),p=R.length-f.length;s[u]={...l,token:R,endIndex:m+p};for(let V=u+1;V<c;V++){const M=s[V];typeof M!="string"&&(M.startIndex+=p,M.endIndex+=p)}}}return`${a}${ls(s)}`}moveFormulaRefOffset(e,t,r,n=!1){const s=this.sequenceNodesBuilder(e);if(s==null)return e;const a=[];for(let u=0,c=s.length;u<c;u++){const l=s[u];if(typeof l=="string"||l.nodeType!==Te.REFERENCE){a.push(l);continue}const{token:f}=l,m=Ht(f),{sheetName:d,unitId:_}=m;let C=m.range;if(!n&&C.startAbsoluteRefType===S.AbsoluteRefType.ALL&&C.endAbsoluteRefType===S.AbsoluteRefType.ALL){a.push(l);continue}else C=S.moveRangeByOffset(C,t,r,n);let E="";S.isValidRange(C)?E=Zr({range:C,unitId:_,sheetName:d}):E=h.REF,a.push({...l,token:E})}return`=${ls(a)}`}_formulaSpellCheck(){if(this._currentLexerNode.getChildren().length===0)return!0;const e=this._currentLexerNode.getChildren()[0];return!!(e instanceof ae||bt.has(e)||Wn.has(e)||e===Ne.AT||e===K.COMMA||e===K.COLON||e===K.OPEN_BRACKET)}getSequenceNode(e){const t=[];let r=!1;for(let n=0,s=e.length;n<s;n++){const a=e[n],u=e[n-1],{segment:c,currentString:l}=a;if(l===K.DOUBLE_QUOTATION&&(r=!0),(c!==""||n===0)&&n!==s-1){t.push(l);continue}let f=(u==null?void 0:u.segment)||"";const m=n-f.length;let d=n-1;const _=n-1;if(n===s-1&&this._isLastMergeString(l)&&(f+=l,d+=1),f===""||Fr.has(f)){t.push(l);continue}const C=f.trim(),E=Oi(C);r===!0&&C[C.length-1]===K.DOUBLE_QUOTATION&&C[0]!==K.OPEN_BRACES?(r=!1,this._processPushSequenceNode(t,Te.STRING,f,m,d,_)):yr(E)&&dr(E)?this._processPushSequenceNode(t,Te.REFERENCE,f,m,d,_):S.Tools.isStringNumber(C)?this._processPushSequenceNode(t,Te.NUMBER,f,m,d,_):C.length>0&&this._processPushSequenceNode(t,Te.FUNCTION,f,m,d,_),(n!==s-1||!this._isLastMergeString(l))&&t.push(l)}return this._mergeSequenceNodeReference(t)}_processPushSequenceNode(e,t,r,n,s,a){this._pushSequenceNode(e,{nodeType:t,token:r,startIndex:n,endIndex:s},a)}_getCurrentParamIndex(e,t){return this._nodeMaker(e,void 0,t)}_isLastMergeString(e){return e===K.DOUBLE_QUOTATION||S.Tools.isStringNumber(e)||!hr(e)}_mergeSequenceNodeReference(e){const t=[],r=e.length;let n=0;for(;n<r;){const s=e[n];if(typeof s=="string"){const a=e[n-1];if(s.trim()===K.CLOSE_BRACES&&a!=null&&typeof a!="string"&&a.nodeType===Te.FUNCTION&&a.token.trim().substring(0,1)===K.OPEN_BRACES){a.nodeType=Te.ARRAY,a.token+=s,a.endIndex+=s.length,n++;continue}t.push(s)}else{const a=e[n+1],u=e[n+2];a===K.COLON&&typeof s!="string"&&u!=null&&typeof u!="string"&&dr((s.token+a+u.token).trim())&&(s.nodeType=Te.REFERENCE,s.token+=a+u.token,s.endIndex=u.endIndex,n+=2),t.push(s)}n++}return this._minusSplitSequenceNode(t)}_minusSplitSequenceNode(e){const t=[];for(const r of e){if(typeof r!="string"){const s=r.token.match(/^(\s*([-@+]\s*)+)(.*)$/);if(s){const a=s[1],u=s[3];if(dr(u.trim())){const c=a.length,l=r.startIndex,f=r.startIndex+c-1,m={nodeType:Te.NORMAL,token:a,startIndex:l,endIndex:f},d={nodeType:Te.REFERENCE,token:u,startIndex:f+1,endIndex:r.endIndex};t.push(m),t.push(d);continue}}}t.push(r)}return t}_pushSequenceNode(e,t,r){const n=r-t.startIndex+1;e.splice(e.length-n,n,t)}nodeMakerTest(e){return this._nodeMaker(e)}treeBuilder(e,t=!0,r,n){if(t===!0){const m=Qn.get(e),d=n==null?void 0:n(e);if(m&&!d)return m}this._resetCurrentLexerNode(),this._currentLexerNode.setToken(Vt);const s=[];let a=this._nodeMaker(e,s);if(a===h.VALUE||s.length===0)return a;let u=!1,c="",l=[];if(r){const{hasDefinedName:m,sequenceString:d,definedNames:_}=r(s);u=m,c=d,l=_}if(u&&(this._resetCurrentLexerNode(),this._currentLexerNode.setToken(Vt),a=this._nodeMaker(`=${c}`),a===h.VALUE))return a;const f=this._getTopNode(this._currentLexerNode);if(f&&(this._currentLexerNode=f),t){if(!this._suffixExpressionHandler(this._currentLexerNode))return h.VALUE;Qn.set(e,this._currentLexerNode)}return u&&this._currentLexerNode.setDefinedNames(l),this._currentLexerNode}_suffixExpressionHandler(e){var u;const t=e.getChildren();if(!t)return!1;const r=t.length,n=[],s=[];let a=!0;for(let c=0;c<r;c++){const l=t[c];if(l instanceof ae)a=this._suffixExpressionHandler(l),n.push(l);else{const f=l.trim();if(f==="")continue;if(bt.has(f)){if(f===X.PLUS&&this._deletePlusForPreNode(t[c-1]))continue;if(f!==X.PLUS&&f!==X.MINUS&&this._deletePlusForPreNode(t[c-1]))return!1;for(;s.length>0;){const m=(u=s[s.length-1])==null?void 0:u.trim();if(!m||m===K.OPEN_BRACKET)break;const d=Fr.get(m),_=Fr.get(f);if(!d||!_)break;if(_>=d)n.push(s.pop());else break}s.push(l)}else if(f===K.OPEN_BRACKET)s.push(l);else if(f===K.CLOSE_BRACKET)this._processSuffixExpressionCloseBracket(n,s,t,c);else{if(this._checkCloseBracket(t[c-1]))return!1;n.push(l)}}}return a?this._processSuffixExpressionRemain(n,s,e):!1}_processSuffixExpressionRemain(e,t,r){const n=e.length,s=e[n-1];for(;t.length>0;){const a=t.pop();if(!(s instanceof ae)&&(a===K.OPEN_BRACKET||a===K.CLOSE_BRACKET))return!1;e.push(a)}return r.setChildren(e),!0}_processSuffixExpressionCloseBracket(e,t,r,n){var s;if(this._checkOpenBracket(r[n-1])||this._checkOperator(r[n-1]))return!1;for(;t.length>0;){const a=(s=t[t.length-1])==null?void 0:s.trim();if(!a)break;if(a===K.OPEN_BRACKET){t.pop();break}e.push(t.pop())}}_checkCloseBracket(e){return e===K.CLOSE_BRACKET||e instanceof ae}_checkOpenBracket(e){return e===K.OPEN_BRACKET}_checkOperator(e){return e==null||e instanceof ae?!1:bt.has(e)}_deletePlusForPreNode(e){if(e==null)return!0;if(!(e instanceof ae)){const t=e.trim();if(bt.has(t)||t===K.OPEN_BRACKET)return!0}return!1}_resetCurrentLexerNode(){this._currentLexerNode=new ae}_resetSegment(){this._segment=""}_openBracket(e=0){this._bracketState.push(e)}_closeBracket(){this._bracketState.pop()}_openSquareBracket(){this._squareBracketState+=1}_closeSquareBracket(){this._squareBracketState-=1}_getCurrentBracket(){const e=this._bracketState;return e[e.length-1]}_changeCurrentBracket(e){const t=this._bracketState;t[t.length-1]=e}_openBraces(){this._bracesState+=1}_closeBraces(){this._bracesState-=1}_openSingleQuotation(){this._singleQuotationState+=1}_closeSingleQuotation(){this._singleQuotationState-=1}_openDoubleQuotation(){this._doubleQuotationState+=1}_closeDoubleQuotation(){this._doubleQuotationState-=1}_openLambda(){this._lambdaState=!0}_closeLambda(){this._lambdaState=!1}_openColon(e){this._upLevel=e,this._colonState=!0}_closeColon(){this._upLevel=0,this._colonState=!1}_isTableBracket(){return this._tableBracketState}_openTableBracket(){this._tableBracketState=!0}_closeTableBracket(){this._tableBracketState=!1}_formalErrorOccurred(){this._formulaErrorCount+=1}_hasFormalError(){return this._formulaErrorCount>0}_getLastChildCurrentLexerNode(){const e=this._currentLexerNode.getChildren();if(e&&e.length>0){const t=e[e.length-1];if(t instanceof ae)return t}return!1}_getLastChildCurrent(){const e=this._currentLexerNode.getChildren();return e&&e.length>0?e[e.length-1]:!1}_setParentCurrentLexerNode(){const e=this._currentLexerNode.getParent();return e?(this._currentLexerNode=e,!0):!1}_setAncestorCurrentLexerNode(){var r,n,s,a,u,c;const e=(r=this._currentLexerNode)==null?void 0:r.getParent();let t=!1;if(e&&e.getToken()===nr){if((n=e==null?void 0:e.getParent())!=null&&n.getParent()){const l=(a=(s=this._currentLexerNode.getParent())==null?void 0:s.getParent())==null?void 0:a.getParent();l&&(this._currentLexerNode=l),t=!0}}else if(e!=null&&e.getParent()){const l=(u=this._currentLexerNode.getParent())==null?void 0:u.getParent();l&&(this._currentLexerNode=l),t=!0}for(let l=0;l<this._upLevel;l++){const f=(c=this._currentLexerNode)==null?void 0:c.getParent();f&&(this._currentLexerNode=f),this._currentLexerNode?t=!0:t=!1}return t}_segmentCount(){return this._segment.trim().length}_pushSegment(e){this._segment+=e}_pushNodeToChildren(e,t=!1){let r=e;if(r!==""){const n=this._currentLexerNode.getChildren();if(!(r instanceof ae)&&this.isColonOpen()){const s=new ae;s.setToken(r),s.setParent(this._currentLexerNode),r=s}t?n.unshift(r):n.push(r)}this.isColonOpen()&&(this._setAncestorCurrentLexerNode(),this._closeColon())}_setCurrentLexerNode(e,t=!1){this._pushNodeToChildren(e,t),e.setParent(this._currentLexerNode),this._currentLexerNode=e}_newAndPushCurrentLexerNode(e,t,r=!1){const n=new ae;n.setToken(e),n.setIndex(t-e.length,t-1),this._setCurrentLexerNode(n,r)}_getTopNode(e){let t=e;for(;t!=null&&t.getParent();)t=t.getParent();return t}_removeLastChild(){this._currentLexerNode.getChildren().splice(-1)}_formulaErrorLastTokenCheck(e,t){const r=this._findPreviousToken(e,t)||"",n=e.length-1===t;if(!n&&this._isOperatorToken(r)||n&&Wu(r))return!0;if(Wn.has(r)){const s=this._findSecondLastNonSpaceToken(e,t);if(s==null||qu(s))return!0}return!1}_findPreviousToken(e,t){let r=t;for(;r>=0;){const n=e[r];if(n!==" ")return n;r--}}_findSecondLastNonSpaceToken(e,t){let r=t,n=0;for(;r>=0;){const s=e[r];if(s!==" "&&(n++,n===2))return s;r--}return null}_findNextToken(e,t){let r=t;for(;r>=0;){const n=e[r];if(n!==" ")return n;r++}}_unexpectedEndingTokenExcludeOperator(e){return e===K.OPEN_BRACKET||e===K.COMMA||e===X.EQUALS||e===""}_unexpectedEndingToken(e){return!!(this._isOperatorToken(e)||this._unexpectedEndingTokenExcludeOperator(e))}_isOperatorToken(e){return!!bt.has(e)}_getSequenceArray(e){const t=[];return this._nodeMaker(e,t),t}_resetTemp(){this._currentLexerNode=new ae,this._upLevel=0,this._segment="",this._bracketState=[],this._bracesState=0,this._singleQuotationState=0,this._doubleQuotationState=0,this._lambdaState=!1,this._colonState=!1,this._formulaErrorCount=0}_checkErrorState(){return!!(this._bracketState.length>0||this._bracesState>0||this._singleQuotationState>0||this._doubleQuotationState>0||this._hasFormalError())}_checkSimilarErrorToken(e,t,r){let n=t;if(e!==He.POUND)return!0;let s=r[++n];for(;s===" ";)s=r[++n];return!!hr(s)}_checkIfErrorObject(e,t){return!!this._findErrorObject(e,t)}_findErrorObject(e,t){for(let r=0;r<Ra.length;r++){const n=Ra[r],s=t.slice(e,e+n).join("").toUpperCase();if(Kt.has(s))return s}}_nodeMaker(e,t,r){let n=e.replace(/\r\n$/,"").replace(/\r/g," ").replace(/\n/g," ");n.substring(0,1)===X.EQUALS&&(n=n.substring(1));const s=n.split(""),a=s.length;let u=0;for(this._resetTemp(),this._formulaErrorLastTokenCheck(s,a-1)&&this._formalErrorOccurred();u<a;){const c=s[u];if(r===u)return[this._currentLexerNode,c];if(c===He.POUND&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()&&this._checkIfErrorObject(u,s)){const l=this._findErrorObject(u,s);if(l==null)return h.VALUE;this._pushNodeToChildren(l);for(let f=0;f<l.length;f++){const m=s[u];this._pushSegment(m),this._addSequenceArray(t,m,u),u++}this._resetSegment();continue}else if(c===K.OPEN_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())if(this._segmentCount()>0||this.isLambdaOpen()){this.isLambdaClose()&&(this._newAndPushCurrentLexerNode(this._segment,u),this._resetSegment()),this._openBracket(1),this._closeLambda();const l=s[u+1];if(l&&l===K.CLOSE_BRACKET){if(!this._setParentCurrentLexerNode()&&u!==a-1)return h.VALUE;this._addSequenceArray(t,c,u),u++,this._addSequenceArray(t,l,u),u++,this._closeBracket();continue}else l&&this._newAndPushCurrentLexerNode(nt,u)}else this._pushNodeToChildren(c),this._openBracket(0),this._resetSegment();else if(c===K.CLOSE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()){this._formulaErrorLastTokenCheck(s,u-1)&&this._formalErrorOccurred(),this._pushNodeToChildren(this._segment),this._resetSegment();const l=this._getCurrentBracket();if(l===0)this._pushNodeToChildren(c);else if(l===1){const f=s[u+1];if(f&&f===K.OPEN_BRACKET){if(!this._setParentCurrentLexerNode()&&u!==a-1)return h.VALUE;this._newAndPushCurrentLexerNode(nr,u,!0),this._openLambda()}else if(!this._setAncestorCurrentLexerNode()&&u!==a-1)return h.VALUE}else return h.VALUE;this._closeBracket()}else if(c===K.OPEN_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()){if(this._pushSegment(c),this._openBraces(),!this._formulaSpellCheck())return h.VALUE}else if(c===K.CLOSE_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._pushSegment(c),this._pushNodeToChildren(this._segment),this._resetSegment(),this._closeBraces();else if(c===K.OPEN_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._segment.length>0&&this._openTableBracket(),this._pushSegment(c),this._openSquareBracket();else if(c===K.CLOSE_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._closeSquareBracket(),this.isSquareBracketClose()?(this._pushSegment(c),this._isTableBracket()&&(this._pushNodeToChildren(this._segment),this._resetSegment()),this._closeTableBracket()):this._pushSegment(c);else if(c===K.DOUBLE_QUOTATION&&this.isSingleQuotationClose()&&this.isSquareBracketClose()){if(this.isDoubleQuotationClose())this._openDoubleQuotation();else{const l=s[u+1];l&&l===K.DOUBLE_QUOTATION?u++:this._closeDoubleQuotation()}this._pushSegment(c)}else if(c===K.SINGLE_QUOTATION&&this.isDoubleQuotationClose()){if(this.isSingleQuotationClose())this._openSingleQuotation(),this._segmentCount()===0&&this._resetSegment();else{const l=s[u+1];if(l&&l===K.SINGLE_QUOTATION){this._pushSegment(c),this._addSequenceArray(t,c,u),u++,this._pushSegment(l),this._addSequenceArray(t,l,u),u++;continue}else this._closeSingleQuotation()}this._pushSegment(c)}else if(c===K.COMMA&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){this._formulaErrorLastTokenCheck(s,u-1)&&this._formalErrorOccurred();const l=this._getCurrentBracket();if(l===1||l==null){if(this._pushNodeToChildren(this._segment),this._resetSegment(),!this._setParentCurrentLexerNode()&&u!==a-1&&l!=null)return h.VALUE;this._newAndPushCurrentLexerNode(nt,u)}else{const f=new ae;f.setToken(bc);const m=new ae;m.setToken(nt),m.changeToParent(f);const d=this._currentLexerNode.getParent();if(d&&d.getToken()===K.COLON){const _=d.getParent();if(!_)return h.VALUE;d.changeToParent(m),_.setChildren([]),f.changeToParent(_)}else return h.VALUE;this._changeCurrentBracket(1),this._pushNodeToChildren(this._segment),this._resetSegment(),this._currentLexerNode=f,this._newAndPushCurrentLexerNode(nt,u)}}else if(c===K.COLON&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){const l=new ae;l.setToken(c);const f=new ae;f.setToken(nt),f.setParent(l);const m=new ae;m.setToken(nt),m.setParent(l),l.getChildren().push(f,m);let d=l,_=0;if(this._segmentCount()>0){let C,E,b=0;const R=this._segment.trim(),p=R[0],V=R[1];if(p===Ne.MINUS&&(C=new ae,C.setToken(Ne.MINUS),b++),(p===Ne.AT||V===Ne.AT)&&(E=new ae,E.setToken(Ne.AT),C&&(C.addChildren(E),E.setParent(C)),b++),b>0&&(this._segment=R.slice(b)),_=b,E)if(E.addChildren(l),l.setParent(E),E.getParent()){const D=E.getParent();D&&(d=D)}else d=E;else C&&(d=C,C.addChildren(l),l.setParent(C));const M=new ae;M.setToken(this._segment),M.setParent(f),f.getChildren().push(M),this._resetSegment()}else{const C=this._getLastChildCurrentLexerNode();C&&C.changeToParent(f)}this._setCurrentLexerNode(d),this._currentLexerNode=m,this._openColon(_)}else if(Wn.has(c)&&this._checkSimilarErrorToken(c,u,s)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()&&this.isBracesClose()){this._pushNodeToChildren(this._segment);const l=new ae;l.setToken(c);const f=this._getLastChildCurrent();f instanceof ae?f.changeToParent(l):f!==!1&&(l.getChildren().push(f),this._removeLastChild()),this._pushNodeToChildren(l),l.setParent(this._currentLexerNode),this._resetSegment()}else if(bt.has(c)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()&&this.isBracesClose()){let l=this._segment.trim();if(c===X.MINUS&&l===""){const f=this._findPreviousToken(s,u-1)||"",m=this._findNextToken(s,u+1)||"";if(this._unexpectedEndingTokenExcludeOperator(f)&&this._isOperatorToken(m)){this._pushNodeToChildren("0"),this._pushNodeToChildren(X.MINUS),this._addSequenceArray(t,c,u),this._resetSegment(),u++;continue}else if(this._unexpectedEndingToken(f))if(m===X.PLUS){this._pushSegment(X.MINUS),this._addSequenceArray(t,c,u),this._addSequenceArray(t,X.PLUS,u+1),u+=2;continue}else{this._pushSegment(X.MINUS),this._addSequenceArray(t,c,u),u++;continue}}else if(this._segment.length>0&&this._isScientificNotation(s,u,c)){this._pushSegment(c),this._addSequenceArray(t,c,u),u++;continue}else this._segment.length>0&&l===""?l=this._segment:(this._pushNodeToChildren(this._segment),l="");if(c===X.LESS_THAN||c===X.GREATER_THAN){const f=s[u+1];if(f&&bt.has(c+f)){this._pushNodeToChildren(l+c+f),this._resetSegment(),this._addSequenceArray(t,c,u),u++,this._addSequenceArray(t,f,u),u++;continue}else this._pushNodeToChildren(l+c)}else this._pushNodeToChildren(l+c);this._resetSegment()}else this._pushSegment(c);this._addSequenceArray(t,c,u),u++}if(this._pushNodeToChildren(this._segment),this._checkErrorState())return h.VALUE}_isScientificNotation(e,t,r){const n=e[t-2];if(n&&Number.isNaN(Number(n))||!(r===X.MINUS||r===X.PLUS))return!1;const s=e[t+1];if(s&&Number.isNaN(Number(s)))return!1;const a=e[t-1];return a&&a.toUpperCase()==="E"}_addSequenceArray(e,t,r){e==null||e.push({segment:this._segment,currentString:t,cur:r,currentLexerNode:this._currentLexerNode})}}function pc(i,o,e,t,r,n,s){const a=(s==null?void 0:s.f)||"",u=(s==null?void 0:s.si)||"",c=S.isFormulaString(a),l=S.isFormulaId(u),f=i.getValue(r,n),m=(f==null?void 0:f.f)||"",d=(f==null?void 0:f.si)||"";function _(){var C;if(S.isFormulaString(m)&&S.isFormulaId(d)){const E=(C=e==null?void 0:e[d])==null?void 0:C.f;E?t.set(d,E):t.set(d,m)}}c&&l?(d!==u&&_(),i.setValue(r,n,{f:a,si:u}),e[u]={f:a,r,c:n},o.setValue(r,n,{f:a,si:u})):c&&!l?(m!==a&&_(),i.setValue(r,n,{f:a}),o.setValue(r,n,{f:a})):!c&&l?(d!==u&&_(),i.setValue(r,n,{f:"",si:u})):!c&&!l&&i.getValue(r,n)&&(_(),i.realDeleteValue(r,n),o.setValue(r,n,null))}function Nc(i,o,e,t){const r=i==null?void 0:i.getValue(e,t);if(r==null)return!0;const n=[];i.forValue((l,f,m)=>{l===e&&f===t||S.Rectangle.intersects(m,r)&&n.push(m)});const{startRow:s,startColumn:a,endRow:u,endColumn:c}=r;for(let l=s;l<=u;l++)for(let f=a;f<=c;f++){let m=!1;const d=S.cellToRange(l,f);n.some(_=>S.Rectangle.contains(_,d)?(m=!0,!0):!1),m||o.realDeleteValue(l,f)}}var Vc=Object.defineProperty,Oc=Object.getOwnPropertyDescriptor,Mc=(i,o,e,t)=>{for(var r=t>1?void 0:t?Oc(o,e):o,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(o,e,r):s(r))||r);return t&&r&&Vc(o,e,r),r},xa=(i,o)=>(e,t)=>o(e,t,i);exports.FormulaDataModel=class extends S.Disposable{constructor(e,t){super();A(this,"_arrayFormulaRange",{});A(this,"_arrayFormulaCellData",{});this._univerInstanceService=e,this._lexerTreeBuilder=t}dispose(){super.dispose(),this._arrayFormulaRange={},this._arrayFormulaCellData={}}clearPreviousArrayFormulaCellData(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;Object.keys(r).forEach(n=>{var l,f,m,d;const s=r[n],a=(f=(l=this._arrayFormulaRange)==null?void 0:l[t])==null?void 0:f[n];if(a==null)return!0;const u=new S.ObjectMatrix(a);let c=new S.ObjectMatrix;((m=this._arrayFormulaCellData[t])==null?void 0:m[n])!=null&&(c=new S.ObjectMatrix((d=this._arrayFormulaCellData[t])==null?void 0:d[n])),s.forValue((_,C)=>{const E=u.getValue(_,C);if(E==null)return!0;const{startRow:b,startColumn:R,endRow:p,endColumn:V}=E;for(let M=b;M<=p;M++)for(let D=R;D<=V;D++)c.setValue(M,D,null);u.realDeleteValue(_,C)}),this._arrayFormulaCellData[t]&&(this._arrayFormulaCellData[t][n]=c.getData())})})}mergeArrayFormulaCellData(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;this._arrayFormulaRange[t]==null&&(this._arrayFormulaRange[t]={}),this._arrayFormulaCellData[t]==null&&(this._arrayFormulaCellData[t]={}),Object.keys(r).forEach(n=>{var c,l;const s=r[n],a=new S.ObjectMatrix((c=this._arrayFormulaRange[t])==null?void 0:c[n]),u=new S.ObjectMatrix((l=this._arrayFormulaCellData[t])==null?void 0:l[n]);s.forValue((f,m)=>{const d=a==null?void 0:a.getValue(f,m);if(d==null)return!0;const{startRow:_,startColumn:C,endRow:E,endColumn:b}=d;for(let R=_;R<=E;R++)for(let p=C;p<=b;p++)u.setValue(R,p,null)}),s.forValue((f,m,d)=>{u.setValue(f,m,d)}),this._arrayFormulaCellData[t]&&(this._arrayFormulaCellData[t][n]=u.getData())})})}getFormulaData(){const e={},t=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET);return t.length===0||t.forEach(r=>{const n=r.getUnitId();e[n]={},r.getSheets().forEach(a=>{const u=a.getCellMatrix(),c=a.getSheetId();fs(e,n,c,u)})}),e}getSheetFormulaData(e,t){const r={},n=this._univerInstanceService.getUnit(e);if(n==null)return{};r[e]={};const s=n.getSheetBySheetId(t);if(s==null)return{};const a=s.getCellMatrix();return fs(r,e,t,a),r[e][t]}getArrayFormulaRange(){return this._arrayFormulaRange}setArrayFormulaRange(e){this._arrayFormulaRange=e}getArrayFormulaCellData(){return this._arrayFormulaCellData}setArrayFormulaCellData(e){this._arrayFormulaCellData=e}mergeArrayFormulaRange(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;this._arrayFormulaRange[t]||(this._arrayFormulaRange[t]={}),Object.keys(r).forEach(n=>{var u;const s=new S.ObjectMatrix(r[n]),a=new S.ObjectMatrix((u=this._arrayFormulaRange[t])==null?void 0:u[n]);s.forValue((c,l,f)=>{a.setValue(c,l,f)}),this._arrayFormulaRange[t]&&(this._arrayFormulaRange[t][n]=a.getData())})})}deleteArrayFormulaRange(e,t,r,n){var u;const s=(u=this._arrayFormulaRange[e])==null?void 0:u[t];if(s==null)return;const a=new S.ObjectMatrix(s);a.getValue(r,n)&&(a.realDeleteValue(r,n),this._arrayFormulaRange[e]&&(this._arrayFormulaRange[e][t]=a.getData()))}getCalculateData(){const e=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET),t={},r={};for(const n of e){const s=n.getUnitId(),a=n.getSheets(),u={},c={};for(const l of a){const f=l.getSheetId(),m=l.getConfig();u[f]={cellData:new S.ObjectMatrix(m.cellData),rowCount:m.rowCount,columnCount:m.columnCount,rowData:m.rowData,columnData:m.columnData,defaultRowHeight:m.defaultRowHeight,defaultColumnWidth:m.defaultColumnWidth},c[l.getName()]=l.getSheetId()}t[s]=u,r[s]=c}return{allUnitData:t,unitSheetNameMap:r}}updateFormulaData(e,t,r){const n=new S.ObjectMatrix(r),s=this._getSheetFormulaIdMap(e,t),a=new Map,u=this.getFormulaData();u[e]==null&&(u[e]={});const c=u[e];c[t]==null&&(c[t]={});const l=new S.ObjectMatrix(c[t]||{}),f=new S.ObjectMatrix;return n.forValue((m,d,_)=>{pc(l,f,s,a,m,d,_)}),l.forValue((m,d,_)=>{const C=(_==null?void 0:_.f)||"",E=(_==null?void 0:_.si)||"";if(S.isFormulaId(E)){const b=s==null?void 0:s[E],R=a.get(E);if(b&&!S.isFormulaString(C)){const p=b.f,V=d-b.c,M=m-b.r;l.setValue(m,d,{f:p,si:E,x:V,y:M}),f.setValue(m,d,{f:p,si:E,x:V,y:M})}else if(typeof R=="string"){const p=(_==null?void 0:_.x)||0,V=(_==null?void 0:_.y)||0,M=this._lexerTreeBuilder.moveFormulaRefOffset(R,p,V);a.set(E,{r:m,c:d,f:M}),l.setValue(m,d,{f:M,si:E}),f.setValue(m,d,{f:M,si:E})}else if(typeof R=="object"){const p=d-R.c,V=m-R.r;l.setValue(m,d,{f:R.f,si:E,x:p,y:V}),f.setValue(m,d,{f:R.f,si:E,x:p,y:V})}}}),f.getMatrix()}updateArrayFormulaRange(e,t,r){var u;const n=(u=this._arrayFormulaRange[e])==null?void 0:u[t];if(!n)return;const s=new S.ObjectMatrix(n);new S.ObjectMatrix(r).forValue((c,l,f)=>{s.realDeleteValue(c,l)})}updateArrayFormulaCellData(e,t,r){var l,f;const n=(l=this._arrayFormulaRange[e])==null?void 0:l[t];if(!n)return;const s=new S.ObjectMatrix(n),a=(f=this._arrayFormulaCellData[e])==null?void 0:f[t];if(!a)return;const u=new S.ObjectMatrix(a);new S.ObjectMatrix(r).forValue((m,d,_)=>{Nc(s,u,m,d)})}getFormulaStringByCell(e,t,r,n){const s=this._univerInstanceService.getUnit(n);if(s==null)return null;const a=s.getSheetBySheetId(r);if(a==null)return null;const u=a.getCellMatrix(),c=u.getValue(e,t);if(c==null)return null;const{f:l,si:f}=c;if(S.isFormulaString(l))return l;if(S.isFormulaId(f)){let m=null;return u.forValue((d,_,C)=>{if(C==null)return!0;const{f:E,si:b}=C;if(S.isFormulaString(E)&&f===b)return m=this._lexerTreeBuilder.moveFormulaRefOffset(E,t-_,e-d),!1}),m}return null}getFormulaDirtyRanges(){const e=this.getFormulaData(),t=[];for(const r in e){const n=e[r];if(!n)continue;const s=this._univerInstanceService.getUnit(r);if(s)for(const a in n){const u=n[a];if(!u)continue;const c=s.getSheetBySheetId(a);if(!c)continue;const l={};for(const f of Object.keys(u)){const m=Number(f);for(const d in u[m]){const _=Number(d),C=c.getCellRaw(m,_),E=S.isFormulaString(C==null?void 0:C.f)||S.isFormulaId(C==null?void 0:C.si),b=(C==null?void 0:C.v)===void 0;if(!(E&&b))continue;l[_]||(l[_]=[]);const R=l[_].slice(-1)[0];R&&R.endRow===m-1?R.endRow=m:l[_].push({startRow:m,endRow:m})}}for(const f in l){const m=l[f];for(let d=0;d<m.length;d++){const _=m[d];t.push({unitId:r,sheetId:a,range:{rangeType:S.RANGE_TYPE.NORMAL,startRow:_.startRow,endRow:_.endRow,startColumn:Number(f),endColumn:Number(f)}})}}}}return t}_getSheetFormulaIdMap(e,t){const r={},n=this._univerInstanceService.getUnit(e);if(n==null)return r;const s=n.getSheetBySheetId(t);return s==null||s.getCellMatrix().forValue((u,c,l)=>{if(l==null)return!0;const{f,si:m}=l;S.isFormulaString(f)&&S.isFormulaId(m)&&(r[m]={f,r:u,c})}),r}};exports.FormulaDataModel=Mc([xa(0,S.IUniverInstanceService),xa(1,S.Inject(pn))],exports.FormulaDataModel);function fs(i,o,e,t){i[o]||(i[o]={}),i[o][e]||(i[o][e]={});const r=new Map,n=new S.ObjectMatrix(i[o][e]);t.forValue((a,u,c)=>{const l=(c==null?void 0:c.f)||"",f=(c==null?void 0:c.si)||"",m=S.isFormulaString(l),d=S.isFormulaId(f);m&&d?(n.setValue(a,u,{f:l,si:f}),r.set(f,{f:l,r:a,c:u})):m&&!d?n.setValue(a,u,{f:l}):!m&&d&&n.setValue(a,u,{f:"",si:f})}),n.forValue((a,u,c)=>{const l=(c==null?void 0:c.f)||"",f=(c==null?void 0:c.si)||"";if(S.isFormulaId(f)&&!S.isFormulaString(l)){const m=r.get(f);if(m){const d=m.f,_=u-m.c,C=a-m.r;n.setValue(a,u,{f:d,si:f,x:_,y:C})}else n.realDeleteValue(a,u)}});const s=n.getMatrix();return{[o]:{[e]:s}}}const Sc=class ms{constructor(o,e){this.low=o,this.high=e}clone(){return new ms(this.low,this.high)}get max(){return this.clone()}less_than(o){return this.low<o.low||this.low===o.low&&this.high<o.high}equal_to(o){return this.low===o.low&&this.high===o.high}intersect(o){return!this.not_intersect(o)}not_intersect(o){return this.high<o.low||o.high<this.low}merge(o){return new ms(this.low===void 0?o.low:this.low<o.low?this.low:o.low,this.high===void 0?o.high:this.high>o.high?this.high:o.high)}output(){return[this.low,this.high]}static comparable_max(o,e){return o.merge(e)}static comparable_less_than(o,e){return o<e}},we=0,_e=1;class Lt{constructor(o=void 0,e=void 0,t=null,r=null,n=null,s=_e){if(this.left=t,this.right=r,this.parent=n,this.color=s,this.item={key:o,value:e},o&&o instanceof Array&&o.length===2&&!Number.isNaN(o[0])&&!Number.isNaN(o[1])){let[a,u]=o;a>u&&([a,u]=[u,a]),this.item.key=new Sc(a,u)}this.max=this.item.key?this.item.key.max:void 0}isNil(){return this.item.key===void 0&&this.item.value===void 0&&this.left===null&&this.right===null&&this.color===_e}_value_less_than(o){return this.item.value&&o.item.value&&this.item.value.less_than?this.item.value.less_than(o.item.value):this.item.value<o.item.value}less_than(o){return this.item.value===this.item.key&&o.item.value===o.item.key?this.item.key.less_than(o.item.key):this.item.key.less_than(o.item.key)||this.item.key.equal_to(o.item.key)&&this._value_less_than(o)}_value_equal(o){return this.item.value&&o.item.value&&this.item.value.equal_to?this.item.value.equal_to(o.item.value):this.item.value===o.item.value}equal_to(o){return this.item.value===this.item.key&&o.item.value===o.item.key?this.item.key.equal_to(o.item.key):this.item.key.equal_to(o.item.key)&&this._value_equal(o)}intersect(o){return this.item.key.intersect(o.item.key)}copy_data(o){this.item.key=o.item.key,this.item.value=o.item.value}update_max(){if(this.max=this.item.key?this.item.key.max:void 0,this.right&&this.right.max){const o=this.item.key.constructor.comparable_max;this.max=o(this.max,this.right.max)}if(this.left&&this.left.max){const o=this.item.key.constructor.comparable_max;this.max=o(this.max,this.left.max)}}not_intersect_left_subtree(o){const e=this.item.key.constructor.comparable_less_than;let t=this.left.max.high!==void 0?this.left.max.high:this.left.max;return e(t,o.item.key.low)}not_intersect_right_subtree(o){const e=this.item.key.constructor.comparable_less_than;let t=this.right.max.low!==void 0?this.right.max.low:this.right.item.key.low;return e(o.item.key.high,t)}}class Fs{constructor(){this.root=null,this.nil_node=new Lt}get size(){let o=0;return this.tree_walk(this.root,()=>o++),o}get keys(){let o=[];return this.tree_walk(this.root,e=>o.push(e.item.key.output?e.item.key.output():e.item.key)),o}get values(){let o=[];return this.tree_walk(this.root,e=>o.push(e.item.value)),o}get items(){let o=[];return this.tree_walk(this.root,e=>o.push({key:e.item.key.output?e.item.key.output():e.item.key,value:e.item.value})),o}isEmpty(){return this.root==null||this.root===this.nil_node}clear(){this.root=null}insert(o,e=o){if(o===void 0)return;let t=new Lt(o,e,this.nil_node,this.nil_node,null,we);return this.tree_insert(t),this.recalc_max(t),t}exist(o,e=o){let t=new Lt(o,e);return!!this.tree_search(this.root,t)}remove(o,e=o){let t=new Lt(o,e),r=this.tree_search(this.root,t);return r&&this.tree_delete(r),r}search(o,e=(t,r)=>t===r?r.output():t){let t=new Lt(o),r=[];return this.tree_search_interval(this.root,t,r),r.map(n=>e(n.item.value,n.item.key))}intersect_any(o){let e=new Lt(o);return this.tree_find_any_interval(this.root,e)}forEach(o){this.tree_walk(this.root,e=>o(e.item.key,e.item.value))}map(o){const e=new Fs;return this.tree_walk(this.root,t=>e.insert(t.item.key,o(t.item.value,t.item.key))),e}*iterate(o,e=(t,r)=>t===r?r.output():t){let t;for(o?t=this.tree_search_nearest_forward(this.root,new Lt(o)):this.root&&(t=this.local_minimum(this.root));t;)yield e(t.item.value,t.item.key),t=this.tree_successor(t)}recalc_max(o){let e=o;for(;e.parent!=null;)e.parent.update_max(),e=e.parent}tree_insert(o){let e=this.root,t=null;if(this.root==null||this.root===this.nil_node)this.root=o;else{for(;e!==this.nil_node;)t=e,o.less_than(e)?e=e.left:e=e.right;o.parent=t,o.less_than(t)?t.left=o:t.right=o}this.insert_fixup(o)}insert_fixup(o){let e,t;for(e=o;e!==this.root&&e.parent.color===we;)e.parent===e.parent.parent.left?(t=e.parent.parent.right,t.color===we?(e.parent.color=_e,t.color=_e,e.parent.parent.color=we,e=e.parent.parent):(e===e.parent.right&&(e=e.parent,this.rotate_left(e)),e.parent.color=_e,e.parent.parent.color=we,this.rotate_right(e.parent.parent))):(t=e.parent.parent.left,t.color===we?(e.parent.color=_e,t.color=_e,e.parent.parent.color=we,e=e.parent.parent):(e===e.parent.left&&(e=e.parent,this.rotate_right(e)),e.parent.color=_e,e.parent.parent.color=we,this.rotate_left(e.parent.parent)));this.root.color=_e}tree_delete(o){let e,t;o.left===this.nil_node||o.right===this.nil_node?e=o:e=this.tree_successor(o),e.left!==this.nil_node?t=e.left:t=e.right,t.parent=e.parent,e===this.root?this.root=t:(e===e.parent.left?e.parent.left=t:e.parent.right=t,e.parent.update_max()),this.recalc_max(t),e!==o&&(o.copy_data(e),o.update_max(),this.recalc_max(o)),e.color===_e&&this.delete_fixup(t)}delete_fixup(o){let e=o,t;for(;e!==this.root&&e.parent!=null&&e.color===_e;)e===e.parent.left?(t=e.parent.right,t.color===we&&(t.color=_e,e.parent.color=we,this.rotate_left(e.parent),t=e.parent.right),t.left.color===_e&&t.right.color===_e?(t.color=we,e=e.parent):(t.right.color===_e&&(t.color=we,t.left.color=_e,this.rotate_right(t),t=e.parent.right),t.color=e.parent.color,e.parent.color=_e,t.right.color=_e,this.rotate_left(e.parent),e=this.root)):(t=e.parent.left,t.color===we&&(t.color=_e,e.parent.color=we,this.rotate_right(e.parent),t=e.parent.left),t.left.color===_e&&t.right.color===_e?(t.color=we,e=e.parent):(t.left.color===_e&&(t.color=we,t.right.color=_e,this.rotate_left(t),t=e.parent.left),t.color=e.parent.color,e.parent.color=_e,t.left.color=_e,this.rotate_right(e.parent),e=this.root));e.color=_e}tree_search(o,e){if(!(o==null||o===this.nil_node))return e.equal_to(o)?o:e.less_than(o)?this.tree_search(o.left,e):this.tree_search(o.right,e)}tree_search_nearest_forward(o,e){let t,r=o;for(;r&&r!==this.nil_node;)r.less_than(e)?r.intersect(e)?(t=r,r=r.left):r=r.right:((!t||r.less_than(t))&&(t=r),r=r.left);return t||null}tree_search_interval(o,e,t){o!=null&&o!==this.nil_node&&(o.left!==this.nil_node&&!o.not_intersect_left_subtree(e)&&this.tree_search_interval(o.left,e,t),o.intersect(e)&&t.push(o),o.right!==this.nil_node&&!o.not_intersect_right_subtree(e)&&this.tree_search_interval(o.right,e,t))}tree_find_any_interval(o,e){let t=!1;return o!=null&&o!==this.nil_node&&(o.left!==this.nil_node&&!o.not_intersect_left_subtree(e)&&(t=this.tree_find_any_interval(o.left,e)),t||(t=o.intersect(e)),!t&&o.right!==this.nil_node&&!o.not_intersect_right_subtree(e)&&(t=this.tree_find_any_interval(o.right,e))),t}local_minimum(o){let e=o;for(;e.left!=null&&e.left!==this.nil_node;)e=e.left;return e}local_maximum(o){let e=o;for(;e.right!=null&&e.right!==this.nil_node;)e=e.right;return e}tree_successor(o){let e,t,r;if(o.right!==this.nil_node)e=this.local_minimum(o.right);else{for(t=o,r=o.parent;r!=null&&r.right===t;)t=r,r=r.parent;e=r}return e}rotate_left(o){let e=o.right;o.right=e.left,e.left!==this.nil_node&&(e.left.parent=o),e.parent=o.parent,o===this.root?this.root=e:o===o.parent.left?o.parent.left=e:o.parent.right=e,e.left=o,o.parent=e,o!=null&&o!==this.nil_node&&o.update_max(),e=o.parent,e!=null&&e!==this.nil_node&&e.update_max()}rotate_right(o){let e=o.left;o.left=e.right,e.right!==this.nil_node&&(e.right.parent=o),e.parent=o.parent,o===this.root?this.root=e:o===o.parent.left?o.parent.left=e:o.parent.right=e,e.right=o,o.parent=e,o!==null&&o!==this.nil_node&&o.update_max(),e=o.parent,e!=null&&e!==this.nil_node&&e.update_max()}tree_walk(o,e){o!=null&&o!==this.nil_node&&(this.tree_walk(o.left,e),e(o),this.tree_walk(o.right,e))}testRedBlackProperty(){let o=!0;return this.tree_walk(this.root,function(e){e.color===we&&(e.left.color===_e&&e.right.color===_e||(o=!1))}),o}testBlackHeightProperty(o){let e=0,t=0,r=0;if(o.color===_e&&e++,o.left!==this.nil_node?t=this.testBlackHeightProperty(o.left):t=1,o.right!==this.nil_node?r=this.testBlackHeightProperty(o.right):r=1,t!==r)throw new Error("Red-black height property violated");return e+=t,e}}class Dc{constructor(){A(this,"_cache",new Map);A(this,"_continueBuildingCache",new Map)}set(o,e,t,r,n){if(!this.shouldContinueBuildingCache(o,e,t,n))return;let s=this._cache.get(o);s==null&&(s=new Map,this._cache.set(o,s));let a=s.get(e);a==null&&(a=new Map,s.set(e,a));let u=a.get(t);u==null&&(u=new Map,a.set(t,u));let c=u.get(r);c==null&&(c=new Set,u.set(r,c)),c.add(n)}getCellValuePositions(o,e,t){var r,n;return(n=(r=this._cache.get(o))==null?void 0:r.get(e))==null?void 0:n.get(t)}getCellPositions(o,e,t,r,n){var a,u,c;const s=(c=(u=(a=this._cache.get(o))==null?void 0:a.get(e))==null?void 0:u.get(t))==null?void 0:c.get(r);return s&&[...s].filter(l=>n.some(([f,m])=>l>=f&&l<=m))}setContinueBuildingCache(o,e,t,r,n){if(t===-1||r===-1||n===-1)return;let s=this._continueBuildingCache.get(o);s==null&&(s=new Map,this._continueBuildingCache.set(o,s));let a=s.get(e);a==null&&(a=new Map,s.set(e,a));let u=a.get(t);if(u==null){u=new Fs,u.insert([r,n]),a.set(t,u);return}this._handleNewInterval(u,r,n)}shouldContinueBuildingCache(o,e,t,r){var a,u;if(t===-1||r===-1)return!1;const n=(u=(a=this._continueBuildingCache.get(o))==null?void 0:a.get(e))==null?void 0:u.get(t);return n?n.search([r,r]).length===0:!0}canUseCache(o,e,t,r,n){var f,m;const s=(m=(f=this._continueBuildingCache.get(o))==null?void 0:f.get(e))==null?void 0:m.get(t);if(t===-1||r===-1||n===-1||!s)return{rowsInCache:[],rowsNotInCache:[]};const a=s.search([r,n]);if(a.length===0)return{rowsInCache:[],rowsNotInCache:[]};a.sort((d,_)=>d[0]-_[0]);const u=[],c=[];let l=r;for(let d=0;d<a.length;d++){const[_,C]=a[d];if(l>=_){if(n<=C){u.push([l,n]);break}u.push([l,C]),l=C+1,d===a.length-1&&l<=n&&c.push([l,n])}else{if(n>C){u.push([_,C]),c.push([l,_-1]),l=C+1,d===a.length-1&&l<=n&&c.push([l,n]);continue}u.push([_,n]),c.push([l,_-1])}}return{rowsInCache:u,rowsNotInCache:c}}clear(){this._cache.clear(),this._continueBuildingCache.clear()}_handleNewInterval(o,e,t){let r=o.search([e,t]);if(r.length===0){const a=[e-1<0?0:e-1,t+1];if(r=o.search(a),r.length===0){o.insert([e,t]);return}}let n=e,s=t;for(const a of r)n=Math.min(n,a[0]),s=Math.max(s,a[1]),o.remove(a);o.insert([n,s])}}const yt=new Dc,Nn="engine-formula.config",xi=1,wc="CYCLE_REFERENCE_COUNT",ja={};var Pc=Object.defineProperty,Lc=Object.getOwnPropertyDescriptor,xc=(i,o,e,t)=>{for(var r=t>1?void 0:t?Lc(o,e):o,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(o,e,r):s(r))||r);return t&&r&&Pc(o,e,r),r},Ua=(i,o)=>(e,t)=>o(e,t,i);exports.FormulaCurrentConfigService=class extends S.Disposable{constructor(e,t){super();A(this,"_unitData",{});A(this,"_unitStylesData",{});A(this,"_arrayFormulaCellData",{});A(this,"_arrayFormulaRange",{});A(this,"_formulaData",{});A(this,"_sheetNameMap",{});A(this,"_forceCalculate",!1);A(this,"_clearDependencyTreeCache",{});A(this,"_dirtyRanges",[]);A(this,"_dirtyNameMap",{});A(this,"_dirtyDefinedNameMap",{});A(this,"_dirtyUnitFeatureMap",{});A(this,"_dirtyUnitOtherFormulaMap",{});A(this,"_excludedCell");A(this,"_sheetIdToNameMap",{});A(this,"_executeUnitId","");A(this,"_executeSubUnitId","");this._univerInstanceService=e,this._localeService=t}dispose(){this._unitData={},this._unitStylesData={},this._formulaData={},this._arrayFormulaCellData={},this._arrayFormulaRange={},this._sheetNameMap={},this._dirtyRanges=[],this._dirtyNameMap={},this._dirtyDefinedNameMap={},this._dirtyUnitFeatureMap={},this._excludedCell={},this._sheetIdToNameMap={},this._dirtyUnitOtherFormulaMap={}}getExecuteUnitId(){return this._executeUnitId}getExecuteSubUnitId(){return this._executeSubUnitId}setExecuteUnitId(e){this._executeUnitId=e}setExecuteSubUnitId(e){this._executeSubUnitId=e}getExcludedRange(){return this._excludedCell}getUnitData(){return this._unitData}getUnitStylesData(){return this._unitStylesData}getFormulaData(){return this._formulaData}getArrayFormulaCellData(){return this._arrayFormulaCellData}getArrayFormulaRange(){return this._arrayFormulaRange}getSheetNameMap(){return this._sheetNameMap}isForceCalculate(){return this._forceCalculate}getDirtyRanges(){return this._dirtyRanges}getDirtyNameMap(){return this._dirtyNameMap}getDirtyDefinedNameMap(){return this._dirtyDefinedNameMap}getDirtyUnitFeatureMap(){return this._dirtyUnitFeatureMap}getDirtyUnitOtherFormulaMap(){return this._dirtyUnitOtherFormulaMap}getSheetName(e,t){return this._sheetIdToNameMap[e]==null?"":this._sheetIdToNameMap[e][t]||""}getClearDependencyTreeCache(){return this._clearDependencyTreeCache}getLocale(){return this._localeService.getCurrentLocale()}getSheetsInfo(){const e=this._univerInstanceService.getCurrentUnitForType(S.UniverInstanceType.UNIVER_SHEET),{id:t,sheetOrder:r}=e.getSnapshot();return{sheetOrder:r,sheetNameMap:this._sheetIdToNameMap[t]}}getSheetRowColumnCount(e,t){const r=this._univerInstanceService.getUnit(e),n=r==null?void 0:r.getSheetBySheetId(t),s=n==null?void 0:n.getSnapshot();if(!s)return{rowCount:0,columnCount:0};const{rowCount:a,columnCount:u}=s;return{rowCount:a,columnCount:u}}load(e){if(e.allUnitData&&e.unitSheetNameMap&&e.unitStylesData)this._unitData=e.allUnitData,this._unitStylesData=e.unitStylesData,this._sheetNameMap=e.unitSheetNameMap;else{const{allUnitData:t,unitSheetNameMap:r,unitStylesData:n}=this._loadSheetData();this._unitData=t,this._unitStylesData=n,this._sheetNameMap=r}this._formulaData=e.formulaData,this._arrayFormulaCellData=Ci(e.arrayFormulaCellData),this._arrayFormulaRange=e.arrayFormulaRange,this._forceCalculate=e.forceCalculate,this._clearDependencyTreeCache=e.clearDependencyTreeCache||{},this._dirtyRanges=e.dirtyRanges,this._dirtyNameMap=e.dirtyNameMap,this._dirtyDefinedNameMap=e.dirtyDefinedNameMap,this._dirtyUnitFeatureMap=e.dirtyUnitFeatureMap,this._dirtyUnitOtherFormulaMap=e.dirtyUnitOtherFormulaMap,this._excludedCell=e.excludedCell,this._mergeNameMap(this._sheetNameMap,this._dirtyNameMap)}getDirtyData(){return{forceCalculation:this._forceCalculate,dirtyRanges:this._dirtyRanges,dirtyNameMap:this._dirtyNameMap,dirtyDefinedNameMap:this._dirtyDefinedNameMap,dirtyUnitFeatureMap:this._dirtyUnitFeatureMap,dirtyUnitOtherFormulaMap:this._dirtyUnitOtherFormulaMap,clearDependencyTreeCache:this._clearDependencyTreeCache}}loadDirtyRangesAndExcludedCell(e,t){this._dirtyRanges=e,this._excludedCell=t,this._dirtyNameMap={}}registerUnitData(e){this._unitData=e}registerFormulaData(e){this._formulaData=e}registerSheetNameMap(e){this._sheetNameMap=e}_mergeNameMap(e,t){Object.keys(t).forEach(r=>{t[r]&&Object.keys(t[r]).forEach(n=>{e[r]==null&&(e[r]={}),e[r][t[r][n]]=n})}),this._sheetIdToNameMap={},Object.keys(e).forEach(r=>{Object.keys(e[r]).forEach(n=>{this._sheetIdToNameMap[r]==null&&(this._sheetIdToNameMap[r]={}),this._sheetIdToNameMap[r][e[r][n]]=n})})}_loadSheetData(){const e=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET),t=this._univerInstanceService.getCurrentUnitForType(S.UniverInstanceType.UNIVER_SHEET),r=t==null?void 0:t.getActiveSheet();this._executeUnitId=t==null?void 0:t.getUnitId(),this._executeSubUnitId=r==null?void 0:r.getSheetId();const n={},s={},a={};for(const u of e){const c=u.getUnitId(),l=u.getSheets(),f={},m={};for(const d of l){const _=d.getSheetId(),C=d.getConfig();f[_]={cellData:new S.ObjectMatrix(C.cellData),rowCount:C.rowCount,columnCount:C.columnCount,rowData:C.rowData,columnData:C.columnData,defaultRowHeight:C.defaultRowHeight,defaultColumnWidth:C.defaultColumnWidth},m[d.getName()]=d.getSheetId()}n[c]=f,s[c]=u.getStyles(),a[c]=m}return{allUnitData:n,unitStylesData:s,unitSheetNameMap:a}}};exports.FormulaCurrentConfigService=xc([Ua(0,S.IUniverInstanceService),Ua(1,S.Inject(S.LocaleService))],exports.FormulaCurrentConfigService);const gt=S.createIdentifier("univer.formula.current-data.service");var jc=Object.defineProperty,Uc=Object.getOwnPropertyDescriptor,Tc=(i,o,e,t)=>{for(var r=t>1?void 0:t?Uc(o,e):o,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(o,e,r):s(r))||r);return t&&r&&jc(o,e,r),r},Kn=(i,o)=>(e,t)=>o(e,t,i);exports.Lexer=class extends S.Disposable{constructor(o,e,t){super(),this._definedNamesService=o,this._lexerTreeBuilder=e,this._formulaCurrentConfigService=t}treeBuilder(o,e=!0){return this._lexerTreeBuilder.treeBuilder(o,e,this._injectDefinedName.bind(this),this._simpleCheckDefinedName.bind(this))}_simpleCheckDefinedName(o){const e=this._formulaCurrentConfigService.getDirtyDefinedNameMap(),t=this._formulaCurrentConfigService.getExecuteUnitId();if(t!=null&&e[t]!=null){const r=Object.keys(e[t]);for(let n=0,s=r.length;n<s;n++){const a=r[n];if(o.indexOf(a)>-1)return!0}}return!1}_checkDefinedNameDirty(o){const e=this._formulaCurrentConfigService.getDirtyDefinedNameMap(),t=this._formulaCurrentConfigService.getExecuteUnitId();if(t!=null&&e[t]!=null){const r=Object.keys(e[t]);for(let n=0,s=r.length;n<s;n++)if(r[n]===o)return!0}return!1}_injectDefinedName(o){const e=this._formulaCurrentConfigService.getExecuteUnitId();if(e==null)return{sequenceString:"",hasDefinedName:!1,definedNames:[]};const t=this._lexerTreeBuilder.getSequenceNode(o);let r="",n=!1;const s=[];for(let a=0,u=t.length;a<u;a++){const c=t[a];if(typeof c=="string"){r+=c;continue}const{nodeType:l,token:f}=c;if(l===Te.REFERENCE||l===Te.FUNCTION){const m=this._definedNamesService.getValueByName(e,f);if(m){let d=m.formulaOrRefString;d.substring(0,1)===X.EQUALS&&(d=d.substring(1)),r+=d,s.push(m.name),n=!0}else this._checkDefinedNameDirty(f)?(r+=h.NAME,n=!0,s.push(f)):r+=f}else r+=f}return{sequenceString:r,hasDefinedName:n,definedNames:s}}};exports.Lexer=Tc([Kn(0,Xt),Kn(1,S.Inject(pn)),Kn(2,gt)],exports.Lexer);function $r(i){if(i==null)return!0;const{v:o,f:e,si:t,p:r}=i;return!(!(o==null||typeof o=="string"&&o.length===0)||e!=null&&e.length>0||t!=null&&t.length>0||r!=null)}function ji(i,o,e,t,r){var s;const n=Object.keys(r);for(const a of n){const u=r[a],c=(s=u==null?void 0:u[t])==null?void 0:s[e];if(c==null)continue;const l=c.getValue(i,o);if(l!=null)return l}}const vc=["$","£","¥","¤","֏","؋","৳","฿","៛","₡","₦","₩","₪","₫","€","₭","₮","₱","₲","₴","₸","₹","₺","₼","₽","₾","₿"],Bc={currency:2,date:4,datetime:5,error:11,fraction:7,general:0,grouped:11,number:1,percent:6,scientific:8,text:9,time:5,unknown:11};function Ic(i,o,e){var u,c;if(i==null||o==null)return o;const t=(e==null?void 0:e.getStyleByCell(i))||i.s,r=(e==null?void 0:e.getStyleByCell(o))||o.s;if(t==null||r==null||typeof t!="object"||typeof r!="object")return o;const n=(u=t==null?void 0:t.n)==null?void 0:u.pattern,s=(c=r==null?void 0:r.n)==null?void 0:c.pattern;if(n==null||s==null)return o;const a=n||s;return r.n.pattern=a,o}const hs=new ht(1e5);function Ta(i){const o=hs.get(i);if(o!==void 0)return o;const e=kc(i);return hs.set(i,e),e}function Fc(){hs.clear()}function kc(i){if($c(i))return 3;const o=S.numfmt.getInfo(i).type||"unknown";return Bc[o]}function $c(i){return!!vc.find(o=>i.includes(o))&&i.startsWith("_(")}function jr(i,o,e){if(i==="")return o;if(o==="")return i;const t=Ta(i),r=Ta(o);return e===X.PLUS||e===X.MINUS?t===4&&r===4||t===11&&r===11?"":o:e===X.MULTIPLY||e===X.DIVIDED?t===6&&r===6||t===7&&r===7||t===8&&r===8||t===9&&r===9?o:"":i||o}const Yc=new Map([[S.LocaleType.EN_US,"$"],[S.LocaleType.RU_RU,"₽"],[S.LocaleType.VI_VN,"₫"],[S.LocaleType.ZH_CN,"¥"],[S.LocaleType.ZH_TW,"NT$"]]);function va(i){return Yc.get(i)||"$"}function Ye(i,o=2){let e=o;o>127&&(e=127);let t="";return e>0&&(t=`.${"0".repeat(e)}`),`"${va(i)}"#,##0${t}_);[Red]("${va(i)}"#,##0${t})`}function Hc(i,o,e=2){return S.numfmt.format(Ye(i,e),o)}const ks=new ht(1e5);function Gc(i){let o=i;o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1));const e=ks.get(o);if(e)return{isNumberPattern:!0,value:e.value,pattern:e.pattern};const t=S.numfmt.parseNumber(o);if(t)return Xn(o,t.v,t.z);const r=S.numfmt.parseDate(o);if(r)return Xn(o,r.v,r.z);const n=S.numfmt.parseTime(o);return n?Xn(o,n.v,n.z):{isNumberPattern:!1}}function Xn(i,o,e){return ks.set(i,{value:o,pattern:e}),{isNumberPattern:!0,value:o,pattern:e}}function Wc(){ks.clear()}class Vn{constructor(){A(this,"pattern","")}dispose(){}getPattern(){return this.pattern}setPattern(o){this.pattern=o}isError(){return!1}isAsyncObject(){return!1}isAsyncArrayObject(){return!1}isReferenceObject(){return!1}isArray(){return!1}isValueObject(){return!1}isEqualType(o){return!1}}class dt extends Vn{constructor(o){super(),this._rawValue=o}isValueObject(){return!0}toUnitRange(){return{range:{startColumn:-1,startRow:-1,endRow:-1,endColumn:-1},sheetId:"",unitId:""}}getValue(){return 0}getArrayValue(){return[]}setValue(o){}setArrayValue(o){}isCube(){return!1}isString(){return!1}isNumber(){return!1}isBoolean(){return!1}isLambda(){return!1}isError(){return!1}isNull(){return!1}sum(){return g.create(h.VALUE)}max(){return g.create(h.VALUE)}min(){return g.create(h.VALUE)}count(){return g.create(h.VALUE)}countA(){return g.create(h.VALUE)}countBlank(){return g.create(h.VALUE)}getNegative(){return g.create(h.VALUE)}getReciprocal(){return g.create(h.VALUE)}plus(o){return g.create(h.VALUE)}minus(o){return g.create(h.VALUE)}multiply(o){return g.create(h.VALUE)}divided(o){return g.create(h.VALUE)}mod(o){return g.create(h.VALUE)}map(o){return g.create(h.NAME)}mapValue(o){return g.create(h.NAME)}compare(o,e,t=!1){return g.create(h.NAME)}isEqual(o){return this.compare(o,Y.EQUALS)}isNotEqual(o){return this.compare(o,Y.NOT_EQUAL)}isGreaterThanOrEqual(o){return this.compare(o,Y.GREATER_THAN_OR_EQUAL)}isLessThanOrEqual(o){return this.compare(o,Y.LESS_THAN_OR_EQUAL)}isLessThan(o){return this.compare(o,Y.LESS_THAN)}isGreaterThan(o){return this.compare(o,Y.GREATER_THAN)}concatenateFront(o){return g.create(h.NAME)}concatenateBack(o){return g.create(h.NAME)}plusBy(o){return g.create(h.VALUE)}minusBy(o){return g.create(h.VALUE)}multiplyBy(o){return g.create(h.VALUE)}dividedBy(o){return g.create(h.VALUE)}modInverse(o){return g.create(h.VALUE)}compareBy(o,e){return g.create(h.NAME)}concatenate(o,e=Je.FRONT){let t=this.getValue().toString();if(typeof o=="string")e===Je.FRONT?t=o+t:t+=o;else if(typeof o=="number")e===Je.FRONT?t=o.toString()+t:t+=o.toString();else if(typeof o=="boolean"){const r=o?"TRUE":"FALSE";e===Je.FRONT?t=r+t:t+=r}return t}pow(o){return g.create(h.VALUE)}powInverse(o){return g.create(h.VALUE)}sqrt(){return g.create(h.VALUE)}cbrt(){return g.create(h.VALUE)}cos(){return g.create(h.VALUE)}cosh(){return g.create(h.VALUE)}acos(){return g.create(h.VALUE)}acosh(){return g.create(h.VALUE)}sin(){return g.create(h.VALUE)}sinh(){return g.create(h.VALUE)}asin(){return g.create(h.VALUE)}asinh(){return g.create(h.VALUE)}tan(){return g.create(h.VALUE)}tanh(){return g.create(h.VALUE)}atan(){return g.create(h.VALUE)}atan2(o){return g.create(h.VALUE)}atan2Inverse(o){return g.create(h.VALUE)}atanh(){return g.create(h.VALUE)}mean(){return this}median(){return this}var(){return this}std(){return this}log(){return g.create(h.VALUE)}log10(){return g.create(h.VALUE)}exp(){return g.create(h.VALUE)}abs(){return g.create(h.VALUE)}round(o){return g.create(h.VALUE)}roundInverse(o){return g.create(h.VALUE)}floor(o){return g.create(h.VALUE)}floorInverse(o){return g.create(h.VALUE)}ceil(o){return g.create(h.VALUE)}ceilInverse(o){return g.create(h.VALUE)}convertToNumberObjectValue(){return g.create(h.VALUE)}convertToBooleanObjectValue(){return g.create(h.VALUE)}}const Qc=1e3,Ba=new ht(Qc);class g extends dt{constructor(o,e=""){super(o),this._errorType=o,this._errorContent=e}static create(o,e=""){const t=`${o}-${e}`,r=Ba.get(t);if(r)return r;const n=new g(o,e);return Ba.set(t,n),n}getValue(){return this._errorType}getErrorType(){return this._errorType}getErrorContent(){return this._errorContent}isEqualType(o){return o.getErrorType()===this.getErrorType()}isError(){return!0}}function qc(i){if(i===null)return 0;if(i!=null&&i.p){const o=i==null?void 0:i.p.body;if(o==null)return 0;const e=o.dataStream;return S.BuildTextUtils.transform.getPlainText(e)}return(i==null?void 0:i.v)||0}var Ut=(i=>(i[i.MIN=0]="MIN",i[i.MAX=1]="MAX",i))(Ut||{}),Me=(i=>(i[i.NORMAL=0]="NORMAL",i[i.MIN=1]="MIN",i[i.MAX=2]="MAX",i))(Me||{});function Jr(){return Intl&&Intl.Collator?new Intl.Collator(void 0,{numeric:!1}).compare:(i,o)=>i.localeCompare(o)}function Kc(i){return i.indexOf("*")>-1||i.indexOf("?")>-1}function Zn(i,o){const e=Zc(o).replace(/~?[*?]/g,r=>r.startsWith("~")?`\\${r.substring(1)}`:r==="*"?".*":r==="?"?".":r);return new RegExp(`^${e}$`).test(i)}function Ia(i){return i.replace(/~?[*?]/g,o=>o.startsWith("~")?o.substring(1):" ")}function Xc(i,o,e){let t=!1;switch(e){case Y.EQUALS:t=Zn(i,o);break;case Y.NOT_EQUAL:t=!Zn(i,o);break;case Y.GREATER_THAN:case Y.GREATER_THAN_OR_EQUAL:t=Zn(i,o)||i>Ia(o);break;case Y.LESS_THAN:case Y.LESS_THAN_OR_EQUAL:t=i<Ia(o);break}return t}function Zc(i){return i.replace(/[.+^${}()|[\]\\]/g,"\\$&")}function gs(i){switch(i){case 1:return 2;case 0:return 0;case-1:return 1;default:return 0}}function ds(i){return i===-2?1:0}function $s(i){let o;switch(i){case Y.EQUALS:o=Y.EQUALS;break;case Y.GREATER_THAN:o=Y.LESS_THAN;break;case Y.GREATER_THAN_OR_EQUAL:o=Y.LESS_THAN_OR_EQUAL;break;case Y.LESS_THAN:o=Y.GREATER_THAN;break;case Y.LESS_THAN_OR_EQUAL:o=Y.GREATER_THAN_OR_EQUAL;break;case Y.NOT_EQUAL:o=Y.NOT_EQUAL;break}return o}/*!
1
+ "use strict";var Bu=Object.defineProperty;var Iu=(i,o,e)=>o in i?Bu(i,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[o]=e;var A=(i,o,e)=>Iu(i,typeof o!="symbol"?o+"":o,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("@univerjs/core"),er=require("rxjs"),Fu=require("@univerjs/rpc");var Mt=(i=>(i.FALSE="FALSE",i.TRUE="TRUE",i))(Mt||{}),pt=(i=>(i[i.SUCCESS=0]="SUCCESS",i[i.ERROR=1]="ERROR",i))(pt||{}),Je=(i=>(i[i.FRONT=0]="FRONT",i[i.BACK=1]="BACK",i))(Je||{});function mi(i,o,e,t,r){for(let n=0,s=i.length;n<s;n++){const a=i[n];if(o!==a.unitId||e!==a.sheetId)continue;const{startRow:u,startColumn:c,endRow:l,endColumn:f}=a.range;if(t>=u&&t<=l&&r>=c&&r<=f)return!0}return!1}var h=(i=>(i.DIV_BY_ZERO="#DIV/0!",i.NAME="#NAME?",i.VALUE="#VALUE!",i.NUM="#NUM!",i.NA="#N/A",i.CYCLE="#CYCLE!",i.REF="#REF!",i.SPILL="#SPILL!",i.CALC="#CALC!",i.ERROR="#ERROR!",i.CONNECT="#GETTING_DATA",i.NULL="#NULL!",i))(h||{});const Kt=new Set(Object.values(h)),Ra=[...new Set(Object.values(h).map(i=>i.length))];var hi=(i=>(i[i.Financial=0]="Financial",i[i.Date=1]="Date",i[i.Math=2]="Math",i[i.Statistical=3]="Statistical",i[i.Lookup=4]="Lookup",i[i.Database=5]="Database",i[i.Text=6]="Text",i[i.Logical=7]="Logical",i[i.Information=8]="Information",i[i.Engineering=9]="Engineering",i[i.Cube=10]="Cube",i[i.Compatibility=11]="Compatibility",i[i.Web=12]="Web",i[i.Array=13]="Array",i[i.Univer=14]="Univer",i[i.User=15]="User",i[i.DefinedName=16]="DefinedName",i))(hi||{}),X=(i=>(i.PLUS="+",i.MINUS="-",i.MULTIPLY="*",i.DIVIDED="/",i.CONCATENATE="&",i.POWER="^",i.EQUALS="=",i.NOT_EQUAL="<>",i.GREATER_THAN=">",i.GREATER_THAN_OR_EQUAL=">=",i.LESS_THAN="<",i.LESS_THAN_OR_EQUAL="<=",i))(X||{}),Y=(i=>(i.EQUALS="=",i.NOT_EQUAL="<>",i.GREATER_THAN=">",i.GREATER_THAN_OR_EQUAL=">=",i.LESS_THAN="<",i.LESS_THAN_OR_EQUAL="<=",i))(Y||{});const Fr=new Map([["<>",4],["<",4],[">=",4],["=",4],[">",4],["<=",4],["&",3],["+",2],["-",2],["/",1],["*",1],["^",0]]),bt=new Set(Fr.keys()),ku=new Set(["=","<>",">",">=","<","<="]);var K=(i=>(i.OPEN_BRACKET="(",i.CLOSE_BRACKET=")",i.COMMA=",",i.SINGLE_QUOTATION="'",i.DOUBLE_QUOTATION='"',i.OPEN_BRACES="{",i.CLOSE_BRACES="}",i.COLON=":",i.OPEN_SQUARE_BRACKET="[",i.CLOSE_SQUARE_BRACKET="]",i))(K||{}),He=(i=>(i.PERCENTAGE="%",i.POUND="#",i))(He||{});const Wn=new Set(["%","#"]);var Ne=(i=>(i.AT="@",i.MINUS="-",i.PLUS="+",i))(Ne||{});const $u=" ",gi=[...Object.values(Y),...Object.values(X),...Object.values(K),...Object.values(He),...Object.values(Ne)];function hr(i){return gi.includes(i)}function di(i){for(const o of gi)if(i.indexOf(o)>-1)return!0;return!1}function Yu(i){return i[0]==="'"&&i[i.length-1]==="'"?i.substring(1,i.length-1):i}function Hu(i){return hr(i)&&i!==K.CLOSE_BRACES&&i!==K.CLOSE_BRACKET&&i!==K.SINGLE_QUOTATION&&i!==K.DOUBLE_QUOTATION||i===" "}const Gu=new Set([X.PLUS,X.MINUS,X.MULTIPLY,X.DIVIDED,X.CONCATENATE,X.POWER,X.EQUALS,X.NOT_EQUAL,X.GREATER_THAN,X.GREATER_THAN_OR_EQUAL,X.LESS_THAN,X.LESS_THAN_OR_EQUAL,K.OPEN_BRACKET,K.COMMA,K.COLON,K.OPEN_BRACES,K.OPEN_SQUARE_BRACKET]);function Wu(i){return Gu.has(i)}const Qu=new Set([X.PLUS,X.MINUS,X.MULTIPLY,X.DIVIDED,X.CONCATENATE,X.POWER,X.EQUALS,X.NOT_EQUAL,X.GREATER_THAN,X.GREATER_THAN_OR_EQUAL,X.LESS_THAN,X.LESS_THAN_OR_EQUAL,K.OPEN_BRACKET,K.COMMA,K.COLON,K.OPEN_BRACES,K.OPEN_SQUARE_BRACKET,He.PERCENTAGE,He.POUND]);function qu(i){return Qu.has(i)}function Ci(i){const o={};return Object.keys(i).forEach(e=>{const t=i[e];if(t==null)return!0;o[e]==null&&(o[e]={}),Object.keys(t).forEach(r=>{const n=t[r];o[e][r]=new S.ObjectMatrix(n)})}),o}function Ku(i){const o={};for(const e in i){const t=i[e];if(t!=null){o[e]==null&&(o[e]={});for(const r in t){const n=t[r],s={};n.forValue((a,u,c)=>{s[a]===void 0&&(s[a]={}),s[a][u]=c}),o[e][r]=s}}}return o}const _i='\\[([^\\[\\]\\/?:"<>|*\\\\]+)\\]',pa=new RegExp(_i),Xu="((?![\\[\\]\\/?*\\\\]).)*!",St="$",xs="\\s*?:\\s*?",qr="[A-Za-z]+",Kr="[1-9][0-9]*",cr=`'?(${_i})?(${Xu})?'?`,is=`\\${St}?${qr}\\${St}?${Kr}`,Zu=`^(${Ne.AT})?${cr}${is}${xs}${is}$`,Na=new RegExp(Zu),zu=`^${cr}\\s*?${is}(${He.POUND})?$`,Va=new RegExp(zu),Ju=`^${cr}\\${St}?${Kr}${xs}\\${St}?${Kr}$`,Oa=new RegExp(Ju),ec=`^${cr}\\${St}?${qr}${xs}\\${St}?${qr}$`,Ma=new RegExp(ec),tc=`^${cr}\\s*?\\${St}?${Kr}$`,Sa=new RegExp(tc),rc=`^${cr}\\s*?\\${St}?${qr}$`,Da=new RegExp(rc),nc="{.*?}",wa=new RegExp(nc,"g");function yr(i){return Va.lastIndex=0,Va.test(i)}function sc(i){return Na.lastIndex=0,Na.test(i)}function Ai(i){return Oa.lastIndex=0,Oa.test(i)}function Ei(i){return Ma.lastIndex=0,Ma.test(i)}function bi(i){return Sa.lastIndex=0,Sa.test(i)}function yi(i){return Da.lastIndex=0,Da.test(i)}function ac(i){return wa.lastIndex=0,wa.test(i)}function Ri(i){return yr(i)||sc(i)||Ai(i)||Ei(i)}const pi={id:"formula.mutation.register-function",type:S.CommandType.MUTATION,handler:()=>!0},Xr={id:"formula.mutation.set-array-formula-data",type:S.CommandType.MUTATION,handler:(i,o)=>!0},ic=/[^0-9]/g,oc=/[^A-Za-z]/g;function gr(i){let o=i[0]==="$";const e=i.substring(1);let t=e.indexOf("$")>-1;return S.Tools.isStringNumber(e)&&o&&!t&&(o=!1,t=!0),o&&t?S.AbsoluteRefType.ALL:o?S.AbsoluteRefType.COLUMN:t?S.AbsoluteRefType.ROW:S.AbsoluteRefType.NONE}function uc(i){const o=i.split("!");o.length>1&&(i=o[o.length-1]);const e=i.split(":");return e.length>1?{startAbsoluteRefType:gr(e[0]),endAbsoluteRefType:gr(e[1])}:{startAbsoluteRefType:gr(e[0])}}function Pa(i=S.AbsoluteRefType.NONE){let o="",e="";return i===S.AbsoluteRefType.ROW?o="$":i===S.AbsoluteRefType.COLUMN?e="$":i===S.AbsoluteRefType.ALL&&(o="$",e="$"),{rowAbsoluteString:o,columnAbsoluteString:e}}function Yt(i){const{startColumn:o,startRow:e,endColumn:t,endRow:r,startAbsoluteRefType:n,endAbsoluteRefType:s,rangeType:a=S.RANGE_TYPE.NORMAL}=i,u=Pa(n),c=Pa(s);if(a===S.RANGE_TYPE.ROW||a===S.RANGE_TYPE.ALL){const m=`${u.rowAbsoluteString}${e+1}`,d=`${c.rowAbsoluteString}${r+1}`;return`${m}:${d}`}if(a===S.RANGE_TYPE.COLUMN){const m=`${u.columnAbsoluteString}${S.Tools.chatAtABC(o)}`,d=`${c.columnAbsoluteString}${S.Tools.chatAtABC(t)}`;return`${m}:${d}`}const l=`${u.columnAbsoluteString}${S.Tools.chatAtABC(o)}${u.rowAbsoluteString}${e+1}`,f=`${c.columnAbsoluteString}${S.Tools.chatAtABC(t)}${c.rowAbsoluteString}${r+1}`;return l===f?l:`${l}:${f}`}function Ni(i,o){return`${Si(i)}!${Yt(o)}`}function Vi(i,o,e){return os(i)||os(o)?`'[${us(i)}]${us(o)}'!${Yt(e)}`:`[${i}]${o}!${Yt(e)}`}function Zr(i){const{unitId:o,sheetName:e,range:t}=i;return o!=null&&o.length>0&&e!=null&&e.length>0?Vi(o,e,t):e!=null&&e.length>0?Ni(e,t):Yt(t)}function kr(i){const o=Number.parseInt(i.replace(ic,""))-1,e=S.Tools.ABCatNum(i.replace(oc,"")),t=gr(i);return{row:o,column:e,absoluteRefType:t}}function _n(i){const o=pa.exec(i);let e="";o!=null&&(e=o[0].trim(),e=La(e.slice(1,e.length-1)),i=i.replace(pa,""));const t=i.indexOf("!");let r="",n="";return t>-1?(r=i.substring(0,t),r[0]==="'"&&r[r.length-1]==="'"&&(r=r.substring(1,r.length-1)),r=La(r),n=i.substring(t+1)):n=i,{refBody:n,sheetName:r,unitId:e}}function Cr(i){const{refBody:o,sheetName:e,unitId:t}=_n(i),r=o.indexOf(":");if(r===-1){const _=kr(o),C=_.row,E=_.column,b=_.absoluteRefType;return{unitId:t,sheetName:e,range:{startRow:C,startColumn:E,endRow:C,endColumn:E,startAbsoluteRefType:b,endAbsoluteRefType:b}}}const n=o.substring(0,r),s=o.substring(r+1),a=kr(n),u=kr(s),c=a.row>u.row?u.row:a.row,l=a.column>u.column?u.column:a.column,f=a.row>u.row?a.row:u.row,m=a.column>u.column?a.column:u.column;let d=S.RANGE_TYPE.NORMAL;return Number.isNaN(c)&&Number.isNaN(f)?d=S.RANGE_TYPE.COLUMN:Number.isNaN(l)&&Number.isNaN(m)&&(d=S.RANGE_TYPE.ROW),{unitId:t,sheetName:e,range:{startRow:c,startColumn:l,endRow:f,endColumn:m,startAbsoluteRefType:a.absoluteRefType,endAbsoluteRefType:u.absoluteRefType,rangeType:d}}}const cc=["LOG10"];function dr(i){const o=Oi(i);if(!Ri(o)||cc.includes(o.toUpperCase().trim()))return!1;const{range:e}=Cr(o);return!(e.endColumn>=16384)}function Oi(i){const o=[];let e=!1;for(let t=0,r=i.length;t<r;t++){const n=i[t];if(n===$u&&!e)o.push(n);else{if(!e&&(n===Ne.AT||n===Ne.MINUS||n===Ne.PLUS))continue;o.push(n),e=!0}}return o.join("")}function lc(i,o){const e=(i==null?void 0:i.split(","))||[];return i===""||e.length===0?[]:Mi(i)?e.map(n=>{const s=Cr(n);return{unitId:s.unitId,sheetId:o(s.sheetName),range:s.range,sheetName:s.sheetName}}):[]}function Mi(i){return((i==null?void 0:i.split(","))||[]).every(e=>dr(e.trim()))}function os(i){return i.length===0?!1:!!(di(i)||fc(i)||mc(i)||hc(i)||/[\s!$%^&*()+\-=\[\]{};':"\\|,.<>\/?()]/.test(i))}function Si(i){return os(i)?`'${us(i)}'`:i}function us(i){return i.replace(/'/g,"''")}function La(i){return i.replace(/''/g,"'")}function fc(i){const o=i.match(/[1-9][0-9]{0,6}/);return/^[A-Z]+[1-9][0-9]{0,6}$/.test(i)&&o!==null}function mc(i){return/^(R(-?[0-9]+)?C(-?[0-9]+)?|C(-?[0-9]+)?|R(-?[0-9]+)?)$/.test(i)}function hc(i){return!new RegExp("^\\p{Letter}","u").test(i.charAt(0))}var gc=Object.defineProperty,dc=Object.getOwnPropertyDescriptor,Cc=(i,o,e,t)=>{for(var r=t>1?void 0:t?dc(o,e):o,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(o,e,r):s(r))||r);return t&&r&&gc(o,e,r),r},_c=(i,o)=>(e,t)=>o(e,t,i);exports.DefinedNamesService=class extends S.Disposable{constructor(e){super();A(this,"_definedNameMap",{});A(this,"_update$",new er.Subject);A(this,"update$",this._update$.asObservable());A(this,"_currentRange",{unitId:"",sheetId:"",range:{startRow:0,endRow:0,startColumn:0,endColumn:0}});A(this,"_currentRange$",new er.Subject);A(this,"currentRange$",this._currentRange$.asObservable());A(this,"_focusRange$",new er.Subject);A(this,"focusRange$",this._focusRange$.asObservable());this._univerInstanceService=e}dispose(){this._definedNameMap={}}getWorksheetByRef(e,t){var n;const{sheetName:r}=_n(t);return(n=this._univerInstanceService.getUnit(e))==null?void 0:n.getSheetBySheetName(r)}focusRange(e,t){const r=this.getValueById(e,t);r!=null&&this._focusRange$.next({...r,unitId:e})}setCurrentRange(e){this._currentRange=e,this._currentRange$.next(e)}getCurrentRange(){return this._currentRange}getCurrentRangeForString(){return Yt(this._currentRange.range)}registerDefinedNames(e,t){this._definedNameMap[e]=t,this._update()}registerDefinedName(e,t){this._definedNameMap[e]==null&&(this._definedNameMap[e]={}),this._definedNameMap[e][t.id]=t,this._update()}removeDefinedName(e,t){var r;(r=this._definedNameMap[e])==null||delete r[t],this._update()}removeUnitDefinedName(e){delete this._definedNameMap[e],this._update()}getDefinedNameMap(e){return this._definedNameMap[e]}getValueByName(e,t){var n;const r=this._definedNameMap[e];return r==null?null:(n=Array.from(Object.values(r)).filter(s=>s.name===t))==null?void 0:n[0]}getValueById(e,t){var r;return(r=this._definedNameMap[e])==null?void 0:r[t]}hasDefinedName(e){return this._definedNameMap[e]==null?!1:(Array.from(Object.values(this._definedNameMap[e])).length||0)!==0}_update(){this._update$.next(null)}};exports.DefinedNamesService=Cc([_c(0,S.IUniverInstanceService)],exports.DefinedNamesService);const Xt=S.createIdentifier("univer.formula.defined-names.service"),Ac=(i,o)=>{const{unitId:e,id:t}=o;return{...i.get(Xt).getValueById(e,t),unitId:e}},An={id:"formula.mutation.set-defined-name",type:S.CommandType.MUTATION,handler:(i,o)=>{if(o==null)return!1;const e=i.get(Xt),{id:t,unitId:r,name:n,formulaOrRefString:s,comment:a,hidden:u,localSheetId:c}=o;return e.registerDefinedName(r,{id:t,name:n.trim(),formulaOrRefString:s.trim(),comment:a==null?void 0:a.trim(),hidden:u,localSheetId:c}),!0}},js={id:"formula.mutation.remove-defined-name",type:S.CommandType.MUTATION,handler:(i,o)=>{if(o==null)return!1;const e=i.get(Xt),{unitId:t,id:r}=o;return e.removeDefinedName(t,r),!0}},En={id:"formula.mutation.set-feature-calculation",type:S.CommandType.MUTATION,handler:()=>!0},bn={id:"formula.mutation.remove-feature-calculation",type:S.CommandType.MUTATION,handler:()=>!0},Us={id:"formula.mutation.set-formula-calculation-start",type:S.CommandType.MUTATION,handler:()=>!0},Ts={id:"formula.mutation.set-formula-calculation-stop",type:S.CommandType.MUTATION,handler:()=>!0},zr={id:"formula.mutation.set-formula-calculation-notification",type:S.CommandType.MUTATION,handler:()=>!0},vs={id:"formula.mutation.set-formula-calculation-result",type:S.CommandType.MUTATION,handler:()=>!0},Bs={id:"formula.mutation.set-formula-data",type:S.CommandType.MUTATION,handler:(i,o)=>!0},yn={id:"formula.mutation.set-other-formula",type:S.CommandType.MUTATION,handler:()=>!0},Rn={id:"formula.mutation.remove-other-formula",type:S.CommandType.MUTATION,handler:()=>!0},Di={id:"formula.mutation.set-super-table",type:S.CommandType.MUTATION,handler:()=>!0},wi={id:"formula.mutation.remove-super-table",type:S.CommandType.MUTATION,handler:()=>!0},Is={id:"formula.mutation.set-super-table-option",type:S.CommandType.MUTATION,handler:()=>!0};class ht{constructor(o){A(this,"_cache");this._cache=new S.LRUMap(o)}set(o,e){const t=this._hash(o);this._cache.set(t,e)}get(o){const e=this._hash(o);return this._cache.get(e)}clear(){this._cache.clear()}_hash(o){return o.length<=64?o:S.hashAlgorithm(o).toString()}}const nt="P_1",Vt="R_1",nr="L_1",Rr="LR_1",Pi="LO_1",Ec="LET",_r="LAMBDA",bc="CUBE",yc=new Set(["RAND","RANDBETWEEN","NOW","TODAY"]),cs=new ht(1e5);function Ht(i){const o=cs.get(i);if(o)return o;const e=Cr(i);return cs.set(i,e),Cr(i)}function Rc(){cs.clear()}var Te=(i=>(i[i.NORMAL=0]="NORMAL",i[i.NUMBER=1]="NUMBER",i[i.STRING=2]="STRING",i[i.FUNCTION=3]="FUNCTION",i[i.REFERENCE=4]="REFERENCE",i[i.ARRAY=5]="ARRAY",i[i.DEFINED_NAME=6]="DEFINED_NAME",i))(Te||{});function ls(i){let o="";for(const e of i)typeof e=="string"?o+=e:o+=e.token;return o}class ae{constructor(){A(this,"_parent");A(this,"_token",Vt);A(this,"_children",[]);A(this,"_lambdaId");A(this,"_functionDefinitionPrivacyVar");A(this,"_lambdaParameter","");A(this,"_startIndex",-1);A(this,"_endIndex",-1);A(this,"_definedNames",[])}dispose(){var o;this._children.forEach(e=>{typeof e!="string"&&e.dispose()}),(o=this._functionDefinitionPrivacyVar)==null||o.clear(),this._functionDefinitionPrivacyVar=null,this._children=[],this._parent=null,this._definedNames=[]}getDefinedNames(){return this._definedNames}getStartIndex(){return this._startIndex}getLambdaId(){return this._lambdaId}setLambdaId(o){this._lambdaId=o}getFunctionDefinitionPrivacyVar(){return this._functionDefinitionPrivacyVar}setLambdaPrivacyVar(o){this._functionDefinitionPrivacyVar=o}getLambdaParameter(){return this._lambdaParameter}setLambdaParameter(o){this._lambdaParameter=o}getParent(){return this._parent}setParent(o){this._parent=o}getChildren(){return this._children}setChildren(o){this._children=o}addChildren(o){this._children.push(o)}addChildrenFirst(o){this._children.unshift(o)}getToken(){return this._token}setToken(o){this._token=o}setIndex(o,e){this._startIndex=o,this._endIndex=e}setDefinedNames(o){this._definedNames=o}hasDefinedNames(){return this._definedNames.length>0}replaceChild(o,e){const t=this._getIndexInParent(o);t!=null&&(this.getChildren().splice(t,1,e),e.setParent(this))}changeToParent(o){const e=this.getParent();e&&e.removeChild(this),this.setParent(o),o.getChildren().push(this)}removeChild(o){const e=this._getIndexInParent(o);e!=null&&this.getChildren().splice(e,1)}serialize(){const o=this.getToken(),e=this.getChildren(),t=[],r=e.length;for(let n=0;n<r;n++){const s=e[n];s instanceof ae?t.push(s.serialize()):t.push(s)}return{token:o,st:this._startIndex,ed:this._endIndex,children:t}}_getIndexInParent(o){const e=this.getChildren(),t=e.length;for(let r=0;r<t;r++)if(e[r]===o)return r}}const Li=2e3,Qn=new ht(Li),qn=new ht(Li);class pn extends S.Disposable{constructor(){super(...arguments);A(this,"_currentLexerNode",new ae);A(this,"_upLevel",0);A(this,"_segment","");A(this,"_bracketState",[]);A(this,"_squareBracketState",0);A(this,"_bracesState",0);A(this,"_singleQuotationState",0);A(this,"_doubleQuotationState",0);A(this,"_lambdaState",!1);A(this,"_colonState",!1);A(this,"_formulaErrorCount",0);A(this,"_tableBracketState",!1)}dispose(){this._resetTemp(),this._currentLexerNode.dispose(),Qn.clear(),qn.clear()}getUpLevel(){return this._upLevel}isColonClose(){return this._colonState===!1}isColonOpen(){return this._colonState===!0}isDoubleQuotationClose(){return this._doubleQuotationState===0}isLambdaOpen(){return this._lambdaState===!0}isLambdaClose(){return this._lambdaState===!1}isSingleQuotationClose(){return this._singleQuotationState===0}isBracesClose(){return this._bracesState===0}isBracketClose(){return this._bracketState.length===0}isSquareBracketClose(){return this._squareBracketState===0}getCurrentLexerNode(){return this._currentLexerNode}getFunctionAndParameter(e,t){const r=this._getCurrentParamIndex(e,t);if(r==null||r===h.VALUE)return;const n=r[0];if(typeof n=="string")return;let s=n.getParent(),a=n;for(;s;){const u=s.getToken();if(u!==nt&&!hr(u)&&s.getStartIndex()!==-1){const c=s.getChildren().indexOf(a);return{functionName:u,paramIndex:c}}a=s,s=s.getParent()}}checkIfAddBracket(e){let t=0,r=e.length-1,n=e[r];for(;(n===K.CLOSE_BRACKET||n===" ")&&r>=0;)n===K.CLOSE_BRACKET&&t++,n=e[--r];const s=this._getCurrentParamIndex(e,e.length-2);if(s==null||s===h.VALUE)return 0;const a=s[0];if(typeof a=="string")return 0;let u=a.getParent(),c=0;for(s[1]===K.OPEN_BRACKET&&c++;u;){const l=u.getToken();l!==nt&&l!==K.COLON&&u.getStartIndex()!==-1&&l.toUpperCase()!==_r&&(t===0?c+=1:t--),u=u.getParent()}return c}sequenceNodesBuilder(e){const t=qn.get(e);if(t)return[...t];const r=this._getSequenceArray(e);if(r.length===0)return;const n=this.getSequenceNode(r);return qn.set(e,[...n]),n}convertRefersToAbsolute(e,t,r,n=""){const s=this.sequenceNodesBuilder(e);if(s==null)return e;let a="";e.substring(0,1)===X.EQUALS&&(a=X.EQUALS);for(let u=0,c=s.length;u<c;u++){const l=s[u];if(typeof l!="string"&&l.nodeType===Te.REFERENCE){const{token:f,endIndex:m}=l,d=Ht(f);if(d==null)continue;const{range:_,sheetName:C,unitId:E}=d,b={..._,startAbsoluteRefType:t,endAbsoluteRefType:r},R=Zr({range:b,unitId:E,sheetName:C||n}),p=R.length-f.length;s[u]={...l,token:R,endIndex:m+p};for(let V=u+1;V<c;V++){const M=s[V];typeof M!="string"&&(M.startIndex+=p,M.endIndex+=p)}}}return`${a}${ls(s)}`}moveFormulaRefOffset(e,t,r,n=!1){const s=this.sequenceNodesBuilder(e);if(s==null)return e;const a=[];for(let u=0,c=s.length;u<c;u++){const l=s[u];if(typeof l=="string"||l.nodeType!==Te.REFERENCE){a.push(l);continue}const{token:f}=l,m=Ht(f),{sheetName:d,unitId:_}=m;let C=m.range;if(!n&&C.startAbsoluteRefType===S.AbsoluteRefType.ALL&&C.endAbsoluteRefType===S.AbsoluteRefType.ALL){a.push(l);continue}else C=S.moveRangeByOffset(C,t,r,n);let E="";S.isValidRange(C)?E=Zr({range:C,unitId:_,sheetName:d}):E=h.REF,a.push({...l,token:E})}return`=${ls(a)}`}_formulaSpellCheck(){if(this._currentLexerNode.getChildren().length===0)return!0;const e=this._currentLexerNode.getChildren()[0];return!!(e instanceof ae||bt.has(e)||Wn.has(e)||e===Ne.AT||e===K.COMMA||e===K.COLON||e===K.OPEN_BRACKET)}getSequenceNode(e){const t=[];let r=!1;for(let n=0,s=e.length;n<s;n++){const a=e[n],u=e[n-1],{segment:c,currentString:l}=a;if(l===K.DOUBLE_QUOTATION&&(r=!0),(c!==""||n===0)&&n!==s-1){t.push(l);continue}let f=(u==null?void 0:u.segment)||"";const m=n-f.length;let d=n-1;const _=n-1;if(n===s-1&&this._isLastMergeString(l)&&(f+=l,d+=1),f===""||Fr.has(f)){t.push(l);continue}const C=f.trim(),E=Oi(C);r===!0&&C[C.length-1]===K.DOUBLE_QUOTATION&&C[0]!==K.OPEN_BRACES?(r=!1,this._processPushSequenceNode(t,Te.STRING,f,m,d,_)):yr(E)&&dr(E)?this._processPushSequenceNode(t,Te.REFERENCE,f,m,d,_):S.Tools.isStringNumber(C)?this._processPushSequenceNode(t,Te.NUMBER,f,m,d,_):C.length>0&&this._processPushSequenceNode(t,Te.FUNCTION,f,m,d,_),(n!==s-1||!this._isLastMergeString(l))&&t.push(l)}return this._mergeSequenceNodeReference(t)}_processPushSequenceNode(e,t,r,n,s,a){this._pushSequenceNode(e,{nodeType:t,token:r,startIndex:n,endIndex:s},a)}_getCurrentParamIndex(e,t){return this._nodeMaker(e,void 0,t)}_isLastMergeString(e){return e===K.DOUBLE_QUOTATION||S.Tools.isStringNumber(e)||!hr(e)}_mergeSequenceNodeReference(e){const t=[],r=e.length;let n=0;for(;n<r;){const s=e[n];if(typeof s=="string"){const a=e[n-1];if(s.trim()===K.CLOSE_BRACES&&a!=null&&typeof a!="string"&&a.nodeType===Te.FUNCTION&&a.token.trim().substring(0,1)===K.OPEN_BRACES){a.nodeType=Te.ARRAY,a.token+=s,a.endIndex+=s.length,n++;continue}t.push(s)}else{const a=e[n+1],u=e[n+2];a===K.COLON&&typeof s!="string"&&u!=null&&typeof u!="string"&&dr((s.token+a+u.token).trim())&&(s.nodeType=Te.REFERENCE,s.token+=a+u.token,s.endIndex=u.endIndex,n+=2),t.push(s)}n++}return this._minusSplitSequenceNode(t)}_minusSplitSequenceNode(e){const t=[];for(const r of e){if(typeof r!="string"){const s=r.token.match(/^(\s*([-@+]\s*)+)(.*)$/);if(s){const a=s[1],u=s[3];if(dr(u.trim())){const c=a.length,l=r.startIndex,f=r.startIndex+c-1,m={nodeType:Te.NORMAL,token:a,startIndex:l,endIndex:f},d={nodeType:Te.REFERENCE,token:u,startIndex:f+1,endIndex:r.endIndex};t.push(m),t.push(d);continue}}}t.push(r)}return t}_pushSequenceNode(e,t,r){const n=r-t.startIndex+1;e.splice(e.length-n,n,t)}nodeMakerTest(e){return this._nodeMaker(e)}treeBuilder(e,t=!0,r,n){if(t===!0){const m=Qn.get(e),d=n==null?void 0:n(e);if(m&&!d)return m}this._resetCurrentLexerNode(),this._currentLexerNode.setToken(Vt);const s=[];let a=this._nodeMaker(e,s);if(a===h.VALUE||s.length===0)return a;let u=!1,c="",l=[];if(r){const{hasDefinedName:m,sequenceString:d,definedNames:_}=r(s);u=m,c=d,l=_}if(u&&(this._resetCurrentLexerNode(),this._currentLexerNode.setToken(Vt),a=this._nodeMaker(`=${c}`),a===h.VALUE))return a;const f=this._getTopNode(this._currentLexerNode);if(f&&(this._currentLexerNode=f),t){if(!this._suffixExpressionHandler(this._currentLexerNode))return h.VALUE;Qn.set(e,this._currentLexerNode)}return u&&this._currentLexerNode.setDefinedNames(l),this._currentLexerNode}_suffixExpressionHandler(e){var u;const t=e.getChildren();if(!t)return!1;const r=t.length,n=[],s=[];let a=!0;for(let c=0;c<r;c++){const l=t[c];if(l instanceof ae)a=this._suffixExpressionHandler(l),n.push(l);else{const f=l.trim();if(f==="")continue;if(bt.has(f)){if(f===X.PLUS&&this._deletePlusForPreNode(t[c-1]))continue;if(f!==X.PLUS&&f!==X.MINUS&&this._deletePlusForPreNode(t[c-1]))return!1;for(;s.length>0;){const m=(u=s[s.length-1])==null?void 0:u.trim();if(!m||m===K.OPEN_BRACKET)break;const d=Fr.get(m),_=Fr.get(f);if(!d||!_)break;if(_>=d)n.push(s.pop());else break}s.push(l)}else if(f===K.OPEN_BRACKET)s.push(l);else if(f===K.CLOSE_BRACKET)this._processSuffixExpressionCloseBracket(n,s,t,c);else{if(this._checkCloseBracket(t[c-1]))return!1;n.push(l)}}}return a?this._processSuffixExpressionRemain(n,s,e):!1}_processSuffixExpressionRemain(e,t,r){const n=e.length,s=e[n-1];for(;t.length>0;){const a=t.pop();if(!(s instanceof ae)&&(a===K.OPEN_BRACKET||a===K.CLOSE_BRACKET))return!1;e.push(a)}return r.setChildren(e),!0}_processSuffixExpressionCloseBracket(e,t,r,n){var s;if(this._checkOpenBracket(r[n-1])||this._checkOperator(r[n-1]))return!1;for(;t.length>0;){const a=(s=t[t.length-1])==null?void 0:s.trim();if(!a)break;if(a===K.OPEN_BRACKET){t.pop();break}e.push(t.pop())}}_checkCloseBracket(e){return e===K.CLOSE_BRACKET||e instanceof ae}_checkOpenBracket(e){return e===K.OPEN_BRACKET}_checkOperator(e){return e==null||e instanceof ae?!1:bt.has(e)}_deletePlusForPreNode(e){if(e==null)return!0;if(!(e instanceof ae)){const t=e.trim();if(bt.has(t)||t===K.OPEN_BRACKET)return!0}return!1}_resetCurrentLexerNode(){this._currentLexerNode=new ae}_resetSegment(){this._segment=""}_openBracket(e=0){this._bracketState.push(e)}_closeBracket(){this._bracketState.pop()}_openSquareBracket(){this._squareBracketState+=1}_closeSquareBracket(){this._squareBracketState-=1}_getCurrentBracket(){const e=this._bracketState;return e[e.length-1]}_changeCurrentBracket(e){const t=this._bracketState;t[t.length-1]=e}_openBraces(){this._bracesState+=1}_closeBraces(){this._bracesState-=1}_openSingleQuotation(){this._singleQuotationState+=1}_closeSingleQuotation(){this._singleQuotationState-=1}_openDoubleQuotation(){this._doubleQuotationState+=1}_closeDoubleQuotation(){this._doubleQuotationState-=1}_openLambda(){this._lambdaState=!0}_closeLambda(){this._lambdaState=!1}_openColon(e){this._upLevel=e,this._colonState=!0}_closeColon(){this._upLevel=0,this._colonState=!1}_isTableBracket(){return this._tableBracketState}_openTableBracket(){this._tableBracketState=!0}_closeTableBracket(){this._tableBracketState=!1}_formalErrorOccurred(){this._formulaErrorCount+=1}_hasFormalError(){return this._formulaErrorCount>0}_getLastChildCurrentLexerNode(){const e=this._currentLexerNode.getChildren();if(e&&e.length>0){const t=e[e.length-1];if(t instanceof ae)return t}return!1}_getLastChildCurrent(){const e=this._currentLexerNode.getChildren();return e&&e.length>0?e[e.length-1]:!1}_setParentCurrentLexerNode(){const e=this._currentLexerNode.getParent();return e?(this._currentLexerNode=e,!0):!1}_setAncestorCurrentLexerNode(){var r,n,s,a,u,c;const e=(r=this._currentLexerNode)==null?void 0:r.getParent();let t=!1;if(e&&e.getToken()===nr){if((n=e==null?void 0:e.getParent())!=null&&n.getParent()){const l=(a=(s=this._currentLexerNode.getParent())==null?void 0:s.getParent())==null?void 0:a.getParent();l&&(this._currentLexerNode=l),t=!0}}else if(e!=null&&e.getParent()){const l=(u=this._currentLexerNode.getParent())==null?void 0:u.getParent();l&&(this._currentLexerNode=l),t=!0}for(let l=0;l<this._upLevel;l++){const f=(c=this._currentLexerNode)==null?void 0:c.getParent();f&&(this._currentLexerNode=f),this._currentLexerNode?t=!0:t=!1}return t}_segmentCount(){return this._segment.trim().length}_pushSegment(e){this._segment+=e}_pushNodeToChildren(e,t=!1){let r=e;if(r!==""){const n=this._currentLexerNode.getChildren();if(!(r instanceof ae)&&this.isColonOpen()){const s=new ae;s.setToken(r),s.setParent(this._currentLexerNode),r=s}t?n.unshift(r):n.push(r)}this.isColonOpen()&&(this._setAncestorCurrentLexerNode(),this._closeColon())}_setCurrentLexerNode(e,t=!1){this._pushNodeToChildren(e,t),e.setParent(this._currentLexerNode),this._currentLexerNode=e}_newAndPushCurrentLexerNode(e,t,r=!1){const n=new ae;n.setToken(e),n.setIndex(t-e.length,t-1),this._setCurrentLexerNode(n,r)}_getTopNode(e){let t=e;for(;t!=null&&t.getParent();)t=t.getParent();return t}_removeLastChild(){this._currentLexerNode.getChildren().splice(-1)}_formulaErrorLastTokenCheck(e,t){const r=this._findPreviousToken(e,t)||"",n=e.length-1===t;if(!n&&this._isOperatorToken(r)||n&&Wu(r))return!0;if(Wn.has(r)){const s=this._findSecondLastNonSpaceToken(e,t);if(s==null||qu(s))return!0}return!1}_findPreviousToken(e,t){let r=t;for(;r>=0;){const n=e[r];if(n!==" ")return n;r--}}_findSecondLastNonSpaceToken(e,t){let r=t,n=0;for(;r>=0;){const s=e[r];if(s!==" "&&(n++,n===2))return s;r--}return null}_findNextToken(e,t){let r=t;for(;r>=0;){const n=e[r];if(n!==" ")return n;r++}}_unexpectedEndingTokenExcludeOperator(e){return e===K.OPEN_BRACKET||e===K.COMMA||e===X.EQUALS||e===""}_unexpectedEndingToken(e){return!!(this._isOperatorToken(e)||this._unexpectedEndingTokenExcludeOperator(e))}_isOperatorToken(e){return!!bt.has(e)}_getSequenceArray(e){const t=[];return this._nodeMaker(e,t),t}_resetTemp(){this._currentLexerNode=new ae,this._upLevel=0,this._segment="",this._bracketState=[],this._bracesState=0,this._singleQuotationState=0,this._doubleQuotationState=0,this._lambdaState=!1,this._colonState=!1,this._formulaErrorCount=0}_checkErrorState(){return!!(this._bracketState.length>0||this._bracesState>0||this._singleQuotationState>0||this._doubleQuotationState>0||this._hasFormalError())}_checkSimilarErrorToken(e,t,r){let n=t;if(e!==He.POUND)return!0;let s=r[++n];for(;s===" ";)s=r[++n];return!!hr(s)}_checkIfErrorObject(e,t){return!!this._findErrorObject(e,t)}_findErrorObject(e,t){for(let r=0;r<Ra.length;r++){const n=Ra[r],s=t.slice(e,e+n).join("").toUpperCase();if(Kt.has(s))return s}}_nodeMaker(e,t,r){let n=e.replace(/\r\n$/,"").replace(/\r/g," ").replace(/\n/g," ");n.substring(0,1)===X.EQUALS&&(n=n.substring(1));const s=n.split(""),a=s.length;let u=0;for(this._resetTemp(),this._formulaErrorLastTokenCheck(s,a-1)&&this._formalErrorOccurred();u<a;){const c=s[u];if(r===u)return[this._currentLexerNode,c];if(c===He.POUND&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()&&this._checkIfErrorObject(u,s)){const l=this._findErrorObject(u,s);if(l==null)return h.VALUE;this._pushNodeToChildren(l);for(let f=0;f<l.length;f++){const m=s[u];this._pushSegment(m),this._addSequenceArray(t,m,u),u++}this._resetSegment();continue}else if(c===K.OPEN_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())if(this._segmentCount()>0||this.isLambdaOpen()){this.isLambdaClose()&&(this._newAndPushCurrentLexerNode(this._segment,u),this._resetSegment()),this._openBracket(1),this._closeLambda();const l=s[u+1];if(l&&l===K.CLOSE_BRACKET){if(!this._setParentCurrentLexerNode()&&u!==a-1)return h.VALUE;this._addSequenceArray(t,c,u),u++,this._addSequenceArray(t,l,u),u++,this._closeBracket();continue}else l&&this._newAndPushCurrentLexerNode(nt,u)}else this._pushNodeToChildren(c),this._openBracket(0),this._resetSegment();else if(c===K.CLOSE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()){this._formulaErrorLastTokenCheck(s,u-1)&&this._formalErrorOccurred(),this._pushNodeToChildren(this._segment),this._resetSegment();const l=this._getCurrentBracket();if(l===0)this._pushNodeToChildren(c);else if(l===1){const f=s[u+1];if(f&&f===K.OPEN_BRACKET){if(!this._setParentCurrentLexerNode()&&u!==a-1)return h.VALUE;this._newAndPushCurrentLexerNode(nr,u,!0),this._openLambda()}else if(!this._setAncestorCurrentLexerNode()&&u!==a-1)return h.VALUE}else return h.VALUE;this._closeBracket()}else if(c===K.OPEN_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()){if(this._pushSegment(c),this._openBraces(),!this._formulaSpellCheck())return h.VALUE}else if(c===K.CLOSE_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._pushSegment(c),this._pushNodeToChildren(this._segment),this._resetSegment(),this._closeBraces();else if(c===K.OPEN_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._segment.length>0&&this._openTableBracket(),this._pushSegment(c),this._openSquareBracket();else if(c===K.CLOSE_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._closeSquareBracket(),this.isSquareBracketClose()?(this._pushSegment(c),this._isTableBracket()&&(this._pushNodeToChildren(this._segment),this._resetSegment()),this._closeTableBracket()):this._pushSegment(c);else if(c===K.DOUBLE_QUOTATION&&this.isSingleQuotationClose()&&this.isSquareBracketClose()){if(this.isDoubleQuotationClose())this._openDoubleQuotation();else{const l=s[u+1];l&&l===K.DOUBLE_QUOTATION?u++:this._closeDoubleQuotation()}this._pushSegment(c)}else if(c===K.SINGLE_QUOTATION&&this.isDoubleQuotationClose()){if(this.isSingleQuotationClose())this._openSingleQuotation(),this._segmentCount()===0&&this._resetSegment();else{const l=s[u+1];if(l&&l===K.SINGLE_QUOTATION){this._pushSegment(c),this._addSequenceArray(t,c,u),u++,this._pushSegment(l),this._addSequenceArray(t,l,u),u++;continue}else this._closeSingleQuotation()}this._pushSegment(c)}else if(c===K.COMMA&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){this._formulaErrorLastTokenCheck(s,u-1)&&this._formalErrorOccurred();const l=this._getCurrentBracket();if(l===1||l==null){if(this._pushNodeToChildren(this._segment),this._resetSegment(),!this._setParentCurrentLexerNode()&&u!==a-1&&l!=null)return h.VALUE;this._newAndPushCurrentLexerNode(nt,u)}else{const f=new ae;f.setToken(bc);const m=new ae;m.setToken(nt),m.changeToParent(f);const d=this._currentLexerNode.getParent();if(d&&d.getToken()===K.COLON){const _=d.getParent();if(!_)return h.VALUE;d.changeToParent(m),_.setChildren([]),f.changeToParent(_)}else return h.VALUE;this._changeCurrentBracket(1),this._pushNodeToChildren(this._segment),this._resetSegment(),this._currentLexerNode=f,this._newAndPushCurrentLexerNode(nt,u)}}else if(c===K.COLON&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){const l=new ae;l.setToken(c);const f=new ae;f.setToken(nt),f.setParent(l);const m=new ae;m.setToken(nt),m.setParent(l),l.getChildren().push(f,m);let d=l,_=0;if(this._segmentCount()>0){let C,E,b=0;const R=this._segment.trim(),p=R[0],V=R[1];if(p===Ne.MINUS&&(C=new ae,C.setToken(Ne.MINUS),b++),(p===Ne.AT||V===Ne.AT)&&(E=new ae,E.setToken(Ne.AT),C&&(C.addChildren(E),E.setParent(C)),b++),b>0&&(this._segment=R.slice(b)),_=b,E)if(E.addChildren(l),l.setParent(E),E.getParent()){const D=E.getParent();D&&(d=D)}else d=E;else C&&(d=C,C.addChildren(l),l.setParent(C));const M=new ae;M.setToken(this._segment),M.setParent(f),f.getChildren().push(M),this._resetSegment()}else{const C=this._getLastChildCurrentLexerNode();C&&C.changeToParent(f)}this._setCurrentLexerNode(d),this._currentLexerNode=m,this._openColon(_)}else if(Wn.has(c)&&this._checkSimilarErrorToken(c,u,s)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()&&this.isBracesClose()){this._pushNodeToChildren(this._segment);const l=new ae;l.setToken(c);const f=this._getLastChildCurrent();f instanceof ae?f.changeToParent(l):f!==!1&&(l.getChildren().push(f),this._removeLastChild()),this._pushNodeToChildren(l),l.setParent(this._currentLexerNode),this._resetSegment()}else if(bt.has(c)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()&&this.isBracesClose()){let l=this._segment.trim();if(c===X.MINUS&&l===""){const f=this._findPreviousToken(s,u-1)||"",m=this._findNextToken(s,u+1)||"";if(this._unexpectedEndingTokenExcludeOperator(f)&&this._isOperatorToken(m)){this._pushNodeToChildren("0"),this._pushNodeToChildren(X.MINUS),this._addSequenceArray(t,c,u),this._resetSegment(),u++;continue}else if(this._unexpectedEndingToken(f))if(m===X.PLUS){this._pushSegment(X.MINUS),this._addSequenceArray(t,c,u),this._addSequenceArray(t,X.PLUS,u+1),u+=2;continue}else{this._pushSegment(X.MINUS),this._addSequenceArray(t,c,u),u++;continue}}else if(this._segment.length>0&&this._isScientificNotation(s,u,c)){this._pushSegment(c),this._addSequenceArray(t,c,u),u++;continue}else this._segment.length>0&&l===""?l=this._segment:(this._pushNodeToChildren(this._segment),l="");if(c===X.LESS_THAN||c===X.GREATER_THAN){const f=s[u+1];if(f&&bt.has(c+f)){this._pushNodeToChildren(l+c+f),this._resetSegment(),this._addSequenceArray(t,c,u),u++,this._addSequenceArray(t,f,u),u++;continue}else this._pushNodeToChildren(l+c)}else this._pushNodeToChildren(l+c);this._resetSegment()}else this._pushSegment(c);this._addSequenceArray(t,c,u),u++}if(this._pushNodeToChildren(this._segment),this._checkErrorState())return h.VALUE}_isScientificNotation(e,t,r){const n=e[t-2];if(n&&Number.isNaN(Number(n))||!(r===X.MINUS||r===X.PLUS))return!1;const s=e[t+1];if(s&&Number.isNaN(Number(s)))return!1;const a=e[t-1];return a&&a.toUpperCase()==="E"}_addSequenceArray(e,t,r){e==null||e.push({segment:this._segment,currentString:t,cur:r,currentLexerNode:this._currentLexerNode})}}function pc(i,o,e,t,r,n,s){const a=(s==null?void 0:s.f)||"",u=(s==null?void 0:s.si)||"",c=S.isFormulaString(a),l=S.isFormulaId(u),f=i.getValue(r,n),m=(f==null?void 0:f.f)||"",d=(f==null?void 0:f.si)||"";function _(){var C;if(S.isFormulaString(m)&&S.isFormulaId(d)){const E=(C=e==null?void 0:e[d])==null?void 0:C.f;E?t.set(d,E):t.set(d,m)}}c&&l?(d!==u&&_(),i.setValue(r,n,{f:a,si:u}),e[u]={f:a,r,c:n},o.setValue(r,n,{f:a,si:u})):c&&!l?(m!==a&&_(),i.setValue(r,n,{f:a}),o.setValue(r,n,{f:a})):!c&&l?(d!==u&&_(),i.setValue(r,n,{f:"",si:u})):!c&&!l&&i.getValue(r,n)&&(_(),i.realDeleteValue(r,n),o.setValue(r,n,null))}function Nc(i,o,e,t){const r=i==null?void 0:i.getValue(e,t);if(r==null)return!0;const n=[];i.forValue((l,f,m)=>{l===e&&f===t||S.Rectangle.intersects(m,r)&&n.push(m)});const{startRow:s,startColumn:a,endRow:u,endColumn:c}=r;for(let l=s;l<=u;l++)for(let f=a;f<=c;f++){let m=!1;const d=S.cellToRange(l,f);n.some(_=>S.Rectangle.contains(_,d)?(m=!0,!0):!1),m||o.realDeleteValue(l,f)}}var Vc=Object.defineProperty,Oc=Object.getOwnPropertyDescriptor,Mc=(i,o,e,t)=>{for(var r=t>1?void 0:t?Oc(o,e):o,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(o,e,r):s(r))||r);return t&&r&&Vc(o,e,r),r},xa=(i,o)=>(e,t)=>o(e,t,i);exports.FormulaDataModel=class extends S.Disposable{constructor(e,t){super();A(this,"_arrayFormulaRange",{});A(this,"_arrayFormulaCellData",{});this._univerInstanceService=e,this._lexerTreeBuilder=t}dispose(){super.dispose(),this._arrayFormulaRange={},this._arrayFormulaCellData={}}clearPreviousArrayFormulaCellData(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;Object.keys(r).forEach(n=>{var l,f,m,d;const s=r[n],a=(f=(l=this._arrayFormulaRange)==null?void 0:l[t])==null?void 0:f[n];if(a==null)return!0;const u=new S.ObjectMatrix(a);let c=new S.ObjectMatrix;((m=this._arrayFormulaCellData[t])==null?void 0:m[n])!=null&&(c=new S.ObjectMatrix((d=this._arrayFormulaCellData[t])==null?void 0:d[n])),s.forValue((_,C)=>{const E=u.getValue(_,C);if(E==null)return!0;const{startRow:b,startColumn:R,endRow:p,endColumn:V}=E;for(let M=b;M<=p;M++)for(let D=R;D<=V;D++)c.setValue(M,D,null);u.realDeleteValue(_,C)}),this._arrayFormulaCellData[t]&&(this._arrayFormulaCellData[t][n]=c.getData())})})}mergeArrayFormulaCellData(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;this._arrayFormulaRange[t]==null&&(this._arrayFormulaRange[t]={}),this._arrayFormulaCellData[t]==null&&(this._arrayFormulaCellData[t]={}),Object.keys(r).forEach(n=>{var c,l;const s=r[n],a=new S.ObjectMatrix((c=this._arrayFormulaRange[t])==null?void 0:c[n]),u=new S.ObjectMatrix((l=this._arrayFormulaCellData[t])==null?void 0:l[n]);s.forValue((f,m)=>{const d=a==null?void 0:a.getValue(f,m);if(d==null)return!0;const{startRow:_,startColumn:C,endRow:E,endColumn:b}=d;for(let R=_;R<=E;R++)for(let p=C;p<=b;p++)u.setValue(R,p,null)}),s.forValue((f,m,d)=>{u.setValue(f,m,d)}),this._arrayFormulaCellData[t]&&(this._arrayFormulaCellData[t][n]=u.getData())})})}getFormulaData(){const e={},t=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET);return t.length===0||t.forEach(r=>{const n=r.getUnitId();e[n]={},r.getSheets().forEach(a=>{const u=a.getCellMatrix(),c=a.getSheetId();fs(e,n,c,u)})}),e}getSheetFormulaData(e,t){const r={},n=this._univerInstanceService.getUnit(e);if(n==null)return{};r[e]={};const s=n.getSheetBySheetId(t);if(s==null)return{};const a=s.getCellMatrix();return fs(r,e,t,a),r[e][t]}getArrayFormulaRange(){return this._arrayFormulaRange}setArrayFormulaRange(e){this._arrayFormulaRange=e}getArrayFormulaCellData(){return this._arrayFormulaCellData}setArrayFormulaCellData(e){this._arrayFormulaCellData=e}mergeArrayFormulaRange(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;this._arrayFormulaRange[t]||(this._arrayFormulaRange[t]={}),Object.keys(r).forEach(n=>{var u;const s=new S.ObjectMatrix(r[n]),a=new S.ObjectMatrix((u=this._arrayFormulaRange[t])==null?void 0:u[n]);s.forValue((c,l,f)=>{a.setValue(c,l,f)}),this._arrayFormulaRange[t]&&(this._arrayFormulaRange[t][n]=a.getData())})})}deleteArrayFormulaRange(e,t,r,n){var u;const s=(u=this._arrayFormulaRange[e])==null?void 0:u[t];if(s==null)return;const a=new S.ObjectMatrix(s);a.getValue(r,n)&&(a.realDeleteValue(r,n),this._arrayFormulaRange[e]&&(this._arrayFormulaRange[e][t]=a.getData()))}getCalculateData(){const e=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET),t={},r={};for(const n of e){const s=n.getUnitId(),a=n.getSheets(),u={},c={};for(const l of a){const f=l.getSheetId(),m=l.getConfig();u[f]={cellData:new S.ObjectMatrix(m.cellData),rowCount:m.rowCount,columnCount:m.columnCount,rowData:m.rowData,columnData:m.columnData,defaultRowHeight:m.defaultRowHeight,defaultColumnWidth:m.defaultColumnWidth},c[l.getName()]=l.getSheetId()}t[s]=u,r[s]=c}return{allUnitData:t,unitSheetNameMap:r}}updateFormulaData(e,t,r){const n=new S.ObjectMatrix(r),s=this._getSheetFormulaIdMap(e,t),a=new Map,u=this.getFormulaData();u[e]==null&&(u[e]={});const c=u[e];c[t]==null&&(c[t]={});const l=new S.ObjectMatrix(c[t]||{}),f=new S.ObjectMatrix;return n.forValue((m,d,_)=>{pc(l,f,s,a,m,d,_)}),l.forValue((m,d,_)=>{const C=(_==null?void 0:_.f)||"",E=(_==null?void 0:_.si)||"";if(S.isFormulaId(E)){const b=s==null?void 0:s[E],R=a.get(E);if(b&&!S.isFormulaString(C)){const p=b.f,V=d-b.c,M=m-b.r;l.setValue(m,d,{f:p,si:E,x:V,y:M}),f.setValue(m,d,{f:p,si:E,x:V,y:M})}else if(typeof R=="string"){const p=(_==null?void 0:_.x)||0,V=(_==null?void 0:_.y)||0,M=this._lexerTreeBuilder.moveFormulaRefOffset(R,p,V);a.set(E,{r:m,c:d,f:M}),l.setValue(m,d,{f:M,si:E}),f.setValue(m,d,{f:M,si:E})}else if(typeof R=="object"){const p=d-R.c,V=m-R.r;l.setValue(m,d,{f:R.f,si:E,x:p,y:V}),f.setValue(m,d,{f:R.f,si:E,x:p,y:V})}}}),f.getMatrix()}updateArrayFormulaRange(e,t,r){var u;const n=(u=this._arrayFormulaRange[e])==null?void 0:u[t];if(!n)return;const s=new S.ObjectMatrix(n);new S.ObjectMatrix(r).forValue((c,l,f)=>{s.realDeleteValue(c,l)})}updateArrayFormulaCellData(e,t,r){var l,f;const n=(l=this._arrayFormulaRange[e])==null?void 0:l[t];if(!n)return;const s=new S.ObjectMatrix(n),a=(f=this._arrayFormulaCellData[e])==null?void 0:f[t];if(!a)return;const u=new S.ObjectMatrix(a);new S.ObjectMatrix(r).forValue((m,d,_)=>{Nc(s,u,m,d)})}getFormulaStringByCell(e,t,r,n){const s=this._univerInstanceService.getUnit(n);if(s==null)return null;const a=s.getSheetBySheetId(r);if(a==null)return null;const u=a.getCellMatrix(),c=u.getValue(e,t);if(c==null)return null;const{f:l,si:f}=c;if(S.isFormulaString(l))return l;if(S.isFormulaId(f)){let m=null;return u.forValue((d,_,C)=>{if(C==null)return!0;const{f:E,si:b}=C;if(S.isFormulaString(E)&&f===b)return m=this._lexerTreeBuilder.moveFormulaRefOffset(E,t-_,e-d),!1}),m}return null}getFormulaDirtyRanges(){const e=this.getFormulaData(),t=[];for(const r in e){const n=e[r];if(!n)continue;const s=this._univerInstanceService.getUnit(r);if(s)for(const a in n){const u=n[a];if(!u)continue;const c=s.getSheetBySheetId(a);if(!c)continue;const l={};for(const f of Object.keys(u)){const m=Number(f);for(const d in u[m]){const _=Number(d),C=c.getCellRaw(m,_),E=S.isFormulaString(C==null?void 0:C.f)||S.isFormulaId(C==null?void 0:C.si),b=(C==null?void 0:C.v)===void 0;if(!(E&&b))continue;l[_]||(l[_]=[]);const R=l[_].slice(-1)[0];R&&R.endRow===m-1?R.endRow=m:l[_].push({startRow:m,endRow:m})}}for(const f in l){const m=l[f];for(let d=0;d<m.length;d++){const _=m[d];t.push({unitId:r,sheetId:a,range:{rangeType:S.RANGE_TYPE.NORMAL,startRow:_.startRow,endRow:_.endRow,startColumn:Number(f),endColumn:Number(f)}})}}}}return t}_getSheetFormulaIdMap(e,t){const r={},n=this._univerInstanceService.getUnit(e);if(n==null)return r;const s=n.getSheetBySheetId(t);return s==null||s.getCellMatrix().forValue((u,c,l)=>{if(l==null)return!0;const{f,si:m}=l;S.isFormulaString(f)&&S.isFormulaId(m)&&(r[m]={f,r:u,c})}),r}};exports.FormulaDataModel=Mc([xa(0,S.IUniverInstanceService),xa(1,S.Inject(pn))],exports.FormulaDataModel);function fs(i,o,e,t){i[o]||(i[o]={}),i[o][e]||(i[o][e]={});const r=new Map,n=new S.ObjectMatrix(i[o][e]);t.forValue((a,u,c)=>{const l=(c==null?void 0:c.f)||"",f=(c==null?void 0:c.si)||"",m=S.isFormulaString(l),d=S.isFormulaId(f);m&&d?(n.setValue(a,u,{f:l,si:f}),r.set(f,{f:l,r:a,c:u})):m&&!d?n.setValue(a,u,{f:l}):!m&&d&&n.setValue(a,u,{f:"",si:f})}),n.forValue((a,u,c)=>{const l=(c==null?void 0:c.f)||"",f=(c==null?void 0:c.si)||"";if(S.isFormulaId(f)&&!S.isFormulaString(l)){const m=r.get(f);if(m){const d=m.f,_=u-m.c,C=a-m.r;n.setValue(a,u,{f:d,si:f,x:_,y:C})}else n.realDeleteValue(a,u)}});const s=n.getMatrix();return{[o]:{[e]:s}}}const Sc=class ms{constructor(o,e){this.low=o,this.high=e}clone(){return new ms(this.low,this.high)}get max(){return this.clone()}less_than(o){return this.low<o.low||this.low===o.low&&this.high<o.high}equal_to(o){return this.low===o.low&&this.high===o.high}intersect(o){return!this.not_intersect(o)}not_intersect(o){return this.high<o.low||o.high<this.low}merge(o){return new ms(this.low===void 0?o.low:this.low<o.low?this.low:o.low,this.high===void 0?o.high:this.high>o.high?this.high:o.high)}output(){return[this.low,this.high]}static comparable_max(o,e){return o.merge(e)}static comparable_less_than(o,e){return o<e}},we=0,_e=1;class Lt{constructor(o=void 0,e=void 0,t=null,r=null,n=null,s=_e){if(this.left=t,this.right=r,this.parent=n,this.color=s,this.item={key:o,value:e},o&&o instanceof Array&&o.length===2&&!Number.isNaN(o[0])&&!Number.isNaN(o[1])){let[a,u]=o;a>u&&([a,u]=[u,a]),this.item.key=new Sc(a,u)}this.max=this.item.key?this.item.key.max:void 0}isNil(){return this.item.key===void 0&&this.item.value===void 0&&this.left===null&&this.right===null&&this.color===_e}_value_less_than(o){return this.item.value&&o.item.value&&this.item.value.less_than?this.item.value.less_than(o.item.value):this.item.value<o.item.value}less_than(o){return this.item.value===this.item.key&&o.item.value===o.item.key?this.item.key.less_than(o.item.key):this.item.key.less_than(o.item.key)||this.item.key.equal_to(o.item.key)&&this._value_less_than(o)}_value_equal(o){return this.item.value&&o.item.value&&this.item.value.equal_to?this.item.value.equal_to(o.item.value):this.item.value===o.item.value}equal_to(o){return this.item.value===this.item.key&&o.item.value===o.item.key?this.item.key.equal_to(o.item.key):this.item.key.equal_to(o.item.key)&&this._value_equal(o)}intersect(o){return this.item.key.intersect(o.item.key)}copy_data(o){this.item.key=o.item.key,this.item.value=o.item.value}update_max(){if(this.max=this.item.key?this.item.key.max:void 0,this.right&&this.right.max){const o=this.item.key.constructor.comparable_max;this.max=o(this.max,this.right.max)}if(this.left&&this.left.max){const o=this.item.key.constructor.comparable_max;this.max=o(this.max,this.left.max)}}not_intersect_left_subtree(o){const e=this.item.key.constructor.comparable_less_than;let t=this.left.max.high!==void 0?this.left.max.high:this.left.max;return e(t,o.item.key.low)}not_intersect_right_subtree(o){const e=this.item.key.constructor.comparable_less_than;let t=this.right.max.low!==void 0?this.right.max.low:this.right.item.key.low;return e(o.item.key.high,t)}}class Fs{constructor(){this.root=null,this.nil_node=new Lt}get size(){let o=0;return this.tree_walk(this.root,()=>o++),o}get keys(){let o=[];return this.tree_walk(this.root,e=>o.push(e.item.key.output?e.item.key.output():e.item.key)),o}get values(){let o=[];return this.tree_walk(this.root,e=>o.push(e.item.value)),o}get items(){let o=[];return this.tree_walk(this.root,e=>o.push({key:e.item.key.output?e.item.key.output():e.item.key,value:e.item.value})),o}isEmpty(){return this.root==null||this.root===this.nil_node}clear(){this.root=null}insert(o,e=o){if(o===void 0)return;let t=new Lt(o,e,this.nil_node,this.nil_node,null,we);return this.tree_insert(t),this.recalc_max(t),t}exist(o,e=o){let t=new Lt(o,e);return!!this.tree_search(this.root,t)}remove(o,e=o){let t=new Lt(o,e),r=this.tree_search(this.root,t);return r&&this.tree_delete(r),r}search(o,e=(t,r)=>t===r?r.output():t){let t=new Lt(o),r=[];return this.tree_search_interval(this.root,t,r),r.map(n=>e(n.item.value,n.item.key))}intersect_any(o){let e=new Lt(o);return this.tree_find_any_interval(this.root,e)}forEach(o){this.tree_walk(this.root,e=>o(e.item.key,e.item.value))}map(o){const e=new Fs;return this.tree_walk(this.root,t=>e.insert(t.item.key,o(t.item.value,t.item.key))),e}*iterate(o,e=(t,r)=>t===r?r.output():t){let t;for(o?t=this.tree_search_nearest_forward(this.root,new Lt(o)):this.root&&(t=this.local_minimum(this.root));t;)yield e(t.item.value,t.item.key),t=this.tree_successor(t)}recalc_max(o){let e=o;for(;e.parent!=null;)e.parent.update_max(),e=e.parent}tree_insert(o){let e=this.root,t=null;if(this.root==null||this.root===this.nil_node)this.root=o;else{for(;e!==this.nil_node;)t=e,o.less_than(e)?e=e.left:e=e.right;o.parent=t,o.less_than(t)?t.left=o:t.right=o}this.insert_fixup(o)}insert_fixup(o){let e,t;for(e=o;e!==this.root&&e.parent.color===we;)e.parent===e.parent.parent.left?(t=e.parent.parent.right,t.color===we?(e.parent.color=_e,t.color=_e,e.parent.parent.color=we,e=e.parent.parent):(e===e.parent.right&&(e=e.parent,this.rotate_left(e)),e.parent.color=_e,e.parent.parent.color=we,this.rotate_right(e.parent.parent))):(t=e.parent.parent.left,t.color===we?(e.parent.color=_e,t.color=_e,e.parent.parent.color=we,e=e.parent.parent):(e===e.parent.left&&(e=e.parent,this.rotate_right(e)),e.parent.color=_e,e.parent.parent.color=we,this.rotate_left(e.parent.parent)));this.root.color=_e}tree_delete(o){let e,t;o.left===this.nil_node||o.right===this.nil_node?e=o:e=this.tree_successor(o),e.left!==this.nil_node?t=e.left:t=e.right,t.parent=e.parent,e===this.root?this.root=t:(e===e.parent.left?e.parent.left=t:e.parent.right=t,e.parent.update_max()),this.recalc_max(t),e!==o&&(o.copy_data(e),o.update_max(),this.recalc_max(o)),e.color===_e&&this.delete_fixup(t)}delete_fixup(o){let e=o,t;for(;e!==this.root&&e.parent!=null&&e.color===_e;)e===e.parent.left?(t=e.parent.right,t.color===we&&(t.color=_e,e.parent.color=we,this.rotate_left(e.parent),t=e.parent.right),t.left.color===_e&&t.right.color===_e?(t.color=we,e=e.parent):(t.right.color===_e&&(t.color=we,t.left.color=_e,this.rotate_right(t),t=e.parent.right),t.color=e.parent.color,e.parent.color=_e,t.right.color=_e,this.rotate_left(e.parent),e=this.root)):(t=e.parent.left,t.color===we&&(t.color=_e,e.parent.color=we,this.rotate_right(e.parent),t=e.parent.left),t.left.color===_e&&t.right.color===_e?(t.color=we,e=e.parent):(t.left.color===_e&&(t.color=we,t.right.color=_e,this.rotate_left(t),t=e.parent.left),t.color=e.parent.color,e.parent.color=_e,t.left.color=_e,this.rotate_right(e.parent),e=this.root));e.color=_e}tree_search(o,e){if(!(o==null||o===this.nil_node))return e.equal_to(o)?o:e.less_than(o)?this.tree_search(o.left,e):this.tree_search(o.right,e)}tree_search_nearest_forward(o,e){let t,r=o;for(;r&&r!==this.nil_node;)r.less_than(e)?r.intersect(e)?(t=r,r=r.left):r=r.right:((!t||r.less_than(t))&&(t=r),r=r.left);return t||null}tree_search_interval(o,e,t){o!=null&&o!==this.nil_node&&(o.left!==this.nil_node&&!o.not_intersect_left_subtree(e)&&this.tree_search_interval(o.left,e,t),o.intersect(e)&&t.push(o),o.right!==this.nil_node&&!o.not_intersect_right_subtree(e)&&this.tree_search_interval(o.right,e,t))}tree_find_any_interval(o,e){let t=!1;return o!=null&&o!==this.nil_node&&(o.left!==this.nil_node&&!o.not_intersect_left_subtree(e)&&(t=this.tree_find_any_interval(o.left,e)),t||(t=o.intersect(e)),!t&&o.right!==this.nil_node&&!o.not_intersect_right_subtree(e)&&(t=this.tree_find_any_interval(o.right,e))),t}local_minimum(o){let e=o;for(;e.left!=null&&e.left!==this.nil_node;)e=e.left;return e}local_maximum(o){let e=o;for(;e.right!=null&&e.right!==this.nil_node;)e=e.right;return e}tree_successor(o){let e,t,r;if(o.right!==this.nil_node)e=this.local_minimum(o.right);else{for(t=o,r=o.parent;r!=null&&r.right===t;)t=r,r=r.parent;e=r}return e}rotate_left(o){let e=o.right;o.right=e.left,e.left!==this.nil_node&&(e.left.parent=o),e.parent=o.parent,o===this.root?this.root=e:o===o.parent.left?o.parent.left=e:o.parent.right=e,e.left=o,o.parent=e,o!=null&&o!==this.nil_node&&o.update_max(),e=o.parent,e!=null&&e!==this.nil_node&&e.update_max()}rotate_right(o){let e=o.left;o.left=e.right,e.right!==this.nil_node&&(e.right.parent=o),e.parent=o.parent,o===this.root?this.root=e:o===o.parent.left?o.parent.left=e:o.parent.right=e,e.right=o,o.parent=e,o!==null&&o!==this.nil_node&&o.update_max(),e=o.parent,e!=null&&e!==this.nil_node&&e.update_max()}tree_walk(o,e){o!=null&&o!==this.nil_node&&(this.tree_walk(o.left,e),e(o),this.tree_walk(o.right,e))}testRedBlackProperty(){let o=!0;return this.tree_walk(this.root,function(e){e.color===we&&(e.left.color===_e&&e.right.color===_e||(o=!1))}),o}testBlackHeightProperty(o){let e=0,t=0,r=0;if(o.color===_e&&e++,o.left!==this.nil_node?t=this.testBlackHeightProperty(o.left):t=1,o.right!==this.nil_node?r=this.testBlackHeightProperty(o.right):r=1,t!==r)throw new Error("Red-black height property violated");return e+=t,e}}class Dc{constructor(){A(this,"_cache",new Map);A(this,"_continueBuildingCache",new Map)}set(o,e,t,r,n){if(!this.shouldContinueBuildingCache(o,e,t,n))return;let s=this._cache.get(o);s==null&&(s=new Map,this._cache.set(o,s));let a=s.get(e);a==null&&(a=new Map,s.set(e,a));let u=a.get(t);u==null&&(u=new Map,a.set(t,u));let c=u.get(r);c==null&&(c=new Set,u.set(r,c)),c.add(n)}getCellValuePositions(o,e,t){var r,n;return(n=(r=this._cache.get(o))==null?void 0:r.get(e))==null?void 0:n.get(t)}getCellPositions(o,e,t,r,n){var a,u,c;const s=(c=(u=(a=this._cache.get(o))==null?void 0:a.get(e))==null?void 0:u.get(t))==null?void 0:c.get(r);return s&&[...s].filter(l=>n.some(([f,m])=>l>=f&&l<=m))}setContinueBuildingCache(o,e,t,r,n){if(t===-1||r===-1||n===-1)return;let s=this._continueBuildingCache.get(o);s==null&&(s=new Map,this._continueBuildingCache.set(o,s));let a=s.get(e);a==null&&(a=new Map,s.set(e,a));let u=a.get(t);if(u==null){u=new Fs,u.insert([r,n]),a.set(t,u);return}this._handleNewInterval(u,r,n)}shouldContinueBuildingCache(o,e,t,r){var a,u;if(t===-1||r===-1)return!1;const n=(u=(a=this._continueBuildingCache.get(o))==null?void 0:a.get(e))==null?void 0:u.get(t);return n?n.search([r,r]).length===0:!0}canUseCache(o,e,t,r,n){var f,m;const s=(m=(f=this._continueBuildingCache.get(o))==null?void 0:f.get(e))==null?void 0:m.get(t);if(t===-1||r===-1||n===-1||!s)return{rowsInCache:[],rowsNotInCache:[]};const a=s.search([r,n]);if(a.length===0)return{rowsInCache:[],rowsNotInCache:[]};a.sort((d,_)=>d[0]-_[0]);const u=[],c=[];let l=r;for(let d=0;d<a.length;d++){const[_,C]=a[d];if(l>=_){if(n<=C){u.push([l,n]);break}u.push([l,C]),l=C+1,d===a.length-1&&l<=n&&c.push([l,n])}else{if(n>C){u.push([_,C]),c.push([l,_-1]),l=C+1,d===a.length-1&&l<=n&&c.push([l,n]);continue}u.push([_,n]),c.push([l,_-1])}}return{rowsInCache:u,rowsNotInCache:c}}clear(){this._cache.clear(),this._continueBuildingCache.clear()}_handleNewInterval(o,e,t){let r=o.search([e,t]);if(r.length===0){const a=[e-1<0?0:e-1,t+1];if(r=o.search(a),r.length===0){o.insert([e,t]);return}}let n=e,s=t;for(const a of r)n=Math.min(n,a[0]),s=Math.max(s,a[1]),o.remove(a);o.insert([n,s])}}const yt=new Dc,Nn="engine-formula.config",xi=1,wc="CYCLE_REFERENCE_COUNT",ja={};var Pc=Object.defineProperty,Lc=Object.getOwnPropertyDescriptor,xc=(i,o,e,t)=>{for(var r=t>1?void 0:t?Lc(o,e):o,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(o,e,r):s(r))||r);return t&&r&&Pc(o,e,r),r},Ua=(i,o)=>(e,t)=>o(e,t,i);exports.FormulaCurrentConfigService=class extends S.Disposable{constructor(e,t){super();A(this,"_unitData",{});A(this,"_unitStylesData",{});A(this,"_arrayFormulaCellData",{});A(this,"_arrayFormulaRange",{});A(this,"_formulaData",{});A(this,"_sheetNameMap",{});A(this,"_forceCalculate",!1);A(this,"_clearDependencyTreeCache",{});A(this,"_dirtyRanges",[]);A(this,"_dirtyNameMap",{});A(this,"_dirtyDefinedNameMap",{});A(this,"_dirtyUnitFeatureMap",{});A(this,"_dirtyUnitOtherFormulaMap",{});A(this,"_excludedCell");A(this,"_sheetIdToNameMap",{});A(this,"_executeUnitId","");A(this,"_executeSubUnitId","");this._univerInstanceService=e,this._localeService=t}dispose(){this._unitData={},this._unitStylesData={},this._formulaData={},this._arrayFormulaCellData={},this._arrayFormulaRange={},this._sheetNameMap={},this._dirtyRanges=[],this._dirtyNameMap={},this._dirtyDefinedNameMap={},this._dirtyUnitFeatureMap={},this._excludedCell={},this._sheetIdToNameMap={},this._dirtyUnitOtherFormulaMap={}}getExecuteUnitId(){return this._executeUnitId}getExecuteSubUnitId(){return this._executeSubUnitId}setExecuteUnitId(e){this._executeUnitId=e}setExecuteSubUnitId(e){this._executeSubUnitId=e}getExcludedRange(){return this._excludedCell}getUnitData(){return this._unitData}getUnitStylesData(){return this._unitStylesData}getFormulaData(){return this._formulaData}getArrayFormulaCellData(){return this._arrayFormulaCellData}getArrayFormulaRange(){return this._arrayFormulaRange}getSheetNameMap(){return this._sheetNameMap}isForceCalculate(){return this._forceCalculate}getDirtyRanges(){return this._dirtyRanges}getDirtyNameMap(){return this._dirtyNameMap}getDirtyDefinedNameMap(){return this._dirtyDefinedNameMap}getDirtyUnitFeatureMap(){return this._dirtyUnitFeatureMap}getDirtyUnitOtherFormulaMap(){return this._dirtyUnitOtherFormulaMap}getSheetName(e,t){return this._sheetIdToNameMap[e]==null?"":this._sheetIdToNameMap[e][t]||""}getClearDependencyTreeCache(){return this._clearDependencyTreeCache}getLocale(){return this._localeService.getCurrentLocale()}getSheetsInfo(){const e=this._univerInstanceService.getCurrentUnitForType(S.UniverInstanceType.UNIVER_SHEET),{id:t,sheetOrder:r}=e.getSnapshot();return{sheetOrder:r,sheetNameMap:this._sheetIdToNameMap[t]}}getSheetRowColumnCount(e,t){const r=this._univerInstanceService.getUnit(e),n=r==null?void 0:r.getSheetBySheetId(t),s=n==null?void 0:n.getSnapshot();if(!s)return{rowCount:0,columnCount:0};const{rowCount:a,columnCount:u}=s;return{rowCount:a,columnCount:u}}load(e){if(e.allUnitData&&e.unitSheetNameMap&&e.unitStylesData)this._unitData=e.allUnitData,this._unitStylesData=e.unitStylesData,this._sheetNameMap=e.unitSheetNameMap;else{const{allUnitData:t,unitSheetNameMap:r,unitStylesData:n}=this._loadSheetData();this._unitData=t,this._unitStylesData=n,this._sheetNameMap=r}this._formulaData=e.formulaData,this._arrayFormulaCellData=Ci(e.arrayFormulaCellData),this._arrayFormulaRange=e.arrayFormulaRange,this._forceCalculate=e.forceCalculate,this._clearDependencyTreeCache=e.clearDependencyTreeCache||{},this._dirtyRanges=e.dirtyRanges,this._dirtyNameMap=e.dirtyNameMap,this._dirtyDefinedNameMap=e.dirtyDefinedNameMap,this._dirtyUnitFeatureMap=e.dirtyUnitFeatureMap,this._dirtyUnitOtherFormulaMap=e.dirtyUnitOtherFormulaMap,this._excludedCell=e.excludedCell,this._mergeNameMap(this._sheetNameMap,this._dirtyNameMap)}getDirtyData(){return{forceCalculation:this._forceCalculate,dirtyRanges:this._dirtyRanges,dirtyNameMap:this._dirtyNameMap,dirtyDefinedNameMap:this._dirtyDefinedNameMap,dirtyUnitFeatureMap:this._dirtyUnitFeatureMap,dirtyUnitOtherFormulaMap:this._dirtyUnitOtherFormulaMap,clearDependencyTreeCache:this._clearDependencyTreeCache}}loadDirtyRangesAndExcludedCell(e,t){this._dirtyRanges=e,this._excludedCell=t,this._dirtyNameMap={}}registerUnitData(e){this._unitData=e}registerFormulaData(e){this._formulaData=e}registerSheetNameMap(e){this._sheetNameMap=e}_mergeNameMap(e,t){Object.keys(t).forEach(r=>{t[r]&&Object.keys(t[r]).forEach(n=>{e[r]==null&&(e[r]={}),e[r][t[r][n]]=n})}),this._sheetIdToNameMap={},Object.keys(e).forEach(r=>{Object.keys(e[r]).forEach(n=>{this._sheetIdToNameMap[r]==null&&(this._sheetIdToNameMap[r]={}),this._sheetIdToNameMap[r][e[r][n]]=n})})}_loadSheetData(){const e=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET),t=this._univerInstanceService.getCurrentUnitForType(S.UniverInstanceType.UNIVER_SHEET),r=t==null?void 0:t.getActiveSheet();this._executeUnitId=t==null?void 0:t.getUnitId(),this._executeSubUnitId=r==null?void 0:r.getSheetId();const n={},s={},a={};for(const u of e){const c=u.getUnitId(),l=u.getSheets(),f={},m={};for(const d of l){const _=d.getSheetId(),C=d.getConfig();f[_]={cellData:new S.ObjectMatrix(C.cellData),rowCount:C.rowCount,columnCount:C.columnCount,rowData:C.rowData,columnData:C.columnData,defaultRowHeight:C.defaultRowHeight,defaultColumnWidth:C.defaultColumnWidth},m[d.getName()]=d.getSheetId()}n[c]=f,s[c]=u.getStyles(),a[c]=m}return{allUnitData:n,unitStylesData:s,unitSheetNameMap:a}}};exports.FormulaCurrentConfigService=xc([Ua(0,S.IUniverInstanceService),Ua(1,S.Inject(S.LocaleService))],exports.FormulaCurrentConfigService);const gt=S.createIdentifier("univer.formula.current-data.service");var jc=Object.defineProperty,Uc=Object.getOwnPropertyDescriptor,Tc=(i,o,e,t)=>{for(var r=t>1?void 0:t?Uc(o,e):o,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(o,e,r):s(r))||r);return t&&r&&jc(o,e,r),r},Kn=(i,o)=>(e,t)=>o(e,t,i);exports.Lexer=class extends S.Disposable{constructor(o,e,t){super(),this._definedNamesService=o,this._lexerTreeBuilder=e,this._formulaCurrentConfigService=t}treeBuilder(o,e=!0){return this._lexerTreeBuilder.treeBuilder(o,e,this._injectDefinedName.bind(this),this._simpleCheckDefinedName.bind(this))}_simpleCheckDefinedName(o){const e=this._formulaCurrentConfigService.getDirtyDefinedNameMap(),t=this._formulaCurrentConfigService.getExecuteUnitId();if(t!=null&&e[t]!=null){const r=Object.keys(e[t]);for(let n=0,s=r.length;n<s;n++){const a=r[n];if(o.indexOf(a)>-1)return!0}}return!1}_checkDefinedNameDirty(o){const e=this._formulaCurrentConfigService.getDirtyDefinedNameMap(),t=this._formulaCurrentConfigService.getExecuteUnitId();if(t!=null&&e[t]!=null){const r=Object.keys(e[t]);for(let n=0,s=r.length;n<s;n++)if(r[n]===o)return!0}return!1}_injectDefinedName(o){const e=this._formulaCurrentConfigService.getExecuteUnitId();if(e==null)return{sequenceString:"",hasDefinedName:!1,definedNames:[]};const t=this._lexerTreeBuilder.getSequenceNode(o);let r="",n=!1;const s=[];for(let a=0,u=t.length;a<u;a++){const c=t[a];if(typeof c=="string"){r+=c;continue}const{nodeType:l,token:f}=c;if(l===Te.REFERENCE||l===Te.FUNCTION){const m=this._definedNamesService.getValueByName(e,f);if(m){let d=m.formulaOrRefString;d.substring(0,1)===X.EQUALS&&(d=d.substring(1)),r+=d,s.push(m.name),n=!0}else this._checkDefinedNameDirty(f)?(r+=h.NAME,n=!0,s.push(f)):r+=f}else r+=f}return{sequenceString:r,hasDefinedName:n,definedNames:s}}};exports.Lexer=Tc([Kn(0,Xt),Kn(1,S.Inject(pn)),Kn(2,gt)],exports.Lexer);function $r(i){if(i==null)return!0;const{v:o,f:e,si:t,p:r}=i;return!(!(o==null||typeof o=="string"&&o.length===0)||e!=null&&e.length>0||t!=null&&t.length>0||r!=null)}function ji(i,o,e,t,r){var s;const n=Object.keys(r);for(const a of n){const u=r[a],c=(s=u==null?void 0:u[t])==null?void 0:s[e];if(c==null)continue;const l=c.getValue(i,o);if(l!=null)return l}}const vc=["$","£","¥","¤","֏","؋","৳","฿","៛","₡","₦","₩","₪","₫","€","₭","₮","₱","₲","₴","₸","₹","₺","₼","₽","₾","₿"],Bc={currency:2,date:4,datetime:5,error:11,fraction:7,general:0,grouped:11,number:1,percent:6,scientific:8,text:9,time:5,unknown:11};function Ic(i,o,e){var u,c;if(i==null||o==null)return o;const t=(e==null?void 0:e.getStyleByCell(i))||i.s,r=(e==null?void 0:e.getStyleByCell(o))||o.s;if(t==null||r==null||typeof t!="object"||typeof r!="object")return o;const n=(u=t==null?void 0:t.n)==null?void 0:u.pattern,s=(c=r==null?void 0:r.n)==null?void 0:c.pattern;if(n==null||s==null)return o;const a=n||s;return r.n.pattern=a,o}const hs=new ht(1e5);function Ta(i){const o=hs.get(i);if(o!==void 0)return o;const e=kc(i);return hs.set(i,e),e}function Fc(){hs.clear()}function kc(i){if($c(i))return 3;const o=S.numfmt.getInfo(i).type||"unknown";return Bc[o]}function $c(i){return!!vc.find(o=>i.includes(o))&&i.startsWith("_(")}function jr(i,o,e){if(i==="")return o;if(o==="")return i;const t=Ta(i),r=Ta(o);return e===X.PLUS||e===X.MINUS?t===4&&r===4||t===11&&r===11?"":o:e===X.MULTIPLY||e===X.DIVIDED?t===6&&r===6||t===7&&r===7||t===8&&r===8||t===9&&r===9?o:"":i||o}const Yc=new Map([[S.LocaleType.EN_US,"$"],[S.LocaleType.RU_RU,"₽"],[S.LocaleType.VI_VN,"₫"],[S.LocaleType.ZH_CN,"¥"],[S.LocaleType.ZH_TW,"NT$"]]);function va(i){return Yc.get(i)||"$"}function Ye(i,o=2){let e=o;o>127&&(e=127);let t="";return e>0&&(t=`.${"0".repeat(e)}`),`"${va(i)}"#,##0${t}_);[Red]("${va(i)}"#,##0${t})`}function Hc(i,o,e=2){return S.numfmt.format(Ye(i,e),o)}const ks=new ht(1e5);function Gc(i){let o=i;o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1));const e=ks.get(o);if(e)return{isNumberPattern:!0,value:e.value,pattern:e.pattern};const t=S.numfmt.parseNumber(o);if(t&&t.z)return Xn(o,t.v,t.z);const r=S.numfmt.parseDate(o);if(r&&r.z)return Xn(o,r.v,r.z);const n=S.numfmt.parseTime(o);return n&&n.z?Xn(o,n.v,n.z):{isNumberPattern:!1}}function Xn(i,o,e){return ks.set(i,{value:o,pattern:e}),{isNumberPattern:!0,value:o,pattern:e}}function Wc(){ks.clear()}class Vn{constructor(){A(this,"pattern","")}dispose(){}getPattern(){return this.pattern}setPattern(o){this.pattern=o}isError(){return!1}isAsyncObject(){return!1}isAsyncArrayObject(){return!1}isReferenceObject(){return!1}isArray(){return!1}isValueObject(){return!1}isEqualType(o){return!1}}class dt extends Vn{constructor(o){super(),this._rawValue=o}isValueObject(){return!0}toUnitRange(){return{range:{startColumn:-1,startRow:-1,endRow:-1,endColumn:-1},sheetId:"",unitId:""}}getValue(){return 0}getArrayValue(){return[]}setValue(o){}setArrayValue(o){}isCube(){return!1}isString(){return!1}isNumber(){return!1}isBoolean(){return!1}isLambda(){return!1}isError(){return!1}isNull(){return!1}sum(){return g.create(h.VALUE)}max(){return g.create(h.VALUE)}min(){return g.create(h.VALUE)}count(){return g.create(h.VALUE)}countA(){return g.create(h.VALUE)}countBlank(){return g.create(h.VALUE)}getNegative(){return g.create(h.VALUE)}getReciprocal(){return g.create(h.VALUE)}plus(o){return g.create(h.VALUE)}minus(o){return g.create(h.VALUE)}multiply(o){return g.create(h.VALUE)}divided(o){return g.create(h.VALUE)}mod(o){return g.create(h.VALUE)}map(o){return g.create(h.NAME)}mapValue(o){return g.create(h.NAME)}compare(o,e,t=!1){return g.create(h.NAME)}isEqual(o){return this.compare(o,Y.EQUALS)}isNotEqual(o){return this.compare(o,Y.NOT_EQUAL)}isGreaterThanOrEqual(o){return this.compare(o,Y.GREATER_THAN_OR_EQUAL)}isLessThanOrEqual(o){return this.compare(o,Y.LESS_THAN_OR_EQUAL)}isLessThan(o){return this.compare(o,Y.LESS_THAN)}isGreaterThan(o){return this.compare(o,Y.GREATER_THAN)}concatenateFront(o){return g.create(h.NAME)}concatenateBack(o){return g.create(h.NAME)}plusBy(o){return g.create(h.VALUE)}minusBy(o){return g.create(h.VALUE)}multiplyBy(o){return g.create(h.VALUE)}dividedBy(o){return g.create(h.VALUE)}modInverse(o){return g.create(h.VALUE)}compareBy(o,e){return g.create(h.NAME)}concatenate(o,e=Je.FRONT){let t=this.getValue().toString();if(typeof o=="string")e===Je.FRONT?t=o+t:t+=o;else if(typeof o=="number")e===Je.FRONT?t=o.toString()+t:t+=o.toString();else if(typeof o=="boolean"){const r=o?"TRUE":"FALSE";e===Je.FRONT?t=r+t:t+=r}return t}pow(o){return g.create(h.VALUE)}powInverse(o){return g.create(h.VALUE)}sqrt(){return g.create(h.VALUE)}cbrt(){return g.create(h.VALUE)}cos(){return g.create(h.VALUE)}cosh(){return g.create(h.VALUE)}acos(){return g.create(h.VALUE)}acosh(){return g.create(h.VALUE)}sin(){return g.create(h.VALUE)}sinh(){return g.create(h.VALUE)}asin(){return g.create(h.VALUE)}asinh(){return g.create(h.VALUE)}tan(){return g.create(h.VALUE)}tanh(){return g.create(h.VALUE)}atan(){return g.create(h.VALUE)}atan2(o){return g.create(h.VALUE)}atan2Inverse(o){return g.create(h.VALUE)}atanh(){return g.create(h.VALUE)}mean(){return this}median(){return this}var(){return this}std(){return this}log(){return g.create(h.VALUE)}log10(){return g.create(h.VALUE)}exp(){return g.create(h.VALUE)}abs(){return g.create(h.VALUE)}round(o){return g.create(h.VALUE)}roundInverse(o){return g.create(h.VALUE)}floor(o){return g.create(h.VALUE)}floorInverse(o){return g.create(h.VALUE)}ceil(o){return g.create(h.VALUE)}ceilInverse(o){return g.create(h.VALUE)}convertToNumberObjectValue(){return g.create(h.VALUE)}convertToBooleanObjectValue(){return g.create(h.VALUE)}}const Qc=1e3,Ba=new ht(Qc);class g extends dt{constructor(o,e=""){super(o),this._errorType=o,this._errorContent=e}static create(o,e=""){const t=`${o}-${e}`,r=Ba.get(t);if(r)return r;const n=new g(o,e);return Ba.set(t,n),n}getValue(){return this._errorType}getErrorType(){return this._errorType}getErrorContent(){return this._errorContent}isEqualType(o){return o.getErrorType()===this.getErrorType()}isError(){return!0}}function qc(i){if(i===null)return 0;if(i!=null&&i.p){const o=i==null?void 0:i.p.body;if(o==null)return 0;const e=o.dataStream;return S.BuildTextUtils.transform.getPlainText(e)}return(i==null?void 0:i.v)||0}var Ut=(i=>(i[i.MIN=0]="MIN",i[i.MAX=1]="MAX",i))(Ut||{}),Me=(i=>(i[i.NORMAL=0]="NORMAL",i[i.MIN=1]="MIN",i[i.MAX=2]="MAX",i))(Me||{});function Jr(){return Intl&&Intl.Collator?new Intl.Collator(void 0,{numeric:!1}).compare:(i,o)=>i.localeCompare(o)}function Kc(i){return i.indexOf("*")>-1||i.indexOf("?")>-1}function Zn(i,o){const e=Zc(o).replace(/~?[*?]/g,r=>r.startsWith("~")?`\\${r.substring(1)}`:r==="*"?".*":r==="?"?".":r);return new RegExp(`^${e}$`).test(i)}function Ia(i){return i.replace(/~?[*?]/g,o=>o.startsWith("~")?o.substring(1):" ")}function Xc(i,o,e){let t=!1;switch(e){case Y.EQUALS:t=Zn(i,o);break;case Y.NOT_EQUAL:t=!Zn(i,o);break;case Y.GREATER_THAN:case Y.GREATER_THAN_OR_EQUAL:t=Zn(i,o)||i>Ia(o);break;case Y.LESS_THAN:case Y.LESS_THAN_OR_EQUAL:t=i<Ia(o);break}return t}function Zc(i){return i.replace(/[.+^${}()|[\]\\]/g,"\\$&")}function gs(i){switch(i){case 1:return 2;case 0:return 0;case-1:return 1;default:return 0}}function ds(i){return i===-2?1:0}function $s(i){let o;switch(i){case Y.EQUALS:o=Y.EQUALS;break;case Y.GREATER_THAN:o=Y.LESS_THAN;break;case Y.GREATER_THAN_OR_EQUAL:o=Y.LESS_THAN_OR_EQUAL;break;case Y.LESS_THAN:o=Y.GREATER_THAN;break;case Y.LESS_THAN_OR_EQUAL:o=Y.GREATER_THAN_OR_EQUAL;break;case Y.NOT_EQUAL:o=Y.NOT_EQUAL;break}return o}/*!
2
2
  * decimal.js v10.4.3
3
3
  * An arbitrary-precision Decimal type for JavaScript.
4
4
  * https://github.com/MikeMcl/decimal.js
package/lib/es/index.js CHANGED
@@ -2782,13 +2782,13 @@ function il(i) {
2782
2782
  pattern: e.pattern
2783
2783
  };
2784
2784
  const t = gt.parseNumber(a);
2785
- if (t)
2785
+ if (t && t.z)
2786
2786
  return os(a, t.v, t.z);
2787
2787
  const r = gt.parseDate(a);
2788
- if (r)
2788
+ if (r && r.z)
2789
2789
  return os(a, r.v, r.z);
2790
2790
  const n = gt.parseTime(a);
2791
- return n ? os(a, n.v, n.z) : {
2791
+ return n && n.z ? os(a, n.v, n.z) : {
2792
2792
  isNumberPattern: !1
2793
2793
  };
2794
2794
  }
package/lib/umd/index.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(w,S){typeof exports=="object"&&typeof module<"u"?S(exports,require("@univerjs/core"),require("rxjs"),require("@univerjs/rpc")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","@univerjs/rpc"],S):(w=typeof globalThis<"u"?globalThis:w||self,S(w.UniverEngineFormula={},w.UniverCore,w.rxjs,w.UniverRpc))})(this,function(w,S,Ze,Io){"use strict";var $E=Object.defineProperty;var YE=(w,S,Ze)=>S in w?$E(w,S,{enumerable:!0,configurable:!0,writable:!0,value:Ze}):w[S]=Ze;var A=(w,S,Ze)=>YE(w,typeof S!="symbol"?S+"":S,Ze);var ya;var Et=(i=>(i.FALSE="FALSE",i.TRUE="TRUE",i))(Et||{}),bt=(i=>(i[i.SUCCESS=0]="SUCCESS",i[i.ERROR=1]="ERROR",i))(bt||{}),ze=(i=>(i[i.FRONT=0]="FRONT",i[i.BACK=1]="BACK",i))(ze||{});function Na(i,u,e,t,r){for(let n=0,s=i.length;n<s;n++){const a=i[n];if(u!==a.unitId||e!==a.sheetId)continue;const{startRow:o,startColumn:c,endRow:l,endColumn:f}=a.range;if(t>=o&&t<=l&&r>=c&&r<=f)return!0}return!1}var h=(i=>(i.DIV_BY_ZERO="#DIV/0!",i.NAME="#NAME?",i.VALUE="#VALUE!",i.NUM="#NUM!",i.NA="#N/A",i.CYCLE="#CYCLE!",i.REF="#REF!",i.SPILL="#SPILL!",i.CALC="#CALC!",i.ERROR="#ERROR!",i.CONNECT="#GETTING_DATA",i.NULL="#NULL!",i))(h||{});const xt=new Set(Object.values(h)),pa=[...new Set(Object.values(h).map(i=>i.length))];var Va=(i=>(i[i.Financial=0]="Financial",i[i.Date=1]="Date",i[i.Math=2]="Math",i[i.Statistical=3]="Statistical",i[i.Lookup=4]="Lookup",i[i.Database=5]="Database",i[i.Text=6]="Text",i[i.Logical=7]="Logical",i[i.Information=8]="Information",i[i.Engineering=9]="Engineering",i[i.Cube=10]="Cube",i[i.Compatibility=11]="Compatibility",i[i.Web=12]="Web",i[i.Array=13]="Array",i[i.Univer=14]="Univer",i[i.User=15]="User",i[i.DefinedName=16]="DefinedName",i))(Va||{}),Z=(i=>(i.PLUS="+",i.MINUS="-",i.MULTIPLY="*",i.DIVIDED="/",i.CONCATENATE="&",i.POWER="^",i.EQUALS="=",i.NOT_EQUAL="<>",i.GREATER_THAN=">",i.GREATER_THAN_OR_EQUAL=">=",i.LESS_THAN="<",i.LESS_THAN_OR_EQUAL="<=",i))(Z||{}),H=(i=>(i.EQUALS="=",i.NOT_EQUAL="<>",i.GREATER_THAN=">",i.GREATER_THAN_OR_EQUAL=">=",i.LESS_THAN="<",i.LESS_THAN_OR_EQUAL="<=",i))(H||{});const Ur=new Map([["<>",4],["<",4],[">=",4],["=",4],[">",4],["<=",4],["&",3],["+",2],["-",2],["/",1],["*",1],["^",0]]),yt=new Set(Ur.keys()),Fo=new Set(["=","<>",">",">=","<","<="]);var X=(i=>(i.OPEN_BRACKET="(",i.CLOSE_BRACKET=")",i.COMMA=",",i.SINGLE_QUOTATION="'",i.DOUBLE_QUOTATION='"',i.OPEN_BRACES="{",i.CLOSE_BRACES="}",i.COLON=":",i.OPEN_SQUARE_BRACKET="[",i.CLOSE_SQUARE_BRACKET="]",i))(X||{}),Ge=(i=>(i.PERCENTAGE="%",i.POUND="#",i))(Ge||{});const Qn=new Set(["%","#"]);var Ve=(i=>(i.AT="@",i.MINUS="-",i.PLUS="+",i))(Ve||{});const ko=" ",Oa=[...Object.values(H),...Object.values(Z),...Object.values(X),...Object.values(Ge),...Object.values(Ve)];function gr(i){return Oa.includes(i)}function Ma(i){for(const u of Oa)if(i.indexOf(u)>-1)return!0;return!1}function $o(i){return i[0]==="'"&&i[i.length-1]==="'"?i.substring(1,i.length-1):i}function Yo(i){return gr(i)&&i!==X.CLOSE_BRACES&&i!==X.CLOSE_BRACKET&&i!==X.SINGLE_QUOTATION&&i!==X.DOUBLE_QUOTATION||i===" "}const Ho=new Set([Z.PLUS,Z.MINUS,Z.MULTIPLY,Z.DIVIDED,Z.CONCATENATE,Z.POWER,Z.EQUALS,Z.NOT_EQUAL,Z.GREATER_THAN,Z.GREATER_THAN_OR_EQUAL,Z.LESS_THAN,Z.LESS_THAN_OR_EQUAL,X.OPEN_BRACKET,X.COMMA,X.COLON,X.OPEN_BRACES,X.OPEN_SQUARE_BRACKET]);function Go(i){return Ho.has(i)}const Wo=new Set([Z.PLUS,Z.MINUS,Z.MULTIPLY,Z.DIVIDED,Z.CONCATENATE,Z.POWER,Z.EQUALS,Z.NOT_EQUAL,Z.GREATER_THAN,Z.GREATER_THAN_OR_EQUAL,Z.LESS_THAN,Z.LESS_THAN_OR_EQUAL,X.OPEN_BRACKET,X.COMMA,X.COLON,X.OPEN_BRACES,X.OPEN_SQUARE_BRACKET,Ge.PERCENTAGE,Ge.POUND]);function Qo(i){return Wo.has(i)}function Sa(i){const u={};return Object.keys(i).forEach(e=>{const t=i[e];if(t==null)return!0;u[e]==null&&(u[e]={}),Object.keys(t).forEach(r=>{const n=t[r];u[e][r]=new S.ObjectMatrix(n)})}),u}function qo(i){const u={};for(const e in i){const t=i[e];if(t!=null){u[e]==null&&(u[e]={});for(const r in t){const n=t[r],s={};n.forValue((a,o,c)=>{s[a]===void 0&&(s[a]={}),s[a][o]=c}),u[e][r]=s}}}return u}const Da='\\[([^\\[\\]\\/?:"<>|*\\\\]+)\\]',wa=new RegExp(Da),Ko="((?![\\[\\]\\/?*\\\\]).)*!",Rt="$",qn="\\s*?:\\s*?",Tr="[A-Za-z]+",vr="[1-9][0-9]*",Jt=`'?(${Da})?(${Ko})?'?`,Kn=`\\${Rt}?${Tr}\\${Rt}?${vr}`,Xo=`^(${Ve.AT})?${Jt}${Kn}${qn}${Kn}$`,Pa=new RegExp(Xo),Zo=`^${Jt}\\s*?${Kn}(${Ge.POUND})?$`,La=new RegExp(Zo),zo=`^${Jt}\\${Rt}?${vr}${qn}\\${Rt}?${vr}$`,ja=new RegExp(zo),Jo=`^${Jt}\\${Rt}?${Tr}${qn}\\${Rt}?${Tr}$`,xa=new RegExp(Jo),ec=`^${Jt}\\s*?\\${Rt}?${vr}$`,Ua=new RegExp(ec),tc=`^${Jt}\\s*?\\${Rt}?${Tr}$`,Ta=new RegExp(tc),rc="{.*?}",va=new RegExp(rc,"g");function dr(i){return La.lastIndex=0,La.test(i)}function nc(i){return Pa.lastIndex=0,Pa.test(i)}function Ba(i){return ja.lastIndex=0,ja.test(i)}function Ia(i){return xa.lastIndex=0,xa.test(i)}function Fa(i){return Ua.lastIndex=0,Ua.test(i)}function ka(i){return Ta.lastIndex=0,Ta.test(i)}function sc(i){return va.lastIndex=0,va.test(i)}function $a(i){return dr(i)||nc(i)||Ba(i)||Ia(i)}const Ya={id:"formula.mutation.register-function",type:S.CommandType.MUTATION,handler:()=>!0},Br={id:"formula.mutation.set-array-formula-data",type:S.CommandType.MUTATION,handler:(i,u)=>!0},ac=/[^0-9]/g,ic=/[^A-Za-z]/g;function Cr(i){let u=i[0]==="$";const e=i.substring(1);let t=e.indexOf("$")>-1;return S.Tools.isStringNumber(e)&&u&&!t&&(u=!1,t=!0),u&&t?S.AbsoluteRefType.ALL:u?S.AbsoluteRefType.COLUMN:t?S.AbsoluteRefType.ROW:S.AbsoluteRefType.NONE}function uc(i){const u=i.split("!");u.length>1&&(i=u[u.length-1]);const e=i.split(":");return e.length>1?{startAbsoluteRefType:Cr(e[0]),endAbsoluteRefType:Cr(e[1])}:{startAbsoluteRefType:Cr(e[0])}}function Ha(i=S.AbsoluteRefType.NONE){let u="",e="";return i===S.AbsoluteRefType.ROW?u="$":i===S.AbsoluteRefType.COLUMN?e="$":i===S.AbsoluteRefType.ALL&&(u="$",e="$"),{rowAbsoluteString:u,columnAbsoluteString:e}}function Ut(i){const{startColumn:u,startRow:e,endColumn:t,endRow:r,startAbsoluteRefType:n,endAbsoluteRefType:s,rangeType:a=S.RANGE_TYPE.NORMAL}=i,o=Ha(n),c=Ha(s);if(a===S.RANGE_TYPE.ROW||a===S.RANGE_TYPE.ALL){const m=`${o.rowAbsoluteString}${e+1}`,d=`${c.rowAbsoluteString}${r+1}`;return`${m}:${d}`}if(a===S.RANGE_TYPE.COLUMN){const m=`${o.columnAbsoluteString}${S.Tools.chatAtABC(u)}`,d=`${c.columnAbsoluteString}${S.Tools.chatAtABC(t)}`;return`${m}:${d}`}const l=`${o.columnAbsoluteString}${S.Tools.chatAtABC(u)}${o.rowAbsoluteString}${e+1}`,f=`${c.columnAbsoluteString}${S.Tools.chatAtABC(t)}${c.rowAbsoluteString}${r+1}`;return l===f?l:`${l}:${f}`}function Ga(i,u){return`${Ka(i)}!${Ut(u)}`}function Wa(i,u,e){return Xn(i)||Xn(u)?`'[${Zn(i)}]${Zn(u)}'!${Ut(e)}`:`[${i}]${u}!${Ut(e)}`}function Ir(i){const{unitId:u,sheetName:e,range:t}=i;return u!=null&&u.length>0&&e!=null&&e.length>0?Wa(u,e,t):e!=null&&e.length>0?Ga(e,t):Ut(t)}function Fr(i){const u=Number.parseInt(i.replace(ac,""))-1,e=S.Tools.ABCatNum(i.replace(ic,"")),t=Cr(i);return{row:u,column:e,absoluteRefType:t}}function kr(i){const u=wa.exec(i);let e="";u!=null&&(e=u[0].trim(),e=Xa(e.slice(1,e.length-1)),i=i.replace(wa,""));const t=i.indexOf("!");let r="",n="";return t>-1?(r=i.substring(0,t),r[0]==="'"&&r[r.length-1]==="'"&&(r=r.substring(1,r.length-1)),r=Xa(r),n=i.substring(t+1)):n=i,{refBody:n,sheetName:r,unitId:e}}function _r(i){const{refBody:u,sheetName:e,unitId:t}=kr(i),r=u.indexOf(":");if(r===-1){const _=Fr(u),C=_.row,E=_.column,b=_.absoluteRefType;return{unitId:t,sheetName:e,range:{startRow:C,startColumn:E,endRow:C,endColumn:E,startAbsoluteRefType:b,endAbsoluteRefType:b}}}const n=u.substring(0,r),s=u.substring(r+1),a=Fr(n),o=Fr(s),c=a.row>o.row?o.row:a.row,l=a.column>o.column?o.column:a.column,f=a.row>o.row?a.row:o.row,m=a.column>o.column?a.column:o.column;let d=S.RANGE_TYPE.NORMAL;return Number.isNaN(c)&&Number.isNaN(f)?d=S.RANGE_TYPE.COLUMN:Number.isNaN(l)&&Number.isNaN(m)&&(d=S.RANGE_TYPE.ROW),{unitId:t,sheetName:e,range:{startRow:c,startColumn:l,endRow:f,endColumn:m,startAbsoluteRefType:a.absoluteRefType,endAbsoluteRefType:o.absoluteRefType,rangeType:d}}}const oc=["LOG10"];function Ar(i){const u=Qa(i);if(!$a(u)||oc.includes(u.toUpperCase().trim()))return!1;const{range:e}=_r(u);return!(e.endColumn>=16384)}function Qa(i){const u=[];let e=!1;for(let t=0,r=i.length;t<r;t++){const n=i[t];if(n===ko&&!e)u.push(n);else{if(!e&&(n===Ve.AT||n===Ve.MINUS||n===Ve.PLUS))continue;u.push(n),e=!0}}return u.join("")}function cc(i,u){const e=(i==null?void 0:i.split(","))||[];return i===""||e.length===0?[]:qa(i)?e.map(n=>{const s=_r(n);return{unitId:s.unitId,sheetId:u(s.sheetName),range:s.range,sheetName:s.sheetName}}):[]}function qa(i){return((i==null?void 0:i.split(","))||[]).every(e=>Ar(e.trim()))}function Xn(i){return i.length===0?!1:!!(Ma(i)||lc(i)||fc(i)||mc(i)||/[\s!$%^&*()+\-=\[\]{};':"\\|,.<>\/?()]/.test(i))}function Ka(i){return Xn(i)?`'${Zn(i)}'`:i}function Zn(i){return i.replace(/'/g,"''")}function Xa(i){return i.replace(/''/g,"'")}function lc(i){const u=i.match(/[1-9][0-9]{0,6}/);return/^[A-Z]+[1-9][0-9]{0,6}$/.test(i)&&u!==null}function fc(i){return/^(R(-?[0-9]+)?C(-?[0-9]+)?|C(-?[0-9]+)?|R(-?[0-9]+)?)$/.test(i)}function mc(i){return!new RegExp("^\\p{Letter}","u").test(i.charAt(0))}var hc=Object.defineProperty,gc=Object.getOwnPropertyDescriptor,dc=(i,u,e,t)=>{for(var r=t>1?void 0:t?gc(u,e):u,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(u,e,r):s(r))||r);return t&&r&&hc(u,e,r),r},Cc=(i,u)=>(e,t)=>u(e,t,i);w.DefinedNamesService=class extends S.Disposable{constructor(e){super();A(this,"_definedNameMap",{});A(this,"_update$",new Ze.Subject);A(this,"update$",this._update$.asObservable());A(this,"_currentRange",{unitId:"",sheetId:"",range:{startRow:0,endRow:0,startColumn:0,endColumn:0}});A(this,"_currentRange$",new Ze.Subject);A(this,"currentRange$",this._currentRange$.asObservable());A(this,"_focusRange$",new Ze.Subject);A(this,"focusRange$",this._focusRange$.asObservable());this._univerInstanceService=e}dispose(){this._definedNameMap={}}getWorksheetByRef(e,t){var n;const{sheetName:r}=kr(t);return(n=this._univerInstanceService.getUnit(e))==null?void 0:n.getSheetBySheetName(r)}focusRange(e,t){const r=this.getValueById(e,t);r!=null&&this._focusRange$.next({...r,unitId:e})}setCurrentRange(e){this._currentRange=e,this._currentRange$.next(e)}getCurrentRange(){return this._currentRange}getCurrentRangeForString(){return Ut(this._currentRange.range)}registerDefinedNames(e,t){this._definedNameMap[e]=t,this._update()}registerDefinedName(e,t){this._definedNameMap[e]==null&&(this._definedNameMap[e]={}),this._definedNameMap[e][t.id]=t,this._update()}removeDefinedName(e,t){var r;(r=this._definedNameMap[e])==null||delete r[t],this._update()}removeUnitDefinedName(e){delete this._definedNameMap[e],this._update()}getDefinedNameMap(e){return this._definedNameMap[e]}getValueByName(e,t){var n;const r=this._definedNameMap[e];return r==null?null:(n=Array.from(Object.values(r)).filter(s=>s.name===t))==null?void 0:n[0]}getValueById(e,t){var r;return(r=this._definedNameMap[e])==null?void 0:r[t]}hasDefinedName(e){return this._definedNameMap[e]==null?!1:(Array.from(Object.values(this._definedNameMap[e])).length||0)!==0}_update(){this._update$.next(null)}},w.DefinedNamesService=dc([Cc(0,S.IUniverInstanceService)],w.DefinedNamesService);const Tt=S.createIdentifier("univer.formula.defined-names.service"),_c=(i,u)=>{const{unitId:e,id:t}=u;return{...i.get(Tt).getValueById(e,t),unitId:e}},$r={id:"formula.mutation.set-defined-name",type:S.CommandType.MUTATION,handler:(i,u)=>{if(u==null)return!1;const e=i.get(Tt),{id:t,unitId:r,name:n,formulaOrRefString:s,comment:a,hidden:o,localSheetId:c}=u;return e.registerDefinedName(r,{id:t,name:n.trim(),formulaOrRefString:s.trim(),comment:a==null?void 0:a.trim(),hidden:o,localSheetId:c}),!0}},zn={id:"formula.mutation.remove-defined-name",type:S.CommandType.MUTATION,handler:(i,u)=>{if(u==null)return!1;const e=i.get(Tt),{unitId:t,id:r}=u;return e.removeDefinedName(t,r),!0}},Yr={id:"formula.mutation.set-feature-calculation",type:S.CommandType.MUTATION,handler:()=>!0},Hr={id:"formula.mutation.remove-feature-calculation",type:S.CommandType.MUTATION,handler:()=>!0},Jn={id:"formula.mutation.set-formula-calculation-start",type:S.CommandType.MUTATION,handler:()=>!0},es={id:"formula.mutation.set-formula-calculation-stop",type:S.CommandType.MUTATION,handler:()=>!0},Gr={id:"formula.mutation.set-formula-calculation-notification",type:S.CommandType.MUTATION,handler:()=>!0},ts={id:"formula.mutation.set-formula-calculation-result",type:S.CommandType.MUTATION,handler:()=>!0},rs={id:"formula.mutation.set-formula-data",type:S.CommandType.MUTATION,handler:(i,u)=>!0},Wr={id:"formula.mutation.set-other-formula",type:S.CommandType.MUTATION,handler:()=>!0},Qr={id:"formula.mutation.remove-other-formula",type:S.CommandType.MUTATION,handler:()=>!0},Za={id:"formula.mutation.set-super-table",type:S.CommandType.MUTATION,handler:()=>!0},za={id:"formula.mutation.remove-super-table",type:S.CommandType.MUTATION,handler:()=>!0},ns={id:"formula.mutation.set-super-table-option",type:S.CommandType.MUTATION,handler:()=>!0};class gt{constructor(u){A(this,"_cache");this._cache=new S.LRUMap(u)}set(u,e){const t=this._hash(u);this._cache.set(t,e)}get(u){const e=this._hash(u);return this._cache.get(e)}clear(){this._cache.clear()}_hash(u){return u.length<=64?u:S.hashAlgorithm(u).toString()}}const at="P_1",Nt="R_1",er="L_1",Er="LR_1",Ja="LO_1",Ac="LET",br="LAMBDA",Ec="CUBE",bc=new Set(["RAND","RANDBETWEEN","NOW","TODAY"]),ss=new gt(1e5);function vt(i){const u=ss.get(i);if(u)return u;const e=_r(i);return ss.set(i,e),_r(i)}function yc(){ss.clear()}var Te=(i=>(i[i.NORMAL=0]="NORMAL",i[i.NUMBER=1]="NUMBER",i[i.STRING=2]="STRING",i[i.FUNCTION=3]="FUNCTION",i[i.REFERENCE=4]="REFERENCE",i[i.ARRAY=5]="ARRAY",i[i.DEFINED_NAME=6]="DEFINED_NAME",i))(Te||{});function as(i){let u="";for(const e of i)typeof e=="string"?u+=e:u+=e.token;return u}class ie{constructor(){A(this,"_parent");A(this,"_token",Nt);A(this,"_children",[]);A(this,"_lambdaId");A(this,"_functionDefinitionPrivacyVar");A(this,"_lambdaParameter","");A(this,"_startIndex",-1);A(this,"_endIndex",-1);A(this,"_definedNames",[])}dispose(){var u;this._children.forEach(e=>{typeof e!="string"&&e.dispose()}),(u=this._functionDefinitionPrivacyVar)==null||u.clear(),this._functionDefinitionPrivacyVar=null,this._children=[],this._parent=null,this._definedNames=[]}getDefinedNames(){return this._definedNames}getStartIndex(){return this._startIndex}getLambdaId(){return this._lambdaId}setLambdaId(u){this._lambdaId=u}getFunctionDefinitionPrivacyVar(){return this._functionDefinitionPrivacyVar}setLambdaPrivacyVar(u){this._functionDefinitionPrivacyVar=u}getLambdaParameter(){return this._lambdaParameter}setLambdaParameter(u){this._lambdaParameter=u}getParent(){return this._parent}setParent(u){this._parent=u}getChildren(){return this._children}setChildren(u){this._children=u}addChildren(u){this._children.push(u)}addChildrenFirst(u){this._children.unshift(u)}getToken(){return this._token}setToken(u){this._token=u}setIndex(u,e){this._startIndex=u,this._endIndex=e}setDefinedNames(u){this._definedNames=u}hasDefinedNames(){return this._definedNames.length>0}replaceChild(u,e){const t=this._getIndexInParent(u);t!=null&&(this.getChildren().splice(t,1,e),e.setParent(this))}changeToParent(u){const e=this.getParent();e&&e.removeChild(this),this.setParent(u),u.getChildren().push(this)}removeChild(u){const e=this._getIndexInParent(u);e!=null&&this.getChildren().splice(e,1)}serialize(){const u=this.getToken(),e=this.getChildren(),t=[],r=e.length;for(let n=0;n<r;n++){const s=e[n];s instanceof ie?t.push(s.serialize()):t.push(s)}return{token:u,st:this._startIndex,ed:this._endIndex,children:t}}_getIndexInParent(u){const e=this.getChildren(),t=e.length;for(let r=0;r<t;r++)if(e[r]===u)return r}}const ei=2e3,is=new gt(ei),us=new gt(ei);class qr extends S.Disposable{constructor(){super(...arguments);A(this,"_currentLexerNode",new ie);A(this,"_upLevel",0);A(this,"_segment","");A(this,"_bracketState",[]);A(this,"_squareBracketState",0);A(this,"_bracesState",0);A(this,"_singleQuotationState",0);A(this,"_doubleQuotationState",0);A(this,"_lambdaState",!1);A(this,"_colonState",!1);A(this,"_formulaErrorCount",0);A(this,"_tableBracketState",!1)}dispose(){this._resetTemp(),this._currentLexerNode.dispose(),is.clear(),us.clear()}getUpLevel(){return this._upLevel}isColonClose(){return this._colonState===!1}isColonOpen(){return this._colonState===!0}isDoubleQuotationClose(){return this._doubleQuotationState===0}isLambdaOpen(){return this._lambdaState===!0}isLambdaClose(){return this._lambdaState===!1}isSingleQuotationClose(){return this._singleQuotationState===0}isBracesClose(){return this._bracesState===0}isBracketClose(){return this._bracketState.length===0}isSquareBracketClose(){return this._squareBracketState===0}getCurrentLexerNode(){return this._currentLexerNode}getFunctionAndParameter(e,t){const r=this._getCurrentParamIndex(e,t);if(r==null||r===h.VALUE)return;const n=r[0];if(typeof n=="string")return;let s=n.getParent(),a=n;for(;s;){const o=s.getToken();if(o!==at&&!gr(o)&&s.getStartIndex()!==-1){const c=s.getChildren().indexOf(a);return{functionName:o,paramIndex:c}}a=s,s=s.getParent()}}checkIfAddBracket(e){let t=0,r=e.length-1,n=e[r];for(;(n===X.CLOSE_BRACKET||n===" ")&&r>=0;)n===X.CLOSE_BRACKET&&t++,n=e[--r];const s=this._getCurrentParamIndex(e,e.length-2);if(s==null||s===h.VALUE)return 0;const a=s[0];if(typeof a=="string")return 0;let o=a.getParent(),c=0;for(s[1]===X.OPEN_BRACKET&&c++;o;){const l=o.getToken();l!==at&&l!==X.COLON&&o.getStartIndex()!==-1&&l.toUpperCase()!==br&&(t===0?c+=1:t--),o=o.getParent()}return c}sequenceNodesBuilder(e){const t=us.get(e);if(t)return[...t];const r=this._getSequenceArray(e);if(r.length===0)return;const n=this.getSequenceNode(r);return us.set(e,[...n]),n}convertRefersToAbsolute(e,t,r,n=""){const s=this.sequenceNodesBuilder(e);if(s==null)return e;let a="";e.substring(0,1)===Z.EQUALS&&(a=Z.EQUALS);for(let o=0,c=s.length;o<c;o++){const l=s[o];if(typeof l!="string"&&l.nodeType===Te.REFERENCE){const{token:f,endIndex:m}=l,d=vt(f);if(d==null)continue;const{range:_,sheetName:C,unitId:E}=d,b={..._,startAbsoluteRefType:t,endAbsoluteRefType:r},R=Ir({range:b,unitId:E,sheetName:C||n}),N=R.length-f.length;s[o]={...l,token:R,endIndex:m+N};for(let V=o+1;V<c;V++){const M=s[V];typeof M!="string"&&(M.startIndex+=N,M.endIndex+=N)}}}return`${a}${as(s)}`}moveFormulaRefOffset(e,t,r,n=!1){const s=this.sequenceNodesBuilder(e);if(s==null)return e;const a=[];for(let o=0,c=s.length;o<c;o++){const l=s[o];if(typeof l=="string"||l.nodeType!==Te.REFERENCE){a.push(l);continue}const{token:f}=l,m=vt(f),{sheetName:d,unitId:_}=m;let C=m.range;if(!n&&C.startAbsoluteRefType===S.AbsoluteRefType.ALL&&C.endAbsoluteRefType===S.AbsoluteRefType.ALL){a.push(l);continue}else C=S.moveRangeByOffset(C,t,r,n);let E="";S.isValidRange(C)?E=Ir({range:C,unitId:_,sheetName:d}):E=h.REF,a.push({...l,token:E})}return`=${as(a)}`}_formulaSpellCheck(){if(this._currentLexerNode.getChildren().length===0)return!0;const e=this._currentLexerNode.getChildren()[0];return!!(e instanceof ie||yt.has(e)||Qn.has(e)||e===Ve.AT||e===X.COMMA||e===X.COLON||e===X.OPEN_BRACKET)}getSequenceNode(e){const t=[];let r=!1;for(let n=0,s=e.length;n<s;n++){const a=e[n],o=e[n-1],{segment:c,currentString:l}=a;if(l===X.DOUBLE_QUOTATION&&(r=!0),(c!==""||n===0)&&n!==s-1){t.push(l);continue}let f=(o==null?void 0:o.segment)||"";const m=n-f.length;let d=n-1;const _=n-1;if(n===s-1&&this._isLastMergeString(l)&&(f+=l,d+=1),f===""||Ur.has(f)){t.push(l);continue}const C=f.trim(),E=Qa(C);r===!0&&C[C.length-1]===X.DOUBLE_QUOTATION&&C[0]!==X.OPEN_BRACES?(r=!1,this._processPushSequenceNode(t,Te.STRING,f,m,d,_)):dr(E)&&Ar(E)?this._processPushSequenceNode(t,Te.REFERENCE,f,m,d,_):S.Tools.isStringNumber(C)?this._processPushSequenceNode(t,Te.NUMBER,f,m,d,_):C.length>0&&this._processPushSequenceNode(t,Te.FUNCTION,f,m,d,_),(n!==s-1||!this._isLastMergeString(l))&&t.push(l)}return this._mergeSequenceNodeReference(t)}_processPushSequenceNode(e,t,r,n,s,a){this._pushSequenceNode(e,{nodeType:t,token:r,startIndex:n,endIndex:s},a)}_getCurrentParamIndex(e,t){return this._nodeMaker(e,void 0,t)}_isLastMergeString(e){return e===X.DOUBLE_QUOTATION||S.Tools.isStringNumber(e)||!gr(e)}_mergeSequenceNodeReference(e){const t=[],r=e.length;let n=0;for(;n<r;){const s=e[n];if(typeof s=="string"){const a=e[n-1];if(s.trim()===X.CLOSE_BRACES&&a!=null&&typeof a!="string"&&a.nodeType===Te.FUNCTION&&a.token.trim().substring(0,1)===X.OPEN_BRACES){a.nodeType=Te.ARRAY,a.token+=s,a.endIndex+=s.length,n++;continue}t.push(s)}else{const a=e[n+1],o=e[n+2];a===X.COLON&&typeof s!="string"&&o!=null&&typeof o!="string"&&Ar((s.token+a+o.token).trim())&&(s.nodeType=Te.REFERENCE,s.token+=a+o.token,s.endIndex=o.endIndex,n+=2),t.push(s)}n++}return this._minusSplitSequenceNode(t)}_minusSplitSequenceNode(e){const t=[];for(const r of e){if(typeof r!="string"){const s=r.token.match(/^(\s*([-@+]\s*)+)(.*)$/);if(s){const a=s[1],o=s[3];if(Ar(o.trim())){const c=a.length,l=r.startIndex,f=r.startIndex+c-1,m={nodeType:Te.NORMAL,token:a,startIndex:l,endIndex:f},d={nodeType:Te.REFERENCE,token:o,startIndex:f+1,endIndex:r.endIndex};t.push(m),t.push(d);continue}}}t.push(r)}return t}_pushSequenceNode(e,t,r){const n=r-t.startIndex+1;e.splice(e.length-n,n,t)}nodeMakerTest(e){return this._nodeMaker(e)}treeBuilder(e,t=!0,r,n){if(t===!0){const m=is.get(e),d=n==null?void 0:n(e);if(m&&!d)return m}this._resetCurrentLexerNode(),this._currentLexerNode.setToken(Nt);const s=[];let a=this._nodeMaker(e,s);if(a===h.VALUE||s.length===0)return a;let o=!1,c="",l=[];if(r){const{hasDefinedName:m,sequenceString:d,definedNames:_}=r(s);o=m,c=d,l=_}if(o&&(this._resetCurrentLexerNode(),this._currentLexerNode.setToken(Nt),a=this._nodeMaker(`=${c}`),a===h.VALUE))return a;const f=this._getTopNode(this._currentLexerNode);if(f&&(this._currentLexerNode=f),t){if(!this._suffixExpressionHandler(this._currentLexerNode))return h.VALUE;is.set(e,this._currentLexerNode)}return o&&this._currentLexerNode.setDefinedNames(l),this._currentLexerNode}_suffixExpressionHandler(e){var o;const t=e.getChildren();if(!t)return!1;const r=t.length,n=[],s=[];let a=!0;for(let c=0;c<r;c++){const l=t[c];if(l instanceof ie)a=this._suffixExpressionHandler(l),n.push(l);else{const f=l.trim();if(f==="")continue;if(yt.has(f)){if(f===Z.PLUS&&this._deletePlusForPreNode(t[c-1]))continue;if(f!==Z.PLUS&&f!==Z.MINUS&&this._deletePlusForPreNode(t[c-1]))return!1;for(;s.length>0;){const m=(o=s[s.length-1])==null?void 0:o.trim();if(!m||m===X.OPEN_BRACKET)break;const d=Ur.get(m),_=Ur.get(f);if(!d||!_)break;if(_>=d)n.push(s.pop());else break}s.push(l)}else if(f===X.OPEN_BRACKET)s.push(l);else if(f===X.CLOSE_BRACKET)this._processSuffixExpressionCloseBracket(n,s,t,c);else{if(this._checkCloseBracket(t[c-1]))return!1;n.push(l)}}}return a?this._processSuffixExpressionRemain(n,s,e):!1}_processSuffixExpressionRemain(e,t,r){const n=e.length,s=e[n-1];for(;t.length>0;){const a=t.pop();if(!(s instanceof ie)&&(a===X.OPEN_BRACKET||a===X.CLOSE_BRACKET))return!1;e.push(a)}return r.setChildren(e),!0}_processSuffixExpressionCloseBracket(e,t,r,n){var s;if(this._checkOpenBracket(r[n-1])||this._checkOperator(r[n-1]))return!1;for(;t.length>0;){const a=(s=t[t.length-1])==null?void 0:s.trim();if(!a)break;if(a===X.OPEN_BRACKET){t.pop();break}e.push(t.pop())}}_checkCloseBracket(e){return e===X.CLOSE_BRACKET||e instanceof ie}_checkOpenBracket(e){return e===X.OPEN_BRACKET}_checkOperator(e){return e==null||e instanceof ie?!1:yt.has(e)}_deletePlusForPreNode(e){if(e==null)return!0;if(!(e instanceof ie)){const t=e.trim();if(yt.has(t)||t===X.OPEN_BRACKET)return!0}return!1}_resetCurrentLexerNode(){this._currentLexerNode=new ie}_resetSegment(){this._segment=""}_openBracket(e=0){this._bracketState.push(e)}_closeBracket(){this._bracketState.pop()}_openSquareBracket(){this._squareBracketState+=1}_closeSquareBracket(){this._squareBracketState-=1}_getCurrentBracket(){const e=this._bracketState;return e[e.length-1]}_changeCurrentBracket(e){const t=this._bracketState;t[t.length-1]=e}_openBraces(){this._bracesState+=1}_closeBraces(){this._bracesState-=1}_openSingleQuotation(){this._singleQuotationState+=1}_closeSingleQuotation(){this._singleQuotationState-=1}_openDoubleQuotation(){this._doubleQuotationState+=1}_closeDoubleQuotation(){this._doubleQuotationState-=1}_openLambda(){this._lambdaState=!0}_closeLambda(){this._lambdaState=!1}_openColon(e){this._upLevel=e,this._colonState=!0}_closeColon(){this._upLevel=0,this._colonState=!1}_isTableBracket(){return this._tableBracketState}_openTableBracket(){this._tableBracketState=!0}_closeTableBracket(){this._tableBracketState=!1}_formalErrorOccurred(){this._formulaErrorCount+=1}_hasFormalError(){return this._formulaErrorCount>0}_getLastChildCurrentLexerNode(){const e=this._currentLexerNode.getChildren();if(e&&e.length>0){const t=e[e.length-1];if(t instanceof ie)return t}return!1}_getLastChildCurrent(){const e=this._currentLexerNode.getChildren();return e&&e.length>0?e[e.length-1]:!1}_setParentCurrentLexerNode(){const e=this._currentLexerNode.getParent();return e?(this._currentLexerNode=e,!0):!1}_setAncestorCurrentLexerNode(){var r,n,s,a,o,c;const e=(r=this._currentLexerNode)==null?void 0:r.getParent();let t=!1;if(e&&e.getToken()===er){if((n=e==null?void 0:e.getParent())!=null&&n.getParent()){const l=(a=(s=this._currentLexerNode.getParent())==null?void 0:s.getParent())==null?void 0:a.getParent();l&&(this._currentLexerNode=l),t=!0}}else if(e!=null&&e.getParent()){const l=(o=this._currentLexerNode.getParent())==null?void 0:o.getParent();l&&(this._currentLexerNode=l),t=!0}for(let l=0;l<this._upLevel;l++){const f=(c=this._currentLexerNode)==null?void 0:c.getParent();f&&(this._currentLexerNode=f),this._currentLexerNode?t=!0:t=!1}return t}_segmentCount(){return this._segment.trim().length}_pushSegment(e){this._segment+=e}_pushNodeToChildren(e,t=!1){let r=e;if(r!==""){const n=this._currentLexerNode.getChildren();if(!(r instanceof ie)&&this.isColonOpen()){const s=new ie;s.setToken(r),s.setParent(this._currentLexerNode),r=s}t?n.unshift(r):n.push(r)}this.isColonOpen()&&(this._setAncestorCurrentLexerNode(),this._closeColon())}_setCurrentLexerNode(e,t=!1){this._pushNodeToChildren(e,t),e.setParent(this._currentLexerNode),this._currentLexerNode=e}_newAndPushCurrentLexerNode(e,t,r=!1){const n=new ie;n.setToken(e),n.setIndex(t-e.length,t-1),this._setCurrentLexerNode(n,r)}_getTopNode(e){let t=e;for(;t!=null&&t.getParent();)t=t.getParent();return t}_removeLastChild(){this._currentLexerNode.getChildren().splice(-1)}_formulaErrorLastTokenCheck(e,t){const r=this._findPreviousToken(e,t)||"",n=e.length-1===t;if(!n&&this._isOperatorToken(r)||n&&Go(r))return!0;if(Qn.has(r)){const s=this._findSecondLastNonSpaceToken(e,t);if(s==null||Qo(s))return!0}return!1}_findPreviousToken(e,t){let r=t;for(;r>=0;){const n=e[r];if(n!==" ")return n;r--}}_findSecondLastNonSpaceToken(e,t){let r=t,n=0;for(;r>=0;){const s=e[r];if(s!==" "&&(n++,n===2))return s;r--}return null}_findNextToken(e,t){let r=t;for(;r>=0;){const n=e[r];if(n!==" ")return n;r++}}_unexpectedEndingTokenExcludeOperator(e){return e===X.OPEN_BRACKET||e===X.COMMA||e===Z.EQUALS||e===""}_unexpectedEndingToken(e){return!!(this._isOperatorToken(e)||this._unexpectedEndingTokenExcludeOperator(e))}_isOperatorToken(e){return!!yt.has(e)}_getSequenceArray(e){const t=[];return this._nodeMaker(e,t),t}_resetTemp(){this._currentLexerNode=new ie,this._upLevel=0,this._segment="",this._bracketState=[],this._bracesState=0,this._singleQuotationState=0,this._doubleQuotationState=0,this._lambdaState=!1,this._colonState=!1,this._formulaErrorCount=0}_checkErrorState(){return!!(this._bracketState.length>0||this._bracesState>0||this._singleQuotationState>0||this._doubleQuotationState>0||this._hasFormalError())}_checkSimilarErrorToken(e,t,r){let n=t;if(e!==Ge.POUND)return!0;let s=r[++n];for(;s===" ";)s=r[++n];return!!gr(s)}_checkIfErrorObject(e,t){return!!this._findErrorObject(e,t)}_findErrorObject(e,t){for(let r=0;r<pa.length;r++){const n=pa[r],s=t.slice(e,e+n).join("").toUpperCase();if(xt.has(s))return s}}_nodeMaker(e,t,r){let n=e.replace(/\r\n$/,"").replace(/\r/g," ").replace(/\n/g," ");n.substring(0,1)===Z.EQUALS&&(n=n.substring(1));const s=n.split(""),a=s.length;let o=0;for(this._resetTemp(),this._formulaErrorLastTokenCheck(s,a-1)&&this._formalErrorOccurred();o<a;){const c=s[o];if(r===o)return[this._currentLexerNode,c];if(c===Ge.POUND&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()&&this._checkIfErrorObject(o,s)){const l=this._findErrorObject(o,s);if(l==null)return h.VALUE;this._pushNodeToChildren(l);for(let f=0;f<l.length;f++){const m=s[o];this._pushSegment(m),this._addSequenceArray(t,m,o),o++}this._resetSegment();continue}else if(c===X.OPEN_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())if(this._segmentCount()>0||this.isLambdaOpen()){this.isLambdaClose()&&(this._newAndPushCurrentLexerNode(this._segment,o),this._resetSegment()),this._openBracket(1),this._closeLambda();const l=s[o+1];if(l&&l===X.CLOSE_BRACKET){if(!this._setParentCurrentLexerNode()&&o!==a-1)return h.VALUE;this._addSequenceArray(t,c,o),o++,this._addSequenceArray(t,l,o),o++,this._closeBracket();continue}else l&&this._newAndPushCurrentLexerNode(at,o)}else this._pushNodeToChildren(c),this._openBracket(0),this._resetSegment();else if(c===X.CLOSE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()){this._formulaErrorLastTokenCheck(s,o-1)&&this._formalErrorOccurred(),this._pushNodeToChildren(this._segment),this._resetSegment();const l=this._getCurrentBracket();if(l===0)this._pushNodeToChildren(c);else if(l===1){const f=s[o+1];if(f&&f===X.OPEN_BRACKET){if(!this._setParentCurrentLexerNode()&&o!==a-1)return h.VALUE;this._newAndPushCurrentLexerNode(er,o,!0),this._openLambda()}else if(!this._setAncestorCurrentLexerNode()&&o!==a-1)return h.VALUE}else return h.VALUE;this._closeBracket()}else if(c===X.OPEN_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()){if(this._pushSegment(c),this._openBraces(),!this._formulaSpellCheck())return h.VALUE}else if(c===X.CLOSE_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._pushSegment(c),this._pushNodeToChildren(this._segment),this._resetSegment(),this._closeBraces();else if(c===X.OPEN_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._segment.length>0&&this._openTableBracket(),this._pushSegment(c),this._openSquareBracket();else if(c===X.CLOSE_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._closeSquareBracket(),this.isSquareBracketClose()?(this._pushSegment(c),this._isTableBracket()&&(this._pushNodeToChildren(this._segment),this._resetSegment()),this._closeTableBracket()):this._pushSegment(c);else if(c===X.DOUBLE_QUOTATION&&this.isSingleQuotationClose()&&this.isSquareBracketClose()){if(this.isDoubleQuotationClose())this._openDoubleQuotation();else{const l=s[o+1];l&&l===X.DOUBLE_QUOTATION?o++:this._closeDoubleQuotation()}this._pushSegment(c)}else if(c===X.SINGLE_QUOTATION&&this.isDoubleQuotationClose()){if(this.isSingleQuotationClose())this._openSingleQuotation(),this._segmentCount()===0&&this._resetSegment();else{const l=s[o+1];if(l&&l===X.SINGLE_QUOTATION){this._pushSegment(c),this._addSequenceArray(t,c,o),o++,this._pushSegment(l),this._addSequenceArray(t,l,o),o++;continue}else this._closeSingleQuotation()}this._pushSegment(c)}else if(c===X.COMMA&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){this._formulaErrorLastTokenCheck(s,o-1)&&this._formalErrorOccurred();const l=this._getCurrentBracket();if(l===1||l==null){if(this._pushNodeToChildren(this._segment),this._resetSegment(),!this._setParentCurrentLexerNode()&&o!==a-1&&l!=null)return h.VALUE;this._newAndPushCurrentLexerNode(at,o)}else{const f=new ie;f.setToken(Ec);const m=new ie;m.setToken(at),m.changeToParent(f);const d=this._currentLexerNode.getParent();if(d&&d.getToken()===X.COLON){const _=d.getParent();if(!_)return h.VALUE;d.changeToParent(m),_.setChildren([]),f.changeToParent(_)}else return h.VALUE;this._changeCurrentBracket(1),this._pushNodeToChildren(this._segment),this._resetSegment(),this._currentLexerNode=f,this._newAndPushCurrentLexerNode(at,o)}}else if(c===X.COLON&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){const l=new ie;l.setToken(c);const f=new ie;f.setToken(at),f.setParent(l);const m=new ie;m.setToken(at),m.setParent(l),l.getChildren().push(f,m);let d=l,_=0;if(this._segmentCount()>0){let C,E,b=0;const R=this._segment.trim(),N=R[0],V=R[1];if(N===Ve.MINUS&&(C=new ie,C.setToken(Ve.MINUS),b++),(N===Ve.AT||V===Ve.AT)&&(E=new ie,E.setToken(Ve.AT),C&&(C.addChildren(E),E.setParent(C)),b++),b>0&&(this._segment=R.slice(b)),_=b,E)if(E.addChildren(l),l.setParent(E),E.getParent()){const D=E.getParent();D&&(d=D)}else d=E;else C&&(d=C,C.addChildren(l),l.setParent(C));const M=new ie;M.setToken(this._segment),M.setParent(f),f.getChildren().push(M),this._resetSegment()}else{const C=this._getLastChildCurrentLexerNode();C&&C.changeToParent(f)}this._setCurrentLexerNode(d),this._currentLexerNode=m,this._openColon(_)}else if(Qn.has(c)&&this._checkSimilarErrorToken(c,o,s)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()&&this.isBracesClose()){this._pushNodeToChildren(this._segment);const l=new ie;l.setToken(c);const f=this._getLastChildCurrent();f instanceof ie?f.changeToParent(l):f!==!1&&(l.getChildren().push(f),this._removeLastChild()),this._pushNodeToChildren(l),l.setParent(this._currentLexerNode),this._resetSegment()}else if(yt.has(c)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()&&this.isBracesClose()){let l=this._segment.trim();if(c===Z.MINUS&&l===""){const f=this._findPreviousToken(s,o-1)||"",m=this._findNextToken(s,o+1)||"";if(this._unexpectedEndingTokenExcludeOperator(f)&&this._isOperatorToken(m)){this._pushNodeToChildren("0"),this._pushNodeToChildren(Z.MINUS),this._addSequenceArray(t,c,o),this._resetSegment(),o++;continue}else if(this._unexpectedEndingToken(f))if(m===Z.PLUS){this._pushSegment(Z.MINUS),this._addSequenceArray(t,c,o),this._addSequenceArray(t,Z.PLUS,o+1),o+=2;continue}else{this._pushSegment(Z.MINUS),this._addSequenceArray(t,c,o),o++;continue}}else if(this._segment.length>0&&this._isScientificNotation(s,o,c)){this._pushSegment(c),this._addSequenceArray(t,c,o),o++;continue}else this._segment.length>0&&l===""?l=this._segment:(this._pushNodeToChildren(this._segment),l="");if(c===Z.LESS_THAN||c===Z.GREATER_THAN){const f=s[o+1];if(f&&yt.has(c+f)){this._pushNodeToChildren(l+c+f),this._resetSegment(),this._addSequenceArray(t,c,o),o++,this._addSequenceArray(t,f,o),o++;continue}else this._pushNodeToChildren(l+c)}else this._pushNodeToChildren(l+c);this._resetSegment()}else this._pushSegment(c);this._addSequenceArray(t,c,o),o++}if(this._pushNodeToChildren(this._segment),this._checkErrorState())return h.VALUE}_isScientificNotation(e,t,r){const n=e[t-2];if(n&&Number.isNaN(Number(n))||!(r===Z.MINUS||r===Z.PLUS))return!1;const s=e[t+1];if(s&&Number.isNaN(Number(s)))return!1;const a=e[t-1];return a&&a.toUpperCase()==="E"}_addSequenceArray(e,t,r){e==null||e.push({segment:this._segment,currentString:t,cur:r,currentLexerNode:this._currentLexerNode})}}function Rc(i,u,e,t,r,n,s){const a=(s==null?void 0:s.f)||"",o=(s==null?void 0:s.si)||"",c=S.isFormulaString(a),l=S.isFormulaId(o),f=i.getValue(r,n),m=(f==null?void 0:f.f)||"",d=(f==null?void 0:f.si)||"";function _(){var C;if(S.isFormulaString(m)&&S.isFormulaId(d)){const E=(C=e==null?void 0:e[d])==null?void 0:C.f;E?t.set(d,E):t.set(d,m)}}c&&l?(d!==o&&_(),i.setValue(r,n,{f:a,si:o}),e[o]={f:a,r,c:n},u.setValue(r,n,{f:a,si:o})):c&&!l?(m!==a&&_(),i.setValue(r,n,{f:a}),u.setValue(r,n,{f:a})):!c&&l?(d!==o&&_(),i.setValue(r,n,{f:"",si:o})):!c&&!l&&i.getValue(r,n)&&(_(),i.realDeleteValue(r,n),u.setValue(r,n,null))}function Nc(i,u,e,t){const r=i==null?void 0:i.getValue(e,t);if(r==null)return!0;const n=[];i.forValue((l,f,m)=>{l===e&&f===t||S.Rectangle.intersects(m,r)&&n.push(m)});const{startRow:s,startColumn:a,endRow:o,endColumn:c}=r;for(let l=s;l<=o;l++)for(let f=a;f<=c;f++){let m=!1;const d=S.cellToRange(l,f);n.some(_=>S.Rectangle.contains(_,d)?(m=!0,!0):!1),m||u.realDeleteValue(l,f)}}var pc=Object.defineProperty,Vc=Object.getOwnPropertyDescriptor,Oc=(i,u,e,t)=>{for(var r=t>1?void 0:t?Vc(u,e):u,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(u,e,r):s(r))||r);return t&&r&&pc(u,e,r),r},ti=(i,u)=>(e,t)=>u(e,t,i);w.FormulaDataModel=class extends S.Disposable{constructor(e,t){super();A(this,"_arrayFormulaRange",{});A(this,"_arrayFormulaCellData",{});this._univerInstanceService=e,this._lexerTreeBuilder=t}dispose(){super.dispose(),this._arrayFormulaRange={},this._arrayFormulaCellData={}}clearPreviousArrayFormulaCellData(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;Object.keys(r).forEach(n=>{var l,f,m,d;const s=r[n],a=(f=(l=this._arrayFormulaRange)==null?void 0:l[t])==null?void 0:f[n];if(a==null)return!0;const o=new S.ObjectMatrix(a);let c=new S.ObjectMatrix;((m=this._arrayFormulaCellData[t])==null?void 0:m[n])!=null&&(c=new S.ObjectMatrix((d=this._arrayFormulaCellData[t])==null?void 0:d[n])),s.forValue((_,C)=>{const E=o.getValue(_,C);if(E==null)return!0;const{startRow:b,startColumn:R,endRow:N,endColumn:V}=E;for(let M=b;M<=N;M++)for(let D=R;D<=V;D++)c.setValue(M,D,null);o.realDeleteValue(_,C)}),this._arrayFormulaCellData[t]&&(this._arrayFormulaCellData[t][n]=c.getData())})})}mergeArrayFormulaCellData(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;this._arrayFormulaRange[t]==null&&(this._arrayFormulaRange[t]={}),this._arrayFormulaCellData[t]==null&&(this._arrayFormulaCellData[t]={}),Object.keys(r).forEach(n=>{var c,l;const s=r[n],a=new S.ObjectMatrix((c=this._arrayFormulaRange[t])==null?void 0:c[n]),o=new S.ObjectMatrix((l=this._arrayFormulaCellData[t])==null?void 0:l[n]);s.forValue((f,m)=>{const d=a==null?void 0:a.getValue(f,m);if(d==null)return!0;const{startRow:_,startColumn:C,endRow:E,endColumn:b}=d;for(let R=_;R<=E;R++)for(let N=C;N<=b;N++)o.setValue(R,N,null)}),s.forValue((f,m,d)=>{o.setValue(f,m,d)}),this._arrayFormulaCellData[t]&&(this._arrayFormulaCellData[t][n]=o.getData())})})}getFormulaData(){const e={},t=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET);return t.length===0||t.forEach(r=>{const n=r.getUnitId();e[n]={},r.getSheets().forEach(a=>{const o=a.getCellMatrix(),c=a.getSheetId();os(e,n,c,o)})}),e}getSheetFormulaData(e,t){const r={},n=this._univerInstanceService.getUnit(e);if(n==null)return{};r[e]={};const s=n.getSheetBySheetId(t);if(s==null)return{};const a=s.getCellMatrix();return os(r,e,t,a),r[e][t]}getArrayFormulaRange(){return this._arrayFormulaRange}setArrayFormulaRange(e){this._arrayFormulaRange=e}getArrayFormulaCellData(){return this._arrayFormulaCellData}setArrayFormulaCellData(e){this._arrayFormulaCellData=e}mergeArrayFormulaRange(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;this._arrayFormulaRange[t]||(this._arrayFormulaRange[t]={}),Object.keys(r).forEach(n=>{var o;const s=new S.ObjectMatrix(r[n]),a=new S.ObjectMatrix((o=this._arrayFormulaRange[t])==null?void 0:o[n]);s.forValue((c,l,f)=>{a.setValue(c,l,f)}),this._arrayFormulaRange[t]&&(this._arrayFormulaRange[t][n]=a.getData())})})}deleteArrayFormulaRange(e,t,r,n){var o;const s=(o=this._arrayFormulaRange[e])==null?void 0:o[t];if(s==null)return;const a=new S.ObjectMatrix(s);a.getValue(r,n)&&(a.realDeleteValue(r,n),this._arrayFormulaRange[e]&&(this._arrayFormulaRange[e][t]=a.getData()))}getCalculateData(){const e=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET),t={},r={};for(const n of e){const s=n.getUnitId(),a=n.getSheets(),o={},c={};for(const l of a){const f=l.getSheetId(),m=l.getConfig();o[f]={cellData:new S.ObjectMatrix(m.cellData),rowCount:m.rowCount,columnCount:m.columnCount,rowData:m.rowData,columnData:m.columnData,defaultRowHeight:m.defaultRowHeight,defaultColumnWidth:m.defaultColumnWidth},c[l.getName()]=l.getSheetId()}t[s]=o,r[s]=c}return{allUnitData:t,unitSheetNameMap:r}}updateFormulaData(e,t,r){const n=new S.ObjectMatrix(r),s=this._getSheetFormulaIdMap(e,t),a=new Map,o=this.getFormulaData();o[e]==null&&(o[e]={});const c=o[e];c[t]==null&&(c[t]={});const l=new S.ObjectMatrix(c[t]||{}),f=new S.ObjectMatrix;return n.forValue((m,d,_)=>{Rc(l,f,s,a,m,d,_)}),l.forValue((m,d,_)=>{const C=(_==null?void 0:_.f)||"",E=(_==null?void 0:_.si)||"";if(S.isFormulaId(E)){const b=s==null?void 0:s[E],R=a.get(E);if(b&&!S.isFormulaString(C)){const N=b.f,V=d-b.c,M=m-b.r;l.setValue(m,d,{f:N,si:E,x:V,y:M}),f.setValue(m,d,{f:N,si:E,x:V,y:M})}else if(typeof R=="string"){const N=(_==null?void 0:_.x)||0,V=(_==null?void 0:_.y)||0,M=this._lexerTreeBuilder.moveFormulaRefOffset(R,N,V);a.set(E,{r:m,c:d,f:M}),l.setValue(m,d,{f:M,si:E}),f.setValue(m,d,{f:M,si:E})}else if(typeof R=="object"){const N=d-R.c,V=m-R.r;l.setValue(m,d,{f:R.f,si:E,x:N,y:V}),f.setValue(m,d,{f:R.f,si:E,x:N,y:V})}}}),f.getMatrix()}updateArrayFormulaRange(e,t,r){var o;const n=(o=this._arrayFormulaRange[e])==null?void 0:o[t];if(!n)return;const s=new S.ObjectMatrix(n);new S.ObjectMatrix(r).forValue((c,l,f)=>{s.realDeleteValue(c,l)})}updateArrayFormulaCellData(e,t,r){var l,f;const n=(l=this._arrayFormulaRange[e])==null?void 0:l[t];if(!n)return;const s=new S.ObjectMatrix(n),a=(f=this._arrayFormulaCellData[e])==null?void 0:f[t];if(!a)return;const o=new S.ObjectMatrix(a);new S.ObjectMatrix(r).forValue((m,d,_)=>{Nc(s,o,m,d)})}getFormulaStringByCell(e,t,r,n){const s=this._univerInstanceService.getUnit(n);if(s==null)return null;const a=s.getSheetBySheetId(r);if(a==null)return null;const o=a.getCellMatrix(),c=o.getValue(e,t);if(c==null)return null;const{f:l,si:f}=c;if(S.isFormulaString(l))return l;if(S.isFormulaId(f)){let m=null;return o.forValue((d,_,C)=>{if(C==null)return!0;const{f:E,si:b}=C;if(S.isFormulaString(E)&&f===b)return m=this._lexerTreeBuilder.moveFormulaRefOffset(E,t-_,e-d),!1}),m}return null}getFormulaDirtyRanges(){const e=this.getFormulaData(),t=[];for(const r in e){const n=e[r];if(!n)continue;const s=this._univerInstanceService.getUnit(r);if(s)for(const a in n){const o=n[a];if(!o)continue;const c=s.getSheetBySheetId(a);if(!c)continue;const l={};for(const f of Object.keys(o)){const m=Number(f);for(const d in o[m]){const _=Number(d),C=c.getCellRaw(m,_),E=S.isFormulaString(C==null?void 0:C.f)||S.isFormulaId(C==null?void 0:C.si),b=(C==null?void 0:C.v)===void 0;if(!(E&&b))continue;l[_]||(l[_]=[]);const R=l[_].slice(-1)[0];R&&R.endRow===m-1?R.endRow=m:l[_].push({startRow:m,endRow:m})}}for(const f in l){const m=l[f];for(let d=0;d<m.length;d++){const _=m[d];t.push({unitId:r,sheetId:a,range:{rangeType:S.RANGE_TYPE.NORMAL,startRow:_.startRow,endRow:_.endRow,startColumn:Number(f),endColumn:Number(f)}})}}}}return t}_getSheetFormulaIdMap(e,t){const r={},n=this._univerInstanceService.getUnit(e);if(n==null)return r;const s=n.getSheetBySheetId(t);return s==null||s.getCellMatrix().forValue((o,c,l)=>{if(l==null)return!0;const{f,si:m}=l;S.isFormulaString(f)&&S.isFormulaId(m)&&(r[m]={f,r:o,c})}),r}},w.FormulaDataModel=Oc([ti(0,S.IUniverInstanceService),ti(1,S.Inject(qr))],w.FormulaDataModel);function os(i,u,e,t){i[u]||(i[u]={}),i[u][e]||(i[u][e]={});const r=new Map,n=new S.ObjectMatrix(i[u][e]);t.forValue((a,o,c)=>{const l=(c==null?void 0:c.f)||"",f=(c==null?void 0:c.si)||"",m=S.isFormulaString(l),d=S.isFormulaId(f);m&&d?(n.setValue(a,o,{f:l,si:f}),r.set(f,{f:l,r:a,c:o})):m&&!d?n.setValue(a,o,{f:l}):!m&&d&&n.setValue(a,o,{f:"",si:f})}),n.forValue((a,o,c)=>{const l=(c==null?void 0:c.f)||"",f=(c==null?void 0:c.si)||"";if(S.isFormulaId(f)&&!S.isFormulaString(l)){const m=r.get(f);if(m){const d=m.f,_=o-m.c,C=a-m.r;n.setValue(a,o,{f:d,si:f,x:_,y:C})}else n.realDeleteValue(a,o)}});const s=n.getMatrix();return{[u]:{[e]:s}}}const Mc=class Ra{constructor(u,e){this.low=u,this.high=e}clone(){return new Ra(this.low,this.high)}get max(){return this.clone()}less_than(u){return this.low<u.low||this.low===u.low&&this.high<u.high}equal_to(u){return this.low===u.low&&this.high===u.high}intersect(u){return!this.not_intersect(u)}not_intersect(u){return this.high<u.low||u.high<this.low}merge(u){return new Ra(this.low===void 0?u.low:this.low<u.low?this.low:u.low,this.high===void 0?u.high:this.high>u.high?this.high:u.high)}output(){return[this.low,this.high]}static comparable_max(u,e){return u.merge(e)}static comparable_less_than(u,e){return u<e}},Pe=0,Ae=1;class Bt{constructor(u=void 0,e=void 0,t=null,r=null,n=null,s=Ae){if(this.left=t,this.right=r,this.parent=n,this.color=s,this.item={key:u,value:e},u&&u instanceof Array&&u.length===2&&!Number.isNaN(u[0])&&!Number.isNaN(u[1])){let[a,o]=u;a>o&&([a,o]=[o,a]),this.item.key=new Mc(a,o)}this.max=this.item.key?this.item.key.max:void 0}isNil(){return this.item.key===void 0&&this.item.value===void 0&&this.left===null&&this.right===null&&this.color===Ae}_value_less_than(u){return this.item.value&&u.item.value&&this.item.value.less_than?this.item.value.less_than(u.item.value):this.item.value<u.item.value}less_than(u){return this.item.value===this.item.key&&u.item.value===u.item.key?this.item.key.less_than(u.item.key):this.item.key.less_than(u.item.key)||this.item.key.equal_to(u.item.key)&&this._value_less_than(u)}_value_equal(u){return this.item.value&&u.item.value&&this.item.value.equal_to?this.item.value.equal_to(u.item.value):this.item.value===u.item.value}equal_to(u){return this.item.value===this.item.key&&u.item.value===u.item.key?this.item.key.equal_to(u.item.key):this.item.key.equal_to(u.item.key)&&this._value_equal(u)}intersect(u){return this.item.key.intersect(u.item.key)}copy_data(u){this.item.key=u.item.key,this.item.value=u.item.value}update_max(){if(this.max=this.item.key?this.item.key.max:void 0,this.right&&this.right.max){const u=this.item.key.constructor.comparable_max;this.max=u(this.max,this.right.max)}if(this.left&&this.left.max){const u=this.item.key.constructor.comparable_max;this.max=u(this.max,this.left.max)}}not_intersect_left_subtree(u){const e=this.item.key.constructor.comparable_less_than;let t=this.left.max.high!==void 0?this.left.max.high:this.left.max;return e(t,u.item.key.low)}not_intersect_right_subtree(u){const e=this.item.key.constructor.comparable_less_than;let t=this.right.max.low!==void 0?this.right.max.low:this.right.item.key.low;return e(u.item.key.high,t)}}class cs{constructor(){this.root=null,this.nil_node=new Bt}get size(){let u=0;return this.tree_walk(this.root,()=>u++),u}get keys(){let u=[];return this.tree_walk(this.root,e=>u.push(e.item.key.output?e.item.key.output():e.item.key)),u}get values(){let u=[];return this.tree_walk(this.root,e=>u.push(e.item.value)),u}get items(){let u=[];return this.tree_walk(this.root,e=>u.push({key:e.item.key.output?e.item.key.output():e.item.key,value:e.item.value})),u}isEmpty(){return this.root==null||this.root===this.nil_node}clear(){this.root=null}insert(u,e=u){if(u===void 0)return;let t=new Bt(u,e,this.nil_node,this.nil_node,null,Pe);return this.tree_insert(t),this.recalc_max(t),t}exist(u,e=u){let t=new Bt(u,e);return!!this.tree_search(this.root,t)}remove(u,e=u){let t=new Bt(u,e),r=this.tree_search(this.root,t);return r&&this.tree_delete(r),r}search(u,e=(t,r)=>t===r?r.output():t){let t=new Bt(u),r=[];return this.tree_search_interval(this.root,t,r),r.map(n=>e(n.item.value,n.item.key))}intersect_any(u){let e=new Bt(u);return this.tree_find_any_interval(this.root,e)}forEach(u){this.tree_walk(this.root,e=>u(e.item.key,e.item.value))}map(u){const e=new cs;return this.tree_walk(this.root,t=>e.insert(t.item.key,u(t.item.value,t.item.key))),e}*iterate(u,e=(t,r)=>t===r?r.output():t){let t;for(u?t=this.tree_search_nearest_forward(this.root,new Bt(u)):this.root&&(t=this.local_minimum(this.root));t;)yield e(t.item.value,t.item.key),t=this.tree_successor(t)}recalc_max(u){let e=u;for(;e.parent!=null;)e.parent.update_max(),e=e.parent}tree_insert(u){let e=this.root,t=null;if(this.root==null||this.root===this.nil_node)this.root=u;else{for(;e!==this.nil_node;)t=e,u.less_than(e)?e=e.left:e=e.right;u.parent=t,u.less_than(t)?t.left=u:t.right=u}this.insert_fixup(u)}insert_fixup(u){let e,t;for(e=u;e!==this.root&&e.parent.color===Pe;)e.parent===e.parent.parent.left?(t=e.parent.parent.right,t.color===Pe?(e.parent.color=Ae,t.color=Ae,e.parent.parent.color=Pe,e=e.parent.parent):(e===e.parent.right&&(e=e.parent,this.rotate_left(e)),e.parent.color=Ae,e.parent.parent.color=Pe,this.rotate_right(e.parent.parent))):(t=e.parent.parent.left,t.color===Pe?(e.parent.color=Ae,t.color=Ae,e.parent.parent.color=Pe,e=e.parent.parent):(e===e.parent.left&&(e=e.parent,this.rotate_right(e)),e.parent.color=Ae,e.parent.parent.color=Pe,this.rotate_left(e.parent.parent)));this.root.color=Ae}tree_delete(u){let e,t;u.left===this.nil_node||u.right===this.nil_node?e=u:e=this.tree_successor(u),e.left!==this.nil_node?t=e.left:t=e.right,t.parent=e.parent,e===this.root?this.root=t:(e===e.parent.left?e.parent.left=t:e.parent.right=t,e.parent.update_max()),this.recalc_max(t),e!==u&&(u.copy_data(e),u.update_max(),this.recalc_max(u)),e.color===Ae&&this.delete_fixup(t)}delete_fixup(u){let e=u,t;for(;e!==this.root&&e.parent!=null&&e.color===Ae;)e===e.parent.left?(t=e.parent.right,t.color===Pe&&(t.color=Ae,e.parent.color=Pe,this.rotate_left(e.parent),t=e.parent.right),t.left.color===Ae&&t.right.color===Ae?(t.color=Pe,e=e.parent):(t.right.color===Ae&&(t.color=Pe,t.left.color=Ae,this.rotate_right(t),t=e.parent.right),t.color=e.parent.color,e.parent.color=Ae,t.right.color=Ae,this.rotate_left(e.parent),e=this.root)):(t=e.parent.left,t.color===Pe&&(t.color=Ae,e.parent.color=Pe,this.rotate_right(e.parent),t=e.parent.left),t.left.color===Ae&&t.right.color===Ae?(t.color=Pe,e=e.parent):(t.left.color===Ae&&(t.color=Pe,t.right.color=Ae,this.rotate_left(t),t=e.parent.left),t.color=e.parent.color,e.parent.color=Ae,t.left.color=Ae,this.rotate_right(e.parent),e=this.root));e.color=Ae}tree_search(u,e){if(!(u==null||u===this.nil_node))return e.equal_to(u)?u:e.less_than(u)?this.tree_search(u.left,e):this.tree_search(u.right,e)}tree_search_nearest_forward(u,e){let t,r=u;for(;r&&r!==this.nil_node;)r.less_than(e)?r.intersect(e)?(t=r,r=r.left):r=r.right:((!t||r.less_than(t))&&(t=r),r=r.left);return t||null}tree_search_interval(u,e,t){u!=null&&u!==this.nil_node&&(u.left!==this.nil_node&&!u.not_intersect_left_subtree(e)&&this.tree_search_interval(u.left,e,t),u.intersect(e)&&t.push(u),u.right!==this.nil_node&&!u.not_intersect_right_subtree(e)&&this.tree_search_interval(u.right,e,t))}tree_find_any_interval(u,e){let t=!1;return u!=null&&u!==this.nil_node&&(u.left!==this.nil_node&&!u.not_intersect_left_subtree(e)&&(t=this.tree_find_any_interval(u.left,e)),t||(t=u.intersect(e)),!t&&u.right!==this.nil_node&&!u.not_intersect_right_subtree(e)&&(t=this.tree_find_any_interval(u.right,e))),t}local_minimum(u){let e=u;for(;e.left!=null&&e.left!==this.nil_node;)e=e.left;return e}local_maximum(u){let e=u;for(;e.right!=null&&e.right!==this.nil_node;)e=e.right;return e}tree_successor(u){let e,t,r;if(u.right!==this.nil_node)e=this.local_minimum(u.right);else{for(t=u,r=u.parent;r!=null&&r.right===t;)t=r,r=r.parent;e=r}return e}rotate_left(u){let e=u.right;u.right=e.left,e.left!==this.nil_node&&(e.left.parent=u),e.parent=u.parent,u===this.root?this.root=e:u===u.parent.left?u.parent.left=e:u.parent.right=e,e.left=u,u.parent=e,u!=null&&u!==this.nil_node&&u.update_max(),e=u.parent,e!=null&&e!==this.nil_node&&e.update_max()}rotate_right(u){let e=u.left;u.left=e.right,e.right!==this.nil_node&&(e.right.parent=u),e.parent=u.parent,u===this.root?this.root=e:u===u.parent.left?u.parent.left=e:u.parent.right=e,e.right=u,u.parent=e,u!==null&&u!==this.nil_node&&u.update_max(),e=u.parent,e!=null&&e!==this.nil_node&&e.update_max()}tree_walk(u,e){u!=null&&u!==this.nil_node&&(this.tree_walk(u.left,e),e(u),this.tree_walk(u.right,e))}testRedBlackProperty(){let u=!0;return this.tree_walk(this.root,function(e){e.color===Pe&&(e.left.color===Ae&&e.right.color===Ae||(u=!1))}),u}testBlackHeightProperty(u){let e=0,t=0,r=0;if(u.color===Ae&&e++,u.left!==this.nil_node?t=this.testBlackHeightProperty(u.left):t=1,u.right!==this.nil_node?r=this.testBlackHeightProperty(u.right):r=1,t!==r)throw new Error("Red-black height property violated");return e+=t,e}}class Sc{constructor(){A(this,"_cache",new Map);A(this,"_continueBuildingCache",new Map)}set(u,e,t,r,n){if(!this.shouldContinueBuildingCache(u,e,t,n))return;let s=this._cache.get(u);s==null&&(s=new Map,this._cache.set(u,s));let a=s.get(e);a==null&&(a=new Map,s.set(e,a));let o=a.get(t);o==null&&(o=new Map,a.set(t,o));let c=o.get(r);c==null&&(c=new Set,o.set(r,c)),c.add(n)}getCellValuePositions(u,e,t){var r,n;return(n=(r=this._cache.get(u))==null?void 0:r.get(e))==null?void 0:n.get(t)}getCellPositions(u,e,t,r,n){var a,o,c;const s=(c=(o=(a=this._cache.get(u))==null?void 0:a.get(e))==null?void 0:o.get(t))==null?void 0:c.get(r);return s&&[...s].filter(l=>n.some(([f,m])=>l>=f&&l<=m))}setContinueBuildingCache(u,e,t,r,n){if(t===-1||r===-1||n===-1)return;let s=this._continueBuildingCache.get(u);s==null&&(s=new Map,this._continueBuildingCache.set(u,s));let a=s.get(e);a==null&&(a=new Map,s.set(e,a));let o=a.get(t);if(o==null){o=new cs,o.insert([r,n]),a.set(t,o);return}this._handleNewInterval(o,r,n)}shouldContinueBuildingCache(u,e,t,r){var a,o;if(t===-1||r===-1)return!1;const n=(o=(a=this._continueBuildingCache.get(u))==null?void 0:a.get(e))==null?void 0:o.get(t);return n?n.search([r,r]).length===0:!0}canUseCache(u,e,t,r,n){var f,m;const s=(m=(f=this._continueBuildingCache.get(u))==null?void 0:f.get(e))==null?void 0:m.get(t);if(t===-1||r===-1||n===-1||!s)return{rowsInCache:[],rowsNotInCache:[]};const a=s.search([r,n]);if(a.length===0)return{rowsInCache:[],rowsNotInCache:[]};a.sort((d,_)=>d[0]-_[0]);const o=[],c=[];let l=r;for(let d=0;d<a.length;d++){const[_,C]=a[d];if(l>=_){if(n<=C){o.push([l,n]);break}o.push([l,C]),l=C+1,d===a.length-1&&l<=n&&c.push([l,n])}else{if(n>C){o.push([_,C]),c.push([l,_-1]),l=C+1,d===a.length-1&&l<=n&&c.push([l,n]);continue}o.push([_,n]),c.push([l,_-1])}}return{rowsInCache:o,rowsNotInCache:c}}clear(){this._cache.clear(),this._continueBuildingCache.clear()}_handleNewInterval(u,e,t){let r=u.search([e,t]);if(r.length===0){const a=[e-1<0?0:e-1,t+1];if(r=u.search(a),r.length===0){u.insert([e,t]);return}}let n=e,s=t;for(const a of r)n=Math.min(n,a[0]),s=Math.max(s,a[1]),u.remove(a);u.insert([n,s])}}const pt=new Sc,Kr="engine-formula.config",ri=1,Dc="CYCLE_REFERENCE_COUNT",ni={};var wc=Object.defineProperty,Pc=Object.getOwnPropertyDescriptor,Lc=(i,u,e,t)=>{for(var r=t>1?void 0:t?Pc(u,e):u,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(u,e,r):s(r))||r);return t&&r&&wc(u,e,r),r},si=(i,u)=>(e,t)=>u(e,t,i);w.FormulaCurrentConfigService=class extends S.Disposable{constructor(e,t){super();A(this,"_unitData",{});A(this,"_unitStylesData",{});A(this,"_arrayFormulaCellData",{});A(this,"_arrayFormulaRange",{});A(this,"_formulaData",{});A(this,"_sheetNameMap",{});A(this,"_forceCalculate",!1);A(this,"_clearDependencyTreeCache",{});A(this,"_dirtyRanges",[]);A(this,"_dirtyNameMap",{});A(this,"_dirtyDefinedNameMap",{});A(this,"_dirtyUnitFeatureMap",{});A(this,"_dirtyUnitOtherFormulaMap",{});A(this,"_excludedCell");A(this,"_sheetIdToNameMap",{});A(this,"_executeUnitId","");A(this,"_executeSubUnitId","");this._univerInstanceService=e,this._localeService=t}dispose(){this._unitData={},this._unitStylesData={},this._formulaData={},this._arrayFormulaCellData={},this._arrayFormulaRange={},this._sheetNameMap={},this._dirtyRanges=[],this._dirtyNameMap={},this._dirtyDefinedNameMap={},this._dirtyUnitFeatureMap={},this._excludedCell={},this._sheetIdToNameMap={},this._dirtyUnitOtherFormulaMap={}}getExecuteUnitId(){return this._executeUnitId}getExecuteSubUnitId(){return this._executeSubUnitId}setExecuteUnitId(e){this._executeUnitId=e}setExecuteSubUnitId(e){this._executeSubUnitId=e}getExcludedRange(){return this._excludedCell}getUnitData(){return this._unitData}getUnitStylesData(){return this._unitStylesData}getFormulaData(){return this._formulaData}getArrayFormulaCellData(){return this._arrayFormulaCellData}getArrayFormulaRange(){return this._arrayFormulaRange}getSheetNameMap(){return this._sheetNameMap}isForceCalculate(){return this._forceCalculate}getDirtyRanges(){return this._dirtyRanges}getDirtyNameMap(){return this._dirtyNameMap}getDirtyDefinedNameMap(){return this._dirtyDefinedNameMap}getDirtyUnitFeatureMap(){return this._dirtyUnitFeatureMap}getDirtyUnitOtherFormulaMap(){return this._dirtyUnitOtherFormulaMap}getSheetName(e,t){return this._sheetIdToNameMap[e]==null?"":this._sheetIdToNameMap[e][t]||""}getClearDependencyTreeCache(){return this._clearDependencyTreeCache}getLocale(){return this._localeService.getCurrentLocale()}getSheetsInfo(){const e=this._univerInstanceService.getCurrentUnitForType(S.UniverInstanceType.UNIVER_SHEET),{id:t,sheetOrder:r}=e.getSnapshot();return{sheetOrder:r,sheetNameMap:this._sheetIdToNameMap[t]}}getSheetRowColumnCount(e,t){const r=this._univerInstanceService.getUnit(e),n=r==null?void 0:r.getSheetBySheetId(t),s=n==null?void 0:n.getSnapshot();if(!s)return{rowCount:0,columnCount:0};const{rowCount:a,columnCount:o}=s;return{rowCount:a,columnCount:o}}load(e){if(e.allUnitData&&e.unitSheetNameMap&&e.unitStylesData)this._unitData=e.allUnitData,this._unitStylesData=e.unitStylesData,this._sheetNameMap=e.unitSheetNameMap;else{const{allUnitData:t,unitSheetNameMap:r,unitStylesData:n}=this._loadSheetData();this._unitData=t,this._unitStylesData=n,this._sheetNameMap=r}this._formulaData=e.formulaData,this._arrayFormulaCellData=Sa(e.arrayFormulaCellData),this._arrayFormulaRange=e.arrayFormulaRange,this._forceCalculate=e.forceCalculate,this._clearDependencyTreeCache=e.clearDependencyTreeCache||{},this._dirtyRanges=e.dirtyRanges,this._dirtyNameMap=e.dirtyNameMap,this._dirtyDefinedNameMap=e.dirtyDefinedNameMap,this._dirtyUnitFeatureMap=e.dirtyUnitFeatureMap,this._dirtyUnitOtherFormulaMap=e.dirtyUnitOtherFormulaMap,this._excludedCell=e.excludedCell,this._mergeNameMap(this._sheetNameMap,this._dirtyNameMap)}getDirtyData(){return{forceCalculation:this._forceCalculate,dirtyRanges:this._dirtyRanges,dirtyNameMap:this._dirtyNameMap,dirtyDefinedNameMap:this._dirtyDefinedNameMap,dirtyUnitFeatureMap:this._dirtyUnitFeatureMap,dirtyUnitOtherFormulaMap:this._dirtyUnitOtherFormulaMap,clearDependencyTreeCache:this._clearDependencyTreeCache}}loadDirtyRangesAndExcludedCell(e,t){this._dirtyRanges=e,this._excludedCell=t,this._dirtyNameMap={}}registerUnitData(e){this._unitData=e}registerFormulaData(e){this._formulaData=e}registerSheetNameMap(e){this._sheetNameMap=e}_mergeNameMap(e,t){Object.keys(t).forEach(r=>{t[r]&&Object.keys(t[r]).forEach(n=>{e[r]==null&&(e[r]={}),e[r][t[r][n]]=n})}),this._sheetIdToNameMap={},Object.keys(e).forEach(r=>{Object.keys(e[r]).forEach(n=>{this._sheetIdToNameMap[r]==null&&(this._sheetIdToNameMap[r]={}),this._sheetIdToNameMap[r][e[r][n]]=n})})}_loadSheetData(){const e=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET),t=this._univerInstanceService.getCurrentUnitForType(S.UniverInstanceType.UNIVER_SHEET),r=t==null?void 0:t.getActiveSheet();this._executeUnitId=t==null?void 0:t.getUnitId(),this._executeSubUnitId=r==null?void 0:r.getSheetId();const n={},s={},a={};for(const o of e){const c=o.getUnitId(),l=o.getSheets(),f={},m={};for(const d of l){const _=d.getSheetId(),C=d.getConfig();f[_]={cellData:new S.ObjectMatrix(C.cellData),rowCount:C.rowCount,columnCount:C.columnCount,rowData:C.rowData,columnData:C.columnData,defaultRowHeight:C.defaultRowHeight,defaultColumnWidth:C.defaultColumnWidth},m[d.getName()]=d.getSheetId()}n[c]=f,s[c]=o.getStyles(),a[c]=m}return{allUnitData:n,unitStylesData:s,unitSheetNameMap:a}}},w.FormulaCurrentConfigService=Lc([si(0,S.IUniverInstanceService),si(1,S.Inject(S.LocaleService))],w.FormulaCurrentConfigService);const dt=S.createIdentifier("univer.formula.current-data.service");var jc=Object.defineProperty,xc=Object.getOwnPropertyDescriptor,Uc=(i,u,e,t)=>{for(var r=t>1?void 0:t?xc(u,e):u,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(u,e,r):s(r))||r);return t&&r&&jc(u,e,r),r},ls=(i,u)=>(e,t)=>u(e,t,i);w.Lexer=class extends S.Disposable{constructor(u,e,t){super(),this._definedNamesService=u,this._lexerTreeBuilder=e,this._formulaCurrentConfigService=t}treeBuilder(u,e=!0){return this._lexerTreeBuilder.treeBuilder(u,e,this._injectDefinedName.bind(this),this._simpleCheckDefinedName.bind(this))}_simpleCheckDefinedName(u){const e=this._formulaCurrentConfigService.getDirtyDefinedNameMap(),t=this._formulaCurrentConfigService.getExecuteUnitId();if(t!=null&&e[t]!=null){const r=Object.keys(e[t]);for(let n=0,s=r.length;n<s;n++){const a=r[n];if(u.indexOf(a)>-1)return!0}}return!1}_checkDefinedNameDirty(u){const e=this._formulaCurrentConfigService.getDirtyDefinedNameMap(),t=this._formulaCurrentConfigService.getExecuteUnitId();if(t!=null&&e[t]!=null){const r=Object.keys(e[t]);for(let n=0,s=r.length;n<s;n++)if(r[n]===u)return!0}return!1}_injectDefinedName(u){const e=this._formulaCurrentConfigService.getExecuteUnitId();if(e==null)return{sequenceString:"",hasDefinedName:!1,definedNames:[]};const t=this._lexerTreeBuilder.getSequenceNode(u);let r="",n=!1;const s=[];for(let a=0,o=t.length;a<o;a++){const c=t[a];if(typeof c=="string"){r+=c;continue}const{nodeType:l,token:f}=c;if(l===Te.REFERENCE||l===Te.FUNCTION){const m=this._definedNamesService.getValueByName(e,f);if(m){let d=m.formulaOrRefString;d.substring(0,1)===Z.EQUALS&&(d=d.substring(1)),r+=d,s.push(m.name),n=!0}else this._checkDefinedNameDirty(f)?(r+=h.NAME,n=!0,s.push(f)):r+=f}else r+=f}return{sequenceString:r,hasDefinedName:n,definedNames:s}}},w.Lexer=Uc([ls(0,Tt),ls(1,S.Inject(qr)),ls(2,dt)],w.Lexer);function Xr(i){if(i==null)return!0;const{v:u,f:e,si:t,p:r}=i;return!(!(u==null||typeof u=="string"&&u.length===0)||e!=null&&e.length>0||t!=null&&t.length>0||r!=null)}function ai(i,u,e,t,r){var s;const n=Object.keys(r);for(const a of n){const o=r[a],c=(s=o==null?void 0:o[t])==null?void 0:s[e];if(c==null)continue;const l=c.getValue(i,u);if(l!=null)return l}}const Tc=["$","£","¥","¤","֏","؋","৳","฿","៛","₡","₦","₩","₪","₫","€","₭","₮","₱","₲","₴","₸","₹","₺","₼","₽","₾","₿"],vc={currency:2,date:4,datetime:5,error:11,fraction:7,general:0,grouped:11,number:1,percent:6,scientific:8,text:9,time:5,unknown:11};function Bc(i,u,e){var o,c;if(i==null||u==null)return u;const t=(e==null?void 0:e.getStyleByCell(i))||i.s,r=(e==null?void 0:e.getStyleByCell(u))||u.s;if(t==null||r==null||typeof t!="object"||typeof r!="object")return u;const n=(o=t==null?void 0:t.n)==null?void 0:o.pattern,s=(c=r==null?void 0:r.n)==null?void 0:c.pattern;if(n==null||s==null)return u;const a=n||s;return r.n.pattern=a,u}const fs=new gt(1e5);function ii(i){const u=fs.get(i);if(u!==void 0)return u;const e=Fc(i);return fs.set(i,e),e}function Ic(){fs.clear()}function Fc(i){if(kc(i))return 3;const u=S.numfmt.getInfo(i).type||"unknown";return vc[u]}function kc(i){return!!Tc.find(u=>i.includes(u))&&i.startsWith("_(")}function Zr(i,u,e){if(i==="")return u;if(u==="")return i;const t=ii(i),r=ii(u);return e===Z.PLUS||e===Z.MINUS?t===4&&r===4||t===11&&r===11?"":u:e===Z.MULTIPLY||e===Z.DIVIDED?t===6&&r===6||t===7&&r===7||t===8&&r===8||t===9&&r===9?u:"":i||u}const $c=new Map([[S.LocaleType.EN_US,"$"],[S.LocaleType.RU_RU,"₽"],[S.LocaleType.VI_VN,"₫"],[S.LocaleType.ZH_CN,"¥"],[S.LocaleType.ZH_TW,"NT$"]]);function ui(i){return $c.get(i)||"$"}function $e(i,u=2){let e=u;u>127&&(e=127);let t="";return e>0&&(t=`.${"0".repeat(e)}`),`"${ui(i)}"#,##0${t}_);[Red]("${ui(i)}"#,##0${t})`}function Yc(i,u,e=2){return S.numfmt.format($e(i,e),u)}const ms=new gt(1e5);function Hc(i){let u=i;u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1));const e=ms.get(u);if(e)return{isNumberPattern:!0,value:e.value,pattern:e.pattern};const t=S.numfmt.parseNumber(u);if(t)return hs(u,t.v,t.z);const r=S.numfmt.parseDate(u);if(r)return hs(u,r.v,r.z);const n=S.numfmt.parseTime(u);return n?hs(u,n.v,n.z):{isNumberPattern:!1}}function hs(i,u,e){return ms.set(i,{value:u,pattern:e}),{isNumberPattern:!0,value:u,pattern:e}}function Gc(){ms.clear()}class zr{constructor(){A(this,"pattern","")}dispose(){}getPattern(){return this.pattern}setPattern(u){this.pattern=u}isError(){return!1}isAsyncObject(){return!1}isAsyncArrayObject(){return!1}isReferenceObject(){return!1}isArray(){return!1}isValueObject(){return!1}isEqualType(u){return!1}}class Ct extends zr{constructor(u){super(),this._rawValue=u}isValueObject(){return!0}toUnitRange(){return{range:{startColumn:-1,startRow:-1,endRow:-1,endColumn:-1},sheetId:"",unitId:""}}getValue(){return 0}getArrayValue(){return[]}setValue(u){}setArrayValue(u){}isCube(){return!1}isString(){return!1}isNumber(){return!1}isBoolean(){return!1}isLambda(){return!1}isError(){return!1}isNull(){return!1}sum(){return g.create(h.VALUE)}max(){return g.create(h.VALUE)}min(){return g.create(h.VALUE)}count(){return g.create(h.VALUE)}countA(){return g.create(h.VALUE)}countBlank(){return g.create(h.VALUE)}getNegative(){return g.create(h.VALUE)}getReciprocal(){return g.create(h.VALUE)}plus(u){return g.create(h.VALUE)}minus(u){return g.create(h.VALUE)}multiply(u){return g.create(h.VALUE)}divided(u){return g.create(h.VALUE)}mod(u){return g.create(h.VALUE)}map(u){return g.create(h.NAME)}mapValue(u){return g.create(h.NAME)}compare(u,e,t=!1){return g.create(h.NAME)}isEqual(u){return this.compare(u,H.EQUALS)}isNotEqual(u){return this.compare(u,H.NOT_EQUAL)}isGreaterThanOrEqual(u){return this.compare(u,H.GREATER_THAN_OR_EQUAL)}isLessThanOrEqual(u){return this.compare(u,H.LESS_THAN_OR_EQUAL)}isLessThan(u){return this.compare(u,H.LESS_THAN)}isGreaterThan(u){return this.compare(u,H.GREATER_THAN)}concatenateFront(u){return g.create(h.NAME)}concatenateBack(u){return g.create(h.NAME)}plusBy(u){return g.create(h.VALUE)}minusBy(u){return g.create(h.VALUE)}multiplyBy(u){return g.create(h.VALUE)}dividedBy(u){return g.create(h.VALUE)}modInverse(u){return g.create(h.VALUE)}compareBy(u,e){return g.create(h.NAME)}concatenate(u,e=ze.FRONT){let t=this.getValue().toString();if(typeof u=="string")e===ze.FRONT?t=u+t:t+=u;else if(typeof u=="number")e===ze.FRONT?t=u.toString()+t:t+=u.toString();else if(typeof u=="boolean"){const r=u?"TRUE":"FALSE";e===ze.FRONT?t=r+t:t+=r}return t}pow(u){return g.create(h.VALUE)}powInverse(u){return g.create(h.VALUE)}sqrt(){return g.create(h.VALUE)}cbrt(){return g.create(h.VALUE)}cos(){return g.create(h.VALUE)}cosh(){return g.create(h.VALUE)}acos(){return g.create(h.VALUE)}acosh(){return g.create(h.VALUE)}sin(){return g.create(h.VALUE)}sinh(){return g.create(h.VALUE)}asin(){return g.create(h.VALUE)}asinh(){return g.create(h.VALUE)}tan(){return g.create(h.VALUE)}tanh(){return g.create(h.VALUE)}atan(){return g.create(h.VALUE)}atan2(u){return g.create(h.VALUE)}atan2Inverse(u){return g.create(h.VALUE)}atanh(){return g.create(h.VALUE)}mean(){return this}median(){return this}var(){return this}std(){return this}log(){return g.create(h.VALUE)}log10(){return g.create(h.VALUE)}exp(){return g.create(h.VALUE)}abs(){return g.create(h.VALUE)}round(u){return g.create(h.VALUE)}roundInverse(u){return g.create(h.VALUE)}floor(u){return g.create(h.VALUE)}floorInverse(u){return g.create(h.VALUE)}ceil(u){return g.create(h.VALUE)}ceilInverse(u){return g.create(h.VALUE)}convertToNumberObjectValue(){return g.create(h.VALUE)}convertToBooleanObjectValue(){return g.create(h.VALUE)}}const Wc=1e3,oi=new gt(Wc);class g extends Ct{constructor(u,e=""){super(u),this._errorType=u,this._errorContent=e}static create(u,e=""){const t=`${u}-${e}`,r=oi.get(t);if(r)return r;const n=new g(u,e);return oi.set(t,n),n}getValue(){return this._errorType}getErrorType(){return this._errorType}getErrorContent(){return this._errorContent}isEqualType(u){return u.getErrorType()===this.getErrorType()}isError(){return!0}}function Qc(i){if(i===null)return 0;if(i!=null&&i.p){const u=i==null?void 0:i.p.body;if(u==null)return 0;const e=u.dataStream;return S.BuildTextUtils.transform.getPlainText(e)}return(i==null?void 0:i.v)||0}var It=(i=>(i[i.MIN=0]="MIN",i[i.MAX=1]="MAX",i))(It||{}),Se=(i=>(i[i.NORMAL=0]="NORMAL",i[i.MIN=1]="MIN",i[i.MAX=2]="MAX",i))(Se||{});function Jr(){return Intl&&Intl.Collator?new Intl.Collator(void 0,{numeric:!1}).compare:(i,u)=>i.localeCompare(u)}function qc(i){return i.indexOf("*")>-1||i.indexOf("?")>-1}function gs(i,u){const e=Xc(u).replace(/~?[*?]/g,r=>r.startsWith("~")?`\\${r.substring(1)}`:r==="*"?".*":r==="?"?".":r);return new RegExp(`^${e}$`).test(i)}function ci(i){return i.replace(/~?[*?]/g,u=>u.startsWith("~")?u.substring(1):" ")}function Kc(i,u,e){let t=!1;switch(e){case H.EQUALS:t=gs(i,u);break;case H.NOT_EQUAL:t=!gs(i,u);break;case H.GREATER_THAN:case H.GREATER_THAN_OR_EQUAL:t=gs(i,u)||i>ci(u);break;case H.LESS_THAN:case H.LESS_THAN_OR_EQUAL:t=i<ci(u);break}return t}function Xc(i){return i.replace(/[.+^${}()|[\]\\]/g,"\\$&")}function ds(i){switch(i){case 1:return 2;case 0:return 0;case-1:return 1;default:return 0}}function Cs(i){return i===-2?1:0}function _s(i){let u;switch(i){case H.EQUALS:u=H.EQUALS;break;case H.GREATER_THAN:u=H.LESS_THAN;break;case H.GREATER_THAN_OR_EQUAL:u=H.LESS_THAN_OR_EQUAL;break;case H.LESS_THAN:u=H.GREATER_THAN;break;case H.LESS_THAN_OR_EQUAL:u=H.GREATER_THAN_OR_EQUAL;break;case H.NOT_EQUAL:u=H.NOT_EQUAL;break}return u}/*!
1
+ (function(w,S){typeof exports=="object"&&typeof module<"u"?S(exports,require("@univerjs/core"),require("rxjs"),require("@univerjs/rpc")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","@univerjs/rpc"],S):(w=typeof globalThis<"u"?globalThis:w||self,S(w.UniverEngineFormula={},w.UniverCore,w.rxjs,w.UniverRpc))})(this,function(w,S,Ze,Io){"use strict";var $E=Object.defineProperty;var YE=(w,S,Ze)=>S in w?$E(w,S,{enumerable:!0,configurable:!0,writable:!0,value:Ze}):w[S]=Ze;var A=(w,S,Ze)=>YE(w,typeof S!="symbol"?S+"":S,Ze);var ya;var Et=(i=>(i.FALSE="FALSE",i.TRUE="TRUE",i))(Et||{}),bt=(i=>(i[i.SUCCESS=0]="SUCCESS",i[i.ERROR=1]="ERROR",i))(bt||{}),ze=(i=>(i[i.FRONT=0]="FRONT",i[i.BACK=1]="BACK",i))(ze||{});function Na(i,u,e,t,r){for(let n=0,s=i.length;n<s;n++){const a=i[n];if(u!==a.unitId||e!==a.sheetId)continue;const{startRow:o,startColumn:c,endRow:l,endColumn:f}=a.range;if(t>=o&&t<=l&&r>=c&&r<=f)return!0}return!1}var h=(i=>(i.DIV_BY_ZERO="#DIV/0!",i.NAME="#NAME?",i.VALUE="#VALUE!",i.NUM="#NUM!",i.NA="#N/A",i.CYCLE="#CYCLE!",i.REF="#REF!",i.SPILL="#SPILL!",i.CALC="#CALC!",i.ERROR="#ERROR!",i.CONNECT="#GETTING_DATA",i.NULL="#NULL!",i))(h||{});const xt=new Set(Object.values(h)),pa=[...new Set(Object.values(h).map(i=>i.length))];var Va=(i=>(i[i.Financial=0]="Financial",i[i.Date=1]="Date",i[i.Math=2]="Math",i[i.Statistical=3]="Statistical",i[i.Lookup=4]="Lookup",i[i.Database=5]="Database",i[i.Text=6]="Text",i[i.Logical=7]="Logical",i[i.Information=8]="Information",i[i.Engineering=9]="Engineering",i[i.Cube=10]="Cube",i[i.Compatibility=11]="Compatibility",i[i.Web=12]="Web",i[i.Array=13]="Array",i[i.Univer=14]="Univer",i[i.User=15]="User",i[i.DefinedName=16]="DefinedName",i))(Va||{}),Z=(i=>(i.PLUS="+",i.MINUS="-",i.MULTIPLY="*",i.DIVIDED="/",i.CONCATENATE="&",i.POWER="^",i.EQUALS="=",i.NOT_EQUAL="<>",i.GREATER_THAN=">",i.GREATER_THAN_OR_EQUAL=">=",i.LESS_THAN="<",i.LESS_THAN_OR_EQUAL="<=",i))(Z||{}),H=(i=>(i.EQUALS="=",i.NOT_EQUAL="<>",i.GREATER_THAN=">",i.GREATER_THAN_OR_EQUAL=">=",i.LESS_THAN="<",i.LESS_THAN_OR_EQUAL="<=",i))(H||{});const Ur=new Map([["<>",4],["<",4],[">=",4],["=",4],[">",4],["<=",4],["&",3],["+",2],["-",2],["/",1],["*",1],["^",0]]),yt=new Set(Ur.keys()),Fo=new Set(["=","<>",">",">=","<","<="]);var X=(i=>(i.OPEN_BRACKET="(",i.CLOSE_BRACKET=")",i.COMMA=",",i.SINGLE_QUOTATION="'",i.DOUBLE_QUOTATION='"',i.OPEN_BRACES="{",i.CLOSE_BRACES="}",i.COLON=":",i.OPEN_SQUARE_BRACKET="[",i.CLOSE_SQUARE_BRACKET="]",i))(X||{}),Ge=(i=>(i.PERCENTAGE="%",i.POUND="#",i))(Ge||{});const Qn=new Set(["%","#"]);var Ve=(i=>(i.AT="@",i.MINUS="-",i.PLUS="+",i))(Ve||{});const ko=" ",Oa=[...Object.values(H),...Object.values(Z),...Object.values(X),...Object.values(Ge),...Object.values(Ve)];function gr(i){return Oa.includes(i)}function Ma(i){for(const u of Oa)if(i.indexOf(u)>-1)return!0;return!1}function $o(i){return i[0]==="'"&&i[i.length-1]==="'"?i.substring(1,i.length-1):i}function Yo(i){return gr(i)&&i!==X.CLOSE_BRACES&&i!==X.CLOSE_BRACKET&&i!==X.SINGLE_QUOTATION&&i!==X.DOUBLE_QUOTATION||i===" "}const Ho=new Set([Z.PLUS,Z.MINUS,Z.MULTIPLY,Z.DIVIDED,Z.CONCATENATE,Z.POWER,Z.EQUALS,Z.NOT_EQUAL,Z.GREATER_THAN,Z.GREATER_THAN_OR_EQUAL,Z.LESS_THAN,Z.LESS_THAN_OR_EQUAL,X.OPEN_BRACKET,X.COMMA,X.COLON,X.OPEN_BRACES,X.OPEN_SQUARE_BRACKET]);function Go(i){return Ho.has(i)}const Wo=new Set([Z.PLUS,Z.MINUS,Z.MULTIPLY,Z.DIVIDED,Z.CONCATENATE,Z.POWER,Z.EQUALS,Z.NOT_EQUAL,Z.GREATER_THAN,Z.GREATER_THAN_OR_EQUAL,Z.LESS_THAN,Z.LESS_THAN_OR_EQUAL,X.OPEN_BRACKET,X.COMMA,X.COLON,X.OPEN_BRACES,X.OPEN_SQUARE_BRACKET,Ge.PERCENTAGE,Ge.POUND]);function Qo(i){return Wo.has(i)}function Sa(i){const u={};return Object.keys(i).forEach(e=>{const t=i[e];if(t==null)return!0;u[e]==null&&(u[e]={}),Object.keys(t).forEach(r=>{const n=t[r];u[e][r]=new S.ObjectMatrix(n)})}),u}function qo(i){const u={};for(const e in i){const t=i[e];if(t!=null){u[e]==null&&(u[e]={});for(const r in t){const n=t[r],s={};n.forValue((a,o,c)=>{s[a]===void 0&&(s[a]={}),s[a][o]=c}),u[e][r]=s}}}return u}const Da='\\[([^\\[\\]\\/?:"<>|*\\\\]+)\\]',wa=new RegExp(Da),Ko="((?![\\[\\]\\/?*\\\\]).)*!",Rt="$",qn="\\s*?:\\s*?",Tr="[A-Za-z]+",vr="[1-9][0-9]*",Jt=`'?(${Da})?(${Ko})?'?`,Kn=`\\${Rt}?${Tr}\\${Rt}?${vr}`,Xo=`^(${Ve.AT})?${Jt}${Kn}${qn}${Kn}$`,Pa=new RegExp(Xo),Zo=`^${Jt}\\s*?${Kn}(${Ge.POUND})?$`,La=new RegExp(Zo),zo=`^${Jt}\\${Rt}?${vr}${qn}\\${Rt}?${vr}$`,ja=new RegExp(zo),Jo=`^${Jt}\\${Rt}?${Tr}${qn}\\${Rt}?${Tr}$`,xa=new RegExp(Jo),ec=`^${Jt}\\s*?\\${Rt}?${vr}$`,Ua=new RegExp(ec),tc=`^${Jt}\\s*?\\${Rt}?${Tr}$`,Ta=new RegExp(tc),rc="{.*?}",va=new RegExp(rc,"g");function dr(i){return La.lastIndex=0,La.test(i)}function nc(i){return Pa.lastIndex=0,Pa.test(i)}function Ba(i){return ja.lastIndex=0,ja.test(i)}function Ia(i){return xa.lastIndex=0,xa.test(i)}function Fa(i){return Ua.lastIndex=0,Ua.test(i)}function ka(i){return Ta.lastIndex=0,Ta.test(i)}function sc(i){return va.lastIndex=0,va.test(i)}function $a(i){return dr(i)||nc(i)||Ba(i)||Ia(i)}const Ya={id:"formula.mutation.register-function",type:S.CommandType.MUTATION,handler:()=>!0},Br={id:"formula.mutation.set-array-formula-data",type:S.CommandType.MUTATION,handler:(i,u)=>!0},ac=/[^0-9]/g,ic=/[^A-Za-z]/g;function Cr(i){let u=i[0]==="$";const e=i.substring(1);let t=e.indexOf("$")>-1;return S.Tools.isStringNumber(e)&&u&&!t&&(u=!1,t=!0),u&&t?S.AbsoluteRefType.ALL:u?S.AbsoluteRefType.COLUMN:t?S.AbsoluteRefType.ROW:S.AbsoluteRefType.NONE}function uc(i){const u=i.split("!");u.length>1&&(i=u[u.length-1]);const e=i.split(":");return e.length>1?{startAbsoluteRefType:Cr(e[0]),endAbsoluteRefType:Cr(e[1])}:{startAbsoluteRefType:Cr(e[0])}}function Ha(i=S.AbsoluteRefType.NONE){let u="",e="";return i===S.AbsoluteRefType.ROW?u="$":i===S.AbsoluteRefType.COLUMN?e="$":i===S.AbsoluteRefType.ALL&&(u="$",e="$"),{rowAbsoluteString:u,columnAbsoluteString:e}}function Ut(i){const{startColumn:u,startRow:e,endColumn:t,endRow:r,startAbsoluteRefType:n,endAbsoluteRefType:s,rangeType:a=S.RANGE_TYPE.NORMAL}=i,o=Ha(n),c=Ha(s);if(a===S.RANGE_TYPE.ROW||a===S.RANGE_TYPE.ALL){const m=`${o.rowAbsoluteString}${e+1}`,d=`${c.rowAbsoluteString}${r+1}`;return`${m}:${d}`}if(a===S.RANGE_TYPE.COLUMN){const m=`${o.columnAbsoluteString}${S.Tools.chatAtABC(u)}`,d=`${c.columnAbsoluteString}${S.Tools.chatAtABC(t)}`;return`${m}:${d}`}const l=`${o.columnAbsoluteString}${S.Tools.chatAtABC(u)}${o.rowAbsoluteString}${e+1}`,f=`${c.columnAbsoluteString}${S.Tools.chatAtABC(t)}${c.rowAbsoluteString}${r+1}`;return l===f?l:`${l}:${f}`}function Ga(i,u){return`${Ka(i)}!${Ut(u)}`}function Wa(i,u,e){return Xn(i)||Xn(u)?`'[${Zn(i)}]${Zn(u)}'!${Ut(e)}`:`[${i}]${u}!${Ut(e)}`}function Ir(i){const{unitId:u,sheetName:e,range:t}=i;return u!=null&&u.length>0&&e!=null&&e.length>0?Wa(u,e,t):e!=null&&e.length>0?Ga(e,t):Ut(t)}function Fr(i){const u=Number.parseInt(i.replace(ac,""))-1,e=S.Tools.ABCatNum(i.replace(ic,"")),t=Cr(i);return{row:u,column:e,absoluteRefType:t}}function kr(i){const u=wa.exec(i);let e="";u!=null&&(e=u[0].trim(),e=Xa(e.slice(1,e.length-1)),i=i.replace(wa,""));const t=i.indexOf("!");let r="",n="";return t>-1?(r=i.substring(0,t),r[0]==="'"&&r[r.length-1]==="'"&&(r=r.substring(1,r.length-1)),r=Xa(r),n=i.substring(t+1)):n=i,{refBody:n,sheetName:r,unitId:e}}function _r(i){const{refBody:u,sheetName:e,unitId:t}=kr(i),r=u.indexOf(":");if(r===-1){const _=Fr(u),C=_.row,E=_.column,b=_.absoluteRefType;return{unitId:t,sheetName:e,range:{startRow:C,startColumn:E,endRow:C,endColumn:E,startAbsoluteRefType:b,endAbsoluteRefType:b}}}const n=u.substring(0,r),s=u.substring(r+1),a=Fr(n),o=Fr(s),c=a.row>o.row?o.row:a.row,l=a.column>o.column?o.column:a.column,f=a.row>o.row?a.row:o.row,m=a.column>o.column?a.column:o.column;let d=S.RANGE_TYPE.NORMAL;return Number.isNaN(c)&&Number.isNaN(f)?d=S.RANGE_TYPE.COLUMN:Number.isNaN(l)&&Number.isNaN(m)&&(d=S.RANGE_TYPE.ROW),{unitId:t,sheetName:e,range:{startRow:c,startColumn:l,endRow:f,endColumn:m,startAbsoluteRefType:a.absoluteRefType,endAbsoluteRefType:o.absoluteRefType,rangeType:d}}}const oc=["LOG10"];function Ar(i){const u=Qa(i);if(!$a(u)||oc.includes(u.toUpperCase().trim()))return!1;const{range:e}=_r(u);return!(e.endColumn>=16384)}function Qa(i){const u=[];let e=!1;for(let t=0,r=i.length;t<r;t++){const n=i[t];if(n===ko&&!e)u.push(n);else{if(!e&&(n===Ve.AT||n===Ve.MINUS||n===Ve.PLUS))continue;u.push(n),e=!0}}return u.join("")}function cc(i,u){const e=(i==null?void 0:i.split(","))||[];return i===""||e.length===0?[]:qa(i)?e.map(n=>{const s=_r(n);return{unitId:s.unitId,sheetId:u(s.sheetName),range:s.range,sheetName:s.sheetName}}):[]}function qa(i){return((i==null?void 0:i.split(","))||[]).every(e=>Ar(e.trim()))}function Xn(i){return i.length===0?!1:!!(Ma(i)||lc(i)||fc(i)||mc(i)||/[\s!$%^&*()+\-=\[\]{};':"\\|,.<>\/?()]/.test(i))}function Ka(i){return Xn(i)?`'${Zn(i)}'`:i}function Zn(i){return i.replace(/'/g,"''")}function Xa(i){return i.replace(/''/g,"'")}function lc(i){const u=i.match(/[1-9][0-9]{0,6}/);return/^[A-Z]+[1-9][0-9]{0,6}$/.test(i)&&u!==null}function fc(i){return/^(R(-?[0-9]+)?C(-?[0-9]+)?|C(-?[0-9]+)?|R(-?[0-9]+)?)$/.test(i)}function mc(i){return!new RegExp("^\\p{Letter}","u").test(i.charAt(0))}var hc=Object.defineProperty,gc=Object.getOwnPropertyDescriptor,dc=(i,u,e,t)=>{for(var r=t>1?void 0:t?gc(u,e):u,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(u,e,r):s(r))||r);return t&&r&&hc(u,e,r),r},Cc=(i,u)=>(e,t)=>u(e,t,i);w.DefinedNamesService=class extends S.Disposable{constructor(e){super();A(this,"_definedNameMap",{});A(this,"_update$",new Ze.Subject);A(this,"update$",this._update$.asObservable());A(this,"_currentRange",{unitId:"",sheetId:"",range:{startRow:0,endRow:0,startColumn:0,endColumn:0}});A(this,"_currentRange$",new Ze.Subject);A(this,"currentRange$",this._currentRange$.asObservable());A(this,"_focusRange$",new Ze.Subject);A(this,"focusRange$",this._focusRange$.asObservable());this._univerInstanceService=e}dispose(){this._definedNameMap={}}getWorksheetByRef(e,t){var n;const{sheetName:r}=kr(t);return(n=this._univerInstanceService.getUnit(e))==null?void 0:n.getSheetBySheetName(r)}focusRange(e,t){const r=this.getValueById(e,t);r!=null&&this._focusRange$.next({...r,unitId:e})}setCurrentRange(e){this._currentRange=e,this._currentRange$.next(e)}getCurrentRange(){return this._currentRange}getCurrentRangeForString(){return Ut(this._currentRange.range)}registerDefinedNames(e,t){this._definedNameMap[e]=t,this._update()}registerDefinedName(e,t){this._definedNameMap[e]==null&&(this._definedNameMap[e]={}),this._definedNameMap[e][t.id]=t,this._update()}removeDefinedName(e,t){var r;(r=this._definedNameMap[e])==null||delete r[t],this._update()}removeUnitDefinedName(e){delete this._definedNameMap[e],this._update()}getDefinedNameMap(e){return this._definedNameMap[e]}getValueByName(e,t){var n;const r=this._definedNameMap[e];return r==null?null:(n=Array.from(Object.values(r)).filter(s=>s.name===t))==null?void 0:n[0]}getValueById(e,t){var r;return(r=this._definedNameMap[e])==null?void 0:r[t]}hasDefinedName(e){return this._definedNameMap[e]==null?!1:(Array.from(Object.values(this._definedNameMap[e])).length||0)!==0}_update(){this._update$.next(null)}},w.DefinedNamesService=dc([Cc(0,S.IUniverInstanceService)],w.DefinedNamesService);const Tt=S.createIdentifier("univer.formula.defined-names.service"),_c=(i,u)=>{const{unitId:e,id:t}=u;return{...i.get(Tt).getValueById(e,t),unitId:e}},$r={id:"formula.mutation.set-defined-name",type:S.CommandType.MUTATION,handler:(i,u)=>{if(u==null)return!1;const e=i.get(Tt),{id:t,unitId:r,name:n,formulaOrRefString:s,comment:a,hidden:o,localSheetId:c}=u;return e.registerDefinedName(r,{id:t,name:n.trim(),formulaOrRefString:s.trim(),comment:a==null?void 0:a.trim(),hidden:o,localSheetId:c}),!0}},zn={id:"formula.mutation.remove-defined-name",type:S.CommandType.MUTATION,handler:(i,u)=>{if(u==null)return!1;const e=i.get(Tt),{unitId:t,id:r}=u;return e.removeDefinedName(t,r),!0}},Yr={id:"formula.mutation.set-feature-calculation",type:S.CommandType.MUTATION,handler:()=>!0},Hr={id:"formula.mutation.remove-feature-calculation",type:S.CommandType.MUTATION,handler:()=>!0},Jn={id:"formula.mutation.set-formula-calculation-start",type:S.CommandType.MUTATION,handler:()=>!0},es={id:"formula.mutation.set-formula-calculation-stop",type:S.CommandType.MUTATION,handler:()=>!0},Gr={id:"formula.mutation.set-formula-calculation-notification",type:S.CommandType.MUTATION,handler:()=>!0},ts={id:"formula.mutation.set-formula-calculation-result",type:S.CommandType.MUTATION,handler:()=>!0},rs={id:"formula.mutation.set-formula-data",type:S.CommandType.MUTATION,handler:(i,u)=>!0},Wr={id:"formula.mutation.set-other-formula",type:S.CommandType.MUTATION,handler:()=>!0},Qr={id:"formula.mutation.remove-other-formula",type:S.CommandType.MUTATION,handler:()=>!0},Za={id:"formula.mutation.set-super-table",type:S.CommandType.MUTATION,handler:()=>!0},za={id:"formula.mutation.remove-super-table",type:S.CommandType.MUTATION,handler:()=>!0},ns={id:"formula.mutation.set-super-table-option",type:S.CommandType.MUTATION,handler:()=>!0};class gt{constructor(u){A(this,"_cache");this._cache=new S.LRUMap(u)}set(u,e){const t=this._hash(u);this._cache.set(t,e)}get(u){const e=this._hash(u);return this._cache.get(e)}clear(){this._cache.clear()}_hash(u){return u.length<=64?u:S.hashAlgorithm(u).toString()}}const at="P_1",Nt="R_1",er="L_1",Er="LR_1",Ja="LO_1",Ac="LET",br="LAMBDA",Ec="CUBE",bc=new Set(["RAND","RANDBETWEEN","NOW","TODAY"]),ss=new gt(1e5);function vt(i){const u=ss.get(i);if(u)return u;const e=_r(i);return ss.set(i,e),_r(i)}function yc(){ss.clear()}var Te=(i=>(i[i.NORMAL=0]="NORMAL",i[i.NUMBER=1]="NUMBER",i[i.STRING=2]="STRING",i[i.FUNCTION=3]="FUNCTION",i[i.REFERENCE=4]="REFERENCE",i[i.ARRAY=5]="ARRAY",i[i.DEFINED_NAME=6]="DEFINED_NAME",i))(Te||{});function as(i){let u="";for(const e of i)typeof e=="string"?u+=e:u+=e.token;return u}class ie{constructor(){A(this,"_parent");A(this,"_token",Nt);A(this,"_children",[]);A(this,"_lambdaId");A(this,"_functionDefinitionPrivacyVar");A(this,"_lambdaParameter","");A(this,"_startIndex",-1);A(this,"_endIndex",-1);A(this,"_definedNames",[])}dispose(){var u;this._children.forEach(e=>{typeof e!="string"&&e.dispose()}),(u=this._functionDefinitionPrivacyVar)==null||u.clear(),this._functionDefinitionPrivacyVar=null,this._children=[],this._parent=null,this._definedNames=[]}getDefinedNames(){return this._definedNames}getStartIndex(){return this._startIndex}getLambdaId(){return this._lambdaId}setLambdaId(u){this._lambdaId=u}getFunctionDefinitionPrivacyVar(){return this._functionDefinitionPrivacyVar}setLambdaPrivacyVar(u){this._functionDefinitionPrivacyVar=u}getLambdaParameter(){return this._lambdaParameter}setLambdaParameter(u){this._lambdaParameter=u}getParent(){return this._parent}setParent(u){this._parent=u}getChildren(){return this._children}setChildren(u){this._children=u}addChildren(u){this._children.push(u)}addChildrenFirst(u){this._children.unshift(u)}getToken(){return this._token}setToken(u){this._token=u}setIndex(u,e){this._startIndex=u,this._endIndex=e}setDefinedNames(u){this._definedNames=u}hasDefinedNames(){return this._definedNames.length>0}replaceChild(u,e){const t=this._getIndexInParent(u);t!=null&&(this.getChildren().splice(t,1,e),e.setParent(this))}changeToParent(u){const e=this.getParent();e&&e.removeChild(this),this.setParent(u),u.getChildren().push(this)}removeChild(u){const e=this._getIndexInParent(u);e!=null&&this.getChildren().splice(e,1)}serialize(){const u=this.getToken(),e=this.getChildren(),t=[],r=e.length;for(let n=0;n<r;n++){const s=e[n];s instanceof ie?t.push(s.serialize()):t.push(s)}return{token:u,st:this._startIndex,ed:this._endIndex,children:t}}_getIndexInParent(u){const e=this.getChildren(),t=e.length;for(let r=0;r<t;r++)if(e[r]===u)return r}}const ei=2e3,is=new gt(ei),us=new gt(ei);class qr extends S.Disposable{constructor(){super(...arguments);A(this,"_currentLexerNode",new ie);A(this,"_upLevel",0);A(this,"_segment","");A(this,"_bracketState",[]);A(this,"_squareBracketState",0);A(this,"_bracesState",0);A(this,"_singleQuotationState",0);A(this,"_doubleQuotationState",0);A(this,"_lambdaState",!1);A(this,"_colonState",!1);A(this,"_formulaErrorCount",0);A(this,"_tableBracketState",!1)}dispose(){this._resetTemp(),this._currentLexerNode.dispose(),is.clear(),us.clear()}getUpLevel(){return this._upLevel}isColonClose(){return this._colonState===!1}isColonOpen(){return this._colonState===!0}isDoubleQuotationClose(){return this._doubleQuotationState===0}isLambdaOpen(){return this._lambdaState===!0}isLambdaClose(){return this._lambdaState===!1}isSingleQuotationClose(){return this._singleQuotationState===0}isBracesClose(){return this._bracesState===0}isBracketClose(){return this._bracketState.length===0}isSquareBracketClose(){return this._squareBracketState===0}getCurrentLexerNode(){return this._currentLexerNode}getFunctionAndParameter(e,t){const r=this._getCurrentParamIndex(e,t);if(r==null||r===h.VALUE)return;const n=r[0];if(typeof n=="string")return;let s=n.getParent(),a=n;for(;s;){const o=s.getToken();if(o!==at&&!gr(o)&&s.getStartIndex()!==-1){const c=s.getChildren().indexOf(a);return{functionName:o,paramIndex:c}}a=s,s=s.getParent()}}checkIfAddBracket(e){let t=0,r=e.length-1,n=e[r];for(;(n===X.CLOSE_BRACKET||n===" ")&&r>=0;)n===X.CLOSE_BRACKET&&t++,n=e[--r];const s=this._getCurrentParamIndex(e,e.length-2);if(s==null||s===h.VALUE)return 0;const a=s[0];if(typeof a=="string")return 0;let o=a.getParent(),c=0;for(s[1]===X.OPEN_BRACKET&&c++;o;){const l=o.getToken();l!==at&&l!==X.COLON&&o.getStartIndex()!==-1&&l.toUpperCase()!==br&&(t===0?c+=1:t--),o=o.getParent()}return c}sequenceNodesBuilder(e){const t=us.get(e);if(t)return[...t];const r=this._getSequenceArray(e);if(r.length===0)return;const n=this.getSequenceNode(r);return us.set(e,[...n]),n}convertRefersToAbsolute(e,t,r,n=""){const s=this.sequenceNodesBuilder(e);if(s==null)return e;let a="";e.substring(0,1)===Z.EQUALS&&(a=Z.EQUALS);for(let o=0,c=s.length;o<c;o++){const l=s[o];if(typeof l!="string"&&l.nodeType===Te.REFERENCE){const{token:f,endIndex:m}=l,d=vt(f);if(d==null)continue;const{range:_,sheetName:C,unitId:E}=d,b={..._,startAbsoluteRefType:t,endAbsoluteRefType:r},R=Ir({range:b,unitId:E,sheetName:C||n}),N=R.length-f.length;s[o]={...l,token:R,endIndex:m+N};for(let V=o+1;V<c;V++){const M=s[V];typeof M!="string"&&(M.startIndex+=N,M.endIndex+=N)}}}return`${a}${as(s)}`}moveFormulaRefOffset(e,t,r,n=!1){const s=this.sequenceNodesBuilder(e);if(s==null)return e;const a=[];for(let o=0,c=s.length;o<c;o++){const l=s[o];if(typeof l=="string"||l.nodeType!==Te.REFERENCE){a.push(l);continue}const{token:f}=l,m=vt(f),{sheetName:d,unitId:_}=m;let C=m.range;if(!n&&C.startAbsoluteRefType===S.AbsoluteRefType.ALL&&C.endAbsoluteRefType===S.AbsoluteRefType.ALL){a.push(l);continue}else C=S.moveRangeByOffset(C,t,r,n);let E="";S.isValidRange(C)?E=Ir({range:C,unitId:_,sheetName:d}):E=h.REF,a.push({...l,token:E})}return`=${as(a)}`}_formulaSpellCheck(){if(this._currentLexerNode.getChildren().length===0)return!0;const e=this._currentLexerNode.getChildren()[0];return!!(e instanceof ie||yt.has(e)||Qn.has(e)||e===Ve.AT||e===X.COMMA||e===X.COLON||e===X.OPEN_BRACKET)}getSequenceNode(e){const t=[];let r=!1;for(let n=0,s=e.length;n<s;n++){const a=e[n],o=e[n-1],{segment:c,currentString:l}=a;if(l===X.DOUBLE_QUOTATION&&(r=!0),(c!==""||n===0)&&n!==s-1){t.push(l);continue}let f=(o==null?void 0:o.segment)||"";const m=n-f.length;let d=n-1;const _=n-1;if(n===s-1&&this._isLastMergeString(l)&&(f+=l,d+=1),f===""||Ur.has(f)){t.push(l);continue}const C=f.trim(),E=Qa(C);r===!0&&C[C.length-1]===X.DOUBLE_QUOTATION&&C[0]!==X.OPEN_BRACES?(r=!1,this._processPushSequenceNode(t,Te.STRING,f,m,d,_)):dr(E)&&Ar(E)?this._processPushSequenceNode(t,Te.REFERENCE,f,m,d,_):S.Tools.isStringNumber(C)?this._processPushSequenceNode(t,Te.NUMBER,f,m,d,_):C.length>0&&this._processPushSequenceNode(t,Te.FUNCTION,f,m,d,_),(n!==s-1||!this._isLastMergeString(l))&&t.push(l)}return this._mergeSequenceNodeReference(t)}_processPushSequenceNode(e,t,r,n,s,a){this._pushSequenceNode(e,{nodeType:t,token:r,startIndex:n,endIndex:s},a)}_getCurrentParamIndex(e,t){return this._nodeMaker(e,void 0,t)}_isLastMergeString(e){return e===X.DOUBLE_QUOTATION||S.Tools.isStringNumber(e)||!gr(e)}_mergeSequenceNodeReference(e){const t=[],r=e.length;let n=0;for(;n<r;){const s=e[n];if(typeof s=="string"){const a=e[n-1];if(s.trim()===X.CLOSE_BRACES&&a!=null&&typeof a!="string"&&a.nodeType===Te.FUNCTION&&a.token.trim().substring(0,1)===X.OPEN_BRACES){a.nodeType=Te.ARRAY,a.token+=s,a.endIndex+=s.length,n++;continue}t.push(s)}else{const a=e[n+1],o=e[n+2];a===X.COLON&&typeof s!="string"&&o!=null&&typeof o!="string"&&Ar((s.token+a+o.token).trim())&&(s.nodeType=Te.REFERENCE,s.token+=a+o.token,s.endIndex=o.endIndex,n+=2),t.push(s)}n++}return this._minusSplitSequenceNode(t)}_minusSplitSequenceNode(e){const t=[];for(const r of e){if(typeof r!="string"){const s=r.token.match(/^(\s*([-@+]\s*)+)(.*)$/);if(s){const a=s[1],o=s[3];if(Ar(o.trim())){const c=a.length,l=r.startIndex,f=r.startIndex+c-1,m={nodeType:Te.NORMAL,token:a,startIndex:l,endIndex:f},d={nodeType:Te.REFERENCE,token:o,startIndex:f+1,endIndex:r.endIndex};t.push(m),t.push(d);continue}}}t.push(r)}return t}_pushSequenceNode(e,t,r){const n=r-t.startIndex+1;e.splice(e.length-n,n,t)}nodeMakerTest(e){return this._nodeMaker(e)}treeBuilder(e,t=!0,r,n){if(t===!0){const m=is.get(e),d=n==null?void 0:n(e);if(m&&!d)return m}this._resetCurrentLexerNode(),this._currentLexerNode.setToken(Nt);const s=[];let a=this._nodeMaker(e,s);if(a===h.VALUE||s.length===0)return a;let o=!1,c="",l=[];if(r){const{hasDefinedName:m,sequenceString:d,definedNames:_}=r(s);o=m,c=d,l=_}if(o&&(this._resetCurrentLexerNode(),this._currentLexerNode.setToken(Nt),a=this._nodeMaker(`=${c}`),a===h.VALUE))return a;const f=this._getTopNode(this._currentLexerNode);if(f&&(this._currentLexerNode=f),t){if(!this._suffixExpressionHandler(this._currentLexerNode))return h.VALUE;is.set(e,this._currentLexerNode)}return o&&this._currentLexerNode.setDefinedNames(l),this._currentLexerNode}_suffixExpressionHandler(e){var o;const t=e.getChildren();if(!t)return!1;const r=t.length,n=[],s=[];let a=!0;for(let c=0;c<r;c++){const l=t[c];if(l instanceof ie)a=this._suffixExpressionHandler(l),n.push(l);else{const f=l.trim();if(f==="")continue;if(yt.has(f)){if(f===Z.PLUS&&this._deletePlusForPreNode(t[c-1]))continue;if(f!==Z.PLUS&&f!==Z.MINUS&&this._deletePlusForPreNode(t[c-1]))return!1;for(;s.length>0;){const m=(o=s[s.length-1])==null?void 0:o.trim();if(!m||m===X.OPEN_BRACKET)break;const d=Ur.get(m),_=Ur.get(f);if(!d||!_)break;if(_>=d)n.push(s.pop());else break}s.push(l)}else if(f===X.OPEN_BRACKET)s.push(l);else if(f===X.CLOSE_BRACKET)this._processSuffixExpressionCloseBracket(n,s,t,c);else{if(this._checkCloseBracket(t[c-1]))return!1;n.push(l)}}}return a?this._processSuffixExpressionRemain(n,s,e):!1}_processSuffixExpressionRemain(e,t,r){const n=e.length,s=e[n-1];for(;t.length>0;){const a=t.pop();if(!(s instanceof ie)&&(a===X.OPEN_BRACKET||a===X.CLOSE_BRACKET))return!1;e.push(a)}return r.setChildren(e),!0}_processSuffixExpressionCloseBracket(e,t,r,n){var s;if(this._checkOpenBracket(r[n-1])||this._checkOperator(r[n-1]))return!1;for(;t.length>0;){const a=(s=t[t.length-1])==null?void 0:s.trim();if(!a)break;if(a===X.OPEN_BRACKET){t.pop();break}e.push(t.pop())}}_checkCloseBracket(e){return e===X.CLOSE_BRACKET||e instanceof ie}_checkOpenBracket(e){return e===X.OPEN_BRACKET}_checkOperator(e){return e==null||e instanceof ie?!1:yt.has(e)}_deletePlusForPreNode(e){if(e==null)return!0;if(!(e instanceof ie)){const t=e.trim();if(yt.has(t)||t===X.OPEN_BRACKET)return!0}return!1}_resetCurrentLexerNode(){this._currentLexerNode=new ie}_resetSegment(){this._segment=""}_openBracket(e=0){this._bracketState.push(e)}_closeBracket(){this._bracketState.pop()}_openSquareBracket(){this._squareBracketState+=1}_closeSquareBracket(){this._squareBracketState-=1}_getCurrentBracket(){const e=this._bracketState;return e[e.length-1]}_changeCurrentBracket(e){const t=this._bracketState;t[t.length-1]=e}_openBraces(){this._bracesState+=1}_closeBraces(){this._bracesState-=1}_openSingleQuotation(){this._singleQuotationState+=1}_closeSingleQuotation(){this._singleQuotationState-=1}_openDoubleQuotation(){this._doubleQuotationState+=1}_closeDoubleQuotation(){this._doubleQuotationState-=1}_openLambda(){this._lambdaState=!0}_closeLambda(){this._lambdaState=!1}_openColon(e){this._upLevel=e,this._colonState=!0}_closeColon(){this._upLevel=0,this._colonState=!1}_isTableBracket(){return this._tableBracketState}_openTableBracket(){this._tableBracketState=!0}_closeTableBracket(){this._tableBracketState=!1}_formalErrorOccurred(){this._formulaErrorCount+=1}_hasFormalError(){return this._formulaErrorCount>0}_getLastChildCurrentLexerNode(){const e=this._currentLexerNode.getChildren();if(e&&e.length>0){const t=e[e.length-1];if(t instanceof ie)return t}return!1}_getLastChildCurrent(){const e=this._currentLexerNode.getChildren();return e&&e.length>0?e[e.length-1]:!1}_setParentCurrentLexerNode(){const e=this._currentLexerNode.getParent();return e?(this._currentLexerNode=e,!0):!1}_setAncestorCurrentLexerNode(){var r,n,s,a,o,c;const e=(r=this._currentLexerNode)==null?void 0:r.getParent();let t=!1;if(e&&e.getToken()===er){if((n=e==null?void 0:e.getParent())!=null&&n.getParent()){const l=(a=(s=this._currentLexerNode.getParent())==null?void 0:s.getParent())==null?void 0:a.getParent();l&&(this._currentLexerNode=l),t=!0}}else if(e!=null&&e.getParent()){const l=(o=this._currentLexerNode.getParent())==null?void 0:o.getParent();l&&(this._currentLexerNode=l),t=!0}for(let l=0;l<this._upLevel;l++){const f=(c=this._currentLexerNode)==null?void 0:c.getParent();f&&(this._currentLexerNode=f),this._currentLexerNode?t=!0:t=!1}return t}_segmentCount(){return this._segment.trim().length}_pushSegment(e){this._segment+=e}_pushNodeToChildren(e,t=!1){let r=e;if(r!==""){const n=this._currentLexerNode.getChildren();if(!(r instanceof ie)&&this.isColonOpen()){const s=new ie;s.setToken(r),s.setParent(this._currentLexerNode),r=s}t?n.unshift(r):n.push(r)}this.isColonOpen()&&(this._setAncestorCurrentLexerNode(),this._closeColon())}_setCurrentLexerNode(e,t=!1){this._pushNodeToChildren(e,t),e.setParent(this._currentLexerNode),this._currentLexerNode=e}_newAndPushCurrentLexerNode(e,t,r=!1){const n=new ie;n.setToken(e),n.setIndex(t-e.length,t-1),this._setCurrentLexerNode(n,r)}_getTopNode(e){let t=e;for(;t!=null&&t.getParent();)t=t.getParent();return t}_removeLastChild(){this._currentLexerNode.getChildren().splice(-1)}_formulaErrorLastTokenCheck(e,t){const r=this._findPreviousToken(e,t)||"",n=e.length-1===t;if(!n&&this._isOperatorToken(r)||n&&Go(r))return!0;if(Qn.has(r)){const s=this._findSecondLastNonSpaceToken(e,t);if(s==null||Qo(s))return!0}return!1}_findPreviousToken(e,t){let r=t;for(;r>=0;){const n=e[r];if(n!==" ")return n;r--}}_findSecondLastNonSpaceToken(e,t){let r=t,n=0;for(;r>=0;){const s=e[r];if(s!==" "&&(n++,n===2))return s;r--}return null}_findNextToken(e,t){let r=t;for(;r>=0;){const n=e[r];if(n!==" ")return n;r++}}_unexpectedEndingTokenExcludeOperator(e){return e===X.OPEN_BRACKET||e===X.COMMA||e===Z.EQUALS||e===""}_unexpectedEndingToken(e){return!!(this._isOperatorToken(e)||this._unexpectedEndingTokenExcludeOperator(e))}_isOperatorToken(e){return!!yt.has(e)}_getSequenceArray(e){const t=[];return this._nodeMaker(e,t),t}_resetTemp(){this._currentLexerNode=new ie,this._upLevel=0,this._segment="",this._bracketState=[],this._bracesState=0,this._singleQuotationState=0,this._doubleQuotationState=0,this._lambdaState=!1,this._colonState=!1,this._formulaErrorCount=0}_checkErrorState(){return!!(this._bracketState.length>0||this._bracesState>0||this._singleQuotationState>0||this._doubleQuotationState>0||this._hasFormalError())}_checkSimilarErrorToken(e,t,r){let n=t;if(e!==Ge.POUND)return!0;let s=r[++n];for(;s===" ";)s=r[++n];return!!gr(s)}_checkIfErrorObject(e,t){return!!this._findErrorObject(e,t)}_findErrorObject(e,t){for(let r=0;r<pa.length;r++){const n=pa[r],s=t.slice(e,e+n).join("").toUpperCase();if(xt.has(s))return s}}_nodeMaker(e,t,r){let n=e.replace(/\r\n$/,"").replace(/\r/g," ").replace(/\n/g," ");n.substring(0,1)===Z.EQUALS&&(n=n.substring(1));const s=n.split(""),a=s.length;let o=0;for(this._resetTemp(),this._formulaErrorLastTokenCheck(s,a-1)&&this._formalErrorOccurred();o<a;){const c=s[o];if(r===o)return[this._currentLexerNode,c];if(c===Ge.POUND&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()&&this._checkIfErrorObject(o,s)){const l=this._findErrorObject(o,s);if(l==null)return h.VALUE;this._pushNodeToChildren(l);for(let f=0;f<l.length;f++){const m=s[o];this._pushSegment(m),this._addSequenceArray(t,m,o),o++}this._resetSegment();continue}else if(c===X.OPEN_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())if(this._segmentCount()>0||this.isLambdaOpen()){this.isLambdaClose()&&(this._newAndPushCurrentLexerNode(this._segment,o),this._resetSegment()),this._openBracket(1),this._closeLambda();const l=s[o+1];if(l&&l===X.CLOSE_BRACKET){if(!this._setParentCurrentLexerNode()&&o!==a-1)return h.VALUE;this._addSequenceArray(t,c,o),o++,this._addSequenceArray(t,l,o),o++,this._closeBracket();continue}else l&&this._newAndPushCurrentLexerNode(at,o)}else this._pushNodeToChildren(c),this._openBracket(0),this._resetSegment();else if(c===X.CLOSE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()){this._formulaErrorLastTokenCheck(s,o-1)&&this._formalErrorOccurred(),this._pushNodeToChildren(this._segment),this._resetSegment();const l=this._getCurrentBracket();if(l===0)this._pushNodeToChildren(c);else if(l===1){const f=s[o+1];if(f&&f===X.OPEN_BRACKET){if(!this._setParentCurrentLexerNode()&&o!==a-1)return h.VALUE;this._newAndPushCurrentLexerNode(er,o,!0),this._openLambda()}else if(!this._setAncestorCurrentLexerNode()&&o!==a-1)return h.VALUE}else return h.VALUE;this._closeBracket()}else if(c===X.OPEN_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()){if(this._pushSegment(c),this._openBraces(),!this._formulaSpellCheck())return h.VALUE}else if(c===X.CLOSE_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._pushSegment(c),this._pushNodeToChildren(this._segment),this._resetSegment(),this._closeBraces();else if(c===X.OPEN_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._segment.length>0&&this._openTableBracket(),this._pushSegment(c),this._openSquareBracket();else if(c===X.CLOSE_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._closeSquareBracket(),this.isSquareBracketClose()?(this._pushSegment(c),this._isTableBracket()&&(this._pushNodeToChildren(this._segment),this._resetSegment()),this._closeTableBracket()):this._pushSegment(c);else if(c===X.DOUBLE_QUOTATION&&this.isSingleQuotationClose()&&this.isSquareBracketClose()){if(this.isDoubleQuotationClose())this._openDoubleQuotation();else{const l=s[o+1];l&&l===X.DOUBLE_QUOTATION?o++:this._closeDoubleQuotation()}this._pushSegment(c)}else if(c===X.SINGLE_QUOTATION&&this.isDoubleQuotationClose()){if(this.isSingleQuotationClose())this._openSingleQuotation(),this._segmentCount()===0&&this._resetSegment();else{const l=s[o+1];if(l&&l===X.SINGLE_QUOTATION){this._pushSegment(c),this._addSequenceArray(t,c,o),o++,this._pushSegment(l),this._addSequenceArray(t,l,o),o++;continue}else this._closeSingleQuotation()}this._pushSegment(c)}else if(c===X.COMMA&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){this._formulaErrorLastTokenCheck(s,o-1)&&this._formalErrorOccurred();const l=this._getCurrentBracket();if(l===1||l==null){if(this._pushNodeToChildren(this._segment),this._resetSegment(),!this._setParentCurrentLexerNode()&&o!==a-1&&l!=null)return h.VALUE;this._newAndPushCurrentLexerNode(at,o)}else{const f=new ie;f.setToken(Ec);const m=new ie;m.setToken(at),m.changeToParent(f);const d=this._currentLexerNode.getParent();if(d&&d.getToken()===X.COLON){const _=d.getParent();if(!_)return h.VALUE;d.changeToParent(m),_.setChildren([]),f.changeToParent(_)}else return h.VALUE;this._changeCurrentBracket(1),this._pushNodeToChildren(this._segment),this._resetSegment(),this._currentLexerNode=f,this._newAndPushCurrentLexerNode(at,o)}}else if(c===X.COLON&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){const l=new ie;l.setToken(c);const f=new ie;f.setToken(at),f.setParent(l);const m=new ie;m.setToken(at),m.setParent(l),l.getChildren().push(f,m);let d=l,_=0;if(this._segmentCount()>0){let C,E,b=0;const R=this._segment.trim(),N=R[0],V=R[1];if(N===Ve.MINUS&&(C=new ie,C.setToken(Ve.MINUS),b++),(N===Ve.AT||V===Ve.AT)&&(E=new ie,E.setToken(Ve.AT),C&&(C.addChildren(E),E.setParent(C)),b++),b>0&&(this._segment=R.slice(b)),_=b,E)if(E.addChildren(l),l.setParent(E),E.getParent()){const D=E.getParent();D&&(d=D)}else d=E;else C&&(d=C,C.addChildren(l),l.setParent(C));const M=new ie;M.setToken(this._segment),M.setParent(f),f.getChildren().push(M),this._resetSegment()}else{const C=this._getLastChildCurrentLexerNode();C&&C.changeToParent(f)}this._setCurrentLexerNode(d),this._currentLexerNode=m,this._openColon(_)}else if(Qn.has(c)&&this._checkSimilarErrorToken(c,o,s)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()&&this.isBracesClose()){this._pushNodeToChildren(this._segment);const l=new ie;l.setToken(c);const f=this._getLastChildCurrent();f instanceof ie?f.changeToParent(l):f!==!1&&(l.getChildren().push(f),this._removeLastChild()),this._pushNodeToChildren(l),l.setParent(this._currentLexerNode),this._resetSegment()}else if(yt.has(c)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()&&this.isBracesClose()){let l=this._segment.trim();if(c===Z.MINUS&&l===""){const f=this._findPreviousToken(s,o-1)||"",m=this._findNextToken(s,o+1)||"";if(this._unexpectedEndingTokenExcludeOperator(f)&&this._isOperatorToken(m)){this._pushNodeToChildren("0"),this._pushNodeToChildren(Z.MINUS),this._addSequenceArray(t,c,o),this._resetSegment(),o++;continue}else if(this._unexpectedEndingToken(f))if(m===Z.PLUS){this._pushSegment(Z.MINUS),this._addSequenceArray(t,c,o),this._addSequenceArray(t,Z.PLUS,o+1),o+=2;continue}else{this._pushSegment(Z.MINUS),this._addSequenceArray(t,c,o),o++;continue}}else if(this._segment.length>0&&this._isScientificNotation(s,o,c)){this._pushSegment(c),this._addSequenceArray(t,c,o),o++;continue}else this._segment.length>0&&l===""?l=this._segment:(this._pushNodeToChildren(this._segment),l="");if(c===Z.LESS_THAN||c===Z.GREATER_THAN){const f=s[o+1];if(f&&yt.has(c+f)){this._pushNodeToChildren(l+c+f),this._resetSegment(),this._addSequenceArray(t,c,o),o++,this._addSequenceArray(t,f,o),o++;continue}else this._pushNodeToChildren(l+c)}else this._pushNodeToChildren(l+c);this._resetSegment()}else this._pushSegment(c);this._addSequenceArray(t,c,o),o++}if(this._pushNodeToChildren(this._segment),this._checkErrorState())return h.VALUE}_isScientificNotation(e,t,r){const n=e[t-2];if(n&&Number.isNaN(Number(n))||!(r===Z.MINUS||r===Z.PLUS))return!1;const s=e[t+1];if(s&&Number.isNaN(Number(s)))return!1;const a=e[t-1];return a&&a.toUpperCase()==="E"}_addSequenceArray(e,t,r){e==null||e.push({segment:this._segment,currentString:t,cur:r,currentLexerNode:this._currentLexerNode})}}function Rc(i,u,e,t,r,n,s){const a=(s==null?void 0:s.f)||"",o=(s==null?void 0:s.si)||"",c=S.isFormulaString(a),l=S.isFormulaId(o),f=i.getValue(r,n),m=(f==null?void 0:f.f)||"",d=(f==null?void 0:f.si)||"";function _(){var C;if(S.isFormulaString(m)&&S.isFormulaId(d)){const E=(C=e==null?void 0:e[d])==null?void 0:C.f;E?t.set(d,E):t.set(d,m)}}c&&l?(d!==o&&_(),i.setValue(r,n,{f:a,si:o}),e[o]={f:a,r,c:n},u.setValue(r,n,{f:a,si:o})):c&&!l?(m!==a&&_(),i.setValue(r,n,{f:a}),u.setValue(r,n,{f:a})):!c&&l?(d!==o&&_(),i.setValue(r,n,{f:"",si:o})):!c&&!l&&i.getValue(r,n)&&(_(),i.realDeleteValue(r,n),u.setValue(r,n,null))}function Nc(i,u,e,t){const r=i==null?void 0:i.getValue(e,t);if(r==null)return!0;const n=[];i.forValue((l,f,m)=>{l===e&&f===t||S.Rectangle.intersects(m,r)&&n.push(m)});const{startRow:s,startColumn:a,endRow:o,endColumn:c}=r;for(let l=s;l<=o;l++)for(let f=a;f<=c;f++){let m=!1;const d=S.cellToRange(l,f);n.some(_=>S.Rectangle.contains(_,d)?(m=!0,!0):!1),m||u.realDeleteValue(l,f)}}var pc=Object.defineProperty,Vc=Object.getOwnPropertyDescriptor,Oc=(i,u,e,t)=>{for(var r=t>1?void 0:t?Vc(u,e):u,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(u,e,r):s(r))||r);return t&&r&&pc(u,e,r),r},ti=(i,u)=>(e,t)=>u(e,t,i);w.FormulaDataModel=class extends S.Disposable{constructor(e,t){super();A(this,"_arrayFormulaRange",{});A(this,"_arrayFormulaCellData",{});this._univerInstanceService=e,this._lexerTreeBuilder=t}dispose(){super.dispose(),this._arrayFormulaRange={},this._arrayFormulaCellData={}}clearPreviousArrayFormulaCellData(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;Object.keys(r).forEach(n=>{var l,f,m,d;const s=r[n],a=(f=(l=this._arrayFormulaRange)==null?void 0:l[t])==null?void 0:f[n];if(a==null)return!0;const o=new S.ObjectMatrix(a);let c=new S.ObjectMatrix;((m=this._arrayFormulaCellData[t])==null?void 0:m[n])!=null&&(c=new S.ObjectMatrix((d=this._arrayFormulaCellData[t])==null?void 0:d[n])),s.forValue((_,C)=>{const E=o.getValue(_,C);if(E==null)return!0;const{startRow:b,startColumn:R,endRow:N,endColumn:V}=E;for(let M=b;M<=N;M++)for(let D=R;D<=V;D++)c.setValue(M,D,null);o.realDeleteValue(_,C)}),this._arrayFormulaCellData[t]&&(this._arrayFormulaCellData[t][n]=c.getData())})})}mergeArrayFormulaCellData(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;this._arrayFormulaRange[t]==null&&(this._arrayFormulaRange[t]={}),this._arrayFormulaCellData[t]==null&&(this._arrayFormulaCellData[t]={}),Object.keys(r).forEach(n=>{var c,l;const s=r[n],a=new S.ObjectMatrix((c=this._arrayFormulaRange[t])==null?void 0:c[n]),o=new S.ObjectMatrix((l=this._arrayFormulaCellData[t])==null?void 0:l[n]);s.forValue((f,m)=>{const d=a==null?void 0:a.getValue(f,m);if(d==null)return!0;const{startRow:_,startColumn:C,endRow:E,endColumn:b}=d;for(let R=_;R<=E;R++)for(let N=C;N<=b;N++)o.setValue(R,N,null)}),s.forValue((f,m,d)=>{o.setValue(f,m,d)}),this._arrayFormulaCellData[t]&&(this._arrayFormulaCellData[t][n]=o.getData())})})}getFormulaData(){const e={},t=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET);return t.length===0||t.forEach(r=>{const n=r.getUnitId();e[n]={},r.getSheets().forEach(a=>{const o=a.getCellMatrix(),c=a.getSheetId();os(e,n,c,o)})}),e}getSheetFormulaData(e,t){const r={},n=this._univerInstanceService.getUnit(e);if(n==null)return{};r[e]={};const s=n.getSheetBySheetId(t);if(s==null)return{};const a=s.getCellMatrix();return os(r,e,t,a),r[e][t]}getArrayFormulaRange(){return this._arrayFormulaRange}setArrayFormulaRange(e){this._arrayFormulaRange=e}getArrayFormulaCellData(){return this._arrayFormulaCellData}setArrayFormulaCellData(e){this._arrayFormulaCellData=e}mergeArrayFormulaRange(e){Object.keys(e).forEach(t=>{const r=e[t];if(r==null)return!0;this._arrayFormulaRange[t]||(this._arrayFormulaRange[t]={}),Object.keys(r).forEach(n=>{var o;const s=new S.ObjectMatrix(r[n]),a=new S.ObjectMatrix((o=this._arrayFormulaRange[t])==null?void 0:o[n]);s.forValue((c,l,f)=>{a.setValue(c,l,f)}),this._arrayFormulaRange[t]&&(this._arrayFormulaRange[t][n]=a.getData())})})}deleteArrayFormulaRange(e,t,r,n){var o;const s=(o=this._arrayFormulaRange[e])==null?void 0:o[t];if(s==null)return;const a=new S.ObjectMatrix(s);a.getValue(r,n)&&(a.realDeleteValue(r,n),this._arrayFormulaRange[e]&&(this._arrayFormulaRange[e][t]=a.getData()))}getCalculateData(){const e=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET),t={},r={};for(const n of e){const s=n.getUnitId(),a=n.getSheets(),o={},c={};for(const l of a){const f=l.getSheetId(),m=l.getConfig();o[f]={cellData:new S.ObjectMatrix(m.cellData),rowCount:m.rowCount,columnCount:m.columnCount,rowData:m.rowData,columnData:m.columnData,defaultRowHeight:m.defaultRowHeight,defaultColumnWidth:m.defaultColumnWidth},c[l.getName()]=l.getSheetId()}t[s]=o,r[s]=c}return{allUnitData:t,unitSheetNameMap:r}}updateFormulaData(e,t,r){const n=new S.ObjectMatrix(r),s=this._getSheetFormulaIdMap(e,t),a=new Map,o=this.getFormulaData();o[e]==null&&(o[e]={});const c=o[e];c[t]==null&&(c[t]={});const l=new S.ObjectMatrix(c[t]||{}),f=new S.ObjectMatrix;return n.forValue((m,d,_)=>{Rc(l,f,s,a,m,d,_)}),l.forValue((m,d,_)=>{const C=(_==null?void 0:_.f)||"",E=(_==null?void 0:_.si)||"";if(S.isFormulaId(E)){const b=s==null?void 0:s[E],R=a.get(E);if(b&&!S.isFormulaString(C)){const N=b.f,V=d-b.c,M=m-b.r;l.setValue(m,d,{f:N,si:E,x:V,y:M}),f.setValue(m,d,{f:N,si:E,x:V,y:M})}else if(typeof R=="string"){const N=(_==null?void 0:_.x)||0,V=(_==null?void 0:_.y)||0,M=this._lexerTreeBuilder.moveFormulaRefOffset(R,N,V);a.set(E,{r:m,c:d,f:M}),l.setValue(m,d,{f:M,si:E}),f.setValue(m,d,{f:M,si:E})}else if(typeof R=="object"){const N=d-R.c,V=m-R.r;l.setValue(m,d,{f:R.f,si:E,x:N,y:V}),f.setValue(m,d,{f:R.f,si:E,x:N,y:V})}}}),f.getMatrix()}updateArrayFormulaRange(e,t,r){var o;const n=(o=this._arrayFormulaRange[e])==null?void 0:o[t];if(!n)return;const s=new S.ObjectMatrix(n);new S.ObjectMatrix(r).forValue((c,l,f)=>{s.realDeleteValue(c,l)})}updateArrayFormulaCellData(e,t,r){var l,f;const n=(l=this._arrayFormulaRange[e])==null?void 0:l[t];if(!n)return;const s=new S.ObjectMatrix(n),a=(f=this._arrayFormulaCellData[e])==null?void 0:f[t];if(!a)return;const o=new S.ObjectMatrix(a);new S.ObjectMatrix(r).forValue((m,d,_)=>{Nc(s,o,m,d)})}getFormulaStringByCell(e,t,r,n){const s=this._univerInstanceService.getUnit(n);if(s==null)return null;const a=s.getSheetBySheetId(r);if(a==null)return null;const o=a.getCellMatrix(),c=o.getValue(e,t);if(c==null)return null;const{f:l,si:f}=c;if(S.isFormulaString(l))return l;if(S.isFormulaId(f)){let m=null;return o.forValue((d,_,C)=>{if(C==null)return!0;const{f:E,si:b}=C;if(S.isFormulaString(E)&&f===b)return m=this._lexerTreeBuilder.moveFormulaRefOffset(E,t-_,e-d),!1}),m}return null}getFormulaDirtyRanges(){const e=this.getFormulaData(),t=[];for(const r in e){const n=e[r];if(!n)continue;const s=this._univerInstanceService.getUnit(r);if(s)for(const a in n){const o=n[a];if(!o)continue;const c=s.getSheetBySheetId(a);if(!c)continue;const l={};for(const f of Object.keys(o)){const m=Number(f);for(const d in o[m]){const _=Number(d),C=c.getCellRaw(m,_),E=S.isFormulaString(C==null?void 0:C.f)||S.isFormulaId(C==null?void 0:C.si),b=(C==null?void 0:C.v)===void 0;if(!(E&&b))continue;l[_]||(l[_]=[]);const R=l[_].slice(-1)[0];R&&R.endRow===m-1?R.endRow=m:l[_].push({startRow:m,endRow:m})}}for(const f in l){const m=l[f];for(let d=0;d<m.length;d++){const _=m[d];t.push({unitId:r,sheetId:a,range:{rangeType:S.RANGE_TYPE.NORMAL,startRow:_.startRow,endRow:_.endRow,startColumn:Number(f),endColumn:Number(f)}})}}}}return t}_getSheetFormulaIdMap(e,t){const r={},n=this._univerInstanceService.getUnit(e);if(n==null)return r;const s=n.getSheetBySheetId(t);return s==null||s.getCellMatrix().forValue((o,c,l)=>{if(l==null)return!0;const{f,si:m}=l;S.isFormulaString(f)&&S.isFormulaId(m)&&(r[m]={f,r:o,c})}),r}},w.FormulaDataModel=Oc([ti(0,S.IUniverInstanceService),ti(1,S.Inject(qr))],w.FormulaDataModel);function os(i,u,e,t){i[u]||(i[u]={}),i[u][e]||(i[u][e]={});const r=new Map,n=new S.ObjectMatrix(i[u][e]);t.forValue((a,o,c)=>{const l=(c==null?void 0:c.f)||"",f=(c==null?void 0:c.si)||"",m=S.isFormulaString(l),d=S.isFormulaId(f);m&&d?(n.setValue(a,o,{f:l,si:f}),r.set(f,{f:l,r:a,c:o})):m&&!d?n.setValue(a,o,{f:l}):!m&&d&&n.setValue(a,o,{f:"",si:f})}),n.forValue((a,o,c)=>{const l=(c==null?void 0:c.f)||"",f=(c==null?void 0:c.si)||"";if(S.isFormulaId(f)&&!S.isFormulaString(l)){const m=r.get(f);if(m){const d=m.f,_=o-m.c,C=a-m.r;n.setValue(a,o,{f:d,si:f,x:_,y:C})}else n.realDeleteValue(a,o)}});const s=n.getMatrix();return{[u]:{[e]:s}}}const Mc=class Ra{constructor(u,e){this.low=u,this.high=e}clone(){return new Ra(this.low,this.high)}get max(){return this.clone()}less_than(u){return this.low<u.low||this.low===u.low&&this.high<u.high}equal_to(u){return this.low===u.low&&this.high===u.high}intersect(u){return!this.not_intersect(u)}not_intersect(u){return this.high<u.low||u.high<this.low}merge(u){return new Ra(this.low===void 0?u.low:this.low<u.low?this.low:u.low,this.high===void 0?u.high:this.high>u.high?this.high:u.high)}output(){return[this.low,this.high]}static comparable_max(u,e){return u.merge(e)}static comparable_less_than(u,e){return u<e}},Pe=0,Ae=1;class Bt{constructor(u=void 0,e=void 0,t=null,r=null,n=null,s=Ae){if(this.left=t,this.right=r,this.parent=n,this.color=s,this.item={key:u,value:e},u&&u instanceof Array&&u.length===2&&!Number.isNaN(u[0])&&!Number.isNaN(u[1])){let[a,o]=u;a>o&&([a,o]=[o,a]),this.item.key=new Mc(a,o)}this.max=this.item.key?this.item.key.max:void 0}isNil(){return this.item.key===void 0&&this.item.value===void 0&&this.left===null&&this.right===null&&this.color===Ae}_value_less_than(u){return this.item.value&&u.item.value&&this.item.value.less_than?this.item.value.less_than(u.item.value):this.item.value<u.item.value}less_than(u){return this.item.value===this.item.key&&u.item.value===u.item.key?this.item.key.less_than(u.item.key):this.item.key.less_than(u.item.key)||this.item.key.equal_to(u.item.key)&&this._value_less_than(u)}_value_equal(u){return this.item.value&&u.item.value&&this.item.value.equal_to?this.item.value.equal_to(u.item.value):this.item.value===u.item.value}equal_to(u){return this.item.value===this.item.key&&u.item.value===u.item.key?this.item.key.equal_to(u.item.key):this.item.key.equal_to(u.item.key)&&this._value_equal(u)}intersect(u){return this.item.key.intersect(u.item.key)}copy_data(u){this.item.key=u.item.key,this.item.value=u.item.value}update_max(){if(this.max=this.item.key?this.item.key.max:void 0,this.right&&this.right.max){const u=this.item.key.constructor.comparable_max;this.max=u(this.max,this.right.max)}if(this.left&&this.left.max){const u=this.item.key.constructor.comparable_max;this.max=u(this.max,this.left.max)}}not_intersect_left_subtree(u){const e=this.item.key.constructor.comparable_less_than;let t=this.left.max.high!==void 0?this.left.max.high:this.left.max;return e(t,u.item.key.low)}not_intersect_right_subtree(u){const e=this.item.key.constructor.comparable_less_than;let t=this.right.max.low!==void 0?this.right.max.low:this.right.item.key.low;return e(u.item.key.high,t)}}class cs{constructor(){this.root=null,this.nil_node=new Bt}get size(){let u=0;return this.tree_walk(this.root,()=>u++),u}get keys(){let u=[];return this.tree_walk(this.root,e=>u.push(e.item.key.output?e.item.key.output():e.item.key)),u}get values(){let u=[];return this.tree_walk(this.root,e=>u.push(e.item.value)),u}get items(){let u=[];return this.tree_walk(this.root,e=>u.push({key:e.item.key.output?e.item.key.output():e.item.key,value:e.item.value})),u}isEmpty(){return this.root==null||this.root===this.nil_node}clear(){this.root=null}insert(u,e=u){if(u===void 0)return;let t=new Bt(u,e,this.nil_node,this.nil_node,null,Pe);return this.tree_insert(t),this.recalc_max(t),t}exist(u,e=u){let t=new Bt(u,e);return!!this.tree_search(this.root,t)}remove(u,e=u){let t=new Bt(u,e),r=this.tree_search(this.root,t);return r&&this.tree_delete(r),r}search(u,e=(t,r)=>t===r?r.output():t){let t=new Bt(u),r=[];return this.tree_search_interval(this.root,t,r),r.map(n=>e(n.item.value,n.item.key))}intersect_any(u){let e=new Bt(u);return this.tree_find_any_interval(this.root,e)}forEach(u){this.tree_walk(this.root,e=>u(e.item.key,e.item.value))}map(u){const e=new cs;return this.tree_walk(this.root,t=>e.insert(t.item.key,u(t.item.value,t.item.key))),e}*iterate(u,e=(t,r)=>t===r?r.output():t){let t;for(u?t=this.tree_search_nearest_forward(this.root,new Bt(u)):this.root&&(t=this.local_minimum(this.root));t;)yield e(t.item.value,t.item.key),t=this.tree_successor(t)}recalc_max(u){let e=u;for(;e.parent!=null;)e.parent.update_max(),e=e.parent}tree_insert(u){let e=this.root,t=null;if(this.root==null||this.root===this.nil_node)this.root=u;else{for(;e!==this.nil_node;)t=e,u.less_than(e)?e=e.left:e=e.right;u.parent=t,u.less_than(t)?t.left=u:t.right=u}this.insert_fixup(u)}insert_fixup(u){let e,t;for(e=u;e!==this.root&&e.parent.color===Pe;)e.parent===e.parent.parent.left?(t=e.parent.parent.right,t.color===Pe?(e.parent.color=Ae,t.color=Ae,e.parent.parent.color=Pe,e=e.parent.parent):(e===e.parent.right&&(e=e.parent,this.rotate_left(e)),e.parent.color=Ae,e.parent.parent.color=Pe,this.rotate_right(e.parent.parent))):(t=e.parent.parent.left,t.color===Pe?(e.parent.color=Ae,t.color=Ae,e.parent.parent.color=Pe,e=e.parent.parent):(e===e.parent.left&&(e=e.parent,this.rotate_right(e)),e.parent.color=Ae,e.parent.parent.color=Pe,this.rotate_left(e.parent.parent)));this.root.color=Ae}tree_delete(u){let e,t;u.left===this.nil_node||u.right===this.nil_node?e=u:e=this.tree_successor(u),e.left!==this.nil_node?t=e.left:t=e.right,t.parent=e.parent,e===this.root?this.root=t:(e===e.parent.left?e.parent.left=t:e.parent.right=t,e.parent.update_max()),this.recalc_max(t),e!==u&&(u.copy_data(e),u.update_max(),this.recalc_max(u)),e.color===Ae&&this.delete_fixup(t)}delete_fixup(u){let e=u,t;for(;e!==this.root&&e.parent!=null&&e.color===Ae;)e===e.parent.left?(t=e.parent.right,t.color===Pe&&(t.color=Ae,e.parent.color=Pe,this.rotate_left(e.parent),t=e.parent.right),t.left.color===Ae&&t.right.color===Ae?(t.color=Pe,e=e.parent):(t.right.color===Ae&&(t.color=Pe,t.left.color=Ae,this.rotate_right(t),t=e.parent.right),t.color=e.parent.color,e.parent.color=Ae,t.right.color=Ae,this.rotate_left(e.parent),e=this.root)):(t=e.parent.left,t.color===Pe&&(t.color=Ae,e.parent.color=Pe,this.rotate_right(e.parent),t=e.parent.left),t.left.color===Ae&&t.right.color===Ae?(t.color=Pe,e=e.parent):(t.left.color===Ae&&(t.color=Pe,t.right.color=Ae,this.rotate_left(t),t=e.parent.left),t.color=e.parent.color,e.parent.color=Ae,t.left.color=Ae,this.rotate_right(e.parent),e=this.root));e.color=Ae}tree_search(u,e){if(!(u==null||u===this.nil_node))return e.equal_to(u)?u:e.less_than(u)?this.tree_search(u.left,e):this.tree_search(u.right,e)}tree_search_nearest_forward(u,e){let t,r=u;for(;r&&r!==this.nil_node;)r.less_than(e)?r.intersect(e)?(t=r,r=r.left):r=r.right:((!t||r.less_than(t))&&(t=r),r=r.left);return t||null}tree_search_interval(u,e,t){u!=null&&u!==this.nil_node&&(u.left!==this.nil_node&&!u.not_intersect_left_subtree(e)&&this.tree_search_interval(u.left,e,t),u.intersect(e)&&t.push(u),u.right!==this.nil_node&&!u.not_intersect_right_subtree(e)&&this.tree_search_interval(u.right,e,t))}tree_find_any_interval(u,e){let t=!1;return u!=null&&u!==this.nil_node&&(u.left!==this.nil_node&&!u.not_intersect_left_subtree(e)&&(t=this.tree_find_any_interval(u.left,e)),t||(t=u.intersect(e)),!t&&u.right!==this.nil_node&&!u.not_intersect_right_subtree(e)&&(t=this.tree_find_any_interval(u.right,e))),t}local_minimum(u){let e=u;for(;e.left!=null&&e.left!==this.nil_node;)e=e.left;return e}local_maximum(u){let e=u;for(;e.right!=null&&e.right!==this.nil_node;)e=e.right;return e}tree_successor(u){let e,t,r;if(u.right!==this.nil_node)e=this.local_minimum(u.right);else{for(t=u,r=u.parent;r!=null&&r.right===t;)t=r,r=r.parent;e=r}return e}rotate_left(u){let e=u.right;u.right=e.left,e.left!==this.nil_node&&(e.left.parent=u),e.parent=u.parent,u===this.root?this.root=e:u===u.parent.left?u.parent.left=e:u.parent.right=e,e.left=u,u.parent=e,u!=null&&u!==this.nil_node&&u.update_max(),e=u.parent,e!=null&&e!==this.nil_node&&e.update_max()}rotate_right(u){let e=u.left;u.left=e.right,e.right!==this.nil_node&&(e.right.parent=u),e.parent=u.parent,u===this.root?this.root=e:u===u.parent.left?u.parent.left=e:u.parent.right=e,e.right=u,u.parent=e,u!==null&&u!==this.nil_node&&u.update_max(),e=u.parent,e!=null&&e!==this.nil_node&&e.update_max()}tree_walk(u,e){u!=null&&u!==this.nil_node&&(this.tree_walk(u.left,e),e(u),this.tree_walk(u.right,e))}testRedBlackProperty(){let u=!0;return this.tree_walk(this.root,function(e){e.color===Pe&&(e.left.color===Ae&&e.right.color===Ae||(u=!1))}),u}testBlackHeightProperty(u){let e=0,t=0,r=0;if(u.color===Ae&&e++,u.left!==this.nil_node?t=this.testBlackHeightProperty(u.left):t=1,u.right!==this.nil_node?r=this.testBlackHeightProperty(u.right):r=1,t!==r)throw new Error("Red-black height property violated");return e+=t,e}}class Sc{constructor(){A(this,"_cache",new Map);A(this,"_continueBuildingCache",new Map)}set(u,e,t,r,n){if(!this.shouldContinueBuildingCache(u,e,t,n))return;let s=this._cache.get(u);s==null&&(s=new Map,this._cache.set(u,s));let a=s.get(e);a==null&&(a=new Map,s.set(e,a));let o=a.get(t);o==null&&(o=new Map,a.set(t,o));let c=o.get(r);c==null&&(c=new Set,o.set(r,c)),c.add(n)}getCellValuePositions(u,e,t){var r,n;return(n=(r=this._cache.get(u))==null?void 0:r.get(e))==null?void 0:n.get(t)}getCellPositions(u,e,t,r,n){var a,o,c;const s=(c=(o=(a=this._cache.get(u))==null?void 0:a.get(e))==null?void 0:o.get(t))==null?void 0:c.get(r);return s&&[...s].filter(l=>n.some(([f,m])=>l>=f&&l<=m))}setContinueBuildingCache(u,e,t,r,n){if(t===-1||r===-1||n===-1)return;let s=this._continueBuildingCache.get(u);s==null&&(s=new Map,this._continueBuildingCache.set(u,s));let a=s.get(e);a==null&&(a=new Map,s.set(e,a));let o=a.get(t);if(o==null){o=new cs,o.insert([r,n]),a.set(t,o);return}this._handleNewInterval(o,r,n)}shouldContinueBuildingCache(u,e,t,r){var a,o;if(t===-1||r===-1)return!1;const n=(o=(a=this._continueBuildingCache.get(u))==null?void 0:a.get(e))==null?void 0:o.get(t);return n?n.search([r,r]).length===0:!0}canUseCache(u,e,t,r,n){var f,m;const s=(m=(f=this._continueBuildingCache.get(u))==null?void 0:f.get(e))==null?void 0:m.get(t);if(t===-1||r===-1||n===-1||!s)return{rowsInCache:[],rowsNotInCache:[]};const a=s.search([r,n]);if(a.length===0)return{rowsInCache:[],rowsNotInCache:[]};a.sort((d,_)=>d[0]-_[0]);const o=[],c=[];let l=r;for(let d=0;d<a.length;d++){const[_,C]=a[d];if(l>=_){if(n<=C){o.push([l,n]);break}o.push([l,C]),l=C+1,d===a.length-1&&l<=n&&c.push([l,n])}else{if(n>C){o.push([_,C]),c.push([l,_-1]),l=C+1,d===a.length-1&&l<=n&&c.push([l,n]);continue}o.push([_,n]),c.push([l,_-1])}}return{rowsInCache:o,rowsNotInCache:c}}clear(){this._cache.clear(),this._continueBuildingCache.clear()}_handleNewInterval(u,e,t){let r=u.search([e,t]);if(r.length===0){const a=[e-1<0?0:e-1,t+1];if(r=u.search(a),r.length===0){u.insert([e,t]);return}}let n=e,s=t;for(const a of r)n=Math.min(n,a[0]),s=Math.max(s,a[1]),u.remove(a);u.insert([n,s])}}const pt=new Sc,Kr="engine-formula.config",ri=1,Dc="CYCLE_REFERENCE_COUNT",ni={};var wc=Object.defineProperty,Pc=Object.getOwnPropertyDescriptor,Lc=(i,u,e,t)=>{for(var r=t>1?void 0:t?Pc(u,e):u,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(u,e,r):s(r))||r);return t&&r&&wc(u,e,r),r},si=(i,u)=>(e,t)=>u(e,t,i);w.FormulaCurrentConfigService=class extends S.Disposable{constructor(e,t){super();A(this,"_unitData",{});A(this,"_unitStylesData",{});A(this,"_arrayFormulaCellData",{});A(this,"_arrayFormulaRange",{});A(this,"_formulaData",{});A(this,"_sheetNameMap",{});A(this,"_forceCalculate",!1);A(this,"_clearDependencyTreeCache",{});A(this,"_dirtyRanges",[]);A(this,"_dirtyNameMap",{});A(this,"_dirtyDefinedNameMap",{});A(this,"_dirtyUnitFeatureMap",{});A(this,"_dirtyUnitOtherFormulaMap",{});A(this,"_excludedCell");A(this,"_sheetIdToNameMap",{});A(this,"_executeUnitId","");A(this,"_executeSubUnitId","");this._univerInstanceService=e,this._localeService=t}dispose(){this._unitData={},this._unitStylesData={},this._formulaData={},this._arrayFormulaCellData={},this._arrayFormulaRange={},this._sheetNameMap={},this._dirtyRanges=[],this._dirtyNameMap={},this._dirtyDefinedNameMap={},this._dirtyUnitFeatureMap={},this._excludedCell={},this._sheetIdToNameMap={},this._dirtyUnitOtherFormulaMap={}}getExecuteUnitId(){return this._executeUnitId}getExecuteSubUnitId(){return this._executeSubUnitId}setExecuteUnitId(e){this._executeUnitId=e}setExecuteSubUnitId(e){this._executeSubUnitId=e}getExcludedRange(){return this._excludedCell}getUnitData(){return this._unitData}getUnitStylesData(){return this._unitStylesData}getFormulaData(){return this._formulaData}getArrayFormulaCellData(){return this._arrayFormulaCellData}getArrayFormulaRange(){return this._arrayFormulaRange}getSheetNameMap(){return this._sheetNameMap}isForceCalculate(){return this._forceCalculate}getDirtyRanges(){return this._dirtyRanges}getDirtyNameMap(){return this._dirtyNameMap}getDirtyDefinedNameMap(){return this._dirtyDefinedNameMap}getDirtyUnitFeatureMap(){return this._dirtyUnitFeatureMap}getDirtyUnitOtherFormulaMap(){return this._dirtyUnitOtherFormulaMap}getSheetName(e,t){return this._sheetIdToNameMap[e]==null?"":this._sheetIdToNameMap[e][t]||""}getClearDependencyTreeCache(){return this._clearDependencyTreeCache}getLocale(){return this._localeService.getCurrentLocale()}getSheetsInfo(){const e=this._univerInstanceService.getCurrentUnitForType(S.UniverInstanceType.UNIVER_SHEET),{id:t,sheetOrder:r}=e.getSnapshot();return{sheetOrder:r,sheetNameMap:this._sheetIdToNameMap[t]}}getSheetRowColumnCount(e,t){const r=this._univerInstanceService.getUnit(e),n=r==null?void 0:r.getSheetBySheetId(t),s=n==null?void 0:n.getSnapshot();if(!s)return{rowCount:0,columnCount:0};const{rowCount:a,columnCount:o}=s;return{rowCount:a,columnCount:o}}load(e){if(e.allUnitData&&e.unitSheetNameMap&&e.unitStylesData)this._unitData=e.allUnitData,this._unitStylesData=e.unitStylesData,this._sheetNameMap=e.unitSheetNameMap;else{const{allUnitData:t,unitSheetNameMap:r,unitStylesData:n}=this._loadSheetData();this._unitData=t,this._unitStylesData=n,this._sheetNameMap=r}this._formulaData=e.formulaData,this._arrayFormulaCellData=Sa(e.arrayFormulaCellData),this._arrayFormulaRange=e.arrayFormulaRange,this._forceCalculate=e.forceCalculate,this._clearDependencyTreeCache=e.clearDependencyTreeCache||{},this._dirtyRanges=e.dirtyRanges,this._dirtyNameMap=e.dirtyNameMap,this._dirtyDefinedNameMap=e.dirtyDefinedNameMap,this._dirtyUnitFeatureMap=e.dirtyUnitFeatureMap,this._dirtyUnitOtherFormulaMap=e.dirtyUnitOtherFormulaMap,this._excludedCell=e.excludedCell,this._mergeNameMap(this._sheetNameMap,this._dirtyNameMap)}getDirtyData(){return{forceCalculation:this._forceCalculate,dirtyRanges:this._dirtyRanges,dirtyNameMap:this._dirtyNameMap,dirtyDefinedNameMap:this._dirtyDefinedNameMap,dirtyUnitFeatureMap:this._dirtyUnitFeatureMap,dirtyUnitOtherFormulaMap:this._dirtyUnitOtherFormulaMap,clearDependencyTreeCache:this._clearDependencyTreeCache}}loadDirtyRangesAndExcludedCell(e,t){this._dirtyRanges=e,this._excludedCell=t,this._dirtyNameMap={}}registerUnitData(e){this._unitData=e}registerFormulaData(e){this._formulaData=e}registerSheetNameMap(e){this._sheetNameMap=e}_mergeNameMap(e,t){Object.keys(t).forEach(r=>{t[r]&&Object.keys(t[r]).forEach(n=>{e[r]==null&&(e[r]={}),e[r][t[r][n]]=n})}),this._sheetIdToNameMap={},Object.keys(e).forEach(r=>{Object.keys(e[r]).forEach(n=>{this._sheetIdToNameMap[r]==null&&(this._sheetIdToNameMap[r]={}),this._sheetIdToNameMap[r][e[r][n]]=n})})}_loadSheetData(){const e=this._univerInstanceService.getAllUnitsForType(S.UniverInstanceType.UNIVER_SHEET),t=this._univerInstanceService.getCurrentUnitForType(S.UniverInstanceType.UNIVER_SHEET),r=t==null?void 0:t.getActiveSheet();this._executeUnitId=t==null?void 0:t.getUnitId(),this._executeSubUnitId=r==null?void 0:r.getSheetId();const n={},s={},a={};for(const o of e){const c=o.getUnitId(),l=o.getSheets(),f={},m={};for(const d of l){const _=d.getSheetId(),C=d.getConfig();f[_]={cellData:new S.ObjectMatrix(C.cellData),rowCount:C.rowCount,columnCount:C.columnCount,rowData:C.rowData,columnData:C.columnData,defaultRowHeight:C.defaultRowHeight,defaultColumnWidth:C.defaultColumnWidth},m[d.getName()]=d.getSheetId()}n[c]=f,s[c]=o.getStyles(),a[c]=m}return{allUnitData:n,unitStylesData:s,unitSheetNameMap:a}}},w.FormulaCurrentConfigService=Lc([si(0,S.IUniverInstanceService),si(1,S.Inject(S.LocaleService))],w.FormulaCurrentConfigService);const dt=S.createIdentifier("univer.formula.current-data.service");var jc=Object.defineProperty,xc=Object.getOwnPropertyDescriptor,Uc=(i,u,e,t)=>{for(var r=t>1?void 0:t?xc(u,e):u,n=i.length-1,s;n>=0;n--)(s=i[n])&&(r=(t?s(u,e,r):s(r))||r);return t&&r&&jc(u,e,r),r},ls=(i,u)=>(e,t)=>u(e,t,i);w.Lexer=class extends S.Disposable{constructor(u,e,t){super(),this._definedNamesService=u,this._lexerTreeBuilder=e,this._formulaCurrentConfigService=t}treeBuilder(u,e=!0){return this._lexerTreeBuilder.treeBuilder(u,e,this._injectDefinedName.bind(this),this._simpleCheckDefinedName.bind(this))}_simpleCheckDefinedName(u){const e=this._formulaCurrentConfigService.getDirtyDefinedNameMap(),t=this._formulaCurrentConfigService.getExecuteUnitId();if(t!=null&&e[t]!=null){const r=Object.keys(e[t]);for(let n=0,s=r.length;n<s;n++){const a=r[n];if(u.indexOf(a)>-1)return!0}}return!1}_checkDefinedNameDirty(u){const e=this._formulaCurrentConfigService.getDirtyDefinedNameMap(),t=this._formulaCurrentConfigService.getExecuteUnitId();if(t!=null&&e[t]!=null){const r=Object.keys(e[t]);for(let n=0,s=r.length;n<s;n++)if(r[n]===u)return!0}return!1}_injectDefinedName(u){const e=this._formulaCurrentConfigService.getExecuteUnitId();if(e==null)return{sequenceString:"",hasDefinedName:!1,definedNames:[]};const t=this._lexerTreeBuilder.getSequenceNode(u);let r="",n=!1;const s=[];for(let a=0,o=t.length;a<o;a++){const c=t[a];if(typeof c=="string"){r+=c;continue}const{nodeType:l,token:f}=c;if(l===Te.REFERENCE||l===Te.FUNCTION){const m=this._definedNamesService.getValueByName(e,f);if(m){let d=m.formulaOrRefString;d.substring(0,1)===Z.EQUALS&&(d=d.substring(1)),r+=d,s.push(m.name),n=!0}else this._checkDefinedNameDirty(f)?(r+=h.NAME,n=!0,s.push(f)):r+=f}else r+=f}return{sequenceString:r,hasDefinedName:n,definedNames:s}}},w.Lexer=Uc([ls(0,Tt),ls(1,S.Inject(qr)),ls(2,dt)],w.Lexer);function Xr(i){if(i==null)return!0;const{v:u,f:e,si:t,p:r}=i;return!(!(u==null||typeof u=="string"&&u.length===0)||e!=null&&e.length>0||t!=null&&t.length>0||r!=null)}function ai(i,u,e,t,r){var s;const n=Object.keys(r);for(const a of n){const o=r[a],c=(s=o==null?void 0:o[t])==null?void 0:s[e];if(c==null)continue;const l=c.getValue(i,u);if(l!=null)return l}}const Tc=["$","£","¥","¤","֏","؋","৳","฿","៛","₡","₦","₩","₪","₫","€","₭","₮","₱","₲","₴","₸","₹","₺","₼","₽","₾","₿"],vc={currency:2,date:4,datetime:5,error:11,fraction:7,general:0,grouped:11,number:1,percent:6,scientific:8,text:9,time:5,unknown:11};function Bc(i,u,e){var o,c;if(i==null||u==null)return u;const t=(e==null?void 0:e.getStyleByCell(i))||i.s,r=(e==null?void 0:e.getStyleByCell(u))||u.s;if(t==null||r==null||typeof t!="object"||typeof r!="object")return u;const n=(o=t==null?void 0:t.n)==null?void 0:o.pattern,s=(c=r==null?void 0:r.n)==null?void 0:c.pattern;if(n==null||s==null)return u;const a=n||s;return r.n.pattern=a,u}const fs=new gt(1e5);function ii(i){const u=fs.get(i);if(u!==void 0)return u;const e=Fc(i);return fs.set(i,e),e}function Ic(){fs.clear()}function Fc(i){if(kc(i))return 3;const u=S.numfmt.getInfo(i).type||"unknown";return vc[u]}function kc(i){return!!Tc.find(u=>i.includes(u))&&i.startsWith("_(")}function Zr(i,u,e){if(i==="")return u;if(u==="")return i;const t=ii(i),r=ii(u);return e===Z.PLUS||e===Z.MINUS?t===4&&r===4||t===11&&r===11?"":u:e===Z.MULTIPLY||e===Z.DIVIDED?t===6&&r===6||t===7&&r===7||t===8&&r===8||t===9&&r===9?u:"":i||u}const $c=new Map([[S.LocaleType.EN_US,"$"],[S.LocaleType.RU_RU,"₽"],[S.LocaleType.VI_VN,"₫"],[S.LocaleType.ZH_CN,"¥"],[S.LocaleType.ZH_TW,"NT$"]]);function ui(i){return $c.get(i)||"$"}function $e(i,u=2){let e=u;u>127&&(e=127);let t="";return e>0&&(t=`.${"0".repeat(e)}`),`"${ui(i)}"#,##0${t}_);[Red]("${ui(i)}"#,##0${t})`}function Yc(i,u,e=2){return S.numfmt.format($e(i,e),u)}const ms=new gt(1e5);function Hc(i){let u=i;u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1));const e=ms.get(u);if(e)return{isNumberPattern:!0,value:e.value,pattern:e.pattern};const t=S.numfmt.parseNumber(u);if(t&&t.z)return hs(u,t.v,t.z);const r=S.numfmt.parseDate(u);if(r&&r.z)return hs(u,r.v,r.z);const n=S.numfmt.parseTime(u);return n&&n.z?hs(u,n.v,n.z):{isNumberPattern:!1}}function hs(i,u,e){return ms.set(i,{value:u,pattern:e}),{isNumberPattern:!0,value:u,pattern:e}}function Gc(){ms.clear()}class zr{constructor(){A(this,"pattern","")}dispose(){}getPattern(){return this.pattern}setPattern(u){this.pattern=u}isError(){return!1}isAsyncObject(){return!1}isAsyncArrayObject(){return!1}isReferenceObject(){return!1}isArray(){return!1}isValueObject(){return!1}isEqualType(u){return!1}}class Ct extends zr{constructor(u){super(),this._rawValue=u}isValueObject(){return!0}toUnitRange(){return{range:{startColumn:-1,startRow:-1,endRow:-1,endColumn:-1},sheetId:"",unitId:""}}getValue(){return 0}getArrayValue(){return[]}setValue(u){}setArrayValue(u){}isCube(){return!1}isString(){return!1}isNumber(){return!1}isBoolean(){return!1}isLambda(){return!1}isError(){return!1}isNull(){return!1}sum(){return g.create(h.VALUE)}max(){return g.create(h.VALUE)}min(){return g.create(h.VALUE)}count(){return g.create(h.VALUE)}countA(){return g.create(h.VALUE)}countBlank(){return g.create(h.VALUE)}getNegative(){return g.create(h.VALUE)}getReciprocal(){return g.create(h.VALUE)}plus(u){return g.create(h.VALUE)}minus(u){return g.create(h.VALUE)}multiply(u){return g.create(h.VALUE)}divided(u){return g.create(h.VALUE)}mod(u){return g.create(h.VALUE)}map(u){return g.create(h.NAME)}mapValue(u){return g.create(h.NAME)}compare(u,e,t=!1){return g.create(h.NAME)}isEqual(u){return this.compare(u,H.EQUALS)}isNotEqual(u){return this.compare(u,H.NOT_EQUAL)}isGreaterThanOrEqual(u){return this.compare(u,H.GREATER_THAN_OR_EQUAL)}isLessThanOrEqual(u){return this.compare(u,H.LESS_THAN_OR_EQUAL)}isLessThan(u){return this.compare(u,H.LESS_THAN)}isGreaterThan(u){return this.compare(u,H.GREATER_THAN)}concatenateFront(u){return g.create(h.NAME)}concatenateBack(u){return g.create(h.NAME)}plusBy(u){return g.create(h.VALUE)}minusBy(u){return g.create(h.VALUE)}multiplyBy(u){return g.create(h.VALUE)}dividedBy(u){return g.create(h.VALUE)}modInverse(u){return g.create(h.VALUE)}compareBy(u,e){return g.create(h.NAME)}concatenate(u,e=ze.FRONT){let t=this.getValue().toString();if(typeof u=="string")e===ze.FRONT?t=u+t:t+=u;else if(typeof u=="number")e===ze.FRONT?t=u.toString()+t:t+=u.toString();else if(typeof u=="boolean"){const r=u?"TRUE":"FALSE";e===ze.FRONT?t=r+t:t+=r}return t}pow(u){return g.create(h.VALUE)}powInverse(u){return g.create(h.VALUE)}sqrt(){return g.create(h.VALUE)}cbrt(){return g.create(h.VALUE)}cos(){return g.create(h.VALUE)}cosh(){return g.create(h.VALUE)}acos(){return g.create(h.VALUE)}acosh(){return g.create(h.VALUE)}sin(){return g.create(h.VALUE)}sinh(){return g.create(h.VALUE)}asin(){return g.create(h.VALUE)}asinh(){return g.create(h.VALUE)}tan(){return g.create(h.VALUE)}tanh(){return g.create(h.VALUE)}atan(){return g.create(h.VALUE)}atan2(u){return g.create(h.VALUE)}atan2Inverse(u){return g.create(h.VALUE)}atanh(){return g.create(h.VALUE)}mean(){return this}median(){return this}var(){return this}std(){return this}log(){return g.create(h.VALUE)}log10(){return g.create(h.VALUE)}exp(){return g.create(h.VALUE)}abs(){return g.create(h.VALUE)}round(u){return g.create(h.VALUE)}roundInverse(u){return g.create(h.VALUE)}floor(u){return g.create(h.VALUE)}floorInverse(u){return g.create(h.VALUE)}ceil(u){return g.create(h.VALUE)}ceilInverse(u){return g.create(h.VALUE)}convertToNumberObjectValue(){return g.create(h.VALUE)}convertToBooleanObjectValue(){return g.create(h.VALUE)}}const Wc=1e3,oi=new gt(Wc);class g extends Ct{constructor(u,e=""){super(u),this._errorType=u,this._errorContent=e}static create(u,e=""){const t=`${u}-${e}`,r=oi.get(t);if(r)return r;const n=new g(u,e);return oi.set(t,n),n}getValue(){return this._errorType}getErrorType(){return this._errorType}getErrorContent(){return this._errorContent}isEqualType(u){return u.getErrorType()===this.getErrorType()}isError(){return!0}}function Qc(i){if(i===null)return 0;if(i!=null&&i.p){const u=i==null?void 0:i.p.body;if(u==null)return 0;const e=u.dataStream;return S.BuildTextUtils.transform.getPlainText(e)}return(i==null?void 0:i.v)||0}var It=(i=>(i[i.MIN=0]="MIN",i[i.MAX=1]="MAX",i))(It||{}),Se=(i=>(i[i.NORMAL=0]="NORMAL",i[i.MIN=1]="MIN",i[i.MAX=2]="MAX",i))(Se||{});function Jr(){return Intl&&Intl.Collator?new Intl.Collator(void 0,{numeric:!1}).compare:(i,u)=>i.localeCompare(u)}function qc(i){return i.indexOf("*")>-1||i.indexOf("?")>-1}function gs(i,u){const e=Xc(u).replace(/~?[*?]/g,r=>r.startsWith("~")?`\\${r.substring(1)}`:r==="*"?".*":r==="?"?".":r);return new RegExp(`^${e}$`).test(i)}function ci(i){return i.replace(/~?[*?]/g,u=>u.startsWith("~")?u.substring(1):" ")}function Kc(i,u,e){let t=!1;switch(e){case H.EQUALS:t=gs(i,u);break;case H.NOT_EQUAL:t=!gs(i,u);break;case H.GREATER_THAN:case H.GREATER_THAN_OR_EQUAL:t=gs(i,u)||i>ci(u);break;case H.LESS_THAN:case H.LESS_THAN_OR_EQUAL:t=i<ci(u);break}return t}function Xc(i){return i.replace(/[.+^${}()|[\]\\]/g,"\\$&")}function ds(i){switch(i){case 1:return 2;case 0:return 0;case-1:return 1;default:return 0}}function Cs(i){return i===-2?1:0}function _s(i){let u;switch(i){case H.EQUALS:u=H.EQUALS;break;case H.GREATER_THAN:u=H.LESS_THAN;break;case H.GREATER_THAN_OR_EQUAL:u=H.LESS_THAN_OR_EQUAL;break;case H.LESS_THAN:u=H.GREATER_THAN;break;case H.LESS_THAN_OR_EQUAL:u=H.GREATER_THAN_OR_EQUAL;break;case H.NOT_EQUAL:u=H.NOT_EQUAL;break}return u}/*!
2
2
  * decimal.js v10.4.3
3
3
  * An arbitrary-precision Decimal type for JavaScript.
4
4
  * https://github.com/MikeMcl/decimal.js
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/engine-formula",
3
- "version": "0.5.4",
3
+ "version": "0.5.5-nightly.202501201336",
4
4
  "private": false,
5
5
  "description": "UniverSheet normal base-formula-engine",
6
6
  "author": "DreamNum <developer@univer.ai>",
@@ -56,15 +56,15 @@
56
56
  "@flatten-js/interval-tree": "^1.1.3",
57
57
  "decimal.js": "^10.4.3",
58
58
  "numfmt": "^2.5.2",
59
- "@univerjs/core": "0.5.4",
60
- "@univerjs/rpc": "0.5.4"
59
+ "@univerjs/core": "0.5.5-nightly.202501201336",
60
+ "@univerjs/rpc": "0.5.5-nightly.202501201336"
61
61
  },
62
62
  "devDependencies": {
63
63
  "rxjs": "^7.8.1",
64
64
  "typescript": "^5.7.2",
65
65
  "vite": "^6.0.7",
66
66
  "vitest": "^2.1.8",
67
- "@univerjs-infra/shared": "0.5.4"
67
+ "@univerjs-infra/shared": "0.5.5"
68
68
  },
69
69
  "scripts": {
70
70
  "test": "vitest run",
package/LICENSE DELETED
@@ -1,176 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS