@univerjs-pro/engine-formula 1.0.0-alpha.2 → 1.0.0-alpha.4

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.
Files changed (32) hide show
  1. package/README.md +7 -2
  2. package/lib/cjs/facade.js +1 -1
  3. package/lib/cjs/index.js +1 -1
  4. package/lib/es/facade.js +1 -1
  5. package/lib/es/index.js +1 -1
  6. package/lib/facade.js +1 -1
  7. package/lib/index.js +1 -1
  8. package/lib/types/controllers/external-reference-data-providers.controller.d.ts +6 -0
  9. package/lib/types/controllers/external-reference-rename.controller.d.ts +9 -0
  10. package/lib/types/controllers/external-reference-resource.controller.d.ts +6 -0
  11. package/lib/types/controllers/formula-reference-data-rpc.controller.d.ts +7 -0
  12. package/lib/types/engine/dependency-engine/dependency-engine.d.ts +11 -0
  13. package/lib/types/engine/dependency-engine/formula-cell-index.d.ts +1 -0
  14. package/lib/types/engine/dependency-engine/range-index.d.ts +1 -0
  15. package/lib/types/engine/dependency-engine/types.d.ts +1 -0
  16. package/lib/types/engine/formula-dependency.d.ts +31 -5
  17. package/lib/types/index.d.ts +22 -4
  18. package/lib/types/models/external-reference-overlay.model.d.ts +41 -0
  19. package/lib/types/models/external-reference.model.d.ts +91 -0
  20. package/lib/types/plugin.d.ts +8 -0
  21. package/lib/types/services/calculate-formula.service.d.ts +20 -3
  22. package/lib/types/services/dependency-manager.service.d.ts +7 -2
  23. package/lib/types/services/external-cache-reference-data.provider.d.ts +10 -0
  24. package/lib/types/services/external-reference-prefetch-planner.d.ts +18 -0
  25. package/lib/types/services/external-reference-prefetch.service.d.ts +38 -0
  26. package/lib/types/services/external-unit-reference-resolver.service.d.ts +8 -0
  27. package/lib/types/services/formula-reference-data.service.d.ts +71 -0
  28. package/lib/types/services/main-formula-reference-data.service.d.ts +12 -0
  29. package/lib/umd/facade.js +1 -1
  30. package/lib/umd/index.js +1 -1
  31. package/package.json +7 -6
  32. package/lib/types/engine/dependency-engine.d.ts +0 -8
package/lib/cjs/index.js CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@univerjs/core"),t=require("@univerjs/engine-formula"),n=require("@univerjs-pro/license");function r(){return{totalFormulaNodes:0,totalSharedFormulaGroups:0,compressedSharedFormulaGroups:0,compressibleSharedFormulaGroups:0,expandedSharedFormulaGroups:0,totalVirtualFormulaNodesInCompressedGroups:0,totalVirtualFormulaNodesInCompressibleGroups:0,skippedExpandedDependencyRegistrationCount:0,sharedPatternCount:0,sharedSourceCoverageEntryCount:0,fallbackReasonCounts:{}}}function i(e,t={}){var n;let i=(n=t.minSharedGroupSize)==null?32:n,s=r(),c=a(e,s),l=[];return c.forEach(e=>{let t=o(e,i);if(l.push(t),s.totalSharedFormulaGroups++,t.mode===`candidate`){s.compressibleSharedFormulaGroups++,s.totalVirtualFormulaNodesInCompressibleGroups+=t.virtualFormulaCount;return}if(s.expandedSharedFormulaGroups++,t.fallbackReason){var n;s.fallbackReasonCounts[t.fallbackReason]=((n=s.fallbackReasonCounts[t.fallbackReason])==null?0:n)+1}}),{groups:l,metrics:s}}function a(e,t){let n=new Map;return Object.keys(e).forEach(r=>{let i=e[r];i!=null&&Object.keys(i).forEach(e=>{let a=i[e];a!=null&&Object.keys(a).forEach(i=>{let o=a[Number(i)];o!=null&&Object.keys(o).forEach(a=>{let s=o[Number(a)];if(s==null||(t.totalFormulaNodes++,s.si==null))return;let c=String(s.si),u=l(r,e,c),d=n.get(u);d==null&&(d={groupId:u,unitId:r,sheetId:e,si:c,members:[]},n.set(u,d)),d.members.push({row:Number(i),col:Number(a),item:s})})})})}),n}function o(e,t){let n=s(e.members),r=n.maxCol-n.minCol+1,i=n.maxRow-n.minRow+1,a={unitId:e.unitId,sheetId:e.sheetId,range:{startRow:n.minRow,endRow:n.maxRow,startColumn:n.minCol,endColumn:n.maxCol}},o=e.members.filter(e=>u(e.item)),l=o.length===1?{unitId:e.unitId,sheetId:e.sheetId,row:o[0].row,col:o[0].col}:void 0,d=c(e,a,o.length,t);return{groupId:e.groupId,unitId:e.unitId,sheetId:e.sheetId,si:e.si,anchor:l,fillRange:a,width:r,height:i,size:e.members.length,virtualFormulaCount:Math.max(0,e.members.length-1),mode:d==null?`candidate`:`expanded`,fallbackReason:d}}function s(e){let t=1/0,n=-1/0,r=1/0,i=-1/0;for(let a=0;a<e.length;a++){let o=e[a];t=Math.min(t,o.row),n=Math.max(n,o.row),r=Math.min(r,o.col),i=Math.max(i,o.col)}return{minRow:t,maxRow:n,minCol:r,maxCol:i}}function c(e,t,n,r){var i;if(n===0)return`missing-anchor-formula`;if(n>1)return`ambiguous-anchor-formula`;if(!d(e.members,t))return`non-rectangular-fill-range`;if(e.members.length<r)return`small-group`;let a=e.members.find(e=>u(e.item)),o=(i=a==null?void 0:a.item.f)==null?``:i;if(m(o))return`external-reference`;if(f(o))return`unsupported-dynamic-reference`;if(p(o))return`volatile-function`;if(h(o))return`array-formula`;if(g(o))return`spill-formula`}function l(e,t,n){return[e,t,n].join(`\0`)}function u(e){var t,n;return((t=e.x)==null?0:t)===0&&((n=e.y)==null?0:n)===0}function d(e,t){let n=t.range.endColumn-t.range.startColumn+1;if(n*(t.range.endRow-t.range.startRow+1)!==e.length)return!1;let r=new Set;for(let i=0;i<e.length;i++){let a=e[i],o=(a.row-t.range.startRow)*n+(a.col-t.range.startColumn);if(r.has(o))return!1;r.add(o)}return!0}function f(e){return _(e,[`INDIRECT`,`OFFSET`])}function p(e){return _(e,[`RAND`,`RANDBETWEEN`,`NOW`,`TODAY`])}function m(e){return/\[[^\]]+\]/.test(e)}function h(e){return/^\s*\{=.*\}\s*$/.test(e)}function g(e){return/#/.test(e)}function _(e,t){for(let n=0;n<t.length;n++)if(RegExp(`(^|[^A-Z0-9_.])${t[n]}\\s*\\(`,`i`).test(e))return!0;return!1}function v(e){"@babel/helpers - typeof";return v=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},v(e)}function y(e,t){if(v(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(v(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function b(e){var t=y(e,`string`);return v(t)==`symbol`?t:t+``}function x(e,t,n){return(t=b(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var S=class extends t.FormulaDependencyGenerator{constructor(...e){super(...e),x(this,`_featureFormulaDirtyDependencies`,[]),x(this,`_calculationTreeCache`,new Map),x(this,`_calculationNodeDataCache`,new Map),x(this,`_forcedRecalculationNodeIndices`,new Set),x(this,`_sharedFormulaCompressionMetrics`,r()),x(this,`_cacheDependencyTreeModelRangeList`,!1)}dispose(){super.dispose(),this._dependencyTreeCache.clear(),this._calculationTreeCache.clear(),this._calculationNodeDataCache=new Map,this._featureFormulaDirtyDependencies.length=0,this._forcedRecalculationNodeIndices.clear(),this._sharedFormulaCompressionMetrics=r()}clearCalculatedDirty(e){this._dependencyManagerService.clearCalculatedDirty(e)}clearCachedCalculationNodeData(){this._calculationNodeDataCache=new Map}clearCachedCalculationTree(){this._calculationTreeCache.clear()}getCachedCalculationNodeData(e){return this._calculationNodeDataCache.get(e)}getCalculationOrder(){return this._dependencyManagerService.getCalculationOrder({detectCycles:!0})}getSharedFormulaCompressionMetrics(){return this._sharedFormulaCompressionMetrics}hasDynamicDepsByIndex(e){return this._dependencyManagerService.hasDynamicDepsByIndex(e)}refreshDynamicDepsByIndex(e,t){return this._dependencyManagerService.refreshDynamicDepsByIndex(e,t)}hasUncalculatedDirtyPrecedentByIndex(e,t){return this._dependencyManagerService.hasUncalculatedDirtyPrecedentByIndex(e,t)}async getAllDependencyJson(){this._featureFormulaDirtyDependencies.length=0,this._updateRangeFlatten();let e=this._currentConfigService.getFormulaData(),t=i(e);this._sharedFormulaCompressionMetrics=t.metrics;let n=this._otherFormulaManagerService.getOtherFormulaData(),r=this._currentConfigService.getUnitData();this._cacheDependencyTreeModelRangeList=!0;try{return await this._generateTreeListPro(e,n,r,t),this._getAllDependencyJsonPro(this._calculationTreeCache)}finally{this._cacheDependencyTreeModelRangeList=!1,this._featureFormulaDirtyDependencies.length=0}}async generatePro(e=!1){this._featureFormulaDirtyDependencies.length=0,this._updateRangeFlatten();let t=this._currentConfigService.getFormulaData(),n=i(t);this._sharedFormulaCompressionMetrics=n.metrics;let r=this._otherFormulaManagerService.getOtherFormulaData(),a=this._currentConfigService.getClearDependencyTreeCache(),o=this._dependencyManagerService;a!=null&&Object.keys(a).forEach(e=>{e!=null&&Object.keys(a[e]).forEach(t=>{t!=null&&(o.clearOtherFormulaDependency(e,t),o.clearFeatureFormulaDependency(e,t),o.clearFormulaDependency(e,t),this._clearCalculationTreeCache(e,t))})});let s=this._currentConfigService.getUnitData();this._cacheDependencyTreeModelRangeList=e;try{await this._generateTreeListPro(t,r,s,n)}finally{this._cacheDependencyTreeModelRangeList=!1}await this._markDirtyDependenciesPro(),this._featureFormulaDirtyDependencies.length=0,this._runtimeService.clearArrayObjectCache();let c=o.getCalculationOrder({detectCycles:!0}),l=this._calculationTreeCache;return e&&this._runtimeService.setDependencyTreeModelData(this._getAllDependencyJsonPro(l)),{calculationOrderResult:c,dependencyTree:l}}async _generateTreeListPro(e,t,n,r){let i=Object.keys(e),a=Object.keys(t);this._registerFeatureFormulasPro(),await this._registerFormulasPro(i,e,n,r),await this._registerOtherFormulasPro(t,a)}_registerFeatureFormulasPro(){this._featureCalculationManagerService.getReferenceExecutorMap().forEach((e,t)=>{e.forEach((e,t)=>{e.forEach((e,t)=>{let n=this._dependencyManagerService.getFeatureFormulaDependency(e.unitId,e.subUnitId,t);this._getFeatureFormulaTreePro(t,n,e)})})})}_getFeatureFormulaTreePro(e,n,r){let{unitId:i,subUnitId:a,dependencyRanges:o,getDirtyData:s}=r,c=new t.FormulaDependencyTree(n||(0,t.generateRandomDependencyTreeId)(this._dependencyManagerService));c.unitId=i,c.subUnitId=a,c.rangeList=o,c.getDirtyData=s;let l=s(this._currentConfigService.getDirtyData(),this._runtimeService.getAllRuntimeData()),u=this._convertDirtyRangesToUnitRange(l.dirtyRanges);c.featureDirtyRanges=u,c.featureId=e,c.type=t.FormulaDependencyTreeType.FEATURE_FORMULA;let d=this._dependencyManagerService.getFeatureFormulaDependencyPro(r.unitId,r.subUnitId,e),f;return d===void 0&&(d=this._dependencyManagerService.addFeatureFormulaDependencyPro(i,a,e,c),f=d),u.length>0&&this._featureFormulaDirtyDependencies.push({node:this._dependencyManagerService.getFeatureFormulaDependencyNodePro(i,a,e),dirtyRanges:u}),this._cacheCalculationTree(d,c),this._releaseDependencyTree(c),f}async _registerOtherFormulasPro(e,n){for(let r of n){let n=e[r];if(n==null)continue;let i=Object.keys(n);for(let e of i){let i=n[e];if(i==null)continue;let{rowCount:a=1/0,columnCount:o=1/0}=this._currentConfigService.getSheetRowColumnCount(r,e)||{},s=Object.keys(i);for(let n of s){let s=this._dependencyManagerService.hasOtherFormulaDataMainData(n),{f:c,ranges:l}=i[n],u=!1;s&&(u=!0);let{firstRow:d,firstColumn:f}=this._getFirstCellOfRange(l),p=new t.FormulaDependencyTree((0,t.generateRandomDependencyTreeId)(this._dependencyManagerService));for(let i=0;i<l.length;i++){let s=l[i],{startRow:m,startColumn:h}=s,{endRow:g,endColumn:_}=s;g=Math.min(g,a-1),_=Math.min(_,o-1);for(let i=m;i<=g;i++)for(let a=h;a<=_;a++){let o=a-f,s=i-d,l=this._dependencyManagerService.getOtherFormulaDependencyPro(r,e,n,o,s);if(o===0&&s===0){p.formula=c,p.unitId=r,p.subUnitId=e,p.formulaId=n,p.type=t.FormulaDependencyTreeType.OTHER_FORMULA,p.isCache=u,p.node||await this._initialAstNodeAndRanges(p);let i=this._getFeatureFormulaDependencyNodes(p.rangeList);l===void 0?l=this._dependencyManagerService.addOtherFormulaDependencyPro(r,e,n,p,i):i.length>0&&(l=this._dependencyManagerService.addOtherFormulaDependencyPro(r,e,n,p,i,`merge`)),this._ensureTreeNodeForCalculation(p),this._cacheCalculationTree(l,p),this._syncForcedRecalculationNodeIndex(l,p);continue}let m=new t.FormulaDependencyTreeVirtual;m.treeId=(0,t.generateRandomDependencyTreeId)(this._dependencyManagerService),m.refTree=p,m.refOffsetX=o,m.refOffsetY=s,m.isCache=u,m.type=t.FormulaDependencyTreeType.OTHER_FORMULA;let h=this._getFeatureFormulaDependencyNodes(m.rangeList);l===void 0?l=this._dependencyManagerService.addOtherFormulaDependencyPro(r,e,n,m,h):h.length>0&&(l=this._dependencyManagerService.addOtherFormulaDependencyPro(r,e,n,m,h,`merge`)),this._cacheCalculationTree(l,m),this._syncForcedRecalculationNodeIndex(l,m),this._releaseDependencyTree(m)}}this._releaseDependencyTree(p)}}}}async _registerFormulasPro(e,n,r,a=i(n)){let o=this._createSharedFormulaGroupMap(a.groups),s=new Map,c=this._dependencyManagerService;for(let i of e){let e=n[i];if(e==null)continue;let a=Object.keys(e);for(let n of a){let a=new Map,l=[],u=e[n];if(u==null)continue;let d=Object.keys(u);for(let e of d){let t=Number.parseInt(e,10),d=u[t];if(d==null)continue;let f=Object.keys(d);for(let e of f){let u=Number.parseInt(e,10),f=d[u];if(f==null)continue;let{x:p=0,y:m=0,si:h}=f;if(!(p===0&&m===0&&h!=null))continue;let g=this._createFDtree(i,n,t,u,r,f),_=this._createSharedFormulaGroupId(i,n,h),v=o.get(_),y=(v==null?void 0:v.mode)===`candidate`?await this._analyzeSharedFormulaCompression(g,v):void 0,b=c.getFormulaDependencyPro(i,n,t,u);if((y==null?void 0:y.mode)===`compressed`)b=c.addFormulaDependencyNodeOnlyPro(i,n,t,u),s.set(_,y),l.push(y);else if((y==null?void 0:y.mode)===`expanded`&&(s.set(_,y),this._recordExpandedSharedFormulaGroupMetrics(y)),b===void 0){g.node||await this._initialAstNodeAndRanges(g);let e=this._getFeatureFormulaDependencyNodes(g.rangeList);b=c.addFormulaDependencyPro(i,n,t,u,g,e)}else{await this._ensureTreeInitializedForDependencies(g);let e=this._getFeatureFormulaDependencyNodes(g.rangeList);e.length>0&&(b=c.addFormulaDependencyPro(i,n,t,u,g,e,`merge`))}this._ensureTreeNodeForCalculation(g),a.set(h,g),this._cacheCalculationTree(b,g),this._syncForcedRecalculationNodeIndex(b,g)}}for(let e of d){let o=Number.parseInt(e,10),l=u[o];if(l==null)continue;let d=Object.keys(l);for(let e of d){let u=Number.parseInt(e,10),d=l[u];if(d==null)continue;let{x:f=0,y:p=0,si:m}=d;if(f===0&&p===0&&m!=null)continue;let h=c.getFormulaDependencyPro(i,n,o,u),g=m==null?void 0:this._createSharedFormulaGroupId(i,n,m),_=g==null?void 0:s.get(g);if((_==null?void 0:_.mode)===`compressed`&&m!=null&&a.has(m)){h=c.addFormulaDependencyNodeOnlyPro(i,n,o,u);let e=a.get(m),{x:t=0,y:r=0}=d;this._cacheCompressedVirtualCalculationTree(h,e,t,r),this._syncCompressedVirtualForcedRecalculationNodeIndex(h,e);continue}let v;if(m!=null&&a.has(m)){let e=a.get(m);v=this._createVirtualFDtree(e,d)}else v=this._createFDtree(i,n,o,u,r,d);if(h===void 0){!v.isVirtual&&!v.node&&await this._initialAstNodeAndRanges(v);let e=this._getFeatureFormulaDependencyNodes(v.rangeList);h=c.addFormulaDependencyPro(i,n,o,u,v,e)}else{await this._ensureTreeInitializedForDependencies(v);let e=this._getFeatureFormulaDependencyNodes(v.rangeList);e.length>0&&(h=c.addFormulaDependencyPro(i,n,o,u,v,e,`merge`))}this._cacheCalculationTree(h,v),this._syncForcedRecalculationNodeIndex(h,v),v instanceof t.FormulaDependencyTreeVirtual?this._releaseDependencyTree(v):m!=null&&a.has(m)||this._releaseDependencyTree(v)}}for(let e=0;e<l.length;e++){let t=l[e];t.patterns&&t.group.fillRange&&(c.registerCompressedSharedFormulaGroup({groupId:t.group.groupId,fillRange:t.group.fillRange,patterns:t.patterns}),this._recordCompressedSharedFormulaGroupMetrics(t))}a.forEach(e=>this._releaseDependencyTree(e)),a.clear()}}}_createSharedFormulaGroupMap(e){let t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].groupId,e[n]);return t}_createSharedFormulaGroupId(e,t,n){return[e,t,String(n)].join(`\0`)}async _analyzeSharedFormulaCompression(e,t){if(t.fillRange==null)return{group:t,mode:`expanded`,fallbackReason:`non-rectangular-fill-range`};e.node||await this._initialAstNodeAndRanges(e);let n=this._getFeatureFormulaDependencyNodes(e.rangeList),r=this._getSharedFormulaUnsupportedReason(e,n.length);if(r)return{group:t,mode:`expanded`,fallbackReason:r};let i=this._convertSharedFormulaPatterns(e);return i==null||i.length===0?{group:t,mode:`expanded`,fallbackReason:`unsupported-range-pattern`}:this._hasSharedFormulaSelfOverlap(t.fillRange,i)?{group:t,mode:`expanded`,fallbackReason:`self-overlap`}:{group:t,mode:`compressed`,patterns:i}}_getSharedFormulaUnsupportedReason(e,t){if(e.addressFunctionNodes&&e.addressFunctionNodes.length>0)return`unsupported-dynamic-reference`;if(t>0||/\$/.test(e.formula))return`unsupported-range-pattern`}_convertSharedFormulaPatterns(e){let t=[],n=new Set,r=e.row,i=e.column;for(let a=0;a<e.rangeList.length;a++){let o=e.rangeList[a],s=this._normalizeSharedFormulaRange(o.range),c;c=s.startRow===s.endRow&&s.startColumn===s.endColumn?{kind:`cell`,unitId:o.unitId,sheetId:o.sheetId,rowDelta:s.startRow-r,colDelta:s.startColumn-i}:{kind:`range`,unitId:o.unitId,sheetId:o.sheetId,startRowDelta:s.startRow-r,startColDelta:s.startColumn-i,endRowDelta:s.endRow-r,endColDelta:s.endColumn-i};let l=JSON.stringify(c);n.has(l)||(n.add(l),t.push(c))}return t}_hasSharedFormulaSelfOverlap(t,n){for(let r=0;r<n.length;r++){let i=this._computeSharedFormulaSourceCoverage(t,n[r]);if(!(i.unitId!==t.unitId||i.sheetId!==t.sheetId)&&e.Rectangle.intersects(i.range,t.range))return!0}return!1}_computeSharedFormulaSourceCoverage(e,t){if(t.kind===`cell`)return{unitId:t.unitId,sheetId:t.sheetId,range:this._normalizeSharedFormulaRange({startRow:e.range.startRow+t.rowDelta,endRow:e.range.endRow+t.rowDelta,startColumn:e.range.startColumn+t.colDelta,endColumn:e.range.endColumn+t.colDelta})};let n=Math.min(t.startRowDelta,t.endRowDelta),r=Math.max(t.startRowDelta,t.endRowDelta),i=Math.min(t.startColDelta,t.endColDelta),a=Math.max(t.startColDelta,t.endColDelta);return{unitId:t.unitId,sheetId:t.sheetId,range:this._normalizeSharedFormulaRange({startRow:e.range.startRow+n,endRow:e.range.endRow+r,startColumn:e.range.startColumn+i,endColumn:e.range.endColumn+a})}}_normalizeSharedFormulaRange(e){return{startRow:Math.min(e.startRow,e.endRow),endRow:Math.max(e.startRow,e.endRow),startColumn:Math.min(e.startColumn,e.endColumn),endColumn:Math.max(e.startColumn,e.endColumn)}}_recordCompressedSharedFormulaGroupMetrics(e){e.mode!==`compressed`||e.patterns==null||(this._sharedFormulaCompressionMetrics.compressedSharedFormulaGroups++,this._sharedFormulaCompressionMetrics.totalVirtualFormulaNodesInCompressedGroups+=e.group.virtualFormulaCount,this._sharedFormulaCompressionMetrics.skippedExpandedDependencyRegistrationCount+=e.group.size*e.patterns.length,this._sharedFormulaCompressionMetrics.sharedPatternCount+=e.patterns.length,this._sharedFormulaCompressionMetrics.sharedSourceCoverageEntryCount+=e.patterns.length)}_recordExpandedSharedFormulaGroupMetrics(e){var t;e.mode!==`expanded`||e.fallbackReason==null||(this._sharedFormulaCompressionMetrics.expandedSharedFormulaGroups++,this._sharedFormulaCompressionMetrics.fallbackReasonCounts[e.fallbackReason]=((t=this._sharedFormulaCompressionMetrics.fallbackReasonCounts[e.fallbackReason])==null?0:t)+1)}async _markDirtyDependenciesPro(){let e=this._dependencyManagerService;if(this._currentConfigService.isForceCalculate()){e.markAllDirty();return}let t=this._currentConfigService.getDirtyRanges();t.length>0&&e.markRangesChanged(t,{includeFormulaCells:!0}),e.markDirtyFeatureCalculations(this._currentConfigService.getDirtyUnitFeatureMap()),e.markDirtyOtherFormulas(this._currentConfigService.getDirtyUnitOtherFormulaMap()),e.markDirtySheetNames(this._currentConfigService.getDirtyNameMap()),this._markForcedRecalculationNodesPro(e),await this._markDirtyDefinedNameDependenciesPro(e)}_markForcedRecalculationNodesPro(e){if(this._forcedRecalculationNodeIndices.size===0)return;let t=[];this._forcedRecalculationNodeIndices.forEach(e=>{t.push(e)}),e.markIndicesChanged(t)}async _markDirtyDefinedNameDependenciesPro(e){let t=this._currentConfigService.getDirtyDefinedNameMap();if(!this._hasDirtyDefinedNames(t))return;let n=[];for(let[e,t]of this._calculationTreeCache)t.formula&&t.formula.length>0&&this._includeDirtyDefinedNamePro(t.formula)&&n.push(e);n.length>0&&e.markIndicesChanged(n)}_cacheCalculationTree(e,t){let n={unitId:t.unitId,subUnitId:t.subUnitId,formula:t.formula,row:t.row,column:t.column,rowCount:t.rowCount,columnCount:t.columnCount,refOffsetX:t.refOffsetX,refOffsetY:t.refOffsetY,formulaId:t.formulaId,featureId:t.featureId,getDirtyData:t.getDirtyData,hasDynamicDeps:t.addressFunctionNodes.length>0,type:t.type};(t.addressFunctionNodes.length>0||this._cacheDependencyTreeModelRangeList)&&(n.rangeList=t.rangeList);let r=t.nodeData;(r==null?void 0:r.node)!=null&&this._calculationNodeDataCache.set(e,{node:r.node,refOffsetX:r.refOffsetX,refOffsetY:r.refOffsetY}),this._calculationTreeCache.set(e,n)}_cacheCompressedVirtualCalculationTree(e,t,n,r){this._calculationTreeCache.set(e,{unitId:t.unitId,subUnitId:t.subUnitId,formula:t.formula,row:t.row+r,column:t.column+n,rowCount:t.rowCount,columnCount:t.columnCount,refOffsetX:n,refOffsetY:r,formulaId:t.formulaId,featureId:t.featureId,getDirtyData:null,hasDynamicDeps:!1,type:t.type}),this._cacheDependencyTreeModelRangeList&&(this._calculationTreeCache.get(e).rangeList=this._getOffsetRangeList(t.rangeList,n,r)),t.node!=null&&this._calculationNodeDataCache.set(e,{node:t.node,refOffsetX:n,refOffsetY:r})}_getOffsetRangeList(e,t,n){return t===0&&n===0?e:e.map(e=>({unitId:e.unitId,sheetId:e.sheetId,range:{startRow:e.range.startRow+n,endRow:e.range.endRow+n,startColumn:e.range.startColumn+t,endColumn:e.range.endColumn+t}}))}_getAllDependencyJsonPro(e){let t=this._dependencyManagerService,n=[];for(let[a,o]of e){var r,i;let s=[],c=[];t.forEachPrecedentNodeByIndex(a,t=>{e.has(t)&&s.push(t)}),t.forEachDependentNodeByIndex(a,t=>{e.has(t)&&c.push(t)}),n.push({children:s,parents:c,treeId:a,formula:o.formula,row:o.row,column:o.column,unitId:o.unitId,subUnitId:o.subUnitId,refOffsetX:o.refOffsetX,refOffsetY:o.refOffsetY,rangeList:(r=o.rangeList)==null?[]:r,refTreeId:void 0,formulaId:o.formulaId,featureId:o.featureId,type:(i=o.type)==null?this._inferDependencyTreeTypePro(o):i})}return n}_inferDependencyTreeTypePro(e){return e.featureId==null?e.formulaId==null?t.FormulaDependencyTreeType.NORMAL_FORMULA:t.FormulaDependencyTreeType.OTHER_FORMULA:t.FormulaDependencyTreeType.FEATURE_FORMULA}_clearCalculationTreeCache(e,t){for(let[n,r]of this._calculationTreeCache)r.unitId===e&&r.subUnitId===t&&(this._calculationTreeCache.delete(n),this._calculationNodeDataCache.delete(n),this._forcedRecalculationNodeIndices.delete(n))}_releaseDependencyTree(e){if(e instanceof t.FormulaDependencyTreeVirtual){e.dispose();return}let n=e;n.dispose(),n.node=null}_hasDirtyDefinedNames(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=e[t[n]];if(r!=null&&Object.keys(r).length>0)return!0}return!1}_syncForcedRecalculationNodeIndex(e,t){if(!t.formula){this._forcedRecalculationNodeIndices.delete(e);return}let n=t.nodeData.node;n&&this._detectForcedRecalculationNodePro(n)?this._forcedRecalculationNodeIndices.add(e):this._forcedRecalculationNodeIndices.delete(e)}_syncCompressedVirtualForcedRecalculationNodeIndex(e,t){t.node&&this._detectForcedRecalculationNodePro(t.node)?this._forcedRecalculationNodeIndices.add(e):this._forcedRecalculationNodeIndices.delete(e)}_detectForcedRecalculationNodePro(e){if(e.isForcedCalculateFunction())return!0;let t=e.getChildren();for(let e=0;e<t.length;e++)if(this._detectForcedRecalculationNodePro(t[e]))return!0;return!1}_includeDirtyDefinedNamePro(e){let t=this._currentConfigService.getExecuteUnitId();if(t==null)return!1;let n=this._currentConfigService.getDirtyDefinedNameMap()[t];if(n==null)return!1;let r=Object.keys(n);for(let t=0;t<r.length;t++)if(e.indexOf(r[t])>-1)return!0;return!1}async _ensureTreeInitializedForDependencies(e){if(e.isVirtual)return;let t=e;t.node||t.formula&&await this._initialAstNodeAndRanges(t)}_ensureTreeNodeForCalculation(e){if(e.node||this._lexer==null||this._astTreeBuilder==null)return;let{unitId:n,formula:r}=e;e.node=(0,t.generateAstNode)(n,r,this._lexer,this._astTreeBuilder,this._currentConfigService),e.addressFunctionNodes=this._getAddressFunctionNodeList(e.node)}_getFeatureFormulaDependencyNodes(e){if(this._featureFormulaDirtyDependencies.length===0||e.length===0)return[];let t=[];for(let n=0;n<this._featureFormulaDirtyDependencies.length;n++){let r=this._featureFormulaDirtyDependencies[n];this._rangesIntersectAny(e,r.dirtyRanges)&&t.push(r.node)}return t}_rangesIntersectAny(t,n){for(let r=0;r<t.length;r++){let i=t[r];for(let t=0;t<n.length;t++){let r=n[t];if(i.unitId===r.unitId&&i.sheetId===r.sheetId&&e.Rectangle.intersects(i.range,r.range))return!0}}return!1}async _initialAstNodeAndRanges(e){let{unitId:n,formula:r}=e,i=(0,t.generateAstNode)(n,r,this._lexer,this._astTreeBuilder,this._currentConfigService);e.node=i,e.addressFunctionNodes=this._getAddressFunctionNodeList(i),this._runtimeService.setCurrent(e.row,e.column,e.rowCount,e.columnCount,e.subUnitId,e.unitId);let a=await this._getRangeListByNode({node:i,refOffsetX:e.refOffsetX,refOffsetY:e.refOffsetY});e.pushRangeList(a)}_createFDtree(e,n,r,i,a,o){let{f:s}=o,c=new t.FormulaDependencyTree((0,t.generateRandomDependencyTreeId)(this._dependencyManagerService)),l=a[e][n];return c.formula=s,c.unitId=e,c.subUnitId=n,c.row=r,c.column=i,c.rowCount=l.rowCount,c.columnCount=l.columnCount,c}},C=`@univerjs-pro/engine-formula`,w=`1.0.0-alpha.2`,T=class extends t.CalculateFormulaService{constructor(...e){super(...e),x(this,`_dynamicRuntimeRanges`,void 0)}async execute(e){this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.START),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()),this._currentConfigService.load(e),this._runtimeService.reset();let n=e.maxIteration||t.DEFAULT_CYCLE_REFERENCE_COUNT;this._isCalculateTreeModel=e.isCalculateTreeModel||!1,this._executeLock.acquire(`FORMULA_EXECUTION_LOCK`,async()=>{await this._executeStep(n),this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.CALCULATION_COMPLETED),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()),this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData()),t.CELL_INVERTED_INDEX_CACHE.clear(),this._runtimeService.reset()})}async _executeStep(e=t.DEFAULT_CYCLE_REFERENCE_COUNT){let n=await this._apply(!1,e);if(n==null)return;let{arrayFormulaRange:r}=n,{dirtyRanges:i,excludedCell:a}=this._getArrayFormulaDirtyRangeAndExcludedRange(r,{});return i==null||i.length===0?!0:(t.FORMULA_REF_TO_ARRAY_CACHE.clear(),this._currentConfigService.loadDirtyRangesAndExcludedCell(i,a),await this._apply(!0,e),!0)}async _apply(e=!1,n=t.DEFAULT_CYCLE_REFERENCE_COUNT){e?this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA):this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.START_DEPENDENCY),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());let r=this._configService.getConfig(t.ENGINE_FORMULA_PLUGIN_CONFIG_KEY),i=(r==null?void 0:r.intervalCount)||t.DEFAULT_INTERVAL_COUNT,a=this._formulaDependencyGenerator;try{let{calculationOrderResult:r,dependencyTree:o}=await a.generatePro(this._isCalculateTreeModel),s=this._getCalculationPlanTreeCount(r,o,n);r.hasCycle&&this._runtimeService.enableCycleDependency(),e?(this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.START_CALCULATION_ARRAY_FORMULA),this._runtimeService.setTotalArrayFormulasToCalculate(s)):(this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.START_CALCULATION),this._runtimeService.setTotalFormulasToCalculate(s)),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());let c=[],l=[],u=new Set,d=!1,f=0,p=0;for(this._runtimeService.setFormulaCycleIndex(0);;){let t=!1;if(await this._forEachCalculationPlanTree(r,o,n,async(n,r,o)=>{if(this._runtimeService.setFormulaCycleIndex(o==null?0:o),await this._waitForExecutionSlot(f,i,e,n,c))return d=!0,!1;await this._calculateDependencyTree(n,r,a)&&this._shouldRescheduleAfterDynamicChange(a,r,u)&&(t=!0),u.has(r)||(u.add(r),l.push(r)),f++}),r.calculationForest.length=0,d||!t)break;if(p++,p>8)throw Error(`Dynamic dependency did not stabilize`);r=a.getCalculationOrder(),r.hasCycle&&this._runtimeService.enableCycleDependency(),s=this._getCalculationPlanTreeCount(r,o,n),e?this._runtimeService.setTotalArrayFormulasToCalculate(s):this._runtimeService.setTotalFormulasToCalculate(s)}for(let e=0;e<c.length;e++)c[e]();return l.length>0&&a.clearCalculatedDirty(l),d?void 0:(s>0||l.length>0?this._runtimeService.markedAsSuccessfullyExecuted():e||this._runtimeService.markedAsNoFunctionsExecuted(),this._runtimeService.getAllRuntimeData())}finally{a.clearCachedCalculationNodeData(),a.clearCachedCalculationTree(),this._dynamicRuntimeRanges=void 0}}_shouldRescheduleAfterDynamicChange(e,t,n){let r=e;return typeof r.hasUncalculatedDirtyPrecedentByIndex==`function`?r.hasUncalculatedDirtyPrecedentByIndex(t,n):!0}async _forEachCalculationPlanTree(e,n,r,i){let a=Math.max(r,1);for(let r=0;r<e.calculationForest.length;r++){let o=e.calculationForest[r];for(let e=0;e<o.plan.length;e++){let r=o.plan[e];if(r.type===`node`){let e=n.get(r.nodeIndex);if(e!=null&&await i(e,r.nodeIndex)===!1)return;continue}if(r.type===`nodes`){for(let e=0;e<r.nodeIndices.length;e++){let t=r.nodeIndices[e],a=n.get(t);if(a!=null&&await i(a,t)===!1)return}r.nodeIndices.length=0;continue}for(let e=0;e<a;e++){e>0&&t.FORMULA_REF_TO_ARRAY_CACHE.clear();for(let t=0;t<r.nodeIndices.length;t++){let a=r.nodeIndices[t],o=n.get(a);if(o!=null&&await i(o,a,e)===!1)return}}}}}_getCalculationPlanTreeCount(e,t,n){let r=Math.max(n,1),i=0;for(let n=0;n<e.calculationForest.length;n++){let a=e.calculationForest[n];for(let e=0;e<a.plan.length;e++){let n=a.plan[e];if(n.type===`node`){t.has(n.nodeIndex)&&i++;continue}if(n.type===`nodes`){for(let e=0;e<n.nodeIndices.length;e++)t.has(n.nodeIndices[e])&&i++;continue}let o=0;for(let e=0;e<n.nodeIndices.length;e++)t.has(n.nodeIndices[e])&&o++;i+=o*r}}return i}_getDynamicResolver(){let e=this._dynamicRuntimeRanges;if(e==null)return;let t=e.map(e=>this._getRangeSignature(e)).sort().join(`|`);return()=>({signature:t,ranges:e,status:e.length>0?`resolved`:`unknown`})}_refreshDynamicDepsAfterCalculate(e,t,n,r){if(n.hasDynamicDeps===!1||!e.hasDynamicDepsByIndex(t))return!1;let i=this._collectAddressFunctionRuntimeRanges(r);if(i.length===0)return!1;this._dynamicRuntimeRanges=i;try{let n=this._getDynamicResolver();return n==null?!1:e.refreshDynamicDepsByIndex(t,n)}finally{this._dynamicRuntimeRanges=void 0}}_collectAddressFunctionRuntimeRanges(e){let t=[];return this._collectAddressFunctionRuntimeRangesInternal(e,t),t}_collectAddressFunctionRuntimeRangesInternal(e,t){if(e.isAddress()){let n=e.getValue();n!=null&&n.isReferenceObject()&&t.push(n.toUnitRange())}let n=e.getChildren();for(let e=0;e<n.length;e++)this._collectAddressFunctionRuntimeRangesInternal(n[e],t)}_getRangeSignature(e){return[e.unitId,e.sheetId,e.range.startRow,e.range.endRow,e.range.startColumn,e.range.endColumn].join(`:`)}async _waitForExecutionSlot(n,r,i,a,o){return n%r===0?(await new Promise(t=>{let n=(0,e.requestImmediateMacroTask)(t);o.push(n)}),i?(this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA),this._runtimeService.setCompletedArrayFormulasCount(n+1)):(this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.CURRENTLY_CALCULATING),this._runtimeService.setCompletedFormulasCount(n+1)),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()),this._runtimeService.isStopExecution()||a.formula==null&&a.getDirtyData==null?(this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.IDLE),this._runtimeService.markedAsStopFunctionsExecuted(),this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData()),!0):!1):!1}async _calculateDependencyTree(e,t,n){let r=e.getDirtyData;if(this._runtimeService.setCurrent(e.row,e.column,e.rowCount,e.columnCount,e.subUnitId,e.unitId),r!=null&&e.featureId!=null){let t=e.featureId,{runtimeCellData:n,dirtyRanges:i}=r(this._currentConfigService.getDirtyData(),this._runtimeService.getAllRuntimeData());return this._runtimeService.setRuntimeFeatureCellData(t,n),this._runtimeService.setRuntimeFeatureRange(t,i),!1}let i=this._getCalculationNodeData(e,t,n),a=i.node,o;try{return o=this._interpreter.checkAsyncNode(i.node)?await this._interpreter.executeAsync(i):this._interpreter.execute(i),e.formulaId==null?this._runtimeService.setRuntimeData(o):this._runtimeService.setRuntimeOtherData(e.formulaId,e.refOffsetX,e.refOffsetY,o),this._refreshDynamicDepsAfterCalculate(n,t,e,a)}finally{a.resetCalculationState()}}_getCalculationNodeData(e,n,r){let i=r.getCachedCalculationNodeData(n);return(i==null?void 0:i.node)==null?{node:(0,t.generateAstNode)(e.unitId,e.formula,this._lexer,this._astTreeBuilder,this._currentConfigService),refOffsetX:e.refOffsetX,refOffsetY:e.refOffsetY}:i}},E=class{constructor(e,t){x(this,`maxRows`,void 0),x(this,`maxCols`,void 0),x(this,`sheetSize`,void 0),x(this,`_sheetKeyById`,new Map),x(this,`_sheetIdByKey`,[]),this.maxRows=e,this.maxCols=t,this.sheetSize=e*t}reset(){this._sheetKeyById.clear(),this._sheetIdByKey.length=0}encodeCell(e,t,n,r){return this.encodeSheet(e,t)*this.sheetSize+n*this.maxCols+r}decodeCell(e){let t=Math.floor(e/this.sheetSize),n=e-t*this.sheetSize,r=Math.floor(n/this.maxCols),i=n-r*this.maxCols,{unitId:a,sheetId:o}=this.decodeSheetKey(t);return{unitId:a,sheetId:o,row:r,col:i}}encodeSheet(e,t){let n=`${e}\0${t}`,r=this._sheetKeyById.get(n);if(r!==void 0)return r;let i=this._sheetIdByKey.length;return this._sheetKeyById.set(n,i),this._sheetIdByKey.push({unitId:e,sheetId:t}),i}decodeSheetKey(e){let t=this._sheetIdByKey[e];if(!t)throw Error(`Unknown sheet key: ${e}`);return t}encodeRow(e,t,n){return this.encodeSheet(e,t)*this.maxRows+n}encodeRowBySheetKey(e,t){return e*this.maxRows+t}decodeRowKey(e){let t=Math.floor(e/this.maxRows),n=e-t*this.maxRows;return{sheetKey:t,...this.decodeSheetKey(t),row:n}}encodeCol(e,t,n){return this.encodeSheet(e,t)*this.maxCols+n}encodeColBySheetKey(e,t){return e*this.maxCols+t}decodeColKey(e){let t=Math.floor(e/this.maxCols),n=e-t*this.maxCols;return{sheetKey:t,...this.decodeSheetKey(t),col:n}}};function D(e){if(typeof e!=`number`)throw TypeError(`CellFormula node id must be a numeric CellId`)}function O(e){let{startRow:t,endRow:n,startColumn:r,endColumn:i}=e.range;if(t<=n&&r<=i)return e;let a=t<n?t:n,o=t<n?n:t,s=r<i?r:i,c=r<i?i:r;return{...e,range:{...e.range,startRow:a,endRow:o,startColumn:s,endColumn:c}}}function k(e){return e.range.endRow-e.range.startRow+1}function A(e){return e.range.endColumn-e.range.startColumn+1}function j(e,t){return e.unitId===t.unitId&&e.sheetId===t.sheetId&&e.range.startRow<=t.row&&t.row<=e.range.endRow&&e.range.startColumn<=t.col&&t.col<=e.range.endColumn}function M(e){if(!e||e.length===0)return[];if(e.length===1)return[e[0]];let t=e.slice().sort((e,t)=>e-t),n=1;for(let e=1;e<t.length;e++)t[e]!==t[n-1]&&(t[n++]=t[e]);return t.length=n,t}function N(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function P(e,t){let n=e.indexOf(t);if(n<0)return!1;let r=e.pop();return n<e.length&&(e[n]=r),!0}function F(e,t,n){let r=e.get(t);r&&(P(r,n),r.length===0&&e.delete(t))}function I(e,t){if(e===void 0)return t;if(typeof e==`number`)return e===t?e:[e,t];for(let n=0;n<e.length;n++)if(e[n]===t)return e;return e.push(t),e}function L(e,t){if(e===void 0)return;if(typeof e==`number`)return e===t?void 0:e;let n=e.indexOf(t);if(n<0)return e;if(e.length===1)return;if(e.length===2)return e[1-n];let r=e.pop();return n<e.length&&(e[n]=r),e}function R(e,t){if(e!==void 0){if(typeof e==`number`){t(e);return}for(let n=0;n<e.length;n++)t(e[n])}}function z(e,t,n){let r=I(e.get(t),n);e.set(t,r)}function B(e,t,n){let r=e.get(t);if(r===void 0)return;let i=L(r,n);i===void 0?e.delete(t):e.set(t,i)}function V(e,t){if(e.length>=t)return e;let n=Math.max(16,e.length);for(;n<t;)n*=2;let r=new Uint8Array(n);return r.set(e),r}function H(e,t){if(e.length>=t)return e;let n=Math.max(16,e.length);for(;n<t;)n*=2;let r=new Uint32Array(n);return r.set(e),r}function U(e){if(!e||e.length===0)return[];let t=new Set,n=[];for(let r=0;r<e.length;r++){let i=e[r],a=`${i.type}:${String(i.id)}`;t.has(a)||(t.add(a),n.push(i))}return n}function W(e){if(e.length<=1){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=O(e[n]);return t}let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=O(e[n]);return K(G(t))}function G(e){let t=e.slice().sort((e,t)=>{let n=e.unitId.localeCompare(t.unitId);if(n!==0)return n;let r=e.sheetId.localeCompare(t.sheetId);return r===0?e.range.startRow===t.range.startRow?e.range.endRow===t.range.endRow?e.range.startColumn===t.range.startColumn?e.range.endColumn-t.range.endColumn:e.range.startColumn-t.range.startColumn:e.range.endRow-t.range.endRow:e.range.startRow-t.range.startRow:r}),n=[];for(let e of t){let t=n[n.length-1];t&&t.unitId===e.unitId&&t.sheetId===e.sheetId&&t.range.startRow===e.range.startRow&&t.range.endRow===e.range.endRow&&e.range.startColumn<=t.range.endColumn+1?e.range.endColumn>t.range.endColumn&&(t.range.endColumn=e.range.endColumn):n.push({...e,range:{...e.range}})}return n}function K(e){let t=e.slice().sort((e,t)=>{let n=e.unitId.localeCompare(t.unitId);if(n!==0)return n;let r=e.sheetId.localeCompare(t.sheetId);return r===0?e.range.startColumn===t.range.startColumn?e.range.endColumn===t.range.endColumn?e.range.startRow===t.range.startRow?e.range.endRow-t.range.endRow:e.range.startRow-t.range.startRow:e.range.endColumn-t.range.endColumn:e.range.startColumn-t.range.startColumn:r}),n=[];for(let e of t){let t=n[n.length-1];t&&t.unitId===e.unitId&&t.sheetId===e.sheetId&&t.range.startColumn===e.range.startColumn&&t.range.endColumn===e.range.endColumn&&e.range.startRow<=t.range.endRow+1?e.range.endRow>t.range.endRow&&(t.range.endRow=e.range.endRow):n.push({...e,range:{...e.range}})}return n}var q=class{constructor(e,t){this._codec=e,this._indexToNodeId=t,x(this,`_rowBuckets`,new Map),x(this,`_colBuckets`,new Map)}addFormulaCell(e,t){let n=this._codec.decodeCell(e);N(this._rowBuckets,this._codec.encodeRow(n.unitId,n.sheetId,n.row),t),N(this._colBuckets,this._codec.encodeCol(n.unitId,n.sheetId,n.col),t)}removeFormulaCell(e,t){let n=this._codec.decodeCell(e);F(this._rowBuckets,this._codec.encodeRow(n.unitId,n.sheetId,n.row),t),F(this._colBuckets,this._codec.encodeCol(n.unitId,n.sheetId,n.col),t)}forEachFormulaInRange(e,t){let n=O(e);return k(n)<=A(n)?this._scanRows(n,t):this._scanCols(n,t)}_scanRows(e,t){if(k(e)<=this._rowBuckets.size){for(let n=e.range.startRow;n<=e.range.endRow;n++)if(this._scanRowBucket(this._codec.encodeRow(e.unitId,e.sheetId,n),e,t)===!1)return!1;return!0}for(let[n]of this._rowBuckets){let r=this._codec.decodeRowKey(n);if(r.unitId===e.unitId&&r.sheetId===e.sheetId&&e.range.startRow<=r.row&&r.row<=e.range.endRow&&this._scanRowBucket(n,e,t)===!1)return!1}return!0}_scanCols(e,t){if(A(e)<=this._colBuckets.size){for(let n=e.range.startColumn;n<=e.range.endColumn;n++)if(this._scanColBucket(this._codec.encodeCol(e.unitId,e.sheetId,n),e,t)===!1)return!1;return!0}for(let[n]of this._colBuckets){let r=this._codec.decodeColKey(n);if(r.unitId===e.unitId&&r.sheetId===e.sheetId&&e.range.startColumn<=r.col&&r.col<=e.range.endColumn&&this._scanColBucket(n,e,t)===!1)return!1}return!0}_scanRowBucket(e,t,n){let r=this._rowBuckets.get(e);if(!r)return!0;for(let e=0;e<r.length;e++){let i=r[e],a=this._indexToNodeId[i],o=this._codec.decodeCell(a);if(o.unitId===t.unitId&&o.sheetId===t.sheetId&&t.range.startColumn<=o.col&&o.col<=t.range.endColumn&&n(i)===!1)return!1}return!0}_scanColBucket(e,t,n){let r=this._colBuckets.get(e);if(!r)return!0;for(let e=0;e<r.length;e++){let i=r[e],a=this._indexToNodeId[i],o=this._codec.decodeCell(a);if(o.unitId===t.unitId&&o.sheetId===t.sheetId&&t.range.startRow<=o.row&&o.row<=t.range.endRow&&n(i)===!1)return!1}return!0}},J=class{constructor(e,t){this._codec=e,this._pointScanCellLimit=t,x(this,`_rowCells`,new Map),x(this,`_colCells`,new Map)}add(e){let t=this._codec.decodeCell(e);N(this._rowCells,this._codec.encodeRow(t.unitId,t.sheetId,t.row),e),N(this._colCells,this._codec.encodeCol(t.unitId,t.sheetId,t.col),e)}remove(e){let t=this._codec.decodeCell(e);F(this._rowCells,this._codec.encodeRow(t.unitId,t.sheetId,t.row),e),F(this._colCells,this._codec.encodeCol(t.unitId,t.sheetId,t.col),e)}forEachCellInRange(e,t){let n=O(e),r=k(n),i=A(n);if(this._isSmallArea(r,i)){for(let e=n.range.startRow;e<=n.range.endRow;e++)for(let r=n.range.startColumn;r<=n.range.endColumn;r++)t(this._codec.encodeCell(n.unitId,n.sheetId,e,r));return}Math.min(r,this._rowCells.size)<=Math.min(i,this._colCells.size)?this._scanRows(n,t):this._scanCols(n,t)}_isSmallArea(e,t){return e<=0||t<=0?!0:e>this._pointScanCellLimit?!1:e*t<=this._pointScanCellLimit}_scanRows(e,t){if(k(e)<=this._rowCells.size){for(let n=e.range.startRow;n<=e.range.endRow;n++)this._scanRowBucket(this._codec.encodeRow(e.unitId,e.sheetId,n),e,t);return}for(let[n]of this._rowCells){let r=this._codec.decodeRowKey(n);r.unitId===e.unitId&&r.sheetId===e.sheetId&&e.range.startRow<=r.row&&r.row<=e.range.endRow&&this._scanRowBucket(n,e,t)}}_scanCols(e,t){if(A(e)<=this._colCells.size){for(let n=e.range.startColumn;n<=e.range.endColumn;n++)this._scanColBucket(this._codec.encodeCol(e.unitId,e.sheetId,n),e,t);return}for(let[n]of this._colCells){let r=this._codec.decodeColKey(n);r.unitId===e.unitId&&r.sheetId===e.sheetId&&e.range.startColumn<=r.col&&r.col<=e.range.endColumn&&this._scanColBucket(n,e,t)}}_scanRowBucket(e,t,n){let r=this._rowCells.get(e);if(r)for(let e=0;e<r.length;e++){let i=r[e],a=this._codec.decodeCell(i);a.unitId===t.unitId&&a.sheetId===t.sheetId&&t.range.startColumn<=a.col&&a.col<=t.range.endColumn&&n(i)}}_scanColBucket(e,t,n){let r=this._colCells.get(e);if(r)for(let e=0;e<r.length;e++){let i=r[e],a=this._codec.decodeCell(i);a.unitId===t.unitId&&a.sheetId===t.sheetId&&t.range.startRow<=a.row&&a.row<=t.range.endRow&&n(i)}}},Y=class{constructor(e,t,n){this._codec=e,this._maxIndexedSpan=n,x(this,`_wholeSheet`,new Map),x(this,`_wholeCol`,new Map),x(this,`_wholeRow`,new Map),x(this,`_rowBuckets`,new Map),x(this,`_colBuckets`,new Map),x(this,`_largeRangeIds`,[]),x(this,`_sheetArr`,void 0),x(this,`_startRowArr`,void 0),x(this,`_endRowArr`,void 0),x(this,`_startColArr`,void 0),x(this,`_endColArr`,void 0),x(this,`_nodeArr`,void 0),x(this,`_kindArr`,void 0),x(this,`_activeArr`,void 0),x(this,`_rangeSeenEpochArr`,void 0),x(this,`_rangeEpoch`,1),x(this,`_nextRangeId`,0),x(this,`_freeRangeIds`,[]),x(this,`_nodeToRangeIds`,new Map),x(this,`_nodeToWholeSheetKeys`,new Map),x(this,`_nodeToWholeColKeys`,new Map),x(this,`_nodeToWholeRowKeys`,new Map);let r=Math.max(16,t);this._sheetArr=new Uint32Array(r),this._startRowArr=new Uint32Array(r),this._endRowArr=new Uint32Array(r),this._startColArr=new Uint32Array(r),this._endColArr=new Uint32Array(r),this._nodeArr=new Uint32Array(r),this._kindArr=new Uint8Array(r),this._activeArr=new Uint8Array(r),this._rangeSeenEpochArr=new Uint32Array(r)}addRange(e,t){let n=O(t),r=this._codec.encodeSheet(n.unitId,n.sheetId),i=k(n),a=A(n),o=a===this._codec.maxCols,s=i===this._codec.maxRows;if(o&&s){z(this._wholeSheet,r,e),N(this._nodeToWholeSheetKeys,e,r);return}if(s){for(let t=n.range.startColumn;t<=n.range.endColumn;t++){let n=this._codec.encodeColBySheetKey(r,t);z(this._wholeCol,n,e),N(this._nodeToWholeColKeys,e,n)}return}if(o){for(let t=n.range.startRow;t<=n.range.endRow;t++){let n=this._codec.encodeRowBySheetKey(r,t);z(this._wholeRow,n,e),N(this._nodeToWholeRowKeys,e,n)}return}let c=Math.min(i,a),l=this._allocRangeId();if(this._setRangeMeta(l,e,n),c>this._maxIndexedSpan)this._kindArr[l]=3,this._largeRangeIds.push(l);else if(i<=a){this._kindArr[l]=1;for(let e=n.range.startRow;e<=n.range.endRow;e++)N(this._rowBuckets,this._codec.encodeRowBySheetKey(r,e),l)}else{this._kindArr[l]=2;for(let e=n.range.startColumn;e<=n.range.endColumn;e++)N(this._colBuckets,this._codec.encodeColBySheetKey(r,e),l)}N(this._nodeToRangeIds,e,l)}removeNode(e){let t=this._nodeToWholeSheetKeys.get(e);if(t){for(let n=0;n<t.length;n++)B(this._wholeSheet,t[n],e);this._nodeToWholeSheetKeys.delete(e)}let n=this._nodeToWholeColKeys.get(e);if(n){for(let t=0;t<n.length;t++)B(this._wholeCol,n[t],e);this._nodeToWholeColKeys.delete(e)}let r=this._nodeToWholeRowKeys.get(e);if(r){for(let t=0;t<r.length;t++)B(this._wholeRow,r[t],e);this._nodeToWholeRowKeys.delete(e)}let i=this._nodeToRangeIds.get(e);if(i){for(let e=0;e<i.length;e++)this._removeRangeId(i[e]);this._nodeToRangeIds.delete(e)}}forEachPoint(e,t,n,r,i){let a=this._codec.encodeSheet(e,t);R(this._wholeSheet.get(a),i),R(this._wholeCol.get(this._codec.encodeColBySheetKey(a,r)),i),R(this._wholeRow.get(this._codec.encodeRowBySheetKey(a,n)),i);let o=this._rowBuckets.get(this._codec.encodeRowBySheetKey(a,n));if(o)for(let e=0;e<o.length;e++){let t=o[e];this._activeArr[t]&&this._rangeContainsPoint(t,a,n,r)&&i(this._nodeArr[t])}let s=this._colBuckets.get(this._codec.encodeColBySheetKey(a,r));if(s)for(let e=0;e<s.length;e++){let t=s[e];this._activeArr[t]&&this._rangeContainsPoint(t,a,n,r)&&i(this._nodeArr[t])}for(let e=0;e<this._largeRangeIds.length;e++){let t=this._largeRangeIds[e];this._activeArr[t]&&this._rangeContainsPoint(t,a,n,r)&&i(this._nodeArr[t])}}forEachRangeIntersecting(e,t){this.forEachRangesIntersecting([e],t)}forEachRangesIntersecting(e,t){if(e.length===0)return;let n=Array(e.length);for(let t=0;t<e.length;t++)n[t]=O(e[t]);this._nextRangeEpoch();for(let e=0;e<n.length;e++){let r=n[e],i=this._codec.encodeSheet(r.unitId,r.sheetId);R(this._wholeSheet.get(i),t),this._scanWholeCols(r,i,t),this._scanWholeRows(r,i,t),this._scanRowIndexedRanges(r,i,t),this._scanColIndexedRanges(r,i,t);for(let e=0;e<this._largeRangeIds.length;e++){let n=this._largeRangeIds[e];this._activeArr[n]&&(this._wasRangeSeen(n)||this._rangeIntersectsInput(n,r,i)&&(this._markRangeSeen(n),t(this._nodeArr[n])))}}}_allocRangeId(){let e=this._freeRangeIds.pop();if(e!==void 0)return e;let t=this._nextRangeId++;return this._ensureRangeCapacity(t+1),t}_ensureRangeCapacity(e){this._sheetArr=H(this._sheetArr,e),this._startRowArr=H(this._startRowArr,e),this._endRowArr=H(this._endRowArr,e),this._startColArr=H(this._startColArr,e),this._endColArr=H(this._endColArr,e),this._nodeArr=H(this._nodeArr,e),this._kindArr=V(this._kindArr,e),this._activeArr=V(this._activeArr,e),this._rangeSeenEpochArr=H(this._rangeSeenEpochArr,e)}_setRangeMeta(e,t,n){this._sheetArr[e]=this._codec.encodeSheet(n.unitId,n.sheetId),this._startRowArr[e]=n.range.startRow,this._endRowArr[e]=n.range.endRow,this._startColArr[e]=n.range.startColumn,this._endColArr[e]=n.range.endColumn,this._nodeArr[e]=t,this._activeArr[e]=1}_removeRangeId(e){if(!this._activeArr[e])return;let t=this._kindArr[e],n=this._sheetArr[e];if(t===1)for(let t=this._startRowArr[e];t<=this._endRowArr[e];t++)F(this._rowBuckets,this._codec.encodeRowBySheetKey(n,t),e);else if(t===2)for(let t=this._startColArr[e];t<=this._endColArr[e];t++)F(this._colBuckets,this._codec.encodeColBySheetKey(n,t),e);else t===3&&P(this._largeRangeIds,e);this._activeArr[e]=0,this._kindArr[e]=0,this._freeRangeIds.push(e)}_nextRangeEpoch(){this._rangeEpoch++,this._rangeEpoch>=4294967295&&(this._rangeSeenEpochArr.fill(0),this._rangeEpoch=1)}_wasRangeSeen(e){return this._rangeSeenEpochArr[e]===this._rangeEpoch}_markRangeSeen(e){this._rangeSeenEpochArr[e]=this._rangeEpoch}_scanWholeCols(e,t,n){if(A(e)<=this._wholeCol.size){for(let r=e.range.startColumn;r<=e.range.endColumn;r++)R(this._wholeCol.get(this._codec.encodeColBySheetKey(t,r)),n);return}let r=this._codec.encodeColBySheetKey(t,e.range.startColumn),i=this._codec.encodeColBySheetKey(t,e.range.endColumn);for(let[e,t]of this._wholeCol)r<=e&&e<=i&&R(t,n)}_scanWholeRows(e,t,n){if(k(e)<=this._wholeRow.size){for(let r=e.range.startRow;r<=e.range.endRow;r++)R(this._wholeRow.get(this._codec.encodeRowBySheetKey(t,r)),n);return}let r=this._codec.encodeRowBySheetKey(t,e.range.startRow),i=this._codec.encodeRowBySheetKey(t,e.range.endRow);for(let[e,t]of this._wholeRow)r<=e&&e<=i&&R(t,n)}_scanRowIndexedRanges(e,t,n){if(k(e)<=this._rowBuckets.size){for(let r=e.range.startRow;r<=e.range.endRow;r++)this._scanRangeIdBucket(this._rowBuckets.get(this._codec.encodeRowBySheetKey(t,r)),e,t,n);return}let r=this._codec.encodeRowBySheetKey(t,e.range.startRow),i=this._codec.encodeRowBySheetKey(t,e.range.endRow);for(let[a,o]of this._rowBuckets)r<=a&&a<=i&&this._scanRangeIdBucket(o,e,t,n)}_scanColIndexedRanges(e,t,n){if(A(e)<=this._colBuckets.size){for(let r=e.range.startColumn;r<=e.range.endColumn;r++)this._scanRangeIdBucket(this._colBuckets.get(this._codec.encodeColBySheetKey(t,r)),e,t,n);return}let r=this._codec.encodeColBySheetKey(t,e.range.startColumn),i=this._codec.encodeColBySheetKey(t,e.range.endColumn);for(let[a,o]of this._colBuckets)r<=a&&a<=i&&this._scanRangeIdBucket(o,e,t,n)}_scanRangeIdBucket(e,t,n,r){if(e)for(let i=0;i<e.length;i++){let a=e[i];this._activeArr[a]&&(this._wasRangeSeen(a)||this._rangeIntersectsInput(a,t,n)&&(this._markRangeSeen(a),r(this._nodeArr[a])))}}_rangeContainsPoint(e,t,n,r){return this._sheetArr[e]===t&&this._startRowArr[e]<=n&&n<=this._endRowArr[e]&&this._startColArr[e]<=r&&r<=this._endColArr[e]}_rangeIntersectsInput(e,t,n){return this._sheetArr[e]===n&&this._startRowArr[e]<=t.range.endRow&&this._endRowArr[e]>=t.range.startRow&&this._startColArr[e]<=t.range.endColumn&&this._endColArr[e]>=t.range.startColumn}},X=class{constructor(e){var t,n,r,i;x(this,`codec`,void 0),x(this,`_maxIndexedSpan`,void 0),x(this,`_pointScanCellLimit`,void 0),x(this,`_initialNodeCapacity`,void 0),x(this,`_initialRangeCapacity`,void 0),x(this,`directDeps`,void 0),x(this,`nodeDeps`,void 0),x(this,`rangeIndex`,void 0),x(this,`cellFormulaToIndex`,void 0),x(this,`otherFormulaToIndex`,void 0),x(this,`featureCalculationToIndex`,void 0),x(this,`indexToNodeId`,void 0),x(this,`dirty`,void 0),x(this,`inQueue`,void 0),x(this,`_indexToNodeType`,void 0),x(this,`_cellPrecedents`,void 0),x(this,`_rangePrecedents`,void 0),x(this,`_nodePrecedents`,void 0),x(this,`_dynamicDeps`,void 0),x(this,`_dynamicSignature`,void 0),x(this,`_runtimeDirectDeps`,void 0),x(this,`_runtimeNodeDeps`,void 0),x(this,`_runtimeRangeIndex`,void 0),x(this,`_runtimeCellPrecedents`,void 0),x(this,`_runtimeRangePrecedents`,void 0),x(this,`_runtimeNodePrecedents`,void 0),x(this,`_activeNode`,void 0),x(this,`_seenNodeEpoch`,void 0),x(this,`_visitNodeEpoch`,void 0),x(this,`_edgeSeenEpoch`,void 0),x(this,`_tarjanSeenEpoch`,void 0),x(this,`_tarjanIndexArr`,void 0),x(this,`_tarjanLowArr`,void 0),x(this,`_tarjanOnStack`,void 0),x(this,`_emitEpoch`,1),x(this,`_visitEpoch`,1),x(this,`_edgeEpoch`,1),x(this,`_tarjanEpoch`,1),x(this,`_propQueue`,[]),x(this,`_dirtyList`,[]),x(this,`_activeNodeCount`,0),x(this,`_dirtyNodeCount`,0),x(this,`_directPointIndex`,void 0),x(this,`_runtimeDirectPointIndex`,void 0),x(this,`_formulaCellIndex`,void 0),x(this,`_sharedFormulaGroups`,void 0),x(this,`_sharedFormulaGroupIndexById`,void 0),x(this,`_sharedFormulaMembershipByNode`,void 0),x(this,`_sharedFormulaSourceEntries`,void 0),x(this,`_sharedFormulaSourceRangeIndex`,void 0),this._maxIndexedSpan=(t=e.maxIndexedSpan)==null?4096:t,this._pointScanCellLimit=(n=e.pointScanCellLimit)==null?4096:n,this._initialNodeCapacity=Math.max(16,(r=e.initialNodeCapacity)==null?1024:r),this._initialRangeCapacity=Math.max(16,(i=e.initialRangeCapacity)==null?1024:i),this.codec=new E(e.maxRows,e.maxCols),this.reset()}reset(){this.codec.reset(),this.directDeps=new Map,this.nodeDeps=new Map,this.rangeIndex=new Y(this.codec,this._initialRangeCapacity,this._maxIndexedSpan),this._runtimeDirectDeps=new Map,this._runtimeNodeDeps=new Map,this._runtimeRangeIndex=new Y(this.codec,this._initialRangeCapacity,this._maxIndexedSpan),this.cellFormulaToIndex=new Map,this.otherFormulaToIndex=new Map,this.featureCalculationToIndex=new Map,this.indexToNodeId=[],this._indexToNodeType=new Uint8Array(this._initialNodeCapacity),this.dirty=new Uint8Array(this._initialNodeCapacity),this.inQueue=new Uint8Array(this._initialNodeCapacity),this._activeNode=new Uint8Array(this._initialNodeCapacity),this._cellPrecedents=[],this._rangePrecedents=[],this._nodePrecedents=[],this._dynamicDeps=[],this._dynamicSignature=[],this._runtimeCellPrecedents=[],this._runtimeRangePrecedents=[],this._runtimeNodePrecedents=[],this._seenNodeEpoch=new Uint32Array(this._initialNodeCapacity),this._visitNodeEpoch=new Uint32Array(this._initialNodeCapacity),this._edgeSeenEpoch=new Uint32Array(this._initialNodeCapacity),this._tarjanSeenEpoch=new Uint32Array(this._initialNodeCapacity),this._tarjanIndexArr=new Uint32Array(this._initialNodeCapacity),this._tarjanLowArr=new Uint32Array(this._initialNodeCapacity),this._tarjanOnStack=new Uint8Array(this._initialNodeCapacity),this._emitEpoch=1,this._visitEpoch=1,this._edgeEpoch=1,this._tarjanEpoch=1,this._propQueue.length=0,this._dirtyList.length=0,this._activeNodeCount=0,this._dirtyNodeCount=0,this._directPointIndex=new J(this.codec,this._pointScanCellLimit),this._runtimeDirectPointIndex=new J(this.codec,this._pointScanCellLimit),this._formulaCellIndex=new q(this.codec,this.indexToNodeId),this._sharedFormulaGroups=[],this._sharedFormulaGroupIndexById=new Map,this._sharedFormulaMembershipByNode=new Int32Array(this._initialNodeCapacity),this._sharedFormulaMembershipByNode.fill(-1),this._sharedFormulaSourceEntries=[],this._sharedFormulaSourceRangeIndex=new Y(this.codec,this._initialRangeCapacity,this._maxIndexedSpan)}encodeCell(e,t,n,r){return this.codec.encodeCell(e,t,n,r)}decodeCell(e){return this.codec.decodeCell(e)}encodeFeatureCalculationId(e,t,n){return`${e}${t}${n}`}decodeFeatureCalculationId(e){let t=this._tryDecodeFeatureCalculationId(e);if(t===void 0)throw Error(`Invalid feature calculation id: ${String(e)}`);return t}encodeOtherFormulaId(e,t,n,r,i){return`${e}${t}${n}${r}${i}`}decodeOtherFormulaId(e){let t=this._tryDecodeOtherFormulaId(e);if(t===void 0)throw Error(`Invalid other formula id: ${String(e)}`);return t}setCellFormulaDeps(e,t,n){var r,i;return this._setCalcNodeDepsByType(1,e,t,(r=n==null?void 0:n.checkCycle)==null?!0:r,(i=n==null?void 0:n.markDirty)==null?!0:i,(n==null?void 0:n.mode)===`merge`)}setOtherFormulaDeps(e,t,n){var r,i;return this._setCalcNodeDepsByType(2,e,t,(r=n==null?void 0:n.checkCycle)==null?!0:r,(i=n==null?void 0:n.markDirty)==null?!0:i,(n==null?void 0:n.mode)===`merge`)}setFeatureCalculationDeps(e,t,n){var r,i;return this._setCalcNodeDepsByType(3,e,t,(r=n==null?void 0:n.checkCycle)==null?!0:r,(i=n==null?void 0:n.markDirty)==null?!0:i,(n==null?void 0:n.mode)===`merge`)}setCalcNodeDeps(e,t,n){var r,i;return this._setCalcNodeDepsByType(e.type,e.id,t,(r=n==null?void 0:n.checkCycle)==null?!0:r,(i=n==null?void 0:n.markDirty)==null?!0:i,(n==null?void 0:n.mode)===`merge`)}registerCompressedSharedFormulaGroup(e){this.unregisterCompressedSharedFormulaGroup(e.groupId);let t=this._sharedFormulaGroups.length,n=O(e.fillRange),r={...n,range:{...n.range}},i={groupId:e.groupId,fillRange:r,patterns:e.patterns.slice(),sourceEntryIds:[]};this._sharedFormulaGroups.push(i),this._sharedFormulaGroupIndexById.set(i.groupId,t),this._markCompressedSharedFormulaMembership(t,r);for(let e=0;e<i.patterns.length;e++){let n=this._getCompressedSharedSourceCoverage(r,i.patterns[e]),a=this._sharedFormulaSourceEntries.length;this._sharedFormulaSourceEntries.push({groupIndex:t,patternIndex:e,sourceCoverage:n,active:!0}),i.sourceEntryIds.push(a),this._sharedFormulaSourceRangeIndex.addRange(a,n)}}unregisterCompressedSharedFormulaGroup(e){let t=this._sharedFormulaGroupIndexById.get(e);if(t===void 0)return;let n=this._sharedFormulaGroups[t];this._sharedFormulaGroupIndexById.delete(e);for(let e=0;e<n.sourceEntryIds.length;e++){let t=n.sourceEntryIds[e],r=this._sharedFormulaSourceEntries[t];r&&(r.active=!1),this._sharedFormulaSourceRangeIndex.removeNode(t)}this._clearCompressedSharedFormulaMembership(t,n.fillRange)}clearCompressedSharedFormulaGroups(e,t){let n=[];for(let r=0;r<this._sharedFormulaGroups.length;r++){let i=this._sharedFormulaGroups[r];this._sharedFormulaGroupIndexById.has(i.groupId)&&(e!==void 0&&i.fillRange.unitId!==e||t!==void 0&&i.fillRange.sheetId!==t||n.push(i.groupId))}for(let e=0;e<n.length;e++)this.unregisterCompressedSharedFormulaGroup(n[e])}_setCalcNodeDepsByType(e,t,n,r,i,a){var o,s,c,l,u,d,f;let p=this._getOrCreateNodeIndexByType(e,t),m=this._activeNode[p]===1,h=m&&e===1&&!this._isEmptyCalcNodeDeps(n)&&this._sharedFormulaMembershipByNode[p]>=0,g=m&&(r||a),_=g?(o=(s=this._cellPrecedents[p])==null?void 0:s.slice())==null?[]:o:[],v=g?(c=(l=this._rangePrecedents[p])==null?void 0:l.slice())==null?[]:c:[],y=g?(u=(d=this._nodePrecedents[p])==null?void 0:d.slice())==null?[]:u:[];m&&this._removeNodeDepsOnly(p);let b=this._normalizeCalcNodeDeps(n),x=b.cells,S=b.ranges,C=b.nodes,w=this._resolveExplicitNodeDeps(C),T=(f=this._dynamicDeps[p])==null?[]:f,E=a?this._mergeDynamicDeps(T,b.dynamics):b.dynamics,O=a?this._mergeSortedUniqueNumbers(_,x):x,k=a?this._mergeRangeDeps(v,S):S,A=a?this._mergeSortedUniqueNumbers(y,w):w;return r&&this._wouldCreateCycleForNewDeps(p,O,k,A)?(m&&this._addNodeDepsOnly(p,_,v,y),{nodeIndex:p,hasCycle:!0}):(h&&this._unregisterCompressedSharedFormulaGroupByNode(p),!m&&e===1&&(D(t),this._formulaCellIndex.addFormulaCell(t,p)),m||this._activeNodeCount++,this._activeNode[p]=1,this._addNodeDepsOnly(p,O,k,A),this._setNodeDynamicDeps(p,E),i&&(this._markNodeIndexDirty(p,!0),this._propagateDirtyQueue()),{nodeIndex:p,hasCycle:!1})}setManyCalcNodeDeps(e,t){var n,r;let i=(n=t==null?void 0:t.markDirty)==null?!0:n,a=(r=t==null?void 0:t.checkCycle)==null?!0:r,o=(t==null?void 0:t.mode)===`merge`,s=Array(e.length),c=[];for(let t=0;t<e.length;t++){let n=e[t],r=this._setCalcNodeDepsByType(n.node.type,n.node.id,n.deps,a,!1,o);s[t]=r,r.hasCycle||c.push(r.nodeIndex)}return i&&c.length>0&&this._markCalcNodeIndicesChanged(c),s}setManyCellFormulaDeps(e,t){var n,r;let i=(n=t==null?void 0:t.markDirty)==null?!0:n,a=(r=t==null?void 0:t.checkCycle)==null?!0:r,o=(t==null?void 0:t.mode)===`merge`,s=Array(e.length),c=[];for(let t=0;t<e.length;t++){let n=e[t],r=this._setCalcNodeDepsByType(1,n.cell,n.deps,a,!1,o);s[t]=r,r.hasCycle||c.push(r.nodeIndex)}return i&&c.length>0&&this._markCalcNodeIndicesChanged(c),s}setManyOtherFormulaDeps(e,t){var n,r;let i=(n=t==null?void 0:t.markDirty)==null?!0:n,a=(r=t==null?void 0:t.checkCycle)==null?!0:r,o=(t==null?void 0:t.mode)===`merge`,s=Array(e.length),c=[];for(let t=0;t<e.length;t++){let n=e[t],r=this._setCalcNodeDepsByType(2,n.id,n.deps,a,!1,o);s[t]=r,r.hasCycle||c.push(r.nodeIndex)}return i&&c.length>0&&this._markCalcNodeIndicesChanged(c),s}setManyFeatureCalculationDeps(e,t){var n,r;let i=(n=t==null?void 0:t.markDirty)==null?!0:n,a=(r=t==null?void 0:t.checkCycle)==null?!0:r,o=(t==null?void 0:t.mode)===`merge`,s=Array(e.length),c=[];for(let t=0;t<e.length;t++){let n=e[t],r=this._setCalcNodeDepsByType(3,n.id,n.deps,a,!1,o);s[t]=r,r.hasCycle||c.push(r.nodeIndex)}return i&&c.length>0&&this._markCalcNodeIndicesChanged(c),s}removeCellFormula(e,t){this._removeCalcNodeByType(1,e,t)}removeOtherFormula(e,t){this._removeCalcNodeByType(2,e,t)}removeFeatureCalculation(e,t){this._removeCalcNodeByType(3,e,t)}removeCellFormulas(e,t){this._removeCalcNodeIds(1,e,t)}removeOtherFormulas(e,t){this._removeCalcNodeIds(2,e,t)}removeFeatureCalculations(e,t){this._removeCalcNodeIds(3,e,t)}removeCalcNodes(e,t){if(e.length===0)return;let n=[];for(let t=0;t<e.length;t++){let r=e[t],i=this._getNodeIndexByType(r.type,r.id);i!==void 0&&this._activeNode[i]&&n.push(i)}this._removeCalcNodeIndices(n,t)}clearCellFormulas(e,t,n){let r=[];for(let[n,i]of this.cellFormulaToIndex){if(!this._activeNode[i])continue;let a=this.codec.decodeCell(n);a.unitId===e&&(t!==void 0&&a.sheetId!==t||r.push(i))}this._removeCalcNodeIndices(r,n)}clearOtherFormulas(e,t,n,r,i,a){if(n!==void 0&&n.length===0)return;let o=[];for(let[a,s]of this.otherFormulaToIndex){if(!this._activeNode[s])continue;let c=this._tryDecodeOtherFormulaId(a);c!==void 0&&c.unitId===e&&(t!==void 0&&c.sheetId!==t||n!==void 0&&!this._includesFormulaId(n,c.formulaId)||r!==void 0&&c.refOffsetX!==r||r!==void 0&&i!==void 0&&c.refOffsetY!==i||o.push(s))}this._removeCalcNodeIndices(o,a)}_includesFormulaId(e,t){for(let n=0;n<e.length;n++)if(e[n]===t)return!0;return!1}clearFeatureCalculations(e,t,n){let r=[];for(let[n,i]of this.featureCalculationToIndex){if(!this._activeNode[i])continue;let a=this._tryDecodeFeatureCalculationId(n);a!==void 0&&a.unitId===e&&(t!==void 0&&a.sheetId!==t||r.push(i))}this._removeCalcNodeIndices(r,n)}_tryDecodeFeatureCalculationId(e){if(typeof e!=`string`)return;let t=e.indexOf(`\0`);if(t<=0)return;let n=e.indexOf(`\0`,t+1);if(!(n<=t+1)&&n!==e.length-1&&e.indexOf(`\0`,n+1)===-1)return{unitId:e.slice(0,t),sheetId:e.slice(t+1,n),formulaId:e.slice(n+1)}}_tryDecodeOtherFormulaId(e){if(typeof e!=`string`)return;let t=e.indexOf(`\0`);if(t<=0)return;let n=e.indexOf(`\0`,t+1);if(n<=t+1)return;let r=e.indexOf(`\0`,n+1);if(r<=n+1)return;let i=e.indexOf(`\0`,r+1);if(i<=r+1||i===e.length-1||e.indexOf(`\0`,i+1)!==-1)return;let a=Number(e.slice(r+1,i)),o=Number(e.slice(i+1));if(!(!Number.isFinite(a)||!Number.isFinite(o)))return{unitId:e.slice(0,t),sheetId:e.slice(t+1,n),formulaId:e.slice(n+1,r),refOffsetX:a,refOffsetY:o}}_removeCalcNodeIds(e,t,n){if(t.length===0)return;let r=[];for(let n=0;n<t.length;n++){let i=this._getNodeIndexByType(e,t[n]);i!==void 0&&this._activeNode[i]&&r.push(i)}this._removeCalcNodeIndices(r,n)}_removeCalcNodeIndices(e,t){if(e.length!==0){if(t!=null&&t.markDependentsDirty&&this._markCalcNodeIndicesChanged(e),t!=null&&t.detachDependents)for(let t=0;t<e.length;t++)this._detachDependentsFromNode(e[t]);for(let t=0;t<e.length;t++)this._removeCalcNodeByIndex(e[t])}}removeCalcNode(e,t){this._removeCalcNodeByType(e.type,e.id,t)}_removeCalcNodeByType(e,t,n){let r=this._getNodeIndexByType(e,t);r!==void 0&&this._activeNode[r]&&(n!=null&&n.markDependentsDirty&&(this._markNodeIndexDirty(r,!0),this._propagateDirtyQueue()),n!=null&&n.detachDependents&&this._detachDependentsFromNode(r),this._removeCalcNodeByIndex(r))}_removeCalcNodeByIndex(e){if(this._activeNode[e]){if(this._unregisterCompressedSharedFormulaGroupByNode(e),this._removeNodeDepsOnly(e),this._removeRuntimeDepsOnly(e),this._dynamicDeps[e]=void 0,this._dynamicSignature[e]=void 0,this._indexToNodeType[e]===1){let t=this.indexToNodeId[e];this._formulaCellIndex.removeFormulaCell(t,e)}this._activeNode[e]=0,this._activeNodeCount--,this.dirty[e]&&(this.dirty[e]=0,this._dirtyNodeCount--,this._compactDirtyList()),this.inQueue[e]=0}}markCellChanged(e){this.markCellsChanged([e])}markCellsChanged(e){this._nextEmitEpoch();for(let t of e)this._forEachDependentIndexByCellRaw(t,e=>{this._emitNodeOnceAndMarkDirty(e)});this._propagateDirtyQueue()}markRangeChanged(e,t){this.markRangesChanged([e],t)}markRangesChanged(e,t){if(e.length===0)return;let n=(t==null?void 0:t.coalesce)===!1?this._normalizeRangeDeps(e):W(e);this._nextEmitEpoch();for(let e=0;e<n.length;e++){let r=n[e];t!=null&&t.includeFormulaCells&&this._formulaCellIndex.forEachFormulaInRange(r,e=>{this._emitNodeOnceAndMarkDirty(e,!0)}),this._directPointIndex.forEachCellInRange(r,e=>{R(this.directDeps.get(e),e=>{this._emitNodeOnceAndMarkDirty(e)})}),this._runtimeDirectPointIndex.forEachCellInRange(r,e=>{R(this._runtimeDirectDeps.get(e),e=>{this._emitNodeOnceAndMarkDirty(e)})})}this._isEveryActiveNodeDirty()||this.rangeIndex.forEachRangesIntersecting(n,e=>{this._emitNodeOnceAndMarkDirty(e)}),this._isEveryActiveNodeDirty()||this._runtimeRangeIndex.forEachRangesIntersecting(n,e=>{this._emitNodeOnceAndMarkDirty(e)});for(let e=0;e<n.length&&!this._isEveryActiveNodeDirty();e++)this._forEachCompressedSharedDependentByRange(n[e],e=>{this._emitNodeOnceAndMarkDirty(e)});this._propagateDirtyQueue()}markCellFormulaChanged(e){this._markCalcNodeChangedByType(1,e)}markOtherFormulaChanged(e){this._markCalcNodeChangedByType(2,e)}markOtherFormulasChanged(e,t,n){if(!(n!==void 0&&n.length===0)){this._nextEmitEpoch();for(let[r,i]of this.otherFormulaToIndex){if(!this._activeNode[i])continue;let a=this._tryDecodeOtherFormulaId(r);a!==void 0&&a.unitId===e&&(t!==void 0&&a.sheetId!==t||n!==void 0&&!this._includesFormulaId(n,a.formulaId)||this._emitNodeOnceAndMarkDirty(i,!0))}this._propagateDirtyQueue()}}markFeatureCalculationChanged(e){this._markCalcNodeChangedByType(3,e)}markCalcNodeChanged(e){this._markCalcNodeChangedByType(e.type,e.id)}_markCalcNodeChangedByType(e,t){let n=this._getNodeIndexByType(e,t);n!==void 0&&this._activeNode[n]&&(this._markNodeIndexDirty(n,!0),this._propagateDirtyQueue())}markCalcNodesChanged(e){if(e.length!==0){this._nextEmitEpoch();for(let t=0;t<e.length;t++){let n=e[t],r=this._getNodeIndexByType(n.type,n.id);r!==void 0&&this._activeNode[r]&&this._emitNodeOnceAndMarkDirty(r,!0)}this._propagateDirtyQueue()}}markAllDirty(){this._nextEmitEpoch();for(let e=0;e<this.indexToNodeId.length;e++)this._activeNode[e]&&this._emitNodeOnceAndMarkDirty(e,!0);this._propagateDirtyQueue()}hasDynamicDeps(e){let t=this.getNodeIndex(e);if(t===void 0)return!1;let n=this._dynamicDeps[t];return n!==void 0&&n.length>0}refreshDynamicDeps(e,t){let n=this.getNodeIndex(e);if(n===void 0||!this._activeNode[n])return!1;let r=this._dynamicDeps[n];if(!r||r.length===0)return!1;let i={cells:[],ranges:[],nodes:[]},a=[];for(let n=0;n<r.length;n++){var o;let s=r[n],c=t(e,s),l=(o=c.status)==null?`resolved`:o;a.push(`${String(s.id)}:${l}:${c.signature}`),this._collectDynamicResolveResult(i,c)}i.cells=M(i.cells),i.ranges=this._normalizeRangeDeps(i.ranges),i.nodes=this._mergeSortedUniqueNumbers([],i.nodes);let s=a.join(`|`),c=this._dynamicSignature[n];return this._removeRuntimeDepsOnly(n),this._addRuntimeDepsOnly(n,i.cells,i.ranges,i.nodes),this._dynamicSignature[n]=s,s===c?!1:(this._markNodeIndexDirty(n,!0),this._propagateDirtyQueue(),!0)}prepareDynamicDependencies(e){let t=this._getDirtyNodeIndicesSnapshot(),n=!1;for(let r=0;r<t.length;r++){let i=t[r],a=this._dynamicDeps[i];!a||a.length===0||this.refreshDynamicDeps(this.getNodeRefByIndex(i),e)&&(n=!0)}return n}getCalculationOrder(e){let t=this._getDirtyNodeIndicesSnapshot();if(t.length===0)return{hasCycle:!1,calculationForest:[]};let n=this._buildDirtyCalculationGraph(t);return{hasCycle:n.hasCycle,calculationForest:n.calculationForest}}clearCalculatedDirty(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];this.dirty[r]&&(this.dirty[r]=0,this._dirtyNodeCount--,t=!0)}t&&this._compactDirtyList()}_compactDirtyList(){let e=0;for(let t=0;t<this._dirtyList.length;t++){let n=this._dirtyList[t];this.dirty[n]&&this._activeNode[n]&&(this._dirtyList[e++]=n)}this._dirtyList.length=e}clearAllDirty(){for(let e=0;e<this._dirtyList.length;e++)this.dirty[this._dirtyList[e]]=0;this._dirtyList.length=0,this._dirtyNodeCount=0}getDirtyNodeIndices(){return this._getDirtyNodeIndicesSnapshot()}getDirtyNodes(){let e=this._getDirtyNodeIndicesSnapshot(),t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=this.getNodeRefByIndex(e[n]);return t}forEachDependentByCell(e,t){this._nextEmitEpoch(),this._forEachDependentIndexByCellRaw(e,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)})}forEachDependentByRange(e,t){this._nextEmitEpoch(),this._directPointIndex.forEachCellInRange(e,e=>{R(this.directDeps.get(e),e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)})}),this._runtimeDirectPointIndex.forEachCellInRange(e,e=>{R(this._runtimeDirectDeps.get(e),e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)})}),this.rangeIndex.forEachRangeIntersecting(e,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}),this._runtimeRangeIndex.forEachRangeIntersecting(e,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}),this._forEachCompressedSharedDependentByRange(e,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)})}forEachDependentByNode(e,t){let n=this.getNodeIndex(e);n!==void 0&&(this._nextEmitEpoch(),this._forEachDependentOfNodeRaw(n,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}))}forEachDependentByIndex(e,t){this._activeNode[e]&&(this._nextEmitEpoch(),this._forEachDependentOfNodeRaw(e,e=>{this._activeNode[e]&&this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}))}forEachPrecedentNode(e,t){let n=this.getNodeIndex(e);n!==void 0&&this._activeNode[n]&&(this._nextEmitEpoch(),this._forEachPrecedentNodeIndex(n,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}))}forEachPrecedentNodeByIndex(e,t){this._activeNode[e]&&(this._nextEmitEpoch(),this._forEachPrecedentNodeIndex(e,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}))}hasUncalculatedDirtyPrecedentByIndex(e,t){if(!this._activeNode[e])return!1;let n=!1;return this._nextEmitEpoch(),this._forEachPrecedentNodeIndex(e,e=>{if(!n&&this.dirty[e]&&!t.has(e))return n=!0,!1}),n}wouldCreateCycle(e,t){let n=this._getOrCreateNodeIndex(e),r=this._normalizeCalcNodeDeps(t),i=r.cells,a=r.ranges,o=r.nodes,s=this._resolveExplicitNodeDeps(o);return this._wouldCreateCycleForNewDeps(n,i,a,s)}_normalizeCalcNodeDeps(e){let t=[],n=[],r=[];return this._collectStaticDeps(e,t,n,r),{cells:M(t),ranges:this._normalizeRangeDeps(n),nodes:U(r),dynamics:e.dynamics?e.dynamics.slice():[]}}_collectStaticDeps(e,t,n,r){if(e&&(e.cells&&t.push(...e.cells),e.ranges&&n.push(...e.ranges),e.nodes&&r.push(...e.nodes),e.dynamics))for(let i=0;i<e.dynamics.length;i++)this._collectStaticDeps(e.dynamics[i].paramDeps,t,n,r)}_mergeDynamicDeps(e,t){if(e.length===0)return t;if(t.length===0)return e;let n=e.slice();for(let e=0;e<t.length;e++){let r=t[e],i=!1;for(let e=0;e<n.length;e++)if(n[e].id===r.id){i=!0;break}i||n.push(r)}return n}_setNodeDynamicDeps(e,t){let n=this._dynamicDeps[e];n===void 0&&t.length===0||this._isSameDynamicDeps(n,t)||(this._removeRuntimeDepsOnly(e),this._dynamicSignature[e]=void 0,this._dynamicDeps[e]=t.length>0?t:void 0)}_isSameDynamicDeps(e,t){var n;if(((n=e==null?void 0:e.length)==null?0:n)!==t.length)return!1;if(!e)return t.length===0;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}_normalizeRangeDeps(e){if(!e||e.length===0)return[];let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=O(e[n]);return t}_mergeSortedUniqueNumbers(e,t){if(e.length===0)return t;if(t.length===0)return e;let n=[],r=0,i=0;for(;r<e.length&&i<t.length;){let a=e[r],o=t[i];a===o?(n.push(a),r++,i++):a<o?(n.push(a),r++):(n.push(o),i++)}for(;r<e.length;)n.push(e[r++]);for(;i<t.length;)n.push(t[i++]);return n}_mergeRangeDeps(e,t){if(e.length===0)return t;if(t.length===0)return e;let n=e.slice();for(let e=0;e<t.length;e++){let r=t[e];this._containsRange(n,r)||n.push(r)}return n}_containsRange(e,t){for(let n=0;n<e.length;n++)if(this._isSameRange(e[n],t))return!0;return!1}_isSameRange(e,t){return e.unitId===t.unitId&&e.sheetId===t.sheetId&&e.range.startRow===t.range.startRow&&e.range.endRow===t.range.endRow&&e.range.startColumn===t.range.startColumn&&e.range.endColumn===t.range.endColumn}canReachNode(e,t){let n=this.getNodeIndex(e),r=this.getNodeIndex(t);return n===void 0||r===void 0?!1:this._canReachNodeIndex(n,r)}hasCellFormula(e){let t=this.cellFormulaToIndex.get(e);return t!==void 0&&this._activeNode[t]===1}hasOtherFormula(e){let t=this.otherFormulaToIndex.get(e);return t!==void 0&&this._activeNode[t]===1}hasFeatureCalculation(e){let t=this.featureCalculationToIndex.get(e);return t!==void 0&&this._activeNode[t]===1}getNodeIndex(e){return this._getNodeIndexByType(e.type,e.id)}_getNodeIndexByType(e,t){switch(e){case 1:return D(t),this.cellFormulaToIndex.get(t);case 2:return this.otherFormulaToIndex.get(t);case 3:return this.featureCalculationToIndex.get(t);default:return}}getNodeRefByIndex(e){return{type:this._indexToNodeType[e],id:this.indexToNodeId[e]}}markCalcNodeIndicesChanged(e,t){this._markCalcNodeIndicesChanged(e,t)}_markCalcNodeIndicesChanged(e,t){if(e.length===0)return;this._nextEmitEpoch();let n=(t==null?void 0:t.onlySelf)!==!0;for(let t=0;t<e.length;t++){let r=e[t];this._activeNode[r]&&this._emitNodeOnceAndMarkDirty(r,n,n)}n&&this._propagateDirtyQueue()}_getOrCreateNodeIndex(e){return this._getOrCreateNodeIndexByType(e.type,e.id)}_getOrCreateNodeIndexByType(e,t){let n=this._getNodeIndexByType(e,t);if(n!==void 0)return n;let r=this.indexToNodeId.length;switch(this.indexToNodeId.push(t),this._ensureNodeCapacity(r+1),this._indexToNodeType[r]=e,e){case 1:D(t),this.cellFormulaToIndex.set(t,r);break;case 2:this.otherFormulaToIndex.set(t,r);break;case 3:this.featureCalculationToIndex.set(t,r);break;default:throw Error(`Unknown CalcNodeType: ${e}`)}return r}_ensureNodeCapacity(e){let t=this._sharedFormulaMembershipByNode.length;this._indexToNodeType=V(this._indexToNodeType,e),this.dirty=V(this.dirty,e),this.inQueue=V(this.inQueue,e),this._activeNode=V(this._activeNode,e),this._seenNodeEpoch=H(this._seenNodeEpoch,e),this._visitNodeEpoch=H(this._visitNodeEpoch,e),this._edgeSeenEpoch=H(this._edgeSeenEpoch,e),this._tarjanSeenEpoch=H(this._tarjanSeenEpoch,e),this._tarjanIndexArr=H(this._tarjanIndexArr,e),this._tarjanLowArr=H(this._tarjanLowArr,e),this._tarjanOnStack=V(this._tarjanOnStack,e),this._sharedFormulaMembershipByNode=this._growIntThirtyTwoArray(this._sharedFormulaMembershipByNode,e,-1),this._sharedFormulaMembershipByNode.length>t&&this._sharedFormulaMembershipByNode.fill(-1,t)}_growIntThirtyTwoArray(e,t,n){if(e.length>=t)return e;let r=Math.max(16,e.length);for(;r<t;)r*=2;let i=new Int32Array(r);return i.fill(n),i.set(e),i}_resolveExplicitNodeDeps(e){if(e.length===0)return[];let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.type===2)throw Error(`OtherFormula cannot be used as a dependency`);let i=this._getOrCreateNodeIndex(r);t.push(i)}if(t.length<=1)return t;t.sort((e,t)=>e-t);let n=1;for(let e=1;e<t.length;e++)t[e]!==t[n-1]&&(t[n++]=t[e]);return t.length=n,t}_isEmptyCalcNodeDeps(e){return(e.cells==null||e.cells.length===0)&&(e.ranges==null||e.ranges.length===0)&&(e.nodes==null||e.nodes.length===0)&&(e.dynamics==null||e.dynamics.length===0)}_unregisterCompressedSharedFormulaGroupByNode(e){let t=this._sharedFormulaMembershipByNode[e];if(t<0)return;let n=this._sharedFormulaGroups[t];if(n==null||!this._sharedFormulaGroupIndexById.has(n.groupId)){this._sharedFormulaMembershipByNode[e]=-1;return}this.unregisterCompressedSharedFormulaGroup(n.groupId)}_markCompressedSharedFormulaMembership(e,t){for(let n=t.range.startRow;n<=t.range.endRow;n++)for(let r=t.range.startColumn;r<=t.range.endColumn;r++){let i=this.codec.encodeCell(t.unitId,t.sheetId,n,r),a=this.cellFormulaToIndex.get(i);a!==void 0&&this._activeNode[a]&&(this._sharedFormulaMembershipByNode[a]=e)}}_clearCompressedSharedFormulaMembership(e,t){for(let n=t.range.startRow;n<=t.range.endRow;n++)for(let r=t.range.startColumn;r<=t.range.endColumn;r++){let i=this.codec.encodeCell(t.unitId,t.sheetId,n,r),a=this.cellFormulaToIndex.get(i);a!==void 0&&this._sharedFormulaMembershipByNode[a]===e&&(this._sharedFormulaMembershipByNode[a]=-1)}}_getCompressedSharedSourceCoverage(e,t){if(t.kind===`cell`)return O({unitId:t.unitId,sheetId:t.sheetId,range:{startRow:e.range.startRow+t.rowDelta,endRow:e.range.endRow+t.rowDelta,startColumn:e.range.startColumn+t.colDelta,endColumn:e.range.endColumn+t.colDelta}});let n=Math.min(t.startRowDelta,t.endRowDelta),r=Math.max(t.startRowDelta,t.endRowDelta),i=Math.min(t.startColDelta,t.endColDelta),a=Math.max(t.startColDelta,t.endColDelta);return O({unitId:t.unitId,sheetId:t.sheetId,range:{startRow:e.range.startRow+n,endRow:e.range.endRow+r,startColumn:e.range.startColumn+i,endColumn:e.range.endColumn+a}})}_forEachCompressedSharedDependentByRange(e,t){let n=O(e);this._sharedFormulaSourceRangeIndex.forEachRangeIntersecting(n,e=>{let r=this._sharedFormulaSourceEntries[e];if(!(r!=null&&r.active))return;let i=this._sharedFormulaGroups[r.groupIndex],a=this._reverseMapCompressedSharedPattern(n,i.fillRange,i.patterns[r.patternIndex]);a!=null&&this._forEachActiveCellFormulaInRange(a,t)})}_forEachActiveCellFormulaInRange(e,t){for(let n=e.range.startRow;n<=e.range.endRow;n++)for(let r=e.range.startColumn;r<=e.range.endColumn;r++){let i=this.codec.encodeCell(e.unitId,e.sheetId,n,r),a=this.cellFormulaToIndex.get(i);a!==void 0&&this._activeNode[a]&&t(a)}}_reverseMapCompressedSharedPattern(e,t,n){let r=n.kind===`cell`?[e.range.startRow-n.rowDelta,e.range.endRow-n.rowDelta]:[e.range.startRow-Math.max(n.startRowDelta,n.endRowDelta),e.range.endRow-Math.min(n.startRowDelta,n.endRowDelta)],i=n.kind===`cell`?[e.range.startColumn-n.colDelta,e.range.endColumn-n.colDelta]:[e.range.startColumn-Math.max(n.startColDelta,n.endColDelta),e.range.endColumn-Math.min(n.startColDelta,n.endColDelta)];return this._intersectRanges(t,{unitId:t.unitId,sheetId:t.sheetId,range:{startRow:r[0],endRow:r[1],startColumn:i[0],endColumn:i[1]}})}_intersectRanges(e,t){if(e.unitId!==t.unitId||e.sheetId!==t.sheetId)return;let n=Math.max(e.range.startRow,t.range.startRow),r=Math.min(e.range.endRow,t.range.endRow),i=Math.max(e.range.startColumn,t.range.startColumn),a=Math.min(e.range.endColumn,t.range.endColumn);if(!(n>r||i>a))return{unitId:e.unitId,sheetId:e.sheetId,range:{startRow:n,endRow:r,startColumn:i,endColumn:a}}}_forEachCompressedSharedPrecedent(e,t){let n=this._sharedFormulaMembershipByNode[e];if(n<0)return!0;let r=this._sharedFormulaGroups[n];for(let e=0;e<r.patterns.length;e++)if(t(r.patterns[e])===!1)return!1;return!0}_getCompressedSharedPrecedentCell(e,t){let n=this.indexToNodeId[e],r=this.codec.decodeCell(n);return this.codec.encodeCell(t.unitId,t.sheetId,r.row+t.rowDelta,r.col+t.colDelta)}_getCompressedSharedPrecedentRange(e,t){let n=this.indexToNodeId[e],r=this.codec.decodeCell(n);return O({unitId:t.unitId,sheetId:t.sheetId,range:{startRow:r.row+t.startRowDelta,startColumn:r.col+t.startColDelta,endRow:r.row+t.endRowDelta,endColumn:r.col+t.endColDelta}})}_addNodeDepsOnly(e,t,n,r){for(let n=0;n<t.length;n++)this._addDirectEdge(t[n],e);this._cellPrecedents[e]=t.length>0?t:void 0,this._rangePrecedents[e]=n.length>0?n:void 0;for(let t=0;t<n.length;t++)this.rangeIndex.addRange(e,n[t]);this._nodePrecedents[e]=r.length>0?r:void 0;for(let t=0;t<r.length;t++)this._addExplicitNodeEdge(r[t],e)}_removeNodeDepsOnly(e){let t=this._cellPrecedents[e];if(t){for(let n=0;n<t.length;n++)this._removeDirectEdge(t[n],e);this._cellPrecedents[e]=void 0}this.rangeIndex.removeNode(e),this._rangePrecedents[e]=void 0;let n=this._nodePrecedents[e];if(n){for(let t=0;t<n.length;t++)this._removeExplicitNodeEdge(n[t],e);this._nodePrecedents[e]=void 0}}_collectDynamicResolveResult(e,t){t.traceCells&&e.cells.push(...t.traceCells),t.cells&&e.cells.push(...t.cells),t.ranges&&e.ranges.push(...t.ranges),t.nodes&&e.nodes.push(...this._resolveExplicitNodeDeps(U(t.nodes)))}_addRuntimeDepsOnly(e,t,n,r){for(let n=0;n<t.length;n++)this._addRuntimeDirectEdge(t[n],e);this._runtimeCellPrecedents[e]=t.length>0?t:void 0,this._runtimeRangePrecedents[e]=n.length>0?n:void 0;for(let t=0;t<n.length;t++)this._runtimeRangeIndex.addRange(e,n[t]);this._runtimeNodePrecedents[e]=r.length>0?r:void 0;for(let t=0;t<r.length;t++)this._addRuntimeExplicitNodeEdge(r[t],e)}_removeRuntimeDepsOnly(e){let t=this._runtimeCellPrecedents[e];if(t){for(let n=0;n<t.length;n++)this._removeRuntimeDirectEdge(t[n],e);this._runtimeCellPrecedents[e]=void 0}this._runtimeRangeIndex.removeNode(e),this._runtimeRangePrecedents[e]=void 0;let n=this._runtimeNodePrecedents[e];if(n){for(let t=0;t<n.length;t++)this._removeRuntimeExplicitNodeEdge(n[t],e);this._runtimeNodePrecedents[e]=void 0}}_detachDependentsFromNode(e){let t=this.nodeDeps.get(e),n=[];R(t,e=>{n.push(e)}),this.nodeDeps.delete(e);for(let t=0;t<n.length;t++)this._detachPrecedentFromDependent(n[t],e);let r=this._runtimeNodeDeps.get(e);if(r===void 0)return;let i=[];R(r,e=>{i.push(e)}),this._runtimeNodeDeps.delete(e);for(let t=0;t<i.length;t++)this._detachRuntimePrecedentFromDependent(i[t],e)}_detachPrecedentFromDependent(e,t){let n=this._nodePrecedents[e];if(n===void 0)return;let r=0,i=!1;for(let e=0;e<n.length;e++){let a=n[e];if(a===t){i=!0;continue}n[r++]=a}i&&(r===0?this._nodePrecedents[e]=void 0:n.length=r)}_detachRuntimePrecedentFromDependent(e,t){let n=this._runtimeNodePrecedents[e];if(n===void 0)return;let r=0,i=!1;for(let e=0;e<n.length;e++){let a=n[e];if(a===t){i=!0;continue}n[r++]=a}i&&(r===0?this._runtimeNodePrecedents[e]=void 0:n.length=r)}_addDirectEdge(e,t){let n=this.directDeps.get(e);n===void 0&&this._directPointIndex.add(e),this.directDeps.set(e,I(n,t))}_removeDirectEdge(e,t){let n=this.directDeps.get(e);if(n===void 0)return;let r=L(n,t);r===void 0?(this.directDeps.delete(e),this._directPointIndex.remove(e)):this.directDeps.set(e,r)}_addRuntimeDirectEdge(e,t){let n=this._runtimeDirectDeps.get(e);n===void 0&&this._runtimeDirectPointIndex.add(e),this._runtimeDirectDeps.set(e,I(n,t))}_removeRuntimeDirectEdge(e,t){let n=this._runtimeDirectDeps.get(e);if(n===void 0)return;let r=L(n,t);r===void 0?(this._runtimeDirectDeps.delete(e),this._runtimeDirectPointIndex.remove(e)):this._runtimeDirectDeps.set(e,r)}_addExplicitNodeEdge(e,t){z(this.nodeDeps,e,t)}_removeExplicitNodeEdge(e,t){B(this.nodeDeps,e,t)}_addRuntimeExplicitNodeEdge(e,t){z(this._runtimeNodeDeps,e,t)}_removeRuntimeExplicitNodeEdge(e,t){B(this._runtimeNodeDeps,e,t)}_forEachDependentIndexByCellRaw(e,t){R(this.directDeps.get(e),t),R(this._runtimeDirectDeps.get(e),t);let n=this.codec.decodeCell(e);this.rangeIndex.forEachPoint(n.unitId,n.sheetId,n.row,n.col,t),this._runtimeRangeIndex.forEachPoint(n.unitId,n.sheetId,n.row,n.col,t),this._forEachCompressedSharedDependentByRange({unitId:n.unitId,sheetId:n.sheetId,range:{startRow:n.row,endRow:n.row,startColumn:n.col,endColumn:n.col}},t)}_forEachDependentOfNodeRaw(e,t){if(this._indexToNodeType[e]===1){let n=this.indexToNodeId[e];this._forEachDependentIndexByCellRaw(n,t)}R(this.nodeDeps.get(e),t),R(this._runtimeNodeDeps.get(e),t)}_markNodeIndexDirty(e,t=!1,n=!0){if(!this._activeNode[e])return;let r=this.dirty[e]===1;r||(this.dirty[e]=1,this._dirtyList.push(e),this._dirtyNodeCount++),n&&(!r||t)&&!this.inQueue[e]&&(this.inQueue[e]=1,this._propQueue.push(e))}_isEveryActiveNodeDirty(){return this._activeNodeCount>0&&this._dirtyNodeCount>=this._activeNodeCount}_propagateDirtyQueue(){if(this._isEveryActiveNodeDirty()){for(let e=0;e<this._propQueue.length;e++)this.inQueue[this._propQueue[e]]=0;this._propQueue.length=0;return}let e=0;for(;e<this._propQueue.length;){let t=this._propQueue[e++];this.inQueue[t]=0,this._activeNode[t]&&this._forEachDependentOfNodeRaw(t,e=>{this._markNodeIndexDirty(e,!1)})}this._propQueue.length=0}_getDirtyNodeIndicesSnapshot(){let e=[];for(let t=0;t<this._dirtyList.length;t++){let n=this._dirtyList[t];this.dirty[n]&&this._activeNode[n]&&e.push(n)}return e}_forEachDependentOfNodeDeduped(e,t){this._nextEdgeEpoch(),this._forEachDependentOfNodeRaw(e,e=>{this._edgeSeenEpoch[e]!==this._edgeEpoch&&(this._edgeSeenEpoch[e]=this._edgeEpoch,t(e))})}_forEachPrecedentNodeIndex(e,t){let n=this._cellPrecedents[e];if(n)for(let e=0;e<n.length;e++){let r=n[e],i=this.cellFormulaToIndex.get(r);if(i!==void 0&&this._activeNode[i]&&t(i)===!1)return!1}let r=this._rangePrecedents[e];if(r)for(let e=0;e<r.length;e++){let n=!0;if(this._formulaCellIndex.forEachFormulaInRange(r[e],e=>{if(n&&this._activeNode[e]&&t(e)===!1)return n=!1,!1}),!n)return!1}if(!this._forEachCompressedSharedPrecedent(e,n=>{if(n.kind===`cell`){let r=this._getCompressedSharedPrecedentCell(e,n),i=this.cellFormulaToIndex.get(r);return i!==void 0&&this._activeNode[i]&&t(i)===!1?!1:void 0}let r=!0;return this._formulaCellIndex.forEachFormulaInRange(this._getCompressedSharedPrecedentRange(e,n),e=>{if(r&&this._activeNode[e]&&t(e)===!1)return r=!1,!1}),r}))return!1;let i=this._nodePrecedents[e];if(i)for(let e=0;e<i.length;e++){let n=i[e];if(this._activeNode[n]&&t(n)===!1)return!1}let a=this._runtimeCellPrecedents[e];if(a)for(let e=0;e<a.length;e++){let n=a[e],r=this.cellFormulaToIndex.get(n);if(r!==void 0&&this._activeNode[r]&&t(r)===!1)return!1}let o=this._runtimeRangePrecedents[e];if(o)for(let e=0;e<o.length;e++){let n=!0;if(this._formulaCellIndex.forEachFormulaInRange(o[e],e=>{if(n&&this._activeNode[e]&&t(e)===!1)return n=!1,!1}),!n)return!1}let s=this._runtimeNodePrecedents[e];if(s)for(let e=0;e<s.length;e++){let n=s[e];if(this._activeNode[n]&&t(n)===!1)return!1}return!0}_wouldCreateCycleForNewDeps(e,t,n,r){for(let n=0;n<t.length;n++){let r=t[n],i=this.cellFormulaToIndex.get(r);if(i!==void 0&&this._activeNode[i]&&(i===e||this._canReachNodeIndex(e,i)))return!0}if(this._indexToNodeType[e]===1){let t=this.indexToNodeId[e],r=this.codec.decodeCell(t);for(let e=0;e<n.length;e++)if(j(n[e],r))return!0}for(let t=0;t<n.length;t++){let r=n[t],i=!1;if(this._formulaCellIndex.forEachFormulaInRange(r,t=>{if(!i&&this._activeNode[t]){if(t===e){i=!0;return}this._canReachNodeIndex(e,t)&&(i=!0)}}),i)return!0}for(let t=0;t<r.length;t++){let n=r[t];if(n===e||this._canReachNodeIndex(e,n))return!0}return!1}_canReachNodeIndex(e,t){if(e===t)return!0;this._nextVisitEpoch();let n=[e];for(;n.length>0;){let e=n.pop(),r=!1;if(this._forEachDependentOfNodeRaw(e,e=>{if(!r&&this._visitNodeEpoch[e]!==this._visitEpoch){if(this._visitNodeEpoch[e]=this._visitEpoch,e===t){r=!0;return}n.push(e)}}),r)return!0}return!1}_buildDirtyCalculationGraph(e){let t=this._tryBuildAcyclicDirtyCalculationGraph(e);return t===void 0?this._buildDirtyCalculationGraphWithScc(e):t}_tryBuildAcyclicDirtyCalculationGraph(e){let t=e.length;this._nextTarjanEpoch();for(let n=0;n<t;n++){let t=e[n];this._tarjanSeenEpoch[t]=this._tarjanEpoch,this._tarjanIndexArr[t]=n+1}let n=new Uint32Array(t),r=new Int32Array(t),i=new Int32Array(t),a=new Uint8Array(t),o=new Uint8Array(t),s=new Uint8Array(t),c=[],l=[],u=new Map,d=[],f=[],p=[],m=[],h=new Y(this.codec,this._initialRangeCapacity,this._maxIndexedSpan);for(let e=0;e<t;e++)i[e]=e,r[e]=-1;for(let g=0;g<t;g++){let t=e[g];this._nextEdgeEpoch(),this._addAcyclicExactPrecedentEdges(t,g,n,r,c,l,i,a,o,s),this._addAcyclicRangePrecedentGroups(t,g,n,u,d,f,p,m,h,i,a,o,s)}let g=new Int32Array(t),_=0,v=0;for(let e=0;e<t;e++)n[e]===0&&(g[v++]=e);let y=new Int32Array(t),b=[],x=-1,S=0,C=!1;for(;_<v;){let t=g[_++],a=e[t];S++,this._appendAcyclicCalculationNode(b,y,i,o,s,t,a,x),C=C||s[t]===1,o[t]===0&&x===-1&&(x=b.length-1);for(let e=r[t];e!==-1;e=l[e]){let t=c[e];n[t]--,n[t]===0&&(g[v++]=t)}if(this._indexToNodeType[a]===1){let e=this.indexToNodeId[a],t=this.codec.decodeCell(e);h.forEachPoint(t.unitId,t.sheetId,t.row,t.col,e=>{if(f[e]<=0||(f[e]--,f[e]!==0))return;let t=p[e];for(let e=0;e<t.length;e++){let r=t[e];n[r]--,n[r]===0&&(g[v++]=r)}})}}if(S===t)return{calculationForest:b,hasCycle:C}}_addAcyclicExactPrecedentEdges(e,t,n,r,i,a,o,s,c,l){let u=e=>{if(e===void 0||!this._activeNode[e]||!this.dirty[e]||this._edgeSeenEpoch[e]===this._edgeEpoch)return;this._edgeSeenEpoch[e]=this._edgeEpoch;let u=this._getCurrentDirtyOrdinal(e);if(!(u<0)){if(c[u]=1,c[t]=1,u===t){l[t]=1;return}a.push(r[u]),i.push(t),r[u]=i.length-1,n[t]++,this._unionCalculationForestComponents(o,s,u,t)}},d=this._cellPrecedents[e];if(d)for(let e=0;e<d.length;e++)u(this.cellFormulaToIndex.get(d[e]));let f=this._nodePrecedents[e];if(f)for(let e=0;e<f.length;e++)u(f[e]);let p=this._runtimeCellPrecedents[e];if(p)for(let e=0;e<p.length;e++)u(this.cellFormulaToIndex.get(p[e]));let m=this._runtimeNodePrecedents[e];if(m)for(let e=0;e<m.length;e++)u(m[e]);this._forEachCompressedSharedPrecedent(e,t=>{t.kind===`cell`&&u(this.cellFormulaToIndex.get(this._getCompressedSharedPrecedentCell(e,t)))})}_addAcyclicRangePrecedentGroups(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=[],m=m=>{let h=this._getOrCreateAcyclicRangeGroup(m,r,i,a,o,s,c,l,u,d);if(a[h]===0)return;for(let e=0;e<p.length;e++)if(p[e]===h)return;p.push(h),o[h].push(t),n[t]++,d[t]=1;let g=s[h];g>=0&&this._unionCalculationForestComponents(l,u,g,t),this._indexToNodeType[e]===1&&j(m,this.codec.decodeCell(this.indexToNodeId[e]))&&(f[t]=1)},h=this._rangePrecedents[e];if(h)for(let e=0;e<h.length;e++)m(h[e]);let g=this._runtimeRangePrecedents[e];if(g)for(let e=0;e<g.length;e++)m(g[e]);this._forEachCompressedSharedPrecedent(e,t=>{t.kind===`range`&&m(this._getCompressedSharedPrecedentRange(e,t))})}_getOrCreateAcyclicRangeGroup(e,t,n,r,i,a,o,s,c,l){let u=O(e),d=[u.unitId,u.sheetId,u.range.startRow,u.range.endRow,u.range.startColumn,u.range.endColumn].join(`:`),f=t.get(d);if(f!==void 0)return f;let p=n.length,m=0,h=-1;return t.set(d,p),n.push(u),i.push([]),o.addRange(p,u),this._formulaCellIndex.forEachFormulaInRange(u,e=>{if(!this._activeNode[e]||!this.dirty[e])return;let t=this._getCurrentDirtyOrdinal(e);if(!(t<0)){if(m++,l[t]=1,h===-1){h=t;return}this._unionCalculationForestComponents(s,c,h,t)}}),r.push(m),a.push(h),p}_appendAcyclicCalculationNode(e,t,n,r,i,a,o,s){let c=r[a]===0,l=this._findCalculationForestRoot(n,a),u=(c?s+1:t[l])-1;if(u===-1&&(u=e.length,c||(t[l]=u+1),e.push({hasCycle:!1,plan:[]})),i[a]===1){e[u].plan.push({type:`cycle`,nodeIndices:[o]}),e[u].hasCycle=!0;return}this._appendCalculationNodePlanItem(e[u].plan,o)}_getCurrentDirtyOrdinal(e){return this._tarjanSeenEpoch[e]===this._tarjanEpoch?this._tarjanIndexArr[e]-1:-1}_buildDirtyCalculationGraphWithScc(e){let t=this._findDirtySccs(e),n=t.componentStarts.length,r=new Int32Array(this.indexToNodeId.length),i=new Int32Array(this.indexToNodeId.length);r.fill(-1),i.fill(-1);for(let t=0;t<e.length;t++)i[e[t]]=t;let a=new Int32Array(n);a.fill(2**53-1);for(let e=0;e<n;e++){let n=2**53-1,o=t.componentStarts[e],s=this._getDirtySccEnd(t,e);for(let a=o;a<s;a++){let o=t.componentNodes[a];r[o]=e;let s=i[o];s>=0&&s<n&&(n=s)}a[e]=n}let o=new Int32Array(n);o.fill(-1);let s=[],c=[],l=new Int32Array(n),u=new Uint8Array(n),d=new Uint8Array(n),f=new Uint32Array(n),p=1,m=new Uint32Array(n);for(let e=0;e<n;e++)l[e]=e;for(let e=0;e<n;e++){p===4294967295&&(f.fill(0),p=1);let n=t.componentStarts[e],i=this._getDirtySccEnd(t,e);for(let a=n;a<i;a++){let n=t.componentNodes[a];this._forEachDependentOfNodeDeduped(n,t=>{if(!this._activeNode[t]||!this.dirty[t])return;let n=r[t];n<0||n===e||f[n]!==p&&(f[n]=p,c.push(o[e]),s.push(n),o[e]=s.length-1,m[n]++,d[e]=1,d[n]=1,this._unionCalculationForestComponents(l,u,e,n))})}p++}let h=this._toposortComponents(o,s,c,m,a),g=this._buildCalculationForest(t,h,l,d);t.componentNodes.length=0,t.componentStarts.length=0,s.length=0,c.length=0,h.length=0;let _=!1;for(let e=0;e<g.length;e++)if(g[e].hasCycle){_=!0;break}return{calculationForest:g,hasCycle:_}}_toposortComponents(e,t,n,r,i){let a=new Uint32Array(r),o=[];for(let e=0;e<a.length;e++)a[e]===0&&this._insertComponentByRank(o,0,e,i);let s=[],c=0;for(;c<o.length;){let r=o[c++];s.push(r);for(let s=e[r];s!==-1;s=n[s]){let e=t[s];a[e]--,a[e]===0&&this._insertComponentByRank(o,c,e,i)}}return s}_insertComponentByRank(e,t,n,r){let i=e.length,a=r[n];for(;i>t&&r[e[i-1]]>a;)i--;e.splice(i,0,n)}_buildCalculationForest(e,t,n,r){let i=new Int32Array(e.componentStarts.length);i.fill(-1);let a=[],o=-1;for(let s=0;s<t.length;s++){let c=t[s],l=this._findCalculationForestRoot(n,c),u=r[c]===0,d=u?o:i[l];d===-1&&(d=a.length,u?o=d:i[l]=d,a.push({hasCycle:!1,plan:[]}));let f=a[d],p=this._createCalculationPlanItem(e,c);if(p.type===`node`){this._appendCalculationNodePlanItem(f.plan,p.nodeIndex);continue}f.plan.push(p),p.type===`cycle`&&(f.hasCycle=!0)}return a}_appendCalculationNodePlanItem(e,t){let n=e[e.length-1];if((n==null?void 0:n.type)===`nodes`&&n.nodeIndices.length<8192){n.nodeIndices.push(t);return}e.push({type:`nodes`,nodeIndices:[t]})}_findCalculationForestRoot(e,t){let n=t;for(;e[n]!==n;)n=e[n];for(;e[t]!==t;){let r=e[t];e[t]=n,t=r}return n}_unionCalculationForestComponents(e,t,n,r){let i=this._findCalculationForestRoot(e,n),a=this._findCalculationForestRoot(e,r);if(i!==a){if(t[i]<t[a]){let e=i;i=a,a=e}e[a]=i,t[i]===t[a]&&t[i]++}}_createCalculationPlanItem(e,t){let n=e.componentStarts[t],r=this._getDirtySccEnd(e,t);if(r-n===1&&!this._hasSelfLoop(e.componentNodes[n]))return{type:`node`,nodeIndex:e.componentNodes[n]};let i=e.componentNodes.slice(n,r);return i.sort((e,t)=>e-t),{type:`cycle`,nodeIndices:i}}_getDirtySccEnd(e,t){return t+1<e.componentStarts.length?e.componentStarts[t+1]:e.componentNodes.length}_findDirtySccs(e){this._nextTarjanEpoch();let t=1,n=[],r=[],i=[],a=e=>{if(this._tarjanSeenEpoch[e]=this._tarjanEpoch,this._tarjanIndexArr[e]=t,this._tarjanLowArr[e]=t,t++,n.push(e),this._tarjanOnStack[e]=1,this._forEachDependentOfNodeDeduped(e,t=>{this._activeNode[t]&&this.dirty[t]&&(this._tarjanSeenEpoch[t]===this._tarjanEpoch?this._tarjanOnStack[t]&&(this._tarjanLowArr[e]=Math.min(this._tarjanLowArr[e],this._tarjanIndexArr[t])):(a(t),this._tarjanLowArr[e]=Math.min(this._tarjanLowArr[e],this._tarjanLowArr[t])))}),this._tarjanLowArr[e]===this._tarjanIndexArr[e])for(i.push(r.length);;){let t=n.pop();if(this._tarjanOnStack[t]=0,r.push(t),t===e)break}};for(let t=0;t<e.length;t++){let n=e[t];this._activeNode[n]&&this.dirty[n]&&this._tarjanSeenEpoch[n]!==this._tarjanEpoch&&a(n)}return{componentNodes:r,componentStarts:i}}_hasSelfLoop(e){let t=!1;return this._forEachDependentOfNodeDeduped(e,n=>{n===e&&(t=!0)}),t}_nextEmitEpoch(){this._emitEpoch++,this._emitEpoch>=4294967295&&(this._seenNodeEpoch.fill(0),this._emitEpoch=1)}_emitNodeOnce(e){return this._seenNodeEpoch[e]===this._emitEpoch?!1:(this._seenNodeEpoch[e]=this._emitEpoch,!0)}_emitNodeOnceAndMarkDirty(e,t=!1,n=!0){this._emitNodeOnce(e)&&this._markNodeIndexDirty(e,t,n)}_nextVisitEpoch(){this._visitEpoch++,this._visitEpoch>=4294967295&&(this._visitNodeEpoch.fill(0),this._visitEpoch=1)}_nextEdgeEpoch(){this._edgeEpoch++,this._edgeEpoch>=4294967295&&(this._edgeSeenEpoch.fill(0),this._edgeEpoch=1)}_nextTarjanEpoch(){this._tarjanEpoch++,this._tarjanEpoch>=4294967295&&(this._tarjanSeenEpoch.fill(0),this._tarjanEpoch=1)}},Z=class extends t.DependencyManagerBaseService{constructor(...e){super(...e),x(this,`_dependencyEngineCache`,new X({maxRows:1048576,maxCols:16384}))}reset(){this._dependencyEngineCache.reset()}_getCellIdsAndRanges(e){let t=[],n=[];for(let r=0;r<e.rangeList.length;r++){let{unitId:i,sheetId:a,range:o}=e.rangeList[r];if(o.startRow===o.endRow&&o.startColumn===o.endColumn){let e=this._dependencyEngineCache.encodeCell(i,a,o.startRow,o.startColumn);t.push(e)}else n.push({unitId:i,sheetId:a,range:o})}return{cellIds:t,ranges:n}}_getDynamicDeps(e,t,n,r){if(!(!e.addressFunctionNodes||e.addressFunctionNodes.length===0))return[{id:`address-functions`,paramDeps:{cells:t,ranges:n,nodes:r}}]}addOtherFormulaDependencyPro(e,t,n,r,i,a=`replace`){let{cellIds:o,ranges:s}=this._getCellIdsAndRanges(r),c=this._getDynamicDeps(r,o,s,i),l=r.refOffsetX||0,u=r.refOffsetY||0,d=this._dependencyEngineCache.encodeOtherFormulaId(e,t,n,l,u);return this._dependencyEngineCache.setOtherFormulaDeps(d,{cells:o,ranges:s,nodes:i,dynamics:c},{checkCycle:!1,markDirty:!1,mode:a}).nodeIndex}removeOtherFormulaDependency(e,t,n){this._dependencyEngineCache.clearOtherFormulas(e,t,n,void 0,void 0,{markDependentsDirty:!0})}clearOtherFormulaDependency(e,t){t?this._dependencyEngineCache.clearOtherFormulas(e,t,void 0,void 0,void 0,{markDependentsDirty:!0}):this._dependencyEngineCache.clearOtherFormulas(e,void 0,void 0,void 0,void 0,{markDependentsDirty:!0})}getOtherFormulaDependencyPro(e,t,n,r,i){let a=this._dependencyEngineCache.encodeOtherFormulaId(e,t,n,r,i);if(this._dependencyEngineCache.hasOtherFormula(a))return this._dependencyEngineCache.getNodeIndex({type:2,id:a})}addFeatureFormulaDependencyPro(e,t,n,r){let{cellIds:i,ranges:a}=this._getCellIdsAndRanges(r),o=this._dependencyEngineCache.encodeFeatureCalculationId(e,t,n);return this._dependencyEngineCache.setFeatureCalculationDeps(o,{cells:i,ranges:a},{checkCycle:!1,markDirty:!1}).nodeIndex}removeFeatureFormulaDependency(e,t,n){let r=n.map(n=>this._dependencyEngineCache.encodeFeatureCalculationId(e,t,n));this._dependencyEngineCache.removeFeatureCalculations(r,{markDependentsDirty:!0,detachDependents:!0})}clearFeatureFormulaDependency(e,t){t?this._dependencyEngineCache.clearFeatureCalculations(e,t,{markDependentsDirty:!0,detachDependents:!0}):this._dependencyEngineCache.clearFeatureCalculations(e,void 0,{markDependentsDirty:!0,detachDependents:!0})}getFeatureFormulaDependencyPro(e,t,n){let r=this._dependencyEngineCache.encodeFeatureCalculationId(e,t,n);if(this._dependencyEngineCache.hasFeatureCalculation(r))return this._dependencyEngineCache.getNodeIndex({type:3,id:r})}getFeatureFormulaDependencyNodePro(e,t,n){return{type:3,id:this._dependencyEngineCache.encodeFeatureCalculationId(e,t,n)}}addFormulaDependencyPro(e,t,n,r,i,a,o=`replace`){let s=this._dependencyEngineCache.encodeCell(e,t,n,r),{cellIds:c,ranges:l}=this._getCellIdsAndRanges(i),u=this._getDynamicDeps(i,c,l,a);return this._dependencyEngineCache.setCellFormulaDeps(s,{cells:c,ranges:l,nodes:a,dynamics:u},{checkCycle:!1,markDirty:!1,mode:o}).nodeIndex}addFormulaDependencyNodeOnlyPro(e,t,n,r){let i=this._dependencyEngineCache.encodeCell(e,t,n,r);return this._dependencyEngineCache.setCellFormulaDeps(i,{},{checkCycle:!1,markDirty:!1}).nodeIndex}registerCompressedSharedFormulaGroup(e){this._dependencyEngineCache.registerCompressedSharedFormulaGroup(e)}clearCompressedSharedFormulaGroups(e,t){this._dependencyEngineCache.clearCompressedSharedFormulaGroups(e,t)}removeFormulaDependency(e,t,n,r){let i=this._dependencyEngineCache.encodeCell(e,t,n,r);this._dependencyEngineCache.removeCellFormula(i,{markDependentsDirty:!0})}clearFormulaDependency(e,t){this._dependencyEngineCache.clearCompressedSharedFormulaGroups(e,t),t?this._dependencyEngineCache.clearCellFormulas(e,t,{markDependentsDirty:!0}):this._dependencyEngineCache.clearCellFormulas(e,void 0,{markDependentsDirty:!0})}getFormulaDependencyPro(e,t,n,r){let i=this._dependencyEngineCache.encodeCell(e,t,n,r);if(this._dependencyEngineCache.hasCellFormula(i))return this._dependencyEngineCache.getNodeIndex({type:1,id:i})}markIndicesChanged(e,t){this._dependencyEngineCache.markCalcNodeIndicesChanged(e,t)}markRangesChanged(e,t){this._dependencyEngineCache.markRangesChanged(e,t)}markDirtyFeatureCalculations(e){let t=[];Object.keys(e).forEach(n=>{let r=e[n];r!=null&&Object.keys(r).forEach(e=>{let i=r[e];i!=null&&Object.keys(i).forEach(r=>{t.push(this.getFeatureFormulaDependencyNodePro(n,e,r))})})}),this._dependencyEngineCache.markCalcNodesChanged(t)}markDirtyOtherFormulas(e){Object.keys(e).forEach(t=>{let n=e[t];n!=null&&Object.keys(n).forEach(e=>{let r=n[e];r!=null&&this._dependencyEngineCache.markOtherFormulasChanged(t,e,Object.keys(r))})})}markDirtySheetNames(e){let t=[];Object.keys(e).forEach(n=>{let r=e[n];r!=null&&Object.keys(r).forEach(e=>{t.push({unitId:n,sheetId:e,range:{startRow:0,endRow:1048575,startColumn:0,endColumn:16383}})})}),this._dependencyEngineCache.markRangesChanged(t,{includeFormulaCells:!1})}markAllDirty(){this._dependencyEngineCache.markAllDirty()}clearCalculatedDirty(e){this._dependencyEngineCache.clearCalculatedDirty(e)}hasDynamicDeps(e){return this._dependencyEngineCache.hasDynamicDeps(e)}hasDynamicDepsByIndex(e){return this._dependencyEngineCache.hasDynamicDeps(this._dependencyEngineCache.getNodeRefByIndex(e))}refreshDynamicDeps(e,t){return this._dependencyEngineCache.refreshDynamicDeps(e,t)}refreshDynamicDepsByIndex(e,t){return this._dependencyEngineCache.refreshDynamicDeps(this._dependencyEngineCache.getNodeRefByIndex(e),t)}hasUncalculatedDirtyPrecedentByIndex(e,t){return this._dependencyEngineCache.hasUncalculatedDirtyPrecedentByIndex(e,t)}forEachPrecedentNodeByIndex(e,t){this._dependencyEngineCache.forEachPrecedentNodeByIndex(e,(e,n)=>{t(n)})}forEachDependentNodeByIndex(e,t){this._dependencyEngineCache.forEachDependentByIndex(e,(e,n)=>{t(n)})}prepareDynamicDependencies(e){return this._dependencyEngineCache.prepareDynamicDependencies(e)}getCalculationOrder(e){return this._dependencyEngineCache.getCalculationOrder(e)}};function Q(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let $=class extends t.UniverFormulaEnginePlugin{_initializeWithOverride(){var e;this._injector.add([t.LexerTreeBuilder,{useClass:t.LexerTreeBuilder}]),(e=this._config)!=null&&e.notExecuteFormula||[[t.ICalculateFormulaService,{useClass:T}],[t.IDependencyManagerService,{useClass:Z}],[t.IFormulaDependencyGenerator,{useClass:S}]].forEach(e=>this._injector.add(e))}};x($,`packageName`,C),x($,`version`,w),$=Q([(0,e.DependentOn)(n.UniverLicensePlugin)],$),exports.CalculateFormulaProService=T,exports.DependencyManagerProService=Z,exports.FormulaDependencyProGenerator=S,Object.defineProperty(exports,"UniverProFormulaEnginePlugin",{enumerable:!0,get:function(){return $}}),Object.keys(t).forEach(function(e){e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}})});
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@univerjs/core"),t=require("@univerjs/engine-formula"),n=require("@univerjs/rpc"),r=require("@univerjs-pro/license");function i(e){"@babel/helpers - typeof";return i=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},i(e)}function a(e,t){if(i(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(i(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function o(e){var t=a(e,`string`);return i(t)==`symbol`?t:t+``}function s(e,t,n){return(t=o(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const c=`SHEET_EXTERNAL_DATA_PLUGIN`;function l(){return{schemaVersion:1,links:[]}}function u(e,t){return`external:${encodeURIComponent(e)}:${t}`}var d=class extends e.Disposable{constructor(...e){super(...e),s(this,`_resources`,new Map),s(this,`_loadErrors`,new Map)}load(e,t){if(!t||typeof t!=`object`)return this._loadErrors.set(e,`invalid-resource`),!1;let n=t;return n.schemaVersion===1?!Array.isArray(n.links)||!n.links.every(f)?(this._loadErrors.set(e,`invalid-resource`),!1):(this._resources.set(e,n),this._loadErrors.delete(e),!0):(this._loadErrors.set(e,`unsupported-version`),!1)}set(e,t){return this.load(e,t)}serialize(e){var t;return(t=this._resources.get(e))==null?l():t}get(e){return this._resources.get(e)}getLoadError(e){return this._loadErrors.get(e)}resolveBinding(e,t){var n,r;let i=(n=(r=this._resources.get(e))==null?void 0:r.links)==null?[]:n,a=/^[1-9]\d*$/.test(t)?Number(t):void 0,o=t.toLowerCase(),s=i.filter(e=>a==null?e.name.toLowerCase()===o||e.target.name.toLowerCase()===o:e.slot===a);return s.length===0?{status:`missing`}:s.length>1?{status:`ambiguous`}:{status:`resolved`,link:s[0]}}renameLiveTarget(e,t,n){let r=[];for(let[i,a]of this._resources)for(let o of a.links)(o.target.liveUnitId===e||o.target.name.toLowerCase()===t.toLowerCase())&&(o.name.toLowerCase()===t.toLowerCase()&&(o.name=n),o.target.name=n,r.push({hostUnitId:i,slot:o.slot}));return r}remove(e){this._resources.delete(e),this._loadErrors.delete(e)}dispose(){super.dispose(),this._resources.clear(),this._loadErrors.clear()}};function f(e){if(!e||typeof e!=`object`)return!1;let t=e;return Number.isInteger(t.slot)&&Number(t.slot)>0&&typeof t.name==`string`&&!!t.target&&typeof t.target.name==`string`&&Array.isArray(t.sheetNames)&&Array.isArray(t.definedNames)&&Array.isArray(t.tables)}function p(e,t){return function(n,r){t(n,r,e)}}function m(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let h=class{constructor(e){this._externalReferenceModel=e,s(this,`id`,`ooxml-external-cache`),s(this,`priority`,-100)}canRead(e){var t;let n=this._externalReferenceModel.resolveBinding(e.hostUnitId,String(e.bindingSlot));return n.status===`resolved`&&((t=n.link.cache)==null?void 0:t.complete)===!0&&(e.requireFresh===!1||n.link.cache.freshness===`fresh`)}async readData(e){var t;let n=this._externalReferenceModel.resolveBinding(e.hostUnitId,String(e.bindingSlot));if(n.status!==`resolved`||((t=n.link.cache)==null?void 0:t.complete)!==!0||e.requireFresh!==!1&&n.link.cache.freshness!==`fresh`)return;let r=n.link.cache,i=[];for(let t of e.ranges){var a,o,s;let e=r.sheets.find(e=>t.sheetId&&e.sheetId===t.sheetId||t.sheetName&&e.name.toLowerCase()===t.sheetName.toLowerCase());if(!e||t.range&&!g(t.range,e.coverage))continue;let n=t.range?[t.range]:e.coverage;i.push({name:e.name,sheetId:(a=e.sheetId)==null?e.name:a,rowCount:(o=e.rowCount)==null?_(n,`endRow`)+1:o,columnCount:(s=e.columnCount)==null?_(n,`endColumn`)+1:s,coverage:n,cells:e.cells.map(e=>{var t;return{row:e.row,column:e.column,cell:{v:e.value,t:(t=e.valueType)==null?v(e.value):t}}})})}if(i.length!==0)return{requestId:e.requestId,calculationId:e.calculationId,source:`ooxml-cache`,freshness:r.freshness,revision:r.revision,sheets:i}}};h=m([p(0,(0,e.Inject)(d))],h);function g(e,t){for(let n=e.startRow;n<=e.endRow;n++)for(let r=e.startColumn;r<=e.endColumn;r++)if(!t.some(e=>n>=e.startRow&&n<=e.endRow&&r>=e.startColumn&&r<=e.endColumn))return!1;return!0}function _(e,t){return e.reduce((e,n)=>Math.max(e,n[t]),0)}function v(t){return typeof t==`number`?e.CellValueType.NUMBER:typeof t==`boolean`?e.CellValueType.BOOLEAN:e.CellValueType.STRING}const y=(0,e.createIdentifier)(`univer-pro.formula.reference-data-service`),b=(0,e.createIdentifier)(`univer-pro.formula.reference-data-provider-registry`);var x=class extends e.Disposable{constructor(...e){super(...e),s(this,`_providers`,new Map)}register(e){return this._providers.set(e.id,e),{dispose:()=>{this._providers.get(e.id)===e&&this._providers.delete(e.id)}}}getProviders(e){return Array.from(this._providers.values()).filter(t=>t.canRead(e)).sort((e,t)=>{var n,r;return((n=t.priority)==null?0:n)-((r=e.priority)==null?0:r)})}dispose(){super.dispose(),this._providers.clear()}};function S(e,t=`#N/A`){return{requestId:e.requestId,calculationId:e.calculationId,source:`unavailable`,freshness:`unavailable`,sheets:[],error:t}}let C=class extends e.Disposable{constructor(e,t){super(),this.disposeWithMe(e.register(t))}};C=m([p(0,b),p(1,(0,e.Inject)(h))],C);let w=class extends e.Disposable{constructor(e,t){super(),this._externalReferenceModel=e,this._superTableService=t,s(this,`_units`,new Map),s(this,`_pendingDirtyRanges`,[])}apply(e,t){var n;let r=(n=this._units.get(e.syntheticUnitId))==null?{hostUnitId:e.hostUnitId,bindingSlot:e.bindingSlot,targetName:e.target.name,targetLiveUnitId:e.target.liveUnitId,targetUnitType:e.target.unitType,source:t.source,freshness:t.freshness,revision:t.revision,sheets:new Map}:n;r.revision!=null&&t.revision!=null&&r.revision!==t.revision&&(this._queueDirty(this._unitRanges(e.syntheticUnitId,r)),r.sheets.clear()),r.targetName=e.target.name,r.targetLiveUnitId=e.target.liveUnitId,r.source=t.source,r.freshness=t.freshness,r.revision=t.revision,this._units.set(e.syntheticUnitId,r);let i=t.sheets.length>0?t.sheets:this._createUnavailableSheets(e),a=[];for(let n of i){let i=this._mergeSheet(r,n);this._writeCoverageMisses(e,t,i,n.coverage),a.push(...n.coverage.map(e=>({sheetId:n.sheetId,range:e})))}return this._registerTables(e.syntheticUnitId,e.hostUnitId,e.bindingSlot,r),this._queueDirty(a.map(({sheetId:t,range:n})=>({unitId:e.syntheticUnitId,sheetId:t,range:n}))),a}materialize(e){var t,n,r,i;let a=(t=e.allUnitData)==null?{}:t,o=(n=e.unitSheetNameMap)==null?{}:n,s=(r=e.unitNameMap)==null?{}:r;for(let[e,t]of this._units){var c,l;let n=(c=a[e])==null?{}:c,r=(l=o[e])==null?{}:l;for(let e of t.sheets.values())n[e.sheetId]={cellData:e.cellData,rowCount:e.rowCount,columnCount:e.columnCount,rowData:{},columnData:{}},r[e.name]=e.sheetId;a[e]=n,o[e]=r,s[e]={name:t.targetName,unitType:t.targetUnitType}}e.allUnitData=a,e.unitSheetNameMap=o,e.unitNameMap=s,e.unitStylesData=(i=e.unitStylesData)==null?{}:i}getCellState(e,n,r,i){var a,o,s;let c=(a=this._units.get(e))==null?void 0:a.sheets.get(n);return!c||!c.coverage.some(e=>T(e,r,i))?{covered:!1,value:t.ErrorType.NA}:{covered:!0,value:(o=(s=c.cellData.getValue(r,i))==null?void 0:s.v)==null?null:o}}isRangeCovered(e,t,n){var r;let i=this._units.get(e),a=Array.from((r=i==null?void 0:i.sheets.values())==null?[]:r).find(e=>!t||e.sheetId===t||e.name.toLowerCase()===t.toLowerCase());if(!a)return!1;for(let e=n.startRow;e<=n.endRow;e++)for(let t=n.startColumn;t<=n.endColumn;t++)if(!a.coverage.some(n=>T(n,e,t)))return!1;return!0}enforceLimits(e,t){let n=0;for(;this._coveredCellCount()>e||this._estimatedBytes()>t;){let e=this._oldestCoverage();if(!e)break;e.sheet.coverage.shift();for(let t=e.range.startRow;t<=e.range.endRow;t++)for(let n=e.range.startColumn;n<=e.range.endColumn;n++)e.sheet.coverage.some(e=>T(e,t,n))||e.sheet.cellData.realDeleteValue(t,n);e.sheet.coverage.length===0&&e.unit.sheets.delete(e.sheet.sheetId),e.unit.sheets.size===0&&this._units.delete(e.unitId),n++}return n}invalidateHost(e){let t=[];for(let[n,r]of this._units)r.hostUnitId===e&&(t.push(...this._unitRanges(n,r)),this._units.delete(n));return this._queueDirty(t),t}invalidateSyntheticUnit(e){let t=this._units.get(e),n=t?this._unitRanges(e,t):[];return this._units.delete(e),this._queueDirty(n),n}invalidateSourceRange(e,t,n){let r=[],i=e.toLowerCase(),a=t.toLowerCase();for(let[o,s]of this._units)if(!(s.targetLiveUnitId!==e&&s.targetName.toLowerCase()!==i))for(let e of s.sheets.values()){if(e.sheetId!==t&&e.name.toLowerCase()!==a)continue;let i=e.coverage.map(e=>E(e,n)).filter(e=>e!=null);if(i.length!==0){e.coverage=e.coverage.flatMap(e=>te(e,n));for(let t of i){for(let n=t.startRow;n<=t.endRow;n++)for(let r=t.startColumn;r<=t.endColumn;r++)e.cellData.realDeleteValue(n,r);r.push({unitId:o,sheetId:e.sheetId,range:t})}}}return this._queueDirty(r),r}invalidateSourceMetadata(e){let t=e.toLowerCase(),n=[];for(let[r,i]of this._units)i.targetLiveUnitId!==e&&i.targetName.toLowerCase()!==t||(n.push(...this._unitRanges(r,i)),this._units.delete(r));return this._queueDirty(n),n}drainDirtyRanges(){return this._pendingDirtyRanges.splice(0)}getUnitCount(){return this._units.size}dispose(){super.dispose(),this._units.clear(),this._pendingDirtyRanges.length=0}_unitRanges(e,t){return Array.from(t.sheets.values()).flatMap(t=>t.coverage.map(n=>({unitId:e,sheetId:t.sheetId,range:n})))}_queueDirty(e){for(let t of e)this._pendingDirtyRanges.some(e=>e.unitId===t.unitId&&e.sheetId===t.sheetId&&ee(e.range,t.range))||this._pendingDirtyRanges.push(t)}_mergeSheet(t,n){var r;let i=(r=t.sheets.get(n.sheetId))==null?{name:n.name,sheetId:n.sheetId,rowCount:n.rowCount,columnCount:n.columnCount,coverage:[],cellData:new e.ObjectMatrix}:r;i.name=n.name,i.rowCount=Math.max(i.rowCount,n.rowCount),i.columnCount=Math.max(i.columnCount,n.columnCount),i.coverage.push(...n.coverage);for(let{row:e,column:t,cell:r}of n.cells)i.cellData.setValue(e,t,r);return t.sheets.set(i.sheetId,i),i}_oldestCoverage(){for(let[e,t]of this._units)for(let n of t.sheets.values()){let r=n.coverage[0];if(r)return{unitId:e,unit:t,sheet:n,range:r}}}_coveredCellCount(){let e=0;for(let t of this._units.values())for(let n of t.sheets.values())for(let t of n.coverage)e+=(t.endRow-t.startRow+1)*(t.endColumn-t.startColumn+1);return e}_estimatedBytes(){let e=0;for(let t of this._units.values())for(let n of t.sheets.values())e+=JSON.stringify(n.cellData.getData()).length;return e}_writeCoverageMisses(n,r,i,a){for(let o of n.ranges)if(!(!o.range||o.sheetId&&o.sheetId!==i.sheetId)&&!(o.sheetName&&o.sheetName.toLowerCase()!==i.name.toLowerCase()))for(let n=o.range.startRow;n<=o.range.endRow;n++)for(let s=o.range.startColumn;s<=o.range.endColumn;s++)(r.error||!a.some(e=>T(e,n,s)))&&i.cellData.setValue(n,s,{v:t.ErrorType.NA,t:e.CellValueType.STRING})}_createUnavailableSheets(e){return e.ranges.filter(e=>!!e.range).map(t=>{var n,r,i,a;return{name:(n=(r=t.sheetName)==null?t.sheetId:r)==null?`External`:n,sheetId:(i=t.sheetId)==null?ne(e.bindingSlot,(a=t.sheetName)==null?`External`:a):i,rowCount:t.range.endRow+1,columnCount:t.range.endColumn+1,coverage:[t.range],cells:[]}})}_registerTables(e,t,n,r){let i=this._externalReferenceModel.resolveBinding(t,String(n));if(i.status===`resolved`)for(let t of i.link.tables){if(!t.range||!t.sheetName)continue;let n=Array.from(r.sheets.values()).find(e=>{var n;return e.name.toLowerCase()===((n=t.sheetName)==null?void 0:n.toLowerCase())});n&&this._superTableService.registerTable(e,t.name,{sheetId:n.sheetId,titleMap:new Map(t.columns.map((e,t)=>[e.name,t])),range:t.range,showHeader:t.showHeader})}}};w=m([p(0,(0,e.Inject)(d)),p(1,t.ISuperTableService)],w);function T(e,t,n){return t>=e.startRow&&t<=e.endRow&&n>=e.startColumn&&n<=e.endColumn}function ee(e,t){return e.startRow===t.startRow&&e.endRow===t.endRow&&e.startColumn===t.startColumn&&e.endColumn===t.endColumn}function E(e,t){let n={startRow:Math.max(e.startRow,t.startRow),endRow:Math.min(e.endRow,t.endRow),startColumn:Math.max(e.startColumn,t.startColumn),endColumn:Math.min(e.endColumn,t.endColumn)};return n.startRow<=n.endRow&&n.startColumn<=n.endColumn?n:void 0}function te(e,t){let n=E(e,t);return n?[{...e,endRow:n.startRow-1},{...e,startRow:n.endRow+1},{startRow:n.startRow,endRow:n.endRow,startColumn:e.startColumn,endColumn:n.startColumn-1},{startRow:n.startRow,endRow:n.endRow,startColumn:n.endColumn+1,endColumn:e.endColumn}].filter(e=>e.startRow<=e.endRow&&e.startColumn<=e.endColumn):[e]}function ne(e,t){return`external-sheet:${e}:${encodeURIComponent(t)}`}let D=class extends e.Disposable{constructor(t,n,r){super(),this._univerInstanceService=t,s(this,`_names`,new Map);for(let t of[e.UniverInstanceType.UNIVER_SHEET,e.UniverInstanceType.UNIVER_BASE])this._univerInstanceService.getAllUnitsForType(t).forEach(e=>{r.invalidateSourceMetadata(e.getUnitId()),this._watch(e,n,r)}),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(t).subscribe(({unit:e})=>{r.invalidateSourceMetadata(e.getUnitId()),this._watch(e,n,r)})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(t).subscribe(e=>{r.invalidateSourceMetadata(e.getUnitId());let t=this._names.get(e.getUnitId());t&&r.invalidateSourceMetadata(t),this._names.delete(e.getUnitId())}))}_watch(e,t,n){let r=e.getUnitId();this.disposeWithMe(e.name$.subscribe(e=>{let i=this._names.get(r);if(this._names.set(r,e),i==null){n.invalidateSourceMetadata(e);return}if(i!==e){n.invalidateSourceMetadata(r),n.invalidateSourceMetadata(i);for(let a of t.renameLiveTarget(r,i,e))n.invalidateSyntheticUnit(u(a.hostUnitId,a.slot))}}))}};D=m([p(0,e.IUniverInstanceService),p(1,(0,e.Inject)(d)),p(2,(0,e.Inject)(w))],D);let O=class extends e.Disposable{constructor(t,n,r){super(),this.disposeWithMe(t.registerPluginResource({pluginName:c,businesses:[e.UniverInstanceType.UNIVER_SHEET,e.UniverInstanceType.UNIVER_BASE],toJson:e=>JSON.stringify(n.serialize(e)),parseJson:e=>JSON.parse(e),onLoad:(e,t)=>(r.invalidateHost(e),n.load(e,t)),onUnLoad:e=>{r.invalidateHost(e),n.remove(e)}}))}};O=m([p(0,e.IResourceManagerService),p(1,(0,e.Inject)(d)),p(2,(0,e.Inject)(w))],O);const re=`univer-pro.formula.reference-data`;let k=class extends e.Disposable{constructor(e,t){super(),e.registerChannel(re,(0,n.fromModule)(t))}};k=m([p(0,n.IRPCChannelService),p(1,y)],k);var ie=`@univerjs-pro/engine-formula`,ae=`1.0.0-alpha.4`;function oe(){return{totalFormulaNodes:0,totalSharedFormulaGroups:0,compressedSharedFormulaGroups:0,compressibleSharedFormulaGroups:0,expandedSharedFormulaGroups:0,totalVirtualFormulaNodesInCompressedGroups:0,totalVirtualFormulaNodesInCompressibleGroups:0,skippedExpandedDependencyRegistrationCount:0,sharedPatternCount:0,sharedSourceCoverageEntryCount:0,fallbackReasonCounts:{}}}function A(e,t={}){var n;let r=(n=t.minSharedGroupSize)==null?32:n,i=oe(),a=se(e,i),o=[];return a.forEach(e=>{let t=ce(e,r);if(o.push(t),i.totalSharedFormulaGroups++,t.mode===`candidate`){i.compressibleSharedFormulaGroups++,i.totalVirtualFormulaNodesInCompressibleGroups+=t.virtualFormulaCount;return}if(i.expandedSharedFormulaGroups++,t.fallbackReason){var n;i.fallbackReasonCounts[t.fallbackReason]=((n=i.fallbackReasonCounts[t.fallbackReason])==null?0:n)+1}}),{groups:o,metrics:i}}function se(e,t){let n=new Map,r=Object.keys(e);for(let i=0;i<r.length;i++){let a=r[i],o=e[a];if(o==null)continue;let s=Object.keys(o);for(let e=0;e<s.length;e++){let r=s[e],i=o[r];if(i==null)continue;let c=Object.keys(i);for(let e=0;e<c.length;e++){let o=+c[e],s=i[o];if(s==null)continue;let l=Object.keys(s);for(let e=0;e<l.length;e++){let i=+l[e],c=s[i];if(c==null||(t.totalFormulaNodes++,c.si==null))continue;let u=String(c.si),d=de(a,r,u),f=n.get(d);f==null&&(f={groupId:d,unitId:a,sheetId:r,si:u,members:[]},n.set(d,f)),f.members.push({row:o,col:i,item:c})}}}}return n}function ce(e,t){var n,r;let i=le(e.members),a=i.maxCol-i.minCol+1,o=i.maxRow-i.minRow+1,s={unitId:e.unitId,sheetId:e.sheetId,range:{startRow:i.minRow,endRow:i.maxRow,startColumn:i.minCol,endColumn:i.maxCol}},c=i.anchorCount===1&&i.anchor!=null?{unitId:e.unitId,sheetId:e.sheetId,row:i.anchor.row,col:i.anchor.col}:void 0,l=ue(e,s,i.anchorCount,t,(n=(r=i.anchor)==null?void 0:r.item.f)==null?``:n);return{groupId:e.groupId,unitId:e.unitId,sheetId:e.sheetId,si:e.si,anchor:c,fillRange:s,width:a,height:o,size:e.members.length,virtualFormulaCount:Math.max(0,e.members.length-1),mode:l==null?`candidate`:`expanded`,fallbackReason:l}}function le(e){let t=1/0,n=-1/0,r=1/0,i=-1/0,a=0,o;for(let s=0;s<e.length;s++){let c=e[s];t=Math.min(t,c.row),n=Math.max(n,c.row),r=Math.min(r,c.col),i=Math.max(i,c.col),fe(c.item)&&(a++,o=c)}return{minRow:t,maxRow:n,minCol:r,maxCol:i,anchorCount:a,anchor:o}}function ue(e,t,n,r,i){if(n===0)return`missing-anchor-formula`;if(n>1)return`ambiguous-anchor-formula`;if(!pe(e.members,t))return`non-rectangular-fill-range`;if(e.members.length<r)return`small-group`;if(ge(i))return`external-reference`;if(me(i))return`unsupported-dynamic-reference`;if(he(i))return`volatile-function`;if(_e(i))return`array-formula`;if(ve(i))return`spill-formula`}function de(e,t,n){return[e,t,n].join(`\0`)}function fe(e){var t,n;return((t=e.x)==null?0:t)===0&&((n=e.y)==null?0:n)===0}function pe(e,t){return(t.range.endColumn-t.range.startColumn+1)*(t.range.endRow-t.range.startRow+1)===e.length}function me(e){return ye(e,[`INDIRECT`,`OFFSET`])}function he(e){return ye(e,[`RAND`,`RANDBETWEEN`,`NOW`,`TODAY`])}function ge(e){return/\[[^\]]+\]/.test(e)}function _e(e){return/^\s*\{=.*\}\s*$/.test(e)}function ve(e){return/#/.test(e)}function ye(e,t){for(let n=0;n<t.length;n++)if(RegExp(`(^|[^A-Z0-9_.])${t[n]}\\s*\\(`,`i`).test(e))return!0;return!1}const be=/\b(?:INDIRECT|ADDRESS|CELL|INFO|FORMULATEXT|RAND|RANDBETWEEN|NOW|TODAY)\s*\(/i,j=/(?:(?:'((?:[^']|'')+)'|([A-Za-z_][A-Za-z0-9_. ]*))!)?\$?([A-Z]{1,3})\$?([1-9]\d{0,6})(?::\$?([A-Z]{1,3})\$?([1-9]\d{0,6}))?/gi,xe=/(?:(?:'((?:[^']|'')+)'|([A-Za-z_][A-Za-z0-9_. ]*))!)?\$?([A-Z]{1,3}):\$?([A-Z]{1,3})(?![A-Za-z0-9_.])/gi,Se=/[A-Za-z_][A-Za-z0-9_.]*/g,Ce=/^(?:TRUE|FALSE)$/i,we=new WeakMap;function Te(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>127)return!0;return!1}function Ee(t){let n=we.get(t);if(n!==void 0)return n;let r=Object.keys(t).filter(e=>e.length>0);return n=r.length>0?e.regexp.createRegExpFromSafeFragment(`(^|[^A-Za-z0-9_])${e.regexp.or(...r)}(\\s*\\[|$|[^A-Za-z0-9_])`,`i`):null,we.set(t,n),n}function M(e){var t;let n=globalThis;n.__UNIVER_PRO_STATIC_DEP_PROFILE_ENABLED__===!0&&(n.__UNIVER_PRO_STATIC_DEP_PROFILE__!=null||(n.__UNIVER_PRO_STATIC_DEP_PROFILE__={}),n.__UNIVER_PRO_STATIC_DEP_PROFILE__[e]=((t=n.__UNIVER_PRO_STATIC_DEP_PROFILE__[e])==null?0:t)+1)}function N(e,t){var n;let r=globalThis;r.__UNIVER_PRO_STATIC_DEP_PROFILE_ENABLED__===!0&&(r.__UNIVER_PRO_STATIC_DEP_SAMPLES__!=null||(r.__UNIVER_PRO_STATIC_DEP_SAMPLES__={}),(n=r.__UNIVER_PRO_STATIC_DEP_SAMPLES__)[e]!=null||(n[e]=[]),r.__UNIVER_PRO_STATIC_DEP_SAMPLES__[e].length<20&&r.__UNIVER_PRO_STATIC_DEP_SAMPLES__[e].push(t))}function P(){var e,t,n;return(e=(t=globalThis.performance)==null||(n=t.now)==null?void 0:n.call(t))==null?Date.now():e}function F(e,t){var n,r;let i=globalThis;if(i.__UNIVER_PRO_PROFILE_ENABLED__!==!0)return;i.__UNIVER_PRO_ENGINE_PROFILE__!=null||(i.__UNIVER_PRO_ENGINE_PROFILE__={}),(n=i.__UNIVER_PRO_ENGINE_PROFILE__).timings!=null||(n.timings={});let a=(r=i.__UNIVER_PRO_ENGINE_PROFILE__.timings[e])==null?{count:0,totalMs:0,maxMs:0}:r;a.count++,a.totalMs+=t,a.maxMs=Math.max(a.maxMs,t),i.__UNIVER_PRO_ENGINE_PROFILE__.timings[e]=a}function I(e,t=1){var n,r;let i=globalThis;i.__UNIVER_PRO_PROFILE_ENABLED__===!0&&(i.__UNIVER_PRO_ENGINE_PROFILE__!=null||(i.__UNIVER_PRO_ENGINE_PROFILE__={}),(n=i.__UNIVER_PRO_ENGINE_PROFILE__).counters!=null||(n.counters={}),i.__UNIVER_PRO_ENGINE_PROFILE__.counters[e]=((r=i.__UNIVER_PRO_ENGINE_PROFILE__.counters[e])==null?0:r)+t)}async function De(e,t){let n=P();try{return await t()}finally{F(e,P()-n)}}function L(e,t){let n=P();try{return t()}finally{F(e,P()-n)}}var Oe=class extends t.FormulaDependencyGenerator{constructor(...e){super(...e),s(this,`_featureFormulaDirtyDependencies`,[]),s(this,`_calculationTreeCache`,new Map),s(this,`_calculationNodeDataCache`,new Map),s(this,`_forcedRecalculationNodeIndices`,new Set),s(this,`_sharedFormulaCompressionMetrics`,oe()),s(this,`_cacheDependencyTreeModelRangeList`,!1)}dispose(){super.dispose(),this._dependencyTreeCache.clear(),this._calculationTreeCache.clear(),this._calculationNodeDataCache=new Map,this._featureFormulaDirtyDependencies.length=0,this._forcedRecalculationNodeIndices.clear(),this._sharedFormulaCompressionMetrics=oe()}clearCalculatedDirty(e){this._dependencyManagerService.clearCalculatedDirty(e)}clearCachedCalculationNodeData(){this._calculationNodeDataCache=new Map}clearCachedCalculationTree(){this._calculationTreeCache.clear()}getCachedCalculationNodeData(e){return this._calculationNodeDataCache.get(e)}getCalculationOrder(){return this._dependencyManagerService.getCalculationOrder({detectCycles:!0})}getSharedFormulaCompressionMetrics(){return this._sharedFormulaCompressionMetrics}hasDynamicDepsByIndex(e){return this._dependencyManagerService.hasDynamicDepsByIndex(e)}refreshDynamicDepsByIndex(e,t){return this._dependencyManagerService.refreshDynamicDepsByIndex(e,t)}hasUncalculatedDirtyPrecedentByIndex(e,t){return this._dependencyManagerService.hasUncalculatedDirtyPrecedentByIndex(e,t)}async getAllDependencyJson(){this._featureFormulaDirtyDependencies.length=0,this._updateRangeFlatten();let e=this._currentConfigService.getFormulaData(),t=A(e);this._sharedFormulaCompressionMetrics=t.metrics;let n=this._otherFormulaManagerService.getOtherFormulaData(),r=this._currentConfigService.getUnitData();this._cacheDependencyTreeModelRangeList=!0;try{return await this._generateTreeListPro(e,n,r,t),this._getAllDependencyJsonPro(this._calculationTreeCache)}finally{this._cacheDependencyTreeModelRangeList=!1,this._featureFormulaDirtyDependencies.length=0}}async generatePro(e=!1){this._featureFormulaDirtyDependencies.length=0,L(`dependency.updateRangeFlatten`,()=>this._updateRangeFlatten());let t=this._currentConfigService.getFormulaData(),n=L(`dependency.analyzeSharedFormulaGroups`,()=>A(t));this._sharedFormulaCompressionMetrics=n.metrics,I(`dependency.formulaNodes`,n.metrics.totalFormulaNodes),I(`dependency.sharedFormulaGroups`,n.groups.length);let r=this._otherFormulaManagerService.getOtherFormulaData(),i=this._currentConfigService.getClearDependencyTreeCache(),a=this._dependencyManagerService;i!=null&&Object.keys(i).forEach(e=>{e!=null&&Object.keys(i[e]).forEach(t=>{t!=null&&(a.clearOtherFormulaDependency(e,t),a.clearFeatureFormulaDependency(e,t),a.clearFormulaDependency(e,t),this._clearCalculationTreeCache(e,t))})});let o=this._currentConfigService.getUnitData();this._cacheDependencyTreeModelRangeList=e;try{await De(`dependency.generateTreeList`,()=>this._generateTreeListPro(t,r,o,n))}finally{this._cacheDependencyTreeModelRangeList=!1}await De(`dependency.markDirtyDependencies`,()=>this._markDirtyDependenciesPro()),this._featureFormulaDirtyDependencies.length=0,L(`dependency.clearArrayObjectCache`,()=>this._runtimeService.clearArrayObjectCache());let s=L(`dependency.getCalculationOrder`,()=>a.getCalculationOrder({detectCycles:!0})),c=this._calculationTreeCache;return e&&this._runtimeService.setDependencyTreeModelData(this._getAllDependencyJsonPro(c)),{calculationOrderResult:s,dependencyTree:c}}async _generateTreeListPro(e,t,n,r){let i=Object.keys(e),a=Object.keys(t);this._registerFeatureFormulasPro(),this._dependencyManagerService.reserveFormulaDependencyCapacity(Math.max(16,r.metrics.totalFormulaNodes),Math.max(16,Math.ceil(r.metrics.totalFormulaNodes/2))),await this._registerFormulasPro(i,e,n,r),await this._registerOtherFormulasPro(t,a)}_registerFeatureFormulasPro(){this._featureCalculationManagerService.getReferenceExecutorMap().forEach((e,t)=>{e.forEach((e,t)=>{e.forEach((e,t)=>{let n=this._dependencyManagerService.getFeatureFormulaDependency(e.unitId,e.subUnitId,t);this._getFeatureFormulaTreePro(t,n,e)})})})}_getFeatureFormulaTreePro(e,n,r){let{unitId:i,subUnitId:a,dependencyRanges:o,getDirtyData:s}=r,c=new t.FormulaDependencyTree(n||(0,t.generateRandomDependencyTreeId)(this._dependencyManagerService));c.unitId=i,c.subUnitId=a,c.rangeList=o,c.getDirtyData=s;let l=s(this._currentConfigService.getDirtyData(),this._runtimeService.getAllRuntimeData()),u=this._convertDirtyRangesToUnitRange(l.dirtyRanges);c.featureDirtyRanges=u,c.featureId=e,c.type=t.FormulaDependencyTreeType.FEATURE_FORMULA;let d=this._dependencyManagerService.getFeatureFormulaDependencyPro(r.unitId,r.subUnitId,e),f;return d===void 0&&(d=this._dependencyManagerService.addFeatureFormulaDependencyPro(i,a,e,c),f=d),u.length>0&&this._featureFormulaDirtyDependencies.push({node:this._dependencyManagerService.getFeatureFormulaDependencyNodePro(i,a,e),dirtyRanges:u}),this._cacheCalculationTree(d,c),this._releaseDependencyTree(c),f}async _registerOtherFormulasPro(e,n){for(let r of n){let n=e[r];if(n==null)continue;let i=Object.keys(n);for(let e of i){let i=n[e];if(i==null)continue;let{rowCount:a=1/0,columnCount:o=1/0}=this._currentConfigService.getSheetRowColumnCount(r,e)||{},s=Object.keys(i);for(let n of s){let s=this._dependencyManagerService.hasOtherFormulaDataMainData(n),{f:c,ranges:l}=i[n],u=!1;s&&(u=!0);let{firstRow:d,firstColumn:f}=this._getFirstCellOfRange(l),p=new t.FormulaDependencyTree((0,t.generateRandomDependencyTreeId)(this._dependencyManagerService));for(let i=0;i<l.length;i++){let s=l[i],{startRow:m,startColumn:h}=s,{endRow:g,endColumn:_}=s;g=Math.min(g,a-1),_=Math.min(_,o-1);for(let i=m;i<=g;i++)for(let a=h;a<=_;a++){let o=a-f,s=i-d,l=this._dependencyManagerService.getOtherFormulaDependencyPro(r,e,n,o,s);if(o===0&&s===0){p.formula=c,p.unitId=r,p.subUnitId=e,p.formulaId=n,p.type=t.FormulaDependencyTreeType.OTHER_FORMULA,p.isCache=u,p.node||await this._initialAstNodeAndRanges(p);let i=this._getFeatureFormulaDependencyNodes(p.rangeList);l===void 0?l=this._dependencyManagerService.addOtherFormulaDependencyPro(r,e,n,p,i):i.length>0&&(l=this._dependencyManagerService.addOtherFormulaDependencyPro(r,e,n,p,i,`merge`)),this._cacheCalculationTree(l,p),this._syncForcedRecalculationNodeIndex(l,p);continue}let m=new t.FormulaDependencyTreeVirtual;m.treeId=(0,t.generateRandomDependencyTreeId)(this._dependencyManagerService),m.refTree=p,m.refOffsetX=o,m.refOffsetY=s,m.isCache=u,m.type=t.FormulaDependencyTreeType.OTHER_FORMULA;let h=this._getFeatureFormulaDependencyNodes(m.rangeList);l===void 0?l=this._dependencyManagerService.addOtherFormulaDependencyPro(r,e,n,m,h):h.length>0&&(l=this._dependencyManagerService.addOtherFormulaDependencyPro(r,e,n,m,h,`merge`)),this._cacheCalculationTree(l,m),this._syncForcedRecalculationNodeIndex(l,m),this._releaseDependencyTree(m)}}this._releaseDependencyTree(p)}}}}async _registerFormulasPro(e,n,r,i=A(n)){let a=this._createSharedFormulaGroupMap(i.groups),o=this._dependencyManagerService,s=this._shouldEagerCacheCalculationTrees();I(s?`dependency.eagerCalculationTreeCache.enabled`:`dependency.eagerCalculationTreeCache.skipped`);for(let i of e){let e=n[i];if(e==null)continue;let c=Object.keys(e);for(let n of c){let c=new Map,l=new Map,u=new Set,d=new Map,f=[],p=e[n];if(p==null)continue;let m=Object.keys(p),h=P();for(let e of m){let t=+e,m=p[t];if(m==null)continue;let h=Object.keys(m);for(let e of h){let p=+e,h=m[p];if(h==null)continue;let{x:g=0,y:_=0,si:v}=h;if(!(g===0&&_===0&&v!=null))continue;let y=String(v),b=this._createFDtree(i,n,t,p,r,h),x=this._createSharedFormulaGroupId(i,n,y),S=a.get(x),C=(S==null?void 0:S.mode)===`candidate`?await this._analyzeSharedFormulaCompression(b,S):void 0,w;if((C==null?void 0:C.mode)===`compressed`){w=o.addFormulaDependencyNodeOnlyPro(i,n,t,p),l.set(y,C),u.add(y),f.push(C);let e=[w];e.push(...o.addFormulaDependencyNodeOnlyRangePro(i,n,C.group.fillRange.range,{row:t,col:p})),d.set(C.group.groupId,e)}else if((C==null?void 0:C.mode)===`expanded`&&(l.set(y,C),this._recordExpandedSharedFormulaGroupMetrics(C)),w=o.getFormulaDependencyPro(i,n,t,p),w===void 0){await this._initialDependencyRanges(b);let e=this._getFeatureFormulaDependencyNodes(b.rangeList);w=o.addFormulaDependencyPro(i,n,t,p,b,e)}else{await this._ensureTreeInitializedForDependencies(b);let e=this._getFeatureFormulaDependencyNodes(b.rangeList);this._includeDirtySuperTablePro(i,b.formula)?w=o.addFormulaDependencyPro(i,n,t,p,b,e,`replace`):e.length>0&&(w=o.addFormulaDependencyPro(i,n,t,p,b,e,`merge`))}c.set(y,b);let T=this._syncForcedRecalculationNodeIndex(w,b);(s||T)&&(I(`dependency.calculationTreeCache.normal`),this._cacheCalculationTree(w,b))}}F(`dependency.registerFormulas.sharedAnchorPass`,P()-h);let g=P();for(let e of m){let a=+e,d=p[a];if(d==null)continue;let f=Object.keys(d);for(let e of f){let f=+e,p=d[f];if(p==null)continue;let{x:m=0,y:h=0,si:g}=p;if(m===0&&h===0&&g!=null)continue;let _=g==null?void 0:String(g);if(!s&&_!=null&&u.has(_))continue;let v=_==null?void 0:l.get(_);if((v==null?void 0:v.mode)===`compressed`&&_!=null&&c.has(_)){if(s){let e=o.getFormulaDependencyPro(i,n,a,f),t=c.get(_),{x:r=0,y:s=0}=p;e!==void 0&&(I(`dependency.calculationTreeCache.compressedVirtual`),this._cacheCompressedVirtualCalculationTree(e,t,r,s))}continue}let y=o.getFormulaDependencyPro(i,n,a,f),b;if(_!=null&&c.has(_)){let e=c.get(_);b=this._createVirtualFDtree(e,p)}else b=this._createFDtree(i,n,a,f,r,p);if(y===void 0){b.isVirtual||await this._initialDependencyRanges(b);let e=this._getFeatureFormulaDependencyNodes(b.rangeList);y=o.addFormulaDependencyPro(i,n,a,f,b,e)}else{let e=this._includeDirtySuperTablePro(i,b.formula);(this._cacheDependencyTreeModelRangeList||this._featureFormulaDirtyDependencies.length>0||e||o.hasDynamicDepsByIndex(y))&&await this._ensureTreeInitializedForDependencies(b);let t=this._getFeatureFormulaDependencyNodes(b.rangeList);e?y=o.addFormulaDependencyPro(i,n,a,f,b,t,`replace`):t.length>0&&(y=o.addFormulaDependencyPro(i,n,a,f,b,t,`merge`))}let x=this._syncForcedRecalculationNodeIndex(y,b);(s||x)&&(I(`dependency.calculationTreeCache.normal`),this._cacheCalculationTree(y,b)),b instanceof t.FormulaDependencyTreeVirtual?this._releaseDependencyTree(b):_!=null&&c.has(_)||this._releaseDependencyTree(b)}}F(`dependency.registerFormulas.virtualPass`,P()-g);let _=P();for(let e=0;e<f.length;e++){let t=f[e];t.patterns&&t.group.fillRange&&(o.registerCompressedSharedFormulaGroup({groupId:t.group.groupId,fillRange:t.group.fillRange,patterns:t.patterns,memberNodeIndices:d.get(t.group.groupId)}),this._recordCompressedSharedFormulaGroupMetrics(t))}F(`dependency.registerFormulas.compressedGroups`,P()-_),c.forEach(e=>this._releaseDependencyTree(e)),c.clear()}}}_createSharedFormulaGroupMap(e){let t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].groupId,e[n]);return t}_createSharedFormulaGroupId(e,t,n){return[e,t,String(n)].join(`\0`)}async _analyzeSharedFormulaCompression(e,t){if(t.fillRange==null)return{group:t,mode:`expanded`,fallbackReason:`non-rectangular-fill-range`};await this._initialDependencyRanges(e);let n=this._getFeatureFormulaDependencyNodes(e.rangeList),r=this._getSharedFormulaUnsupportedReason(e,n.length);if(r)return{group:t,mode:`expanded`,fallbackReason:r};let i=this._convertSharedFormulaPatterns(e);return i==null||i.length===0?{group:t,mode:`expanded`,fallbackReason:`unsupported-range-pattern`}:this._hasSharedFormulaSelfOverlap(t.fillRange,i)?{group:t,mode:`expanded`,fallbackReason:`self-overlap`}:{group:t,mode:`compressed`,patterns:i}}_getSharedFormulaUnsupportedReason(e,t){if(e.addressFunctionNodes&&e.addressFunctionNodes.length>0)return`unsupported-dynamic-reference`;if(t>0||/\$/.test(e.formula))return`unsupported-range-pattern`}_convertSharedFormulaPatterns(e){let t=[],n=new Set,r=e.row,i=e.column;for(let a=0;a<e.rangeList.length;a++){let o=e.rangeList[a],s=this._normalizeSharedFormulaRange(o.range),c;c=s.startRow===s.endRow&&s.startColumn===s.endColumn?{kind:`cell`,unitId:o.unitId,sheetId:o.sheetId,rowDelta:s.startRow-r,colDelta:s.startColumn-i}:{kind:`range`,unitId:o.unitId,sheetId:o.sheetId,startRowDelta:s.startRow-r,startColDelta:s.startColumn-i,endRowDelta:s.endRow-r,endColDelta:s.endColumn-i};let l=JSON.stringify(c);n.has(l)||(n.add(l),t.push(c))}return t}_hasSharedFormulaSelfOverlap(t,n){for(let r=0;r<n.length;r++){let i=this._computeSharedFormulaSourceCoverage(t,n[r]);if(!(i.unitId!==t.unitId||i.sheetId!==t.sheetId)&&e.Rectangle.intersects(i.range,t.range))return!0}return!1}_computeSharedFormulaSourceCoverage(e,t){if(t.kind===`cell`)return{unitId:t.unitId,sheetId:t.sheetId,range:this._normalizeSharedFormulaRange({startRow:e.range.startRow+t.rowDelta,endRow:e.range.endRow+t.rowDelta,startColumn:e.range.startColumn+t.colDelta,endColumn:e.range.endColumn+t.colDelta})};let n=Math.min(t.startRowDelta,t.endRowDelta),r=Math.max(t.startRowDelta,t.endRowDelta),i=Math.min(t.startColDelta,t.endColDelta),a=Math.max(t.startColDelta,t.endColDelta);return{unitId:t.unitId,sheetId:t.sheetId,range:this._normalizeSharedFormulaRange({startRow:e.range.startRow+n,endRow:e.range.endRow+r,startColumn:e.range.startColumn+i,endColumn:e.range.endColumn+a})}}_normalizeSharedFormulaRange(e){return{startRow:Math.min(e.startRow,e.endRow),endRow:Math.max(e.startRow,e.endRow),startColumn:Math.min(e.startColumn,e.endColumn),endColumn:Math.max(e.startColumn,e.endColumn)}}_recordCompressedSharedFormulaGroupMetrics(e){e.mode!==`compressed`||e.patterns==null||(this._sharedFormulaCompressionMetrics.compressedSharedFormulaGroups++,this._sharedFormulaCompressionMetrics.totalVirtualFormulaNodesInCompressedGroups+=e.group.virtualFormulaCount,this._sharedFormulaCompressionMetrics.skippedExpandedDependencyRegistrationCount+=e.group.size*e.patterns.length,this._sharedFormulaCompressionMetrics.sharedPatternCount+=e.patterns.length,this._sharedFormulaCompressionMetrics.sharedSourceCoverageEntryCount+=e.patterns.length)}_recordExpandedSharedFormulaGroupMetrics(e){var t;e.mode!==`expanded`||e.fallbackReason==null||(this._sharedFormulaCompressionMetrics.expandedSharedFormulaGroups++,this._sharedFormulaCompressionMetrics.fallbackReasonCounts[e.fallbackReason]=((t=this._sharedFormulaCompressionMetrics.fallbackReasonCounts[e.fallbackReason])==null?0:t)+1)}_shouldEagerCacheCalculationTrees(){var e,t;return this._cacheDependencyTreeModelRangeList||this._currentConfigService.isForceCalculate()||this._currentConfigService.getDirtyRanges().length>0?!0:this._hasAnyDirtyMapValue(this._currentConfigService.getDirtyNameMap())||this._hasAnyDirtyMapValue(this._currentConfigService.getDirtyDefinedNameMap())||this._hasAnyDirtyMapValue((e=(t=this._currentConfigService).getDirtySuperTableMap)==null?void 0:e.call(t))||this._hasAnyDirtyMapValue(this._currentConfigService.getDirtyUnitFeatureMap())||this._hasAnyDirtyMapValue(this._currentConfigService.getDirtyUnitOtherFormulaMap())}_hasAnyDirtyMapValue(e){if(e==null)return!1;if(Array.isArray(e))return e.length>0;if(typeof e!=`object`)return!0;let t=Object.values(e);for(let e=0;e<t.length;e++)if(this._hasAnyDirtyMapValue(t[e]))return!0;return!1}async _markDirtyDependenciesPro(){let e=this._dependencyManagerService;if(this._currentConfigService.isForceCalculate()){e.markAllDirty();return}let t=this._currentConfigService.getDirtyRanges();t.length>0&&e.markRangesChanged(t,{includeFormulaCells:!0}),e.markDirtyFeatureCalculations(this._currentConfigService.getDirtyUnitFeatureMap()),e.markDirtyOtherFormulas(this._currentConfigService.getDirtyUnitOtherFormulaMap()),e.markDirtySheetNames(this._currentConfigService.getDirtyNameMap()),this._markForcedRecalculationNodesPro(e),await this._markDirtyDefinedNameDependenciesPro(e),this._markDirtySuperTableDependenciesPro(e)}_markForcedRecalculationNodesPro(e){if(this._forcedRecalculationNodeIndices.size===0)return;let t=[];this._forcedRecalculationNodeIndices.forEach(e=>{t.push(e)}),e.markIndicesChanged(t)}async _markDirtyDefinedNameDependenciesPro(e){let t=this._currentConfigService.getDirtyDefinedNameMap();if(!this._hasDirtyDefinedNames(t))return;let n=[];for(let[e,t]of this._calculationTreeCache)t.formula&&t.formula.length>0&&this._includeDirtyDefinedNamePro(t.formula)&&n.push(e);n.length>0&&e.markIndicesChanged(n)}_markDirtySuperTableDependenciesPro(e){var t,n;let r=(t=(n=this._currentConfigService).getDirtySuperTableMap)==null?void 0:t.call(n);if(!this._hasAnyDirtyMapValue(r))return;let i=[];for(let[e,t]of this._calculationTreeCache)this._includeDirtySuperTablePro(t.unitId,t.formula)&&i.push(e);i.length>0&&e.markIndicesChanged(i)}_cacheCalculationTree(e,t){let n={unitId:t.unitId,subUnitId:t.subUnitId,formula:t.formula,row:t.row,column:t.column,rowCount:t.rowCount,columnCount:t.columnCount,refOffsetX:t.refOffsetX,refOffsetY:t.refOffsetY,formulaId:t.formulaId,featureId:t.featureId,getDirtyData:t.getDirtyData,hasDynamicDeps:t.addressFunctionNodes.length>0,type:t.type};(t.addressFunctionNodes.length>0||this._cacheDependencyTreeModelRangeList)&&(n.rangeList=t.rangeList);let r=t.nodeData;(r==null?void 0:r.node)!=null&&this._calculationNodeDataCache.set(e,{node:r.node,refOffsetX:r.refOffsetX,refOffsetY:r.refOffsetY}),this._calculationTreeCache.set(e,n)}_cacheCompressedVirtualCalculationTree(e,t,n,r){this._calculationTreeCache.set(e,{unitId:t.unitId,subUnitId:t.subUnitId,formula:t.formula,row:t.row+r,column:t.column+n,rowCount:t.rowCount,columnCount:t.columnCount,refOffsetX:n,refOffsetY:r,formulaId:t.formulaId,featureId:t.featureId,getDirtyData:null,hasDynamicDeps:!1,type:t.type}),this._cacheDependencyTreeModelRangeList&&(this._calculationTreeCache.get(e).rangeList=this._getOffsetRangeList(t.rangeList,n,r)),t.node!=null&&this._calculationNodeDataCache.set(e,{node:t.node,refOffsetX:n,refOffsetY:r})}_getOffsetRangeList(e,t,n){return t===0&&n===0?e:e.map(e=>({unitId:e.unitId,sheetId:e.sheetId,range:{startRow:e.range.startRow+n,endRow:e.range.endRow+n,startColumn:e.range.startColumn+t,endColumn:e.range.endColumn+t}}))}_getAllDependencyJsonPro(e){let t=this._dependencyManagerService,n=[];for(let[a,o]of e){var r,i;let s=[],c=[];t.forEachPrecedentNodeByIndex(a,t=>{e.has(t)&&s.push(t)}),t.forEachDependentNodeByIndex(a,t=>{e.has(t)&&c.push(t)}),n.push({children:s,parents:c,treeId:a,formula:o.formula,row:o.row,column:o.column,unitId:o.unitId,subUnitId:o.subUnitId,refOffsetX:o.refOffsetX,refOffsetY:o.refOffsetY,rangeList:(r=o.rangeList)==null?[]:r,refTreeId:void 0,formulaId:o.formulaId,featureId:o.featureId,type:(i=o.type)==null?this._inferDependencyTreeTypePro(o):i})}return n}_inferDependencyTreeTypePro(e){return e.featureId==null?e.formulaId==null?t.FormulaDependencyTreeType.NORMAL_FORMULA:t.FormulaDependencyTreeType.OTHER_FORMULA:t.FormulaDependencyTreeType.FEATURE_FORMULA}_clearCalculationTreeCache(e,t){for(let[n,r]of this._calculationTreeCache)r.unitId===e&&r.subUnitId===t&&(this._calculationTreeCache.delete(n),this._calculationNodeDataCache.delete(n),this._forcedRecalculationNodeIndices.delete(n))}_releaseDependencyTree(e){if(e instanceof t.FormulaDependencyTreeVirtual){e.dispose();return}let n=e;n.dispose(),n.node=null}_hasDirtyDefinedNames(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=e[t[n]];if(r!=null&&Object.keys(r).length>0)return!0}return!1}_syncForcedRecalculationNodeIndex(e,t){return t.formula&&(this._hasForcedRecalculationFunction(t.formula)||t.node&&this._detectForcedRecalculationNodePro(t.node))?(this._forcedRecalculationNodeIndices.add(e),!0):(this._forcedRecalculationNodeIndices.delete(e),!1)}_hasForcedRecalculationFunction(e){return/\b(?:RAND|RANDBETWEEN|NOW|TODAY)\s*\(/i.test(e)}_detectForcedRecalculationNodePro(e){if(e.isForcedCalculateFunction())return!0;let t=e.getChildren();for(let e=0;e<t.length;e++)if(this._detectForcedRecalculationNodePro(t[e]))return!0;return!1}_includeDirtyDefinedNamePro(e){let t=this._runtimeService.currentUnitId;if(t==null)return!1;let n=this._currentConfigService.getDirtyDefinedNameMap()[t];if(n==null)return!1;let r=Object.keys(n);for(let t=0;t<r.length;t++)if(e.indexOf(r[t])>-1)return!0;return!1}_includeDirtySuperTablePro(e,t){var n,r,i,a;if(!t)return!1;let o=(n=(r=this._currentConfigService).getDirtySuperTableMap)==null||(n=n.call(r))==null?void 0:n[e];return o==null||(i=(a=Ee(o))==null?void 0:a.test(t))==null?!1:i}async _ensureTreeInitializedForDependencies(e){if(e.isVirtual)return;let t=e;t.node||t.formula&&await this._initialAstNodeAndRanges(t)}_getFeatureFormulaDependencyNodes(e){if(this._featureFormulaDirtyDependencies.length===0||e.length===0)return[];let t=[];for(let n=0;n<this._featureFormulaDirtyDependencies.length;n++){let r=this._featureFormulaDirtyDependencies[n];this._rangesIntersectAny(e,r.dirtyRanges)&&t.push(r.node)}return t}_rangesIntersectAny(t,n){for(let r=0;r<t.length;r++){let i=t[r];for(let t=0;t<n.length;t++){let r=n[t];if(i.unitId===r.unitId&&i.sheetId===r.sheetId&&e.Rectangle.intersects(i.range,r.range))return!0}}return!1}async _initialAstNodeAndRanges(e){let{unitId:n,formula:r}=e;this._runtimeService.setCurrent(e.row,e.column,e.rowCount,e.columnCount,e.subUnitId,e.unitId);let i=(0,t.generateAstNode)(n,r,this._lexer,this._astTreeBuilder,this._currentConfigService,e.subUnitId);e.node=i,e.addressFunctionNodes=this._getAddressFunctionNodeList(i);let a=await this._getRangeListByNode({node:i,refOffsetX:e.refOffsetX,refOffsetY:e.refOffsetY});e.pushRangeList(a)}async _initialDependencyRanges(e){if(!(e.node||e.rangeList.length>0)){if(this._tryInitialStaticReferenceRanges(e)){M(`static.hit`);return}M(`ast.init`),await this._initialAstNodeAndRanges(e)}}_tryInitialStaticReferenceRanges(e){var t,n;let r=e.formula;if(!r||r.charCodeAt(0)!==61)return M(`static.skip.notFormula`),!1;let i=r.slice(1);if(i.indexOf(`[`)>=0||i.indexOf(`]`)>=0||i.indexOf(`{`)>=0||i.indexOf(`}`)>=0||i.indexOf(`#`)>=0||be.test(i))return M(`static.skip.unsupportedSyntax`),N(`unsupportedSyntax`,r),!1;let a=this._replaceDoubleQuotedStrings(i),o=this._replaceQuotedSheetNames(a);if(Te(o)||!this._hasOnlyStaticReferenceSafeIdentifiers(o))return M(`static.skip.identifier`),N(`identifier`,r),!1;let s=[],c=(t=(n=this._currentConfigService).getSheetNameMap)==null?void 0:t.call(n),l=c==null?{}:c;if(/\bOFFSET\s*\(/i.test(a)){let t=this._tryExtractStaticOffsetRanges(e,l,a);if(t==null)return M(`static.skip.offset`),N(`offset`,r),!1;s.push(...t)}xe.lastIndex=0;let u;for(;(u=xe.exec(a))!=null;){if(!this._isStaticReferenceTokenBoundarySafe(a,u.index,xe.lastIndex))continue;let t=this._tryCreateStaticColumnReferenceRange(e,l,u);if(t==null)return M(`static.skip.referenceParse`),N(`referenceParse`,r),!1;s.push(t)}j.lastIndex=0;let d;for(;(d=j.exec(a))!=null;){if(!this._isStaticReferenceTokenBoundarySafe(a,d.index,j.lastIndex))continue;let t=this._tryCreateStaticReferenceRange(e,l,d);if(t==null)return M(`static.skip.referenceParse`),N(`referenceParse`,r),!1;s.push(t)}return e.addressFunctionNodes=[],e.rangeList.push(...this._dedupeStaticReferenceRanges(s)),!0}_replaceDoubleQuotedStrings(e){let t=``,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i===`"`){if(t+=` `,n&&e[r+1]===`"`){r++,t+=` `;continue}n=!n;continue}t+=n?` `:i}return t}_replaceQuotedSheetNames(e){return e.replace(/'(?:(?:[^']|'')+)'(?=!)/g,e=>` `.repeat(e.length))}_hasOnlyStaticReferenceSafeIdentifiers(e){Se.lastIndex=0;let t;for(;(t=Se.exec(e))!=null;){let n=t[0],r=t.index,i=Se.lastIndex,a=this._nextNonSpaceChar(e,i);if(!(a===`(`||a===`!`||Ce.test(n))&&!this._looksLikeA1ReferenceAt(e,r,i)&&!this._looksLikeColumnReferencePart(e,r,i))return!1}return!0}_looksLikeA1ReferenceAt(e,t,n){var r;let i=e.slice(t,n),a=/^([A-Za-z]{1,3})([1-9]\d*)$/.exec(i);if(a&&this._columnNameToIndex(a[1])!==void 0)return!0;let o=n;return e[o]===`$`&&o++,/\d/.test((r=e[o])==null?``:r)?this._columnNameToIndex(i)!==void 0:!1}_looksLikeColumnReferencePart(e,t,n){var r,i,a,o;let s=e.slice(t,n);if(this._columnNameToIndex(s)===void 0)return!1;let c=e[t-1]===`$`?(r=e[t-2])==null?``:r:(i=e[t-1])==null?``:i,l=e[n]===`$`?(a=e[n+1])==null?``:a:(o=e[n])==null?``:o;return c===`:`||l===`:`}_isStaticReferenceTokenBoundarySafe(e,t,n){var r,i;let a=(r=e[t-1])==null?``:r,o=(i=e[n])==null?``:i;return!(/[A-Za-z0-9_.]/.test(a)||o===`(`||/[A-Za-z0-9_.]/.test(o))}_tryCreateStaticReferenceRange(e,t,n){var r,i,a,o;let s=(r=n[1])==null?void 0:r.replace(/''/g,`'`),c=s==null?n[2]:s,l=c==null?e.subUnitId:(i=t[e.unitId])==null?void 0:i[c];if(!l)return;let u=this._columnNameToIndex(n[3]),d=Number(n[4])-1,f=this._columnNameToIndex((a=n[5])==null?n[3]:a),p=Number((o=n[6])==null?n[4]:o)-1,m=this._getStaticReferenceSheetSize(e,l);if(!(u===void 0||f===void 0||d<0||p<0||Math.max(d,p)>=m.rowCount||Math.max(u,f)>=m.columnCount))return{unitId:e.unitId,sheetId:l,range:{startRow:Math.min(d,p),endRow:Math.max(d,p),startColumn:Math.min(u,f),endColumn:Math.max(u,f)}}}_tryCreateStaticColumnReferenceRange(e,t,n){var r,i;let a=(r=n[1])==null?void 0:r.replace(/''/g,`'`),o=a==null?n[2]:a,s=o==null?e.subUnitId:(i=t[e.unitId])==null?void 0:i[o];if(!s)return;let c=this._columnNameToIndex(n[3]),l=this._columnNameToIndex(n[4]);if(c===void 0||l===void 0)return;let u=this._getStaticReferenceSheetSize(e,s);if(!(Math.max(c,l)>=u.columnCount||u.rowCount<=0))return{unitId:e.unitId,sheetId:s,range:{startRow:0,endRow:u.rowCount-1,startColumn:Math.min(c,l),endColumn:Math.max(c,l)}}}_tryExtractStaticOffsetRanges(e,t,n){let r=this._extractFunctionCalls(n,`OFFSET`),i=[];for(let n=0;n<r.length;n++){let a=this._tryCreateStaticOffsetRange(e,t,r[n]);if(a==null)return;i.push(a)}return i}_tryCreateStaticOffsetRange(e,t,n){if(n.length<3)return;let r=this._tryParseSingleStaticReference(e,t,n[0]),i=this._tryInferOffsetRowSpan(e,t,n[1],r),a=this._tryParseInteger(n[2]),o=n[3]==null?1:this._tryInferPositiveInteger(n[3]),s=n[4]==null?1:this._tryInferPositiveInteger(n[4]);if(r==null||i==null||a==null||o==null||s==null||o<1||s<1)return;let c=this._getStaticReferenceSheetSize(e,r.sheetId),l=r.range.startRow+i.startOffset,u=r.range.startRow+i.endOffset+o-1,d=r.range.startColumn+a,f=d+s-1;if(!(l<0||u<l||u>=c.rowCount||d<0||f<d||f>=c.columnCount))return{unitId:r.unitId,sheetId:r.sheetId,range:{startRow:l,endRow:u,startColumn:d,endColumn:f}}}_tryInferOffsetRowSpan(e,t,n,r){let i=this._tryParseInteger(n);if(i!=null)return{startOffset:i,endOffset:i};if(r==null)return;let a=this._extractFunctionCalls(n,`MATCH`)[0];if(a==null||a.length<2)return;let o=this._tryParseSingleStaticReference(e,t,a[1]);if(o==null||o.sheetId!==r.sheetId||o.unitId!==r.unitId)return;let s=n.slice(n.toUpperCase().indexOf(`MATCH`));if(/\)\s*-\s*1\s*$/.test(s))return{startOffset:o.range.startRow-r.range.startRow,endOffset:o.range.endRow-r.range.startRow}}_tryInferPositiveInteger(e){let t=this._tryParseInteger(e);if(t!=null)return t;let n=this._extractFunctionCalls(e,`ROW`)[0];if(n==null||n.length!==1)return;let r=/^\s*\$?([1-9]\d*):\$?([1-9]\d*)\s*$/.exec(n[0]);if(r!=null)return Math.max(Number(r[1]),Number(r[2]))}_tryParseInteger(e){return/^\s*-?\d+\s*$/.exec(e)==null?void 0:Number(e)}_tryParseSingleStaticReference(e,t,n){let r=n.trim();j.lastIndex=0;let i=j.exec(r);if(!(i==null||i.index!==0||j.lastIndex!==r.length))return this._tryCreateStaticReferenceRange(e,t,i)}_extractFunctionCalls(e,t){let n=[],r=e.toUpperCase(),i=t.toUpperCase(),a=0;for(;a<e.length;){var o;let t=r.indexOf(i,a);if(t<0)break;let s=(o=e[t-1])==null?``:o,c=t+i.length;for(;e[c]===` `;)c++;if(/[A-Za-z0-9_.]/.test(s)||e[c]!==`(`){a=t+i.length;continue}let l=this._findMatchingParen(e,c);if(l<0)break;n.push(this._splitTopLevelArguments(e.slice(c+1,l))),a=l+1}return n}_findMatchingParen(e,t){let n=0;for(let r=t;r<e.length;r++){let t=e[r];if(t===`(`)n++;else if(t===`)`&&(n--,n===0))return r}return-1}_splitTopLevelArguments(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let a=e[i];a===`(`?n++:a===`)`?n--:a===`,`&&n===0&&(t.push(e.slice(r,i).trim()),r=i+1)}return t.push(e.slice(r).trim()),t}_getStaticReferenceSheetSize(e,t){if(t===e.subUnitId)return{rowCount:e.rowCount,columnCount:e.columnCount};let n=this._currentConfigService.getSheetRowColumnCount(e.unitId,t);return{rowCount:n.rowCount||e.rowCount,columnCount:n.columnCount||e.columnCount}}_dedupeStaticReferenceRanges(e){if(e.length<2)return e;let t=new Set,n=[];for(let r=0;r<e.length;r++){let i=e[r],a=`${i.unitId}\0${i.sheetId}\0${i.range.startRow}\0${i.range.endRow}\0${i.range.startColumn}\0${i.range.endColumn}`;t.has(a)||(t.add(a),n.push(i))}return n}_columnNameToIndex(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n),i=r>=97&&r<=122?r-32:r;if(i<65||i>90)return;t=t*26+i-64}let n=t-1;return n>=0&&n<16384?n:void 0}_nextNonSpaceChar(e,t){for(let n=t;n<e.length;n++)if(e[n]!==` `)return e[n];return``}_createFDtree(e,n,r,i,a,o){let{f:s}=o,c=new t.FormulaDependencyTree((0,t.generateRandomDependencyTreeId)(this._dependencyManagerService)),l=a[e][n];return c.formula=s,c.unitId=e,c.subUnitId=n,c.row=r,c.column=i,c.rowCount=l.rowCount,c.columnCount=l.columnCount,c}};const ke=/'?\[([^\]]+)\]([^'!]+)'?!\$?([A-Za-z]+)\$?([1-9]\d*)(?:\s*:\s*\$?([A-Za-z]+)\$?([1-9]\d*))?/g,Ae=/(?:'((?:[^']|'')+)'|\[([^\]]+)\]|([A-Za-z0-9_.-]+))!([^\s!\[\]]+)\[/g,je=/\bINDIRECT\s*\(\s*"((?:[^"]|"")*)"/gi;function Me(e){let t=``,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i!==`"`){n||(t+=i);continue}if(n&&e[r+1]===`"`){r++;continue}n=!n,t+=` `}let r=[t];for(let t of e.matchAll(je))r.push(t[1].replace(/""/g,`"`));return r}let R=class{constructor(e){this._externalReferenceModel=e,s(this,`_calculationCounter`,0),s(this,`_requestCounter`,0)}plan(e){var t;let n=`external-calculation-${++this._calculationCounter}`,r=new Map;for(let[i,a]of Object.entries((t=e.formulaData)==null?{}:t))if(this._externalReferenceModel.get(i))for(let e of Object.values(a==null?{}:a))for(let t of Object.values(e==null?{}:e))for(let e of Object.values(t==null?{}:t)){let t=Ne(e);if(typeof t==`string`)for(let e of Me(t))this._collectA1(r,n,i,e),this._collectTables(r,n,i,e)}return Array.from(r.values())}planDynamic(e,t){let n=`external-calculation-${++this._calculationCounter}`,r=new Map,i=this._externalReferenceModel.get(e);if(!i)return[];for(let a of t){let t=i.links.find(t=>u(e,t.slot)===a.unitId);!t||!a.sheetName||!a.range||this._addRange(r,n,e,t,{sheetName:a.sheetName,range:a.range})}return Array.from(r.values())}_collectA1(t,n,r,i){for(let s of i.matchAll(ke)){var a,o;let i=this._externalReferenceModel.resolveBinding(r,s[1]);if(i.status!==`resolved`)continue;let c=e.Tools.ABCatNum(s[3]),l=e.Tools.ABCatNum((a=s[5])==null?s[3]:a),u=Number(s[4])-1,d=Number((o=s[6])==null?s[4]:o)-1;this._addRange(t,n,r,i.link,{sheetName:s[2].replace(/''/g,`'`),range:{startRow:Math.min(u,d),endRow:Math.max(u,d),startColumn:Math.min(c,l),endColumn:Math.max(c,l)}})}}_collectTables(e,t,n,r){for(let o of r.matchAll(Ae)){var i,a;let r=((i=(a=o[1])==null?o[2]:a)==null?o[3]:i).replace(/''/g,`'`),s=this._externalReferenceModel.resolveBinding(n,r);if(s.status!==`resolved`)continue;let c=s.link.tables.find(e=>e.name.toLowerCase()===o[4].toLowerCase());this._addRange(e,t,n,s.link,{tableName:o[4],sheetName:c==null?void 0:c.sheetName,range:c==null?void 0:c.range})}}_addRange(e,t,n,r,i){var a;let o=`${n}\0${r.slot}`,s=(a=e.get(o))==null?{requestId:`external-request-${++this._requestCounter}`,calculationId:t,hostUnitId:n,bindingSlot:r.slot,syntheticUnitId:u(n,r.slot),target:r.target,ranges:[],requireFresh:!0}:a;s.ranges.some(e=>JSON.stringify(e)===JSON.stringify(i))||s.ranges.push(i),e.set(o,s)}};R=m([p(0,(0,e.Inject)(d))],R);function Ne(e){return typeof e==`object`&&e&&`f`in e&&typeof e.f==`string`?e.f:void 0}const Pe={maxCells:1e5,maxBytes:5e6,concurrency:4,timeoutMs:15e3};let z=class extends e.Disposable{constructor(e,t,n){super(),this._referenceDataService=e,this._overlayModel=t,this._formulaDataModel=n,s(this,`_inflight`,new Map),s(this,`_latestCalculation`,new Map)}async prefetch(e,t,n={}){this._hydrateLiveUnits(t);let r={...Pe,...n},i=Fe(e).map(e=>({...e,ranges:e.ranges.filter(t=>{var n;return!t.range||!this._overlayModel.isRangeCovered(e.syntheticUnitId,(n=t.sheetId)==null?t.sheetName:n,t.range)})})).filter(e=>e.ranges.length>0);Ie(i,r);for(let e of i)this._latestCalculation.set(e.hostUnitId,e.calculationId);let a=[],o=[],s=0,c=0,l=Array.from({length:Math.min(r.concurrency,i.length)},async()=>{for(;c<i.length;){let e=i[c++],n=this._hasWorkerLiveUnit(e,t)?Re(e):await this._readWithInflight(e,r.timeoutMs);if(this._latestCalculation.get(e.hostUnitId)!==e.calculationId||n.calculationId!==e.calculationId){s++;continue}if(a.push(n),n.source!==`worker-live`){let t=this._overlayModel.apply(e,n);this._overlayModel.enforceLimits(r.maxCells,r.maxBytes);for(let n of t)o.push({unitId:e.syntheticUnitId,...n})}}});return await Promise.all(l),this._overlayModel.materialize(t),{responses:a,dirtyRanges:o,discarded:s}}cancelHost(e,t){this._latestCalculation.set(e,t)}getInflightCount(){return this._inflight.size}drainDirtyRanges(){return this._overlayModel.drainDirtyRanges()}dispose(){super.dispose(),this._inflight.clear(),this._latestCalculation.clear()}_hydrateLiveUnits(e){let t=this._formulaDataModel.getCalculateData();e.allUnitData={...e.allUnitData,...t.allUnitData},e.unitSheetNameMap={...e.unitSheetNameMap,...t.unitSheetNameMap},e.unitStylesData={...e.unitStylesData,...t.unitStylesData},e.unitNameMap={...e.unitNameMap,...t.unitNameMap}}_hasWorkerLiveUnit(e,n){var r,i;let a=(r=n.allUnitData)==null?{}:r;if(e.target.liveUnitId&&e.target.liveUnitId!==e.syntheticUnitId&&a[e.target.liveUnitId])return!0;let o=Object.entries((i=n.unitNameMap)==null?{}:i).filter(([t,n])=>t!==e.syntheticUnitId&&!t.startsWith(`external:`)&&!!a[t]&&n.unitType===e.target.unitType),s=e.target.name.toLowerCase(),c=o.filter(([,e])=>e.name.toLowerCase()===s);if(c.length>0)return c.length===1;let l=(0,t.normalizeFormulaUnitName)(e.target.name);return o.filter(([,e])=>(0,t.normalizeFormulaUnitName)(e.name)===l).length===1}_readWithInflight(e,t){let n=Le(e),r=this._inflight.get(n);if(r)return r.then(t=>({...t,requestId:e.requestId,calculationId:e.calculationId}));let i=Promise.race([this._referenceDataService.readData(e),new Promise(n=>{setTimeout(()=>n(S(e)),t)})]).finally(()=>this._inflight.delete(n));return this._inflight.set(n,i),i}};z=m([p(0,y),p(1,(0,e.Inject)(w)),p(2,(0,e.Inject)(t.FormulaDataModel))],z);function Fe(e){let t=new Map;for(let n of e){let e=`${n.hostUnitId}\0${n.bindingSlot}\0${n.calculationId}`,r=t.get(e);if(!r){t.set(e,{...n,ranges:[...n.ranges]});continue}for(let e of n.ranges)r.ranges.some(t=>JSON.stringify(t)===JSON.stringify(e))||r.ranges.push(e)}return Array.from(t.values())}function Ie(e,t){let n=0;for(let t of e)for(let e of t.ranges)e.range&&(n+=(e.range.endRow-e.range.startRow+1)*(e.range.endColumn-e.range.startColumn+1));if(n>t.maxCells)throw Error(`External formula prefetch cell limit exceeded`);if(JSON.stringify(e).length>t.maxBytes)throw Error(`External formula prefetch byte limit exceeded`)}function Le(e){return`${e.hostUnitId}\0${e.bindingSlot}\0${JSON.stringify(e.ranges)}`}function Re(e){return{requestId:e.requestId,calculationId:e.calculationId,source:`worker-live`,freshness:`fresh`,sheets:[]}}let ze=class extends t.CalculateFormulaService{constructor(e,t,n,r,i,a,o,c,l){super(e,t,n,r,i,a,o),this._externalPrefetchPlanner=c,this._externalPrefetchService=l,s(this,`_dynamicRuntimeRanges`,void 0),s(this,`_externalFormulaDatasetConfig`,void 0),s(this,`_externalPrefetchedNodes`,new Set)}async execute(e){this._externalFormulaDatasetConfig=e;let n=this._externalPrefetchPlanner.plan(e);n.length>0&&await this._externalPrefetchService.prefetch(n,e);let r=this._externalPrefetchService.drainDirtyRanges();r.length>0&&e.dirtyRanges.push(...r),this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.START),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()),this._currentConfigService.load(e),this._runtimeService.reset();let i=e.maxIteration||t.DEFAULT_CYCLE_REFERENCE_COUNT;this._isCalculateTreeModel=e.isCalculateTreeModel||!1,this._executeLock.acquire(`FORMULA_EXECUTION_LOCK`,async()=>{await this._executeStep(i),this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.CALCULATION_COMPLETED),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()),this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData()),t.CELL_INVERTED_INDEX_CACHE.clear(),this._runtimeService.reset()})}async _executeStep(e=t.DEFAULT_CYCLE_REFERENCE_COUNT){let n=await this._apply(!1,e);if(n==null)return;let{arrayFormulaRange:r}=n,{dirtyRanges:i,excludedCell:a}=this._getArrayFormulaDirtyRangeAndExcludedRange(r,{});return i==null||i.length===0?!0:(t.FORMULA_REF_TO_ARRAY_CACHE.clear(),this._currentConfigService.loadDirtyRangesAndExcludedCell(i,a),await this._apply(!0,e),!0)}async _apply(e=!1,n=t.DEFAULT_CYCLE_REFERENCE_COUNT){this._setFormulaExecuteStage(e,t.FormulaExecuteStageType.START_DEPENDENCY,t.FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());let r=this._configService.getConfig(t.ENGINE_FORMULA_PLUGIN_CONFIG_KEY),i=(r==null?void 0:r.intervalCount)||t.DEFAULT_INTERVAL_COUNT,a=this._formulaDependencyGenerator;try{let{calculationOrderResult:r,dependencyTree:o}=await a.generatePro(this._isCalculateTreeModel),s=this._getCalculationPlanTreeCount(r,o,n);r.hasCycle&&this._runtimeService.enableCycleDependency(),this._setFormulaExecuteStage(e,t.FormulaExecuteStageType.START_CALCULATION,t.FormulaExecuteStageType.START_CALCULATION_ARRAY_FORMULA),this._setTotalFormulasToCalculate(e,s),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());let c=[],l=[],u=new Set,d=!1,f=0,p=0;for(this._runtimeService.setFormulaCycleIndex(0);;){let t=!1,m=!1;if(await this._forEachCalculationPlanTree(r,o,n,async(n,r,o,s)=>{var p,h;if(this._runtimeService.setFormulaCycleIndex(o==null?0:o),await this._waitForExecutionSlot(f,i,e,n,c))return d=!0,!1;if(s){u.has(r)||(u.add(r),l.push(r)),f++;return}let g=await this._calculateDependencyTree(n,r,a);m||(m=(p=(h=this._externalPrefetchedNodes)==null?void 0:h.has(r))==null?!1:p),g&&this._shouldRescheduleAfterDynamicChange(a,r,u)&&(t=!0),u.has(r)||(u.add(r),l.push(r)),f++}),r.calculationForest.length=0,d||!t)break;if(p++,p>8)throw Error(`Dynamic dependency did not stabilize`);a.clearCachedCalculationNodeData(),m?{calculationOrderResult:r,dependencyTree:o}=await a.generatePro(this._isCalculateTreeModel):r=a.getCalculationOrder(),r.hasCycle&&this._runtimeService.enableCycleDependency(),s=this._getCalculationPlanTreeCount(r,o,n),this._setTotalFormulasToCalculate(e,s)}for(let e=0;e<c.length;e++)c[e]();return l.length>0&&a.clearCalculatedDirty(l),d?void 0:(s>0||l.length>0?this._runtimeService.markedAsSuccessfullyExecuted():e||this._runtimeService.markedAsNoFunctionsExecuted(),this._runtimeService.getAllRuntimeData())}finally{var o;a.clearCachedCalculationNodeData(),a.clearCachedCalculationTree(),this._dynamicRuntimeRanges=void 0,(o=this._externalPrefetchedNodes)==null||o.clear()}}_setFormulaExecuteStage(e,t,n){this._runtimeService.setFormulaExecuteStage(e?n:t)}_setTotalFormulasToCalculate(e,t){if(e){this._runtimeService.setTotalArrayFormulasToCalculate(t);return}this._runtimeService.setTotalFormulasToCalculate(t)}_shouldRescheduleAfterDynamicChange(e,t,n){var r;if((r=this._externalPrefetchedNodes)!=null&&r.delete(t))return!0;let i=e;return typeof i.hasUncalculatedDirtyPrecedentByIndex==`function`?i.hasUncalculatedDirtyPrecedentByIndex(t,n):!0}async _forEachCalculationPlanTree(e,n,r,i){let a=Math.max(r,1);for(let o=0;o<e.calculationForest.length;o++){let s=e.calculationForest[o],c=s.hasCycle&&r<=t.DEFAULT_CYCLE_REFERENCE_COUNT&&this._calculationPlanHasSelfReference(s,n);for(let e=0;e<s.plan.length;e++){let r=s.plan[e];if(r.type===`node`){let e=n.get(r.nodeIndex);if(e!=null&&await i(e,r.nodeIndex,void 0,c)===!1)return;continue}if(r.type===`nodes`){for(let e=0;e<r.nodeIndices.length;e++){let t=r.nodeIndices[e],a=n.get(t);if(a!=null&&await i(a,t,void 0,c)===!1)return}r.nodeIndices.length=0;continue}for(let e=0;e<a;e++){e>0&&t.FORMULA_REF_TO_ARRAY_CACHE.clear();for(let t=0;t<r.nodeIndices.length;t++){let a=r.nodeIndices[t],o=n.get(a);if(o!=null&&await i(o,a,e,c)===!1)return}}}}}_calculationPlanHasSelfReference(e,t){for(let n of e.plan){if(n.type===`node`){let e=t.get(n.nodeIndex);if(e!=null&&this._formulaReferencesTreeCell(e))return!0;continue}for(let e of n.nodeIndices){let n=t.get(e);if(n!=null&&this._formulaReferencesTreeCell(n))return!0}}return!1}_getCalculationPlanTreeCount(e,t,n){let r=Math.max(n,1),i=0;for(let n=0;n<e.calculationForest.length;n++){let a=e.calculationForest[n];for(let e=0;e<a.plan.length;e++){let n=a.plan[e];if(n.type===`node`){t.has(n.nodeIndex)&&i++;continue}if(n.type===`nodes`){for(let e=0;e<n.nodeIndices.length;e++)t.has(n.nodeIndices[e])&&i++;continue}let o=0;for(let e=0;e<n.nodeIndices.length;e++)t.has(n.nodeIndices[e])&&o++;i+=o*r}}return i}_getDynamicResolver(){let e=this._dynamicRuntimeRanges;if(e==null)return;let t=e.map(e=>this._getRangeSignature(e)).sort().join(`|`);return()=>({signature:t,ranges:e,status:e.length>0?`resolved`:`unknown`})}_refreshDynamicDepsAfterCalculate(e,t,n,r){if(n.hasDynamicDeps===!1||!e.hasDynamicDepsByIndex(t))return!1;let i=this._collectAddressFunctionRuntimeRanges(r);if(i.length===0)return!1;this._dynamicRuntimeRanges=i;try{let n=this._getDynamicResolver();return n==null?!1:e.refreshDynamicDepsByIndex(t,n)}finally{this._dynamicRuntimeRanges=void 0}}_collectAddressFunctionRuntimeRanges(e){let t=[];return this._collectAddressFunctionRuntimeRangesInternal(e,t),t}_collectAddressFunctionRuntimeRangesInternal(e,n){if(e.isAddress()){let r=e.getValue();r instanceof t.BaseReferenceObject&&n.push(r.toUnitRange())}let r=e.getChildren();for(let e=0;e<r.length;e++)this._collectAddressFunctionRuntimeRangesInternal(r[e],n)}_getRangeSignature(e){return[e.unitId,e.sheetId,e.range.startRow,e.range.endRow,e.range.startColumn,e.range.endColumn].join(`:`)}async _waitForExecutionSlot(n,r,i,a,o){return n%r===0?(await new Promise(t=>{let n=(0,e.requestImmediateMacroTask)(t);o.push(n)}),i?(this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA),this._runtimeService.setCompletedArrayFormulasCount(n+1)):(this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.CURRENTLY_CALCULATING),this._runtimeService.setCompletedFormulasCount(n+1)),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()),this._runtimeService.isStopExecution()||a.formula==null&&a.getDirtyData==null?(this._runtimeService.setFormulaExecuteStage(t.FormulaExecuteStageType.IDLE),this._runtimeService.markedAsStopFunctionsExecuted(),this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData()),!0):!1):!1}async _calculateDependencyTree(e,t,n){let r=e.getDirtyData;if(this._formulaReferencesTreeCell(e))return!1;if(this._runtimeService.setCurrent(e.row,e.column,e.rowCount,e.columnCount,e.subUnitId,e.unitId),r!=null&&e.featureId!=null){let t=e.featureId,{runtimeCellData:n,dirtyRanges:i}=r(this._currentConfigService.getDirtyData(),this._runtimeService.getAllRuntimeData());return this._runtimeService.setRuntimeFeatureCellData(t,n),this._runtimeService.setRuntimeFeatureRange(t,i),!1}let i=this._getCalculationNodeData(e,t,n),a=i.node,o;try{let r=this._setFunctionRefInfoForTree(e);try{o=this._interpreter.checkAsyncNode(i.node)?await this._interpreter.executeAsync(i):this._interpreter.execute(i)}finally{r()}e.formulaId==null?this._runtimeService.setRuntimeData(o):this._runtimeService.setRuntimeOtherData(e.formulaId,e.refOffsetX,e.refOffsetY,o);let c=await this._prefetchDynamicExternalReferences(e,a);if(c){var s;((s=this._externalPrefetchedNodes)==null?this._externalPrefetchedNodes=new Set:s).add(t)}let l=this._refreshDynamicDepsAfterCalculate(n,t,e,a);return c||l}finally{a.resetCalculationState()}}async _prefetchDynamicExternalReferences(e,t){if(!this._externalFormulaDatasetConfig)return!1;let n=this._collectAddressFunctionRuntimeReferences(t),r=this._externalPrefetchPlanner.planDynamic(e.unitId,n);if(r.length===0)return!1;let i=await this._externalPrefetchService.prefetch(r,this._externalFormulaDatasetConfig);i.dirtyRanges.length>0&&this._currentConfigService.load(this._externalFormulaDatasetConfig);let a=this._externalPrefetchService.drainDirtyRanges();return i.dirtyRanges.length>0||a.length>0}_collectAddressFunctionRuntimeReferences(e){let n=[],r=e=>{if(e.isAddress()){let r=e.getValue();if(r instanceof t.BaseReferenceObject){let e=r.getUnitId(),t=r.getForcedSheetName()||this._currentConfigService.getSheetName(e,r.getSheetId());n.push({unitId:e,sheetName:t,range:r.getRangeData()})}}e.getChildren().forEach(r)};return r(e),n}_setFunctionRefInfoForTree(e){return e.formulaId==null?this._runtimeService.setFunctionRefInfoOverride(1,1):()=>{}}_formulaReferencesTreeCell(e){let t=e.formula.replace(/"([^"]|"")*"/g,``);for(let n of t.matchAll(/(\$?[A-Z]{1,3}\$?\d+)(?::(\$?[A-Z]{1,3}\$?\d+))?/gi)){if(t[n.index-1]===`!`||this._isReferenceMetadataFunctionArgument(t,n.index))continue;let r=this._parseA1Reference(n[1]),i=this._parseA1Reference(n[2]||n[1]);if(r==null||i==null)continue;let a=Math.min(r.row,i.row),o=Math.max(r.row,i.row),s=Math.min(r.column,i.column),c=Math.max(r.column,i.column);if(e.row>=a&&e.row<=o&&e.column>=s&&e.column<=c)return!0}return!1}_isReferenceMetadataFunctionArgument(e,t){var n;let r=e.lastIndexOf(`(`,t);if(r<0)return!1;let i=(n=e.slice(0,r).match(/([A-Z][A-Z0-9.]*)\s*$/i))==null||(n=n[1])==null?void 0:n.toUpperCase();return i===`ROW`||i===`ROWS`||i===`COLUMN`||i===`COLUMNS`}_parseA1Reference(e){let t=e==null?void 0:e.replace(/\$/g,``).match(/^([A-Z]{1,3})(\d+)$/i);if(!t)return null;let[,n,r]=t,i=0;for(let e of n.toUpperCase())i=i*26+e.charCodeAt(0)-64;return{row:Number(r)-1,column:i-1}}_getCalculationNodeData(e,n,r){let i=r.getCachedCalculationNodeData(n);return(i==null?void 0:i.node)==null?{node:(0,t.generateAstNode)(e.unitId,e.formula,this._lexer,this._astTreeBuilder,this._currentConfigService,e.subUnitId),refOffsetX:e.refOffsetX,refOffsetY:e.refOffsetY}:i}};ze=m([p(0,e.IConfigService),p(1,(0,e.Inject)(t.Lexer)),p(2,t.IFormulaCurrentConfigService),p(3,t.IFormulaRuntimeService),p(4,t.IFormulaDependencyGenerator),p(5,(0,e.Inject)(t.Interpreter)),p(6,(0,e.Inject)(t.AstTreeBuilder)),p(7,(0,e.Inject)(R)),p(8,(0,e.Inject)(z))],ze);var Be=class{constructor(e,t){s(this,`maxRows`,void 0),s(this,`maxCols`,void 0),s(this,`sheetSize`,void 0),s(this,`_sheetKeyById`,new Map),s(this,`_sheetIdByKey`,[]),this.maxRows=e,this.maxCols=t,this.sheetSize=e*t}reset(){this._sheetKeyById.clear(),this._sheetIdByKey.length=0}encodeCell(e,t,n,r){return this.encodeSheet(e,t)*this.sheetSize+n*this.maxCols+r}decodeCell(e){let t=Math.floor(e/this.sheetSize),n=e-t*this.sheetSize,r=Math.floor(n/this.maxCols),i=n-r*this.maxCols,{unitId:a,sheetId:o}=this.decodeSheetKey(t);return{unitId:a,sheetId:o,row:r,col:i}}encodeSheet(e,t){let n=`${e}\0${t}`,r=this._sheetKeyById.get(n);if(r!==void 0)return r;let i=this._sheetIdByKey.length;return this._sheetKeyById.set(n,i),this._sheetIdByKey.push({unitId:e,sheetId:t}),i}decodeSheetKey(e){let t=this._sheetIdByKey[e];if(!t)throw Error(`Unknown sheet key: ${e}`);return t}encodeRow(e,t,n){return this.encodeSheet(e,t)*this.maxRows+n}encodeRowBySheetKey(e,t){return e*this.maxRows+t}decodeRowKey(e){let t=Math.floor(e/this.maxRows),n=e-t*this.maxRows;return{sheetKey:t,...this.decodeSheetKey(t),row:n}}encodeCol(e,t,n){return this.encodeSheet(e,t)*this.maxCols+n}encodeColBySheetKey(e,t){return e*this.maxCols+t}decodeColKey(e){let t=Math.floor(e/this.maxCols),n=e-t*this.maxCols;return{sheetKey:t,...this.decodeSheetKey(t),col:n}}};function Ve(e){if(typeof e!=`number`)throw TypeError(`CellFormula node id must be a numeric CellId`)}function B(e){let{startRow:t,endRow:n,startColumn:r,endColumn:i}=e.range;if(t<=n&&r<=i)return e;let a=t<n?t:n,o=t<n?n:t,s=r<i?r:i,c=r<i?i:r;return{...e,range:{...e.range,startRow:a,endRow:o,startColumn:s,endColumn:c}}}function V(e){return e.range.endRow-e.range.startRow+1}function H(e){return e.range.endColumn-e.range.startColumn+1}function He(e,t){return e.unitId===t.unitId&&e.sheetId===t.sheetId&&e.range.startRow<=t.row&&t.row<=e.range.endRow&&e.range.startColumn<=t.col&&t.col<=e.range.endColumn}function Ue(e){if(!e||e.length===0)return[];if(e.length===1)return[e[0]];let t=e.slice().sort((e,t)=>e-t),n=1;for(let e=1;e<t.length;e++)t[e]!==t[n-1]&&(t[n++]=t[e]);return t.length=n,t}function U(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function We(e,t){let n=e.indexOf(t);if(n<0)return!1;let r=e.pop();return n<e.length&&(e[n]=r),!0}function W(e,t,n){let r=e.get(t);r&&(We(r,n),r.length===0&&e.delete(t))}function Ge(e,t){if(e===void 0)return t;if(typeof e==`number`)return e===t?e:[e,t];for(let n=0;n<e.length;n++)if(e[n]===t)return e;return e.push(t),e}function Ke(e,t){if(e===void 0)return;if(typeof e==`number`)return e===t?void 0:e;let n=e.indexOf(t);if(n<0)return e;if(e.length===1)return;if(e.length===2)return e[1-n];let r=e.pop();return n<e.length&&(e[n]=r),e}function G(e,t){if(e!==void 0){if(typeof e==`number`){t(e);return}for(let n=0;n<e.length;n++)t(e[n])}}function K(e,t,n){let r=Ge(e.get(t),n);e.set(t,r)}function q(e,t,n){let r=e.get(t);if(r===void 0)return;let i=Ke(r,n);i===void 0?e.delete(t):e.set(t,i)}function J(e,t){if(e.length>=t)return e;let n=Math.max(16,e.length);for(;n<t;)n*=2;let r=new Uint8Array(n);return r.set(e),r}function Y(e,t){if(e.length>=t)return e;let n=Math.max(16,e.length);for(;n<t;)n*=2;let r=new Uint32Array(n);return r.set(e),r}function qe(e){if(!e||e.length===0)return[];let t=new Set,n=[];for(let r=0;r<e.length;r++){let i=e[r],a=`${i.type}:${String(i.id)}`;t.has(a)||(t.add(a),n.push(i))}return n}function Je(e){if(e.length<=1){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=B(e[n]);return t}let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=B(e[n]);return Xe(Ye(t))}function Ye(e){let t=e.slice().sort((e,t)=>{let n=e.unitId.localeCompare(t.unitId);if(n!==0)return n;let r=e.sheetId.localeCompare(t.sheetId);return r===0?e.range.startRow===t.range.startRow?e.range.endRow===t.range.endRow?e.range.startColumn===t.range.startColumn?e.range.endColumn-t.range.endColumn:e.range.startColumn-t.range.startColumn:e.range.endRow-t.range.endRow:e.range.startRow-t.range.startRow:r}),n=[];for(let e of t){let t=n[n.length-1];t&&t.unitId===e.unitId&&t.sheetId===e.sheetId&&t.range.startRow===e.range.startRow&&t.range.endRow===e.range.endRow&&e.range.startColumn<=t.range.endColumn+1?e.range.endColumn>t.range.endColumn&&(t.range.endColumn=e.range.endColumn):n.push({...e,range:{...e.range}})}return n}function Xe(e){let t=e.slice().sort((e,t)=>{let n=e.unitId.localeCompare(t.unitId);if(n!==0)return n;let r=e.sheetId.localeCompare(t.sheetId);return r===0?e.range.startColumn===t.range.startColumn?e.range.endColumn===t.range.endColumn?e.range.startRow===t.range.startRow?e.range.endRow-t.range.endRow:e.range.startRow-t.range.startRow:e.range.endColumn-t.range.endColumn:e.range.startColumn-t.range.startColumn:r}),n=[];for(let e of t){let t=n[n.length-1];t&&t.unitId===e.unitId&&t.sheetId===e.sheetId&&t.range.startColumn===e.range.startColumn&&t.range.endColumn===e.range.endColumn&&e.range.startRow<=t.range.endRow+1?e.range.endRow>t.range.endRow&&(t.range.endRow=e.range.endRow):n.push({...e,range:{...e.range}})}return n}var Ze=class{constructor(e,t){this._codec=e,this._indexToNodeId=t,s(this,`_rowBuckets`,new Map),s(this,`_colBuckets`,new Map)}addFormulaCell(e,t){let n=this._codec.decodeCell(e);U(this._rowBuckets,this._codec.encodeRow(n.unitId,n.sheetId,n.row),t),U(this._colBuckets,this._codec.encodeCol(n.unitId,n.sheetId,n.col),t)}addFormulaCellByPosition(e,t,n,r){U(this._rowBuckets,this._codec.encodeRowBySheetKey(e,t),r),U(this._colBuckets,this._codec.encodeColBySheetKey(e,n),r)}removeFormulaCell(e,t){let n=this._codec.decodeCell(e);W(this._rowBuckets,this._codec.encodeRow(n.unitId,n.sheetId,n.row),t),W(this._colBuckets,this._codec.encodeCol(n.unitId,n.sheetId,n.col),t)}forEachFormulaInRange(e,t){let n=B(e);return V(n)<=H(n)?this._scanRows(n,t):this._scanCols(n,t)}_scanRows(e,t){if(V(e)<=this._rowBuckets.size){for(let n=e.range.startRow;n<=e.range.endRow;n++)if(this._scanRowBucket(this._codec.encodeRow(e.unitId,e.sheetId,n),e,t)===!1)return!1;return!0}for(let[n]of this._rowBuckets){let r=this._codec.decodeRowKey(n);if(r.unitId===e.unitId&&r.sheetId===e.sheetId&&e.range.startRow<=r.row&&r.row<=e.range.endRow&&this._scanRowBucket(n,e,t)===!1)return!1}return!0}_scanCols(e,t){if(H(e)<=this._colBuckets.size){for(let n=e.range.startColumn;n<=e.range.endColumn;n++)if(this._scanColBucket(this._codec.encodeCol(e.unitId,e.sheetId,n),e,t)===!1)return!1;return!0}for(let[n]of this._colBuckets){let r=this._codec.decodeColKey(n);if(r.unitId===e.unitId&&r.sheetId===e.sheetId&&e.range.startColumn<=r.col&&r.col<=e.range.endColumn&&this._scanColBucket(n,e,t)===!1)return!1}return!0}_scanRowBucket(e,t,n){let r=this._rowBuckets.get(e);if(!r)return!0;for(let e=0;e<r.length;e++){let i=r[e],a=this._indexToNodeId[i],o=this._codec.decodeCell(a);if(o.unitId===t.unitId&&o.sheetId===t.sheetId&&t.range.startColumn<=o.col&&o.col<=t.range.endColumn&&n(i)===!1)return!1}return!0}_scanColBucket(e,t,n){let r=this._colBuckets.get(e);if(!r)return!0;for(let e=0;e<r.length;e++){let i=r[e],a=this._indexToNodeId[i],o=this._codec.decodeCell(a);if(o.unitId===t.unitId&&o.sheetId===t.sheetId&&t.range.startRow<=o.row&&o.row<=t.range.endRow&&n(i)===!1)return!1}return!0}},Qe=class{constructor(e,t){this._codec=e,this._pointScanCellLimit=t,s(this,`_rowCells`,new Map),s(this,`_colCells`,new Map)}add(e){let t=this._codec.decodeCell(e);U(this._rowCells,this._codec.encodeRow(t.unitId,t.sheetId,t.row),e),U(this._colCells,this._codec.encodeCol(t.unitId,t.sheetId,t.col),e)}remove(e){let t=this._codec.decodeCell(e);W(this._rowCells,this._codec.encodeRow(t.unitId,t.sheetId,t.row),e),W(this._colCells,this._codec.encodeCol(t.unitId,t.sheetId,t.col),e)}forEachCellInRange(e,t){let n=B(e),r=V(n),i=H(n);if(this._isSmallArea(r,i)){for(let e=n.range.startRow;e<=n.range.endRow;e++)for(let r=n.range.startColumn;r<=n.range.endColumn;r++)t(this._codec.encodeCell(n.unitId,n.sheetId,e,r));return}Math.min(r,this._rowCells.size)<=Math.min(i,this._colCells.size)?this._scanRows(n,t):this._scanCols(n,t)}_isSmallArea(e,t){return e<=0||t<=0?!0:e>this._pointScanCellLimit?!1:e*t<=this._pointScanCellLimit}_scanRows(e,t){if(V(e)<=this._rowCells.size){for(let n=e.range.startRow;n<=e.range.endRow;n++)this._scanRowBucket(this._codec.encodeRow(e.unitId,e.sheetId,n),e,t);return}for(let[n]of this._rowCells){let r=this._codec.decodeRowKey(n);r.unitId===e.unitId&&r.sheetId===e.sheetId&&e.range.startRow<=r.row&&r.row<=e.range.endRow&&this._scanRowBucket(n,e,t)}}_scanCols(e,t){if(H(e)<=this._colCells.size){for(let n=e.range.startColumn;n<=e.range.endColumn;n++)this._scanColBucket(this._codec.encodeCol(e.unitId,e.sheetId,n),e,t);return}for(let[n]of this._colCells){let r=this._codec.decodeColKey(n);r.unitId===e.unitId&&r.sheetId===e.sheetId&&e.range.startColumn<=r.col&&r.col<=e.range.endColumn&&this._scanColBucket(n,e,t)}}_scanRowBucket(e,t,n){let r=this._rowCells.get(e);if(r)for(let e=0;e<r.length;e++){let i=r[e],a=this._codec.decodeCell(i);a.unitId===t.unitId&&a.sheetId===t.sheetId&&t.range.startColumn<=a.col&&a.col<=t.range.endColumn&&n(i)}}_scanColBucket(e,t,n){let r=this._colCells.get(e);if(r)for(let e=0;e<r.length;e++){let i=r[e],a=this._codec.decodeCell(i);a.unitId===t.unitId&&a.sheetId===t.sheetId&&t.range.startRow<=a.row&&a.row<=t.range.endRow&&n(i)}}},X=class{constructor(e,t,n){this._codec=e,this._maxIndexedSpan=n,s(this,`_wholeSheet`,new Map),s(this,`_wholeCol`,new Map),s(this,`_wholeRow`,new Map),s(this,`_rowBuckets`,new Map),s(this,`_colBuckets`,new Map),s(this,`_largeRangeIds`,[]),s(this,`_sheetArr`,void 0),s(this,`_startRowArr`,void 0),s(this,`_endRowArr`,void 0),s(this,`_startColArr`,void 0),s(this,`_endColArr`,void 0),s(this,`_nodeArr`,void 0),s(this,`_kindArr`,void 0),s(this,`_activeArr`,void 0),s(this,`_rangeSeenEpochArr`,void 0),s(this,`_rangeEpoch`,1),s(this,`_nextRangeId`,0),s(this,`_freeRangeIds`,[]),s(this,`_nodeToRangeIds`,new Map),s(this,`_nodeToWholeSheetKeys`,new Map),s(this,`_nodeToWholeColKeys`,new Map),s(this,`_nodeToWholeRowKeys`,new Map);let r=Math.max(16,t);this._sheetArr=new Uint32Array(r),this._startRowArr=new Uint32Array(r),this._endRowArr=new Uint32Array(r),this._startColArr=new Uint32Array(r),this._endColArr=new Uint32Array(r),this._nodeArr=new Uint32Array(r),this._kindArr=new Uint8Array(r),this._activeArr=new Uint8Array(r),this._rangeSeenEpochArr=new Uint32Array(r)}reserveCapacity(e){this._ensureRangeCapacity(e)}addRange(e,t){let n=B(t),r=this._codec.encodeSheet(n.unitId,n.sheetId),i=V(n),a=H(n),o=a===this._codec.maxCols,s=i===this._codec.maxRows;if(o&&s){K(this._wholeSheet,r,e),U(this._nodeToWholeSheetKeys,e,r);return}if(s){for(let t=n.range.startColumn;t<=n.range.endColumn;t++){let n=this._codec.encodeColBySheetKey(r,t);K(this._wholeCol,n,e),U(this._nodeToWholeColKeys,e,n)}return}if(o){for(let t=n.range.startRow;t<=n.range.endRow;t++){let n=this._codec.encodeRowBySheetKey(r,t);K(this._wholeRow,n,e),U(this._nodeToWholeRowKeys,e,n)}return}let c=Math.min(i,a),l=this._allocRangeId();if(this._setRangeMeta(l,e,n),c>this._maxIndexedSpan)this._kindArr[l]=3,this._largeRangeIds.push(l);else if(i<=a){this._kindArr[l]=1;for(let e=n.range.startRow;e<=n.range.endRow;e++)U(this._rowBuckets,this._codec.encodeRowBySheetKey(r,e),l)}else{this._kindArr[l]=2;for(let e=n.range.startColumn;e<=n.range.endColumn;e++)U(this._colBuckets,this._codec.encodeColBySheetKey(r,e),l)}U(this._nodeToRangeIds,e,l)}removeNode(e){let t=this._nodeToWholeSheetKeys.get(e);if(t){for(let n=0;n<t.length;n++)q(this._wholeSheet,t[n],e);this._nodeToWholeSheetKeys.delete(e)}let n=this._nodeToWholeColKeys.get(e);if(n){for(let t=0;t<n.length;t++)q(this._wholeCol,n[t],e);this._nodeToWholeColKeys.delete(e)}let r=this._nodeToWholeRowKeys.get(e);if(r){for(let t=0;t<r.length;t++)q(this._wholeRow,r[t],e);this._nodeToWholeRowKeys.delete(e)}let i=this._nodeToRangeIds.get(e);if(i){for(let e=0;e<i.length;e++)this._removeRangeId(i[e]);this._nodeToRangeIds.delete(e)}}forEachPoint(e,t,n,r,i){let a=this._codec.encodeSheet(e,t);G(this._wholeSheet.get(a),i),G(this._wholeCol.get(this._codec.encodeColBySheetKey(a,r)),i),G(this._wholeRow.get(this._codec.encodeRowBySheetKey(a,n)),i);let o=this._rowBuckets.get(this._codec.encodeRowBySheetKey(a,n));if(o)for(let e=0;e<o.length;e++){let t=o[e];this._activeArr[t]&&this._rangeContainsPoint(t,a,n,r)&&i(this._nodeArr[t])}let s=this._colBuckets.get(this._codec.encodeColBySheetKey(a,r));if(s)for(let e=0;e<s.length;e++){let t=s[e];this._activeArr[t]&&this._rangeContainsPoint(t,a,n,r)&&i(this._nodeArr[t])}for(let e=0;e<this._largeRangeIds.length;e++){let t=this._largeRangeIds[e];this._activeArr[t]&&this._rangeContainsPoint(t,a,n,r)&&i(this._nodeArr[t])}}forEachRangeIntersecting(e,t){this.forEachRangesIntersecting([e],t)}forEachRangesIntersecting(e,t){if(e.length===0)return;let n=Array(e.length);for(let t=0;t<e.length;t++)n[t]=B(e[t]);this._nextRangeEpoch();for(let e=0;e<n.length;e++){let r=n[e],i=this._codec.encodeSheet(r.unitId,r.sheetId);G(this._wholeSheet.get(i),t),this._scanWholeCols(r,i,t),this._scanWholeRows(r,i,t),this._scanRowIndexedRanges(r,i,t),this._scanColIndexedRanges(r,i,t);for(let e=0;e<this._largeRangeIds.length;e++){let n=this._largeRangeIds[e];this._activeArr[n]&&(this._wasRangeSeen(n)||this._rangeIntersectsInput(n,r,i)&&(this._markRangeSeen(n),t(this._nodeArr[n])))}}}_allocRangeId(){let e=this._freeRangeIds.pop();if(e!==void 0)return e;let t=this._nextRangeId++;return this._ensureRangeCapacity(t+1),t}_ensureRangeCapacity(e){this._sheetArr=Y(this._sheetArr,e),this._startRowArr=Y(this._startRowArr,e),this._endRowArr=Y(this._endRowArr,e),this._startColArr=Y(this._startColArr,e),this._endColArr=Y(this._endColArr,e),this._nodeArr=Y(this._nodeArr,e),this._kindArr=J(this._kindArr,e),this._activeArr=J(this._activeArr,e),this._rangeSeenEpochArr=Y(this._rangeSeenEpochArr,e)}_setRangeMeta(e,t,n){this._sheetArr[e]=this._codec.encodeSheet(n.unitId,n.sheetId),this._startRowArr[e]=n.range.startRow,this._endRowArr[e]=n.range.endRow,this._startColArr[e]=n.range.startColumn,this._endColArr[e]=n.range.endColumn,this._nodeArr[e]=t,this._activeArr[e]=1}_removeRangeId(e){if(!this._activeArr[e])return;let t=this._kindArr[e],n=this._sheetArr[e];if(t===1)for(let t=this._startRowArr[e];t<=this._endRowArr[e];t++)W(this._rowBuckets,this._codec.encodeRowBySheetKey(n,t),e);else if(t===2)for(let t=this._startColArr[e];t<=this._endColArr[e];t++)W(this._colBuckets,this._codec.encodeColBySheetKey(n,t),e);else t===3&&We(this._largeRangeIds,e);this._activeArr[e]=0,this._kindArr[e]=0,this._freeRangeIds.push(e)}_nextRangeEpoch(){this._rangeEpoch++,this._rangeEpoch>=4294967295&&(this._rangeSeenEpochArr.fill(0),this._rangeEpoch=1)}_wasRangeSeen(e){return this._rangeSeenEpochArr[e]===this._rangeEpoch}_markRangeSeen(e){this._rangeSeenEpochArr[e]=this._rangeEpoch}_scanWholeCols(e,t,n){if(H(e)<=this._wholeCol.size){for(let r=e.range.startColumn;r<=e.range.endColumn;r++)G(this._wholeCol.get(this._codec.encodeColBySheetKey(t,r)),n);return}let r=this._codec.encodeColBySheetKey(t,e.range.startColumn),i=this._codec.encodeColBySheetKey(t,e.range.endColumn);for(let[e,t]of this._wholeCol)r<=e&&e<=i&&G(t,n)}_scanWholeRows(e,t,n){if(V(e)<=this._wholeRow.size){for(let r=e.range.startRow;r<=e.range.endRow;r++)G(this._wholeRow.get(this._codec.encodeRowBySheetKey(t,r)),n);return}let r=this._codec.encodeRowBySheetKey(t,e.range.startRow),i=this._codec.encodeRowBySheetKey(t,e.range.endRow);for(let[e,t]of this._wholeRow)r<=e&&e<=i&&G(t,n)}_scanRowIndexedRanges(e,t,n){if(V(e)<=this._rowBuckets.size){for(let r=e.range.startRow;r<=e.range.endRow;r++)this._scanRangeIdBucket(this._rowBuckets.get(this._codec.encodeRowBySheetKey(t,r)),e,t,n);return}let r=this._codec.encodeRowBySheetKey(t,e.range.startRow),i=this._codec.encodeRowBySheetKey(t,e.range.endRow);for(let[a,o]of this._rowBuckets)r<=a&&a<=i&&this._scanRangeIdBucket(o,e,t,n)}_scanColIndexedRanges(e,t,n){if(H(e)<=this._colBuckets.size){for(let r=e.range.startColumn;r<=e.range.endColumn;r++)this._scanRangeIdBucket(this._colBuckets.get(this._codec.encodeColBySheetKey(t,r)),e,t,n);return}let r=this._codec.encodeColBySheetKey(t,e.range.startColumn),i=this._codec.encodeColBySheetKey(t,e.range.endColumn);for(let[a,o]of this._colBuckets)r<=a&&a<=i&&this._scanRangeIdBucket(o,e,t,n)}_scanRangeIdBucket(e,t,n,r){if(e)for(let i=0;i<e.length;i++){let a=e[i];this._activeArr[a]&&(this._wasRangeSeen(a)||this._rangeIntersectsInput(a,t,n)&&(this._markRangeSeen(a),r(this._nodeArr[a])))}}_rangeContainsPoint(e,t,n,r){return this._sheetArr[e]===t&&this._startRowArr[e]<=n&&n<=this._endRowArr[e]&&this._startColArr[e]<=r&&r<=this._endColArr[e]}_rangeIntersectsInput(e,t,n){return this._sheetArr[e]===n&&this._startRowArr[e]<=t.range.endRow&&this._endRowArr[e]>=t.range.startRow&&this._startColArr[e]<=t.range.endColumn&&this._endColArr[e]>=t.range.startColumn}},$e=class{constructor(e){var t,n,r,i;s(this,`codec`,void 0),s(this,`_maxIndexedSpan`,void 0),s(this,`_pointScanCellLimit`,void 0),s(this,`_initialNodeCapacity`,void 0),s(this,`_initialRangeCapacity`,void 0),s(this,`directDeps`,void 0),s(this,`nodeDeps`,void 0),s(this,`rangeIndex`,void 0),s(this,`cellFormulaToIndex`,void 0),s(this,`otherFormulaToIndex`,void 0),s(this,`featureCalculationToIndex`,void 0),s(this,`indexToNodeId`,void 0),s(this,`dirty`,void 0),s(this,`inQueue`,void 0),s(this,`_indexToNodeType`,void 0),s(this,`_cellPrecedents`,void 0),s(this,`_rangePrecedents`,void 0),s(this,`_nodePrecedents`,void 0),s(this,`_dynamicDeps`,void 0),s(this,`_dynamicSignature`,void 0),s(this,`_runtimeDirectDeps`,void 0),s(this,`_runtimeNodeDeps`,void 0),s(this,`_runtimeRangeIndex`,void 0),s(this,`_runtimeCellPrecedents`,void 0),s(this,`_runtimeRangePrecedents`,void 0),s(this,`_runtimeNodePrecedents`,void 0),s(this,`_activeNode`,void 0),s(this,`_seenNodeEpoch`,void 0),s(this,`_visitNodeEpoch`,void 0),s(this,`_edgeSeenEpoch`,void 0),s(this,`_tarjanSeenEpoch`,void 0),s(this,`_tarjanIndexArr`,void 0),s(this,`_tarjanLowArr`,void 0),s(this,`_tarjanOnStack`,void 0),s(this,`_emitEpoch`,1),s(this,`_visitEpoch`,1),s(this,`_edgeEpoch`,1),s(this,`_tarjanEpoch`,1),s(this,`_propQueue`,[]),s(this,`_dirtyList`,[]),s(this,`_activeNodeCount`,0),s(this,`_dirtyNodeCount`,0),s(this,`_directPointIndex`,void 0),s(this,`_runtimeDirectPointIndex`,void 0),s(this,`_formulaCellIndex`,void 0),s(this,`_sharedFormulaGroups`,void 0),s(this,`_sharedFormulaGroupIndexById`,void 0),s(this,`_sharedFormulaMembershipByNode`,void 0),s(this,`_sharedFormulaSourceEntries`,void 0),s(this,`_sharedFormulaSourceRangeIndex`,void 0),this._maxIndexedSpan=(t=e.maxIndexedSpan)==null?4096:t,this._pointScanCellLimit=(n=e.pointScanCellLimit)==null?4096:n,this._initialNodeCapacity=Math.max(16,(r=e.initialNodeCapacity)==null?1024:r),this._initialRangeCapacity=Math.max(16,(i=e.initialRangeCapacity)==null?1024:i),this.codec=new Be(e.maxRows,e.maxCols),this.reset()}reset(){this.codec.reset(),this.directDeps=new Map,this.nodeDeps=new Map,this.rangeIndex=new X(this.codec,this._initialRangeCapacity,this._maxIndexedSpan),this._runtimeDirectDeps=new Map,this._runtimeNodeDeps=new Map,this._runtimeRangeIndex=new X(this.codec,this._initialRangeCapacity,this._maxIndexedSpan),this.cellFormulaToIndex=new Map,this.otherFormulaToIndex=new Map,this.featureCalculationToIndex=new Map,this.indexToNodeId=[],this._indexToNodeType=new Uint8Array(this._initialNodeCapacity),this.dirty=new Uint8Array(this._initialNodeCapacity),this.inQueue=new Uint8Array(this._initialNodeCapacity),this._activeNode=new Uint8Array(this._initialNodeCapacity),this._cellPrecedents=[],this._rangePrecedents=[],this._nodePrecedents=[],this._dynamicDeps=[],this._dynamicSignature=[],this._runtimeCellPrecedents=[],this._runtimeRangePrecedents=[],this._runtimeNodePrecedents=[],this._seenNodeEpoch=new Uint32Array(this._initialNodeCapacity),this._visitNodeEpoch=new Uint32Array(this._initialNodeCapacity),this._edgeSeenEpoch=new Uint32Array(this._initialNodeCapacity),this._tarjanSeenEpoch=new Uint32Array(this._initialNodeCapacity),this._tarjanIndexArr=new Uint32Array(this._initialNodeCapacity),this._tarjanLowArr=new Uint32Array(this._initialNodeCapacity),this._tarjanOnStack=new Uint8Array(this._initialNodeCapacity),this._emitEpoch=1,this._visitEpoch=1,this._edgeEpoch=1,this._tarjanEpoch=1,this._propQueue.length=0,this._dirtyList.length=0,this._activeNodeCount=0,this._dirtyNodeCount=0,this._directPointIndex=new Qe(this.codec,this._pointScanCellLimit),this._runtimeDirectPointIndex=new Qe(this.codec,this._pointScanCellLimit),this._formulaCellIndex=new Ze(this.codec,this.indexToNodeId),this._sharedFormulaGroups=[],this._sharedFormulaGroupIndexById=new Map,this._sharedFormulaMembershipByNode=new Int32Array(this._initialNodeCapacity),this._sharedFormulaMembershipByNode.fill(-1),this._sharedFormulaSourceEntries=[],this._sharedFormulaSourceRangeIndex=new X(this.codec,this._initialRangeCapacity,this._maxIndexedSpan)}encodeCell(e,t,n,r){return this.codec.encodeCell(e,t,n,r)}reserveDependencyCapacity(e,t=e){this._ensureNodeCapacity(e),this.rangeIndex.reserveCapacity(t),this._runtimeRangeIndex.reserveCapacity(t),this._sharedFormulaSourceRangeIndex.reserveCapacity(t)}decodeCell(e){return this.codec.decodeCell(e)}encodeFeatureCalculationId(e,t,n){return`${e}${t}${n}`}decodeFeatureCalculationId(e){let t=this._tryDecodeFeatureCalculationId(e);if(t===void 0)throw Error(`Invalid feature calculation id: ${String(e)}`);return t}encodeOtherFormulaId(e,t,n,r,i){return`${e}${t}${n}${r}${i}`}decodeOtherFormulaId(e){let t=this._tryDecodeOtherFormulaId(e);if(t===void 0)throw Error(`Invalid other formula id: ${String(e)}`);return t}setCellFormulaDeps(e,t,n){var r,i;return this._setCalcNodeDepsByType(1,e,t,(r=n==null?void 0:n.checkCycle)==null?!0:r,(i=n==null?void 0:n.markDirty)==null?!0:i,(n==null?void 0:n.mode)===`merge`)}setNewCellFormulaDeps(e,t){let n=this.cellFormulaToIndex.get(e);if(n!==void 0&&this._activeNode[n]===1)return this.setCellFormulaDeps(e,t,{checkCycle:!1,markDirty:!1});let r=this._getOrCreateNodeIndexByType(1,e),i=this._normalizeCalcNodeDeps(t),a=this._resolveExplicitNodeDeps(i.nodes);return this._formulaCellIndex.addFormulaCell(e,r),this._activeNodeCount++,this._activeNode[r]=1,this._addNewNodeDepsOnly(r,i.cells,i.ranges,a),i.dynamics.length>0&&this._setNodeDynamicDeps(r,i.dynamics),{nodeIndex:r,hasCycle:!1}}setNewCellFormulaNodeOnly(e){let t=this.cellFormulaToIndex.get(e);if(t!==void 0&&this._activeNode[t]===1)return this.setCellFormulaDeps(e,{},{checkCycle:!1,markDirty:!1});let n=this._getOrCreateNodeIndexByType(1,e);return this._formulaCellIndex.addFormulaCell(e,n),this._activeNodeCount++,this._activeNode[n]=1,{nodeIndex:n,hasCycle:!1}}setNewCellFormulaNodeOnlyRange(e,t,n,r){let i=this.codec.encodeSheet(e,t),a=i*this.codec.sheetSize,o=[];for(let e=n.startRow;e<=n.endRow;e++){let t=a+e*this.codec.maxCols;for(let a=n.startColumn;a<=n.endColumn;a++){if(r!=null&&r.row===e&&r.col===a)continue;let n=t+a,s=this.cellFormulaToIndex.get(n);if(s!==void 0&&this._activeNode[s]===1){o.push(this.setCellFormulaDeps(n,{},{checkCycle:!1,markDirty:!1}).nodeIndex);continue}let c=this._getOrCreateNodeIndexByType(1,n);this._formulaCellIndex.addFormulaCellByPosition(i,e,a,c),this._activeNodeCount++,this._activeNode[c]=1,o.push(c)}}return o}setOtherFormulaDeps(e,t,n){var r,i;return this._setCalcNodeDepsByType(2,e,t,(r=n==null?void 0:n.checkCycle)==null?!0:r,(i=n==null?void 0:n.markDirty)==null?!0:i,(n==null?void 0:n.mode)===`merge`)}setFeatureCalculationDeps(e,t,n){var r,i;return this._setCalcNodeDepsByType(3,e,t,(r=n==null?void 0:n.checkCycle)==null?!0:r,(i=n==null?void 0:n.markDirty)==null?!0:i,(n==null?void 0:n.mode)===`merge`)}setCalcNodeDeps(e,t,n){var r,i;return this._setCalcNodeDepsByType(e.type,e.id,t,(r=n==null?void 0:n.checkCycle)==null?!0:r,(i=n==null?void 0:n.markDirty)==null?!0:i,(n==null?void 0:n.mode)===`merge`)}registerCompressedSharedFormulaGroup(e){var t;this.unregisterCompressedSharedFormulaGroup(e.groupId);let n=this._sharedFormulaGroups.length,r=B(e.fillRange),i={...r,range:{...r.range}},a={groupId:e.groupId,fillRange:i,patterns:e.patterns.slice(),sourceEntryIds:[],memberNodeIndices:(t=e.memberNodeIndices)==null?void 0:t.slice()};this._sharedFormulaGroups.push(a),this._sharedFormulaGroupIndexById.set(a.groupId,n),e.memberNodeIndices==null?this._markCompressedSharedFormulaMembership(n,i):this._markCompressedSharedFormulaMembershipByNodeIndices(n,e.memberNodeIndices);for(let e=0;e<a.patterns.length;e++){let t=this._getCompressedSharedSourceCoverage(i,a.patterns[e]),r=this._sharedFormulaSourceEntries.length;this._sharedFormulaSourceEntries.push({groupIndex:n,patternIndex:e,sourceCoverage:t,active:!0}),a.sourceEntryIds.push(r),this._sharedFormulaSourceRangeIndex.addRange(r,t)}}unregisterCompressedSharedFormulaGroup(e){let t=this._sharedFormulaGroupIndexById.get(e);if(t===void 0)return;let n=this._sharedFormulaGroups[t];this._sharedFormulaGroupIndexById.delete(e);for(let e=0;e<n.sourceEntryIds.length;e++){let t=n.sourceEntryIds[e],r=this._sharedFormulaSourceEntries[t];r&&(r.active=!1),this._sharedFormulaSourceRangeIndex.removeNode(t)}n.memberNodeIndices==null?this._clearCompressedSharedFormulaMembership(t,n.fillRange):this._clearCompressedSharedFormulaMembershipByNodeIndices(t,n.memberNodeIndices)}clearCompressedSharedFormulaGroups(e,t){let n=[];for(let r=0;r<this._sharedFormulaGroups.length;r++){let i=this._sharedFormulaGroups[r];this._sharedFormulaGroupIndexById.has(i.groupId)&&(e!==void 0&&i.fillRange.unitId!==e||t!==void 0&&i.fillRange.sheetId!==t||n.push(i.groupId))}for(let e=0;e<n.length;e++)this.unregisterCompressedSharedFormulaGroup(n[e])}_setCalcNodeDepsByType(e,t,n,r,i,a){var o,s,c,l,u,d,f;let p=this._getOrCreateNodeIndexByType(e,t),m=this._activeNode[p]===1,h=m&&e===1&&!this._isEmptyCalcNodeDeps(n)&&this._sharedFormulaMembershipByNode[p]>=0,g=m&&(r||a),_=g?(o=(s=this._cellPrecedents[p])==null?void 0:s.slice())==null?[]:o:[],v=g?(c=(l=this._rangePrecedents[p])==null?void 0:l.slice())==null?[]:c:[],y=g?(u=(d=this._nodePrecedents[p])==null?void 0:d.slice())==null?[]:u:[];m&&this._removeNodeDepsOnly(p);let b=this._normalizeCalcNodeDeps(n),x=b.cells,S=b.ranges,C=b.nodes,w=this._resolveExplicitNodeDeps(C),T=(f=this._dynamicDeps[p])==null?[]:f,ee=a?this._mergeDynamicDeps(T,b.dynamics):b.dynamics,E=a?this._mergeSortedUniqueNumbers(_,x):x,te=a?this._mergeRangeDeps(v,S):S,ne=a?this._mergeSortedUniqueNumbers(y,w):w;return r&&this._wouldCreateCycleForNewDeps(p,E,te,ne)?(m&&this._addNodeDepsOnly(p,_,v,y),{nodeIndex:p,hasCycle:!0}):(h&&this._unregisterCompressedSharedFormulaGroupByNode(p),!m&&e===1&&(Ve(t),this._formulaCellIndex.addFormulaCell(t,p)),m||this._activeNodeCount++,this._activeNode[p]=1,this._addNodeDepsOnly(p,E,te,ne),this._setNodeDynamicDeps(p,ee),i&&(this._markNodeIndexDirty(p,!0),this._propagateDirtyQueue()),{nodeIndex:p,hasCycle:!1})}setManyCalcNodeDeps(e,t){var n,r;let i=(n=t==null?void 0:t.markDirty)==null?!0:n,a=(r=t==null?void 0:t.checkCycle)==null?!0:r,o=(t==null?void 0:t.mode)===`merge`,s=Array(e.length),c=[];for(let t=0;t<e.length;t++){let n=e[t],r=this._setCalcNodeDepsByType(n.node.type,n.node.id,n.deps,a,!1,o);s[t]=r,r.hasCycle||c.push(r.nodeIndex)}return i&&c.length>0&&this._markCalcNodeIndicesChanged(c),s}setManyCellFormulaDeps(e,t){var n,r;let i=(n=t==null?void 0:t.markDirty)==null?!0:n,a=(r=t==null?void 0:t.checkCycle)==null?!0:r,o=(t==null?void 0:t.mode)===`merge`,s=Array(e.length),c=[];for(let t=0;t<e.length;t++){let n=e[t],r=this._setCalcNodeDepsByType(1,n.cell,n.deps,a,!1,o);s[t]=r,r.hasCycle||c.push(r.nodeIndex)}return i&&c.length>0&&this._markCalcNodeIndicesChanged(c),s}setManyOtherFormulaDeps(e,t){var n,r;let i=(n=t==null?void 0:t.markDirty)==null?!0:n,a=(r=t==null?void 0:t.checkCycle)==null?!0:r,o=(t==null?void 0:t.mode)===`merge`,s=Array(e.length),c=[];for(let t=0;t<e.length;t++){let n=e[t],r=this._setCalcNodeDepsByType(2,n.id,n.deps,a,!1,o);s[t]=r,r.hasCycle||c.push(r.nodeIndex)}return i&&c.length>0&&this._markCalcNodeIndicesChanged(c),s}setManyFeatureCalculationDeps(e,t){var n,r;let i=(n=t==null?void 0:t.markDirty)==null?!0:n,a=(r=t==null?void 0:t.checkCycle)==null?!0:r,o=(t==null?void 0:t.mode)===`merge`,s=Array(e.length),c=[];for(let t=0;t<e.length;t++){let n=e[t],r=this._setCalcNodeDepsByType(3,n.id,n.deps,a,!1,o);s[t]=r,r.hasCycle||c.push(r.nodeIndex)}return i&&c.length>0&&this._markCalcNodeIndicesChanged(c),s}removeCellFormula(e,t){this._removeCalcNodeByType(1,e,t)}removeOtherFormula(e,t){this._removeCalcNodeByType(2,e,t)}removeFeatureCalculation(e,t){this._removeCalcNodeByType(3,e,t)}removeCellFormulas(e,t){this._removeCalcNodeIds(1,e,t)}removeOtherFormulas(e,t){this._removeCalcNodeIds(2,e,t)}removeFeatureCalculations(e,t){this._removeCalcNodeIds(3,e,t)}removeCalcNodes(e,t){if(e.length===0)return;let n=[];for(let t=0;t<e.length;t++){let r=e[t],i=this._getNodeIndexByType(r.type,r.id);i!==void 0&&this._activeNode[i]&&n.push(i)}this._removeCalcNodeIndices(n,t)}clearCellFormulas(e,t,n){let r=[];for(let[n,i]of this.cellFormulaToIndex){if(!this._activeNode[i])continue;let a=this.codec.decodeCell(n);a.unitId===e&&(t!==void 0&&a.sheetId!==t||r.push(i))}this._removeCalcNodeIndices(r,n)}clearOtherFormulas(e,t,n,r,i,a){if(n!==void 0&&n.length===0)return;let o=[];for(let[a,s]of this.otherFormulaToIndex){if(!this._activeNode[s])continue;let c=this._tryDecodeOtherFormulaId(a);c!==void 0&&c.unitId===e&&(t!==void 0&&c.sheetId!==t||n!==void 0&&!this._includesFormulaId(n,c.formulaId)||r!==void 0&&c.refOffsetX!==r||r!==void 0&&i!==void 0&&c.refOffsetY!==i||o.push(s))}this._removeCalcNodeIndices(o,a)}_includesFormulaId(e,t){for(let n=0;n<e.length;n++)if(e[n]===t)return!0;return!1}clearFeatureCalculations(e,t,n){let r=[];for(let[n,i]of this.featureCalculationToIndex){if(!this._activeNode[i])continue;let a=this._tryDecodeFeatureCalculationId(n);a!==void 0&&a.unitId===e&&(t!==void 0&&a.sheetId!==t||r.push(i))}this._removeCalcNodeIndices(r,n)}_tryDecodeFeatureCalculationId(e){if(typeof e!=`string`)return;let t=e.indexOf(`\0`);if(t<=0)return;let n=e.indexOf(`\0`,t+1);if(!(n<=t+1)&&n!==e.length-1&&e.indexOf(`\0`,n+1)===-1)return{unitId:e.slice(0,t),sheetId:e.slice(t+1,n),formulaId:e.slice(n+1)}}_tryDecodeOtherFormulaId(e){if(typeof e!=`string`)return;let t=e.indexOf(`\0`);if(t<=0)return;let n=e.indexOf(`\0`,t+1);if(n<=t+1)return;let r=e.indexOf(`\0`,n+1);if(r<=n+1)return;let i=e.indexOf(`\0`,r+1);if(i<=r+1||i===e.length-1||e.indexOf(`\0`,i+1)!==-1)return;let a=Number(e.slice(r+1,i)),o=Number(e.slice(i+1));if(!(!Number.isFinite(a)||!Number.isFinite(o)))return{unitId:e.slice(0,t),sheetId:e.slice(t+1,n),formulaId:e.slice(n+1,r),refOffsetX:a,refOffsetY:o}}_removeCalcNodeIds(e,t,n){if(t.length===0)return;let r=[];for(let n=0;n<t.length;n++){let i=this._getNodeIndexByType(e,t[n]);i!==void 0&&this._activeNode[i]&&r.push(i)}this._removeCalcNodeIndices(r,n)}_removeCalcNodeIndices(e,t){if(e.length!==0){if(t!=null&&t.markDependentsDirty&&this._markCalcNodeIndicesChanged(e),t!=null&&t.detachDependents)for(let t=0;t<e.length;t++)this._detachDependentsFromNode(e[t]);for(let t=0;t<e.length;t++)this._removeCalcNodeByIndex(e[t])}}removeCalcNode(e,t){this._removeCalcNodeByType(e.type,e.id,t)}_removeCalcNodeByType(e,t,n){let r=this._getNodeIndexByType(e,t);r!==void 0&&this._activeNode[r]&&(n!=null&&n.markDependentsDirty&&(this._markNodeIndexDirty(r,!0),this._propagateDirtyQueue()),n!=null&&n.detachDependents&&this._detachDependentsFromNode(r),this._removeCalcNodeByIndex(r))}_removeCalcNodeByIndex(e){if(this._activeNode[e]){if(this._unregisterCompressedSharedFormulaGroupByNode(e),this._removeNodeDepsOnly(e),this._removeRuntimeDepsOnly(e),this._dynamicDeps[e]=void 0,this._dynamicSignature[e]=void 0,this._indexToNodeType[e]===1){let t=this.indexToNodeId[e];this._formulaCellIndex.removeFormulaCell(t,e)}this._activeNode[e]=0,this._activeNodeCount--,this.dirty[e]&&(this.dirty[e]=0,this._dirtyNodeCount--,this._compactDirtyList()),this.inQueue[e]=0}}markCellChanged(e){this.markCellsChanged([e])}markCellsChanged(e){this._nextEmitEpoch();for(let t of e)this._forEachDependentIndexByCellRaw(t,e=>{this._emitNodeOnceAndMarkDirty(e)});this._propagateDirtyQueue()}markRangeChanged(e,t){this.markRangesChanged([e],t)}markRangesChanged(e,t){if(e.length===0)return;let n=(t==null?void 0:t.coalesce)===!1?this._normalizeRangeDeps(e):Je(e);this._nextEmitEpoch();for(let e=0;e<n.length;e++){let r=n[e];t!=null&&t.includeFormulaCells&&this._formulaCellIndex.forEachFormulaInRange(r,e=>{this._emitNodeOnceAndMarkDirty(e,!0)}),this._directPointIndex.forEachCellInRange(r,e=>{G(this.directDeps.get(e),e=>{this._emitNodeOnceAndMarkDirty(e)})}),this._runtimeDirectPointIndex.forEachCellInRange(r,e=>{G(this._runtimeDirectDeps.get(e),e=>{this._emitNodeOnceAndMarkDirty(e)})})}this._isEveryActiveNodeDirty()||this.rangeIndex.forEachRangesIntersecting(n,e=>{this._emitNodeOnceAndMarkDirty(e)}),this._isEveryActiveNodeDirty()||this._runtimeRangeIndex.forEachRangesIntersecting(n,e=>{this._emitNodeOnceAndMarkDirty(e)});for(let e=0;e<n.length&&!this._isEveryActiveNodeDirty();e++)this._forEachCompressedSharedDependentByRange(n[e],e=>{this._emitNodeOnceAndMarkDirty(e)});this._propagateDirtyQueue()}markCellFormulaChanged(e){this._markCalcNodeChangedByType(1,e)}markOtherFormulaChanged(e){this._markCalcNodeChangedByType(2,e)}markOtherFormulasChanged(e,t,n){if(!(n!==void 0&&n.length===0)){this._nextEmitEpoch();for(let[r,i]of this.otherFormulaToIndex){if(!this._activeNode[i])continue;let a=this._tryDecodeOtherFormulaId(r);a!==void 0&&a.unitId===e&&(t!==void 0&&a.sheetId!==t||n!==void 0&&!this._includesFormulaId(n,a.formulaId)||this._emitNodeOnceAndMarkDirty(i,!0))}this._propagateDirtyQueue()}}markFeatureCalculationChanged(e){this._markCalcNodeChangedByType(3,e)}markCalcNodeChanged(e){this._markCalcNodeChangedByType(e.type,e.id)}_markCalcNodeChangedByType(e,t){let n=this._getNodeIndexByType(e,t);n!==void 0&&this._activeNode[n]&&(this._markNodeIndexDirty(n,!0),this._propagateDirtyQueue())}markCalcNodesChanged(e){if(e.length!==0){this._nextEmitEpoch();for(let t=0;t<e.length;t++){let n=e[t],r=this._getNodeIndexByType(n.type,n.id);r!==void 0&&this._activeNode[r]&&this._emitNodeOnceAndMarkDirty(r,!0)}this._propagateDirtyQueue()}}markAllDirty(){this._nextEmitEpoch();for(let e=0;e<this.indexToNodeId.length;e++)this._activeNode[e]&&this._emitNodeOnceAndMarkDirty(e,!0);this._propagateDirtyQueue()}hasDynamicDeps(e){let t=this.getNodeIndex(e);if(t===void 0)return!1;let n=this._dynamicDeps[t];return n!==void 0&&n.length>0}refreshDynamicDeps(e,t){let n=this.getNodeIndex(e);if(n===void 0||!this._activeNode[n])return!1;let r=this._dynamicDeps[n];if(!r||r.length===0)return!1;let i={cells:[],ranges:[],nodes:[]},a=[];for(let n=0;n<r.length;n++){var o;let s=r[n],c=t(e,s),l=(o=c.status)==null?`resolved`:o;a.push(`${String(s.id)}:${l}:${c.signature}`),this._collectDynamicResolveResult(i,c)}i.cells=Ue(i.cells),i.ranges=this._normalizeRangeDeps(i.ranges),i.nodes=this._mergeSortedUniqueNumbers([],i.nodes);let s=a.join(`|`),c=this._dynamicSignature[n];return this._removeRuntimeDepsOnly(n),this._addRuntimeDepsOnly(n,i.cells,i.ranges,i.nodes),this._dynamicSignature[n]=s,s===c?!1:(this._markNodeIndexDirty(n,!0),this._propagateDirtyQueue(),!0)}prepareDynamicDependencies(e){let t=this._getDirtyNodeIndicesSnapshot(),n=!1;for(let r=0;r<t.length;r++){let i=t[r],a=this._dynamicDeps[i];!a||a.length===0||this.refreshDynamicDeps(this.getNodeRefByIndex(i),e)&&(n=!0)}return n}getCalculationOrder(e){let t=this._getDirtyNodeIndicesSnapshot();if(t.length===0)return{hasCycle:!1,calculationForest:[]};let n=this._buildDirtyCalculationGraph(t);return{hasCycle:n.hasCycle,calculationForest:n.calculationForest}}clearCalculatedDirty(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];this.dirty[r]&&(this.dirty[r]=0,this._dirtyNodeCount--,t=!0)}t&&this._compactDirtyList()}_compactDirtyList(){let e=0;for(let t=0;t<this._dirtyList.length;t++){let n=this._dirtyList[t];this.dirty[n]&&this._activeNode[n]&&(this._dirtyList[e++]=n)}this._dirtyList.length=e}clearAllDirty(){for(let e=0;e<this._dirtyList.length;e++)this.dirty[this._dirtyList[e]]=0;this._dirtyList.length=0,this._dirtyNodeCount=0}getDirtyNodeIndices(){return this._getDirtyNodeIndicesSnapshot()}getDirtyNodes(){let e=this._getDirtyNodeIndicesSnapshot(),t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=this.getNodeRefByIndex(e[n]);return t}forEachDependentByCell(e,t){this._nextEmitEpoch(),this._forEachDependentIndexByCellRaw(e,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)})}forEachDependentByRange(e,t){this._nextEmitEpoch(),this._directPointIndex.forEachCellInRange(e,e=>{G(this.directDeps.get(e),e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)})}),this._runtimeDirectPointIndex.forEachCellInRange(e,e=>{G(this._runtimeDirectDeps.get(e),e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)})}),this.rangeIndex.forEachRangeIntersecting(e,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}),this._runtimeRangeIndex.forEachRangeIntersecting(e,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}),this._forEachCompressedSharedDependentByRange(e,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)})}forEachDependentByNode(e,t){let n=this.getNodeIndex(e);n!==void 0&&(this._nextEmitEpoch(),this._forEachDependentOfNodeRaw(n,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}))}forEachDependentByIndex(e,t){this._activeNode[e]&&(this._nextEmitEpoch(),this._forEachDependentOfNodeRaw(e,e=>{this._activeNode[e]&&this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}))}forEachPrecedentNode(e,t){let n=this.getNodeIndex(e);n!==void 0&&this._activeNode[n]&&(this._nextEmitEpoch(),this._forEachPrecedentNodeIndex(n,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}))}forEachPrecedentNodeByIndex(e,t){this._activeNode[e]&&(this._nextEmitEpoch(),this._forEachPrecedentNodeIndex(e,e=>{this._emitNodeOnce(e)&&t(this.getNodeRefByIndex(e),e)}))}hasUncalculatedDirtyPrecedentByIndex(e,t){if(!this._activeNode[e])return!1;let n=!1;return this._nextEmitEpoch(),this._forEachPrecedentNodeIndex(e,e=>{if(!n&&this.dirty[e]&&!t.has(e))return n=!0,!1}),n}wouldCreateCycle(e,t){let n=this._getOrCreateNodeIndex(e),r=this._normalizeCalcNodeDeps(t),i=r.cells,a=r.ranges,o=r.nodes,s=this._resolveExplicitNodeDeps(o);return this._wouldCreateCycleForNewDeps(n,i,a,s)}_normalizeCalcNodeDeps(e){let t=[],n=[],r=[];return this._collectStaticDeps(e,t,n,r),{cells:Ue(t),ranges:this._normalizeRangeDeps(n),nodes:qe(r),dynamics:e.dynamics?e.dynamics.slice():[]}}_collectStaticDeps(e,t,n,r){if(e&&(e.cells&&t.push(...e.cells),e.ranges&&n.push(...e.ranges),e.nodes&&r.push(...e.nodes),e.dynamics))for(let i=0;i<e.dynamics.length;i++)this._collectStaticDeps(e.dynamics[i].paramDeps,t,n,r)}_mergeDynamicDeps(e,t){if(e.length===0)return t;if(t.length===0)return e;let n=e.slice();for(let e=0;e<t.length;e++){let r=t[e],i=!1;for(let e=0;e<n.length;e++)if(n[e].id===r.id){i=!0;break}i||n.push(r)}return n}_setNodeDynamicDeps(e,t){let n=this._dynamicDeps[e];n===void 0&&t.length===0||this._isSameDynamicDeps(n,t)||(this._removeRuntimeDepsOnly(e),this._dynamicSignature[e]=void 0,this._dynamicDeps[e]=t.length>0?t:void 0)}_isSameDynamicDeps(e,t){var n;if(((n=e==null?void 0:e.length)==null?0:n)!==t.length)return!1;if(!e)return t.length===0;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}_normalizeRangeDeps(e){if(!e||e.length===0)return[];let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=B(e[n]);return t}_mergeSortedUniqueNumbers(e,t){if(e.length===0)return t;if(t.length===0)return e;let n=[],r=0,i=0;for(;r<e.length&&i<t.length;){let a=e[r],o=t[i];a===o?(n.push(a),r++,i++):a<o?(n.push(a),r++):(n.push(o),i++)}for(;r<e.length;)n.push(e[r++]);for(;i<t.length;)n.push(t[i++]);return n}_mergeRangeDeps(e,t){if(e.length===0)return t;if(t.length===0)return e;let n=e.slice();for(let e=0;e<t.length;e++){let r=t[e];this._containsRange(n,r)||n.push(r)}return n}_containsRange(e,t){for(let n=0;n<e.length;n++)if(this._isSameRange(e[n],t))return!0;return!1}_isSameRange(e,t){return e.unitId===t.unitId&&e.sheetId===t.sheetId&&e.range.startRow===t.range.startRow&&e.range.endRow===t.range.endRow&&e.range.startColumn===t.range.startColumn&&e.range.endColumn===t.range.endColumn}canReachNode(e,t){let n=this.getNodeIndex(e),r=this.getNodeIndex(t);return n===void 0||r===void 0?!1:this._canReachNodeIndex(n,r)}hasCellFormula(e){let t=this.cellFormulaToIndex.get(e);return t!==void 0&&this._activeNode[t]===1}hasOtherFormula(e){let t=this.otherFormulaToIndex.get(e);return t!==void 0&&this._activeNode[t]===1}hasFeatureCalculation(e){let t=this.featureCalculationToIndex.get(e);return t!==void 0&&this._activeNode[t]===1}getNodeIndex(e){return this._getNodeIndexByType(e.type,e.id)}_getNodeIndexByType(e,t){switch(e){case 1:return Ve(t),this.cellFormulaToIndex.get(t);case 2:return this.otherFormulaToIndex.get(t);case 3:return this.featureCalculationToIndex.get(t);default:return}}getNodeRefByIndex(e){return{type:this._indexToNodeType[e],id:this.indexToNodeId[e]}}markCalcNodeIndicesChanged(e,t){this._markCalcNodeIndicesChanged(e,t)}_markCalcNodeIndicesChanged(e,t){if(e.length===0)return;this._nextEmitEpoch();let n=(t==null?void 0:t.onlySelf)!==!0;for(let t=0;t<e.length;t++){let r=e[t];this._activeNode[r]&&this._emitNodeOnceAndMarkDirty(r,n,n)}n&&this._propagateDirtyQueue()}_getOrCreateNodeIndex(e){return this._getOrCreateNodeIndexByType(e.type,e.id)}_getOrCreateNodeIndexByType(e,t){let n=this._getNodeIndexByType(e,t);if(n!==void 0)return n;let r=this.indexToNodeId.length;switch(this.indexToNodeId.push(t),this._ensureNodeCapacity(r+1),this._indexToNodeType[r]=e,e){case 1:Ve(t),this.cellFormulaToIndex.set(t,r);break;case 2:this.otherFormulaToIndex.set(t,r);break;case 3:this.featureCalculationToIndex.set(t,r);break;default:throw Error(`Unknown CalcNodeType: ${e}`)}return r}_ensureNodeCapacity(e){let t=this._sharedFormulaMembershipByNode.length;this._indexToNodeType=J(this._indexToNodeType,e),this.dirty=J(this.dirty,e),this.inQueue=J(this.inQueue,e),this._activeNode=J(this._activeNode,e),this._seenNodeEpoch=Y(this._seenNodeEpoch,e),this._visitNodeEpoch=Y(this._visitNodeEpoch,e),this._edgeSeenEpoch=Y(this._edgeSeenEpoch,e),this._tarjanSeenEpoch=Y(this._tarjanSeenEpoch,e),this._tarjanIndexArr=Y(this._tarjanIndexArr,e),this._tarjanLowArr=Y(this._tarjanLowArr,e),this._tarjanOnStack=J(this._tarjanOnStack,e),this._sharedFormulaMembershipByNode=this._growIntThirtyTwoArray(this._sharedFormulaMembershipByNode,e,-1),this._sharedFormulaMembershipByNode.length>t&&this._sharedFormulaMembershipByNode.fill(-1,t)}_growIntThirtyTwoArray(e,t,n){if(e.length>=t)return e;let r=Math.max(16,e.length);for(;r<t;)r*=2;let i=new Int32Array(r);return i.fill(n),i.set(e),i}_resolveExplicitNodeDeps(e){if(e.length===0)return[];let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.type===2)throw Error(`OtherFormula cannot be used as a dependency`);let i=this._getOrCreateNodeIndex(r);t.push(i)}if(t.length<=1)return t;t.sort((e,t)=>e-t);let n=1;for(let e=1;e<t.length;e++)t[e]!==t[n-1]&&(t[n++]=t[e]);return t.length=n,t}_isEmptyCalcNodeDeps(e){return(e.cells==null||e.cells.length===0)&&(e.ranges==null||e.ranges.length===0)&&(e.nodes==null||e.nodes.length===0)&&(e.dynamics==null||e.dynamics.length===0)}_unregisterCompressedSharedFormulaGroupByNode(e){let t=this._sharedFormulaMembershipByNode[e];if(t<0)return;let n=this._sharedFormulaGroups[t];if(n==null||!this._sharedFormulaGroupIndexById.has(n.groupId)){this._sharedFormulaMembershipByNode[e]=-1;return}this.unregisterCompressedSharedFormulaGroup(n.groupId)}_markCompressedSharedFormulaMembership(e,t){for(let n=t.range.startRow;n<=t.range.endRow;n++)for(let r=t.range.startColumn;r<=t.range.endColumn;r++){let i=this.codec.encodeCell(t.unitId,t.sheetId,n,r),a=this.cellFormulaToIndex.get(i);a!==void 0&&this._activeNode[a]&&(this._sharedFormulaMembershipByNode[a]=e)}}_markCompressedSharedFormulaMembershipByNodeIndices(e,t){for(let n=0;n<t.length;n++){let r=t[n];this._activeNode[r]&&(this._sharedFormulaMembershipByNode[r]=e)}}_clearCompressedSharedFormulaMembership(e,t){for(let n=t.range.startRow;n<=t.range.endRow;n++)for(let r=t.range.startColumn;r<=t.range.endColumn;r++){let i=this.codec.encodeCell(t.unitId,t.sheetId,n,r),a=this.cellFormulaToIndex.get(i);a!==void 0&&this._sharedFormulaMembershipByNode[a]===e&&(this._sharedFormulaMembershipByNode[a]=-1)}}_clearCompressedSharedFormulaMembershipByNodeIndices(e,t){for(let n=0;n<t.length;n++){let r=t[n];this._sharedFormulaMembershipByNode[r]===e&&(this._sharedFormulaMembershipByNode[r]=-1)}}_getCompressedSharedSourceCoverage(e,t){if(t.kind===`cell`)return B({unitId:t.unitId,sheetId:t.sheetId,range:{startRow:e.range.startRow+t.rowDelta,endRow:e.range.endRow+t.rowDelta,startColumn:e.range.startColumn+t.colDelta,endColumn:e.range.endColumn+t.colDelta}});let n=Math.min(t.startRowDelta,t.endRowDelta),r=Math.max(t.startRowDelta,t.endRowDelta),i=Math.min(t.startColDelta,t.endColDelta),a=Math.max(t.startColDelta,t.endColDelta);return B({unitId:t.unitId,sheetId:t.sheetId,range:{startRow:e.range.startRow+n,endRow:e.range.endRow+r,startColumn:e.range.startColumn+i,endColumn:e.range.endColumn+a}})}_forEachCompressedSharedDependentByRange(e,t){let n=B(e);this._sharedFormulaSourceRangeIndex.forEachRangeIntersecting(n,e=>{let r=this._sharedFormulaSourceEntries[e];if(!(r!=null&&r.active))return;let i=this._sharedFormulaGroups[r.groupIndex],a=this._reverseMapCompressedSharedPattern(n,i.fillRange,i.patterns[r.patternIndex]);a!=null&&this._forEachActiveCellFormulaInRange(a,t)})}_forEachActiveCellFormulaInRange(e,t){for(let n=e.range.startRow;n<=e.range.endRow;n++)for(let r=e.range.startColumn;r<=e.range.endColumn;r++){let i=this.codec.encodeCell(e.unitId,e.sheetId,n,r),a=this.cellFormulaToIndex.get(i);a!==void 0&&this._activeNode[a]&&t(a)}}_reverseMapCompressedSharedPattern(e,t,n){let r=n.kind===`cell`?[e.range.startRow-n.rowDelta,e.range.endRow-n.rowDelta]:[e.range.startRow-Math.max(n.startRowDelta,n.endRowDelta),e.range.endRow-Math.min(n.startRowDelta,n.endRowDelta)],i=n.kind===`cell`?[e.range.startColumn-n.colDelta,e.range.endColumn-n.colDelta]:[e.range.startColumn-Math.max(n.startColDelta,n.endColDelta),e.range.endColumn-Math.min(n.startColDelta,n.endColDelta)];return this._intersectRanges(t,{unitId:t.unitId,sheetId:t.sheetId,range:{startRow:r[0],endRow:r[1],startColumn:i[0],endColumn:i[1]}})}_intersectRanges(e,t){if(e.unitId!==t.unitId||e.sheetId!==t.sheetId)return;let n=Math.max(e.range.startRow,t.range.startRow),r=Math.min(e.range.endRow,t.range.endRow),i=Math.max(e.range.startColumn,t.range.startColumn),a=Math.min(e.range.endColumn,t.range.endColumn);if(!(n>r||i>a))return{unitId:e.unitId,sheetId:e.sheetId,range:{startRow:n,endRow:r,startColumn:i,endColumn:a}}}_forEachCompressedSharedPrecedent(e,t){let n=this._sharedFormulaMembershipByNode[e];if(n<0)return!0;let r=this._sharedFormulaGroups[n];for(let e=0;e<r.patterns.length;e++)if(t(r.patterns[e])===!1)return!1;return!0}_getCompressedSharedPrecedentCell(e,t){let n=this.indexToNodeId[e],r=this.codec.decodeCell(n);return this.codec.encodeCell(t.unitId,t.sheetId,r.row+t.rowDelta,r.col+t.colDelta)}_getCompressedSharedPrecedentRange(e,t){let n=this.indexToNodeId[e],r=this.codec.decodeCell(n);return B({unitId:t.unitId,sheetId:t.sheetId,range:{startRow:r.row+t.startRowDelta,startColumn:r.col+t.startColDelta,endRow:r.row+t.endRowDelta,endColumn:r.col+t.endColDelta}})}_addNodeDepsOnly(e,t,n,r){for(let n=0;n<t.length;n++)this._addDirectEdge(t[n],e);this._cellPrecedents[e]=t.length>0?t:void 0,this._rangePrecedents[e]=n.length>0?n:void 0;for(let t=0;t<n.length;t++)this.rangeIndex.addRange(e,n[t]);this._nodePrecedents[e]=r.length>0?r:void 0;for(let t=0;t<r.length;t++)this._addExplicitNodeEdge(r[t],e)}_addNewNodeDepsOnly(e,t,n,r){for(let n=0;n<t.length;n++)this._addDirectEdgeForNewNode(t[n],e);this._cellPrecedents[e]=t.length>0?t:void 0,this._rangePrecedents[e]=n.length>0?n:void 0;for(let t=0;t<n.length;t++)this.rangeIndex.addRange(e,n[t]);this._nodePrecedents[e]=r.length>0?r:void 0;for(let t=0;t<r.length;t++)this._addExplicitNodeEdge(r[t],e)}_removeNodeDepsOnly(e){let t=this._cellPrecedents[e];if(t){for(let n=0;n<t.length;n++)this._removeDirectEdge(t[n],e);this._cellPrecedents[e]=void 0}this.rangeIndex.removeNode(e),this._rangePrecedents[e]=void 0;let n=this._nodePrecedents[e];if(n){for(let t=0;t<n.length;t++)this._removeExplicitNodeEdge(n[t],e);this._nodePrecedents[e]=void 0}}_collectDynamicResolveResult(e,t){t.traceCells&&e.cells.push(...t.traceCells),t.cells&&e.cells.push(...t.cells),t.ranges&&e.ranges.push(...t.ranges),t.nodes&&e.nodes.push(...this._resolveExplicitNodeDeps(qe(t.nodes)))}_addRuntimeDepsOnly(e,t,n,r){for(let n=0;n<t.length;n++)this._addRuntimeDirectEdge(t[n],e);this._runtimeCellPrecedents[e]=t.length>0?t:void 0,this._runtimeRangePrecedents[e]=n.length>0?n:void 0;for(let t=0;t<n.length;t++)this._runtimeRangeIndex.addRange(e,n[t]);this._runtimeNodePrecedents[e]=r.length>0?r:void 0;for(let t=0;t<r.length;t++)this._addRuntimeExplicitNodeEdge(r[t],e)}_removeRuntimeDepsOnly(e){let t=this._runtimeCellPrecedents[e];if(t){for(let n=0;n<t.length;n++)this._removeRuntimeDirectEdge(t[n],e);this._runtimeCellPrecedents[e]=void 0}this._runtimeRangeIndex.removeNode(e),this._runtimeRangePrecedents[e]=void 0;let n=this._runtimeNodePrecedents[e];if(n){for(let t=0;t<n.length;t++)this._removeRuntimeExplicitNodeEdge(n[t],e);this._runtimeNodePrecedents[e]=void 0}}_detachDependentsFromNode(e){let t=this.nodeDeps.get(e),n=[];G(t,e=>{n.push(e)}),this.nodeDeps.delete(e);for(let t=0;t<n.length;t++)this._detachPrecedentFromDependent(n[t],e);let r=this._runtimeNodeDeps.get(e);if(r===void 0)return;let i=[];G(r,e=>{i.push(e)}),this._runtimeNodeDeps.delete(e);for(let t=0;t<i.length;t++)this._detachRuntimePrecedentFromDependent(i[t],e)}_detachPrecedentFromDependent(e,t){let n=this._nodePrecedents[e];if(n===void 0)return;let r=0,i=!1;for(let e=0;e<n.length;e++){let a=n[e];if(a===t){i=!0;continue}n[r++]=a}i&&(r===0?this._nodePrecedents[e]=void 0:n.length=r)}_detachRuntimePrecedentFromDependent(e,t){let n=this._runtimeNodePrecedents[e];if(n===void 0)return;let r=0,i=!1;for(let e=0;e<n.length;e++){let a=n[e];if(a===t){i=!0;continue}n[r++]=a}i&&(r===0?this._runtimeNodePrecedents[e]=void 0:n.length=r)}_addDirectEdge(e,t){let n=this.directDeps.get(e);n===void 0&&this._directPointIndex.add(e),this.directDeps.set(e,Ge(n,t))}_addDirectEdgeForNewNode(e,t){let n=this.directDeps.get(e);if(n===void 0){this._directPointIndex.add(e),this.directDeps.set(e,t);return}if(typeof n==`number`){n!==t&&this.directDeps.set(e,[n,t]);return}n[n.length-1]!==t&&n.push(t)}_removeDirectEdge(e,t){let n=this.directDeps.get(e);if(n===void 0)return;let r=Ke(n,t);r===void 0?(this.directDeps.delete(e),this._directPointIndex.remove(e)):this.directDeps.set(e,r)}_addRuntimeDirectEdge(e,t){let n=this._runtimeDirectDeps.get(e);n===void 0&&this._runtimeDirectPointIndex.add(e),this._runtimeDirectDeps.set(e,Ge(n,t))}_removeRuntimeDirectEdge(e,t){let n=this._runtimeDirectDeps.get(e);if(n===void 0)return;let r=Ke(n,t);r===void 0?(this._runtimeDirectDeps.delete(e),this._runtimeDirectPointIndex.remove(e)):this._runtimeDirectDeps.set(e,r)}_addExplicitNodeEdge(e,t){K(this.nodeDeps,e,t)}_removeExplicitNodeEdge(e,t){q(this.nodeDeps,e,t)}_addRuntimeExplicitNodeEdge(e,t){K(this._runtimeNodeDeps,e,t)}_removeRuntimeExplicitNodeEdge(e,t){q(this._runtimeNodeDeps,e,t)}_forEachDependentIndexByCellRaw(e,t){G(this.directDeps.get(e),t),G(this._runtimeDirectDeps.get(e),t);let n=this.codec.decodeCell(e);this.rangeIndex.forEachPoint(n.unitId,n.sheetId,n.row,n.col,t),this._runtimeRangeIndex.forEachPoint(n.unitId,n.sheetId,n.row,n.col,t),this._forEachCompressedSharedDependentByRange({unitId:n.unitId,sheetId:n.sheetId,range:{startRow:n.row,endRow:n.row,startColumn:n.col,endColumn:n.col}},t)}_forEachDependentOfNodeRaw(e,t){if(this._indexToNodeType[e]===1){let n=this.indexToNodeId[e];this._forEachDependentIndexByCellRaw(n,t)}G(this.nodeDeps.get(e),t),G(this._runtimeNodeDeps.get(e),t)}_markNodeIndexDirty(e,t=!1,n=!0){if(!this._activeNode[e])return;let r=this.dirty[e]===1;r||(this.dirty[e]=1,this._dirtyList.push(e),this._dirtyNodeCount++),n&&(!r||t)&&!this.inQueue[e]&&(this.inQueue[e]=1,this._propQueue.push(e))}_isEveryActiveNodeDirty(){return this._activeNodeCount>0&&this._dirtyNodeCount>=this._activeNodeCount}_propagateDirtyQueue(){if(this._isEveryActiveNodeDirty()){for(let e=0;e<this._propQueue.length;e++)this.inQueue[this._propQueue[e]]=0;this._propQueue.length=0;return}let e=0;for(;e<this._propQueue.length;){let t=this._propQueue[e++];this.inQueue[t]=0,this._activeNode[t]&&this._forEachDependentOfNodeRaw(t,e=>{this._markNodeIndexDirty(e,!1)})}this._propQueue.length=0}_getDirtyNodeIndicesSnapshot(){let e=[];for(let t=0;t<this._dirtyList.length;t++){let n=this._dirtyList[t];this.dirty[n]&&this._activeNode[n]&&e.push(n)}return e}_forEachDependentOfNodeDeduped(e,t){this._nextEdgeEpoch(),this._forEachDependentOfNodeRaw(e,e=>{this._edgeSeenEpoch[e]!==this._edgeEpoch&&(this._edgeSeenEpoch[e]=this._edgeEpoch,t(e))})}_forEachPrecedentNodeIndex(e,t){let n=this._cellPrecedents[e];if(n)for(let e=0;e<n.length;e++){let r=n[e],i=this.cellFormulaToIndex.get(r);if(i!==void 0&&this._activeNode[i]&&t(i)===!1)return!1}let r=this._rangePrecedents[e];if(r)for(let e=0;e<r.length;e++){let n=!0;if(this._formulaCellIndex.forEachFormulaInRange(r[e],e=>{if(n&&this._activeNode[e]&&t(e)===!1)return n=!1,!1}),!n)return!1}if(!this._forEachCompressedSharedPrecedent(e,n=>{if(n.kind===`cell`){let r=this._getCompressedSharedPrecedentCell(e,n),i=this.cellFormulaToIndex.get(r);return i!==void 0&&this._activeNode[i]&&t(i)===!1?!1:void 0}let r=!0;return this._formulaCellIndex.forEachFormulaInRange(this._getCompressedSharedPrecedentRange(e,n),e=>{if(r&&this._activeNode[e]&&t(e)===!1)return r=!1,!1}),r}))return!1;let i=this._nodePrecedents[e];if(i)for(let e=0;e<i.length;e++){let n=i[e];if(this._activeNode[n]&&t(n)===!1)return!1}let a=this._runtimeCellPrecedents[e];if(a)for(let e=0;e<a.length;e++){let n=a[e],r=this.cellFormulaToIndex.get(n);if(r!==void 0&&this._activeNode[r]&&t(r)===!1)return!1}let o=this._runtimeRangePrecedents[e];if(o)for(let e=0;e<o.length;e++){let n=!0;if(this._formulaCellIndex.forEachFormulaInRange(o[e],e=>{if(n&&this._activeNode[e]&&t(e)===!1)return n=!1,!1}),!n)return!1}let s=this._runtimeNodePrecedents[e];if(s)for(let e=0;e<s.length;e++){let n=s[e];if(this._activeNode[n]&&t(n)===!1)return!1}return!0}_wouldCreateCycleForNewDeps(e,t,n,r){for(let n=0;n<t.length;n++){let r=t[n],i=this.cellFormulaToIndex.get(r);if(i!==void 0&&this._activeNode[i]&&(i===e||this._canReachNodeIndex(e,i)))return!0}if(this._indexToNodeType[e]===1){let t=this.indexToNodeId[e],r=this.codec.decodeCell(t);for(let e=0;e<n.length;e++)if(He(n[e],r))return!0}for(let t=0;t<n.length;t++){let r=n[t],i=!1;if(this._formulaCellIndex.forEachFormulaInRange(r,t=>{if(!i&&this._activeNode[t]){if(t===e){i=!0;return}this._canReachNodeIndex(e,t)&&(i=!0)}}),i)return!0}for(let t=0;t<r.length;t++){let n=r[t];if(n===e||this._canReachNodeIndex(e,n))return!0}return!1}_canReachNodeIndex(e,t){if(e===t)return!0;this._nextVisitEpoch();let n=[e];for(;n.length>0;){let e=n.pop(),r=!1;if(this._forEachDependentOfNodeRaw(e,e=>{if(!r&&this._visitNodeEpoch[e]!==this._visitEpoch){if(this._visitNodeEpoch[e]=this._visitEpoch,e===t){r=!0;return}n.push(e)}}),r)return!0}return!1}_buildDirtyCalculationGraph(e){let t=this._tryBuildAcyclicDirtyCalculationGraph(e);return t===void 0?this._buildDirtyCalculationGraphWithScc(e):t}_tryBuildAcyclicDirtyCalculationGraph(e){let t=e.length;this._nextTarjanEpoch();for(let n=0;n<t;n++){let t=e[n];this._tarjanSeenEpoch[t]=this._tarjanEpoch,this._tarjanIndexArr[t]=n+1}let n=new Uint32Array(t),r=new Int32Array(t),i=new Int32Array(t),a=new Uint8Array(t),o=new Uint8Array(t),s=new Uint8Array(t),c=[],l=[],u=new Map,d=[],f=[],p=[],m=[],h=new X(this.codec,this._initialRangeCapacity,this._maxIndexedSpan);for(let e=0;e<t;e++)i[e]=e,r[e]=-1;for(let g=0;g<t;g++){let t=e[g];this._nextEdgeEpoch(),this._addAcyclicExactPrecedentEdges(t,g,n,r,c,l,i,a,o,s),this._addAcyclicRangePrecedentGroups(t,g,n,u,d,f,p,m,h,i,a,o,s)}let g=new Int32Array(t),_=0,v=0;for(let e=0;e<t;e++)n[e]===0&&(g[v++]=e);let y=new Int32Array(t),b=[],x=-1,S=0,C=!1;for(;_<v;){let t=g[_++],a=e[t];S++,this._appendAcyclicCalculationNode(b,y,i,o,s,t,a,x),C=C||s[t]===1,o[t]===0&&x===-1&&(x=b.length-1);for(let e=r[t];e!==-1;e=l[e]){let t=c[e];n[t]--,n[t]===0&&(g[v++]=t)}if(this._indexToNodeType[a]===1){let e=this.indexToNodeId[a],t=this.codec.decodeCell(e);h.forEachPoint(t.unitId,t.sheetId,t.row,t.col,e=>{if(f[e]<=0||(f[e]--,f[e]!==0))return;let t=p[e];for(let e=0;e<t.length;e++){let r=t[e];n[r]--,n[r]===0&&(g[v++]=r)}})}}if(S===t)return{calculationForest:b,hasCycle:C}}_addAcyclicExactPrecedentEdges(e,t,n,r,i,a,o,s,c,l){let u=e=>{if(e===void 0||!this._activeNode[e]||!this.dirty[e]||this._edgeSeenEpoch[e]===this._edgeEpoch)return;this._edgeSeenEpoch[e]=this._edgeEpoch;let u=this._getCurrentDirtyOrdinal(e);if(!(u<0)){if(c[u]=1,c[t]=1,u===t){l[t]=1;return}a.push(r[u]),i.push(t),r[u]=i.length-1,n[t]++,this._unionCalculationForestComponents(o,s,u,t)}},d=this._cellPrecedents[e];if(d)for(let e=0;e<d.length;e++)u(this.cellFormulaToIndex.get(d[e]));let f=this._nodePrecedents[e];if(f)for(let e=0;e<f.length;e++)u(f[e]);let p=this._runtimeCellPrecedents[e];if(p)for(let e=0;e<p.length;e++)u(this.cellFormulaToIndex.get(p[e]));let m=this._runtimeNodePrecedents[e];if(m)for(let e=0;e<m.length;e++)u(m[e]);this._forEachCompressedSharedPrecedent(e,t=>{t.kind===`cell`&&u(this.cellFormulaToIndex.get(this._getCompressedSharedPrecedentCell(e,t)))})}_addAcyclicRangePrecedentGroups(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=[],m=m=>{let h=this._getOrCreateAcyclicRangeGroup(m,r,i,a,o,s,c,l,u,d);if(a[h]===0)return;for(let e=0;e<p.length;e++)if(p[e]===h)return;p.push(h),o[h].push(t),n[t]++,d[t]=1;let g=s[h];g>=0&&this._unionCalculationForestComponents(l,u,g,t),this._indexToNodeType[e]===1&&He(m,this.codec.decodeCell(this.indexToNodeId[e]))&&(f[t]=1)},h=this._rangePrecedents[e];if(h)for(let e=0;e<h.length;e++)m(h[e]);let g=this._runtimeRangePrecedents[e];if(g)for(let e=0;e<g.length;e++)m(g[e]);this._forEachCompressedSharedPrecedent(e,t=>{t.kind===`range`&&m(this._getCompressedSharedPrecedentRange(e,t))})}_getOrCreateAcyclicRangeGroup(e,t,n,r,i,a,o,s,c,l){let u=B(e),d=[u.unitId,u.sheetId,u.range.startRow,u.range.endRow,u.range.startColumn,u.range.endColumn].join(`:`),f=t.get(d);if(f!==void 0)return f;let p=n.length,m=0,h=-1;return t.set(d,p),n.push(u),i.push([]),o.addRange(p,u),this._formulaCellIndex.forEachFormulaInRange(u,e=>{if(!this._activeNode[e]||!this.dirty[e])return;let t=this._getCurrentDirtyOrdinal(e);if(!(t<0)){if(m++,l[t]=1,h===-1){h=t;return}this._unionCalculationForestComponents(s,c,h,t)}}),r.push(m),a.push(h),p}_appendAcyclicCalculationNode(e,t,n,r,i,a,o,s){let c=r[a]===0,l=this._findCalculationForestRoot(n,a),u=(c?s+1:t[l])-1;if(u===-1&&(u=e.length,c||(t[l]=u+1),e.push({hasCycle:!1,plan:[]})),i[a]===1){e[u].plan.push({type:`cycle`,nodeIndices:[o]}),e[u].hasCycle=!0;return}this._appendCalculationNodePlanItem(e[u].plan,o)}_getCurrentDirtyOrdinal(e){return this._tarjanSeenEpoch[e]===this._tarjanEpoch?this._tarjanIndexArr[e]-1:-1}_buildDirtyCalculationGraphWithScc(e){let t=this._findDirtySccs(e),n=t.componentStarts.length,r=new Int32Array(this.indexToNodeId.length),i=new Int32Array(this.indexToNodeId.length);r.fill(-1),i.fill(-1);for(let t=0;t<e.length;t++)i[e[t]]=t;let a=new Int32Array(n);a.fill(2**53-1);for(let e=0;e<n;e++){let n=2**53-1,o=t.componentStarts[e],s=this._getDirtySccEnd(t,e);for(let a=o;a<s;a++){let o=t.componentNodes[a];r[o]=e;let s=i[o];s>=0&&s<n&&(n=s)}a[e]=n}let o=new Int32Array(n);o.fill(-1);let s=[],c=[],l=new Int32Array(n),u=new Uint8Array(n),d=new Uint8Array(n),f=new Uint32Array(n),p=1,m=new Uint32Array(n);for(let e=0;e<n;e++)l[e]=e;for(let e=0;e<n;e++){p===4294967295&&(f.fill(0),p=1);let n=t.componentStarts[e],i=this._getDirtySccEnd(t,e);for(let a=n;a<i;a++){let n=t.componentNodes[a];this._forEachDependentOfNodeDeduped(n,t=>{if(!this._activeNode[t]||!this.dirty[t])return;let n=r[t];n<0||n===e||f[n]!==p&&(f[n]=p,c.push(o[e]),s.push(n),o[e]=s.length-1,m[n]++,d[e]=1,d[n]=1,this._unionCalculationForestComponents(l,u,e,n))})}p++}let h=this._toposortComponents(o,s,c,m,a),g=this._buildCalculationForest(t,h,l,d);t.componentNodes.length=0,t.componentStarts.length=0,s.length=0,c.length=0,h.length=0;let _=!1;for(let e=0;e<g.length;e++)if(g[e].hasCycle){_=!0;break}return{calculationForest:g,hasCycle:_}}_toposortComponents(e,t,n,r,i){let a=new Uint32Array(r),o=[];for(let e=0;e<a.length;e++)a[e]===0&&this._insertComponentByRank(o,0,e,i);let s=[],c=0;for(;c<o.length;){let r=o[c++];s.push(r);for(let s=e[r];s!==-1;s=n[s]){let e=t[s];a[e]--,a[e]===0&&this._insertComponentByRank(o,c,e,i)}}return s}_insertComponentByRank(e,t,n,r){let i=e.length,a=r[n];for(;i>t&&r[e[i-1]]>a;)i--;e.splice(i,0,n)}_buildCalculationForest(e,t,n,r){let i=new Int32Array(e.componentStarts.length);i.fill(-1);let a=[],o=-1;for(let s=0;s<t.length;s++){let c=t[s],l=this._findCalculationForestRoot(n,c),u=r[c]===0,d=u?o:i[l];d===-1&&(d=a.length,u?o=d:i[l]=d,a.push({hasCycle:!1,plan:[]}));let f=a[d],p=this._createCalculationPlanItem(e,c);if(p.type===`node`){this._appendCalculationNodePlanItem(f.plan,p.nodeIndex);continue}f.plan.push(p),p.type===`cycle`&&(f.hasCycle=!0)}return a}_appendCalculationNodePlanItem(e,t){let n=e[e.length-1];if((n==null?void 0:n.type)===`nodes`&&n.nodeIndices.length<8192){n.nodeIndices.push(t);return}e.push({type:`nodes`,nodeIndices:[t]})}_findCalculationForestRoot(e,t){let n=t;for(;e[n]!==n;)n=e[n];for(;e[t]!==t;){let r=e[t];e[t]=n,t=r}return n}_unionCalculationForestComponents(e,t,n,r){let i=this._findCalculationForestRoot(e,n),a=this._findCalculationForestRoot(e,r);if(i!==a){if(t[i]<t[a]){let e=i;i=a,a=e}e[a]=i,t[i]===t[a]&&t[i]++}}_createCalculationPlanItem(e,t){let n=e.componentStarts[t],r=this._getDirtySccEnd(e,t);if(r-n===1&&!this._hasSelfLoop(e.componentNodes[n]))return{type:`node`,nodeIndex:e.componentNodes[n]};let i=e.componentNodes.slice(n,r);return i.sort((e,t)=>e-t),{type:`cycle`,nodeIndices:i}}_getDirtySccEnd(e,t){return t+1<e.componentStarts.length?e.componentStarts[t+1]:e.componentNodes.length}_findDirtySccs(e){this._nextTarjanEpoch();let t=1,n=[],r=[],i=[],a=e=>{let t=[];return this._forEachDependentOfNodeDeduped(e,e=>{this._activeNode[e]&&this.dirty[e]&&t.push(e)}),t},o=(e,r)=>(this._tarjanSeenEpoch[e]=this._tarjanEpoch,this._tarjanIndexArr[e]=t,this._tarjanLowArr[e]=t,t++,n.push(e),this._tarjanOnStack[e]=1,{nodeIndex:e,dependents:a(e),nextDependentIndex:0,parentNodeIndex:r}),s=e=>{if(this._tarjanLowArr[e]===this._tarjanIndexArr[e])for(i.push(r.length);;){let t=n.pop();if(this._tarjanOnStack[t]=0,r.push(t),t===e)break}},c=e=>{let t=[o(e)];for(;t.length>0;){let e=t[t.length-1],n=e.nodeIndex;if(e.nextDependentIndex<e.dependents.length){let r=e.dependents[e.nextDependentIndex++];this._tarjanSeenEpoch[r]===this._tarjanEpoch?this._tarjanOnStack[r]&&(this._tarjanLowArr[n]=Math.min(this._tarjanLowArr[n],this._tarjanIndexArr[r])):t.push(o(r,n));continue}t.pop(),e.parentNodeIndex!==void 0&&(this._tarjanLowArr[e.parentNodeIndex]=Math.min(this._tarjanLowArr[e.parentNodeIndex],this._tarjanLowArr[n])),s(n)}};for(let t=0;t<e.length;t++){let n=e[t];this._activeNode[n]&&this.dirty[n]&&this._tarjanSeenEpoch[n]!==this._tarjanEpoch&&c(n)}return{componentNodes:r,componentStarts:i}}_hasSelfLoop(e){let t=!1;return this._forEachDependentOfNodeDeduped(e,n=>{n===e&&(t=!0)}),t}_nextEmitEpoch(){this._emitEpoch++,this._emitEpoch>=4294967295&&(this._seenNodeEpoch.fill(0),this._emitEpoch=1)}_emitNodeOnce(e){return this._seenNodeEpoch[e]===this._emitEpoch?!1:(this._seenNodeEpoch[e]=this._emitEpoch,!0)}_emitNodeOnceAndMarkDirty(e,t=!1,n=!0){this._emitNodeOnce(e)&&this._markNodeIndexDirty(e,t,n)}_nextVisitEpoch(){this._visitEpoch++,this._visitEpoch>=4294967295&&(this._visitNodeEpoch.fill(0),this._visitEpoch=1)}_nextEdgeEpoch(){this._edgeEpoch++,this._edgeEpoch>=4294967295&&(this._edgeSeenEpoch.fill(0),this._edgeEpoch=1)}_nextTarjanEpoch(){this._tarjanEpoch++,this._tarjanEpoch>=4294967295&&(this._tarjanSeenEpoch.fill(0),this._tarjanEpoch=1)}},et=class extends t.DependencyManagerBaseService{constructor(...e){super(...e),s(this,`_dependencyEngineCache`,new $e({maxRows:1048576,maxCols:16384}))}reset(){this._dependencyEngineCache.reset()}_getCellIdsAndRanges(e){let t=[],n=[];for(let r=0;r<e.rangeList.length;r++){let{unitId:i,sheetId:a,range:o}=e.rangeList[r];if(o.startRow===o.endRow&&o.startColumn===o.endColumn){let e=this._dependencyEngineCache.encodeCell(i,a,o.startRow,o.startColumn);t.push(e)}else n.push({unitId:i,sheetId:a,range:o})}return{cellIds:t,ranges:n}}_getDynamicDeps(e,t,n,r){if(!(!e.addressFunctionNodes||e.addressFunctionNodes.length===0))return[{id:`address-functions`,paramDeps:{cells:t,ranges:n,nodes:r}}]}addOtherFormulaDependencyPro(e,t,n,r,i,a=`replace`){let{cellIds:o,ranges:s}=this._getCellIdsAndRanges(r),c=this._getDynamicDeps(r,o,s,i),l=r.refOffsetX||0,u=r.refOffsetY||0,d=this._dependencyEngineCache.encodeOtherFormulaId(e,t,n,l,u);return this._dependencyEngineCache.setOtherFormulaDeps(d,{cells:o,ranges:s,nodes:i,dynamics:c},{checkCycle:!1,markDirty:!1,mode:a}).nodeIndex}removeOtherFormulaDependency(e,t,n){this._dependencyEngineCache.clearOtherFormulas(e,t,n,void 0,void 0,{markDependentsDirty:!0})}clearOtherFormulaDependency(e,t){t?this._dependencyEngineCache.clearOtherFormulas(e,t,void 0,void 0,void 0,{markDependentsDirty:!0}):this._dependencyEngineCache.clearOtherFormulas(e,void 0,void 0,void 0,void 0,{markDependentsDirty:!0})}getOtherFormulaDependencyPro(e,t,n,r,i){let a=this._dependencyEngineCache.encodeOtherFormulaId(e,t,n,r,i);if(this._dependencyEngineCache.hasOtherFormula(a))return this._dependencyEngineCache.getNodeIndex({type:2,id:a})}addFeatureFormulaDependencyPro(e,t,n,r){let{cellIds:i,ranges:a}=this._getCellIdsAndRanges(r),o=this._dependencyEngineCache.encodeFeatureCalculationId(e,t,n);return this._dependencyEngineCache.setFeatureCalculationDeps(o,{cells:i,ranges:a},{checkCycle:!1,markDirty:!1}).nodeIndex}removeFeatureFormulaDependency(e,t,n){let r=n.map(n=>this._dependencyEngineCache.encodeFeatureCalculationId(e,t,n));this._dependencyEngineCache.removeFeatureCalculations(r,{markDependentsDirty:!0,detachDependents:!0})}clearFeatureFormulaDependency(e,t){t?this._dependencyEngineCache.clearFeatureCalculations(e,t,{markDependentsDirty:!0,detachDependents:!0}):this._dependencyEngineCache.clearFeatureCalculations(e,void 0,{markDependentsDirty:!0,detachDependents:!0})}getFeatureFormulaDependencyPro(e,t,n){let r=this._dependencyEngineCache.encodeFeatureCalculationId(e,t,n);if(this._dependencyEngineCache.hasFeatureCalculation(r))return this._dependencyEngineCache.getNodeIndex({type:3,id:r})}getFeatureFormulaDependencyNodePro(e,t,n){return{type:3,id:this._dependencyEngineCache.encodeFeatureCalculationId(e,t,n)}}reserveFormulaDependencyCapacity(e,t=e){this._dependencyEngineCache.reserveDependencyCapacity(e,t)}addFormulaDependencyPro(e,t,n,r,i,a,o=`replace`){let s=this._dependencyEngineCache.encodeCell(e,t,n,r),{cellIds:c,ranges:l}=this._getCellIdsAndRanges(i),u={cells:c,ranges:l,nodes:a,dynamics:this._getDynamicDeps(i,c,l,a)};return(o===`replace`?this._dependencyEngineCache.setNewCellFormulaDeps(s,u):this._dependencyEngineCache.setCellFormulaDeps(s,u,{checkCycle:!1,markDirty:!1,mode:o})).nodeIndex}addFormulaDependencyNodeOnlyPro(e,t,n,r){let i=this._dependencyEngineCache.encodeCell(e,t,n,r);return this._dependencyEngineCache.setNewCellFormulaNodeOnly(i).nodeIndex}addFormulaDependencyNodeOnlyRangePro(e,t,n,r){return this._dependencyEngineCache.setNewCellFormulaNodeOnlyRange(e,t,n,r)}registerCompressedSharedFormulaGroup(e){this._dependencyEngineCache.registerCompressedSharedFormulaGroup(e)}clearCompressedSharedFormulaGroups(e,t){this._dependencyEngineCache.clearCompressedSharedFormulaGroups(e,t)}removeFormulaDependency(e,t,n,r){let i=this._dependencyEngineCache.encodeCell(e,t,n,r);this._dependencyEngineCache.removeCellFormula(i,{markDependentsDirty:!0})}clearFormulaDependency(e,t){this._dependencyEngineCache.clearCompressedSharedFormulaGroups(e,t),t?this._dependencyEngineCache.clearCellFormulas(e,t,{markDependentsDirty:!0}):this._dependencyEngineCache.clearCellFormulas(e,void 0,{markDependentsDirty:!0})}getFormulaDependencyPro(e,t,n,r){let i=this._dependencyEngineCache.encodeCell(e,t,n,r);if(this._dependencyEngineCache.hasCellFormula(i))return this._dependencyEngineCache.getNodeIndex({type:1,id:i})}markIndicesChanged(e,t){this._dependencyEngineCache.markCalcNodeIndicesChanged(e,t)}markRangesChanged(e,t){this._dependencyEngineCache.markRangesChanged(e,t)}markDirtyFeatureCalculations(e){let t=[];Object.keys(e).forEach(n=>{let r=e[n];r!=null&&Object.keys(r).forEach(e=>{let i=r[e];i!=null&&Object.keys(i).forEach(r=>{t.push(this.getFeatureFormulaDependencyNodePro(n,e,r))})})}),this._dependencyEngineCache.markCalcNodesChanged(t)}markDirtyOtherFormulas(e){Object.keys(e).forEach(t=>{let n=e[t];n!=null&&Object.keys(n).forEach(e=>{let r=n[e];r!=null&&this._dependencyEngineCache.markOtherFormulasChanged(t,e,Object.keys(r))})})}markDirtySheetNames(e){let t=[];Object.keys(e).forEach(n=>{let r=e[n];r!=null&&Object.keys(r).forEach(e=>{t.push({unitId:n,sheetId:e,range:{startRow:0,endRow:1048575,startColumn:0,endColumn:16383}})})}),this._dependencyEngineCache.markRangesChanged(t,{includeFormulaCells:!1})}markAllDirty(){this._dependencyEngineCache.markAllDirty()}clearCalculatedDirty(e){this._dependencyEngineCache.clearCalculatedDirty(e)}hasDynamicDeps(e){return this._dependencyEngineCache.hasDynamicDeps(e)}hasDynamicDepsByIndex(e){return this._dependencyEngineCache.hasDynamicDeps(this._dependencyEngineCache.getNodeRefByIndex(e))}refreshDynamicDeps(e,t){return this._dependencyEngineCache.refreshDynamicDeps(e,t)}refreshDynamicDepsByIndex(e,t){return this._dependencyEngineCache.refreshDynamicDeps(this._dependencyEngineCache.getNodeRefByIndex(e),t)}hasUncalculatedDirtyPrecedentByIndex(e,t){return this._dependencyEngineCache.hasUncalculatedDirtyPrecedentByIndex(e,t)}forEachPrecedentNodeByIndex(e,t){this._dependencyEngineCache.forEachPrecedentNodeByIndex(e,(e,n)=>{t(n)})}forEachDependentNodeByIndex(e,t){this._dependencyEngineCache.forEachDependentByIndex(e,(e,n)=>{t(n)})}prepareDynamicDependencies(e){return this._dependencyEngineCache.prepareDynamicDependencies(e)}getCalculationOrder(e){return this._dependencyEngineCache.getCalculationOrder(e)}};let Z=class extends t.FormulaUnitReferenceResolver{constructor(e,t){super(e),this._externalReferenceModel=t}resolve(n){let r=this._externalReferenceModel.resolveBinding(n.hostUnitId,n.qualifier);if(r.status===`ambiguous`)return t.ErrorType.REF;if(r.status===`resolved`){let{link:i}=r;if(n.referenceKind===`a1`&&i.target.unitType===e.UniverInstanceType.UNIVER_BASE)return t.ErrorType.REF;if(i.target.liveUnitId){let e=super.resolve({...n,qualifier:i.target.liveUnitId});if(typeof e!=`string`)return e}let a=super.resolve({...n,qualifier:i.target.name});return typeof a!=`string`&&(a.unitType==null||a.unitType===i.target.unitType)?a:{unitId:u(n.hostUnitId,i.slot),unitType:i.target.unitType}}return super.resolve(n)}};Z=m([p(0,t.IFormulaCurrentConfigService),p(1,(0,e.Inject)(d))],Z);let Q=class{constructor(e,t,n){this._formulaDataModel=e,this._superTableService=t,this._providerRegistry=n}async readData(e){let t=this._formulaDataModel.getCalculateData(),n=rt(e,t.unitNameMap,t.allUnitData);if(n){let r=this._readLiveSheets(e,n,t.allUnitData,t.unitSheetNameMap);if(r.length>0)return{requestId:e.requestId,calculationId:e.calculationId,source:`main-live`,freshness:`fresh`,sheets:r}}for(let t of this._providerRegistry.getProviders(e)){let n=await t.readData(e);if(n&&(e.requireFresh===!1||n.freshness===`fresh`))return n.source===`ooxml-cache`?n:{...n,source:`provider`}}return S(e)}_readLiveSheets(e,t,n,r){let i=[];for(let o of e.ranges){var a;let e=this._resolveLiveRange(t,o,n,r);if(!e)continue;let{sheetId:s,sheetName:c,range:l}=e,u=(a=n[t])==null?void 0:a[s];if(!u)continue;let d=[];for(let e=l.startRow;e<=l.endRow;e++)for(let t=l.startColumn;t<=l.endColumn;t++){let n=u.cellData.getValue(e,t);n!=null&&d.push({row:e,column:t,cell:n})}i.push({name:c,sheetId:s,rowCount:u.rowCount,columnCount:u.columnCount,coverage:[l],cells:d})}return i}_resolveLiveRange(e,t,n,r){return t.tableName?tt(e,t.tableName,r,this._superTableService):nt(e,t,n,r)}};Q=m([p(0,(0,e.Inject)(t.FormulaDataModel)),p(1,t.ISuperTableService),p(2,b)],Q);function tt(e,t,n,r){var i,a,o,s,c;let l=r.getTableMap(e),u=(i=Array.from((a=l==null?void 0:l.entries())==null?[]:a).find(([e])=>e.toLowerCase()===t.toLowerCase()))==null?void 0:i[1];if(!u)return;let d=(o=(s=Object.entries((c=n[e])==null?{}:c).find(([,e])=>e===u.sheetId))==null?void 0:s[0])==null?u.sheetId:o;return{sheetId:u.sheetId,sheetName:d,range:u.range}}function nt(e,t,n,r){var i,a,o,s,c,l,u;let d=(i=r[e])==null?{}:i,f=(a=t.sheetId)==null?t.sheetName?(o=Object.entries(d).find(([e])=>{var n;return e.toLowerCase()===((n=t.sheetName)==null?void 0:n.toLowerCase())}))==null?void 0:o[1]:void 0:a;if(!(!f||!t.range||!((s=n[e])!=null&&s[f])))return{sheetId:f,sheetName:(c=(l=t.sheetName)==null?(u=Object.entries(d).find(([,e])=>e===f))==null?void 0:u[0]:l)==null?f:c,range:t.range}}function rt(e,n,r){if(e.target.liveUnitId&&r[e.target.liveUnitId])return e.target.liveUnitId;let i=Object.entries(n).filter(([t,n])=>!!r[t]&&n.unitType===e.target.unitType),a=e.target.name.toLowerCase(),o=i.filter(([,e])=>e.name.toLowerCase()===a),s=o.length>0?o:i.filter(([,n])=>(0,t.normalizeFormulaUnitName)(n.name)===(0,t.normalizeFormulaUnitName)(e.target.name));return s.length===1?s[0][0]:void 0}let $=class extends t.UniverFormulaEnginePlugin{_extendFormulaExecutionDependencies(e){}_initializeWithOverride(){var e;if(this._injector.add([t.LexerTreeBuilder,{useClass:t.LexerTreeBuilder}]),this._injector.add([d]),this._injector.add([w]),this._injector.add([O]),this._injector.add([D]),this._injector.add([b,{useClass:x}]),this._injector.add([h]),this._injector.add([C]),this._injector.add([Q]),this._config.notExecuteFormula===!0?(this._injector.add([y,{useClass:Q}]),this._injector.add([k])):this._injector.add([y,{useFactory:()=>{try{return(0,n.toModule)(this._injector.get(n.IRPCChannelService).requestChannel(re))}catch{return this._injector.get(Q)}}}]),!((e=this._config)!=null&&e.notExecuteFormula)){let e=[[t.ICalculateFormulaService,{useClass:ze}],[t.IDependencyManagerService,{useClass:et}],[t.IFormulaDependencyGenerator,{useClass:Oe}],[t.IFormulaUnitReferenceResolver,{useClass:Z}],[R],[z]];this._extendFormulaExecutionDependencies(e),e.forEach(e=>this._injector.add(e))}}onReady(){super.onReady(),(0,e.touchDependencies)(this._injector,[[O],[D]]),(0,e.touchDependencies)(this._injector,[[C]]),this._config.notExecuteFormula===!0&&(0,e.touchDependencies)(this._injector,[[k]])}};s($,`packageName`,ie),s($,`version`,ae),$=m([(0,e.DependentOn)(r.UniverLicensePlugin)],$),exports.EXTERNAL_REFERENCE_SCHEMA_VERSION=1,Object.defineProperty(exports,"ExternalCacheReferenceDataProvider",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"ExternalFormulaUnitReferenceResolver",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"ExternalReferenceDataProvidersController",{enumerable:!0,get:function(){return C}}),exports.ExternalReferenceModel=d,Object.defineProperty(exports,"ExternalReferenceOverlayModel",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"ExternalReferencePrefetchPlanner",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"ExternalReferencePrefetchService",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"ExternalReferenceRenameController",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"ExternalReferenceResourceController",{enumerable:!0,get:function(){return O}}),exports.FORMULA_REFERENCE_DATA_RPC_CHANNEL=re,Object.defineProperty(exports,"FormulaCalculationTriggerService",{enumerable:!0,get:function(){return t.FormulaCalculationTriggerService}}),Object.defineProperty(exports,"FormulaDataModel",{enumerable:!0,get:function(){return t.FormulaDataModel}}),exports.FormulaReferenceDataProviderRegistry=x,Object.defineProperty(exports,"FormulaReferenceDataRpcController",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"IActiveDirtyManagerService",{enumerable:!0,get:function(){return t.IActiveDirtyManagerService}}),exports.IFormulaReferenceDataProviderRegistry=b,exports.IFormulaReferenceDataService=y,Object.defineProperty(exports,"ISuperTableService",{enumerable:!0,get:function(){return t.ISuperTableService}}),Object.defineProperty(exports,"MainFormulaReferenceDataService",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"RemoveSuperTableMutation",{enumerable:!0,get:function(){return t.RemoveSuperTableMutation}}),exports.SHEET_EXTERNAL_DATA_PLUGIN=c,Object.defineProperty(exports,"SetFormulaCalculationResultMutation",{enumerable:!0,get:function(){return t.SetFormulaCalculationResultMutation}}),Object.defineProperty(exports,"SetFormulaCalculationStartMutation",{enumerable:!0,get:function(){return t.SetFormulaCalculationStartMutation}}),Object.defineProperty(exports,"SetFormulaDataMutation",{enumerable:!0,get:function(){return t.SetFormulaDataMutation}}),Object.defineProperty(exports,"SetSuperTableMutation",{enumerable:!0,get:function(){return t.SetSuperTableMutation}}),Object.defineProperty(exports,"SetTriggerFormulaCalculationStartMutation",{enumerable:!0,get:function(){return t.SetTriggerFormulaCalculationStartMutation}}),Object.defineProperty(exports,"UniverProFormulaEnginePlugin",{enumerable:!0,get:function(){return $}}),exports.createEmptyExternalReferenceResource=l,exports.createExternalSyntheticUnitId=u,exports.createUnavailableReferenceDataResponse=S,Object.defineProperty(exports,"refactorFormulaUnitQualifier",{enumerable:!0,get:function(){return t.refactorFormulaUnitQualifier}});
package/lib/es/facade.js CHANGED
@@ -1 +1 @@
1
- function _0x4af1(_0x342b44,_0x34a499){_0x342b44=_0x342b44-0x9f;var _0x3edc8c=_0x3edc();var _0x4af1dc=_0x3edc8c[_0x342b44];return _0x4af1dc;}function _0x3edc(){var _0x73a6b0=['3262rnTLgh','30AGxzAy','22pqEIaO','64428VWvXnE','3000072uwPceT','304065wpgkYM','8mdjZkl','2271857HvBjCr','1nOjBMA','6rVHhcg','915542JImruh','684548NkCEWR','95mmiRRU','37336wvoKxP'];_0x3edc=function(){return _0x73a6b0;};return _0x3edc();}(function(_0x4393b2,_0x1bbfc0){var _0x188ddb=_0x4af1,_0x59f641=_0x4393b2();while(!![]){try{var _0x102472=-parseInt(_0x188ddb(0xa8))/0x1*(-parseInt(_0x188ddb(0xaa))/0x2)+-parseInt(_0x188ddb(0xa9))/0x3*(-parseInt(_0x188ddb(0xab))/0x4)+parseInt(_0x188ddb(0xac))/0x5*(parseInt(_0x188ddb(0xa3))/0x6)+-parseInt(_0x188ddb(0xa7))/0x7*(-parseInt(_0x188ddb(0xa6))/0x8)+parseInt(_0x188ddb(0xa5))/0x9*(parseInt(_0x188ddb(0xa1))/0xa)+parseInt(_0x188ddb(0xa2))/0xb*(-parseInt(_0x188ddb(0xa4))/0xc)+-parseInt(_0x188ddb(0x9f))/0xd*(parseInt(_0x188ddb(0xa0))/0xe);if(_0x102472===_0x1bbfc0)break;else _0x59f641['push'](_0x59f641['shift']());}catch(_0x52ed69){_0x59f641['push'](_0x59f641['shift']());}}}(_0x3edc,0x3fab1));import{FFormula as _0x5cff42}from'@univerjs/engine-formula/facade';export{_0x5cff42 as FFormula};
1
+ (function(_0x1641b0,_0x441357){var _0xe431a2=_0x1581,_0xe1c821=_0x1641b0();while(!![]){try{var _0x558aa3=-parseInt(_0xe431a2(0x7c))/0x1+parseInt(_0xe431a2(0x7b))/0x2+parseInt(_0xe431a2(0x81))/0x3+-parseInt(_0xe431a2(0x7d))/0x4*(parseInt(_0xe431a2(0x7f))/0x5)+parseInt(_0xe431a2(0x80))/0x6*(parseInt(_0xe431a2(0x7e))/0x7)+-parseInt(_0xe431a2(0x78))/0x8+-parseInt(_0xe431a2(0x79))/0x9*(-parseInt(_0xe431a2(0x7a))/0xa);if(_0x558aa3===_0x441357)break;else _0xe1c821['push'](_0xe1c821['shift']());}catch(_0x93a4e6){_0xe1c821['push'](_0xe1c821['shift']());}}}(_0x1833,0xe9ef0));function _0x1833(){var _0x8aac07=['14995uhjOqu','1504518AmjfeV','2727465MIJKhI','9706800dUxsJF','9WuVuRl','23006330DeEROH','310774nHUpJO','504536cIZkXx','1588LJjtuM','14DqxqUZ'];_0x1833=function(){return _0x8aac07;};return _0x1833();}import{FFormula as _0x4bfcdb}from'@univerjs/engine-formula/facade';function _0x1581(_0xf13598,_0xe2cad1){_0xf13598=_0xf13598-0x78;var _0x1833a3=_0x1833();var _0x15816b=_0x1833a3[_0xf13598];return _0x15816b;}export{_0x4bfcdb as FFormula};