@allyhub/sdk 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node_modules/@allyhub-next/audio/package.json +1 -1
- package/dist/node_modules/@allyhub-next/chart/package.json +1 -1
- package/dist/node_modules/@allyhub-next/formats/dist/data/sheet.d.ts +179 -0
- package/dist/node_modules/@allyhub-next/formats/dist/data/sheet.js +1 -1
- package/dist/node_modules/@allyhub-next/formats/dist/data/slides.d.ts +303 -11
- package/dist/node_modules/@allyhub-next/formats/dist/data/slides.js +1 -1
- package/dist/node_modules/@allyhub-next/formats/dist/index.d.ts +1 -0
- package/dist/node_modules/@allyhub-next/formats/dist/index.js +1 -1
- package/dist/node_modules/@allyhub-next/formats/dist/items.js +1 -1
- package/dist/node_modules/@allyhub-next/formats/dist/schemas.d.ts +135 -3
- package/dist/node_modules/@allyhub-next/formats/dist/zip.d.ts +17 -0
- package/dist/node_modules/@allyhub-next/formats/dist/zip.js +2 -0
- package/dist/node_modules/@allyhub-next/formats/package.json +1 -1
- package/dist/node_modules/@allyhub-next/protocol/dist/editor.d.ts +10 -0
- package/dist/node_modules/@allyhub-next/protocol/dist/editor.js +1 -1
- package/dist/node_modules/@allyhub-next/protocol/dist/notes.d.ts +2 -0
- package/dist/node_modules/@allyhub-next/protocol/dist/notes.js +1 -1
- package/dist/node_modules/@allyhub-next/protocol/package.json +1 -1
- package/dist/node_modules/@allyhub-next/runtimes/package.json +1 -1
- package/dist/node_modules/@allyhub-next/scenery/package.json +1 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/api/capabilities.js +1 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/api/index.d.ts +1 -0
- package/dist/node_modules/@allyhub-next/sheet/dist/api/index.js +1 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/api/page.d.ts +83 -0
- package/dist/node_modules/@allyhub-next/sheet/dist/api/page.js +2 -0
- package/dist/node_modules/@allyhub-next/sheet/dist/api/workbook.d.ts +40 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/api/workbook.js +1 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/check.js +1 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/structure.js +1 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/xlsx/charts.d.ts +2 -0
- package/dist/node_modules/@allyhub-next/sheet/dist/xlsx/charts.js +1 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/xlsx/import.d.ts +3 -0
- package/dist/node_modules/@allyhub-next/sheet/dist/xlsx/import.js +1 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/xlsx/read.d.ts +2 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/xlsx/read.js +1 -1
- package/dist/node_modules/@allyhub-next/sheet/dist/xlsx/write.js +1 -1
- package/dist/node_modules/@allyhub-next/sheet/package.json +1 -1
- package/dist/node_modules/@allyhub-next/slides-core/dist/api.d.ts +64 -7
- package/dist/node_modules/@allyhub-next/slides-core/dist/api.js +2 -2
- package/dist/node_modules/@allyhub-next/slides-core/dist/capabilities.js +1 -1
- package/dist/node_modules/@allyhub-next/slides-core/dist/chart-api.d.ts +23 -0
- package/dist/node_modules/@allyhub-next/slides-core/dist/chart-api.js +1 -1
- package/dist/node_modules/@allyhub-next/slides-core/dist/chart-file.js +1 -1
- package/dist/node_modules/@allyhub-next/slides-core/dist/enums.d.ts +20 -0
- package/dist/node_modules/@allyhub-next/slides-core/dist/enums.js +1 -1
- package/dist/node_modules/@allyhub-next/slides-core/dist/index.d.ts +1 -0
- package/dist/node_modules/@allyhub-next/slides-core/dist/index.js +1 -1
- package/dist/node_modules/@allyhub-next/slides-core/dist/model.d.ts +37 -1
- package/dist/node_modules/@allyhub-next/slides-core/dist/office.d.ts +10 -0
- package/dist/node_modules/@allyhub-next/slides-core/dist/office.js +1 -1
- package/dist/node_modules/@allyhub-next/slides-core/dist/preset.d.ts +5 -0
- package/dist/node_modules/@allyhub-next/slides-core/dist/preset.js +2 -0
- package/dist/node_modules/@allyhub-next/slides-core/dist/resolve.d.ts +7 -2
- package/dist/node_modules/@allyhub-next/slides-core/dist/resolve.js +1 -1
- package/dist/node_modules/@allyhub-next/slides-core/package.json +1 -1
- package/dist/node_modules/@allyhub-next/video-core/package.json +1 -1
- package/dist/sheets.d.ts +1 -1
- package/dist/sheets.js +1 -1
- package/docs/defaults.md +23 -0
- package/docs/sheets.md +25 -0
- package/docs/slides.md +4 -4
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
|
|
2
|
-
import{SHEET_DATA as H,SHEET_FILE as z,strict as g}from"@allyhub-next/formats";import{columnIndex as E,columnLetter as N,cellName as C,contains as L,rangeName as x,readAddress as b,readArea as k}from"../address.js";import{Calc as U}from"../calc/engine.js";import{checkWorkbook as G}from"../check.js";import{readCsv as V,writeCsv as Y}from"../csv.js";import{GENERATED as q}from"../generated.js";import{moveFormula as Q,relativeKey as X}from"../formula/move.js";import{parseFormula as F}from"../formula/parse.js";import{printFormula as A}from"../formula/print.js";import{rewriteFormula as Z}from"../formula/rewrite.js";import{isDateCode as S}from"../format.js";import{patchCsv as ee}from"../patch.js";import{CellError as P,dateOfSerial as te,isoOfSerial as se,readTyped as M,serialOfDate as oe,writeTyped as ne}from"../values.js";import{FormulaCell as re,readWorkbook as B,validName as W}from"../workbook.js";import{restructure as ie,tableShape as le}from"../structure.js";import{patchYaml as ae}from"../write.js";import{anchorOf as he,chartOfSpec as fe}from"./charts.js";import{HINT as w}from"./hint.js";import{rectangles as T}from"./rectangles.js";import{AutoFilter as I,ConditionalFormattingList as ce,DataValidationList as ue,validationOf as _e,validationSpec as de}from"./rules.js";import{alignmentLook as me,alignmentOf as pe,borderLook as we,borderOf as ge,fillLook as ke,fillOf as ye,fontLook as be,fontOf as ve}from"./styles.js";const K=()=>process.getBuiltinModule("node:fs"),$=(...l)=>process.getBuiltinModule("node:path").join(...l);export const BLOCK_CELLS=100;const xe=l=>Math.round(l*7+5),Ee=l=>(l-5)/7,Se=l=>l*4/3,$e=l=>l*3/4;function Ce(l,e){const t={},s=l,o=e;for(const n of new Set([...Object.keys(s),...Object.keys(o)])){const r=o[n];JSON.stringify(r??!1)!==JSON.stringify(s[n]??!1)&&(t[n]=r??!1)}return t}const p=l=>Object.keys(l).length===0,y=(l,e)=>{if(!Number.isInteger(l)||l<1)throw new RangeError(`A ${e} is a whole number from 1: ${String(l)}.`);return l},j=(l,e)=>Object.fromEntries(Object.entries(l).filter(([t])=>t!==e));export class Cell{row;column;_ws;_value;_formula=void 0;_look;_changed=!1;_styled=!1;_fresh=!1;constructor(e,t,s){this._ws=e,this.row=t,this.column=s;const o=t-1,n=s-1,r=e._model?.at(o,n);return this._value=null,r instanceof re?this._formula=r.text:r!==void 0&&(this._value=r),this._look=e._model?.lookAt(o,n)??{},this._fresh=r===void 0,g(this,"Cell",w)}get parent(){return this._ws}get coordinate(){return C({row:this.row-1,col:this.column-1})}get column_letter(){return N(this.column-1)}get col_idx(){return this.column}get value(){return this._ws.parent.data_only?this.computed:this._formula!==void 0?this._formula:this._shown(this._value)}set value(e){if(e===void 0)throw new TypeError(`${this.coordinate}: a value is not undefined.`);if(this._formula=void 0,this._changed=!0,this._ws.parent._pending=!0,e instanceof Date){if(Number.isNaN(e.getTime()))throw new TypeError(`${this.coordinate}: the date is not valid.`);this._value=oe(e),S(this._look.format)||(this._look={...this._look,format:Number.isInteger(this._value)?"yyyy-mm-dd":"yyyy-mm-dd hh:mm"});return}if(typeof e=="string"&&e.length>1&&e.startsWith("=")){this._formula=e,this._value=null;return}this._value=e}_shown(e){return typeof e=="number"&&S(this._look.format)?te(e)??e:e instanceof P?e.code:e}get computed(){const{calc:e,model:t}=this._ws.parent._computed(),s=t.sheet(this._ws.title);return s?this._shown(e.value(s,this.row-1,this.column-1)):null}get data_type(){if(this._formula!==void 0)return"f";const e=this._value;return e===null?"n":typeof e=="number"?S(this._look.format)?"d":"n":typeof e=="boolean"?"b":e instanceof P?"e":"s"}get is_date(){return this.data_type==="d"}get number_format(){return this._look.format??"General"}set number_format(e){this._setLook({format:e})}_setLook(e){this._look={...this._look,...e},this._styled=!0,this._ws.parent._pending=!0}get font(){return ve(this._look)}set font(e){this._setLook(be(e))}get fill(){return ye(this._look)}set fill(e){this._setLook(ke(e))}get border(){return ge(this._look)}set border(e){this._setLook(we(e))}get alignment(){return pe(this._look)}set alignment(e){this._setLook(me(e))}get has_style(){return!p(this._look)}offset(e=0,t=0){return this._ws.cell(this.row+e,this.column+t)}}export class ColumnDimension{index;_width;_hidden;_files;_ws;constructor(e,t){this._ws=e,this.index=t;const s=e._spec()?.columns?.[t];return this._width=s?.width,this._hidden=s?.hidden,this._files=s?.files,g(this,"ColumnDimension",w)}get files(){return this._files}set files(e){this._files=e,this._ws._dimensions=!0}get width(){return this._width===void 0?void 0:Ee(this._width)}set width(e){this._width=e===void 0?void 0:xe(e),this._ws._dimensions=!0}get hidden(){return this._hidden??!1}set hidden(e){this._hidden=e,this._ws._dimensions=!0}}export class RowDimension{index;_height;_hidden;_ws;constructor(e,t){this._ws=e,this.index=t;const s=e._spec()?.rows?.[String(t)];return this._height=s?.height,this._hidden=s?.hidden,g(this,"RowDimension",w)}get height(){return this._height===void 0?void 0:$e(this._height)}set height(e){this._height=e===void 0?void 0:Se(e),this._ws._dimensions=!0}get hidden(){return this._hidden??!1}set hidden(e){this._hidden=e,this._ws._dimensions=!0}}export class Table{displayName;ref;key;_spec;autoFilter;constructor(e){for(const t of Object.keys(e))if(!["displayName","ref","key"].includes(t))throw new TypeError(`Table takes displayName, ref and key; it has no ${t}. ${w}`);if(!W(e.displayName))throw new TypeError(`${e.displayName} cannot be a table's name.`);if(!k(e.ref))throw new TypeError(`${e.ref} is not a range.`);return this.displayName=e.displayName,this.ref=e.ref,this.key=e.key,this.autoFilter=new I(e.ref,()=>{}),g(this,"Table",w)}get name(){return this.displayName}}export class TableList{_items=new Map;constructor(){return g(this,"TableList",w,{key:e=>this._items.get(e)})}add(e){this._items.set(e.name,e)}get(e){return this._items.get(e)}keys(){return[...this._items.keys()]}values(){return[...this._items.values()]}items(){return[...this._items.entries()]}pop(e){const t=this._items.get(e);return this._items.delete(e),t}}export class DefinedName{name;attr_text;constructor(e,t){if(!W(e))throw new TypeError(`${e} cannot be a name.`);return this.name=e,this.attr_text=t.attr_text.replace(/^=/u,""),g(this,"DefinedName",w)}get value(){return this.attr_text}set value(e){this.attr_text=e.replace(/^=/u,"")}}export class DefinedNameDict{_items=new Map;constructor(){return g(this,"DefinedNameDict",w,{key:e=>this._items.get(e),setKey:(e,t)=>t instanceof DefinedName?(this._items.set(e,t),!0):!1})}add(e){this._items.set(e.name,e)}get(e){return this._items.get(e)}keys(){return[...this._items.keys()]}values(){return[...this._items.values()]}items(){return[...this._items.entries()]}pop(e){const t=this._items.get(e);return this._items.delete(e),t}}const v=l=>{if(l._formula!==void 0)return l._formula;const e=l._value;return typeof e=="number"&&S(l._look.format)?se(e):ne(e)};function J(l){if(l._formula!==void 0)return l._formula;const e=l._value;return e===null?null:typeof e=="number"&&!S(l._look.format)||typeof e=="boolean"?e:v(l)}const Te=l=>l.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/gu,"")||"rows";export class Worksheet{_parent;_title;_was;_model;_cells=new Map;_columns=new Map;_rows=new Map;_tables=new TableList;_freeze;_merges=[];_state="visible";_dimensions=!1;_lastRow=0;_rules=[];_validations=[];_filter;_charts=[];constructor(e,t,s){if(this._parent=e,this._title=t,this._filter=new I(void 0,()=>{this._parent._pending=!0}),s){this._model=s,this._was=t,this._freeze=s.spec.freeze,this._merges=[...s.spec.merges??[]],this._state=s.spec.hidden===!0?"hidden":"visible",this._lastRow=(s.used?.bottom??-1)+1,this._heldRules(s.spec);for(const o of s.tables){const n=new Table({displayName:o.name,ref:x(o.area),...o.spec.key===void 0?{}:{key:o.spec.key}});n._spec=o.spec;const{filter:r}=o.spec;if(r)for(const[a,f]of Object.entries(r.columns)){const u=o.column(a);u&&n.autoFilter._columns.set(u.index,f)}this._tables.add(n)}}return g(this,"Worksheet",w,{index:o=>this._rowCells(o),key:o=>this._at(o),setKey:(o,n)=>{const r=b(o);return r?(this.cell(r.row+1,r.col+1).value=n,!0):!1}})}_spec(){return this._parent._file.sheets.find(e=>e.name===(this._was??this._title))}_heldRules(e){this._rules=[...e?.conditional??[]],this._validations=(e?.validations??[]).map(_e),this._charts=(e?.charts??[]).map(fe),this._filter.ref=e?.filter?.range,this._filter._columns.clear();const t=e?.filter?k(e.filter.range):void 0;for(const[s,o]of Object.entries(e?.filter?.columns??{})){const n=E(s);t&&n!==void 0&&this._filter._columns.set(n-t.left,o)}}_at(e){const t=b(e);if(t)return this.cell(t.row+1,t.col+1);const s=k(e);if(s)return this._area(s);const o=E(e);if(o!==void 0){const n=[];for(let r=1;r<=this.max_row;r++)n.push(this.cell(r,o+1));return n}}_rowCells(e){const t=[];for(let s=1;s<=this.max_column;s++)t.push(this.cell(e,s));return t}_area(e){const t=[];for(let s=e.top;s<=e.bottom;s++){const o=[];for(let n=e.left;n<=e.right;n++)o.push(this.cell(s+1,n+1));t.push(o)}return t}get parent(){return this._parent}get title(){return this._title}set title(e){const t=this._title;e!==t&&this._parent._renameSheet(this,t,e)}get sheet_state(){return this._state}set sheet_state(e){this._state=e}cell(e,t,s){if(e<1||t<1)throw new RangeError(`Row and column values must be at least 1: ${String(e)}, ${String(t)}.`);const o=(e-1)*16384+t-1;let n=this._cells.get(o);return n||(n=new Cell(this,e,t),this._cells.set(o,n)),s!==void 0&&(n.value=s),e>this._lastRow&&(this._lastRow=e),n}append(e){const t=this._lastRow+1,s=(o,n)=>{n!=null&&this.cell(t,o,n)};if(Array.isArray(e))e.forEach((o,n)=>{s(n+1,o)});else for(const[o,n]of Object.entries(e)){const r=/^\d+$/u.test(o)?Number(o)-1:E(o);if(r===void 0)throw new TypeError(`${o} is not a column.`);s(r+1,n)}this._lastRow=t}get max_row(){return Math.max(1,this._lastRow)}get max_column(){let e=this._model?.columnsUsed??0;for(const t of this._cells.values())(t._value!==null||t._formula!==void 0)&&t.column>e&&(e=t.column);return Math.max(1,e)}min_row=1;min_column=1;get dimensions(){return x({top:0,left:0,bottom:this.max_row-1,right:this.max_column-1})}iter_rows(e={}){const t=this._area({top:(e.min_row??1)-1,left:(e.min_col??1)-1,bottom:(e.max_row??this.max_row)-1,right:(e.max_col??this.max_column)-1});return e.values_only===!0?t.map(s=>s.map(o=>o.value)):t}iter_cols(e={}){const t=this.iter_rows(e);return(t[0]??[]).map((o,n)=>t.map(r=>r[n]))}get rows(){return this.iter_rows()}get columns(){return this.iter_cols()}get values(){return this.iter_rows({values_only:!0})}insert_rows(e,t=1){this._parent._restructure({op:"insert-rows",sheet:this._title,at:y(e,"row")-1,count:y(t,"amount")})}delete_rows(e,t=1){this._parent._restructure({op:"delete-rows",sheet:this._title,at:y(e,"row")-1,count:y(t,"amount")})}insert_cols(e,t=1){this._parent._restructure({op:"insert-columns",sheet:this._title,at:y(e,"column")-1,count:y(t,"amount")})}delete_cols(e,t=1){this._parent._restructure({op:"delete-columns",sheet:this._title,at:y(e,"column")-1,count:y(t,"amount")})}merge_cells(e){if(!k(e))throw new TypeError(`${e} is not a range.`);this._merges.includes(e)||this._merges.push(e),this._parent._pending=!0}unmerge_cells(e){this._merges=this._merges.filter(t=>t!==e),this._parent._pending=!0}get merged_cells(){return[...this._merges]}get freeze_panes(){return this._freeze}set freeze_panes(e){const t=e instanceof Cell?e.coordinate:e;if(t!==void 0&&!b(t))throw new TypeError(`${t} is not a cell.`);this._freeze=t,this._parent._pending=!0}get column_dimensions(){return new Proxy({},{get:(e,t)=>{if(typeof t!="string")return;const s=t.toUpperCase();if(E(s)===void 0)throw new TypeError(`${t} is not a column.`);let o=this._columns.get(s);return o||(o=new ColumnDimension(this,s),this._columns.set(s,o)),o}})}get row_dimensions(){return new Proxy({},{get:(e,t)=>{if(typeof t!="string"||!/^[1-9]\d*$/u.test(t))throw new TypeError(`${String(t)} is not a row.`);const s=Number(t);let o=this._rows.get(s);return o||(o=new RowDimension(this,s),this._rows.set(s,o)),o}})}get tables(){return this._tables}get conditional_formatting(){return new ce(this._rules,()=>{this._parent._pending=!0})}get data_validations(){return new ue(this._validations,()=>{this._parent._pending=!0})}add_data_validation(e){this._validations.push(e),this._parent._pending=!0}get auto_filter(){return this._filter}add_chart(e,t){e.anchor=he(t)??e.anchor,this._charts.push(e),this._parent._pending=!0}add_table(e){if(this._parent._tableNamed(e.name))throw new Error(`There is already a table named ${e.name}.`);this._tables.add(e),this._parent._pending=!0}}export class Workbook{worksheets=[];defined_names=new DefinedNameDict;data_only;title;path;block_cells=BLOCK_CELLS;_file={sheets:[]};_text="";_disk={text:"",csv:new Map};_csv=new Map;_model;_names=new Map;_active=0;_pending=!1;_making=!1;_calc=void 0;constructor(e={}){this.data_only=e.data_only??!1;const t=g(this,"Workbook",w,{key:s=>this.worksheets.find(o=>o.title===s),index:s=>this.worksheets[s]});return t.worksheets=[new Worksheet(t,"Sheet")],t}static open(e,t={}){const s=new Workbook(t);return s.path=e,s._read(e),s}_read(e){const{readFileSync:t}=K(),s=t($(e,z),"utf8"),o=new Map,n=r=>{try{const a=t($(e,r),"utf8");return o.set(r,a),a}catch{return}};this._load(s,n);for(const[r,a]of o)this._keepCsv(r,a);this._disk={text:s,csv:o}}_keepCsv(e,t){const s=V(t);this._csv.set(e,{parsed:s,rows:s.records.map(o=>o.end===o.start?[]:[...o.fields])})}_load(e,t){const{workbook:s,problems:o}=B({text:e,read:t});if(!s)throw new Error(`sheet.yaml cannot be opened: ${o.map(n=>n.message).join("; ")}`);this._text=e,this._file=structuredClone(s.file),this._model=s,this.title=s.title,this.worksheets=s.sheets.map(n=>new Worksheet(this,n.name,n));for(const n of s.names.values()){if(n.source.path?.[0]!=="names")continue;const r=n.formula?n.formula.text:n.value??null;this._names.set(n.name,r),this.defined_names.add(new DefinedName(n.name,{attr_text:String(r)}))}}get active(){const e=this.worksheets[this._active]??this.worksheets[0];if(!e)throw new Error("The workbook has no sheets.");return e}set active(e){this._active=this.worksheets.indexOf(e)}get sheetnames(){return this.worksheets.map(e=>e.title)}get_sheet_by_name(e){return this.worksheets.find(t=>t.title===e)}index(e){return this.worksheets.indexOf(e)}create_sheet(e,t){let s=e??"Sheet";for(let n=1;this.worksheets.some(r=>r.title===s);n++)s=`${e??"Sheet"}${String(n)}`;const o=new Worksheet(this,s);return this.worksheets.splice(t??this.worksheets.length,0,o),this._pending=!0,o}remove(e){this.worksheets=this.worksheets.filter(t=>t!==e),this._pending=!0}move_sheet(e,t=0){const s=this.worksheets.indexOf(e);this.worksheets.splice(s,1),this.worksheets.splice(s+t,0,e),this._pending=!0}_tableNamed(e){for(const t of this.worksheets){const s=t._tables.get(e);if(s)return s}}_renameSheet(e,t,s){if(this.worksheets.some(n=>n!==e&&n.title===s))throw new Error(`There is already a sheet named ${s}.`);this._apply(),this._rewrite({op:"rename-sheet",from:t,to:s}),e._title=s,e._was=s;const o=this._file.sheets.find(n=>n.name===t);o&&(o.name=s),this._apply()}_restructure(e){this._apply();const t=ie({file:this._file,rows:new Map([...this._csv].map(([o,n])=>[o,n.rows]))},e);if(t.refused!==void 0)throw new Error(t.refused==="table-header"?"A table's header row is not deleted: delete the table's rows, or all of it.":"That sheet is not there.");this._file=t.file;for(const[o,n]of t.rows){const r=this._csv.get(o);r&&(r.rows=n.map(a=>[...a]))}for(const o of this.worksheets){const n=this._file.sheets.find(r=>r.name===o._title);o._cells.clear(),o._columns.clear(),o._rows.clear(),o._merges=[...n?.merges??[]],o._freeze=n?.freeze,o._heldRules(n)}const s=this._build();this._rebase(s.text,s.files);for(const o of this.worksheets){const n=this._model?.sheet(o._title);if(n){o._lastRow=(n.used?.bottom??-1)+1;for(const r of n.tables){const a=o._tables.get(r.name);a&&(a.ref=x(r.area))}}}}_rewrite(e){const t=(o,n)=>{const r=F(o);if(!r.ok)return o;const a=Z(r.node,e,n);return a===r.node?o:A(a)},{_file:s}=this;if(s.names){for(const[o,n]of Object.entries(s.names))if(typeof n=="string"&&n.startsWith("=")){const r=t(n,s.sheets[0]?.name??"");s.names[o]=r,this._names.set(o,r);const a=this.defined_names.get(o);a&&(a.attr_text=r.slice(1))}}for(const o of s.checks??[])o.formula=t(o.formula,s.sheets[0]?.name??"");for(const o of s.sheets){for(const[n,r]of Object.entries(o.cells??{}))typeof r=="string"&&r.startsWith("=")?o.cells[n]=t(r,o.name):r!==null&&typeof r=="object"&&r.formula!==void 0&&(r.formula=t(r.formula,o.name));for(const n of o.tables??[]){for(const r of Object.values(n.columns??{}))r.formula!==void 0&&(r.formula=t(r.formula,o.name));this._rewriteCsv(n.rows,o.name,t)}for(const n of o.blocks??[])this._rewriteCsv(n.rows,o.name,t)}}_rewriteCsv(e,t,s){const o=this._csv.get(e);o&&(o.rows=o.rows.map(n=>n.map(r=>M(r).formula!==void 0?s(r,t):r)))}_sheetEntry(e){const t=e._was??e._title;let s=this._file.sheets.find(o=>o.name===t);return s||(s={name:e._title},this._file.sheets.push(s)),s.name=e._title,s}_dataPath(e){const t=`${H}/${Te(e)}`;let s=`${t}.csv`;const o=n=>this._csv.has(n)||this._file.sheets.some(r=>r.tables?.some(a=>a.rows===n)??r.blocks?.some(a=>a.rows===n));for(let n=2;o(s);n++)s=`${t}-${String(n)}.csv`;return s}_writeNewTable(e,t,s){const o=k(s.ref);if(!o)throw new Error(`${s.ref} is not a range.`);const n=[];for(let i=o.left;i<=o.right;i++){const h=e.cell(o.top+1,i+1).value;if(h===null||h==="")throw new Error(`Table ${s.name}'s header has no name at ${C({row:o.top,col:i})}.`);n.push(String(h))}const r={},a=[];n.forEach((i,h)=>{const c=o.left+h,d=this._columnFormula(e,o,c);d===void 0?a.push(h):r[i]={formula:d};const m=this._columnFormat(e,o,c);m!==void 0&&(r[i]={...r[i],format:m})}),this._columnsStyled(e,o);const f=[a.map(i=>n[i]??"")];for(let i=o.top+1;i<=o.bottom;i++)f.push(a.map(h=>v(e.cell(i+1,o.left+h+1))));t.cells&&(t.cells=Object.fromEntries(Object.entries(t.cells).filter(([i])=>{const h=b(i);return!h||!L(o,h.row,h.col)})));const u=this._dataPath(s.name);this._csv.set(u,{parsed:void 0,rows:f});const _={name:s.name,at:C({row:o.top,col:o.left}),rows:u,...s.key===void 0?{}:{key:s.key},...p(r)?{}:{columns:r}};(t.tables??=[]).push(_),s._spec=_}_columnsStyled(e,t){for(let s=t.left;s<=t.right;s++)for(let o=t.top+1;o<=t.bottom;o++){const n=e.cell(o+1,s+1),{format:r,...a}=this._ownLook(n);r!==void 0&&p(a)&&(n._styled=!1)}}_columnFormula(e,t,s){if(t.bottom<=t.top)return;const o=e.cell(t.top+2,s+1),n=D(o);if(n!==void 0){for(let r=t.top+2;r<=t.bottom;r++)if(D(e.cell(r+1,s+1))!==n)return;return o._formula}}_columnFormat(e,t,s){if(t.bottom<=t.top)return;const o=r=>this._ownLook(e.cell(r+1,s+1)).format,n=o(t.top+1);for(let r=t.top+2;r<=t.bottom;r++)if(o(r)!==n)return;return n}_held(e){const t=this._csv.get(e);if(!t)throw new Error(`${e} was not read.`);return t}_setCsvCell(e,t,s,o){const{rows:n}=this._held(e);for(;n.length<=t;)n.push([]);const r=n[t];if(r){for(;r.length<=s;)r.push("");r[s]=o}}_recordOf(e,t){let s=0;for(let o=0;o<t;){if(s+=1,s>=e.length)return s+t-o-1;e[s]?.length!==0&&(o+=1)}return s}_writeTableCell(e,t,s){const o=this._held(e.rows),n=o.rows[0]??[],r=s.column-1-t.left,a=this._recordOf(o.rows,s.row-1-t.top),f=Object.keys(e.columns??{}).filter(c=>!n.some(d=>d.trim().toLowerCase()===c.toLowerCase())),_=[...n.map(c=>c.trim()),...f][r];if(_===void 0)return;if(a===0){r<n.length&&(n[r]=v(s));return}const i=e.columns?.[_]?.formula;if(i!==void 0){const c=this._movedColumn(i,t,s);if(s._formula===c){const d=n.findIndex(m=>m.trim()===_);d>=0&&this._setCsvCell(e.rows,a,d,"");return}}let h=n.findIndex(c=>c.trim()===_);h<0&&(h=n.length,this._setCsvCell(e.rows,0,h,_)),this._setCsvCell(e.rows,a,h,v(s))}_movedColumn(e,t,s){const o=F(e);if(!o.ok)return e;const n=s.row-1-(t.top+1);return n===0?e:A(Q(o.node,n,0))}_apply(){this.title===void 0?delete this._file.title:this._file.title=this.title;const e=new Set(this.worksheets.map(s=>s._was??s._title));this._file.sheets=this._file.sheets.filter(s=>e.has(s.name));for(const s of this.worksheets)this._applySheet(s);this._file.sheets=this.worksheets.map(s=>this._sheetEntry(s)),this._applyNames();const t=this._build();this._rebase(t.text,t.files)}_applyNames(){const e={};for(const t of this.defined_names.values()){const s=M(t.attr_text),o=this._names.get(t.name);e[t.name]=o!==void 0&&String(o).replace(/^=/u,"")===t.attr_text?o:typeof s.value=="number"||typeof s.value=="boolean"?s.value:/^"[^"]*"$/u.test(t.attr_text)?t.attr_text.slice(1,-1):`=${t.attr_text}`}p(e)?delete this._file.names:this._file.names=e}_applySheet(e){const t=this._sheetEntry(e);e._freeze===void 0?delete t.freeze:t.freeze=e._freeze,e._merges.length===0?delete t.merges:t.merges=[...e._merges],e._state==="hidden"?t.hidden=!0:delete t.hidden,e._rules.length===0?delete t.conditional:t.conditional=[...e._rules],e._validations.length===0?delete t.validations:t.validations=e._validations.map(de),e._charts.length===0?delete t.charts:t.charts=e._charts.map(o=>o._spec(e._title)),this._applyFilter(e,t);const s=new Set(t.tables?.map(o=>o.name.toLowerCase()));for(const o of e._tables.values())s.has(o.name.toLowerCase())||this._writeNewTable(e,t,o);this._applyTableFilters(e,t),this._applyCells(e,t),this._applyDimensions(e,t),t.cells&&p(t.cells)&&delete t.cells,t.columns&&p(t.columns)&&delete t.columns,t.rows&&p(t.rows)&&delete t.rows,t.format?.length===0&&delete t.format,t.tables?.length===0&&delete t.tables,t.blocks?.length===0&&delete t.blocks}_applyFilter(e,t){const{ref:s,_columns:o}=e._filter;if(s===void 0){delete t.filter;return}const n=k(s);if(!n)throw new TypeError(`${s} is not a range.`);const r={};for(const[a,f]of o)r[N(n.left+a)]=f;t.filter={range:s,...p(r)?{}:{columns:r}}}_applyTableFilters(e,t){for(const s of t.tables??[]){const o=e._tables.get(s.name);if(!o||o.autoFilter._columns.size===0)continue;const n=this._csv.get(s.rows)?.rows??[],r=le(s,n)?.names??[],a={};for(const[f,u]of o.autoFilter._columns){const _=r[f];if(_===void 0)throw new RangeError(`Table ${s.name} has no column at ${String(f)}.`);a[_]=u}s.filter={columns:a}}}_applyDimensions(e,t){if(e._dimensions){for(const[s,o]of e._columns){const n={...t.columns?.[s]};o._width===void 0?delete n.width:n.width=o._width,o._hidden===void 0?delete n.hidden:n.hidden=o._hidden,o._files===void 0?delete n.files:n.files=o._files;const r=j(t.columns??{},s);t.columns=p(n)?r:{...r,[s]:n}}for(const[s,o]of e._rows){const n={...t.rows?.[String(s)]};o._height===void 0?delete n.height:n.height=o._height,o._hidden===void 0?delete n.hidden:n.hidden=o._hidden;const r=j(t.rows??{},String(s));t.rows=p(n)?r:{...r,[String(s)]:n}}e._dimensions=!1}}_applyCells(e,t){const s=(t.tables??[]).flatMap(r=>{const a=b(r.at),f=e._tables.get(r.name),u=f?k(f.ref):void 0;return a&&u?[{entry:r,area:u}]:[]}),o=(t.blocks??[]).flatMap(r=>{const a=e._model?.blocks.find(f=>f.file===r.rows);return a?[{entry:r,area:a.area}]:[]}),n=[];for(const r of e._cells.values()){if(!r._changed&&!r._styled)continue;const a=r.row-1,f=r.column-1,u=s.find(i=>L(i.area,a,f)),_=o.find(i=>L(i.area,a,f));u?(r._changed&&this._writeTableCell(u.entry,u.area,r),r._styled&&this._styleByFormat(t,r)):_?(r._changed&&this._setCsvCell(_.entry.rows,a-_.area.top,f-_.area.left,v(r)),r._styled&&this._styleByFormat(t,r)):r._fresh&&!e._model?.keys.has(a*16384+f)?n.push(r):this._writeLoose(e,t,r),r._changed=!1,r._styled=!1}this._consolidate(e,t,n),Oe(t)}_styleByFormat(e,t){(e.format??=[]).push({range:t.coordinate,...this._ownLook(t)})}_ownLook(e){const t=e._ws._model?.lookAt(e.row-1,e.column-1)??{},s=Ce(t,e._look);return s.format!==void 0&&e._formula===void 0&&M(v(e)).format===s.format&&delete s.format,s}_writeLoose(e,t,s){const o=s.coordinate,n=t.cells??={},r=J(s),a=this._ownLook(s),f=n[o],_={...f!==null&&typeof f=="object"?Object.fromEntries(Object.entries(f).filter(([c])=>c!=="value"&&c!=="formula"&&c!=="name")):{},...a},i=f!==null&&typeof f=="object"&&f.name!==void 0?{name:f.name}:{},h=e._model?.at(s.row-1,s.column-1)!==void 0;if(r===null&&p(_)&&!h){t.cells=j(n,o);return}n[o]=p(_)&&p(i)?r:{...typeof r=="string"&&r.startsWith("=")?{formula:r}:r===null?{}:{value:r},...i,..._}}_consolidate(e,t,s){const o=s.filter(i=>i._value!==null||i._formula!==void 0),n=new Map;for(const i of s){const h=this._ownLook(i);if(p(h))continue;const c=JSON.stringify(h),d=n.get(c);d?d.push(i):n.set(c,[i])}const r=new Map(o.map(i=>[`${String(i.row)}:${String(i.column)}`,i])),a=i=>r.get(`${String(i.row+1)}:${String(i.col+1)}`)??e.cell(i.row+1,i.col+1),f=new Map,u=[];for(const i of o){const h={row:i.row-1,col:i.column-1},c=i._formula===void 0?void 0:D(i);if(c===void 0){u.push(h);continue}const d=f.get(c);d?d.push(h):f.set(c,[h])}const _=t.cells??={};for(const i of f.values())for(const h of T(i))_[x(h)]=a({row:h.top,col:h.left})._formula??null;for(const i of T(u))if((i.bottom-i.top+1)*(i.right-i.left+1)>=this.block_cells){const c=[];for(let m=i.top;m<=i.bottom;m++){const R=[];for(let O=i.left;O<=i.right;O++)R.push(v(a({row:m,col:O})));c.push(R)}const d=this._dataPath(e._title);this._csv.set(d,{parsed:void 0,rows:c}),(t.blocks??=[]).push({at:C({row:i.top,col:i.left}),rows:d})}else for(let c=i.top;c<=i.bottom;c++)for(let d=i.left;d<=i.right;d++){const m=a({row:c,col:d});_[m.coordinate]=J(m)}for(const i of n.values()){const[h]=i;if(!h)continue;const c=this._ownLook(h),d=i.map(m=>({row:m.row-1,col:m.column-1}));for(const m of T(d))(t.format??=[]).push({range:x(m),...c})}}_build(){const e=new Map;for(const[t,s]of this._csv)e.set(t,s.parsed?ee(s.parsed,s.rows):Y(s.rows));return{text:ae(this._text,this._file),files:e}}_rebase(e,t){const{workbook:s,problems:o}=B({text:e,read:n=>t.get(n)});if(!s)throw new Error(`The workbook is not one: ${o.map(n=>n.message).join("; ")}`);this._text=e,this._file=structuredClone(s.file),this._model=s;for(const[n,r]of t)this._keepCsv(n,r);this._calc=void 0,this._pending=!1;for(const n of this.worksheets){n._was=n._title;const r=s.sheet(n._title);r&&(n._model=r);for(const a of n._cells.values())a._fresh=r?.at(a.row-1,a.column-1)===void 0}this._names=new Map;for(const n of s.names.values())n.source.path?.[0]==="names"&&this._names.set(n.name,n.formula?n.formula.text:n.value??null)}_computed(){const e=[...this.defined_names.values()];if((this._pending||e.length!==this._names.size||e.some(t=>String(this._names.get(t.name)).replace(/^=/u,"")!==t.attr_text))&&this._apply(),!this._calc){const t=this._model;if(!t)throw new Error("The workbook has no sheets.");this._calc={calc:new U(t).calculate(),model:t}}return this._calc}check(){this._apply();const{text:e,files:t}=this._build();return G({text:e,read:s=>t.get(s)}).problems}_generated(){if(this.worksheets.length===0)return this._applyNames(),{sheets:[],csv:{},...this._file.names?{names:this._file.names}:{}};this._apply();const e=structuredClone(this._file.sheets),t=o=>`${q}${o}`;for(const o of e){for(const n of o.tables??[])n.rows=t(n.rows);for(const n of o.blocks??[])n.rows=t(n.rows)}const s={};for(const[o,n]of this._build().files)s[t(o)]=n;return{sheets:e,csv:s,...this._file.names?{names:this._file.names}:{}}}save(e){if(this._making)throw new Error("sheet.ts makes sheets and saves nothing: what it adds to wb is what it makes.");const t=e??this.path;if(t===void 0)throw new TypeError("A new workbook is saved to a folder: wb.save('content/budget').");if(this.worksheets.length===0)throw new Error("A workbook has at least one sheet.");const{text:s,csv:o}=this._disk;this._apply();const n=new Set(this._file.sheets.flatMap(i=>[...(i.tables??[]).map(h=>h.rows),...(i.blocks??[]).map(h=>h.rows)])),r=[...this._csv.keys()].filter(i=>!n.has(i));for(const i of r)this._csv.delete(i);const{mkdirSync:a,rmSync:f,writeFileSync:u}=K(),_=process.getBuiltinModule("node:path");a(t,{recursive:!0}),(this._text!==s||e!==void 0)&&u($(t,z),this._text);for(const[i,h]of this._csv){const c=h.parsed?.source??"";if(e===void 0&&o.get(i)===c)continue;const d=$(t,i);a(_.dirname(d),{recursive:!0}),u(d,c)}if(e===void 0||t===this.path)for(const i of r)f($(t,i),{force:!0});this._disk={text:this._text,csv:new Map([...this._csv].map(([i,h])=>[i,h.parsed?.source??""]))},this.path=t}}function D(l){if(l._formula===void 0)return;const e=F(l._formula);if(e.ok)return X(e.node,l.row-1,l.column-1)}function Oe(l){const e=l.format;if(!e||e.length<2)return;const t=[],s=new Map;for(const o of e){const{range:n,...r}=o,a=b(n);if(!a){t.push(o);continue}const f=JSON.stringify(r),u=s.get(f);u?u.places.push(a):s.set(f,{look:r,places:[a]})}for(const{look:o,places:n}of s.values())for(const r of T(n))t.push({range:x(r),...o});l.format=t}export function load_workbook(l,e={}){return Workbook.open(l,e)}export const get_column_letter=l=>N(l-1);export function column_index_from_string(l){const e=E(l);if(e===void 0)throw new TypeError(`${l} is not a column.`);return e+1}export function coordinate_to_tuple(l){const e=b(l);if(!e)throw new TypeError(`${l} is not a cell.`);return[e.row+1,e.col+1]}export function range_boundaries(l){const e=k(l);if(!e)throw new TypeError(`${l} is not a range.`);return[e.left+1,e.top+1,e.right+1,e.bottom+1]}
|
|
2
|
+
import{SHEET_DATA as G,SHEET_FILE as P,strict as g}from"@allyhub-next/formats";import{Comment as z,HeaderFooter as A,PageMargins as V,PageSetup as Y,SheetProtection as q}from"./page.js";import{columnIndex as E,columnLetter as L,cellName as C,contains as N,rangeName as x,readAddress as y,readArea as k}from"../address.js";import{Calc as Q}from"../calc/engine.js";import{checkWorkbook as X}from"../check.js";import{readCsv as Z,writeCsv as ee}from"../csv.js";import{GENERATED as te}from"../generated.js";import{moveFormula as se,relativeKey as ne}from"../formula/move.js";import{parseFormula as F}from"../formula/parse.js";import{printFormula as B}from"../formula/print.js";import{rewriteFormula as oe}from"../formula/rewrite.js";import{isDateCode as S}from"../format.js";import{patchCsv as re}from"../patch.js";import{CellError as W,dateOfSerial as ie,isoOfSerial as le,readTyped as M,serialOfDate as ae,writeTyped as he}from"../values.js";import{FormulaCell as fe,readWorkbook as I,validName as H}from"../workbook.js";import{restructure as _e,tableShape as ce}from"../structure.js";import{patchYaml as ue}from"../write.js";import{anchorOf as de,chartOfSpec as me}from"./charts.js";import{HINT as w}from"./hint.js";import{rectangles as T}from"./rectangles.js";import{AutoFilter as K,ConditionalFormattingList as pe,DataValidationList as we,validationOf as ge,validationSpec as ke}from"./rules.js";import{alignmentLook as ye,alignmentOf as be,borderLook as ve,borderOf as xe,fillLook as Ee,fillOf as Se,fontLook as $e,fontOf as Ce}from"./styles.js";const J=()=>process.getBuiltinModule("node:fs"),$=(...l)=>process.getBuiltinModule("node:path").join(...l);export const BLOCK_CELLS=100;const Te=l=>Math.round(l*7+5),Oe=l=>(l-5)/7,Le=l=>l*4/3,Ne=l=>l*3/4;function Fe(l,e){const t={},s=l,n=e;for(const o of new Set([...Object.keys(s),...Object.keys(n)])){const r=n[o];JSON.stringify(r??!1)!==JSON.stringify(s[o]??!1)&&(t[o]=r??!1)}return t}const m=l=>Object.keys(l).length===0,b=(l,e)=>{if(!Number.isInteger(l)||l<1)throw new RangeError(`A ${e} is a whole number from 1: ${String(l)}.`);return l},j=(l,e)=>Object.fromEntries(Object.entries(l).filter(([t])=>t!==e));export class Cell{row;column;_ws;_value;_formula=void 0;_look;_changed=!1;_styled=!1;_fresh=!1;constructor(e,t,s){this._ws=e,this.row=t,this.column=s;const n=t-1,o=s-1,r=e._model?.at(n,o);return this._value=null,r instanceof fe?this._formula=r.text:r!==void 0&&(this._value=r),this._look=e._model?.lookAt(n,o)??{},this._fresh=r===void 0,g(this,"Cell",w)}get parent(){return this._ws}get coordinate(){return C({row:this.row-1,col:this.column-1})}get column_letter(){return L(this.column-1)}get col_idx(){return this.column}get value(){return this._ws.parent.data_only?this.computed:this._formula!==void 0?this._formula:this._shown(this._value)}set value(e){if(e===void 0)throw new TypeError(`${this.coordinate}: a value is not undefined.`);if(this._formula=void 0,this._changed=!0,this._ws.parent._pending=!0,e instanceof Date){if(Number.isNaN(e.getTime()))throw new TypeError(`${this.coordinate}: the date is not valid.`);this._value=ae(e),S(this._look.format)||(this._look={...this._look,format:Number.isInteger(this._value)?"yyyy-mm-dd":"yyyy-mm-dd hh:mm"});return}if(typeof e=="string"&&e.length>1&&e.startsWith("=")){this._formula=e,this._value=null;return}this._value=e}_shown(e){return typeof e=="number"&&S(this._look.format)?ie(e)??e:e instanceof W?e.code:e}get computed(){const{calc:e,model:t}=this._ws.parent._computed(),s=t.sheet(this._ws.title);return s?this._shown(e.value(s,this.row-1,this.column-1)):null}get data_type(){if(this._formula!==void 0)return"f";const e=this._value;return e===null?"n":typeof e=="number"?S(this._look.format)?"d":"n":typeof e=="boolean"?"b":e instanceof W?"e":"s"}get is_date(){return this.data_type==="d"}get hyperlink(){return this._ws._links[this.coordinate]}set hyperlink(e){e===void 0?Reflect.deleteProperty(this._ws._links,this.coordinate):this._ws._links[this.coordinate]=e,this._ws._changed()}get comment(){const e=this._ws._notes[this.coordinate];if(e!==void 0)return typeof e=="string"?new z(e):new z(e.text,e.author)}set comment(e){e===void 0?Reflect.deleteProperty(this._ws._notes,this.coordinate):this._ws._notes[this.coordinate]=e._file(),this._ws._changed()}get number_format(){return this._look.format??"General"}set number_format(e){this._setLook({format:e})}_setLook(e){this._look={...this._look,...e},this._styled=!0,this._ws.parent._pending=!0}get font(){return Ce(this._look)}set font(e){this._setLook($e(e))}get fill(){return Se(this._look)}set fill(e){this._setLook(Ee(e))}get border(){return xe(this._look)}set border(e){this._setLook(ve(e))}get alignment(){return be(this._look)}set alignment(e){this._setLook(ye(e))}get has_style(){return!m(this._look)}offset(e=0,t=0){return this._ws.cell(this.row+e,this.column+t)}}export class ColumnDimension{index;_width;_hidden;_files;_level;_ws;constructor(e,t){this._ws=e,this.index=t;const s=e._spec()?.columns?.[t];return this._level=s?.level,this._width=s?.width,this._hidden=s?.hidden,this._files=s?.files,g(this,"ColumnDimension",w)}get outlineLevel(){return this._level}set outlineLevel(e){this._level=e,this._ws._dimensions=!0}get files(){return this._files}set files(e){this._files=e,this._ws._dimensions=!0}get width(){return this._width===void 0?void 0:Oe(this._width)}set width(e){this._width=e===void 0?void 0:Te(e),this._ws._dimensions=!0}get hidden(){return this._hidden??!1}set hidden(e){this._hidden=e,this._ws._dimensions=!0}}export class RowDimension{index;_height;_hidden;_level;_ws;constructor(e,t){this._ws=e,this.index=t;const s=e._spec()?.rows?.[String(t)];return this._level=s?.level,this._height=s?.height,this._hidden=s?.hidden,g(this,"RowDimension",w)}get outlineLevel(){return this._level}set outlineLevel(e){this._level=e,this._ws._dimensions=!0}get height(){return this._height===void 0?void 0:Ne(this._height)}set height(e){this._height=e===void 0?void 0:Le(e),this._ws._dimensions=!0}get hidden(){return this._hidden??!1}set hidden(e){this._hidden=e,this._ws._dimensions=!0}}export class Table{displayName;ref;key;_spec;autoFilter;constructor(e){for(const t of Object.keys(e))if(!["displayName","ref","key"].includes(t))throw new TypeError(`Table takes displayName, ref and key; it has no ${t}. ${w}`);if(!H(e.displayName))throw new TypeError(`${e.displayName} cannot be a table's name.`);if(!k(e.ref))throw new TypeError(`${e.ref} is not a range.`);return this.displayName=e.displayName,this.ref=e.ref,this.key=e.key,this.autoFilter=new K(e.ref,()=>{}),g(this,"Table",w)}get name(){return this.displayName}}export class TableList{_items=new Map;constructor(){return g(this,"TableList",w,{key:e=>this._items.get(e)})}add(e){this._items.set(e.name,e)}get(e){return this._items.get(e)}keys(){return[...this._items.keys()]}values(){return[...this._items.values()]}items(){return[...this._items.entries()]}pop(e){const t=this._items.get(e);return this._items.delete(e),t}}export class DefinedName{name;attr_text;constructor(e,t){if(!H(e))throw new TypeError(`${e} cannot be a name.`);return this.name=e,this.attr_text=t.attr_text.replace(/^=/u,""),g(this,"DefinedName",w)}get value(){return this.attr_text}set value(e){this.attr_text=e.replace(/^=/u,"")}}export class DefinedNameDict{_items=new Map;constructor(){return g(this,"DefinedNameDict",w,{key:e=>this._items.get(e),setKey:(e,t)=>t instanceof DefinedName?(this._items.set(e,t),!0):!1})}add(e){this._items.set(e.name,e)}get(e){return this._items.get(e)}keys(){return[...this._items.keys()]}values(){return[...this._items.values()]}items(){return[...this._items.entries()]}pop(e){const t=this._items.get(e);return this._items.delete(e),t}}const v=l=>{if(l._formula!==void 0)return l._formula;const e=l._value;return typeof e=="number"&&S(l._look.format)?le(e):he(e)};function U(l){if(l._formula!==void 0)return l._formula;const e=l._value;return e===null?null:typeof e=="number"&&!S(l._look.format)||typeof e=="boolean"?e:v(l)}const Me=l=>l.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/gu,"")||"rows";export class Worksheet{_parent;_title;_was;_model;_cells=new Map;_columns=new Map;_rows=new Map;_tables=new TableList;_freeze;_merges=[];_state="visible";_dimensions=!1;_lastRow=0;_rules=[];_validations=[];_filter;_charts=[];_print={};_links={};_notes={};_pictures=[];_protect=!1;constructor(e,t,s){if(this._parent=e,this._title=t,this._filter=new K(void 0,()=>{this._parent._pending=!0}),s){this._model=s,this._was=t,this._freeze=s.spec.freeze,this._heldPage(s.spec),this._merges=[...s.spec.merges??[]],this._state=s.spec.hidden===!0?"hidden":"visible",this._lastRow=(s.used?.bottom??-1)+1,this._heldRules(s.spec);for(const n of s.tables){const o=new Table({displayName:n.name,ref:x(n.area),...n.spec.key===void 0?{}:{key:n.spec.key}});o._spec=n.spec;const{filter:r}=n.spec;if(r)for(const[a,f]of Object.entries(r.columns)){const c=n.column(a);c&&o.autoFilter._columns.set(c.index,f)}this._tables.add(o)}}return g(this,"Worksheet",w,{index:n=>this._rowCells(n),key:n=>this._at(n),setKey:(n,o)=>{const r=y(n);return r?(this.cell(r.row+1,r.col+1).value=o,!0):!1}})}_spec(){return this._parent._file.sheets.find(e=>e.name===(this._was??this._title))}_heldRules(e){this._rules=[...e?.conditional??[]],this._validations=(e?.validations??[]).map(ge),this._charts=(e?.charts??[]).map(me),this._filter.ref=e?.filter?.range,this._filter._columns.clear();const t=e?.filter?k(e.filter.range):void 0;for(const[s,n]of Object.entries(e?.filter?.columns??{})){const o=E(s);t&&o!==void 0&&this._filter._columns.set(o-t.left,n)}}_at(e){const t=y(e);if(t)return this.cell(t.row+1,t.col+1);const s=k(e);if(s)return this._area(s);const n=E(e);if(n!==void 0){const o=[];for(let r=1;r<=this.max_row;r++)o.push(this.cell(r,n+1));return o}}_rowCells(e){const t=[];for(let s=1;s<=this.max_column;s++)t.push(this.cell(e,s));return t}_area(e){const t=[];for(let s=e.top;s<=e.bottom;s++){const n=[];for(let o=e.left;o<=e.right;o++)n.push(this.cell(s+1,o+1));t.push(n)}return t}get parent(){return this._parent}get title(){return this._title}set title(e){const t=this._title;e!==t&&this._parent._renameSheet(this,t,e)}get sheet_state(){return this._state}set sheet_state(e){this._state=e}cell(e,t,s){if(e<1||t<1)throw new RangeError(`Row and column values must be at least 1: ${String(e)}, ${String(t)}.`);const n=(e-1)*16384+t-1;let o=this._cells.get(n);return o||(o=new Cell(this,e,t),this._cells.set(n,o)),s!==void 0&&(o.value=s),e>this._lastRow&&(this._lastRow=e),o}append(e){const t=this._lastRow+1,s=(n,o)=>{o!=null&&this.cell(t,n,o)};if(Array.isArray(e))e.forEach((n,o)=>{s(o+1,n)});else for(const[n,o]of Object.entries(e)){const r=/^\d+$/u.test(n)?Number(n)-1:E(n);if(r===void 0)throw new TypeError(`${n} is not a column.`);s(r+1,o)}this._lastRow=t}get max_row(){return Math.max(1,this._lastRow)}get max_column(){let e=this._model?.columnsUsed??0;for(const t of this._cells.values())(t._value!==null||t._formula!==void 0)&&t.column>e&&(e=t.column);return Math.max(1,e)}min_row=1;min_column=1;get dimensions(){return x({top:0,left:0,bottom:this.max_row-1,right:this.max_column-1})}iter_rows(e={}){const t=this._area({top:(e.min_row??1)-1,left:(e.min_col??1)-1,bottom:(e.max_row??this.max_row)-1,right:(e.max_col??this.max_column)-1});return e.values_only===!0?t.map(s=>s.map(n=>n.value)):t}iter_cols(e={}){const t=this.iter_rows(e);return(t[0]??[]).map((n,o)=>t.map(r=>r[o]))}get rows(){return this.iter_rows()}get columns(){return this.iter_cols()}get values(){return this.iter_rows({values_only:!0})}insert_rows(e,t=1){this._parent._restructure({op:"insert-rows",sheet:this._title,at:b(e,"row")-1,count:b(t,"amount")})}delete_rows(e,t=1){this._parent._restructure({op:"delete-rows",sheet:this._title,at:b(e,"row")-1,count:b(t,"amount")})}insert_cols(e,t=1){this._parent._restructure({op:"insert-columns",sheet:this._title,at:b(e,"column")-1,count:b(t,"amount")})}delete_cols(e,t=1){this._parent._restructure({op:"delete-columns",sheet:this._title,at:b(e,"column")-1,count:b(t,"amount")})}merge_cells(e){if(!k(e))throw new TypeError(`${e} is not a range.`);this._merges.includes(e)||this._merges.push(e),this._parent._pending=!0}unmerge_cells(e){this._merges=this._merges.filter(t=>t!==e),this._parent._pending=!0}get merged_cells(){return[...this._merges]}get freeze_panes(){return this._freeze}set freeze_panes(e){const t=e instanceof Cell?e.coordinate:e;if(t!==void 0&&!y(t))throw new TypeError(`${t} is not a cell.`);this._freeze=t,this._parent._pending=!0}get column_dimensions(){return new Proxy({},{get:(e,t)=>{if(typeof t!="string")return;const s=t.toUpperCase();if(E(s)===void 0)throw new TypeError(`${t} is not a column.`);let n=this._columns.get(s);return n||(n=new ColumnDimension(this,s),this._columns.set(s,n)),n}})}get row_dimensions(){return new Proxy({},{get:(e,t)=>{if(typeof t!="string"||!/^[1-9]\d*$/u.test(t))throw new TypeError(`${String(t)} is not a row.`);const s=Number(t);let n=this._rows.get(s);return n||(n=new RowDimension(this,s),this._rows.set(s,n)),n}})}get tables(){return this._tables}get conditional_formatting(){return new pe(this._rules,()=>{this._parent._pending=!0})}get data_validations(){return new we(this._validations,()=>{this._parent._pending=!0})}add_data_validation(e){this._validations.push(e),this._parent._pending=!0}get auto_filter(){return this._filter}_changed(){this._parent._pending=!0}_heldPage(e){this._print=structuredClone(e?.print??{}),this._links={...e?.links},this._notes={...e?.notes},this._pictures=[...e?.pictures??[]],this._protect=e?.protect===!0}get page_setup(){return new Y(this)}get page_margins(){return new V(this)}get oddHeader(){return new A(this,"header")}get oddFooter(){return new A(this,"footer")}get protection(){return new q(()=>this._protect,e=>{this._protect=e,this._changed()})}get print_area(){return this._print.area}set print_area(e){if(e===void 0)delete this._print.area;else if(k(e))this._print.area=e;else throw new TypeError(`${e} is not a range.`);this._changed()}get print_title_rows(){return this._print.title_rows}set print_title_rows(e){e===void 0?delete this._print.title_rows:this._print.title_rows=e,this._changed()}get print_title_cols(){return this._print.title_cols}set print_title_cols(e){e===void 0?delete this._print.title_cols:this._print.title_cols=e,this._changed()}add_image(e,t){const s=t??e.anchor??"A1";if(!y(s))throw new TypeError(`${s} is not a cell.`);this._pictures.push({file:e.path,at:s,...e.width===void 0?{}:{width:e.width},...e.height===void 0?{}:{height:e.height}}),this._changed()}add_chart(e,t){e.anchor=de(t)??e.anchor,this._charts.push(e),this._parent._pending=!0}add_table(e){if(this._parent._tableNamed(e.name))throw new Error(`There is already a table named ${e.name}.`);this._tables.add(e),this._parent._pending=!0}}export class Workbook{worksheets=[];defined_names=new DefinedNameDict;data_only;title;path;block_cells=BLOCK_CELLS;_file={sheets:[]};_text="";_disk={text:"",csv:new Map};_csv=new Map;_model;_names=new Map;_active=0;_pending=!1;_making=!1;_calc=void 0;constructor(e={}){this.data_only=e.data_only??!1;const t=g(this,"Workbook",w,{key:s=>this.worksheets.find(n=>n.title===s),index:s=>this.worksheets[s]});return t.worksheets=[new Worksheet(t,"Sheet")],t}static open(e,t={}){const s=new Workbook(t);return s.path=e,s._read(e),s}_read(e){const{readFileSync:t}=J(),s=t($(e,P),"utf8"),n=new Map,o=r=>{try{const a=t($(e,r),"utf8");return n.set(r,a),a}catch{return}};this._load(s,o);for(const[r,a]of n)this._keepCsv(r,a);this._disk={text:s,csv:n}}_keepCsv(e,t){const s=Z(t);this._csv.set(e,{parsed:s,rows:s.records.map(n=>n.end===n.start?[]:[...n.fields])})}_load(e,t){const{workbook:s,problems:n}=I({text:e,read:t});if(!s)throw new Error(`sheet.yaml cannot be opened: ${n.map(o=>o.message).join("; ")}`);this._text=e,this._file=structuredClone(s.file),this._model=s,this.title=s.title,this.worksheets=s.sheets.map(o=>new Worksheet(this,o.name,o));for(const o of s.names.values()){if(o.source.path?.[0]!=="names")continue;const r=o.formula?o.formula.text:o.value??null;this._names.set(o.name,r),this.defined_names.add(new DefinedName(o.name,{attr_text:String(r)}))}}get active(){const e=this.worksheets[this._active]??this.worksheets[0];if(!e)throw new Error("The workbook has no sheets.");return e}set active(e){this._active=this.worksheets.indexOf(e)}get sheetnames(){return this.worksheets.map(e=>e.title)}get_sheet_by_name(e){return this.worksheets.find(t=>t.title===e)}index(e){return this.worksheets.indexOf(e)}create_sheet(e,t){let s=e??"Sheet";for(let o=1;this.worksheets.some(r=>r.title===s);o++)s=`${e??"Sheet"}${String(o)}`;const n=new Worksheet(this,s);return this.worksheets.splice(t??this.worksheets.length,0,n),this._pending=!0,n}remove(e){this.worksheets=this.worksheets.filter(t=>t!==e),this._pending=!0}move_sheet(e,t=0){const s=this.worksheets.indexOf(e);this.worksheets.splice(s,1),this.worksheets.splice(s+t,0,e),this._pending=!0}_tableNamed(e){for(const t of this.worksheets){const s=t._tables.get(e);if(s)return s}}_renameSheet(e,t,s){if(this.worksheets.some(o=>o!==e&&o.title===s))throw new Error(`There is already a sheet named ${s}.`);this._apply(),this._rewrite({op:"rename-sheet",from:t,to:s}),e._title=s,e._was=s;const n=this._file.sheets.find(o=>o.name===t);n&&(n.name=s),this._apply()}_restructure(e){this._apply();const t=_e({file:this._file,rows:new Map([...this._csv].map(([n,o])=>[n,o.rows]))},e);if(t.refused!==void 0)throw new Error(t.refused==="table-header"?"A table's header row is not deleted: delete the table's rows, or all of it.":"That sheet is not there.");this._file=t.file;for(const[n,o]of t.rows){const r=this._csv.get(n);r&&(r.rows=o.map(a=>[...a]))}for(const n of this.worksheets){const o=this._file.sheets.find(r=>r.name===n._title);n._cells.clear(),n._columns.clear(),n._rows.clear(),n._merges=[...o?.merges??[]],n._freeze=o?.freeze,n._heldPage(o),n._heldRules(o)}const s=this._build();this._rebase(s.text,s.files);for(const n of this.worksheets){const o=this._model?.sheet(n._title);if(o){n._lastRow=(o.used?.bottom??-1)+1;for(const r of o.tables){const a=n._tables.get(r.name);a&&(a.ref=x(r.area))}}}}_rewrite(e){const t=(n,o)=>{const r=F(n);if(!r.ok)return n;const a=oe(r.node,e,o);return a===r.node?n:B(a)},{_file:s}=this;if(s.names){for(const[n,o]of Object.entries(s.names))if(typeof o=="string"&&o.startsWith("=")){const r=t(o,s.sheets[0]?.name??"");s.names[n]=r,this._names.set(n,r);const a=this.defined_names.get(n);a&&(a.attr_text=r.slice(1))}}for(const n of s.checks??[])n.formula=t(n.formula,s.sheets[0]?.name??"");for(const n of s.sheets){for(const[o,r]of Object.entries(n.cells??{}))typeof r=="string"&&r.startsWith("=")?n.cells[o]=t(r,n.name):r!==null&&typeof r=="object"&&r.formula!==void 0&&(r.formula=t(r.formula,n.name));for(const o of n.tables??[]){for(const r of Object.values(o.columns??{}))r.formula!==void 0&&(r.formula=t(r.formula,n.name));this._rewriteCsv(o.rows,n.name,t)}for(const o of n.blocks??[])this._rewriteCsv(o.rows,n.name,t)}}_rewriteCsv(e,t,s){const n=this._csv.get(e);n&&(n.rows=n.rows.map(o=>o.map(r=>M(r).formula!==void 0?s(r,t):r)))}_sheetEntry(e){const t=e._was??e._title;let s=this._file.sheets.find(n=>n.name===t);return s||(s={name:e._title},this._file.sheets.push(s)),s.name=e._title,s}_dataPath(e){const t=`${G}/${Me(e)}`;let s=`${t}.csv`;const n=o=>this._csv.has(o)||this._file.sheets.some(r=>r.tables?.some(a=>a.rows===o)??r.blocks?.some(a=>a.rows===o));for(let o=2;n(s);o++)s=`${t}-${String(o)}.csv`;return s}_writeNewTable(e,t,s){const n=k(s.ref);if(!n)throw new Error(`${s.ref} is not a range.`);const o=[];for(let i=n.left;i<=n.right;i++){const h=e.cell(n.top+1,i+1).value;if(h===null||h==="")throw new Error(`Table ${s.name}'s header has no name at ${C({row:n.top,col:i})}.`);o.push(String(h))}const r={},a=[];o.forEach((i,h)=>{const _=n.left+h,d=this._columnFormula(e,n,_);d===void 0?a.push(h):r[i]={formula:d};const p=this._columnFormat(e,n,_);p!==void 0&&(r[i]={...r[i],format:p})}),this._columnsStyled(e,n);const f=[a.map(i=>o[i]??"")];for(let i=n.top+1;i<=n.bottom;i++)f.push(a.map(h=>v(e.cell(i+1,n.left+h+1))));t.cells&&(t.cells=Object.fromEntries(Object.entries(t.cells).filter(([i])=>{const h=y(i);return!h||!N(n,h.row,h.col)})));const c=this._dataPath(s.name);this._csv.set(c,{parsed:void 0,rows:f});const u={name:s.name,at:C({row:n.top,col:n.left}),rows:c,...s.key===void 0?{}:{key:s.key},...m(r)?{}:{columns:r}};(t.tables??=[]).push(u),s._spec=u}_columnsStyled(e,t){for(let s=t.left;s<=t.right;s++)for(let n=t.top+1;n<=t.bottom;n++){const o=e.cell(n+1,s+1),{format:r,...a}=this._ownLook(o);r!==void 0&&m(a)&&(o._styled=!1)}}_columnFormula(e,t,s){if(t.bottom<=t.top)return;const n=e.cell(t.top+2,s+1),o=R(n);if(o!==void 0){for(let r=t.top+2;r<=t.bottom;r++)if(R(e.cell(r+1,s+1))!==o)return;return n._formula}}_columnFormat(e,t,s){if(t.bottom<=t.top)return;const n=r=>this._ownLook(e.cell(r+1,s+1)).format,o=n(t.top+1);for(let r=t.top+2;r<=t.bottom;r++)if(n(r)!==o)return;return o}_held(e){const t=this._csv.get(e);if(!t)throw new Error(`${e} was not read.`);return t}_setCsvCell(e,t,s,n){const{rows:o}=this._held(e);for(;o.length<=t;)o.push([]);const r=o[t];if(r){for(;r.length<=s;)r.push("");r[s]=n}}_recordOf(e,t){let s=0;for(let n=0;n<t;){if(s+=1,s>=e.length)return s+t-n-1;e[s]?.length!==0&&(n+=1)}return s}_writeTableCell(e,t,s){const n=this._held(e.rows),o=n.rows[0]??[],r=s.column-1-t.left,a=this._recordOf(n.rows,s.row-1-t.top),f=Object.keys(e.columns??{}).filter(_=>!o.some(d=>d.trim().toLowerCase()===_.toLowerCase())),u=[...o.map(_=>_.trim()),...f][r];if(u===void 0)return;if(a===0){r<o.length&&(o[r]=v(s));return}const i=e.columns?.[u]?.formula;if(i!==void 0){const _=this._movedColumn(i,t,s);if(s._formula===_){const d=o.findIndex(p=>p.trim()===u);d>=0&&this._setCsvCell(e.rows,a,d,"");return}}let h=o.findIndex(_=>_.trim()===u);h<0&&(h=o.length,this._setCsvCell(e.rows,0,h,u)),this._setCsvCell(e.rows,a,h,v(s))}_movedColumn(e,t,s){const n=F(e);if(!n.ok)return e;const o=s.row-1-(t.top+1);return o===0?e:B(se(n.node,o,0))}_apply(){this.title===void 0?delete this._file.title:this._file.title=this.title;const e=new Set(this.worksheets.map(s=>s._was??s._title));this._file.sheets=this._file.sheets.filter(s=>e.has(s.name));for(const s of this.worksheets)this._applySheet(s);this._file.sheets=this.worksheets.map(s=>this._sheetEntry(s)),this._applyNames();const t=this._build();this._rebase(t.text,t.files)}_applyNames(){const e={};for(const t of this.defined_names.values()){const s=M(t.attr_text),n=this._names.get(t.name);e[t.name]=n!==void 0&&String(n).replace(/^=/u,"")===t.attr_text?n:typeof s.value=="number"||typeof s.value=="boolean"?s.value:/^"[^"]*"$/u.test(t.attr_text)?t.attr_text.slice(1,-1):`=${t.attr_text}`}m(e)?delete this._file.names:this._file.names=e}_applySheet(e){const t=this._sheetEntry(e);e._freeze===void 0?delete t.freeze:t.freeze=e._freeze,m(e._print)?delete t.print:t.print=e._print,m(e._links)?delete t.links:t.links=e._links,m(e._notes)?delete t.notes:t.notes=e._notes,e._pictures.length===0?delete t.pictures:t.pictures=e._pictures,e._protect?t.protect=!0:delete t.protect,e._merges.length===0?delete t.merges:t.merges=[...e._merges],e._state==="hidden"?t.hidden=!0:delete t.hidden,e._rules.length===0?delete t.conditional:t.conditional=[...e._rules],e._validations.length===0?delete t.validations:t.validations=e._validations.map(ke),e._charts.length===0?delete t.charts:t.charts=e._charts.map(n=>n._spec(e._title)),this._applyFilter(e,t);const s=new Set(t.tables?.map(n=>n.name.toLowerCase()));for(const n of e._tables.values())s.has(n.name.toLowerCase())||this._writeNewTable(e,t,n);this._applyTableFilters(e,t),this._applyCells(e,t),this._applyDimensions(e,t),t.cells&&m(t.cells)&&delete t.cells,t.columns&&m(t.columns)&&delete t.columns,t.rows&&m(t.rows)&&delete t.rows,t.format?.length===0&&delete t.format,t.tables?.length===0&&delete t.tables,t.blocks?.length===0&&delete t.blocks}_applyFilter(e,t){const{ref:s,_columns:n}=e._filter;if(s===void 0){delete t.filter;return}const o=k(s);if(!o)throw new TypeError(`${s} is not a range.`);const r={};for(const[a,f]of n)r[L(o.left+a)]=f;t.filter={range:s,...m(r)?{}:{columns:r}}}_applyTableFilters(e,t){for(const s of t.tables??[]){const n=e._tables.get(s.name);if(!n||n.autoFilter._columns.size===0)continue;const o=this._csv.get(s.rows)?.rows??[],r=ce(s,o)?.names??[],a={};for(const[f,c]of n.autoFilter._columns){const u=r[f];if(u===void 0)throw new RangeError(`Table ${s.name} has no column at ${String(f)}.`);a[u]=c}s.filter={columns:a}}}_applyDimensions(e,t){if(e._dimensions){for(const[s,n]of e._columns){const o={...t.columns?.[s]};n._width===void 0?delete o.width:o.width=n._width,n._hidden===void 0?delete o.hidden:o.hidden=n._hidden,n._files===void 0?delete o.files:o.files=n._files,n._level===void 0?delete o.level:o.level=n._level;const r=j(t.columns??{},s);t.columns=m(o)?r:{...r,[s]:o}}for(const[s,n]of e._rows){const o={...t.rows?.[String(s)]};n._height===void 0?delete o.height:o.height=n._height,n._hidden===void 0?delete o.hidden:o.hidden=n._hidden,n._level===void 0?delete o.level:o.level=n._level;const r=j(t.rows??{},String(s));t.rows=m(o)?r:{...r,[String(s)]:o}}e._dimensions=!1}}_applyCells(e,t){const s=(t.tables??[]).flatMap(r=>{const a=y(r.at),f=e._tables.get(r.name),c=f?k(f.ref):void 0;return a&&c?[{entry:r,area:c}]:[]}),n=(t.blocks??[]).flatMap(r=>{const a=e._model?.blocks.find(f=>f.file===r.rows);return a?[{entry:r,area:a.area}]:[]}),o=[];for(const r of e._cells.values()){if(!r._changed&&!r._styled)continue;const a=r.row-1,f=r.column-1,c=s.find(i=>N(i.area,a,f)),u=n.find(i=>N(i.area,a,f));c?(r._changed&&this._writeTableCell(c.entry,c.area,r),r._styled&&this._styleByFormat(t,r)):u?(r._changed&&this._setCsvCell(u.entry.rows,a-u.area.top,f-u.area.left,v(r)),r._styled&&this._styleByFormat(t,r)):r._fresh&&!e._model?.keys.has(a*16384+f)?o.push(r):this._writeLoose(e,t,r),r._changed=!1,r._styled=!1}this._consolidate(e,t,o),je(t)}_styleByFormat(e,t){(e.format??=[]).push({range:t.coordinate,...this._ownLook(t)})}_ownLook(e){const t=e._ws._model?.lookAt(e.row-1,e.column-1)??{},s=Fe(t,e._look);return s.format!==void 0&&e._formula===void 0&&M(v(e)).format===s.format&&delete s.format,s}_writeLoose(e,t,s){const n=s.coordinate,o=t.cells??={},r=U(s),a=this._ownLook(s),f=o[n],u={...f!==null&&typeof f=="object"?Object.fromEntries(Object.entries(f).filter(([_])=>_!=="value"&&_!=="formula"&&_!=="name")):{},...a},i=f!==null&&typeof f=="object"&&f.name!==void 0?{name:f.name}:{},h=e._model?.at(s.row-1,s.column-1)!==void 0;if(r===null&&m(u)&&!h){t.cells=j(o,n);return}o[n]=m(u)&&m(i)?r:{...typeof r=="string"&&r.startsWith("=")?{formula:r}:r===null?{}:{value:r},...i,...u}}_consolidate(e,t,s){const n=s.filter(i=>i._value!==null||i._formula!==void 0),o=new Map;for(const i of s){const h=this._ownLook(i);if(m(h))continue;const _=JSON.stringify(h),d=o.get(_);d?d.push(i):o.set(_,[i])}const r=new Map(n.map(i=>[`${String(i.row)}:${String(i.column)}`,i])),a=i=>r.get(`${String(i.row+1)}:${String(i.col+1)}`)??e.cell(i.row+1,i.col+1),f=new Map,c=[];for(const i of n){const h={row:i.row-1,col:i.column-1},_=i._formula===void 0?void 0:R(i);if(_===void 0){c.push(h);continue}const d=f.get(_);d?d.push(h):f.set(_,[h])}const u=t.cells??={};for(const i of f.values())for(const h of T(i))u[x(h)]=a({row:h.top,col:h.left})._formula??null;for(const i of T(c))if((i.bottom-i.top+1)*(i.right-i.left+1)>=this.block_cells){const _=[];for(let p=i.top;p<=i.bottom;p++){const D=[];for(let O=i.left;O<=i.right;O++)D.push(v(a({row:p,col:O})));_.push(D)}const d=this._dataPath(e._title);this._csv.set(d,{parsed:void 0,rows:_}),(t.blocks??=[]).push({at:C({row:i.top,col:i.left}),rows:d})}else for(let _=i.top;_<=i.bottom;_++)for(let d=i.left;d<=i.right;d++){const p=a({row:_,col:d});u[p.coordinate]=U(p)}for(const i of o.values()){const[h]=i;if(!h)continue;const _=this._ownLook(h),d=i.map(p=>({row:p.row-1,col:p.column-1}));for(const p of T(d))(t.format??=[]).push({range:x(p),..._})}}_build(){const e=new Map;for(const[t,s]of this._csv)e.set(t,s.parsed?re(s.parsed,s.rows):ee(s.rows));return{text:ue(this._text,this._file),files:e}}_rebase(e,t){const{workbook:s,problems:n}=I({text:e,read:o=>t.get(o)});if(!s)throw new Error(`The workbook is not one: ${n.map(o=>o.message).join("; ")}`);this._text=e,this._file=structuredClone(s.file),this._model=s;for(const[o,r]of t)this._keepCsv(o,r);this._calc=void 0,this._pending=!1;for(const o of this.worksheets){o._was=o._title;const r=s.sheet(o._title);r&&(o._model=r);for(const a of o._cells.values())a._fresh=r?.at(a.row-1,a.column-1)===void 0}this._names=new Map;for(const o of s.names.values())o.source.path?.[0]==="names"&&this._names.set(o.name,o.formula?o.formula.text:o.value??null)}_computed(){const e=[...this.defined_names.values()];if((this._pending||e.length!==this._names.size||e.some(t=>String(this._names.get(t.name)).replace(/^=/u,"")!==t.attr_text))&&this._apply(),!this._calc){const t=this._model;if(!t)throw new Error("The workbook has no sheets.");this._calc={calc:new Q(t).calculate(),model:t}}return this._calc}check(){this._apply();const{text:e,files:t}=this._build();return X({text:e,read:s=>t.get(s)}).problems}_generated(){if(this.worksheets.length===0)return this._applyNames(),{sheets:[],csv:{},...this._file.names?{names:this._file.names}:{}};this._apply();const e=structuredClone(this._file.sheets),t=n=>`${te}${n}`;for(const n of e){for(const o of n.tables??[])o.rows=t(o.rows);for(const o of n.blocks??[])o.rows=t(o.rows)}const s={};for(const[n,o]of this._build().files)s[t(n)]=o;return{sheets:e,csv:s,...this._file.names?{names:this._file.names}:{}}}save(e){if(this._making)throw new Error("sheet.ts makes sheets and saves nothing: what it adds to wb is what it makes.");const t=e??this.path;if(t===void 0)throw new TypeError("A new workbook is saved to a folder: wb.save('content/budget').");if(this.worksheets.length===0)throw new Error("A workbook has at least one sheet.");const{text:s,csv:n}=this._disk;this._apply();const o=new Set(this._file.sheets.flatMap(i=>[...(i.tables??[]).map(h=>h.rows),...(i.blocks??[]).map(h=>h.rows)])),r=[...this._csv.keys()].filter(i=>!o.has(i));for(const i of r)this._csv.delete(i);const{mkdirSync:a,rmSync:f,writeFileSync:c}=J(),u=process.getBuiltinModule("node:path");a(t,{recursive:!0}),(this._text!==s||e!==void 0)&&c($(t,P),this._text);for(const[i,h]of this._csv){const _=h.parsed?.source??"";if(e===void 0&&n.get(i)===_)continue;const d=$(t,i);a(u.dirname(d),{recursive:!0}),c(d,_)}if(e===void 0||t===this.path)for(const i of r)f($(t,i),{force:!0});this._disk={text:this._text,csv:new Map([...this._csv].map(([i,h])=>[i,h.parsed?.source??""]))},this.path=t}}function R(l){if(l._formula===void 0)return;const e=F(l._formula);if(e.ok)return ne(e.node,l.row-1,l.column-1)}function je(l){const e=l.format;if(!e||e.length<2)return;const t=[],s=new Map;for(const n of e){const{range:o,...r}=n,a=y(o);if(!a){t.push(n);continue}const f=JSON.stringify(r),c=s.get(f);c?c.places.push(a):s.set(f,{look:r,places:[a]})}for(const{look:n,places:o}of s.values())for(const r of T(o))t.push({range:x(r),...n});l.format=t}export function load_workbook(l,e={}){return Workbook.open(l,e)}export const get_column_letter=l=>L(l-1);export function column_index_from_string(l){const e=E(l);if(e===void 0)throw new TypeError(`${l} is not a column.`);return e+1}export function coordinate_to_tuple(l){const e=y(l);if(!e)throw new TypeError(`${l} is not a cell.`);return[e.row+1,e.col+1]}export function range_boundaries(l){const e=k(l);if(!e)throw new TypeError(`${l} is not a range.`);return[e.left+1,e.top+1,e.right+1,e.bottom+1]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
|
|
2
|
-
import{cellName as d,rangeName as b}from"./address.js";import{ERR as p,Matrix as w,CellError as m}from"./values.js";import{analyse as $}from"./calc/analyse.js";import{Calc as k}from"./calc/engine.js";import{toBool as g}from"./calc/coerce.js";import{ENTRY as l}from"./file.js";import{fileCells as x}from"./files.js";import{applyScenario as y}from"./scenario.js";import{readWorkbook as S}from"./workbook.js";class O{problems;wb;lineOf;constructor(t,
|
|
2
|
+
import{cellName as d,rangeName as b}from"./address.js";import{ERR as p,Matrix as w,CellError as m}from"./values.js";import{analyse as $}from"./calc/analyse.js";import{Calc as k}from"./calc/engine.js";import{toBool as g}from"./calc/coerce.js";import{ENTRY as l}from"./file.js";import{fileCells as x}from"./files.js";import{applyScenario as y}from"./scenario.js";import{readWorkbook as S}from"./workbook.js";class O{problems;wb;lineOf;constructor(t,o){this.wb=t,this.problems=[...o.problems],this.lineOf=o.lineOf}at(t,o){const e=t.line??(t.path===void 0?void 0:this.lineOf(t.path));this.problems.push({file:t.file===""?l:t.file,...e===void 0?{}:{line:e},message:o})}formulas(){const t=new Map;for(const o of this.wb.sheets){for(const e of o.formulas)t.set(e.shared,o);for(const e of o.tables)for(const s of e.columns)s.formula&&t.set(s.formula,o);for(const e of o.conditions)for(const s of e.formulas)t.set(s,o);for(const e of o.validations)for(const s of e.formulas)s&&t.set(s,o);for(const e of o.charts){e.title&&t.set(e.title,o),e.categories&&t.set(e.categories,o);for(const s of e.series)t.set(s.values,o),s.x&&t.set(s.x,o),s.name&&t.set(s.name,o)}}for(const o of this.wb.names.values())o.formula&&t.set(o.formula,void 0);for(const o of this.wb.checks)t.set(o.formula,void 0);return t}formulaProblems(){for(const[t,o]of this.formulas()){const e=n=>{this.at(t.source,`${t.text}: ${n}`)};if(t.error){e(`does not parse: ${t.error.message}`);continue}const s=$(this.wb,t);t.analysis=s;for(const n of new Set(s.unknownNames))e(`there is no name ${n}`);for(const n of new Set(s.unknownFunctions))e(`there is no function ${n}`);for(const n of s.arguments)e(`${n.name} takes ${n.min===n.max?String(n.min):`${String(n.min)} to ${String(n.max)}`} arguments and is given ${String(n.given)}`);for(const n of s.reads){if(n.kind==="ref"){for(const r of[n.sheet,n.lastSheet])r!==void 0&&!this.wb.sheet(r)&&e(`there is no sheet ${r}`);continue}const f=n.table===void 0?o?.tableAt(t.row,t.col):this.wb.table(n.table);if(!f){e(n.table===void 0?"a column named with no table, outside a table":`there is no table ${n.table}`);continue}for(const r of n.columns)f.column(r)||e(`table ${f.name} has no column ${r}; it has ${f.columns.map(c=>c.name).join(", ")}`)}}}cycles(t){for(const o of t.cycles){const e=o.reduce((r,c,u)=>{const a=o[r];return a&&(c.row<a.row||c.row===a.row&&c.col<a.col)?u:r},0),s=[...o.slice(e),...o.slice(0,e)],n=s[0];if(!n)continue;const f=[...s,n].map(r=>`${r.sheet.name}!${d(r)}`).join(" → ");this.at(n.shared.source,`a circular reference: ${f}`)}}scenarios(){const{scenarios:t}=this.wb.file;for(const[o,e]of Object.entries(t??{}))for(const s of Object.keys(e))this.wb.name(s)||this.at({file:l,path:["scenarios",o,s]},`scenario ${o} sets ${s}, and there is no name ${s}`)}files(t,o){for(const e of this.wb.sheets)for(const{row:s,col:n,paths:f}of x(e,t))for(const r of f)o(r)||this.at(this.wb.sourceOf(e,s,n)??{file:l},`${placeName(e,s,n)} names ${r}, which is not there`);for(const e of this.wb.sheets)for(const s of e.spec.pictures??[])o(s.file)||this.at({file:l},`${e.name} has a picture ${s.file}, which is not there`)}checks(t){const o=this.wb.sheets[0];if(o)for(const e of this.wb.checks){if(!e.formula.node)continue;const s=t.evaluate(e.formula,o),n=h(s);n!==void 0&&this.at(e.source,`check "${e.name}" does not hold: ${e.formula.text} is ${n}`)}}}function h(i){if(i instanceof w){for(const o of i.data){const e=h(o);if(e!==void 0)return e}return}if(i instanceof m)return i.code;const t=g(i);return t instanceof m?p.VALUE.code:t?void 0:"FALSE"}export function checkWorkbook(i,t={}){const o=S(i),{workbook:e}=o;if(!e)return{problems:o.problems};const s=new O(e,o);s.scenarios(),t.scenario!==void 0&&y(e,t.scenario);const n=new k(e,t);return s.formulaProblems(),n.calculate(),s.cycles(n),s.checks(n),i.exists&&s.files(n,i.exists),{workbook:e,calc:n,problems:s.problems}}export const placeName=(i,t,o)=>`${i.name}!${b({top:t,left:o,bottom:t,right:o})}`;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
|
|
2
|
-
import{MAX_COLUMNS as q,MAX_ROWS as D,cellName as S,columnIndex as R,columnLetter as _,rangeName as x,readAddress as y,readArea as A,readAreas as G}from"./address.js";import{chartAfter as H}from"./chart.js";import{moveFormula as J,relativeKey as Q}from"./formula/move.js";import{parseFormula as z}from"./formula/parse.js";import{printFormula as N}from"./formula/print.js";import{rewriteFormula as B}from"./formula/rewrite.js";import{walk as V}from"./formula/walk.js";import{readTyped as Y}from"./values.js";import{chartFormula as Z}from"./workbook.js";const E=r=>r.op==="insert-rows"||r.op==="delete-rows"||r.op==="insert-columns"||r.op==="delete-columns",k=r=>r.op==="insert-rows"||r.op==="insert-columns",b=r=>r.op==="insert-rows"||r.op==="delete-rows";function v(r,t){return k(t)?r>=t.at?r+t.count:r:r<t.at?r:r>=t.at+t.count?r-t.count:void 0}const tt=r=>b(r)?D:q;function $(r,t,n){const s=tt(n);if(k(n)){const e=r>=n.at?r+n.count:r,c=t>=n.at?t+n.count:t;return e>=s?void 0:[e,Math.min(c,s-1)]}const i=n.at+n.count-1;if(r>=n.at&&t<=i)return;const a=r<n.at?r:r>i?r-n.count:n.at,o=t<n.at?t:t>i?t-n.count:n.at-1;return[a,o]}function L(r,t){const n=b(t)?$(r.top,r.bottom,t):$(r.left,r.right,t);if(n)return b(t)?{...r,top:n[0],bottom:n[1]}:{...r,left:n[0],right:n[1]}}function nt(r,t,n,s){let i=0;const a=(o,e)=>{o&&!o.abs&&(i=Math.max(i,Math.abs(o.index-e)))};return V(r,o=>{o.kind==="ref"&&(t?(a(o.row,n),a(o.row2,n)):(a(o.col,s),a(o.col2,s)))}),i}function et(r,t,n,s){const i=new Set,a=l=>{for(let f=l-s-1;f<=l+s+1;f++)f>=r&&f<=t&&i.add(f)};a(n.at),a(n.at+n.count);const o=[...i].sort((l,f)=>l-f),e=[];let c=r;for(const l of o)l>c&&e.push([c,l-1]),e.push([l,l]),c=l+1;return c<=t&&e.push([c,t]),e}function ot(r,t,n,s,i){const a=z(t);if(!a.ok){const m=i?L(r,s):r;return m?[{area:m,text:t}]:[]}const o=b(s),[e,c]=o?[r.top,r.bottom]:[r.left,r.right],l=nt(a.node,o,r.top,r.left),f=[];let u=!0;for(const[m,d]of et(e,c,s,l)){const w=o?m:r.top,p=o?r.left:m,h=i?v(m,s):m;if(h===void 0)continue;const g=i?v(d,s):d;if(g===void 0)continue;const C=J(a.node,w-r.top,p-r.left),j=B(C,s,n);j!==C&&(u=!1);const U=o?h:r.top,X=o?r.left:h,F=Q(j,U,X),I=f[f.length-1];I?.key===F&&I.to+1===h?I.to=g:f.push({from:h,to:g,key:F,text:N(j)})}return f.map(m=>({area:o?{...r,top:m.from,bottom:m.to}:{...r,left:m.from,right:m.to},text:u&&f.length===1?t:m.text}))}function W(r,t){return r!==null&&typeof r=="object"?{...r,formula:t}:t}const st=r=>{if(typeof r=="string")return r.startsWith("=")?r:void 0;if(!(r===null||typeof r!="object"))return r.formula!==void 0?r.formula.startsWith("=")?r.formula:`=${r.formula}`:typeof r.value=="string"&&r.value.startsWith("=")?r.value:void 0};function O(r,t,n,s){const i=z(r);if(!i.ok)return r;const a=B(i.node,t,n,s);return a===i.node?r:N(a)}function rt(r,t,n,s){const i={},a=E(n)?n:void 0;for(const[o,e]of Object.entries(r)){const c=st(e),l=A(o);if(!l){i[o]=e;continue}const f=s&&a!==void 0;if(o.includes(":")){if(!a){i[o]=c===void 0?e:W(e,O(c,n,t));continue}if(c!==void 0){for(const h of ot(l,c,t,a,f))i[x(h.area)]=W(e,h.text);continue}if(!f){i[o]=e;continue}if(!k(a)){const h=L(l,a);h&&(i[x(h)]=e);continue}const d=b(a),[w,p]=d?[l.top,l.bottom]:[l.left,l.right];for(const[h,g]of[[w,Math.min(p,a.at-1)],[Math.max(w,a.at),p]]){if(h>g)continue;const C=h>=a.at?a.count:0,j=d?{...l,top:h+C,bottom:g+C}:{...l,left:h+C,right:g+C};i[x(j)]=e}continue}const u={row:l.top,col:l.left};let m=u;if(f){const d=v(b(a)?u.row:u.col,a);m=d===void 0?void 0:b(a)?{...u,row:d}:{...u,col:d}}m&&(i[S(m)]=c===void 0?e:W(e,O(c,n,t)))}return i}export function tableShape(r,t){const n=y(r.at);if(!n)return;const s=t[0]??[],i=s.map(e=>e.trim()),a=new Set(i.map(e=>e.toLowerCase()));for(const e of Object.keys(r.columns??{}))a.has(e.toLowerCase())||i.push(e);const o=[];return t.forEach((e,c)=>{c>0&&e.length>0&&o.push(c)}),{at:n,header:s,names:i,places:o}}const P=r=>r.reduce((t,n)=>Math.max(t,n.length),0);function K(r,t,n){const s=Math.max(P(r),1),i=Array.from({length:n},()=>new Array(s).fill(""));return[...r.slice(0,t),...i,...r.slice(t)]}export function freeColumn(r,t="Column"){const n=new Set(r.map(s=>s.toLowerCase()));for(let s=1;;s++){const i=`${t}${String(s)}`;if(!n.has(i.toLowerCase()))return i}}export function uniqueColumn(r,t){const n=new Set(r.map(s=>s.toLowerCase()));if(!n.has(t.toLowerCase()))return t;for(let s=2;;s++){const i=`${t}${String(s)}`;if(!n.has(i.toLowerCase()))return i}}export function withColumnsUpTo(r,t,n){const s=r.map(o=>[...o]),i=s[0]??[];for(s.length===0&&s.push(i);i.length<=n;)i.push(t[i.length]??"");const a=i.length;for(let o=1;o<s.length;o++){const e=s[o];if(e&&e.length>0)for(;e.length<a;)e.push("")}return s}class T{file;rows;edit;after=[];refused;constructor(t,n){this.file=structuredClone(t.file),this.rows=new Map(t.rows),this.edit=n}sheets(){return this.file.sheets}rewrite(t){const n=this.file.sheets[0]?.name??"";if(this.file.names)for(const[s,i]of Object.entries(this.file.names))typeof i=="string"&&i.startsWith("=")&&(this.file.names[s]=O(i,t,n));for(const s of this.file.checks??[])s.formula=O(s.formula,t,n);for(const s of this.sheets())this.rewriteSheet(s,t)}rewriteSheet(t,n){const s=E(n)&&M(t.name,n.sheet);t.cells&&(t.cells=rt(t.cells,t.name,n,s));for(const i of t.tables??[]){for(const a of Object.values(i.columns??{}))a.formula!==void 0&&(a.formula=O(a.formula,n,t.name,i.name));this.rewriteCsv(i.rows,n,t.name,i.name)}for(const i of t.blocks??[])this.rewriteCsv(i.rows,n,t.name);this.rewriteRules(t,n)}freePath(t,n){const s=t.slice(0,t.lastIndexOf("/")+1),i=o=>[...this.rows.keys()].some(e=>M(e,o));let a=`${s}${n}.csv`;for(let o=2;i(a);o++)a=`${s}${n}-${String(o)}.csv`;return a}duplicate(t,n){const s=this.sheets(),i=s.findIndex(f=>M(f.name,t)),a=s[i];if(!a){this.refused="no-sheet";return}const o=structuredClone(a);o.name=n,delete o.hidden;for(const f of Object.values(o.cells??{}))f!==null&&typeof f=="object"&&delete f.name;const e=new Set(s.flatMap(f=>f.tables??[]).map(f=>f.name.toLowerCase())),c=new Set(Object.keys(this.file.names??{}).map(f=>f.toLowerCase())),l=[];for(const f of o.tables??[]){let u=f.name;for(let d=2;;d++){u=`${f.name}${String(d)}`;const w=u.toLowerCase();if(!e.has(w)&&!c.has(w))break}e.add(u.toLowerCase());const m=this.freePath(f.rows,u);this.rows.set(m,this.rows.get(f.rows)??[]),l.push({op:"rename-table",from:f.name,to:u}),f.rows=m,f.name=u}for(const f of o.blocks??[]){const u=f.rows.slice(f.rows.lastIndexOf("/")+1,-4),m=this.freePath(f.rows,u);this.rows.set(m,this.rows.get(f.rows)??[]),f.rows=m}this.file.sheets=[...s.slice(0,i+1),o,...s.slice(i+1)],this.rewriteSheet(o,{op:"rename-sheet",from:t,to:n});for(const f of l)this.rewriteSheet(o,f)}rewriteRules(t,n){const s=e=>typeof e=="string"&&e.startsWith("=")?O(e,n,t.name):e,i=e=>e.value===void 0?e:{...e,value:s(e.value)},a=t.conditional?.map(e=>{switch(e.type){case"cellIs":return{...e,formula:e.formula.map(s)};case"expression":return{...e,formula:O(e.formula.startsWith("=")?e.formula:`=${e.formula}`,n,t.name)};case"dataBar":return{...e,...e.min?{min:i(e.min)}:{},...e.max?{max:i(e.max)}:{}};case"colorScale":return{...e,stops:e.stops.map(i)};case"iconSet":return e.stops?{...e,stops:e.stops.map(i)}:e;default:return e}});a&&(t.conditional=a);const o=t.validations?.map(e=>e.formula?{...e,formula:e.formula.map(s)}:e);o&&(t.validations=o),t.charts&&(t.charts=t.charts.map(e=>H(e,c=>{const l=c.startsWith("="),f=O(Z(c),n,t.name);return l?f:f.slice(1)})))}rewriteCsv(t,n,s,i){const a=this.rows.get(t);if(!a)return;let o;a.forEach((e,c)=>{if(!e.some(f=>f.charCodeAt(0)===61))return;const l=e.map(f=>Y(f).formula===void 0?f:O(f,n,s,i));l.every((f,u)=>f===e[u])||(o??=[...a],o[c]=l)}),o&&this.rows.set(t,o)}tableOn(t,n){const s=b(n),i=[];for(const a of t.tables??[]){const o=this.rows.get(a.rows),e=o&&tableShape(a,o);if(!o||!e){i.push(a);continue}const c=e.at.row,l=e.at.col,f=c+e.places.length,u=l+Math.max(e.names.length,1)-1,[m,d]=s?[c,f]:[l,u];if(!k(n)&&n.at<=m&&n.at+n.count-1>=d){this.after.push({op:"delete-table",name:a.name});continue}const w={...e.at};if(s)if(k(n)){if(n.at<=c)w.row+=n.count;else if(n.at<=f){const p=e.places[n.at-c-1]??o.length;this.rows.set(a.rows,K(o,p,n.count))}}else{const p=n.at+n.count-1;if(p<c)w.row-=n.count;else if(n.at<=c){this.refused="table-header";return}else if(n.at<=f){const h=new Set(e.places.slice(n.at-c-1,p-c));this.rows.set(a.rows,o.filter((g,C)=>!h.has(C)))}}else if(k(n))n.at<=l?w.col+=n.count:n.at<=u&&this.columnsIn(a,e,n.at-l,n.count);else{const p=n.at+n.count-1;if(p<l)w.col-=n.count;else if(n.at<=u){w.col=Math.min(l,n.at);const h=Math.max(0,n.at-l),g=Math.min(e.names.length-1,p-l);this.columnsOut(a,e,h,g)}}a.at=S(w),i.push(a)}t.tables=i,i.length===0&&delete t.tables}columnsIn(t,n,s,i){const a=this.rows.get(t.rows)??[],o=s>0?withColumnsUpTo(a,n.names,s-1):a.map(c=>[...c]),e=[...n.names];o.forEach((c,l)=>{if(l>0&&c.length===0)return;const f=[];for(let u=0;u<i;u++)if(l===0){const m=freeColumn(e);e.push(m),f.push(m)}else f.push("");for(;c.length<s;)c.push("");c.splice(s,0,...f)}),this.rows.set(t.rows,o)}columnsOut(t,n,s,i){const a=n.names.slice(s,i+1),o=this.rows.get(t.rows)??[],e=n.header.length,c=new Set;for(let l=s;l<=i&&l<e;l++)c.add(l);if(c.size>0&&this.rows.set(t.rows,o.map(l=>l.length===0?l:l.filter((f,u)=>!c.has(u)))),t.columns){const l=new Set(a.map(f=>f.toLowerCase()));t.columns=Object.fromEntries(Object.entries(t.columns).filter(([f])=>!l.has(f.toLowerCase()))),Object.keys(t.columns).length===0&&delete t.columns}if(t.key!==void 0&&a.some(l=>l.toLowerCase()===t.key?.toLowerCase())&&delete t.key,t.filter){const l=new Set(a.map(u=>u.toLowerCase())),f=Object.fromEntries(Object.entries(t.filter.columns).filter(([u])=>!l.has(u.toLowerCase())));Object.keys(f).length>0?t.filter={columns:f}:delete t.filter}for(const l of a)this.after.push({op:"delete-column",table:t.name,name:l})}blocksOn(t,n){const s=b(n),i=(t.blocks??[]).flatMap(a=>{const o=y(a.at),e=this.rows.get(a.rows);if(!o||!e)return[a];const c=s?o.row:o.col,l=s?e.length:Math.max(P(e),1),f=c+l-1,u=$(c,f,n);if(!u)return[];const m=s?{...o,row:u[0]}:{...o,col:u[0]};if(k(n)&&n.at>c&&n.at<=f){const d=n.at-c;this.rows.set(a.rows,s?K(e,d,n.count):e.map(w=>{if(w.length===0)return w;const p=[...w];for(;p.length<d;)p.push("");return p.splice(d,0,...new Array(n.count).fill("")),p}))}else if(!k(n)&&n.at<=f){const d=Math.max(n.at,c)-c,w=Math.min(n.at+n.count-1,f)-c;this.rows.set(a.rows,s?e.filter((p,h)=>h<d||h>w):e.map(p=>p.filter((h,g)=>g<d||g>w)))}return[{...a,at:S(m)}]});t.blocks=i,i.length===0&&delete t.blocks}looksOn(t,n){const s=b(n);t.format&&(t.format=t.format.flatMap(o=>{const e=A(o.range);if(!e)return[o];const c=L(e,n);return c?[{...o,range:x(c)}]:[]})),t.format?.length===0&&delete t.format,t.merges&&(t.merges=t.merges.flatMap(o=>{const e=A(o);if(!e)return[o];const c=L(e,n);return c?[x(c)]:[]})),t.merges?.length===0&&delete t.merges;const i=o=>{const e=G(o);if(!e)return o;const c=e.flatMap(l=>{const f=L(l,n);return f?[x(f)]:[]});return c.length===0?void 0:c.join(" ")};if(t.conditional&&(t.conditional=t.conditional.flatMap(o=>{const e=i(o.range);return e===void 0?[]:[{...o,range:e}]})),t.conditional?.length===0&&delete t.conditional,t.validations&&(t.validations=t.validations.flatMap(o=>{const e=i(o.range);return e===void 0?[]:[{...o,range:e}]})),t.validations?.length===0&&delete t.validations,t.charts&&(t.charts=t.charts.map(o=>{const e=y(o.at);if(!e)return o;const c=s?e.row:e.col,l=v(c,n)??n.at;return{...o,at:S(s?{...e,row:l}:{...e,col:l})}})),t.filter){const o=A(t.filter.range),e=o&&L(o,n);if(o&&!e)delete t.filter;else if(e){const c=s?t.filter.columns:Object.fromEntries(Object.entries(t.filter.columns??{}).flatMap(([l,f])=>{const u=R(l),m=u===void 0?void 0:v(u,n);return m===void 0?[]:[[_(m),f]]}));t.filter={range:x(e),...c&&Object.keys(c).length>0?{columns:c}:{}}}}if(t.freeze!==void 0){const o=y(t.freeze);if(o){const e=s?o.row:o.col,c=$(0,e-1,n),l=e===0?0:c?c[1]+1:0;t.freeze=S(s?{...o,row:l}:{...o,col:l})}}const a=(o,e,c)=>{if(!o)return;const l={};for(const[f,u]of Object.entries(o)){const m=e(f),d=m===void 0?void 0:v(m,n);m===void 0?l[f]=u:d!==void 0&&(l[c(d)]=u)}return l};if(s){const o=a(t.rows,e=>/^[1-9]\d*$/u.test(e)?Number(e)-1:void 0,e=>String(e+1));o&&(t.rows=o)}else{const o=a(t.columns,R,_);o&&(t.columns=o)}}run(){const t=this.edit;if(E(t)){const n=this.sheets().find(s=>M(s.name,t.sheet));if(!n){this.refused="no-sheet";return}if(this.rewrite(t),this.tableOn(n,t),this.refused)return;this.blocksOn(n,t),this.looksOn(n,t);for(const s of this.after)this.rewrite(s);return}switch(t.op){case"rename-sheet":{this.rewrite(t);const n=this.sheets().find(s=>M(s.name,t.from));n&&(n.name=t.to);return}case"rename-column":{this.renameColumn(t.table,t.from,t.to),this.rewrite(t);return}case"delete-sheet":{const n=this.sheets(),s=n.find(i=>M(i.name,t.name));if(!s){this.refused="no-sheet";return}if(n.filter(i=>i.hidden!==!0).length<=1){this.refused="last-sheet";return}this.rewrite(t);for(const i of s.tables??[])this.rewrite({op:"delete-table",name:i.name});this.file.sheets=n.filter(i=>i!==s);return}default:this.rewrite(t)}}renameColumn(t,n,s){const i=this.sheets().flatMap(c=>c.tables??[]).find(c=>M(c.name,t));if(!i)return;const a=n.toLowerCase(),o=this.rows.get(i.rows),e=o?.[0]?.findIndex(c=>c.trim().toLowerCase()===a)??-1;if(o&&e>=0){const c=[...o[0]??[]];c[e]=s,this.rows.set(i.rows,[c,...o.slice(1)])}if(i.columns){const c=Object.keys(i.columns).find(l=>l.toLowerCase()===a);c!==void 0&&(i.columns=Object.fromEntries(Object.entries(i.columns).map(([l,f])=>[l===c?s:l,f])))}i.key?.toLowerCase()===a&&(i.key=s),i.filter&&(i.filter={columns:Object.fromEntries(Object.entries(i.filter.columns).map(([c,l])=>[c.toLowerCase()===a?s:c,l]))})}}const M=(r,t)=>r.toLowerCase()===t.toLowerCase();export function restructure(r,t){const n=new T(r,t);return n.run(),n.refused?{file:r.file,rows:new Map(r.rows),refused:n.refused}:{file:n.file,rows:n.rows}}export function duplicated(r,t,n){const s=new T(r,{op:"rename-sheet",from:t,to:n});return s.duplicate(t,n),s.refused?{file:r.file,rows:new Map(r.rows),refused:s.refused}:{file:s.file,rows:s.rows}}
|
|
2
|
+
import{MAX_COLUMNS as G,MAX_ROWS as H,cellName as v,columnIndex as R,columnLetter as _,rangeName as M,readAddress as y,readArea as A,readAreas as J}from"./address.js";import{chartAfter as Q}from"./chart.js";import{moveFormula as V,relativeKey as Y}from"./formula/move.js";import{parseFormula as z}from"./formula/parse.js";import{printFormula as N}from"./formula/print.js";import{rewriteFormula as B}from"./formula/rewrite.js";import{walk as Z}from"./formula/walk.js";import{readTyped as tt}from"./values.js";import{chartFormula as nt}from"./workbook.js";const $=r=>r.op==="insert-rows"||r.op==="delete-rows"||r.op==="insert-columns"||r.op==="delete-columns",k=r=>r.op==="insert-rows"||r.op==="insert-columns",b=r=>r.op==="insert-rows"||r.op==="delete-rows";function x(r,t){return k(t)?r>=t.at?r+t.count:r:r<t.at?r:r>=t.at+t.count?r-t.count:void 0}function P(r,t){const n=y(r);if(!n)return r;const s=x(b(t)?n.row:n.col,t);if(s!==void 0)return v(b(t)?{...n,row:s}:{...n,col:s})}function K(r,t){return Object.fromEntries(Object.entries(r).flatMap(([n,s])=>{const i=P(n,t);return i===void 0?[]:[[i,s]]}))}const et=r=>b(r)?H:G;function E(r,t,n){const s=et(n);if(k(n)){const e=r>=n.at?r+n.count:r,c=t>=n.at?t+n.count:t;return e>=s?void 0:[e,Math.min(c,s-1)]}const i=n.at+n.count-1;if(r>=n.at&&t<=i)return;const a=r<n.at?r:r>i?r-n.count:n.at,o=t<n.at?t:t>i?t-n.count:n.at-1;return[a,o]}function L(r,t){const n=b(t)?E(r.top,r.bottom,t):E(r.left,r.right,t);if(n)return b(t)?{...r,top:n[0],bottom:n[1]}:{...r,left:n[0],right:n[1]}}function ot(r,t,n,s){let i=0;const a=(o,e)=>{o&&!o.abs&&(i=Math.max(i,Math.abs(o.index-e)))};return Z(r,o=>{o.kind==="ref"&&(t?(a(o.row,n),a(o.row2,n)):(a(o.col,s),a(o.col2,s)))}),i}function st(r,t,n,s){const i=new Set,a=l=>{for(let f=l-s-1;f<=l+s+1;f++)f>=r&&f<=t&&i.add(f)};a(n.at),a(n.at+n.count);const o=[...i].sort((l,f)=>l-f),e=[];let c=r;for(const l of o)l>c&&e.push([c,l-1]),e.push([l,l]),c=l+1;return c<=t&&e.push([c,t]),e}function rt(r,t,n,s,i){const a=z(t);if(!a.ok){const m=i?L(r,s):r;return m?[{area:m,text:t}]:[]}const o=b(s),[e,c]=o?[r.top,r.bottom]:[r.left,r.right],l=ot(a.node,o,r.top,r.left),f=[];let u=!0;for(const[m,d]of st(e,c,s,l)){const w=o?m:r.top,p=o?r.left:m,h=i?x(m,s):m;if(h===void 0)continue;const g=i?x(d,s):d;if(g===void 0)continue;const C=V(a.node,w-r.top,p-r.left),S=B(C,s,n);S!==C&&(u=!1);const q=o?h:r.top,D=o?r.left:h,F=Y(S,q,D),I=f[f.length-1];I?.key===F&&I.to+1===h?I.to=g:f.push({from:h,to:g,key:F,text:N(S)})}return f.map(m=>({area:o?{...r,top:m.from,bottom:m.to}:{...r,left:m.from,right:m.to},text:u&&f.length===1?t:m.text}))}function W(r,t){return r!==null&&typeof r=="object"?{...r,formula:t}:t}const it=r=>{if(typeof r=="string")return r.startsWith("=")?r:void 0;if(!(r===null||typeof r!="object"))return r.formula!==void 0?r.formula.startsWith("=")?r.formula:`=${r.formula}`:typeof r.value=="string"&&r.value.startsWith("=")?r.value:void 0};function O(r,t,n,s){const i=z(r);if(!i.ok)return r;const a=B(i.node,t,n,s);return a===i.node?r:N(a)}function ct(r,t,n,s){const i={},a=$(n)?n:void 0;for(const[o,e]of Object.entries(r)){const c=it(e),l=A(o);if(!l){i[o]=e;continue}const f=s&&a!==void 0;if(o.includes(":")){if(!a){i[o]=c===void 0?e:W(e,O(c,n,t));continue}if(c!==void 0){for(const h of rt(l,c,t,a,f))i[M(h.area)]=W(e,h.text);continue}if(!f){i[o]=e;continue}if(!k(a)){const h=L(l,a);h&&(i[M(h)]=e);continue}const d=b(a),[w,p]=d?[l.top,l.bottom]:[l.left,l.right];for(const[h,g]of[[w,Math.min(p,a.at-1)],[Math.max(w,a.at),p]]){if(h>g)continue;const C=h>=a.at?a.count:0,S=d?{...l,top:h+C,bottom:g+C}:{...l,left:h+C,right:g+C};i[M(S)]=e}continue}const u={row:l.top,col:l.left};let m=u;if(f){const d=x(b(a)?u.row:u.col,a);m=d===void 0?void 0:b(a)?{...u,row:d}:{...u,col:d}}m&&(i[v(m)]=c===void 0?e:W(e,O(c,n,t)))}return i}export function tableShape(r,t){const n=y(r.at);if(!n)return;const s=t[0]??[],i=s.map(e=>e.trim()),a=new Set(i.map(e=>e.toLowerCase()));for(const e of Object.keys(r.columns??{}))a.has(e.toLowerCase())||i.push(e);const o=[];return t.forEach((e,c)=>{c>0&&e.length>0&&o.push(c)}),{at:n,header:s,names:i,places:o}}const T=r=>r.reduce((t,n)=>Math.max(t,n.length),0);function U(r,t,n){const s=Math.max(T(r),1),i=Array.from({length:n},()=>new Array(s).fill(""));return[...r.slice(0,t),...i,...r.slice(t)]}export function freeColumn(r,t="Column"){const n=new Set(r.map(s=>s.toLowerCase()));for(let s=1;;s++){const i=`${t}${String(s)}`;if(!n.has(i.toLowerCase()))return i}}export function uniqueColumn(r,t){const n=new Set(r.map(s=>s.toLowerCase()));if(!n.has(t.toLowerCase()))return t;for(let s=2;;s++){const i=`${t}${String(s)}`;if(!n.has(i.toLowerCase()))return i}}export function withColumnsUpTo(r,t,n){const s=r.map(o=>[...o]),i=s[0]??[];for(s.length===0&&s.push(i);i.length<=n;)i.push(t[i.length]??"");const a=i.length;for(let o=1;o<s.length;o++){const e=s[o];if(e&&e.length>0)for(;e.length<a;)e.push("")}return s}class X{file;rows;edit;after=[];refused;constructor(t,n){this.file=structuredClone(t.file),this.rows=new Map(t.rows),this.edit=n}sheets(){return this.file.sheets}rewrite(t){const n=this.file.sheets[0]?.name??"";if(this.file.names)for(const[s,i]of Object.entries(this.file.names))typeof i=="string"&&i.startsWith("=")&&(this.file.names[s]=O(i,t,n));for(const s of this.file.checks??[])s.formula=O(s.formula,t,n);for(const s of this.sheets())this.rewriteSheet(s,t)}rewriteSheet(t,n){const s=$(n)&&j(t.name,n.sheet);t.cells&&(t.cells=ct(t.cells,t.name,n,s));for(const i of t.tables??[]){for(const a of Object.values(i.columns??{}))a.formula!==void 0&&(a.formula=O(a.formula,n,t.name,i.name));this.rewriteCsv(i.rows,n,t.name,i.name)}for(const i of t.blocks??[])this.rewriteCsv(i.rows,n,t.name);this.rewriteRules(t,n)}freePath(t,n){const s=t.slice(0,t.lastIndexOf("/")+1),i=o=>[...this.rows.keys()].some(e=>j(e,o));let a=`${s}${n}.csv`;for(let o=2;i(a);o++)a=`${s}${n}-${String(o)}.csv`;return a}duplicate(t,n){const s=this.sheets(),i=s.findIndex(f=>j(f.name,t)),a=s[i];if(!a){this.refused="no-sheet";return}const o=structuredClone(a);o.name=n,delete o.hidden;for(const f of Object.values(o.cells??{}))f!==null&&typeof f=="object"&&delete f.name;const e=new Set(s.flatMap(f=>f.tables??[]).map(f=>f.name.toLowerCase())),c=new Set(Object.keys(this.file.names??{}).map(f=>f.toLowerCase())),l=[];for(const f of o.tables??[]){let u=f.name;for(let d=2;;d++){u=`${f.name}${String(d)}`;const w=u.toLowerCase();if(!e.has(w)&&!c.has(w))break}e.add(u.toLowerCase());const m=this.freePath(f.rows,u);this.rows.set(m,this.rows.get(f.rows)??[]),l.push({op:"rename-table",from:f.name,to:u}),f.rows=m,f.name=u}for(const f of o.blocks??[]){const u=f.rows.slice(f.rows.lastIndexOf("/")+1,-4),m=this.freePath(f.rows,u);this.rows.set(m,this.rows.get(f.rows)??[]),f.rows=m}this.file.sheets=[...s.slice(0,i+1),o,...s.slice(i+1)],this.rewriteSheet(o,{op:"rename-sheet",from:t,to:n});for(const f of l)this.rewriteSheet(o,f)}rewriteRules(t,n){const s=e=>typeof e=="string"&&e.startsWith("=")?O(e,n,t.name):e,i=e=>e.value===void 0?e:{...e,value:s(e.value)},a=t.conditional?.map(e=>{switch(e.type){case"cellIs":return{...e,formula:e.formula.map(s)};case"expression":return{...e,formula:O(e.formula.startsWith("=")?e.formula:`=${e.formula}`,n,t.name)};case"dataBar":return{...e,...e.min?{min:i(e.min)}:{},...e.max?{max:i(e.max)}:{}};case"colorScale":return{...e,stops:e.stops.map(i)};case"iconSet":return e.stops?{...e,stops:e.stops.map(i)}:e;default:return e}});a&&(t.conditional=a);const o=t.validations?.map(e=>e.formula?{...e,formula:e.formula.map(s)}:e);o&&(t.validations=o),$(n)&&n.sheet===t.name&&(t.links&&(t.links=K(t.links,n)),t.notes&&(t.notes=K(t.notes,n)),t.pictures&&(t.pictures=t.pictures.flatMap(e=>{const c=P(e.at,n);return c===void 0?[]:[{...e,at:c}]}))),t.charts&&(t.charts=t.charts.map(e=>Q(e,c=>{const l=c.startsWith("="),f=O(nt(c),n,t.name);return l?f:f.slice(1)})))}rewriteCsv(t,n,s,i){const a=this.rows.get(t);if(!a)return;let o;a.forEach((e,c)=>{if(!e.some(f=>f.charCodeAt(0)===61))return;const l=e.map(f=>tt(f).formula===void 0?f:O(f,n,s,i));l.every((f,u)=>f===e[u])||(o??=[...a],o[c]=l)}),o&&this.rows.set(t,o)}tableOn(t,n){const s=b(n),i=[];for(const a of t.tables??[]){const o=this.rows.get(a.rows),e=o&&tableShape(a,o);if(!o||!e){i.push(a);continue}const c=e.at.row,l=e.at.col,f=c+e.places.length,u=l+Math.max(e.names.length,1)-1,[m,d]=s?[c,f]:[l,u];if(!k(n)&&n.at<=m&&n.at+n.count-1>=d){this.after.push({op:"delete-table",name:a.name});continue}const w={...e.at};if(s)if(k(n)){if(n.at<=c)w.row+=n.count;else if(n.at<=f){const p=e.places[n.at-c-1]??o.length;this.rows.set(a.rows,U(o,p,n.count))}}else{const p=n.at+n.count-1;if(p<c)w.row-=n.count;else if(n.at<=c){this.refused="table-header";return}else if(n.at<=f){const h=new Set(e.places.slice(n.at-c-1,p-c));this.rows.set(a.rows,o.filter((g,C)=>!h.has(C)))}}else if(k(n))n.at<=l?w.col+=n.count:n.at<=u&&this.columnsIn(a,e,n.at-l,n.count);else{const p=n.at+n.count-1;if(p<l)w.col-=n.count;else if(n.at<=u){w.col=Math.min(l,n.at);const h=Math.max(0,n.at-l),g=Math.min(e.names.length-1,p-l);this.columnsOut(a,e,h,g)}}a.at=v(w),i.push(a)}t.tables=i,i.length===0&&delete t.tables}columnsIn(t,n,s,i){const a=this.rows.get(t.rows)??[],o=s>0?withColumnsUpTo(a,n.names,s-1):a.map(c=>[...c]),e=[...n.names];o.forEach((c,l)=>{if(l>0&&c.length===0)return;const f=[];for(let u=0;u<i;u++)if(l===0){const m=freeColumn(e);e.push(m),f.push(m)}else f.push("");for(;c.length<s;)c.push("");c.splice(s,0,...f)}),this.rows.set(t.rows,o)}columnsOut(t,n,s,i){const a=n.names.slice(s,i+1),o=this.rows.get(t.rows)??[],e=n.header.length,c=new Set;for(let l=s;l<=i&&l<e;l++)c.add(l);if(c.size>0&&this.rows.set(t.rows,o.map(l=>l.length===0?l:l.filter((f,u)=>!c.has(u)))),t.columns){const l=new Set(a.map(f=>f.toLowerCase()));t.columns=Object.fromEntries(Object.entries(t.columns).filter(([f])=>!l.has(f.toLowerCase()))),Object.keys(t.columns).length===0&&delete t.columns}if(t.key!==void 0&&a.some(l=>l.toLowerCase()===t.key?.toLowerCase())&&delete t.key,t.filter){const l=new Set(a.map(u=>u.toLowerCase())),f=Object.fromEntries(Object.entries(t.filter.columns).filter(([u])=>!l.has(u.toLowerCase())));Object.keys(f).length>0?t.filter={columns:f}:delete t.filter}for(const l of a)this.after.push({op:"delete-column",table:t.name,name:l})}blocksOn(t,n){const s=b(n),i=(t.blocks??[]).flatMap(a=>{const o=y(a.at),e=this.rows.get(a.rows);if(!o||!e)return[a];const c=s?o.row:o.col,l=s?e.length:Math.max(T(e),1),f=c+l-1,u=E(c,f,n);if(!u)return[];const m=s?{...o,row:u[0]}:{...o,col:u[0]};if(k(n)&&n.at>c&&n.at<=f){const d=n.at-c;this.rows.set(a.rows,s?U(e,d,n.count):e.map(w=>{if(w.length===0)return w;const p=[...w];for(;p.length<d;)p.push("");return p.splice(d,0,...new Array(n.count).fill("")),p}))}else if(!k(n)&&n.at<=f){const d=Math.max(n.at,c)-c,w=Math.min(n.at+n.count-1,f)-c;this.rows.set(a.rows,s?e.filter((p,h)=>h<d||h>w):e.map(p=>p.filter((h,g)=>g<d||g>w)))}return[{...a,at:v(m)}]});t.blocks=i,i.length===0&&delete t.blocks}looksOn(t,n){const s=b(n);t.format&&(t.format=t.format.flatMap(o=>{const e=A(o.range);if(!e)return[o];const c=L(e,n);return c?[{...o,range:M(c)}]:[]})),t.format?.length===0&&delete t.format,t.merges&&(t.merges=t.merges.flatMap(o=>{const e=A(o);if(!e)return[o];const c=L(e,n);return c?[M(c)]:[]})),t.merges?.length===0&&delete t.merges;const i=o=>{const e=J(o);if(!e)return o;const c=e.flatMap(l=>{const f=L(l,n);return f?[M(f)]:[]});return c.length===0?void 0:c.join(" ")};if(t.conditional&&(t.conditional=t.conditional.flatMap(o=>{const e=i(o.range);return e===void 0?[]:[{...o,range:e}]})),t.conditional?.length===0&&delete t.conditional,t.validations&&(t.validations=t.validations.flatMap(o=>{const e=i(o.range);return e===void 0?[]:[{...o,range:e}]})),t.validations?.length===0&&delete t.validations,t.charts&&(t.charts=t.charts.map(o=>{const e=y(o.at);if(!e)return o;const c=s?e.row:e.col,l=x(c,n)??n.at;return{...o,at:v(s?{...e,row:l}:{...e,col:l})}})),t.filter){const o=A(t.filter.range),e=o&&L(o,n);if(o&&!e)delete t.filter;else if(e){const c=s?t.filter.columns:Object.fromEntries(Object.entries(t.filter.columns??{}).flatMap(([l,f])=>{const u=R(l),m=u===void 0?void 0:x(u,n);return m===void 0?[]:[[_(m),f]]}));t.filter={range:M(e),...c&&Object.keys(c).length>0?{columns:c}:{}}}}if(t.freeze!==void 0){const o=y(t.freeze);if(o){const e=s?o.row:o.col,c=E(0,e-1,n),l=e===0?0:c?c[1]+1:0;t.freeze=v(s?{...o,row:l}:{...o,col:l})}}const a=(o,e,c)=>{if(!o)return;const l={};for(const[f,u]of Object.entries(o)){const m=e(f),d=m===void 0?void 0:x(m,n);m===void 0?l[f]=u:d!==void 0&&(l[c(d)]=u)}return l};if(s){const o=a(t.rows,e=>/^[1-9]\d*$/u.test(e)?Number(e)-1:void 0,e=>String(e+1));o&&(t.rows=o)}else{const o=a(t.columns,R,_);o&&(t.columns=o)}}run(){const t=this.edit;if($(t)){const n=this.sheets().find(s=>j(s.name,t.sheet));if(!n){this.refused="no-sheet";return}if(this.rewrite(t),this.tableOn(n,t),this.refused)return;this.blocksOn(n,t),this.looksOn(n,t);for(const s of this.after)this.rewrite(s);return}switch(t.op){case"rename-sheet":{this.rewrite(t);const n=this.sheets().find(s=>j(s.name,t.from));n&&(n.name=t.to);return}case"rename-column":{this.renameColumn(t.table,t.from,t.to),this.rewrite(t);return}case"delete-sheet":{const n=this.sheets(),s=n.find(i=>j(i.name,t.name));if(!s){this.refused="no-sheet";return}if(n.filter(i=>i.hidden!==!0).length<=1){this.refused="last-sheet";return}this.rewrite(t);for(const i of s.tables??[])this.rewrite({op:"delete-table",name:i.name});this.file.sheets=n.filter(i=>i!==s);return}default:this.rewrite(t)}}renameColumn(t,n,s){const i=this.sheets().flatMap(c=>c.tables??[]).find(c=>j(c.name,t));if(!i)return;const a=n.toLowerCase(),o=this.rows.get(i.rows),e=o?.[0]?.findIndex(c=>c.trim().toLowerCase()===a)??-1;if(o&&e>=0){const c=[...o[0]??[]];c[e]=s,this.rows.set(i.rows,[c,...o.slice(1)])}if(i.columns){const c=Object.keys(i.columns).find(l=>l.toLowerCase()===a);c!==void 0&&(i.columns=Object.fromEntries(Object.entries(i.columns).map(([l,f])=>[l===c?s:l,f])))}i.key?.toLowerCase()===a&&(i.key=s),i.filter&&(i.filter={columns:Object.fromEntries(Object.entries(i.filter.columns).map(([c,l])=>[c.toLowerCase()===a?s:c,l]))})}}const j=(r,t)=>r.toLowerCase()===t.toLowerCase();export function restructure(r,t){const n=new X(r,t);return n.run(),n.refused?{file:r.file,rows:new Map(r.rows),refused:n.refused}:{file:n.file,rows:n.rows}}export function duplicated(r,t,n){const s=new X(r,{op:"rename-sheet",from:t,to:n});return s.duplicate(t,n),s.refused?{file:r.file,rows:new Map(r.rows),refused:s.refused}:{file:s.file,rows:s.rows}}
|
|
@@ -10,6 +10,8 @@ export interface DrawnPicture {
|
|
|
10
10
|
col: number;
|
|
11
11
|
/** How far into its cell, px. */
|
|
12
12
|
x: number;
|
|
13
|
+
/** Down it: a picture over the cells; one in a cell has none, and its row grows to hold it. */
|
|
14
|
+
y?: number;
|
|
13
15
|
width: number;
|
|
14
16
|
height: number;
|
|
15
17
|
name: string;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
|
|
2
|
-
import{CHART_DEFAULTS as Q,chartSpaceXml as ce}from"@allyhub-next/chart";import{columnLetter as Y}from"../address.js";import{Reference as Z,Union as ae}from"../calc/types.js";import{chartDef as fe,chartSize as de}from"../chart.js";import{sheetPrefix as le}from"../formula/print.js";import{HEAD as ue,attr as
|
|
2
|
+
import{CHART_DEFAULTS as Q,chartSpaceXml as ce}from"@allyhub-next/chart";import{columnLetter as Y}from"../address.js";import{Reference as Z,Union as ae}from"../calc/types.js";import{chartDef as fe,chartSize as de}from"../chart.js";import{sheetPrefix as le}from"../formula/print.js";import{HEAD as ue,attr as C,el as s,flag as ee,numberAttr as P,tag as o,tags as S,textOf as y}from"./xml.js";const he="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",me="http://schemas.openxmlformats.org/drawingml/2006/main",te="http://schemas.openxmlformats.org/drawingml/2006/chart",re="http://schemas.openxmlformats.org/officeDocument/2006/relationships",p=9525,xe=(e,t)=>`${le(e.sheet.name)}$${Y(e.left)}$${String(e.top+1)}${e.single?"":`:$${Y(e.right)}$${String(t+1)}`}`;function k(e,t,r){if(!r?.node)return;const n=e.eval(r.node,{sheet:t,row:0,col:0,dr:0,dc:0}),i=a=>xe(a,Math.min(a.bottom,Math.max(a.top,a.sheet.lastRow)));if(n instanceof Z)return i(n);if(n instanceof ae)return`(${n.parts.map(i).join(",")})`}function ge(e,t,r){if(!r?.node)return!1;const n=e.eval(r.node,{sheet:t,row:0,col:0,dr:0,dc:0});return n instanceof Z&&typeof e.value(n.sheet,n.top,n.left)=="number"}export function chartPart(e,t,r){const n=fe(e,t,r),i={name:f=>k(e,t,r.series[f]?.name),categories:k(e,t,r.categories),numeric:ge(e,t,r.categories),values:f=>k(e,t,r.series[f]?.values)??"",x:f=>k(e,t,r.series[f]?.x??r.categories)},a=k(e,t,r.title);return ce(n,{refs:i,...a===void 0?{}:{titleRef:a}})}const pe=(e,t,r)=>s("xdr:oneCellAnchor",{},s("xdr:from",{},`<xdr:col>${String(e.col)}</xdr:col>`,`<xdr:colOff>${String(Math.round(e.x*p))}</xdr:colOff>`,`<xdr:row>${String(e.row)}</xdr:row>`,`<xdr:rowOff>${String(Math.round((e.y??0)*p))}</xdr:rowOff>`),s("xdr:ext",{cx:Math.round(e.width*p),cy:Math.round(e.height*p)}),s("xdr:pic",{},s("xdr:nvPicPr",{},s("xdr:cNvPr",{id:t,name:e.name}),s("xdr:cNvPicPr",{},s("a:picLocks",{noChangeAspect:!0}))),s("xdr:blipFill",{},s("a:blip",{"xmlns:r":re,"r:embed":`rId${String(r)}`}),s("a:stretch",{},s("a:fillRect"))),s("xdr:spPr",{},s("a:xfrm",{},s("a:off",{x:0,y:0}),s("a:ext",{cx:Math.round(e.width*p),cy:Math.round(e.height*p)})),s("a:prstGeom",{prst:"rect"},s("a:avLst")))),s("xdr:clientData"));export function drawingPart(e,t=[]){const r=(n,i)=>{const{width:a,height:f}=de(n.spec);return s("xdr:oneCellAnchor",{},s("xdr:from",{},`<xdr:col>${String(n.at.col)}</xdr:col>`,`<xdr:colOff>${String(Math.round((n.spec.x??0)*p))}</xdr:colOff>`,`<xdr:row>${String(n.at.row)}</xdr:row>`,`<xdr:rowOff>${String(Math.round((n.spec.y??0)*p))}</xdr:rowOff>`),s("xdr:ext",{cx:Math.round(a*p),cy:Math.round(f*p)}),s("xdr:graphicFrame",{macro:""},s("xdr:nvGraphicFramePr",{},s("xdr:cNvPr",{id:i+2,name:`Chart ${String(i+1)}`}),s("xdr:cNvGraphicFramePr")),s("xdr:xfrm",{},s("a:off",{x:0,y:0}),s("a:ext",{cx:0,cy:0})),s("a:graphic",{},s("a:graphicData",{uri:te},s("c:chart",{"xmlns:c":te,"xmlns:r":re,"r:id":`rId${String(i+1)}`})))),s("xdr:clientData"))};return ue+s("xdr:wsDr",{"xmlns:xdr":he,"xmlns:a":me},...e.map(r),...t.map((n,i)=>pe(n,e.length+i+2,e.length+i+1)))}function G(e){if(Array.isArray(e))return e.map(G).join("");if(typeof e!="object"||e===null)return"";const t=e,r=[];for(const[n,i]of Object.entries(t))n==="t"?r.push(y(i)):typeof i=="object"&&r.push(G(i));return r.join("")}const T=e=>{const t=o(e?.solidFill),r=C(o(t?.srgbClr),"val");return r!==void 0?`#${r.toUpperCase()}`:we[C(o(t?.schemeClr),"val")??""]},we={accent1:"#4472C4",accent2:"#ED7D31",accent3:"#A5A5A5",accent4:"#FFC000",accent5:"#5B9BD5",accent6:"#70AD47"},O=(e,t)=>C(o(e?.[t]),"val"),$=(e,t)=>P(o(e?.[t]),"val"),D=(e,t)=>ee(o(e?.[t]),"val");function ne(e){if(!e)return;const t=o(e.tx),r=o(t?.strRef);if(r)return`=${y(r.f)}`;const n=G(t?.rich);return n===""?void 0:n}function oe(e){if(!e)return;const t=o(e.scaling),r=o(e.numFmt),n=C(r,"formatCode"),i={},a=ne(o(e.title));a!==void 0&&(i.title=a);const f=$(t,"min"),w=$(t,"max"),l=$(e,"majorUnit");return f!==void 0&&(i.min=f),w!==void 0&&(i.max=w),l!==void 0&&l>0&&(i.major=l),D(e,"delete")===!0&&(i.visible=!1),O(t,"orientation")==="maxMin"&&(i.reverse=!0),n!==void 0&&n!=="General"&&ee(r,"sourceLinked")!==!0&&(i.format=n),i}const R=e=>{const t=o(e?.numRef)??o(e?.strRef),r=t?y(t.f):"";return r===""?void 0:r};function be(e,t){const r=R(o(e[t?"yVal":"val"]));if(r===void 0)return"its numbers are written in the chart";const n={values:r},i=o(e.tx),a=R(i);if(a!==void 0)n.name=`=${a}`;else{const g=y(i?.v);g!==""&&(n.name=g)}const f=o(e.spPr),w=o(f?.ln),l=o(e.marker),c=t||l!==void 0,d=T(f)??(c?T(w)??T(o(l?.spPr)):void 0);d!==void 0&&(n.color=d);const h=P(w,"w");if(c&&h!==void 0&&w?.noFill===void 0){const g=Number((h/12700).toFixed(2));g!==Q.lineWidth&&(n.line_width=g)}D(e,"smooth")===!0&&(n.smooth=!0);const m=$(l,"size");m!==void 0&&m!==Q.marker&&(n.marker_size=m);const b=t?R(o(e.xVal)):void 0;b!==void 0&&(n.x=b);const x=t?void 0:R(o(e.cat));return{series:n,...x===void 0?{}:{categories:x}}}function ve(e){const t=O(e,"barDir")==="bar"?"bar":"column",r=O(e,"grouping");return r==="stacked"?`${t}-stacked`:r==="percentStacked"?`${t}-stacked-100`:`${t}-clustered`}function ye(e){const t=O(e,"grouping");return t==="stacked"?"area-stacked":t==="percentStacked"?"area-stacked-100":"area"}export function readChart(e){const t=o(e?.chartSpace),r=o(t?.chart),n=o(r?.plotArea);if(!r||!n)return"it has no plot";const i=Object.entries(n).filter(([u])=>u.endsWith("Chart")),[a]=i;if(!a)return"it has no plot";if(i.length>1||Array.isArray(a[1])&&a[1].length>1)return"it combines several kinds of chart";const[f,w]=a,l=o(w);if(!l)return"it has no plot";const c=S(l.ser),d=f==="scatterChart",h=[];let m;for(const u of c){const A=be(u,d);if(typeof A=="string")return A;h.push(A.series),m??=A.categories}if(h.length===0)return"it has no series";const b=u=>o(o(u.spPr)?.ln)?.noFill!==void 0,x=u=>O(o(u.marker),"symbol")==="none",g=(()=>{switch(f){case"barChart":return ve(l);case"lineChart":return c.every(x)?"line":"line-markers";case"areaChart":return ye(l);case"pieChart":return"pie";case"doughnutChart":return"doughnut";case"scatterChart":return c.every(b)?"scatter":c.some(u=>D(u,"smooth")===!0)?"scatter-smooth":"scatter-lines";default:return}})();if(!g)return`a sheet has no ${f.replace(/Chart$/u,"")} chart`;const U=ne(o(r.title)),I=o(r.legend),j=O(I,"legendPos"),V=o(l.dLbls),v=u=>D(V,u)===!0,se=v("showVal")||v("showPercent")||v("showCatName")||v("showSerName"),H=O(V,"dLblPos"),F=$(l,"gapWidth"),W=$(l,"overlap"),N=$(l,"holeSize"),X=D(l,"varyColors"),B=g==="pie"||g==="doughnut",M={value:S(n.valAx).find((u,A,ie)=>d?A===ie.length-1:!0),category:d?S(n.valAx)[0]:o(n.catAx)??o(n.dateAx)},L=oe(M.value),z=oe(M.category);L&&M.value?.majorGridlines===void 0&&(L.gridlines=!1),z&&M.category?.majorGridlines!==void 0&&(z.gridlines=!0);const E=P(o(o(o(o(t?.txPr)?.p)?.pPr)?.defRPr),"sz"),q=u=>u&&Object.keys(u).length>0?u:void 0,J=q(L),K=q(z);return{type:g,at:"A1",...U===void 0?{}:{title:U},...m===void 0?{}:{categories:m},series:B?h.slice(0,1):h,...I?{legend:j==="b"?"bottom":j==="t"?"top":j==="l"?"left":"right"}:{},...se?{labels:{...v("showVal")?{value:!0}:{},...v("showPercent")?{percentage:!0}:{},...v("showCatName")?{category:!0}:{},...v("showSerName")?{series:!0}:{},...H===void 0?{}:{position:H}}}:{},...F===void 0||F===150?{}:{gap_width:F},...W===void 0||g.includes("stacked")?{}:{overlap:W},...N===void 0||N===50?{}:{hole_size:N},...X===!0&&f==="barChart"?{vary_by_categories:!0}:{},...X===!1&&B?{vary_by_categories:!1}:{},...J?{value_axis:J}:{},...K?{category_axis:K}:{},...E===void 0||E===900?{}:{size:E/100}}}const _=e=>Math.round(e/p);export function chartAnchors(e,t,r){const n=o(e?.wsDr),i=[];let a=0;const f=c=>({col:Number(y(c?.col)),row:Number(y(c?.row)),colOff:_(Number(y(c?.colOff))),rowOff:_(Number(y(c?.rowOff)))}),w=c=>C(o(o(o(o(c.graphicFrame)?.graphic)?.graphicData)?.chart),"id"),l=(c,d,h,m)=>{const b=w(c);if(b===void 0){a+=1;return}i.push({id:b,at:{row:d.row,col:d.col},...d.colOff>0?{x:d.colOff}:{},...d.rowOff>0?{y:d.rowOff}:{},width:h,height:m})};for(const c of S(n?.oneCellAnchor)){const d=o(c.ext);l(c,f(o(c.from)),_(P(d,"cx")??0),_(P(d,"cy")??0))}for(const c of S(n?.twoCellAnchor)){const d=f(o(c.from)),h=f(o(c.to));let m=h.colOff-d.colOff;for(let x=d.col;x<h.col;x++)m+=t(x);let b=h.rowOff-d.rowOff;for(let x=d.row;x<h.row;x++)b+=r(x);l(c,d,m,b)}return{anchors:i,others:a}}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ZipLimits } from "@allyhub-next/formats";
|
|
1
2
|
import type { SheetProblem } from "../file.js";
|
|
2
3
|
import { type Scalar } from "../values.js";
|
|
3
4
|
/** How far apart two numbers may be, as a share of the larger, and be the same. */
|
|
@@ -36,6 +37,8 @@ export interface ImportOptions {
|
|
|
36
37
|
name: string;
|
|
37
38
|
/** See COMPARE_TOLERANCE. */
|
|
38
39
|
tolerance?: number;
|
|
40
|
+
/** What the file may unzip to; ZIP_LIMITS unless it says. */
|
|
41
|
+
zip?: Partial<ZipLimits>;
|
|
39
42
|
}
|
|
40
43
|
/** Whether a value the engine gives is what a file cached. */
|
|
41
44
|
export declare function sameValue(a: Scalar, b: Scalar, tolerance: number): boolean;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
|
|
2
|
-
import{SHEET_DATA as G,SHEET_FILE as Q}from"@allyhub-next/formats";import{cellName as $,columnLetter as A,contains as z,overlaps as D,rangeName as x,readAddress as Z,readArea as ee}from"../address.js";import{rectangles as _}from"../api/rectangles.js";import{chartAfter as te}from"../chart.js";import{analyse as oe}from"../calc/analyse.js";import{FUNCTIONS as ne}from"../calc/functions/index.js";import{checkWorkbook as se}from"../check.js";import{writeCsv as I}from"../csv.js";import{isDateCode as W}from"../format.js";import{moveFormula as re,relativeKey as B}from"../formula/move.js";import{printFormula as M,sheetPrefix as ie}from"../formula/print.js";import{mapNode as le,walk as N}from"../formula/walk.js";import{CellError as T,isoOfSerial as fe,readTyped as F,writeTyped as P}from"../values.js";import{FormulaCell as ae,placeKey as g,validName as R}from"../workbook.js";import{writeYaml as ce}from"../write.js";import{readFileFormula as ue}from"./formula.js";import{hasDate as H}from"./numfmt.js";import{placesLine as J,readXlsx as de}from"./read.js";const K=100,he=.5,q=1462;export const COMPARE_TOLERANCE=1e-9;const me=f=>f.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/gu,"")||"rows",b=f=>Object.keys(f).length===0,V=(f,e)=>`${String(f)} ${e}${f===1?"":"s"}`,C=f=>({row:f.row,col:f.col});function X(f,e){const o=e.toLowerCase();return le(f,n=>n.kind!=="structured"||n.table?.toLowerCase()!==o?n:Object.fromEntries(Object.entries(n).filter(([i])=>i!=="table")))}function Y(f){return f.headers===0?"has no header row":f.columns.length!==f.ref.right-f.ref.left+1||!R(f.name)?"cannot be held as a table":new Set(f.columns.map(e=>e.name.toLowerCase())).size===f.columns.length?void 0:"has two columns of one name"}function U(f,e,o){let n;const i=new Set;N(f,t=>{t.kind==="call"&&(t.name==="LET"||t.name==="LAMBDA")&&t.args.forEach(r=>{r.kind==="name"&&i.add(r.name.toLowerCase())})});const s=t=>i.has(t)||o===void 0||o.names.has(t)||o.tables.has(t);return N(f,t=>{n===void 0&&(t.kind==="call"&&!ne.has(t.name)&&(s(t.written.toLowerCase())||(n=`no function ${t.name}`)),t.kind==="name"&&!s(t.name.toLowerCase())&&(n=`no name ${t.name}`),t.kind==="structured"&&t.table!==void 0&&!s(t.table.toLowerCase())&&(n=`no table ${t.table}`),(t.kind==="ref"||t.kind==="name"||t.kind==="error")&&t.sheet!==void 0&&(t.sheet.startsWith("[")?n="it reads another workbook":e.has(t.sheet.toLowerCase())||(n=`no sheet ${t.sheet}`)))}),n}function pe(f){const e=new Set(f.book.sheets.map(o=>o.name.toLowerCase()));for(const o of f.book.sheets){const n=new Map,i=(t,r)=>{const l=n.get(r),c=$(t);l?l.push(c):n.set(r,[c])},s=[];for(const t of o.cells){if(t.unread!==void 0){i(t,/^\[|[!']\[|\[\d+\]/u.test(t.unread)?"it reads another workbook":`it could not be read: ${t.unread}`);continue}if(!t.node)continue;const r=U(t.node,e,f);r!==void 0?(delete t.node,i(t,r)):(f.carried.set(t,o),t.array&&x(t.array)!==$(t)&&s.push(t))}we(f,o,s);for(const[t,r]of n)f.lost.push(`${o.name}: ${V(r.length,"formula")} kept as ${r.length===1?"its value":"their values"}, as ${t} (${J(r)})`)}}function we(f,e,o){if(o.length===0)return;const n=new Set;for(const i of o){const{array:s}=i;if(s)for(const t of e.cells)t!==i&&!t.node&&z(s,t.row,t.col)&&n.add(t)}e.cells=e.cells.filter(i=>!n.has(i));for(const i of n)f.spilled.set(i,e)}function O(f,e){const{value:o}=e;if(!f.book.date1904||typeof o!="number")return o;const n=f.book.looks[e.style]?.format;return W(n)&&n!==void 0&&H(n)?o+q:o}function j(f,e){if(typeof f!="number"||e===void 0||!W(e)||!H(e)||f<1)return;const o=fe(f);return F(o).value===f?o:void 0}const ge=(f,e)=>j(f,e)??P(f??null);function ke(f,e){const o=j(f,e);return o!==void 0?o:f==null?null:typeof f=="number"||typeof f=="boolean"?f:P(f)}function be(f){const e={top:1/0,left:1/0,bottom:-1,right:-1};for(const{row:o,col:n}of f)e.top=Math.min(e.top,o),e.left=Math.min(e.left,n),e.bottom=Math.max(e.bottom,o),e.right=Math.max(e.right,n);return e}class ye{ctx;read;byPlace=new Map;inTables=new Set;columnLooks=new Map;rowLooks=new Map;lookDone=new Set;tables=[];areas=[];filtered=[];constructor(e,o){this.ctx=e,this.read=o;for(const n of o.cells)this.byPlace.set(g(n.row,n.col),n)}look(e){return this.ctx.book.looks[e.style]??{}}code(e){return this.look(e).format}text(e){return e.node?M(e.node):ge(O(this.ctx,e),this.code(e))}baseLooks(){const{read:e}=this,{looks:o}=this.ctx.book,n=e.cells.reduce((s,t)=>Math.max(s,t.col),-1);for(const s of e.columns){if(s.style===void 0)continue;const t=o[s.style];if(!(!t||b(t)))for(let r=s.min;r<=Math.min(s.max,n);r++)this.columnLooks.set(r,t)}for(const s of e.rows){const t=s.style===void 0?void 0:o[s.style];t&&!b(t)&&this.rowLooks.set(s.row,t)}const i=(s,t)=>Object.keys(t).every(r=>r in s);for(const s of e.cells){const t=this.look(s),r=this.columnLooks.get(s.col);r&&!i(t,r)&&this.columnLooks.delete(s.col);const l=this.rowLooks.get(s.row);l&&!i(t,l)&&this.rowLooks.delete(s.row)}}ownLook(e){const o={...this.columnLooks.get(e.col),...this.rowLooks.get(e.row)},n={};for(const[s,t]of Object.entries(this.look(e)))JSON.stringify(t)!==JSON.stringify(o[s])&&(n[s]=t);const i=n.format;if(typeof i=="string"){const s=e.node?void 0:j(O(this.ctx,e),i);s!==void 0&&F(s).format===i&&delete n.format}return n}columnFormula(e,o,n){const i=new Map,s=n-o+1;for(let r=o;r<=n;r++){const l=this.byPlace.get(g(r,e));if(!l||l.value===void 0&&!l.node||l.value===null&&!l.node)return;if(!l.node)continue;l.key??=B(l.node,l.row,l.col);const c=i.get(l.key);c?c.n+=1:i.set(l.key,{n:1,cell:l})}let t;for(const r of i.values())(!t||r.n>t.n)&&(t=r);return t&&t.n*2>s?t.cell:void 0}table(e){const{read:o,ctx:n}=this,i=h=>n.lost.push(`${o.name}: table ${e.name} ${h}`),s=e.ref.right-e.ref.left+1,t=Y(e);if(t!==void 0)return i(`${t}, so its cells are kept and it is no table`),!1;const r=e.ref.top,l=r+1,c=e.ref.bottom-e.totals;e.totals>0&&i("has a totals row, kept as plain cells under it");const a=e.columns.map((h,m)=>c>=l?this.columnFormula(e.ref.left+m,l,c):void 0),u=h=>{const m=a[h];if(!m)return!1;for(let k=l;k<=c;k++)if(this.byPlace.get(g(k,e.ref.left+h))?.key!==m.key)return!1;return!0};let d=s;for(;d>1&&u(d-1);)d-=1;const w=[e.columns.slice(0,d).map(h=>h.name)],p={};for(let h=l;h<=c;h++){const m=[];for(let k=0;k<d;k++){const y=this.byPlace.get(g(h,e.ref.left+k)),v=a[k];y?v&&y.key===v.key?m.push(""):y.node?m.push(M(X(y.node,e.name))):m.push(this.text(y)):m.push("")}w.push(m)}for(let h=e.ref.top;h<=c;h++)for(let m=e.ref.left;m<=e.ref.right;m++)this.inTables.add(g(h,m));e.columns.forEach((h,m)=>{const k=e.ref.left+m,y=this.columnLook(k,l,c),v=a[m];v?.node&&(y.formula=M(X(re(v.node,l-v.row,0),e.name))),b(y)||(p[h.name]=y)});const L=this.path(e.name);n.files.set(L,I(w));const E=new Map;for(const[h,m]of e.filter?.columns??[]){const k=e.columns[h]?.name;k!==void 0&&E.set(k,m)}return(e.filter?.unread??0)>0&&i(`has ${V(e.filter?.unread??0,"filter")} by condition, its rows left as they were hidden`),this.tables.push({name:e.name,at:$({row:r,col:e.ref.left}),rows:L,...e.style!==void 0&&e.style!=="TableStyleMedium2"?{style:e.style}:{},...b(p)?{}:{columns:p},...e.filter===void 0?{filter:!1}:E.size>0?{filter:{columns:Object.fromEntries(E)}}:{}}),e.filter?.unread===0&&e.filter.columns.size>0&&this.filtered.push({...e.ref,bottom:c}),this.areas.push({...e.ref,bottom:c}),!0}columnLook(e,o,n){let i,s={};for(let t=o;t<=n;t++){const r=this.byPlace.get(g(t,e)),l=r?this.ownLook(r):{},c=JSON.stringify(l);if(i===void 0)i=c,s=l;else if(i!==c)return{}}if(b(s))return{};for(let t=o;t<=n;t++)this.lookDone.add(g(t,e));return{...s}}path(e){const o=`${G}/${me(e)}`;let n=`${o}.csv`;for(let i=2;this.ctx.files.has(n);i++)n=`${o}-${String(i)}.csv`;return n}loose(){const e=[],o=[];for(const n of this.read.cells)this.inTables.has(g(n.row,n.col))||(n.node?e.push(n):n.value!==void 0&&n.value!==null&&o.push(n));return{formulas:e,typed:o}}blockAreas(e,o){const n=new Map;e.forEach((a,u)=>n.set(g(a.row,a.col),u));const i=e.map((a,u)=>u),s=a=>{let u=a;for(;i[u]!==u;){const d=i[i[u]??u]??u;i[u]=d,u=d}return u};e.forEach((a,u)=>{for(const d of[n.get(g(a.row,a.col-1)),n.get(g(a.row-1,a.col))])d!==void 0&&(i[s(u)]=s(d))});const t=new Map;e.forEach((a,u)=>{const d=s(u),w=t.get(d);w?w.push(a):t.set(d,[a])});const r=[],l=a=>!r.some(u=>D(u,a))&&!this.areas.some(u=>D(u,a))&&!o.some(u=>z(a,u.row,u.col)),c=a=>(a.bottom-a.top+1)*(a.right-a.left+1);for(const a of t.values()){const u=be(a);if(!(c(u)<K)){if(a.length/c(u)>=he&&l(u)){r.push(u);continue}for(const d of _(a.map(C)))c(d)>=K&&l(d)&&r.push(d)}}return r.sort((a,u)=>a.top-u.top||a.left-u.left)}cells(e){const{formulas:o,typed:n}=this.loose(),i=this.blockAreas(n,o),s=l=>i.some(c=>z(c,l.row,l.col));i.length>0&&(e.blocks=i.map(l=>{const c=[];for(let u=l.top;u<=l.bottom;u++){const d=[];for(let w=l.left;w<=l.right;w++){const p=this.byPlace.get(g(u,w));d.push(p?this.text(p):"")}c.push(d)}const a=this.path(this.read.name);return this.ctx.files.set(a,I(c)),{at:$({row:l.top,col:l.left}),rows:a}}));const t=[],r=new Map;for(const l of o){if(!l.node)continue;l.key??=B(l.node,l.row,l.col);const c=r.get(l.key);c?c.push(l):r.set(l.key,[l])}for(const l of r.values())for(const c of _(l.map(C))){const a=this.byPlace.get(g(c.top,c.left));a?.node&&t.push([{row:c.top,col:c.left},x(c),M(a.node)])}for(const l of n)i.length>0&&s(l)||t.push([C(l),$(l),ke(O(this.ctx,l),this.code(l))]);t.sort(([l],[c])=>l.row-c.row||l.col-c.col),t.length>0&&(e.cells=Object.fromEntries(t.map(([,l,c])=>[l,c])))}formats(e){const o=new Map;for(const i of this.read.cells){if(this.lookDone.has(g(i.row,i.col)))continue;const s=this.ownLook(i);if(b(s))continue;const t=JSON.stringify(s),r=o.get(t);r?r.places.push(C(i)):o.set(t,{look:s,places:[C(i)]})}const n=[];for(const{look:i,places:s}of o.values())for(const t of _(s))n.push({range:x(t),...i});n.length>0&&(e.format=n)}columns(e){const{read:o}=this,n=new Map,i=o.cells.reduce((t,r)=>Math.max(t,r.col),0),s=[];for(const t of o.columns)if(!(t.width===void 0&&t.hidden!==!0)){t.max>i&&s.push(A(Math.max(t.min,i+1)));for(let r=t.min;r<=Math.min(t.max,i);r++)n.set(r,{...t.width===void 0?{}:{width:t.width},...t.hidden===!0?{hidden:!0}:{}})}for(const[t,r]of this.columnLooks)n.set(t,{...n.get(t),...r});n.size>0&&(e.columns=Object.fromEntries([...n.keys()].sort((t,r)=>t-r).map(t=>[A(t),n.get(t)??{}]))),s.some(Boolean)&&o.columns.some(t=>t.max>i&&t.hidden===!0)&&this.ctx.lost.push(`${o.name}: the size of the columns past its last used one`)}rows(e){const o={};for(const n of this.read.rows){const i=this.rowLooks.get(n.row),s=this.filtered.some(r=>n.row>r.top&&n.row<=r.bottom),t={...n.height===void 0?{}:{height:n.height},...n.hidden===!0&&!s?{hidden:!0}:{},...i};b(t)||(o[String(n.row+1)]=t)}b(o)||(e.rows=o)}build(){const{read:e}=this;this.baseLooks();for(const n of e.tables)this.table(n);const o={name:e.name};return e.state!=="visible"&&(o.hidden=!0),e.gridlines===!1&&(o.gridlines=!1),e.tab!==void 0&&(o.tab=e.tab),e.state==="veryHidden"&&this.ctx.lost.push(`${e.name}: being very hidden; it is hidden`),e.freeze&&(e.freeze.row>0||e.freeze.col>0)&&(o.freeze=$(e.freeze)),this.tables.length>0&&(o.tables=this.tables),this.filter(o),this.columns(o),this.rows(o),this.cells(o),e.merges.length>0&&(o.merges=e.merges.map(x)),this.formats(o),e.conditional.length>0&&(o.conditional=e.conditional),e.validations.length>0&&(o.validations=e.validations),e.charts.length>0&&(o.charts=e.charts.map(n=>this.chart(n))),o}chart(e){return te(e,o=>{const n=this.chartReference(o.replace(/^=/u,""));return o.startsWith("=")?`=${n}`:n})}chartReference(e){const o=e.lastIndexOf("!"),i=(o<0?this.read.name:e.slice(0,o)).replace(/^'|'$/gu,"").replaceAll("''","'"),s=ee(e.slice(o+1).replaceAll("$",""));if(!s)return e;const t=this.ctx.book.sheets.find(r=>r.name.toLowerCase()===i.toLowerCase());for(const r of t?.tables??[]){const l=r.ref.top+1,a=s.left===s.right&&s.top===l&&s.bottom===r.ref.bottom&&s.left>=r.ref.left&&s.left<=r.ref.right?r.columns[s.left-r.ref.left]:void 0;if(a&&this.ctx.tables.has(r.name.toLowerCase()))return`${r.name}[${a.name}]`}return`${t===this.read||o<0?"":`${e.slice(0,o)}!`}${x(s)}`}filter(e){const{filter:o}=this.read;if(!o)return;const n={};for(const[i,s]of o.columns)n[A(o.ref.left+i)]=s;e.filter={range:x(o.ref),...b(n)?{}:{columns:n}},o.unread===0&&!b(n)&&this.filtered.push(o.ref)}}function $e(f){const e={},{book:o,lost:n}=f,i=new Set(o.sheets.map(r=>r.name.toLowerCase())),s=new Set,t=new Set;for(const r of o.names){if(r.name.startsWith("_xlnm.")){r.name==="_xlnm.Print_Area"?t.add("print areas"):r.name==="_xlnm.Print_Titles"?t.add("print titles"):r.name!=="_xlnm._FilterDatabase"&&n.push(`Excel's name ${r.name}`);continue}if(/^_xl(?:fn|pm|ws|udf)/iu.test(r.name))continue;const l=r.name.toLowerCase();if(!R(r.name)||f.tables.has(l)){n.push(`the name ${r.name}, which cannot be held here`);continue}if(s.has(l)){n.push(`a second name ${r.name}, for one sheet: names here are the workbook's`);continue}const c=xe(r.text);if(c!==void 0)e[r.name]=typeof c=="string"?P(c):c,s.add(l),f.names.add(l);else{const a=ue(r.text,!0),u=a.ok?U(a.node,i):"it could not be read";if(!a.ok||u!==void 0||ve(a.node)){n.push(`the name ${r.name} (${r.text})${u===void 0?"":`: ${u}`}`);continue}e[r.name]=M(a.node),s.add(l),f.names.add(l)}r.sheet!==void 0&&n.push(`the name ${r.name} belonging to one sheet: here it is the workbook's`)}return t.size>0&&n.push([...t].join(" and ")),e}function Le(f,e){const o={},n=new Map;for(const[i,s]of Object.entries(e))typeof s=="string"&&s.startsWith("=")&&n.set(s.slice(1).replaceAll("$","").toLowerCase(),i);for(const i of f.book.sheets)for(const s of i.scenarios){const t={};let r=!0;for(const{at:l,value:c}of s.cells){const a=Z(l),u=a&&i.cells.find(p=>p.row===a.row&&p.col===a.col);String(u?.value??"")!==c&&(r=!1);const d=n.get(`${ie(i.name)}${l}`.toLowerCase())??n.get(l.toLowerCase()),w=F(c);d===void 0?f.lost.push(`${i.name}: scenario ${s.name}'s cell ${l}, which has no name`):t[d]=typeof w.value=="number"?w.value:c}!r&&!b(t)&&(o[s.name]={...o[s.name],...t})}return o}function ve(f){let e=!1;return N(f,o=>{e||=o.kind==="error"&&o.code==="#REF!"}),e}function xe(f){const e=f.trim();return/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/u.test(e)?Number(e):/^true$/iu.test(e)?!0:/^false$/iu.test(e)?!1:/^"((?:[^"]|"")*)"$/u.exec(e)?.[1]?.replaceAll('""','"')}const S=f=>f instanceof T?f.code:f??null;export function sameValue(f,e,o){if(typeof f=="number"&&typeof e=="number")return f===e?!0:Math.abs(f-e)<=Math.max(Math.abs(f),Math.abs(e))*o;if(f instanceof T||e instanceof T)return f?.code===e?.code;if(f===null||e===null){const n=f??e;return n===null||n===""||n===0||n===!1}return f===e}function Me(f,e){const o=[];for(const s of e.sheets)for(const t of s.formulas)t.shared.node&&oe(e,t.shared).volatile&&o.push(t);const n=new Set(o),i=[...o];for(;;){const s=i.pop();if(!s)return n;for(const t of f.readers(s.sheet,s.row,s.col))n.has(t)||(n.add(t),i.push(t))}}function Ce(f,e,o,n){const i={formulas:0,same:0,uncached:0,moving:0,differences:[]},s=Me(o,e);for(const[t,r]of f.carried){if(!t.node)continue;const l=e.sheet(r.name);if(!l)continue;i.formulas+=1;const c=l.at(t.row,t.col);if(c instanceof ae&&s.has(c)){i.moving+=1;continue}const a=O(f,t);if(a===void 0){i.uncached+=1;continue}const u=o.value(l,t.row,t.col);sameValue(a,u,n)?i.same+=1:i.differences.push({sheet:r.name,cell:$(t),formula:M(t.node),file:S(a),engine:S(u)})}for(const[t,r]of f.spilled){const l=e.sheet(r.name);if(!l)continue;i.formulas+=1;const c=l.spillAt(t.row,t.col);if(c&&s.has(c)){i.moving+=1;continue}const a=O(f,t),u=o.value(l,t.row,t.col);a===void 0?i.uncached+=1:sameValue(a,u,n)?i.same+=1:i.differences.push({sheet:r.name,cell:$(t),formula:c?`${$(c)}#`:"",file:S(a),engine:S(u)})}return i}function Oe(f,e){const o=new Map,n=[];for(const i of f){const s=e.find(l=>i.startsWith(`${l}: `));if(s===void 0){n.push(i);continue}const t=i.slice(s.length+2),r=o.get(t);r?r.push(s):o.set(t,[s])}for(const[i,s]of o)n.push(s.length===1?`${s[0]??""}: ${i}`:`${i}, on ${String(s.length)} sheets (${J(s)})`);return n}export function importXlsx(f,e){const o=de(f);if(o.sheets.length===0)throw new Error("It holds no sheets.");const n={book:o,files:new Map,lost:[...o.lost],tables:new Set(o.sheets.flatMap(p=>p.tables.filter(L=>Y(L)===void 0).map(L=>L.name.toLowerCase()))),names:new Set,carried:new Map,spilled:new Map};o.date1904&&n.lost.push(`the 1904 date system: dates are moved to the 1900 one, ${String(q)} days on`),(o.font.name!==void 0&&o.font.name!=="Calibri"||o.font.size!==void 0&&o.font.size!==11)&&n.lost.push(`its default font, ${o.font.name??""} ${String(o.font.size??"")}`);const i=$e(n);pe(n);const s=o.sheets.map(p=>new ye(n,p).build()),t=Le(n,i),r={title:e.name,...b(i)?{}:{names:i},sheets:s,...b(t)?{}:{scenarios:t}},l=ce(r),c=new Map([[Q,l],...n.files]),a=se({text:l,read:p=>c.get(p)}),{workbook:u,calc:d,problems:w}=a;return{files:c,lost:Oe(n.lost,o.sheets.map(p=>p.name)),problems:w,compared:u&&d?Ce(n,u,d,e.tolerance??COMPARE_TOLERANCE):{formulas:0,same:0,uncached:0,moving:0,differences:[]},sheets:o.sheets.length,tables:n.tables.size}}
|
|
2
|
+
import{SHEET_DATA as G,SHEET_FILE as Q}from"@allyhub-next/formats";import{cellName as $,columnLetter as z,contains as A,overlaps as D,rangeName as x,readAddress as Z,readArea as ee}from"../address.js";import{rectangles as _}from"../api/rectangles.js";import{chartAfter as te}from"../chart.js";import{analyse as oe}from"../calc/analyse.js";import{FUNCTIONS as ne}from"../calc/functions/index.js";import{checkWorkbook as se}from"../check.js";import{writeCsv as I}from"../csv.js";import{isDateCode as W}from"../format.js";import{moveFormula as re,relativeKey as B}from"../formula/move.js";import{printFormula as M,sheetPrefix as ie}from"../formula/print.js";import{mapNode as le,walk as N}from"../formula/walk.js";import{CellError as T,isoOfSerial as fe,readTyped as F,writeTyped as P}from"../values.js";import{FormulaCell as ae,placeKey as g,validName as R}from"../workbook.js";import{writeYaml as ce}from"../write.js";import{readFileFormula as ue}from"./formula.js";import{hasDate as H}from"./numfmt.js";import{placesLine as J,readXlsx as de}from"./read.js";const K=100,he=.5,q=1462;export const COMPARE_TOLERANCE=1e-9;const me=f=>f.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/gu,"")||"rows",b=f=>Object.keys(f).length===0,V=(f,e)=>`${String(f)} ${e}${f===1?"":"s"}`,C=f=>({row:f.row,col:f.col});function X(f,e){const o=e.toLowerCase();return le(f,n=>n.kind!=="structured"||n.table?.toLowerCase()!==o?n:Object.fromEntries(Object.entries(n).filter(([i])=>i!=="table")))}function Y(f){return f.headers===0?"has no header row":f.columns.length!==f.ref.right-f.ref.left+1||!R(f.name)?"cannot be held as a table":new Set(f.columns.map(e=>e.name.toLowerCase())).size===f.columns.length?void 0:"has two columns of one name"}function U(f,e,o){let n;const i=new Set;N(f,t=>{t.kind==="call"&&(t.name==="LET"||t.name==="LAMBDA")&&t.args.forEach(r=>{r.kind==="name"&&i.add(r.name.toLowerCase())})});const s=t=>i.has(t)||o===void 0||o.names.has(t)||o.tables.has(t);return N(f,t=>{n===void 0&&(t.kind==="call"&&!ne.has(t.name)&&(s(t.written.toLowerCase())||(n=`no function ${t.name}`)),t.kind==="name"&&!s(t.name.toLowerCase())&&(n=`no name ${t.name}`),t.kind==="structured"&&t.table!==void 0&&!s(t.table.toLowerCase())&&(n=`no table ${t.table}`),(t.kind==="ref"||t.kind==="name"||t.kind==="error")&&t.sheet!==void 0&&(t.sheet.startsWith("[")?n="it reads another workbook":e.has(t.sheet.toLowerCase())||(n=`no sheet ${t.sheet}`)))}),n}function pe(f){const e=new Set(f.book.sheets.map(o=>o.name.toLowerCase()));for(const o of f.book.sheets){const n=new Map,i=(t,r)=>{const l=n.get(r),c=$(t);l?l.push(c):n.set(r,[c])},s=[];for(const t of o.cells){if(t.unread!==void 0){i(t,/^\[|[!']\[|\[\d+\]/u.test(t.unread)?"it reads another workbook":`it could not be read: ${t.unread}`);continue}if(!t.node)continue;const r=U(t.node,e,f);r!==void 0?(delete t.node,i(t,r)):(f.carried.set(t,o),t.array&&x(t.array)!==$(t)&&s.push(t))}we(f,o,s);for(const[t,r]of n)f.lost.push(`${o.name}: ${V(r.length,"formula")} kept as ${r.length===1?"its value":"their values"}, as ${t} (${J(r)})`)}}function we(f,e,o){if(o.length===0)return;const n=new Set;for(const i of o){const{array:s}=i;if(s)for(const t of e.cells)t!==i&&!t.node&&A(s,t.row,t.col)&&n.add(t)}e.cells=e.cells.filter(i=>!n.has(i));for(const i of n)f.spilled.set(i,e)}function O(f,e){const{value:o}=e;if(!f.book.date1904||typeof o!="number")return o;const n=f.book.looks[e.style]?.format;return W(n)&&n!==void 0&&H(n)?o+q:o}function j(f,e){if(typeof f!="number"||e===void 0||!W(e)||!H(e)||f<1)return;const o=fe(f);return F(o).value===f?o:void 0}const ge=(f,e)=>j(f,e)??P(f??null);function ke(f,e){const o=j(f,e);return o!==void 0?o:f==null?null:typeof f=="number"||typeof f=="boolean"?f:P(f)}function be(f){const e={top:1/0,left:1/0,bottom:-1,right:-1};for(const{row:o,col:n}of f)e.top=Math.min(e.top,o),e.left=Math.min(e.left,n),e.bottom=Math.max(e.bottom,o),e.right=Math.max(e.right,n);return e}class ye{ctx;read;byPlace=new Map;inTables=new Set;columnLooks=new Map;rowLooks=new Map;lookDone=new Set;tables=[];areas=[];filtered=[];constructor(e,o){this.ctx=e,this.read=o;for(const n of o.cells)this.byPlace.set(g(n.row,n.col),n)}look(e){return this.ctx.book.looks[e.style]??{}}code(e){return this.look(e).format}text(e){return e.node?M(e.node):ge(O(this.ctx,e),this.code(e))}baseLooks(){const{read:e}=this,{looks:o}=this.ctx.book,n=e.cells.reduce((s,t)=>Math.max(s,t.col),-1);for(const s of e.columns){if(s.style===void 0)continue;const t=o[s.style];if(!(!t||b(t)))for(let r=s.min;r<=Math.min(s.max,n);r++)this.columnLooks.set(r,t)}for(const s of e.rows){const t=s.style===void 0?void 0:o[s.style];t&&!b(t)&&this.rowLooks.set(s.row,t)}const i=(s,t)=>Object.keys(t).every(r=>r in s);for(const s of e.cells){const t=this.look(s),r=this.columnLooks.get(s.col);r&&!i(t,r)&&this.columnLooks.delete(s.col);const l=this.rowLooks.get(s.row);l&&!i(t,l)&&this.rowLooks.delete(s.row)}}ownLook(e){const o={...this.columnLooks.get(e.col),...this.rowLooks.get(e.row)},n={};for(const[s,t]of Object.entries(this.look(e)))JSON.stringify(t)!==JSON.stringify(o[s])&&(n[s]=t);const i=n.format;if(typeof i=="string"){const s=e.node?void 0:j(O(this.ctx,e),i);s!==void 0&&F(s).format===i&&delete n.format}return n}columnFormula(e,o,n){const i=new Map,s=n-o+1;for(let r=o;r<=n;r++){const l=this.byPlace.get(g(r,e));if(!l||l.value===void 0&&!l.node||l.value===null&&!l.node)return;if(!l.node)continue;l.key??=B(l.node,l.row,l.col);const c=i.get(l.key);c?c.n+=1:i.set(l.key,{n:1,cell:l})}let t;for(const r of i.values())(!t||r.n>t.n)&&(t=r);return t&&t.n*2>s?t.cell:void 0}table(e){const{read:o,ctx:n}=this,i=h=>n.lost.push(`${o.name}: table ${e.name} ${h}`),s=e.ref.right-e.ref.left+1,t=Y(e);if(t!==void 0)return i(`${t}, so its cells are kept and it is no table`),!1;const r=e.ref.top,l=r+1,c=e.ref.bottom-e.totals;e.totals>0&&i("has a totals row, kept as plain cells under it");const a=e.columns.map((h,m)=>c>=l?this.columnFormula(e.ref.left+m,l,c):void 0),u=h=>{const m=a[h];if(!m)return!1;for(let k=l;k<=c;k++)if(this.byPlace.get(g(k,e.ref.left+h))?.key!==m.key)return!1;return!0};let d=s;for(;d>1&&u(d-1);)d-=1;const w=[e.columns.slice(0,d).map(h=>h.name)],p={};for(let h=l;h<=c;h++){const m=[];for(let k=0;k<d;k++){const y=this.byPlace.get(g(h,e.ref.left+k)),v=a[k];y?v&&y.key===v.key?m.push(""):y.node?m.push(M(X(y.node,e.name))):m.push(this.text(y)):m.push("")}w.push(m)}for(let h=e.ref.top;h<=c;h++)for(let m=e.ref.left;m<=e.ref.right;m++)this.inTables.add(g(h,m));e.columns.forEach((h,m)=>{const k=e.ref.left+m,y=this.columnLook(k,l,c),v=a[m];v?.node&&(y.formula=M(X(re(v.node,l-v.row,0),e.name))),b(y)||(p[h.name]=y)});const L=this.path(e.name);n.files.set(L,I(w));const E=new Map;for(const[h,m]of e.filter?.columns??[]){const k=e.columns[h]?.name;k!==void 0&&E.set(k,m)}return(e.filter?.unread??0)>0&&i(`has ${V(e.filter?.unread??0,"filter")} by condition, its rows left as they were hidden`),this.tables.push({name:e.name,at:$({row:r,col:e.ref.left}),rows:L,...e.style!==void 0&&e.style!=="TableStyleMedium2"?{style:e.style}:{},...b(p)?{}:{columns:p},...e.filter===void 0?{filter:!1}:E.size>0?{filter:{columns:Object.fromEntries(E)}}:{}}),e.filter?.unread===0&&e.filter.columns.size>0&&this.filtered.push({...e.ref,bottom:c}),this.areas.push({...e.ref,bottom:c}),!0}columnLook(e,o,n){let i,s={};for(let t=o;t<=n;t++){const r=this.byPlace.get(g(t,e)),l=r?this.ownLook(r):{},c=JSON.stringify(l);if(i===void 0)i=c,s=l;else if(i!==c)return{}}if(b(s))return{};for(let t=o;t<=n;t++)this.lookDone.add(g(t,e));return{...s}}path(e){const o=`${G}/${me(e)}`;let n=`${o}.csv`;for(let i=2;this.ctx.files.has(n);i++)n=`${o}-${String(i)}.csv`;return n}loose(){const e=[],o=[];for(const n of this.read.cells)this.inTables.has(g(n.row,n.col))||(n.node?e.push(n):n.value!==void 0&&n.value!==null&&o.push(n));return{formulas:e,typed:o}}blockAreas(e,o){const n=new Map;e.forEach((a,u)=>n.set(g(a.row,a.col),u));const i=e.map((a,u)=>u),s=a=>{let u=a;for(;i[u]!==u;){const d=i[i[u]??u]??u;i[u]=d,u=d}return u};e.forEach((a,u)=>{for(const d of[n.get(g(a.row,a.col-1)),n.get(g(a.row-1,a.col))])d!==void 0&&(i[s(u)]=s(d))});const t=new Map;e.forEach((a,u)=>{const d=s(u),w=t.get(d);w?w.push(a):t.set(d,[a])});const r=[],l=a=>!r.some(u=>D(u,a))&&!this.areas.some(u=>D(u,a))&&!o.some(u=>A(a,u.row,u.col)),c=a=>(a.bottom-a.top+1)*(a.right-a.left+1);for(const a of t.values()){const u=be(a);if(!(c(u)<K)){if(a.length/c(u)>=he&&l(u)){r.push(u);continue}for(const d of _(a.map(C)))c(d)>=K&&l(d)&&r.push(d)}}return r.sort((a,u)=>a.top-u.top||a.left-u.left)}cells(e){const{formulas:o,typed:n}=this.loose(),i=this.blockAreas(n,o),s=l=>i.some(c=>A(c,l.row,l.col));i.length>0&&(e.blocks=i.map(l=>{const c=[];for(let u=l.top;u<=l.bottom;u++){const d=[];for(let w=l.left;w<=l.right;w++){const p=this.byPlace.get(g(u,w));d.push(p?this.text(p):"")}c.push(d)}const a=this.path(this.read.name);return this.ctx.files.set(a,I(c)),{at:$({row:l.top,col:l.left}),rows:a}}));const t=[],r=new Map;for(const l of o){if(!l.node)continue;l.key??=B(l.node,l.row,l.col);const c=r.get(l.key);c?c.push(l):r.set(l.key,[l])}for(const l of r.values())for(const c of _(l.map(C))){const a=this.byPlace.get(g(c.top,c.left));a?.node&&t.push([{row:c.top,col:c.left},x(c),M(a.node)])}for(const l of n)i.length>0&&s(l)||t.push([C(l),$(l),ke(O(this.ctx,l),this.code(l))]);t.sort(([l],[c])=>l.row-c.row||l.col-c.col),t.length>0&&(e.cells=Object.fromEntries(t.map(([,l,c])=>[l,c])))}formats(e){const o=new Map;for(const i of this.read.cells){if(this.lookDone.has(g(i.row,i.col)))continue;const s=this.ownLook(i);if(b(s))continue;const t=JSON.stringify(s),r=o.get(t);r?r.places.push(C(i)):o.set(t,{look:s,places:[C(i)]})}const n=[];for(const{look:i,places:s}of o.values())for(const t of _(s))n.push({range:x(t),...i});n.length>0&&(e.format=n)}columns(e){const{read:o}=this,n=new Map,i=o.cells.reduce((t,r)=>Math.max(t,r.col),0),s=[];for(const t of o.columns)if(!(t.width===void 0&&t.hidden!==!0)){t.max>i&&s.push(z(Math.max(t.min,i+1)));for(let r=t.min;r<=Math.min(t.max,i);r++)n.set(r,{...t.width===void 0?{}:{width:t.width},...t.hidden===!0?{hidden:!0}:{}})}for(const[t,r]of this.columnLooks)n.set(t,{...n.get(t),...r});n.size>0&&(e.columns=Object.fromEntries([...n.keys()].sort((t,r)=>t-r).map(t=>[z(t),n.get(t)??{}]))),s.some(Boolean)&&o.columns.some(t=>t.max>i&&t.hidden===!0)&&this.ctx.lost.push(`${o.name}: the size of the columns past its last used one`)}rows(e){const o={};for(const n of this.read.rows){const i=this.rowLooks.get(n.row),s=this.filtered.some(r=>n.row>r.top&&n.row<=r.bottom),t={...n.height===void 0?{}:{height:n.height},...n.hidden===!0&&!s?{hidden:!0}:{},...i};b(t)||(o[String(n.row+1)]=t)}b(o)||(e.rows=o)}build(){const{read:e}=this;this.baseLooks();for(const n of e.tables)this.table(n);const o={name:e.name};return e.state!=="visible"&&(o.hidden=!0),e.gridlines===!1&&(o.gridlines=!1),e.tab!==void 0&&(o.tab=e.tab),e.state==="veryHidden"&&this.ctx.lost.push(`${e.name}: being very hidden; it is hidden`),e.freeze&&(e.freeze.row>0||e.freeze.col>0)&&(o.freeze=$(e.freeze)),this.tables.length>0&&(o.tables=this.tables),this.filter(o),this.columns(o),this.rows(o),this.cells(o),e.merges.length>0&&(o.merges=e.merges.map(x)),this.formats(o),e.conditional.length>0&&(o.conditional=e.conditional),e.validations.length>0&&(o.validations=e.validations),e.charts.length>0&&(o.charts=e.charts.map(n=>this.chart(n))),o}chart(e){return te(e,o=>{const n=this.chartReference(o.replace(/^=/u,""));return o.startsWith("=")?`=${n}`:n})}chartReference(e){const o=e.lastIndexOf("!"),i=(o<0?this.read.name:e.slice(0,o)).replace(/^'|'$/gu,"").replaceAll("''","'"),s=ee(e.slice(o+1).replaceAll("$",""));if(!s)return e;const t=this.ctx.book.sheets.find(r=>r.name.toLowerCase()===i.toLowerCase());for(const r of t?.tables??[]){const l=r.ref.top+1,a=s.left===s.right&&s.top===l&&s.bottom===r.ref.bottom&&s.left>=r.ref.left&&s.left<=r.ref.right?r.columns[s.left-r.ref.left]:void 0;if(a&&this.ctx.tables.has(r.name.toLowerCase()))return`${r.name}[${a.name}]`}return`${t===this.read||o<0?"":`${e.slice(0,o)}!`}${x(s)}`}filter(e){const{filter:o}=this.read;if(!o)return;const n={};for(const[i,s]of o.columns)n[z(o.ref.left+i)]=s;e.filter={range:x(o.ref),...b(n)?{}:{columns:n}},o.unread===0&&!b(n)&&this.filtered.push(o.ref)}}function $e(f){const e={},{book:o,lost:n}=f,i=new Set(o.sheets.map(r=>r.name.toLowerCase())),s=new Set,t=new Set;for(const r of o.names){if(r.name.startsWith("_xlnm.")){r.name==="_xlnm.Print_Area"?t.add("print areas"):r.name==="_xlnm.Print_Titles"?t.add("print titles"):r.name!=="_xlnm._FilterDatabase"&&n.push(`Excel's name ${r.name}`);continue}if(/^_xl(?:fn|pm|ws|udf)/iu.test(r.name))continue;const l=r.name.toLowerCase();if(!R(r.name)||f.tables.has(l)){n.push(`the name ${r.name}, which cannot be held here`);continue}if(s.has(l)){n.push(`a second name ${r.name}, for one sheet: names here are the workbook's`);continue}const c=xe(r.text);if(c!==void 0)e[r.name]=typeof c=="string"?P(c):c,s.add(l),f.names.add(l);else{const a=ue(r.text,!0),u=a.ok?U(a.node,i):"it could not be read";if(!a.ok||u!==void 0||ve(a.node)){n.push(`the name ${r.name} (${r.text})${u===void 0?"":`: ${u}`}`);continue}e[r.name]=M(a.node),s.add(l),f.names.add(l)}r.sheet!==void 0&&n.push(`the name ${r.name} belonging to one sheet: here it is the workbook's`)}return t.size>0&&n.push([...t].join(" and ")),e}function Le(f,e){const o={},n=new Map;for(const[i,s]of Object.entries(e))typeof s=="string"&&s.startsWith("=")&&n.set(s.slice(1).replaceAll("$","").toLowerCase(),i);for(const i of f.book.sheets)for(const s of i.scenarios){const t={};let r=!0;for(const{at:l,value:c}of s.cells){const a=Z(l),u=a&&i.cells.find(p=>p.row===a.row&&p.col===a.col);String(u?.value??"")!==c&&(r=!1);const d=n.get(`${ie(i.name)}${l}`.toLowerCase())??n.get(l.toLowerCase()),w=F(c);d===void 0?f.lost.push(`${i.name}: scenario ${s.name}'s cell ${l}, which has no name`):t[d]=typeof w.value=="number"?w.value:c}!r&&!b(t)&&(o[s.name]={...o[s.name],...t})}return o}function ve(f){let e=!1;return N(f,o=>{e||=o.kind==="error"&&o.code==="#REF!"}),e}function xe(f){const e=f.trim();return/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/u.test(e)?Number(e):/^true$/iu.test(e)?!0:/^false$/iu.test(e)?!1:/^"((?:[^"]|"")*)"$/u.exec(e)?.[1]?.replaceAll('""','"')}const S=f=>f instanceof T?f.code:f??null;export function sameValue(f,e,o){if(typeof f=="number"&&typeof e=="number")return f===e?!0:Math.abs(f-e)<=Math.max(Math.abs(f),Math.abs(e))*o;if(f instanceof T||e instanceof T)return f?.code===e?.code;if(f===null||e===null){const n=f??e;return n===null||n===""||n===0||n===!1}return f===e}function Me(f,e){const o=[];for(const s of e.sheets)for(const t of s.formulas)t.shared.node&&oe(e,t.shared).volatile&&o.push(t);const n=new Set(o),i=[...o];for(;;){const s=i.pop();if(!s)return n;for(const t of f.readers(s.sheet,s.row,s.col))n.has(t)||(n.add(t),i.push(t))}}function Ce(f,e,o,n){const i={formulas:0,same:0,uncached:0,moving:0,differences:[]},s=Me(o,e);for(const[t,r]of f.carried){if(!t.node)continue;const l=e.sheet(r.name);if(!l)continue;i.formulas+=1;const c=l.at(t.row,t.col);if(c instanceof ae&&s.has(c)){i.moving+=1;continue}const a=O(f,t);if(a===void 0){i.uncached+=1;continue}const u=o.value(l,t.row,t.col);sameValue(a,u,n)?i.same+=1:i.differences.push({sheet:r.name,cell:$(t),formula:M(t.node),file:S(a),engine:S(u)})}for(const[t,r]of f.spilled){const l=e.sheet(r.name);if(!l)continue;i.formulas+=1;const c=l.spillAt(t.row,t.col);if(c&&s.has(c)){i.moving+=1;continue}const a=O(f,t),u=o.value(l,t.row,t.col);a===void 0?i.uncached+=1:sameValue(a,u,n)?i.same+=1:i.differences.push({sheet:r.name,cell:$(t),formula:c?`${$(c)}#`:"",file:S(a),engine:S(u)})}return i}function Oe(f,e){const o=new Map,n=[];for(const i of f){const s=e.find(l=>i.startsWith(`${l}: `));if(s===void 0){n.push(i);continue}const t=i.slice(s.length+2),r=o.get(t);r?r.push(s):o.set(t,[s])}for(const[i,s]of o)n.push(s.length===1?`${s[0]??""}: ${i}`:`${i}, on ${String(s.length)} sheets (${J(s)})`);return n}export function importXlsx(f,e){const o=de(f,e.zip);if(o.sheets.length===0)throw new Error("It holds no sheets.");const n={book:o,files:new Map,lost:[...o.lost],tables:new Set(o.sheets.flatMap(p=>p.tables.filter(L=>Y(L)===void 0).map(L=>L.name.toLowerCase()))),names:new Set,carried:new Map,spilled:new Map};o.date1904&&n.lost.push(`the 1904 date system: dates are moved to the 1900 one, ${String(q)} days on`),(o.font.name!==void 0&&o.font.name!=="Calibri"||o.font.size!==void 0&&o.font.size!==11)&&n.lost.push(`its default font, ${o.font.name??""} ${String(o.font.size??"")}`);const i=$e(n);pe(n);const s=o.sheets.map(p=>new ye(n,p).build()),t=Le(n,i),r={title:e.name,...b(i)?{}:{names:i},sheets:s,...b(t)?{}:{scenarios:t}},l=ce(r),c=new Map([[Q,l],...n.files]),a=se({text:l,read:p=>c.get(p)}),{workbook:u,calc:d,problems:w}=a;return{files:c,lost:Oe(n.lost,o.sheets.map(p=>p.name)),problems:w,compared:u&&d?Ce(n,u,d,e.tolerance??COMPARE_TOLERANCE):{formulas:0,same:0,uncached:0,moving:0,differences:[]},sheets:o.sheets.length,tables:n.tables.size}}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ZipLimits } from "@allyhub-next/formats";
|
|
1
2
|
import type { SheetConditional, SheetFilterColumn, SheetValidation } from "@allyhub-next/formats";
|
|
2
3
|
import { type Area, type Place } from "../address.js";
|
|
3
4
|
import type { Node } from "../formula/ast.js";
|
|
@@ -113,5 +114,5 @@ export interface ReadBook {
|
|
|
113
114
|
/** Places as a line: the first few and how many more. */
|
|
114
115
|
export declare function placesLine(places: readonly string[]): string;
|
|
115
116
|
/** What a .xlsx, .xlsm or .xltx file holds. */
|
|
116
|
-
export declare function readXlsx(bytes: Uint8Array): ReadBook;
|
|
117
|
+
export declare function readXlsx(bytes: Uint8Array, zip?: Partial<ZipLimits>): ReadBook;
|
|
117
118
|
//# sourceMappingURL=read.d.ts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
|
|
2
|
-
import{strFromU8 as ie,unzipSync as ae}from"fflate";import{SHEET_ICONS as le,SHEET_OPERATORS as ce,SHEET_VALIDATIONS as de}from"@allyhub-next/formats";import{cellName as J,readAddress as K,readArea as z,readAreas as Q}from"../address.js";import{SHEET_CHART_DEFAULTS as Y}from"../chart.js";import{moveFormula as ue,relativeKey as fe}from"../formula/move.js";import{printFormula as Z}from"../formula/print.js";import{ERR as me,errorOf as he,serialOfDate as pe}from"../values.js";import{OFFICE_THEME as be,colorOf as C,paletteOf as ee,themeColors as ge}from"./colors.js";import{chartAnchors as xe,readChart as ye}from"./charts.js";import{readFileFormula as P}from"./formula.js";import{BUILTIN_FORMATS as we}from"./numfmt.js";import{attr as d,flag as k,numberAttr as x,readXml as ve,readXstring as L,tag as l,tags as b,textOf as F}from"./xml.js";const te=7,ke=o=>Math.floor((256*o+Math.floor(128/te))/256*te),$e=o=>Math.round(o*4/3),B=5;export function placesLine(o){const e=o.slice(0,B).join(", ");return o.length>B?`${e} and ${String(o.length-B)} more`:e}const H=(o,e,t=`${e}s`)=>`${String(o)} ${o===1?e:t}`;class Se{parts;names;constructor(e){this.parts=ae(e),this.names=Object.keys(this.parts)}has(e){return this.parts[e]!==void 0}text(e){const t=this.parts[e];return t?ie(t):void 0}xml(e){const t=this.text(e);return t===void 0?void 0:ve(t)}rels(e){const t=e.lastIndexOf("/"),n=`${e.slice(0,t+1)}_rels/${e.slice(t+1)}.rels`,s=this.xml(n);return b(l(s?.Relationships)?.Relationship).map(r=>{const a=d(r,"Type")??"",c=d(r,"Target")??"",i=d(r,"TargetMode")==="External";return{id:d(r,"Id")??"",type:a.slice(a.lastIndexOf("/")+1),target:i?c:Te(e,c),external:i}})}count(e){return this.names.filter(t=>e.test(t)).length}}function Te(o,e){if(e.startsWith("/"))return e.slice(1);const t=o.split("/").slice(0,-1);for(const n of e.split("/"))n===".."?t.pop():n!=="."&&t.push(n);return t.join("/")}function Ee(o,e){const t=e===void 0?void 0:o.xml(e);return b(l(t?.sst)?.si).map(n=>{const s=b(n.r);return s.length>0?{text:L(s.map(r=>F(r.t)).join("")),rich:!0}:{text:L(F(n.t)),rich:!1}})}function M(o,e){const t=o[e];if(t===void 0)return!1;const n=d(l(t),"val");return n===void 0||n!=="0"&&n!=="false"}const Oe=new Set(["double","singleAccounting","doubleAccounting"]);function Ie(o,e,t){const n={},s=(i,m)=>d(l(i?.[m]),"val");if(M(o,"b")&&(n.bold=!0),M(o,"i")&&(n.italic=!0),M(o,"strike")&&(n.strike=!0),M(o,"u")){const i=s(o,"u");n.underline=i!==void 0&&Oe.has(i)?i:!0}const r=s(o,"name");r!==void 0&&r!==s(e,"name")&&(n.font=r);const a=s(o,"sz");a!==void 0&&a!==s(e,"sz")&&(n.size=Number(a));const c=C(l(o.color),t);return c!==void 0&&c!==C(l(e?.color),t)&&(n.color=c),n}function Ae(o,e){const t=l(o.patternFill),n=d(t,"patternType");if(n===void 0||n==="none")return;const s=C(l(t?.fgColor),e),r=C(l(t?.bgColor),e);return n==="solid"&&s!==void 0?s:{pattern:n,...s===void 0?{}:{color:s},...r===void 0?{}:{background:r}}}function ne(o,e){const t={};for(const n of["left","right","top","bottom"]){const s=l(o[n]),r=d(s,"style");if(r===void 0||r==="none")continue;const a=C(l(s?.color),e);t[n]={style:r,...a===void 0?{}:{color:a}}}return Object.keys(t).length===0?void 0:t}function Ce(o){const e={},t=d(o,"horizontal");t!==void 0&&t!=="general"&&(e.align=t);const n=d(o,"vertical");n!==void 0&&n!=="bottom"&&(e.valign=n),k(o,"wrapText")===!0&&(e.wrap=!0),k(o,"shrinkToFit")===!0&&(e.shrink=!0);const s=x(o,"indent");s!==void 0&&s>0&&(e.indent=s);const r=x(o,"textRotation");return r!==void 0&&r>0&&r<=180&&(e.rotation=r),e}function Fe(o,e){const t={},n=l(o.font);if(n){const i=(f,u)=>{n[f]!==void 0&&(t[u]=M(n,f))};i("b","bold"),i("i","italic"),i("strike","strike"),n.u!==void 0&&(t.underline=M(n,"u"));const m=C(l(n.color),e);m!==void 0&&(t.color=m)}const s=l(l(o.fill)?.patternFill),r=C(l(s?.bgColor),e)??C(l(s?.fgColor),e);r!==void 0&&(t.fill=r);const a=l(o.border),c=a&&ne(a,e);return c!==void 0&&(t.border=c),t}function Re(o,e){const t=l(o?.styleSheet),n=ee(e,t),s=new Map(b(l(t?.numFmts)?.numFmt).map(p=>[x(p,"numFmtId")??-1,d(p,"formatCode")??"General"])),r=b(l(t?.fonts)?.font),a=b(l(t?.fills)?.fill),c=b(l(t?.borders)?.border),i=b(l(t?.cellXfs)?.xf),m=r[x(i[0],"fontId")??0],f=new Set;a.some(p=>p.gradientFill!==void 0)&&f.add("gradient fills");const u=i.map(p=>{const y={},$=r[x(p,"fontId")??0];$&&(Object.assign(y,Ie($,m,n)),$.vertAlign!==void 0&&f.add("superscript and subscript"));const T=a[x(p,"fillId")??0],O=T&&Ae(T,n);O!==void 0&&(y.fill=O);const R=c[x(p,"borderId")??0],I=R&&ne(R,n);I!==void 0&&(y.border=I),R&&d(l(R.diagonal),"style")!==void 0&&f.add("diagonal borders");const w=l(p.alignment);w&&(Object.assign(y,Ce(w)),x(w,"textRotation")===255&&f.add("vertical text"));const S=x(p,"numFmtId")??0,A=s.get(S)??we[S];return A!==void 0&&A!=="General"&&(y.format=A),y}),h=d(l(m?.name),"val"),v=d(l(m?.sz),"val");return{looks:u,dxfs:b(l(t?.dxfs)?.dxf).map(p=>Fe(p,n)),font:{...h===void 0?{}:{name:h},...v===void 0?{}:{size:Number(v)}},lost:[...f]}}function oe(o){const e=new Map;let t=0;for(const n of b(o.filterColumn)){const s=x(n,"colId")??0,r=l(n.filters);if(!r){Object.keys(n).some(c=>c!=="colId"&&c!=="hiddenButton")&&(t+=1);continue}if(r.dateGroupItem!==void 0){t+=1;continue}const a=b(r.filter).map(c=>L(d(c,"val")??""));e.set(s,{...a.length===0?{}:{values:a},...k(r,"blank")===!0?{blanks:!0}:{}})}return{columns:e,unread:t}}function Le(o){const e=l(o?.table),t=z(d(e,"ref")??""),n=d(e,"displayName")??d(e,"name");if(!t||n===void 0)return;const s=l(e?.tableStyleInfo),r=l(e?.autoFilter);return{name:n,ref:t,headers:x(e,"headerRowCount")??1,totals:x(e,"totalsRowCount")??0,columns:b(l(e?.tableColumns)?.tableColumn).map(a=>({name:L(d(a,"name")??"").trim(),calculated:a.calculatedColumnFormula!==void 0})),style:d(s,"name")??"none",...r?{filter:oe(r)}:{}}}function W(o){const e=o.trim();if(e==="")return;const t=/^"((?:[^"]|"")*)"$/u.exec(e);if(t)return(t[1]??"").replaceAll('""','"');const n=Number(e);if(!Number.isNaN(n))return n;const s=P(e,!0);return s.ok?Z(s.node):void 0}const re=o=>o!==void 0&&ce.includes(o);function q(o){const e=d(o,"type")??"num",t=d(o,"val"),n=t===void 0?void 0:W(t);return{at:e,...n===void 0?{}:{value:n}}}const Ne=le;function je(o,e,t,n){const s=d(o,"type")??"",r={range:e,...k(o,"stopIfTrue")===!0?{stop:!0}:{}},a=x(o,"dxfId"),c=a===void 0?{}:t[a]??{},i={...c.bold===void 0?{}:{bold:c.bold},...c.italic===void 0?{}:{italic:c.italic},...c.underline===void 0?{}:{underline:c.underline!==!1},...c.strike===void 0?{}:{strike:c.strike},...c.color===void 0?{}:{color:c.color},...typeof c.fill=="string"?{fill:c.fill}:{},...c.border===void 0?{}:{border:c.border}},m=o.formula,f=(Array.isArray(m)?m:m===void 0?[]:[m]).map(F);switch(s){case"cellIs":{const u=d(o,"operator"),h=f.flatMap(v=>{const p=W(v);return p===void 0?[]:[p]});return!re(u)||h.length===0?`a cellIs rule of ${u??"no operator"}`:{...r,...i,type:"cellIs",operator:u,formula:h}}case"containsText":case"notContainsText":case"beginsWith":case"endsWith":{const u=d(o,"text");return u===void 0?`a ${s} rule with no text`:{...r,...i,type:"containsText",...s==="containsText"?{}:{operator:s==="notContainsText"?"notContains":s},text:L(u)}}case"duplicateValues":case"uniqueValues":return{...r,...i,type:s};case"top10":return{...r,...i,type:"top10",rank:x(o,"rank")??10,...k(o,"percent")===!0?{percent:!0}:{},...k(o,"bottom")===!0?{bottom:!0}:{}};case"aboveAverage":return{...r,...i,type:"aboveAverage",...k(o,"aboveAverage")===!1?{below:!0}:{},...k(o,"equalAverage")===!0?{equal:!0}:{}};case"expression":{const u=f[0]===void 0?void 0:P(f[0],!0);return u?.ok?{...r,...i,type:"expression",formula:Z(u.node)}:"an expression rule that cannot be read"}case"dataBar":{const u=l(o.dataBar),h=C(l(u?.color),n),[v,p]=b(u?.cfvo).map(q);return h===void 0?"a data bar with no colour":{...r,type:"dataBar",color:h,...v&&v.at!=="min"?{min:v}:{},...p&&p.at!=="max"?{max:p}:{},...k(u,"showValue")===!1?{show:!1}:{}}}case"colorScale":{const u=l(o.colorScale),h=b(u?.cfvo).map(q),v=b(u?.color).map(y=>C(y,n)),p=h.flatMap((y,$)=>{const T=v[$];return T===void 0?[]:[{...y,color:T}]});return p.length<2?"a colour scale with too few stops":{...r,type:"colorScale",stops:p.slice(0,3)}}case"iconSet":{const u=l(o.iconSet),h=d(u,"iconSet")??"3TrafficLights1";if(!Ne.includes(h))return`the icon set ${h}`;const v=b(u?.cfvo).map(q);return{...r,type:"iconSet",icons:h,...v.length>=3?{stops:v.slice(0,5)}:{},...k(u,"reverse")===!0?{reverse:!0}:{},...k(u,"showValue")===!1?{show:!1}:{}}}default:return`a ${s} rule`}}function Me(o,e,t){const n=[],s=[];for(const r of b(o.conditionalFormatting)){const a=d(r,"sqref")??"";if(!Q(a)){s.push(`a rule on ${a}`);continue}for(const c of b(r.cfRule)){const i=je(c,a,e,t);typeof i=="string"?s.push(`${i} on ${a}`):n.push({priority:x(c,"priority")??0,rule:i})}}return{rules:n.sort((r,a)=>r.priority-a.priority).map(r=>r.rule),unread:s}}const De=de;function Ve(o){const e=[],t=[];for(const n of b(l(o.dataValidations)?.dataValidation)){const s=d(n,"sqref")??"",r=d(n,"type")??"none";if(r==="none"&&d(n,"prompt")===void 0)continue;if(!De.includes(r)||!Q(s)){t.push(`a ${r} rule on ${s}`);continue}const a=F(n.formula1),c=F(n.formula2),i=/^"((?:[^"]|"")*)"$/u.exec(a.trim()),m=r==="list"&&i?(i[1]??"").replaceAll('""','"').split(","):void 0,f=[a,c].flatMap(T=>{const O=W(T);return O===void 0?[]:[O]}),u=d(n,"operator"),h=T=>Object.fromEntries(Object.entries(T).filter(([,O])=>O!==void 0)),v=h({title:d(n,"promptTitle"),message:d(n,"prompt")}),p=h({style:d(n,"errorStyle"),title:d(n,"errorTitle"),message:d(n,"error")}),y=k(n,"showInputMessage")!==!0,$=k(n,"showErrorMessage")!==!0;e.push({range:s,type:r,...re(u)&&u!=="between"?{operator:u}:{},...m?{values:m}:{formula:f},...k(n,"allowBlank")===!0?{}:{blank:!1},...k(n,"showDropDown")===!0?{dropdown:!1}:{},...y||Object.keys(v).length>0?{prompt:{...v,...y?{show:!1}:{}}}:{},...$||Object.keys(p).length>0?{error:{...p,...$?{show:!1}:{}}}:{}})}return{rules:e,unread:t}}function U(o,e){const t=P(o,e);return t.ok?{node:t.node}:{unread:o}}class ze{cells=[];rich=[];masters=new Map;strings;constructor(e){this.strings=e}value(e,t){const n=d(e,"t")??"n",s=e.v;if(n==="inlineStr"){const a=l(e.is),c=b(a?.r);return c.length>0?{value:L(c.map(i=>F(i.t)).join("")),rich:!0}:{value:L(F(a?.t))}}if(s===void 0)return{value:void 0};const r=F(s);switch(n){case"s":{const a=this.strings[Number(r)];return a?{value:a.text,...a.rich?{rich:!0}:{}}:{value:""}}case"str":return{value:L(r)};case"b":return{value:r.trim()==="1"||r.trim()==="true"};case"e":return{value:he(r.trim())??me.VALUE};case"d":{const a=new Date(r.trim());return{value:Number.isNaN(a.getTime())?r:pe(a)}}default:{if(r.trim()==="")return{value:void 0};const a=Number(r);if(Number.isNaN(a))throw new Error(`${t} says it holds a number and holds ${r}.`);return{value:a}}}}formula(e,t,n,s){const r=e.f;if(r===void 0)return;const a=l(r),c=d(a,"t")??"normal",i=F(r);if(c==="dataTable"){s.unread=`a data table's {=TABLE(${d(a,"r1")??""})}`;return}if(c==="array"){const m=e.cm!==void 0;Object.assign(s,U(i,!0));const f=z(d(a,"ref")??"");f&&(s.array=f),m&&(s.dynamic=!0);return}if(c==="shared"){const m=d(a,"si")??"";if(i!==""){const u=U(i,!1);this.masters.set(m,{node:u.node,unread:u.unread,row:t,col:n,key:u.node?fe(u.node,t,n):"",dynamicArray:!1}),Object.assign(s,u),u.node&&(s.key=this.masters.get(m)?.key??"");return}const f=this.masters.get(m);if(!f){s.unread=`a shared formula of a group that has no first cell (${m})`;return}f.node?(s.node=ue(f.node,t-f.row,n-f.col),s.key=f.key):f.unread!==void 0&&(s.unread=f.unread);return}i!==""&&Object.assign(s,U(i,!1))}readRows(e){let t=0;for(const n of e){const s=x(n,"r"),r=s===void 0?t:s-1;t=r+1;let a=0;for(const c of b(n.c)){const i=d(c,"r"),f=(i===void 0?void 0:K(i))?.col??a;a=f+1;const u=i??J({row:r,col:f}),{value:h,rich:v}=this.value(c,u),p={row:r,col:f,value:h,style:x(c,"s")??0};v===!0&&(p.rich=!0,this.rich.push(u)),this.formula(c,r,f,p),this.cells.push(p)}}}}function He(o,e,t){const n=[],s=i=>n.push(`${o}: ${i}`);t.length>0&&s(`${H(t.length,"cell")} of rich text, kept as plain text (${placesLine(t)})`);const r=b(l(e.hyperlinks)?.hyperlink);r.length>0&&s(`${H(r.length,"hyperlink")} (${placesLine(r.map(i=>d(i,"ref")??""))})`),e.sortState!==void 0&&s("a sort"),k(l(e.sheetProtection),"sheet")===!0&&s("protection"),e.protectedRanges!==void 0&&s("protected ranges"),e.headerFooter!==void 0&&F(e.headerFooter).trim()!==""&&s("its print header and footer"),l(e.headerFooter)?.oddHeader!==void 0&&s("its print header"),l(e.headerFooter)?.oddFooter!==void 0&&s("its print footer"),(e.rowBreaks!==void 0||e.colBreaks!==void 0)&&s("its page breaks"),e.oleObjects!==void 0&&s("embedded objects"),e.controls!==void 0&&s("form controls"),e.dataConsolidate!==void 0&&s("a consolidation"),e.customSheetViews!==void 0&&s("custom views"),b(l(e.sheetViews)?.sheetView).some(i=>d(l(i.pane),"state")==="split")&&s("a split, not frozen, window");const c=JSON.stringify(e.extLst??"");return c.includes("sparklineGroups")&&s("sparklines"),X(e.extLst)&&s("conditional formats of Excel 2010 and later"),c.includes("dataValidations")&&s("data validations of Excel 2010 and later"),c.includes("slicerList")&&s("slicers"),n}function X(o){if(typeof o!="object"||o===null)return!1;if(Array.isArray(o))return o.some(X);const e=o;return b(e.cfRule).some(t=>d(t,"type")!=="dataBar")&&e.cfRule!==void 0?!0:Object.values(e).some(X)}function _e(o){const e=[],t=(n,s,r)=>{const a=o.count(n);a>0&&e.push(H(a,s,r))};return o.has("xl/vbaProject.bin")&&e.push("VBA macros"),t(/^xl\/pivotTables\/pivotTable\d*\.xml$/u,"pivot table"),t(/^xl\/chartsheets\/[^/]+\.xml$/u,"chart sheet"),t(/^xl\/dialogsheets\/[^/]+\.xml$/u,"dialog sheet"),t(/^xl\/macrosheets\/[^/]+\.xml$/u,"macro sheet"),t(/^xl\/media\//u,"image"),t(/^xl\/embeddings\//u,"embedded object"),t(/^xl\/comments\d*\.xml$/u,"sheet's comments","sheets' comments"),t(/^xl\/threadedComments\//u,"sheet's threaded comments","sheets' threaded comments"),t(/^xl\/slicers\/[^/]+\.xml$/u,"slicer part"),t(/^xl\/timelines\/[^/]+\.xml$/u,"timeline part"),t(/^xl\/ctrlProps\/[^/]+\.xml$/u,"form control"),t(/^xl\/activeX\/[^/]+\.xml$/u,"ActiveX control"),t(/^xl\/queryTables\/[^/]+\.xml$/u,"query table"),o.has("xl/connections.xml")&&e.push("data connections"),o.names.some(n=>n.startsWith("xl/richData/"))&&e.push("rich values (data types, pictures in cells)"),o.names.some(n=>/^customXml\/item\d+\.xml$/u.test(n)&&(o.text(n)??"").includes("DataMashup"))&&e.push("Power Query queries"),e}function Pe(o,e,t,n,s,r,a){const c=o.xml(e),i=l(c?.worksheet);if(!i)throw new Error(`${e} is not a worksheet.`);const m=new ze(s);m.readRows(b(l(i.sheetData)?.row));const f=b(l(i.cols)?.col).map(g=>{const E=x(g,"width"),D=x(g,"style");return{min:(x(g,"min")??1)-1,max:(x(g,"max")??1)-1,...E===void 0||k(g,"customWidth")===!1?{}:{width:ke(E)},...k(g,"hidden")===!0?{hidden:!0}:{},...D===void 0||D===0?{}:{style:D}}}),u=[];let h=b(l(i.cols)?.col).some(g=>(x(g,"outlineLevel")??0)>0);b(l(i.sheetData)?.row).forEach((g,E)=>{const D=(x(g,"r")??E+1)-1;(x(g,"outlineLevel")??0)>0&&(h=!0);const G=x(g,"ht"),_=x(g,"s"),V={row:D};G!==void 0&&k(g,"customHeight")===!0&&(V.height=$e(G)),k(g,"hidden")===!0&&(V.hidden=!0),_!==void 0&&_!==0&&k(g,"customFormat")===!0&&(V.style=_),Object.keys(V).length>1&&u.push(V)});const v=b(l(i.mergeCells)?.mergeCell).flatMap(g=>{const E=z(d(g,"ref")??"");return E?[E]:[]}),p=b(l(i.sheetViews)?.sheetView)[0],y=l(p?.pane);let $;const T=d(y,"state");if(T==="frozen"||T==="frozenSplit"){const g=K(d(p,"topLeftCell")??"A1")??{row:0,col:0};$={row:g.row+(x(y,"ySplit")??0),col:g.col+(x(y,"xSplit")??0)}}const O=o.rels(e).filter(g=>g.type==="table").flatMap(g=>{const E=Le(o.xml(g.target));return E?[E]:[]}),R=C(l(l(i.sheetPr)?.tabColor),r),I=He(t,i,m.rich);h&&I.push(`${t}: its grouped rows or columns, left ungrouped`);const w=Me(i,a,r),S=Ve(i);for(const g of w.unread)I.push(`${t}: a conditional format, ${g}`);for(const g of S.unread)I.push(`${t}: a data validation, ${g}`);const A=l(i.autoFilter),j=z(d(A,"ref")??""),N=A&&j?{ref:j,...oe(A)}:void 0;N&&N.unread>0&&I.push(`${t}: ${H(N.unread,"filter")} by condition on ${d(A,"ref")??""}, its rows left as they were hidden`);const se=qe(o,e,t,f,u,I);return{sheet:{name:t,state:n,cells:m.cells,merges:v,...$?{freeze:$}:{},...d(p,"showGridLines")==="0"?{gridlines:!1}:{},...R===void 0?{}:{tab:R},columns:f,rows:u,tables:O,conditional:w.rules,validations:S.rules,scenarios:b(l(i.scenarios)?.scenario).map(g=>({name:d(g,"name")??"",cells:b(g.inputCells).map(E=>({at:d(E,"r")??"",value:d(E,"val")??""}))})),...N?{filter:N}:{},charts:se},lost:I}}const Be=64,We=20;function qe(o,e,t,n,s,r){const a=m=>n.find(f=>m>=f.min&&m<=f.max)?.width??Be,c=m=>s.find(f=>f.row===m)?.height??We,i=[];for(const m of o.rels(e).filter(f=>f.type==="drawing")){const{anchors:f}=xe(o.xml(m.target),a,c),u=o.rels(m.target);for(const h of f){const v=u.find($=>$.id===h.id),p=ye(v?o.xml(v.target):void 0),y=J(h.at);if(typeof p=="string"){r.push(`${t}: the chart at ${y}, as ${p}`);continue}i.push({...p,at:y,...h.x===void 0?{}:{x:h.x},...h.y===void 0?{}:{y:h.y},...h.width===Y.width?{}:{width:h.width},...h.height===Y.height?{}:{height:h.height}})}}return i}export function readXlsx(o){let e;try{e=new Se(o)}catch{throw new Error("It is not a zip file, as an .xlsx file is.")}const n=e.rels("").find(w=>w.type==="officeDocument")?.target??"xl/workbook.xml";if(n.endsWith(".bin"))throw new Error("It is a binary workbook (.xlsb): save it as .xlsx.");const s=e.xml(n),r=l(s?.workbook);if(!r)throw new Error("It has no workbook part.");const a=e.rels(n),c=w=>a.find(S=>S.type===w)?.target,i=(()=>{const w=c("theme");return w===void 0?void 0:e.text(w)})(),m=i===void 0?be:ge(i),f=c("styles"),u=f===void 0?void 0:e.xml(f),h=Re(u,m),v=ee(m,l(u?.styleSheet)),p=Ee(e,c("sharedStrings")),y=[..._e(e)];for(const w of h.lost)y.push(w);const $=l(r.workbookPr),T=l(r.calcPr);k(T,"iterate")===!0&&y.push("iterative calculation");const O=l(r.workbookProtection);(k(O,"lockStructure")===!0||k(O,"lockWindows")===!0)&&y.push("the workbook's protection"),r.fileSharing!==void 0&&y.push("its write protection");const R=[],I=new Map(a.map(w=>[w.id,w]));for(const w of b(l(r.sheets)?.sheet)){const S=I.get(d(w,"id")??""),A=L(d(w,"name")??"");if(S?.type!=="worksheet"){S?.type!=="chartsheet"&&S?.type!=="dialogsheet"&&y.push(`${A}: a sheet of a kind this cannot read`);continue}const j=d(w,"state"),N=Pe(e,S.target,A,j==="hidden"||j==="veryHidden"?j:"visible",p,v,h.dxfs);R.push(N.sheet),y.push(...N.lost)}return{sheets:R,names:b(l(r.definedNames)?.definedName).map(w=>{const S=x(w,"localSheetId");return{name:d(w,"name")??"",text:L(F(w)),...S===void 0?{}:{sheet:S}}}),looks:h.looks,dxfs:h.dxfs,date1904:k($,"date1904")===!0,font:h.font,lost:y}}
|
|
2
|
+
import{strFromU8 as ie,unzipSync as ae}from"fflate";import{withinZip as le,ZipLimitError as ce}from"@allyhub-next/formats";import{SHEET_ICONS as de,SHEET_OPERATORS as ue,SHEET_VALIDATIONS as fe}from"@allyhub-next/formats";import{cellName as J,readAddress as K,readArea as H,readAreas as Q}from"../address.js";import{SHEET_CHART_DEFAULTS as Y}from"../chart.js";import{moveFormula as me,relativeKey as he}from"../formula/move.js";import{printFormula as ee}from"../formula/print.js";import{ERR as pe,errorOf as be,serialOfDate as ge}from"../values.js";import{OFFICE_THEME as xe,colorOf as A,paletteOf as te,themeColors as ye}from"./colors.js";import{chartAnchors as we,readChart as ve}from"./charts.js";import{readFileFormula as B}from"./formula.js";import{BUILTIN_FORMATS as ke}from"./numfmt.js";import{attr as d,flag as v,numberAttr as y,readXml as $e,readXstring as L,tag as l,tags as b,textOf as C}from"./xml.js";const ne=7,Se=n=>Math.floor((256*n+Math.floor(128/ne))/256*ne),Te=n=>Math.round(n*4/3),W=5;export function placesLine(n){const e=n.slice(0,W).join(", ");return n.length>W?`${e} and ${String(n.length-W)} more`:e}const _=(n,e,t=`${e}s`)=>`${String(n)} ${n===1?e:t}`;class Ee{parts;names;constructor(e,t){this.parts=ae(e,{filter:le(t)}),this.names=Object.keys(this.parts)}has(e){return this.parts[e]!==void 0}text(e){const t=this.parts[e];return t?ie(t):void 0}xml(e){const t=this.text(e);return t===void 0?void 0:$e(t)}rels(e){const t=e.lastIndexOf("/"),o=`${e.slice(0,t+1)}_rels/${e.slice(t+1)}.rels`,r=this.xml(o);return b(l(r?.Relationships)?.Relationship).map(s=>{const i=d(s,"Type")??"",c=d(s,"Target")??"",a=d(s,"TargetMode")==="External";return{id:d(s,"Id")??"",type:i.slice(i.lastIndexOf("/")+1),target:a?c:Oe(e,c),external:a}})}count(e){return this.names.filter(t=>e.test(t)).length}}function Oe(n,e){if(e.startsWith("/"))return e.slice(1);const t=n.split("/").slice(0,-1);for(const o of e.split("/"))o===".."?t.pop():o!=="."&&t.push(o);return t.join("/")}function Ie(n,e){const t=e===void 0?void 0:n.xml(e);return b(l(t?.sst)?.si).map(o=>{const r=b(o.r);return r.length>0?{text:L(r.map(s=>C(s.t)).join("")),rich:!0}:{text:L(C(o.t)),rich:!1}})}function j(n,e){const t=n[e];if(t===void 0)return!1;const o=d(l(t),"val");return o===void 0||o!=="0"&&o!=="false"}const Ae=new Set(["double","singleAccounting","doubleAccounting"]);function Ce(n,e,t){const o={},r=(a,m)=>d(l(a?.[m]),"val");if(j(n,"b")&&(o.bold=!0),j(n,"i")&&(o.italic=!0),j(n,"strike")&&(o.strike=!0),j(n,"u")){const a=r(n,"u");o.underline=a!==void 0&&Ae.has(a)?a:!0}const s=r(n,"name");s!==void 0&&s!==r(e,"name")&&(o.font=s);const i=r(n,"sz");i!==void 0&&i!==r(e,"sz")&&(o.size=Number(i));const c=A(l(n.color),t);return c!==void 0&&c!==A(l(e?.color),t)&&(o.color=c),o}function Fe(n,e){const t=l(n.patternFill),o=d(t,"patternType");if(o===void 0||o==="none")return;const r=A(l(t?.fgColor),e),s=A(l(t?.bgColor),e);return o==="solid"&&r!==void 0?r:{pattern:o,...r===void 0?{}:{color:r},...s===void 0?{}:{background:s}}}function oe(n,e){const t={};for(const o of["left","right","top","bottom"]){const r=l(n[o]),s=d(r,"style");if(s===void 0||s==="none")continue;const i=A(l(r?.color),e);t[o]={style:s,...i===void 0?{}:{color:i}}}return Object.keys(t).length===0?void 0:t}function Le(n){const e={},t=d(n,"horizontal");t!==void 0&&t!=="general"&&(e.align=t);const o=d(n,"vertical");o!==void 0&&o!=="bottom"&&(e.valign=o),v(n,"wrapText")===!0&&(e.wrap=!0),v(n,"shrinkToFit")===!0&&(e.shrink=!0);const r=y(n,"indent");r!==void 0&&r>0&&(e.indent=r);const s=y(n,"textRotation");return s!==void 0&&s>0&&s<=180&&(e.rotation=s),e}function Re(n,e){const t={},o=l(n.font);if(o){const a=(f,u)=>{o[f]!==void 0&&(t[u]=j(o,f))};a("b","bold"),a("i","italic"),a("strike","strike"),o.u!==void 0&&(t.underline=j(o,"u"));const m=A(l(o.color),e);m!==void 0&&(t.color=m)}const r=l(l(n.fill)?.patternFill),s=A(l(r?.bgColor),e)??A(l(r?.fgColor),e);s!==void 0&&(t.fill=s);const i=l(n.border),c=i&&oe(i,e);return c!==void 0&&(t.border=c),t}function Ne(n,e){const t=l(n?.styleSheet),o=te(e,t),r=new Map(b(l(t?.numFmts)?.numFmt).map(h=>[y(h,"numFmtId")??-1,d(h,"formatCode")??"General"])),s=b(l(t?.fonts)?.font),i=b(l(t?.fills)?.fill),c=b(l(t?.borders)?.border),a=b(l(t?.cellXfs)?.xf),m=s[y(a[0],"fontId")??0],f=new Set;i.some(h=>h.gradientFill!==void 0)&&f.add("gradient fills");const u=a.map(h=>{const k={},$=s[y(h,"fontId")??0];$&&(Object.assign(k,Ce($,m,o)),$.vertAlign!==void 0&&f.add("superscript and subscript"));const T=i[y(h,"fillId")??0],I=T&&Fe(T,o);I!==void 0&&(k.fill=I);const F=c[y(h,"borderId")??0],O=F&&oe(F,o);O!==void 0&&(k.border=O),F&&d(l(F.diagonal),"style")!==void 0&&f.add("diagonal borders");const N=l(h.alignment);N&&(Object.assign(k,Le(N)),y(N,"textRotation")===255&&f.add("vertical text"));const w=y(h,"numFmtId")??0,S=r.get(w)??ke[w];return S!==void 0&&S!=="General"&&(k.format=S),k}),p=d(l(m?.name),"val"),x=d(l(m?.sz),"val");return{looks:u,dxfs:b(l(t?.dxfs)?.dxf).map(h=>Re(h,o)),font:{...p===void 0?{}:{name:p},...x===void 0?{}:{size:Number(x)}},lost:[...f]}}function re(n){const e=new Map;let t=0;for(const o of b(n.filterColumn)){const r=y(o,"colId")??0,s=l(o.filters);if(!s){Object.keys(o).some(c=>c!=="colId"&&c!=="hiddenButton")&&(t+=1);continue}if(s.dateGroupItem!==void 0){t+=1;continue}const i=b(s.filter).map(c=>L(d(c,"val")??""));e.set(r,{...i.length===0?{}:{values:i},...v(s,"blank")===!0?{blanks:!0}:{}})}return{columns:e,unread:t}}function je(n){const e=l(n?.table),t=H(d(e,"ref")??""),o=d(e,"displayName")??d(e,"name");if(!t||o===void 0)return;const r=l(e?.tableStyleInfo),s=l(e?.autoFilter);return{name:o,ref:t,headers:y(e,"headerRowCount")??1,totals:y(e,"totalsRowCount")??0,columns:b(l(e?.tableColumns)?.tableColumn).map(i=>({name:L(d(i,"name")??"").trim(),calculated:i.calculatedColumnFormula!==void 0})),style:d(r,"name")??"none",...s?{filter:re(s)}:{}}}function q(n){const e=n.trim();if(e==="")return;const t=/^"((?:[^"]|"")*)"$/u.exec(e);if(t)return(t[1]??"").replaceAll('""','"');const o=Number(e);if(!Number.isNaN(o))return o;const r=B(e,!0);return r.ok?ee(r.node):void 0}const se=n=>n!==void 0&&ue.includes(n);function U(n){const e=d(n,"type")??"num",t=d(n,"val"),o=t===void 0?void 0:q(t);return{at:e,...o===void 0?{}:{value:o}}}const Me=de;function De(n,e,t,o){const r=d(n,"type")??"",s={range:e,...v(n,"stopIfTrue")===!0?{stop:!0}:{}},i=y(n,"dxfId"),c=i===void 0?{}:t[i]??{},a={...c.bold===void 0?{}:{bold:c.bold},...c.italic===void 0?{}:{italic:c.italic},...c.underline===void 0?{}:{underline:c.underline!==!1},...c.strike===void 0?{}:{strike:c.strike},...c.color===void 0?{}:{color:c.color},...typeof c.fill=="string"?{fill:c.fill}:{},...c.border===void 0?{}:{border:c.border}},m=n.formula,f=(Array.isArray(m)?m:m===void 0?[]:[m]).map(C);switch(r){case"cellIs":{const u=d(n,"operator"),p=f.flatMap(x=>{const h=q(x);return h===void 0?[]:[h]});return!se(u)||p.length===0?`a cellIs rule of ${u??"no operator"}`:{...s,...a,type:"cellIs",operator:u,formula:p}}case"containsText":case"notContainsText":case"beginsWith":case"endsWith":{const u=d(n,"text");return u===void 0?`a ${r} rule with no text`:{...s,...a,type:"containsText",...r==="containsText"?{}:{operator:r==="notContainsText"?"notContains":r},text:L(u)}}case"duplicateValues":case"uniqueValues":return{...s,...a,type:r};case"top10":return{...s,...a,type:"top10",rank:y(n,"rank")??10,...v(n,"percent")===!0?{percent:!0}:{},...v(n,"bottom")===!0?{bottom:!0}:{}};case"aboveAverage":return{...s,...a,type:"aboveAverage",...v(n,"aboveAverage")===!1?{below:!0}:{},...v(n,"equalAverage")===!0?{equal:!0}:{}};case"expression":{const u=f[0]===void 0?void 0:B(f[0],!0);return u?.ok?{...s,...a,type:"expression",formula:ee(u.node)}:"an expression rule that cannot be read"}case"dataBar":{const u=l(n.dataBar),p=A(l(u?.color),o),[x,h]=b(u?.cfvo).map(U);return p===void 0?"a data bar with no colour":{...s,type:"dataBar",color:p,...x&&x.at!=="min"?{min:x}:{},...h&&h.at!=="max"?{max:h}:{},...v(u,"showValue")===!1?{show:!1}:{}}}case"colorScale":{const u=l(n.colorScale),p=b(u?.cfvo).map(U),x=b(u?.color).map(k=>A(k,o)),h=p.flatMap((k,$)=>{const T=x[$];return T===void 0?[]:[{...k,color:T}]});return h.length<2?"a colour scale with too few stops":{...s,type:"colorScale",stops:h.slice(0,3)}}case"iconSet":{const u=l(n.iconSet),p=d(u,"iconSet")??"3TrafficLights1";if(!Me.includes(p))return`the icon set ${p}`;const x=b(u?.cfvo).map(U);return{...s,type:"iconSet",icons:p,...x.length>=3?{stops:x.slice(0,5)}:{},...v(u,"reverse")===!0?{reverse:!0}:{},...v(u,"showValue")===!1?{show:!1}:{}}}default:return`a ${r} rule`}}function Ve(n,e,t){const o=[],r=[];for(const s of b(n.conditionalFormatting)){const i=d(s,"sqref")??"";if(!Q(i)){r.push(`a rule on ${i}`);continue}for(const c of b(s.cfRule)){const a=De(c,i,e,t);typeof a=="string"?r.push(`${a} on ${i}`):o.push({priority:y(c,"priority")??0,rule:a})}}return{rules:o.sort((s,i)=>s.priority-i.priority).map(s=>s.rule),unread:r}}const ze=fe;function He(n){const e=[],t=[];for(const o of b(l(n.dataValidations)?.dataValidation)){const r=d(o,"sqref")??"",s=d(o,"type")??"none";if(s==="none"&&d(o,"prompt")===void 0)continue;if(!ze.includes(s)||!Q(r)){t.push(`a ${s} rule on ${r}`);continue}const i=C(o.formula1),c=C(o.formula2),a=/^"((?:[^"]|"")*)"$/u.exec(i.trim()),m=s==="list"&&a?(a[1]??"").replaceAll('""','"').split(","):void 0,f=[i,c].flatMap(T=>{const I=q(T);return I===void 0?[]:[I]}),u=d(o,"operator"),p=T=>Object.fromEntries(Object.entries(T).filter(([,I])=>I!==void 0)),x=p({title:d(o,"promptTitle"),message:d(o,"prompt")}),h=p({style:d(o,"errorStyle"),title:d(o,"errorTitle"),message:d(o,"error")}),k=v(o,"showInputMessage")!==!0,$=v(o,"showErrorMessage")!==!0;e.push({range:r,type:s,...se(u)&&u!=="between"?{operator:u}:{},...m?{values:m}:{formula:f},...v(o,"allowBlank")===!0?{}:{blank:!1},...v(o,"showDropDown")===!0?{dropdown:!1}:{},...k||Object.keys(x).length>0?{prompt:{...x,...k?{show:!1}:{}}}:{},...$||Object.keys(h).length>0?{error:{...h,...$?{show:!1}:{}}}:{}})}return{rules:e,unread:t}}function X(n,e){const t=B(n,e);return t.ok?{node:t.node}:{unread:n}}class _e{cells=[];rich=[];masters=new Map;strings;constructor(e){this.strings=e}value(e,t){const o=d(e,"t")??"n",r=e.v;if(o==="inlineStr"){const i=l(e.is),c=b(i?.r);return c.length>0?{value:L(c.map(a=>C(a.t)).join("")),rich:!0}:{value:L(C(i?.t))}}if(r===void 0)return{value:void 0};const s=C(r);switch(o){case"s":{const i=this.strings[Number(s)];return i?{value:i.text,...i.rich?{rich:!0}:{}}:{value:""}}case"str":return{value:L(s)};case"b":return{value:s.trim()==="1"||s.trim()==="true"};case"e":return{value:be(s.trim())??pe.VALUE};case"d":{const i=new Date(s.trim());return{value:Number.isNaN(i.getTime())?s:ge(i)}}default:{if(s.trim()==="")return{value:void 0};const i=Number(s);if(Number.isNaN(i))throw new Error(`${t} says it holds a number and holds ${s}.`);return{value:i}}}}formula(e,t,o,r){const s=e.f;if(s===void 0)return;const i=l(s),c=d(i,"t")??"normal",a=C(s);if(c==="dataTable"){r.unread=`a data table's {=TABLE(${d(i,"r1")??""})}`;return}if(c==="array"){const m=e.cm!==void 0;Object.assign(r,X(a,!0));const f=H(d(i,"ref")??"");f&&(r.array=f),m&&(r.dynamic=!0);return}if(c==="shared"){const m=d(i,"si")??"";if(a!==""){const u=X(a,!1);this.masters.set(m,{node:u.node,unread:u.unread,row:t,col:o,key:u.node?he(u.node,t,o):"",dynamicArray:!1}),Object.assign(r,u),u.node&&(r.key=this.masters.get(m)?.key??"");return}const f=this.masters.get(m);if(!f){r.unread=`a shared formula of a group that has no first cell (${m})`;return}f.node?(r.node=me(f.node,t-f.row,o-f.col),r.key=f.key):f.unread!==void 0&&(r.unread=f.unread);return}a!==""&&Object.assign(r,X(a,!1))}readRows(e){let t=0;for(const o of e){const r=y(o,"r"),s=r===void 0?t:r-1;t=s+1;let i=0;for(const c of b(o.c)){const a=d(c,"r"),f=(a===void 0?void 0:K(a))?.col??i;i=f+1;const u=a??J({row:s,col:f}),{value:p,rich:x}=this.value(c,u),h={row:s,col:f,value:p,style:y(c,"s")??0};x===!0&&(h.rich=!0,this.rich.push(u)),this.formula(c,s,f,h),this.cells.push(h)}}}}function Pe(n,e,t){const o=[],r=a=>o.push(`${n}: ${a}`);t.length>0&&r(`${_(t.length,"cell")} of rich text, kept as plain text (${placesLine(t)})`);const s=b(l(e.hyperlinks)?.hyperlink);s.length>0&&r(`${_(s.length,"hyperlink")} (${placesLine(s.map(a=>d(a,"ref")??""))})`),e.sortState!==void 0&&r("a sort"),v(l(e.sheetProtection),"sheet")===!0&&r("protection"),e.protectedRanges!==void 0&&r("protected ranges"),e.headerFooter!==void 0&&C(e.headerFooter).trim()!==""&&r("its print header and footer"),l(e.headerFooter)?.oddHeader!==void 0&&r("its print header"),l(e.headerFooter)?.oddFooter!==void 0&&r("its print footer"),(e.rowBreaks!==void 0||e.colBreaks!==void 0)&&r("its page breaks"),e.oleObjects!==void 0&&r("embedded objects"),e.controls!==void 0&&r("form controls"),e.dataConsolidate!==void 0&&r("a consolidation"),e.customSheetViews!==void 0&&r("custom views"),b(l(e.sheetViews)?.sheetView).some(a=>d(l(a.pane),"state")==="split")&&r("a split, not frozen, window");const c=JSON.stringify(e.extLst??"");return c.includes("sparklineGroups")&&r("sparklines"),G(e.extLst)&&r("conditional formats of Excel 2010 and later"),c.includes("dataValidations")&&r("data validations of Excel 2010 and later"),c.includes("slicerList")&&r("slicers"),o}function G(n){if(typeof n!="object"||n===null)return!1;if(Array.isArray(n))return n.some(G);const e=n;return b(e.cfRule).some(t=>d(t,"type")!=="dataBar")&&e.cfRule!==void 0?!0:Object.values(e).some(G)}function Be(n){const e=[],t=(o,r,s)=>{const i=n.count(o);i>0&&e.push(_(i,r,s))};return n.has("xl/vbaProject.bin")&&e.push("VBA macros"),t(/^xl\/pivotTables\/pivotTable\d*\.xml$/u,"pivot table"),t(/^xl\/chartsheets\/[^/]+\.xml$/u,"chart sheet"),t(/^xl\/dialogsheets\/[^/]+\.xml$/u,"dialog sheet"),t(/^xl\/macrosheets\/[^/]+\.xml$/u,"macro sheet"),t(/^xl\/media\//u,"image"),t(/^xl\/embeddings\//u,"embedded object"),t(/^xl\/comments\d*\.xml$/u,"sheet's comments","sheets' comments"),t(/^xl\/threadedComments\//u,"sheet's threaded comments","sheets' threaded comments"),t(/^xl\/slicers\/[^/]+\.xml$/u,"slicer part"),t(/^xl\/timelines\/[^/]+\.xml$/u,"timeline part"),t(/^xl\/ctrlProps\/[^/]+\.xml$/u,"form control"),t(/^xl\/activeX\/[^/]+\.xml$/u,"ActiveX control"),t(/^xl\/queryTables\/[^/]+\.xml$/u,"query table"),n.has("xl/connections.xml")&&e.push("data connections"),n.names.some(o=>o.startsWith("xl/richData/"))&&e.push("rich values (data types, pictures in cells)"),n.names.some(o=>/^customXml\/item\d+\.xml$/u.test(o)&&(n.text(o)??"").includes("DataMashup"))&&e.push("Power Query queries"),e}function We(n,e,t,o,r,s,i){const c=n.xml(e),a=l(c?.worksheet);if(!a)throw new Error(`${e} is not a worksheet.`);const m=new _e(r);m.readRows(b(l(a.sheetData)?.row));const f=b(l(a.cols)?.col).map(g=>{const E=y(g,"width"),D=y(g,"style");return{min:(y(g,"min")??1)-1,max:(y(g,"max")??1)-1,...E===void 0||v(g,"customWidth")===!1?{}:{width:Se(E)},...v(g,"hidden")===!0?{hidden:!0}:{},...D===void 0||D===0?{}:{style:D}}}),u=[];let p=b(l(a.cols)?.col).some(g=>(y(g,"outlineLevel")??0)>0);b(l(a.sheetData)?.row).forEach((g,E)=>{const D=(y(g,"r")??E+1)-1;(y(g,"outlineLevel")??0)>0&&(p=!0);const Z=y(g,"ht"),P=y(g,"s"),V={row:D};Z!==void 0&&v(g,"customHeight")===!0&&(V.height=Te(Z)),v(g,"hidden")===!0&&(V.hidden=!0),P!==void 0&&P!==0&&v(g,"customFormat")===!0&&(V.style=P),Object.keys(V).length>1&&u.push(V)});const x=b(l(a.mergeCells)?.mergeCell).flatMap(g=>{const E=H(d(g,"ref")??"");return E?[E]:[]}),h=b(l(a.sheetViews)?.sheetView)[0],k=l(h?.pane);let $;const T=d(k,"state");if(T==="frozen"||T==="frozenSplit"){const g=K(d(h,"topLeftCell")??"A1")??{row:0,col:0};$={row:g.row+(y(k,"ySplit")??0),col:g.col+(y(k,"xSplit")??0)}}const I=n.rels(e).filter(g=>g.type==="table").flatMap(g=>{const E=je(n.xml(g.target));return E?[E]:[]}),F=A(l(l(a.sheetPr)?.tabColor),s),O=Pe(t,a,m.rich);p&&O.push(`${t}: its grouped rows or columns, left ungrouped`);const N=Ve(a,i,s),w=He(a);for(const g of N.unread)O.push(`${t}: a conditional format, ${g}`);for(const g of w.unread)O.push(`${t}: a data validation, ${g}`);const S=l(a.autoFilter),M=H(d(S,"ref")??""),R=S&&M?{ref:M,...re(S)}:void 0;R&&R.unread>0&&O.push(`${t}: ${_(R.unread,"filter")} by condition on ${d(S,"ref")??""}, its rows left as they were hidden`);const z=Xe(n,e,t,f,u,O);return{sheet:{name:t,state:o,cells:m.cells,merges:x,...$?{freeze:$}:{},...d(h,"showGridLines")==="0"?{gridlines:!1}:{},...F===void 0?{}:{tab:F},columns:f,rows:u,tables:I,conditional:N.rules,validations:w.rules,scenarios:b(l(a.scenarios)?.scenario).map(g=>({name:d(g,"name")??"",cells:b(g.inputCells).map(E=>({at:d(E,"r")??"",value:d(E,"val")??""}))})),...R?{filter:R}:{},charts:z},lost:O}}const qe=64,Ue=20;function Xe(n,e,t,o,r,s){const i=m=>o.find(f=>m>=f.min&&m<=f.max)?.width??qe,c=m=>r.find(f=>f.row===m)?.height??Ue,a=[];for(const m of n.rels(e).filter(f=>f.type==="drawing")){const{anchors:f}=we(n.xml(m.target),i,c),u=n.rels(m.target);for(const p of f){const x=u.find($=>$.id===p.id),h=ve(x?n.xml(x.target):void 0),k=J(p.at);if(typeof h=="string"){s.push(`${t}: the chart at ${k}, as ${h}`);continue}a.push({...h,at:k,...p.x===void 0?{}:{x:p.x},...p.y===void 0?{}:{y:p.y},...p.width===Y.width?{}:{width:p.width},...p.height===Y.height?{}:{height:p.height}})}}return a}export function readXlsx(n,e){let t;try{t=new Ee(n,e)}catch(w){throw w instanceof ce?w:new Error("It is not a zip file, as an .xlsx file is.")}const r=t.rels("").find(w=>w.type==="officeDocument")?.target??"xl/workbook.xml";if(r.endsWith(".bin"))throw new Error("It is a binary workbook (.xlsb): save it as .xlsx.");const s=t.xml(r),i=l(s?.workbook);if(!i)throw new Error("It has no workbook part.");const c=t.rels(r),a=w=>c.find(S=>S.type===w)?.target,m=(()=>{const w=a("theme");return w===void 0?void 0:t.text(w)})(),f=m===void 0?xe:ye(m),u=a("styles"),p=u===void 0?void 0:t.xml(u),x=Ne(p,f),h=te(f,l(p?.styleSheet)),k=Ie(t,a("sharedStrings")),$=[...Be(t)];for(const w of x.lost)$.push(w);const T=l(i.workbookPr),I=l(i.calcPr);v(I,"iterate")===!0&&$.push("iterative calculation");const F=l(i.workbookProtection);(v(F,"lockStructure")===!0||v(F,"lockWindows")===!0)&&$.push("the workbook's protection"),i.fileSharing!==void 0&&$.push("its write protection");const O=[],N=new Map(c.map(w=>[w.id,w]));for(const w of b(l(i.sheets)?.sheet)){const S=N.get(d(w,"id")??""),M=L(d(w,"name")??"");if(S?.type!=="worksheet"){S?.type!=="chartsheet"&&S?.type!=="dialogsheet"&&$.push(`${M}: a sheet of a kind this cannot read`);continue}const R=d(w,"state"),z=We(t,S.target,M,R==="hidden"||R==="veryHidden"?R:"visible",k,h,x.dxfs);O.push(z.sheet),$.push(...z.lost)}return{sheets:O,names:b(l(i.definedNames)?.definedName).map(w=>{const S=y(w,"localSheetId");return{name:d(w,"name")??"",text:L(C(w)),...S===void 0?{}:{sheet:S}}}),looks:x.looks,dxfs:x.dxfs,date1904:v(T,"date1904")===!0,font:x.font,lost:$}}
|