@8sheets/data-grid 1.1.1 → 1.2.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.
- package/README.md +1 -1
- package/a11y/cell-alt-text.js +1 -1
- package/api/serialize.js +1 -1
- package/api/style-refs.js +1 -1
- package/calc/adjust.js +1 -1
- package/calc/compile.js +1 -1
- package/calc/engine.js +1 -1
- package/calc/functions/array.js +1 -1
- package/calc/functions/database.js +1 -1
- package/calc/functions/date.js +1 -1
- package/calc/functions/engineering.js +1 -1
- package/calc/functions/financial.js +1 -1
- package/calc/functions/helpers.js +1 -1
- package/calc/functions/index.js +3 -2
- package/calc/functions/info.js +1 -1
- package/calc/functions/logical.js +1 -1
- package/calc/functions/lookup.js +1 -1
- package/calc/functions/math.js +1 -1
- package/calc/functions/stat.js +1 -1
- package/calc/functions/text.js +1 -1
- package/calc/parser.js +2 -2
- package/calc/shown-refs.js +1 -0
- package/calc/values.js +1 -1
- package/calcx/calc-control.js +1 -0
- package/calcx/external-read.js +1 -1
- package/calcx/external.js +1 -1
- package/calcx/lang/convert.js +1 -1
- package/cells/axis-ops.js +1 -1
- package/cells/book-css.js +7 -2
- package/cells/cell-styles-xml.js +1 -1
- package/cells/cf-engine.js +1 -1
- package/cells/cf-file.js +1 -1
- package/cells/docprops-xml.js +2 -2
- package/cells/filter-eval.js +1 -0
- package/cells/filter-file.js +1 -1
- package/cells/find-engine.js +2 -2
- package/cells/find.js +1 -1
- package/cells/goto.js +1 -1
- package/cells/link-model.js +1 -0
- package/cells/name-box.js +1 -1
- package/cells/note-box.js +3 -0
- package/cells/options.js +1 -1
- package/cells/outline-column.js +1 -1
- package/cells/protected-menu.js +1 -0
- package/cells/rich-data-xml.js +1 -1
- package/cells/selection-modes.js +1 -1
- package/cells/sheet-views-file.js +2 -0
- package/cells/shift-check.js +1 -1
- package/cells/sort-compare.js +1 -0
- package/cells/ui-kit.js +1 -1
- package/cells/undo-group.js +1 -1
- package/celltypes/dropdowns.js +2 -2
- package/core/address.js +1 -1
- package/core/autofill.js +1 -1
- package/core/axis.js +1 -1
- package/core/cond-format.js +1 -1
- package/core/culture.js +5 -1
- package/core/custom-views.js +1 -1
- package/core/data-tools.js +1 -0
- package/core/date-codes.js +1 -0
- package/core/default-names.js +1 -1
- package/core/edit-ranges.js +1 -0
- package/core/formula-refs.js +1 -1
- package/core/host-rules.js +1 -0
- package/core/input.js +1 -1
- package/core/numfmt.js +1 -1
- package/core/precision.js +1 -0
- package/core/protection.js +1 -1
- package/core/region-input.js +1 -1
- package/core/rule-refs.js +1 -0
- package/core/shared-view.js +1 -0
- package/core/sheet.js +1 -1
- package/core/sparklines.js +1 -1
- package/core/sparse.js +1 -1
- package/core/spills.js +1 -0
- package/core/strings.js +1 -1
- package/core/structure.js +1 -1
- package/core/table-columns.js +1 -0
- package/core/tables.js +2 -2
- package/core/validation-ranges.js +1 -1
- package/core/whatif.js +1 -1
- package/core/workbook.js +1 -1
- package/datasheets/formula.js +1 -1
- package/datasheets/manager.js +1 -1
- package/datasheets/path-binding.js +1 -1
- package/datasheets/persist-writer.js +1 -1
- package/datasheets/persist.js +1 -1
- package/datasheets/report.js +1 -1
- package/extras/getdata/persist.js +2 -2
- package/extras/getdata/rows.js +1 -1
- package/extras/getdata/shared-steps.js +1 -0
- package/extras/getdata/steps-formula.js +1 -0
- package/extras/getdata/steps-more.js +1 -0
- package/extras/getdata/steps-tables.js +1 -0
- package/extras/getdata/steps.js +1 -1
- package/i18n/de/a11y.js +1 -0
- package/i18n/de/cells.js +2 -0
- package/i18n/de/charts.js +1 -0
- package/i18n/de/common.js +1 -0
- package/i18n/de/datasheets.js +1 -0
- package/i18n/de/format.js +1 -0
- package/i18n/de/misc.js +1 -0
- package/i18n/de/pivot.js +1 -0
- package/i18n/de/proofing.js +1 -0
- package/i18n/de/ribbon.js +1 -0
- package/i18n/de/shapes.js +1 -0
- package/i18n/de/shell.js +3 -0
- package/i18n/de/touch.js +1 -0
- package/i18n/de.js +1 -0
- package/i18n/en/cells.js +2 -1
- package/i18n/en/charts.js +1 -1
- package/i18n/en/format.js +1 -1
- package/i18n/en/misc.js +1 -1
- package/i18n/en/pivot.js +1 -1
- package/i18n/en/proofing.js +1 -1
- package/i18n/en/ribbon.js +1 -1
- package/i18n/en/shapes.js +1 -1
- package/i18n/en/shell.js +3 -2
- package/i18n/en/touch.js +1 -1
- package/i18n/es/a11y.js +1 -0
- package/i18n/es/cells.js +2 -0
- package/i18n/es/charts.js +1 -0
- package/i18n/es/common.js +1 -0
- package/i18n/es/datasheets.js +1 -0
- package/i18n/es/format.js +1 -0
- package/i18n/es/misc.js +1 -0
- package/i18n/es/pivot.js +1 -0
- package/i18n/es/proofing.js +1 -0
- package/i18n/es/ribbon.js +1 -0
- package/i18n/es/shapes.js +1 -0
- package/i18n/es/shell.js +3 -0
- package/i18n/es/touch.js +1 -0
- package/i18n/es.js +1 -0
- package/i18n/fr/a11y.js +1 -0
- package/i18n/fr/cells.js +2 -0
- package/i18n/fr/charts.js +1 -0
- package/i18n/fr/common.js +1 -0
- package/i18n/fr/datasheets.js +1 -0
- package/i18n/fr/format.js +1 -0
- package/i18n/fr/misc.js +1 -0
- package/i18n/fr/pivot.js +1 -0
- package/i18n/fr/proofing.js +1 -0
- package/i18n/fr/ribbon.js +1 -0
- package/i18n/fr/shapes.js +1 -0
- package/i18n/fr/shell.js +3 -0
- package/i18n/fr/touch.js +1 -0
- package/i18n/fr.js +1 -0
- package/i18n/index.js +1 -1
- package/i18n/languages.js +1 -1
- package/i18n/pl/cells.js +2 -1
- package/i18n/pl/charts.js +1 -1
- package/i18n/pl/format.js +1 -1
- package/i18n/pl/misc.js +1 -1
- package/i18n/pl/pivot.js +1 -1
- package/i18n/pl/proofing.js +1 -1
- package/i18n/pl/ribbon.js +1 -1
- package/i18n/pl/shapes.js +1 -1
- package/i18n/pl/shell.js +3 -2
- package/i18n/pl/touch.js +1 -1
- package/io/blob-sink.js +1 -0
- package/io/canonical-xml.js +1 -0
- package/io/client.js +1 -1
- package/io/crypto/cfb-build.js +1 -0
- package/io/crypto/cfb-read.js +1 -1
- package/io/crypto/cfb-write.js +1 -1
- package/io/crypto/errors.js +1 -1
- package/io/csv.js +8 -8
- package/io/encoding.js +1 -0
- package/io/foreign-sheets.js +2 -2
- package/io/io.worker.js +1 -1
- package/io/open-package.js +1 -0
- package/io/package-paths.js +1 -1
- package/io/plan.js +1 -1
- package/io/text-split.js +3 -3
- package/io/xls/chart-sheet.js +1 -0
- package/io/xls/chart.js +1 -0
- package/io/xls/crypt.js +1 -0
- package/io/xls/dml-color.js +1 -0
- package/io/xls/drawing.js +1 -0
- package/io/xls/formula.js +1 -0
- package/io/xls/geometry.js +1 -0
- package/io/xls/index.js +1 -0
- package/io/xls/pictures.js +1 -0
- package/io/xls/pivot.js +1 -0
- package/io/xls/props.js +1 -0
- package/io/xls/records.js +1 -0
- package/io/xls/shapes.js +1 -0
- package/io/xls/sheet-ext.js +1 -0
- package/io/xls/sheet.js +1 -0
- package/io/xls/styles.js +1 -0
- package/io/xls/vba.js +1 -0
- package/io/xls/workbook.js +1 -0
- package/io/xlsb/filter.js +1 -0
- package/io/xlsb/formula.js +2 -0
- package/io/xlsb/functions.js +1 -0
- package/io/xlsb/index.js +1 -0
- package/io/xlsb/parts.js +1 -0
- package/io/xlsb/pivot.js +1 -0
- package/io/xlsb/records.js +1 -0
- package/io/xlsb/sheet-ext.js +1 -0
- package/io/xlsb/sheet.js +1 -0
- package/io/xlsb/slicer.js +1 -0
- package/io/xlsb/styles.js +1 -0
- package/io/xlsb/workbook.js +1 -0
- package/io/xlsb/xml.js +2 -0
- package/io/xlsx-read.js +1 -1
- package/io/xlsx-styles.js +2 -2
- package/io/xlsx-tail.js +1 -1
- package/io/xlsx-write.js +2 -2
- package/io/xml-escape.js +1 -1
- package/io/xml-scan.js +2 -2
- package/io/zip-reader.js +1 -1
- package/objects/chart-model.js +1 -1
- package/objects/drawing-xml.js +1 -1
- package/package.json +1 -1
- package/pivot/calc-items.js +1 -0
- package/pivot/engine.js +1 -1
- package/pivot/xml.js +2 -2
- package/print/note-pages.js +2 -0
- package/print/page-setup.js +1 -1
- package/print/paginate.js +1 -1
- package/print/pdf-crypt.js +1 -0
- package/print/pdf-links.js +1 -0
- package/print/pdf-tags.js +1 -0
- package/print/pdf.js +24 -13
- package/print/render-page.js +3 -3
- package/print/shown-notes.js +1 -0
- package/shapes/form-xml.js +1 -1
- package/slicers/custom-styles.js +1 -1
- package/slicers/format.js +1 -1
- package/slicers/structured.js +1 -1
- package/slicers/write.js +1 -1
- package/table-view/files.js +1 -1
- package/table-view/mount.js +1 -1
- package/table-view/version.js +1 -1
- package/ui/dialogs.js +3 -3
- package/ui/icons.js +1 -1
- package/ui/menu-base.js +1 -1
- package/ui/protection-ui.js +1 -1
package/objects/drawing-xml.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{child as l,children as Z}from"../io/xml-scan.js";import{escapeMarkup as x,xmlLiteralText as k}from"../io/xml-escape.js";import{relativeTarget as ee,relsPathOf as R,resolveTarget as b}from"../io/package-paths.js";import{NS as d,XML_HEAD as M,parseColor as te,parseFill as re,parseSpPr as N,parseTextBody as ne,parseXml as H,parseXfrm as V,toBool as X,toNum as m,writeColor as I,writeFill as ae,writeLine as ce,writeSpPr as ie,writeTextBody as j}from"./dml.js";import{chartExRequires as se}from"../charts/chartex.js";import{parseChart as oe,parseChartEx as le}from"./chart-model.js";const fe={drawing:`${d.r}/drawing`,chart:`${d.r}/chart`,image:`${d.r}/image`,chartEx:"http://schemas.microsoft.com/office/2014/relationships/chartEx",hyperlink:`${d.r}/hyperlink`},Me={drawing:"application/vnd.openxmlformats-officedocument.drawing+xml",chart:"application/vnd.openxmlformats-officedocument.drawingml.chart+xml",chartEx:"application/vnd.ms-office.chartex+xml"},_={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",tif:"image/tiff",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp",emf:"image/x-emf",wmf:"image/x-wmf"};function He(e){switch(e){case"image/jpeg":return"jpeg";case"image/gif":return"gif";case"image/bmp":return"bmp";case"image/tiff":return"tiff";case"image/svg+xml":return"svg";case"image/webp":return"webp";default:return"png"}}const C={twoCellAnchor:"twoCell",oneCellAnchor:"oneCell",absoluteAnchor:"absolute"},B=new Set(["sp","pic","cxnSp","grpSp","graphicFrame","contentPart"]);function O(e){if(e)return{col:m(l(e,"col")?.t,0),colOff:m(l(e,"colOff")?.t,0),row:m(l(e,"row")?.t,0),rowOff:m(l(e,"rowOff")?.t,0)}}function pe(e,t){const n={type:t};if(t==="twoCell")n.editAs=e.a.editAs??"twoCell",n.from=O(l(e,"from")),n.to=O(l(e,"to"));else if(t==="oneCell")n.from=O(l(e,"from"));else{const c=l(e,"pos");n.pos={x:m(c?.a.x,0),y:m(c?.a.y,0)}}const r=l(e,"ext");return r&&(n.ext={cx:m(r.a.cx,0),cy:m(r.a.cy,0)}),n}function v(e,t){const n=l(e,t),r=l(n,"cNvPr");return{id:m(r?.a.id,0),name:r?.a.name??"",descr:r?.a.descr,title:r?.a.title,hidden:X(r?.a.hidden,!1),...(l(r,"extLst")?.c??[]).some(c=>l(c,"decorative")&&l(c,"decorative").a.val!=="0")?{decorative:!0}:{}}}function S(e){if(e)return{idx:m(e.a.idx,0),color:te(e)}}function z(e){if(e)return{lnRef:S(l(e,"lnRef")),fillRef:S(l(e,"fillRef")),effectRef:S(l(e,"effectRef")),fontRef:S(l(e,"fontRef"))}}function xe(e,t){const n=N(l(e,"spPr"),t)??{},r=X(l(l(e,"nvSpPr"),"cNvSpPr")?.a.txBox,!1),c=l(e,"txBody");return{kind:r?"textbox":"shape",...v(e,"nvSpPr"),xfrm:n.xfrm,rot:n.xfrm?.rot??0,flipH:n.xfrm?.flipH??!1,flipV:n.xfrm?.flipV??!1,geom:n.geom,fill:n.fill,line:n.line,style:z(l(e,"style")),text:ne(c,t),macro:e.a.macro,textlink:e.a.textlink}}function de(e,t){const n=N(l(e,"spPr"),t)??{};return{kind:"connector",...v(e,"nvCxnSpPr"),xfrm:n.xfrm,rot:n.xfrm?.rot??0,flipH:n.xfrm?.flipH??!1,flipV:n.xfrm?.flipV??!1,geom:n.geom,line:n.line,fill:n.fill,style:z(l(e,"style"))}}function q(e,t){const n=l(e,"blipFill"),r=l(n,"blip"),c=l(n,"srcRect"),a=N(l(e,"spPr"),t)??{},i=c?{l:m(c.a.l,0)/1e5,t:m(c.a.t,0)/1e5,r:m(c.a.r,0)/1e5,b:m(c.a.b,0)/1e5}:void 0;return{kind:"picture",...v(e,"nvPicPr"),embed:r?.a.embed,link:r?.a.link,crop:i,xfrm:a.xfrm,rot:a.xfrm?.rot??0,flipH:a.xfrm?.flipH??!1,flipV:a.xfrm?.flipV??!1,geom:a.geom,line:a.line}}function me(e,t){const n=l(e,"grpSpPr"),r=V(l(n,"xfrm")),c=[];for(const a of e.c)if(B.has(a.n)){const i=A(a,t);i&&c.push(i)}return{kind:"group",...v(e,"nvGrpSpPr"),xfrm:r,rot:r?.rot??0,flipH:r?.flipH??!1,flipV:r?.flipV??!1,fill:re(n),children:c}}function ue(e){const t=l(l(e,"graphic"),"graphicData"),n=l(t,"chart"),r=v(e,"nvGraphicFramePr"),c=V(l(e,"xfrm"));return n?{kind:/chartex/.test(t.a.uri??"")?"chartex":"chart",...r,xfrm:c,rel:n.a.id}:{kind:"unknown",...r,xfrm:c,uri:t?.a.uri}}function A(e,t){switch(e.n){case"sp":return xe(e,t);case"cxnSp":return de(e,t);case"pic":return q(e,t);case"grpSp":return me(e,t);case"graphicFrame":return ue(e);case"contentPart":return{kind:"unknown",rel:e.a.id};default:return null}}function $e(e,t){const n=l(e,"Choice"),r=l(e,"Fallback"),c=u=>u?.c.find(g=>B.has(g.n)),a=c(n),i=a?A(a,t):null;if(i&&i.kind!=="unknown")return i;const s=c(r),p=s?A(s,t):null;return F(i?{...i,visual:p}:{kind:"unknown",visual:p,...p?{id:p.id,name:p.name}:{}})}function F(e){if(e.kind!=="unknown"||e.visual?.kind!=="picture")return e;const t=e.uri??"";return/drawingml\/2006\/diagram/.test(t)||(e.media=/model3d/i.test(t)?"model3d":/audio|sound/i.test(t)?"audio":/video|movie|media/i.test(t)?"video":"media"),e}function he(e,t,n,r){const c=l(t,"Fallback");if(!e||e.visual||!c||c===n)return;const i=c.c.find(s=>C[s.n])?.c.find(s=>s.n==="pic");i&&(e.visual=q(i,r),F(e))}function we(e,t){return e.replace(/<((?:\w+:)?)(twoCellAnchor|oneCellAnchor|absoluteAnchor)\b[\s\S]*?<\/\1\2>/g,(n,r)=>{const c=(i,s)=>`<${r}${i}><${r}col>${s.col}</${r}col><${r}colOff>${f(s.colOff)}</${r}colOff><${r}row>${s.row}</${r}row><${r}rowOff>${f(s.rowOff)}</${r}rowOff></${r}${i}>`;let a=n;return t.from&&(a=a.replace(new RegExp(`<${r}from>[\\s\\S]*?</${r}from>`),()=>c("from",t.from))),t.to&&(a=a.replace(new RegExp(`<${r}to>[\\s\\S]*?</${r}to>`),()=>c("to",t.to))),t.ext&&(a=a.replace(new RegExp(`<${r}ext\\b[^>]*/>`),()=>`<${r}ext cx="${f(t.ext.cx)}" cy="${f(t.ext.cy)}"/>`)),t.pos&&(a=a.replace(new RegExp(`<${r}pos\\b[^>]*/>`),()=>`<${r}pos x="${f(t.pos.x)}" y="${f(t.pos.y)}"/>`)),a})}function ge(e,{path:t=null,rels:n=[]}={}){const r=H(e),c=r.root,a=[],i=(s,p)=>{const u=C[s.n],g=pe(s,u),h=s.c.find(y=>B.has(y.n)||y.n==="AlternateContent");let o;if(h?.n==="AlternateContent"?o=$e(h,r):h?o=A(h,r):o={kind:"unknown"},/drawing\/20(?:10|12)\/(?:time)?slicer/.test(o.uri??"")){a.push({kind:"foreign",raw:r.raw(p??s)});return}o.anchor=g,o.raw=r.raw(p??s),o.rawContent=h?r.raw(h):"";const w=l(s,"clientData");o.clientData=w?r.raw(w):void 0,o.wrapped=!!p,a.push(o)};for(const s of c.c)if(C[s.n])i(s,null);else if(s.n==="AlternateContent"){const p=l(s,"Choice")??l(s,"Fallback"),u=p?.c.find(g=>C[g.n]);u?(i(u,s),he(a[a.length-1],s,p,r)):a.push({kind:"foreign",raw:r.raw(s)})}else a.push({kind:"foreign",raw:r.raw(s)});return{path:t,rels:n,rootOpen:r.openTag(c),objects:a}}function L(e){const t=H(e);return Z(t.root,"Relationship").map(n=>({id:n.a.Id,type:n.a.Type,target:n.a.Target,targetMode:n.a.TargetMode}))}function ye(e){const t=e.map(n=>`<Relationship Id="${x(n.id)}" Type="${x(n.type)}" Target="${x(n.target)}"${n.targetMode?` TargetMode="${x(n.targetMode)}"`:""}/>`).join("");return`${M}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${t}</Relationships>`}const f=e=>Math.round(e);function D(e,t){return`<xdr:${e}><xdr:col>${t.col}</xdr:col><xdr:colOff>${f(t.colOff)}</xdr:colOff><xdr:row>${t.row}</xdr:row><xdr:rowOff>${f(t.rowOff)}</xdr:rowOff></xdr:${e}>`}function be(e){return e.type==="twoCell"?[`<xdr:twoCellAnchor${e.editAs&&e.editAs!=="twoCell"?` editAs="${x(e.editAs)}"`:""}>${D("from",e.from)}${D("to",e.to)}`,"</xdr:twoCellAnchor>"]:e.type==="oneCell"?[`<xdr:oneCellAnchor>${D("from",e.from)}<xdr:ext cx="${f(e.ext.cx)}" cy="${f(e.ext.cy)}"/>`,"</xdr:oneCellAnchor>"]:[`<xdr:absoluteAnchor><xdr:pos x="${f(e.pos.x)}" y="${f(e.pos.y)}"/><xdr:ext cx="${f(e.ext.cx)}" cy="${f(e.ext.cy)}"/>`,"</xdr:absoluteAnchor>"]}function ve(e,t){return e.replace(/(<(\w+:)?spPr\b[^>]*>)([\s\S]*?)(<\/\2spPr>)/,(n,r,c,a,i)=>{const s=/<a:(?:prstGeom|custGeom)\b[\s\S]*?<\/a:(?:prstGeom|custGeom)>|<a:prstGeom\b[^>]*\/>/.exec(a)?.[0]??"",p=/<a:xfrm\b[\s\S]*?<\/a:xfrm>/.exec(a)?.[0]??"",u=/<a:(?:effectLst|effectDag|scene3d|sp3d|extLst)\b[\s\S]*$/.exec(a)?.[0]??"";return`${r}${p}${s}${t.fill?ae(t.fill):""}${t.line?ce(t.line):""}${u}${i}`})}function Pe(e,t){return e.replace(/(<(?:[\w]+:)?off\s+x=")-?\d+("\s+y=")-?\d+("\s*\/>\s*<(?:[\w]+:)?ext\s+cx=")\d+("\s+cy=")\d+(")/,(n,r,c,a,i,s)=>`${r}${f(t.x)}${c}${f(t.y)}${a}${f(t.cx)}${i}${f(t.cy)}${s}`)}function ke(e,t){const n=j("xdr:txBody",{...t,raw:void 0});return/<(?:\w+:)?txBody\b/.test(e)?e.replace(/<((?:\w+:)?)txBody\b[\s\S]*?<\/\1txBody>/,()=>n):e.replace(/<\/((?:\w+:)?)sp>\s*$/,r=>`${n}${r}`)}const G='<a:ext uri="{C183D7F6-B498-43B3-948B-1728B52AA6E4}"><adec:decorative xmlns:adec="http://schemas.microsoft.com/office/drawing/2017/decorative" val="1"/></a:ext>',Y=e=>`${e.descr?` descr="${k(e.descr)}"`:""}${e.title?` title="${k(e.title)}"`:""}`,E=e=>`<xdr:cNvPr id="${e.id}" name="${k(e.name??"")}"${Y(e)}${e.decorative?`><a:extLst>${G}</a:extLst></xdr:cNvPr>`:"/>"}`;function J(e,t){return e.replace(/<((?:\w+:)?)cNvPr\b([^>]*?)(?:\/>|>([\s\S]*?)<\/\1cNvPr>)/,(n,r,c,a="")=>{let i=c.replace(/\s(?:descr|title)="[^"]*"/g,"").replace(/\sname="[^"]*"/,` name="${k(t.name??"")}"`);i+=Y(t);let s=a.replace(/<a:ext uri="\{C183D7F6-B498-43B3-948B-1728B52AA6E4\}">[\s\S]*?<\/a:ext>/,"");return t.decorative&&(s=/<a:extLst>/.test(s)?s.replace("</a:extLst>",`${G}</a:extLst>`):`${s}<a:extLst>${G}</a:extLst>`),s=s.replace(/<a:extLst>\s*<\/a:extLst>/,""),s?`<${r}cNvPr${i}>${s}</${r}cNvPr>`:`<${r}cNvPr${i}/>`})}function W(e,t){return`<a:xfrm${`${e.rot?` rot="${Math.round(e.rot*6e4)}"`:""}${e.flipH?' flipH="1"':""}${e.flipV?' flipV="1"':""}`}><a:off x="${f(t.x)}" y="${f(t.y)}"/><a:ext cx="${f(t.cx)}" cy="${f(t.cy)}"/></a:xfrm>`}function Re(e){const t=Object.entries(e?.av??{}).map(([n,r])=>`<a:gd name="${x(n)}" fmla="val ${r}"/>`).join("");return`<a:prstGeom prst="${x(e?.prst??"rect")}"><a:avLst>${t}</a:avLst></a:prstGeom>`}function K(e){if(!e)return"";const t=(r,c)=>c?`<a:${r} idx="${c.idx??0}">${I(c.color)}</a:${r}>`:`<a:${r} idx="0"/>`,n=e.fontRef?`<a:fontRef idx="minor">${I(e.fontRef.color)}</a:fontRef>`:'<a:fontRef idx="minor"/>';return`<xdr:style>${t("lnRef",e.lnRef)}${t("fillRef",e.fillRef)}${t("effectRef",e.effectRef)}${n}</xdr:style>`}function Ce(e,t){const n=ie({fill:e.fill,line:e.line},"xdr:spPr",`${W(e,t)}${Re(e.geom)}`),r=e.text?j("xdr:txBody",{...e.text,raw:void 0}):"";if(e.kind==="connector")return`<xdr:cxnSp macro=""><xdr:nvCxnSpPr>${E(e)}<xdr:cNvCxnSpPr/></xdr:nvCxnSpPr>${n}${K(e.style)}</xdr:cxnSp>`;const c=e.kind==="textbox"?' txBox="1"':"";return`<xdr:sp macro="" textlink=""><xdr:nvSpPr>${E(e)}<xdr:cNvSpPr${c}/></xdr:nvSpPr>${n}${K(e.style)}${r}</xdr:sp>`}function Se(e,t){const n=e.crop,r=n?`<a:srcRect l="${Math.round((n.l??0)*1e5)}" t="${Math.round((n.t??0)*1e5)}" r="${Math.round((n.r??0)*1e5)}" b="${Math.round((n.b??0)*1e5)}"/>`:"";return`<xdr:pic><xdr:nvPicPr>${E(e)}<xdr:cNvPicPr><a:picLocks noChangeAspect="1"/></xdr:cNvPicPr></xdr:nvPicPr><xdr:blipFill><a:blip xmlns:r="${d.r}" r:embed="${x(e.embed)}"/>${r}<a:stretch><a:fillRect/></a:stretch></xdr:blipFill><xdr:spPr>${W(e,t)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic>`}function Ae(e){const t=n=>`<xdr:graphicFrame macro=""><xdr:nvGraphicFramePr>${E(e)}<xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic>${n}</a:graphic></xdr:graphicFrame>`;if(e.kind==="chartex"){const n=t(`<a:graphicData uri="${d.cx}"><cx:chart xmlns:cx="${d.cx}" xmlns:r="${d.r}" r:id="${x(e.rel)}"/></a:graphicData>`),r=se(e.model?.type);return`<mc:AlternateContent xmlns:mc="${d.mc}"><mc:Choice xmlns:${r}="${d[r]}" Requires="${r}">${n}</mc:Choice><mc:Fallback><xdr:sp macro="" textlink=""><xdr:nvSpPr><xdr:cNvPr id="0" name=""/><xdr:cNvSpPr><a:spLocks noTextEdit="1"/></xdr:cNvSpPr></xdr:nvSpPr><xdr:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr><xdr:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>This chart isn't available in your version of Excel.</a:t></a:r></a:p></xdr:txBody></xdr:sp></mc:Fallback></mc:AlternateContent>`}return t(`<a:graphicData uri="${d.c}"><c:chart xmlns:c="${d.c}" xmlns:r="${d.r}" r:id="${x(e.rel)}"/></a:graphicData>`)}function Ee(e,t){if(e.kind==="foreign")return e.raw;const n=e.touched?.names===!0;if(e.raw&&!e.moved&&!e.textEdited&&!e.formatEdited)return n?J(e.raw,e):e.raw;if(e.media&&e.raw)return we(e.raw,e.anchor);const[r,c]=be(e.anchor),a=e.clientData??"<xdr:clientData/>";let i;e.rawContent!==void 0?(i=e.moved&&e.kind!=="chart"&&e.kind!=="chartex"&&!e.smartArt?Pe(e.rawContent,t):e.rawContent,e.textEdited&&e.text&&(i=ke(i,e.text)),e.formatEdited&&(i=ve(i,e)),n&&(i=J(i,e))):e.kind==="picture"?i=Se(e,t):e.kind==="chart"||e.kind==="chartex"?i=Ae(e):i=Ce(e,t);const s=`${r}${i}${a}${c}`;return e.wrapped&&e.raw?e.raw.replace(/<((?:\w+:)?)(twoCellAnchor|oneCellAnchor|absoluteAnchor)\b[\s\S]*?<\/\1\2>/,()=>s):s}function Ve(e,t){let n=e.rootOpen??`<xdr:wsDr xmlns:xdr="${d.xdr}" xmlns:a="${d.a}">`;for(const[a,i]of[["xdr",d.xdr],["a",d.a]])new RegExp(`xmlns:${a}=`).test(n)||(n=n.replace(/>$/,` xmlns:${a}="${i}">`));const r=n.replace(/^<([^\s>]+)[\s\S]*$/,"</$1>");let c="";for(const a of e.objects){const i=a.kind==="foreign"?null:t(a);c+=Ee(a,i)}return`${M}${n}${c}${r}`}async function Xe(e,t){const n=e.zip?e:{zip:e},{zip:r}=n,c=R(t);if(!r.has(c))return null;const a=L(await r.bytes(c)).find(o=>o.type===fe.drawing||/\/drawing$/.test(o.type));if(!a)return null;const i=b(t,a.target);if(!r.has(i))return null;const s=R(i),p=r.has(s)?L(await r.bytes(s)):[],u=ge(await r.bytes(i),{path:i,rels:p});u.sheetRelId=a.id;const g=new Map(p.map(o=>[o.id,o])),h=async o=>{if(o.kind==="group"){for(const w of o.children??[])await h(w);return}if(o.kind==="chart"||o.kind==="chartex"){const w=g.get(o.rel);if(!w||(o.chartPath=b(i,w.target),!r.has(o.chartPath)))return;const y=await r.bytes(o.chartPath);try{o.model=o.kind==="chart"?oe(y):le(y)}catch($){o.modelError=$.message}const P=R(o.chartPath);r.has(P)&&(o.chartRels=L(await r.bytes(P)).map($=>({...$,path:$.targetMode==="External"?null:b(o.chartPath,$.target)})),o.loadRelBlob=async $=>{const Q=await n.zip.stream($.path),U=$.path.split(".").pop().toLowerCase(),T=await new Response(Q).blob();return T.type?T:new Blob([T],{type:_[U]??""})})}else if(o.kind==="picture"&&o.embed){const w=g.get(o.embed);if(!w)return;o.mediaPath=b(i,w.target),o.loadBlob=async()=>{const y=await n.zip.stream(o.mediaPath),P=o.mediaPath.split(".").pop().toLowerCase(),$=await new Response(y).blob();return $.type?$:new Blob([$],{type:_[P]??""})}}o.visual&&await h(o.visual)};for(const o of u.objects)o.kind!=="foreign"&&await h(o);return u}const Te=/<(?:legacyDrawing|legacyDrawingHF|drawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst)\b|<\/worksheet>/;function Ie(e,t){if(/<drawing\b/.test(e))return e;const n=Te.exec(e);return n?e.slice(0,n.index)+t+e.slice(n.index):e+t}function je(e,t){const n=e||ye([]);return n.includes(`Id="${t.id}"`)?n:n.replace("</Relationships>",`<Relationship Id="${x(t.id)}" Type="${x(t.type)}" Target="${x(t.target)}"/></Relationships>`)}function _e(e,t=[],n=[]){let r=e;for(const a of n)r=r.replace(new RegExp(`<Override\\b[^>]*PartName="${a.replace(/[.*+?^\${}()|[\]\\/]/g,"\\$&")}"[^>]*/>`),"");let c="";for(const a of t)a.partName?r.includes(`PartName="${a.partName}"`)||(c+=`<Override PartName="${x(a.partName)}" ContentType="${x(a.contentType)}"/>`):new RegExp(`<Default\\b[^>]*Extension="${a.extension}"`,"i").test(r)||(r=r.replace(/(<Types\b[^>]*>)/,`$1<Default Extension="${x(a.extension)}" ContentType="${x(a.contentType)}"/>`));return r.replace("</Types>",`${c}</Types>`)}export{Me as CONTENT_TYPE,_ as IMAGE_TYPES,fe as REL,Ie as ensureDrawingElement,He as extensionForType,_e as mergeContentTypes,je as mergeRelationship,ge as parseDrawing,L as parseRels,Xe as readSheetDrawing,ee as relativeTarget,R as relsPathOf,b as resolveTarget,Ve as writeDrawing,ye as writeRels};
|
|
1
|
+
import{child as l,children as ee}from"../io/xml-scan.js";import{escapeMarkup as x,xmlLiteralText as k}from"../io/xml-escape.js";import{relativeTarget as te,relsPathOf as R,resolveTarget as b}from"../io/package-paths.js";import{NS as d,XML_HEAD as M,parseColor as re,parseFill as ne,parseSpPr as N,parseTextBody as ae,parseXml as H,parseXfrm as V,toBool as X,toNum as m,writeColor as I,writeFill as ie,writeLine as ce,writeSpPr as se,writeTextBody as j}from"./dml.js";import{chartExRequires as oe}from"../charts/chartex.js";import{parseChart as le,parseChartEx as fe}from"./chart-model.js";const pe={drawing:`${d.r}/drawing`,chart:`${d.r}/chart`,image:`${d.r}/image`,chartEx:"http://schemas.microsoft.com/office/2014/relationships/chartEx",hyperlink:`${d.r}/hyperlink`},Me={drawing:"application/vnd.openxmlformats-officedocument.drawing+xml",chart:"application/vnd.openxmlformats-officedocument.drawingml.chart+xml",chartEx:"application/vnd.ms-office.chartex+xml"},_={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",tif:"image/tiff",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp",emf:"image/x-emf",wmf:"image/x-wmf"};function He(e){switch(e){case"image/jpeg":return"jpeg";case"image/gif":return"gif";case"image/bmp":return"bmp";case"image/tiff":return"tiff";case"image/svg+xml":return"svg";case"image/webp":return"webp";default:return"png"}}const C={twoCellAnchor:"twoCell",oneCellAnchor:"oneCell",absoluteAnchor:"absolute"},B=new Set(["sp","pic","cxnSp","grpSp","graphicFrame","contentPart"]);function O(e){if(e)return{col:m(l(e,"col")?.t,0),colOff:m(l(e,"colOff")?.t,0),row:m(l(e,"row")?.t,0),rowOff:m(l(e,"rowOff")?.t,0)}}function xe(e,t){const n={type:t};if(t==="twoCell")n.editAs=e.a.editAs??"twoCell",n.from=O(l(e,"from")),n.to=O(l(e,"to"));else if(t==="oneCell")n.from=O(l(e,"from"));else{const i=l(e,"pos");n.pos={x:m(i?.a.x,0),y:m(i?.a.y,0)}}const r=l(e,"ext");return r&&(n.ext={cx:m(r.a.cx,0),cy:m(r.a.cy,0)}),n}function v(e,t){const n=l(e,t),r=l(n,"cNvPr");return{id:m(r?.a.id,0),name:r?.a.name??"",descr:r?.a.descr,title:r?.a.title,hidden:X(r?.a.hidden,!1),...(l(r,"extLst")?.c??[]).some(i=>l(i,"decorative")&&l(i,"decorative").a.val!=="0")?{decorative:!0}:{}}}function S(e){if(e)return{idx:m(e.a.idx,0),color:re(e)}}function z(e){if(e)return{lnRef:S(l(e,"lnRef")),fillRef:S(l(e,"fillRef")),effectRef:S(l(e,"effectRef")),fontRef:S(l(e,"fontRef"))}}function de(e,t){const n=N(l(e,"spPr"),t)??{},r=X(l(l(e,"nvSpPr"),"cNvSpPr")?.a.txBox,!1),i=l(e,"txBody");return{kind:r?"textbox":"shape",...v(e,"nvSpPr"),xfrm:n.xfrm,rot:n.xfrm?.rot??0,flipH:n.xfrm?.flipH??!1,flipV:n.xfrm?.flipV??!1,geom:n.geom,fill:n.fill,line:n.line,style:z(l(e,"style")),text:ae(i,t),macro:e.a.macro,textlink:e.a.textlink}}function me(e,t){const n=N(l(e,"spPr"),t)??{};return{kind:"connector",...v(e,"nvCxnSpPr"),xfrm:n.xfrm,rot:n.xfrm?.rot??0,flipH:n.xfrm?.flipH??!1,flipV:n.xfrm?.flipV??!1,geom:n.geom,line:n.line,fill:n.fill,style:z(l(e,"style"))}}function q(e,t){const n=l(e,"blipFill"),r=l(n,"blip"),i=l(n,"srcRect"),a=N(l(e,"spPr"),t)??{},c=i?{l:m(i.a.l,0)/1e5,t:m(i.a.t,0)/1e5,r:m(i.a.r,0)/1e5,b:m(i.a.b,0)/1e5}:void 0;return{kind:"picture",...v(e,"nvPicPr"),embed:r?.a.embed,link:r?.a.link,crop:c,xfrm:a.xfrm,rot:a.xfrm?.rot??0,flipH:a.xfrm?.flipH??!1,flipV:a.xfrm?.flipV??!1,geom:a.geom,line:a.line}}function ue(e,t){const n=l(e,"grpSpPr"),r=V(l(n,"xfrm")),i=[];for(const a of e.c)if(B.has(a.n)){const c=A(a,t);c&&i.push(c)}else a.n==="AlternateContent"&&i.push(Y(a,t));return{kind:"group",...v(e,"nvGrpSpPr"),xfrm:r,rot:r?.rot??0,flipH:r?.flipH??!1,flipV:r?.flipV??!1,fill:ne(n),children:i}}function $e(e){const t=l(l(e,"graphic"),"graphicData"),n=l(t,"chart"),r=v(e,"nvGraphicFramePr"),i=V(l(e,"xfrm"));return n?{kind:/chartex/.test(t.a.uri??"")?"chartex":"chart",...r,xfrm:i,rel:n.a.id}:{kind:"unknown",...r,xfrm:i,uri:t?.a.uri}}function A(e,t){switch(e.n){case"sp":return de(e,t);case"cxnSp":return me(e,t);case"pic":return q(e,t);case"grpSp":return ue(e,t);case"graphicFrame":return $e(e);case"contentPart":return{kind:"unknown",rel:e.a.id};default:return null}}function Y(e,t){const n=l(e,"Choice"),r=l(e,"Fallback"),i=u=>u?.c.find(g=>B.has(g.n)),a=i(n),c=a?A(a,t):null;if(c&&c.kind!=="unknown")return c;const s=i(r),p=s?A(s,t):null;return F(c?{...c,visual:p}:{kind:"unknown",visual:p,...p?{id:p.id,name:p.name}:{}})}function F(e){if(e.kind!=="unknown"||e.visual?.kind!=="picture")return e;const t=e.uri??"";return/drawingml\/2006\/diagram/.test(t)||(e.media=/model3d/i.test(t)?"model3d":/audio|sound/i.test(t)?"audio":/video|movie|media/i.test(t)?"video":"media"),e}function he(e,t,n,r){const i=l(t,"Fallback");if(!e||e.visual||!i||i===n)return;const c=i.c.find(s=>C[s.n])?.c.find(s=>s.n==="pic");c&&(e.visual=q(c,r),F(e))}function we(e,t){return e.replace(/<((?:\w+:)?)(twoCellAnchor|oneCellAnchor|absoluteAnchor)\b[\s\S]*?<\/\1\2>/g,(n,r)=>{const i=(c,s)=>`<${r}${c}><${r}col>${s.col}</${r}col><${r}colOff>${f(s.colOff)}</${r}colOff><${r}row>${s.row}</${r}row><${r}rowOff>${f(s.rowOff)}</${r}rowOff></${r}${c}>`;let a=n;return t.from&&(a=a.replace(new RegExp(`<${r}from>[\\s\\S]*?</${r}from>`),()=>i("from",t.from))),t.to&&(a=a.replace(new RegExp(`<${r}to>[\\s\\S]*?</${r}to>`),()=>i("to",t.to))),t.ext&&(a=a.replace(new RegExp(`<${r}ext\\b[^>]*/>`),()=>`<${r}ext cx="${f(t.ext.cx)}" cy="${f(t.ext.cy)}"/>`)),t.pos&&(a=a.replace(new RegExp(`<${r}pos\\b[^>]*/>`),()=>`<${r}pos x="${f(t.pos.x)}" y="${f(t.pos.y)}"/>`)),a})}function ge(e,{path:t=null,rels:n=[]}={}){const r=H(e),i=r.root,a=[],c=(s,p)=>{const u=C[s.n],g=xe(s,u),h=s.c.find(y=>B.has(y.n)||y.n==="AlternateContent");let o;if(h?.n==="AlternateContent"?o=Y(h,r):h?o=A(h,r):o={kind:"unknown"},/drawing\/20(?:10|12)\/(?:time)?slicer/.test(o.uri??"")){a.push({kind:"foreign",raw:r.raw(p??s)});return}o.anchor=g,o.raw=r.raw(p??s),o.rawContent=h?r.raw(h):"";const w=l(s,"clientData");o.clientData=w?r.raw(w):void 0,o.wrapped=!!p,a.push(o)};for(const s of i.c)if(C[s.n])c(s,null);else if(s.n==="AlternateContent"){const p=l(s,"Choice")??l(s,"Fallback"),u=p?.c.find(g=>C[g.n]);u?(c(u,s),he(a[a.length-1],s,p,r)):a.push({kind:"foreign",raw:r.raw(s)})}else a.push({kind:"foreign",raw:r.raw(s)});return{path:t,rels:n,rootOpen:r.openTag(i),objects:a}}function L(e){const t=H(e);return ee(t.root,"Relationship").map(n=>({id:n.a.Id,type:n.a.Type,target:n.a.Target,targetMode:n.a.TargetMode}))}function ye(e){const t=e.map(n=>`<Relationship Id="${x(n.id)}" Type="${x(n.type)}" Target="${x(n.target)}"${n.targetMode?` TargetMode="${x(n.targetMode)}"`:""}/>`).join("");return`${M}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${t}</Relationships>`}const f=e=>Math.round(e);function D(e,t){return`<xdr:${e}><xdr:col>${t.col}</xdr:col><xdr:colOff>${f(t.colOff)}</xdr:colOff><xdr:row>${t.row}</xdr:row><xdr:rowOff>${f(t.rowOff)}</xdr:rowOff></xdr:${e}>`}function be(e){return e.type==="twoCell"?[`<xdr:twoCellAnchor${e.editAs&&e.editAs!=="twoCell"?` editAs="${x(e.editAs)}"`:""}>${D("from",e.from)}${D("to",e.to)}`,"</xdr:twoCellAnchor>"]:e.type==="oneCell"?[`<xdr:oneCellAnchor>${D("from",e.from)}<xdr:ext cx="${f(e.ext.cx)}" cy="${f(e.ext.cy)}"/>`,"</xdr:oneCellAnchor>"]:[`<xdr:absoluteAnchor><xdr:pos x="${f(e.pos.x)}" y="${f(e.pos.y)}"/><xdr:ext cx="${f(e.ext.cx)}" cy="${f(e.ext.cy)}"/>`,"</xdr:absoluteAnchor>"]}function ve(e,t){return e.replace(/(<(\w+:)?spPr\b[^>]*>)([\s\S]*?)(<\/\2spPr>)/,(n,r,i,a,c)=>{const s=/<a:(?:prstGeom|custGeom)\b[\s\S]*?<\/a:(?:prstGeom|custGeom)>|<a:prstGeom\b[^>]*\/>/.exec(a)?.[0]??"",p=/<a:xfrm\b[\s\S]*?<\/a:xfrm>/.exec(a)?.[0]??"",u=/<a:(?:effectLst|effectDag|scene3d|sp3d|extLst)\b[\s\S]*$/.exec(a)?.[0]??"";return`${r}${p}${s}${t.fill?ie(t.fill):""}${t.line?ce(t.line):""}${u}${c}`})}function Pe(e,t){return e.replace(/(<(?:[\w]+:)?off\s+x=")-?\d+("\s+y=")-?\d+("\s*\/>\s*<(?:[\w]+:)?ext\s+cx=")\d+("\s+cy=")\d+(")/,(n,r,i,a,c,s)=>`${r}${f(t.x)}${i}${f(t.y)}${a}${f(t.cx)}${c}${f(t.cy)}${s}`)}function ke(e,t){const n=j("xdr:txBody",{...t,raw:void 0});return/<(?:\w+:)?txBody\b/.test(e)?e.replace(/<((?:\w+:)?)txBody\b[\s\S]*?<\/\1txBody>/,()=>n):e.replace(/<\/((?:\w+:)?)sp>\s*$/,r=>`${n}${r}`)}const G='<a:ext uri="{C183D7F6-B498-43B3-948B-1728B52AA6E4}"><adec:decorative xmlns:adec="http://schemas.microsoft.com/office/drawing/2017/decorative" val="1"/></a:ext>',J=e=>`${e.descr?` descr="${k(e.descr)}"`:""}${e.title?` title="${k(e.title)}"`:""}`,E=e=>`<xdr:cNvPr id="${e.id}" name="${k(e.name??"")}"${J(e)}${e.decorative?`><a:extLst>${G}</a:extLst></xdr:cNvPr>`:"/>"}`;function W(e,t){return e.replace(/<((?:\w+:)?)cNvPr\b([^>]*?)(?:\/>|>([\s\S]*?)<\/\1cNvPr>)/,(n,r,i,a="")=>{let c=i.replace(/\s(?:descr|title)="[^"]*"/g,"").replace(/\sname="[^"]*"/,()=>` name="${k(t.name??"")}"`);c+=J(t);let s=a.replace(/<a:ext uri="\{C183D7F6-B498-43B3-948B-1728B52AA6E4\}">[\s\S]*?<\/a:ext>/,"");return t.decorative&&(s=/<a:extLst>/.test(s)?s.replace("</a:extLst>",()=>`${G}</a:extLst>`):`${s}<a:extLst>${G}</a:extLst>`),s=s.replace(/<a:extLst>\s*<\/a:extLst>/,""),s?`<${r}cNvPr${c}>${s}</${r}cNvPr>`:`<${r}cNvPr${c}/>`})}function K(e,t){return`<a:xfrm${`${e.rot?` rot="${Math.round(e.rot*6e4)}"`:""}${e.flipH?' flipH="1"':""}${e.flipV?' flipV="1"':""}`}><a:off x="${f(t.x)}" y="${f(t.y)}"/><a:ext cx="${f(t.cx)}" cy="${f(t.cy)}"/></a:xfrm>`}function Re(e){const t=Object.entries(e?.av??{}).map(([n,r])=>`<a:gd name="${x(n)}" fmla="val ${r}"/>`).join("");return`<a:prstGeom prst="${x(e?.prst??"rect")}"><a:avLst>${t}</a:avLst></a:prstGeom>`}function Q(e){if(!e)return"";const t=(r,i)=>i?`<a:${r} idx="${i.idx??0}">${I(i.color)}</a:${r}>`:`<a:${r} idx="0"/>`,n=e.fontRef?`<a:fontRef idx="minor">${I(e.fontRef.color)}</a:fontRef>`:'<a:fontRef idx="minor"/>';return`<xdr:style>${t("lnRef",e.lnRef)}${t("fillRef",e.fillRef)}${t("effectRef",e.effectRef)}${n}</xdr:style>`}function Ce(e,t){const n=se({fill:e.fill,line:e.line},"xdr:spPr",`${K(e,t)}${Re(e.geom)}`),r=e.text?j("xdr:txBody",{...e.text,raw:void 0}):"";if(e.kind==="connector")return`<xdr:cxnSp macro=""><xdr:nvCxnSpPr>${E(e)}<xdr:cNvCxnSpPr/></xdr:nvCxnSpPr>${n}${Q(e.style)}</xdr:cxnSp>`;const i=e.kind==="textbox"?' txBox="1"':"";return`<xdr:sp macro="" textlink=""><xdr:nvSpPr>${E(e)}<xdr:cNvSpPr${i}/></xdr:nvSpPr>${n}${Q(e.style)}${r}</xdr:sp>`}function Se(e,t){const n=e.crop,r=n?`<a:srcRect l="${Math.round((n.l??0)*1e5)}" t="${Math.round((n.t??0)*1e5)}" r="${Math.round((n.r??0)*1e5)}" b="${Math.round((n.b??0)*1e5)}"/>`:"";return`<xdr:pic><xdr:nvPicPr>${E(e)}<xdr:cNvPicPr><a:picLocks noChangeAspect="1"/></xdr:cNvPicPr></xdr:nvPicPr><xdr:blipFill><a:blip xmlns:r="${d.r}" r:embed="${x(e.embed)}"/>${r}<a:stretch><a:fillRect/></a:stretch></xdr:blipFill><xdr:spPr>${K(e,t)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic>`}function Ae(e){const t=n=>`<xdr:graphicFrame macro=""><xdr:nvGraphicFramePr>${E(e)}<xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic>${n}</a:graphic></xdr:graphicFrame>`;if(e.kind==="chartex"){const n=t(`<a:graphicData uri="${d.cx}"><cx:chart xmlns:cx="${d.cx}" xmlns:r="${d.r}" r:id="${x(e.rel)}"/></a:graphicData>`),r=oe(e.model?.type);return`<mc:AlternateContent xmlns:mc="${d.mc}"><mc:Choice xmlns:${r}="${d[r]}" Requires="${r}">${n}</mc:Choice><mc:Fallback><xdr:sp macro="" textlink=""><xdr:nvSpPr><xdr:cNvPr id="0" name=""/><xdr:cNvSpPr><a:spLocks noTextEdit="1"/></xdr:cNvSpPr></xdr:nvSpPr><xdr:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr><xdr:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>This chart isn't available in your version of Excel.</a:t></a:r></a:p></xdr:txBody></xdr:sp></mc:Fallback></mc:AlternateContent>`}return t(`<a:graphicData uri="${d.c}"><c:chart xmlns:c="${d.c}" xmlns:r="${d.r}" r:id="${x(e.rel)}"/></a:graphicData>`)}function Ee(e,t){if(e.kind==="foreign")return e.raw;const n=e.touched?.names===!0;if(e.raw&&!e.moved&&!e.textEdited&&!e.formatEdited)return n?W(e.raw,e):e.raw;if(e.media&&e.raw)return we(e.raw,e.anchor);const[r,i]=be(e.anchor),a=e.clientData??"<xdr:clientData/>";let c;e.rawContent!==void 0?(c=e.moved&&e.kind!=="chart"&&e.kind!=="chartex"&&!e.smartArt?Pe(e.rawContent,t):e.rawContent,e.textEdited&&e.text&&(c=ke(c,e.text)),e.formatEdited&&(c=ve(c,e)),n&&(c=W(c,e))):e.kind==="picture"?c=Se(e,t):e.kind==="chart"||e.kind==="chartex"?c=Ae(e):c=Ce(e,t);const s=`${r}${c}${a}${i}`;return e.wrapped&&e.raw?e.raw.replace(/<((?:\w+:)?)(twoCellAnchor|oneCellAnchor|absoluteAnchor)\b[\s\S]*?<\/\1\2>/,()=>s):s}function Ve(e,t){let n=e.rootOpen?.replace(/\/>$/,">")??`<xdr:wsDr xmlns:xdr="${d.xdr}" xmlns:a="${d.a}">`;for(const[a,c]of[["xdr",d.xdr],["a",d.a]])new RegExp(`xmlns:${a}=`).test(n)||(n=n.replace(/>$/,()=>` xmlns:${a}="${c}">`));const r=n.replace(/^<([^\s>]+)[\s\S]*$/,"</$1>");let i="";for(const a of e.objects){const c=a.kind==="foreign"?null:t(a);i+=Ee(a,c)}return`${M}${n}${i}${r}`}async function Xe(e,t){const n=e.zip?e:{zip:e},{zip:r}=n,i=R(t);if(!r.has(i))return null;const a=L(await r.bytes(i)).find(o=>o.type===pe.drawing||/\/drawing$/.test(o.type));if(!a)return null;const c=b(t,a.target);if(!r.has(c))return null;const s=R(c),p=r.has(s)?L(await r.bytes(s)):[],u=ge(await r.bytes(c),{path:c,rels:p});u.sheetRelId=a.id;const g=new Map(p.map(o=>[o.id,o])),h=async o=>{if(o.kind==="group"){for(const w of o.children??[])await h(w);return}if(o.kind==="chart"||o.kind==="chartex"){const w=g.get(o.rel);if(!w||(o.chartPath=b(c,w.target),!r.has(o.chartPath)))return;const y=await r.bytes(o.chartPath);try{o.model=o.kind==="chart"?le(y):fe(y)}catch($){o.modelError=$.message}const P=R(o.chartPath);r.has(P)&&(o.chartRels=L(await r.bytes(P)).map($=>({...$,path:$.targetMode==="External"?null:b(o.chartPath,$.target)})),o.loadRelBlob=async $=>{const U=await n.zip.stream($.path),Z=$.path.split(".").pop().toLowerCase(),T=await new Response(U).blob();return T.type?T:new Blob([T],{type:_[Z]??""})})}else if(o.kind==="picture"&&o.embed){const w=g.get(o.embed);if(!w)return;o.mediaPath=b(c,w.target),o.loadBlob=async()=>{const y=await n.zip.stream(o.mediaPath),P=o.mediaPath.split(".").pop().toLowerCase(),$=await new Response(y).blob();return $.type?$:new Blob([$],{type:_[P]??""})}}o.visual&&await h(o.visual)};for(const o of u.objects)o.kind!=="foreign"&&await h(o);return u}const Te=/<(?:legacyDrawing|legacyDrawingHF|drawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst)\b|<\/worksheet>/;function Ie(e,t){if(/<drawing\b/.test(e))return e;const n=Te.exec(e);return n?e.slice(0,n.index)+t+e.slice(n.index):e+t}function je(e,t){const n=e||ye([]);return n.includes(`Id="${t.id}"`)?n:n.replace("</Relationships>",()=>`<Relationship Id="${x(t.id)}" Type="${x(t.type)}" Target="${x(t.target)}"/></Relationships>`)}function _e(e,t=[],n=[]){let r=e;for(const a of n)r=r.replace(new RegExp(`<Override\\b[^>]*PartName="${a.replace(/[.*+?^\${}()|[\]\\/]/g,"\\$&")}"[^>]*/>`),"");let i="";for(const a of t)a.partName?r.includes(`PartName="${a.partName}"`)||(i+=`<Override PartName="${x(a.partName)}" ContentType="${x(a.contentType)}"/>`):new RegExp(`<Default\\b[^>]*Extension="${a.extension}"`,"i").test(r)||(r=r.replace(/(<Types\b[^>]*>)/,`$1<Default Extension="${x(a.extension)}" ContentType="${x(a.contentType)}"/>`));return r.replace("</Types>",()=>`${i}</Types>`)}export{Me as CONTENT_TYPE,_ as IMAGE_TYPES,pe as REL,Ie as ensureDrawingElement,He as extensionForType,_e as mergeContentTypes,je as mergeRelationship,ge as parseDrawing,L as parseRels,Xe as readSheetDrawing,te as relativeTarget,R as relsPathOf,b as resolveTarget,Ve as writeDrawing,ye as writeRels};
|
package/package.json
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ERR as _,ERR_BY_INDEX as V,XlError as T}from"../calc/values.js";import{compileCalc as k,PivotError as L}from"./engine.js";function Y(s){return s.fields.filter(t=>t.calcItems&&!t.removed).flatMap(t=>t.calcItems.map(e=>({field:t,item:e}))).sort((t,e)=>t.item.order-e.item.order)}const W=s=>s.fields.some(t=>t.calcItems?.length>0&&!t.removed),R=s=>/^[\p{L}_][\p{L}\p{N}_.]*$/u.test(s)?s:`'${s.replace(/'/g,"''")}'`,j=(s,t)=>R(s.labelOf(t));function U(s,t){const e=t.item??t.v,r=e.toLowerCase(),o=s.items.findIndex((n,i)=>s.labelOf(i).toLowerCase()===r);return o>=0||t.item===void 0||t.quoted||!/^\d+$/.test(e)?o:s.rank().indexOf(Number(e)-1)}function z(s,t,e,r=null){t.ensure();const o=[],n=f=>{if(f.item!==void 0&&f.v.toLowerCase()!==t.name.toLowerCase())throw new L("A calculated item can only use items of its own field: {name}",{name:f.v});const l=U(t,f);if(l<0)throw new L("The formula refers to an unknown item: {name}",{name:f.item??f.v});if(r!==null&&t.items[l]===r&&l>=t.items.length-t.calcItems.length)throw new L("The formula is not valid.");let u=o.indexOf(l);return u<0&&(u=o.push(l)-1),h=>h(u)},{fn:i}=k(e,s,n);return{fn:i,refs:o}}function Z(s,t,e){t.ensure();const r=[];try{k(e,s,n=>{const i=U(t,n);return i>=0&&r.push({token:n,id:i}),()=>0})}catch{return e}let o=e;for(const{token:n,id:i}of r.sort((f,l)=>l.token.start-f.token.start))o=`${o.slice(0,n.start)}${R(t.name)}[${j(t,i)}]${o.slice(n.end)}`;return o}function tt(s,t,e){const r=[];try{k(e,s,n=>(n.item!==void 0&&n.v.toLowerCase()===t.name.toLowerCase()&&!/^\d+$/.test(n.item)&&r.push(n),()=>0))}catch{return e}let o=e;for(const n of r.sort((i,f)=>f.start-i.start))o=`${o.slice(0,n.start)}${R(n.item)}${o.slice(n.end)}`;return o}class B{constructor(t,e){this.levels=t.levels.map((r,o)=>{const n=e.fields[t.fields[o]].items.length,i=new Map,f=new Map,l=Array.from(r.parents.subarray(0,r.count)),u=Array.from(r.items.subarray(0,r.count));return u.forEach((h,w)=>{i.set(l[w]*n+h,w),f.has(l[w])||f.set(l[w],[]),f.get(l[w]).push(w)}),{card:n,index:i,kids:f,parents:l,items:u,recorded:r.recorded,listed:r.count}})}child(t,e,r){const o=this.levels[t];return o.index.get(e*o.card+r)??-1}kidsOf(t,e){return this.levels[t].kids.get(e)??[]}add(t,e,r){const o=this.child(t,e,r);if(o>=0)return o;const n=this.levels[t],i=n.items.length;return n.items.push(r),n.parents.push(e),n.index.set(e*n.card+r,i),n.kids.has(e)||n.kids.set(e,[]),n.kids.get(e).push(i),i}grown(){return this.levels.map(t=>({parents:Int32Array.from(t.parents),items:Int32Array.from(t.items),count:t.items.length,recorded:t.recorded,listed:t.listed}))}}const H=4e5;function et(s,t,e,r,o){const n=Y(s).filter(({field:c})=>t.fields.includes(c.index)||e.fields.includes(c.index));if(n.length===0)return null;const i=[new B(t,s),new B(e,s)],f=[t,e],l=Array.from(r.row.subarray(0,r.count)),u=Array.from(r.col.subarray(0,r.count)),h=[new Map,new Map],w=(c,v,m)=>{[[h[0],c,v],[h[1],v,c]].forEach(([d,C,g])=>{d.has(C)||d.set(C,new Map),d.get(C).set(g,m)})};for(let c=0;c<r.count;c++)w(l[c],u[c],c);const O=c=>c.levels[c.levels.length-1]?.items.length??1,E=f.map(c=>c.fields.map(v=>o(v))),M=[];for(const{field:c,item:v}of n){const m=t.fields.includes(c.index)?0:1,d=i[m],C=f[m],g=C.fields.indexOf(c.index),D=c.items.length-c.calcItems.length+c.calcItems.indexOf(v);let A;try{A=z(s,c,v.formula,v.name)}catch(a){if(!(a instanceof L))throw a;A={refs:[],fn:()=>{throw _.NAME}}}const F={fn:A.fn,cells:[]};M.push(F);const G=c.items.length-c.calcItems.length,S=g===0?1:d.levels[g-1].items.length,X=E[m].slice(g+1),$=O(i[1-m]),N=$>0&&l.length+X.reduce((a,x)=>a*Math.max(1,x.length),S*$)<=H,P=(a,x)=>{const y=N?Array.from({length:$},(I,p)=>p):new Set(x.flatMap(I=>I<0?[]:[...h[m].get(I)?.keys()??[]]));for(const I of y){let p=h[m].get(a)?.get(I);p===void 0&&(p=l.length,l.push(m===0?a:I),u.push(m===0?I:a),w(l[p],u[p],p)),F.cells.push([p,A.refs.length?x.map(b=>b<0?-1:h[m].get(b)?.get(I)??-1):[]])}},q=(a,x,y)=>{if(a===C.k-1){P(x,y);return}const I=N?X[a-g]:new Set(y.flatMap(p=>p<0?[]:d.kidsOf(a+1,p).map(b=>d.levels[a+1].items[b])));for(const p of I)q(a+1,d.add(a+1,x,p),y.map(b=>b<0?-1:d.child(a+1,b,p)))};for(let a=0;a<S;a++){const x=A.refs.length?A.refs.map(y=>d.child(g,a,y)):d.kidsOf(g,a).filter(y=>d.levels[g].items[y]<G);!N&&!x.some(y=>y>=0)||q(g,d.add(g,a,D),x)}}return{rows:i[0].grown(),cols:i[1].grown(),cells:{row:Int32Array.from(l),col:Int32Array.from(u),count:l.length},steps:M}}function nt(s,t){for(const{fn:e,cells:r}of s)for(const[o,n]of r)for(const i of t)J(i,o,n,e)}function J(s,t,e,r){const{calcErrs:o}=s,n={cnt:s.cntMore,num:s.numMore},i=u=>{const h=s[u],w=n[u],O=u in n?null:s.err,E=o?.[u],M=r(v=>{const m=e[v];if(m<0||s.cnt[m]===0)return 0;const d=(E?.[m]??0)||(O?.[m]??0);if(d!==0)throw V[d-1];const C=h[m]+(w?.[m]??0);return Number.isFinite(C)?C:0});if(M instanceof T)throw M;const c=typeof M=="boolean"?Number(M):M;if(typeof c!="number")throw _.VALUE;if(!Number.isFinite(c))throw _.NUM;return c},f={},l={};for(const u of["cnt","num","sum","min","max","prod","mean"])if(s[u]!==null)try{f[u]=i(u)}catch(h){if(!(h instanceof T))throw h;l[u]=h.index+1}s.setCalculated(t,f,l)}export{z as compileItem,Z as fileFormula,W as hasCalcItems,j as itemName,et as placeCalcItems,nt as solveCalcItems,Y as solveOrder,tt as typedFormula};
|
package/pivot/engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{withNoDataItems as Zt}from"../slicers/pivot-file.js";import{dateOptionFlags as te}from"../slicers/date-filters.js";import{BOOL as at,CHUNK_BITS as Ct,CHUNK_MASK as Tt,EMPTY as K,ERR as ct,ERRORS as Dt,KIND_MASK as Ft,NUM as B,STR as Z}from"../core/sheet.js";import{formatGeneral as St,getFormatter as Vt,partsToSerial as ee,serialToParts as pt}from"../core/numfmt.js";import{MAX_COLS as se,MAX_ROWS as ne}from"../core/address.js";import{compareText as Ut,ERR as U,ERR_BY_INDEX as Rt,numberToText as re,XlError as $}from"../calc/values.js";import{FUNCS as oe}from"../calc/functions/registry.js";import"../calc/functions/index.js";import{t as G}from"../i18n/index.js";const L=-2,Ke=["sum","count","average","max","min","product","countNums","stdDev","stdDevp","var","varp"],kt={sum:"Sum",count:"Count",average:"Average",max:"Max",min:"Min",product:"Product",countNums:"Count Numbers",stdDev:"StdDev",stdDevp:"StdDevp",var:"Var",varp:"Varp"},le={...kt,countNums:"Count"};function Lt(c,t){switch(c){case"count":case"countNums":return G("pivot|Count of {field}",{field:t});case"average":return G("pivot|Average of {field}",{field:t});case"max":return G("pivot|Max of {field}",{field:t});case"min":return G("pivot|Min of {field}",{field:t});case"product":return G("pivot|Product of {field}",{field:t});case"stdDev":return G("pivot|StdDev of {field}",{field:t});case"stdDevp":return G("pivot|StdDevp of {field}",{field:t});case"var":return G("pivot|Var of {field}",{field:t});case"varp":return G("pivot|Varp of {field}",{field:t});default:return G("pivot|Sum of {field}",{field:t})}}const je=[["normal","No Calculation"],["percentOfTotal","% of Grand Total"],["percentOfCol","% of Column Total"],["percentOfRow","% of Row Total"],["percent","% Of"],["percentOfParentRow","% of Parent Row Total"],["percentOfParentCol","% of Parent Column Total"],["percentOfParent","% of Parent Total"],["difference","Difference From"],["percentDiff","% Difference From"],["runTotal","Running Total In"],["percentOfRunningTotal","% Running Total In"],["rankAscending","Rank Smallest to Largest"],["rankDescending","Rank Largest to Smallest"],["index","Index"]],ie=new Set(["percent","percentOfParent","difference","percentDiff","runTotal","percentOfRunningTotal","rankAscending","rankDescending"]),Ye=c=>ie.has(c),Xe=c=>c==="percent"||c==="difference"||c==="percentDiff",ae=new Set(["percentOfTotal","percentOfCol","percentOfRow","percent","percentOfParentRow","percentOfParentCol","percentOfParent","percentDiff","percentOfRunningTotal"]),Qe=["captionEqual","captionNotEqual","captionBeginsWith","captionNotBeginsWith","captionEndsWith","captionNotEndsWith","captionContains","captionNotContains","captionGreaterThan","captionGreaterThanOrEqual","captionLessThan","captionLessThanOrEqual","captionBetween","captionNotBetween"],ze=["valueEqual","valueNotEqual","valueGreaterThan","valueGreaterThanOrEqual","valueLessThan","valueLessThanOrEqual","valueBetween","valueNotBetween"],E={NONE:0,PAGE_LABEL:1,PAGE_VALUE:2,CORNER:3,HEADER_BLANK:4,COL_CAPTION:5,ROW_CAPTION:6,COL_ITEM:7,COL_SUBTOTAL:8,COL_GRAND:9,DATA_HEADER:10,ROW_ITEM:11,ROW_PARENT:12,ROW_SUBTOTAL:13,ROW_GRAND:14,DATA:15,DATA_PARENT:16,DATA_SUBTOTAL:17,DATA_GRAND_ROW:18,DATA_GRAND_COL:19,PLACEHOLDER:20},X=0,lt=1,st=2,mt=3,Je={ITEM:X,SUBTOTAL:lt,GRAND:st,BLANK:mt},Pt=1<<23,ce=1<<24,xt="";class S extends Error{constructor(t,e){super(G(t,e))}}function ut(c){if(c==null)return"blank";switch(typeof c){case"number":return`n${c}`;case"string":return`s${c.toLowerCase()}`;case"boolean":return c?"b1":"b0";default:return`e${c.code}`}}const Bt=c=>c===null?4:typeof c=="number"?0:typeof c=="string"?1:typeof c=="boolean"?2:3,ue=[["sun","mon","tue","wed","thu","fri","sat"],["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],["january","february","march","april","may","june","july","august","september","october","november","december"]].map(c=>new Map(c.map((t,e)=>[t,e])));function fe(c){let t=ue,e=!1;for(const s of c){if(typeof s!="string")continue;e=!0;const n=s.toLowerCase();if(t=t.filter(o=>o.has(n)),t.length===0)return null}return e?t[0]:null}const $t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Gt=[31,29,31,30,31,30,31,31,30,31,30,31],he=["seconds","minutes","hours","days","months","quarters","years"],de={seconds:"Seconds",minutes:"Minutes",hours:"Hours",days:"Days",months:"Months",quarters:"Quarters",years:"Years"};function pe(c,t){let e=0;for(let s=0;s<c-1;s++)e+=Gt[s];return e+t-1}function me(c,t,e){switch(c){case"years":{const s=[];for(let n=t;n<=e;n++)s.push(String(n));return s}case"quarters":return["Qtr1","Qtr2","Qtr3","Qtr4"];case"months":return $t;case"days":{const s=[];return Gt.forEach((n,o)=>{for(let r=1;r<=n;r++)s.push(`${r}-${$t[o]}`)}),s}case"hours":{const s=[];for(let n=0;n<24;n++)s.push(`${n%12===0?12:n%12} ${n<12?"AM":"PM"}`);return s}default:{const s=[];for(let n=0;n<60;n++)s.push(`:${n<10?"0":""}${n}`);return s}}}function we(c,t,e){switch(c){case"years":return t.year-e;case"quarters":return Math.floor((t.month-1)/3);case"months":return t.month-1;case"days":return pe(t.month,t.day);case"hours":return Math.floor(t.ms/36e5);case"minutes":return Math.floor(t.ms/6e4)%60;default:return Math.floor(t.ms/1e3)%60}}class ft{constructor(t,e,s){this.cache=t,this.index=e,this.name=s,this.numFmt="General",this.isDate=!1,this.kinds=null,this.uniformKind=K,this.nums=null,this.strs=null,this.shared=null,this.rawIds=null,this.ids=null,this.items=null,this.group=null,this.base=-1,this.par=-1,this.formula=null,this.calc=null,this.removed=!1,this.xml=null,this._keys=null,this._rank=null}get isVirtual(){return this.base>=0||this.formula!==null}get isCalculated(){return this.formula!==null}reset(){this.shared=null,this.rawIds=null,this.invalidate()}invalidate(){this.ids=null,this.items=null,this._keys=null,this._rank=null}ensureRaw(){if(this.rawIds!==null)return this;if(this.base>=0){const l=this.cache.fields[this.base].ensureRaw();return this.rawIds=l.rawIds,this.shared=l.shared,this}const t=this.cache.recordCount,e=new Int32Array(t),s=[],{kinds:n,nums:o,strs:r}=this;if(r!==null)ye(this.cache,r,null,null,t,e,s);else if(o!==null&&n===null&&this.uniformKind===B){const l=new Map;let i=NaN,u=-1;for(let f=0;f<t;f++){const w=o[f];if(w!==i){let p=l.get(w);p===void 0&&(p=s.length,s.push(w),l.set(w,p)),i=w,u=p}e[f]=u}}else n!==null?Ae(this.cache,n,o,t,e,s):t>0&&s.push(null);return this.rawIds=e,this.shared=s,this}ensure(){if(this.ids!==null)return this;if(this.ensureRaw(),this.group===null)return this.ids=this.rawIds,this.items=this.shared,this;const{map:t,labels:e}=be(this),s=this.rawIds,n=s.length,o=new Int32Array(n);for(let r=0;r<n;r++)o[r]=t[s[r]];return this.ids=o,this.items=e,this.groupMap=t,this}ensureColumn(){if(this.nums!==null||this.strs!==null||this.rawIds===null)return this;if(this.base>=0)return this;const t=this.rawIds.length,e=new Uint8Array(t),s=new Float64Array(t),n=this.rawIds,o=this.shared,r=new Uint8Array(o.length),l=new Float64Array(o.length);o.forEach((i,u)=>{typeof i=="number"?(r[u]=B,l[u]=i):typeof i=="string"?r[u]=Z:typeof i=="boolean"?(r[u]=at,l[u]=i?1:0):i instanceof $&&(r[u]=ct,l[u]=i.index)});for(let i=0;i<t;i++){const u=n[i];e[i]=r[u],s[i]=l[u]}return this.kinds=e,this.nums=s,this}get keyIndex(){if(this._keys===null){this.ensure();const t=new Map;this.items.forEach((e,s)=>{const n=ut(e);t.has(n)||t.set(n,s)}),this._keys=t}return this._keys}keyOf(t){return ut(this.items[t])}labelOf(t){return this.labelOfValue(this.items[t])}labelOfValue(t){return t==null?"(blank)":typeof t=="string"?t:typeof t=="number"?this.numFmt!=="General"?Vt(this.numFmt).number(t):St(t):typeof t=="boolean"?t?"TRUE":"FALSE":t.code}rank(){if(this._rank!==null)return this._rank;this.ensure();const{items:t}=this,e=new Int32Array(t.length);if(this.group!==null&&this.group.kind!=="discrete")for(let s=0;s<e.length;s++)e[s]=s;else{const s=fe(t),n=Array.from(t.keys());n.sort((o,r)=>ge(t[o],t[r],s)),n.forEach((o,r)=>{e[o]=r})}return this._rank=e,e}}function ge(c,t,e){const s=Bt(c),n=Bt(t);return s!==n?s-n:s===0?c-t:s===1?e!==null?e.get(c.toLowerCase())-e.get(t.toLowerCase()):Ut(c,t):s===2?c===t?0:c?1:-1:s===3?c.index-t.index:0}function ye(c,t,e,s,n,o,r){let l=-1;for(let f=0;f<n;f++)t[f]>l&&(l=t[f]);const i=new Int32Array(l+1).fill(-1),u=new Map;for(let f=0;f<n;f++){const w=t[f];let p=i[w];if(p<0){const h=c.getString(w),a=h.toLowerCase();p=u.get(a),p===void 0&&(p=r.length,r.push(h),u.set(a,p)),i[w]=p}o[f]=p}}function Ae(c,t,e,s,n,o){const r=new Map,l=new Map,i=new Map,u=new Map;let f=-1;for(let w=0;w<s;w++){const p=t[w];let h;if(p===B){const a=e[w];h=r.get(a),h===void 0&&(h=o.length,o.push(a),r.set(a,h))}else if(p===Z){const a=e[w];if(h=i.get(a),h===void 0){const d=c.getString(a),m=d.toLowerCase();h=l.get(m),h===void 0&&(h=o.length,o.push(d),l.set(m,h)),i.set(a,h)}}else if(p===K)f<0&&(f=o.length,o.push(null)),h=f;else{const a=p*100+e[w];h=u.get(a),h===void 0&&(h=o.length,o.push(p===at?e[w]!==0:Rt[e[w]]??U.NA),u.set(a,h))}n[w]=h}}function be(c){const t=c.group,e=c.shared,s=new Int32Array(e.length);if(t.kind==="date"){const l=pt(t.start),i=pt(t.end),u=`<${Wt(t.start)}`,f=`>${Wt(t.end+1)}`,w=me(t.part,l.year,i.year);let p=[u,...w,f];t.labels&&t.labels.length===p.length&&(p=t.labels);for(let h=0;h<e.length;h++){const a=e[h];typeof a!="number"||a<t.start?s[h]=0:a>=t.end+1?s[h]=p.length-1:s[h]=1+we(t.part,pt(a),l.year)}return{map:s,labels:p}}if(t.kind==="bins"){const{start:l,end:i,interval:u}=t,f=Math.max(1,Math.ceil((i-l)/u-1e-9)),w=[`<${bt(l)}`];for(let h=0;h<f;h++){const a=l+h*u,d=t.integer?Math.max(a+u-1,h===f-1?i:0):a+u;w.push(`${bt(a)}-${bt(d)}`)}w.push(`>${bt(i)}`);const p=t.labels&&t.labels.length===w.length?t.labels:w;for(let h=0;h<e.length;h++){const a=e[h];typeof a!="number"||a<l?s[h]=0:a>i?s[h]=f+1:s[h]=1+Math.min(f-1,Math.floor((a-l)/u+1e-9))}return{map:s,labels:p}}const n=t.groups.map(l=>l.name),o=new Map;t.groups.forEach((l,i)=>{for(const u of l.keys)o.set(u,i)});const r=new Map;for(let l=0;l<e.length;l++){const i=ut(e[l]);let u=o.get(i);u===void 0&&(u=r.get(i),u===void 0&&(u=n.length,n.push(e[l]),r.set(i,u))),s[l]=u}return{map:s,labels:n}}const bt=c=>re(Number(c.toPrecision(12)));function Wt(c){const t=pt(c);return`${t.month}/${t.day}/${t.year}`}class ve{constructor(){this.list=[],this.index=new Map}get size(){return this.list.length}get(t){return this.list[t]??""}add(t){let e=this.index.get(t);return e===void 0&&(e=this.list.length,this.list.push(t),this.index.set(t,e)),e}}function _e(c,t,e,s,n,o){const r=c.columns[t];if(r===void 0)return;const l=e+s;for(let i=e>>>Ct;i<=l-1>>>Ct;i++){const u=r[i];if(u===void 0)continue;const f=i<<Ct,w=Math.max(e,f)&Tt,p=Math.min(l-1,f+Tt)&Tt,h=f-e,a=u.kinds,d=u.values;for(let m=w;m<=p;m++)n[h+m]=a[m]&Ft,o[h+m]=d[m]}}class gt{constructor(){this.fields=[],this.recordCount=0,this.strings=new ve,this.source=null,this.generation=0,this.xml=null,this.id=0,this.needsRefresh=!1}getString(t){return this.strings.get(t)}field(t){if(typeof t=="number")return this.fields[t];const e=String(t).toLowerCase();return this.fields.find(s=>s.name.toLowerCase()===e&&!s.removed)}fieldIndex(t){if(typeof t=="number")return t;const e=this.field(t);if(!e)throw new S("Unknown field: {name}",{name:t});return e.index}static fromSheet(t,e,s){const n=new gt;return n.strings=t.strings,n.source={type:"range",book:t,sheet:e,range:s},n.refresh(),n}static fromTable(t,e){const s=new gt;return s.strings=t.strings,s.source={type:"table",book:t,table:e},s.refresh(),s}static fromRows(t,e){const s=new gt,n=e.length;return s.recordCount=n,t.forEach((o,r)=>{const l=new Uint8Array(n),i=new Float64Array(n);for(let f=0;f<n;f++){const w=e[f][r];typeof w=="number"?(l[f]=B,i[f]=w):typeof w=="string"?(l[f]=Z,i[f]=s.strings.add(w)):typeof w=="boolean"?(l[f]=at,i[f]=w?1:0):w instanceof $&&(l[f]=ct,i[f]=w.index)}const u=new ft(s,r,o);Ht(u,l,i,n),s.fields.push(u)}),s}static fromColumns(t,e,s){const n=new gt;return s&&(n.strings=s),n.recordCount=e,t.forEach((o,r)=>{const l=new ft(n,r,o.name);l.kinds=o.kinds??null,l.nums=o.nums??null,l.strs=o.strs??null,l.uniformKind=o.strs?Z:o.kinds?K:B,o.numFmt&&qt(l,o.numFmt),n.fields.push(l)}),n}refresh(){const t=this.source;if(t===null){for(const p of this.fields)p.invalidate();return this.generation++,!1}const{book:e}=t;this.strings=e.strings;let s,n,o,r,l;if(t.type==="table"){const p=t.table;s=p.sheet??e.sheets[p.sheetIndex],n=p.r0,o=p.c0,r=p.r1-(p.totalsRows??0),l=p.c1}else{if({sheet:s}=t,typeof s=="string"&&(s=e.sheets.find(p=>p.name===t.sheet)),!s)throw new S("The PivotTable source sheet no longer exists.");({r0:n,c0:o,r1:r,c1:l}=t.range),r=Math.min(r,s.maxRow),l=Math.min(l,s.maxCol)}if(r<=n)throw new S("The PivotTable source needs a header row and at least one row of data.");const i=r-n,u=new Map,f=[];for(let p=o;p<=l;p++){const h=Ce(e,s,n,p);if(h==="")throw new S("The PivotTable field name is not valid: every source column needs a header.");const a=h.toLowerCase(),d=(u.get(a)??0)+1;u.set(a,d),f.push(d>1?`${h}${d}`:h)}const w=new Map(this.fields.filter(p=>!p.isVirtual).map(p=>[p.name.toLowerCase(),p]));this.recordCount=i,f.forEach((p,h)=>{let a=w.get(p.toLowerCase());a?w.delete(p.toLowerCase()):(a=new ft(this,this.fields.length,p),this.fields.push(a));const d=o+h,m=new Uint8Array(i),A=new Float64Array(i);_e(s,d,n+1,i,m,A),Ht(a,m,A,i),a.removed=!1,a.reset();for(let g=0;g<i;g++)if(m[g]!==K){qt(a,e.styles.get(s.style(n+1+g,d)).numFmt);break}});for(const p of w.values())p.removed=!0,p.kinds=null,p.nums=null,p.strs=null,p.uniformKind=K,p.reset();for(const p of this.fields)p.isVirtual&&p.reset();return this._rescaleGroups(),this.generation++,this.needsRefresh=!1,!0}_rescaleGroups(){for(const t of this.fields){const e=t.group;if(t.base>=0||t.removed||e===null||e.kind==="discrete"||!(e.autoStart||e.autoEnd))continue;let s;try{s=this._numericRange(t)}catch{continue}for(let n=t;n;n=n.par>=0?this.fields[n.par]:null){const o=n.group;o.autoStart&&(o.start=e.kind==="date"?Math.floor(s.min):s.min),o.autoEnd&&(o.end=e.kind==="date"?Math.floor(s.max):s.max),o.labels=void 0}}}addCalculatedField(t,e){const s=new ft(this,this.fields.length,this._uniqueName(t));return s.formula=e.replace(/^\s*=\s*/,""),s.calc=Nt(s.formula,this),this.fields.push(s),s.index}updateCalculatedField(t,e){const s=this.fields[t],n=e.replace(/^\s*=\s*/,"");s.calc=Nt(n,this),s.formula=n,this.generation++}_uniqueName(t){let e=t,s=2;for(;this.fields.some(n=>n.name.toLowerCase()===e.toLowerCase());)e=`${t}${s++}`;return e}_numericRange(t){t.ensureRaw();let e=1/0,s=-1/0,n=!0;for(const o of t.shared){if(typeof o!="number")throw new S("Cannot group that selection.");o<e&&(e=o),o>s&&(s=o),Number.isInteger(o)||(n=!1)}if(e===1/0)throw new S("Cannot group that selection.");return{min:e,max:s,integer:n}}groupDates(t,e,{start:s,end:n}={}){const o=this.fields[t];if(o.isCalculated||o.base>=0)throw new S("Cannot group that selection.");const{min:r,max:l}=this._numericRange(o),i=he.filter(p=>e.includes(p));if(i.length===0)throw new S("Choose at least one grouping unit.");this.ungroup(t);const u={start:s??Math.floor(r),end:n??Math.floor(l)};o.group={kind:"date",part:i[0],...u,autoStart:s===void 0,autoEnd:n===void 0},o.invalidate();const f=[t];let w=o;for(const p of i.slice(1)){const h=new ft(this,this.fields.length,this._uniqueName(de[p]));h.base=t,h.group={kind:"date",part:p,...u,autoStart:s===void 0,autoEnd:n===void 0},this.fields.push(h),w.par=h.index,w=h,f.unshift(h.index)}return f}groupNumbers(t,{start:e,end:s,interval:n=10}={}){const o=this.fields[t];if(o.isCalculated||o.base>=0)throw new S("Cannot group that selection.");if(!(n>0))throw new S("The grouping interval must be greater than zero.");const{min:r,max:l,integer:i}=this._numericRange(o);this.ungroup(t);const u=e??r,f=s??l;if(f<=u)throw new S("The ending value must be greater than the starting value.");return o.group={kind:"bins",start:u,end:f,interval:n,integer:i&&Number.isInteger(u)&&Number.isInteger(n),autoStart:e===void 0,autoEnd:s===void 0},o.invalidate(),t}groupText(t,e,s){const n=this.fields[t];if(n.isCalculated)throw new S("Cannot group that selection.");n.ensureRaw();let o=n.par>=0?this.fields[n.par]:null;if(o&&o.group?.kind!=="discrete")throw new S("Cannot group that selection.");return o?(o.group.groups.push(...e),o.invalidate(),o.index):(o=new ft(this,this.fields.length,this._uniqueName(s??`${n.name}2`)),o.base=t,o.group={kind:"discrete",groups:e.map(r=>({name:r.name,keys:[...r.keys]}))},this.fields.push(o),n.par=o.index,o.index)}ungroup(t){const e=this.fields[t];if(e.base>=0&&e.group?.kind==="discrete"){this.fields[e.base].par=-1,e.removed=!0,e.group={kind:"discrete",groups:[]},e.invalidate();return}e.group=null,e.invalidate();let s=e.par;for(e.par=-1;s>=0;){const n=this.fields[s];n.removed=!0,s=n.par,n.par=-1}}}function qt(c,t){c.numFmt=t??"General";try{c.isDate=c.numFmt!=="General"&&Vt(c.numFmt).isDate===!0}catch{c.isDate=!1}}function Ce(c,t,e,s){const n=t.kind(e,s)&Ft,o=t.value(e,s);return n===Z?c.strings.get(o).trim():n===B?St(o):n===at?o?"TRUE":"FALSE":n===ct?Dt[o]??"":""}function Ht(c,t,e,s){let n=0,o=0;for(let r=0;r<s;r++){const l=t[r];l===B?n++:l===Z&&o++}if(c.strs=null,c.kinds=null,c.nums=null,n===s&&s>0)c.uniformKind=B,c.nums=e;else if(o===s&&s>0){c.uniformKind=Z;const r=new Int32Array(s);for(let l=0;l<s;l++)r[l]=e[l];c.strs=r}else c.uniformKind=K,c.kinds=t,c.nums=e}const Te=["<=",">=","<>","+","-","*","/","^","%","(",")",",","=","<",">","&"];function Re(c){const t=[];let e=0;for(;e<c.length;){const s=c[e];if(s<=" ")e++;else if(s>="0"&&s<="9"||s==="."&&c[e+1]>="0"&&c[e+1]<="9"){const n=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(c.slice(e));t.push({t:"num",v:Number(n[0])}),e+=n[0].length}else if(s==="'"||s==='"'){let n=e+1,o="";for(;;){if(n>=c.length)throw new S("The formula has an unmatched quote.");if(c[n]===s){if(c[n+1]!==s)break;n++}o+=c[n++]}t.push({t:s==="'"?"name":"str",v:o}),e=n+1}else if(/[\p{L}_\\]/u.test(s)){const n=/^[\p{L}\p{N}_.\\]+/u.exec(c.slice(e));t.push({t:"name",v:n[0],bare:!0}),e+=n[0].length}else{const n=Te.find(o=>c.startsWith(o,e));if(!n)throw new S("The formula has an unexpected character: {char}",{char:s});t.push({t:"op",v:n}),e+=n.length}}return t}const Kt=c=>c instanceof $?c:null,F=c=>{if(typeof c=="number")return c;if(typeof c=="boolean")return c?1:0;if(c===null)return 0;if(c instanceof $)throw c;const t=Number(c);if(typeof c=="string"&&c.trim()!==""&&!Number.isNaN(t))return t;throw U.VALUE},jt={IF:c=>{const t=c[0]();if(Kt(t))throw t;return(typeof t=="number"?t!==0:t===!0)?c[1]?c[1]():!0:c[2]?c[2]():!1},IFERROR:c=>{try{const t=c[0]();return Kt(t)?c[1]():t}catch(t){if(t instanceof $)return c[1]();throw t}},AND:c=>c.every(t=>F(t())!==0),OR:c=>c.some(t=>F(t())!==0),NOT:c=>F(c[0]())===0,SUM:c=>c.reduce((t,e)=>t+F(e()),0),MIN:c=>Math.min(...c.map(t=>F(t()))),MAX:c=>Math.max(...c.map(t=>F(t()))),AVERAGE:c=>c.reduce((t,e)=>t+F(e()),0)/c.length,COUNT:c=>c.length,TRUE:()=>!0,FALSE:()=>!1};function Nt(c,t){const e=Re(c);let s=0;const n=new Set,o=g=>e[s]?.t==="op"&&e[s].v===g,r=()=>new S("The formula is not valid."),l=g=>{const y=t.fields.find(b=>b.name.toLowerCase()===g.v.toLowerCase()&&!b.isCalculated),v=t.fields.find(b=>b.name.toLowerCase()===g.v.toLowerCase()&&b.isCalculated);if(v){for(const b of v.calc.refs)n.add(b);return b=>v.calc.fn(b)}if(!y)throw new S("The formula refers to an unknown field: {name}",{name:g.v});n.add(y.index);const _=y.index;return b=>b(_)},i=()=>{const g=e[s];if(!g)throw r();if(g.t==="num"){s++;const y=g.v;return()=>y}if(g.t==="str"){s++;const y=g.v;return()=>y}if(g.t==="name"){if(s++,g.bare&&o("(")){s++;const y=[];if(!o(")"))for(y.push(a());o(",");)s++,y.push(a());if(!o(")"))throw r();return s++,d(g.v.toUpperCase(),y)}if(g.bare&&m.has(g.v.toUpperCase())&&!t.field(g.v)){const y=jt[g.v.toUpperCase()];return()=>y([])}return l(g)}if(o("(")){s++;const y=a();if(!o(")"))throw r();return s++,y}throw r()},u=()=>{let g=i();for(;o("%");){s++;const y=g;g=v=>F(y(v))/100}return g},f=()=>{if(o("-")){s++;const g=f();return y=>-F(g(y))}return o("+")?(s++,f()):u()},w=()=>{let g=f();for(;o("^");){s++;const y=g,v=f();g=_=>{const b=F(y(_))**F(v(_));if(!Number.isFinite(b))throw U.NUM;return b}}return g},p=()=>{let g=w();for(;o("*")||o("/");){const y=e[s++].v,v=g,_=w();g=y==="*"?b=>F(v(b))*F(_(b)):b=>{const x=F(_(b));if(x===0)throw U.DIV0;return F(v(b))/x}}return g},h=()=>{let g=p();for(;o("+")||o("-");){const y=e[s++].v,v=g,_=p();g=y==="+"?b=>F(v(b))+F(_(b)):b=>F(v(b))-F(_(b))}return g},a=()=>{let g=h();for(;e[s]?.t==="op"&&["=","<>","<",">","<=",">="].includes(e[s].v);){const y=e[s++].v,v=g,_=h();g=b=>{const x=F(v(b)),R=F(_(b));switch(y){case"=":return x===R;case"<>":return x!==R;case"<":return x<R;case">":return x>R;case"<=":return x<=R;default:return x>=R}}}return g},d=(g,y)=>{const v=jt[g];if(v)return b=>v(y.map(x=>()=>x(b)));const _=oe.get(g);if(!_||_.kind!=="lift")throw new S("The formula uses a function a calculated field can't call: {name}",{name:g});if(y.length<_.min||y.length>_.max)throw r();return b=>{const x=y.map(R=>R(b));for(const R of x)if(R instanceof $)throw R;return _.fn(...x)}},m=new Set(["TRUE","FALSE"]),A=a();if(s<e.length)throw r();return{fn:A,refs:[...n]}}const ke={sum:"sum",average:"sum",count:"",countNums:"",max:"mm",min:"mm",product:"prod",stdDev:"var",stdDevp:"var",var:"var",varp:"var"};class Et{constructor(t,e){this.size=t,this.cnt=new Int32Array(t),this.num=new Int32Array(t),this.sum=e.sum?new Float64Array(t):null,this.min=e.mm?new Float64Array(t).fill(1/0):null,this.max=e.mm?new Float64Array(t).fill(-1/0):null,this.prod=e.prod?new Float64Array(t).fill(1):null,this.mean=e.var?new Float64Array(t):null,this.m2=e.var?new Float64Array(t):null,this.err=null}merge(t,e,s){const n=e.cnt[s];if(n===0)return;this.cnt[t]+=n;const o=e.num[s],r=this.num[t];if(this.num[t]=r+o,e.err!==null&&e.err[s]!==0&&(this.err===null&&(this.err=new Int8Array(this.size)),this.err[t]===0&&(this.err[t]=e.err[s])),o!==0&&(this.sum!==null&&(this.sum[t]+=e.sum[s]),this.min!==null&&(e.min[s]<this.min[t]&&(this.min[t]=e.min[s]),e.max[s]>this.max[t]&&(this.max[t]=e.max[s])),this.prod!==null&&(this.prod[t]*=e.prod[s]),this.mean!==null)){const l=e.mean[s]-this.mean[t],i=r+o;this.m2[t]+=e.m2[s]+l*l*r*o/i,this.mean[t]+=l*o/i}}value(t,e){const s=this.cnt[t];if(s===0)return null;if(e==="count")return s;if(e==="countNums")return this.num[t];if(this.err!==null&&this.err[t]!==0)return Rt[this.err[t]-1];const n=this.num[t];switch(e){case"sum":return this.sum[t];case"average":return n===0?U.DIV0:this.sum[t]/n;case"max":return n===0?0:this.max[t];case"min":return n===0?0:this.min[t];case"product":return n===0?0:this.prod[t];case"stdDev":return n<2?U.DIV0:Math.sqrt(this.m2[t]/(n-1));case"stdDevp":return n<1?U.DIV0:Math.sqrt(this.m2[t]/n);case"var":return n<2?U.DIV0:this.m2[t]/(n-1);case"varp":return n<1?U.DIV0:this.m2[t]/n;default:return null}}}function Le(c,t,e,s){const{cnt:n,num:o}=c;t.base<0&&t.ensureColumn();const{kinds:r,nums:l}=t;if(l===null||t.base>=0){for(let a=0;a<s;a++){const d=e[a];d>=0&&n[d]++}return}if(r===null){for(let a=0;a<s;a++){const d=e[a];d>=0&&n[d]++}o.set(n)}else for(let a=0;a<s;a++){const d=e[a];if(d<0)continue;const m=r[a];m!==K&&(n[d]++,m===B?o[d]++:m===ct&&(c.err===null&&(c.err=new Int8Array(c.size)),c.err[d]===0&&(c.err[d]=l[a]+1)))}const{sum:i,min:u,max:f,prod:w,mean:p,m2:h}=c;if(i!==null)if(r===null)for(let a=0;a<s;a++){const d=e[a];d>=0&&(i[d]+=l[a])}else for(let a=0;a<s;a++){const d=e[a];d>=0&&r[a]===B&&(i[d]+=l[a])}if(u!==null)for(let a=0;a<s;a++){const d=e[a];if(d<0||r!==null&&r[a]!==B)continue;const m=l[a];m<u[d]&&(u[d]=m),m>f[d]&&(f[d]=m)}if(w!==null)for(let a=0;a<s;a++){const d=e[a];d>=0&&(r===null||r[a]===B)&&(w[d]*=l[a])}if(p!==null){const a=new Int32Array(c.size);for(let d=0;d<s;d++){const m=e[d];if(m<0||r!==null&&r[d]!==B)continue;const A=++a[m],g=l[d]-p[m];p[m]+=g/A,h[m]+=g*(l[d]-p[m])}}}class xe{constructor(t,e,s){this.fields=e,this.slots=s,this.k=e.length,this.leaf=null,this.nLeaves=1,this.levelBase=[1],this.nNodes=1,this.parent=new Int32Array([-1]),this.item=new Int32Array([-1]),this.depth=new Uint8Array(1),this.cache=t,this.alive=null,this.childStart=null,this.childList=null,this.pos=null,this._childIndex=null,this.lines=null}leafNode(t){return this.k===0?0:this.levelBase[this.k-1]+t}ancestorAt(t,e){let s=t;for(;this.depth[s]>e;)s=this.parent[s];return this.depth[s]===e?s:-1}fieldAt(t){return this.cache.fields[this.fields[t-1]]}children(t){return this.childList.subarray(this.childStart[t],this.childStart[t+1])}findChild(t,e){if(this._childIndex===null){const s=new Map;this.stride=1;for(const n of this.fields)this.stride=Math.max(this.stride,this.cache.fields[n].items.length+1);for(let n=1;n<this.nNodes;n++)this.alive[n]&&s.set(this.parent[n]*this.stride+this.item[n],n);this._childIndex=s}return this._childIndex.get(t*this.stride+e)??-1}pathKeys(t){const e=[];for(let s=t;s>0;s=this.parent[s])e.push(this.fieldAt(this.depth[s]).keyOf(this.item[s]));return e.reverse()}peer(t,e,s){if(s<0)return-1;if(this.depth[t]===e)return s;const n=[];for(let r=t;this.depth[r]>e;r=this.parent[r])n.push(this.item[r]);let o=s;for(let r=n.length-1;r>=0&&o>=0;r--)o=this.findChild(o,n[r]);return o}}function Yt(c,t,e,s,n,o=null){const r=new xe(c,t,e),l=t.length;if(l===0)return r;let i=null,u=1;const f=[];for(let h=0;h<l;h++){const a=c.fields[t[h]].ensure(),d=a.ids,m=a.items.length,A=u*m,g=new Int32Array(s),y=Math.min(A,Math.max(s,1)),v=new Int32Array(y),_=new Int32Array(y);let b=0;if(A<=Pt){const D=new Int32Array(A).fill(-1);if(i===null)for(let T=0;T<s;T++){if(n!==null&&n[T]===0){g[T]=-1;continue}const N=d[T];let P=D[N];P<0&&(P=b++,D[N]=P,_[P]=N),g[T]=P}else for(let T=0;T<s;T++){const N=i[T];if(N<0){g[T]=-1;continue}const P=N*m+d[T];let I=D[P];I<0&&(I=b++,D[P]=I,v[I]=N,_[I]=d[T]),g[T]=I}}else{const D=new Map;for(let T=0;T<s;T++){const N=i===null?0:i[T];if(N<0||i===null&&n!==null&&n[T]===0){g[T]=-1;continue}const P=N*m+d[T];let I=D.get(P);I===void 0&&(I=b++,D.set(P,I),v[I]=N,_[I]=d[T]),g[T]=I}}const x=o?.(t[h]),R=x?Zt({parents:v,items:_,count:b},u,m,x.hide):{parents:v,items:_,count:b};f.push(R),i=g,u=Math.max(R.count,1)}r.leaf=i,r.nLeaves=f[l-1].count;let w=1;const p=[];for(const h of f)p.push(w),w+=h.count;return r.levelBase=p,r.nNodes=w,r.parent=new Int32Array(w),r.item=new Int32Array(w),r.depth=new Uint8Array(w),r.parent[0]=-1,r.item[0]=-1,f.forEach((h,a)=>{const d=p[a],m=a===0?0:p[a-1];for(let A=0;A<h.count;A++)r.parent[d+A]=a===0?0:m+h.parents[A],r.item[d+A]=h.items[A],r.depth[d+A]=a+1}),r}class Ne{constructor(t=1024){this.count=0,this.capacity=t,this.rows=new Int32Array(t),this.cols=new Int32Array(t),this.kinds=new Uint8Array(t),this.values=new Float64Array(t),this.roles=new Uint8Array(t),this.levels=new Uint8Array(t),this.formats=new Uint16Array(t),this.texts=[],this._textIndex=new Map,this.formatList=["General"],this._formatIndex=new Map([["General",0]])}_grow(){const t=this.capacity*2,e=(s,n)=>{const o=new s(t);return o.set(n),o};this.rows=e(Int32Array,this.rows),this.cols=e(Int32Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.values=e(Float64Array,this.values),this.roles=e(Uint8Array,this.roles),this.levels=e(Uint8Array,this.levels),this.formats=e(Uint16Array,this.formats),this.capacity=t}format(t){let e=this._formatIndex.get(t);return e===void 0&&(e=this.formatList.length,this.formatList.push(t),this._formatIndex.set(t,e)),e}text(t){let e=this._textIndex.get(t);return e===void 0&&(e=this.texts.length,this.texts.push(t),this._textIndex.set(t,e)),e}push(t,e,s,n,o,r=0,l=0){this.count===this.capacity&&this._grow();const i=this.count++;this.rows[i]=t,this.cols[i]=e,this.kinds[i]=s,this.values[i]=n,this.roles[i]=o,this.levels[i]=r,this.formats[i]=l}pushValue(t,e,s,n,o=0,r=0){s==null?this.push(t,e,K,0,n,o,r):typeof s=="number"?this.push(t,e,B,s,n,o,r):typeof s=="string"?this.push(t,e,Z,this.text(s),n,o,r):typeof s=="boolean"?this.push(t,e,at,s?1:0,n,o,r):this.push(t,e,ct,s.index,n,o,r)}valueAt(t){switch(this.kinds[t]){case B:return this.values[t];case Z:return this.texts[this.values[t]];case at:return this.values[t]!==0;case ct:return Dt[this.values[t]]??"#N/A";default:return null}}}function Xt(c){const t=c.replace(/[.+^${}()|[\]\\*?~]/g,e=>e==="*"?".*":e==="?"?".":`\\${e}`);return new RegExp(`^${t}$`,"is")}const Qt=c=>c.replace(/[.+^${}()|[\]\\]/g,"\\$&");function Ee(c){const{op:t}=c,e=String(c.value??""),s=String(c.value2??""),n=e.split(/([*?])/).map(r=>r==="*"?".*":r==="?"?".":Qt(r)).join(""),o=(r,l,i)=>{const u=typeof l=="number"?l:Number.NaN,f=i.trim()===""?Number.NaN:Number(i);return!Number.isNaN(u)&&!Number.isNaN(f)?u-f:Ut(r,i)};switch(t){case"captionEqual":{const r=Xt(e);return l=>r.test(l)}case"captionNotEqual":{const r=Xt(e);return l=>!r.test(l)}case"captionBeginsWith":{const r=new RegExp(`^${n}`,"is");return l=>r.test(l)}case"captionNotBeginsWith":{const r=new RegExp(`^${n}`,"is");return l=>!r.test(l)}case"captionEndsWith":{const r=new RegExp(`${n}$`,"is");return l=>r.test(l)}case"captionNotEndsWith":{const r=new RegExp(`${n}$`,"is");return l=>!r.test(l)}case"captionContains":{const r=new RegExp(n,"is");return l=>r.test(l)}case"captionNotContains":{const r=new RegExp(n,"is");return l=>!r.test(l)}case"captionGreaterThan":return(r,l)=>o(r,l,e)>0;case"captionGreaterThanOrEqual":return(r,l)=>o(r,l,e)>=0;case"captionLessThan":return(r,l)=>o(r,l,e)<0;case"captionLessThanOrEqual":return(r,l)=>o(r,l,e)<=0;case"captionBetween":return(r,l)=>o(r,l,e)>=0&&o(r,l,s)<=0;case"captionNotBetween":return(r,l)=>o(r,l,e)<0||o(r,l,s)>0;default:return()=>!0}}function Oe(c){const t=Number(c.value),e=Number(c.value2);switch(c.op){case"valueEqual":return s=>s===t;case"valueNotEqual":return s=>s!==t;case"valueGreaterThan":return s=>s>t;case"valueGreaterThanOrEqual":return s=>s>=t;case"valueLessThan":return s=>s<t;case"valueLessThanOrEqual":return s=>s<=t;case"valueBetween":return s=>s>=Math.min(t,e)&&s<=Math.max(t,e);case"valueNotBetween":return s=>s<Math.min(t,e)||s>Math.max(t,e);default:return()=>!0}}function wt(c,t){if(!t)return null;const e=t.hidden&&t.hidden.length>0;if(!e&&!t.labelFilter)return null;c.ensure();const s=new Uint8Array(c.items.length);if(e){const n=c.keyIndex;for(const o of t.hidden){const r=n.get(o);r!==void 0&&(s[r]=1)}}if(t.labelFilter){const n=Ee(t.labelFilter);c.items.forEach((o,r)=>{n(c.labelOfValue(o),o)||(s[r]=1)})}return s}function zt(c,t){return c.ensureRaw(),te(c.shared,t)}class Ie{constructor(t,e){this.rows=t,this.cols=e,this.dense=t*e<=ce,this.map=this.dense?null:new Map,this.size=this.dense?t*e:0}ensure(t,e){const s=t*this.cols+e;if(this.dense)return s;let n=this.map.get(s);return n===void 0&&(n=this.size++,this.map.set(s,n)),n}get(t,e){const s=t*this.cols+e;return this.dense?s:this.map.get(s)??-1}}class Me{constructor(t){this.pivot=t,this.cache=t.cache,this.spec=t.spec,this._aggregate(),this._arrange()}opts(t){return this.spec.fieldOptions[t]??null}_resolveData(){const{cache:t,spec:e}=this,s=new Map,n=(r,l)=>{let i=s.get(r);i===void 0&&(i={sum:!1,mm:!1,prod:!1,var:!1},s.set(r,i));const u=ke[l];u&&(i[u]=!0)},o=new Set;for(const r of Object.keys(e.fieldOptions)){const l=e.fieldOptions[r].subtotals;if(Array.isArray(l))for(const i of l)o.add(i)}this.data=e.values.map((r,l)=>{const i=t.fields[r.field],u={index:l,field:r.field,name:r.name,agg:r.agg,showAs:r.showAs??null,numFmt:r.numFmt??null,calc:null};if(i.isCalculated){u.calc=i.calc??(i.calc=Nt(i.formula,t));for(const f of u.calc.refs)n(f,"sum")}else{n(r.field,r.agg);for(const f of o)n(r.field,f)}return u}),this.needs=s}_recordMask(t){const{spec:e,cache:s}=this;let n=null;for(const o of Object.keys(e.fieldOptions)){const r=s.fields[o];if(!r||r.removed||r.isCalculated)continue;const l=wt(r,e.fieldOptions[o]);if(l!==null){n===null&&(n=new Uint8Array(t).fill(1));const i=r.ensure().ids;for(let u=0;u<t;u++)l[i[u]]===1&&(n[u]=0)}if(e.fieldOptions[o].range||e.fieldOptions[o].dateFilter){n===null&&(n=new Uint8Array(t).fill(1));const i=zt(r,e.fieldOptions[o]),u=r.rawIds;for(let f=0;f<t;f++)i[u[f]]===1&&(n[f]=0)}}return n}_aggregate(){const{cache:t,spec:e}=this,s=t.recordCount;this._resolveData();const n=this.data.length,o=y=>y.filter(v=>v!==L||n>1);let r=o(e.rows),l=o(e.cols);n>1&&!r.includes(L)&&!l.includes(L)&&(l=[...l,L]),r=r.filter(y=>y===L||!t.fields[y].removed),l=l.filter(y=>y===L||!t.fields[y].removed);const i=this._recordMask(s);this.mask=i;const u=y=>{const v=e.fieldOptions[y];return v?.showAll?{hide:wt(t.fields[y],v)}:null},f=Yt(t,r.filter(y=>y!==L),r,s,i,u),w=Yt(t,l.filter(y=>y!==L),l,s,i,u);this.rows=f,this.cols=w;let p,h,a,d;const m=f.nLeaves,A=w.nLeaves;if(f.leaf!==null&&w.leaf!==null){const y=f.leaf,v=w.leaf;p=new Int32Array(s);const _=m*A,b=Math.min(_,Math.max(s,1));if(h=new Int32Array(b),a=new Int32Array(b),d=0,_<=Pt){const x=new Int32Array(_).fill(-1);for(let R=0;R<s;R++){const D=y[R];if(D<0){p[R]=-1;continue}const T=D*A+v[R];let N=x[T];N<0&&(N=d++,x[T]=N,h[N]=D,a[N]=v[R]),p[R]=N}}else{const x=new Map;for(let R=0;R<s;R++){const D=y[R];if(D<0){p[R]=-1;continue}const T=D*A+v[R];let N=x.get(T);N===void 0&&(N=d++,x.set(T,N),h[N]=D,a[N]=v[R]),p[R]=N}}}else if(f.leaf!==null||w.leaf!==null){p=f.leaf??w.leaf,d=f.leaf!==null?m:A;const y=new Int32Array(d);for(let _=0;_<d;_++)y[_]=_;const v=new Int32Array(d);h=f.leaf!==null?y:v,a=f.leaf!==null?v:y}else{if(p=new Int32Array(s),d=1,i!==null)for(let y=0;y<s;y++)i[y]===0&&(p[y]=-1);h=new Int32Array(1),a=new Int32Array(1)}this.cellCount=d,this.cellRow=h,this.cellCol=a,this.cells=p;const g=new Map;for(const[y,v]of this.needs){const _=new Et(d,v);Le(_,t.fields[y],p,s),g.set(y,_)}this.leafAccs=g,this._applyValueFilters(),this._rollUp()}_slotValue(t,e,s,n){if(t.calc!==null){let o=!1;const r=l=>{const i=e.get(l);if(i.cnt[s]!==0&&(o=!0),i.err!==null&&i.err[s]!==0)throw Rt[i.err[s]-1];return i.sum[s]};try{const l=t.calc.fn(r);return o?typeof l=="number"?Number.isFinite(l)?l:U.NUM:typeof l=="boolean"?l?1:0:l instanceof $?l:U.VALUE:null}catch(l){if(l instanceof $)return l;throw l}}return e.get(t.field).value(s,n??t.agg)}_applyValueFilters(){const{rows:t,cols:e,data:s}=this;this.rowDead=new Uint8Array(t.nNodes),this.colDead=new Uint8Array(e.nNodes);const n=(o,r,l)=>{for(let i=1;i<=o.k;i++){const u=o.fields[i-1],f=this.opts(u);if(!f||!f.valueFilter&&!f.top)continue;const w=f.valueFilter??f.top,p=s[w.data??0];if(!p)continue;const h=this._nodeAccs(o,p,l),a=o.levelBase[i-1],d=i<o.k?o.levelBase[i]:o.nNodes,m=new Map;for(let A=a;A<d;A++){if(r[A]||r[o.parent[A]]){r[A]=1;continue}const g=o.parent[A];let y=m.get(g);y===void 0&&(y=[],m.set(g,y)),y.push(A)}for(const A of m.values()){const g=y=>{const v=this._slotValue(p,h,y,null);return typeof v=="number"?v:null};if(f.valueFilter){const y=Oe(f.valueFilter);for(const v of A){const _=g(v);(_===null||!y(_))&&(r[v]=1)}}if(f.top){const y=A.filter(v=>!r[v]);for(const v of Fe(y,g,f.top,!0))r[v]=1}}for(let A=d;A<o.nNodes;A++)r[o.parent[A]]&&(r[A]=1)}};n(t,this.rowDead,!0),n(e,this.colDead,!1)}_nodeAccs(t,e,s){const n=e.calc!==null?e.calc.refs:[e.field],o=new Map;for(const a of n)o.set(a,new Et(t.nNodes,this.needs.get(a)));const r=[...o.entries()].map(([a,d])=>[d,this.leafAccs.get(a)]),{cellRow:l,cellCol:i,rows:u,cols:f,rowDead:w,colDead:p}=this,h=s?l:i;for(let a=0;a<this.cellCount;a++){const d=u.leafNode(l[a]),m=f.leafNode(i[a]);if(w[d]||p[m])continue;let A=t.leafNode(h[a]);for(;A>=0;){for(const[g,y]of r)g.merge(A,y,a);A=t.parent[A]}}return o}_rollUp(){const{rows:t,cols:e,cellRow:s,cellCol:n,rowDead:o,colDead:r,cellCount:l}=this,i=new Uint8Array(t.nNodes),u=new Uint8Array(e.nNodes),f=new Ie(t.nNodes,e.nNodes),w=t.parent,p=e.parent,h=new Uint8Array(l);for(let g=0;g<l;g++){const y=t.leafNode(s[g]),v=e.leafNode(n[g]);if(!(o[y]||r[v])){h[g]=1;for(let _=y;_>=0;_=w[_])if(i[_]=1,!f.dense)for(let b=v;b>=0;b=p[b])f.ensure(_,b);for(let _=v;_>=0;_=p[_])u[_]=1}}t.alive=i,e.alive=u;const a=new Map,d=[];for(const[g,y]of this.needs){const v=new Et(Math.max(f.size,1),y);a.set(g,v),d.push([v,this.leafAccs.get(g)])}const m=f.dense,A=f.cols;for(let g=0;g<l;g++){if(h[g]===0)continue;const y=t.leafNode(s[g]),v=e.leafNode(n[g]);for(let _=y;_>=0;_=w[_])for(let b=v;b>=0;b=p[b]){const x=m?_*A+b:f.get(_,b);for(let R=0;R<d.length;R++)d[R][0].merge(x,d[R][1],g)}}this.slots=f,this.accs=a,this.cells=null,t.leaf=null,e.leaf=null}raw(t,e,s,n=null){if(e<0||s<0)return null;const o=this.slots.get(e,s);return o<0?null:this._slotValue(t,this.accs,o,n)}_baseLoc(t){if(t._loc!==void 0)return t._loc;const e=t.showAs?.baseField;let s=null;if(e!=null&&e>=0){let n=this.rows.fields.indexOf(e);n>=0?s={tree:this.rows,isRow:!0,depth:n+1}:(n=this.cols.fields.indexOf(e),n>=0&&(s={tree:this.cols,isRow:!1,depth:n+1}))}return t._loc=s,s}show(t,e,s,n=null){const o=t.showAs?.type;if(!o||o==="normal")return this.raw(t,e,s,n);const r=this.raw(t,e,s,n);if(r instanceof $)return r;const l=(m,A)=>this.raw(t,m,A,n),i=m=>m instanceof $?m:r===null?m===null?null:0:m===null||m===0?U.DIV0:r/m;switch(o){case"percentOfTotal":return i(l(0,0));case"percentOfCol":return i(l(0,s));case"percentOfRow":return i(l(e,0));case"percentOfParentRow":return i(e===0?r:l(this.rows.parent[e],s));case"percentOfParentCol":return i(s===0?r:l(e,this.cols.parent[s]));case"index":{const m=l(0,0),A=l(e,0),g=l(0,s);return[m,A,g].some(y=>y instanceof $)?U.VALUE:!A||!g?U.DIV0:(r??0)*m/(A*g)}default:}const u=this._baseLoc(t);if(u===null)return U.NA;const{tree:f,isRow:w,depth:p}=u,h=w?e:s;if(f.depth[h]<p)return null;const a=m=>w?l(m,s):l(e,m),d=f.ancestorAt(h,p);switch(o){case"percentOfParent":return i(a(d));case"percent":case"difference":case"percentDiff":{const m=this._baseSibling(t,f,d,p);if(m==="missing")return U.NA;if(m===-1)return o==="percent"?r===null?null:1:null;const A=a(f.peer(h,p,m));return m===d?o==="percent"?r===null?null:1:null:A instanceof $?A:o==="percent"&&r===null?U.NULL:o==="difference"?r===null&&A===null?null:(r??0)-(A??0):r===null||A===null?null:A===0?U.DIV0:o==="percent"?r/A:(r-A)/A}case"runTotal":case"percentOfRunningTotal":{const m=this._running(t,f,w,p,h,w?s:e,d,n);if(m instanceof $||o==="runTotal")return m;const A=f.children(f.parent[d]),g=this._running(t,f,w,p,h,w?s:e,A[A.length-1],n);return g instanceof $?g:g===0?U.DIV0:m/g}case"rankAscending":case"rankDescending":return r===null?null:this._rank(t,f,w,p,h,w?s:e,r,o==="rankAscending",n);default:return r}}_baseSibling(t,e,s,n){const o=t.showAs.baseItem,r=e.parent[s];if(o==="prev"||o==="next"){const f=e.children(r),w=e.pos[s]+(o==="prev"?-1:1);return w>=0&&w<f.length?f[w]:-1}const i=e.fieldAt(n).keyIndex.get(o);if(i===void 0)return"missing";const u=e.findChild(r,i);return u<0?"missing":u}_running(t,e,s,n,o,r,l,i){t._run===void 0&&(t._run=new Map);let u=t._run.get(i);u===void 0&&(u=new Map,t._run.set(i,u));const f=e.children(e.parent[l]),w=e.pos[l],p=s?this.cols.nNodes:this.rows.nNodes;let h=w,a=0;for(;h>=0;){const d=e.peer(o,n,f[h]),m=d>=0?u.get(d*p+r):void 0;if(m!==void 0){a=m;break}h--}for(let d=h+1;d<=w;d++){const m=e.peer(o,n,f[d]);if(m<0)continue;const A=s?this.raw(t,m,r,i):this.raw(t,r,m,i);if(A instanceof $)return A;typeof A=="number"&&(a+=A),u.set(m*p+r,a)}return a}_rank(t,e,s,n,o,r,l,i,u){t._ranks===void 0&&(t._ranks=new Map);const f=e.ancestorAt(o,n),w=e.pathKeys(o).slice(n).join(xt),p=`${e.parent[f]}|${r}|${w}`;let h=t._ranks.get(p);if(h===void 0){const m=[];for(const A of e.children(e.parent[f])){const g=e.peer(o,n,A);if(g<0)continue;const y=s?this.raw(t,g,r,u):this.raw(t,r,g,u);typeof y=="number"&&m.push(y)}h=Float64Array.from(m).sort(),t._ranks.set(p,h)}let a=0,d=h.length;if(i){for(;a<d;){const m=a+d>>1;h[m]<l?a=m+1:d=m}return a+1}for(;a<d;){const m=a+d>>1;h[m]<=l?a=m+1:d=m}return h.length-a+1}_arrange(){for(const t of this.data)t._run=void 0,t._ranks=void 0;this._buildChildren(this.rows,!0),this._buildChildren(this.cols,!1),this.rows.lines=this._buildLines(this.rows,!0),this.cols.lines=this._buildLines(this.cols,!1),this._layout()}rearrange(){return this._arrange(),this}_buildChildren(t,e){const{nNodes:s,parent:n,alive:o}=t,r=new Int32Array(s+1);for(let u=1;u<s;u++)o[u]&&r[n[u]+1]++;for(let u=0;u<s;u++)r[u+1]+=r[u];const l=new Int32Array(r[s]),i=r.slice();for(let u=1;u<s;u++)o[u]&&(l[i[n[u]]++]=u);t.childStart=r,t.childList=l,t.pos=new Int32Array(s),t._childIndex=null;for(let u=0;u<t.k;u++){const f=this._sortCompare(t,u+1,e),w=u===0?0:t.levelBase[u-1],p=u===0?1:t.levelBase[u];for(let h=w;h<p;h++){const a=r[h],d=r[h+1];if(d-a>1){const m=Array.from(l.subarray(a,d));m.sort(f),l.set(m,a)}for(let m=a;m<d;m++)t.pos[l[m]]=m-a}}}_sortCompare(t,e,s){const n=t.fields[e-1],o=this.cache.fields[n].ensure(),r=o.rank(),{item:l}=t,i=this.opts(n)?.sort;if((!i||i.order==="asc"||i.order===void 0)&&(!i||i.data===void 0||i.data===null))return(d,m)=>r[l[d]]-r[l[m]];if(i.order==="manual"){const d=i.keys??[],m=new Map(d.map((g,y)=>[g,y])),A=new Float64Array(o.items.length);return o.items.forEach((g,y)=>{const v=m.get(ut(g));A[y]=v===void 0?d.length+r[y]:v}),(g,y)=>A[l[g]]-A[l[y]]}const u=i.order==="desc"?-1:1;if(i.data===void 0||i.data===null)return(d,m)=>u*(r[l[d]]-r[l[m]]);const f=this.data[i.data];if(!f)return(d,m)=>r[l[d]]-r[l[m]];let w=0;if(i.path){const d=s?this.cols:this.rows;this._ensureItems(d);for(let m=0;m<i.path.length&&w>=0;m++){const g=d.fieldAt(m+1).keyIndex.get(i.path[m]);w=g===void 0?-1:d.findChild(w,g)}}const p=d=>{const m=s?this.raw(f,d,w):this.raw(f,w,d);return typeof m=="number"?m:null},h=new Map,a=d=>{let m=h.get(d);return m===void 0&&(m=p(d),h.set(d,m)),m};return(d,m)=>{const A=a(d),g=a(m);return A===null||g===null?A===g?r[l[d]]-r[l[m]]:A===null?1:-1:A===g?r[l[d]]-r[l[m]]:u*(A-g)}}_ensureItems(t){for(const e of t.fields)this.cache.fields[e].ensure()}_form(t){return this.opts(t)?.layout??this.spec.layout}_isCollapsed(t,e,s){const n=t.depth[e],o=s[n];return o===null?!1:!!(o.items!==null&&o.items.has(t.fieldAt(n).keyOf(t.item[e]))||o.paths!==null&&o.paths.has(t.pathKeys(e).join(xt)))}_buildLines(t,e){const{slots:s}=t,n=this.data.length,o={node:[],data:[],type:[],level:[],first:[],func:[],top:[],parentLine:[]},r=(h,a,d,m,A,g,y,v)=>{o.node.push(h),o.data.push(a),o.type.push(d),o.level.push(m),o.first.push(A),o.func.push(g),o.top.push(y?1:0),o.parentLine.push(v?1:0)},l=s.length-1,i=h=>e?s[h]===L?this.spec.layout:this._form(s[h]):"tabular",u=[null];for(let h=1;h<=t.k;h++){const a=this.opts(t.fields[h-1]),d=a?.collapsedItems?.length?new Set(a.collapsedItems):null,m=a?.collapsed?.length?new Set(a.collapsed):null;u.push(d||m?{items:d,paths:m}:null)}const f=h=>this.opts(h)?.subtotalTop??this.spec.subtotalTop,w=(h,a,d,m)=>{const A=s[a];if(A===L){for(let _=0;_<n;_++){const b=_===0&&m!==-1?m:a;a===l?r(h,_,X,a,b,null,!1,!1):i(a)==="tabular"?w(h,a+1,_,b):(r(h,_,X,a,b,null,!1,!0),o.noValues??=new Set,o.noValues.add(o.node.length-1),w(h,a+1,_,-1))}return}const g=t.children(h),y=this.opts(A),v=y?.blankLine===!0&&e;for(let _=0;_<g.length;_++){const b=g[_],x=_===0&&m!==-1?m:a;if(a===l){r(b,d,X,a,x,null,!1,!1);continue}const R=i(a),D=d<0&&s.indexOf(L,a+1)>=0;if(this._isCollapsed(t,b,u)){if(D)for(let z=0;z<n;z++)r(b,z,X,a,z===0?x:a,null,!1,R!=="tabular");else r(b,d,X,a,x,null,!1,R!=="tabular");o.collapsed??=new Set,o.collapsed.add(b),v&&r(b,d,mt,a,a,null,!1,!1);continue}const T=y?.subtotals??"auto",N=Array.isArray(T),P=T!=="none"&&!(N&&T.length===0),I=R!=="tabular"&&!D&&!N&&P&&f(A);if(R==="tabular"?w(b,a+1,d,x):(r(b,d,X,a,x,null,I,!0),I||(o.noValues??=new Set,o.noValues.add(o.node.length-1)),w(b,a+1,d,-1)),!I&&P&&!(a+1===l&&s[a+1]===L&&!N)){const yt=N?T:[null];if(D)for(let tt=0;tt<n;tt++)for(const vt of yt)r(b,tt,lt,a,a,vt,!1,!1);else for(const tt of yt)r(b,d,lt,a,a,tt,!1,!1)}v&&r(b,d,mt,a,a,null,!1,!1)}};if(s.length===0)return r(0,-1,X,-1,0,null,!1,!1),o;if(w(0,0,-1,-1),t.k>0&&(e?this.spec.grandRow:this.spec.grandCol))if(s.includes(L))for(let h=0;h<n;h++)r(0,h,st,0,0,null,!1,!1);else r(0,-1,st,0,0,null,!1,!1);return o}fieldCaption(t){return t===L?this.spec.dataCaption:this.opts(t)?.caption??this.cache.fields[t].name}itemCaption(t,e){const s=t.fieldAt(t.depth[e]),n=t.item[e],o=this.opts(s.index)?.itemCaptions;if(o){const r=o[s.keyOf(n)];if(r!==void 0)return r}return null}_labelValue(t,e){const s=this.itemCaption(t,e);if(s!==null)return s===""?null:s;const n=t.fieldAt(t.depth[e]).items[t.item[e]];return n===""?null:n??"(blank)"}_labelText(t,e){const s=this.itemCaption(t,e);return s!==null?s:t.fieldAt(t.depth[e]).labelOf(t.item[e])}_subtotalLabel(t,e,s){const n=this._labelText(t,e.node[s]),o=e.data[s],r=e.func[s];return r!==null&&o>=0?`${n} ${kt[r]} of ${this.data[o].name}`:r!==null?`${n} ${kt[r]}`:o>=0?`${n} ${this.data[o].name}`:`${n} Total`}_pageValue(t){const e=this.cache.fields[t].ensure(),s=wt(e,this.opts(t));if(s===null)return{text:"(All)",value:"(All)"};let n=0,o=-1;for(let r=0;r<s.length;r++)s[r]===0&&(n++,o=r);return n===s.length?{text:"(All)",value:"(All)"}:n===1?{text:e.labelOf(o),value:e.items[o]??"(blank)"}:{text:"(Multiple Items)",value:"(Multiple Items)"}}_layout(){const{spec:t,rows:e,cols:s,data:n}=this,o=new Ne;this.buffer=o;const r=n.length,l=t.filters.filter(C=>!this.cache.fields[C].removed),i=l.length>0?l.length+1:0,u=e.slots.length===0&&s.slots.length===0&&r===0;l.forEach((C,k)=>{o.pushValue(k,0,this.fieldCaption(C),E.PAGE_LABEL);const O=this.cache.fields[C],W=this._pageValue(C);o.pushValue(k,1,W.value,E.PAGE_VALUE,0,typeof W.value=="number"?o.format(O.numFmt):0)});const f=[],w=[];let p=0;if(e.slots.length>0){let C=0,k=0;for(let W=0;W<e.slots.length;W++)f.push(C),w.push(k),(e.slots[W]===L?t.layout:this._form(e.slots[W]))==="compact"?k++:(C++,k=0);p=(e.slots[e.slots.length-1]===L?t.layout:this._form(e.slots[e.slots.length-1]))==="compact"?C+1:C}else r<=1&&s.slots.length>0&&!(s.slots.length===1&&s.slots[0]===L)&&(p=1);const h=e.lines,a=s.lines,d=a.node.length,m=h.node.length,A=s.slots.length===1&&s.slots[0]===L,g=A&&!t.hideValuesRow&&e.slots.length>0,y=s.slots.length>0&&(!A||g),v=u?0:y?1+s.slots.length:1,_=y?t.layout==="compact"?1:s.slots.length:0,b=p+Math.max(r>0||y?d:0,_),x=r>0||e.slots.length>0?m:0,R=i,D=new Uint8Array(v*Math.max(b,1)),T=(C,k,O,W,H=0,V=0)=>{o.pushValue(R+C,k,O,W,V,H),D[C*b+k]=1},N=C=>t.layout==="compact"?null:C.map(k=>this.fieldCaption(k));u&&o.pushValue(R,0,t.name,E.PLACEHOLDER);const P=v-1;if(e.slots.length>0){const C=N(e.slots);C===null?T(P,0,t.rowCaption??G("Row Labels"),E.ROW_CAPTION):e.slots.forEach((k,O)=>{(k===L?t.layout:this._form(k))==="compact"&&O>0&&f[O]===f[O-1]||D[P*b+f[O]]||T(P,f[O],C[O],E.ROW_CAPTION)})}if(y){r===1&&e.slots.length>0&&T(0,0,n[0].name,E.CORNER);const C=N(s.slots);g?T(0,p,t.dataCaption,E.COL_CAPTION):C===null?T(0,p,t.colCaption??G("Column Labels"),E.COL_CAPTION):C.forEach((k,O)=>T(0,p+O,k,E.COL_CAPTION))}else r===1&&!A&&!e.slots.includes(L)&&T(0,p,n[0].name,E.DATA_HEADER);const I=y?1:0;if(r>0||y)for(let C=0;C<d;C++){const k=a.type[C],O=p+C,W=a.node[C];if(k===st){const V=a.data[C],ht=V>=0?`Total ${n[V].name}`:t.grandCaption??G("Grand Total");T(I,O,ht,E.COL_GRAND);continue}if(k===lt){T(I+a.level[C],O,this._subtotalLabel(s,a,C),E.COL_SUBTOTAL);continue}const H=a.level[C];for(let V=a.first[C];V<=H;V++){if(V<0||V>=s.slots.length)continue;if(s.slots[V]===L){const j=a.data[C];j>=0&&T(I+V,O,n[j].name,E.DATA_HEADER)}else{const j=Ot(s.slots,V),J=s.ancestorAt(W,j);if(V===H&&a.collapsed?.has(J))T(I+V,O,`${this._labelText(s,J)} Total`,E.COL_ITEM);else{const At=this._labelValue(s,J);T(I+V,O,At,E.COL_ITEM,typeof At=="number"?o.format(s.fieldAt(j).numFmt):0,t.showExpandButtons&&j<s.k?1:0)}}}}for(let C=0;C<v;C++)for(let k=0;k<b;k++)D[C*b+k]===0&&o.push(R+C,k,K,0,E.HEADER_BLANK);const z=R+v,yt=n.map(C=>{const k=C.numFmt??De(C);return o.format(k)}),tt=h.noValues??null,vt=C=>e.slots[C];for(let C=0;C<x;C++){const k=z+C,O=h.type[C];if(O===mt)continue;const W=h.node[C],H=h.level[C],V=h.parentLine[C]===1;let ht=E.ROW_ITEM,j=E.DATA;O===lt?(ht=E.ROW_SUBTOTAL,j=E.DATA_SUBTOTAL):O===st?(ht=E.ROW_GRAND,j=E.DATA_GRAND_ROW):V&&(j=E.DATA_PARENT);const J=Math.max(H,0);if(p>0)if(e.slots.length===0)r===1&&o.pushValue(k,0,n[0].name,E.ROW_ITEM);else if(O===st){const q=h.data[C];o.pushValue(k,0,q>=0?`Total ${n[q].name}`:t.grandCaption??G("Grand Total"),E.ROW_GRAND);for(let M=1;M<p;M++)o.push(k,M,K,0,E.ROW_GRAND)}else if(O===lt){const q=f[H];for(let M=0;M<p;M++)M===q?o.pushValue(k,M,this._subtotalLabel(e,h,C),E.ROW_SUBTOTAL,w[H]):o.push(k,M,K,0,E.ROW_SUBTOTAL)}else{const q=this._labelStart(h,C,e);for(let M=q;M<=H;M++){const dt=vt(M),nt=f[M],rt=M===H&&V?E.ROW_PARENT:E.ROW_ITEM;if(dt===L){const Q=h.data[C];Q>=0&&o.pushValue(k,nt,n[Q].name,rt,w[M])}else{const Q=Ot(e.slots,M),ot=e.ancestorAt(W,Q),Y=t.showExpandButtons&&Q<e.k?1:0;if(M===H&&h.collapsed?.has(ot)&&this._form(dt)==="tabular")o.pushValue(k,nt,`${this._labelText(e,ot)} Total`,rt,w[M]+Y);else{const et=this._labelValue(e,ot),Jt=typeof et=="number"?o.format(e.fieldAt(Q).numFmt):0;o.pushValue(k,nt,et,rt,w[M]+Y,Jt)}}}}if(r===0||tt!==null&&tt.has(C))continue;const _t=h.data[C],At=h.func[C];for(let q=0;q<d;q++){const M=a.type[q];if(M===mt)continue;const dt=a.data[q],nt=_t>=0?_t:dt>=0?dt:r===1?0:-1;if(nt<0)continue;const rt=n[nt],Q=At??a.func[q],ot=this.show(rt,W,a.node[q],Q);let Y=j;O!==st&&M===st?Y=E.DATA_GRAND_COL:O===X&&!V&&M===lt&&(Y=E.DATA);const it=p+q,et=Q&&Q!==rt.agg&&!rt.numFmt?0:yt[nt];ot===null?t.showMissing===!1?o.pushValue(k,it,0,Y,J,et):t.emptyText!==""?o.pushValue(k,it,t.emptyText,Y,J,et):Y!==E.DATA&&o.push(k,it,K,0,Y,J,et):ot instanceof $&&t.errorText!==null?o.pushValue(k,it,t.errorText,Y,J,et):o.pushValue(k,it,ot,Y,J,et)}}const It=u?R+1:z+x,Mt=Math.max(b,l.length>0?2:0,u?1:0);if(It>ne||Mt>se)throw new S("The PivotTable is too large for a worksheet.");this.layout={cells:o,rows:It,cols:Mt,bodyCols:b,pageRows:i,pageFields:l,headerRows:v,labelCols:p,bodyTop:z,dataRows:x,colForLevel:f,indentForLevel:w,colRowBase:I,firstHeaderRow:u||y?1:r>1?0:1,firstDataRow:u?1:v,firstDataCol:p}}_labelStart(t,e,s){const n=t.level[e],o=t.first[e];if(o===0)return 0;for(let r=0;r<o;r++){const l=s.slots[r];if(l!==L&&this.opts(l)?.repeatLabels||l!==L&&this.spec.repeatLabels&&this._form(l)!=="compact")return r}return Math.min(o,n)}toRows(){const{cells:t,rows:e,cols:s}=this.layout,n=[];for(let o=0;o<e;o++)n.push(new Array(s).fill(null));for(let o=0;o<t.count;o++)n[t.rows[o]][t.cols[o]]=t.valueAt(o);return n}hitTest(t,e){const s=this.layout,{spec:n,rows:o,cols:r}=this;if(t<s.pageRows-1){const i=s.pageFields[t];return i!==void 0&&e===1?{kind:"pageFilter",field:i}:null}const l=t-s.pageRows;if(l<0||t>=s.rows)return null;if(l===s.headerRows-1&&e<s.labelCols&&o.fields.length>0){const i=n.layout==="compact"?o.fields:o.slots.filter((u,f)=>u!==L&&s.colForLevel[f]===e);if(i.length>0)return{kind:"filter",axis:"row",fields:i}}if(l===0&&e>=s.labelCols&&r.fields.length>0&&s.colRowBase===1){const i=n.layout==="compact"?e===s.labelCols?r.fields:[]:r.slots.filter((u,f)=>u!==L&&f===e-s.labelCols);if(i.length>0)return{kind:"filter",axis:"col",fields:i}}if(l>=s.headerRows&&e<s.labelCols){const i=this._rowLabelAt(l-s.headerRows,e);if(i!==null)return i}if(l>=s.colRowBase&&l<s.headerRows&&e>=s.labelCols){const i=this._colLabelAt(e-s.labelCols,l-s.colRowBase);if(i!==null)return i}return l>=s.headerRows&&e>=s.labelCols?{kind:"value",rowLine:l-s.headerRows,colLine:e-s.labelCols}:null}_rowLabelAt(t,e){const{rows:s}=this,n=s.lines;if(t>=n.node.length||n.type[t]!==X)return null;const o=this.layout.colForLevel;for(let r=n.level[t];r>=this._labelStart(n,t,s);r--)if(o[r]===e)return this._labelHit(s,n,t,r,"row");return null}_colLabelAt(t,e){const{cols:s}=this,n=s.lines;return t>=n.node.length||n.type[t]!==X||e<n.first[t]||e>n.level[t]?null:this._labelHit(s,n,t,e,"col")}_labelHit(t,e,s,n,o){const r=t.slots[n];if(r===L||r===void 0)return null;const l=Ot(t.slots,n),i=t.ancestorAt(e.node[s],l),u=l<t.k;return{kind:"label",axis:o,node:i,field:r,path:t.pathKeys(i),expandable:u,collapsed:u&&e.collapsed?.has(i)===!0}}togglesIn(t,e,s,n){const o=[],r=this.layout,{rows:l,cols:i}=this;if(this.spec.showExpandButtons===!1)return o;if(l.k>1)for(let u=Math.max(t,r.bodyTop);u<=Math.min(s,r.rows-1);u++)for(let f=e;f<=Math.min(n,r.labelCols-1);f++){const w=this._rowLabelAt(u-r.bodyTop,f);w!==null&&w.expandable&&o.push({row:u,col:f,collapsed:w.collapsed,indent:this._levelIndent(w)})}if(i.k>1){const u=r.pageRows+r.colRowBase;for(let f=Math.max(t,u);f<=Math.min(s,r.pageRows+r.headerRows-1);f++)for(let w=Math.max(e,r.labelCols);w<=Math.min(n,r.cols-1);w++){const p=this._colLabelAt(w-r.labelCols,f-u);p!==null&&p.expandable&&o.push({row:f,col:w,collapsed:p.collapsed,indent:0})}}return o}_levelIndent(t){const e=this.rows.slots.indexOf(t.field);return e>=0?this.layout.indentForLevel[e]:0}filterButtons(){const t=this.layout,{rows:e,cols:s,spec:n}=this,o=[];if(t.pageFields.forEach((r,l)=>o.push({row:l,col:1,axis:"page",fields:[r]})),e.fields.length>0&&n.showFieldHeaders!==!1){const r=t.pageRows+t.headerRows-1;n.layout==="compact"?o.push({row:r,col:0,axis:"row",fields:e.fields}):e.slots.forEach((l,i)=>{l!==L&&(i===0||t.colForLevel[i]!==t.colForLevel[i-1])&&o.push({row:r,col:t.colForLevel[i],axis:"row",fields:[l]})})}if(s.fields.length>0&&n.showFieldHeaders!==!1&&t.colRowBase===1){const r=t.pageRows;n.layout==="compact"?o.push({row:r,col:t.labelCols,axis:"col",fields:s.fields}):s.slots.forEach((l,i)=>{l!==L&&o.push({row:r,col:t.labelCols+i,axis:"col",fields:[l]})})}return o}}function Ot(c,t){let e=0;for(let s=0;s<=t;s++)c[s]!==L&&e++;return e}function De(c){const t=c.showAs?.type;return ae.has(t)?"0.00%":t==="index"?"0.00":"General"}function Fe(c,t,e,s){const n=e.count??10,o=e.by??"items",r=e.bottom===!0,l=c.map(u=>[u,t(u)]).filter(u=>u[1]!==null);l.sort((u,f)=>r?u[1]-f[1]:f[1]-u[1]);const i=new Set;if(o==="items"){if(l.length>0&&n>0){const u=l[Math.min(n,l.length)-1][1];for(const[f,w]of l)(r?w<=u:w>=u)&&i.add(f)}}else{const u=l.reduce((p,h)=>p+h[1],0),f=o==="percent"?u*n/100:n;let w=0;for(const[p,h]of l)if(i.add(p),w+=h,w>=f)break}return s?c.filter(u=>!i.has(u)):c.filter(u=>i.has(u))}function Se(c){return{name:"PivotTable1",rows:[],cols:[],values:[],filters:[],fieldOptions:{},layout:"compact",subtotalTop:!0,grandRow:!0,grandCol:!0,repeatLabels:!1,rowCaption:null,colCaption:null,dataCaption:G("Values"),grandCaption:null,emptyText:"",errorText:null,style:{name:"PivotStyleLight16",rowHeaders:!0,colHeaders:!0,rowStripes:!1,colStripes:!1,lastColumn:!0},showExpandButtons:!0,showFieldHeaders:!0,hideValuesRow:!0,...c}}class Ze{constructor(t,e={}){this.cache=t,this.spec=Se(e),this.rememberLayout(),this.result=null,this.listeners=new Set,this.anchor=null,this.xml=null,this.dirty=!0}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(){this.dirty=!0;for(const t of this.listeners)t(this)}rememberLayout(){this.renderedLayout={cache:this.cache,spec:structuredClone(this.spec)}}update(){if(this.cache.needsRefresh){if(this.cache.source===null)throw new S("The PivotTable report was saved without the underlying data. Its source is not available.");this.cache.refresh()}return this._dropRemoved(),this.result=new Me(this),this._emit(),this.result}rearrange(){return this.result===null?this.update():(this.result.rearrange(),this._emit(),this.result)}refresh(){return this.cache.refresh(),this.update()}_dropRemoved(){const{spec:t,cache:e}=this,s=n=>n===L||!e.fields[n]?.removed;t.rows=t.rows.filter(s),t.cols=t.cols.filter(s),t.filters=t.filters.filter(s),t.values=t.values.filter(n=>s(n.field))}options(t){const{fieldOptions:e}=this.spec;let s=e[t];return s===void 0&&(s={},e[t]=s),s}defaultAgg(t){const e=this.cache.fields[t];return e.isCalculated?"sum":e.base>=0||e.isDate?"count":this._allNumeric(e)?"sum":"count"}_allNumeric(t){return t.strs!==null?!1:t.rawIds!==null?t.shared.every(e=>typeof e=="number"):t.kinds===null?t.nums!==null:t.kinds.every(e=>e===B)}uniqueDataName(t,e=-1){let s=t,n=2;const o=r=>this.spec.values.some((l,i)=>i!==e&&l.name.toLowerCase()===r.toLowerCase());for(;o(s);)s=`${t}${n++}`;return s}addValue(t,e=this.defaultAgg(t),s=this.spec.values.length){const n=this.cache.fields[t],o=Lt(n.isCalculated?"sum":e,n.name);return this.spec.values.splice(s,0,{field:t,agg:e,name:this.uniqueDataName(o)}),this.spec.values.length>1&&!this.spec.rows.includes(L)&&!this.spec.cols.includes(L)&&this.spec.cols.push(L),this.spec.values.length-1}setValueAgg(t,e){const s=this.spec.values[t],n=this.cache.fields[s.field],o=[Lt(s.agg,n.name),`${le[s.agg]} of ${n.name}`].some(r=>new RegExp(`^${Qt(r)}\\d*$`).test(s.name));s.agg=e,o&&(s.name=this.uniqueDataName(Lt(e,n.name),t))}place(t,e,s){const{spec:n}=this;for(const r of["rows","cols","filters"])n[r]=n[r].filter(l=>l!==t);if(t===L&&e==="filters")return;const o=n[e];s===void 0||s>o.length?o.push(t):o.splice(s,0,t)}removeFromLayout(t){const{spec:e}=this;for(const s of["rows","cols","filters"])e[s]=e[s].filter(n=>n!==t);e.values=e.values.filter(s=>s.field!==t),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==L),e.cols=e.cols.filter(s=>s!==L))}removeValue(t){const{spec:e}=this;e.values.splice(t,1),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==L),e.cols=e.cols.filter(s=>s!==L))}moveValue(t,e){const s=this.spec.values,[n]=s.splice(t,1);s.splice(Math.max(0,Math.min(e,s.length)),0,n)}isUsed(t){const{spec:e}=this;return e.rows.includes(t)||e.cols.includes(t)||e.filters.includes(t)||e.values.some(s=>s.field===t)}itemsOf(t){const e=this.cache.fields[t].ensure(),s=e.rank(),n=wt(e,{hidden:this.spec.fieldOptions[t]?.hidden})??new Uint8Array(e.items.length),o=new Array(e.items.length);for(let r=0;r<o.length;r++)o[s[r]]={id:r,key:ut(e.items[r]),label:e.labelOf(r),value:e.items[r],hidden:n[r]===1};return o}itemsWithData(t){const e=this.cache.fields[t].ensure(),s=new Uint8Array(e.items.length),n=this.cache.recordCount,o=[];for(const l of Object.keys(this.spec.fieldOptions)){if(Number(l)===t)continue;const i=this.cache.fields[l];if(!i||i.removed||i.isCalculated)continue;const u=wt(i,this.spec.fieldOptions[l]);if(u!==null&&o.push([i.ensure().ids,u]),this.spec.fieldOptions[l].range||this.spec.fieldOptions[l].dateFilter){const f=zt(i,this.spec.fieldOptions[l]);o.push([i.rawIds,f])}}const{ids:r}=e;t:for(let l=0;l<n;l++){for(let i=0;i<o.length;i++)if(o[i][1][o[i][0][l]]===1)continue t;s[r[l]]=1}return s}setHidden(t,e){const s=this.options(t);s.hidden=[...e]}clearFilters(t){const e=this.options(t);delete e.hidden,delete e.labelFilter,delete e.valueFilter,delete e.top,delete e.range,delete e.dateFilter}hasFilter(t){const e=this.spec.fieldOptions[t];return!!e&&(e.hidden&&e.hidden.length>0||!!e.labelFilter||!!e.valueFilter||!!e.top||!!e.range||!!e.dateFilter)}toggleCollapse(t){const e=this.options(t.field),s=t.path.join(xt),n=new Set(e.collapsed??[]),o=t.path[t.path.length-1];return t.collapsed?(n.delete(s),e.collapsedItems&&(e.collapsedItems=e.collapsedItems.filter(r=>r!==o))):n.add(s),e.collapsed=[...n],this.rearrange()}setFieldCollapsed(t,e){const s=this.options(t);s.collapsed=[];const n=this.cache.fields[t].ensure();return s.collapsedItems=e?n.items.map(o=>ut(o)):[],this.rearrange()}}export{Ke as AGGS,kt as AGG_LABEL,Ne as CellBuffer,Qe as LABEL_FILTERS,Je as LINE,gt as PivotCache,S as PivotError,ft as PivotField,Me as PivotResult,Ze as PivotTable,E as ROLE,je as SHOW_AS,L as VALUES,ze as VALUE_FILTERS,qt as applyNumFmt,Nt as compileCalc,wt as hiddenItemFlags,ut as itemKey,ee as partsToSerial,pt as serialToParts,Ye as showAsNeedsBaseField,Xe as showAsNeedsBaseItem,Ht as storeColumn,Lt as valueFieldName};
|
|
1
|
+
import{withNoDataItems as ue}from"../slicers/pivot-file.js";import{dateOptionFlags as fe}from"../slicers/date-filters.js";import{BOOL as pt,CHUNK_BITS as It,CHUNK_MASK as Rt,EMPTY as j,ERR as mt,ERRORS as Ut,KIND_MASK as $t,NUM as U,STR as Q}from"../core/sheet.js";import{formatGeneral as Bt,getFormatter as Gt,partsToSerial as he,serialToParts as it}from"../core/numfmt.js";import{MAX_COLS as de,MAX_ROWS as pe}from"../core/address.js";import{compareText as qt,ERR as V,ERR_BY_INDEX as Ct,numberToText as me,XlError as $}from"../calc/values.js";import{FUNCS as we}from"../calc/functions/registry.js";import{compileItem as jt,hasCalcItems as xt,placeCalcItems as ge,solveCalcItems as ye,solveOrder as be}from"./calc-items.js";import"../calc/functions/index.js";import{t as B}from"../i18n/index.js";const x=-2,fs=["sum","count","average","max","min","product","countNums","stdDev","stdDevp","var","varp"],Lt={sum:"Sum",count:"Count",average:"Average",max:"Max",min:"Min",product:"Product",countNums:"Count Numbers",stdDev:"StdDev",stdDevp:"StdDevp",var:"Var",varp:"Varp"},Ae={...Lt,countNums:"Count"};function Et(c,t){switch(c){case"count":case"countNums":return B("pivot|Count of {field}",{field:t});case"average":return B("pivot|Average of {field}",{field:t});case"max":return B("pivot|Max of {field}",{field:t});case"min":return B("pivot|Min of {field}",{field:t});case"product":return B("pivot|Product of {field}",{field:t});case"stdDev":return B("pivot|StdDev of {field}",{field:t});case"stdDevp":return B("pivot|StdDevp of {field}",{field:t});case"var":return B("pivot|Var of {field}",{field:t});case"varp":return B("pivot|Varp of {field}",{field:t});default:return B("pivot|Sum of {field}",{field:t})}}const hs=[["normal","No Calculation"],["percentOfTotal","% of Grand Total"],["percentOfCol","% of Column Total"],["percentOfRow","% of Row Total"],["percent","% Of"],["percentOfParentRow","% of Parent Row Total"],["percentOfParentCol","% of Parent Column Total"],["percentOfParent","% of Parent Total"],["difference","Difference From"],["percentDiff","% Difference From"],["runTotal","Running Total In"],["percentOfRunningTotal","% Running Total In"],["rankAscending","Rank Smallest to Largest"],["rankDescending","Rank Largest to Smallest"],["index","Index"]],ve=new Set(["percent","percentOfParent","difference","percentDiff","runTotal","percentOfRunningTotal","rankAscending","rankDescending"]),ds=c=>ve.has(c),ps=c=>c==="percent"||c==="difference"||c==="percentDiff",_e=new Set(["percentOfTotal","percentOfCol","percentOfRow","percent","percentOfParentRow","percentOfParentCol","percentOfParent","percentDiff","percentOfRunningTotal"]),ms=["captionEqual","captionNotEqual","captionBeginsWith","captionNotBeginsWith","captionEndsWith","captionNotEndsWith","captionContains","captionNotContains","captionGreaterThan","captionGreaterThanOrEqual","captionLessThan","captionLessThanOrEqual","captionBetween","captionNotBetween"],ws=["valueEqual","valueNotEqual","valueGreaterThan","valueGreaterThanOrEqual","valueLessThan","valueLessThanOrEqual","valueBetween","valueNotBetween"],N={NONE:0,PAGE_LABEL:1,PAGE_VALUE:2,CORNER:3,HEADER_BLANK:4,COL_CAPTION:5,ROW_CAPTION:6,COL_ITEM:7,COL_SUBTOTAL:8,COL_GRAND:9,DATA_HEADER:10,ROW_ITEM:11,ROW_PARENT:12,ROW_SUBTOTAL:13,ROW_GRAND:14,DATA:15,DATA_PARENT:16,DATA_SUBTOTAL:17,DATA_GRAND_ROW:18,DATA_GRAND_COL:19,PLACEHOLDER:20},W=0,lt=1,st=2,bt=3,gs={ITEM:W,SUBTOTAL:lt,GRAND:st,BLANK:bt};let Ce=0;const J=()=>++Ce,Wt=1<<23,ke=1<<24,Nt="";class L extends Error{constructor(t,e){super(B(t,e))}}function at(c){if(c==null)return"blank";switch(typeof c){case"number":return`n${c}`;case"string":return`s${c.toLowerCase()}`;case"boolean":return c?"b1":"b0";default:return`e${c.code}`}}function Te(c){const t=Math.round(c*86400),e=Math.floor(t/86400);return e+(t-e*86400)/86400}const Ht=c=>c===null?4:typeof c=="number"?0:typeof c=="string"?1:typeof c=="boolean"?2:3,Ie=[["sun","mon","tue","wed","thu","fri","sat"],["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],["january","february","march","april","may","june","july","august","september","october","november","december"]].map(c=>new Map(c.map((t,e)=>[t,e])));function Kt(c){let t=Ie,e=!1;for(const s of c){if(typeof s!="string")continue;e=!0;const n=s.toLowerCase();if(t=t.filter(r=>r.has(n)),t.length===0)return null}return e?t[0]:null}const zt=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Yt=[31,29,31,30,31,30,31,31,30,31,30,31],Re=["seconds","minutes","hours","days","months","quarters","years"],Xt={seconds:"Seconds",minutes:"Minutes",hours:"Hours",days:"Days",months:"Months",quarters:"Quarters",years:"Years"};function xe(c,t){let e=0;for(let s=0;s<c-1;s++)e+=Yt[s];return e+t-1}function Le(c,t,e){switch(c){case"years":{const s=[];for(let n=t;n<=e;n++)s.push(String(n));return s}case"quarters":return["Qtr1","Qtr2","Qtr3","Qtr4"];case"months":return zt;case"days":{const s=[];return Yt.forEach((n,r)=>{for(let o=1;o<=n;o++)s.push(`${o}-${zt[r]}`)}),s}case"hours":{const s=[];for(let n=0;n<24;n++)s.push(`${n%12===0?12:n%12} ${n<12?"AM":"PM"}`);return s}default:{const s=[];for(let n=0;n<60;n++)s.push(`:${n<10?"0":""}${n}`);return s}}}function Ee(c,t,e){switch(c){case"years":return t.year-e;case"quarters":return Math.floor((t.month-1)/3);case"months":return t.month-1;case"days":return xe(t.month,t.day);case"hours":return Math.floor(t.ms/36e5);case"minutes":return Math.floor(t.ms/6e4)%60;default:return Math.floor(t.ms/1e3)%60}}class ct{constructor(t,e,s){this.cache=t,this.index=e,this.name=s,this.numFmt="General",this.isDate=!1,this.kinds=null,this.uniformKind=j,this.nums=null,this.strs=null,this.shared=null,this.rawIds=null,this.ids=null,this.items=null,this.group=null,this.base=-1,this.par=-1,this.calcItems=null,this.formula=null,this.calc=null,this.removed=!1,this.xml=null,this._keys=null,this._rank=null,this.known=[]}get isVirtual(){return this.base>=0||this.formula!==null}get isCalculated(){return this.formula!==null}reset(){this.shared=null,this.rawIds=null,this.invalidate()}invalidate(){this.ids=null,this.items=null,this._keys=null,this._rank=null}ensureRaw(){if(this.rawIds!==null)return this;if(this.cache.load(),this.base>=0){const i=this.cache.fields[this.base].ensureRaw();return this.rawIds=i.rawIds,this.shared=i.shared,this}const t=this.cache.recordCount,e=new Int32Array(t),s=[],{kinds:n,nums:r,strs:o}=this;if(o!==null)Ne(this.cache,o,null,null,t,e,s);else if(r!==null&&n===null&&this.uniformKind===U){const i=new Map;let l=NaN,u=-1;for(let f=0;f<t;f++){const m=r[f];if(m!==l){const y=this.itemValue(m);let p=i.get(y);p===void 0&&(p=s.length,s.push(y),i.set(y,p)),l=m,u=p}e[f]=u}}else n!==null?Oe(this,t,e,s):t>0&&s.push(null);return this.rawIds=e,this.shared=s,this}ensure(){if(this.ids!==null)return this;if(this.ensureRaw(),this.group===null)return this.ids=this.rawIds,this.items=this.calcItems?[...this.shared,...this.calcItems.map(o=>o.name)]:this.shared,this;const{map:t,labels:e}=Me(this),s=this.rawIds,n=s.length,r=new Int32Array(n);for(let o=0;o<n;o++)r[o]=t[s[o]];return this.ids=r,this.items=e,this.groupMap=t,this}ensureColumn(){if(this.nums!==null||this.strs!==null||this.rawIds===null)return this;if(this.base>=0)return this;const t=this.rawIds.length,e=new Uint8Array(t),s=new Float64Array(t),n=this.rawIds,r=this.shared,o=new Uint8Array(r.length),i=new Float64Array(r.length);r.forEach((l,u)=>{typeof l=="number"?(o[u]=U,i[u]=l):typeof l=="string"?o[u]=Q:typeof l=="boolean"?(o[u]=pt,i[u]=l?1:0):l instanceof $&&(o[u]=mt,i[u]=l.index)});for(let l=0;l<t;l++){const u=n[l];e[l]=o[u],s[l]=i[u]}return this.kinds=e,this.nums=s,this}get keyIndex(){if(this._keys===null){this.ensure();const t=new Map;this.items.forEach((e,s)=>{const n=at(e);t.has(n)||t.set(n,s)}),this._keys=t}return this._keys}keyOf(t){return at(this.items[t])}itemValue(t){return this.isDate?Te(t):t}keyOfValue(t){return at(typeof t=="number"?this.itemValue(t):t)}labelOf(t){return this.labelOfValue(this.items[t])}labelOfValue(t){return t==null?"(blank)":typeof t=="string"?t:typeof t=="number"?this.numFmt!=="General"?Gt(this.numFmt).number(t):Bt(t):typeof t=="boolean"?t?"TRUE":"FALSE":t.code}rank(t=!1){if(t&&this.calcItems)return this._rankAll();if(this._rank!==null)return this._rank;this.ensure();const{items:e}=this,s=new Int32Array(e.length);if(this.group!==null&&this.group.kind!=="discrete")for(let n=0;n<s.length;n++)s[n]=n;else{const n=e.length-(this.calcItems?.length??0),r=Kt(e),o=Array.from(e.keys());o.sort((i,l)=>i>=n||l>=n?i-l:Qt(e[i],e[l],r)),o.forEach((i,l)=>{s[i]=l})}return this._rank=s,s}_rankAll(){const{items:t}=this.ensure(),e=Kt(t),s=new Int32Array(t.length);return Array.from(t.keys()).sort((n,r)=>Qt(t[n],t[r],e)).forEach((n,r)=>{s[n]=r}),s}}function Qt(c,t,e){const s=Ht(c),n=Ht(t);return s!==n?s-n:s===0?c-t:s===1?e!==null?e.get(c.toLowerCase())-e.get(t.toLowerCase()):qt(c,t):s===2?c===t?0:c?1:-1:s===3?c.index-t.index:0}function Ne(c,t,e,s,n,r,o){let i=-1;for(let f=0;f<n;f++)t[f]>i&&(i=t[f]);const l=new Int32Array(i+1).fill(-1),u=new Map;for(let f=0;f<n;f++){const m=t[f];let y=l[m];if(y<0){const p=c.getString(m),a=p.toLowerCase();y=u.get(a),y===void 0&&(y=o.length,o.push(p),u.set(a,y)),l[m]=y}r[f]=y}}function Oe(c,t,e,s){const{cache:n,kinds:r,nums:o}=c,i=new Map,l=new Map,u=new Map,f=new Map;let m=-1;for(let y=0;y<t;y++){const p=r[y];let a;if(p===U){const h=c.itemValue(o[y]);a=i.get(h),a===void 0&&(a=s.length,s.push(h),i.set(h,a))}else if(p===Q){const h=o[y];if(a=u.get(h),a===void 0){const d=n.getString(h),b=d.toLowerCase();a=l.get(b),a===void 0&&(a=s.length,s.push(d),l.set(b,a)),u.set(h,a)}}else if(p===j)m<0&&(m=s.length,s.push(null)),a=m;else{const h=p*100+o[y];a=f.get(h),a===void 0&&(a=s.length,s.push(p===pt?o[y]!==0:Ct[o[y]]??V.NA),f.set(h,a))}e[y]=a}}function Me(c){const t=c.group,e=c.shared,s=new Int32Array(e.length);if(t.kind==="date"){const i=it(t.start),l=it(t.end),u=`<${Jt(t.start)}`,f=t.autoEnd?a=>a>=t.end+1:a=>a>t.end,m=`>${Jt(t.autoEnd?t.end+1:t.end)}`,y=Le(t.part,i.year,l.year);let p=[u,...y,m];t.labels&&t.labels.length===p.length&&(p=t.labels);for(let a=0;a<e.length;a++){const h=e[a];typeof h!="number"||h<t.start?s[a]=0:f(h)?s[a]=p.length-1:s[a]=1+Ee(t.part,it(h),i.year)}return{map:s,labels:p}}if(t.kind==="bins"){const{start:i,end:l,interval:u}=t,f=Math.max(1,Math.ceil((l-i)/u-1e-9)),m=[`<${kt(i)}`];for(let p=0;p<f;p++){const a=i+p*u,h=t.integer?Math.max(a+u-1,p===f-1?l:0):a+u;m.push(`${kt(a)}-${kt(h)}`)}m.push(`>${kt(l)}`);const y=t.labels&&t.labels.length===m.length?t.labels:m;for(let p=0;p<e.length;p++){const a=e[p];typeof a!="number"||a<i?s[p]=0:a>l?s[p]=f+1:s[p]=1+Math.min(f-1,Math.floor((a-i)/u+1e-9))}return{map:s,labels:y}}const n=t.groups.map(i=>i.name),r=new Map;t.groups.forEach((i,l)=>{for(const u of i.keys)r.set(u,l)});const o=new Map;for(let i=0;i<e.length;i++){const l=at(e[i]);let u=r.get(l);u===void 0&&(u=o.get(l),u===void 0&&(u=n.length,n.push(e[i]),o.set(l,u))),s[i]=u}return{map:s,labels:n}}const kt=c=>me(Number(c.toPrecision(12)));function Jt(c){const t=it(c);return`${t.month}/${t.day}/${t.year}`}class Se{constructor(){this.list=[],this.index=new Map}get size(){return this.list.length}get(t){return this.list[t]??""}add(t){let e=this.index.get(t);return e===void 0&&(e=this.list.length,this.list.push(t),this.index.set(t,e)),e}}function De(c,t,e,s,n,r){const o=c.columns[t];if(o===void 0)return;const i=e+s;for(let l=e>>>It;l<=i-1>>>It;l++){const u=o[l];if(u===void 0)continue;const f=l<<It,m=Math.max(e,f)&Rt,y=Math.min(i-1,f+Rt)&Rt,p=f-e,a=u.kinds,h=u.values;for(let d=m;d<=y;d++)n[p+d]=a[d]&$t,r[p+d]=h[d]}}function Fe(c,t,e){const s=new Int32Array(t);let n=0;for(let r=0;r<t;r++)e(c+r)||(s[n++]=r);return n===t?null:s.subarray(0,n)}function Zt(c){const t=c.book.engine?.tables;if(!t)return c.table;const e=t.get(c.table.name.toUpperCase());return e&&(c.table=e),e??null}function te(c){if(c.locate){const s=c.locate();if(!s)return null;Object.assign(c,s)}const{book:t,sheet:e}=c;return t.sheets.find(s=>typeof e=="string"?s.name===e:s===e)??null}class At{constructor(){this.fields=[],this.recordCount=0,this.strings=new Se,this.source=null,this.generation=0,this.xml=null,this.id=0,this.recordsPart=null,this.links=[],this.needsRefresh=!1,this.deferred=!1}getString(t){return this.strings.get(t)}field(t){if(typeof t=="number")return this.fields[t];const e=String(t).toLowerCase();return this.fields.find(s=>s.name.toLowerCase()===e&&!s.removed)}fieldIndex(t){if(typeof t=="number")return t;const e=this.field(t);if(!e)throw new L("Unknown field: {name}",{name:t});return e.index}static fromSheet(t,e,s){const n=new At;return n.strings=t.strings,n.source={type:"range",book:t,sheet:e,range:s},n.refresh(),n}static fromTable(t,e){const s=new At;return s.strings=t.strings,s.source={type:"table",book:t,table:e},s.refresh(),s}static fromRows(t,e){const s=new At,n=e.length;return s.recordCount=n,t.forEach((r,o)=>{const i=new Uint8Array(n),l=new Float64Array(n);for(let f=0;f<n;f++){const m=e[f][o];typeof m=="number"?(i[f]=U,l[f]=m):typeof m=="string"?(i[f]=Q,l[f]=s.strings.add(m)):typeof m=="boolean"?(i[f]=pt,l[f]=m?1:0):m instanceof $&&(i[f]=mt,l[f]=m.index)}const u=new ct(s,o,r);se(u,i,l,n),s.fields.push(u)}),s}static fromColumns(t,e,s){const n=new At;return s&&(n.strings=s),n.recordCount=e,t.forEach((r,o)=>{const i=new ct(n,o,r.name);i.kinds=r.kinds??null,i.nums=r.nums??null,i.strs=r.strs??null,i.uniformKind=r.strs?Q:r.kinds?j:U,r.numFmt&&ee(i,r.numFmt),n.fields.push(i)}),n}require(){if(this.deferred&&!this.refresh())throw new L("The PivotTable report was saved without the underlying data. Its source is not available.")}snapshot(){const{fields:t,recordCount:e,strings:s,generation:n,needsRefresh:r,deferred:o}=this,i=t.map(l=>({f:l,state:{...l,group:l.group&&{...l.group}}}));return()=>{Object.assign(this,{fields:i.map(({f:l,state:u})=>Object.assign(l,u)),recordCount:e,strings:s,generation:n,needsRefresh:r,deferred:o})}}load(){if(!(!this.deferred||this.source===null))try{this.refresh()}catch(t){if(!(t instanceof L))throw t}}get hasSource(){const t=this.source;return t!==null&&!t.deleted&&(t.type==="table"?Zt(t):te(t))!==null}refresh(){const t=this.source;if(t===null){for(const a of this.fields)a.invalidate();return this.generation=J(),!1}const{book:e}=t;this.strings=e.strings;let s,n,r,o,i;if(t.type==="table"){const a=Zt(t);if(!a)throw new L("The PivotTable source table no longer exists.");s=a.sheet??e.sheets[a.sheetIndex],n=a.r0,r=a.c0,o=a.r1-(a.totalsRows??0),i=a.c1}else{if(s=te(t),!s)throw new L("The PivotTable source sheet no longer exists.");if(t.deleted)throw new L("The PivotTable source range no longer exists.");({r0:n,c0:r,r1:o,c1:i}=t.range),o=Math.min(o,s.maxRow),i=Math.min(i,s.maxCol)}if(o<=n)throw new L("The PivotTable source needs a header row and at least one row of data.");if(t.headers&&t.headers.length!==i-r+1)throw new L("The PivotTable source needs a header for every column.");const l=o-n,u=t.skipRow?Fe(n+1,l,t.skipRow):null,f=u?u.length:l;if(f===0)throw new L("The PivotTable source needs a header row and at least one row of data.");const m=new Set,y=[];for(let a=r;a<=i;a++){const h=t.headers?String(t.headers[a-r]).trim():Ve(e,s,n,a);if(h==="")throw new L("The PivotTable field name is not valid: every source column needs a header.");let d=h;for(let b=2;m.has(d.toLowerCase());b++)d=`${h}${b}`;m.add(d.toLowerCase()),y.push(d)}for(const a of this.fields)(a.items!==null||a.shared!==null)&&(a.known=[...a.known.slice(-7),{generation:this.generation,keys:new Set(a.keyIndex.keys())}]);const p=new Map(this.fields.filter(a=>!a.isVirtual).map(a=>[a.name.toLowerCase(),a]));this.recordCount=f,y.forEach((a,h)=>{let d=p.get(a.toLowerCase());d?p.delete(a.toLowerCase()):(d=new ct(this,this.fields.length,a),this.fields.push(d));const b=r+h;let v=new Uint8Array(l),w=new Float64Array(l);De(s,b,n+1,l,v,w),u&&(v=Uint8Array.from(u,g=>v[g]),w=Float64Array.from(u,g=>w[g])),se(d,v,w,f),d.removed=!1,d.reset();for(let g=0;g<f;g++)if(v[g]!==j){ee(d,e.styles.get(s.style(n+1+(u?u[g]:g),b)).numFmt);break}});for(const a of p.values())a.removed=!0,a.kinds=null,a.nums=null,a.strs=null,a.uniformKind=j,a.reset();for(const a of this.fields)a.isVirtual&&a.reset();return this.needsRefresh=!1,this.deferred=!1,this._rescaleGroups(),this.generation=J(),!0}_rescaleGroups(){for(const t of this.fields){const e=t.group;if(t.base<0&&!t.removed&&e===null&&t.par>=0&&this.fields[t.par].group?.kind==="date"){this._rescaleAbove(t);continue}if(t.base>=0||t.removed||e===null||e.kind==="discrete"||!(e.autoStart||e.autoEnd))continue;let s;try{s=this._numericRange(t)}catch{continue}for(let n=t;n;n=n.par>=0?this.fields[n.par]:null){const r=n.group;r.autoStart&&(r.start=e.kind==="date"?Math.floor(s.min):s.min),r.autoEnd&&(r.end=e.kind==="date"?Math.floor(s.max):s.max),r.labels=void 0}}}_rescaleAbove(t){let e;try{e=this._numericRange(t,{blanks:!0})}catch{return}for(const{group:s}of this.fields.filter(n=>n.base===t.index&&!n.removed&&n.group?.kind==="date"))s.autoStart&&(s.start=Math.floor(e.min)),s.autoEnd&&(s.end=Math.floor(e.max)),s.labels=void 0}renameFields(t){const e=new Map(Object.entries(t).map(([s,n])=>[s.toLowerCase(),n]));for(const s of this.fields)s.isCalculated?(s.formula=Ue(s.formula,e),s.calc=null):s.isVirtual||(s.name=e.get(s.name.toLowerCase())??s.name);this.generation=J()}addCalculatedField(t,e){const s=new ct(this,this.fields.length,this._uniqueName(t));return s.formula=e.replace(/^\s*=\s*/,""),s.calc=Mt(s.formula,this),this.fields.push(s),s.index}addCalculatedItem(t,e,s,n=[]){const r=this.fields[t];if(r.isVirtual||r.removed)throw new L("A calculated item can't be added to this field.");if(r.group!==null||r.par>=0)throw new L("A calculated item can't be added to a grouped field. Ungroup it first.");const o=e.trim();if(o==="")throw new L("Enter a name.");if(r.ensure(),r.items.some((u,f)=>r.labelOf(f).toLowerCase()===o.toLowerCase()))throw new L("The field already has an item with this name.");for(const u of n)u.cache===this&&Tt(u.spec,this,r.index);const i={name:o,formula:s.replace(/^\s*=\s*/,""),order:1+Math.max(-1,...be(this).map(u=>u.item.order))},l=r.calcItems;r.calcItems=[...l??[],i],r.invalidate();try{jt(this,r,i.formula,o)}catch(u){throw r.calcItems=l,r.invalidate(),u}return this.generation=J(),r.items.length-1}updateCalculatedItem(t,e,s){const n=this.fields[t],r=s.replace(/^\s*=\s*/,"");jt(this,n,r,e),n.calcItems=n.calcItems.map(o=>o.name===e?{...o,formula:r}:o),this.generation=J()}removeCalculatedItem(t,e){const s=this.fields[t],n=(s.calcItems??[]).filter(r=>r.name!==e);s.calcItems=n.length?n:null,s.invalidate(),this.generation=J()}setSolveOrder(t){for(const e of this.fields)e.calcItems&&(e.calcItems=e.calcItems.map(s=>{const n=t.findIndex(r=>r.field===e.index&&r.name===s.name);return{...s,order:n<0?t.length:n}}));this.generation=J()}updateCalculatedField(t,e){const s=this.fields[t],n=e.replace(/^\s*=\s*/,"");s.calc=Mt(n,this),s.formula=n,this.generation=J()}_uniqueName(t){let e=t,s=2;for(;this.fields.some(n=>n.name.toLowerCase()===e.toLowerCase());)e=`${t}${s++}`;return e}_numericRange(t,{blanks:e=!1}={}){t.ensureRaw();let s=1/0,n=-1/0,r=!0;for(const o of t.shared)if(!(o===null&&e)){if(typeof o!="number")throw new L("Cannot group that selection.");o<s&&(s=o),o>n&&(n=o),Number.isInteger(o)||(r=!1)}if(s===1/0)throw new L("Cannot group that selection.");return{min:s,max:n,integer:r}}groupDates(t,e,{start:s,end:n}={}){const r=this.fields[t];if(r.isCalculated||r.base>=0||r.calcItems)throw new L("Cannot group that selection.");const{min:o,max:i}=this._numericRange(r),l=Re.filter(y=>e.includes(y));if(l.length===0)throw new L("Choose at least one grouping unit.");this.ungroup(t);const u={start:s??Math.floor(o),end:n??Math.floor(i)};r.group={kind:"date",part:l[0],...u,autoStart:s===void 0,autoEnd:n===void 0},r.invalidate();const f=[t];let m=r;for(const y of l.slice(1)){const p=new ct(this,this.fields.length,this._uniqueName(Xt[y]));p.base=t,p.group={kind:"date",part:y,...u,autoStart:s===void 0,autoEnd:n===void 0},this.fields.push(p),m.par=p.index,m=p,f.unshift(p.index)}return f}autoGroupDates(t){const e=this.fields[t];if(!e.isDate||e.isCalculated||e.base>=0||e.group!==null||e.par>=0||e.calcItems)return null;let s;try{s=this._numericRange(e,{blanks:!0})}catch{return null}const n=it(s.min),r=it(s.max);let o;if(n.year!==r.year)o=["months","quarters","years"];else if(n.month!==r.month)o=["days","months"];else if(n.day!==r.day&&!s.integer)o=[...e.shared.some(f=>f!==null&&Math.round(f*86400)%60!==0)?["seconds"]:[],"minutes","hours","days"];else return null;const i=[t];let l=e;for(const u of o){let f=this.fields.find(m=>m.removed&&m.base===t&&m.group?.kind==="date"&&m.group.part===u);f||(f=new ct(this,this.fields.length,this._uniqueName(`${Xt[u]} (${e.name})`)),this.fields.push(f)),f.removed=!1,f.par=-1,f.invalidate(),f.base=t,f.group={kind:"date",part:u,start:Math.floor(s.min),end:Math.floor(s.max),autoStart:!0,autoEnd:!0},l.par=f.index,l=f,i.unshift(f.index)}return i}groupState(){return this.fields.map(t=>({group:t.group&&{...t.group,...t.group.groups?{groups:[...t.group.groups]}:{}},par:t.par,removed:t.removed}))}restoreGroups(t){this.fields.forEach((e,s)=>{const n=t[s]??(e.base>=0?{group:e.group,par:-1,removed:!0}:null);n&&(e.group=n.group&&{...n.group},e.par=n.par,e.removed=n.removed,e.invalidate())}),this.renderedGroups=this.groupState(),this.generation=J()}groupNumbers(t,{start:e,end:s,interval:n=10}={}){const r=this.fields[t];if(r.isCalculated||r.base>=0||r.calcItems)throw new L("Cannot group that selection.");if(!(n>0))throw new L("The grouping interval must be greater than zero.");const{min:o,max:i,integer:l}=this._numericRange(r);this.ungroup(t);const u=e??o,f=s??i;if(f<=u)throw new L("The ending value must be greater than the starting value.");return r.group={kind:"bins",start:u,end:f,interval:n,integer:l&&Number.isInteger(u)&&Number.isInteger(n),autoStart:e===void 0,autoEnd:s===void 0},r.invalidate(),t}groupText(t,e,s){const n=this.fields[t];if(n.isCalculated||n.calcItems)throw new L("Cannot group that selection.");n.ensureRaw();let r=n.par>=0?this.fields[n.par]:null;if(r&&r.group?.kind!=="discrete")throw new L("Cannot group that selection.");return r?(r.group.groups.push(...e),r.invalidate(),r.index):(r=new ct(this,this.fields.length,this._uniqueName(s??`${n.name}2`)),r.base=t,r.group={kind:"discrete",groups:e.map(o=>({name:o.name,keys:[...o.keys]}))},this.fields.push(r),n.par=r.index,r.index)}ungroup(t){const e=this.fields[t];if(e.base>=0&&e.group?.kind==="discrete"){this.fields[e.base].par=-1,e.removed=!0,e.group={kind:"discrete",groups:[]},e.invalidate();return}e.group=null,e.invalidate();let s=e.par;for(e.par=-1;s>=0;){const n=this.fields[s];n.removed=!0,s=n.par,n.par=-1}}}function ee(c,t){c.numFmt=t??"General";try{c.isDate=c.numFmt!=="General"&&Gt(c.numFmt).isDate===!0}catch{c.isDate=!1}}function Ve(c,t,e,s){const n=t.kind(e,s)&$t,r=t.value(e,s);return n===Q?c.strings.get(r).trim():n===U?Bt(r):n===pt?r?"TRUE":"FALSE":n===mt?Ut[r]??"":""}function se(c,t,e,s){let n=0,r=0;for(let o=0;o<s;o++){const i=t[o];i===U?n++:i===Q&&r++}if(c.strs=null,c.kinds=null,c.nums=null,n===s&&s>0)c.uniformKind=U,c.nums=e;else if(r===s&&s>0){c.uniformKind=Q;const o=new Int32Array(s);for(let i=0;i<s;i++)o[i]=e[i];c.strs=o}else c.uniformKind=j,c.kinds=t,c.nums=e}const Pe=["<=",">=","<>","+","-","*","/","^","%","(",")",",","=","<",">","&"];function Ue(c,t){return c.replace(/"(?:[^"]|"")*"|'((?:[^']|'')*)'|[\p{L}_\\][\p{L}\p{N}_.\\]*(?!\s*\(|[\p{L}\p{N}_.\\])/gu,(e,s)=>{if(e[0]==='"')return e;const n=t.get((s===void 0?e:s.replace(/''/g,"'")).toLowerCase());return n===void 0?e:`'${n.replace(/'/g,"''")}'`})}function $e(c){const t=[];let e=0;for(;e<c.length;){const s=c[e];if(s<=" ")e++;else if(s>="0"&&s<="9"||s==="."&&c[e+1]>="0"&&c[e+1]<="9"){const n=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(c.slice(e));t.push({t:"num",v:Number(n[0])}),e+=n[0].length}else if(s==="'"||s==='"'){let n=e+1,r="";for(;;){if(n>=c.length)throw new L("The formula has an unmatched quote.");if(c[n]===s){if(c[n+1]!==s)break;n++}r+=c[n++]}t.push({t:s==="'"?"name":"str",v:r,start:e,end:n+1}),e=n+1}else if(/[\p{L}_\\]/u.test(s)){const n=/^[\p{L}\p{N}_.\\]+/u.exec(c.slice(e));t.push({t:"name",v:n[0],bare:!0,start:e,end:e+n[0].length}),e+=n[0].length}else if(s==="["&&t.at(-1)?.t==="name"&&t.at(-1).end===e&&t.at(-1).item===void 0){const n=/^\[\s*(?:'((?:[^']|'')*)'|([^\]']*))\s*\]/u.exec(c.slice(e));if(!n)throw new L("The formula is not valid.");const r=t.at(-1);r.item=n[1]!==void 0?n[1].replace(/''/g,"'"):n[2].trim(),r.quoted=n[1]!==void 0,r.bare=!1,e+=n[0].length,r.end=e}else{const n=Pe.find(r=>c.startsWith(r,e));if(!n)throw new L("The formula has an unexpected character: {char}",{char:s});t.push({t:"op",v:n}),e+=n.length}}return t}const ne=c=>c instanceof $?c:null,D=c=>{if(typeof c=="number")return c;if(typeof c=="boolean")return c?1:0;if(c===null)return 0;if(c instanceof $)throw c;const t=Number(c);if(typeof c=="string"&&c.trim()!==""&&!Number.isNaN(t))return t;throw V.VALUE},re={IF:c=>{const t=c[0]();if(ne(t))throw t;return(typeof t=="number"?t!==0:t===!0)?c[1]?c[1]():!0:c[2]?c[2]():!1},IFERROR:c=>{try{const t=c[0]();return ne(t)?c[1]():t}catch(t){if(t instanceof $)return c[1]();throw t}},AND:c=>c.every(t=>D(t())!==0),OR:c=>c.some(t=>D(t())!==0),NOT:c=>D(c[0]())===0,SUM:c=>c.reduce((t,e)=>t+D(e()),0),MIN:c=>Math.min(...c.map(t=>D(t()))),MAX:c=>Math.max(...c.map(t=>D(t()))),AVERAGE:c=>c.reduce((t,e)=>t+D(e()),0)/c.length,COUNT:c=>c.length,TRUE:()=>!0,FALSE:()=>!1},Ot=new Set;function oe(c,t){if(c.calc)return c.calc;if(Ot.has(c))throw new L("The formula is not valid.");Ot.add(c);try{c.calc=Mt(c.formula,t)}finally{Ot.delete(c)}return c.calc}function Mt(c,t,e=null){const s=$e(c);let n=0;const r=new Set,o=w=>s[n]?.t==="op"&&s[n].v===w,i=()=>new L("The formula is not valid."),l=w=>{const g=t.fields.find(_=>_.name.toLowerCase()===w.v.toLowerCase()&&!_.isCalculated),C=t.fields.find(_=>_.name.toLowerCase()===w.v.toLowerCase()&&_.isCalculated);if(C){oe(C,t);for(const _ of C.calc.refs)r.add(_);return _=>C.calc.fn(_)}if(!g||w.item!==void 0)throw new L("The formula refers to an unknown field: {name}",{name:w.item??w.v});r.add(g.index);const A=g.index;return _=>_(A)},u=()=>{const w=s[n];if(!w)throw i();if(w.t==="num"){n++;const g=w.v;return()=>g}if(w.t==="str"){n++;const g=w.v;return()=>g}if(w.t==="name"){if(n++,w.bare&&o("(")){n++;const g=[];if(!o(")"))for(g.push(h());o(",");)n++,g.push(h());if(!o(")"))throw i();return n++,d(w.v.toUpperCase(),g)}if(w.bare&&b.has(w.v.toUpperCase())&&(e||!t.field(w.v))){const g=re[w.v.toUpperCase()];return()=>g([])}return e?e(w):l(w)}if(o("(")){n++;const g=h();if(!o(")"))throw i();return n++,g}throw i()},f=()=>{let w=u();for(;o("%");){n++;const g=w;w=C=>D(g(C))/100}return w},m=()=>{if(o("-")){n++;const w=m();return g=>-D(w(g))}return o("+")?(n++,m()):f()},y=()=>{let w=m();for(;o("^");){n++;const g=w,C=m();w=A=>{const _=D(g(A))**D(C(A));if(!Number.isFinite(_))throw V.NUM;return _}}return w},p=()=>{let w=y();for(;o("*")||o("/");){const g=s[n++].v,C=w,A=y();w=g==="*"?_=>D(C(_))*D(A(_)):_=>{const k=D(A(_));if(k===0)throw V.DIV0;return D(C(_))/k}}return w},a=()=>{let w=p();for(;o("+")||o("-");){const g=s[n++].v,C=w,A=p();w=g==="+"?_=>D(C(_))+D(A(_)):_=>D(C(_))-D(A(_))}return w},h=()=>{let w=a();for(;s[n]?.t==="op"&&["=","<>","<",">","<=",">="].includes(s[n].v);){const g=s[n++].v,C=w,A=a();w=_=>{const k=D(C(_)),I=D(A(_));switch(g){case"=":return k===I;case"<>":return k!==I;case"<":return k<I;case">":return k>I;case"<=":return k<=I;default:return k>=I}}}return w},d=(w,g)=>{const C=re[w];if(C)return _=>C(g.map(k=>()=>k(_)));const A=we.get(w);if(!A||A.kind!=="lift")throw new L("The formula uses a function a calculated field can't call: {name}",{name:w});if(g.length<A.min||g.length>A.max)throw i();return _=>{const k=g.map(I=>I(_));for(const I of k)if(I instanceof $)throw I;return A.fn(...k)}},b=new Set(["TRUE","FALSE"]),v=h();if(n<s.length)throw i();return{fn:v,refs:[...r]}}const Be={sum:"sum",average:"sum",count:"",countNums:"",max:"mm",min:"mm",product:"prod",stdDev:"var",stdDevp:"var",var:"var",varp:"var"},Ge={count:"cnt",countNums:"num",sum:"sum",average:"sum",max:"max",min:"min",product:"prod",stdDev:"mean",stdDevp:"mean",var:"mean",varp:"mean"};class St{constructor(t,e){this.size=t,this.cnt=new Int32Array(t),this.num=new Int32Array(t),this.sum=e.sum?new Float64Array(t):null,this.min=e.mm?new Float64Array(t).fill(1/0):null,this.max=e.mm?new Float64Array(t).fill(-1/0):null,this.prod=e.prod?new Float64Array(t).fill(1):null,this.mean=e.var?new Float64Array(t):null,this.m2=e.var?new Float64Array(t):null,this.err=null,this.cntMore=null,this.numMore=null,this.calcErrs=null}setCalculated(t,e,s){this.cnt[t]=1,this.num[t]=1,this.cntMore??=new Float64Array(this.size),this.numMore??=new Float64Array(this.size),this.cntMore[t]=(e.cnt??1)-1,this.numMore[t]=(e.num??1)-1;for(const n of["sum","min","max","prod","mean"])this[n]!==null&&(this[n][t]=e[n]??0);this.m2!==null&&(this.m2[t]=0);for(const n of Object.keys(s))this._calcErrsOf(n)[t]=s[n]}_calcErrsOf(t){return this.calcErrs??={},this.calcErrs[t]??=new Int8Array(this.size)}merge(t,e,s){const n=e.cnt[s];if(n===0)return;this.cnt[t]+=n;const r=e.num[s],o=this.num[t];if(this.num[t]=o+r,e.cntMore!==null&&(this.cntMore??=new Float64Array(this.size),this.numMore??=new Float64Array(this.size),this.cntMore[t]+=e.cntMore[s],this.numMore[t]+=e.numMore[s]),e.calcErrs!==null)for(const i in e.calcErrs){const l=e.calcErrs[i][s];if(l===0)continue;const u=this._calcErrsOf(i);u[t]===0&&(u[t]=l)}if(e.err!==null&&e.err[s]!==0&&(this.err===null&&(this.err=new Int8Array(this.size)),this.err[t]===0&&(this.err[t]=e.err[s])),r!==0&&(this.sum!==null&&(this.sum[t]+=e.sum[s]),this.min!==null&&(e.min[s]<this.min[t]&&(this.min[t]=e.min[s]),e.max[s]>this.max[t]&&(this.max[t]=e.max[s])),this.prod!==null&&(this.prod[t]*=e.prod[s]),this.mean!==null)){const i=e.mean[s]-this.mean[t],l=o+r;this.m2[t]+=e.m2[s]+i*i*o*r/l,this.mean[t]+=i*r/l}}value(t,e){const s=this.cnt[t];if(s===0)return null;const n=this.calcErrs?.[Ge[e]]?.[t]??0;if(n!==0)return Ct[n-1];if(e==="count")return s+(this.cntMore?.[t]??0);if(e==="countNums")return this.num[t]+(this.numMore?.[t]??0);if(this.err!==null&&this.err[t]!==0)return Ct[this.err[t]-1];const r=this.num[t];switch(e){case"sum":return this.sum[t];case"average":return r===0?V.DIV0:this.sum[t]/r;case"max":return r===0?0:this.max[t];case"min":return r===0?0:this.min[t];case"product":return r===0?0:this.prod[t];case"stdDev":return r<2?V.DIV0:Math.sqrt(this.m2[t]/(r-1));case"stdDevp":return r<1?V.DIV0:Math.sqrt(this.m2[t]/r);case"var":return r<2?V.DIV0:this.m2[t]/(r-1);case"varp":return r<1?V.DIV0:this.m2[t]/r;default:return null}}}function qe(c,t,e,s){const{cnt:n,num:r}=c;t.base<0&&t.ensureColumn();const{kinds:o,nums:i}=t;if(i===null||t.base>=0){for(let a=0;a<s;a++){const h=e[a];h>=0&&n[h]++}return}if(o===null){for(let a=0;a<s;a++){const h=e[a];h>=0&&n[h]++}r.set(n)}else for(let a=0;a<s;a++){const h=e[a];if(h<0)continue;const d=o[a];d!==j&&(n[h]++,d===U?r[h]++:d===mt&&(c.err===null&&(c.err=new Int8Array(c.size)),c.err[h]===0&&(c.err[h]=i[a]+1)))}const{sum:l,min:u,max:f,prod:m,mean:y,m2:p}=c;if(l!==null)if(o===null)for(let a=0;a<s;a++){const h=e[a];h>=0&&(l[h]+=i[a])}else for(let a=0;a<s;a++){const h=e[a];h>=0&&o[a]===U&&(l[h]+=i[a])}if(u!==null)for(let a=0;a<s;a++){const h=e[a];if(h<0||o!==null&&o[a]!==U)continue;const d=i[a];d<u[h]&&(u[h]=d),d>f[h]&&(f[h]=d)}if(m!==null)for(let a=0;a<s;a++){const h=e[a];h>=0&&(o===null||o[a]===U)&&(m[h]*=i[a])}if(y!==null){const a=new Int32Array(c.size);for(let h=0;h<s;h++){const d=e[h];if(d<0||o!==null&&o[h]!==U)continue;const b=++a[d],v=i[h]-y[d];y[d]+=v/b,p[d]+=v*(i[h]-y[d])}}}class je{constructor(t,e,s){this.fields=e,this.slots=s,this.k=e.length,this.levels=[],this.leaf=null,this.nLeaves=1,this.levelBase=[1],this.noData=[],this.nNodes=1,this.parent=new Int32Array([-1]),this.item=new Int32Array([-1]),this.depth=new Uint8Array(1),this.cache=t,this.alive=null,this.childStart=null,this.childList=null,this.pos=null,this._childIndex=null,this.lines=null}leafNode(t){return this.k===0?0:this.levelBase[this.k-1]+t}ancestorAt(t,e){let s=t;for(;this.depth[s]>e;)s=this.parent[s];return this.depth[s]===e?s:-1}fieldAt(t){return this.cache.fields[this.fields[t-1]]}children(t){return this.childList.subarray(this.childStart[t],this.childStart[t+1])}findChild(t,e){if(this._childIndex===null){const s=new Map;this.stride=1;for(const n of this.fields)this.stride=Math.max(this.stride,this.cache.fields[n].items.length+1);for(let n=1;n<this.nNodes;n++)this.alive[n]&&s.set(this.parent[n]*this.stride+this.item[n],n);this._childIndex=s}return this._childIndex.get(t*this.stride+e)??-1}pathKeys(t){const e=[];for(let s=t;s>0;s=this.parent[s])e.push(this.fieldAt(this.depth[s]).keyOf(this.item[s]));return e.reverse()}peer(t,e,s){if(s<0)return-1;if(this.depth[t]===e)return s;const n=[];for(let o=t;this.depth[o]>e;o=this.parent[o])n.push(this.item[o]);let r=s;for(let o=n.length-1;o>=0&&r>=0;o--)r=this.findChild(r,n[o]);return r}}function ie(c,t,e,s,n,r=null){const o=new je(c,t,e),i=t.length;if(i===0)return o;let l=null,u=1;const f=[];for(let m=0;m<i;m++){const y=c.fields[t[m]].ensure(),p=y.ids,a=y.items.length,h=u*a,d=new Int32Array(s),b=Math.min(h,Math.max(s,1)),v=new Int32Array(b),w=new Int32Array(b);let g=0;if(h<=Wt){const _=new Int32Array(h).fill(-1);if(l===null)for(let k=0;k<s;k++){if(n!==null&&n[k]===0){d[k]=-1;continue}const I=p[k];let E=_[I];E<0&&(E=g++,_[I]=E,w[E]=I),d[k]=E}else for(let k=0;k<s;k++){const I=l[k];if(I<0){d[k]=-1;continue}const E=I*a+p[k];let O=_[E];O<0&&(O=g++,_[E]=O,v[O]=I,w[O]=p[k]),d[k]=O}}else{const _=new Map;for(let k=0;k<s;k++){const I=l===null?0:l[k];if(I<0||l===null&&n!==null&&n[k]===0){d[k]=-1;continue}const E=I*a+p[k];let O=_.get(E);O===void 0&&(O=g++,_.set(E,O),v[O]=I,w[O]=p[k]),d[k]=O}}const C=r?.(t[m]),A=C?ue({parents:v,items:w,count:g},m===0?1:f[m-1].count,a,C.hide):{parents:v,items:w,count:g};A.recorded=g,f.push(A),l=d,u=Math.max(A.count,1)}return o.leaf=l,Dt(o,f),o}function Dt(c,t){c.levels=t,c.nLeaves=t[t.length-1].count;let e=1;const s=[];for(const n of t)s.push(e),e+=n.count;c.levelBase=s,c.noData=t.map((n,r)=>[s[r]+n.recorded,s[r]+(n.listed??n.count)]),c.nNodes=e,c.parent=new Int32Array(e),c.item=new Int32Array(e),c.depth=new Uint8Array(e),c.parent[0]=-1,c.item[0]=-1,t.forEach((n,r)=>{const o=s[r],i=r===0?0:s[r-1];for(let l=0;l<n.count;l++)c.parent[o+l]=r===0?0:i+n.parents[l],c.item[o+l]=n.items[l],c.depth[o+l]=r+1})}class We{constructor(t=1024){this.count=0,this.capacity=t,this.rows=new Int32Array(t),this.cols=new Int32Array(t),this.kinds=new Uint8Array(t),this.values=new Float64Array(t),this.roles=new Uint8Array(t),this.levels=new Uint8Array(t),this.formats=new Uint16Array(t),this.texts=[],this._textIndex=new Map,this.formatList=["General"],this._formatIndex=new Map([["General",0]])}_grow(){const t=this.capacity*2,e=(s,n)=>{const r=new s(t);return r.set(n),r};this.rows=e(Int32Array,this.rows),this.cols=e(Int32Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.values=e(Float64Array,this.values),this.roles=e(Uint8Array,this.roles),this.levels=e(Uint8Array,this.levels),this.formats=e(Uint16Array,this.formats),this.capacity=t}format(t){let e=this._formatIndex.get(t);return e===void 0&&(e=this.formatList.length,this.formatList.push(t),this._formatIndex.set(t,e)),e}text(t){let e=this._textIndex.get(t);return e===void 0&&(e=this.texts.length,this.texts.push(t),this._textIndex.set(t,e)),e}push(t,e,s,n,r,o=0,i=0){this.count===this.capacity&&this._grow();const l=this.count++;this.rows[l]=t,this.cols[l]=e,this.kinds[l]=s,this.values[l]=n,this.roles[l]=r,this.levels[l]=o,this.formats[l]=i}pushValue(t,e,s,n,r=0,o=0){s==null?this.push(t,e,j,0,n,r,o):typeof s=="number"?this.push(t,e,U,s,n,r,o):typeof s=="string"?this.push(t,e,Q,this.text(s),n,r,o):typeof s=="boolean"?this.push(t,e,pt,s?1:0,n,r,o):this.push(t,e,mt,s.index,n,r,o)}valueAt(t){switch(this.kinds[t]){case U:return this.values[t];case Q:return this.texts[this.values[t]];case pt:return this.values[t]!==0;case mt:return Ut[this.values[t]]??"#N/A";default:return null}}}function le(c){const t=c.replace(/[.+^${}()|[\]\\*?~]/g,e=>e==="*"?".*":e==="?"?".":`\\${e}`);return new RegExp(`^${t}$`,"is")}const ae=c=>c.replace(/[.+^${}()|[\]\\]/g,"\\$&");function He(c){const{op:t}=c,e=String(c.value??""),s=String(c.value2??""),n=e.split(/([*?])/).map(o=>o==="*"?".*":o==="?"?".":ae(o)).join(""),r=(o,i,l)=>{const u=typeof i=="number"?i:Number.NaN,f=l.trim()===""?Number.NaN:Number(l);return!Number.isNaN(u)&&!Number.isNaN(f)?u-f:qt(o,l)};switch(t){case"captionEqual":{const o=le(e);return i=>o.test(i)}case"captionNotEqual":{const o=le(e);return i=>!o.test(i)}case"captionBeginsWith":{const o=new RegExp(`^${n}`,"is");return i=>o.test(i)}case"captionNotBeginsWith":{const o=new RegExp(`^${n}`,"is");return i=>!o.test(i)}case"captionEndsWith":{const o=new RegExp(`${n}$`,"is");return i=>o.test(i)}case"captionNotEndsWith":{const o=new RegExp(`${n}$`,"is");return i=>!o.test(i)}case"captionContains":{const o=new RegExp(n,"is");return i=>o.test(i)}case"captionNotContains":{const o=new RegExp(n,"is");return i=>!o.test(i)}case"captionGreaterThan":return(o,i)=>r(o,i,e)>0;case"captionGreaterThanOrEqual":return(o,i)=>r(o,i,e)>=0;case"captionLessThan":return(o,i)=>r(o,i,e)<0;case"captionLessThanOrEqual":return(o,i)=>r(o,i,e)<=0;case"captionBetween":return(o,i)=>r(o,i,e)>=0&&r(o,i,s)<=0;case"captionNotBetween":return(o,i)=>r(o,i,e)<0||r(o,i,s)>0;default:return()=>!0}}function Ke(c){const t=Number(c.value),e=Number(c.value2);switch(c.op){case"valueEqual":return s=>s===t;case"valueNotEqual":return s=>s!==t;case"valueGreaterThan":return s=>s>t;case"valueGreaterThanOrEqual":return s=>s>=t;case"valueLessThan":return s=>s<t;case"valueLessThanOrEqual":return s=>s<=t;case"valueBetween":return s=>s>=Math.min(t,e)&&s<=Math.max(t,e);case"valueNotBetween":return s=>s<Math.min(t,e)||s>Math.max(t,e);default:return()=>!0}}function ut(c,t){if(!t)return null;const e=t.hidden&&t.hidden.length>0;if(!e&&!t.labelFilter)return null;c.ensure();const s=new Uint8Array(c.items.length);if(e){const n=c.keyIndex;for(const r of t.hidden){const o=n.get(r);o!==void 0&&(s[o]=1)}}if(t.labelFilter){const n=He(t.labelFilter);c.items.forEach((r,o)=>{n(c.labelOfValue(r),r)||(s[o]=1)})}return s}function Ft(c,t){return c.ensureRaw(),fe(c.shared,t)}class ze{constructor(t,e){this.rows=t,this.cols=e,this.dense=t*e<=ke,this.map=this.dense?null:new Map,this.size=this.dense?t*e:0}ensure(t,e){const s=t*this.cols+e;if(this.dense)return s;let n=this.map.get(s);return n===void 0&&(n=this.size++,this.map.set(s,n)),n}get(t,e){const s=t*this.cols+e;return this.dense?s:this.map.get(s)??-1}}class Ye{constructor(t){this.pivot=t,this.cache=t.cache,this.spec=t.spec,this._aggregate(),this._arrange()}opts(t){return this.spec.fieldOptions[t]??null}_resolveData(){const{cache:t,spec:e}=this,s=new Map,n=(o,i)=>{let l=s.get(o);l===void 0&&(l={sum:!1,mm:!1,prod:!1,var:!1},s.set(o,l));const u=Be[i];u&&(l[u]=!0)},r=new Set;for(const o of Object.keys(e.fieldOptions)){const i=e.fieldOptions[o].subtotals;if(Array.isArray(i))for(const l of i)r.add(l)}this.data=e.values.map((o,i)=>{const l=t.fields[o.field],u={index:i,field:o.field,name:o.name,agg:o.agg,showAs:o.showAs??null,numFmt:o.numFmt??null,calc:null};if(l.isCalculated){u.calc=oe(l,t);for(const f of u.calc.refs)n(f,"sum")}else{n(o.field,o.agg);for(const f of r)n(o.field,f)}return u}),this.needs=s}_recordMask(t){const{spec:e,cache:s}=this;let n=null;for(const r of Object.keys(e.fieldOptions)){const o=s.fields[r];if(!o||o.removed||o.isCalculated)continue;const i=this.calcFields.has(o.index)?null:ut(o,e.fieldOptions[r]);if(i!==null){n===null&&(n=new Uint8Array(t).fill(1));const l=o.ensure().ids;for(let u=0;u<t;u++)i[l[u]]===1&&(n[u]=0)}if(e.fieldOptions[r].range||e.fieldOptions[r].dateFilter){n===null&&(n=new Uint8Array(t).fill(1));const l=Ft(o,e.fieldOptions[r]),u=o.rawIds;for(let f=0;f<t;f++)l[u[f]]===1&&(n[f]=0)}}return n}_itemsShown(t,e){const s=this.cache.fields[t].ensure(),n=this.spec.fieldOptions[t],r=new Uint8Array(s.items.length),o=n?.range||n?.dateFilter?Ft(s,n):null;for(let u=0;u<e;u++)(o===null||o[s.rawIds[u]]===0)&&(r[s.ids[u]]=1);s.calcItems&&r.fill(1,s.items.length-s.calcItems.length);const i=this.calcFields.has(t)?null:ut(s,n),l=[];return r.forEach((u,f)=>{u&&!i?.[f]&&l.push(f)}),l}_aggregate(){const{cache:t,spec:e}=this,s=t.recordCount;this._resolveData();const n=this.data.length,r=g=>g.filter(C=>C!==x||n>1);let o=r(e.rows),i=r(e.cols);n>1&&!o.includes(x)&&!i.includes(x)&&(i=[...i,x]),o=o.filter(g=>g===x||!t.fields[g].removed),i=i.filter(g=>g===x||!t.fields[g].removed),this.calcFields=new Set([...o,...i].filter(g=>g!==x&&t.fields[g].calcItems));const l=this._recordMask(s);this.mask=l;const u=g=>{const C=e.fieldOptions[g];return C?.showAll?{hide:ut(t.fields[g],C)}:null},f=ie(t,o.filter(g=>g!==x),o,s,l,u),m=ie(t,i.filter(g=>g!==x),i,s,l,u);this.rows=f,this.cols=m;let y,p,a,h;const d=f.nLeaves,b=m.nLeaves;if(f.leaf!==null&&m.leaf!==null){const g=f.leaf,C=m.leaf;y=new Int32Array(s);const A=d*b,_=Math.min(A,Math.max(s,1));if(p=new Int32Array(_),a=new Int32Array(_),h=0,A<=Wt){const k=new Int32Array(A).fill(-1);for(let I=0;I<s;I++){const E=g[I];if(E<0){y[I]=-1;continue}const O=E*b+C[I];let F=k[O];F<0&&(F=h++,k[O]=F,p[F]=E,a[F]=C[I]),y[I]=F}}else{const k=new Map;for(let I=0;I<s;I++){const E=g[I];if(E<0){y[I]=-1;continue}const O=E*b+C[I];let F=k.get(O);F===void 0&&(F=h++,k.set(O,F),p[F]=E,a[F]=C[I]),y[I]=F}}}else if(f.leaf!==null||m.leaf!==null){y=f.leaf??m.leaf,h=f.leaf!==null?d:b;const g=new Int32Array(h);for(let A=0;A<h;A++)g[A]=A;const C=new Int32Array(h);p=f.leaf!==null?g:C,a=f.leaf!==null?C:g}else{if(y=new Int32Array(s),h=1,l!==null)for(let g=0;g<s;g++)l[g]===0&&(y[g]=-1);p=new Int32Array(1),a=new Int32Array(1)}const v=this.calcFields.size>0?ge(t,f,m,{row:p,col:a,count:h},g=>this._itemsShown(g,s)):null;v&&(f.k>0&&Dt(f,v.rows),m.k>0&&Dt(m,v.cols),{row:p,col:a,count:h}=v.cells),this.cellCount=h,this.cellRow=p,this.cellCol=a,this.cells=y;const w=new Map;for(const[g,C]of this.needs){const A=new St(h,C);qe(A,t.fields[g],y,s),w.set(g,A)}v&&ye(v.steps,[...w.values()]),this.leafAccs=w,this._applyValueFilters(),this._rollUp()}_slotValue(t,e,s,n){if(t.calc!==null){let r=!1;const o=i=>{const l=e.get(i);if(l.cnt[s]!==0&&(r=!0),l.err!==null&&l.err[s]!==0)throw Ct[l.err[s]-1];return l.sum[s]};try{const i=t.calc.fn(o);return r?typeof i=="number"?Number.isFinite(i)?i:V.NUM:typeof i=="boolean"?i?1:0:i instanceof $?i:V.VALUE:null}catch(i){if(i instanceof $)return i;throw i}}return e.get(t.field).value(s,n??t.agg)}_applyValueFilters(){const{rows:t,cols:e,data:s}=this;this.rowDead=new Uint8Array(t.nNodes),this.colDead=new Uint8Array(e.nNodes),this.calcFields.size>0&&(this._hideItems(t,this.rowDead),this._hideItems(e,this.colDead));const n=(r,o,i)=>{for(let l=1;l<=r.k;l++){const u=r.fields[l-1],f=this.opts(u);if(!f||!f.valueFilter&&!f.top)continue;const m=f.valueFilter??f.top,y=s[m.data??0];if(!y)continue;const p=this._nodeAccs(r,y,i),a=r.levelBase[l-1],h=l<r.k?r.levelBase[l]:r.nNodes,d=new Map;for(let b=a;b<h;b++){if(o[b]||o[r.parent[b]]){o[b]=1;continue}const v=r.parent[b];let w=d.get(v);w===void 0&&(w=[],d.set(v,w)),w.push(b)}for(const b of d.values()){const v=w=>{const g=this._slotValue(y,p,w,null);return typeof g=="number"?g:null};if(f.valueFilter){const w=Ke(f.valueFilter);for(const g of b){const C=v(g);(C===null||!w(C))&&(o[g]=1)}}if(f.top){const w=b.filter(g=>!o[g]);for(const g of Je(w,v,f.top,!0))o[g]=1}}for(let b=h;b<r.nNodes;b++)o[r.parent[b]]&&(o[b]=1)}};n(t,this.rowDead,!0),n(e,this.colDead,!1)}_hideItems(t,e){const s=t.fields.map(n=>this.calcFields.has(n)?ut(this.cache.fields[n],this.opts(n)):null);for(let n=1;n<t.nNodes;n++)(e[t.parent[n]]||s[t.depth[n]-1]?.[t.item[n]])&&(e[n]=1)}_nodeAccs(t,e,s){const n=e.calc!==null?e.calc.refs:[e.field],r=new Map;for(const a of n)r.set(a,new St(t.nNodes,this.needs.get(a)));const o=[...r.entries()].map(([a,h])=>[h,this.leafAccs.get(a)]),{cellRow:i,cellCol:l,rows:u,cols:f,rowDead:m,colDead:y}=this,p=s?i:l;for(let a=0;a<this.cellCount;a++){const h=u.leafNode(i[a]),d=f.leafNode(l[a]);if(m[h]||y[d])continue;let b=t.leafNode(p[a]);for(;b>=0;){for(const[v,w]of o)v.merge(b,w,a);b=t.parent[b]}}return r}_rollUp(){const{rows:t,cols:e,cellRow:s,cellCol:n,rowDead:r,colDead:o,cellCount:i}=this,l=new Uint8Array(t.nNodes),u=new Uint8Array(e.nNodes),f=new ze(t.nNodes,e.nNodes),m=t.parent,y=e.parent,p=new Uint8Array(i);for(let w=0;w<i;w++){const g=t.leafNode(s[w]),C=e.leafNode(n[w]);if(!r[g])for(let A=g;A>=0;A=m[A])l[A]=1;if(!o[C])for(let A=C;A>=0;A=y[A])u[A]=1;if(!(r[g]||o[C])&&(p[w]=1,!f.dense))for(let A=g;A>=0;A=m[A])for(let _=C;_>=0;_=y[_])f.ensure(A,_)}const a=(w,g,C)=>{for(const[A,_]of w.noData)for(let k=A;k<_;k++)C[k]===0&&(w.parent[k]===0||g[w.parent[k]])&&(g[k]=1)};a(t,l,r),a(e,u,o),t.alive=l,e.alive=u;const h=new Map,d=[];for(const[w,g]of this.needs){const C=new St(Math.max(f.size,1),g);h.set(w,C),d.push([C,this.leafAccs.get(w)])}const b=f.dense,v=f.cols;for(let w=0;w<i;w++){if(p[w]===0)continue;const g=t.leafNode(s[w]),C=e.leafNode(n[w]);for(let A=g;A>=0;A=m[A])for(let _=C;_>=0;_=y[_]){const k=b?A*v+_:f.get(A,_);for(let I=0;I<d.length;I++)d[I][0].merge(k,d[I][1],w)}}this.slots=f,this.accs=h,this.cells=null,t.leaf=null,e.leaf=null}raw(t,e,s,n=null){if(e<0||s<0)return null;const r=this.slots.get(e,s);return r<0?null:this._slotValue(t,this.accs,r,n)}_baseLoc(t){if(t._loc!==void 0)return t._loc;const e=t.showAs?.baseField;let s=null;if(e!=null&&e>=0){let n=this.rows.fields.indexOf(e);n>=0?s={tree:this.rows,isRow:!0,depth:n+1}:(n=this.cols.fields.indexOf(e),n>=0&&(s={tree:this.cols,isRow:!1,depth:n+1}))}return t._loc=s,s}show(t,e,s,n=null){const r=t.showAs?.type;if(!r||r==="normal")return this.raw(t,e,s,n);const o=this.raw(t,e,s,n);if(o instanceof $)return o;const i=(d,b)=>this.raw(t,d,b,n),l=d=>d instanceof $?d:o===null?d===null?null:0:d===null||d===0?V.DIV0:o/d;switch(r){case"percentOfTotal":return l(i(0,0));case"percentOfCol":return l(i(0,s));case"percentOfRow":return l(i(e,0));case"percentOfParentRow":return l(e===0?o:i(this.rows.parent[e],s));case"percentOfParentCol":return l(s===0?o:i(e,this.cols.parent[s]));case"index":{const d=i(0,0),b=i(e,0),v=i(0,s);return[d,b,v].some(w=>w instanceof $)?V.VALUE:!b||!v?V.DIV0:(o??0)*d/(b*v)}default:}const u=this._baseLoc(t);if(u===null)return V.NA;const{tree:f,isRow:m,depth:y}=u,p=m?e:s;if(f.depth[p]<y)return null;const a=d=>m?i(d,s):i(e,d),h=f.ancestorAt(p,y);switch(r){case"percentOfParent":return l(a(h));case"percent":case"difference":case"percentDiff":{const d=this._baseSibling(t,f,h,y);if(d==="missing")return V.NA;if(d===-1)return r==="percent"?o===null?null:1:null;const b=a(f.peer(p,y,d));return d===h?r==="percent"?o===null?null:1:null:b instanceof $?b:r==="percent"&&o===null?V.NULL:r==="difference"?o===null&&b===null?null:(o??0)-(b??0):o===null||b===null?null:b===0?V.DIV0:r==="percent"?o/b:(o-b)/b}case"runTotal":case"percentOfRunningTotal":{const d=this._running(t,f,m,y,p,m?s:e,h,n);if(d instanceof $||r==="runTotal")return d;const b=f.children(f.parent[h]),v=this._running(t,f,m,y,p,m?s:e,b[b.length-1],n);return v instanceof $?v:v===0?V.DIV0:d/v}case"rankAscending":case"rankDescending":return o===null?null:this._rank(t,f,m,y,p,m?s:e,o,r==="rankAscending",n);default:return o}}_baseSibling(t,e,s,n){const r=t.showAs.baseItem,o=e.parent[s];if(r==="prev"||r==="next"){const f=e.children(o),m=e.pos[s]+(r==="prev"?-1:1);return m>=0&&m<f.length?f[m]:-1}const l=e.fieldAt(n).keyIndex.get(r);if(l===void 0)return"missing";const u=e.findChild(o,l);return u<0?"missing":u}_running(t,e,s,n,r,o,i,l){t._run===void 0&&(t._run=new Map);let u=t._run.get(l);u===void 0&&(u=new Map,t._run.set(l,u));const f=e.children(e.parent[i]),m=e.pos[i],y=s?this.cols.nNodes:this.rows.nNodes;let p=m,a=0;for(;p>=0;){const h=e.peer(r,n,f[p]),d=h>=0?u.get(h*y+o):void 0;if(d!==void 0){a=d;break}p--}for(let h=p+1;h<=m;h++){const d=e.peer(r,n,f[h]);if(d<0)continue;const b=s?this.raw(t,d,o,l):this.raw(t,o,d,l);if(b instanceof $)return b;typeof b=="number"&&(a+=b),u.set(d*y+o,a)}return a}_rank(t,e,s,n,r,o,i,l,u){t._ranks===void 0&&(t._ranks=new Map);const f=e.ancestorAt(r,n),m=e.pathKeys(r).slice(n).join(Nt),y=`${u??""}|${e.parent[f]}|${o}|${m}`;let p=t._ranks.get(y);if(p===void 0){const d=[];for(const b of e.children(e.parent[f])){const v=e.peer(r,n,b);if(v<0)continue;const w=s?this.raw(t,v,o,u):this.raw(t,o,v,u);typeof w=="number"&&d.push(w)}p=Float64Array.from(d).sort(),t._ranks.set(y,p)}let a=0,h=p.length;if(l){for(;a<h;){const d=a+h>>1;p[d]<i?a=d+1:h=d}return a+1}for(;a<h;){const d=a+h>>1;p[d]<=i?a=d+1:h=d}return p.length-a+1}_arrange(){for(const t of this.data)t._run=void 0,t._ranks=void 0;this._buildChildren(this.rows,!0),this._buildChildren(this.cols,!1),this.rows.lines=this._buildLines(this.rows,!0),this.cols.lines=this._buildLines(this.cols,!1),this._layout()}rearrange(){return this._arrange(),this}_buildChildren(t,e){const{nNodes:s,parent:n,alive:r}=t,o=new Int32Array(s+1);for(let u=1;u<s;u++)r[u]&&o[n[u]+1]++;for(let u=0;u<s;u++)o[u+1]+=o[u];const i=new Int32Array(o[s]),l=o.slice();for(let u=1;u<s;u++)r[u]&&(i[l[n[u]]++]=u);t.childStart=o,t.childList=i,t.pos=new Int32Array(s),t._childIndex=null;for(let u=0;u<t.k;u++){const f=this._sortCompare(t,u+1,e),m=u===0?0:t.levelBase[u-1],y=u===0?1:t.levelBase[u];for(let p=m;p<y;p++){const a=o[p],h=o[p+1];if(h-a>1){const d=Array.from(i.subarray(a,h));d.sort(f),i.set(d,a)}for(let d=a;d<h;d++)t.pos[i[d]]=d-a}}}_sortCompare(t,e,s){const n=t.fields[e-1],r=this.cache.fields[n].ensure(),{item:o}=t,i=this.opts(n)?.sort,l=r.rank(Xe(i));if((!i||i.order==="asc"||i.order===void 0)&&(!i||i.data===void 0||i.data===null))return(h,d)=>l[o[h]]-l[o[d]];if(i.order==="manual"){const h=i.keys??[],d=new Map(h.map((v,w)=>[v,w])),b=new Float64Array(r.items.length);return r.items.forEach((v,w)=>{const g=d.get(at(v));b[w]=g===void 0?h.length+l[w]:g}),(v,w)=>b[o[v]]-b[o[w]]}const u=i.order==="desc"?-1:1;if(i.data===void 0||i.data===null)return(h,d)=>u*(l[o[h]]-l[o[d]]);const f=this.data[i.data];if(!f)return(h,d)=>l[o[h]]-l[o[d]];let m=0;if(i.path){const h=s?this.cols:this.rows;this._ensureItems(h);for(let d=0;d<i.path.length&&m>=0;d++){const v=h.fieldAt(d+1).keyIndex.get(i.path[d]);m=v===void 0?-1:h.findChild(m,v)}}const y=h=>{const d=s?this.raw(f,h,m):this.raw(f,m,h);return typeof d=="number"?d:null},p=new Map,a=h=>{let d=p.get(h);return d===void 0&&(d=y(h),p.set(h,d)),d};return(h,d)=>{const b=a(h),v=a(d);return b===null||v===null?b===v?l[o[h]]-l[o[d]]:b===null?1:-1:b===v?l[o[h]]-l[o[d]]:u*(b-v)}}_ensureItems(t){for(const e of t.fields)this.cache.fields[e].ensure()}_form(t){return this.opts(t)?.layout??this.spec.layout}_isCollapsed(t,e,s){const n=t.depth[e],r=s[n];return r===null?!1:!!(r.items!==null&&r.items.has(t.fieldAt(n).keyOf(t.item[e]))||r.paths!==null&&r.paths.has(t.pathKeys(e).join(Nt)))}_buildLines(t,e){const{slots:s}=t,n=this.data.length,r={node:[],data:[],type:[],level:[],first:[],func:[],top:[],parentLine:[]},o=(p,a,h,d,b,v,w,g)=>{r.node.push(p),r.data.push(a),r.type.push(h),r.level.push(d),r.first.push(b),r.func.push(v),r.top.push(w?1:0),r.parentLine.push(g?1:0)},i=s.length-1,l=p=>e?s[p]===x?this.spec.layout:this._form(s[p]):"tabular",u=[null];for(let p=1;p<=t.k;p++){const a=this.opts(t.fields[p-1]),h=a?.collapsedItems?.length?new Set(a.collapsedItems):null,d=a?.collapsed?.length?new Set(a.collapsed):null;u.push(h||d?{items:h,paths:d}:null)}const f=p=>this.opts(p)?.subtotalTop??this.spec.subtotalTop,m=(p,a,h,d)=>{const b=s[a];if(b===x){for(let C=0;C<n;C++){const A=C===0&&d!==-1?d:a;a===i?o(p,C,W,a,A,null,!1,!1):l(a)==="tabular"?m(p,a+1,C,A):(o(p,C,W,a,A,null,!1,!0),r.noValues??=new Set,r.noValues.add(r.node.length-1),m(p,a+1,C,-1))}return}const v=t.children(p),w=this.opts(b),g=w?.blankLine===!0&&e;for(let C=0;C<v.length;C++){const A=v[C],_=C===0&&d!==-1?d:a;if(a===i){o(A,h,W,a,_,null,!1,!1);continue}const k=l(a),I=h<0&&s.indexOf(x,a+1)>=0,E=this._isCollapsed(t,A,u);if(E||t.depth[A]<t.k&&t.children(A).length===0){if(I){const wt=s.indexOf(x,a+1);k!=="tabular"&&(o(A,h,W,a,_,null,!1,!0),r.noValues??=new Set,r.noValues.add(r.node.length-1));for(let K=0;K<n;K++)o(A,K,W,wt,k==="tabular"&&K===0?_:wt,null,!1,!1)}else o(A,h,W,a,_,null,!1,k!=="tabular");E&&(r.collapsed??=new Set,r.collapsed.add(A)),g&&o(A,h,bt,a,a,null,!1,!1);continue}const O=w?.subtotals??"auto",F=Array.isArray(O),Z=O!=="none"&&!(F&&O.length===0),nt=k!=="tabular"&&!I&&!F&&Z&&f(b);if(k==="tabular"?m(A,a+1,h,_):(o(A,h,W,a,_,null,nt,!0),nt||(r.noValues??=new Set,r.noValues.add(r.node.length-1)),m(A,a+1,h,-1)),!nt&&Z&&!(a+1===i&&s[a+1]===x&&!F)){const K=F?O:[null];if(I)for(let rt=0;rt<n;rt++)for(const vt of K)o(A,rt,lt,a,a,vt,!1,!1);else for(const rt of K)o(A,h,lt,a,a,rt,!1,!1)}g&&o(A,h,bt,a,a,null,!1,!1)}};if(s.length===0)return o(0,-1,W,-1,0,null,!1,!1),r;if(m(0,0,-1,-1),t.k>0&&(e?this.spec.grandRow:this.spec.grandCol))if(s.includes(x))for(let p=0;p<n;p++)o(0,p,st,0,0,null,!1,!1);else o(0,-1,st,0,0,null,!1,!1);return r}fieldCaption(t){return t===x?this.spec.dataCaption:this.opts(t)?.caption??this.cache.fields[t].name}itemCaption(t,e){const s=t.fieldAt(t.depth[e]),n=t.item[e],r=this.opts(s.index)?.itemCaptions;if(r){const o=r[s.keyOf(n)];if(o!==void 0)return o}return null}_labelValue(t,e){const s=this.itemCaption(t,e);if(s!==null)return s===""?null:s;const n=t.fieldAt(t.depth[e]),r=n.items[t.item[e]];return r===""?null:typeof r=="number"?r:n.labelOfValue(r)}_labelText(t,e){const s=this.itemCaption(t,e);return s!==null?s:t.fieldAt(t.depth[e]).labelOf(t.item[e])}_subtotalLabel(t,e,s){const n=this._labelText(t,e.node[s]),o=t.slots.indexOf(x)<e.level[s]?-1:e.data[s],i=e.func[s];return i!==null&&o>=0?`${n} ${Lt[i]} of ${this.data[o].name}`:i!==null?`${n} ${Lt[i]}`:o>=0?`${n} ${this.data[o].name}`:`${n} Total`}_pageValue(t){const e=this.cache.fields[t].ensure(),s=ut(e,this.opts(t));if(s===null)return{text:"(All)",value:"(All)"};let n=0,r=-1;for(let o=0;o<s.length;o++)s[o]===0&&(n++,r=o);return n===s.length?{text:"(All)",value:"(All)"}:n===1?{text:e.labelOf(r),value:typeof e.items[r]=="number"?e.items[r]:e.labelOf(r)}:{text:"(Multiple Items)",value:"(Multiple Items)"}}_layout(){const{spec:t,rows:e,cols:s,data:n}=this,r=new We;this.buffer=r;const o=n.length,i=t.filters.filter(T=>!this.cache.fields[T].removed),l=i.length>0?i.length+1:0,u=e.slots.length===0&&s.slots.length===0&&o===0;i.forEach((T,R)=>{r.pushValue(R,0,this.fieldCaption(T),N.PAGE_LABEL);const S=this.cache.fields[T],G=this._pageValue(T);r.pushValue(R,1,G.value,N.PAGE_VALUE,0,typeof G.value=="number"?r.format(S.numFmt):0)});const f=[],m=[];let y=0;if(e.slots.length>0){let T=0,R=0;for(let G=0;G<e.slots.length;G++)f.push(T),m.push(R),(e.slots[G]===x?t.layout:this._form(e.slots[G]))==="compact"?R++:(T++,R=0);y=(e.slots[e.slots.length-1]===x?t.layout:this._form(e.slots[e.slots.length-1]))==="compact"?T+1:T}else o<=1&&s.slots.length>0&&!(s.slots.length===1&&s.slots[0]===x)&&(y=1);const p=e.lines,a=s.lines,h=a.node.length,d=p.node.length,b=s.slots.length===1&&s.slots[0]===x,v=b&&!t.hideValuesRow&&e.slots.length>0,w=s.slots.length>0&&(!b||v),g=u?0:w?1+s.slots.length:1,C=w?t.layout==="compact"?1:s.slots.length:0,A=y+Math.max(o>0||w?h:0,C),_=o>0||e.slots.length>0?d:0,k=l,I=new Uint8Array(g*Math.max(A,1)),E=(T,R,S,G,z=0,P=0)=>{r.pushValue(k+T,R,S,G,P,z),I[T*A+R]=1},O=T=>t.layout==="compact"?null:T.map(R=>this.fieldCaption(R));u&&r.pushValue(k,0,t.name,N.PLACEHOLDER);const F=g-1;if(e.slots.length>0&&e.slots.forEach((T,R)=>{if(R>0&&f[R]===f[R-1])return;const S=R===0&&t.layout==="compact"&&e.fields.length>0?t.rowCaption??B("Row Labels"):this.fieldCaption(T);E(F,f[R],S,N.ROW_CAPTION)}),w){o===1&&e.slots.length>0&&E(0,0,n[0].name,N.CORNER);const T=O(s.slots);v?E(0,y,t.dataCaption,N.COL_CAPTION):T===null?E(0,y,t.colCaption??B("Column Labels"),N.COL_CAPTION):T.forEach((R,S)=>E(0,y+S,R,N.COL_CAPTION))}else o===1&&!b&&!e.slots.includes(x)&&E(0,y,n[0].name,N.DATA_HEADER);const Z=w?1:0;if(o>0||w)for(let T=0;T<h;T++){const R=a.type[T],S=y+T,G=a.node[T];if(R===st){const P=a.data[T],gt=P>=0?`Total ${n[P].name}`:t.grandCaption??B("Grand Total");E(Z,S,gt,N.COL_GRAND);continue}if(R===lt){E(Z+a.level[T],S,this._subtotalLabel(s,a,T),N.COL_SUBTOTAL);continue}const z=a.level[T];for(let P=a.first[T];P<=z;P++){if(P<0||P>=s.slots.length)continue;if(s.slots[P]===x){const H=a.data[T];H>=0&&E(Z+P,S,n[H].name,N.DATA_HEADER)}else{const H=Vt(s.slots,P),tt=s.ancestorAt(G,H);if(tt<0)continue;const yt=this._labelValue(s,tt);E(Z+P,S,yt,N.COL_ITEM,typeof yt=="number"?r.format(s.fieldAt(H).numFmt):0,t.showExpandButtons&&H<s.k?1:0)}}}for(let T=0;T<g;T++)for(let R=0;R<A;R++)I[T*A+R]===0&&r.push(k+T,R,j,0,N.HEADER_BLANK);const nt=k+g,wt=n.map(T=>{const R=T.numFmt??Qe(T);return r.format(R)}),K=p.noValues??null,rt=T=>e.slots[T];for(let T=0;T<_;T++){const R=nt+T,S=p.type[T];if(S===bt)continue;const G=p.node[T],z=p.level[T],P=p.parentLine[T]===1;let gt=N.ROW_ITEM,H=N.DATA;S===lt?(gt=N.ROW_SUBTOTAL,H=N.DATA_SUBTOTAL):S===st?(gt=N.ROW_GRAND,H=N.DATA_GRAND_ROW):P&&(H=N.DATA_PARENT);const tt=Math.max(z,0);if(y>0)if(e.slots.length===0)o===1&&r.pushValue(R,0,n[0].name,N.ROW_ITEM);else if(S===st){const q=p.data[T];r.pushValue(R,0,q>=0?`Total ${n[q].name}`:t.grandCaption??B("Grand Total"),N.ROW_GRAND);for(let M=1;M<y;M++)r.push(R,M,j,0,N.ROW_GRAND)}else if(S===lt){const q=f[z];for(let M=0;M<y;M++)M===q?r.pushValue(R,M,this._subtotalLabel(e,p,T),N.ROW_SUBTOTAL,m[z]):r.push(R,M,j,0,N.ROW_SUBTOTAL)}else{const q=this._labelStart(p,T,e);for(let M=q;M<=z;M++){const _t=rt(M),ft=f[M],ht=M===z&&P?N.ROW_PARENT:N.ROW_ITEM;if(_t===x){const Y=p.data[T];Y>=0&&r.pushValue(R,ft,n[Y].name,ht,m[M])}else{const Y=Vt(e.slots,M),dt=e.ancestorAt(G,Y);if(dt<0)continue;const X=t.showExpandButtons&&Y<e.k?1:0,et=this._labelValue(e,dt),ot=typeof et=="number"?r.format(e.fieldAt(Y).numFmt):0;r.pushValue(R,ft,et,ht,m[M]+X,ot)}}}if(o===0||K!==null&&K.has(T))continue;const yt=p.data[T],ce=p.func[T];for(let q=0;q<h;q++){const M=a.type[q];if(M===bt)continue;const _t=a.data[q],ft=yt>=0?yt:_t>=0?_t:o===1?0:-1;if(ft<0)continue;const ht=n[ft],Y=ce??a.func[q],dt=this.show(ht,G,a.node[q],Y);let X=H;S!==st&&M===st?X=N.DATA_GRAND_COL:S===W&&!P&&M===lt&&(X=N.DATA);const et=y+q,ot=Y&&Y!==ht.agg&&!ht.numFmt?0:wt[ft];dt===null?t.showMissing===!1?r.pushValue(R,et,0,X,tt,ot):t.emptyText!==""?r.pushValue(R,et,t.emptyText,X,tt,ot):X!==N.DATA&&r.push(R,et,j,0,X,tt,ot):dt instanceof $&&t.errorText!==null?r.pushValue(R,et,t.errorText,X,tt,ot):r.pushValue(R,et,dt,X,tt,ot)}}const vt=u?k+1:nt+_,Pt=Math.max(A,i.length>0?2:0,u?1:0);if(vt>pe||Pt>de)throw new L("The PivotTable is too large for a worksheet.");this.layout={cells:r,rows:vt,cols:Pt,bodyCols:A,pageRows:l,pageFields:i,headerRows:g,labelCols:y,bodyTop:nt,dataRows:_,colForLevel:f,indentForLevel:m,colRowBase:Z,firstHeaderRow:u||w?1:o>1?0:1,firstDataRow:u?1:g,firstDataCol:y}}_labelStart(t,e,s){const n=t.level[e],r=t.first[e];if(r===0)return 0;for(let o=0;o<r;o++){const i=s.slots[o];if(i!==x&&this.opts(i)?.repeatLabels||i!==x&&this.spec.repeatLabels&&this._form(i)!=="compact")return o}return Math.min(r,n)}toRows(){const{cells:t,rows:e,cols:s}=this.layout,n=[];for(let r=0;r<e;r++)n.push(new Array(s).fill(null));for(let r=0;r<t.count;r++)n[t.rows[r]][t.cols[r]]=t.valueAt(r);return n}hitTest(t,e){const s=this.layout,{spec:n,rows:r,cols:o}=this;if(t<s.pageRows-1){const l=s.pageFields[t];return l!==void 0&&e===1?{kind:"pageFilter",field:l}:null}const i=t-s.pageRows;if(i<0||t>=s.rows)return null;if(i===s.headerRows-1&&e<s.labelCols&&r.fields.length>0){const l=r.slots.filter((u,f)=>u!==x&&s.colForLevel[f]===e);if(l.length>0)return{kind:"filter",axis:"row",fields:l}}if(i===0&&e>=s.labelCols&&o.fields.length>0&&s.colRowBase===1){const l=n.layout==="compact"?e===s.labelCols?o.fields:[]:o.slots.filter((u,f)=>u!==x&&f===e-s.labelCols);if(l.length>0)return{kind:"filter",axis:"col",fields:l}}if(i>=s.headerRows&&e<s.labelCols){const l=this._rowLabelAt(i-s.headerRows,e);if(l!==null)return l}if(i>=s.colRowBase&&i<s.headerRows&&e>=s.labelCols){const l=this._colLabelAt(e-s.labelCols,i-s.colRowBase);if(l!==null)return l}return i>=s.headerRows&&e>=s.labelCols?{kind:"value",rowLine:i-s.headerRows,colLine:e-s.labelCols}:null}_rowLabelAt(t,e){const{rows:s}=this,n=s.lines;if(t>=n.node.length||n.type[t]!==W)return null;const r=this.layout.colForLevel;for(let o=n.level[t];o>=this._labelStart(n,t,s);o--)if(r[o]===e)return this._labelHit(s,n,t,o,"row");return null}_colLabelAt(t,e){const{cols:s}=this,n=s.lines;return t>=n.node.length||n.type[t]!==W||e<n.first[t]||e>n.level[t]?null:this._labelHit(s,n,t,e,"col")}_labelHit(t,e,s,n,r){const o=t.slots[n];if(o===x||o===void 0)return null;const i=Vt(t.slots,n),l=t.ancestorAt(e.node[s],i);if(l<0)return null;const u=i<t.k;return{kind:"label",axis:r,node:l,field:o,path:t.pathKeys(l),expandable:u,collapsed:u&&e.collapsed?.has(l)===!0}}togglesIn(t,e,s,n){const r=[],o=this.layout,{rows:i,cols:l}=this;if(this.spec.showExpandButtons===!1)return r;if(i.k>1)for(let u=Math.max(t,o.bodyTop);u<=Math.min(s,o.rows-1);u++)for(let f=e;f<=Math.min(n,o.labelCols-1);f++){const m=this._rowLabelAt(u-o.bodyTop,f);m!==null&&m.expandable&&r.push({row:u,col:f,collapsed:m.collapsed,indent:this._levelIndent(m)})}if(l.k>1){const u=o.pageRows+o.colRowBase;for(let f=Math.max(t,u);f<=Math.min(s,o.pageRows+o.headerRows-1);f++)for(let m=Math.max(e,o.labelCols);m<=Math.min(n,o.cols-1);m++){const y=this._colLabelAt(m-o.labelCols,f-u);y!==null&&y.expandable&&r.push({row:f,col:m,collapsed:y.collapsed,indent:0})}}return r}_levelIndent(t){const e=this.rows.slots.indexOf(t.field);return e>=0?this.layout.indentForLevel[e]:0}filterButtons(){const t=this.layout,{rows:e,cols:s,spec:n}=this,r=[];if(t.pageFields.forEach((o,i)=>r.push({row:i,col:1,axis:"page",fields:[o]})),e.fields.length>0&&n.showFieldHeaders!==!1){const o=t.pageRows+t.headerRows-1;for(let i=0;i<t.labelCols;i++){const l=e.slots.filter((u,f)=>u!==x&&t.colForLevel[f]===i);l.length>0&&r.push({row:o,col:i,axis:"row",fields:l})}}if(s.fields.length>0&&n.showFieldHeaders!==!1&&t.colRowBase===1){const o=t.pageRows;n.layout==="compact"?r.push({row:o,col:t.labelCols,axis:"col",fields:s.fields}):s.slots.forEach((i,l)=>{i!==x&&r.push({row:o,col:t.labelCols+l,axis:"col",fields:[i]})})}return r}}const Xe=c=>c?.order==="asc"||c?.order==="desc";function Vt(c,t){let e=0;for(let s=0;s<=t;s++)c[s]!==x&&e++;return e}function Qe(c){const t=c.showAs?.type;return _e.has(t)?"0.00%":t==="index"?"0.00":"General"}function Je(c,t,e,s){const n=e.count??10,r=e.by??"items",o=e.bottom===!0,i=c.map(u=>[u,t(u)]).filter(u=>u[1]!==null);i.sort((u,f)=>o?u[1]-f[1]:f[1]-u[1]);const l=new Set;if(r==="items"){if(i.length>0&&n>0){const u=i[Math.min(n,i.length)-1][1];for(const[f,m]of i)(o?m<=u:m>=u)&&l.add(f)}}else{const u=i.reduce((y,p)=>y+p[1],0),f=r==="percent"?u*n/100:n;let m=0;for(const[y,p]of i)if(l.add(y),m+=p,m>=f)break}return s?c.filter(u=>!l.has(u)):c.filter(u=>l.has(u))}const Ze=new Set(["average","stdDev","stdDevp","var","varp"]);function Tt(c,t,e=null){const s=n=>n!==x&&(n===e||t.fields[n].calcItems);if(!(e===null&&!xt(t))){if(c.values.some(n=>Ze.has(n.agg)&&!t.fields[n.field].isCalculated))throw new L("Averages, standard deviations and variances are not supported when a PivotTable has calculated items.");if(new Set(c.values.map(n=>n.field)).size<c.values.length)throw new L("A field can't be in the Values area twice when a PivotTable has calculated items.");if(c.filters.some(s))throw new L("A field with a calculated item can't be in the Filters area.")}}function ts(c){return{name:"PivotTable1",rows:[],cols:[],values:[],filters:[],fieldOptions:{},layout:"compact",subtotalTop:!0,grandRow:!0,grandCol:!0,repeatLabels:!1,rowCaption:null,colCaption:null,dataCaption:B("Values"),grandCaption:null,emptyText:"",errorText:null,style:{name:"PivotStyleLight16",rowHeaders:!0,colHeaders:!0,rowStripes:!1,colStripes:!1,lastColumn:!0},showExpandButtons:!0,showFieldHeaders:!0,hideValuesRow:!0,...c}}class ys{constructor(t,e={}){this.cache=t,this.spec=ts(e),this.rememberLayout(),this.result=null,this.generation=t.generation,this.listeners=new Set,this.anchor=null,this.xml=null,this.dirty=!0}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(){this.dirty=!0;for(const t of this.listeners)t(this)}rememberLayout(){this.renderedLayout={cache:this.cache,spec:structuredClone(this.spec)}}update(){if(this.cache.needsRefresh){if(this.cache.source===null)throw new L("The PivotTable report was saved without the underlying data. Its source is not available.");this.cache.refresh()}return this._dropRemoved(),this._hideNewItems(),this.result=new Ye(this),this._emit(),this.result}rearrange(){return this.result===null?this.update():(this.result.rearrange(),this._emit(),this.result)}refresh(){return this.cache.refresh(),this.update()}_dropRemoved(){const{spec:t,cache:e}=this,s=n=>n===x||!e.fields[n]?.removed;t.rows=t.rows.filter(s),t.cols=t.cols.filter(s),t.filters=t.filters.filter(s),t.values.every(n=>s(n.field))||this.setValues(t.values.filter(n=>s(n.field)))}_hideNewItems(){const{cache:t}=this,e=this.generation;if(e!==t.generation){this.generation=t.generation;for(const[s,n]of Object.entries(this.spec.fieldOptions)){const r=t.fields[s];if(!n.hidden?.length||n.includeNewItems||!r||r.removed)continue;const o=r.known.find(l=>l.generation>=e)?.keys;if(!o)continue;r.ensure();const i=new Set(n.hidden);for(const l of r.keyIndex.keys())o.has(l)||i.add(l);[...r.keyIndex.keys()].some(l=>!i.has(l))&&(n.hidden=[...i])}}}options(t){const{fieldOptions:e}=this.spec;let s=e[t];return s===void 0&&(s={},e[t]=s),s}defaultAgg(t){this.cache.load();const e=this.cache.fields[t];return e.isCalculated?"sum":e.base>=0||e.isDate?"count":this._allNumeric(e)?"sum":"count"}_allNumeric(t){return t.strs!==null?!1:t.rawIds!==null?t.shared.every(e=>typeof e=="number"):t.kinds===null?t.nums!==null:t.kinds.every(e=>e===U)}uniqueDataName(t,e=-1){let s=t,n=2;const r=o=>this.spec.values.some((i,l)=>l!==e&&i.name.toLowerCase()===o.toLowerCase());for(;r(s);)s=`${t}${n++}`;return s}addValue(t,e=this.defaultAgg(t),s=this.spec.values.length){const n=this.cache.fields[t];xt(this.cache)&&Tt({...this.spec,values:[...this.spec.values,{field:t,agg:e}]},this.cache);const r=Et(n.isCalculated?"sum":e,n.name);s=Math.min(s,this.spec.values.length);const o=this.spec.values.slice();return o.splice(s,0,{field:t,agg:e,name:this.uniqueDataName(r)}),this.setValues(o),this.spec.values.length>1&&!this.spec.rows.includes(x)&&!this.spec.cols.includes(x)&&this.spec.cols.push(x),this.spec.values.length-1}setValueAgg(t,e){const s=this.spec.values[t],n=this.cache.fields[s.field];xt(this.cache)&&Tt({...this.spec,values:[{...s,agg:e}]},this.cache);const r=[Et(s.agg,n.name),`${Ae[s.agg]} of ${n.name}`].some(o=>new RegExp(`^${ae(o)}\\d*$`).test(s.name));s.agg=e,r&&(s.name=this.uniqueDataName(Et(e,n.name),t))}checkPlace(t,e){e==="filters"&&this.cache.fields[t]?.calcItems&&Tt({...this.spec,values:[],filters:[t]},this.cache)}place(t,e,s){const{spec:n}=this;this.checkPlace(t,e);for(const o of["rows","cols","filters"])n[o]=n[o].filter(i=>i!==t);if(t===x&&e==="filters")return;const r=n[e];s===void 0||s>r.length?r.push(t):r.splice(s,0,t)}removeFromLayout(t){const{spec:e}=this;for(const s of["rows","cols","filters"])e[s]=e[s].filter(n=>n!==t);this.setValues(e.values.filter(s=>s.field!==t)),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==x),e.cols=e.cols.filter(s=>s!==x))}removeValue(t){const{spec:e}=this;this.setValues(e.values.filter((s,n)=>n!==t)),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==x),e.cols=e.cols.filter(s=>s!==x))}moveValue(t,e){const s=this.spec.values.slice(),[n]=s.splice(t,1);s.splice(Math.max(0,Math.min(e,s.length)),0,n),this.setValues(s)}setValues(t,e=s=>t.indexOf(s)){const{spec:s}=this,n=s.values.map(e),r=i=>n[i.data??0]===-1,o=i=>({...i,data:n[i.data??0]??i.data});for(const i of Object.values(s.fieldOptions)){i.sort?.data!==void 0&&i.sort.data!==null&&(r(i.sort)?delete i.sort:i.sort=o(i.sort));for(const l of["valueFilter","top"])i[l]&&(r(i[l])?delete i[l]:i[l]=o(i[l]))}s.conditionalFormats&&(s.conditionalFormats=s.conditionalFormats.filter(i=>n[i.dataIndex]!==-1).map(i=>({...i,dataIndex:n[i.dataIndex]??i.dataIndex}))),s.values=t}isUsed(t){const{spec:e}=this;return e.rows.includes(t)||e.cols.includes(t)||e.filters.includes(t)||e.values.some(s=>s.field===t)}itemsOf(t){this.cache.load();const e=this.cache.fields[t].ensure(),s=e.rank(),n=ut(e,{hidden:this.spec.fieldOptions[t]?.hidden})??new Uint8Array(e.items.length),r=new Array(e.items.length);for(let o=0;o<r.length;o++)r[s[o]]={id:o,key:at(e.items[o]),label:e.labelOf(o),value:e.items[o],hidden:n[o]===1};return r}itemsWithData(t){const e=this.cache.fields[t].ensure(),s=new Uint8Array(e.items.length),n=this.cache.recordCount,r=[];for(const i of Object.keys(this.spec.fieldOptions)){if(Number(i)===t)continue;const l=this.cache.fields[i];if(!l||l.removed||l.isCalculated)continue;const u=ut(l,this.spec.fieldOptions[i]);if(u!==null&&r.push([l.ensure().ids,u]),this.spec.fieldOptions[i].range||this.spec.fieldOptions[i].dateFilter){const f=Ft(l,this.spec.fieldOptions[i]);r.push([l.rawIds,f])}}e.calcItems&&s.fill(1,e.items.length-e.calcItems.length);const{ids:o}=e;t:for(let i=0;i<n;i++){for(let l=0;l<r.length;l++)if(r[l][1][r[l][0][i]]===1)continue t;s[o[i]]=1}return s}setHidden(t,e){const s=this.options(t);s.hidden=[...e]}clearFilters(t){const e=this.options(t);delete e.hidden,delete e.labelFilter,delete e.valueFilter,delete e.top,delete e.range,delete e.dateFilter}hasFilter(t){const e=this.spec.fieldOptions[t];return!!e&&(e.hidden&&e.hidden.length>0||!!e.labelFilter||!!e.valueFilter||!!e.top||!!e.range||!!e.dateFilter)}toggleCollapse(t){const e=this.options(t.field),s=t.path.join(Nt),n=new Set(e.collapsed??[]),r=t.path[t.path.length-1];return t.collapsed?(n.delete(s),e.collapsedItems&&(e.collapsedItems=e.collapsedItems.filter(o=>o!==r))):n.add(s),e.collapsed=[...n],this.rearrange()}setFieldCollapsed(t,e){const s=this.options(t);s.collapsed=[];const n=this.cache.fields[t].ensure();return s.collapsedItems=e?n.items.map(r=>at(r)):[],this.rearrange()}}export{fs as AGGS,Lt as AGG_LABEL,We as CellBuffer,ms as LABEL_FILTERS,gs as LINE,At as PivotCache,L as PivotError,ct as PivotField,Ye as PivotResult,ys as PivotTable,N as ROLE,hs as SHOW_AS,x as VALUES,ws as VALUE_FILTERS,ee as applyNumFmt,Mt as compileCalc,ut as hiddenItemFlags,Xe as isSorted,at as itemKey,J as newGeneration,he as partsToSerial,Tt as refuseWithCalcItems,it as serialToParts,ds as showAsNeedsBaseField,ps as showAsNeedsBaseItem,se as storeColumn,Et as valueFieldName,Te as wholeSeconds};
|