@8sheets/data-grid 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +1 -1
  2. package/api/theme-core.js +2 -0
  3. package/calc/compile.js +1 -1
  4. package/calc/engine.js +1 -1
  5. package/calc/functions/info.js +1 -1
  6. package/calc/functions/math.js +1 -1
  7. package/calc/parser.js +3 -3
  8. package/calc/values.js +1 -1
  9. package/calcx/culture/custom.js +1 -0
  10. package/calcx/culture/format-locale.js +1 -1
  11. package/calcx/culture/separators.js +1 -0
  12. package/calcx/lang/convert.js +1 -0
  13. package/cells/axis-ops.js +1 -1
  14. package/cells/block.js +1 -0
  15. package/cells/book-css.js +2 -2
  16. package/cells/cell-defaults.js +1 -1
  17. package/cells/consolidate-links.js +1 -1
  18. package/cells/find-engine.js +2 -2
  19. package/cells/format-panes.js +3 -3
  20. package/cells/format-tabs.js +2 -2
  21. package/cells/outline-column.js +1 -1
  22. package/cells/panes.js +1 -1
  23. package/cells/selection-modes.js +1 -1
  24. package/cells/shift-check.js +1 -0
  25. package/cells/table-rows.js +1 -0
  26. package/cells/text-layout.js +9 -8
  27. package/cells/ui-kit.js +15 -0
  28. package/cells/view-options.js +1 -1
  29. package/celltypes/diagonal.js +1 -1
  30. package/celltypes/dropdowns.js +2 -2
  31. package/core/autofill.js +1 -1
  32. package/core/axis-styles.js +1 -0
  33. package/core/axis.js +1 -1
  34. package/core/culture.js +1 -0
  35. package/core/formula-refs.js +1 -1
  36. package/core/input.js +1 -1
  37. package/core/merge.js +1 -0
  38. package/core/numfmt.js +1 -1
  39. package/core/region-input.js +1 -0
  40. package/core/row-fit.js +1 -0
  41. package/core/sheet.js +1 -1
  42. package/core/structure.js +1 -0
  43. package/core/styles.js +1 -1
  44. package/core/tables.js +2 -2
  45. package/core/whatif.js +1 -1
  46. package/core/workbook.js +1 -1
  47. package/datasheets/data-core.js +1 -1
  48. package/datasheets/gantt-paint.js +1 -1
  49. package/datasheets/path-binding.js +2 -2
  50. package/datasheets/rules.js +1 -1
  51. package/datasheets/view.js +2 -2
  52. package/i18n/dom.js +1 -1
  53. package/i18n/en/cells.js +1 -1
  54. package/i18n/en/format.js +1 -1
  55. package/i18n/en/shell.js +2 -2
  56. package/i18n/pl/cells.js +1 -1
  57. package/i18n/pl/format.js +1 -1
  58. package/i18n/pl/shell.js +2 -2
  59. package/io/csv.js +8 -8
  60. package/io/plan.js +1 -1
  61. package/io/text-split.js +3 -3
  62. package/io/xlsx-write.js +1 -1
  63. package/objects/chart-model.js +1 -1
  64. package/package.json +1 -1
  65. package/pivot/engine.js +1 -1
  66. package/print/paginate.js +1 -1
  67. package/print/render-page.js +3 -3
  68. package/table-view/api.js +1 -1
  69. package/table-view/cell-editor.js +2 -1
  70. package/table-view/chart.js +1 -0
  71. package/table-view/column-drag.js +1 -1
  72. package/table-view/context-menu.js +1 -0
  73. package/table-view/editors.js +1 -0
  74. package/table-view/events.js +1 -1
  75. package/table-view/files.js +1 -1
  76. package/table-view/fill-handle.js +1 -0
  77. package/table-view/filter-builder.js +1 -0
  78. package/table-view/find.js +1 -0
  79. package/table-view/grid-keys.js +2 -2
  80. package/table-view/labels-de.js +1 -0
  81. package/table-view/labels-es.js +1 -0
  82. package/table-view/labels-fr.js +1 -0
  83. package/table-view/labels-ja.js +1 -0
  84. package/table-view/labels.js +1 -1
  85. package/table-view/model.js +1 -1
  86. package/table-view/mount.js +1 -1
  87. package/table-view/panel.js +1 -1
  88. package/table-view/pivot-spec.js +1 -0
  89. package/table-view/pivot.js +1 -1
  90. package/table-view/public.d.ts +277 -28
  91. package/table-view/reader.worker.js +1 -1
  92. package/table-view/remote.js +1 -1
  93. package/table-view/row-drag.js +1 -0
  94. package/table-view/sparkline.js +1 -0
  95. package/table-view/state-check.js +1 -0
  96. package/table-view/table-css.js +380 -0
  97. package/table-view/version.js +1 -1
  98. package/ui/dialogs.js +3 -3
  99. package/ui/menu-base.js +1 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  A data grid for the web in plain JavaScript modules with no runtime dependencies. Open a CSV or Excel file, or pass your records, and search, filter, sort, group, total, pivot and export them as CSV, Excel or PDF. Files are read in a Worker as a stream, the page keeps a bounded DOM, and a million records stay responsive. Server data plugs in through a query contract, so search, filters and totals cover the whole result.
4
4
 
5
- This is version 1.0.2. Components for [React](https://www.npmjs.com/package/@8sheets/data-grid-react), [Vue](https://www.npmjs.com/package/@8sheets/data-grid-vue) and [Angular](https://www.npmjs.com/package/@8sheets/data-grid-angular) build on it. For a full Excel-compatible workbook, see the Spreadsheet, [`@8sheets/core`](https://www.npmjs.com/package/@8sheets/core).
5
+ This is version 1.1.0. Components for [React](https://www.npmjs.com/package/@8sheets/data-grid-react), [Vue](https://www.npmjs.com/package/@8sheets/data-grid-vue) and [Angular](https://www.npmjs.com/package/@8sheets/data-grid-angular) build on it. For a full Excel-compatible workbook, see the Spreadsheet, [`@8sheets/core`](https://www.npmjs.com/package/@8sheets/core).
6
6
 
7
7
  ## Install
8
8
 
@@ -0,0 +1,2 @@
1
+ import{refLive as S}from"./style-refs.js";import{xmlLiteralText as w}from"../io/xml-escape.js";const p=["dk1","lt1","dk2","lt2","accent1","accent2","accent3","accent4","accent5","accent6","hlink","folHlink"],g={lt1:0,dk1:1,lt2:2,dk2:3,accent1:4,accent2:5,accent3:6,accent4:7,accent5:8,accent6:9,hlink:10,folHlink:11},N=Object.keys(g),O=[1,0,3,2,4,5,6,7,8,9,10,11],k="000000 FFFFFF 0E2841 E8E8E8 156082 E97132 196B24 0F9ED5 A02B93 4EA72E 467886 96607D".split(" "),u=()=>({name:"Office Theme",colors:Object.fromEntries(k.map((e,t)=>[p[t],e])),major:"Aptos Display",minor:"Aptos Narrow"});function R(e,t=u()){const o={...t.colors};for(const[l,a]of Object.entries(e.colors??{})){if(!p.includes(l))throw new TypeError(`Unknown theme color "${l}". Slots: ${p.join(", ")}`);const c=String(a).replace(/^#/,"").toUpperCase();if(!/^[0-9A-F]{6}$/.test(c))throw new TypeError(`Theme color ${l} must be six hex digits, not "${a}"`);o[l]=c}return{name:e.name??"Custom",colorName:e.colorName??e.name??t.colorName??t.name,fontName:e.fontName??e.name??t.fontName??t.name,colors:o,major:e.major??t.major,minor:e.minor??t.minor}}const C=w,I='<a:fmtScheme name="8sheets"><a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"><a:tint val="85000"/></a:schemeClr></a:solidFill><a:solidFill><a:schemeClr val="phClr"><a:shade val="85000"/></a:schemeClr></a:solidFill></a:fillStyleLst><a:lnStyleLst><a:ln w="6350" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="12700" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="19050" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"><a:tint val="95000"/></a:schemeClr></a:solidFill><a:solidFill><a:schemeClr val="phClr"><a:shade val="95000"/></a:schemeClr></a:solidFill></a:bgFillStyleLst></a:fmtScheme>';function _(e){const t=p.map(l=>{const a=e.colors[l];return l==="dk1"&&a==="000000"?'<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>':l==="lt1"&&a==="FFFFFF"?'<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>':`<a:${l}><a:srgbClr val="${a}"/></a:${l}>`}).join(""),o=l=>`<a:latin typeface="${C(l)}"/><a:ea typeface=""/><a:cs typeface=""/>`;return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ <a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="${C(e.name)}"><a:themeElements><a:clrScheme name="${C(e.colorName??e.name)}">${t}</a:clrScheme><a:fontScheme name="${C(e.fontName??e.name)}"><a:majorFont>${o(e.major)}</a:majorFont><a:minorFont>${o(e.minor)}</a:minorFont></a:fontScheme>${I}</a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/></a:theme>`}const y=(e,t)=>new RegExp(`\\b${t}="([^"]*)"`).exec(e)?.[1];function H(e){const t=/<a:clrScheme\b[^>]*>([\s\S]*?)<\/a:clrScheme>/.exec(e);if(!t)throw new Error("This theme part has no color scheme");const o={};for(const a of p){const c=new RegExp(`<a:${a}>\\s*<a:(?:srgbClr val|sysClr[^>]*?lastClr)="([0-9A-Fa-f]{6})"`).exec(t[1]);o[a]=(c?.[1]??"000000").toUpperCase()}const l=a=>new RegExp(`<a:${a}>\\s*<a:latin\\s+typeface="([^"]*)"`).exec(e)?.[1]??"Calibri";return{name:y(/<a:theme\b[^>]*>/.exec(e)?.[0]??"","name")??"Imported",colorName:y(/<a:clrScheme\b[^>]*>/.exec(e)?.[0]??"","name"),fontName:y(/<a:fontScheme\b[^>]*>/.exec(e)?.[0]??"","name"),colors:o,major:l("majorFont"),minor:l("minorFont")}}function b(e){return N.map(t=>e.colors[t])}function U(e){const t=[];return e.forEach((o,l)=>{t[O[l]]=o}),t}function D(e,t){if(!t)return e.toUpperCase();const o=parseInt(e.slice(0,2),16)/255,l=parseInt(e.slice(2,4),16)/255,a=parseInt(e.slice(4,6),16)/255,c=Math.max(o,l,a),r=Math.min(o,l,a);let n=(c+r)/2;const i=c-r,f=i===0?0:i/(1-Math.abs(2*n-1));let s=0;i!==0&&(c===o?s=((l-a)/i+6)%6:c===l?s=(a-o)/i+2:s=(o-l)/i+4),n=t<0?n*(1+t):n*(1-t)+t;const m=(1-Math.abs(2*n-1))*f,h=m*(1-Math.abs(s%2-1)),v=n-m/2,[T,L,$]=s<1?[m,h,0]:s<2?[h,m,0]:s<3?[0,m,h]:s<4?[0,h,m]:s<5?[h,0,m]:[m,0,h],E=j=>Math.round((j+v)*255).toString(16).padStart(2,"0");return(E(T)+E(L)+E($)).toUpperCase()}function x(e,t=0,o=b(u())){const l=typeof e=="number"?e:g[e];if(l===void 0)throw new TypeError(`Unknown theme color "${e}"`);return{t:l,tint:t,hex:`#${D(o[l]??"000000",t)}`}}function z(e,t,o={}){const l=b(t),c=(o.previous??e.themeInfo??null)?.minor??null;for(const r of e.styles.list){let n=r.themeRefs;if(!n?.font&&c&&r.fontName===c&&(n={...n,font:"minor"},r.themeRefs=n),n){const i=(f,s=n)=>{const m=s[f];return s[f]=x(m.t,m.tint,l),s[f].hex};if(n=r.themeRefs={...n},n.color&&S(n.color,r.color??"#000000")){const f=i("color");r.color=f==="#000000"?null:f}if(S(n.fill,r.fill)&&(r.fill=i("fill")),n.patternFg&&r.pattern&&S(n.patternFg,r.pattern.fg)&&(r.pattern={...r.pattern,fg:i("patternFg")}),n.border&&r.borders){n.border={...n.border};const f={...r.borders};for(const s of["l","r","t","b","d"]){const m=n.border[s];m&&f[s]&&S(m,f[s].color)&&(f[s]={...f[s],color:i(s,n.border)})}r.borders=f}n.font==="major"?r.fontName=t.major:n.font==="minor"&&(r.fontName=t.minor)}}e.styles.index=null,e.styles.deriveCache?.clear(),e.theme=l,e.themeInfo=t,e.themeXml=_(t),e.themeChanged=!0;for(const r of e.sheets)r.cfEval?.invalidate(),r.revision++}const F=(e,t,o=0)=>({style:e,slot:t,tint:o}),d={Title:{fontSize:18,slot:"dk2",font:"major"},"Heading 1":{fontSize:15,bold:!0,slot:"dk2",bottom:F("thick","accent1")},"Heading 2":{fontSize:13,bold:!0,slot:"dk2",bottom:F("thick","accent1",.5)},"Heading 3":{bold:!0,slot:"dk2",bottom:F("medium","accent1",.4)},"Heading 4":{bold:!0,slot:"dk2"},Total:{bold:!0,slot:"dk1",top:F("thin","accent1"),bottom:F("double","accent1")}};for(let e=1;e<=6;e++){const t=`accent${e}`;d[`Accent${e}`]={fillSlot:t,slot:"lt1"},d[`20% - Accent${e}`]={fillSlot:t,fillTint:.8,slot:"dk1"},d[`40% - Accent${e}`]={fillSlot:t,fillTint:.6,slot:"dk1"},d[`60% - Accent${e}`]={fillSlot:t,fillTint:.4,slot:"lt1"}}const X=Object.keys(d);function B(e,t){const o=d[e];if(!o)return null;const l=t.theme?.length>=10?t.theme:b(u()),a={},c={};if(o.fontSize&&(c.fontSize=o.fontSize),o.bold&&(c.bold=!0),o.slot&&(a.color=x(o.slot,0,l),c.color=a.color.hex),o.fillSlot&&(a.fill=x(o.fillSlot,o.fillTint??0,l),c.fill=a.fill.hex),o.bottom||o.top){a.border={};const r=(n,i)=>n?(a.border[i]=x(n.slot,n.tint,l),{style:n.style,color:a.border[i].hex}):null;c.borders={l:null,r:null,t:r(o.top,"t"),b:r(o.bottom,"b")}}return o.font&&(a.font=o.font,c.fontName=o.font==="major"?t.themeInfo?.major??u().major:t.themeInfo?.minor??u().minor),c.themeRefs=a,c}import{refLive as q}from"./style-refs.js";export{p as COLOR_SLOTS,X as THEMED_CELL_STYLE_NAMES,g as THEME_INDEX,z as applyThemeToBook,R as buildTheme,u as defaultTheme,U as fileOrderToIndex,x as makeRef,H as parseThemeXml,q as refLive,b as themeArray,_ as themeXml,B as themedCellStylePatch,D as tintHex};
package/calc/compile.js CHANGED
@@ -1 +1 @@
1
- import{MAX_COLS as A,MAX_ROWS as d}from"../core/address.js";import{Arr as x,compareValues as L,ERR as p,Lambda as w,num as k,OMITTED as M,Ref as m,RefList as g,REJECTED as R,str as V,XlError as b}from"./values.js";import{FUNCS as E}from"./functions/registry.js";const C=5e-16;class B{constructor(e){this.cx=e,this.refs=[],this.names=[],this.tables=[],this.isVolatile=!1,this.mayArray=!1,this.external=!1,this.arrayCtx=!1,this.scopes=[],this.slots=0,this.rangeSlots=new Set}compileTop(e){const i=this.any(e),{slots:a,cx:o}=this;return a===0?i:(c,t,s)=>{const r=o.frame;o.frame=new Array(a);try{return i(c,t,s)}finally{o.frame=r}}}sheetOf(e){const{cx:i}=this;if(e==null)return t=>t;if(e.book!==null&&e.book!==void 0){const t=i.externalSheet?.(e.book,e.sheet)??null;return t===null&&(this.external=!0),()=>t}const a=e.sheet;let o=-1,c=null;return()=>(o!==i.sheetGen&&(c=i.sheetByName(a),o=i.sheetGen),c)}cellRefClosure(e){const i=this.sheetOf(e.sheet),{rAbs:a,cAbs:o,r:c,c:t}=e;return this.refs.push({sheet:e.sheet,rAbs0:a,r0:c,rAbs1:a,r1:c,cAbs0:o,c0:t,cAbs1:o,c1:t}),e.sheet?.sheet2?this.sheet3d(e.sheet,(s,r,n)=>{const h=a?c:r+c,u=o?t:n+t;return new m(s,h,u,h,u)}):(s,r,n)=>{const h=a?c:s+c,u=o?t:r+t,l=i(n);return l===null||h<0||u<0||h>=d||u>=A?p.REF:new m(l,h,u,h,u)}}sheet3d(e,i){const{cx:a}=this;return(o,c)=>{const t=a.sheetsBetween(e.sheet,e.sheet2);return t===null?p.REF:new g(t.map(s=>i(s,o,c)))}}rangeClosure(e){const{a:i,b:a}=e,o=this.sheetOf(e.sheet);this.refs.push({sheet:e.sheet,rAbs0:i.rAbs,r0:i.r,rAbs1:a.rAbs,r1:a.r,cAbs0:i.cAbs,c0:i.c,cAbs1:a.cAbs,c1:a.c});const c=(t,s,r)=>{const n=i.rAbs?i.r:s+i.r,h=i.cAbs?i.c:r+i.c,u=a.rAbs?a.r:s+a.r,l=a.cAbs?a.c:r+a.c;return n<0||h<0||u<0||l<0||n>=d||u>=d||h>=A||l>=A?p.REF:new m(t,Math.min(n,u),Math.min(h,l),Math.max(n,u),Math.max(h,l))};return e.sheet?.sheet2?this.sheet3d(e.sheet,c):(t,s,r)=>{const n=o(r);return n===null?p.REF:c(n,t,s)}}rowsClosure(e){const i=this.sheetOf(e.sheet);return this.refs.push({sheet:e.sheet,rAbs0:e.a0,r0:e.r0,rAbs1:e.a1,r1:e.r1,cAbs0:!0,c0:0,cAbs1:!0,c1:A-1}),(a,o,c)=>{const t=e.a0?e.r0:a+e.r0,s=e.a1?e.r1:a+e.r1,r=i(c);return r===null||t<0||s<0||t>=d||s>=d?p.REF:new m(r,Math.min(t,s),0,Math.max(t,s),A-1)}}colsClosure(e){const i=this.sheetOf(e.sheet);return this.refs.push({sheet:e.sheet,rAbs0:!0,r0:0,rAbs1:!0,r1:d-1,cAbs0:e.a0,c0:e.c0,cAbs1:e.a1,c1:e.c1}),(a,o,c)=>{const t=e.a0?e.c0:o+e.c0,s=e.a1?e.c1:o+e.c1,r=i(c);return r===null||t<0||s<0||t>=A||s>=A?p.REF:new m(r,0,Math.min(t,s),d-1,Math.max(t,s))}}any(e){const{cx:i}=this;switch(e.t){case"lit":{const a=e.v;return()=>a}case"omit":return()=>M;case"paren":return this.any(e.e);case"cell":return this.cellRefClosure(e);case"range":return this.rangeClosure(e);case"rows":return this.rowsClosure(e);case"cols":return this.colsClosure(e);case"array":{const a=x.of2D(e.rows);return()=>a}case"union":{const a=e.items.map(o=>this.any(o));return(o,c,t)=>{const s=[];for(const r of a){const n=r(o,c,t);if(n instanceof m)s.push(n);else if(n instanceof g)s.push(...n.refs);else return n instanceof b?n:p.VALUE}return new g(s)}}case"intersect":{const a=this.any(e.l),o=this.any(e.r);return(c,t,s)=>{const r=a(c,t,s),n=o(c,t,s);if(r instanceof b)return r;if(n instanceof b)return n;if(!(r instanceof m)||!(n instanceof m)||r.sheet!==n.sheet)return p.VALUE;const h=Math.max(r.r0,n.r0),u=Math.min(r.r1,n.r1),l=Math.max(r.c0,n.c0),f=Math.min(r.c1,n.c1);return h>u||l>f?p.NULL:new m(r.sheet,h,l,u,f)}}case"rangeOp":{const a=this.any(e.l),o=this.any(e.r);return(c,t,s)=>{const r=a(c,t,s),n=o(c,t,s);return r instanceof b?r:n instanceof b?n:!(r instanceof m)||!(n instanceof m)||r.sheet!==n.sheet?p.REF:new m(r.sheet,Math.min(r.r0,n.r0),Math.min(r.c0,n.c0),Math.max(r.r1,n.r1),Math.max(r.c1,n.c1))}}case"implicit":{const a=this.any(e.e);return(o,c,t)=>{const s=a(o,c,t);return s instanceof m?s.isCell?i.read(s.sheet,s.r0,s.c0):i.intersect(s,o,c):s instanceof x?s.data[0]:s}}case"spillRef":{const a=this.any(e.e);return(o,c,t)=>{const s=a(o,c,t);return s instanceof m?i.spillRange(s):p.REF}}case"name":return this.nameNode(e);case"table":return this.tables.push({name:e.name,spec:e.spec}),(a,o,c)=>i.resolveTable(e.name,e.spec,a,o,c);case"call":return this.call(e);case"apply":{const a=this.any(e.fn),o=e.args.map(c=>this.any(c));return(c,t,s)=>{const r=a(c,t,s);return r instanceof b?r:r instanceof w?i.invoke(r,o.map(n=>n(c,t,s)),c,t,s):p.VALUE}}default:return this.value(e)}}nameNode(e){const{cx:i}=this,a=this.lookupVar(e.name);if(a!==null){const s=a;return()=>i.frame[s]}this.names.push(e.name);const o=e.name,c=e.sheet?this.sheetOf(e.sheet):s=>s,t=e.sheet?void 0:E.get(o.toUpperCase());if(t!==void 0){const s=new w([],null,null);return s.native=t,s.label=o.toUpperCase(),(r,n,h)=>{const u=i.evalName(o,r,n,h);return u===p.NAME?s:u}}return(s,r,n)=>i.evalName(o,s,r,c(n)??n)}lookupVar(e){const i=e.toUpperCase();for(let a=this.scopes.length-1;a>=0;a--){const o=this.scopes[a].get(i);if(o!==void 0)return o}return null}deref(e){const{cx:i}=this;return this.arrayCtx?(a,o,c)=>{const t=e(a,o,c);return t instanceof m||t instanceof g?i.refToValue(t):t}:(a,o,c)=>{const t=e(a,o,c);return t instanceof m||t instanceof g?i.refAuto(t,a,o):t}}value(e){const{cx:i}=this;switch(e.t){case"lit":{const a=e.v;return()=>a}case"paren":return this.value(e.e);case"cell":{const{rAbs:a,cAbs:o,r:c,c:t}=e;if(this.refs.push({sheet:e.sheet,rAbs0:a,r0:c,rAbs1:a,r1:c,cAbs0:o,c0:t,cAbs1:o,c1:t}),e.sheet?.sheet2)return()=>p.VALUE;const s=e.sheet?this.sheetOf(e.sheet):null;return s===null?!a&&!o?(r,n,h)=>{const u=r+c,l=n+t;return u<0||l<0||u>=d||l>=A?p.REF:i.read(h,u,l)}:(r,n,h)=>{const u=a?c:r+c,l=o?t:n+t;return u<0||l<0||u>=d||l>=A?p.REF:i.read(h,u,l)}:(r,n,h)=>{const u=a?c:r+c,l=o?t:n+t,f=s(h);return f===null||u<0||l<0||u>=d||l>=A?p.REF:i.read(f,u,l)}}case"range":case"rows":case"cols":return this.arrayCtx||(this.mayArray=!0),this.deref(this.any(e));case"neg":{const a=this.value(e.e);return(o,c,t)=>{const s=a(o,c,t);return typeof s=="number"?-s:i.unary(s,r=>-r)}}case"pct":{const a=this.value(e.e);return(o,c,t)=>{const s=a(o,c,t);return typeof s=="number"?s/100:i.unary(s,r=>r/100)}}case"bin":return this.binary(e);default:return!this.arrayCtx&&this.mayYieldRange(e)&&(this.mayArray=!0),this.deref(this.any(e))}}mayYieldRange(e){switch(e.t){case"paren":return this.mayYieldRange(e.e);case"range":case"rows":case"cols":case"union":case"rangeOp":case"intersect":case"spillRef":case"apply":return!0;case"table":return!/^\[\[#This Row\],\[[^\]]+\]\]$/i.test(e.spec);case"name":{if(e.sheet)return!0;const i=this.lookupVar(e.name);return i!==null?this.rangeSlots.has(i):this.cx.nameMayYieldRange?.(e.name)??!0}case"call":{if(e.name==="LET"||e.name==="LAMBDA"||this.lookupVar(e.name)!==null)return!0;const i=E.get(e.name);return i===void 0||i.refResult?!0:i.passes?e.args.some((a,o)=>i.passes(o,e.args.length)&&this.mayYieldRange(a)):!1}default:return!1}}binary(e){const{cx:i}=this,a=this.value(e.l),o=this.value(e.r);switch(e.op){case"+":return(c,t,s)=>{const r=a(c,t,s),n=o(c,t,s);if(typeof r=="number"&&typeof n=="number"){const h=r+n;return Math.abs(h)<Math.abs(r)*C?0:h}return i.slowBin("+",r,n)};case"-":return(c,t,s)=>{const r=a(c,t,s),n=o(c,t,s);if(typeof r=="number"&&typeof n=="number"){const h=r-n;return Math.abs(h)<Math.abs(r)*C?0:h}return i.slowBin("-",r,n)};case"*":return(c,t,s)=>{const r=a(c,t,s),n=o(c,t,s);return typeof r=="number"&&typeof n=="number"?r*n:i.slowBin("*",r,n)};case"/":return(c,t,s)=>{const r=a(c,t,s),n=o(c,t,s);return typeof r=="number"&&typeof n=="number"&&n!==0?r/n:i.slowBin("/",r,n)};case"^":return(c,t,s)=>i.slowBin("^",a(c,t,s),o(c,t,s));case"&":return(c,t,s)=>i.slowBin("&",a(c,t,s),o(c,t,s));default:{const c=e.op;return(t,s,r)=>i.slowBin(c,a(t,s,r),o(t,s,r))}}}call(e){const{cx:i}=this,{name:a,args:o}=e;if(a==="LET")return this.compileLet(o);if(a==="LAMBDA")return this.compileLambda(o);const c=this.lookupVar(a);if(c!==null){const s=c,r=o.map(n=>this.any(n));return(n,h,u)=>{const l=i.frame[s];return l instanceof w?i.invoke(l,r.map(f=>f(n,h,u)),n,h,u):p.VALUE}}const t=E.get(a);if(t===void 0){this.names.push(a);const s=o.map(r=>this.any(r));return(r,n,h)=>{const u=i.evalName(a,r,n,h);return u instanceof w?i.invoke(u,s.map(l=>l(r,n,h)),r,n,h):p.NAME}}if((o.length<t.min||o.length>t.max)&&!(o.length===1&&o[0].t==="omit"&&t.min===0))return()=>p.VALUE;if(t.volatile&&(this.isVolatile=!0),t.notInExcel&&(this.notInExcel=!0),t.frozen&&(this.external=!0),t.kind==="lazy"||t.kind==="raw"){const s=this.arrayCtx;t.array&&(this.arrayCtx=!0);const r=o.map(h=>this.any(h));this.arrayCtx=s;const{fn:n}=t;return t.kind==="lazy"?(h,u,l)=>{try{return n(i,r,h,u,l)}catch(f){if(f instanceof b)return f;throw f}}:(h,u,l)=>{const f=new Array(r.length);for(let y=0;y<r.length;y++)f[y]=r[y](h,u,l);try{return n(i,f,h,u,l)}catch(y){if(y instanceof b)return y;throw y}}}return this.lifted(t,o)}toolpakArg(e,i){const{cx:a}=this,o=t=>typeof t=="boolean"&&!i?R:t;if(e.t!=="range"&&e.t!=="rows"&&e.t!=="cols"&&e.t!=="union"&&e.t!=="call"&&e.t!=="name"){const t=this.value(e);return(s,r,n)=>o(t(s,r,n))}const c=this.any(e);return(t,s,r)=>{const n=c(t,s,r);return n instanceof g||!a.legacy&&n instanceof m&&(n.r0!==n.r1||n.c0!==n.c1)?R:o(n instanceof m?a.refAuto(n,t,s):n)}}lifted(e,i){const{cx:a}=this,{fn:o,errors:c}=e,t=i.map((r,n)=>r.t==="omit"?()=>M:e.toolpak?this.toolpakArg(r,e.toolpak.logical.includes(n)):this.value(r)),s=t.length;if(s===1){const r=t[0];return(n,h,u)=>{const l=r(n,h,u);if(l instanceof x)return a.liftArr(o,[l],c);if(!c&&l instanceof b)return l;try{return o(l)}catch(f){if(f instanceof b)return f;throw f}}}if(s===2){const[r,n]=t;return(h,u,l)=>{const f=r(h,u,l),y=n(h,u,l);if(f instanceof x||y instanceof x)return a.liftArr(o,[f,y],c);if(!c){if(f instanceof b)return f;if(y instanceof b)return y}try{return o(f,y)}catch(v){if(v instanceof b)return v;throw v}}}return(r,n,h)=>{const u=new Array(s);let l=!1;for(let f=0;f<s;f++){const y=t[f](r,n,h);u[f]=y,y instanceof x&&(l=!0)}if(l)return a.liftArr(o,u,c);if(!c){for(let f=0;f<s;f++)if(u[f]instanceof b)return u[f]}try{return o(...u)}catch(f){if(f instanceof b)return f;throw f}}}compileLet(e){const{cx:i}=this;if(e.length<3||e.length%2===0)return()=>p.VALUE;const a=new Map;this.scopes.push(a);const o=[];for(let t=0;t+1<e.length;t+=2){const s=e[t];if(s.t!=="name")return this.scopes.pop(),()=>p.VALUE;const r=this.any(e[t+1]),n=this.slots++;this.mayYieldRange(e[t+1])&&this.rangeSlots.add(n),a.set(s.name.toUpperCase(),n),o.push(n,r)}const c=this.any(e[e.length-1]);return this.scopes.pop(),(t,s,r)=>{for(let n=0;n<o.length;n+=2)i.frame[o[n]]=o[n+1](t,s,r);return c(t,s,r)}}compileLambda(e){const{cx:i}=this;if(e.length===0)return()=>p.VALUE;const a=new Map;this.scopes.push(a);const o=[];for(let t=0;t<e.length-1;t++){const s=e[t];if(s.t!=="name")return this.scopes.pop(),()=>p.VALUE;const r=this.slots++;this.rangeSlots.add(r),a.set(s.name.toUpperCase(),r),o.push(r)}const c=this.any(e[e.length-1]);return this.scopes.pop(),()=>new w(o,c,i.frame)}}export{B as Compiler,L as compareValues,k as num,V as str};
1
+ import{MAX_COLS as d,MAX_ROWS as A}from"../core/address.js";import{Arr as x,compareValues as L,ERR as p,Lambda as w,num as k,OMITTED as M,Ref as m,RefList as g,REJECTED as R,str as U,XlError as b}from"./values.js";import{FUNCS as E}from"./functions/registry.js";const C=5e-16;class N{constructor(e){this.cx=e,this.refs=[],this.names=[],this.tables=[],this.isVolatile=!1,this.readsSheets=!1,this.mayArray=!1,this.external=!1,this.arrayCtx=!1,this.scopes=[],this.slots=0,this.rangeSlots=new Set}compileTop(e){const i=this.any(e),{slots:a,cx:c}=this;return a===0?i:(o,t,r)=>{const s=c.frame;c.frame=new Array(a);try{return i(o,t,r)}finally{c.frame=s}}}sheetOf(e){const{cx:i}=this;if(e==null)return t=>t;if(e.book!==null&&e.book!==void 0){const t=i.externalSheet?.(e.book,e.sheet)??null;return t===null&&(this.external=!0),()=>t}const a=e.sheet;let c=-1,o=null;return()=>(c!==i.sheetGen&&(o=i.sheetByName(a),c=i.sheetGen),o)}cellRefClosure(e){const i=this.sheetOf(e.sheet),{rAbs:a,cAbs:c,r:o,c:t}=e;return this.refs.push({sheet:e.sheet,rAbs0:a,r0:o,rAbs1:a,r1:o,cAbs0:c,c0:t,cAbs1:c,c1:t}),e.sheet?.sheet2?this.sheet3d(e.sheet,(r,s,n)=>{const u=a?o:s+o,h=c?t:n+t;return new m(r,u,h,u,h)}):(r,s,n)=>{const u=a?o:r+o,h=c?t:s+t,l=i(n);return l===null||u<0||h<0||u>=A||h>=d?p.REF:new m(l,u,h,u,h)}}sheet3d(e,i){const{cx:a}=this;return(c,o)=>{const t=a.sheetsBetween(e.sheet,e.sheet2);return t===null?p.REF:new g(t.map(r=>i(r,c,o)))}}rangeClosure(e){const{a:i,b:a}=e,c=this.sheetOf(e.sheet);this.refs.push({sheet:e.sheet,rAbs0:i.rAbs,r0:i.r,rAbs1:a.rAbs,r1:a.r,cAbs0:i.cAbs,c0:i.c,cAbs1:a.cAbs,c1:a.c});const o=(t,r,s)=>{const n=i.rAbs?i.r:r+i.r,u=i.cAbs?i.c:s+i.c,h=a.rAbs?a.r:r+a.r,l=a.cAbs?a.c:s+a.c;return n<0||u<0||h<0||l<0||n>=A||h>=A||u>=d||l>=d?p.REF:new m(t,Math.min(n,h),Math.min(u,l),Math.max(n,h),Math.max(u,l))};return e.sheet?.sheet2?this.sheet3d(e.sheet,o):(t,r,s)=>{const n=c(s);return n===null?p.REF:o(n,t,r)}}rowsClosure(e){const i=this.sheetOf(e.sheet);return this.refs.push({sheet:e.sheet,rAbs0:e.a0,r0:e.r0,rAbs1:e.a1,r1:e.r1,cAbs0:!0,c0:0,cAbs1:!0,c1:d-1}),(a,c,o)=>{const t=e.a0?e.r0:a+e.r0,r=e.a1?e.r1:a+e.r1,s=i(o);return s===null||t<0||r<0||t>=A||r>=A?p.REF:new m(s,Math.min(t,r),0,Math.max(t,r),d-1)}}colsClosure(e){const i=this.sheetOf(e.sheet);return this.refs.push({sheet:e.sheet,rAbs0:!0,r0:0,rAbs1:!0,r1:A-1,cAbs0:e.a0,c0:e.c0,cAbs1:e.a1,c1:e.c1}),(a,c,o)=>{const t=e.a0?e.c0:c+e.c0,r=e.a1?e.c1:c+e.c1,s=i(o);return s===null||t<0||r<0||t>=d||r>=d?p.REF:new m(s,0,Math.min(t,r),A-1,Math.max(t,r))}}any(e){const{cx:i}=this;switch(e.t){case"lit":{const a=e.v;return()=>a}case"omit":return()=>M;case"paren":return this.any(e.e);case"cell":return this.cellRefClosure(e);case"range":return this.rangeClosure(e);case"rows":return this.rowsClosure(e);case"cols":return this.colsClosure(e);case"array":{const a=x.of2D(e.rows);return()=>a}case"union":{const a=e.items.map(c=>this.any(c));return(c,o,t)=>{const r=[];for(const s of a){const n=s(c,o,t);if(n instanceof m)r.push(n);else if(n instanceof g)r.push(...n.refs);else return n instanceof b?n:p.VALUE}return new g(r)}}case"intersect":{const a=this.any(e.l),c=this.any(e.r);return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);if(s instanceof b)return s;if(n instanceof b)return n;if(!(s instanceof m)||!(n instanceof m)||s.sheet!==n.sheet)return p.VALUE;const u=Math.max(s.r0,n.r0),h=Math.min(s.r1,n.r1),l=Math.max(s.c0,n.c0),f=Math.min(s.c1,n.c1);return u>h||l>f?p.NULL:new m(s.sheet,u,l,h,f)}}case"rangeOp":{const a=this.any(e.l),c=this.any(e.r);return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);return s instanceof b?s:n instanceof b?n:!(s instanceof m)||!(n instanceof m)||s.sheet!==n.sheet?p.REF:new m(s.sheet,Math.min(s.r0,n.r0),Math.min(s.c0,n.c0),Math.max(s.r1,n.r1),Math.max(s.c1,n.c1))}}case"implicit":{const a=this.any(e.e);return(c,o,t)=>{const r=a(c,o,t);return r instanceof m?r.isCell?i.read(r.sheet,r.r0,r.c0):i.intersect(r,c,o):r instanceof x?r.data[0]:r}}case"spillRef":{const a=this.any(e.e);return(c,o,t)=>{const r=a(c,o,t);return r instanceof m?i.spillRange(r):p.REF}}case"name":return this.nameNode(e);case"table":return this.tables.push({name:e.name,spec:e.spec}),(a,c,o)=>i.resolveTable(e.name,e.spec,a,c,o);case"call":return this.call(e);case"apply":{const a=this.any(e.fn),c=e.args.map(o=>this.any(o));return(o,t,r)=>{const s=a(o,t,r);return s instanceof b?s:s instanceof w?i.invoke(s,c.map(n=>n(o,t,r)),o,t,r):p.VALUE}}default:return this.value(e)}}nameNode(e){const{cx:i}=this,a=this.lookupVar(e.name);if(a!==null){const s=a;return()=>i.frame[s]}const c=i.tables?.get(e.name.toUpperCase());if(c&&(!e.sheet||e.sheet.book===null&&!e.sheet.sheet2&&e.sheet.sheet.toUpperCase()===c.sheet.name.toUpperCase()))return this.any({t:"table",name:e.name,spec:"[]"});this.names.push(e.name);const o=e.name,t=e.sheet?this.sheetOf(e.sheet):s=>s,r=e.sheet?void 0:E.get(o.toUpperCase());if(r!==void 0){const s=new w([],null,null);return s.native=r,s.label=o.toUpperCase(),(n,u,h)=>{const l=i.evalName(o,n,u,h);return l===p.NAME?s:l}}return(s,n,u)=>i.evalName(o,s,n,t(u)??u)}lookupVar(e){const i=e.toUpperCase();for(let a=this.scopes.length-1;a>=0;a--){const c=this.scopes[a].get(i);if(c!==void 0)return c}return null}deref(e){const{cx:i}=this;return this.arrayCtx?(a,c,o)=>{const t=e(a,c,o);return t instanceof m||t instanceof g?i.refToValue(t):t}:(a,c,o)=>{const t=e(a,c,o);return t instanceof m||t instanceof g?i.refAuto(t,a,c):t}}value(e){const{cx:i}=this;switch(e.t){case"lit":{const a=e.v;return()=>a}case"paren":return this.value(e.e);case"cell":{const{rAbs:a,cAbs:c,r:o,c:t}=e;if(this.refs.push({sheet:e.sheet,rAbs0:a,r0:o,rAbs1:a,r1:o,cAbs0:c,c0:t,cAbs1:c,c1:t}),e.sheet?.sheet2)return()=>p.VALUE;const r=e.sheet?this.sheetOf(e.sheet):null;return r===null?!a&&!c?(s,n,u)=>{const h=s+o,l=n+t;return h<0||l<0||h>=A||l>=d?p.REF:i.read(u,h,l)}:(s,n,u)=>{const h=a?o:s+o,l=c?t:n+t;return h<0||l<0||h>=A||l>=d?p.REF:i.read(u,h,l)}:(s,n,u)=>{const h=a?o:s+o,l=c?t:n+t,f=r(u);return f===null||h<0||l<0||h>=A||l>=d?p.REF:i.read(f,h,l)}}case"range":case"rows":case"cols":return this.arrayCtx||(this.mayArray=!0),this.deref(this.any(e));case"neg":{const a=this.value(e.e);return(c,o,t)=>{const r=a(c,o,t);return typeof r=="number"?-r:i.unary(r,s=>-s)}}case"pct":{const a=this.value(e.e);return(c,o,t)=>{const r=a(c,o,t);return typeof r=="number"?r/100:i.unary(r,s=>s/100)}}case"bin":return this.binary(e);default:return!this.arrayCtx&&this.mayYieldRange(e)&&(this.mayArray=!0),this.deref(this.any(e))}}mayYieldRange(e){switch(e.t){case"paren":return this.mayYieldRange(e.e);case"range":case"rows":case"cols":case"union":case"rangeOp":case"intersect":case"spillRef":case"apply":return!0;case"table":return!/^\[\[#This Row\],\[[^\]]+\]\]$/i.test(e.spec);case"name":{if(e.sheet)return!0;const i=this.lookupVar(e.name);return i!==null?this.rangeSlots.has(i):this.cx.nameMayYieldRange?.(e.name)??!0}case"call":{if(e.name==="LET"||e.name==="LAMBDA"||this.lookupVar(e.name)!==null)return!0;const i=E.get(e.name);return i===void 0||i.refResult?!0:i.passes?e.args.some((a,c)=>i.passes(c,e.args.length)&&this.mayYieldRange(a)):!1}default:return!1}}binary(e){const{cx:i}=this,a=this.value(e.l),c=this.value(e.r);switch(e.op){case"+":return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);if(typeof s=="number"&&typeof n=="number"){const u=s+n;return Math.abs(u)<Math.abs(s)*C?0:u}return i.slowBin("+",s,n)};case"-":return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);if(typeof s=="number"&&typeof n=="number"){const u=s-n;return Math.abs(u)<Math.abs(s)*C?0:u}return i.slowBin("-",s,n)};case"*":return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);return typeof s=="number"&&typeof n=="number"?s*n:i.slowBin("*",s,n)};case"/":return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);return typeof s=="number"&&typeof n=="number"&&n!==0?s/n:i.slowBin("/",s,n)};case"^":return(o,t,r)=>i.slowBin("^",a(o,t,r),c(o,t,r));case"&":return(o,t,r)=>i.slowBin("&",a(o,t,r),c(o,t,r));default:{const o=e.op;return(t,r,s)=>i.slowBin(o,a(t,r,s),c(t,r,s))}}}call(e){const{cx:i}=this,{name:a,args:c}=e;if(a==="LET")return this.compileLet(c);if(a==="LAMBDA")return this.compileLambda(c);const o=this.lookupVar(a);if(o!==null){const r=o,s=c.map(n=>this.any(n));return(n,u,h)=>{const l=i.frame[r];return l instanceof w?i.invoke(l,s.map(f=>f(n,u,h)),n,u,h):p.VALUE}}const t=E.get(a);if(t===void 0){this.names.push(a);const r=c.map(s=>this.any(s));return(s,n,u)=>{const h=i.evalName(a,s,n,u);return h instanceof w?i.invoke(h,r.map(l=>l(s,n,u)),s,n,u):p.NAME}}if((c.length<t.min||c.length>t.max)&&!(c.length===1&&c[0].t==="omit"&&t.min===0))return()=>p.VALUE;if(t.volatile&&(this.isVolatile=!0),t.readsSheets&&(this.readsSheets=!0),t.notInExcel&&(this.notInExcel=!0),t.frozen&&(this.external=!0),t.kind==="lazy"||t.kind==="raw"){const r=this.arrayCtx;t.array&&(this.arrayCtx=!0);const s=c.map(u=>this.any(u));this.arrayCtx=r;const{fn:n}=t;return t.kind==="lazy"?(u,h,l)=>{try{return n(i,s,u,h,l)}catch(f){if(f instanceof b)return f;throw f}}:(u,h,l)=>{const f=new Array(s.length);for(let y=0;y<s.length;y++)f[y]=s[y](u,h,l);try{return n(i,f,u,h,l)}catch(y){if(y instanceof b)return y;throw y}}}return this.lifted(t,c)}toolpakArg(e,i){const{cx:a}=this,c=t=>typeof t=="boolean"&&!i?R:t;if(e.t!=="range"&&e.t!=="rows"&&e.t!=="cols"&&e.t!=="union"&&e.t!=="call"&&e.t!=="name"){const t=this.value(e);return(r,s,n)=>c(t(r,s,n))}const o=this.any(e);return(t,r,s)=>{const n=o(t,r,s);return n instanceof g||!a.legacy&&n instanceof m&&(n.r0!==n.r1||n.c0!==n.c1)?R:c(n instanceof m?a.refAuto(n,t,r):n)}}lifted(e,i){const{cx:a}=this,{fn:c,errors:o}=e,t=i.map((s,n)=>s.t==="omit"?()=>M:e.toolpak?this.toolpakArg(s,e.toolpak.logical.includes(n)):this.value(s)),r=t.length;if(r===1){const s=t[0];return(n,u,h)=>{const l=s(n,u,h);if(l instanceof x)return a.liftArr(c,[l],o);if(!o&&l instanceof b)return l;try{return c(l)}catch(f){if(f instanceof b)return f;throw f}}}if(r===2){const[s,n]=t;return(u,h,l)=>{const f=s(u,h,l),y=n(u,h,l);if(f instanceof x||y instanceof x)return a.liftArr(c,[f,y],o);if(!o){if(f instanceof b)return f;if(y instanceof b)return y}try{return c(f,y)}catch(v){if(v instanceof b)return v;throw v}}}return(s,n,u)=>{const h=new Array(r);let l=!1;for(let f=0;f<r;f++){const y=t[f](s,n,u);h[f]=y,y instanceof x&&(l=!0)}if(l)return a.liftArr(c,h,o);if(!o){for(let f=0;f<r;f++)if(h[f]instanceof b)return h[f]}try{return c(...h)}catch(f){if(f instanceof b)return f;throw f}}}compileLet(e){const{cx:i}=this;if(e.length<3||e.length%2===0)return()=>p.VALUE;const a=new Map;this.scopes.push(a);const c=[];for(let t=0;t+1<e.length;t+=2){const r=e[t];if(r.t!=="name")return this.scopes.pop(),()=>p.VALUE;const s=this.any(e[t+1]),n=this.slots++;this.mayYieldRange(e[t+1])&&this.rangeSlots.add(n),a.set(r.name.toUpperCase(),n),c.push(n,s)}const o=this.any(e[e.length-1]);return this.scopes.pop(),(t,r,s)=>{for(let n=0;n<c.length;n+=2)i.frame[c[n]]=c[n+1](t,r,s);return o(t,r,s)}}compileLambda(e){const{cx:i}=this;if(e.length===0)return()=>p.VALUE;const a=new Map;this.scopes.push(a);const c=[];for(let t=0;t<e.length-1;t++){const r=e[t];if(r.t!=="name")return this.scopes.pop(),()=>p.VALUE;const s=this.slots++;this.rangeSlots.add(s),a.set(r.name.toUpperCase(),s),c.push(s)}const o=this.any(e[e.length-1]);return this.scopes.pop(),()=>new w(c,o,i.frame)}}export{N as Compiler,L as compareValues,k as num,U as str};
package/calc/engine.js CHANGED
@@ -1 +1 @@
1
- import{resolveStructuredSpec as yt}from"../slicers/structured.js";import{Arr as C,compareValues as v,ERR as k,ERR_BY_INDEX as Y,Lambda as kt,num as S,power as _t,Ref as q,RefList as $,RichValue as O,str as rt,XlError as x}from"./values.js";import{entityVm as at,richValueAt as gt}from"../cells/rich-values.js";import{Compiler as lt}from"./compile.js";import{FormulaSyntaxError as W,Parser as j,templateKey as bt,tokenize as z,toDisplayFormula as Mt}from"./parser.js";import{BOOL as G,CHUNK_BITS as E,CHUNK_MASK as T,CONTENT_MASK as ot,DIRTY as w,EMPTY as Q,EVALUATING as X,FORMULA as R,KIND_MASK as V,NUM as U,SPILL as H,STR as B,ERR as N}from"../core/sheet.js";import{colName as ct,MAX_COLS as M,MAX_ROWS as J,parseRangeRef as P}from"../core/address.js";import{CellSet as wt}from"./cell-set.js";import{isRowBelow as At}from"./fill-shape.js";import"./functions/index.js";const Z=Symbol("pending"),ht=200,Ct=4096,xt=64,tt=2147483647,D=4;class et{constructor(){this.n=0,this.data=new Int32Array(D*8)}push(t,e,s,n){if((this.n+1)*D>this.data.length){const a=new Int32Array(this.data.length*2);a.set(this.data),this.data=a}const i=this.n++*D,r=this.data;r[i]=t,r[i+1]=e,r[i+2]=s,r[i+3]=n}}function Tt(m,t){if(!m.valueMeta.has(t))return;const e=new Map(m.valueMeta);e.delete(t),m.valueMeta=e.size>0?e:null}function ft(m,t,e){if(m.valueMeta?.get(t)===e)return;const s=new Map(m.valueMeta??[]);s.set(t,e),m.valueMeta=s}function st(m,t){let e=m.get(t);return e===void 0&&(e=new wt,m.set(t,e)),e}class Rt{constructor(){this.buckets=[],this.wide=[],this.all=new et,this.allCols=[]}}class Bt{constructor(t){this.book=t,this.sheetGen=0,this.sheetMap=new Map,this.deps=new Map,this.templates=new Map,this.lastOwn={row:-2,col:-1,text:"",tpl:{cacheKey:void 0}},this.frame=null,this.depth=0,this.legacy=!1,this.pendingSheet=null,this.pendingRow=0,this.pendingCol=0,this.circular=null,this.evalStack=new Int32Array(3*256),this.evalTop=0,this.cycleLow=tt,this.iterate=null,this.cycleFound=[],this.cycleMembers=null,this.iterating=!1,this.sliceMs=10,this.syncLimit=4e3,this.externalLinks=null,this.names=new Map,this.nameTemplates=new Map,this.tables=new Map,this.volatile=new Map,this.visibilityReaders=new Map,this.styleReaders=new Map,this.wakePending=0,this.queue=new Int32Array(4096),this.qHead=0,this.qLen=0,this.sheetsByUid=new Map,this.running=!1,this.timer=0,this.manual=!1,this.graphReady=!0,this.pendingChanges=[],this.waiters=[],this.onChange=null,this.dataTables=[],this.tablesDirty=!1,this.inTables=!1,this.tablesForced=!1,this.onProgress=null,this.lookupCache=new Map,this.colRevisions=new Map,this.channel=null,this.sheetsChanged()}orderChanged(){this.sheetsChanged(),this.has3D&&this.rebuild()}sheetsChanged(){this.sheetGen++,this.sheetMap.clear(),this.sheetsByUid.clear();for(const t of this.book.sheets)this.sheetMap.set(t.name.toUpperCase(),t),this.sheetsByUid.set(t.uid,t),t.rows.watcher=this,t.cols.watcher=this}sheetByName(t){return this.sheetMap.get(t.toUpperCase())??null}externalSheet(t,e){return this.externalLinks?.sheet(t,e)??null}sheetsBetween(t,e){const{sheets:s}=this.book,n=s.findIndex(r=>r.name.toUpperCase()===t.toUpperCase()),i=s.findIndex(r=>r.name.toUpperCase()===e.toUpperCase());return n<0||i<0?null:s.slice(Math.min(n,i),Math.max(n,i)+1)}setNames(t){this.names.clear(),this.nameTemplates.clear();for(const e of t){const s=e.localSheetId!==void 0?`${e.localSheetId}!${e.name.toUpperCase()}`:e.name.toUpperCase();this.names.set(s,{text:e.text,name:e.name,hidden:e.hidden,comment:e.comment})}}setTables(t){this.tables.clear();for(const e of t)this.tables.set(e.name.toUpperCase(),e)}template(t,e,s){let n;try{n=z(t)}catch(a){if(a instanceof W)return this._broken(t);throw a}const i=bt(n,e,s);let r=this.templates.get(i);if(r===void 0){try{const a=new j(n,e,s).parse();r=this._compile(a)}catch(a){if(!(a instanceof W))throw a;r=this._broken(t)}r.cacheKey=i,this.templates.set(i,r)}return r}_ownTemplate(t,e,s){const n=this.lastOwn;let i;return n.row===e-1&&n.col===s&&this.templates.get(n.tpl.cacheKey)===n.tpl&&At(n.text,t)?i=n.tpl:i=this.template(t,e,s),n.row=e,n.col=s,n.text=t,n.tpl=i,i}_compile(t){const e=new lt(this);return{fn:e.compileTop(t),refs:e.refs,names:e.names,tables:e.tables,isVolatile:e.isVolatile,notInExcel:e.notInExcel===!0,mayArray:e.mayArray,external:e.external}}_broken(){return{invalid:!0,fn:()=>k.NAME,refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1,external:!0}}validate(t){it(new j(z(t),0,0).parse())}_templateFor(t,e,s,n){if(n.tpl!==void 0)return n.tpl;let i;return n.t==="dataTable"?i=this._dataTableTemplate():n.f!==void 0&&n.base===void 0?i=this._ownTemplate(n.f,e,s):n.f!==void 0?i=this.template(n.f,Math.floor(n.base/M),n.base%M):n.sf!==void 0?i=this.template(n.sf,Math.floor(n.base/M),n.base%M):i=this._broken(),n.tpl=i,i}_index(t){let e=this.deps.get(t);return e===void 0&&(e=new Rt,this.deps.set(t,e)),e}_addDep(t,e,s,n,i,r,a,o){const l=this._index(t),c=r.uid<<14|o;if(i-s>=xt){l.all.push(a,c,e,n),l.allCols.push(s,i);return}if(n-e>=Ct){for(let p=s;p<=i;p++){let f=l.wide[p];f===void 0&&(f=new et,l.wide[p]=f),f.push(a,c,e,n)}return}const u=e>>>E,d=n>>>E;for(let p=s;p<=i;p++){let f=l.buckets[p];f===void 0&&(f=[],l.buckets[p]=f);for(let h=u;h<=d;h++){let y=f[h];y===void 0&&(y=new et,f[h]=y),y.push(a,c,e,n)}}}register(t,e,s,n){const i=this._templateFor(t,e,s,n);if(i.external)return i;for(const r of i.refs)this._addRefDep(r,t,e,s);for(const r of i.names)this._addNameDeps(r,t,e,s);for(const r of i.tables)this._addTableDep(r,t,e,s);return i.isVolatile&&st(this.volatile,t).add(e,s),i.readsVisibility??=/SUBTOTAL|AGGREGATE|SPARK_/i.test(n.f??n.sf??""),i.readsVisibility&&st(this.visibilityReaders,t).add(e,s),i.readsStyles??=/SPARK_BLOCK/i.test(n.f??n.sf??""),i.readsStyles&&st(this.styleReaders,t).add(e,s),i}_addRefDep(t,e,s,n){const i=t.rAbs0?t.r0:s+t.r0,r=t.rAbs1?t.r1:s+t.r1,a=t.cAbs0?t.c0:n+t.c0,o=t.cAbs1?t.c1:n+t.c1,l=Math.max(0,Math.min(i,r)),c=Math.min(J-1,Math.max(i,r)),u=Math.max(0,Math.min(a,o)),d=Math.min(M-1,Math.max(a,o));if(l>c||u>d)return;if(t.sheet?.sheet2&&(t.sheet.book===null||t.sheet.book===void 0)){this.has3D=!0;for(const f of this.sheetsBetween(t.sheet.sheet,t.sheet.sheet2)??[])this._addDep(f,l,u,c,d,e,s,n);return}if(t.sheet?.book!==null&&t.sheet?.book!==void 0)return;const p=t.sheet?this.sheetByName(t.sheet.sheet):e;p&&this._addDep(p,l,u,c,d,e,s,n)}_addNameDeps(t,e,s,n){const i=this._nameTemplate(t,e);if(i!==null){for(const r of i.refs)this._addRefDep(r,e,s,n);for(const r of i.names)r.toUpperCase()!==t.toUpperCase()&&this._addNameDeps(r,e,s,n)}}_addTableDep(t,e,s,n){const i=this.resolveTable(t.name,t.spec,s,n,e);i instanceof q&&this._addDep(i.sheet,i.r0,i.c0,i.r1,i.c1,e,s,n)}rebuild(){this.has3D=!1,this.deps.clear(),this.volatile.clear(),this.visibilityReaders.clear(),this.styleReaders.clear(),this.lookupCache.clear(),this.qHead=0,this.qLen=0,this.cycleFound=[],this.cycleMembers=null,this.sheetGen++,this.buildGraph({fullCalc:!0})}buildGraph({fullCalc:t=!1,onDone:e}={}){this.graphReady=!1,this.dataTables=[],t&&(this.tablesDirty=!0);const s=this,n=this.book.sheets.map(c=>[c,c.formulas]);let i=0,r=0,a=0,o=0;const l=()=>{const c=performance.now()+s.sliceMs;let u=0;for(;i<n.length;i++,r=0,a=0,o=0){const[p,f]=n[i],{columns:h}=f;for(;r<h.length;r++,a=0,o=0){const y=h[r];if(y!==void 0)for(;a<y.length;a++,o=0){const _=y[a];if(_===void 0)continue;const{ids:g}=_,b=a<<E;for(;o<=T;o++){const L=g[o];if(L===0)continue;const A=f.infos[L],I=b+o;A.t==="dataTable"&&s.dataTables.push({sheet:p,row:I,col:r,info:A});const F=s.register(p,I,r,A);if(s._initFormula(p,I,r,A,F,t),++u%256===0&&performance.now()>c){o++,s.onProgress?.({preparing:!0}),s._later(l);return}}}}}s.graphReady=!0;const d=s.pendingChanges;s.pendingChanges=[];for(const[p,f,h,y]of d)s.cellsChanged(p,f,h,y);s._schedule(),e?.()};l()}_initFormula(t,e,s,n,i,r){const a=t._chunk(e,s);if(a===void 0)return;const o=e&T;if(n.t==="array"&&n.ref&&this._markArrayChildren(t,e,s,n),i.external)return;const l=a.kinds[o];(r||i.isVolatile||(l&V)===Q||i.notInExcel&&(l&V)===N)&&(a.kinds[o]=l|w,this._enqueue(t,e,s))}_markArrayChildren(t,e,s,n){const i=P(n.ref);if(i!==null){t.spills||(t.spills=new Map),t.spills.set(e*M+s,{...i,blocked:!1,fixed:!n.cm});for(let r=i.r0;r<=i.r1;r++)for(let a=i.c0;a<=i.c1;a++){if(r===e&&a===s)continue;const o=t._ensure(r,a);o.kinds[r&T]|=H}}}_enqueue(t,e,s){if(this.qLen+3>this.queue.length)if(this.qHead>this.queue.length>>>1)this.queue.copyWithin(0,this.qHead,this.qLen),this.qLen-=this.qHead,this.qHead=0;else{const n=new Int32Array(this.queue.length*2);n.set(this.queue),this.queue=n}this.queue[this.qLen++]=t.uid,this.queue[this.qLen++]=e,this.queue[this.qLen++]=s}_dirtyFrom(t,e,s,n,i){const r=[t,e,s,n,i];for(;r.length>0;){const a=r.pop(),o=r.pop(),l=r.pop(),c=r.pop(),u=r.pop(),d=this.deps.get(u);if(d===void 0)continue;const p=(y,_)=>{const g=this.sheetsByUid.get(_>>>14);if(g===void 0)return;const b=_&16383,L=g._chunk(y,b);if(L===void 0)return;const A=y&T,I=L.kinds[A];(I&R)===0||(I&w)!==0||(L.kinds[A]=I|w,this._enqueue(g,y,b),r.push(g,b,b,y,y))},f=o>>>E,h=a>>>E;for(let y=c;y<=l;y++){const _=d.buckets[y];if(_!==void 0)for(let b=f;b<=h;b++){const L=_[b];if(L===void 0)continue;const{data:A}=L,I=L.n*D;for(let F=0;F<I;F+=D)a>=A[F+2]&&o<=A[F+3]&&p(A[F],A[F+1])}const g=d.wide[y];if(g!==void 0){const{data:b}=g,L=g.n*D;for(let A=0;A<L;A+=D)a>=b[A+2]&&o<=b[A+3]&&p(b[A],b[A+1])}}if(d.all.n>0){const{data:y}=d.all;for(let _=0;_<d.all.n;_++){const g=_*D;a>=y[g+2]&&o<=y[g+3]&&l>=d.allCols[_*2]&&c<=d.allCols[_*2+1]&&p(y[g],y[g+1])}}}}cellsChanged(t,e,s,n){if(n===0)return;if(this.inTables||(this.tablesDirty=!0),!this.graphReady){this.pendingChanges.push([t,e.slice(0,n),s.slice(0,n),n]);return}this.lookupCache.clear();const i=new Map;for(let r=0;r<n;r++){const a=e[r],o=s[r],l=i.get(o);l===void 0?i.set(o,[a,a]):(a<l[0]&&(l[0]=a),a>l[1]&&(l[1]=a));const c=t._chunk(a,o);if(c===void 0)continue;const u=a&T,d=c.kinds[u];if(d&R){const p=t.formula(a,o);p&&(this.register(t,a,o,p),d&w||(c.kinds[u]=d|w,this._enqueue(t,a,o)))}t.spills&&this._spillTouched(t,a,o)}for(const[r,a]of i)this._dirtyFrom(t,r,r,a[0],a[1]);this._markVolatile(),this._schedule()}_spillTouched(t,e,s){const n=e*M+s;for(const[i,r]of t.spills){const a=Math.floor(i/M),o=i-a*M;if(i===n){(t.kind(a,o)&R)===0&&(this._clearSpill(t,r,a,o),t.spills.delete(i));continue}if(e>=r.r0&&e<=r.r1&&s>=r.c0&&s<=r.c1){const l=t._chunk(a,o);if(l===void 0)continue;const c=a&T,u=l.kinds[c];u&R&&!(u&w)&&(l.kinds[c]=u|w,this._enqueue(t,a,o),this._dirtyFrom(t,o,o,a,a))}}}_markVolatile(){for(const[t,e]of this.volatile)e.forEach((s,n)=>{const i=t._chunk(s,n);if(i===void 0)return;const r=s&T,a=i.kinds[r];if(!(a&R)){e.delete(s,n);return}a&w||(i.kinds[r]=a|w,this._enqueue(t,s,n),this._dirtyFrom(t,n,n,s,s))})}get pending(){return(this.qLen-this.qHead)/3}_later(t){if(this._next=t,typeof MessageChannel>"u"){setTimeout(()=>this._tick(),0);return}this.channel===null&&(this.channel=new MessageChannel,this.channel.port1.onmessage=()=>this._tick()),this.channel.port2.postMessage(0)}_tick(){const t=this._next;this._next=null,t?.(),this._next===null&&this.channel!==null&&(this.channel.port1.close(),this.channel=null)}_schedule(){if(this.manual||this.inTables||this.running||!this.graphReady)return;if(this.pending===0){this._finish();return}const t=this.pending;if(t<=this.syncLimit&&(this._slice(this.syncLimit===1/0?1/0:this.sliceMs),this.pending===0)){this._finish();return}this.running=!0,this._total=t;const e=()=>{this._slice(this.sliceMs),this.pending>0?(this.onProgress?.({remaining:this.pending,total:Math.max(this._total,this.pending)}),this._later(e)):(this.running=!1,this._finish())};this._later(e)}_slice(t){const e=t!==1/0;let s=e?performance.now():0;const n=s+t;let i=1,r=1;for(;this.qHead<this.qLen;){const a=this.queue[this.qHead++],o=this.queue[this.qHead++],l=this.queue[this.qHead++],c=this.sheetsByUid.get(a);if(c!==void 0&&(this._run(c,o,l),e&&--r===0)){const u=performance.now();if(u>n)break;i=u-s<.5?Math.min(i*2,16):1,r=i,s=u}}this.qHead>=this.qLen&&(this.qHead=0,this.qLen=0)}_finish(){for(;this.cycleFound.length>0;)this._iterateCycles();const t=this.tablesForced;this.tablesForced=!1,this.tablesDirty&&this.dataTables.length>0&&(!this.skipTables||t)&&(this.tablesDirty=!1,this._computeDataTables()),this.onChange?.();const e=this.waiters;this.waiters=[];for(const s of e)s()}_dataTableTemplate(){const t=this;return{fn:(s,n,i)=>t._plainValue(i,s,n),refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1}}_plainValue(t,e,s){const n=t.value(e,s);switch(t.kind(e,s)&V){case U:return n;case B:return this.book.strings.get(n);case G:return n!==0;case N:return Y[n];default:return null}}_writePlain(t,e,s,n){const i=t.kind(e,s)&R;n==null?t.setCell(e,s,i|U,0):typeof n=="number"?Number.isFinite(n)?t.setCell(e,s,i|U,n):t.setCell(e,s,i|N,k.NUM.index):typeof n=="boolean"?t.setCell(e,s,i|G,n?1:0):n instanceof x?t.setCell(e,s,i|N,n.index):t.setCell(e,s,i|B,this.book.strings.add(String(n)))}_setInputs(t,e){const s=new Uint32Array(e.length),n=new Uint32Array(e.length);e.forEach((i,r)=>{t.setCell(i.row,i.col,i.kind,i.value),s[r]=i.row,n[r]=i.col}),this.cellsChanged(t,s,n,e.length),this._slice(1/0)}evaluateWith(t,e,s){const n=e.map(({row:r,col:a})=>({row:r,col:a,kind:t.kind(r,a)&(V|R),value:t.value(r,a)})),i=this.inTables;this.inTables=!0;try{return this._setInputs(t,e.map(({row:r,col:a,text:o})=>{const l=Number(o);return o!==""&&Number.isFinite(l)?{row:r,col:a,kind:U,value:l}:{row:r,col:a,kind:B,value:this.book.strings.add(String(o))}})),s()}finally{this._setInputs(t,n),this.inTables=i}}_computeDataTables(){this.inTables=!0;const t=this.dataTables.filter(e=>e.sheet.formula(e.row,e.col)===e.info&&this.book.sheets.includes(e.sheet));this.dataTables=t;try{for(const e of t)this._computeDataTable(e)}finally{this.inTables=!1}}_computeDataTable({sheet:t,info:e}){const s=P(e.ref),n=P(e.r1??"");if(!s||!n)return;const i=e.r2?P(e.r2):null,r=e.dt2D==="1"||e.dt2D==="true",a=e.dtr==="1"||e.dtr==="true",o=(h,y)=>({kind:t.kind(h,y)&V,value:t.value(h,y)}),c=[n,i].filter(Boolean).map(h=>({row:h.r0,col:h.c0,kind:t.kind(h.r0,h.c0)&(V|R),value:t.value(h.r0,h.c0)})),u=[];for(let h=s.r0;h<=s.r1;h++)for(let y=s.c0;y<=s.c1;y++){let _,g;r?(_=[{row:n.r0,col:n.c0,...o(s.r0-1,y)},{row:i.r0,col:i.c0,...o(h,s.c0-1)}],g=[s.r0-1,s.c0-1]):a?(_=[{row:n.r0,col:n.c0,...o(s.r0-1,y)}],g=[h,s.c0-1]):(_=[{row:n.r0,col:n.c0,...o(h,s.c0-1)}],g=[s.r0-1,y]),this._setInputs(t,_);let b=this.read(t,g[0],g[1]);b instanceof C&&(b=b.data[0]),u.push(h,y,b)}this._setInputs(t,c);const d=u.length/3,p=new Uint32Array(d),f=new Uint32Array(d);for(let h=0;h<d;h++)p[h]=u[h*3],f[h]=u[h*3+1],this._writePlain(t,p[h],f[h],u[h*3+2]);this.cellsChanged(t,p,f,d),this._slice(1/0),t.revision++}dataTableAt(t,e,s){for(const n of this.dataTables){if(n.sheet!==t)continue;const i=P(n.info.ref);if(i&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1)return n}return null}calculateNow(){const{manual:t,skipTables:e}=this;this.manual=!1,this.skipTables=!1,this.tablesDirty=!0,this.tablesForced=!0,this._markVolatile(),this._markCycles(),this._schedule(),this.manual=t,this.skipTables=e}whenIdle(){return this.pending===0&&this.graphReady&&!this.running?Promise.resolve():new Promise(t=>{this.waiters.push(t),this._schedule()})}_iterateCycles(){const t=this.cycleFound;this.cycleFound=[];const e=new Map,s=(a,o,l)=>{let c=e.get(a.uid);c===void 0&&(c=new Map,e.set(a.uid,c)),c.set(o*M+l,[a,o,l])};for(let a=0;a<t.length;a+=3)s(t[a],t[a+1],t[a+2]);const n=[];for(const a of this.book.sheets){const o=e.get(a.uid);o&&n.push(...[...o.keys()].sort((l,c)=>l-c).map(l=>o.get(l)))}this.cycleMembers??=new Map;for(const a of n)this.cycleMembers.set(`${a[0].uid}:${a[1]}:${a[2]}`,a);const{count:i,delta:r}=this.iterate;for(let a=1;a<=i;a++){let o=0;for(const[l,c,u]of n){const d=l._chunk(c,u);if(d===void 0)continue;const p=c&T;if(!(d.kinds[p]&R))continue;const f=d.values[p];d.kinds[p]|=w,this.iterating=!0,this._run(l,c,u),this.iterating=!1;const h=Math.abs(d.values[p]-f);h>o&&(o=h)}if(this.onProgress?.({iteration:a,iterations:i}),o<r)break}for(const[a,o,l]of n)this._dirtyFrom(a,l,l,o,o);for(const[a,o,l]of n){const c=a._chunk(o,l);c!==void 0&&(c.kinds[o&T]&=~w)}this._slice(1/0)}_markCycles(){if(!(this.iterate===null||this.cycleMembers===null))for(const[t,e,s]of this.cycleMembers.values()){const n=t._chunk(e,s);n===void 0||!(n.kinds[e&T]&R)||(n.kinds[e&T]|=w,this._enqueue(t,e,s))}}_run(t,e,s){const n=[t,e,s];for(;n.length>0;){const i=n[n.length-1],r=n[n.length-2],a=n[n.length-3];try{this.depth=0,this.evalTop=0,this.cycleLow=tt,this._calc(a,r,i),n.length-=3}catch(o){if(o!==Z)throw o;n.push(this.pendingSheet,this.pendingRow,this.pendingCol)}}}_calc(t,e,s){const n=t._chunk(e,s);if(n===void 0)return;const i=e&T,r=n.kinds[i];if(!(r&w))return;if(r&X){this.circular={sheet:t,row:e,col:s},this.iterating||this._cycleHit(t.uid,e,s);return}if(this.depth>=ht)throw this.pendingSheet=t,this.pendingRow=e,this.pendingCol=s,Z;const a=t.formula(e,s);if(a===void 0||!(r&R)){n.kinds[i]=r&~w;return}const o=this._templateFor(t,e,s,a);if(o.external){n.kinds[i]=r&~w;return}n.kinds[i]=r|X;const l=this.evalTop;l+3>this.evalStack.length&&this._growEvalStack(),this.evalStack[l]=t.uid,this.evalStack[l+1]=e,this.evalStack[l+2]=s,this.evalTop=l+3;const c=this.cycleLow;this.cycleLow=tt;const u=this.legacy,d=this.frame,p=a.typed!==!0&&a.t!=="array";this.legacy=p,this.depth++;let f;try{f=o.fn(e,s,t)}catch(y){if(n.kinds[i]&=~X,this.depth--,this.legacy=u,this.frame=d,this.evalTop=l,this.cycleLow=c,y===Z)throw y;y instanceof x?f=y:(console.error("Formula evaluation failed",y),f=k.VALUE),this._store(t,n,i,e,s,f,a,p);return}this.depth--,this.legacy=u,this.frame=d,this.evalTop=l;const h=this.cycleLow;if(this.cycleLow=h<l&&h<c?h:c,h<=l){if(this.iterate!==null){n.kinds[i]=r&~(w|X),this.cycleFound.push(t,e,s);return}f=0}this._store(t,n,i,e,s,f,a,p)}_cycleHit(t,e,s){const n=this.evalStack;for(let i=this.evalTop-3;i>=0;i-=3)if(n[i]===t&&n[i+1]===e&&n[i+2]===s){i<this.cycleLow&&(this.cycleLow=i);return}}_growEvalStack(){const t=new Int32Array(this.evalStack.length*2);t.set(this.evalStack),this.evalStack=t}_store(t,e,s,n,i,r,a,o){let l=r;(l instanceof q||l instanceof $)&&(l=o?this.refAuto(l,n,i):this.refToValue(l)),l instanceof kt&&(l=k.CALC),l instanceof C?a.t==="array"&&!a.cm&&a.ref?l=this._fillFixedArray(t,n,i,a,l):o||l.rows===1&&l.cols===1?(l=l.data[0],t.spills&&this._releaseSpill(t,n,i)):l=this._spill(t,n,i,a,l):t.spills&&!(a.t==="array"&&!a.cm)&&this._releaseSpill(t,n,i),a.t==="array"&&!a.cm&&a.ref&&!(r instanceof C)&&(l=this._fillFixedArray(t,n,i,a,C.filled(1,1,l)));let c=R,u=0;typeof l=="number"?Number.isFinite(l)?(c|=U,u=l):(c|=N,u=k.NUM.index):typeof l=="string"?(c|=B,u=this.book.strings.add(l)):typeof l=="boolean"?(c|=G,u=l?1:0):l instanceof x?(c|=N,u=l.index):l instanceof O?(c|=N,u=k.VALUE.index):c|=U,l instanceof O?ft(t,n*M+i,at(this.book,l.index)):t.valueMeta!==null&&((e.kinds[s]&ot)!==c||e.values[s]!==u)&&!/IMAGE\(/i.test(a.f??a.sf??"")&&Tt(t,n*M+i),e.kinds[s]=c,e.values[s]=u,n>t.maxRow&&(t.maxRow=n),i>t.maxCol&&(t.maxCol=i)}_writeArrayCell(t,e,s,n){let i=H,r=0;typeof n=="number"?(i|=Number.isFinite(n)?U:N,r=Number.isFinite(n)?n:k.NUM.index):typeof n=="string"?(i|=B,r=this.book.strings.add(n)):typeof n=="boolean"?(i|=G,r=n?1:0):n instanceof x?(i|=N,r=n.index):n==null?i|=U:(i|=N,r=k.VALUE.index,n instanceof O&&ft(t,e*M+s,at(this.book,n.index))),t.setCell(e,s,i,r)}_fillFixedArray(t,e,s,n,i){const r=P(n.ref);if(r===null)return i.data[0];t.spills||(t.spills=new Map),t.spills.set(e*M+s,{...r,blocked:!1,fixed:!0});const a=(l,c)=>{const u=i.rows===1?0:l,d=i.cols===1?0:c;return u>=i.rows||d>=i.cols?k.NA:i.get(u,d)};for(let l=r.r0;l<=r.r1;l++)for(let c=r.c0;c<=r.c1;c++)l===e&&c===s||this._writeArrayCell(t,l,c,a(l-r.r0,c-r.c0));this._dirtyFrom(t,r.c0,r.c1,r.r0,r.r1);const o=a(e-r.r0,s-r.c0);return o===null?0:o}_spill(t,e,s,n,i){const r=e*M+s;t.spills||(t.spills=new Map);const a=t.spills.get(r),o=e+i.rows-1,l=s+i.cols-1,c={r0:e,c0:s,r1:o,c1:l,blocked:!1,fixed:!1},u=(f,h)=>a&&f>=a.r0&&f<=a.r1&&h>=a.c0&&h<=a.c1;let d=o>=J||l>=M;if(!d)t:for(let f=e;f<=o;f++)for(let h=s;h<=l;h++){if(f===e&&h===s)continue;const y=t.kind(f,h);if((y&ot)!==0&&!(y&H&&u(f,h))){d=!0;break t}if(t.merges.length>0&&t.mergeAt(f,h)){d=!0;break t}}if(d)return a&&!a.blocked&&this._clearSpill(t,a,e,s),c.blocked=!0,c.r1=Math.min(o,J-1),c.c1=Math.min(l,M-1),t.spills.set(r,c),k.SPILL;if(a&&!a.blocked){for(let f=a.r0;f<=a.r1;f++)for(let h=a.c0;h<=a.c1;h++)f>=c.r0&&f<=c.r1&&h>=c.c0&&h<=c.c1||(t.kind(f,h)&H)!==0&&t.setCell(f,h,Q,0);this._dirtyFrom(t,a.c0,a.c1,a.r0,a.r1)}t.spills.set(r,c);for(let f=e;f<=o;f++)for(let h=s;h<=l;h++)f===e&&h===s||this._writeArrayCell(t,f,h,i.get(f-e,h-s));n.t="array",n.ref=`${ut(s)}${e+1}:${ut(l)}${o+1}`,n.cm=1,delete n.raw,this._dirtyFrom(t,s,l,e,o);const p=i.data[0];return p===null?0:p}_clearSpill(t,e,s,n){for(let i=e.r0;i<=e.r1;i++)for(let r=e.c0;r<=e.c1;r++)i===s&&r===n||(t.kind(i,r)&H)!==0&&t.setCell(i,r,Q,0);this._dirtyFrom(t,e.c0,e.c1,e.r0,e.r1)}_releaseSpill(t,e,s){const n=e*M+s,i=t.spills.get(n);if(i===void 0)return;i.blocked||this._clearSpill(t,i,e,s),t.spills.delete(n);const r=t.formula(e,s);r&&r.typed&&(delete r.ref,delete r.cm,delete r.t)}spillMaster(t,e,s){if(!t.spills)return null;for(const[n,i]of t.spills)if(!i.blocked&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1){const r=Math.floor(n/M);return{row:r,col:n-r*M,rect:i}}return null}spillRange(t){const{sheet:e,r0:s,c0:n}=t;this.read(e,s,n);const i=e.spills?.get(s*M+n);return!i||i.blocked?k.REF:new q(e,i.r0,i.c0,i.r1,i.c1)}read(t,e,s){const n=t.columns[s];if(n===void 0)return null;const i=n[e>>>E];if(i===void 0)return null;const r=e&T;let a=i.kinds[r];if(a===0)return null;switch(a&w&&(this._calc(t,e,s),a=i.kinds[r]),a&V){case U:return i.values[r];case B:return this.book.strings.get(i.values[r]);case G:return i.values[r]!==0;case N:{if(t.valueMeta!==null&&this.book.richValues){const o=gt(this.book,t,e,s);if(o!==null)return o}return Y[i.values[r]]??k.NA}default:return null}}refToValue(t){return t instanceof $?t.refs.length===1?this.refToValue(t.refs[0]):k.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.toArr(t)}refAuto(t,e,s){return t instanceof $?t.refs.length===1?this.refAuto(t.refs[0],e,s):k.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.legacy?this.intersect(t,e,s):this.toArr(t)}intersect(t,e,s){return t.cols===1&&e>=t.r0&&e<=t.r1?this.read(t.sheet,e,t.c0):t.rows===1&&s>=t.c0&&s<=t.c1?this.read(t.sheet,t.r0,s):k.VALUE}trim(t){const{sheet:e}=t;return{r0:t.r0,c0:t.c0,r1:Math.min(t.r1,Math.max(e.maxRow,t.r0)),c1:Math.min(t.c1,Math.max(e.maxCol,t.c0))}}toArr(t){if(t instanceof C)return t;if(t instanceof q){const{r0:e,c0:s,r1:n,c1:i}=this.trim(t),r=n-e+1,a=i-s+1,o=new Array(r*a);let l=0;for(let c=e;c<=n;c++)for(let u=s;u<=i;u++)o[l++]=this.read(t.sheet,c,u);return new C(r,a,o)}if(t instanceof $){if(t.refs.length===1)return this.toArr(t.refs[0]);throw k.VALUE}if(t instanceof x)throw t;return new C(1,1,[t])}scalar(t,e,s){return t instanceof q?t.isCell?this.read(t.sheet,t.r0,t.c0):this.intersect(t,e,s):t instanceof $?k.VALUE:t instanceof C?t.data[0]:t}scan(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);for(let r=t.c0;r<=n;r++){const a=s.columns[r];if(a!==void 0)for(let o=t.r0>>>E;o<=i>>>E;o++){const l=a[o];if(l===void 0)continue;const c=o<<E,u=Math.max(t.r0-c,0),d=Math.min(i-c,T),{kinds:p}=l;for(let f=u;f<=d;f++){if(p[f]===0)continue;const h=this.read(s,c+f,r);h!==null&&e(h,c+f,r)}}}}sumRange(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);let{sum:r,count:a}=e;for(let o=t.c0;o<=n;o++){const l=s.columns[o];if(l!==void 0)for(let c=t.r0>>>E;c<=i>>>E;c++){const u=l[c];if(u===void 0)continue;const d=c<<E,p=Math.max(t.r0-d,0),f=Math.min(i-d,T),{kinds:h,values:y}=u;for(let _=p;_<=f;_++){let g=h[_];if(g===0)continue;g&w&&(this._calc(s,d+_,o),g=h[_]);const b=g&V;if(b===U)r+=y[_],a++;else if(b===N)throw Y[y[_]]}}}e.sum=r,e.count=a}unary(t,e){if(t instanceof x)return t;if(t instanceof C)return new C(t.rows,t.cols,t.data.map(s=>{try{return s instanceof x?s:e(S(s))}catch(n){return n}}));try{return e(S(t))}catch(s){if(s instanceof x)return s;throw s}}slowBin(t,e,s){if(e instanceof C||s instanceof C)return this._binArr(t,e,s);if(e instanceof x)return e;if(s instanceof x)return s;try{return dt(t,e,s)}catch(n){if(n instanceof x)return n;throw n}}_binArr(t,e,s){const n=e instanceof C?e:null,i=s instanceof C?s:null,r=Math.max(n?n.rows:1,i?i.rows:1),a=Math.max(n?n.cols:1,i?i.cols:1),o=new Array(r*a);for(let l=0;l<r;l++)for(let c=0;c<a;c++){const u=nt(e,l,c),d=nt(s,l,c);let p;if(u instanceof x)p=u;else if(d instanceof x)p=d;else try{p=dt(t,u,d)}catch(f){p=f}o[l*a+c]=p}return new C(r,a,o)}liftArr(t,e,s){let n=1,i=1;for(const l of e)l instanceof C&&(l.rows>n&&(n=l.rows),l.cols>i&&(i=l.cols));const r=new Array(n*i),a=e.length,o=new Array(a);for(let l=0;l<n;l++)for(let c=0;c<i;c++){let u=null;for(let d=0;d<a;d++){const p=nt(e[d],l,c);o[d]=p,!s&&u===null&&p instanceof x&&(u=p)}if(u!==null){r[l*i+c]=u;continue}try{r[l*i+c]=t(...o)}catch(d){if(d instanceof x)r[l*i+c]=d;else throw d}}return new C(n,i,r)}invoke(t,e,s,n,i){if(t.native)return this._invokeNative(t.native,e,s,n,i);const r=t.frame?t.frame.slice():[],{params:a}=t;if(e.length>a.length)return k.VALUE;for(let l=0;l<a.length;l++)r[a[l]]=l<e.length?e[l]:void 0;const o=this.frame;if(this.frame=r,this.depth++,this.depth>=ht*4)return this.depth--,this.frame=o,k.NUM;try{return t.body(s,n,i)}finally{this.depth--,this.frame=o}}_invokeNative(t,e,s,n,i){if(e.length<t.min||e.length>t.max)return k.VALUE;try{if(t.kind==="raw")return t.fn(this,e,s,n,i);if(t.kind==="lazy")return t.fn(this,e.map(a=>()=>a),s,n,i);const r=e.map(a=>a instanceof q||a instanceof $?this.refToValue(a):a);if(r.some(a=>a instanceof C))return this.liftArr(t.fn,r,t.errors);if(!t.errors){for(const a of r)if(a instanceof x)return a}return t.fn(...r)}catch(r){if(r instanceof x)return r;throw r}}_nameEntry(t,e){const s=t.toUpperCase();if(e){const i=this.book.sheets.indexOf(e),r=this.names.get(`${i}!${s}`);if(r)return{key:`${i}!${s}`,entry:r}}const n=this.names.get(s);return n?{key:s,entry:n}:null}_nameTemplate(t,e){const s=this._nameEntry(t,e);if(s===null)return null;let n=this.nameTemplates.get(s.key);if(n===void 0){try{n=this._compile(new j(z(s.entry.text),0,0).parse())}catch(i){if(!(i instanceof W))throw i;n=this._broken()}this.nameTemplates.set(s.key,n)}return n}nameMayYieldRange(t){const e=t.toUpperCase(),s=[];for(const[n,i]of this.names)(n===e||n.endsWith(`!${e}`))&&s.push(i);if(s.length===0||(this._rangeNames??=new Set,this._rangeNames.has(e)))return!0;this._rangeNames.add(e);try{return s.some(n=>{try{return new lt(this).mayYieldRange(new j(z(n.text),0,0).parse())}catch(i){if(i instanceof W)return!1;throw i}})}finally{this._rangeNames.delete(e)}}evalName(t,e,s,n){const i=this._nameTemplate(t,n);return i===null?k.NAME:i.fn(e,s,n)}tableSpecToA1(t,e,s){const n=mt(t,e,s);if(!(n instanceof q))return null;const i=/#This Row|^\[\s*@/i.test(e),r=(a,o)=>i?`${ct(o)}${a+1}`:`$${ct(o)}$${a+1}`;return n.isCell?r(n.r0,n.c0):`${r(n.r0,n.c0)}:${r(n.r1,n.c1)}`}resolveTable(t,e,s,n,i){let r=t?this.tables.get(t.toUpperCase()):null;if(!t){for(const a of this.tables.values())if(a.sheet===i&&s>=a.r0&&s<=a.r1&&n>=a.c0&&n<=a.c1){r=a;break}}return r?mt(r,e,s):k.REF}exactIndex(t){const e=`${t.sheet.uid}:${t.r0}:${t.c0}:${t.r1}:${t.c1}`;let s=this.lookupCache.get(e);if(s!==void 0)return s;s=new Map;const n=t.cols===1;return this.scan(t,(i,r,a)=>{const o=typeof i=="string"?`s${i.toLowerCase()}`:typeof i=="number"?i:`b${i}`;if(i instanceof x)return;const l=n?r-t.r0:a-t.c0,c=s.get(o);(c===void 0||l<c)&&s.set(o,l)}),this.lookupCache.set(e,s),s}visibilityChanged(){this._wakeReaders(this.visibilityReaders)}presentationChanged(){this._wakeLater(2)}axisHiddenChanged(){this._wakeLater(1)}axisResized(){this._wakeLater(2)}_wakeLater(t){(t===1?this.visibilityReaders:this.styleReaders).size!==0&&(this.wakePending===0&&queueMicrotask(()=>{const e=this.wakePending;this.wakePending=0,e&1&&this._wakeReaders(this.visibilityReaders),e&2&&this._wakeReaders(this.styleReaders)}),this.wakePending|=t)}_wakeReaders(t){if(!this.graphReady||t.size===0)return;let e=!1;for(const[s,n]of t)n.forEach((i,r)=>{const a=s._chunk(i,r);if(a===void 0)return;const o=i&T,l=a.kinds[o];if(!(l&R)){n.delete(i,r);return}l&w||(a.kinds[o]=l|w,this._enqueue(s,i,r)),this._dirtyFrom(s,r,r,i,i),e=!0});e&&this._schedule()}isSubtotalCell(t,e,s){if((t.kind(e,s)&R)===0)return!1;const n=t.formula(e,s),i=n?.f??n?.sf??"";return/^\s*(_xlfn\.)?(SUBTOTAL|AGGREGATE)\(/i.test(i)}displayFormula(t){return Mt(t)}}function ut(m){let t="";for(let e=m+1;e>0;e=Math.floor((e-1)/26))t=String.fromCharCode(65+(e-1)%26)+t;return t}function nt(m,t,e){if(!(m instanceof C))return m;const s=m.rows===1?0:t,n=m.cols===1?0:e;return s>=m.rows||n>=m.cols?k.NA:m.data[s*m.cols+n]}function dt(m,t,e){if((t instanceof O||e instanceof O)&&m!=="="&&m!=="<>"&&m!=="&")throw k.VALUE;switch(m){case"+":{const s=S(t),n=s+S(e);return Math.abs(n)<Math.abs(s)*pt?0:K(n)}case"-":{const s=S(t),n=s-S(e);return Math.abs(n)<Math.abs(s)*pt?0:K(n)}case"*":return K(S(t)*S(e));case"/":{const s=S(t),n=S(e);if(n===0)throw k.DIV0;return K(s/n)}case"^":{const s=S(t),n=S(e);if(s===0&&n===0)throw k.NUM;if(s===0&&n<0)throw k.DIV0;const i=_t(s,n);if(Number.isNaN(i))throw k.NUM;return K(i)}case"&":return rt(t)+rt(e);case"=":return v(t,e)===0;case"<>":return v(t,e)!==0;case"<":return v(t,e)<0;case">":return v(t,e)>0;case"<=":return v(t,e)<=0;case">=":return v(t,e)>=0;default:throw k.VALUE}}const pt=5e-16;function K(m){if(!Number.isFinite(m))throw k.NUM;return m}function mt(m,t,e){const s=yt(m,t,e);return s==="REF"?k.REF:s==="VALUE"?k.VALUE:new q(m.sheet,s.top,s.left,s.bottom,s.right)}const Lt={COUNTIF:[0],COUNTIFS:["even",0],SUMIF:[0,2],SUMIFS:[0,"odd",1],AVERAGEIF:[0,2],AVERAGEIFS:[0,"odd",1],MAXIFS:[0,"odd",1],MINIFS:[0,"odd",1],COUNTBLANK:[0],RANK:[1],"RANK.EQ":[1],"RANK.AVG":[1]};function St(m,t){for(let e=0;e<m.length;e++){const s=m[e];if(s===t||s==="odd"&&t>=m[e+1]&&t%2===1||s==="even"&&t>=m[e+1]&&t%2===0)return!0}return!1}function it(m){if(!(m===null||typeof m!="object")){if(Array.isArray(m)){for(const t of m)it(t);return}if(m.t==="call"){const t=Lt[String(m.name).replace(/^_xl(?:fn|ws)\./i,"").toUpperCase()];t&&m.args.forEach((e,s)=>{if(e?.t==="array"&&St(t,s))throw new Error(`${m.name} takes a range here`)})}for(const t of Object.values(m))t!==null&&typeof t=="object"&&it(t)}}export{Bt as Engine};
1
+ import{resolveStructuredSpec as kt}from"../slicers/structured.js";import{Arr as A,compareValues as v,ERR as k,ERR_BY_INDEX as Q,Lambda as _t,num as S,power as gt,Ref as q,RefList as $,RichValue as O,str as rt,XlError as C}from"./values.js";import{entityVm as at,richValueAt as bt}from"../cells/rich-values.js";import{Compiler as lt}from"./compile.js";import{formulaEntryLimit as wt,FormulaSyntaxError as P,Parser as z,templateKey as Mt,tokenize as X,toDisplayFormula as At}from"./parser.js";import{BOOL as H,CHUNK_BITS as L,CHUNK_MASK as x,CONTENT_MASK as ot,DIRTY as M,EMPTY as J,EVALUATING as Y,FORMULA as T,KIND_MASK as V,NUM as F,SPILL as K,STR as B,ERR as E}from"../core/sheet.js";import{colName as ct,MAX_COLS as w,MAX_ROWS as Z,parseRangeRef as G}from"../core/address.js";import{CellSet as Ct}from"./cell-set.js";import{isRowBelow as Rt}from"./fill-shape.js";import{FUNCS as xt}from"./functions/registry.js";import"./functions/index.js";const Tt=new Set(["range","rows","cols","rangeOp","intersect","union"]),tt=Symbol("pending"),ht=200,St=4096,Lt=64,et=2147483647,D=4;class st{constructor(){this.n=0,this.data=new Int32Array(D*8)}push(t,e,s,n){if((this.n+1)*D>this.data.length){const r=new Int32Array(this.data.length*2);r.set(this.data),this.data=r}const i=this.n++*D,a=this.data;a[i]=t,a[i+1]=e,a[i+2]=s,a[i+3]=n}}function Et(m,t){if(!m.valueMeta.has(t))return;const e=new Map(m.valueMeta);e.delete(t),m.valueMeta=e.size>0?e:null}function ft(m,t,e){if(m.valueMeta?.get(t)===e)return;const s=new Map(m.valueMeta??[]);s.set(t,e),m.valueMeta=s}function W(m,t){let e=m.get(t);return e===void 0&&(e=new Ct,m.set(t,e)),e}class Nt{constructor(){this.buckets=[],this.wide=[],this.all=new st,this.allCols=[]}}class Kt{constructor(t){this.book=t,this.sheetGen=0,this.sheetMap=new Map,this.deps=new Map,this.templates=new Map,this.lastOwn={row:-2,col:-1,text:"",tpl:{cacheKey:void 0}},this.frame=null,this.depth=0,this.legacy=!1,this.pendingSheet=null,this.pendingRow=0,this.pendingCol=0,this.circular=null,this.evalStack=new Int32Array(3*256),this.evalTop=0,this.cycleLow=et,this.iterate=null,this.cycleFound=[],this.cycleMembers=null,this.iterating=!1,this.sliceMs=10,this.syncLimit=4e3,this.externalLinks=null,this.names=new Map,this.nameTemplates=new Map,this.tables=new Map,this.volatile=new Map,this.visibilityReaders=new Map,this.sheetReaders=new Map,this.styleReaders=new Map,this.wakePending=0,this.queue=new Int32Array(4096),this.qHead=0,this.qLen=0,this.sheetsByUid=new Map,this.running=!1,this.timer=0,this.manual=!1,this.graphReady=!0,this.pendingChanges=[],this.waiters=[],this.onChange=null,this.dataTables=[],this.tablesDirty=!1,this.inTables=!1,this.tablesForced=!1,this.onProgress=null,this.lookupCache=new Map,this.colRevisions=new Map,this.channel=null,this.sheetsChanged()}orderChanged(){this.sheetsChanged(),this.has3D&&this.rebuild()}sheetsChanged(){this.sheetGen++,this.sheetMap.clear(),this.sheetsByUid.clear();for(const t of this.book.sheets)this.sheetMap.set(t.name.toUpperCase(),t),this.sheetsByUid.set(t.uid,t),t.rows.watcher=this,t.cols.watcher=this;this._wakeReaders(this.sheetReaders)}sheetByName(t){return this.sheetMap.get(t.toUpperCase())??null}externalSheet(t,e){return this.externalLinks?.sheet(t,e)??null}sheetsBetween(t,e){const{sheets:s}=this.book,n=s.findIndex(a=>a.name.toUpperCase()===t.toUpperCase()),i=s.findIndex(a=>a.name.toUpperCase()===e.toUpperCase());return n<0||i<0?null:s.slice(Math.min(n,i),Math.max(n,i)+1)}setNames(t){this.names.clear(),this.nameTemplates.clear();for(const e of t){const s=e.localSheetId!==void 0?`${e.localSheetId}!${e.name.toUpperCase()}`:e.name.toUpperCase();this.names.set(s,{text:e.text,name:e.name,hidden:e.hidden,comment:e.comment})}}setTables(t){this.tables.clear();for(const e of t)this.tables.set(e.name.toUpperCase(),e)}template(t,e,s){let n;try{n=X(t)}catch(r){if(r instanceof P)return this._broken(t);throw r}const i=Mt(n,e,s);let a=this.templates.get(i);if(a===void 0){try{const r=new z(n,e,s).parse();a=this._compile(r)}catch(r){if(!(r instanceof P))throw r;a=this._broken(t)}a.cacheKey=i,this.templates.set(i,a)}return a}_ownTemplate(t,e,s){const n=this.lastOwn;let i;return n.row===e-1&&n.col===s&&this.templates.get(n.tpl.cacheKey)===n.tpl&&Rt(n.text,t)?i=n.tpl:i=this.template(t,e,s),n.row=e,n.col=s,n.text=t,n.tpl=i,i}_compile(t){const e=new lt(this),s=e.compileTop(t);for(;t.t==="paren";)t=t.e;return{fn:s,refs:e.refs,names:e.names,tables:e.tables,isVolatile:e.isVolatile,readsSheets:e.readsSheets,notInExcel:e.notInExcel===!0,mayArray:e.mayArray,rangeResult:Tt.has(t.t)||t.t==="call"&&xt.get(t.name)?.refResult===!0,external:e.external}}_broken(){return{invalid:!0,fn:()=>k.NAME,refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1,external:!0}}validate(t){const e=wt(t);if(e)throw new P(e);it(new z(X(t),0,0).parse())}_templateFor(t,e,s,n){if(n.tpl!==void 0)return n.tpl;let i;return n.t==="dataTable"?i=this._dataTableTemplate():n.f!==void 0&&n.base===void 0?i=this._ownTemplate(n.f,e,s):n.f!==void 0?i=this.template(n.f,Math.floor(n.base/w),n.base%w):n.sf!==void 0?i=this.template(n.sf,Math.floor(n.base/w),n.base%w):i=this._broken(),n.tpl=i,i}_index(t){let e=this.deps.get(t);return e===void 0&&(e=new Nt,this.deps.set(t,e)),e}_addDep(t,e,s,n,i,a,r,o){const l=this._index(t),c=a.uid<<14|o;if(i-s>=Lt){l.all.push(r,c,e,n),l.allCols.push(s,i);return}if(n-e>=St){for(let p=s;p<=i;p++){let f=l.wide[p];f===void 0&&(f=new st,l.wide[p]=f),f.push(r,c,e,n)}return}const u=e>>>L,d=n>>>L;for(let p=s;p<=i;p++){let f=l.buckets[p];f===void 0&&(f=[],l.buckets[p]=f);for(let h=u;h<=d;h++){let y=f[h];y===void 0&&(y=new st,f[h]=y),y.push(r,c,e,n)}}}register(t,e,s,n){const i=this._templateFor(t,e,s,n);if(i.external)return i;for(const a of i.refs)this._addRefDep(a,t,e,s);for(const a of i.names)this._addNameDeps(a,t,e,s);for(const a of i.tables)this._addTableDep(a,t,e,s);return i.readsSheets&&W(this.sheetReaders,t).add(e,s),i.isVolatile&&W(this.volatile,t).add(e,s),i.readsVisibility??=/SUBTOTAL|AGGREGATE|SPARK_/i.test(n.f??n.sf??""),i.readsVisibility&&W(this.visibilityReaders,t).add(e,s),i.readsStyles??=/SPARK_BLOCK/i.test(n.f??n.sf??""),i.readsStyles&&W(this.styleReaders,t).add(e,s),i}_addRefDep(t,e,s,n){const i=t.rAbs0?t.r0:s+t.r0,a=t.rAbs1?t.r1:s+t.r1,r=t.cAbs0?t.c0:n+t.c0,o=t.cAbs1?t.c1:n+t.c1,l=Math.max(0,Math.min(i,a)),c=Math.min(Z-1,Math.max(i,a)),u=Math.max(0,Math.min(r,o)),d=Math.min(w-1,Math.max(r,o));if(l>c||u>d)return;if(t.sheet?.sheet2&&(t.sheet.book===null||t.sheet.book===void 0)){this.has3D=!0;for(const f of this.sheetsBetween(t.sheet.sheet,t.sheet.sheet2)??[])this._addDep(f,l,u,c,d,e,s,n);return}if(t.sheet?.book!==null&&t.sheet?.book!==void 0)return;const p=t.sheet?this.sheetByName(t.sheet.sheet):e;p&&this._addDep(p,l,u,c,d,e,s,n)}_addNameDeps(t,e,s,n){const i=this._nameTemplate(t,e);if(i!==null){i.readsSheets&&W(this.sheetReaders,e).add(s,n);for(const a of i.refs)this._addRefDep(a,e,s,n);for(const a of i.tables)this._addTableDep(a,e,s,n);for(const a of i.names)a.toUpperCase()!==t.toUpperCase()&&this._addNameDeps(a,e,s,n)}}_addTableDep(t,e,s,n){const i=this.resolveTable(t.name,t.spec,s,n,e);i instanceof q&&this._addDep(i.sheet,i.r0,i.c0,i.r1,i.c1,e,s,n)}rebuild(){this.has3D=!1,this.deps.clear(),this.volatile.clear(),this.visibilityReaders.clear(),this.styleReaders.clear(),this.sheetReaders.clear(),this.lookupCache.clear(),this.qHead=0,this.qLen=0,this.cycleFound=[],this.cycleMembers=null,this.sheetGen++,this.buildGraph({fullCalc:!0})}buildGraph({fullCalc:t=!1,onDone:e}={}){this.graphReady=!1,this.dataTables=[],t&&(this.tablesDirty=!0);const s=this,n=this.sheetGen,i=this.book.sheets.map(u=>[u,u.formulas]);let a=0,r=0,o=0,l=0;const c=()=>{const u=performance.now()+s.sliceMs;let d=0;for(;a<i.length;a++,r=0,o=0,l=0){const[f,h]=i[a],{columns:y}=h;for(;r<y.length;r++,o=0,l=0){const _=y[r];if(_!==void 0)for(;o<_.length;o++,l=0){const g=_[o];if(g===void 0)continue;const{ids:b}=g,N=o<<L;for(;l<=x;l++){const R=b[l];if(R===0)continue;const U=h.infos[R],I=N+l;U.t==="dataTable"&&s.dataTables.push({sheet:f,row:I,col:r,info:U});const yt=s.register(f,I,r,U);if(s._initFormula(f,I,r,U,yt,t),++d%256===0&&performance.now()>u){l++,s.onProgress?.({preparing:!0}),s._later(c);return}}}}}s.graphReady=!0,s.sheetGen!==n&&s._wakeReaders(s.sheetReaders);const p=s.pendingChanges;s.pendingChanges=[];for(const[f,h,y,_]of p)s.cellsChanged(f,h,y,_);s._schedule(),e?.()};c()}_initFormula(t,e,s,n,i,a){const r=t._chunk(e,s);if(r===void 0)return;const o=e&x;if(n.t==="array"&&n.ref&&this._markArrayChildren(t,e,s,n),i.external)return;const l=r.kinds[o];(a||i.isVolatile||(l&V)===J||i.notInExcel&&(l&V)===E)&&(r.kinds[o]=l|M,this._enqueue(t,e,s))}_markArrayChildren(t,e,s,n){const i=G(n.ref);if(i!==null){t.spills||(t.spills=new Map),t.spills.set(e*w+s,{...i,blocked:!1,fixed:!n.cm});for(let a=i.r0;a<=i.r1;a++)for(let r=i.c0;r<=i.c1;r++){if(a===e&&r===s)continue;const o=t._ensure(a,r);o.kinds[a&x]|=K}}}_enqueue(t,e,s){if(this.qLen+3>this.queue.length)if(this.qHead>this.queue.length>>>1)this.queue.copyWithin(0,this.qHead,this.qLen),this.qLen-=this.qHead,this.qHead=0;else{const n=new Int32Array(this.queue.length*2);n.set(this.queue),this.queue=n}this.queue[this.qLen++]=t.uid,this.queue[this.qLen++]=e,this.queue[this.qLen++]=s}_dirtyFrom(t,e,s,n,i){const a=[t,e,s,n,i];for(;a.length>0;){const r=a.pop(),o=a.pop(),l=a.pop(),c=a.pop(),u=a.pop(),d=this.deps.get(u);if(d===void 0)continue;const p=(y,_)=>{const g=this.sheetsByUid.get(_>>>14);if(g===void 0)return;const b=_&16383,N=g._chunk(y,b);if(N===void 0)return;const R=y&x,U=N.kinds[R];(U&T)===0||(U&M)!==0||(N.kinds[R]=U|M,this._enqueue(g,y,b),a.push(g,b,b,y,y))},f=o>>>L,h=r>>>L;for(let y=c;y<=l;y++){const _=d.buckets[y];if(_!==void 0)for(let b=f;b<=h;b++){const N=_[b];if(N===void 0)continue;const{data:R}=N,U=N.n*D;for(let I=0;I<U;I+=D)r>=R[I+2]&&o<=R[I+3]&&p(R[I],R[I+1])}const g=d.wide[y];if(g!==void 0){const{data:b}=g,N=g.n*D;for(let R=0;R<N;R+=D)r>=b[R+2]&&o<=b[R+3]&&p(b[R],b[R+1])}}if(d.all.n>0){const{data:y}=d.all;for(let _=0;_<d.all.n;_++){const g=_*D;r>=y[g+2]&&o<=y[g+3]&&l>=d.allCols[_*2]&&c<=d.allCols[_*2+1]&&p(y[g],y[g+1])}}}}cellsChanged(t,e,s,n){if(n===0)return;if(this.inTables||(this.tablesDirty=!0),!this.graphReady){this.pendingChanges.push([t,e.slice(0,n),s.slice(0,n),n]);return}this.lookupCache.clear();const i=new Map;for(let a=0;a<n;a++){const r=e[a],o=s[a],l=i.get(o);l===void 0?i.set(o,[r,r]):(r<l[0]&&(l[0]=r),r>l[1]&&(l[1]=r));const c=t._chunk(r,o);if(c===void 0)continue;const u=r&x,d=c.kinds[u];if(d&T){const p=t.formula(r,o);p&&(this.register(t,r,o,p),d&M||(c.kinds[u]=d|M,this._enqueue(t,r,o)))}t.spills&&this._spillTouched(t,r,o)}for(const[a,r]of i)this._dirtyFrom(t,a,a,r[0],r[1]);this._markVolatile(),this._schedule()}_spillTouched(t,e,s){const n=e*w+s;for(const[i,a]of t.spills){const r=Math.floor(i/w),o=i-r*w;if(i===n){(t.kind(r,o)&T)===0&&(this._clearSpill(t,a,r,o),t.spills.delete(i));continue}if(e>=a.r0&&e<=a.r1&&s>=a.c0&&s<=a.c1){const l=t._chunk(r,o);if(l===void 0)continue;const c=r&x,u=l.kinds[c];u&T&&!(u&M)&&(l.kinds[c]=u|M,this._enqueue(t,r,o),this._dirtyFrom(t,o,o,r,r))}}}_markVolatile(){for(const[t,e]of this.volatile)e.forEach((s,n)=>{const i=t._chunk(s,n);if(i===void 0)return;const a=s&x,r=i.kinds[a];if(!(r&T)){e.delete(s,n);return}r&M||(i.kinds[a]=r|M,this._enqueue(t,s,n),this._dirtyFrom(t,n,n,s,s))})}get pending(){return(this.qLen-this.qHead)/3}_later(t){if(this._next=t,typeof MessageChannel>"u"){setTimeout(()=>this._tick(),0);return}this.channel===null&&(this.channel=new MessageChannel,this.channel.port1.onmessage=()=>this._tick()),this.channel.port2.postMessage(0)}_tick(){const t=this._next;this._next=null,t?.(),this._next===null&&this.channel!==null&&(this.channel.port1.close(),this.channel=null)}_schedule(){if(this.manual||this.inTables||this.running||!this.graphReady)return;if(this.pending===0){this._finish();return}const t=this.pending;if(t<=this.syncLimit&&(this._slice(this.syncLimit===1/0?1/0:this.sliceMs),this.pending===0)){this._finish();return}this.running=!0,this._total=t;const e=()=>{this._slice(this.sliceMs),this.pending>0?(this.onProgress?.({remaining:this.pending,total:Math.max(this._total,this.pending)}),this._later(e)):(this.running=!1,this._finish())};this._later(e)}_slice(t){const e=t!==1/0;let s=e?performance.now():0;const n=s+t;let i=1,a=1;for(;this.qHead<this.qLen;){const r=this.queue[this.qHead++],o=this.queue[this.qHead++],l=this.queue[this.qHead++],c=this.sheetsByUid.get(r);if(c!==void 0&&(this._run(c,o,l),e&&--a===0)){const u=performance.now();if(u>n)break;i=u-s<.5?Math.min(i*2,16):1,a=i,s=u}}this.qHead>=this.qLen&&(this.qHead=0,this.qLen=0)}_finish(){for(;this.cycleFound.length>0;)this._iterateCycles();const t=this.tablesForced;this.tablesForced=!1,this.tablesDirty&&this.dataTables.length>0&&(!this.skipTables||t)&&(this.tablesDirty=!1,this._computeDataTables()),this.onChange?.();const e=this.waiters;this.waiters=[];for(const s of e)s()}_dataTableTemplate(){const t=this;return{fn:(s,n,i)=>t._plainValue(i,s,n),refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1}}_plainValue(t,e,s){const n=t.value(e,s);switch(t.kind(e,s)&V){case F:return n;case B:return this.book.strings.get(n);case H:return n!==0;case E:return Q[n];default:return null}}_writePlain(t,e,s,n){const i=t.kind(e,s)&T;n==null?t.setCell(e,s,i|F,0):typeof n=="number"?Number.isFinite(n)?t.setCell(e,s,i|F,n):t.setCell(e,s,i|E,k.NUM.index):typeof n=="boolean"?t.setCell(e,s,i|H,n?1:0):n instanceof C?t.setCell(e,s,i|E,n.index):t.setCell(e,s,i|B,this.book.strings.add(String(n)))}_setInputs(t,e){const s=new Uint32Array(e.length),n=new Uint32Array(e.length);e.forEach((i,a)=>{t.setCell(i.row,i.col,i.kind,i.value),s[a]=i.row,n[a]=i.col}),this.cellsChanged(t,s,n,e.length),this._slice(1/0)}evaluateWith(t,e,s){const n=e.map(({row:a,col:r})=>({row:a,col:r,kind:t.kind(a,r)&(V|T),value:t.value(a,r)})),i=this.inTables;this.inTables=!0;try{return this._setInputs(t,e.map(({row:a,col:r,text:o})=>{const l=Number(o);return o!==""&&Number.isFinite(l)?{row:a,col:r,kind:F,value:l}:{row:a,col:r,kind:B,value:this.book.strings.add(String(o))}})),s()}finally{this._setInputs(t,n),this.inTables=i}}_computeDataTables(){this.inTables=!0;const t=this.dataTables.filter(e=>e.sheet.formula(e.row,e.col)===e.info&&this.book.sheets.includes(e.sheet));this.dataTables=t;try{for(const e of t)this._computeDataTable(e)}finally{this.inTables=!1}}_computeDataTable({sheet:t,info:e}){const s=G(e.ref),n=G(e.r1??"");if(!s||!n)return;const i=e.r2?G(e.r2):null,a=e.dt2D==="1"||e.dt2D==="true",r=e.dtr==="1"||e.dtr==="true",o=(h,y)=>({kind:t.kind(h,y)&V,value:t.value(h,y)}),c=[n,i].filter(Boolean).map(h=>({row:h.r0,col:h.c0,kind:t.kind(h.r0,h.c0)&(V|T),value:t.value(h.r0,h.c0)})),u=[];for(let h=s.r0;h<=s.r1;h++)for(let y=s.c0;y<=s.c1;y++){let _,g;a?(_=[{row:n.r0,col:n.c0,...o(s.r0-1,y)},{row:i.r0,col:i.c0,...o(h,s.c0-1)}],g=[s.r0-1,s.c0-1]):r?(_=[{row:n.r0,col:n.c0,...o(s.r0-1,y)}],g=[h,s.c0-1]):(_=[{row:n.r0,col:n.c0,...o(h,s.c0-1)}],g=[s.r0-1,y]),this._setInputs(t,_);let b=this.read(t,g[0],g[1]);b instanceof A&&(b=b.data[0]),u.push(h,y,b)}this._setInputs(t,c);const d=u.length/3,p=new Uint32Array(d),f=new Uint32Array(d);for(let h=0;h<d;h++)p[h]=u[h*3],f[h]=u[h*3+1],this._writePlain(t,p[h],f[h],u[h*3+2]);this.cellsChanged(t,p,f,d),this._slice(1/0),t.revision++}dataTableAt(t,e,s){for(const n of this.dataTables){if(n.sheet!==t)continue;const i=G(n.info.ref);if(i&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1)return n}return null}calculateNow(){const{manual:t,skipTables:e}=this;this.manual=!1,this.skipTables=!1,this.tablesDirty=!0,this.tablesForced=!0,this._markVolatile(),this._markCycles(),this._schedule(),this.manual=t,this.skipTables=e}whenIdle(){return this.pending===0&&this.graphReady&&!this.running?Promise.resolve():new Promise(t=>{this.waiters.push(t),this._schedule()})}_iterateCycles(){const t=this.cycleFound;this.cycleFound=[];const e=new Map,s=(r,o,l)=>{let c=e.get(r.uid);c===void 0&&(c=new Map,e.set(r.uid,c)),c.set(o*w+l,[r,o,l])};for(let r=0;r<t.length;r+=3)s(t[r],t[r+1],t[r+2]);const n=[];for(const r of this.book.sheets){const o=e.get(r.uid);o&&n.push(...[...o.keys()].sort((l,c)=>l-c).map(l=>o.get(l)))}this.cycleMembers??=new Map;for(const r of n)this.cycleMembers.set(`${r[0].uid}:${r[1]}:${r[2]}`,r);const{count:i,delta:a}=this.iterate;for(let r=1;r<=i;r++){let o=0;for(const[l,c,u]of n){const d=l._chunk(c,u);if(d===void 0)continue;const p=c&x;if(!(d.kinds[p]&T))continue;const f=d.values[p];d.kinds[p]|=M,this.iterating=!0,this._run(l,c,u),this.iterating=!1;const h=Math.abs(d.values[p]-f);h>o&&(o=h)}if(this.onProgress?.({iteration:r,iterations:i}),o<a)break}for(const[r,o,l]of n)this._dirtyFrom(r,l,l,o,o);for(const[r,o,l]of n){const c=r._chunk(o,l);c!==void 0&&(c.kinds[o&x]&=~M)}this._slice(1/0)}_markCycles(){if(!(this.iterate===null||this.cycleMembers===null))for(const[t,e,s]of this.cycleMembers.values()){const n=t._chunk(e,s);n===void 0||!(n.kinds[e&x]&T)||(n.kinds[e&x]|=M,this._enqueue(t,e,s))}}_run(t,e,s){const n=[t,e,s];for(;n.length>0;){const i=n[n.length-1],a=n[n.length-2],r=n[n.length-3];try{this.depth=0,this.evalTop=0,this.cycleLow=et,this._calc(r,a,i),n.length-=3}catch(o){if(o!==tt)throw o;n.push(this.pendingSheet,this.pendingRow,this.pendingCol)}}}_calc(t,e,s){const n=t._chunk(e,s);if(n===void 0)return;const i=e&x,a=n.kinds[i];if(!(a&M))return;if(a&Y){this.circular={sheet:t,row:e,col:s},this.iterating||this._cycleHit(t.uid,e,s);return}if(this.depth>=ht)throw this.pendingSheet=t,this.pendingRow=e,this.pendingCol=s,tt;const r=t.formula(e,s);if(r===void 0||!(a&T)){n.kinds[i]=a&~M;return}const o=this._templateFor(t,e,s,r);if(o.external){n.kinds[i]=a&~M;return}n.kinds[i]=a|Y;const l=this.evalTop;l+3>this.evalStack.length&&this._growEvalStack(),this.evalStack[l]=t.uid,this.evalStack[l+1]=e,this.evalStack[l+2]=s,this.evalTop=l+3;const c=this.cycleLow;this.cycleLow=et;const u=this.legacy,d=this.frame,p=r.typed!==!0&&r.t!=="array";this.legacy=p,this.depth++;let f;try{f=o.fn(e,s,t),(f instanceof q||f instanceof $)&&(f=this.refAuto(f,e,s))}catch(y){if(n.kinds[i]&=~Y,this.depth--,this.legacy=u,this.frame=d,this.evalTop=l,this.cycleLow=c,y===tt)throw y;y instanceof C?f=y:(console.error("Formula evaluation failed",y),f=k.VALUE),this._store(t,n,i,e,s,f,r,p);return}this.depth--,this.legacy=u,this.frame=d,this.evalTop=l;const h=this.cycleLow;if(this.cycleLow=h<l&&h<c?h:c,h<=l){if(this.iterate!==null){n.kinds[i]=a&~(M|Y),this.cycleFound.push(t,e,s);return}f=0}this._store(t,n,i,e,s,f,r,p)}_cycleHit(t,e,s){const n=this.evalStack;for(let i=this.evalTop-3;i>=0;i-=3)if(n[i]===t&&n[i+1]===e&&n[i+2]===s){i<this.cycleLow&&(this.cycleLow=i);return}}_growEvalStack(){const t=new Int32Array(this.evalStack.length*2);t.set(this.evalStack),this.evalStack=t}_store(t,e,s,n,i,a,r,o){let l=a;l instanceof _t&&(l=k.CALC),l instanceof A?r.t==="array"&&!r.cm&&r.ref?l=this._fillFixedArray(t,n,i,r,l):o||l.rows===1&&l.cols===1?(l=l.data[0],t.spills&&this._releaseSpill(t,n,i)):l=this._spill(t,n,i,r,l):t.spills&&!(r.t==="array"&&!r.cm)&&this._releaseSpill(t,n,i),r.t==="array"&&!r.cm&&r.ref&&!(a instanceof A)&&(l=this._fillFixedArray(t,n,i,r,A.filled(1,1,l)));let c=T,u=0;typeof l=="number"?Number.isFinite(l)?(c|=F,u=l):(c|=E,u=k.NUM.index):typeof l=="string"?(c|=B,u=this.book.strings.add(l)):typeof l=="boolean"?(c|=H,u=l?1:0):l instanceof C?(c|=E,u=l.index):l instanceof O?(c|=E,u=k.VALUE.index):c|=F,l instanceof O?ft(t,n*w+i,at(this.book,l.index)):t.valueMeta!==null&&((e.kinds[s]&ot)!==c||e.values[s]!==u)&&!/IMAGE\(/i.test(r.f??r.sf??"")&&Et(t,n*w+i),e.kinds[s]=c,e.values[s]=u,n>t.maxRow&&(t.maxRow=n),i>t.maxCol&&(t.maxCol=i)}_writeArrayCell(t,e,s,n){let i=K,a=0;typeof n=="number"?(i|=Number.isFinite(n)?F:E,a=Number.isFinite(n)?n:k.NUM.index):typeof n=="string"?(i|=B,a=this.book.strings.add(n)):typeof n=="boolean"?(i|=H,a=n?1:0):n instanceof C?(i|=E,a=n.index):n==null?i|=F:(i|=E,a=k.VALUE.index,n instanceof O&&ft(t,e*w+s,at(this.book,n.index))),t.setCell(e,s,i,a)}_fillFixedArray(t,e,s,n,i){const a=G(n.ref);if(a===null)return i.data[0];t.spills||(t.spills=new Map),t.spills.set(e*w+s,{...a,blocked:!1,fixed:!0});const r=(l,c)=>{const u=i.rows===1?0:l,d=i.cols===1?0:c;return u>=i.rows||d>=i.cols?k.NA:i.get(u,d)};for(let l=a.r0;l<=a.r1;l++)for(let c=a.c0;c<=a.c1;c++)l===e&&c===s||this._writeArrayCell(t,l,c,r(l-a.r0,c-a.c0));this._dirtyFrom(t,a.c0,a.c1,a.r0,a.r1);const o=r(e-a.r0,s-a.c0);return o===null?0:o}_spill(t,e,s,n,i){const a=e*w+s;t.spills||(t.spills=new Map);const r=t.spills.get(a),o=e+i.rows-1,l=s+i.cols-1,c={r0:e,c0:s,r1:o,c1:l,blocked:!1,fixed:!1},u=(f,h)=>r&&f>=r.r0&&f<=r.r1&&h>=r.c0&&h<=r.c1;let d=o>=Z||l>=w;if(!d)t:for(let f=e;f<=o;f++)for(let h=s;h<=l;h++){if(f===e&&h===s)continue;const y=t.kind(f,h);if((y&ot)!==0&&!(y&K&&u(f,h))){d=!0;break t}if(t.merges.length>0&&t.mergeAt(f,h)){d=!0;break t}}if(d)return r&&!r.blocked&&this._clearSpill(t,r,e,s),c.blocked=!0,c.r1=Math.min(o,Z-1),c.c1=Math.min(l,w-1),t.spills.set(a,c),k.SPILL;if(r&&!r.blocked){for(let f=r.r0;f<=r.r1;f++)for(let h=r.c0;h<=r.c1;h++)f>=c.r0&&f<=c.r1&&h>=c.c0&&h<=c.c1||(t.kind(f,h)&K)!==0&&t.setCell(f,h,J,0);this._dirtyFrom(t,r.c0,r.c1,r.r0,r.r1)}t.spills.set(a,c);for(let f=e;f<=o;f++)for(let h=s;h<=l;h++)f===e&&h===s||this._writeArrayCell(t,f,h,i.get(f-e,h-s));n.t="array",n.ref=`${ut(s)}${e+1}:${ut(l)}${o+1}`,n.cm=1,delete n.raw,this._dirtyFrom(t,s,l,e,o);const p=i.data[0];return p===null?0:p}_clearSpill(t,e,s,n){for(let i=e.r0;i<=e.r1;i++)for(let a=e.c0;a<=e.c1;a++)i===s&&a===n||(t.kind(i,a)&K)!==0&&t.setCell(i,a,J,0);this._dirtyFrom(t,e.c0,e.c1,e.r0,e.r1)}_releaseSpill(t,e,s){const n=e*w+s,i=t.spills.get(n);if(i===void 0)return;i.blocked||this._clearSpill(t,i,e,s),t.spills.delete(n);const a=t.formula(e,s);a&&a.typed&&(delete a.ref,delete a.cm,delete a.t)}spillMaster(t,e,s){if(!t.spills)return null;for(const[n,i]of t.spills)if(!i.blocked&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1){const a=Math.floor(n/w);return{row:a,col:n-a*w,rect:i}}return null}spillRange(t){const{sheet:e,r0:s,c0:n}=t;this.read(e,s,n);const i=e.spills?.get(s*w+n);return!i||i.blocked?k.REF:new q(e,i.r0,i.c0,i.r1,i.c1)}read(t,e,s){const n=t.columns[s];if(n===void 0)return null;const i=n[e>>>L];if(i===void 0)return null;const a=e&x;let r=i.kinds[a];if(r===0)return null;switch(r&M&&(this._calc(t,e,s),r=i.kinds[a]),r&V){case F:return i.values[a];case B:return this.book.strings.get(i.values[a]);case H:return i.values[a]!==0;case E:{if(t.valueMeta!==null&&this.book.richValues){const o=bt(this.book,t,e,s);if(o!==null)return o}return Q[i.values[a]]??k.NA}default:return null}}refToValue(t){return t instanceof $?t.refs.length===1?this.refToValue(t.refs[0]):k.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.toArr(t)}refAuto(t,e,s){return t instanceof $?t.refs.length===1?this.refAuto(t.refs[0],e,s):k.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.legacy?this.intersect(t,e,s):this.toArr(t)}intersect(t,e,s){return t.cols===1&&e>=t.r0&&e<=t.r1?this.read(t.sheet,e,t.c0):t.rows===1&&s>=t.c0&&s<=t.c1?this.read(t.sheet,t.r0,s):k.VALUE}trim(t){const{sheet:e}=t;return{r0:t.r0,c0:t.c0,r1:Math.min(t.r1,Math.max(e.maxRow,t.r0)),c1:Math.min(t.c1,Math.max(e.maxCol,t.c0))}}toArr(t){if(t instanceof A)return t;if(t instanceof q){const{r0:e,c0:s,r1:n,c1:i}=this.trim(t),a=n-e+1,r=i-s+1,o=new Array(a*r);let l=0;for(let c=e;c<=n;c++)for(let u=s;u<=i;u++)o[l++]=this.read(t.sheet,c,u);return new A(a,r,o)}if(t instanceof $){if(t.refs.length===1)return this.toArr(t.refs[0]);throw k.VALUE}if(t instanceof C)throw t;return new A(1,1,[t])}scalar(t,e,s){return t instanceof q?t.isCell?this.read(t.sheet,t.r0,t.c0):this.intersect(t,e,s):t instanceof $?k.VALUE:t instanceof A?t.data[0]:t}scan(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);for(let a=t.c0;a<=n;a++){const r=s.columns[a];if(r!==void 0)for(let o=t.r0>>>L;o<=i>>>L;o++){const l=r[o];if(l===void 0)continue;const c=o<<L,u=Math.max(t.r0-c,0),d=Math.min(i-c,x),{kinds:p}=l;for(let f=u;f<=d;f++){if(p[f]===0)continue;const h=this.read(s,c+f,a);h!==null&&e(h,c+f,a)}}}}sumRange(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);let{sum:a,count:r}=e;for(let o=t.c0;o<=n;o++){const l=s.columns[o];if(l!==void 0)for(let c=t.r0>>>L;c<=i>>>L;c++){const u=l[c];if(u===void 0)continue;const d=c<<L,p=Math.max(t.r0-d,0),f=Math.min(i-d,x),{kinds:h,values:y}=u;for(let _=p;_<=f;_++){let g=h[_];if(g===0)continue;g&M&&(this._calc(s,d+_,o),g=h[_]);const b=g&V;if(b===F)a+=y[_],r++;else if(b===E)throw Q[y[_]]}}}e.sum=a,e.count=r}unary(t,e){if(t instanceof C)return t;if(t instanceof A)return new A(t.rows,t.cols,t.data.map(s=>{try{return s instanceof C?s:e(S(s))}catch(n){return n}}));try{return e(S(t))}catch(s){if(s instanceof C)return s;throw s}}slowBin(t,e,s){if(e instanceof A||s instanceof A)return this._binArr(t,e,s);if(e instanceof C)return e;if(s instanceof C)return s;try{return dt(t,e,s)}catch(n){if(n instanceof C)return n;throw n}}_binArr(t,e,s){const n=e instanceof A?e:null,i=s instanceof A?s:null,a=Math.max(n?n.rows:1,i?i.rows:1),r=Math.max(n?n.cols:1,i?i.cols:1),o=new Array(a*r);for(let l=0;l<a;l++)for(let c=0;c<r;c++){const u=nt(e,l,c),d=nt(s,l,c);let p;if(u instanceof C)p=u;else if(d instanceof C)p=d;else try{p=dt(t,u,d)}catch(f){p=f}o[l*r+c]=p}return new A(a,r,o)}liftArr(t,e,s){let n=1,i=1;for(const l of e)l instanceof A&&(l.rows>n&&(n=l.rows),l.cols>i&&(i=l.cols));const a=new Array(n*i),r=e.length,o=new Array(r);for(let l=0;l<n;l++)for(let c=0;c<i;c++){let u=null;for(let d=0;d<r;d++){const p=nt(e[d],l,c);o[d]=p,!s&&u===null&&p instanceof C&&(u=p)}if(u!==null){a[l*i+c]=u;continue}try{a[l*i+c]=t(...o)}catch(d){if(d instanceof C)a[l*i+c]=d;else throw d}}return new A(n,i,a)}invoke(t,e,s,n,i){if(t.native)return this._invokeNative(t.native,e,s,n,i);const a=t.frame?t.frame.slice():[],{params:r}=t;if(e.length>r.length)return k.VALUE;for(let l=0;l<r.length;l++)a[r[l]]=l<e.length?e[l]:void 0;const o=this.frame;if(this.frame=a,this.depth++,this.depth>=ht*4)return this.depth--,this.frame=o,k.NUM;try{return t.body(s,n,i)}finally{this.depth--,this.frame=o}}_invokeNative(t,e,s,n,i){if(e.length<t.min||e.length>t.max)return k.VALUE;try{if(t.kind==="raw")return t.fn(this,e,s,n,i);if(t.kind==="lazy")return t.fn(this,e.map(r=>()=>r),s,n,i);const a=e.map(r=>r instanceof q||r instanceof $?this.refToValue(r):r);if(a.some(r=>r instanceof A))return this.liftArr(t.fn,a,t.errors);if(!t.errors){for(const r of a)if(r instanceof C)return r}return t.fn(...a)}catch(a){if(a instanceof C)return a;throw a}}_nameEntry(t,e){const s=t.toUpperCase();if(e){const i=this.book.sheets.indexOf(e),a=this.names.get(`${i}!${s}`);if(a)return{key:`${i}!${s}`,entry:a}}const n=this.names.get(s);return n?{key:s,entry:n}:null}_nameTemplate(t,e){const s=this._nameEntry(t,e);if(s===null)return null;let n=this.nameTemplates.get(s.key);if(n===void 0){try{n=this._compile(new z(X(s.entry.text),0,0).parse())}catch(i){if(!(i instanceof P))throw i;n=this._broken()}this.nameTemplates.set(s.key,n)}return n}nameMayYieldRange(t){const e=t.toUpperCase(),s=[];for(const[n,i]of this.names)(n===e||n.endsWith(`!${e}`))&&s.push(i);if(s.length===0||(this._rangeNames??=new Set,this._rangeNames.has(e)))return!0;this._rangeNames.add(e);try{return s.some(n=>{try{return new lt(this).mayYieldRange(new z(X(n.text),0,0).parse())}catch(i){if(i instanceof P)return!1;throw i}})}finally{this._rangeNames.delete(e)}}evalName(t,e,s,n){const i=this._nameTemplate(t,n);return i===null?k.NAME:i.fn(e,s,n)}tableSpecToA1(t,e,s){const n=mt(t,e,s);if(!(n instanceof q))return null;const i=/#This Row|^\[\s*@/i.test(e),a=(r,o)=>i?`${ct(o)}${r+1}`:`$${ct(o)}$${r+1}`;return n.isCell?a(n.r0,n.c0):`${a(n.r0,n.c0)}:${a(n.r1,n.c1)}`}resolveTable(t,e,s,n,i){let a=t?this.tables.get(t.toUpperCase()):null;if(!t){for(const r of this.tables.values())if(r.sheet===i&&s>=r.r0&&s<=r.r1&&n>=r.c0&&n<=r.c1){a=r;break}}return a?mt(a,e,s):k.REF}exactIndex(t){const e=`${t.sheet.uid}:${t.r0}:${t.c0}:${t.r1}:${t.c1}`;let s=this.lookupCache.get(e);if(s!==void 0)return s;s=new Map;const n=t.cols===1;return this.scan(t,(i,a,r)=>{const o=typeof i=="string"?`s${i.toLowerCase()}`:typeof i=="number"?i:`b${i}`;if(i instanceof C)return;const l=n?a-t.r0:r-t.c0,c=s.get(o);(c===void 0||l<c)&&s.set(o,l)}),this.lookupCache.set(e,s),s}visibilityChanged(){this._wakeReaders(this.visibilityReaders)}presentationChanged(){this._wakeLater(2)}axisHiddenChanged(){this._wakeLater(1)}axisResized(){this._wakeLater(2)}_wakeLater(t){(t===1?this.visibilityReaders:this.styleReaders).size!==0&&(this.wakePending===0&&queueMicrotask(()=>{const e=this.wakePending;this.wakePending=0,e&1&&this._wakeReaders(this.visibilityReaders),e&2&&this._wakeReaders(this.styleReaders)}),this.wakePending|=t)}_wakeReaders(t){if(!this.graphReady||t.size===0)return;let e=!1;for(const[s,n]of t)n.forEach((i,a)=>{const r=s._chunk(i,a);if(r===void 0)return;const o=i&x,l=r.kinds[o];if(!(l&T)){n.delete(i,a);return}l&M||(r.kinds[o]=l|M,this._enqueue(s,i,a)),this._dirtyFrom(s,a,a,i,i),e=!0});e&&this._schedule()}isSubtotalCell(t,e,s){if((t.kind(e,s)&T)===0)return!1;const n=t.formula(e,s),i=n?.f??n?.sf??"";return/^\s*(_xlfn\.)?(SUBTOTAL|AGGREGATE)\(/i.test(i)}displayFormula(t){return At(t)}}function ut(m){let t="";for(let e=m+1;e>0;e=Math.floor((e-1)/26))t=String.fromCharCode(65+(e-1)%26)+t;return t}function nt(m,t,e){if(!(m instanceof A))return m;const s=m.rows===1?0:t,n=m.cols===1?0:e;return s>=m.rows||n>=m.cols?k.NA:m.data[s*m.cols+n]}function dt(m,t,e){if((t instanceof O||e instanceof O)&&m!=="="&&m!=="<>"&&m!=="&")throw k.VALUE;switch(m){case"+":{const s=S(t),n=s+S(e);return Math.abs(n)<Math.abs(s)*pt?0:j(n)}case"-":{const s=S(t),n=s-S(e);return Math.abs(n)<Math.abs(s)*pt?0:j(n)}case"*":return j(S(t)*S(e));case"/":{const s=S(t),n=S(e);if(n===0)throw k.DIV0;return j(s/n)}case"^":{const s=S(t),n=S(e);if(s===0&&n===0)throw k.NUM;if(s===0&&n<0)throw k.DIV0;const i=gt(s,n);if(Number.isNaN(i))throw k.NUM;return j(i)}case"&":return rt(t)+rt(e);case"=":return v(t,e)===0;case"<>":return v(t,e)!==0;case"<":return v(t,e)<0;case">":return v(t,e)>0;case"<=":return v(t,e)<=0;case">=":return v(t,e)>=0;default:throw k.VALUE}}const pt=5e-16;function j(m){if(!Number.isFinite(m))throw k.NUM;return m}function mt(m,t,e){const s=kt(m,t,e);return s==="REF"?k.REF:s==="VALUE"?k.VALUE:new q(m.sheet,s.top,s.left,s.bottom,s.right)}const Ut={COUNTIF:[0],COUNTIFS:["even",0],SUMIF:[0,2],SUMIFS:[0,"odd",1],AVERAGEIF:[0,2],AVERAGEIFS:[0,"odd",1],MAXIFS:[0,"odd",1],MINIFS:[0,"odd",1],COUNTBLANK:[0],RANK:[1],"RANK.EQ":[1],"RANK.AVG":[1]};function It(m,t){for(let e=0;e<m.length;e++){const s=m[e];if(s===t||s==="odd"&&t>=m[e+1]&&t%2===1||s==="even"&&t>=m[e+1]&&t%2===0)return!0}return!1}function it(m){if(!(m===null||typeof m!="object")){if(Array.isArray(m)){for(const t of m)it(t);return}if(m.t==="call"){const t=Ut[String(m.name).replace(/^_xl(?:fn|ws)\./i,"").toUpperCase()];t&&m.args.forEach((e,s)=>{if(e?.t==="array"&&It(t,s))throw new Error(`${m.name} takes a range here`)})}for(const t of Object.values(m))t!==null&&typeof t=="object"&&it(t)}}export{Kt as Engine};
@@ -1 +1 @@
1
- import{setCategory as I}from"./registry.js";import{lift as m,raw as f}from"./registry.js";import{Arr as R,ERR as o,Lambda as S,num as y,OMITTED as A,Ref as i,RefList as p,RichValue as L,XlError as E}from"../values.js";import{CONTENT_MASK as w,FORMULA as g}from"../../core/sheet.js";import{cellRef as b,colName as T,sheetPrefix as O}from"../../core/address.js";import{newBookName as k}from"../../core/default-names.js";import{str as d}from"../values.js";I("Information");const s=(e,t)=>m(e,1,1,t,{errors:!0});s("ISERROR",e=>e instanceof E),s("ISERR",e=>e instanceof E&&e!==o.NA),s("ISNA",e=>e===o.NA),s("ISNUMBER",e=>typeof e=="number"),s("ISTEXT",e=>typeof e=="string"),s("ISNONTEXT",e=>typeof e!="string"),s("ISLOGICAL",e=>typeof e=="boolean"),s("ISBLANK",e=>e==null),m("ISEVEN",1,1,e=>Math.trunc(y(e))%2===0),m("ISODD",1,1,e=>Math.trunc(y(e))%2!==0),f("ISREF",1,1,(e,t)=>t[0]instanceof i||t[0]instanceof p),f("ISFORMULA",1,1,(e,t)=>{const r=t[0];if(!(r instanceof i))throw o.VALUE;return(r.sheet.kind(r.r0,r.c0)&g)!==0}),m("N",1,1,e=>{if(typeof e=="number")return e;if(typeof e=="boolean")return e?1:0;if(e instanceof L)throw o.VALUE;return 0}),m("NA",0,0,()=>o.NA),s("ERROR.TYPE",e=>{if(!(e instanceof E))throw o.NA;return{"#NULL!":1,"#DIV/0!":2,"#VALUE!":3,"#REF!":4,"#NAME?":5,"#NUM!":6,"#N/A":7,"#GETTING_DATA":8,"#SPILL!":9,"#FIELD!":13,"#CALC!":14}[e.code]}),f("TYPE",1,1,(e,t)=>{const r=t[0]instanceof i&&t[0].isCell?e.read(t[0].sheet,t[0].r0,t[0].c0):t[0];return r instanceof i||r instanceof p||r instanceof R?64:r===null||typeof r=="number"?1:typeof r=="string"?2:typeof r=="boolean"?4:r instanceof E?16:r instanceof S||r instanceof L?128:1}),f("SHEET",0,1,(e,t,r,u,c)=>{if(t.length===0||t[0]===A)return e.book.sheets.indexOf(c)+1;if(t[0]instanceof i)return e.book.sheets.indexOf(t[0].sheet)+1;if(typeof t[0]=="string"){const h=e.sheetByName(t[0]);if(!h)throw o.NA;return e.book.sheets.indexOf(h)+1}throw o.VALUE}),f("SHEETS",0,1,(e,t)=>{if(t.length===0||t[0]===A)return e.book.sheets.length;if(t[0]instanceof p)return new Set(t[0].refs.map(r=>r.sheet)).size;if(t[0]instanceof i)return 1;throw o.REF}),f("INFO",1,1,(e,t,r,u)=>{switch(d(e.scalar(t[0],r,u)).toLowerCase()){case"numfile":return e.book.sheets.length;case"recalc":return e.manual?"Manual":"Automatic";case"release":return"16.0";case"system":return"mac";case"origin":return"$A:$A$1";case"directory":return"";default:throw o.VALUE}}),f("CELL",1,2,(e,t,r,u,c)=>{const h=d(e.scalar(t[0],r,u)).toLowerCase(),n=t[1]===void 0||t[1]===A?new i(c,r,u,r,u):t[1];if(!(n instanceof i))throw o.VALUE;const a=e.read(n.sheet,n.r0,n.c0),l=e.book.styles.get(n.sheet.style(n.r0,n.c0));switch(h){case"address":{const N=`$${T(n.c0)}$${n.r0+1}`;return n.sheet===c?N:`${O(n.sheet.name,{book:e.book.fileName??k()})}${N}`}case"col":return n.c0+1;case"row":return n.r0+1;case"contents":return a===null?0:a;case"filename":return"";case"type":return a===null?"b":typeof a=="string"?"l":"v";case"width":return Math.round(n.sheet.cols.sizeOf(n.c0)/6);case"color":return/\[red\]/i.test(l.numFmt)?1:0;case"format":return F(l.numFmt);case"parentheses":return/\(/.test(l.numFmt)?1:0;case"prefix":return typeof a=="string"?l.hAlign==="right"?'"':l.hAlign==="center"?"^":"'":"";case"protect":return 1;default:throw o.VALUE}});function F(e){return e==="General"?"G":e==="0"?"F0":e==="#,##0"?",0":e==="0.00"?"F2":e==="#,##0.00"?",2":/%/.test(e)?`P${(/\.(0+)/.exec(e)?.[1]??"").length}`:/E\+/i.test(e)?"S2":/[ymd]/i.test(e)?"D1":"G"}export{w as CONTENT_MASK,b as cellRef};
1
+ import{setCategory as S}from"./registry.js";import{lift as h,raw as f}from"./registry.js";import{Arr as I,ERR as o,Lambda as R,num as N,OMITTED as A,Ref as i,RefList as d,RichValue as y,XlError as E}from"../values.js";import{CONTENT_MASK as w,FORMULA as g}from"../../core/sheet.js";import{cellRef as b,colName as T,sheetPrefix as O}from"../../core/address.js";import{newBookName as k}from"../../core/default-names.js";import{str as L}from"../values.js";S("Information");const s=(e,t)=>h(e,1,1,t,{errors:!0});s("ISERROR",e=>e instanceof E),s("ISERR",e=>e instanceof E&&e!==o.NA),s("ISNA",e=>e===o.NA),s("ISNUMBER",e=>typeof e=="number"),s("ISTEXT",e=>typeof e=="string"),s("ISNONTEXT",e=>typeof e!="string"),s("ISLOGICAL",e=>typeof e=="boolean"),s("ISBLANK",e=>e==null),h("ISEVEN",1,1,e=>Math.trunc(N(e))%2===0),h("ISODD",1,1,e=>Math.trunc(N(e))%2!==0),f("ISREF",1,1,(e,t)=>t[0]instanceof i||t[0]instanceof d),f("ISFORMULA",1,1,(e,t)=>{const r=t[0];if(!(r instanceof i))throw o.VALUE;return(r.sheet.kind(r.r0,r.c0)&g)!==0}),h("N",1,1,e=>{if(typeof e=="number")return e;if(typeof e=="boolean")return e?1:0;if(e instanceof y)throw o.VALUE;return 0}),h("NA",0,0,()=>o.NA),s("ERROR.TYPE",e=>{if(!(e instanceof E))throw o.NA;return{"#NULL!":1,"#DIV/0!":2,"#VALUE!":3,"#REF!":4,"#NAME?":5,"#NUM!":6,"#N/A":7,"#GETTING_DATA":8,"#SPILL!":9,"#FIELD!":13,"#CALC!":14}[e.code]}),f("TYPE",1,1,(e,t)=>{const r=t[0]instanceof i&&t[0].isCell?e.read(t[0].sheet,t[0].r0,t[0].c0):t[0];return r instanceof i||r instanceof d||r instanceof I?64:r===null||typeof r=="number"?1:typeof r=="string"?2:typeof r=="boolean"?4:r instanceof E?16:r instanceof R||r instanceof y?128:1}),f("SHEET",0,1,(e,t,r,u,c)=>{if(t.length===0||t[0]===A)return e.book.sheets.indexOf(c)+1;if(t[0]instanceof i)return e.book.sheets.indexOf(t[0].sheet)+1;if(typeof t[0]=="string"){const m=e.sheetByName(t[0]);if(!m)throw o.NA;return e.book.sheets.indexOf(m)+1}throw o.VALUE},{readsSheets:!0}),f("SHEETS",0,1,(e,t)=>{if(t.length===0||t[0]===A)return e.book.sheets.length;if(t[0]instanceof d)return new Set(t[0].refs.map(r=>r.sheet)).size;if(t[0]instanceof i)return 1;throw o.REF},{readsSheets:!0}),f("INFO",1,1,(e,t,r,u)=>{switch(L(e.scalar(t[0],r,u)).toLowerCase()){case"numfile":return e.book.sheets.length;case"recalc":return e.manual?"Manual":"Automatic";case"release":return"16.0";case"system":return"mac";case"origin":return"$A:$A$1";case"directory":return"";default:throw o.VALUE}},{readsSheets:!0}),f("CELL",1,2,(e,t,r,u,c)=>{const m=L(e.scalar(t[0],r,u)).toLowerCase(),n=t[1]===void 0||t[1]===A?new i(c,r,u,r,u):t[1];if(!(n instanceof i))throw o.VALUE;const a=e.read(n.sheet,n.r0,n.c0),l=e.book.styles.get(n.sheet.style(n.r0,n.c0));switch(m){case"address":{const p=`$${T(n.c0)}$${n.r0+1}`;return n.sheet===c?p:`${O(n.sheet.name,{book:e.book.fileName??k()})}${p}`}case"col":return n.c0+1;case"row":return n.r0+1;case"contents":return a===null?0:a;case"filename":return"";case"type":return a===null?"b":typeof a=="string"?"l":"v";case"width":return Math.round(n.sheet.cols.sizeOf(n.c0)/6);case"color":return/\[red\]/i.test(l.numFmt)?1:0;case"format":return F(l.numFmt);case"parentheses":return/\(/.test(l.numFmt)?1:0;case"prefix":return typeof a=="string"?l.hAlign==="right"?'"':l.hAlign==="center"?"^":"'":"";case"protect":return 1;default:throw o.VALUE}});function F(e){return e==="General"?"G":e==="0"?"F0":e==="#,##0"?",0":e==="0.00"?"F2":e==="#,##0.00"?",2":/%/.test(e)?`P${(/\.(0+)/.exec(e)?.[1]??"").length}`:/E\+/i.test(e)?"S2":/[ymd]/i.test(e)?"D1":"G"}export{w as CONTENT_MASK,b as cellRef};
@@ -1 +1 @@
1
- import{setCategory as $}from"./registry.js";import{alias as x,lift as l,raw as m}from"./registry.js";import{Arr as D,bool as tt,checked as L,ERR as c,int as R,num as a,OMITTED as A,opt as rt,power as nt,Ref as p,RefList as b,str as k,XlError as V}from"../values.js";import{collectNumbers as j,eachValue as ot,makeCriteria as et,matrixOf as T,toolpakScalar as P}from"./helpers.js";$("Math & Trig");const M=(t,r)=>l(t,1,1,o=>L(r(a(o)))),st=2**27,g=t=>r=>{if(Math.abs(r)>=st)throw c.NUM;return t(r)},Q=t=>r=>{if(!Number.isFinite(r*r))throw c.NUM;return t(r)},W=t=>r=>{if(!Number.isFinite(Math.exp(Math.abs(r))))throw c.NUM;return t(r)};M("ABS",Math.abs),M("ACOS",t=>{if(t<-1||t>1)throw c.NUM;return Math.acos(t)}),M("ACOSH",Q(t=>{if(t<1)throw c.NUM;return Math.acosh(t)})),M("ACOT",t=>Math.PI/2-Math.atan(t)),M("ACOTH",t=>{if(Math.abs(t)<=1)throw c.NUM;return .5*Math.log((t+1)/(t-1))}),M("ASIN",t=>{if(t<-1||t>1)throw c.NUM;return Math.asin(t)}),M("ASINH",Q(Math.asinh)),M("ATAN",Math.atan),M("ATANH",t=>{if(t<=-1||t>=1)throw c.NUM;return Math.atanh(t)}),M("COS",g(Math.cos)),M("COSH",W(Math.cosh)),M("COT",g(t=>{if(t===0)throw c.DIV0;return 1/Math.tan(t)})),M("COTH",t=>{if(t===0)throw c.DIV0;return 1/Math.tanh(t)}),M("CSC",g(t=>{if(t===0)throw c.DIV0;return 1/Math.sin(t)})),M("CSCH",t=>{if(t===0)throw c.DIV0;return 1/Math.sinh(t)}),M("DEGREES",t=>t*180/Math.PI),M("EXP",Math.exp),M("INT",Math.floor),M("LN",t=>{if(t<=0)throw c.NUM;return Math.log(t)}),M("LOG10",t=>{if(t<=0)throw c.NUM;return Math.log10(t)}),M("RADIANS",t=>t*Math.PI/180),M("SEC",g(t=>1/Math.cos(t))),M("SECH",t=>1/Math.cosh(t)),M("SIGN",Math.sign),M("SIN",g(Math.sin)),M("SINH",W(Math.sinh)),M("SQRT",t=>{if(t<0)throw c.NUM;return Math.sqrt(t)}),M("SQRTPI",t=>{if(t<0)throw c.NUM;return Math.sqrt(t*Math.PI)}),M("TAN",g(Math.tan)),M("TANH",Math.tanh),l("ATAN2",2,2,(t,r)=>{const o=a(t),n=a(r);if(o===0&&n===0)throw c.DIV0;return Math.atan2(n,o)}),l("LOG",1,2,(t,r)=>{const o=a(t),n=r===void 0||r===A?10:a(r);if(o<=0||n<=0)throw c.NUM;if(n===1)throw c.DIV0;return n===10?Math.log10(o):Math.log(o)/Math.log(n)}),l("PI",0,0,()=>Math.PI),l("POWER",2,2,(t,r)=>{const o=a(t),n=a(r);if(o===0&&n===0)throw c.NUM;if(o===0&&n<0)throw c.DIV0;return L(nt(o,n))}),l("MOD",2,2,(t,r)=>{const o=a(t),n=a(r);if(n===0)throw c.DIV0;if(Math.abs(o/n)>=2**40)throw c.NUM;return L(o-n*Math.floor(o/n))}),l("QUOTIENT",2,2,(t,r)=>{const o=a(r);if(o===0)throw c.DIV0;return Math.trunc(a(t)/o)});function Y(t,r){if(!Number.isFinite(t))throw c.NUM;r>15&&(r=15);const o=10**Math.abs(r),n=r>=0?Math.abs(t)*o:Math.abs(t)/o,e=Number(n.toPrecision(15)),s=Math.floor(e+.5),f=r>=0?s/o:s*o;return t<0?-f:f}function H(t,r,o){r>15&&(r=15);const n=10**Math.abs(r),e=r>=0?Math.abs(t)*n:Math.abs(t)/n,s=Number(e.toPrecision(15)),f=o?Math.ceil(s):Math.floor(s),i=r>=0?f/n:f*n;return t<0?-i:i}l("ROUND",2,2,(t,r)=>Y(a(t),R(r))),l("ROUNDUP",2,2,(t,r)=>H(a(t),R(r),!0)),l("ROUNDDOWN",2,2,(t,r)=>H(a(t),R(r),!1)),l("TRUNC",1,2,(t,r)=>H(a(t),r===void 0||r===A?0:R(r),!1)),l("EVEN",1,1,t=>{const r=a(t),o=Math.ceil(Number((Math.abs(r)/2).toPrecision(15)))*2;return r<0?-o:o}),l("ODD",1,1,t=>{const r=Math.abs(a(t));let o=Math.ceil(Number(r.toPrecision(15)));return o%2===0&&(o+=1),a(t)<0?-o:o}),l("MROUND",2,2,(t,r)=>{const o=a(t),n=a(r);if(n===0)return 0;if(o*n<0)throw c.NUM;return Y(o/n,0)*n});function S(t,r){const o=Number((t/r).toPrecision(15));return Math.ceil(o)*r}function O(t,r){const o=Number((t/r).toPrecision(15));return Math.floor(o)*r}l("CEILING",2,2,(t,r)=>{const o=a(t),n=a(r);if(n===0)return 0;if(o>0&&n<0)throw c.NUM;return o<0&&n<0?-S(-o,-n):S(o,n)}),l("FLOOR",2,2,(t,r)=>{const o=a(t),n=a(r);if(n===0){if(o===0)return 0;throw c.DIV0}if(o>0&&n<0)throw c.NUM;return o<0&&n<0?-O(-o,-n):O(o,n)}),l("CEILING.MATH",1,3,(t,r,o)=>{const n=a(t),e=Math.abs(r===void 0||r===A?1:a(r))||0;if(e===0)return 0;const s=o===void 0||o===A?0:a(o);return n<0&&s!==0?-S(-n,e):S(n,e)}),l("FLOOR.MATH",1,3,(t,r,o)=>{const n=a(t),e=Math.abs(r===void 0||r===A?1:a(r))||0;if(e===0)return 0;const s=o===void 0||o===A?0:a(o);return n<0&&s!==0?-O(-n,e):O(n,e)}),l("CEILING.PRECISE",1,2,(t,r)=>{const o=Math.abs(r===void 0||r===A?1:a(r));return o===0?0:S(a(t),o)}),x("ISO.CEILING","CEILING.PRECISE"),l("FLOOR.PRECISE",1,2,(t,r)=>{const o=Math.abs(r===void 0||r===A?1:a(r));return o===0?0:O(a(t),o)});function ct(t){if(t<0)throw c.NUM;if(t>170)throw c.NUM;let r=1;for(let o=2;o<=t;o++)r*=o;return r}l("FACT",1,1,t=>ct(Math.floor(a(t)))),l("FACTDOUBLE",1,1,t=>{const r=Math.floor(a(t));if(r<-1)throw c.NUM;let o=1;for(let n=r;n>1;n-=2)if(o*=n,!Number.isFinite(o))throw c.NUM;return L(o)});function F(t,r){if(r<0||t<0||r>t)throw c.NUM;const o=Math.min(r,t-r);let n=1;for(let e=1;e<=o;e++)n=n*(t-o+e)/e;return L(Math.round(n))}l("COMBIN",2,2,(t,r)=>F(Math.trunc(a(t)),Math.trunc(a(r)))),l("COMBINA",2,2,(t,r)=>{const o=Math.trunc(a(t)),n=Math.trunc(a(r));if(o<0||n<0)throw c.NUM;return o===0&&n===0?1:o===0?0:F(o+n-1,n)});function _(t,r){for(;r!==0;)[t,r]=[r,t%r];return t}const G=(t,r)=>{const o=[];for(const n of r)if(n instanceof p||n instanceof b||n instanceof D)ot(t,n,e=>{if(e instanceof V)throw e;if(typeof e=="number"){if(e<0)throw c.NUM;o.push(Math.trunc(e))}else if(typeof e=="string")throw c.VALUE});else{const e=Math.trunc(a(n));if(e<0)throw c.NUM;o.push(e)}return o};m("GCD",1,255,(t,r)=>G(t,r).reduce(_,0)),m("LCM",1,255,(t,r)=>{let o=1;for(const n of G(t,r)){if(n===0)return 0;o=o/_(o,n)*n}return L(o)}),m("MULTINOMIAL",1,255,(t,r)=>{const o=G(t,r);let n=0,e=1;for(const s of o)n+=s,e*=F(n,s);return L(e)}),l("ARABIC",1,1,t=>{const r=k(t).trim().toUpperCase();if(r==="")return 0;const o=r[0]==="-",n=o?r.slice(1):r,e={M:1e3,D:500,C:100,L:50,X:10,V:5,I:1};let s=0;for(let f=0;f<n.length;f++){const i=e[n[f]];if(i===void 0)throw c.VALUE;const h=e[n[f+1]]??0;s+=i<h?-i:i}return o?-s:s}),l("ROMAN",1,2,(t,r)=>{const o=Math.trunc(a(t)),n=r===void 0||r===A?0:typeof r=="boolean"?r?0:4:Math.trunc(a(r));if(o<0||o>3999)throw c.VALUE;if(n<0||n>4)throw c.VALUE;if(o===0)return"";const e={0:[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],1:[[1e3,"M"],[950,"LM"],[900,"CM"],[500,"D"],[450,"LD"],[400,"CD"],[100,"C"],[95,"VC"],[90,"XC"],[50,"L"],[45,"VL"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],2:[[1e3,"M"],[990,"XM"],[950,"LM"],[900,"CM"],[500,"D"],[490,"XD"],[450,"LD"],[400,"CD"],[100,"C"],[99,"IC"],[95,"VC"],[90,"XC"],[50,"L"],[49,"IL"],[45,"VL"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],3:[[1e3,"M"],[995,"VM"],[990,"XM"],[950,"LM"],[900,"CM"],[500,"D"],[495,"VD"],[490,"XD"],[450,"LD"],[400,"CD"],[100,"C"],[99,"IC"],[95,"VC"],[90,"XC"],[50,"L"],[49,"IL"],[45,"VL"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],4:[[1e3,"M"],[999,"IM"],[995,"VM"],[990,"XM"],[950,"LM"],[900,"CM"],[500,"D"],[499,"ID"],[495,"VD"],[490,"XD"],[450,"LD"],[400,"CD"],[100,"C"],[99,"IC"],[95,"VC"],[90,"XC"],[50,"L"],[49,"IL"],[45,"VL"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]]};let s=o,f="";for(const[i,h]of e[n])for(;s>=i;)f+=h,s-=i;return f}),l("BASE",2,3,(t,r,o)=>{const n=Math.trunc(a(t)),e=Math.trunc(a(r)),s=o===void 0||o===A?0:Math.trunc(a(o));if(n<0||n>=2**53||e<2||e>36||s<0||s>255)throw c.NUM;return n.toString(e).toUpperCase().padStart(s,"0")}),l("DECIMAL",2,2,(t,r)=>{const o=k(t).trim().toLowerCase(),n=Math.trunc(a(r));if(n<2||n>36||o.length>255)throw c.NUM;let e=0;for(const s of o){const f=parseInt(s,36);if(Number.isNaN(f)||f>=n)throw c.NUM;e=e*n+f}return L(e)}),l("RAND",0,0,()=>Math.random(),{volatile:!0}),l("RANDBETWEEN",2,2,(t,r)=>{const o=Math.ceil(a(t)),n=Math.floor(a(r));if(o>n)throw c.NUM;return o+Math.floor(Math.random()*(n-o+1))},{volatile:!0}),m("SUM",1,255,(t,r)=>{let o=0;const n={sum:0,count:0};for(const e of r)if(typeof e=="number")o+=e;else if(e instanceof p)t.sumRange(e,n);else if(e instanceof b)for(const s of e.refs)t.sumRange(s,n);else if(e instanceof D){for(const s of e.data)if(typeof s=="number")o+=s;else if(s instanceof V)throw s}else e!==null&&e!==A&&(o+=a(e));return L(o+n.sum)}),m("PRODUCT",1,255,(t,r)=>{let o=1,n=!1;for(const e of j(t,r))o*=e,n=!0;return n?L(o):0}),m("SUMSQ",1,255,(t,r)=>L(j(t,r).reduce((o,n)=>o+n*n,0)));function ft(t,r,o,n){return{row:t.r0+(o-r.r0),col:t.c0+(n-r.c0)}}function v(t,r,o){const[n,e]=o[0],s=n.rows,f=n.cols;for(const[U]of o)if(U.rows!==s||U.cols!==f)throw c.VALUE;let i=0,h=0;const w=(U,E)=>{for(let I=1;I<o.length;I++){const[C,d]=o[I];if(!d(t.read(C.sheet,C.r0+(U-n.r0),C.c0+(E-n.c0))))return!1}return!0},N=e(null),u=(U,E,I)=>{if(!(!e(U)||!w(E,I))&&(h++,r!==null)){const C=ft(r,n,E,I),d=t.read(r.sheet,C.row,C.col);if(d instanceof V)throw d;typeof d=="number"&&(i+=d)}};if(N){const U=Math.min(n.r1,Math.max(n.sheet.maxRow,n.r0)),E=Math.min(n.c1,Math.max(n.sheet.maxCol,n.c0));for(let I=n.c0;I<=E;I++)for(let C=n.r0;C<=U;C++)u(t.read(n.sheet,C,I),C,I)}else t.scan(n,u);return{sum:i,count:h}}const X=t=>{if(t instanceof V)throw t;if(!(t instanceof p))throw c.VALUE;return t},z=(t,r,o,n)=>{const e=t.scalar(r,o,n);return et(e)};m("SUMIF",2,3,(t,r,o,n)=>{const e=X(r[0]),s=r[2]===void 0||r[2]===A?e:X(r[2]);return v(t,s,[[e,z(t,r[1],o,n)]]).sum}),m("SUMIFS",3,255,(t,r,o,n)=>{if(r.length%2===0)throw c.VALUE;const e=[];for(let f=1;f<r.length;f+=2)e.push([X(r[f]),z(t,r[f+1],o,n)]);const s=X(r[0]);if(s.rows!==e[0][0].rows||s.cols!==e[0][0].cols)throw c.VALUE;return v(t,s,e).sum}),m("SUMPRODUCT",1,255,(t,r)=>{const o=r.map(i=>{if(i instanceof V)throw i;return t.toArr(i)}),{rows:n,cols:e}=o[0];for(const i of o)if(i.rows!==n||i.cols!==e)throw c.VALUE;let s=0;const f=n*e;for(let i=0;i<f;i++){let h=1;for(const w of o){const N=w.data[i];if(N instanceof V)throw N;h*=typeof N=="number"?N:0}s+=h}return L(s)},{array:!0});const it=(t,r,o)=>{const n=t.toArr(r),e=t.toArr(o);if(n.rows!==e.rows||n.cols!==e.cols)throw c.NA;return[n.data,e.data]},B=(t,r)=>m(t,2,2,(o,n)=>{const[e,s]=it(o,n[0],n[1]);let f=0;for(let i=0;i<e.length;i++){if(e[i]instanceof V)throw e[i];if(s[i]instanceof V)throw s[i];typeof e[i]=="number"&&typeof s[i]=="number"&&(f+=r(e[i],s[i]))}return L(f)},{array:!0});B("SUMX2MY2",(t,r)=>t*t-r*r),B("SUMX2PY2",(t,r)=>t*t+r*r),B("SUMXMY2",(t,r)=>(t-r)**2),m("SERIESSUM",4,4,(t,r,o,n)=>{const e=a(P(t,r[0],o,n)),s=a(P(t,r[1],o,n)),f=a(P(t,r[2],o,n));let i=0,h=0;for(const w of t.toArr(r[3]).data)i+=a(w)*e**(s+h*f),h++;return L(i)});function J(t,r,o,n,e){const{sheet:s}=r;t.scan(r,(f,i,h)=>{if(!(!o&&(s.rows.isHidden(i)||s.filteredRows?.has(i)))&&!t.isSubtotalCell(s,i,h)){if(f instanceof V){if(n)return;throw f}e.push(f)}})}function K(t,r,o){const n=r.length,e=()=>r.reduce((i,h)=>i+h,0),s=()=>e()/n,f=i=>{const h=s();return r.reduce((w,N)=>w+(N-h)**2,0)/(i?n:n-1)};switch(t){case 1:if(n===0)throw c.DIV0;return s();case 2:return n;case 3:return o.length;case 4:return n===0?0:Math.max(...r);case 5:return n===0?0:Math.min(...r);case 6:return n===0?0:r.reduce((i,h)=>i*h,1);case 7:if(n<2)throw c.DIV0;return Math.sqrt(f(!1));case 8:if(n===0)throw c.DIV0;return Math.sqrt(f(!0));case 9:return e();case 10:if(n<2)throw c.DIV0;return f(!1);case 11:if(n===0)throw c.DIV0;return f(!0);default:throw c.VALUE}}m("SUBTOTAL",2,255,(t,r,o,n)=>{const e=Math.trunc(a(t.scalar(r[0],o,n))),s=e>=1&&e<=11,f=e>100?e-100:e;if(f<1||f>11)throw c.VALUE;const i=[];for(let h=1;h<r.length;h++){const w=r[h]instanceof b?r[h].refs:[r[h]];for(const N of w){if(!(N instanceof p))throw c.VALUE;J(t,N,s,!1,i)}}return K(f,i.filter(h=>typeof h=="number"),i)});function y(t,r){const o=t.length;if(o===0||r<0||r>1)throw c.NUM;const n=r*(o-1),e=Math.floor(n),s=n-e;return s===0?t[e]:t[e]+s*(t[e+1]-t[e])}function q(t,r){const o=t.length,n=r*(o+1)-1;if(r<=0||r>=1||n<0||n>o-1)throw c.NUM;const e=Math.floor(n),s=n-e;return s===0?t[e]:t[e]+s*(t[e+1]-t[e])}m("AGGREGATE",3,255,(t,r,o,n)=>{const e=Math.trunc(a(t.scalar(r[0],o,n))),s=Math.trunc(a(t.scalar(r[1],o,n)));if(s<0||s>7)throw c.VALUE;const f=s===1||s===3||s===5||s===7,i=s===2||s===3||s===6||s===7,h=u=>{const U=[],E=u instanceof b?u.refs:[u];for(const I of E)if(I instanceof p)J(t,I,!f,i,U);else if(I instanceof D)for(const C of I.data)if(C instanceof V){if(!i)throw C}else C!==null&&U.push(C);else if(I instanceof V){if(!i)throw I}else I!==A&&I!==null&&I!==void 0&&U.push(a(I));return U};if(e>=1&&e<=13){for(let u=2;u<r.length;u++)if(r[u]instanceof V)throw r[u];for(let u=2;u<r.length;u++)if(!(r[u]instanceof p||r[u]instanceof b))throw c.VALUE}if(e>=1&&e<=11){const u=[];for(let U=2;U<r.length;U++)u.push(...h(r[U]));return K(e,u.filter(U=>typeof U=="number"),u)}const w=h(r[2]).filter(u=>typeof u=="number").sort((u,U)=>u-U),N=a(t.scalar(r[3],o,n));switch(e){case 12:return y(w,.5);case 13:return Z(w);case 14:{const u=Math.ceil(N);if(u<1||u>w.length)throw c.NUM;return w[w.length-u]}case 15:{const u=Math.ceil(N);if(u<1||u>w.length)throw c.NUM;return w[u-1]}case 16:return y(w,N);case 17:return y(w,N/4);case 18:return q(w,N);case 19:return q(w,N/4);default:throw c.VALUE}},{array:!0});function Z(t){const r=new Map;let o=null,n=1;for(const e of t){const s=(r.get(e)??0)+1;r.set(e,s),s>n&&(n=s,o=e)}if(o===null)throw c.NA;return o}function at(t){const r=t.length,o=t.map(e=>e.slice());let n=1;for(let e=0;e<r;e++){let s=e;for(let f=e+1;f<r;f++)Math.abs(o[f][e])>Math.abs(o[s][e])&&(s=f);if(o[s][e]===0)return 0;s!==e&&([o[s],o[e]]=[o[e],o[s]],n=-n),n*=o[e][e];for(let f=e+1;f<r;f++){const i=o[f][e]/o[e][e];for(let h=e;h<r;h++)o[f][h]-=i*o[e][h]}}return n}m("MDETERM",1,1,(t,r)=>{const o=T(t,r[0]);if(o.length!==o[0].length)throw c.VALUE;return at(o)},{array:!0}),m("MINVERSE",1,1,(t,r)=>{const o=T(t,r[0]),n=o.length;if(n!==o[0].length)throw c.VALUE;const e=o.map((s,f)=>[...s,...s.map((i,h)=>f===h?1:0)]);for(let s=0;s<n;s++){let f=s;for(let h=s+1;h<n;h++)Math.abs(e[h][s])>Math.abs(e[f][s])&&(f=h);if(Math.abs(e[f][s])<1e-300)throw c.NUM;[e[f],e[s]]=[e[s],e[f]];const i=e[s][s];for(let h=0;h<2*n;h++)e[s][h]/=i;for(let h=0;h<n;h++){if(h===s)continue;const w=e[h][s];for(let N=0;N<2*n;N++)e[h][N]-=w*e[s][N]}}return D.of2D(e.map(s=>s.slice(n)))},{array:!0}),m("MMULT",2,2,(t,r)=>{const o=T(t,r[0]),n=T(t,r[1]);if(o[0].length!==n.length)throw c.VALUE;const e=[];for(let s=0;s<o.length;s++){const f=[];for(let i=0;i<n[0].length;i++){let h=0;for(let w=0;w<n.length;w++)h+=o[s][w]*n[w][i];f.push(h)}e.push(f)}return D.of2D(e)},{array:!0}),l("MUNIT",1,1,t=>{const r=Math.trunc(a(t));if(r<1)throw c.VALUE;const o=new Array(r*r).fill(0);for(let n=0;n<r;n++)o[n*r+n]=1;return new D(r,r,o)});export{tt as bool,Z as modeOf,rt as opt,q as percentileExc,y as percentileInc,v as sumIfs};
1
+ import{setCategory as $}from"./registry.js";import{alias as x,lift as l,raw as m}from"./registry.js";import{Arr as D,bool as tt,checked as L,ERR as c,int as R,num as a,OMITTED as A,opt as rt,power as nt,Ref as p,RefList as b,str as k,XlError as V}from"../values.js";import{collectNumbers as j,eachValue as ot,makeCriteria as et,matrixOf as T,toolpakScalar as P}from"./helpers.js";$("Math & Trig");const w=(t,r)=>l(t,1,1,o=>L(r(a(o)))),st=2**27,g=t=>r=>{if(Math.abs(r)>=st)throw c.NUM;return t(r)},Q=t=>r=>{if(!Number.isFinite(r*r))throw c.NUM;return t(r)},W=t=>r=>{if(!Number.isFinite(Math.exp(Math.abs(r))))throw c.NUM;return t(r)};w("ABS",Math.abs),w("ACOS",t=>{if(t<-1||t>1)throw c.NUM;return Math.acos(t)}),w("ACOSH",Q(t=>{if(t<1)throw c.NUM;return Math.acosh(t)})),w("ACOT",t=>Math.PI/2-Math.atan(t)),w("ACOTH",t=>{if(Math.abs(t)<=1)throw c.NUM;return .5*Math.log((t+1)/(t-1))}),w("ASIN",t=>{if(t<-1||t>1)throw c.NUM;return Math.asin(t)}),w("ASINH",Q(Math.asinh)),w("ATAN",Math.atan),w("ATANH",t=>{if(t<=-1||t>=1)throw c.NUM;return Math.atanh(t)}),w("COS",g(Math.cos)),w("COSH",W(Math.cosh)),w("COT",g(t=>{if(t===0)throw c.DIV0;return 1/Math.tan(t)})),w("COTH",t=>{if(t===0)throw c.DIV0;return 1/Math.tanh(t)}),w("CSC",g(t=>{if(t===0)throw c.DIV0;return 1/Math.sin(t)})),w("CSCH",t=>{if(t===0)throw c.DIV0;return 1/Math.sinh(t)}),w("DEGREES",t=>t*180/Math.PI),w("EXP",Math.exp),w("INT",Math.floor),w("LN",t=>{if(t<=0)throw c.NUM;return Math.log(t)}),w("LOG10",t=>{if(t<=0)throw c.NUM;return Math.log10(t)}),w("RADIANS",t=>t*Math.PI/180),w("SEC",g(t=>1/Math.cos(t))),w("SECH",t=>1/Math.cosh(t)),w("SIGN",Math.sign),w("SIN",g(Math.sin)),w("SINH",W(Math.sinh)),w("SQRT",t=>{if(t<0)throw c.NUM;return Math.sqrt(t)}),w("SQRTPI",t=>{if(t<0)throw c.NUM;return Math.sqrt(t*Math.PI)}),w("TAN",g(Math.tan)),w("TANH",Math.tanh),l("ATAN2",2,2,(t,r)=>{const o=a(t),n=a(r);if(o===0&&n===0)throw c.DIV0;return Math.atan2(n,o)}),l("LOG",1,2,(t,r)=>{const o=a(t),n=r===void 0||r===A?10:a(r);if(o<=0||n<=0)throw c.NUM;if(n===1)throw c.DIV0;return n===10?Math.log10(o):Math.log(o)/Math.log(n)}),l("PI",0,0,()=>Math.PI),l("POWER",2,2,(t,r)=>{const o=a(t),n=a(r);if(o===0&&n===0)throw c.NUM;if(o===0&&n<0)throw c.DIV0;return L(nt(o,n))}),l("MOD",2,2,(t,r)=>{const o=a(t),n=a(r);if(n===0)throw c.DIV0;if(Math.abs(o/n)>=2**40)throw c.NUM;return L(o-n*Math.floor(o/n))}),l("QUOTIENT",2,2,(t,r)=>{const o=a(r);if(o===0)throw c.DIV0;return Math.trunc(a(t)/o)});function Y(t,r){if(!Number.isFinite(t))throw c.NUM;r>15&&(r=15);const o=10**Math.abs(r),n=r>=0?Math.abs(t)*o:Math.abs(t)/o,e=Number(n.toPrecision(15)),s=Math.floor(e+.5),f=r>=0?s/o:s*o;return t<0?-f:f}function H(t,r,o){r>15&&(r=15);const n=10**Math.abs(r),e=r>=0?Math.abs(t)*n:Math.abs(t)/n,s=Number(e.toPrecision(15)),f=o?Math.ceil(s):Math.floor(s),i=r>=0?f/n:f*n;return t<0?-i:i}l("ROUND",2,2,(t,r)=>Y(a(t),R(r))),l("ROUNDUP",2,2,(t,r)=>H(a(t),R(r),!0)),l("ROUNDDOWN",2,2,(t,r)=>H(a(t),R(r),!1)),l("TRUNC",1,2,(t,r)=>H(a(t),r===void 0||r===A?0:R(r),!1)),l("EVEN",1,1,t=>{const r=a(t),o=Math.ceil(Number((Math.abs(r)/2).toPrecision(15)))*2;return r<0?-o:o}),l("ODD",1,1,t=>{const r=Math.abs(a(t));let o=Math.ceil(Number(r.toPrecision(15)));return o%2===0&&(o+=1),a(t)<0?-o:o}),l("MROUND",2,2,(t,r)=>{const o=a(t),n=a(r);if(n===0)return 0;if(o*n<0)throw c.NUM;return Y(o/n,0)*n});function S(t,r){const o=Number((t/r).toPrecision(15));return Math.ceil(o)*r}function O(t,r){const o=Number((t/r).toPrecision(15));return Math.floor(o)*r}l("CEILING",2,2,(t,r)=>{const o=a(t),n=a(r);if(n===0)return 0;if(o>0&&n<0)throw c.NUM;return o<0&&n<0?-S(-o,-n):S(o,n)}),l("FLOOR",2,2,(t,r)=>{const o=a(t),n=a(r);if(n===0){if(o===0)return 0;throw c.DIV0}if(o>0&&n<0)throw c.NUM;return o<0&&n<0?-O(-o,-n):O(o,n)}),l("CEILING.MATH",1,3,(t,r,o)=>{const n=a(t),e=Math.abs(r===void 0||r===A?1:a(r))||0;if(e===0)return 0;const s=o===void 0||o===A?0:a(o);return n<0&&s!==0?-S(-n,e):S(n,e)}),l("FLOOR.MATH",1,3,(t,r,o)=>{const n=a(t),e=Math.abs(r===void 0||r===A?1:a(r))||0;if(e===0)return 0;const s=o===void 0||o===A?0:a(o);return n<0&&s!==0?-O(-n,e):O(n,e)}),l("CEILING.PRECISE",1,2,(t,r)=>{const o=Math.abs(r===void 0||r===A?1:a(r));return o===0?0:S(a(t),o)}),x("ISO.CEILING","CEILING.PRECISE"),l("FLOOR.PRECISE",1,2,(t,r)=>{const o=Math.abs(r===void 0||r===A?1:a(r));return o===0?0:O(a(t),o)});function ct(t){if(t<0)throw c.NUM;if(t>170)throw c.NUM;let r=1;for(let o=2;o<=t;o++)r*=o;return r}l("FACT",1,1,t=>ct(Math.floor(a(t)))),l("FACTDOUBLE",1,1,t=>{const r=Math.floor(a(t));if(r<-1)throw c.NUM;let o=1;for(let n=r;n>1;n-=2)if(o*=n,!Number.isFinite(o))throw c.NUM;return L(o)});function F(t,r){if(r<0||t<0||r>t)throw c.NUM;const o=Math.min(r,t-r);let n=1;for(let e=1;e<=o;e++)n=n*(t-o+e)/e;return L(Math.round(n))}l("COMBIN",2,2,(t,r)=>F(Math.trunc(a(t)),Math.trunc(a(r)))),l("COMBINA",2,2,(t,r)=>{const o=Math.trunc(a(t)),n=Math.trunc(a(r));if(o<0||n<0)throw c.NUM;return o===0&&n===0?1:o===0?0:F(o+n-1,n)});function _(t,r){for(;r!==0;)[t,r]=[r,t%r];return t}const G=(t,r)=>{const o=[];for(const n of r)if(n instanceof p||n instanceof b||n instanceof D)ot(t,n,e=>{if(e instanceof V)throw e;if(typeof e=="number"){if(e<0)throw c.NUM;o.push(Math.trunc(e))}else if(typeof e=="string")throw c.VALUE});else{const e=Math.trunc(a(n));if(e<0)throw c.NUM;o.push(e)}return o};m("GCD",1,255,(t,r)=>G(t,r).reduce(_,0)),m("LCM",1,255,(t,r)=>{let o=1;for(const n of G(t,r)){if(n===0)return 0;o=o/_(o,n)*n}return L(o)}),m("MULTINOMIAL",1,255,(t,r)=>{const o=G(t,r);let n=0,e=1;for(const s of o)n+=s,e*=F(n,s);return L(e)}),l("ARABIC",1,1,t=>{const r=k(t).trim().toUpperCase();if(r==="")return 0;const o=r[0]==="-",n=o?r.slice(1):r,e={M:1e3,D:500,C:100,L:50,X:10,V:5,I:1};let s=0;for(let f=0;f<n.length;f++){const i=e[n[f]];if(i===void 0)throw c.VALUE;const h=e[n[f+1]]??0;s+=i<h?-i:i}return o?-s:s}),l("ROMAN",1,2,(t,r)=>{const o=Math.trunc(a(t)),n=r===void 0||r===A?0:typeof r=="boolean"?r?0:4:Math.trunc(a(r));if(o<0||o>3999)throw c.VALUE;if(n<0||n>4)throw c.VALUE;if(o===0)return"";const e={0:[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],1:[[1e3,"M"],[950,"LM"],[900,"CM"],[500,"D"],[450,"LD"],[400,"CD"],[100,"C"],[95,"VC"],[90,"XC"],[50,"L"],[45,"VL"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],2:[[1e3,"M"],[990,"XM"],[950,"LM"],[900,"CM"],[500,"D"],[490,"XD"],[450,"LD"],[400,"CD"],[100,"C"],[99,"IC"],[95,"VC"],[90,"XC"],[50,"L"],[49,"IL"],[45,"VL"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],3:[[1e3,"M"],[995,"VM"],[990,"XM"],[950,"LM"],[900,"CM"],[500,"D"],[495,"VD"],[490,"XD"],[450,"LD"],[400,"CD"],[100,"C"],[99,"IC"],[95,"VC"],[90,"XC"],[50,"L"],[49,"IL"],[45,"VL"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],4:[[1e3,"M"],[999,"IM"],[995,"VM"],[990,"XM"],[950,"LM"],[900,"CM"],[500,"D"],[499,"ID"],[495,"VD"],[490,"XD"],[450,"LD"],[400,"CD"],[100,"C"],[99,"IC"],[95,"VC"],[90,"XC"],[50,"L"],[49,"IL"],[45,"VL"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]]};let s=o,f="";for(const[i,h]of e[n])for(;s>=i;)f+=h,s-=i;return f}),l("BASE",2,3,(t,r,o)=>{const n=Math.trunc(a(t)),e=Math.trunc(a(r)),s=o===void 0||o===A?0:Math.trunc(a(o));if(n<0||n>=2**53||e<2||e>36||s<0||s>255)throw c.NUM;return n.toString(e).toUpperCase().padStart(s,"0")}),l("DECIMAL",2,2,(t,r)=>{const o=k(t).trim().toLowerCase(),n=Math.trunc(a(r));if(n<2||n>36||o.length>255)throw c.NUM;let e=0;for(const s of o){const f=parseInt(s,36);if(Number.isNaN(f)||f>=n)throw c.NUM;e=e*n+f}return L(e)}),l("RAND",0,0,()=>Math.random(),{volatile:!0}),l("RANDBETWEEN",2,2,(t,r)=>{const o=Math.ceil(a(t)),n=Math.floor(a(r));if(o>n)throw c.NUM;return o+Math.floor(Math.random()*(n-o+1))},{volatile:!0}),m("SUM",1,255,(t,r)=>{let o=0;const n={sum:0,count:0};for(const e of r)if(typeof e=="number")o+=e;else if(e instanceof p)t.sumRange(e,n);else if(e instanceof b)for(const s of e.refs)t.sumRange(s,n);else if(e instanceof D){for(const s of e.data)if(typeof s=="number")o+=s;else if(s instanceof V)throw s}else e!==null&&e!==A&&(o+=a(e));return L(o+n.sum)}),m("PRODUCT",1,255,(t,r)=>{let o=1,n=!1;for(const e of j(t,r))o*=e,n=!0;return n?L(o):0}),m("SUMSQ",1,255,(t,r)=>L(j(t,r).reduce((o,n)=>o+n*n,0)));function ft(t,r,o,n){return{row:t.r0+(o-r.r0),col:t.c0+(n-r.c0)}}function v(t,r,o){const[n,e]=o[0],s=n.rows,f=n.cols;for(const[U]of o)if(U.rows!==s||U.cols!==f)throw c.VALUE;let i=0,h=0;const M=(U,E)=>{for(let I=1;I<o.length;I++){const[C,d]=o[I];if(!d(t.read(C.sheet,C.r0+(U-n.r0),C.c0+(E-n.c0))))return!1}return!0},N=e(null),u=(U,E,I)=>{if(!(!e(U)||!M(E,I))&&(h++,r!==null)){const C=ft(r,n,E,I),d=t.read(r.sheet,C.row,C.col);if(d instanceof V)throw d;typeof d=="number"&&(i+=d)}};if(N){const U=Math.min(n.r1,Math.max(n.sheet.maxRow,n.r0)),E=Math.min(n.c1,Math.max(n.sheet.maxCol,n.c0));for(let I=n.c0;I<=E;I++)for(let C=n.r0;C<=U;C++)u(t.read(n.sheet,C,I),C,I)}else t.scan(n,u);return{sum:i,count:h}}const X=t=>{if(t instanceof V)throw t;if(!(t instanceof p))throw c.VALUE;return t},z=(t,r,o,n)=>{const e=t.scalar(r,o,n);return et(e)};m("SUMIF",2,3,(t,r,o,n)=>{const e=X(r[0]),s=r[2]===void 0||r[2]===A?e:X(r[2]);return v(t,s,[[e,z(t,r[1],o,n)]]).sum}),m("SUMIFS",3,255,(t,r,o,n)=>{if(r.length%2===0)throw c.VALUE;const e=[];for(let f=1;f<r.length;f+=2)e.push([X(r[f]),z(t,r[f+1],o,n)]);const s=X(r[0]);if(s.rows!==e[0][0].rows||s.cols!==e[0][0].cols)throw c.VALUE;return v(t,s,e).sum}),m("SUMPRODUCT",1,255,(t,r)=>{const o=r.map(i=>{if(i instanceof V)throw i;return t.toArr(i)}),{rows:n,cols:e}=o[0];for(const i of o)if(i.rows!==n||i.cols!==e)throw c.VALUE;let s=0;const f=n*e;for(let i=0;i<f;i++){let h=1;for(const M of o){const N=M.data[i];if(N instanceof V)throw N;h*=typeof N=="number"?N:0}s+=h}return L(s)},{array:!0});const it=(t,r,o)=>{const n=t.toArr(r),e=t.toArr(o);if(n.rows!==e.rows||n.cols!==e.cols)throw c.NA;return[n.data,e.data]},B=(t,r)=>m(t,2,2,(o,n)=>{const[e,s]=it(o,n[0],n[1]);let f=0;for(let i=0;i<e.length;i++){if(e[i]instanceof V)throw e[i];if(s[i]instanceof V)throw s[i];typeof e[i]=="number"&&typeof s[i]=="number"&&(f+=r(e[i],s[i]))}return L(f)},{array:!0});B("SUMX2MY2",(t,r)=>t*t-r*r),B("SUMX2PY2",(t,r)=>t*t+r*r),B("SUMXMY2",(t,r)=>(t-r)**2),m("SERIESSUM",4,4,(t,r,o,n)=>{const e=a(P(t,r[0],o,n)),s=a(P(t,r[1],o,n)),f=a(P(t,r[2],o,n));let i=0,h=0;for(const M of t.toArr(r[3]).data)i+=a(M)*e**(s+h*f),h++;return L(i)});function J(t,r,o,n,e,s){const{sheet:f}=r;t.scan(r,(i,h,M)=>{if(!(!n&&f.filteredRows?.has(h)||!o&&f.rows.isHidden(h))&&!t.isSubtotalCell(f,h,M)){if(i instanceof V){if(e)return;throw i}s.push(i)}})}function K(t,r,o){const n=r.length,e=()=>r.reduce((i,h)=>i+h,0),s=()=>e()/n,f=i=>{const h=s();return r.reduce((M,N)=>M+(N-h)**2,0)/(i?n:n-1)};switch(t){case 1:if(n===0)throw c.DIV0;return s();case 2:return n;case 3:return o.length;case 4:return n===0?0:Math.max(...r);case 5:return n===0?0:Math.min(...r);case 6:return n===0?0:r.reduce((i,h)=>i*h,1);case 7:if(n<2)throw c.DIV0;return Math.sqrt(f(!1));case 8:if(n===0)throw c.DIV0;return Math.sqrt(f(!0));case 9:return e();case 10:if(n<2)throw c.DIV0;return f(!1);case 11:if(n===0)throw c.DIV0;return f(!0);default:throw c.VALUE}}m("SUBTOTAL",2,255,(t,r,o,n)=>{const e=Math.trunc(a(t.scalar(r[0],o,n))),s=e>=1&&e<=11,f=e>100?e-100:e;if(f<1||f>11)throw c.VALUE;const i=[];for(let h=1;h<r.length;h++){const M=r[h]instanceof b?r[h].refs:[r[h]];for(const N of M){if(!(N instanceof p))throw c.VALUE;J(t,N,s,!1,!1,i)}}return K(f,i.filter(h=>typeof h=="number"),i)});function y(t,r){const o=t.length;if(o===0||r<0||r>1)throw c.NUM;const n=r*(o-1),e=Math.floor(n),s=n-e;return s===0?t[e]:t[e]+s*(t[e+1]-t[e])}function q(t,r){const o=t.length,n=r*(o+1)-1;if(r<=0||r>=1||n<0||n>o-1)throw c.NUM;const e=Math.floor(n),s=n-e;return s===0?t[e]:t[e]+s*(t[e+1]-t[e])}m("AGGREGATE",3,255,(t,r,o,n)=>{const e=Math.trunc(a(t.scalar(r[0],o,n))),s=Math.trunc(a(t.scalar(r[1],o,n)));if(s<0||s>7)throw c.VALUE;const f=s===1||s===3||s===5||s===7,i=s===2||s===3||s===6||s===7,h=u=>{const U=[],E=u instanceof b?u.refs:[u];for(const I of E)if(I instanceof p)J(t,I,!f,!f,i,U);else if(I instanceof D)for(const C of I.data)if(C instanceof V){if(!i)throw C}else C!==null&&U.push(C);else if(I instanceof V){if(!i)throw I}else I!==A&&I!==null&&I!==void 0&&U.push(a(I));return U};if(e>=1&&e<=13){for(let u=2;u<r.length;u++)if(r[u]instanceof V)throw r[u];for(let u=2;u<r.length;u++)if(!(r[u]instanceof p||r[u]instanceof b))throw c.VALUE}if(e>=1&&e<=11){const u=[];for(let U=2;U<r.length;U++)u.push(...h(r[U]));return K(e,u.filter(U=>typeof U=="number"),u)}const M=h(r[2]).filter(u=>typeof u=="number").sort((u,U)=>u-U),N=a(t.scalar(r[3],o,n));switch(e){case 12:return y(M,.5);case 13:return Z(M);case 14:{const u=Math.ceil(N);if(u<1||u>M.length)throw c.NUM;return M[M.length-u]}case 15:{const u=Math.ceil(N);if(u<1||u>M.length)throw c.NUM;return M[u-1]}case 16:return y(M,N);case 17:return y(M,N/4);case 18:return q(M,N);case 19:return q(M,N/4);default:throw c.VALUE}},{array:!0});function Z(t){const r=new Map;let o=null,n=1;for(const e of t){const s=(r.get(e)??0)+1;r.set(e,s),s>n&&(n=s,o=e)}if(o===null)throw c.NA;return o}function at(t){const r=t.length,o=t.map(e=>e.slice());let n=1;for(let e=0;e<r;e++){let s=e;for(let f=e+1;f<r;f++)Math.abs(o[f][e])>Math.abs(o[s][e])&&(s=f);if(o[s][e]===0)return 0;s!==e&&([o[s],o[e]]=[o[e],o[s]],n=-n),n*=o[e][e];for(let f=e+1;f<r;f++){const i=o[f][e]/o[e][e];for(let h=e;h<r;h++)o[f][h]-=i*o[e][h]}}return n}m("MDETERM",1,1,(t,r)=>{const o=T(t,r[0]);if(o.length!==o[0].length)throw c.VALUE;return at(o)},{array:!0}),m("MINVERSE",1,1,(t,r)=>{const o=T(t,r[0]),n=o.length;if(n!==o[0].length)throw c.VALUE;const e=o.map((s,f)=>[...s,...s.map((i,h)=>f===h?1:0)]);for(let s=0;s<n;s++){let f=s;for(let h=s+1;h<n;h++)Math.abs(e[h][s])>Math.abs(e[f][s])&&(f=h);if(Math.abs(e[f][s])<1e-300)throw c.NUM;[e[f],e[s]]=[e[s],e[f]];const i=e[s][s];for(let h=0;h<2*n;h++)e[s][h]/=i;for(let h=0;h<n;h++){if(h===s)continue;const M=e[h][s];for(let N=0;N<2*n;N++)e[h][N]-=M*e[s][N]}}return D.of2D(e.map(s=>s.slice(n)))},{array:!0}),m("MMULT",2,2,(t,r)=>{const o=T(t,r[0]),n=T(t,r[1]);if(o[0].length!==n.length)throw c.VALUE;const e=[];for(let s=0;s<o.length;s++){const f=[];for(let i=0;i<n[0].length;i++){let h=0;for(let M=0;M<n.length;M++)h+=o[s][M]*n[M][i];f.push(h)}e.push(f)}return D.of2D(e)},{array:!0}),l("MUNIT",1,1,t=>{const r=Math.trunc(a(t));if(r<1)throw c.VALUE;const o=new Array(r*r).fill(0);for(let n=0;n<r;n++)o[n*r+n]=1;return new D(r,r,o)});export{tt as bool,Z as modeOf,rt as opt,q as percentileExc,y as percentileInc,v as sumIfs};
package/calc/parser.js CHANGED
@@ -1,3 +1,3 @@
1
- import{colIndex as O,MAX_COLS as S,MAX_ROWS as V,PLAIN_SHEET as B}from"../core/address.js";import{ERR_BY_CODE as w}from"./values.js";import{CATEGORIES as y,categoryFunctions as H,FUNCS as T}from"./functions/registry.js";const g=s=>T.has(s);class f extends Error{}const W=/\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6}/y,X=/(\$?)([A-Za-z]{1,3}):(\$?)([A-Za-z]{1,3})/y,Y=/(\$?)([1-9][0-9]{0,6}):(\$?)([1-9][0-9]{0,6})/y,x=/(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y,z=/[A-Za-z_\\\u0080-￿][A-Za-z0-9_.\\?\u0080-￿]*/y,K=/#(?:NULL!|DIV\/0!|VALUE!|REF!|NAME\?|NUM!|N\/A|GETTING_DATA|SPILL!|CALC!|BUSY!|CONNECT!|BLOCKED!|FIELD!|UNKNOWN!)/iy,L=/^(?:_xlfn\._xlws\.|_xlfn\.|_xlws\.|_xlpm\.|_xludf\.|_xleta\.)/i,N=s=>s!==void 0&&/[A-Za-z0-9_.\u0080-￿]/.test(s);function p(s,t,e){return s.lastIndex=e,s.exec(t)}function $(s){if(s.indexOf(".:")<0&&s.indexOf(":.")<0)return d(s);const t=new Set,e=new Map;if(C(s,(c,l)=>{for(const a of c.matchAll(b)){const[,r,h,u]=a;if(!h&&!u)continue;const A=l+a.index+r.length+h.length;h&&t.add(A-1),u&&t.add(A+1),e.set(A,h&&u?"ALL":h?"LEADING":"TRAILING")}return c}),t.size===0)return d(s);let n="";const o=[];for(let c=0;c<s.length;c++)t.has(c)||(o.push(c),n+=s[c]);o.push(s.length);const i=d(n);for(const c of i){const l=o[c.s],a=c.e>0?o[c.e-1]+1:0;for(const[r,h]of e)r>=l&&r<a&&(c.trim=h);c.s=l,c.e=a}return i}function d(s){const t=[];let e=0;const n=s.length,o=(i,c,l,a)=>t.push({t:i,v:c,s:l,e:a});for(;e<n;){const i=s[e];if(i===" "||i===`
2
- `||i==="\r"||i===" "){const l=e;for(;e<n&&(s[e]===" "||s[e]===`
3
- `||s[e]==="\r"||s[e]===" ");)e++;o("ws",null,l,e);continue}if(i==='"'){const l=e;let a="";for(e++;;){if(e>=n)throw new f("Unterminated string");if(s[e]==='"'){if(s[e+1]==='"'){a+='"',e+=2;continue}e++;break}a+=s[e++]}o("str",a,l,e);continue}if(i==="'"||i==="["){const l=v(s,e);if(l){o("sheet",l.value,e,l.end),e=l.end;continue}if(i==="["){const a=R(s,e);o("table",{name:null,spec:s.slice(e,a)},e,a),e=a;continue}throw new f("Unexpected quote")}if(i==="#"){const l=p(K,s,e);l?(o("err",w.get(l[0].toUpperCase()),e,e+l[0].length),e+=l[0].length):(o("op","#",e,e+1),e++);continue}if(i>="0"&&i<="9"||i==="."||i==="$"||/[A-Za-z_\\\u0080-￿]/.test(i)){let l=p(Y,s,e);if(l&&!N(s[e+l[0].length])){o("rows",{a0:l[1]==="$",r0:Number(l[2])-1,a1:l[3]==="$",r1:Number(l[4])-1},e,e+l[0].length),e+=l[0].length;continue}if(l=p(X,s,e),l&&!N(s[e+l[0].length])&&s[e+l[0].length]!=="("&&s[e+l[0].length]!=="!"){const a=O(l[2]),r=O(l[4]);if(a<S&&r<S){o("cols",{a0:l[1]==="$",c0:a,a1:l[3]==="$",c1:r},e,e+l[0].length),e+=l[0].length;continue}}if(l=p(W,s,e),l){const a=s[e+l[0].length];if(!N(a)&&a!=="("&&a!=="!"&&a!=="["){const r=I(l[0]);if(r){o("cell",r,e,e+l[0].length),e+=l[0].length;continue}}else if(a==="."&&i==="$"){const r=p(/[A-Za-z0-9_.\\?\u0080-￿]*/y,s,e+l[0].length),h=e+l[0].length+r[0].length;o(s[h]==="["?"table":"name",s[h]==="["?{name:s.slice(e,h),spec:s.slice(h,R(s,h))}:s.slice(e,h),e,s[h]==="["?R(s,h):h),e=t[t.length-1].e;continue}}if(i>="0"&&i<="9"||i==="."){if(l=p(x,s,e),!l)throw new f("Bad number");o("num",Number(l[0]),e,e+l[0].length),e+=l[0].length;continue}if(l=p(z,s,e),l){const a=e+l[0].length,r=s[a];if(r==="!"||r===":"&&Z(s,a)){const h=v(s,e);if(h){o("sheet",h.value,e,h.end),e=h.end;continue}}if(r==="(")o("func",l[0].replace(L,"").toUpperCase(),e,a);else if(r==="["){const h=R(s,a);o("table",{name:l[0],spec:s.slice(a,h)},e,h),e=h;continue}else o("name",l[0].replace(L,""),e,a);e=a;continue}}const c=s.slice(e,e+2);if(c==="<="||c===">="||c==="<>"){o("op",c,e,e+2),e+=2;continue}if("+-*/^&=<>%(),;:{}@".includes(i)){o("op",i,e,e+1),e++;continue}throw new f(`Unexpected character ${i}`)}return t}function Z(s,t){return/^:'?[^'!:]+'?!/.exec(s.slice(t,t+64))!==null}function R(s,t){let e=0;for(let n=t;n<s.length;n++){if(s[n]==="'"&&s[n+1]!==void 0){n++;continue}if(s[n]==="[")e++;else if(s[n]==="]"&&(e--,e===0))return n+1}throw new f("Unterminated [")}function v(s,t){let e=t,n=null;const o=()=>{if(s[e]==="'"){let r="";for(e++;;){if(e>=s.length)return null;if(s[e]==="'"){if(s[e+1]==="'"){r+="'",e+=2;continue}return e++,r}r+=s[e++]}}const a=e;for(;e<s.length&&!'!:,()+-*/^&=<>%{}; "'.includes(s[e]);)e++;return e>a?s.slice(a,e):null};if(s[e]==="["){const a=s.indexOf("]",e);if(a<0)return null;n=s.slice(e+1,a),e=a+1}let i=o();if(i===null)return null;const c=/\[([^\]]+)\](.*)$/.exec(i);c&&(n=c[1],i=c[2]);let l=null;return s[e]===":"&&(e++,l=o(),l===null)||s[e]!=="!"?null:(e++,{value:{book:n,sheet:i,sheet2:l},end:e})}function I(s){let t=0;const e=s[t]==="$";e&&t++;const n=t;for(;/[A-Za-z]/.test(s[t]);)t++;const o=O(s.slice(n,t)),i=s[t]==="$";i&&t++;const c=Number(s.slice(t))-1;return o>=S||c>=V?null:{r:c,c:o,rAbs:i,cAbs:e}}const Q=new Set(["=","<>","<",">","<=",">="]),E=s=>s===0,D=new Map(Object.entries({PHONETIC:E,ROW:E,COLUMN:E,AREAS:E,COUNTBLANK:E,COUNTIF:E,SUMIF:s=>s===0||s===2,AVERAGEIF:s=>s===0||s===2,COUNTIFS:s=>s%2===0,SUMIFS:s=>s===0||s%2===1,AVERAGEIFS:s=>s===0||s%2===1,MAXIFS:s=>s===0||s%2===1,MINIFS:s=>s===0||s%2===1,SUBTOTAL:s=>s>=1,RANK:s=>s===1,"RANK.EQ":s=>s===1,"RANK.AVG":s=>s===1,AGGREGATE:(s,t)=>t>=5&&s>=4}));for(const s of["DAVERAGE","DCOUNT","DCOUNTA","DGET","DMAX","DMIN","DPRODUCT","DSTDEV","DSTDEVP","DSUM","DVAR","DVARP"])D.set(s,E);const F=s=>s.t==="lit"||s.t==="array"||s.t==="neg"||s.t==="pct"||s.t==="bin"||s.t==="paren"&&F(s.e);let M=null,_=-1;const J=s=>(_!==T.size&&(M=new Set(y.filter(t=>t!=="Barcode"&&t!=="Sparkline").flatMap(t=>H(t))),_=T.size),M.has(s));function j(s,t){const e=J(s)?T.get(s):null,n=t.length,o=n===1&&t[0].t==="omit";if(e&&!o&&(n<e.min||n>e.max))throw new f(`${s} has the wrong number of arguments`);const i=D.get(s);if(i&&t.forEach((c,l)=>{if(i(l,n)&&F(c))throw new f(`${s} needs a reference`)}),s==="IFS"&&n%2===1)throw new f("IFS needs pairs of tests and values");if(s==="SORTBY"&&n>2&&n%2===0)throw new f("SORTBY needs a sort order after each array but the last");if(s==="LAMBDA"&&t.slice(0,-1).some(c=>c.t!=="name"||c.sheet))throw new f("LAMBDA parameters must be names")}class pe{constructor(t,e=0,n=0){this.toks=t,this.i=0,this.baseRow=e,this.baseCol=n}peek(){return this.toks[this.i]}skipWs(){for(;this.toks[this.i]?.t==="ws";)this.i++}isOp(t){this.skipWs();const e=this.toks[this.i];return e!==void 0&&e.t==="op"&&e.v===t}eat(t){if(!this.isOp(t))throw new f(`Expected ${t}`);this.i++}parse(){const t=this.expr();if(this.skipWs(),this.i<this.toks.length)throw new f("Unexpected text after the formula");return t}expr(){return this.compare()}compare(){let t=this.concat();for(;;){this.skipWs();const e=this.peek();if(e?.t==="op"&&Q.has(e.v))this.i++,t={t:"bin",op:e.v,l:t,r:this.concat()};else return t}}concat(){let t=this.add();for(;this.isOp("&");)this.i++,t={t:"bin",op:"&",l:t,r:this.add()};return t}add(){let t=this.mul();for(;;)if(this.isOp("+"))this.i++,t={t:"bin",op:"+",l:t,r:this.mul()};else if(this.isOp("-"))this.i++,t={t:"bin",op:"-",l:t,r:this.mul()};else return t}mul(){let t=this.pow();for(;;)if(this.isOp("*"))this.i++,t={t:"bin",op:"*",l:t,r:this.pow()};else if(this.isOp("/"))this.i++,t={t:"bin",op:"/",l:t,r:this.pow()};else return t}pow(){let t=this.unary();for(;this.isOp("^");)this.i++,t={t:"bin",op:"^",l:t,r:this.unary()};return t}unary(){return this.isOp("-")?(this.i++,{t:"neg",e:this.unary()}):this.isOp("+")?(this.i++,this.unary()):this.isOp("@")?(this.i++,{t:"implicit",e:this.unary()}):this.postfix()}postfix(){let t=this.refExpr();for(;;)if(this.isOp("%"))this.i++,t={t:"pct",e:t};else if(this.peek()?.t==="op"&&this.peek().v==="#")this.i++,t={t:"spillRef",e:t};else return t}refExpr(){let t=this.rangeExpr();for(;;){const e=this.i;if(this.peek()?.t==="ws"){this.skipWs();const n=this.peek();if(n&&this.startsPrimary(n)){t={t:"intersect",l:t,r:this.rangeExpr()};continue}this.i=e}return t}}startsPrimary(t){return t.t==="op"?t.v==="(":t.t==="cell"||t.t==="cols"||t.t==="rows"||t.t==="name"||t.t==="func"||t.t==="sheet"||t.t==="table"}rangeExpr(){let t=this.trimmed(this.primary());for(;this.peek()?.t==="op"&&this.peek().v===":";){const e=this.toks[this.i++],n=this.primary();t=k(t,n),e.trim&&(t=m(t,e.trim)),t=this.trimmed(t)}return t}trimmed(t){const e=this.pendingTrim;return this.pendingTrim=null,e?m(t,e):t}cellNode(t,e=null){return{t:"cell",sheet:e,rAbs:t.rAbs,cAbs:t.cAbs,r:t.rAbs?t.r:t.r-this.baseRow,c:t.cAbs?t.c:t.c-this.baseCol}}rowsNode(t,e=null){return{t:"rows",sheet:e,a0:t.a0,a1:t.a1,r0:t.a0?t.r0:t.r0-this.baseRow,r1:t.a1?t.r1:t.r1-this.baseRow}}colsNode(t,e=null){return{t:"cols",sheet:e,a0:t.a0,a1:t.a1,c0:t.a0?t.c0:t.c0-this.baseCol,c1:t.a1?t.c1:t.c1-this.baseCol}}primary(){this.skipWs();const t=this.peek();if(t===void 0)throw new f("Unexpected end of formula");switch(this.i++,t.t){case"num":return{t:"lit",v:t.v};case"str":return{t:"lit",v:t.v};case"err":{const e=this.peek();if(t.v===w.get("#REF!")&&e&&e.s===t.e&&(e.t==="cell"||e.t==="rows"||e.t==="cols"||e.t==="name")){this.i++;const n=this.peek(),o=this.toks[this.i+1];n?.t==="op"&&n.v===":"&&n.s===e.e&&o&&o.s===n.e&&(o.t==="cell"||o.t==="name")&&(this.i+=2)}return{t:"lit",v:t.v}}case"cell":return this.cellNode(t.v);case"rows":return this.pendingTrim=t.trim??null,this.rowsNode(t.v);case"cols":return this.pendingTrim=t.trim??null,this.colsNode(t.v);case"table":return{t:"table",name:t.v.name,spec:t.v.spec};case"sheet":{const e=this.peek();if(e===void 0)throw new f("Expected a reference");if(this.i++,e.t==="cell"){let n=this.cellNode(e.v,t.v);if(this.peek()?.t==="op"&&this.peek().v===":"&&this.toks[this.i+1]?.t==="cell"){const o=this.toks[this.i++],i=this.toks[this.i++];n=k(n,this.cellNode(i.v,t.v)),o.trim&&(n=m(n,o.trim))}return n}if(e.t==="rows")return this.pendingTrim=e.trim??null,this.rowsNode(e.v,t.v);if(e.t==="cols")return this.pendingTrim=e.trim??null,this.colsNode(e.v,t.v);if(e.t==="name")return{t:"name",name:e.v,sheet:t.v};if(e.t==="err")return{t:"lit",v:e.v};if(e.t==="func")return this.i--,this.primary();throw new f("Expected a reference after the sheet name")}case"name":{const e=t.v.toUpperCase();if(e==="TRUE")return{t:"lit",v:!0};if(e==="FALSE")return{t:"lit",v:!1};const n=/^\$?([A-Za-z]{1,3})\$?([1-9][0-9]{0,6})\.(.+)$/.exec(t.v),o=n?I(`$${n[1]}$${n[2]}`):null;return o?{t:"call",name:"_FV",args:[this.cellNode(o),...n[3].split(".").map(i=>({t:"lit",v:i}))]}:{t:"name",name:t.v}}case"func":return this.call(t.v);case"op":if(t.v==="("){const e=this.expr(),n=[e];for(;this.isOp(",");)this.i++,n.push(this.expr());return this.eat(")"),n.length===1?{t:"paren",e}:{t:"union",items:n}}if(t.v==="{")return this.arrayLiteral();throw new f(`Unexpected ${t.v}`);default:throw new f("Unexpected token")}}call(t){let e=this._callArgs(t);if((t==="_FV"||t==="FIELDVALUE")&&e.t==="call"&&e.args.length===2){const n=e.args[0];n?.t==="call"&&(n.name==="_FV"||n.name==="FIELDVALUE")&&n.args.length>=2&&(e={t:"call",name:"_FV",args:[...n.args,e.args[1]]})}if(t==="CALL"||t==="REGISTER.ID")throw new f(`${t} can't be used in a worksheet formula`);return e.t==="call"&&j(t,e.args),e}_callArgs(t){this.eat("(");const e=[];if(this.isOp(")")){this.i++;const n={t:"call",name:t,args:e};return this.afterCall(n)}for(;;){if(this.skipWs(),this.isOp(",")||this.isOp(")")?e.push({t:"omit"}):e.push(this.expr()),this.isOp(",")){this.i++;continue}this.eat(")");break}return this.afterCall({t:"call",name:t,args:e})}afterCall(t){let e=t;for(;this.peek()?.t==="op"&&this.peek().v==="(";){this.i++;const n=[];if(this.isOp(")"))this.i++;else for(;;){if(this.skipWs(),this.isOp(",")||this.isOp(")")?n.push({t:"omit"}):n.push(this.expr()),this.isOp(",")){this.i++;continue}this.eat(")");break}e={t:"apply",fn:e,args:n}}return e}arrayLiteral(){const t=[[]];for(;;){this.skipWs();let e=!1;for(;this.isOp("-")||this.isOp("+");)this.peek().v==="-"&&(e=!e),this.i++;this.skipWs();const n=this.peek();if(n===void 0)throw new f("Unterminated array");if(this.i++,n.t==="num")t[t.length-1].push(e?-n.v:n.v);else if(n.t==="str"||n.t==="err")t[t.length-1].push(n.v);else if(n.t==="name"&&/^(true|false)$/i.test(n.v))t[t.length-1].push(n.v.toUpperCase()==="TRUE");else throw new f("Arrays can hold only constants");if(this.isOp(","))this.i++;else if(this.isOp(";"))this.i++,t.push([]);else{this.eat("}");break}}return{t:"array",rows:t}}}function k(s,t){return s.t==="cell"&&t.t==="cell"?{t:"range",sheet:s.sheet??t.sheet,a:s,b:t}:{t:"rangeOp",l:s,r:t}}function Ee(s,t,e){let n="";for(let o=0;o<s.length;o++){const i=s[o];switch(i.t){case"cell":{const c=i.v;n+=`R${c.rAbs?c.r:`[${c.r-t}]`}C${c.cAbs?c.c:`[${c.c-e}]`}`;break}case"rows":{const c=i.v;n+=`R${c.a0?c.r0:`[${c.r0-t}]`}:R${c.a1?c.r1:`[${c.r1-t}]`}`;break}case"cols":{const c=i.v;n+=`C${c.a0?c.c0:`[${c.c0-e}]`}:C${c.a1?c.c1:`[${c.c1-e}]`}`;break}case"num":case"func":n+=`${i.t==="num"?"":"~"}${i.v}`;break;case"op":n+=i.v;break;case"ws":n+=" ";break;case"str":n+=JSON.stringify(i.v);break;case"name":n+=`${i.v}`;break;case"err":n+=i.v.code;break;default:n+=`${JSON.stringify(i.v)}`}}return n}const q=new Set(["FILTER","SORT","PY"]),ee=new Set("_TRO_ALL _TRO_LEADING _TRO_TRAILING DETECTLANGUAGE ENCODEURL STOCKHISTORY TRANSLATE ACOT ACOTH AGGREGATE ARABIC ARRAYTOTEXT ANCHORARRAY BASE BETA.DIST BETA.INV BINOM.DIST BINOM.DIST.RANGE BINOM.INV BITAND BITLSHIFT BITOR BITRSHIFT BITXOR BYCOL BYROW CEILING.MATH CEILING.PRECISE CHISQ.DIST CHISQ.DIST.RT CHISQ.INV CHISQ.INV.RT CHISQ.TEST CHOOSECOLS CHOOSEROWS COMBINA CONCAT CONFIDENCE.NORM CONFIDENCE.T COT COTH COVARIANCE.P COVARIANCE.S CSC CSCH DAYS DECIMAL DROP ECMA.CEILING ERF.PRECISE ERFC.PRECISE EXPAND EXPON.DIST F.DIST F.DIST.RT F.INV F.INV.RT F.TEST FIELDVALUE FILTERXML FLOOR.MATH FLOOR.PRECISE FORECAST.ETS FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT FORECAST.LINEAR FORMULATEXT GAMMA GAMMA.DIST GAMMA.INV GAMMALN.PRECISE GAUSS GROUPBY HSTACK HYPGEOM.DIST IFNA IFS IMAGE IMCOSH IMCOT IMCSC IMCSCH IMSEC IMSECH IMSINH IMTAN ISFORMULA ISO.CEILING ISOMITTED ISOWEEKNUM LAMBDA LET LOGNORM.DIST LOGNORM.INV MAKEARRAY MAP MAXIFS MINIFS MODE.MULT MODE.SNGL MUNIT NEGBINOM.DIST NETWORKDAYS.INTL NORM.DIST NORM.INV NORM.S.DIST NORM.S.INV NUMBERVALUE PDURATION PERCENTILE.EXC PERCENTILE.INC PERCENTOF PERCENTRANK.EXC PERCENTRANK.INC PERMUTATIONA PHI PIVOTBY POISSON.DIST QUARTILE.EXC QUARTILE.INC QUERYSTRING RANDARRAY RANK.AVG RANK.EQ REDUCE REGEXEXTRACT REGEXREPLACE REGEXTEST RRI SCAN SEC SECH SEQUENCE SHEET SHEETS SINGLE SKEW.P SORTBY STDEV.P STDEV.S SWITCH T.DIST T.DIST.2T T.DIST.RT T.INV T.INV.2T T.TEST TAKE TEXTAFTER TEXTBEFORE TEXTJOIN TEXTSPLIT TOCOL TOROW TRIMRANGE UNICHAR UNICODE UNIQUE VALUETOTEXT VAR.P VAR.S VSTACK WEBSERVICE WEIBULL.DIST WORKDAY.INTL WRAPCOLS WRAPROWS XLOOKUP XMATCH XOR Z.TEST".split(" ")),te=new Set(["BYCOL","BYROW","GROUPBY","MAKEARRAY","MAP","PIVOTBY","REDUCE","SCAN"]);function Ae(s,t){if(s.indexOf("[")<0)return s;let e;try{e=$(s)}catch{return s}let n="",o=0;for(const i of e){if(i.t!=="table")continue;const c=i.v.name??t()?.name;if(!c)continue;const l=i.v.spec.slice(1,-1).trim();let a=i.v.spec;if(l[0]==="@"){const r=l.slice(1).trim().replace(/^\[|\]$/g,"");a=r?`[[#This Row],[${r}]]`:"[#This Row]"}n+=`${s.slice(o,i.s)}${c}${a}`,o=i.e}return n+s.slice(o)}function se(s){if(s.t==="name"){const t=/^(\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6})\.(.+)$/.exec(s.v);return!t||!I(t[1])||t[2].split(".").some(e=>e==="")?null:{cell:t[1],fields:t[2].split(".")}}if(s.t==="table"&&s.v.name){const t=/^(\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6})\.((?:[A-Za-z_][\w]*\.)*)$/.exec(s.v.name),e=/^\[([^[\]]+)\]$/.exec(s.v.spec);return!t||!e||!I(t[1])?null:{cell:t[1],fields:[...t[2].split(".").filter(Boolean),e[1]]}}return null}const ne=String.raw`(?:(?:'(?:[^']|'')*'|${B})!)?\$?[A-Za-z]{1,3}\$?[0-9]+(?:\.(?:[A-Za-z_]\w*|\[[^\]]*\]))*`,ie=new RegExp(String.raw`_FV\((${ne}),"((?:[^"]|"")*)"\)`,"g");function re(s){let t=s;for(let e=0;e<8&&t.indexOf("_FV(")>=0;e++){const n=t.replace(ie,(o,i,c)=>{const l=c.replace(/""/g,'"');return/^[A-Za-z_]\w*$/.test(l)?`${i}.${l}`:/[[\]]/.test(l)?o:`${i}.[${l}]`});if(n===t)break;t=n}return t}function Te(s){let t=s.indexOf("#This Row")<0?s:s.replace(/\[\[#This Row\],\[([^\]]+)\]\]/g,(e,n)=>/^[\w.]+$/.test(n)?`[@${n}]`:`[@[${n}]]`);return t.indexOf("_FV(")>=0&&(t=re(t)),t.indexOf("_xl")<0?t:(t.indexOf("_TRO_")>=0&&(t=ae(t)),t.replace(/_xlfn\.SINGLE\(([^()]*)\)/g,"@$1").replace(/_xlfn\.ANCHORARRAY\(([^()]*)\)/g,"$1#").replace(/_xlfn\._xlws\.|_xlfn\.|_xlws\.|_xlpm\.|_xludf\.|_xleta\./g,""))}function Re(s,t=null){if(!/[A-Za-z]/.test(s))return s;s=ce(s);let e;try{e=$(s)}catch{return s}const n=le(e);let o="",i=0;const c=[],l=[];for(let a=0;a<e.length;a++){const r=e[a];r.t==="op"&&r.v==="("?c.push(l.pop()===!0):r.t==="op"&&r.v===")"&&c.pop(),r.t==="func"&&l.push(te.has(r.v)||c.includes(!0));const h=se(r);if(h!==null){const u=e[a-1]?.t==="sheet"&&e[a-1].s>=i?e[a-1].s:r.s,A=s.slice(u,r.s)+h.cell;o+=s.slice(i,u)+h.fields.reduce((G,P)=>`_FV(${G},"${P.replace(/"/g,'""')}")`,A),i=r.e}else if(r.t==="name"&&c.includes(!0)&&!n.has(r.v.toUpperCase())&&g(r.v.toUpperCase()))o+=`${s.slice(i,r.s)}_xleta.${r.v.toUpperCase()}`,i=r.e;else if(r.t==="func")o+=s.slice(i,r.s),n.has(r.v)?o+=`_xlpm.${s.slice(r.s,r.e)}`:q.has(r.v)?o+=`_xlfn._xlws.${r.v}`:ee.has(r.v)?o+=`_xlfn.${r.v}`:o+=!g(r.v)&&t?.get(r.v)?.name?t.get(r.v).name:r.v,i=r.e;else if(r.t==="name"&&n.has(r.v.toUpperCase()))o+=`${s.slice(i,r.s)}_xlpm.${r.v}`,i=r.e;else if(r.t==="op"&&r.v==="@"){const u=e[a+1];u&&(u.t==="cell"||u.t==="name")&&(o+=`${s.slice(i,r.s)}_xlfn.SINGLE(${s.slice(u.s,u.e)})`,i=u.e,a++)}else r.t==="cell"&&e[a+1]?.t==="op"&&e[a+1].v==="#"&&(o+=`${s.slice(i,r.s)}_xlfn.ANCHORARRAY(${s.slice(r.s,r.e)})`,i=e[a+1].e,a++)}return o+s.slice(i)}function le(s){const t=new Set;for(let e=0;e<s.length;e++){const n=s[e];if(n.t!=="func"||n.v!=="LET"&&n.v!=="LAMBDA")continue;let o=0,i=0,c=!0;const l=[];for(let r=e+1;r<s.length;r++){const h=s[r];if(h.t!=="ws"){if(h.t==="op"&&(h.v==="("||h.v==="{")){if(o++,o===1){c=!0;continue}}else if(h.t==="op"&&(h.v===")"||h.v==="}")){if(o--,o===0)break}else if(h.t==="op"&&h.v===","&&o===1){i++,c=!0;continue}c&&o>=1&&(l.push({argIndex:i,token:h,next:s[r+1]}),c=!1)}}const a=i+1;for(const r of l){if(r.token.t!=="name"||!(r.next===void 0||r.next.t==="ws"||r.next.t==="op"&&(r.next.v===","||r.next.v===")")))continue;(n.v==="LET"?r.argIndex%2===0&&r.argIndex<a-1:r.argIndex<a-1)&&t.add(r.token.v.toUpperCase())}}return t}const oe=String.raw`(?:'(?:[^']|'')+'|[A-Za-z_À-￿][\w.À-￿]*)!`,U=String.raw`\$?[A-Za-z]{1,3}\$?\d{1,7}|\$?[A-Za-z]{1,3}|\$?\d{1,7}`,b=new RegExp(String.raw`(?<![\w.$!'])((?:${oe})?(?:${U}))(\.?):(\.?)(${U})(?![\w(!])`,"g");function C(s,t){let e="",n=0;const o=/"(?:[^"]|"")*"/g;for(let i=o.exec(s);i!==null;i=o.exec(s))e+=t(s.slice(n,i.index),n)+i[0],n=i.index+i[0].length;return e+t(s.slice(n),n)}const m=(s,t)=>({t:"call",name:`_TRO_${t}`,args:[s]});function ce(s){return s.indexOf(".:")<0&&s.indexOf(":.")<0?s:C(s,t=>t.replace(b,(e,n,o,i,c)=>!o&&!i?e:`_xlfn._TRO_${o&&i?"ALL":o?"LEADING":"TRAILING"}(${n}:${c})`))}function ae(s){return C(s,t=>t.replace(/(?:_xlfn\.)?_TRO_(ALL|LEADING|TRAILING)\(((?:'(?:[^']|'')*'|[^()'])*)\)/g,(e,n,o)=>{const i=o.lastIndexOf(":");if(i<0)return e;const c=n!=="TRAILING"?".":"",l=n!=="LEADING"?".":"";return`${o.slice(0,i)}${c}:${l}${o.slice(i+1)}`}))}export{f as FormulaSyntaxError,pe as Parser,Ae as expandStructured,Ee as templateKey,Te as toDisplayFormula,Re as toFileFormula,$ as tokenize,ce as trimRefsToFile};
1
+ import{colIndex as S,MAX_COLS as d,MAX_ROWS as y,PLAIN_SHEET as B}from"../core/address.js";import{ERR_BY_CODE as g}from"./values.js";import{CATEGORIES as H,categoryFunctions as W,FUNCS as R}from"./functions/registry.js";const L=s=>R.has(s);class h extends Error{}function Te(s){if(s.length>8192)return"A formula cannot contain more than 8,192 characters.";if(s.length<130||!s.includes('"')&&!s.includes("("))return null;let e;try{e=T(s)}catch(r){if(r instanceof h)return null;throw r}const t=[];let n=0;for(let r=0;r<e.length;r++){const i=e[r];if(i.t==="str"&&i.v.length>255)return"Text values in formulas are limited to 255 characters.";if(i.t==="op")if(i.v==="("){const c=e[r-1]?.t==="func";if(t.push(c),c&&++n>64)return"A formula cannot nest more than 64 levels of functions."}else i.v===")"&&t.pop()&&n--}return null}const X=/\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6}/y,Y=/(\$?)([A-Za-z]{1,3}):(\$?)([A-Za-z]{1,3})/y,z=/(\$?)([1-9][0-9]{0,6}):(\$?)([1-9][0-9]{0,6})/y,K=/(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y,Z=/[A-Za-z_\\\u0080-￿][A-Za-z0-9_.\\?\u0080-￿]*/y,x=/#(?:NULL!|DIV\/0!|VALUE!|REF!|NAME\?|NUM!|N\/A|GETTING_DATA|SPILL!|CALC!|BUSY!|CONNECT!|BLOCKED!|FIELD!|UNKNOWN!)/iy,$=/^(?:_xlfn\._xlws\.|_xlfn\.|_xlws\.|_xlpm\.|_xludf\.|_xleta\.)/i,N=s=>s!==void 0&&/[A-Za-z0-9_.\u0080-￿]/.test(s);function p(s,e,t){return s.lastIndex=t,s.exec(e)}function T(s){if(s.indexOf(".:")<0&&s.indexOf(":.")<0)return C(s);const e=new Set,t=new Map;if(m(s,(c,l)=>{for(const a of c.matchAll(G)){const[,o,f,u]=a;if(!f&&!u)continue;const A=l+a.index+o.length+f.length;f&&e.add(A-1),u&&e.add(A+1),t.set(A,f&&u?"ALL":f?"LEADING":"TRAILING")}return c}),e.size===0)return C(s);let n="";const r=[];for(let c=0;c<s.length;c++)e.has(c)||(r.push(c),n+=s[c]);r.push(s.length);const i=C(n);for(const c of i){const l=r[c.s],a=c.e>0?r[c.e-1]+1:0;for(const[o,f]of t)o>=l&&o<a&&(c.trim=f);c.s=l,c.e=a}return i}function C(s){const e=[];let t=0;const n=s.length,r=(i,c,l,a)=>e.push({t:i,v:c,s:l,e:a});for(;t<n;){const i=s[t];if(i===" "||i===`
2
+ `||i==="\r"||i===" "){const l=t;for(;t<n&&(s[t]===" "||s[t]===`
3
+ `||s[t]==="\r"||s[t]===" ");)t++;r("ws",null,l,t);continue}if(i==='"'){const l=t;let a="";for(t++;;){if(t>=n)throw new h("Unterminated string");if(s[t]==='"'){if(s[t+1]==='"'){a+='"',t+=2;continue}t++;break}a+=s[t++]}r("str",a,l,t);continue}if(i==="'"||i==="["){const l=v(s,t);if(l){r("sheet",l.value,t,l.end),t=l.end;continue}if(i==="["){const a=I(s,t);r("table",{name:null,spec:s.slice(t,a)},t,a),t=a;continue}throw new h("Unexpected quote")}if(i==="#"){const l=p(x,s,t);l?(r("err",g.get(l[0].toUpperCase()),t,t+l[0].length),t+=l[0].length):(r("op","#",t,t+1),t++);continue}if(i>="0"&&i<="9"||i==="."||i==="$"||/[A-Za-z_\\\u0080-￿]/.test(i)){let l=p(z,s,t);if(l&&!N(s[t+l[0].length])){r("rows",{a0:l[1]==="$",r0:Number(l[2])-1,a1:l[3]==="$",r1:Number(l[4])-1},t,t+l[0].length),t+=l[0].length;continue}if(l=p(Y,s,t),l&&!N(s[t+l[0].length])&&s[t+l[0].length]!=="("&&s[t+l[0].length]!=="!"){const a=S(l[2]),o=S(l[4]);if(a<d&&o<d){r("cols",{a0:l[1]==="$",c0:a,a1:l[3]==="$",c1:o},t,t+l[0].length),t+=l[0].length;continue}}if(l=p(X,s,t),l){const a=s[t+l[0].length];if(!N(a)&&a!=="("&&a!=="!"&&a!=="["){const o=O(l[0]);if(o){r("cell",o,t,t+l[0].length),t+=l[0].length;continue}}else if(a==="."&&i==="$"){const o=p(/[A-Za-z0-9_.\\?\u0080-￿]*/y,s,t+l[0].length),f=t+l[0].length+o[0].length;r(s[f]==="["?"table":"name",s[f]==="["?{name:s.slice(t,f),spec:s.slice(f,I(s,f))}:s.slice(t,f),t,s[f]==="["?I(s,f):f),t=e[e.length-1].e;continue}}if(i>="0"&&i<="9"||i==="."){if(l=p(K,s,t),!l)throw new h("Bad number");r("num",Number(l[0]),t,t+l[0].length),t+=l[0].length;continue}if(l=p(Z,s,t),l){const a=t+l[0].length,o=s[a];if(o==="!"||o===":"&&Q(s,a)){const f=v(s,t);if(f){r("sheet",f.value,t,f.end),t=f.end;continue}}if(o==="(")r("func",l[0].replace($,"").toUpperCase(),t,a);else if(o==="["){const f=I(s,a);r("table",{name:l[0],spec:s.slice(a,f)},t,f),t=f;continue}else r("name",l[0].replace($,""),t,a);t=a;continue}}const c=s.slice(t,t+2);if(c==="<="||c===">="||c==="<>"){r("op",c,t,t+2),t+=2;continue}if("+-*/^&=<>%(),;:{}@".includes(i)){r("op",i,t,t+1),t++;continue}throw new h(`Unexpected character ${i}`)}return e}function Q(s,e){return/^:'?[^'!:]+'?!/.exec(s.slice(e,e+64))!==null}function I(s,e){let t=0;for(let n=e;n<s.length;n++){if(s[n]==="'"&&s[n+1]!==void 0){n++;continue}if(s[n]==="[")t++;else if(s[n]==="]"&&(t--,t===0))return n+1}throw new h("Unterminated [")}function v(s,e){let t=e,n=null;const r=()=>{if(s[t]==="'"){let o="";for(t++;;){if(t>=s.length)return null;if(s[t]==="'"){if(s[t+1]==="'"){o+="'",t+=2;continue}return t++,o}o+=s[t++]}}const a=t;for(;t<s.length&&!'!:,()+-*/^&=<>%{}; "'.includes(s[t]);)t++;return t>a?s.slice(a,t):null};if(s[t]==="["){const a=s.indexOf("]",t);if(a<0)return null;n=s.slice(t+1,a),t=a+1}let i=r();if(i===null)return null;const c=/\[([^\]]+)\](.*)$/.exec(i);c&&(n=c[1],i=c[2]);let l=null;return s[t]===":"&&(t++,l=r(),l===null)||s[t]!=="!"?null:(t++,{value:{book:n,sheet:i,sheet2:l},end:t})}function O(s){let e=0;const t=s[e]==="$";t&&e++;const n=e;for(;/[A-Za-z]/.test(s[e]);)e++;const r=S(s.slice(n,e)),i=s[e]==="$";i&&e++;const c=Number(s.slice(e))-1;return r>=d||c>=y?null:{r:c,c:r,rAbs:i,cAbs:t}}const J=new Set(["=","<>","<",">","<=",">="]),E=s=>s===0,F=new Map(Object.entries({PHONETIC:E,ROW:E,COLUMN:E,AREAS:E,COUNTBLANK:E,COUNTIF:E,SUMIF:s=>s===0||s===2,AVERAGEIF:s=>s===0||s===2,COUNTIFS:s=>s%2===0,SUMIFS:s=>s===0||s%2===1,AVERAGEIFS:s=>s===0||s%2===1,MAXIFS:s=>s===0||s%2===1,MINIFS:s=>s===0||s%2===1,SUBTOTAL:s=>s>=1,RANK:s=>s===1,"RANK.EQ":s=>s===1,"RANK.AVG":s=>s===1,AGGREGATE:(s,e)=>e>=5&&s>=4}));for(const s of["DAVERAGE","DCOUNT","DCOUNTA","DGET","DMAX","DMIN","DPRODUCT","DSTDEV","DSTDEVP","DSUM","DVAR","DVARP"])F.set(s,E);const D=s=>s.t==="lit"||s.t==="array"||s.t==="neg"||s.t==="pct"||s.t==="bin"||s.t==="paren"&&D(s.e);let M=null,_=-1;const j=s=>(_!==R.size&&(M=new Set(H.filter(e=>e!=="Barcode"&&e!=="Sparkline").flatMap(e=>W(e))),_=R.size),M.has(s));function q(s,e){const t=j(s)?R.get(s):null,n=e.length,r=n===1&&e[0].t==="omit";if(t&&!r&&(n<t.min||n>t.max))throw new h(`${s} has the wrong number of arguments`);const i=F.get(s);if(i&&e.forEach((c,l)=>{if(i(l,n)&&D(c))throw new h(`${s} needs a reference`)}),s==="IFS"&&n%2===1)throw new h("IFS needs pairs of tests and values");if(s==="SORTBY"&&n>2&&n%2===0)throw new h("SORTBY needs a sort order after each array but the last");if(s==="LAMBDA"&&e.slice(0,-1).some(c=>c.t!=="name"||c.sheet))throw new h("LAMBDA parameters must be names")}class U{constructor(e,t=0,n=0){this.toks=e,this.i=0,this.baseRow=t,this.baseCol=n}peek(){return this.toks[this.i]}skipWs(){for(;this.toks[this.i]?.t==="ws";)this.i++}isOp(e){this.skipWs();const t=this.toks[this.i];return t!==void 0&&t.t==="op"&&t.v===e}eat(e){if(!this.isOp(e))throw new h(`Expected ${e}`);this.i++}parse(){const e=this.expr();if(this.skipWs(),this.i<this.toks.length)throw new h("Unexpected text after the formula");return e}expr(){return this.compare()}compare(){let e=this.concat();for(;;){this.skipWs();const t=this.peek();if(t?.t==="op"&&J.has(t.v))this.i++,e={t:"bin",op:t.v,l:e,r:this.concat()};else return e}}concat(){let e=this.add();for(;this.isOp("&");)this.i++,e={t:"bin",op:"&",l:e,r:this.add()};return e}add(){let e=this.mul();for(;;)if(this.isOp("+"))this.i++,e={t:"bin",op:"+",l:e,r:this.mul()};else if(this.isOp("-"))this.i++,e={t:"bin",op:"-",l:e,r:this.mul()};else return e}mul(){let e=this.pow();for(;;)if(this.isOp("*"))this.i++,e={t:"bin",op:"*",l:e,r:this.pow()};else if(this.isOp("/"))this.i++,e={t:"bin",op:"/",l:e,r:this.pow()};else return e}pow(){let e=this.unary();for(;this.isOp("^");)this.i++,e={t:"bin",op:"^",l:e,r:this.unary()};return e}unary(){return this.isOp("-")?(this.i++,{t:"neg",e:this.unary()}):this.isOp("+")?(this.i++,this.unary()):this.isOp("@")?(this.i++,{t:"implicit",e:this.unary()}):this.postfix()}postfix(){let e=this.refExpr();for(;;)if(this.isOp("%"))this.i++,e={t:"pct",e};else if(this.peek()?.t==="op"&&this.peek().v==="#")this.i++,e={t:"spillRef",e};else return e}refExpr(){let e=this.rangeExpr();for(;;){const t=this.i;if(this.peek()?.t==="ws"){this.skipWs();const n=this.peek();if(n&&this.startsPrimary(n)){e={t:"intersect",l:e,r:this.rangeExpr()};continue}this.i=t}return e}}startsPrimary(e){return e.t==="op"?e.v==="(":e.t==="cell"||e.t==="cols"||e.t==="rows"||e.t==="name"||e.t==="func"||e.t==="sheet"||e.t==="table"}rangeExpr(){let e=this.trimmed(this.primary());for(;this.peek()?.t==="op"&&this.peek().v===":";){const t=this.toks[this.i++],n=this.primary();e=k(e,n),t.trim&&(e=w(e,t.trim)),e=this.trimmed(e)}return e}trimmed(e){const t=this.pendingTrim;return this.pendingTrim=null,t?w(e,t):e}cellNode(e,t=null){return{t:"cell",sheet:t,rAbs:e.rAbs,cAbs:e.cAbs,r:e.rAbs?e.r:e.r-this.baseRow,c:e.cAbs?e.c:e.c-this.baseCol}}rowsNode(e,t=null){return{t:"rows",sheet:t,a0:e.a0,a1:e.a1,r0:e.a0?e.r0:e.r0-this.baseRow,r1:e.a1?e.r1:e.r1-this.baseRow}}colsNode(e,t=null){return{t:"cols",sheet:t,a0:e.a0,a1:e.a1,c0:e.a0?e.c0:e.c0-this.baseCol,c1:e.a1?e.c1:e.c1-this.baseCol}}primary(){this.skipWs();const e=this.peek();if(e===void 0)throw new h("Unexpected end of formula");switch(this.i++,e.t){case"num":return{t:"lit",v:e.v};case"str":return{t:"lit",v:e.v};case"err":{const t=this.peek();if(e.v===g.get("#REF!")&&t&&t.s===e.e&&(t.t==="cell"||t.t==="rows"||t.t==="cols"||t.t==="name")){this.i++;const n=this.peek(),r=this.toks[this.i+1];n?.t==="op"&&n.v===":"&&n.s===t.e&&r&&r.s===n.e&&(r.t==="cell"||r.t==="name")&&(this.i+=2)}return{t:"lit",v:e.v}}case"cell":return this.cellNode(e.v);case"rows":return this.pendingTrim=e.trim??null,this.rowsNode(e.v);case"cols":return this.pendingTrim=e.trim??null,this.colsNode(e.v);case"table":return{t:"table",name:e.v.name,spec:e.v.spec};case"sheet":{const t=this.peek();if(t===void 0)throw new h("Expected a reference");if(this.i++,t.t==="cell"){let n=this.cellNode(t.v,e.v);if(this.peek()?.t==="op"&&this.peek().v===":"&&this.toks[this.i+1]?.t==="cell"){const r=this.toks[this.i++],i=this.toks[this.i++];n=k(n,this.cellNode(i.v,e.v)),r.trim&&(n=w(n,r.trim))}return n}if(t.t==="rows")return this.pendingTrim=t.trim??null,this.rowsNode(t.v,e.v);if(t.t==="cols")return this.pendingTrim=t.trim??null,this.colsNode(t.v,e.v);if(t.t==="name")return{t:"name",name:t.v,sheet:e.v};if(t.t==="err")return{t:"lit",v:t.v};if(t.t==="func")return this.i--,this.primary();throw new h("Expected a reference after the sheet name")}case"name":{const t=e.v.toUpperCase();if(t==="TRUE")return{t:"lit",v:!0};if(t==="FALSE")return{t:"lit",v:!1};const n=/^\$?([A-Za-z]{1,3})\$?([1-9][0-9]{0,6})\.(.+)$/.exec(e.v),r=n?O(`$${n[1]}$${n[2]}`):null;return r?{t:"call",name:"_FV",args:[this.cellNode(r),...n[3].split(".").map(i=>({t:"lit",v:i}))]}:{t:"name",name:e.v}}case"func":return this.call(e.v);case"op":if(e.v==="("){const t=this.expr(),n=[t];for(;this.isOp(",");)this.i++,n.push(this.expr());return this.eat(")"),n.length===1?{t:"paren",e:t}:{t:"union",items:n}}if(e.v==="{")return this.arrayLiteral();throw new h(`Unexpected ${e.v}`);default:throw new h("Unexpected token")}}call(e){let t=this._callArgs(e);if((e==="_FV"||e==="FIELDVALUE")&&t.t==="call"&&t.args.length===2){const n=t.args[0];n?.t==="call"&&(n.name==="_FV"||n.name==="FIELDVALUE")&&n.args.length>=2&&(t={t:"call",name:"_FV",args:[...n.args,t.args[1]]})}if(e==="CALL"||e==="REGISTER.ID")throw new h(`${e} can't be used in a worksheet formula`);return t.t==="call"&&q(e,t.args),t}_callArgs(e){this.eat("(");const t=[];if(this.isOp(")")){this.i++;const n={t:"call",name:e,args:t};return this.afterCall(n)}for(;;){if(this.skipWs(),this.isOp(",")||this.isOp(")")?t.push({t:"omit"}):t.push(this.expr()),this.isOp(",")){this.i++;continue}this.eat(")");break}return this.afterCall({t:"call",name:e,args:t})}afterCall(e){let t=e;for(;this.peek()?.t==="op"&&this.peek().v==="(";){this.i++;const n=[];if(this.isOp(")"))this.i++;else for(;;){if(this.skipWs(),this.isOp(",")||this.isOp(")")?n.push({t:"omit"}):n.push(this.expr()),this.isOp(",")){this.i++;continue}this.eat(")");break}t={t:"apply",fn:t,args:n}}return t}arrayLiteral(){const e=[[]];for(;;){this.skipWs();let t=!1;for(;this.isOp("-")||this.isOp("+");)this.peek().v==="-"&&(t=!t),this.i++;this.skipWs();const n=this.peek();if(n===void 0)throw new h("Unterminated array");if(this.i++,n.t==="num")e[e.length-1].push(t?-n.v:n.v);else if(n.t==="str"||n.t==="err")e[e.length-1].push(n.v);else if(n.t==="name"&&/^(true|false)$/i.test(n.v))e[e.length-1].push(n.v.toUpperCase()==="TRUE");else throw new h("Arrays can hold only constants");if(this.isOp(","))this.i++;else if(this.isOp(";"))this.i++,e.push([]);else{this.eat("}");break}}return{t:"array",rows:e}}}function k(s,e){return s.t==="cell"&&e.t==="cell"?{t:"range",sheet:s.sheet??e.sheet,a:s,b:e}:{t:"rangeOp",l:s,r:e}}function Re(s,e,t){let n="";for(let r=0;r<s.length;r++){const i=s[r];switch(i.t){case"cell":{const c=i.v;n+=`R${c.rAbs?c.r:`[${c.r-e}]`}C${c.cAbs?c.c:`[${c.c-t}]`}`;break}case"rows":{const c=i.v;n+=`R${c.a0?c.r0:`[${c.r0-e}]`}:R${c.a1?c.r1:`[${c.r1-e}]`}`;break}case"cols":{const c=i.v;n+=`C${c.a0?c.c0:`[${c.c0-t}]`}:C${c.a1?c.c1:`[${c.c1-t}]`}`;break}case"num":case"func":n+=`${i.t==="num"?"":"~"}${i.v}`;break;case"op":n+=i.v;break;case"ws":n+=" ";break;case"str":n+=JSON.stringify(i.v);break;case"name":n+=`${i.v}`;break;case"err":n+=i.v.code;break;default:n+=`${JSON.stringify(i.v)}`}}return n}const ee=new Set(["FILTER","SORT","PY"]),te=new Set("_TRO_ALL _TRO_LEADING _TRO_TRAILING DETECTLANGUAGE ENCODEURL STOCKHISTORY TRANSLATE ACOT ACOTH AGGREGATE ARABIC ARRAYTOTEXT ANCHORARRAY BASE BETA.DIST BETA.INV BINOM.DIST BINOM.DIST.RANGE BINOM.INV BITAND BITLSHIFT BITOR BITRSHIFT BITXOR BYCOL BYROW CEILING.MATH CEILING.PRECISE CHISQ.DIST CHISQ.DIST.RT CHISQ.INV CHISQ.INV.RT CHISQ.TEST CHOOSECOLS CHOOSEROWS COMBINA CONCAT CONFIDENCE.NORM CONFIDENCE.T COT COTH COVARIANCE.P COVARIANCE.S CSC CSCH DAYS DECIMAL DROP ECMA.CEILING ERF.PRECISE ERFC.PRECISE EXPAND EXPON.DIST F.DIST F.DIST.RT F.INV F.INV.RT F.TEST FIELDVALUE FILTERXML FLOOR.MATH FLOOR.PRECISE FORECAST.ETS FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT FORECAST.LINEAR FORMULATEXT GAMMA GAMMA.DIST GAMMA.INV GAMMALN.PRECISE GAUSS GROUPBY HSTACK HYPGEOM.DIST IFNA IFS IMAGE IMCOSH IMCOT IMCSC IMCSCH IMSEC IMSECH IMSINH IMTAN ISFORMULA ISO.CEILING ISOMITTED ISOWEEKNUM LAMBDA LET LOGNORM.DIST LOGNORM.INV MAKEARRAY MAP MAXIFS MINIFS MODE.MULT MODE.SNGL MUNIT NEGBINOM.DIST NETWORKDAYS.INTL NORM.DIST NORM.INV NORM.S.DIST NORM.S.INV NUMBERVALUE PDURATION PERCENTILE.EXC PERCENTILE.INC PERCENTOF PERCENTRANK.EXC PERCENTRANK.INC PERMUTATIONA PHI PIVOTBY POISSON.DIST QUARTILE.EXC QUARTILE.INC QUERYSTRING RANDARRAY RANK.AVG RANK.EQ REDUCE REGEXEXTRACT REGEXREPLACE REGEXTEST RRI SCAN SEC SECH SEQUENCE SHEET SHEETS SINGLE SKEW.P SORTBY STDEV.P STDEV.S SWITCH T.DIST T.DIST.2T T.DIST.RT T.INV T.INV.2T T.TEST TAKE TEXTAFTER TEXTBEFORE TEXTJOIN TEXTSPLIT TOCOL TOROW TRIMRANGE UNICHAR UNICODE UNIQUE VALUETOTEXT VAR.P VAR.S VSTACK WEBSERVICE WEIBULL.DIST WORKDAY.INTL WRAPCOLS WRAPROWS XLOOKUP XMATCH XOR Z.TEST".split(" ")),se=new Set(["BYCOL","BYROW","GROUPBY","MAKEARRAY","MAP","PIVOTBY","REDUCE","SCAN"]);function Ie(s,e){if(s.indexOf("[")<0)return s;let t;try{t=T(s)}catch{return s}let n="",r=0;for(const i of t){if(i.t!=="table")continue;const c=i.v.name??e()?.name;if(!c)continue;const l=i.v.spec.slice(1,-1).trim();let a=i.v.spec;if(l[0]==="@"){const o=l.slice(1).trim().replace(/^\[|\]$/g,"");a=o?`[[#This Row],[${o}]]`:"[#This Row]"}n+=`${s.slice(r,i.s)}${c}${a}`,r=i.e}return n+s.slice(r)}function ne(s){if(s.t==="name"){const e=/^(\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6})\.(.+)$/.exec(s.v);return!e||!O(e[1])||e[2].split(".").some(t=>t==="")?null:{cell:e[1],fields:e[2].split(".")}}if(s.t==="table"&&s.v.name){const e=/^(\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6})\.((?:[A-Za-z_][\w]*\.)*)$/.exec(s.v.name),t=/^\[([^[\]]+)\]$/.exec(s.v.spec);return!e||!t||!O(e[1])?null:{cell:e[1],fields:[...e[2].split(".").filter(Boolean),t[1]]}}return null}const ie=String.raw`(?:(?:'(?:[^']|'')*'|${B})!)?\$?[A-Za-z]{1,3}\$?[0-9]+(?:\.(?:[A-Za-z_]\w*|\[[^\]]*\]))*`,re=new RegExp(String.raw`_FV\((${ie}),"((?:[^"]|"")*)"\)`,"g");function le(s){let e=s;for(let t=0;t<8&&e.indexOf("_FV(")>=0;t++){const n=e.replace(re,(r,i,c)=>{const l=c.replace(/""/g,'"');return/^[A-Za-z_]\w*$/.test(l)?`${i}.${l}`:/[[\]]/.test(l)?r:`${i}.[${l}]`});if(n===e)break;e=n}return e}function oe(s){let e;try{e=T(s)}catch(r){if(r instanceof h)return s;throw r}const t=[],n=[];for(let r=0;r<e.length;r++){const i=e[r];if(i.t==="op"){if(i.v==="(")t.push(r);else if(i.v===")"){const c=t.pop(),l=e[c-1];if(l?.t!=="func"||s.slice(l.s,l.e).toUpperCase()!=="_XLFN.SINGLE")continue;const a=new U(e);a.i=c+1;try{a.unary()}catch(f){if(f instanceof h)continue;throw f}const o=a.i!==r;n.push([l.s,e[c].e,o?"@(":"@"],[i.s,i.e,o?")":""])}}}for(const[r,i,c]of n.sort((l,a)=>a[0]-l[0]))s=s.slice(0,r)+c+s.slice(i);return s}function Oe(s){let e=s.indexOf("#This Row")<0?s:s.replace(/\[\[#This Row\],\[([^\]]+)\]\]/g,(t,n)=>/^[\w.]+$/.test(n)?`[@${n}]`:`[@[${n}]]`);return e.indexOf("_FV(")>=0&&(e=le(e)),e.indexOf("_xl")<0?e:(e.indexOf("_TRO_")>=0&&(e=ue(e)),e.includes("_xlfn.SINGLE(")&&(e=oe(e)),e.replace(/_xlfn\.ANCHORARRAY\(([^()]*)\)/g,"$1#").replace(/_xlfn\._xlws\.|_xlfn\.|_xlws\.|_xlpm\.|_xludf\.|_xleta\./g,""))}function ce(s,e){const t=[],n=new U(e);for(let i=0;i<e.length;i++){const c=e[i];if(c.t!=="op"||c.v!=="@")continue;n.i=i+1,n.unary();let l=n.i-1;for(;e[l].t==="ws";)l--;t.push([c.s,c.e,"_xlfn.SINGLE("],[e[l].e,e[l].e,")"])}let r=s;for(const[i,c,l]of t.sort((a,o)=>o[0]-a[0]))r=r.slice(0,i)+l+r.slice(c);return r}function Se(s,e=null){if(!/[A-Za-z@]/.test(s))return s;s=he(s);let t;try{t=T(s),t.some(a=>a.t==="op"&&a.v==="@")&&(s=ce(s,t),t=T(s))}catch(a){if(a instanceof h)return s;throw a}const n=ae(t);let r="",i=0;const c=[],l=[];for(let a=0;a<t.length;a++){const o=t[a];o.t==="op"&&o.v==="("?c.push(l.pop()===!0):o.t==="op"&&o.v===")"&&c.pop(),o.t==="func"&&l.push(se.has(o.v)||c.includes(!0));const f=ne(o);if(f!==null){const u=t[a-1]?.t==="sheet"&&t[a-1].s>=i?t[a-1].s:o.s,A=s.slice(u,o.s)+f.cell.toUpperCase();r+=s.slice(i,u)+f.fields.reduce((P,V)=>`_FV(${P},"${V.replace(/"/g,'""')}")`,A),i=o.e}else if(o.t==="name"&&c.includes(!0)&&!n.has(o.v.toUpperCase())&&L(o.v.toUpperCase()))r+=`${s.slice(i,o.s)}_xleta.${o.v.toUpperCase()}`,i=o.e;else if(o.t==="func")r+=s.slice(i,o.s),n.has(o.v)?r+=`_xlpm.${s.slice(o.s,o.e)}`:ee.has(o.v)?r+=`_xlfn._xlws.${o.v}`:te.has(o.v)?r+=`_xlfn.${o.v}`:r+=!L(o.v)&&e?.get(o.v)?.name?e.get(o.v).name:o.v,i=o.e;else if(o.t==="name"&&n.has(o.v.toUpperCase()))r+=`${s.slice(i,o.s)}_xlpm.${o.v}`,i=o.e;else if(o.t==="cell"&&t[a+1]?.t==="op"&&t[a+1].v==="#"){const u=t[a-1]?.t==="sheet"?t[a-1].s:o.s;r+=`${s.slice(i,u)}_xlfn.ANCHORARRAY(${s.slice(u,o.s)}${s.slice(o.s,o.e).toUpperCase()})`,i=t[a+1].e,a++}else(o.t==="cell"||o.t==="cols")&&(r+=s.slice(i,o.s)+s.slice(o.s,o.e).toUpperCase(),i=o.e)}return r+s.slice(i)}function ae(s){const e=new Set;for(let t=0;t<s.length;t++){const n=s[t];if(n.t!=="func"||n.v!=="LET"&&n.v!=="LAMBDA")continue;let r=0,i=0,c=!0;const l=[];for(let o=t+1;o<s.length;o++){const f=s[o];if(f.t!=="ws"){if(f.t==="op"&&(f.v==="("||f.v==="{")){if(r++,r===1){c=!0;continue}}else if(f.t==="op"&&(f.v===")"||f.v==="}")){if(r--,r===0)break}else if(f.t==="op"&&f.v===","&&r===1){i++,c=!0;continue}c&&r>=1&&(l.push({argIndex:i,token:f,next:s[o+1]}),c=!1)}}const a=i+1;for(const o of l){if(o.token.t!=="name"||!(o.next===void 0||o.next.t==="ws"||o.next.t==="op"&&(o.next.v===","||o.next.v===")")))continue;(n.v==="LET"?o.argIndex%2===0&&o.argIndex<a-1:o.argIndex<a-1)&&e.add(o.token.v.toUpperCase())}}return e}const fe=String.raw`(?:'(?:[^']|'')+'|[A-Za-z_À-￿][\w.À-￿]*)!`,b=String.raw`\$?[A-Za-z]{1,3}\$?\d{1,7}|\$?[A-Za-z]{1,3}|\$?\d{1,7}`,G=new RegExp(String.raw`(?<![\w.$!'])((?:${fe})?(?:${b}))(\.?):(\.?)(${b})(?![\w(!])`,"g");function m(s,e){let t="",n=0;const r=/"(?:[^"]|"")*"/g;for(let i=r.exec(s);i!==null;i=r.exec(s))t+=e(s.slice(n,i.index),n)+i[0],n=i.index+i[0].length;return t+e(s.slice(n),n)}const w=(s,e)=>({t:"call",name:`_TRO_${e}`,args:[s]});function he(s){return s.indexOf(".:")<0&&s.indexOf(":.")<0?s:m(s,e=>e.replace(G,(t,n,r,i,c)=>!r&&!i?t:`_xlfn._TRO_${r&&i?"ALL":r?"LEADING":"TRAILING"}(${n}:${c})`))}function ue(s){return m(s,e=>e.replace(/(?:_xlfn\.)?_TRO_(ALL|LEADING|TRAILING)\(((?:'(?:[^']|'')*'|[^()'])*)\)/g,(t,n,r)=>{const i=r.lastIndexOf(":");if(i<0)return t;const c=n!=="TRAILING"?".":"",l=n!=="LEADING"?".":"";return`${r.slice(0,i)}${c}:${l}${r.slice(i+1)}`}))}export{h as FormulaSyntaxError,U as Parser,Ie as expandStructured,Te as formulaEntryLimit,Re as templateKey,Oe as toDisplayFormula,Se as toFileFormula,T as tokenize,he as trimRefsToFile};
package/calc/values.js CHANGED
@@ -1 +1 @@
1
- import{NUM as g}from"../core/sheet.js";import{parseInput as N}from"../core/input.js";class s{constructor(e,n){this.code=e,this.index=n}toString(){return this.code}}const c={NULL:new s("#NULL!",0),DIV0:new s("#DIV/0!",1),VALUE:new s("#VALUE!",2),REF:new s("#REF!",3),NAME:new s("#NAME?",4),NUM:new s("#NUM!",5),NA:new s("#N/A",6),GETTING:new s("#GETTING_DATA",7),SPILL:new s("#SPILL!",8),CALC:new s("#CALC!",9),BUSY:new s("#BUSY!",10),CONNECT:new s("#CONNECT!",11),BLOCKED:new s("#BLOCKED!",12),FIELD:new s("#FIELD!",13),UNKNOWN:new s("#UNKNOWN!",14)},L=Object.values(c),R=new Map(L.map(t=>[t.code,t]));class S{constructor(e,n,r,i,o){this.sheet=e,this.r0=n,this.c0=r,this.r1=i,this.c1=o}get rows(){return this.r1-this.r0+1}get cols(){return this.c1-this.c0+1}get isCell(){return this.r0===this.r1&&this.c0===this.c1}}class ${constructor(e){this.refs=e}}class u{constructor(e,n,r){this.rows=e,this.cols=n,this.data=r}get(e,n){return this.data[e*this.cols+n]}static of2D(e){const n=e.reduce((i,o)=>Math.max(i,o.length),0),r=[];for(const i of e)for(let o=0;o<n;o++)r.push(o<i.length?i[o]:c.NA);return new u(e.length,n,r)}static column(e){return new u(e.length,1,e)}static row(e){return new u(1,e.length,e)}static filled(e,n,r){return new u(e,n,new Array(e*n).fill(r))}}class b{constructor(e,n,r,i){this.params=e,this.body=n,this.frame=r,this.optional=i}}class l{constructor(e,n){this.rich=e,this.index=n}get text(){return this.rich.view(this.index)?.text??""}equals(e){return e instanceof l&&e.rich===this.rich&&(e.index===this.index||this.rich.sameValue(this.index,e.index))}toString(){return this.text}toJSON(){return this.text}}const a=Symbol("omitted");function M(t){if(Number.isInteger(t)&&Math.abs(t)<1e15)return String(t);if(!Number.isFinite(t))return c.NUM.code;const e=t<0,n=Math.abs(t).toExponential(14),r=n.indexOf("e"),i=(n[0]+n.slice(2,r)).replace(/0+$/,"")||"0",o=Number(n.slice(r+1));let f;if(o>=0){const h=i.length>o+1?i.slice(0,o+1):i.padEnd(o+1,"0"),p=i.length>o+1?i.slice(o+1):"";f=p?`${h}.${p}`:h}else f=`0.${"0".repeat(-o-1)}${i}`;if(f.length>20){const h=Math.abs(o);f=`${i.length>1?`${i[0]}.${i.slice(1)}`:i}E${o<0?"-":"+"}${h<10?"0":""}${h}`}return e?`-${f}`:f}function U(t){const e=t.trim();if(e==="")return null;const n=N(e);return n.kind===g?n.value:null}function D(t,e){if(t<0&&!Number.isInteger(e)){const n=1/e,r=Math.round(n);if(Math.abs(n-r)<1e-9&&Math.abs(r)%2===1)return-((-t)**e)}return t**e}const V=Object.freeze({rejected:!0});function d(t){if(typeof t=="number")return t;if(t==null||t===a)return 0;if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){const e=U(t);if(e===null)throw c.VALUE;return e}if(t instanceof s)throw t;if(t instanceof u)return d(t.data[0]);throw c.VALUE}function y(t){if(typeof t=="string")return t;if(typeof t=="number")return M(t);if(t==null||t===a)return"";if(typeof t=="boolean")return t?"TRUE":"FALSE";if(t instanceof s)throw t;if(t instanceof u)return y(t.data[0]);throw c.VALUE}function C(t){if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(t==null||t===a)return!1;if(typeof t=="string"){const e=t.trim().toUpperCase();if(e==="TRUE")return!0;if(e==="FALSE")return!1;throw c.VALUE}if(t instanceof s)throw t;if(t instanceof u)return C(t.data[0]);throw c.VALUE}const F=t=>Math.trunc(d(t)),B=t=>t===a||t===void 0,Y=(t,e)=>t===a||t===void 0?e:t;function k(t){if(!Number.isFinite(t))throw c.NUM;return t}const x=t=>typeof t=="number"?0:typeof t=="string"?1:typeof t=="boolean"?2:3,T=new Intl.Collator("en",{sensitivity:"accent",numeric:!1}),m=' !"#$%&()*,./:;?@[\\]^_`{|}~+<=>';function A(t,e){const n=Math.min(t.length,e.length);for(let r=0;r<n;r++){if(t[r]===e[r])continue;const i=m.indexOf(t[r]),o=m.indexOf(e[r]);if(i>=0&&o>=0)return i<o?-1:1;if(i>=0||o>=0)return i>=0?-1:1;break}return T.compare(t,e)||(t<e?-1:t>e?1:0)}const w=t=>t.includes("-")||t.includes("'")?t.replace(/['-]/g,""):t;function E(t,e){if(t===e)return 0;const n=t.toLowerCase(),r=e.toLowerCase();if(n===r)return 0;const i=A(w(n),w(r));return i!==0?i:n.length!==r.length?n.length<r.length?-1:1:n<r?-1:1}function G(t,e){if(t instanceof l||e instanceof l)return t instanceof l?e instanceof l?t.equals(e)?0:E(t.text,e.text)||(t.index<e.index?-1:1):1:-1;if(t==null){if(e==null)return 0;t=typeof e=="number"?0:typeof e=="string"?"":!1}else e==null&&(e=typeof t=="number"?0:typeof t=="string"?"":!1);const n=x(t),r=x(e);return n!==r?n<r?-1:1:n===0?t===e||Math.abs(t-e)<=Math.abs(t)*1e-13&&Number(t.toPrecision(15))===Number(e.toPrecision(15))?0:t<e?-1:1:n===1?E(t,e):t===e?0:t?1:-1}export{u as Arr,c as ERR,R as ERR_BY_CODE,L as ERR_BY_INDEX,b as Lambda,a as OMITTED,V as REJECTED,S as Ref,$ as RefList,l as RichValue,s as XlError,C as bool,k as checked,E as compareText,G as compareValues,F as int,B as isOmitted,d as num,M as numberToText,Y as opt,D as power,y as str,U as textToNumber};
1
+ import{NUM as g}from"../core/sheet.js";import{parseInput as N}from"../core/input.js";class s{constructor(e,n){this.code=e,this.index=n}toString(){return this.code}}const u={NULL:new s("#NULL!",0),DIV0:new s("#DIV/0!",1),VALUE:new s("#VALUE!",2),REF:new s("#REF!",3),NAME:new s("#NAME?",4),NUM:new s("#NUM!",5),NA:new s("#N/A",6),GETTING:new s("#GETTING_DATA",7),SPILL:new s("#SPILL!",8),CALC:new s("#CALC!",9),BUSY:new s("#BUSY!",10),CONNECT:new s("#CONNECT!",11),BLOCKED:new s("#BLOCKED!",12),FIELD:new s("#FIELD!",13),UNKNOWN:new s("#UNKNOWN!",14)},L=Object.values(u),R=new Map(L.map(t=>[t.code,t]));class S{constructor(e,n,i,r,o){this.sheet=e,this.r0=n,this.c0=i,this.r1=r,this.c1=o}get rows(){return this.r1-this.r0+1}get cols(){return this.c1-this.c0+1}get isCell(){return this.r0===this.r1&&this.c0===this.c1}}class ${constructor(e){this.refs=e}}class f{constructor(e,n,i){this.rows=e,this.cols=n,this.data=i}get(e,n){return this.data[e*this.cols+n]}static of2D(e){const n=e.reduce((r,o)=>Math.max(r,o.length),0),i=[];for(const r of e)for(let o=0;o<n;o++)i.push(o<r.length?r[o]:u.NA);return new f(e.length,n,i)}static column(e){return new f(e.length,1,e)}static row(e){return new f(1,e.length,e)}static filled(e,n,i){return new f(e,n,new Array(e*n).fill(i))}}class b{constructor(e,n,i,r){this.params=e,this.body=n,this.frame=i,this.optional=r}}class l{constructor(e,n){this.rich=e,this.index=n}get text(){return this.rich.view(this.index)?.text??""}equals(e){return e instanceof l&&e.rich===this.rich&&(e.index===this.index||this.rich.sameValue(this.index,e.index))}toString(){return this.text}toJSON(){return this.text}}const a=Symbol("omitted");function M(t){if(Number.isInteger(t)&&Math.abs(t)<1e15)return String(t);if(!Number.isFinite(t))return u.NUM.code;const e=t<0,n=Math.abs(t).toExponential(14),i=n.indexOf("e"),r=(n[0]+n.slice(2,i)).replace(/0+$/,"")||"0",o=Number(n.slice(i+1));let c;if(o>=0){const h=r.length>o+1?r.slice(0,o+1):r.padEnd(o+1,"0"),p=r.length>o+1?r.slice(o+1):"";c=p?`${h}.${p}`:h}else c=`0.${"0".repeat(-o-1)}${r}`;if(c.length>20){const h=Math.abs(o);c=`${r.length>1?`${r[0]}.${r.slice(1)}`:r}E${o<0?"-":"+"}${h<10?"0":""}${h}`}return e?`-${c}`:c}function U(t){const e=t.trim();if(e==="")return null;const n=N(e);return n.kind===g?n.value:null}function D(t,e){if(t<0&&!Number.isInteger(e)){const n=1/e,i=Math.round(n);if(Math.abs(n-i)<1e-9&&Math.abs(i)%2===1)return-((-t)**e)}return t**e}const V=Object.freeze({rejected:!0});function d(t){if(typeof t=="number")return t;if(t==null||t===a)return 0;if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){const e=U(t);if(e===null)throw u.VALUE;return e}if(t instanceof s)throw t;if(t instanceof f)return d(t.data[0]);throw u.VALUE}function y(t){if(typeof t=="string")return t;if(typeof t=="number")return M(t);if(t==null||t===a)return"";if(typeof t=="boolean")return t?"TRUE":"FALSE";if(t instanceof s)throw t;if(t instanceof f)return y(t.data[0]);throw u.VALUE}function C(t){if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(t==null||t===a)return!1;if(typeof t=="string"){const e=t.trim().toUpperCase();if(e==="TRUE")return!0;if(e==="FALSE")return!1;throw u.VALUE}if(t instanceof s)throw t;if(t instanceof f)return C(t.data[0]);throw u.VALUE}const F=t=>Math.trunc(d(t)),B=t=>t===a||t===void 0,Y=(t,e)=>t===a||t===void 0?e:t;function k(t){if(!Number.isFinite(t))throw u.NUM;return t}const x=t=>typeof t=="number"?0:typeof t=="string"?1:typeof t=="boolean"?2:3,T=new Intl.Collator("en",{sensitivity:"accent",numeric:!1}),m=' !"#$%&()*,./:;?@[\\]^_`{|}~+<=>';function A(t,e,n){const i=Math.min(t.length,e.length);for(let r=0;r<i;r++){if(t[r]===e[r])continue;const o=m.indexOf(t[r]),c=m.indexOf(e[r]);if(o>=0&&c>=0)return o<c?-1:1;if(o>=0||c>=0)return o>=0?-1:1;break}return n.compare(t,e)||(t<e?-1:t>e?1:0)}const w=t=>t.includes("-")||t.includes("'")?t.replace(/['-]/g,""):t;function E(t,e,n=T){if(t===e)return 0;const i=t.toLowerCase(),r=e.toLowerCase();if(i===r)return 0;const o=A(w(i),w(r),n);return o!==0?o:i.length!==r.length?i.length<r.length?-1:1:i<r?-1:1}function G(t,e){if(t instanceof l||e instanceof l)return t instanceof l?e instanceof l?t.equals(e)?0:E(t.text,e.text)||(t.index<e.index?-1:1):1:-1;if(t==null){if(e==null)return 0;t=typeof e=="number"?0:typeof e=="string"?"":!1}else e==null&&(e=typeof t=="number"?0:typeof t=="string"?"":!1);const n=x(t),i=x(e);return n!==i?n<i?-1:1:n===0?t===e||Math.abs(t-e)<=Math.abs(t)*1e-13&&Number(t.toPrecision(15))===Number(e.toPrecision(15))?0:t<e?-1:1:n===1?E(t,e):t===e?0:t?1:-1}export{f as Arr,u as ERR,R as ERR_BY_CODE,L as ERR_BY_INDEX,b as Lambda,a as OMITTED,V as REJECTED,S as Ref,$ as RefList,l as RichValue,s as XlError,C as bool,k as checked,E as compareText,G as compareValues,F as int,B as isOmitted,d as num,M as numberToText,Y as opt,D as power,y as str,U as textToNumber};
@@ -0,0 +1 @@
1
+ const r=new Map;function o(e,t,n="en-US"){if(typeof e!="string"||e==="")throw new Error("A culture needs a name");if(t.months&&t.months.length!==12)throw new Error("months needs 12 names");if(t.days&&t.days.length!==7)throw new Error("days needs 7 names");r.set(e.toLowerCase(),{tag:e,fields:t,parent:n})}const s=e=>r.get(String(e).toLowerCase())??null,u=()=>[...r.values()].map(e=>e.tag);function a(e){return r.delete(String(e).toLowerCase())}export{s as customCulture,u as customCultures,o as defineCulture,a as removeCulture};
@@ -1 +1 @@
1
- import{LCID_TAGS as z}from"./lcid.js";const C=new Map,N={ja:["午前","午後"],ko:["오전","오후"],zh:["上午","下午"]},A={es:{shortMonths:["ene.","feb.","mar.","abr.","may.","jun.","jul.","ago.","sep.","oct.","nov.","dic."],shortDays:["do.","lu.","ma.","mi.","ju.","vi.","sá."]},pl:{shortDays:["niedz.","pon.","wt.","śr.","czw.","pt.","sob."]},ru:{shortDays:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]},de:{shortDays:["So","Mo","Di","Mi","Do","Fr","Sa"]},cs:{shortMonths:["I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII"]},sv:{shortDays:[,,,,"tor"]},he:{shortDays:["יום א","יום ב","יום ג","יום ד","יום ה","יום ו"]},ar:{shortDays:[,"الإثنين"],days:[,"الإثنين"]}},T={"pt-PT":{shortDays:["domingo","segunda","terça","quarta","quinta","sexta","sábado"],shortMonths:["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"]}},S=(e,n)=>n?e.map((t,o)=>n[o]??t):e;function H(e){let n=C.get(e);if(n!==void 0)return n;const t=[],o=[],s=[],r=[],c=l=>new Intl.DateTimeFormat(e,{...l,timeZone:"UTC",calendar:"gregory"}),a=c({month:"long"}),u=c({month:"short"}),p=c({weekday:"long"}),i=c({weekday:"short"});for(let l=0;l<12;l++){const f=new Date(Date.UTC(2024,l,15));t.push(a.format(f)),o.push(u.format(f))}for(let l=0;l<7;l++){const f=new Date(Date.UTC(2024,0,7+l));s.push(p.format(f)),r.push(i.format(f))}const m=e.split("-")[0],d=T[e]??A[m];return n={tag:e,months:t,shortMonths:S(o,d?.shortMonths),days:S(s,d?.days),shortDays:S(r,d?.shortDays),am:N[m]?.[0]??"AM",pm:N[m]?.[1]??"PM"},C.set(e,n),n}function Z(e){const n=/^\$([^-]*)(?:-(.*))?$/.exec(e);if(n===null)return null;const t={currency:n[1]||null,tag:null,calendar:0,numerals:0,gannen:!1,system:null},o=n[2];if(o===void 0||o==="")return t;const s=o.toLowerCase();if(s==="x-sysdate")t.system="date";else if(s==="x-systime")t.system="time";else if(/^[0-9a-f]{1,8}$/i.test(o)){const r=parseInt(o,16);(r&65535)===63488?t.system="date":(r&65535)===62464?t.system="time":(t.numerals=r>>>24&255,t.calendar=r>>>16&255,t.tag=z[r&65535]??null)}else{t.gannen=/-x-gannen$/i.test(o),t.tag=o.replace(/-x-.*$/i,"");try{Intl.getCanonicalLocales(t.tag)}catch{t.tag=null}}return t}const L=[{start:0,name:"明治",abbreviation:"明",symbol:"M",firstYear:1868},{start:4595,name:"大正",abbreviation:"大",symbol:"T",firstYear:1912},{start:9856,name:"昭和",abbreviation:"昭",symbol:"S",firstYear:1926},{start:32516,name:"平成",abbreviation:"平",symbol:"H",firstYear:1989},{start:43586,name:"令和",abbreviation:"令",symbol:"R",firstYear:2019}];function q(e){return e.map(n=>{const[t,o,s]=n.start.split("-").map(Number),r=Date.UTC(t,o-1,s)/864e5+25569;return{...n,start:r<61?r-1:r,firstYear:t}}).sort((n,t)=>n.start-t.start)}function K(e,n){if(n?.eras)return n.eras;const t=e?.tag??n?.tag??null;return e?.calendar===3||t&&t.split("-")[0]==="ja"?L:null}function Q(e,n){let t=e[0];for(const o of e)n>=o.start&&(t=o);return t}const O=1948439,P=2415019;function k(e){const n=Math.floor(e),t=(n<60?n+1:n)+P-O,o=Math.floor(t/10631);let s=t-o*10631,r=0;for(;;){const a=_(r+1)?355:354;if(s<a)break;s-=a,r++}let c=0;for(;;){const a=c%2===0||c===11&&_(r+1)?30:29;if(s<a)break;s-=a,c++}return{year:o*30+r+1,month:c+1,day:s+1}}const v=new Set([2,5,7,10,13,15,18,21,24,26,29]),_=e=>v.has((e-1)%30+1),R=["محرم","صفر","ربيع الأول","ربيع الثاني","جمادى الأولى","جمادى الثانية","رجب","شعبان","رمضان","شوال","ذو القعدة","ذو الحجة"],$=e=>(7*e+1)%19<7;function h(e){const n=Math.floor((235*e-234)/19),t=12084+13753*n;let o=n*29+Math.floor(t/25920);return 3*(o+1)%7<3&&o++,o}function y(e){const n=h(e-1),t=h(e);return h(e+1)-t===356?2:t-n===382?1:0}const Y=e=>h(e+1)+y(e+1)-h(e)-y(e),b=-1373427,F=693594;function B(e){const n=Math.floor(e),t=(n<60?n+1:n)+F;let o=Math.floor((t-b)/365.2468)+1;for(;b+h(o)+y(o)>t;)o--;for(;b+h(o+1)+y(o+1)<=t;)o++;let s=t-(b+h(o)+y(o));const r=Y(o),c=$(o),a=[30,r%10===5?30:29,r%10===3?29:30,29,30];c?a.push(30,29):a.push(29),a.push(30,29,30,29,30,29);let u=0;for(;s>=a[u];)s-=a[u],u++;return{year:o,month:u+1,day:s+1,leap:c}}const J=["תשרי","חשון","כסלו","טבת","שבט","אדר","ניסן","אייר","סיון","תמוז","אב","אלול"],U=["תשרי","חשון","כסלו","טבת","שבט","אדר א","אדר ב","ניסן","אייר","סיון","תמוז","אב","אלול"];function tt(e,n,t,o){switch(e){case 6:case"hijri":{const s=k(n);return{...s,monthName:o===null||o.startsWith("ar")?R[s.month-1]:null}}case 7:return{year:t.year+543,month:t.month,day:t.day};case 5:return{year:t.year+2333,month:t.month,day:t.day};case 8:{const s=B(n),r=s.leap?U:J;return{...s,monthName:o?.startsWith("he")?r[s.month-1]:null}}default:return null}}const et=()=>H("ar-SA"),D="0123456789",j={ja:{1:"〇一二三四五六七八九",2:"〇壱弐参四伍六七八九",3:D},"zh-CN":{1:"○一二三四五六七八九",2:"零壹贰叁肆伍陆柒捌玖",3:D},zh:{1:"○一二三四五六七八九",2:"零壹貳參肆伍陸柒捌玖",3:D},ko:{1:"0一二三四五六七八九",2:"零壹貳參四伍六七八九",3:D}};function nt(e,n){if(!n)return null;const t=n.split("-")[0];return j[n==="zh-CN"||n==="zh-SG"?"zh-CN":t]?.[e]??null}const W={ja:{1:{small:"十百千",big:"万億兆",dropOne:!0},2:{small:"拾百阡",big:"万億兆"},3:{small:"十百千",big:"万億兆",dropOne:!0}},ko:{1:{small:"十百千",big:"万億兆"}},"zh-CN":{1:{small:"十百千",big:"万亿兆",zeroes:!0},2:{small:"拾佰仟",big:"万亿兆",zeroes:!0}}};function ot(e,n,t){if(!t)return null;const o=t.split("-")[0],s=t==="zh-CN"||t==="zh-SG"?"zh-CN":o,r=W[s]?.[n],c=j[s]?.[n];if(!r||!c)return null;const a=/^(\d+)(\.\d+)?$/.exec(e);if(a===null)return null;const u=[...c],p=a[1];if(/^0+$/.test(p))return u[0]+(a[2]?`.${[...a[2].slice(1)].map(l=>u[Number(l)]).join("")}`:"");let i="",m=!1;const d=Math.ceil(p.length/4);for(let l=0;l<d;l++){const f=p.length-(d-1-l)*4,I=p.slice(Math.max(0,f-4),f);let g=!1;for(let x=0;x<I.length;x++){const M=Number(I[x]),w=I.length-1-x;if(M===0){m=i!==""||g;continue}m&&r.zeroes&&(i+=u[0]),m=!1,w>0&&M===1&&r.dropOne||(i+=u[M]),w>0&&(i+=[...r.small][w-1]),g=!0}const E=d-1-l;g&&E>0&&(i+=[...r.big][E-1])}return i+(a[2]?`.${[...a[2].slice(1)].map(l=>u[Number(l)]).join("")}`:"")}const X={2:1632,3:1776,4:2406,5:2534,6:2662,7:2790,8:2918,10:3174,11:3302,12:3430,13:3664,14:3792,15:3872,16:4160,18:6112,19:6160};function st(e){if(e===9)return"0௧௨௩௪௫௬௭௮௯";if(e===17)return"0፩፪፫፬፭፮፯፰፱";const n=X[e];return n===void 0?null:Array.from({length:10},(t,o)=>String.fromCodePoint(n+o)).join("")}function rt(e,n){const t=[...n];let o="";for(let s=0;s<e.length;s++){const r=e.charCodeAt(s);o+=r>=48&&r<=57?t[r-48]:e[s]}return o}export{tt as calendarParts,nt as dbnumDigits,ot as dbnumPlaces,Q as eraAt,K as erasOf,et as hijriLocale,H as localeData,rt as mapDigits,st as numeralDigits,Z as parseLocaleBracket,q as preparedEras};
1
+ import{LCID_TAGS as z}from"./lcid.js";const C=new Map,N={ja:["午前","午後"],ko:["오전","오후"],zh:["上午","下午"]},T={es:{shortMonths:["ene.","feb.","mar.","abr.","may.","jun.","jul.","ago.","sep.","oct.","nov.","dic."],shortDays:["do.","lu.","ma.","mi.","ju.","vi.","sá."]},pl:{shortDays:["niedz.","pon.","wt.","śr.","czw.","pt.","sob."]},ru:{shortDays:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]},de:{shortDays:["So","Mo","Di","Mi","Do","Fr","Sa"]},cs:{shortMonths:["I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII"]},sv:{shortDays:[,,,,"tor"]},he:{shortDays:["יום א","יום ב","יום ג","יום ד","יום ה","יום ו"]},ar:{shortDays:[,"الإثنين"],days:[,"الإثنين"]}},A={"pt-PT":{shortDays:["domingo","segunda","terça","quarta","quinta","sexta","sábado"],shortMonths:["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"]}},E=(e,n)=>n?e.map((t,o)=>n[o]??t):e;function H(e){let n=C.get(e);if(n!==void 0)return n;const t=[],o=[],s=[],r=[],l=[],a=c=>new Intl.DateTimeFormat(e,{...c,timeZone:"UTC",calendar:"gregory"}),u=a({month:"long"}),d=a({day:"numeric",month:"long"}),h=a({month:"short"}),y=a({weekday:"long"}),x=a({weekday:"short"});for(let c=0;c<12;c++){const f=new Date(Date.UTC(2024,c,15));t.push(u.format(f)),o.push(d.formatToParts(f).find(D=>D.type==="month").value),s.push(h.format(f))}for(let c=0;c<7;c++){const f=new Date(Date.UTC(2024,0,7+c));r.push(y.format(f)),l.push(x.format(f))}const i=e.split("-")[0],p=A[e]??T[i];return n={tag:e,months:t,monthsWithDay:o,shortMonths:E(s,p?.shortMonths),days:E(r,p?.days),shortDays:E(l,p?.shortDays),am:N[i]?.[0]??"AM",pm:N[i]?.[1]??"PM"},C.set(e,n),n}function Z(e){const n=/^\$([^-]*)(?:-(.*))?$/.exec(e);if(n===null)return null;const t={currency:n[1]||null,tag:null,calendar:0,numerals:0,gannen:!1,system:null},o=n[2];if(o===void 0||o==="")return t;const s=o.toLowerCase();if(s==="x-sysdate")t.system="date";else if(s==="x-systime")t.system="time";else if(/^[0-9a-f]{1,8}$/i.test(o)){const r=parseInt(o,16);(r&65535)===63488?t.system="date":(r&65535)===62464?t.system="time":(t.numerals=r>>>24&255,t.calendar=r>>>16&255,t.tag=z[r&65535]??null)}else{t.gannen=/-x-gannen$/i.test(o),t.tag=o.replace(/-x-.*$/i,"");try{Intl.getCanonicalLocales(t.tag)}catch{t.tag=null}}return t}const L=[{start:0,name:"明治",abbreviation:"明",symbol:"M",firstYear:1868},{start:4595,name:"大正",abbreviation:"大",symbol:"T",firstYear:1912},{start:9856,name:"昭和",abbreviation:"昭",symbol:"S",firstYear:1926},{start:32516,name:"平成",abbreviation:"平",symbol:"H",firstYear:1989},{start:43586,name:"令和",abbreviation:"令",symbol:"R",firstYear:2019}];function q(e){return e.map(n=>{const[t,o,s]=n.start.split("-").map(Number),r=Date.UTC(t,o-1,s)/864e5+25569;return{...n,start:r<61?r-1:r,firstYear:t}}).sort((n,t)=>n.start-t.start)}function K(e,n){if(n?.eras)return n.eras;const t=e?.tag??n?.tag??null;return e?.calendar===3||t&&t.split("-")[0]==="ja"?L:null}function Q(e,n){let t=e[0];for(const o of e)n>=o.start&&(t=o);return t}const P=1948439,v=2415019;function O(e){const n=Math.floor(e),t=(n<60?n+1:n)+v-P,o=Math.floor(t/10631);let s=t-o*10631,r=0;for(;;){const a=_(r+1)?355:354;if(s<a)break;s-=a,r++}let l=0;for(;;){const a=l%2===0||l===11&&_(r+1)?30:29;if(s<a)break;s-=a,l++}return{year:o*30+r+1,month:l+1,day:s+1}}const k=new Set([2,5,7,10,13,15,18,21,24,26,29]),_=e=>k.has((e-1)%30+1),R=["محرم","صفر","ربيع الأول","ربيع الثاني","جمادى الأولى","جمادى الثانية","رجب","شعبان","رمضان","شوال","ذو القعدة","ذو الحجة"],$=e=>(7*e+1)%19<7;function m(e){const n=Math.floor((235*e-234)/19),t=12084+13753*n;let o=n*29+Math.floor(t/25920);return 3*(o+1)%7<3&&o++,o}function b(e){const n=m(e-1),t=m(e);return m(e+1)-t===356?2:t-n===382?1:0}const Y=e=>m(e+1)+b(e+1)-m(e)-b(e),g=-1373427,F=693594;function W(e){const n=Math.floor(e),t=(n<60?n+1:n)+F;let o=Math.floor((t-g)/365.2468)+1;for(;g+m(o)+b(o)>t;)o--;for(;g+m(o+1)+b(o+1)<=t;)o++;let s=t-(g+m(o)+b(o));const r=Y(o),l=$(o),a=[30,r%10===5?30:29,r%10===3?29:30,29,30];l?a.push(30,29):a.push(29),a.push(30,29,30,29,30,29);let u=0;for(;s>=a[u];)s-=a[u],u++;return{year:o,month:u+1,day:s+1,leap:l}}const B=["תשרי","חשון","כסלו","טבת","שבט","אדר","ניסן","אייר","סיון","תמוז","אב","אלול"],J=["תשרי","חשון","כסלו","טבת","שבט","אדר א","אדר ב","ניסן","אייר","סיון","תמוז","אב","אלול"];function tt(e,n,t,o){switch(e){case 6:case"hijri":{const s=O(n);return{...s,monthName:o===null||o.startsWith("ar")?R[s.month-1]:null}}case 7:return{year:t.year+543,month:t.month,day:t.day};case 5:return{year:t.year+2333,month:t.month,day:t.day};case 8:{const s=W(n),r=s.leap?J:B;return{...s,monthName:o?.startsWith("he")?r[s.month-1]:null}}default:return null}}const et=()=>H("ar-SA"),M="0123456789",j={ja:{1:"〇一二三四五六七八九",2:"〇壱弐参四伍六七八九",3:M},"zh-CN":{1:"○一二三四五六七八九",2:"零壹贰叁肆伍陆柒捌玖",3:M},zh:{1:"○一二三四五六七八九",2:"零壹貳參肆伍陸柒捌玖",3:M},ko:{1:"0一二三四五六七八九",2:"零壹貳參四伍六七八九",3:M}};function nt(e,n){if(!n)return null;const t=n.split("-")[0];return j[n==="zh-CN"||n==="zh-SG"?"zh-CN":t]?.[e]??null}const U={ja:{1:{small:"十百千",big:"万億兆",dropOne:!0},2:{small:"拾百阡",big:"万億兆"},3:{small:"十百千",big:"万億兆",dropOne:!0}},ko:{1:{small:"十百千",big:"万億兆"}},"zh-CN":{1:{small:"十百千",big:"万亿兆",zeroes:!0},2:{small:"拾佰仟",big:"万亿兆",zeroes:!0}}};function ot(e,n,t){if(!t)return null;const o=t.split("-")[0],s=t==="zh-CN"||t==="zh-SG"?"zh-CN":o,r=U[s]?.[n],l=j[s]?.[n];if(!r||!l)return null;const a=/^(\d+)(\.\d+)?$/.exec(e);if(a===null)return null;const u=[...l],d=a[1];if(/^0+$/.test(d))return u[0]+(a[2]?`.${[...a[2].slice(1)].map(i=>u[Number(i)]).join("")}`:"");let h="",y=!1;const x=Math.ceil(d.length/4);for(let i=0;i<x;i++){const p=d.length-(x-1-i)*4,c=d.slice(Math.max(0,p-4),p);let f=!1;for(let I=0;I<c.length;I++){const w=Number(c[I]),S=c.length-1-I;if(w===0){y=h!==""||f;continue}y&&r.zeroes&&(h+=u[0]),y=!1,S>0&&w===1&&r.dropOne||(h+=u[w]),S>0&&(h+=[...r.small][S-1]),f=!0}const D=x-1-i;f&&D>0&&(h+=[...r.big][D-1])}return h+(a[2]?`.${[...a[2].slice(1)].map(i=>u[Number(i)]).join("")}`:"")}const X={2:1632,3:1776,4:2406,5:2534,6:2662,7:2790,8:2918,10:3174,11:3302,12:3430,13:3664,14:3792,15:3872,16:4160,18:6112,19:6160};function st(e){if(e===9)return"0௧௨௩௪௫௬௭௮௯";if(e===17)return"0፩፪፫፬፭፮፯፰፱";const n=X[e];return n===void 0?null:Array.from({length:10},(t,o)=>String.fromCodePoint(n+o)).join("")}function rt(e,n){const t=[...n];let o="";for(let s=0;s<e.length;s++){const r=e.charCodeAt(s);o+=r>=48&&r<=57?t[r-48]:e[s]}return o}export{tt as calendarParts,nt as dbnumDigits,ot as dbnumPlaces,Q as eraAt,K as erasOf,et as hijriLocale,H as localeData,rt as mapDigits,st as numeralDigits,Z as parseLocaleBracket,q as preparedEras};