@libraz/formulon 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,8 +14,8 @@ Known differences from Excel are listed case by case in [`tests/divergence.yaml`
14
14
 
15
15
  ## What's inside
16
16
 
17
- - **Formula engine** — 526 Excel function names, 511 implemented locally; dynamic arrays, `LET` / `LAMBDA`, and `REGEX*`. [Coverage](https://formulon.libraz.net/compatibility/formula-coverage)
18
- - **Workbook I/O** — read, recalculate and write `.xlsx` and `.xlsb`, including styles, conditional formatting, tables, pivot tables, charts and print layout. [File formats](https://formulon.libraz.net/compatibility/file-format-support)
17
+ - **Formula engine** — 527 Excel function names, 512 implemented locally; dynamic arrays, `LET` / `LAMBDA`, and `REGEX*`. [Coverage](https://formulon.libraz.net/compatibility/formula-coverage)
18
+ - **Workbook I/O** — read, recalculate and write `.xlsx` and `.xlsb`, including styles, conditional formatting, tables, pivot tables (refresh and grouping), charts, chartsheets, in-cell pictures, theme apply and save, and print layout; `.xlsb` carries pictures, charts and pivot tables too. A loaded workbook keeps its cached values where Excel would, and `recalcFull()` recomputes everything. A save of a workbook that holds something the target format cannot store fails with `IoFeatureNotWritable` and writes nothing. [File formats](https://formulon.libraz.net/compatibility/file-format-support)
19
19
  - **Locale profiles** — 28 Excel behavior profiles across fourteen locales on Mac and Windows hosts. [Locale profiles](https://formulon.libraz.net/compatibility/locale-profiles)
20
20
  - **Excel oracle** — formula results are compared bit for bit against goldens captured from Mac Excel 365 in fourteen locales. [Oracle testing](https://formulon.libraz.net/compatibility/oracle-testing)
21
21
  - **Two builds** — a single-threaded default that loads anywhere, and `@libraz/formulon/threads` for parallel recalculation. [Choosing a build](#choosing-a-build)
@@ -26,82 +26,144 @@ Known differences from Excel are listed case by case in [`tests/divergence.yaml`
26
26
  npm install @libraz/formulon # browsers and Node 22+
27
27
  ```
28
28
 
29
- The package is ES modules only and ships its TypeScript declarations.
29
+ The package is ES modules only (no `require`) and ships its TypeScript declarations, which need TypeScript 5.7 or later. It runs on Node 22+ and the current releases of the major browsers; the `threads` build also needs a cross-origin isolated page (see [Choosing a build](#choosing-a-build)). Deno and Bun are not tested.
30
+
31
+ Changes between releases are listed in the [CHANGELOG](https://github.com/libraz/formulon/blob/main/CHANGELOG.md). Until 1.0 a minor release may break the API; a patch release does not.
30
32
 
31
33
  ## Quick start
32
34
 
33
- ```js
35
+ ```js run
34
36
  import createFormulon from '@libraz/formulon';
35
37
 
36
- const Module = await createFormulon();
37
- console.log(Module.evalFormula('=SUM(1,2,3)').value.number); // 6
38
+ const formulon = await createFormulon();
39
+ console.log(formulon.evaluateFormula('=SUM(1,2,3)')); // 6
40
+ console.log(formulon.evaluateFormula('=1/0') instanceof formulon.ExcelError); // true
38
41
  ```
39
42
 
40
- Excel errors such as `#DIV/0!` come back as values (`value.kind === 4`); `status.ok === false` is reserved for host-side failures. See [Errors](https://formulon.libraz.net/compatibility/errors).
43
+ `evaluateFormula` returns a plain JavaScript value: `null` for a blank, a number, a boolean or a string, an `ExcelError` for an Excel error such as `#DIV/0!`, and a 2-D array for an array result. `evaluateTypedFormula` returns the tagged `Value` instead. A host-side failure throws `FormulonError`, whose `code` is a `StatusCode`. See [Errors](https://formulon.libraz.net/compatibility/errors).
41
44
 
42
45
  ## Recalculate a workbook
43
46
 
44
- ```js
47
+ ```js run
45
48
  import createFormulon from '@libraz/formulon';
46
49
  import { readFile, writeFile } from 'node:fs/promises';
47
50
 
48
- const Module = await createFormulon();
49
- const wb = Module.Workbook.loadBytes(await readFile('input.xlsx'));
51
+ const formulon = await createFormulon();
52
+
53
+ // Create input.xlsx first; any existing workbook file works the same way.
54
+ const seed = formulon.Workbook.createDefault();
50
55
  try {
51
- if (!wb.isValid()) throw new Error(Module.lastErrorMessage());
56
+ await writeFile('input.xlsx', seed.save());
57
+ } finally {
58
+ seed.dispose();
59
+ }
52
60
 
53
- wb.setNumber(0, 0, 0, 42); // Sheet1!A1
54
- wb.setFormula(0, 1, 0, '=A1*2'); // Sheet1!A2
61
+ const wb = formulon.Workbook.load(await readFile('input.xlsx'));
62
+ try {
63
+ const ws = wb.sheet(0); // or wb.sheet('Sheet1')
64
+ ws.setValue('A1', 42);
65
+ ws.setFormula('A2', '=A1*2');
66
+ console.log(wb.hasDirtyCells()); // true
55
67
  wb.recalc();
56
- console.log(wb.getValue(0, 1, 0).value.number); // 84
68
+ console.log(wb.hasDirtyCells()); // false
69
+ console.log(ws.getValue('A2')); // 84
57
70
 
58
- const saved = wb.save();
59
- if (saved.status.ok) await writeFile('output.xlsx', saved.bytes);
71
+ await writeFile('output.xlsx', wb.save());
60
72
  } finally {
61
- wb.delete(); // workbooks wrap a native handle
73
+ wb.dispose(); // workbooks wrap a native handle; `wb.disposed` turns true
62
74
  }
63
75
  ```
64
76
 
65
- ## Switching locale profiles
77
+ On Node 24+ and in bundlers that support explicit resource management, `using wb = formulon.Workbook.load(...)` releases the workbook at the end of the scope instead. `dispose()` frees the workbook at the moment you call it. A workbook dropped without it is released when the garbage collector reclaims it, which is best effort and may never happen, so dispose workbooks you are done with.
78
+
79
+ A `Sheet` handle stays on the same sheet when sheets are added, moved or removed around it. `wb.sheet('Sheet1')` finds a sheet by name (it throws `FormulonError` with `StatusCode.NotFound` when there is none), `wb.listSheets()` lists them all, and `ws.name` and `ws.index` read its current name and position. Every method that takes a cell accepts either `(row, col)` or an A1 string (`ws.setValue('A1', 42)`, `ws.getValue('A2')`), and a rectangle argument accepts `'A1:B2'`. `ws.getValues('A1:B2')` reads a block as rows of values and `ws.setValues('A1', [[1, 'x'], [true, null]])` writes one. A string that starts with `=` passed to `setValue` or `setValues` is entered as a formula; enter untrusted text with `ws.setText('A1', text)`, which always stores text.
66
80
 
67
- New workbooks use `win-365-en_US`. Formulas are always written with English function names and the stored separators; the profile decides how text is parsed and how results are rendered. Switch it per workbook and recalculate:
81
+ `ws.updateCellFormat(range, patch)` changes the number format, font, fill, border, alignment and protection of a cell or range, and leaves every attribute the patch does not name as it was. Whole-column and whole-row spans take the same strings as the size operations:
68
82
 
69
- ```js
70
- const wb = Module.Workbook.createDefault();
83
+ ```js run
84
+ import createFormulon from '@libraz/formulon';
85
+
86
+ const formulon = await createFormulon();
87
+ const wb = formulon.Workbook.createDefault();
71
88
  try {
72
- wb.setFormula(0, 0, 0, '=LENB("日本")'); // A1
73
- wb.setFormula(0, 1, 0, '=VALUE("1,5")'); // A2
74
- wb.setFormula(0, 2, 0, '=ISEVEN(2)'); // A3
75
-
76
- for (const id of ['mac-365-en_US', 'mac-365-ja_JP', 'mac-365-de_DE']) {
77
- wb.setExcelProfileId(id);
78
- wb.recalc(); // a profile change marks formulas dirty
79
- console.log(id, [0, 1, 2].map((row) => wb.getDisplayText(0, row, 0).text));
80
- }
89
+ const ws = wb.sheet(0);
90
+ ws.setValue('A1', 0.256);
91
+ ws.updateCellFormat('A1', { numberFormat: '0.0%', font: { bold: true, color: '#C00000' } });
92
+ ws.updateCellFormat('B:B', { alignment: { horizontal: formulon.HorizontalAlign.Center } });
93
+ ws.setColumnWidth('B:D', 12);
94
+ console.log(ws.getDisplayText('A1').text); // 25.6%
95
+ console.log(ws.getCellFormat('A1').font.bold); // true
81
96
  } finally {
82
- wb.delete();
97
+ wb.dispose();
83
98
  }
84
- // mac-365-en_US [ '2', '#VALUE!', 'TRUE' ]
85
- // mac-365-ja_JP [ '4', '#VALUE!', 'TRUE' ]
86
- // mac-365-de_DE [ '2', '1,5', 'WAHR' ]
87
99
  ```
88
100
 
89
- The ids are `{mac,win}-365-{ja_JP,en_US,de_DE,fr_FR,zh_CN,ko_KR,th_TH,es_ES,es_MX,pt_BR,ru_RU,zh_TW,it_IT,nl_NL}`. Every `mac-*` profile and `win-365-ja_JP` is measured against Excel; the other `win-*` profiles are estimated from the Mac measurements. On a `mac-*` profile, text comparison, sorting, lookups and grouping follow that locale's measured Mac Excel collation; `win-*` profiles add the Windows word-sort rules measured on Windows Excel 365 ja-JP to that locale's collation. The profile is not saved into the file, so store the id your application targets and apply it again after loading.
101
+ In the default automatic calculation mode a read calculates pending cells first; in manual mode it returns the value as of the last `recalc()`, and `wb.hasDirtyCells()` tells whether edits are still waiting for one. `ErrorDisplayName[ErrorCode.Div0]` gives `'#DIV/0!'` without a workbook. New workbooks use `win-365-en_US`; `wb.setProfileId(id)` takes any of `{mac,win}-365-{ja_JP,en_US,de_DE,fr_FR,zh_CN,ko_KR,th_TH,es_ES,es_MX,pt_BR,ru_RU,zh_TW,it_IT,nl_NL}`. Switching profiles is covered in the [root README](https://github.com/libraz/formulon#switching-excel-profiles).
90
102
 
91
- For a new workbook that matches what Excel creates in a locale, use `Workbook.createForProfile(id)` instead of `createDefault`: it selects the profile and also sets the body and phonetic fonts, the localized Normal style and first sheet names, and the page margins Excel uses there. Sheets added later take the first sheet's row metrics, page margins and phonetic settings.
103
+ ## Tables, pivot tables and charts
104
+
105
+ `addTable`, `addPivot`, `addPivotCache`, `addChart`, `addShape`, `addSlicer` and `addPicture` return a handle that stays on its object while other tables, pivots or drawings come and go. The operations on the object are methods of the handle; the workbook and the sheet keep adding, listing, looking up and removing:
106
+
107
+ ```js run
108
+ import createFormulon from '@libraz/formulon';
109
+
110
+ const formulon = await createFormulon();
111
+ const wb = formulon.Workbook.createDefault();
112
+ try {
113
+ const ws = wb.sheet(0);
114
+ ws.setValues('A1', [['Region', 'Amount'], ['East', 10], ['West', 30]]);
115
+
116
+ const chart = ws.addChart({ type: formulon.ChartPlotType.Bar, range: 'Sheet1!$A$1:$B$3' });
117
+ chart.setTitle('Sales');
118
+ console.log(chart.getProperties().title?.text); // Sales
119
+
120
+ const cache = wb.addPivotCache();
121
+ cache.setWorksheetSource({ range: 'A1:B3', sheet: 'Sheet1' });
122
+ cache.addField('Region');
123
+ cache.addField('Amount');
124
+ for (const [region, amount] of [['East', 10], ['West', 30]]) {
125
+ const record = cache.addRecord();
126
+ cache.setRecordValue(record, 0, region);
127
+ cache.setRecordValue(record, 1, amount);
128
+ }
129
+ const pivot = ws.addPivot({ name: 'ByRegion', cacheId: cache.cacheId, anchor: 'E1' });
130
+ pivot.setFieldAxis('Region', formulon.PivotAxis.Row);
131
+ pivot.addDataField({ name: 'Sum of Amount', fieldIndex: 'Amount', aggregation: formulon.PivotAggregation.Sum });
132
+ pivot.rename('Totals');
133
+ console.log(ws.pivot('Totals') === pivot); // true
134
+
135
+ ws.removePivot(pivot);
136
+ try {
137
+ pivot.getProperties();
138
+ } catch (e) {
139
+ console.log(e instanceof formulon.FormulonError && e.code === formulon.StatusCode.NotFound); // true
140
+ }
141
+ } finally {
142
+ wb.dispose();
143
+ }
144
+ ```
145
+
146
+ A handle of a removed object throws `FormulonError` with `StatusCode.NotFound`. Tables are added with `ws.addTable(input)` and reached with `ws.table(ref)` (a name or a sheet-local index), or by name from any sheet with `wb.table(name)`, charts and the other drawings with `ws.chart(id)`, `ws.shape(id)`, `ws.slicer(id)`, `ws.picture(id)` and `ws.drawing(id)`.
92
147
 
93
148
  ## Choosing a build
94
149
 
95
150
  | Import | Threads | Hosting requirement |
96
151
  | --- | --- | --- |
97
- | `@libraz/formulon` | none; `recalcParallel` runs serially | none; loads in any page, worker, Electron `file://` page, or Node |
98
- | `@libraz/formulon/threads` | up to 8 workers for `recalcParallel` | a browser page must be cross-origin isolated (COOP / COEP); bundlers need ES module workers |
152
+ | `@libraz/formulon` | none; `recalcParallel` and `recalcFullParallel` run serially | none; loads in any page, worker, Electron `file://` page, or Node |
153
+ | `@libraz/formulon/threads` | up to 8 workers for `recalcParallel` and `recalcFullParallel` | a browser page must be cross-origin isolated (COOP / COEP); bundlers need ES module workers |
99
154
 
100
155
  Bundler settings for Vite, webpack and esbuild are in [Bundler requirements](https://formulon.libraz.net/runtimes/wasm#bundler-requirements).
101
156
 
157
+ Vite may warn that `node:module` "has been externalized for browser compatibility" when it bundles `@libraz/formulon`. The warning is expected and harmless: the import runs only after the loader has detected Node, so a browser never reaches it.
158
+
102
159
  ## Non-goals
103
160
 
104
- VBA execution, legacy `.xls`, chart rendering, Power Query / DAX, pivot cache refresh from source data, live external connections, and a spreadsheet UI are permanently out of scope. See [Non-goals](https://formulon.libraz.net/compatibility/non-goals).
161
+ VBA execution, legacy `.xls`, chart rendering, Power Query / DAX, live external connections, and a spreadsheet UI are permanently out of scope. See [Non-goals](https://formulon.libraz.net/compatibility/non-goals).
162
+
163
+ ## Related projects
164
+
165
+ - [formulon-cell](https://formulon.libraz.net/cell/) — Excel-like spreadsheet component for the browser, React and Vue ([repository](https://github.com/libraz/formulon-cell))
166
+ - [formulon-mcp](https://formulon.libraz.net/mcp/) — MCP server that gives AI agents workbook tools ([repository](https://github.com/libraz/formulon-mcp))
105
167
 
106
168
  ## License
107
169