@8sheets/data-grid 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +1 -1
  2. package/api/serialize.js +1 -1
  3. package/calc/engine.js +1 -1
  4. package/calc/functions/info.js +1 -1
  5. package/calcx/lang/convert.js +1 -1
  6. package/cells/book-css.js +7 -2
  7. package/cells/cf-engine.js +1 -1
  8. package/cells/find-engine.js +2 -2
  9. package/cells/find.js +1 -1
  10. package/cells/goto.js +1 -1
  11. package/cells/link-model.js +1 -0
  12. package/cells/selection-modes.js +1 -1
  13. package/celltypes/dropdowns.js +2 -2
  14. package/core/cond-format.js +1 -1
  15. package/core/culture.js +1 -1
  16. package/core/edit-ranges.js +1 -0
  17. package/core/host-rules.js +1 -0
  18. package/core/protection.js +1 -1
  19. package/core/sheet.js +1 -1
  20. package/core/structure.js +1 -1
  21. package/core/workbook.js +1 -1
  22. package/datasheets/manager.js +1 -1
  23. package/datasheets/persist.js +1 -1
  24. package/extras/getdata/persist.js +2 -2
  25. package/i18n/en/cells.js +1 -1
  26. package/i18n/en/format.js +1 -1
  27. package/i18n/en/misc.js +1 -1
  28. package/i18n/en/ribbon.js +1 -1
  29. package/i18n/pl/cells.js +1 -1
  30. package/i18n/pl/format.js +1 -1
  31. package/i18n/pl/misc.js +1 -1
  32. package/i18n/pl/ribbon.js +1 -1
  33. package/io/client.js +1 -1
  34. package/io/csv.js +7 -7
  35. package/io/encoding.js +1 -0
  36. package/io/foreign-sheets.js +2 -2
  37. package/io/plan.js +1 -1
  38. package/io/xlsx-tail.js +1 -1
  39. package/io/xlsx-write.js +2 -2
  40. package/package.json +1 -1
  41. package/pivot/engine.js +1 -1
  42. package/pivot/xml.js +2 -2
  43. package/print/note-pages.js +2 -0
  44. package/print/paginate.js +1 -1
  45. package/print/pdf-links.js +1 -0
  46. package/print/pdf.js +11 -11
  47. package/print/render-page.js +3 -3
  48. package/table-view/files.js +1 -1
  49. package/table-view/mount.js +1 -1
  50. package/table-view/version.js +1 -1
  51. package/ui/dialogs.js +3 -3
  52. package/ui/icons.js +1 -1
  53. package/ui/protection-ui.js +1 -1
package/io/xlsx-write.js CHANGED
@@ -1,2 +1,2 @@
1
- import{ZipWriter as et}from"./zip-writer.js";import{splitPaneXml as tt}from"../cells/view-xml.js";import{setSheetPicture as st}from"../cells/background-xml.js";import{calcPrAnchor as ie,setIterationAttributes as ne}from"../calcx/external-read.js";import{writeThemePart as le}from"../api/style-refs.js";import{buildStylesXml as at,patchStylesXml as rt}from"./xlsx-styles.js";import{pxToWidth as ot,pump as it}from"./xlsx-read.js";import{relativeTarget as E,relsPathOf as V,resolveTarget as B}from"./package-paths.js";import{BOOL as ee,ERR as Z,ERRORS as nt,FORMULA as lt,KIND_MASK as ce,NUM as me,STR as te}from"../core/sheet.js";import{colName as de,MAX_COLS as ct,parseRangeRef as he,rangeRef as se}from"../core/address.js";import{adjustRange as mt}from"../calc/adjust.js";import{patchSparklines as dt}from"../core/sparklines.js";import{ensureDrawingElement as ht,mergeContentTypes as X}from"../objects/drawing-xml.js";import{applyControls as pt}from"../shapes/form-xml.js";import{relationshipsXml as ft}from"../pivot/xml.js";import{applySlicerSheet as ut,patchSlicerContentTypes as pe,patchSlicerWorkbook as fe,patchSlicerWorkbookRels as ue,removedSlicerParts as wt,writeSlicerParts as xt}from"../slicers/write.js";import{patchCustomStyles as we}from"../slicers/custom-styles.js";import{patchTableXml as gt}from"../core/tables.js";import{addCellTypeEntries as ae,dropCellTypeParts as $t}from"../celltypes/persist.js";import{dropQueryParts as bt}from"../extras/getdata/persist.js";import{richSiXml as yt}from"../cells/rich-xml.js";import{isRichError as xe}from"../cells/rich-data-xml.js";import{patchDataSheetContentTypes as ge,patchDataSheetWorkbookRels as $e,skipOldDataSheetParts as Pt,writeDataSheetParts as kt}from"../datasheets/persist-writer.js";import{patchChartSheetPageSetup as be,patchWorkbookPrintNames as ye,patchWorksheetHead as Tt,patchWorksheetTail as St}from"../print/page-setup.js";import{patchFilterNames as Pe,patchSheetProps as Rt}from"../cells/filter-file.js";import{patchCf as vt}from"../cells/cf-file.js";import{dxfXml as ke,hyperlinksXml as Ct,protectionXml as It,replaceElement as D,scenariosXml as Nt,validationsXml as Et}from"./xlsx-tail.js";import{patchCustomViews as At}from"../core/custom-views.js";import{escapeMarkup as T,xmlAttr as L,xmlText as K}from"./xml-escape.js";import{dropExternalReferences as Ot,patchExternalLinkParts as Dt}from"../calcx/external-write.js";import{applyKeptSheet as _t,clearKeptShapeIds as Vt,declareKeptNamespaces as jt,keptTableRels as zt,keptTableXml as Mt,planKeptParts as Xt,writeKeptParts as Lt}from"./foreign-sheets.js";const F=new TextEncoder,Bt=new TextDecoder,O=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
- `,q="http://schemas.openxmlformats.org/spreadsheetml/2006/main",A="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Ft="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",Ht="http://schemas.openxmlformats.org/markup-compatibility/2006",Wt="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac",Ut=6e7;class Kt{constructor(e){this.write=e,this.buf=new Uint8Array(1<<20),this.pos=0}async flush(){this.pos>0&&(await this.write(this.buf.subarray(0,this.pos)),this.pos=0)}async text(e){if(e.length*3+this.pos>this.buf.length&&(await this.flush(),e.length*3>this.buf.length)){await this.write(F.encode(e));return}this.pos+=F.encodeInto(e,this.buf.subarray(this.pos)).written}}const Te=[];function qt(t){let e=Te[t];return e===void 0&&(e=F.encode(de(t)),Te[t]=e),e}const _=t=>F.encode(t),Gt=_('<c r="'),Yt=_('" s="'),G=_('" t="'),Q=_('"><v>'),J=_("</v></c>"),Zt=_('"/>'),Se=_("</c>"),Re=_('">'),Qt=_('" cm="'),ve=_('" vm="');function S(t,e,s){for(let a=0;a<s.length;a++)t[e+a]=s[a];return e+s.length}function H(t,e,s){if(s<10)return t[e]=48+s,e+1;let a=0;for(let c=s;c>0;c=Math.floor(c/10))a++;for(let c=e+a-1,n=s;c>=e;c--){const l=Math.floor(n/10);t[c]=48+(n-l*10),n=l}return e+a}function Jt(t,e,s){if(Number.isInteger(s)&&Math.abs(s)<1e15)return s<0&&(t[e++]=45,s=-s),H(t,e,s);const a=String(s);for(let c=0;c<a.length;c++)t[e+c]=a.charCodeAt(c);return e+a.length}function Ce(t){if(t.raw!==void 0)return` ${t.raw}`;let e="";t.t&&(e+=` t="${t.t}"`),t.si!==void 0&&(e+=` si="${t.si}"`),t.ref&&(e+=` ref="${T(t.ref)}"`);for(const s of["dt2D","dtr","r1","r2","del1","del2"])t[s]!==void 0&&(e+=` ${s}="${T(t[s])}"`);return t.ca&&(e+=` ca="${t.ca}"`),e}const Ie=t=>xe(t)?"#VALUE!":nt[t];async function es(t,e,s){const{rows:a,cols:c,kinds:n,values:l,styles:p,count:f,formulas:w,valueMeta:b,rowMeta:d}=e,m=e.inlineText??null;let x=0,u=0,$=0;const g=d?d.length:0,R=async(h,r)=>{let i=`<row r="${h+1}"`;if($<g&&d[$]===h){const o=d[$+1];o>=0&&(i+=d[$+4]?` ht="${o}" customHeight="1"`:` ht="${o}"`),d[$+2]&&(i+=' hidden="1"'),d[$+3]&&(i+=` s="${d[$+3]}" customFormat="1"`),d[$+5]&&(i+=` ${d[$+5]}`),$+=6}await t.text(i+(r?">":"/>"))},j=async h=>{for(;$<g&&d[$]<h;)await R(d[$],!1)};let N=s.row;for(let h=0;h<f;h++){const r=a[h];r!==N&&(N>=0&&await t.text("</row>"),await j(r),await R(r,!0),N=r),t.pos+512>t.buf.length&&await t.flush();const i=t.buf;let o=S(i,t.pos,Gt);o=S(i,o,qt(c[h])),o=H(i,o,r+1);const k=p[h];k!==0&&(o=S(i,o,Yt),o=H(i,o,k)),b!==null&&u<b.length&&b[u][0]===h?(o=S(i,o,ve),o=H(i,o,b[u][1]),u++):(n[h]&ce)===Z&&s.errorVms&&xe(l[h])&&s.errorVms[l[h]]!==void 0&&(o=S(i,o,ve),o=H(i,o,s.errorVms[l[h]]));const C=n[h],y=C&ce,P=l[h];if(C&lt){const[z,M,Y]=w[x];if(z!==h)throw new Error("Formula list out of order");x++,M.cm&&(o=S(i,o,Qt),o=H(i,o,M.cm)),y===te?(o=S(i,o,G),i[o++]=115,i[o++]=116,i[o++]=114):y===ee?(o=S(i,o,G),i[o++]=98):y===Z&&(o=S(i,o,G),i[o++]=101),t.pos=S(i,o,Re);const v=M.f!==void 0?`<f${Ce(M)}>${T(M.f)}</f>`:`<f${Ce(M)}/>`;let I="";y===me?I=`<v>${P}</v>`:y===te?I=`<v>${K(Y??"")}</v>`:y===ee?I=`<v>${P}</v>`:y===Z&&(I=`<v>${Ie(P)}</v>`),await t.text(v+I),t.pos+8>t.buf.length&&await t.flush(),t.pos=S(t.buf,t.pos,Se);continue}switch(y){case me:o=S(i,o,Q),o=Jt(i,o,P),t.pos=S(i,o,J);break;case te:if(o=S(i,o,G),i[o++]=115,m!==null&&m.has(h)){i[o++]=116,i[o++]=114,t.pos=S(i,o,Re),await t.text(`<v>${K(m.get(h))}</v>`),t.pos+8>t.buf.length&&await t.flush(),t.pos=S(t.buf,t.pos,Se);continue}o=S(i,o,Q),o=H(i,o,P),t.pos=S(i,o,J);break;case ee:o=S(i,o,G),i[o++]=98,o=S(i,o,Q),o=H(i,o,P),t.pos=S(i,o,J);break;case Z:o=S(i,o,G),i[o++]=101,o=S(i,o,Q),o=S(i,o,_(Ie(P))),t.pos=S(i,o,J);break;default:t.pos=S(i,o,Zt)}}s.row=N,$<g&&(N>=0&&await t.text("</row>"),s.row=-1,await j(1/0))}const Ne=t=>t.startsWith("xl/chartsheets/"),Ee=t=>Ne(t)?ts:Ft,ts="application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml";async function ss(t,e,s,a,c,n,l,p,f){const w=await Ae("</worksheet>",e,s,a,n,p),b=a===c.activeSheet||e.tabSelected===!0;if(l){const d=await n.zip.text(s);let m=d;if(/\btabSelected="(?:1|true)"/.test(d)!==b&&(m=m.replace(/<sheetView\b[^>]*>/,x=>{const u=x.replace(/\s+tabSelected="[^"]*"/,"");return b?u.replace("<sheetView",'<sheetView tabSelected="1"'):u})),e.pageSetup&&(m=be(m,e.pageSetup)),m===d)return;await t.addBytes(s,new TextEncoder().encode(m))}else{let d=`${O}<chartsheet xmlns="${q}" xmlns:r="${A}"><sheetPr/><sheetViews><sheetView${b?' tabSelected="1"':""} workbookViewId="0" zoomToFit="1"/></sheetViews><pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>${w.replace("</worksheet>","</chartsheet>")}`;e.pageSetup&&(d=be(d,e.pageSetup)),await t.addBytes(s,new TextEncoder().encode(d))}f.add(s)}async function Ae(t,e,s,a,c,n){let l=t;e.cf!==null&&e.cf!==void 0&&(l=vt(l,e.cf,D)),e.validations!==null&&e.validations!==void 0&&(l=D(l,"dataValidations",Et(e.validations))),e.sparklines!==null&&e.sparklines!==void 0&&(l=dt(l,e.sparklines)),e.scenarios!==null&&e.scenarios!==void 0&&(l=D(l,"scenarios",Nt(e.scenarios))),e.dataConsolidate!==null&&e.dataConsolidate!==void 0&&(l=D(l,"dataConsolidate",e.dataConsolidate)),e.customSheetViews!==null&&e.customSheetViews!==void 0&&(l=D(l,"customSheetViews",e.customSheetViews)),e.protection!==null&&e.protection!==void 0&&(l=D(l,"sheetProtection",It(e.protection))),e.ignoredErrors!==null&&e.ignoredErrors!==void 0&&(l=D(l,"ignoredErrors",e.ignoredErrors));const p=V(s);e.sheetPicture&&(l=st(l,e.sheetPicture),e.sheetPicture.path&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${e.sheetPicture.rid}"`)||(n.rels.has(p)||n.rels.set(p,[]),n.rels.get(p).push(`<Relationship Id="${e.sheetPicture.rid}" Type="${A}/image" Target="${T(E(s,e.sheetPicture.path))}"/>`)))),e.headerPicture&&(l=D(l,"legacyDrawingHF",e.headerPicture.rid?`<legacyDrawingHF r:id="${e.headerPicture.rid}"/>`:""),e.headerPicture.rid&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${e.headerPicture.rid}"`)||(n.rels.has(p)||n.rels.set(p,[]),n.rels.get(p).push(`<Relationship Id="${e.headerPicture.rid}" Type="${A}/vmlDrawing" Target="${T(E(s,e.headerPicture.vml))}"/>`))));for(const m of n.plan.removedTableRids?.[a]??[])l=l.replace(new RegExp(`<tablePart\\b[^>]*r:id="${m}"[^>]*/>`),"");if(n.plan.removedTableRids?.[a]){const m=(l.match(/<tablePart\b/g)??[]).length;l=m===0?l.replace(/<tableParts\b[^>]*\/>|<tableParts\b[^>]*>\s*<\/tableParts>/,""):l.replace(/(<tableParts\b[^>]*\bcount=")\d+/,`$1${m}`)}const f=(n.plan.tables??[]).filter(m=>m.isNew&&m.sheetIndex===a),w=(m,x,u,$)=>{n.rels.has(p)||n.rels.set(p,[]);const g=x==="threadedCommentExternal"?bs:`${A}/${x}`;n.rels.get(p).push(`<Relationship Id="${m}" Type="${g}" Target="${T(u)}"${$?' TargetMode="External"':""}/>`)};if(f.length>0){const m=[...l.matchAll(/<tablePart\b[^>]*\/>/g)].map($=>$[0]),x=f.map(($,g)=>{const R=`rIdTable${a}_${g}`;return w(R,"table",E(s,$.part),!1),`<tablePart r:id="${R}"/>`}),u=[...m,...x];l=D(l,"tableParts",`<tableParts count="${u.length}">${u.join("")}</tableParts>`)}if(e.hyperlinks!==null&&e.hyperlinks!==void 0){const m=e.hyperlinks.map((x,u)=>{if(x.rid||!x.target)return x;const $=`rIdLink${a}_${u}`;return w($,"hyperlink",x.target,!0),{...x,rid:$}});l=D(l,"hyperlinks",Ct(m))}if(e.threads){const m=n.plan.threadParts?.[a];m&&(n.parts.push({path:m.path,xml:ks(e.threads)}),m.existing||w(`rIdThreads${a+1}`,"threadedCommentExternal",E(s,m.path),!1))}const b=n.plan.noteParts?.[a];if(b&&e.comments){if(b.existing)n.parts.push({path:b.comments,xml:Oe(e.comments)}),b.vml&&n.parts.push({path:b.vml,xml:_e(b.vmlSource,e.comments)}),b.threaded&&n.parts.push({path:b.threaded,xml:Le(b.threadedSource,e.structureOps??[])});else if(e.comments.length>0){const{comments:m,vml:x,n:u}=b;n.parts.push({path:m,xml:Oe(e.comments)}),w(`rIdComments${u}`,"comments",E(s,m),!1);const $=/<legacyDrawing\b[^>]*r:id="([^"]+)"/.exec(l)?.[1],g=$&&c?.zip.has(p)?await c.zip.text(p):"",R=g?[...g.matchAll(/<Relationship\b[^>]*\/>/g)].map(h=>h[0]).find(h=>h.includes(`Id="${$}"`)):null,j=R?/Target="([^"]+)"/.exec(R)?.[1]:null,N=j?B(s,j):null;N&&c.zip.has(N)?n.parts.push({path:N,xml:_e(await c.zip.text(N),e.comments)}):(n.parts.push({path:x,xml:as(e.comments)}),w(`rIdVml${u}`,"vmlDrawing",E(s,x),!1),l=D(l,"legacyDrawing",`<legacyDrawing r:id="rIdVml${u}"/>`))}}const d=e.objects;if(d){n.parts.push({path:d.path,xml:d.xml}),d.relsXml&&n.parts.push({path:d.relsPath,xml:d.relsXml});for(const m of d.parts)n.parts.push({path:m.path,xml:m.data instanceof Blob?new Uint8Array(await m.data.arrayBuffer()):m.data});d.isNew&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${d.sheetRel.id}"`)||w(d.sheetRel.id,"drawing",d.sheetRel.target,!1),l=ht(l,d.sheetDrawingXml)),d.controls&&(n.rels.has(p)||n.rels.set(p,[]),l=await pt(l,d.controls,{source:c,part:s,relsName:p,addRel:w,extraParts:n.parts,pendingRels:n.rels.get(p),relativeTo:E,resolveTarget:B}))}return ut({tail:l,index:a,info:e,source:c,extra:n,relsName:p})}function Oe(t){const e=[...new Set(t.map(s=>s.author??""))];return`${O}<comments xmlns="${q}"><authors>${e.map(s=>`<author>${K(s)}</author>`).join("")}</authors><commentList>${t.map(s=>`<comment ref="${s.ref}" authorId="${e.indexOf(s.author??"")}"><text>${ps(s,K)}</text></comment>`).join("")}</commentList></comments>`}function De(t,e=1025){return t.map((s,a)=>hs(s,e+a,a+1,he(s.ref))).join("")}function _e(t,e){const s=t.replace(/<v:shape\b(?:(?!<\/v:shape>)[\s\S])*?ObjectType="Note"[\s\S]*?<\/v:shape>/g,"");let a=1024;for(const c of s.matchAll(/_x0000_s(\d+)/g))a=Math.max(a,Number(c[1]));return s.replace("</xml>",`${De(e,a+1)}</xml>`)}function as(t){return`<xml xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1"/></o:shapelayout><v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter"/><v:path gradientshapeok="t" o:connecttype="rect"/></v:shapetype>${De(t)}</xml>`}function Ve(t){return!t||t.length===0?"":`<cols>${t.map(s=>{let a=`<col min="${s.min+1}" max="${s.max+1}" width="${ot(s.px)}"`;return s.custom&&(a+=' customWidth="1"'),s.hidden&&(a+=' hidden="1"'),s.style&&(a+=` style="${s.style}"`),s.extra&&(a+=` ${s.extra}`),a+"/>"}).join("")}</cols>`}function je(t,e){const s=cs(t,e);let a="";if(t.frozenRows||t.frozenCols){const c=t.frozenRows&&t.frozenCols?"bottomRight":t.frozenRows?"bottomLeft":"topRight",n=(t.frozenCols?` xSplit="${t.frozenCols}"`:"")+(t.frozenRows?` ySplit="${t.frozenRows}"`:""),l=de(t.frozenCols)+(t.frozenRows+1);a=`<pane${n} topLeftCell="${l}" activePane="${c}" state="frozen"/>`}else t.split&&(a=tt(t));return`<sheetViews><sheetView${s} workbookViewId="0">${a}</sheetView></sheetViews>`}function ze(t){return t.maxRow<0||t.maxCol<0?"A1":se({r0:0,c0:0,r1:t.maxRow,c1:t.maxCol})}function rs(t,e){const s=t.tabColor?`<sheetPr><tabColor rgb="FF${t.tabColor.slice(1)}"/></sheetPr>`:"";return`${O}<worksheet xmlns="${q}" xmlns:r="${A}" xmlns:mc="${Ht}" mc:Ignorable="x14ac" xmlns:x14ac="${Wt}">${s}<dimension ref="${ze(t)}"/>${je(t,e)}<sheetFormatPr baseColWidth="10" defaultRowHeight="${t.defaultHeight}"/>${Ve(t.cols)}`}function os(t,e){let s=t;if(e.tabColor!==null&&e.tabColor!==void 0&&(s=s.replace(/<tabColor\b[^>]*\/>/,""),e.tabColor)){const c=`<tabColor rgb="FF${e.tabColor.slice(1)}"/>`;/<sheetPr\b[^>]*\/>/.test(s)?s=s.replace(/<sheetPr\b([^>]*)\/>/,`<sheetPr$1>${c}</sheetPr>`):/<sheetPr\b[^>]*>/.test(s)?s=s.replace(/(<sheetPr\b[^>]*>)/,`$1${c}`):s=s.replace(/(<worksheet\b[^>]*>)/,`$1<sheetPr>${c}</sheetPr>`)}const a=`<dimension ref="${ze(e)}"/>`;if(/<dimension\b[^>]*\/>/.test(s)&&(s=s.replace(/<dimension\b[^>]*\/>/,a)),e.viewChanged?/<sheetViews\b[\s\S]*<\/sheetViews>/.test(s)&&(s=s.replace(/<sheetViews\b[\s\S]*<\/sheetViews>/,je(e,e.tabSelected))):s=ls(s,e),e.defaultsChanged&&(s=s.replace(/(<sheetFormatPr\b[^>]*?\bdefaultRowHeight=")[^"]*"/,`$1${e.defaultHeight}"`)),e.colsChanged){const c=Ve(e.cols);/<cols\b[\s\S]*<\/cols>/.test(s)?s=s.replace(/<cols\b[\s\S]*<\/cols>/,c):s+=c}return s}import{bookViewsXml as is,patchBookViews as ns,patchTabSelected as ls,sheetViewAttrs as cs}from"../cells/view-xml.js";import{docPropsRels as ms,docPropsTypes as Me,writeDocProps as ds}from"../cells/docprops-xml.js";import{noteShapeXml as hs,noteTextXml as ps}from"../cells/note-xml.js";const fs=/<(phoneticPr|conditionalFormatting|dataValidations|hyperlinks|printOptions|pageMargins|pageSetup|headerFooter|rowBreaks|colBreaks|customProperties|cellWatches|ignoredErrors|smartTags|drawing|legacyDrawing|legacyDrawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst)\b|<\/worksheet>/;function Xe(t){return t.length===0?"":`<mergeCells count="${t.length}">${t.map(e=>`<mergeCell ref="${se(e)}"/>`).join("")}</mergeCells>`}function Le(t,e){return e.length===0?t:t.replace(/\b(sqref|ref)="([^"]*)"/g,(s,a,c)=>{const n=c.split(/\s+/).map(p=>{let f=he(p);if(f===null)return null;for(const w of e){if(f===null)break;f=mt(f,w)}return f===null?"":se(f)});if(n.includes(null))return s;const l=n.filter(p=>p!=="");return l.length?`${a}="${l.join(" ")}"`:`${a}="A1048576"`})}function us(t,e,s=[]){t=Le(t,s);const a=Xe(e),c=/<mergeCells\b[\s\S]*?<\/mergeCells>/;if(c.test(t))return t.replace(c,a);if(!a)return t;const n=fs.exec(t);return n?t.slice(0,n.index)+a+t.slice(n.index):t+a}const ws=new TextDecoder("latin1");async function xs(t,e,s,a){let n=new Uint8Array(0),l=!0;await it(await e.stream(s),async b=>{let d=b;if(l){l=!1;const m=Bt.decode(d.subarray(0,Math.min(d.length,512))),x=/<sst\b[^>]*>/.exec(m);if(x){const u=x[0].replace(/\s(count|uniqueCount)="\d+"/g,""),$=F.encode(m.slice(0,x.index)+u),g=F.encode(m.slice(0,x.index+x[0].length)).length;await t($),d=d.subarray(g)}}if(d.length>=16)n.length&&await t(n),await t(d.subarray(0,d.length-16)),n=d.slice(d.length-16);else{const m=new Uint8Array(n.length+d.length);m.set(n),m.set(d,n.length),n=m}});const p=ws.decode(n),f=F.encode(a),w=p.lastIndexOf("</sst>");w>=0?(await t(n.subarray(0,w)),await t(f),await t(n.subarray(w))):p.endsWith("/>")?(await t(n.subarray(0,n.length-2)),await t(F.encode(`>${a}</sst>`))):(await t(n),await t(f))}const W="xl/metadata.xml",Be="application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",Fe=`${O}<metadata xmlns="${q}" xmlns:xda="http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray"><metadataTypes count="1"><metadataType name="XLDAPR" minSupportedVersion="120000" copy="1" pasteAll="1" pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1" clearComments="1" assign="1" coerce="1" cellMeta="1"/></metadataTypes><futureMetadata name="XLDAPR" count="1"><bk><extLst><ext uri="{bdbb8cdc-fa1e-496e-a857-3c3f30c029c3}"><xda:dynamicArrayProperties fDynamic="1" fCollapsed="0"/></ext></extLst></bk></futureMetadata><cellMetadata count="1"><bk><rc t="1" v="0"/></bk></cellMetadata></metadata>`,gs=(t,e)=>e?yt(t,e,K):`<si><t xml:space="preserve">${K(t)}</t></si>`;async function pa(t,e,s,a=null,c=null){const n=new et(t),l=[],p=new Set;a&&e.dataSheets&&Pt(a.zip,p,e.dataSheets);for(const r of e.sheets)if(r.objects)for(const i of r.objects.removedParts)p.add(i);const f=e.pivots??null,w=new Set([...e.sheets.flatMap(r=>(r.objects?.removedParts??[]).filter(i=>i.startsWith("xl/ctrlProps/"))),...f?.replaced??[],...wt(e),...(e.removedTables??[]).map(r=>r.part)]);for(const r of w)p.add(r),p.add(V(r));e.sheetRefs=e.sheets.map((r,i)=>({rid:`rId${i+1}`,sheetId:i+1})),e.written=[];const b=new Set(a?a.sheets.map(r=>r.part):[]),d=new Set(e.sheets.filter(r=>r.sourceIndex>=0).map(r=>a.sheets[r.sourceIndex].part)),m=new Set(a?a.sheets.map(r=>r.part).filter(r=>!d.has(r)):[]);let x=1;const u=e.sheets.map(r=>{if(r.sourceIndex>=0)return a.sheets[r.sourceIndex].part;let i;do i=`xl/${r.chartSheet?"chartsheets":"worksheets"}/sheet${x++}.xml`;while(b.has(i));return b.add(i),l.push(i),i}),$=a?.stringsPart??"xl/sharedStrings.xml",g=a?.stylesPart??"xl/styles.xml";e.noteParts=await $s(e,u,a),{threads:e.threadParts,personPart:e.personPart}=await Ss(e,u,a);let R=null;if(a)await Rs(n,a,e,u,l,$,g,p);else{let r=vs(u,e.dynamicArrays,e);for(const P of e.sheets)P.objects&&(r=X(r,P.objects.contentTypes,P.objects.removedOverrides));f&&(r=X(r,f.contentTypes,[])),r=pe(r,e),r=X(r,We(e),[]),{types:r}=ae(r,"</Relationships>",e.cellTypes),r=Me(r,e.docProps),e.dataSheets&&(r=ge(r,e.dataSheets));let i=null;e.themeXml&&({types:r,rels:i}=await le(n,{types:r,rels:"</Relationships>"},e.themeXml));const o=c?.plan??null;o&&(r=X(r,[...o.overrides,...o.defaults],[])),R=Xt(o,e),R&&(r=X(r,R.types,[])),r=Ye(r,e.workbookType),o?.macro&&(r=r.replace(/application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)\.main\+xml/,Cs)),await n.addBytes("[Content_Types].xml",r);const k=(o?.rootRels??[]).map((P,z)=>`<Relationship Id="rIdForeign${z+1}" Type="${T(P.type)}" Target="${T(P.target)}"/>`).join("");await n.addBytes("_rels/.rels",`${O}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${A}/officeDocument" Target="xl/workbook.xml"/>${ms(e.docProps)}${k}</Relationships>`);let C=Ge(ne(Ke(Ze(Is(Es(e),o?.codeNames.workbook),e.workbookProtection),e.calcMode),e.calcSettings),e.fileSharing),y=ae("</Types>",As(u,e.dynamicArrays),e.cellTypes).rels;i&&(y=y.replace("</Relationships>",i)),e.personPart&&(y=y.replace("</Relationships>",`<Relationship Id="rIdPersons" Type="${He}" Target="${E("xl/workbook.xml",e.personPart.path)}"/></Relationships>`)),f&&(y=y.replace("</Relationships>",`${Qe(f)}</Relationships>`),C=Je(C,f)),y=ue(y,e),await n.addBytes("xl/workbook.xml",fe(C,e)),e.dataSheets&&(y=$e(y,e.dataSheets)),o?.workbookRels.length&&(y=y.replace("</Relationships>",`${o.workbookRels.map((P,z)=>`<Relationship Id="rIdForeign${z+1}" Type="${T(P.type)}" Target="${T(E("xl/workbook.xml",P.target))}"/>`).join("")}</Relationships>`)),await n.addBytes("xl/_rels/workbook.xml.rels",y),e.dynamicArrays&&await n.addBytes(W,Fe),await n.addBytes(g,we(at(e.styles,(e.newDxfs??[]).map(ke),e),e.customStyles))}const j=e.extraRich?new Map(e.extraRich):null,N=e.extraStrings.map((r,i)=>gs(r,j?.get(i))).join("");a?.stringsPart&&a.zip.has(a.stringsPart)?await n.add($,r=>xs(r,a.zip,a.stringsPart,N)):await n.addBytes($,`${O}<sst xmlns="${q}">${N}</sst>`),p.add($);const h={rels:new Map,parts:[],next:1,plan:e};if(e.removedTableRids={},a&&(e.removedTables??[]).length>0)for(const r of e.removedTables){const i=V(u[r.sheetIndex]);if(!a.zip.has(i))continue;const o=await a.zip.text(i);for(const k of o.matchAll(/<Relationship\b[^>]*\/>/g)){const C=/\bTarget="([^"]+)"/.exec(k[0])?.[1],y=/\bId="([^"]+)"/.exec(k[0])?.[1];C&&y&&B(u[r.sheetIndex],C)===r.part&&(e.removedTableRids[r.sheetIndex]??=[]).push(y)}h.rels.has(i)||h.rels.set(i,[])}for(let r=0;r<e.sheets.length;r++){const i=e.sheets[r],o=i.sourceIndex>=0?a.sheets[i.sourceIndex]:null;if(i.chartSheet){await ss(n,i,u[r],r,e,a,o,h,p),e.written[r]={head:"",tail:""},e.onSheetDone?.(r);continue}p.add(u[r]);const k=i.cellEstimate>Ut;await n.add(u[r],async C=>{const y=new Kt(C);let P=o?.head?os(o.head,i):rs(i,r===e.activeSheet||i.tabSelected===!0);P=Rt(P,i.sheetProps),!o&&c?.plan.codeNames.sheets[i.name]&&(P=Ns(P,c.plan.codeNames.sheets[i.name])),i.pageSetup&&(P=Tt(P,i.pageSetup));const z=o?null:R?.sheets.get(r);z&&(P=jt(P,z),Vt(i.objects,z)),e.written[r]={head:P},await y.text(P),await y.text("<sheetData>");const M={row:-1,errorVms:e.errorVms??null};for(let I=0;I>=0;){const U=await s.block(r,I);await es(y,U,M),I=U.nextRow,s.recycle?.(U)}M.row>=0&&await y.text("</row>"),await y.text("</sheetData>");const Y=i.autoFilter??"";let v=o?us(o.tail??"</worksheet>",i.merges,i.structureOps??[]):`${Y}${Xe(i.merges)}</worksheet>`;if(!o&&!/xmlns:r=/.test(v)&&(v=`${v}`),o&&i.autoFilter!==null&&i.autoFilter!==void 0){v=v.replace(/<autoFilter\b[^>]*?(?:\/>|>[\s\S]*?<\/autoFilter>)/,"").replace(/<sortState\b[^>]*?(?:\/>|>[\s\S]*?<\/sortState>)/,"");const I=/<mergeCells\b|<(?:sortState|dataConsolidate|customSheetViews|phoneticPr|conditionalFormatting|dataValidations|hyperlinks|printOptions|pageMargins|pageSetup|headerFooter|rowBreaks|colBreaks|customProperties|cellWatches|ignoredErrors|smartTags|drawing|legacyDrawing|legacyDrawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst)\b|<\/worksheet>/.exec(v);v=I?v.slice(0,I.index)+Y+v.slice(I.index):v+Y}if(v=await Ae(v,i,u[r],r,a,h),i.pageSetup&&(v=St(v,i.pageSetup)),!o){v=v.replace(/(<pageSetup\b[^>]*?)\sr:id="[^"]*"/,"$1");const I=R?.sheets.get(r);if(I){const U=V(u[r]);h.rels.has(U)||h.rels.set(U,[]),v=await _t(v,{group:I,part:u[r],pending:h.rels.get(U),extraParts:h.parts,foreignZip:c.zip,names:R.names,kept:R.kept})}}e.written[r].tail=v,await y.text(v),await y.flush()},{large:k}),e.onSheetDone?.(r)}if(f){for(const o of f.parts)await n.addBytes(o.name,o.xml),p.add(o.name);const r=new Map;let i=0;for(const o of f.relationships)if(o.from!==null)r.has(o.from)||r.set(o.from,[]),r.get(o.from).push(o);else if(o.sheetIndex>=0){const k=V(u[o.sheetIndex]);h.rels.has(k)||h.rels.set(k,[]),h.rels.get(k).push(`<Relationship Id="rIdPivot${++i}" Type="${o.type}" Target="${T(o.target)}"/>`)}for(const[o,k]of r){const C=V(o);await n.addBytes(C,ft(k)),p.add(C)}for(const o of u){const k=V(o);a?.zip.has(k)&&!h.rels.has(k)&&h.rels.set(k,[])}}if(e.slicers?.removedParts.length)for(const r of u){const i=V(r);a?.zip.has(i)&&!h.rels.has(i)&&h.rels.set(i,[])}await xt(n,e,p);for(const r of e.tables??[]){let i=r.xml;i===null&&(i=gt(await a.zip.text(r.part),r.patch));const o=R?.tables.get(r.part);if(o){i=Mt(i,o);const k=zt(r.part,o,R.names);await n.addBytes(k.path,k.xml),p.add(k.path)}await n.addBytes(r.part,i),p.add(r.part)}for(const r of e.cellTypes??[])await n.addBytes(r.path,r.xml),p.add(r.path);e.personPart&&(await n.addBytes(e.personPart.path,Ts(e.persons)),p.add(e.personPart.path));for(const r of h.parts)await n.addBytes(r.path,r.xml),p.add(r.path);for(const[r,i]of h.rels){let o=a?.zip.has(r)?await a.zip.text(r):`${O}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>`;if(w.size>0){const C=r.replace("_rels/","").replace(/\.rels$/,"");o=oe(o,C,w)}const k=o.replace("</Relationships>",`${i.join("")}</Relationships>`);await n.addBytes(r,k),p.add(r)}if(await ds(n,a?.zip??null,e.docProps,p),await kt(n,e.dataSheets,p),a){const r=new Set([...p,a.calcChainPart,...m].map(i=>a.zip.entry(i)?.name).filter(Boolean));for(const[i,o]of a.zip.entries)r.has(i)||await n.copyRaw(a.zip,o)}if(!a&&c){const r=new Set(n.central.map(i=>i.name));for(const i of c.plan.entries){const o=c.zip.entries.get(i);o&&!r.has(i)&&await n.copyRaw(c.zip,o)}R&&await Lt(n,R,c.zip,r)}await n.finish(),e.result={sheets:e.sheets.map((r,i)=>({name:r.name,part:u[i],rid:e.sheetRefs[i].rid,sheetId:e.sheetRefs[i].sheetId,hidden:r.hidden,veryHidden:r.veryHidden,head:e.written[i].head,tail:e.written[i].tail})),workbookPart:a?.workbookPart??"xl/workbook.xml",wbRelsPath:a?.wbRelsPath??"xl/_rels/workbook.xml.rels",stringsPart:$,stylesPart:g}}async function $s(t,e,s){const a={};let c=1;for(let n=0;n<t.sheets.length;n++){const l=t.sheets[n];if(!l.comments)continue;const p=V(e[n]);if(s?.zip.has(p)&&l.sourceIndex>=0){const f=await s.zip.text(p),w=d=>{const m=[...f.matchAll(/<Relationship\b[^>]*\/>/g)].map(u=>u[0]).find(u=>new RegExp(`\\bType="[^"]*/${d}"`).test(u)),x=m&&/\bTarget="([^"]+)"/.exec(m)?.[1];return x?B(e[n],x):null},b=w("comments");if(b){const d=w("vmlDrawing"),m=w("threadedComment");a[n]={existing:!0,comments:b,vml:d,vmlSource:d?await s.zip.text(d):null,threaded:m,threadedSource:m?await s.zip.text(m):null};continue}}if(l.comments.length!==0){for(;s?.zip.has(`xl/comments${100+c}.xml`)||s?.zip.has(`xl/drawings/vmlDrawing${100+c}.vml`);)c++;a[n]={existing:!1,comments:`xl/comments${100+c}.xml`,vml:`xl/drawings/vmlDrawing${100+c}.vml`,n:c},c++}}return a}const bs="http://schemas.microsoft.com/office/2017/10/relationships/threadedComment",He="http://schemas.microsoft.com/office/2017/10/relationships/person",ys="application/vnd.ms-excel.threadedcomments+xml",Ps="application/vnd.ms-excel.person+xml";function ks(t){const e=t.map(s=>`<threadedComment ref="${s.ref}" dT="${T(s.date)}" personId="${T(s.personId)}" id="${T(s.id)}"${s.parentId?` parentId="${T(s.parentId)}"`:""}${s.done?' done="1"':""}><text>${K(s.text)}</text>${s.mentions?.length?`<mentions>${s.mentions.map(a=>`<mention mentionpersonId="${T(a.personId)}" mentionId="${T(a.id??s.id.replace(/^.{9}/,`{${String(a.start).padStart(8,"0")}`))}" startIndex="${a.start}" length="${a.length}"/>`).join("")}</mentions>`:""}</threadedComment>`).join("");return`${O}<ThreadedComments xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">${e}</ThreadedComments>`}function Ts(t){const e=t.map(s=>`<person displayName="${L(s.displayName)}" id="${T(s.id)}" userId="${T(s.userId)}" providerId="${T(s.providerId)}"/>`).join("");return`${O}<personList xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">${e}</personList>`}async function Ss(t,e,s){const a={};let c=1;for(let l=0;l<t.sheets.length;l++){const p=t.sheets[l];if(!p.threads)continue;const f=V(e[l]);let w=null;if(s?.zip.has(f)&&p.sourceIndex>=0){const d=[...(await s.zip.text(f)).matchAll(/<Relationship\b[^>]*\/>/g)].map(x=>x[0]).find(x=>/\/threadedComment"/.test(x)),m=d&&/\bTarget="([^"]+)"/.exec(d)?.[1];m&&(w=B(e[l],m))}if(w){a[l]={path:w,existing:!0};continue}if(p.threads.length!==0){for(;s?.zip.has(`xl/threadedComments/threadedComment${100+c}.xml`);)c++;a[l]={path:`xl/threadedComments/threadedComment${100+c}.xml`,existing:!1},c++}}let n=null;if(t.persons){let l=null;if(s?.zip.has(s.wbRelsPath)){const f=[...(await s.zip.text(s.wbRelsPath)).matchAll(/<Relationship\b[^>]*\/>/g)].map(b=>b[0]).find(b=>/\/person"/.test(b)),w=f&&/\bTarget="([^"]+)"/.exec(f)?.[1];w&&(l=B(s.workbookPart,w))}n=l?{path:l,existing:!0}:{path:"xl/persons/person.xml",existing:!1}}return{threads:a,personPart:n}}const We=t=>[...Object.values(t.threadParts??{}).filter(e=>!e.existing).map(e=>({partName:`/${e.path}`,contentType:ys})),...t.personPart&&!t.personPart.existing?[{partName:`/${t.personPart.path}`,contentType:Ps}]:[]],Ue="application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",re=t=>Object.values(t.noteParts??{}).filter(e=>!e.existing);function Ke(t,e){if(e==null)return t;const s=e==="auto"?"":` calcMode="${e}"`;if(/<calcPr\b/.test(t))return t.replace(/<calcPr\b([^>]*?)\/>/,(c,n)=>`<calcPr${n.replace(/\s*calcMode="[^"]*"/,"")}${s}/>`);if(!s)return t;const a=ie(t);return t.replace(a,`${a}<calcPr${s}/>`)}const qe=(t,e)=>e.customViews?At(t,e.customViews.workbookXml,e.customViews.names):t;function Ge(t,e){if(e==null)return t;const s=t.replace(/<fileSharing\b[^>]*\/>/,""),a=Object.keys(e).filter(f=>e[f]!==void 0&&e[f]!==null&&e[f]!=="");if(a.length===0)return s;const c=`<fileSharing ${a.map(f=>`${f}="${T(e[f])}"`).join(" ")}/>`,n=/<fileVersion\b[^>]*\/>/.exec(s),l=/<workbook\b[^>]*>/.exec(s),p=n?n.index+n[0].length:l.index+l[0].length;return s.slice(0,p)+c+s.slice(p)}function Ye(t,e){if(!e)return t;const s=e==="template"?"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":e==="macro"?"application/vnd.ms-excel.sheet.macroEnabled.main+xml":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",a=e==="workbook"?/application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)\.main\+xml/:/application\/vnd\.(?:openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)|ms-excel\.sheet\.macroEnabled)\.main\+xml/;return t.replace(a,s)}function Ze(t,e){if(e==null)return t;const s=t.replace(/<workbookProtection\b[^>]*\/>/,""),a=Object.keys(e);if(a.length===0)return s;const c=`<workbookProtection ${a.map(l=>`${l}="${T(e[l])}"`).join(" ")}/>`,n=/<bookViews\b|<sheets\b/.exec(s);return s.slice(0,n.index)+c+s.slice(n.index)}const Qe=t=>t.caches.map(e=>`<Relationship Id="${e.relId}" Type="${e.type}" Target="${T(e.target)}"/>`).join("");function oe(t,e,s){return t.replace(/<Relationship\b[^>]*\/>/g,a=>{const c=/\bTarget="([^"]+)"/.exec(a);return c&&s.has(B(e,c[1]))?"":a})}function Je(t,e,s=null){let a="";const c=/<pivotCaches\b[^>]*>([\s\S]*?)<\/pivotCaches>/.exec(t);c&&s&&(a=[...c[1].matchAll(/<pivotCache\b[^>]*\/>/g)].map(w=>w[0]).filter(w=>s.has(/r:id="([^"]+)"/.exec(w)?.[1])).join(""));const n=e.caches.map(w=>`<pivotCache cacheId="${w.cacheId}" r:id="${w.relId}"/>`).join(""),l=t.replace(/<pivotCaches\b[^>]*>[\s\S]*?<\/pivotCaches>/,""),p=a||n?`<pivotCaches>${a}${n}</pivotCaches>`:"";if(!p)return l;const f=/<(?:smartTagPr|smartTagTypes|webPublishing|fileRecoveryPr|webPublishObjects|extLst)\b|<\/workbook>/.exec(l);return f?l.slice(0,f.index)+p+l.slice(f.index):l+p}async function Rs(t,e,s,a,c,n,l,p){const f=e.zip,w=await f.text(e.wbRelsPath);let b=null,d=w.replace(/<Relationship\b[^>]*calcChain[^>]*\/>/g,h=>{const r=/Target="([^"]+)"/.exec(h);return r&&(b=B(e.workbookPart,r[1])),""});e.calcChainPart=b;let m=await f.text("[Content_Types].xml");m=m.replace(/<Override\b[^>]*calcChain[^>]*\/>/g,"");const x=c.map(h=>`<Override PartName="/${h}" ContentType="${Ee(h)}"/>`);if(f.has(n)||(x.push(`<Override PartName="/${n}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>`),d=d.replace("</Relationships>",`<Relationship Id="rIdStrings" Type="${A}/sharedStrings" Target="${E(e.workbookPart,n)}"/></Relationships>`)),re(s).length>0){/Extension="vml"/.test(m)||(m=m.replace(/(<Types\b[^>]*>)/,'$1<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>'));for(const h of re(s))x.push(`<Override PartName="/${h.comments}" ContentType="${Ue}"/>`)}s.dynamicArrays&&!f.has(W)&&(x.push(`<Override PartName="/${W}" ContentType="${Be}"/>`),d=d.replace("</Relationships>",`<Relationship Id="rIdMetadata" Type="${A}/sheetMetadata" Target="${E(e.workbookPart,W)}"/></Relationships>`),await t.addBytes(W,Fe),p.add(W)),s.dynamicArrays&&f.has(W);for(const h of s.tables??[])h.isNew&&x.push(`<Override PartName="/${h.part}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/>`);m=m.replace("</Types>",`${x.join("")}</Types>`);for(const h of s.sheets)h.objects&&(m=X(m,h.objects.contentTypes,h.objects.removedOverrides));m=X(m,We(s),[]),s.personPart&&!s.personPart.existing&&(d=d.replace("</Relationships>",`<Relationship Id="rIdPersons" Type="${He}" Target="${E(e.workbookPart,s.personPart.path)}"/></Relationships>`)),s.dataSheets&&(m=ge(m,s.dataSheets),d=$e(d,s.dataSheets)),{types:m,rels:d}=await $t(f,m,d,p),{types:m,rels:d}=await bt(f,m,d,p),{types:m,rels:d}=ae(m,d,s.cellTypes,e.workbookPart),m=Me(m,s.docProps);const u=s.pivots??null;m=X(m,[],[...u?.replaced??[],...(s.removedTables??[]).map(h=>h.part)].map(h=>`/${h}`)),m=pe(m,s),s.slicers&&(d=ue(oe(d,e.workbookPart,new Set(s.slicers.removedParts)),s)),u&&(m=X(m,u.contentTypes,[]),d=oe(d,e.workbookPart,new Set(u.replaced)),d=d.replace("</Relationships>",`${Qe(u)}</Relationships>`));let $=[];s.externalLinks?.length&&({types:m,rels:d,removedIds:$}=await Dt(t,m,d,p,s.externalLinks,e.workbookPart,E));let g=Ot(await f.text(e.workbookPart),$),R=0;for(const h of e.sheets)R=Math.max(R,Number(h.sheetId));const j=s.sheets.map((h,r)=>{if(h.sourceIndex>=0){const o=e.sheets[h.sourceIndex];s.sheetRefs[r]={rid:o.rid,sheetId:o.sheetId};const k=h.veryHidden?' state="veryHidden"':h.hidden?' state="hidden"':"";return`<sheet name="${L(h.name)}" sheetId="${o.sheetId}"${k} r:id="${o.rid}"/>`}const i=`rIdNew${r}`;return d=d.replace("</Relationships>",`<Relationship Id="${i}" Type="${A}/${h.chartSheet?"chartsheet":"worksheet"}" Target="${E(e.workbookPart,a[r])}"/></Relationships>`),s.sheetRefs[r]={rid:i,sheetId:R+1},`<sheet name="${L(h.name)}" sheetId="${++R}" r:id="${i}"/>`});g=g.replace(/<sheets\b[\s\S]*?<\/sheets>/,`<sheets>${j.join("")}</sheets>`);const N=h=>qe(Pe(ye(h,s.printNames??[]),s.filterNames,s.sheets),s);if(s.definedNames){const h=[...g.matchAll(/<definedName\b[^>]*name="_xlnm\.[^>]*>[\s\S]*?<\/definedName>/g)].map(o=>o[0]),r=s.definedNames.map(o=>`<definedName name="${T(o.name)}"${o.comment?` comment="${L(o.comment)}"`:""}${o.localSheetId!==void 0?` localSheetId="${o.localSheetId}"`:""}${o.hidden?' hidden="1"':""}>${T(o.text)}</definedName>`),i=h.length+r.length?`<definedNames>${[...h,...r].join("")}</definedNames>`:"";/<definedNames\b/.test(g)?g=g.replace(/<definedNames\b[\s\S]*?<\/definedNames>/,i):g=g.replace("</sheets>",`</sheets>${i}`)}if(s.formulasEdited){if(/<calcPr\b/.test(g))g=g.replace(/<calcPr\b([^>]*?)\/>/,(h,r)=>/fullCalcOnLoad/.test(r)?h:`<calcPr${r} fullCalcOnLoad="1"/>`);else if(/<\/sheets>/.test(g)){const h=ie(g);g=g.replace(h,`${h}<calcPr fullCalcOnLoad="1"/>`)}}if(s.themeXml&&({types:m,rels:d}=await le(t,{types:m,rels:d,handled:p},s.themeXml)),await t.addBytes("[Content_Types].xml",Ye(m,s.workbookType)),p.add("[Content_Types].xml"),u){const h=new Set([...d.matchAll(/\bId="([^"]+)"/g)].map(r=>r[1]));g=Je(g,u,h)}g=Ge(ne(Ke(Ze(g,s.workbookProtection),s.calcMode),s.calcSettings),s.fileSharing),g=ns(g,s.bookView),await t.addBytes(e.workbookPart,fe(N(g),s)),p.add(e.workbookPart),await t.addBytes(e.wbRelsPath,d),p.add(e.wbRelsPath),l&&f.has(l)&&(s.styles.length>0||(s.newDxfs??[]).length>0||(s.pivotNumFmts??[]).length>0||s.customStyles||s.namedStyles?.some(h=>!h.keep)?await t.addBytes(l,we(rt(await f.text(l),s.styles,(s.newDxfs??[]).map(ke),s),s.customStyles)):await t.copyRaw(f,f.entry(l)),p.add(l))}function vs(t,e,s){const a=(s.tables??[]).map(l=>`<Override PartName="/${l.part}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/>`).join(""),c=re(s).map(l=>`<Override PartName="/${l.comments}" ContentType="${Ue}"/>`).join(""),n=t.map(l=>`<Override PartName="/${l}" ContentType="${Ee(l)}"/>`).join("");return`${O}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>${c?'<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>':""}${c}<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>${n}<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/><Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>${a}${e?`<Override PartName="/${W}" ContentType="${Be}"/>`:""}</Types>`}const Cs="application/vnd.ms-excel.sheet.macroEnabled.main+xml";function Is(t,e){if(!e)return t;const s=`<workbookPr codeName="${L(e)}"/>`;if(/<workbookPr\b/.test(t))return t.replace(/<workbookPr\b([^>]*?)(\/?)>/,(c,n,l)=>`<workbookPr${n.replace(/\scodeName="[^"]*"/,"")} codeName="${L(e)}"${l}>`);const a=/<(?:workbookProtection|bookViews|sheets)\b/.exec(t);return a?t.slice(0,a.index)+s+t.slice(a.index):t}function Ns(t,e){const s=L(e);return/<sheetPr\b/.test(t)?t.replace(/<sheetPr\b([^>]*?)(\/?)>/,(a,c,n)=>`<sheetPr${c.replace(/\scodeName="[^"]*"/,"")} codeName="${s}"${n}>`):t.replace(/(<worksheet\b[^>]*>)/,`$1<sheetPr codeName="${s}"/>`)}function Es(t){const e=t.sheets.map((l,p)=>`<sheet name="${L(l.name)}" sheetId="${p+1}"${l.veryHidden?' state="veryHidden"':l.hidden?' state="hidden"':""} r:id="rId${p+1}"/>`).join(""),s=t.definedNames?.length?`<definedNames>${t.definedNames.map(l=>`<definedName name="${T(l.name)}"${l.comment?` comment="${L(l.comment)}"`:""}${l.localSheetId!==void 0?` localSheetId="${l.localSheetId}"`:""}${l.hidden?' hidden="1"':""}>${T(l.text)}</definedName>`).join("")}</definedNames>`:"",a=is(t),c=t.date1904?'<workbookPr date1904="1"/>':"",n=t.formulasEdited?'<calcPr fullCalcOnLoad="1"/>':"";return qe(Pe(ye(`${O}<workbook xmlns="${q}" xmlns:r="${A}">${c}${a}<sheets>${e}</sheets>${s}${n}</workbook>`,t.printNames??[]),t.filterNames,t.sheets),t)}function As(t,e){const s=t.map((c,n)=>`<Relationship Id="rId${n+1}" Type="${A}/${Ne(c)?"chartsheet":"worksheet"}" Target="${c.slice(3)}"/>`).join(""),a=t.length;return`${O}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${s}<Relationship Id="rId${a+1}" Type="${A}/styles" Target="styles.xml"/><Relationship Id="rId${a+2}" Type="${A}/sharedStrings" Target="sharedStrings.xml"/>${e?`<Relationship Id="rId${a+3}" Type="${A}/sheetMetadata" Target="metadata.xml"/>`:""}</Relationships>`}export{ct as MAX_COLS,pa as writeXlsx};
1
+ import{ZipWriter as et}from"./zip-writer.js";import{splitPaneXml as tt}from"../cells/view-xml.js";import{setSheetPicture as st}from"../cells/background-xml.js";import{calcPrAnchor as ie,setIterationAttributes as ne}from"../calcx/external-read.js";import{writeThemePart as le}from"../api/style-refs.js";import{buildStylesXml as at,patchStylesXml as rt}from"./xlsx-styles.js";import{pxToWidth as ot,pump as it}from"./xlsx-read.js";import{relativeTarget as E,relsPathOf as V,resolveTarget as B}from"./package-paths.js";import{BOOL as ee,ERR as Z,ERRORS as nt,FORMULA as lt,KIND_MASK as ce,NUM as me,STR as te}from"../core/sheet.js";import{colName as de,MAX_COLS as ct,parseRangeRef as he,rangeRef as se}from"../core/address.js";import{adjustRange as mt}from"../calc/adjust.js";import{patchSparklines as dt}from"../core/sparklines.js";import{ensureDrawingElement as ht,mergeContentTypes as X}from"../objects/drawing-xml.js";import{applyControls as pt}from"../shapes/form-xml.js";import{relationshipsXml as ft}from"../pivot/xml.js";import{applySlicerSheet as ut,patchSlicerContentTypes as pe,patchSlicerWorkbook as fe,patchSlicerWorkbookRels as ue,removedSlicerParts as wt,writeSlicerParts as xt}from"../slicers/write.js";import{patchCustomStyles as we}from"../slicers/custom-styles.js";import{patchTableXml as gt}from"../core/tables.js";import{addCellTypeEntries as ae,dropCellTypeParts as $t}from"../celltypes/persist.js";import{dropQueryParts as bt}from"../extras/getdata/persist.js";import{richSiXml as yt}from"../cells/rich-xml.js";import{isRichError as xe}from"../cells/rich-data-xml.js";import{patchDataSheetContentTypes as ge,patchDataSheetWorkbookRels as $e,skipOldDataSheetParts as Pt,writeDataSheetParts as kt}from"../datasheets/persist-writer.js";import{patchChartSheetPageSetup as be,patchWorkbookPrintNames as ye,patchWorksheetHead as Tt,patchWorksheetTail as St}from"../print/page-setup.js";import{patchFilterNames as Pe,patchSheetProps as Rt}from"../cells/filter-file.js";import{patchCf as vt}from"../cells/cf-file.js";import{dxfXml as ke,hyperlinksXml as Ct,protectionXml as It,replaceElement as O,scenariosXml as Nt,validationsXml as Et}from"./xlsx-tail.js";import{patchCustomViews as At}from"../core/custom-views.js";import{escapeMarkup as T,xmlAttr as L,xmlText as K}from"./xml-escape.js";import{dropExternalReferences as Ot,patchExternalLinkParts as Dt}from"../calcx/external-write.js";import{applyKeptSheet as _t,clearKeptShapeIds as Vt,declareKeptNamespaces as jt,keptTableRels as zt,keptTableXml as Mt,planKeptParts as Xt,writeKeptParts as Lt}from"./foreign-sheets.js";const F=new TextEncoder,Bt=new TextDecoder,D=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ `,q="http://schemas.openxmlformats.org/spreadsheetml/2006/main",A="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Ft="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",Ht="http://schemas.openxmlformats.org/markup-compatibility/2006",Wt="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac",Ut=6e7;class Kt{constructor(e){this.write=e,this.buf=new Uint8Array(1<<20),this.pos=0}async flush(){this.pos>0&&(await this.write(this.buf.subarray(0,this.pos)),this.pos=0)}async text(e){if(e.length*3+this.pos>this.buf.length&&(await this.flush(),e.length*3>this.buf.length)){await this.write(F.encode(e));return}this.pos+=F.encodeInto(e,this.buf.subarray(this.pos)).written}}const Te=[];function qt(t){let e=Te[t];return e===void 0&&(e=F.encode(de(t)),Te[t]=e),e}const _=t=>F.encode(t),Gt=_('<c r="'),Yt=_('" s="'),G=_('" t="'),Q=_('"><v>'),J=_("</v></c>"),Zt=_('"/>'),Se=_("</c>"),Re=_('">'),Qt=_('" cm="'),ve=_('" vm="');function S(t,e,s){for(let a=0;a<s.length;a++)t[e+a]=s[a];return e+s.length}function H(t,e,s){if(s<10)return t[e]=48+s,e+1;let a=0;for(let c=s;c>0;c=Math.floor(c/10))a++;for(let c=e+a-1,n=s;c>=e;c--){const l=Math.floor(n/10);t[c]=48+(n-l*10),n=l}return e+a}function Jt(t,e,s){if(Number.isInteger(s)&&Math.abs(s)<1e15)return s<0&&(t[e++]=45,s=-s),H(t,e,s);const a=String(s);for(let c=0;c<a.length;c++)t[e+c]=a.charCodeAt(c);return e+a.length}function Ce(t){if(t.raw!==void 0)return` ${t.raw}`;let e="";t.t&&(e+=` t="${t.t}"`),t.si!==void 0&&(e+=` si="${t.si}"`),t.ref&&(e+=` ref="${T(t.ref)}"`);for(const s of["dt2D","dtr","r1","r2","del1","del2"])t[s]!==void 0&&(e+=` ${s}="${T(t[s])}"`);return t.ca&&(e+=` ca="${t.ca}"`),e}const Ie=t=>xe(t)?"#VALUE!":nt[t];async function es(t,e,s){const{rows:a,cols:c,kinds:n,values:l,styles:p,count:f,formulas:w,valueMeta:b,rowMeta:d}=e,m=e.inlineText??null;let x=0,u=0,$=0;const g=d?d.length:0,R=async(h,r)=>{let i=`<row r="${h+1}"`;if($<g&&d[$]===h){const o=d[$+1];o>=0&&(i+=d[$+4]?` ht="${o}" customHeight="1"`:` ht="${o}"`),d[$+2]&&(i+=' hidden="1"'),d[$+3]&&(i+=` s="${d[$+3]}" customFormat="1"`),d[$+5]&&(i+=` ${d[$+5]}`),$+=6}await t.text(i+(r?">":"/>"))},j=async h=>{for(;$<g&&d[$]<h;)await R(d[$],!1)};let N=s.row;for(let h=0;h<f;h++){const r=a[h];r!==N&&(N>=0&&await t.text("</row>"),await j(r),await R(r,!0),N=r),t.pos+512>t.buf.length&&await t.flush();const i=t.buf;let o=S(i,t.pos,Gt);o=S(i,o,qt(c[h])),o=H(i,o,r+1);const k=p[h];k!==0&&(o=S(i,o,Yt),o=H(i,o,k)),b!==null&&u<b.length&&b[u][0]===h?(o=S(i,o,ve),o=H(i,o,b[u][1]),u++):(n[h]&ce)===Z&&s.errorVms&&xe(l[h])&&s.errorVms[l[h]]!==void 0&&(o=S(i,o,ve),o=H(i,o,s.errorVms[l[h]]));const C=n[h],y=C&ce,P=l[h];if(C&lt){const[z,M,Y]=w[x];if(z!==h)throw new Error("Formula list out of order");x++,M.cm&&(o=S(i,o,Qt),o=H(i,o,M.cm)),y===te?(o=S(i,o,G),i[o++]=115,i[o++]=116,i[o++]=114):y===ee?(o=S(i,o,G),i[o++]=98):y===Z&&(o=S(i,o,G),i[o++]=101),t.pos=S(i,o,Re);const v=M.f!==void 0?`<f${Ce(M)}>${T(M.f)}</f>`:`<f${Ce(M)}/>`;let I="";y===me?I=`<v>${P}</v>`:y===te?I=`<v>${K(Y??"")}</v>`:y===ee?I=`<v>${P}</v>`:y===Z&&(I=`<v>${Ie(P)}</v>`),await t.text(v+I),t.pos+8>t.buf.length&&await t.flush(),t.pos=S(t.buf,t.pos,Se);continue}switch(y){case me:o=S(i,o,Q),o=Jt(i,o,P),t.pos=S(i,o,J);break;case te:if(o=S(i,o,G),i[o++]=115,m!==null&&m.has(h)){i[o++]=116,i[o++]=114,t.pos=S(i,o,Re),await t.text(`<v>${K(m.get(h))}</v>`),t.pos+8>t.buf.length&&await t.flush(),t.pos=S(t.buf,t.pos,Se);continue}o=S(i,o,Q),o=H(i,o,P),t.pos=S(i,o,J);break;case ee:o=S(i,o,G),i[o++]=98,o=S(i,o,Q),o=H(i,o,P),t.pos=S(i,o,J);break;case Z:o=S(i,o,G),i[o++]=101,o=S(i,o,Q),o=S(i,o,_(Ie(P))),t.pos=S(i,o,J);break;default:t.pos=S(i,o,Zt)}}s.row=N,$<g&&(N>=0&&await t.text("</row>"),s.row=-1,await j(1/0))}const Ne=t=>t.startsWith("xl/chartsheets/"),Ee=t=>Ne(t)?ts:Ft,ts="application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml";async function ss(t,e,s,a,c,n,l,p,f){const w=await Ae("</worksheet>",e,s,a,n,p),b=a===c.activeSheet||e.tabSelected===!0;if(l){const d=await n.zip.text(s);let m=d;if(/\btabSelected="(?:1|true)"/.test(d)!==b&&(m=m.replace(/<sheetView\b[^>]*>/,x=>{const u=x.replace(/\s+tabSelected="[^"]*"/,"");return b?u.replace("<sheetView",'<sheetView tabSelected="1"'):u})),e.pageSetup&&(m=be(m,e.pageSetup)),m===d)return;await t.addBytes(s,new TextEncoder().encode(m))}else{let d=`${D}<chartsheet xmlns="${q}" xmlns:r="${A}"><sheetPr/><sheetViews><sheetView${b?' tabSelected="1"':""} workbookViewId="0" zoomToFit="1"/></sheetViews><pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>${w.replace("</worksheet>","</chartsheet>")}`;e.pageSetup&&(d=be(d,e.pageSetup)),await t.addBytes(s,new TextEncoder().encode(d))}f.add(s)}async function Ae(t,e,s,a,c,n){let l=t;e.cf!==null&&e.cf!==void 0&&(l=vt(l,e.cf,O)),e.validations!==null&&e.validations!==void 0&&(l=O(l,"dataValidations",Et(e.validations))),e.sparklines!==null&&e.sparklines!==void 0&&(l=dt(l,e.sparklines)),e.scenarios!==null&&e.scenarios!==void 0&&(l=O(l,"scenarios",Nt(e.scenarios))),e.dataConsolidate!==null&&e.dataConsolidate!==void 0&&(l=O(l,"dataConsolidate",e.dataConsolidate)),e.customSheetViews!==null&&e.customSheetViews!==void 0&&(l=O(l,"customSheetViews",e.customSheetViews)),e.protection!==null&&e.protection!==void 0&&(l=O(l,"sheetProtection",It(e.protection))),e.protectedRanges!==null&&e.protectedRanges!==void 0&&(l=O(l,"protectedRanges",e.protectedRanges)),e.ignoredErrors!==null&&e.ignoredErrors!==void 0&&(l=O(l,"ignoredErrors",e.ignoredErrors));const p=V(s);e.sheetPicture&&(l=st(l,e.sheetPicture),e.sheetPicture.path&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${e.sheetPicture.rid}"`)||(n.rels.has(p)||n.rels.set(p,[]),n.rels.get(p).push(`<Relationship Id="${e.sheetPicture.rid}" Type="${A}/image" Target="${T(E(s,e.sheetPicture.path))}"/>`)))),e.headerPicture&&(l=O(l,"legacyDrawingHF",e.headerPicture.rid?`<legacyDrawingHF r:id="${e.headerPicture.rid}"/>`:""),e.headerPicture.rid&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${e.headerPicture.rid}"`)||(n.rels.has(p)||n.rels.set(p,[]),n.rels.get(p).push(`<Relationship Id="${e.headerPicture.rid}" Type="${A}/vmlDrawing" Target="${T(E(s,e.headerPicture.vml))}"/>`))));for(const m of n.plan.removedTableRids?.[a]??[])l=l.replace(new RegExp(`<tablePart\\b[^>]*r:id="${m}"[^>]*/>`),"");if(n.plan.removedTableRids?.[a]){const m=(l.match(/<tablePart\b/g)??[]).length;l=m===0?l.replace(/<tableParts\b[^>]*\/>|<tableParts\b[^>]*>\s*<\/tableParts>/,""):l.replace(/(<tableParts\b[^>]*\bcount=")\d+/,`$1${m}`)}const f=(n.plan.tables??[]).filter(m=>m.isNew&&m.sheetIndex===a),w=(m,x,u,$)=>{n.rels.has(p)||n.rels.set(p,[]);const g=x==="threadedCommentExternal"?bs:`${A}/${x}`;n.rels.get(p).push(`<Relationship Id="${m}" Type="${g}" Target="${T(u)}"${$?' TargetMode="External"':""}/>`)};if(f.length>0){const m=[...l.matchAll(/<tablePart\b[^>]*\/>/g)].map($=>$[0]),x=f.map(($,g)=>{const R=`rIdTable${a}_${g}`;return w(R,"table",E(s,$.part),!1),`<tablePart r:id="${R}"/>`}),u=[...m,...x];l=O(l,"tableParts",`<tableParts count="${u.length}">${u.join("")}</tableParts>`)}if(e.hyperlinks!==null&&e.hyperlinks!==void 0){const m=e.hyperlinks.map((x,u)=>{if(x.rid||!x.target)return x;const $=`rIdLink${a}_${u}`;return w($,"hyperlink",x.target,!0),{...x,rid:$}});l=O(l,"hyperlinks",Ct(m))}if(e.threads){const m=n.plan.threadParts?.[a];m&&(n.parts.push({path:m.path,xml:ks(e.threads)}),m.existing||w(`rIdThreads${a+1}`,"threadedCommentExternal",E(s,m.path),!1))}const b=n.plan.noteParts?.[a];if(b&&e.comments){if(b.existing)n.parts.push({path:b.comments,xml:Oe(e.comments)}),b.vml&&n.parts.push({path:b.vml,xml:_e(b.vmlSource,e.comments)}),b.threaded&&n.parts.push({path:b.threaded,xml:Le(b.threadedSource,e.structureOps??[])});else if(e.comments.length>0){const{comments:m,vml:x,n:u}=b;n.parts.push({path:m,xml:Oe(e.comments)}),w(`rIdComments${u}`,"comments",E(s,m),!1);const $=/<legacyDrawing\b[^>]*r:id="([^"]+)"/.exec(l)?.[1],g=$&&c?.zip.has(p)?await c.zip.text(p):"",R=g?[...g.matchAll(/<Relationship\b[^>]*\/>/g)].map(h=>h[0]).find(h=>h.includes(`Id="${$}"`)):null,j=R?/Target="([^"]+)"/.exec(R)?.[1]:null,N=j?B(s,j):null;N&&c.zip.has(N)?n.parts.push({path:N,xml:_e(await c.zip.text(N),e.comments)}):(n.parts.push({path:x,xml:as(e.comments)}),w(`rIdVml${u}`,"vmlDrawing",E(s,x),!1),l=O(l,"legacyDrawing",`<legacyDrawing r:id="rIdVml${u}"/>`))}}const d=e.objects;if(d){n.parts.push({path:d.path,xml:d.xml}),d.relsXml&&n.parts.push({path:d.relsPath,xml:d.relsXml});for(const m of d.parts)n.parts.push({path:m.path,xml:m.data instanceof Blob?new Uint8Array(await m.data.arrayBuffer()):m.data});d.isNew&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${d.sheetRel.id}"`)||w(d.sheetRel.id,"drawing",d.sheetRel.target,!1),l=ht(l,d.sheetDrawingXml)),d.controls&&(n.rels.has(p)||n.rels.set(p,[]),l=await pt(l,d.controls,{source:c,part:s,relsName:p,addRel:w,extraParts:n.parts,pendingRels:n.rels.get(p),relativeTo:E,resolveTarget:B}))}return ut({tail:l,index:a,info:e,source:c,extra:n,relsName:p})}function Oe(t){const e=[...new Set(t.map(s=>s.author??""))];return`${D}<comments xmlns="${q}"><authors>${e.map(s=>`<author>${K(s)}</author>`).join("")}</authors><commentList>${t.map(s=>`<comment ref="${s.ref}" authorId="${e.indexOf(s.author??"")}"><text>${ps(s,K)}</text></comment>`).join("")}</commentList></comments>`}function De(t,e=1025){return t.map((s,a)=>hs(s,e+a,a+1,he(s.ref))).join("")}function _e(t,e){const s=t.replace(/<v:shape\b(?:(?!<\/v:shape>)[\s\S])*?ObjectType="Note"[\s\S]*?<\/v:shape>/g,"");let a=1024;for(const c of s.matchAll(/_x0000_s(\d+)/g))a=Math.max(a,Number(c[1]));return s.replace("</xml>",`${De(e,a+1)}</xml>`)}function as(t){return`<xml xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1"/></o:shapelayout><v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter"/><v:path gradientshapeok="t" o:connecttype="rect"/></v:shapetype>${De(t)}</xml>`}function Ve(t){return!t||t.length===0?"":`<cols>${t.map(s=>{let a=`<col min="${s.min+1}" max="${s.max+1}" width="${ot(s.px)}"`;return s.custom&&(a+=' customWidth="1"'),s.hidden&&(a+=' hidden="1"'),s.style&&(a+=` style="${s.style}"`),s.extra&&(a+=` ${s.extra}`),a+"/>"}).join("")}</cols>`}function je(t,e){const s=cs(t,e);let a="";if(t.frozenRows||t.frozenCols){const c=t.frozenRows&&t.frozenCols?"bottomRight":t.frozenRows?"bottomLeft":"topRight",n=(t.frozenCols?` xSplit="${t.frozenCols}"`:"")+(t.frozenRows?` ySplit="${t.frozenRows}"`:""),l=de(t.frozenCols)+(t.frozenRows+1);a=`<pane${n} topLeftCell="${l}" activePane="${c}" state="frozen"/>`}else t.split&&(a=tt(t));return`<sheetViews><sheetView${s} workbookViewId="0">${a}</sheetView></sheetViews>`}function ze(t){return t.maxRow<0||t.maxCol<0?"A1":se({r0:0,c0:0,r1:t.maxRow,c1:t.maxCol})}function rs(t,e){const s=t.tabColor?`<sheetPr><tabColor rgb="FF${t.tabColor.slice(1)}"/></sheetPr>`:"";return`${D}<worksheet xmlns="${q}" xmlns:r="${A}" xmlns:mc="${Ht}" mc:Ignorable="x14ac" xmlns:x14ac="${Wt}">${s}<dimension ref="${ze(t)}"/>${je(t,e)}<sheetFormatPr baseColWidth="10" defaultRowHeight="${t.defaultHeight}"/>${Ve(t.cols)}`}function os(t,e){let s=t;if(e.tabColor!==null&&e.tabColor!==void 0&&(s=s.replace(/<tabColor\b[^>]*\/>/,""),e.tabColor)){const c=`<tabColor rgb="FF${e.tabColor.slice(1)}"/>`;/<sheetPr\b[^>]*\/>/.test(s)?s=s.replace(/<sheetPr\b([^>]*)\/>/,`<sheetPr$1>${c}</sheetPr>`):/<sheetPr\b[^>]*>/.test(s)?s=s.replace(/(<sheetPr\b[^>]*>)/,`$1${c}`):s=s.replace(/(<worksheet\b[^>]*>)/,`$1<sheetPr>${c}</sheetPr>`)}const a=`<dimension ref="${ze(e)}"/>`;if(/<dimension\b[^>]*\/>/.test(s)&&(s=s.replace(/<dimension\b[^>]*\/>/,a)),e.viewChanged?/<sheetViews\b[\s\S]*<\/sheetViews>/.test(s)&&(s=s.replace(/<sheetViews\b[\s\S]*<\/sheetViews>/,je(e,e.tabSelected))):s=ls(s,e),e.defaultsChanged&&(s=s.replace(/(<sheetFormatPr\b[^>]*?\bdefaultRowHeight=")[^"]*"/,`$1${e.defaultHeight}"`)),e.colsChanged){const c=Ve(e.cols);/<cols\b[\s\S]*<\/cols>/.test(s)?s=s.replace(/<cols\b[\s\S]*<\/cols>/,c):s+=c}return s}import{bookViewsXml as is,patchBookViews as ns,patchTabSelected as ls,sheetViewAttrs as cs}from"../cells/view-xml.js";import{docPropsRels as ms,docPropsTypes as Me,writeDocProps as ds}from"../cells/docprops-xml.js";import{noteShapeXml as hs,noteTextXml as ps}from"../cells/note-xml.js";const fs=/<(phoneticPr|conditionalFormatting|dataValidations|hyperlinks|printOptions|pageMargins|pageSetup|headerFooter|rowBreaks|colBreaks|customProperties|cellWatches|ignoredErrors|smartTags|drawing|legacyDrawing|legacyDrawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst)\b|<\/worksheet>/;function Xe(t){return t.length===0?"":`<mergeCells count="${t.length}">${t.map(e=>`<mergeCell ref="${se(e)}"/>`).join("")}</mergeCells>`}function Le(t,e){return e.length===0?t:t.replace(/\b(sqref|ref)="([^"]*)"/g,(s,a,c)=>{const n=c.split(/\s+/).map(p=>{let f=he(p);if(f===null)return null;for(const w of e){if(f===null)break;f=mt(f,w)}return f===null?"":se(f)});if(n.includes(null))return s;const l=n.filter(p=>p!=="");return l.length?`${a}="${l.join(" ")}"`:`${a}="A1048576"`})}function us(t,e,s=[]){t=Le(t,s);const a=Xe(e),c=/<mergeCells\b[\s\S]*?<\/mergeCells>/;if(c.test(t))return t.replace(c,a);if(!a)return t;const n=fs.exec(t);return n?t.slice(0,n.index)+a+t.slice(n.index):t+a}const ws=new TextDecoder("latin1");async function xs(t,e,s,a){let n=new Uint8Array(0),l=!0;await it(await e.stream(s),async b=>{let d=b;if(l){l=!1;const m=Bt.decode(d.subarray(0,Math.min(d.length,512))),x=/<sst\b[^>]*>/.exec(m);if(x){const u=x[0].replace(/\s(count|uniqueCount)="\d+"/g,""),$=F.encode(m.slice(0,x.index)+u),g=F.encode(m.slice(0,x.index+x[0].length)).length;await t($),d=d.subarray(g)}}if(d.length>=16)n.length&&await t(n),await t(d.subarray(0,d.length-16)),n=d.slice(d.length-16);else{const m=new Uint8Array(n.length+d.length);m.set(n),m.set(d,n.length),n=m}});const p=ws.decode(n),f=F.encode(a),w=p.lastIndexOf("</sst>");w>=0?(await t(n.subarray(0,w)),await t(f),await t(n.subarray(w))):p.endsWith("/>")?(await t(n.subarray(0,n.length-2)),await t(F.encode(`>${a}</sst>`))):(await t(n),await t(f))}const W="xl/metadata.xml",Be="application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",Fe=`${D}<metadata xmlns="${q}" xmlns:xda="http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray"><metadataTypes count="1"><metadataType name="XLDAPR" minSupportedVersion="120000" copy="1" pasteAll="1" pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1" clearComments="1" assign="1" coerce="1" cellMeta="1"/></metadataTypes><futureMetadata name="XLDAPR" count="1"><bk><extLst><ext uri="{bdbb8cdc-fa1e-496e-a857-3c3f30c029c3}"><xda:dynamicArrayProperties fDynamic="1" fCollapsed="0"/></ext></extLst></bk></futureMetadata><cellMetadata count="1"><bk><rc t="1" v="0"/></bk></cellMetadata></metadata>`,gs=(t,e)=>e?yt(t,e,K):`<si><t xml:space="preserve">${K(t)}</t></si>`;async function pa(t,e,s,a=null,c=null){const n=new et(t),l=[],p=new Set;a&&e.dataSheets&&Pt(a.zip,p,e.dataSheets);for(const r of e.sheets)if(r.objects)for(const i of r.objects.removedParts)p.add(i);const f=e.pivots??null,w=new Set([...e.sheets.flatMap(r=>(r.objects?.removedParts??[]).filter(i=>i.startsWith("xl/ctrlProps/"))),...f?.replaced??[],...wt(e),...(e.removedTables??[]).map(r=>r.part)]);for(const r of w)p.add(r),p.add(V(r));e.sheetRefs=e.sheets.map((r,i)=>({rid:`rId${i+1}`,sheetId:i+1})),e.written=[];const b=new Set(a?a.sheets.map(r=>r.part):[]),d=new Set(e.sheets.filter(r=>r.sourceIndex>=0).map(r=>a.sheets[r.sourceIndex].part)),m=new Set(a?a.sheets.map(r=>r.part).filter(r=>!d.has(r)):[]);let x=1;const u=e.sheets.map(r=>{if(r.sourceIndex>=0)return a.sheets[r.sourceIndex].part;let i;do i=`xl/${r.chartSheet?"chartsheets":"worksheets"}/sheet${x++}.xml`;while(b.has(i));return b.add(i),l.push(i),i}),$=a?.stringsPart??"xl/sharedStrings.xml",g=a?.stylesPart??"xl/styles.xml";e.noteParts=await $s(e,u,a),{threads:e.threadParts,personPart:e.personPart}=await Ss(e,u,a);let R=null;if(a)await Rs(n,a,e,u,l,$,g,p);else{let r=vs(u,e.dynamicArrays,e);for(const P of e.sheets)P.objects&&(r=X(r,P.objects.contentTypes,P.objects.removedOverrides));f&&(r=X(r,f.contentTypes,[])),r=pe(r,e),r=X(r,We(e),[]),{types:r}=ae(r,"</Relationships>",e.cellTypes),r=Me(r,e.docProps),e.dataSheets&&(r=ge(r,e.dataSheets));let i=null;e.themeXml&&({types:r,rels:i}=await le(n,{types:r,rels:"</Relationships>"},e.themeXml));const o=c?.plan??null;o&&(r=X(r,[...o.overrides,...o.defaults],[])),R=Xt(o,e),R&&(r=X(r,R.types,[])),r=Ye(r,e.workbookType),o?.macro&&(r=r.replace(/application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)\.main\+xml/,Cs)),await n.addBytes("[Content_Types].xml",r);const k=(o?.rootRels??[]).map((P,z)=>`<Relationship Id="rIdForeign${z+1}" Type="${T(P.type)}" Target="${T(P.target)}"/>`).join("");await n.addBytes("_rels/.rels",`${D}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${A}/officeDocument" Target="xl/workbook.xml"/>${ms(e.docProps)}${k}</Relationships>`);let C=Ge(ne(Ke(Ze(Is(Es(e),o?.codeNames.workbook),e.workbookProtection),e.calcMode),e.calcSettings),e.fileSharing),y=ae("</Types>",As(u,e.dynamicArrays),e.cellTypes).rels;i&&(y=y.replace("</Relationships>",i)),e.personPart&&(y=y.replace("</Relationships>",`<Relationship Id="rIdPersons" Type="${He}" Target="${E("xl/workbook.xml",e.personPart.path)}"/></Relationships>`)),f&&(y=y.replace("</Relationships>",`${Qe(f)}</Relationships>`),C=Je(C,f)),y=ue(y,e),await n.addBytes("xl/workbook.xml",fe(C,e)),e.dataSheets&&(y=$e(y,e.dataSheets)),o?.workbookRels.length&&(y=y.replace("</Relationships>",`${o.workbookRels.map((P,z)=>`<Relationship Id="rIdForeign${z+1}" Type="${T(P.type)}" Target="${T(E("xl/workbook.xml",P.target))}"/>`).join("")}</Relationships>`)),await n.addBytes("xl/_rels/workbook.xml.rels",y),e.dynamicArrays&&await n.addBytes(W,Fe),await n.addBytes(g,we(at(e.styles,(e.newDxfs??[]).map(ke),e),e.customStyles))}const j=e.extraRich?new Map(e.extraRich):null,N=e.extraStrings.map((r,i)=>gs(r,j?.get(i))).join("");a?.stringsPart&&a.zip.has(a.stringsPart)?await n.add($,r=>xs(r,a.zip,a.stringsPart,N)):await n.addBytes($,`${D}<sst xmlns="${q}">${N}</sst>`),p.add($);const h={rels:new Map,parts:[],next:1,plan:e};if(e.removedTableRids={},a&&(e.removedTables??[]).length>0)for(const r of e.removedTables){const i=V(u[r.sheetIndex]);if(!a.zip.has(i))continue;const o=await a.zip.text(i);for(const k of o.matchAll(/<Relationship\b[^>]*\/>/g)){const C=/\bTarget="([^"]+)"/.exec(k[0])?.[1],y=/\bId="([^"]+)"/.exec(k[0])?.[1];C&&y&&B(u[r.sheetIndex],C)===r.part&&(e.removedTableRids[r.sheetIndex]??=[]).push(y)}h.rels.has(i)||h.rels.set(i,[])}for(let r=0;r<e.sheets.length;r++){const i=e.sheets[r],o=i.sourceIndex>=0?a.sheets[i.sourceIndex]:null;if(i.chartSheet){await ss(n,i,u[r],r,e,a,o,h,p),e.written[r]={head:"",tail:""},e.onSheetDone?.(r);continue}p.add(u[r]);const k=i.cellEstimate>Ut;await n.add(u[r],async C=>{const y=new Kt(C);let P=o?.head?os(o.head,i):rs(i,r===e.activeSheet||i.tabSelected===!0);P=Rt(P,i.sheetProps),!o&&c?.plan.codeNames.sheets[i.name]&&(P=Ns(P,c.plan.codeNames.sheets[i.name])),i.pageSetup&&(P=Tt(P,i.pageSetup));const z=o?null:R?.sheets.get(r);z&&(P=jt(P,z),Vt(i.objects,z)),e.written[r]={head:P},await y.text(P),await y.text("<sheetData>");const M={row:-1,errorVms:e.errorVms??null};for(let I=0;I>=0;){const U=await s.block(r,I);await es(y,U,M),I=U.nextRow,s.recycle?.(U)}M.row>=0&&await y.text("</row>"),await y.text("</sheetData>");const Y=i.autoFilter??"";let v=o?us(o.tail??"</worksheet>",i.merges,i.structureOps??[]):`${Y}${Xe(i.merges)}</worksheet>`;if(!o&&!/xmlns:r=/.test(v)&&(v=`${v}`),o&&i.autoFilter!==null&&i.autoFilter!==void 0){v=v.replace(/<autoFilter\b[^>]*?(?:\/>|>[\s\S]*?<\/autoFilter>)/,"").replace(/<sortState\b[^>]*?(?:\/>|>[\s\S]*?<\/sortState>)/,"");const I=/<mergeCells\b|<(?:sortState|dataConsolidate|customSheetViews|phoneticPr|conditionalFormatting|dataValidations|hyperlinks|printOptions|pageMargins|pageSetup|headerFooter|rowBreaks|colBreaks|customProperties|cellWatches|ignoredErrors|smartTags|drawing|legacyDrawing|legacyDrawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst)\b|<\/worksheet>/.exec(v);v=I?v.slice(0,I.index)+Y+v.slice(I.index):v+Y}if(v=await Ae(v,i,u[r],r,a,h),i.pageSetup&&(v=St(v,i.pageSetup)),!o){v=v.replace(/(<pageSetup\b[^>]*?)\sr:id="[^"]*"/,"$1");const I=R?.sheets.get(r);if(I){const U=V(u[r]);h.rels.has(U)||h.rels.set(U,[]),v=await _t(v,{group:I,part:u[r],pending:h.rels.get(U),extraParts:h.parts,foreignZip:c.zip,names:R.names,kept:R.kept,written:e.sheets[r].protectedRanges===null?[]:["protectedRanges"]})}}e.written[r].tail=v,await y.text(v),await y.flush()},{large:k}),e.onSheetDone?.(r)}if(f){for(const o of f.parts)await n.addBytes(o.name,o.xml),p.add(o.name);const r=new Map;let i=0;for(const o of f.relationships)if(o.from!==null)r.has(o.from)||r.set(o.from,[]),r.get(o.from).push(o);else if(o.sheetIndex>=0){const k=V(u[o.sheetIndex]);h.rels.has(k)||h.rels.set(k,[]),h.rels.get(k).push(`<Relationship Id="rIdPivot${++i}" Type="${o.type}" Target="${T(o.target)}"/>`)}for(const[o,k]of r){const C=V(o);await n.addBytes(C,ft(k)),p.add(C)}for(const o of u){const k=V(o);a?.zip.has(k)&&!h.rels.has(k)&&h.rels.set(k,[])}}if(e.slicers?.removedParts.length)for(const r of u){const i=V(r);a?.zip.has(i)&&!h.rels.has(i)&&h.rels.set(i,[])}await xt(n,e,p);for(const r of e.tables??[]){let i=r.xml;i===null&&(i=gt(await a.zip.text(r.part),r.patch));const o=R?.tables.get(r.part);if(o){i=Mt(i,o);const k=zt(r.part,o,R.names);await n.addBytes(k.path,k.xml),p.add(k.path)}await n.addBytes(r.part,i),p.add(r.part)}for(const r of e.cellTypes??[])await n.addBytes(r.path,r.xml),p.add(r.path);e.personPart&&(await n.addBytes(e.personPart.path,Ts(e.persons)),p.add(e.personPart.path));for(const r of h.parts)await n.addBytes(r.path,r.xml),p.add(r.path);for(const[r,i]of h.rels){let o=a?.zip.has(r)?await a.zip.text(r):`${D}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>`;if(w.size>0){const C=r.replace("_rels/","").replace(/\.rels$/,"");o=oe(o,C,w)}const k=o.replace("</Relationships>",`${i.join("")}</Relationships>`);await n.addBytes(r,k),p.add(r)}if(await ds(n,a?.zip??null,e.docProps,p),await kt(n,e.dataSheets,p),a){const r=new Set([...p,a.calcChainPart,...m].map(i=>a.zip.entry(i)?.name).filter(Boolean));for(const[i,o]of a.zip.entries)r.has(i)||await n.copyRaw(a.zip,o)}if(!a&&c){const r=new Set(n.central.map(i=>i.name));for(const i of c.plan.entries){const o=c.zip.entries.get(i);o&&!r.has(i)&&await n.copyRaw(c.zip,o)}R&&await Lt(n,R,c.zip,r)}await n.finish(),e.result={sheets:e.sheets.map((r,i)=>({name:r.name,part:u[i],rid:e.sheetRefs[i].rid,sheetId:e.sheetRefs[i].sheetId,hidden:r.hidden,veryHidden:r.veryHidden,head:e.written[i].head,tail:e.written[i].tail})),workbookPart:a?.workbookPart??"xl/workbook.xml",wbRelsPath:a?.wbRelsPath??"xl/_rels/workbook.xml.rels",stringsPart:$,stylesPart:g}}async function $s(t,e,s){const a={};let c=1;for(let n=0;n<t.sheets.length;n++){const l=t.sheets[n];if(!l.comments)continue;const p=V(e[n]);if(s?.zip.has(p)&&l.sourceIndex>=0){const f=await s.zip.text(p),w=d=>{const m=[...f.matchAll(/<Relationship\b[^>]*\/>/g)].map(u=>u[0]).find(u=>new RegExp(`\\bType="[^"]*/${d}"`).test(u)),x=m&&/\bTarget="([^"]+)"/.exec(m)?.[1];return x?B(e[n],x):null},b=w("comments");if(b){const d=w("vmlDrawing"),m=w("threadedComment");a[n]={existing:!0,comments:b,vml:d,vmlSource:d?await s.zip.text(d):null,threaded:m,threadedSource:m?await s.zip.text(m):null};continue}}if(l.comments.length!==0){for(;s?.zip.has(`xl/comments${100+c}.xml`)||s?.zip.has(`xl/drawings/vmlDrawing${100+c}.vml`);)c++;a[n]={existing:!1,comments:`xl/comments${100+c}.xml`,vml:`xl/drawings/vmlDrawing${100+c}.vml`,n:c},c++}}return a}const bs="http://schemas.microsoft.com/office/2017/10/relationships/threadedComment",He="http://schemas.microsoft.com/office/2017/10/relationships/person",ys="application/vnd.ms-excel.threadedcomments+xml",Ps="application/vnd.ms-excel.person+xml";function ks(t){const e=t.map(s=>`<threadedComment ref="${s.ref}" dT="${T(s.date)}" personId="${T(s.personId)}" id="${T(s.id)}"${s.parentId?` parentId="${T(s.parentId)}"`:""}${s.done?' done="1"':""}><text>${K(s.text)}</text>${s.mentions?.length?`<mentions>${s.mentions.map(a=>`<mention mentionpersonId="${T(a.personId)}" mentionId="${T(a.id??s.id.replace(/^.{9}/,`{${String(a.start).padStart(8,"0")}`))}" startIndex="${a.start}" length="${a.length}"/>`).join("")}</mentions>`:""}</threadedComment>`).join("");return`${D}<ThreadedComments xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">${e}</ThreadedComments>`}function Ts(t){const e=t.map(s=>`<person displayName="${L(s.displayName)}" id="${T(s.id)}" userId="${T(s.userId)}" providerId="${T(s.providerId)}"/>`).join("");return`${D}<personList xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">${e}</personList>`}async function Ss(t,e,s){const a={};let c=1;for(let l=0;l<t.sheets.length;l++){const p=t.sheets[l];if(!p.threads)continue;const f=V(e[l]);let w=null;if(s?.zip.has(f)&&p.sourceIndex>=0){const d=[...(await s.zip.text(f)).matchAll(/<Relationship\b[^>]*\/>/g)].map(x=>x[0]).find(x=>/\/threadedComment"/.test(x)),m=d&&/\bTarget="([^"]+)"/.exec(d)?.[1];m&&(w=B(e[l],m))}if(w){a[l]={path:w,existing:!0};continue}if(p.threads.length!==0){for(;s?.zip.has(`xl/threadedComments/threadedComment${100+c}.xml`);)c++;a[l]={path:`xl/threadedComments/threadedComment${100+c}.xml`,existing:!1},c++}}let n=null;if(t.persons){let l=null;if(s?.zip.has(s.wbRelsPath)){const f=[...(await s.zip.text(s.wbRelsPath)).matchAll(/<Relationship\b[^>]*\/>/g)].map(b=>b[0]).find(b=>/\/person"/.test(b)),w=f&&/\bTarget="([^"]+)"/.exec(f)?.[1];w&&(l=B(s.workbookPart,w))}n=l?{path:l,existing:!0}:{path:"xl/persons/person.xml",existing:!1}}return{threads:a,personPart:n}}const We=t=>[...Object.values(t.threadParts??{}).filter(e=>!e.existing).map(e=>({partName:`/${e.path}`,contentType:ys})),...t.personPart&&!t.personPart.existing?[{partName:`/${t.personPart.path}`,contentType:Ps}]:[]],Ue="application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",re=t=>Object.values(t.noteParts??{}).filter(e=>!e.existing);function Ke(t,e){if(e==null)return t;const s=e==="auto"?"":` calcMode="${e}"`;if(/<calcPr\b/.test(t))return t.replace(/<calcPr\b([^>]*?)\/>/,(c,n)=>`<calcPr${n.replace(/\s*calcMode="[^"]*"/,"")}${s}/>`);if(!s)return t;const a=ie(t);return t.replace(a,`${a}<calcPr${s}/>`)}const qe=(t,e)=>e.customViews?At(t,e.customViews.workbookXml,e.customViews.names):t;function Ge(t,e){if(e==null)return t;const s=t.replace(/<fileSharing\b[^>]*\/>/,""),a=Object.keys(e).filter(f=>e[f]!==void 0&&e[f]!==null&&e[f]!=="");if(a.length===0)return s;const c=`<fileSharing ${a.map(f=>`${f}="${T(e[f])}"`).join(" ")}/>`,n=/<fileVersion\b[^>]*\/>/.exec(s),l=/<workbook\b[^>]*>/.exec(s),p=n?n.index+n[0].length:l.index+l[0].length;return s.slice(0,p)+c+s.slice(p)}function Ye(t,e){if(!e)return t;const s=e==="template"?"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":e==="macroTemplate"?"application/vnd.ms-excel.template.macroEnabled.main+xml":e==="macro"?"application/vnd.ms-excel.sheet.macroEnabled.main+xml":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",a=e==="workbook"?/application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)\.main\+xml/:/application\/vnd\.(?:openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)|ms-excel\.(?:sheet|template)\.macroEnabled)\.main\+xml/;return t.replace(a,s)}function Ze(t,e){if(e==null)return t;const s=t.replace(/<workbookProtection\b[^>]*\/>/,""),a=Object.keys(e);if(a.length===0)return s;const c=`<workbookProtection ${a.map(l=>`${l}="${T(e[l])}"`).join(" ")}/>`,n=/<bookViews\b|<sheets\b/.exec(s);return s.slice(0,n.index)+c+s.slice(n.index)}const Qe=t=>t.caches.map(e=>`<Relationship Id="${e.relId}" Type="${e.type}" Target="${T(e.target)}"/>`).join("");function oe(t,e,s){return t.replace(/<Relationship\b[^>]*\/>/g,a=>{const c=/\bTarget="([^"]+)"/.exec(a);return c&&s.has(B(e,c[1]))?"":a})}function Je(t,e,s=null){let a="";const c=/<pivotCaches\b[^>]*>([\s\S]*?)<\/pivotCaches>/.exec(t);c&&s&&(a=[...c[1].matchAll(/<pivotCache\b[^>]*\/>/g)].map(w=>w[0]).filter(w=>s.has(/r:id="([^"]+)"/.exec(w)?.[1])).join(""));const n=e.caches.map(w=>`<pivotCache cacheId="${w.cacheId}" r:id="${w.relId}"/>`).join(""),l=t.replace(/<pivotCaches\b[^>]*>[\s\S]*?<\/pivotCaches>/,""),p=a||n?`<pivotCaches>${a}${n}</pivotCaches>`:"";if(!p)return l;const f=/<(?:smartTagPr|smartTagTypes|webPublishing|fileRecoveryPr|webPublishObjects|extLst)\b|<\/workbook>/.exec(l);return f?l.slice(0,f.index)+p+l.slice(f.index):l+p}async function Rs(t,e,s,a,c,n,l,p){const f=e.zip,w=await f.text(e.wbRelsPath);let b=null,d=w.replace(/<Relationship\b[^>]*calcChain[^>]*\/>/g,h=>{const r=/Target="([^"]+)"/.exec(h);return r&&(b=B(e.workbookPart,r[1])),""});e.calcChainPart=b;let m=await f.text("[Content_Types].xml");m=m.replace(/<Override\b[^>]*calcChain[^>]*\/>/g,"");const x=c.map(h=>`<Override PartName="/${h}" ContentType="${Ee(h)}"/>`);if(f.has(n)||(x.push(`<Override PartName="/${n}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>`),d=d.replace("</Relationships>",`<Relationship Id="rIdStrings" Type="${A}/sharedStrings" Target="${E(e.workbookPart,n)}"/></Relationships>`)),re(s).length>0){/Extension="vml"/.test(m)||(m=m.replace(/(<Types\b[^>]*>)/,'$1<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>'));for(const h of re(s))x.push(`<Override PartName="/${h.comments}" ContentType="${Ue}"/>`)}s.dynamicArrays&&!f.has(W)&&(x.push(`<Override PartName="/${W}" ContentType="${Be}"/>`),d=d.replace("</Relationships>",`<Relationship Id="rIdMetadata" Type="${A}/sheetMetadata" Target="${E(e.workbookPart,W)}"/></Relationships>`),await t.addBytes(W,Fe),p.add(W)),s.dynamicArrays&&f.has(W);for(const h of s.tables??[])h.isNew&&x.push(`<Override PartName="/${h.part}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/>`);m=m.replace("</Types>",`${x.join("")}</Types>`);for(const h of s.sheets)h.objects&&(m=X(m,h.objects.contentTypes,h.objects.removedOverrides));m=X(m,We(s),[]),s.personPart&&!s.personPart.existing&&(d=d.replace("</Relationships>",`<Relationship Id="rIdPersons" Type="${He}" Target="${E(e.workbookPart,s.personPart.path)}"/></Relationships>`)),s.dataSheets&&(m=ge(m,s.dataSheets),d=$e(d,s.dataSheets)),{types:m,rels:d}=await $t(f,m,d,p),{types:m,rels:d}=await bt(f,m,d,p),{types:m,rels:d}=ae(m,d,s.cellTypes,e.workbookPart),m=Me(m,s.docProps);const u=s.pivots??null;m=X(m,[],[...u?.replaced??[],...(s.removedTables??[]).map(h=>h.part)].map(h=>`/${h}`)),m=pe(m,s),s.slicers&&(d=ue(oe(d,e.workbookPart,new Set(s.slicers.removedParts)),s)),u&&(m=X(m,u.contentTypes,[]),d=oe(d,e.workbookPart,new Set(u.replaced)),d=d.replace("</Relationships>",`${Qe(u)}</Relationships>`));let $=[];s.externalLinks?.length&&({types:m,rels:d,removedIds:$}=await Dt(t,m,d,p,s.externalLinks,e.workbookPart,E));let g=Ot(await f.text(e.workbookPart),$),R=0;for(const h of e.sheets)R=Math.max(R,Number(h.sheetId));const j=s.sheets.map((h,r)=>{if(h.sourceIndex>=0){const o=e.sheets[h.sourceIndex];s.sheetRefs[r]={rid:o.rid,sheetId:o.sheetId};const k=h.veryHidden?' state="veryHidden"':h.hidden?' state="hidden"':"";return`<sheet name="${L(h.name)}" sheetId="${o.sheetId}"${k} r:id="${o.rid}"/>`}const i=`rIdNew${r}`;return d=d.replace("</Relationships>",`<Relationship Id="${i}" Type="${A}/${h.chartSheet?"chartsheet":"worksheet"}" Target="${E(e.workbookPart,a[r])}"/></Relationships>`),s.sheetRefs[r]={rid:i,sheetId:R+1},`<sheet name="${L(h.name)}" sheetId="${++R}" r:id="${i}"/>`});g=g.replace(/<sheets\b[\s\S]*?<\/sheets>/,`<sheets>${j.join("")}</sheets>`);const N=h=>qe(Pe(ye(h,s.printNames??[]),s.filterNames,s.sheets),s);if(s.definedNames){const h=[...g.matchAll(/<definedName\b[^>]*name="_xlnm\.[^>]*>[\s\S]*?<\/definedName>/g)].map(o=>o[0]),r=s.definedNames.map(o=>`<definedName name="${T(o.name)}"${o.comment?` comment="${L(o.comment)}"`:""}${o.localSheetId!==void 0?` localSheetId="${o.localSheetId}"`:""}${o.hidden?' hidden="1"':""}>${T(o.text)}</definedName>`),i=h.length+r.length?`<definedNames>${[...h,...r].join("")}</definedNames>`:"";/<definedNames\b/.test(g)?g=g.replace(/<definedNames\b[\s\S]*?<\/definedNames>/,i):g=g.replace("</sheets>",`</sheets>${i}`)}if(s.formulasEdited){if(/<calcPr\b/.test(g))g=g.replace(/<calcPr\b([^>]*?)\/>/,(h,r)=>/fullCalcOnLoad/.test(r)?h:`<calcPr${r} fullCalcOnLoad="1"/>`);else if(/<\/sheets>/.test(g)){const h=ie(g);g=g.replace(h,`${h}<calcPr fullCalcOnLoad="1"/>`)}}if(s.themeXml&&({types:m,rels:d}=await le(t,{types:m,rels:d,handled:p},s.themeXml)),await t.addBytes("[Content_Types].xml",Ye(m,s.workbookType)),p.add("[Content_Types].xml"),u){const h=new Set([...d.matchAll(/\bId="([^"]+)"/g)].map(r=>r[1]));g=Je(g,u,h)}g=Ge(ne(Ke(Ze(g,s.workbookProtection),s.calcMode),s.calcSettings),s.fileSharing),g=ns(g,s.bookView),await t.addBytes(e.workbookPart,fe(N(g),s)),p.add(e.workbookPart),await t.addBytes(e.wbRelsPath,d),p.add(e.wbRelsPath),l&&f.has(l)&&(s.styles.length>0||(s.newDxfs??[]).length>0||(s.pivotNumFmts??[]).length>0||s.customStyles||s.namedStyles?.some(h=>!h.keep)?await t.addBytes(l,we(rt(await f.text(l),s.styles,(s.newDxfs??[]).map(ke),s),s.customStyles)):await t.copyRaw(f,f.entry(l)),p.add(l))}function vs(t,e,s){const a=(s.tables??[]).map(l=>`<Override PartName="/${l.part}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/>`).join(""),c=re(s).map(l=>`<Override PartName="/${l.comments}" ContentType="${Ue}"/>`).join(""),n=t.map(l=>`<Override PartName="/${l}" ContentType="${Ee(l)}"/>`).join("");return`${D}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>${c?'<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>':""}${c}<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>${n}<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/><Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>${a}${e?`<Override PartName="/${W}" ContentType="${Be}"/>`:""}</Types>`}const Cs="application/vnd.ms-excel.sheet.macroEnabled.main+xml";function Is(t,e){if(!e)return t;const s=`<workbookPr codeName="${L(e)}"/>`;if(/<workbookPr\b/.test(t))return t.replace(/<workbookPr\b([^>]*?)(\/?)>/,(c,n,l)=>`<workbookPr${n.replace(/\scodeName="[^"]*"/,"")} codeName="${L(e)}"${l}>`);const a=/<(?:workbookProtection|bookViews|sheets)\b/.exec(t);return a?t.slice(0,a.index)+s+t.slice(a.index):t}function Ns(t,e){const s=L(e);return/<sheetPr\b/.test(t)?t.replace(/<sheetPr\b([^>]*?)(\/?)>/,(a,c,n)=>`<sheetPr${c.replace(/\scodeName="[^"]*"/,"")} codeName="${s}"${n}>`):t.replace(/(<worksheet\b[^>]*>)/,`$1<sheetPr codeName="${s}"/>`)}function Es(t){const e=t.sheets.map((l,p)=>`<sheet name="${L(l.name)}" sheetId="${p+1}"${l.veryHidden?' state="veryHidden"':l.hidden?' state="hidden"':""} r:id="rId${p+1}"/>`).join(""),s=t.definedNames?.length?`<definedNames>${t.definedNames.map(l=>`<definedName name="${T(l.name)}"${l.comment?` comment="${L(l.comment)}"`:""}${l.localSheetId!==void 0?` localSheetId="${l.localSheetId}"`:""}${l.hidden?' hidden="1"':""}>${T(l.text)}</definedName>`).join("")}</definedNames>`:"",a=is(t),c=t.date1904?'<workbookPr date1904="1"/>':"",n=t.formulasEdited?'<calcPr fullCalcOnLoad="1"/>':"";return qe(Pe(ye(`${D}<workbook xmlns="${q}" xmlns:r="${A}">${c}${a}<sheets>${e}</sheets>${s}${n}</workbook>`,t.printNames??[]),t.filterNames,t.sheets),t)}function As(t,e){const s=t.map((c,n)=>`<Relationship Id="rId${n+1}" Type="${A}/${Ne(c)?"chartsheet":"worksheet"}" Target="${c.slice(3)}"/>`).join(""),a=t.length;return`${D}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${s}<Relationship Id="rId${a+1}" Type="${A}/styles" Target="styles.xml"/><Relationship Id="rId${a+2}" Type="${A}/sharedStrings" Target="sharedStrings.xml"/>${e?`<Relationship Id="rId${a+3}" Type="${A}/sheetMetadata" Target="metadata.xml"/>`:""}</Relationships>`}export{ct as MAX_COLS,pa as writeXlsx};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@8sheets/data-grid",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "license": "SEE LICENSE IN LICENSE.md",
5
5
  "homepage": "https://8sheets.com",
6
6
  "author": "8cells",
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 ee}from"../slicers/pivot-file.js";import{dateOptionFlags as se}from"../slicers/date-filters.js";import{BOOL as at,CHUNK_BITS as Tt,CHUNK_MASK as Ct,EMPTY as H,ERR as ct,ERRORS as Ft,KIND_MASK as St,NUM as B,STR as Z}from"../core/sheet.js";import{formatGeneral as Vt,getFormatter as Pt,partsToSerial as ne,serialToParts as pt}from"../core/numfmt.js";import{MAX_COLS as re,MAX_ROWS as oe}from"../core/address.js";import{compareText as Ut,ERR as P,ERR_BY_INDEX as Rt,numberToText as le,XlError as $}from"../calc/values.js";import{FUNCS as ie}from"../calc/functions/registry.js";import"../calc/functions/index.js";import{t as G}from"../i18n/index.js";const k=-2,Qe=["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 kt(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 ze=[["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"]],ce=new Set(["percent","percentOfParent","difference","percentDiff","runTotal","percentOfRunningTotal","rankAscending","rankDescending"]),Je=c=>ce.has(c),Ze=c=>c==="percent"||c==="difference"||c==="percentDiff",ue=new Set(["percentOfTotal","percentOfCol","percentOfRow","percent","percentOfParentRow","percentOfParentCol","percentOfParent","percentDiff","percentOfRunningTotal"]),ts=["captionEqual","captionNotEqual","captionBeginsWith","captionNotBeginsWith","captionEndsWith","captionNotEndsWith","captionContains","captionNotContains","captionGreaterThan","captionGreaterThanOrEqual","captionLessThan","captionLessThanOrEqual","captionBetween","captionNotBetween"],es=["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,ss={ITEM:X,SUBTOTAL:lt,GRAND:st,BLANK:mt},Bt=1<<23,fe=1<<24,Nt="";class I 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 $t=c=>c===null?4:typeof c=="number"?0:typeof c=="string"?1:typeof c=="boolean"?2:3,he=[["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 de(c){let t=he,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 Gt=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Wt=[31,29,31,30,31,30,31,31,30,31,30,31],pe=["seconds","minutes","hours","days","months","quarters","years"],me={seconds:"Seconds",minutes:"Minutes",hours:"Hours",days:"Days",months:"Months",quarters:"Quarters",years:"Years"};function we(c,t){let e=0;for(let s=0;s<c-1;s++)e+=Wt[s];return e+t-1}function ge(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 Gt;case"days":{const s=[];return Wt.forEach((n,r)=>{for(let o=1;o<=n;o++)s.push(`${o}-${Gt[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 ye(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 we(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=H,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.cache.load(),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:r,strs:o}=this;if(o!==null)Ae(this.cache,o,null,null,t,e,s);else if(r!==null&&n===null&&this.uniformKind===B){const l=new Map;let i=NaN,u=-1;for(let f=0;f<t;f++){const m=r[f];if(m!==i){let y=l.get(m);y===void 0&&(y=s.length,s.push(m),l.set(m,y)),i=m,u=y}e[f]=u}}else n!==null?ve(this.cache,n,r,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}=_e(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),l=new Float64Array(r.length);r.forEach((i,u)=>{typeof i=="number"?(o[u]=B,l[u]=i):typeof i=="string"?o[u]=Z:typeof i=="boolean"?(o[u]=at,l[u]=i?1:0):i instanceof $&&(o[u]=ct,l[u]=i.index)});for(let i=0;i<t;i++){const u=n[i];e[i]=o[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"?Pt(this.numFmt).number(t):Vt(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=de(t),n=Array.from(t.keys());n.sort((r,o)=>be(t[r],t[o],s)),n.forEach((r,o)=>{e[r]=o})}return this._rank=e,e}}function be(c,t,e){const s=$t(c),n=$t(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 Ae(c,t,e,s,n,r,o){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 m=t[f];let y=i[m];if(y<0){const h=c.getString(m),a=h.toLowerCase();y=u.get(a),y===void 0&&(y=o.length,o.push(h),u.set(a,y)),i[m]=y}r[f]=y}}function ve(c,t,e,s,n,r){const o=new Map,l=new Map,i=new Map,u=new Map;let f=-1;for(let m=0;m<s;m++){const y=t[m];let h;if(y===B){const a=e[m];h=o.get(a),h===void 0&&(h=r.length,r.push(a),o.set(a,h))}else if(y===Z){const a=e[m];if(h=i.get(a),h===void 0){const d=c.getString(a),p=d.toLowerCase();h=l.get(p),h===void 0&&(h=r.length,r.push(d),l.set(p,h)),i.set(a,h)}}else if(y===H)f<0&&(f=r.length,r.push(null)),h=f;else{const a=y*100+e[m];h=u.get(a),h===void 0&&(h=r.length,r.push(y===at?e[m]!==0:Rt[e[m]]??P.NA),u.set(a,h))}n[m]=h}}function _e(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=`<${qt(t.start)}`,f=`>${qt(t.end+1)}`,m=ge(t.part,l.year,i.year);let y=[u,...m,f];t.labels&&t.labels.length===y.length&&(y=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]=y.length-1:s[h]=1+ye(t.part,pt(a),l.year)}return{map:s,labels:y}}if(t.kind==="bins"){const{start:l,end:i,interval:u}=t,f=Math.max(1,Math.ceil((i-l)/u-1e-9)),m=[`<${At(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;m.push(`${At(a)}-${At(d)}`)}m.push(`>${At(i)}`);const y=t.labels&&t.labels.length===m.length?t.labels:m;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:y}}const n=t.groups.map(l=>l.name),r=new Map;t.groups.forEach((l,i)=>{for(const u of l.keys)r.set(u,i)});const o=new Map;for(let l=0;l<e.length;l++){const i=ut(e[l]);let u=r.get(i);u===void 0&&(u=o.get(i),u===void 0&&(u=n.length,n.push(e[l]),o.set(i,u))),s[l]=u}return{map:s,labels:n}}const At=c=>le(Number(c.toPrecision(12)));function qt(c){const t=pt(c);return`${t.month}/${t.day}/${t.year}`}class Te{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 Ce(c,t,e,s,n,r){const o=c.columns[t];if(o===void 0)return;const l=e+s;for(let i=e>>>Tt;i<=l-1>>>Tt;i++){const u=o[i];if(u===void 0)continue;const f=i<<Tt,m=Math.max(e,f)&Ct,y=Math.min(l-1,f+Ct)&Ct,h=f-e,a=u.kinds,d=u.values;for(let p=m;p<=y;p++)n[h+p]=a[p]&St,r[h+p]=d[p]}}function Re(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)}class gt{constructor(){this.fields=[],this.recordCount=0,this.strings=new Te,this.source=null,this.generation=0,this.xml=null,this.id=0,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 I("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((r,o)=>{const l=new Uint8Array(n),i=new Float64Array(n);for(let f=0;f<n;f++){const m=e[f][o];typeof m=="number"?(l[f]=B,i[f]=m):typeof m=="string"?(l[f]=Z,i[f]=s.strings.add(m)):typeof m=="boolean"?(l[f]=at,i[f]=m?1:0):m instanceof $&&(l[f]=ct,i[f]=m.index)}const u=new ft(s,o,r);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((r,o)=>{const l=new ft(n,o,r.name);l.kinds=r.kinds??null,l.nums=r.nums??null,l.strs=r.strs??null,l.uniformKind=r.strs?Z:r.kinds?H:B,r.numFmt&&jt(l,r.numFmt),n.fields.push(l)}),n}require(){if(this.deferred&&!this.refresh())throw new I("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,l=t.map(i=>({f:i,state:{...i,group:i.group&&{...i.group}}}));return()=>{Object.assign(this,{fields:l.map(({f:i,state:u})=>Object.assign(i,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 I))throw t}}refresh(){const t=this.source;if(t===null){for(const a of this.fields)a.invalidate();return this.generation++,!1}const{book:e}=t;this.strings=e.strings;let s,n,r,o,l;if(t.type==="table"){const a=t.table;s=a.sheet??e.sheets[a.sheetIndex],n=a.r0,r=a.c0,o=a.r1-(a.totalsRows??0),l=a.c1}else{if({sheet:s}=t,typeof s=="string"&&(s=e.sheets.find(a=>a.name===t.sheet)),!s)throw new I("The PivotTable source sheet no longer exists.");({r0:n,c0:r,r1:o,c1:l}=t.range),o=Math.min(o,s.maxRow),l=Math.min(l,s.maxCol)}if(o<=n)throw new I("The PivotTable source needs a header row and at least one row of data.");if(t.headers&&t.headers.length!==l-r+1)throw new I("The PivotTable source needs a header for every column.");const i=o-n,u=t.skipRow?Re(n+1,i,t.skipRow):null,f=u?u.length:i;if(f===0)throw new I("The PivotTable source needs a header row and at least one row of data.");const m=new Map,y=[];for(let a=r;a<=l;a++){const d=t.headers?String(t.headers[a-r]).trim():Le(e,s,n,a);if(d==="")throw new I("The PivotTable field name is not valid: every source column needs a header.");const p=d.toLowerCase(),b=(m.get(p)??0)+1;m.set(p,b),y.push(b>1?`${d}${b}`:d)}const h=new Map(this.fields.filter(a=>!a.isVirtual).map(a=>[a.name.toLowerCase(),a]));this.recordCount=f,y.forEach((a,d)=>{let p=h.get(a.toLowerCase());p?h.delete(a.toLowerCase()):(p=new ft(this,this.fields.length,a),this.fields.push(p));const b=r+d;let w=new Uint8Array(i),g=new Float64Array(i);Ce(s,b,n+1,i,w,g),u&&(w=Uint8Array.from(u,A=>w[A]),g=Float64Array.from(u,A=>g[A])),Ht(p,w,g,f),p.removed=!1,p.reset();for(let A=0;A<f;A++)if(w[A]!==H){jt(p,e.styles.get(s.style(n+1+(u?u[A]:A),b)).numFmt);break}});for(const a of h.values())a.removed=!0,a.kinds=null,a.nums=null,a.strs=null,a.uniformKind=H,a.reset();for(const a of this.fields)a.isVirtual&&a.reset();return this.needsRefresh=!1,this.deferred=!1,this._rescaleGroups(),this.generation++,!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 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}}}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=Ne(s.formula,e),s.calc=null):s.isVirtual||(s.name=e.get(s.name.toLowerCase())??s.name);this.generation++}addCalculatedField(t,e){const s=new ft(this,this.fields.length,this._uniqueName(t));return s.formula=e.replace(/^\s*=\s*/,""),s.calc=Et(s.formula,this),this.fields.push(s),s.index}updateCalculatedField(t,e){const s=this.fields[t],n=e.replace(/^\s*=\s*/,"");s.calc=Et(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 r of t.shared){if(typeof r!="number")throw new I("Cannot group that selection.");r<e&&(e=r),r>s&&(s=r),Number.isInteger(r)||(n=!1)}if(e===1/0)throw new I("Cannot group that selection.");return{min:e,max:s,integer:n}}groupDates(t,e,{start:s,end:n}={}){const r=this.fields[t];if(r.isCalculated||r.base>=0)throw new I("Cannot group that selection.");const{min:o,max:l}=this._numericRange(r),i=pe.filter(y=>e.includes(y));if(i.length===0)throw new I("Choose at least one grouping unit.");this.ungroup(t);const u={start:s??Math.floor(o),end:n??Math.floor(l)};r.group={kind:"date",part:i[0],...u,autoStart:s===void 0,autoEnd:n===void 0},r.invalidate();const f=[t];let m=r;for(const y of i.slice(1)){const h=new ft(this,this.fields.length,this._uniqueName(me[y]));h.base=t,h.group={kind:"date",part:y,...u,autoStart:s===void 0,autoEnd:n===void 0},this.fields.push(h),m.par=h.index,m=h,f.unshift(h.index)}return f}groupNumbers(t,{start:e,end:s,interval:n=10}={}){const r=this.fields[t];if(r.isCalculated||r.base>=0)throw new I("Cannot group that selection.");if(!(n>0))throw new I("The grouping interval must be greater than zero.");const{min:o,max:l,integer:i}=this._numericRange(r);this.ungroup(t);const u=e??o,f=s??l;if(f<=u)throw new I("The ending value must be greater than the starting value.");return r.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},r.invalidate(),t}groupText(t,e,s){const n=this.fields[t];if(n.isCalculated)throw new I("Cannot group that selection.");n.ensureRaw();let r=n.par>=0?this.fields[n.par]:null;if(r&&r.group?.kind!=="discrete")throw new I("Cannot group that selection.");return r?(r.group.groups.push(...e),r.invalidate(),r.index):(r=new ft(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 jt(c,t){c.numFmt=t??"General";try{c.isDate=c.numFmt!=="General"&&Pt(c.numFmt).isDate===!0}catch{c.isDate=!1}}function Le(c,t,e,s){const n=t.kind(e,s)&St,r=t.value(e,s);return n===Z?c.strings.get(r).trim():n===B?Vt(r):n===at?r?"TRUE":"FALSE":n===ct?Ft[r]??"":""}function Ht(c,t,e,s){let n=0,r=0;for(let o=0;o<s;o++){const l=t[o];l===B?n++:l===Z&&r++}if(c.strs=null,c.kinds=null,c.nums=null,n===s&&s>0)c.uniformKind=B,c.nums=e;else if(r===s&&s>0){c.uniformKind=Z;const o=new Int32Array(s);for(let l=0;l<s;l++)o[l]=e[l];c.strs=o}else c.uniformKind=H,c.kinds=t,c.nums=e}const ke=["<=",">=","<>","+","-","*","/","^","%","(",")",",","=","<",">","&"];function Ne(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 xe(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 I("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}),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=ke.find(r=>c.startsWith(r,e));if(!n)throw new I("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,S=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 P.VALUE},Yt={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=>S(t())!==0),OR:c=>c.some(t=>S(t())!==0),NOT:c=>S(c[0]())===0,SUM:c=>c.reduce((t,e)=>t+S(e()),0),MIN:c=>Math.min(...c.map(t=>S(t()))),MAX:c=>Math.max(...c.map(t=>S(t()))),AVERAGE:c=>c.reduce((t,e)=>t+S(e()),0)/c.length,COUNT:c=>c.length,TRUE:()=>!0,FALSE:()=>!1},xt=new Set;function Xt(c,t){if(c.calc)return c.calc;if(xt.has(c))throw new I("The formula is not valid.");xt.add(c);try{c.calc=Et(c.formula,t)}finally{xt.delete(c)}return c.calc}function Et(c,t){const e=xe(c);let s=0;const n=new Set,r=w=>e[s]?.t==="op"&&e[s].v===w,o=()=>new I("The formula is not valid."),l=w=>{const g=t.fields.find(v=>v.name.toLowerCase()===w.v.toLowerCase()&&!v.isCalculated),A=t.fields.find(v=>v.name.toLowerCase()===w.v.toLowerCase()&&v.isCalculated);if(A){Xt(A,t);for(const v of A.calc.refs)n.add(v);return v=>A.calc.fn(v)}if(!g)throw new I("The formula refers to an unknown field: {name}",{name:w.v});n.add(g.index);const _=g.index;return v=>v(_)},i=()=>{const w=e[s];if(!w)throw o();if(w.t==="num"){s++;const g=w.v;return()=>g}if(w.t==="str"){s++;const g=w.v;return()=>g}if(w.t==="name"){if(s++,w.bare&&r("(")){s++;const g=[];if(!r(")"))for(g.push(a());r(",");)s++,g.push(a());if(!r(")"))throw o();return s++,d(w.v.toUpperCase(),g)}if(w.bare&&p.has(w.v.toUpperCase())&&!t.field(w.v)){const g=Yt[w.v.toUpperCase()];return()=>g([])}return l(w)}if(r("(")){s++;const g=a();if(!r(")"))throw o();return s++,g}throw o()},u=()=>{let w=i();for(;r("%");){s++;const g=w;w=A=>S(g(A))/100}return w},f=()=>{if(r("-")){s++;const w=f();return g=>-S(w(g))}return r("+")?(s++,f()):u()},m=()=>{let w=f();for(;r("^");){s++;const g=w,A=f();w=_=>{const v=S(g(_))**S(A(_));if(!Number.isFinite(v))throw P.NUM;return v}}return w},y=()=>{let w=m();for(;r("*")||r("/");){const g=e[s++].v,A=w,_=m();w=g==="*"?v=>S(A(v))*S(_(v)):v=>{const N=S(_(v));if(N===0)throw P.DIV0;return S(A(v))/N}}return w},h=()=>{let w=y();for(;r("+")||r("-");){const g=e[s++].v,A=w,_=y();w=g==="+"?v=>S(A(v))+S(_(v)):v=>S(A(v))-S(_(v))}return w},a=()=>{let w=h();for(;e[s]?.t==="op"&&["=","<>","<",">","<=",">="].includes(e[s].v);){const g=e[s++].v,A=w,_=h();w=v=>{const N=S(A(v)),R=S(_(v));switch(g){case"=":return N===R;case"<>":return N!==R;case"<":return N<R;case">":return N>R;case"<=":return N<=R;default:return N>=R}}}return w},d=(w,g)=>{const A=Yt[w];if(A)return v=>A(g.map(N=>()=>N(v)));const _=ie.get(w);if(!_||_.kind!=="lift")throw new I("The formula uses a function a calculated field can't call: {name}",{name:w});if(g.length<_.min||g.length>_.max)throw o();return v=>{const N=g.map(R=>R(v));for(const R of N)if(R instanceof $)throw R;return _.fn(...N)}},p=new Set(["TRUE","FALSE"]),b=a();if(s<e.length)throw o();return{fn:b,refs:[...n]}}const Ee={sum:"sum",average:"sum",count:"",countNums:"",max:"mm",min:"mm",product:"prod",stdDev:"var",stdDevp:"var",var:"var",varp:"var"};class Ot{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 r=e.num[s],o=this.num[t];if(this.num[t]=o+r,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 l=e.mean[s]-this.mean[t],i=o+r;this.m2[t]+=e.m2[s]+l*l*o*r/i,this.mean[t]+=l*r/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?P.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?P.DIV0:Math.sqrt(this.m2[t]/(n-1));case"stdDevp":return n<1?P.DIV0:Math.sqrt(this.m2[t]/n);case"var":return n<2?P.DIV0:this.m2[t]/(n-1);case"varp":return n<1?P.DIV0:this.m2[t]/n;default:return null}}}function Oe(c,t,e,s){const{cnt:n,num:r}=c;t.base<0&&t.ensureColumn();const{kinds:o,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(o===null){for(let a=0;a<s;a++){const d=e[a];d>=0&&n[d]++}r.set(n)}else for(let a=0;a<s;a++){const d=e[a];if(d<0)continue;const p=o[a];p!==H&&(n[d]++,p===B?r[d]++:p===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:m,mean:y,m2:h}=c;if(i!==null)if(o===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&&o[a]===B&&(i[d]+=l[a])}if(u!==null)for(let a=0;a<s;a++){const d=e[a];if(d<0||o!==null&&o[a]!==B)continue;const p=l[a];p<u[d]&&(u[d]=p),p>f[d]&&(f[d]=p)}if(m!==null)for(let a=0;a<s;a++){const d=e[a];d>=0&&(o===null||o[a]===B)&&(m[d]*=l[a])}if(y!==null){const a=new Int32Array(c.size);for(let d=0;d<s;d++){const p=e[d];if(p<0||o!==null&&o[d]!==B)continue;const b=++a[p],w=l[d]-y[p];y[p]+=w/b,h[p]+=w*(l[d]-y[p])}}}class Ie{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 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 Qt(c,t,e,s,n,r=null){const o=new Ie(c,t,e),l=t.length;if(l===0)return o;let i=null,u=1;const f=[];for(let h=0;h<l;h++){const a=c.fields[t[h]].ensure(),d=a.ids,p=a.items.length,b=u*p,w=new Int32Array(s),g=Math.min(b,Math.max(s,1)),A=new Int32Array(g),_=new Int32Array(g);let v=0;if(b<=Bt){const F=new Int32Array(b).fill(-1);if(i===null)for(let C=0;C<s;C++){if(n!==null&&n[C]===0){w[C]=-1;continue}const x=d[C];let U=F[x];U<0&&(U=v++,F[x]=U,_[U]=x),w[C]=U}else for(let C=0;C<s;C++){const x=i[C];if(x<0){w[C]=-1;continue}const U=x*p+d[C];let M=F[U];M<0&&(M=v++,F[U]=M,A[M]=x,_[M]=d[C]),w[C]=M}}else{const F=new Map;for(let C=0;C<s;C++){const x=i===null?0:i[C];if(x<0||i===null&&n!==null&&n[C]===0){w[C]=-1;continue}const U=x*p+d[C];let M=F.get(U);M===void 0&&(M=v++,F.set(U,M),A[M]=x,_[M]=d[C]),w[C]=M}}const N=r?.(t[h]),R=N?ee({parents:A,items:_,count:v},u,p,N.hide):{parents:A,items:_,count:v};f.push(R),i=w,u=Math.max(R.count,1)}o.leaf=i,o.nLeaves=f[l-1].count;let m=1;const y=[];for(const h of f)y.push(m),m+=h.count;return o.levelBase=y,o.nNodes=m,o.parent=new Int32Array(m),o.item=new Int32Array(m),o.depth=new Uint8Array(m),o.parent[0]=-1,o.item[0]=-1,f.forEach((h,a)=>{const d=y[a],p=a===0?0:y[a-1];for(let b=0;b<h.count;b++)o.parent[d+b]=a===0?0:p+h.parents[b],o.item[d+b]=h.items[b],o.depth[d+b]=a+1}),o}class Me{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,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]=r,this.levels[i]=o,this.formats[i]=l}pushValue(t,e,s,n,r=0,o=0){s==null?this.push(t,e,H,0,n,r,o):typeof s=="number"?this.push(t,e,B,s,n,r,o):typeof s=="string"?this.push(t,e,Z,this.text(s),n,r,o):typeof s=="boolean"?this.push(t,e,at,s?1:0,n,r,o):this.push(t,e,ct,s.index,n,r,o)}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 Ft[this.values[t]]??"#N/A";default:return null}}}function zt(c){const t=c.replace(/[.+^${}()|[\]\\*?~]/g,e=>e==="*"?".*":e==="?"?".":`\\${e}`);return new RegExp(`^${t}$`,"is")}const Jt=c=>c.replace(/[.+^${}()|[\]\\]/g,"\\$&");function De(c){const{op:t}=c,e=String(c.value??""),s=String(c.value2??""),n=e.split(/([*?])/).map(o=>o==="*"?".*":o==="?"?".":Jt(o)).join(""),r=(o,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(o,i)};switch(t){case"captionEqual":{const o=zt(e);return l=>o.test(l)}case"captionNotEqual":{const o=zt(e);return l=>!o.test(l)}case"captionBeginsWith":{const o=new RegExp(`^${n}`,"is");return l=>o.test(l)}case"captionNotBeginsWith":{const o=new RegExp(`^${n}`,"is");return l=>!o.test(l)}case"captionEndsWith":{const o=new RegExp(`${n}$`,"is");return l=>o.test(l)}case"captionNotEndsWith":{const o=new RegExp(`${n}$`,"is");return l=>!o.test(l)}case"captionContains":{const o=new RegExp(n,"is");return l=>o.test(l)}case"captionNotContains":{const o=new RegExp(n,"is");return l=>!o.test(l)}case"captionGreaterThan":return(o,l)=>r(o,l,e)>0;case"captionGreaterThanOrEqual":return(o,l)=>r(o,l,e)>=0;case"captionLessThan":return(o,l)=>r(o,l,e)<0;case"captionLessThanOrEqual":return(o,l)=>r(o,l,e)<=0;case"captionBetween":return(o,l)=>r(o,l,e)>=0&&r(o,l,s)<=0;case"captionNotBetween":return(o,l)=>r(o,l,e)<0||r(o,l,s)>0;default:return()=>!0}}function Fe(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 r of t.hidden){const o=n.get(r);o!==void 0&&(s[o]=1)}}if(t.labelFilter){const n=De(t.labelFilter);c.items.forEach((r,o)=>{n(c.labelOfValue(r),r)||(s[o]=1)})}return s}function Zt(c,t){return c.ensureRaw(),se(c.shared,t)}class Se{constructor(t,e){this.rows=t,this.cols=e,this.dense=t*e<=fe,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 Ve{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,l)=>{let i=s.get(o);i===void 0&&(i={sum:!1,mm:!1,prod:!1,var:!1},s.set(o,i));const u=Ee[l];u&&(i[u]=!0)},r=new Set;for(const o of Object.keys(e.fieldOptions)){const l=e.fieldOptions[o].subtotals;if(Array.isArray(l))for(const i of l)r.add(i)}this.data=e.values.map((o,l)=>{const i=t.fields[o.field],u={index:l,field:o.field,name:o.name,agg:o.agg,showAs:o.showAs??null,numFmt:o.numFmt??null,calc:null};if(i.isCalculated){u.calc=Xt(i,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 l=wt(o,e.fieldOptions[r]);if(l!==null){n===null&&(n=new Uint8Array(t).fill(1));const i=o.ensure().ids;for(let u=0;u<t;u++)l[i[u]]===1&&(n[u]=0)}if(e.fieldOptions[r].range||e.fieldOptions[r].dateFilter){n===null&&(n=new Uint8Array(t).fill(1));const i=Zt(o,e.fieldOptions[r]),u=o.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,r=g=>g.filter(A=>A!==k||n>1);let o=r(e.rows),l=r(e.cols);n>1&&!o.includes(k)&&!l.includes(k)&&(l=[...l,k]),o=o.filter(g=>g===k||!t.fields[g].removed),l=l.filter(g=>g===k||!t.fields[g].removed);const i=this._recordMask(s);this.mask=i;const u=g=>{const A=e.fieldOptions[g];return A?.showAll?{hide:wt(t.fields[g],A)}:null},f=Qt(t,o.filter(g=>g!==k),o,s,i,u),m=Qt(t,l.filter(g=>g!==k),l,s,i,u);this.rows=f,this.cols=m;let y,h,a,d;const p=f.nLeaves,b=m.nLeaves;if(f.leaf!==null&&m.leaf!==null){const g=f.leaf,A=m.leaf;y=new Int32Array(s);const _=p*b,v=Math.min(_,Math.max(s,1));if(h=new Int32Array(v),a=new Int32Array(v),d=0,_<=Bt){const N=new Int32Array(_).fill(-1);for(let R=0;R<s;R++){const F=g[R];if(F<0){y[R]=-1;continue}const C=F*b+A[R];let x=N[C];x<0&&(x=d++,N[C]=x,h[x]=F,a[x]=A[R]),y[R]=x}}else{const N=new Map;for(let R=0;R<s;R++){const F=g[R];if(F<0){y[R]=-1;continue}const C=F*b+A[R];let x=N.get(C);x===void 0&&(x=d++,N.set(C,x),h[x]=F,a[x]=A[R]),y[R]=x}}}else if(f.leaf!==null||m.leaf!==null){y=f.leaf??m.leaf,d=f.leaf!==null?p:b;const g=new Int32Array(d);for(let _=0;_<d;_++)g[_]=_;const A=new Int32Array(d);h=f.leaf!==null?g:A,a=f.leaf!==null?A:g}else{if(y=new Int32Array(s),d=1,i!==null)for(let g=0;g<s;g++)i[g]===0&&(y[g]=-1);h=new Int32Array(1),a=new Int32Array(1)}this.cellCount=d,this.cellRow=h,this.cellCol=a,this.cells=y;const w=new Map;for(const[g,A]of this.needs){const _=new Ot(d,A);Oe(_,t.fields[g],y,s),w.set(g,_)}this.leafAccs=w,this._applyValueFilters(),this._rollUp()}_slotValue(t,e,s,n){if(t.calc!==null){let r=!1;const o=l=>{const i=e.get(l);if(i.cnt[s]!==0&&(r=!0),i.err!==null&&i.err[s]!==0)throw Rt[i.err[s]-1];return i.sum[s]};try{const l=t.calc.fn(o);return r?typeof l=="number"?Number.isFinite(l)?l:P.NUM:typeof l=="boolean"?l?1:0:l instanceof $?l:P.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=(r,o,l)=>{for(let i=1;i<=r.k;i++){const u=r.fields[i-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 h=this._nodeAccs(r,y,l),a=r.levelBase[i-1],d=i<r.k?r.levelBase[i]:r.nNodes,p=new Map;for(let b=a;b<d;b++){if(o[b]||o[r.parent[b]]){o[b]=1;continue}const w=r.parent[b];let g=p.get(w);g===void 0&&(g=[],p.set(w,g)),g.push(b)}for(const b of p.values()){const w=g=>{const A=this._slotValue(y,h,g,null);return typeof A=="number"?A:null};if(f.valueFilter){const g=Fe(f.valueFilter);for(const A of b){const _=w(A);(_===null||!g(_))&&(o[A]=1)}}if(f.top){const g=b.filter(A=>!o[A]);for(const A of Ue(g,w,f.top,!0))o[A]=1}}for(let b=d;b<r.nNodes;b++)o[r.parent[b]]&&(o[b]=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],r=new Map;for(const a of n)r.set(a,new Ot(t.nNodes,this.needs.get(a)));const o=[...r.entries()].map(([a,d])=>[d,this.leafAccs.get(a)]),{cellRow:l,cellCol:i,rows:u,cols:f,rowDead:m,colDead:y}=this,h=s?l:i;for(let a=0;a<this.cellCount;a++){const d=u.leafNode(l[a]),p=f.leafNode(i[a]);if(m[d]||y[p])continue;let b=t.leafNode(h[a]);for(;b>=0;){for(const[w,g]of o)w.merge(b,g,a);b=t.parent[b]}}return r}_rollUp(){const{rows:t,cols:e,cellRow:s,cellCol:n,rowDead:r,colDead:o,cellCount:l}=this,i=new Uint8Array(t.nNodes),u=new Uint8Array(e.nNodes),f=new Se(t.nNodes,e.nNodes),m=t.parent,y=e.parent,h=new Uint8Array(l);for(let w=0;w<l;w++){const g=t.leafNode(s[w]),A=e.leafNode(n[w]);if(!(r[g]||o[A])){h[w]=1;for(let _=g;_>=0;_=m[_])if(i[_]=1,!f.dense)for(let v=A;v>=0;v=y[v])f.ensure(_,v);for(let _=A;_>=0;_=y[_])u[_]=1}}t.alive=i,e.alive=u;const a=new Map,d=[];for(const[w,g]of this.needs){const A=new Ot(Math.max(f.size,1),g);a.set(w,A),d.push([A,this.leafAccs.get(w)])}const p=f.dense,b=f.cols;for(let w=0;w<l;w++){if(h[w]===0)continue;const g=t.leafNode(s[w]),A=e.leafNode(n[w]);for(let _=g;_>=0;_=m[_])for(let v=A;v>=0;v=y[v]){const N=p?_*b+v:f.get(_,v);for(let R=0;R<d.length;R++)d[R][0].merge(N,d[R][1],w)}}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 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 l=(p,b)=>this.raw(t,p,b,n),i=p=>p instanceof $?p:o===null?p===null?null:0:p===null||p===0?P.DIV0:o/p;switch(r){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?o:l(this.rows.parent[e],s));case"percentOfParentCol":return i(s===0?o:l(e,this.cols.parent[s]));case"index":{const p=l(0,0),b=l(e,0),w=l(0,s);return[p,b,w].some(g=>g instanceof $)?P.VALUE:!b||!w?P.DIV0:(o??0)*p/(b*w)}default:}const u=this._baseLoc(t);if(u===null)return P.NA;const{tree:f,isRow:m,depth:y}=u,h=m?e:s;if(f.depth[h]<y)return null;const a=p=>m?l(p,s):l(e,p),d=f.ancestorAt(h,y);switch(r){case"percentOfParent":return i(a(d));case"percent":case"difference":case"percentDiff":{const p=this._baseSibling(t,f,d,y);if(p==="missing")return P.NA;if(p===-1)return r==="percent"?o===null?null:1:null;const b=a(f.peer(h,y,p));return p===d?r==="percent"?o===null?null:1:null:b instanceof $?b:r==="percent"&&o===null?P.NULL:r==="difference"?o===null&&b===null?null:(o??0)-(b??0):o===null||b===null?null:b===0?P.DIV0:r==="percent"?o/b:(o-b)/b}case"runTotal":case"percentOfRunningTotal":{const p=this._running(t,f,m,y,h,m?s:e,d,n);if(p instanceof $||r==="runTotal")return p;const b=f.children(f.parent[d]),w=this._running(t,f,m,y,h,m?s:e,b[b.length-1],n);return w instanceof $?w:w===0?P.DIV0:p/w}case"rankAscending":case"rankDescending":return o===null?null:this._rank(t,f,m,y,h,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 i=e.fieldAt(n).keyIndex.get(r);if(i===void 0)return"missing";const u=e.findChild(o,i);return u<0?"missing":u}_running(t,e,s,n,r,o,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]),m=e.pos[l],y=s?this.cols.nNodes:this.rows.nNodes;let h=m,a=0;for(;h>=0;){const d=e.peer(r,n,f[h]),p=d>=0?u.get(d*y+o):void 0;if(p!==void 0){a=p;break}h--}for(let d=h+1;d<=m;d++){const p=e.peer(r,n,f[d]);if(p<0)continue;const b=s?this.raw(t,p,o,i):this.raw(t,o,p,i);if(b instanceof $)return b;typeof b=="number"&&(a+=b),u.set(p*y+o,a)}return a}_rank(t,e,s,n,r,o,l,i,u){t._ranks===void 0&&(t._ranks=new Map);const f=e.ancestorAt(r,n),m=e.pathKeys(r).slice(n).join(Nt),y=`${e.parent[f]}|${o}|${m}`;let h=t._ranks.get(y);if(h===void 0){const p=[];for(const b of e.children(e.parent[f])){const w=e.peer(r,n,b);if(w<0)continue;const g=s?this.raw(t,w,o,u):this.raw(t,o,w,u);typeof g=="number"&&p.push(g)}h=Float64Array.from(p).sort(),t._ranks.set(y,h)}let a=0,d=h.length;if(i){for(;a<d;){const p=a+d>>1;h[p]<l?a=p+1:d=p}return a+1}for(;a<d;){const p=a+d>>1;h[p]<=l?a=p+1:d=p}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: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 l=new Int32Array(o[s]),i=o.slice();for(let u=1;u<s;u++)r[u]&&(l[i[n[u]]++]=u);t.childStart=o,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),m=u===0?0:t.levelBase[u-1],y=u===0?1:t.levelBase[u];for(let h=m;h<y;h++){const a=o[h],d=o[h+1];if(d-a>1){const p=Array.from(l.subarray(a,d));p.sort(f),l.set(p,a)}for(let p=a;p<d;p++)t.pos[l[p]]=p-a}}}_sortCompare(t,e,s){const n=t.fields[e-1],r=this.cache.fields[n].ensure(),o=r.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,p)=>o[l[d]]-o[l[p]];if(i.order==="manual"){const d=i.keys??[],p=new Map(d.map((w,g)=>[w,g])),b=new Float64Array(r.items.length);return r.items.forEach((w,g)=>{const A=p.get(ut(w));b[g]=A===void 0?d.length+o[g]:A}),(w,g)=>b[l[w]]-b[l[g]]}const u=i.order==="desc"?-1:1;if(i.data===void 0||i.data===null)return(d,p)=>u*(o[l[d]]-o[l[p]]);const f=this.data[i.data];if(!f)return(d,p)=>o[l[d]]-o[l[p]];let m=0;if(i.path){const d=s?this.cols:this.rows;this._ensureItems(d);for(let p=0;p<i.path.length&&m>=0;p++){const w=d.fieldAt(p+1).keyIndex.get(i.path[p]);m=w===void 0?-1:d.findChild(m,w)}}const y=d=>{const p=s?this.raw(f,d,m):this.raw(f,m,d);return typeof p=="number"?p:null},h=new Map,a=d=>{let p=h.get(d);return p===void 0&&(p=y(d),h.set(d,p)),p};return(d,p)=>{const b=a(d),w=a(p);return b===null||w===null?b===w?o[l[d]]-o[l[p]]:b===null?1:-1:b===w?o[l[d]]-o[l[p]]:u*(b-w)}}_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=(h,a,d,p,b,w,g,A)=>{r.node.push(h),r.data.push(a),r.type.push(d),r.level.push(p),r.first.push(b),r.func.push(w),r.top.push(g?1:0),r.parentLine.push(A?1:0)},l=s.length-1,i=h=>e?s[h]===k?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,p=a?.collapsed?.length?new Set(a.collapsed):null;u.push(d||p?{items:d,paths:p}:null)}const f=h=>this.opts(h)?.subtotalTop??this.spec.subtotalTop,m=(h,a,d,p)=>{const b=s[a];if(b===k){for(let _=0;_<n;_++){const v=_===0&&p!==-1?p:a;a===l?o(h,_,X,a,v,null,!1,!1):i(a)==="tabular"?m(h,a+1,_,v):(o(h,_,X,a,v,null,!1,!0),r.noValues??=new Set,r.noValues.add(r.node.length-1),m(h,a+1,_,-1))}return}const w=t.children(h),g=this.opts(b),A=g?.blankLine===!0&&e;for(let _=0;_<w.length;_++){const v=w[_],N=_===0&&p!==-1?p:a;if(a===l){o(v,d,X,a,N,null,!1,!1);continue}const R=i(a),F=d<0&&s.indexOf(k,a+1)>=0;if(this._isCollapsed(t,v,u)){if(F)for(let z=0;z<n;z++)o(v,z,X,a,z===0?N:a,null,!1,R!=="tabular");else o(v,d,X,a,N,null,!1,R!=="tabular");r.collapsed??=new Set,r.collapsed.add(v),A&&o(v,d,mt,a,a,null,!1,!1);continue}const C=g?.subtotals??"auto",x=Array.isArray(C),U=C!=="none"&&!(x&&C.length===0),M=R!=="tabular"&&!F&&!x&&U&&f(b);if(R==="tabular"?m(v,a+1,d,N):(o(v,d,X,a,N,null,M,!0),M||(r.noValues??=new Set,r.noValues.add(r.node.length-1)),m(v,a+1,d,-1)),!M&&U&&!(a+1===l&&s[a+1]===k&&!x)){const yt=x?C:[null];if(F)for(let tt=0;tt<n;tt++)for(const vt of yt)o(v,tt,lt,a,a,vt,!1,!1);else for(const tt of yt)o(v,d,lt,a,a,tt,!1,!1)}A&&o(v,d,mt,a,a,null,!1,!1)}};if(s.length===0)return o(0,-1,X,-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(k))for(let h=0;h<n;h++)o(0,h,st,0,0,null,!1,!1);else o(0,-1,st,0,0,null,!1,!1);return r}fieldCaption(t){return t===k?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]).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]),r=e.data[s],o=e.func[s];return o!==null&&r>=0?`${n} ${Lt[o]} of ${this.data[r].name}`:o!==null?`${n} ${Lt[o]}`:r>=0?`${n} ${this.data[r].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,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:e.items[r]??"(blank)"}:{text:"(Multiple Items)",value:"(Multiple Items)"}}_layout(){const{spec:t,rows:e,cols:s,data:n}=this,r=new Me;this.buffer=r;const o=n.length,l=t.filters.filter(T=>!this.cache.fields[T].removed),i=l.length>0?l.length+1:0,u=e.slots.length===0&&s.slots.length===0&&o===0;l.forEach((T,L)=>{r.pushValue(L,0,this.fieldCaption(T),E.PAGE_LABEL);const O=this.cache.fields[T],W=this._pageValue(T);r.pushValue(L,1,W.value,E.PAGE_VALUE,0,typeof W.value=="number"?r.format(O.numFmt):0)});const f=[],m=[];let y=0;if(e.slots.length>0){let T=0,L=0;for(let W=0;W<e.slots.length;W++)f.push(T),m.push(L),(e.slots[W]===k?t.layout:this._form(e.slots[W]))==="compact"?L++:(T++,L=0);y=(e.slots[e.slots.length-1]===k?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]===k)&&(y=1);const h=e.lines,a=s.lines,d=a.node.length,p=h.node.length,b=s.slots.length===1&&s.slots[0]===k,w=b&&!t.hideValuesRow&&e.slots.length>0,g=s.slots.length>0&&(!b||w),A=u?0:g?1+s.slots.length:1,_=g?t.layout==="compact"?1:s.slots.length:0,v=y+Math.max(o>0||g?d:0,_),N=o>0||e.slots.length>0?p:0,R=i,F=new Uint8Array(A*Math.max(v,1)),C=(T,L,O,W,j=0,V=0)=>{r.pushValue(R+T,L,O,W,V,j),F[T*v+L]=1},x=T=>t.layout==="compact"?null:T.map(L=>this.fieldCaption(L));u&&r.pushValue(R,0,t.name,E.PLACEHOLDER);const U=A-1;if(e.slots.length>0){const T=x(e.slots);T===null?C(U,0,t.rowCaption??G("Row Labels"),E.ROW_CAPTION):e.slots.forEach((L,O)=>{(L===k?t.layout:this._form(L))==="compact"&&O>0&&f[O]===f[O-1]||F[U*v+f[O]]||C(U,f[O],T[O],E.ROW_CAPTION)})}if(g){o===1&&e.slots.length>0&&C(0,0,n[0].name,E.CORNER);const T=x(s.slots);w?C(0,y,t.dataCaption,E.COL_CAPTION):T===null?C(0,y,t.colCaption??G("Column Labels"),E.COL_CAPTION):T.forEach((L,O)=>C(0,y+O,L,E.COL_CAPTION))}else o===1&&!b&&!e.slots.includes(k)&&C(0,y,n[0].name,E.DATA_HEADER);const M=g?1:0;if(o>0||g)for(let T=0;T<d;T++){const L=a.type[T],O=y+T,W=a.node[T];if(L===st){const V=a.data[T],ht=V>=0?`Total ${n[V].name}`:t.grandCaption??G("Grand Total");C(M,O,ht,E.COL_GRAND);continue}if(L===lt){C(M+a.level[T],O,this._subtotalLabel(s,a,T),E.COL_SUBTOTAL);continue}const j=a.level[T];for(let V=a.first[T];V<=j;V++){if(V<0||V>=s.slots.length)continue;if(s.slots[V]===k){const K=a.data[T];K>=0&&C(M+V,O,n[K].name,E.DATA_HEADER)}else{const K=It(s.slots,V),J=s.ancestorAt(W,K);if(V===j&&a.collapsed?.has(J))C(M+V,O,`${this._labelText(s,J)} Total`,E.COL_ITEM);else{const bt=this._labelValue(s,J);C(M+V,O,bt,E.COL_ITEM,typeof bt=="number"?r.format(s.fieldAt(K).numFmt):0,t.showExpandButtons&&K<s.k?1:0)}}}}for(let T=0;T<A;T++)for(let L=0;L<v;L++)F[T*v+L]===0&&r.push(R+T,L,H,0,E.HEADER_BLANK);const z=R+A,yt=n.map(T=>{const L=T.numFmt??Pe(T);return r.format(L)}),tt=h.noValues??null,vt=T=>e.slots[T];for(let T=0;T<N;T++){const L=z+T,O=h.type[T];if(O===mt)continue;const W=h.node[T],j=h.level[T],V=h.parentLine[T]===1;let ht=E.ROW_ITEM,K=E.DATA;O===lt?(ht=E.ROW_SUBTOTAL,K=E.DATA_SUBTOTAL):O===st?(ht=E.ROW_GRAND,K=E.DATA_GRAND_ROW):V&&(K=E.DATA_PARENT);const J=Math.max(j,0);if(y>0)if(e.slots.length===0)o===1&&r.pushValue(L,0,n[0].name,E.ROW_ITEM);else if(O===st){const q=h.data[T];r.pushValue(L,0,q>=0?`Total ${n[q].name}`:t.grandCaption??G("Grand Total"),E.ROW_GRAND);for(let D=1;D<y;D++)r.push(L,D,H,0,E.ROW_GRAND)}else if(O===lt){const q=f[j];for(let D=0;D<y;D++)D===q?r.pushValue(L,D,this._subtotalLabel(e,h,T),E.ROW_SUBTOTAL,m[j]):r.push(L,D,H,0,E.ROW_SUBTOTAL)}else{const q=this._labelStart(h,T,e);for(let D=q;D<=j;D++){const dt=vt(D),nt=f[D],rt=D===j&&V?E.ROW_PARENT:E.ROW_ITEM;if(dt===k){const Q=h.data[T];Q>=0&&r.pushValue(L,nt,n[Q].name,rt,m[D])}else{const Q=It(e.slots,D),ot=e.ancestorAt(W,Q),Y=t.showExpandButtons&&Q<e.k?1:0;if(D===j&&h.collapsed?.has(ot)&&this._form(dt)==="tabular")r.pushValue(L,nt,`${this._labelText(e,ot)} Total`,rt,m[D]+Y);else{const et=this._labelValue(e,ot),te=typeof et=="number"?r.format(e.fieldAt(Q).numFmt):0;r.pushValue(L,nt,et,rt,m[D]+Y,te)}}}}if(o===0||tt!==null&&tt.has(T))continue;const _t=h.data[T],bt=h.func[T];for(let q=0;q<d;q++){const D=a.type[q];if(D===mt)continue;const dt=a.data[q],nt=_t>=0?_t:dt>=0?dt:o===1?0:-1;if(nt<0)continue;const rt=n[nt],Q=bt??a.func[q],ot=this.show(rt,W,a.node[q],Q);let Y=K;O!==st&&D===st?Y=E.DATA_GRAND_COL:O===X&&!V&&D===lt&&(Y=E.DATA);const it=y+q,et=Q&&Q!==rt.agg&&!rt.numFmt?0:yt[nt];ot===null?t.showMissing===!1?r.pushValue(L,it,0,Y,J,et):t.emptyText!==""?r.pushValue(L,it,t.emptyText,Y,J,et):Y!==E.DATA&&r.push(L,it,H,0,Y,J,et):ot instanceof $&&t.errorText!==null?r.pushValue(L,it,t.errorText,Y,J,et):r.pushValue(L,it,ot,Y,J,et)}}const Mt=u?R+1:z+N,Dt=Math.max(v,l.length>0?2:0,u?1:0);if(Mt>oe||Dt>re)throw new I("The PivotTable is too large for a worksheet.");this.layout={cells:r,rows:Mt,cols:Dt,bodyCols:v,pageRows:i,pageFields:l,headerRows:A,labelCols:y,bodyTop:z,dataRows:N,colForLevel:f,indentForLevel:m,colRowBase:M,firstHeaderRow:u||g?1:o>1?0:1,firstDataRow:u?1:A,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 l=s.slots[o];if(l!==k&&this.opts(l)?.repeatLabels||l!==k&&this.spec.repeatLabels&&this._form(l)!=="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 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&&r.fields.length>0){const i=n.layout==="compact"?r.fields:r.slots.filter((u,f)=>u!==k&&s.colForLevel[f]===e);if(i.length>0)return{kind:"filter",axis:"row",fields:i}}if(l===0&&e>=s.labelCols&&o.fields.length>0&&s.colRowBase===1){const i=n.layout==="compact"?e===s.labelCols?o.fields:[]:o.slots.filter((u,f)=>u!==k&&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 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]!==X||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===k||o===void 0)return null;const l=It(t.slots,n),i=t.ancestorAt(e.node[s],l),u=l<t.k;return{kind:"label",axis:r,node:i,field:o,path:t.pathKeys(i),expandable:u,collapsed:u&&e.collapsed?.has(i)===!0}}togglesIn(t,e,s,n){const r=[],o=this.layout,{rows:l,cols:i}=this;if(this.spec.showExpandButtons===!1)return r;if(l.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(i.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,l)=>r.push({row:l,col:1,axis:"page",fields:[o]})),e.fields.length>0&&n.showFieldHeaders!==!1){const o=t.pageRows+t.headerRows-1;n.layout==="compact"?r.push({row:o,col:0,axis:"row",fields:e.fields}):e.slots.forEach((l,i)=>{l!==k&&(i===0||t.colForLevel[i]!==t.colForLevel[i-1])&&r.push({row:o,col:t.colForLevel[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((l,i)=>{l!==k&&r.push({row:o,col:t.labelCols+i,axis:"col",fields:[l]})})}return r}}function It(c,t){let e=0;for(let s=0;s<=t;s++)c[s]!==k&&e++;return e}function Pe(c){const t=c.showAs?.type;return ue.has(t)?"0.00%":t==="index"?"0.00":"General"}function Ue(c,t,e,s){const n=e.count??10,r=e.by??"items",o=e.bottom===!0,l=c.map(u=>[u,t(u)]).filter(u=>u[1]!==null);l.sort((u,f)=>o?u[1]-f[1]:f[1]-u[1]);const i=new Set;if(r==="items"){if(l.length>0&&n>0){const u=l[Math.min(n,l.length)-1][1];for(const[f,m]of l)(o?m<=u:m>=u)&&i.add(f)}}else{const u=l.reduce((y,h)=>y+h[1],0),f=r==="percent"?u*n/100:n;let m=0;for(const[y,h]of l)if(i.add(y),m+=h,m>=f)break}return s?c.filter(u=>!i.has(u)):c.filter(u=>i.has(u))}function Be(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 ns{constructor(t,e={}){this.cache=t,this.spec=Be(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 I("The PivotTable report was saved without the underlying data. Its source is not available.");this.cache.refresh()}return this._dropRemoved(),this.result=new Ve(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===k||!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){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===B)}uniqueDataName(t,e=-1){let s=t,n=2;const r=o=>this.spec.values.some((l,i)=>i!==e&&l.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],r=kt(n.isCalculated?"sum":e,n.name);return this.spec.values.splice(s,0,{field:t,agg:e,name:this.uniqueDataName(r)}),this.spec.values.length>1&&!this.spec.rows.includes(k)&&!this.spec.cols.includes(k)&&this.spec.cols.push(k),this.spec.values.length-1}setValueAgg(t,e){const s=this.spec.values[t],n=this.cache.fields[s.field],r=[kt(s.agg,n.name),`${ae[s.agg]} of ${n.name}`].some(o=>new RegExp(`^${Jt(o)}\\d*$`).test(s.name));s.agg=e,r&&(s.name=this.uniqueDataName(kt(e,n.name),t))}place(t,e,s){const{spec:n}=this;for(const o of["rows","cols","filters"])n[o]=n[o].filter(l=>l!==t);if(t===k&&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);e.values=e.values.filter(s=>s.field!==t),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==k),e.cols=e.cols.filter(s=>s!==k))}removeValue(t){const{spec:e}=this;e.values.splice(t,1),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==k),e.cols=e.cols.filter(s=>s!==k))}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){this.cache.load();const e=this.cache.fields[t].ensure(),s=e.rank(),n=wt(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:ut(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 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&&r.push([i.ensure().ids,u]),this.spec.fieldOptions[l].range||this.spec.fieldOptions[l].dateFilter){const f=Zt(i,this.spec.fieldOptions[l]);r.push([i.rawIds,f])}}const{ids:o}=e;t:for(let l=0;l<n;l++){for(let i=0;i<r.length;i++)if(r[i][1][r[i][0][l]]===1)continue t;s[o[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(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=>ut(r)):[],this.rearrange()}}export{Qe as AGGS,Lt as AGG_LABEL,Me as CellBuffer,ts as LABEL_FILTERS,ss as LINE,gt as PivotCache,I as PivotError,ft as PivotField,Ve as PivotResult,ns as PivotTable,E as ROLE,ze as SHOW_AS,k as VALUES,es as VALUE_FILTERS,jt as applyNumFmt,Et as compileCalc,wt as hiddenItemFlags,ut as itemKey,ne as partsToSerial,pt as serialToParts,Je as showAsNeedsBaseField,Ze as showAsNeedsBaseItem,Ht as storeColumn,kt as valueFieldName};