@libraz/formulon 0.12.0 โ†’ 0.14.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
@@ -5,18 +5,28 @@
5
5
  [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/libraz/formulon/blob/main/LICENSE)
6
6
  [![Docs](https://img.shields.io/badge/docs-formulon.libraz.net-2563eb)](https://formulon.libraz.net)
7
7
 
8
- Excel 365 calculation engine, compiled to WebAssembly. Evaluates formulas,
9
- loads and saves `.xlsx` workbooks, and defaults to the `win-365-ja_JP`
10
- behavior profile. Hosts can select the separately supported
11
- `mac-365-ja_JP` profile when required.
8
+ **Recalculate Excel workbooks and formulas in the browser and Node, with results checked against real Excel 365.**
9
+ The engine is a C++17 core compiled to WebAssembly, so it needs no Excel install, no Windows and no server: a workbook a user opens in the page is calculated on their machine and never uploaded.
12
10
 
13
- ## Install
11
+ Known differences from Excel are listed case by case in [`tests/divergence.yaml`](https://github.com/libraz/formulon/blob/main/tests/divergence.yaml), each with a reason and the Excel build it was last verified on.
14
12
 
15
- ```sh
16
- npm install @libraz/formulon
13
+ ๐Ÿ“– **[Documentation](https://formulon.libraz.net)**  ยท  **[WASM guide](https://formulon.libraz.net/runtimes/wasm)**  ยท  **[API](https://formulon.libraz.net/api/wasm)**  ยท  **[Demos](https://formulon.libraz.net/demos)**
14
+
15
+ ## What's inside
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 and print layout. [File formats](https://formulon.libraz.net/compatibility/file-format-support)
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
+ - **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
+ - **Two builds** โ€” a single-threaded default that loads anywhere, and `@libraz/formulon/threads` for parallel recalculation. [Choosing a build](#choosing-a-build)
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install @libraz/formulon # browsers and Node 22+
17
27
  ```
18
28
 
19
- Requires Node.js 22 or newer (the package is shipped as ES modules).
29
+ The package is ES modules only and ships its TypeScript declarations.
20
30
 
21
31
  ## Quick start
22
32
 
@@ -24,192 +34,73 @@ Requires Node.js 22 or newer (the package is shipped as ES modules).
24
34
  import createFormulon from '@libraz/formulon';
25
35
 
26
36
  const Module = await createFormulon();
27
-
28
- const r = Module.evalFormula('=SUM(1,2,3)');
29
- console.log(r.value.number); // 6
37
+ console.log(Module.evalFormula('=SUM(1,2,3)').value.number); // 6
30
38
  ```
31
39
 
32
- `evalFormula` returns an envelope of the form `{ status, value }`. Excel
33
- errors (e.g. `#DIV/0!`) are surfaced as a `value.kind === 4` (Error)
34
- result rather than a failed status; only host-side problems
35
- (out-of-memory, parser crashes) populate `status.ok === false`.
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).
36
41
 
37
- ## Workbook example
42
+ ## Recalculate a workbook
38
43
 
39
44
  ```js
40
45
  import createFormulon from '@libraz/formulon';
41
46
  import { readFile, writeFile } from 'node:fs/promises';
42
47
 
43
48
  const Module = await createFormulon();
44
-
45
- // Load an existing workbook from disk.
46
- const bytes = await readFile('input.xlsx');
47
- const wb = Module.Workbook.loadBytes(bytes);
49
+ const wb = Module.Workbook.loadBytes(await readFile('input.xlsx'));
48
50
  try {
49
- if (!wb.isValid()) {
50
- throw new Error(`load failed: ${Module.lastErrorMessage()}`);
51
- }
51
+ if (!wb.isValid()) throw new Error(Module.lastErrorMessage());
52
52
 
53
- // Mutate, recalc, save.
54
- wb.setNumber(0, 0, 0, 42); // Sheet1!A1 = 42
55
- wb.setFormula(0, 1, 0, '=A1*2'); // Sheet1!A2 = =A1*2
53
+ wb.setNumber(0, 0, 0, 42); // Sheet1!A1
54
+ wb.setFormula(0, 1, 0, '=A1*2'); // Sheet1!A2
56
55
  wb.recalc();
57
-
58
- const a2 = wb.getValue(0, 1, 0);
59
- console.log(a2.value.number); // 84
56
+ console.log(wb.getValue(0, 1, 0).value.number); // 84
60
57
 
61
58
  const saved = wb.save();
62
- if (saved.status.ok) {
63
- await writeFile('output.xlsx', saved.bytes);
64
- }
59
+ if (saved.status.ok) await writeFile('output.xlsx', saved.bytes);
65
60
  } finally {
66
- // Always release the native handle.
67
- wb.delete();
61
+ wb.delete(); // workbooks wrap a native handle
68
62
  }
69
63
  ```
70
64
 
71
- ## Choosing a build
72
-
73
- The package ships two builds of the same API:
74
-
75
- | Import | Threads | Hosting requirement |
76
- | --- | --- | --- |
77
- | `@libraz/formulon` | none | none; loads in any page, worker, Electron `file://` page, or Node |
78
- | `@libraz/formulon/threads` | up to 8 Web Workers for `recalcParallel` | a browser page must be cross-origin isolated |
65
+ ## Switching locale profiles
79
66
 
80
- The default build uses ordinary (non-shared) memory and starts no workers.
81
- `recalcParallel` is still callable there and runs the pass serially,
82
- reporting `workerThreadsStarted: 0`.
83
-
84
- The threads build allocates its memory as a `SharedArrayBuffer` and
85
- pre-spawns its worker pool when the factory is called, so in a browser it
86
- only loads when the page is served with `Cross-Origin-Opener-Policy:
87
- same-origin` and `Cross-Origin-Embedder-Policy: require-corp`. Node needs
88
- no extra setup.
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:
89
68
 
90
69
  ```js
91
- import createFormulon from '@libraz/formulon/threads';
70
+ const wb = Module.Workbook.createDefault();
71
+ 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
+ }
81
+ } finally {
82
+ wb.delete();
83
+ }
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' ]
92
87
  ```
93
88
 
94
- ## Bundler integration (Vite, webpack, esbuild)
95
-
96
- Each build is an ES module factory plus a companion `.wasm`
97
- (`formulon.wasm`, or `formulon_threads.wasm` for the threads build).
98
- Consumer-side concerns worth knowing about:
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 compare text case-insensitively by bytes, because Windows ordering is not measured. The profile is not saved into the file, so store the id your application targets and apply it again after loading.
99
90
 
100
- **1. The threads build needs ES module workers.** Its pthread workers are
101
- spawned by Emscripten with
102
- `new Worker(new URL("formulon_threads_core.js", import.meta.url), {type: "module"})`.
103
- Bundlers default to classic (IIFE) workers and must be told otherwise:
104
-
105
- ```ts
106
- // vite.config.ts
107
- export default defineConfig({
108
- worker: { format: 'es' },
109
- });
110
- ```
91
+ ## Choosing a build
111
92
 
112
- webpack 5 picks up the `{type: "module"}` automatically when
113
- `output.module: true`. esbuild requires `--format=esm` for the worker
114
- chunk.
115
-
116
- **2. Node bridging code is compiled in.** The factory contains a Node
117
- branch (lazy-loaded `node:module`, plus `node:worker_threads` in the
118
- threads build) that browser bundlers will warn about as
119
- "externalised". The warnings are harmless โ€” the branch is dead code at
120
- runtime in browsers โ€” but if you want to silence them, mark the imports
121
- external:
122
-
123
- ```ts
124
- // vite.config.ts
125
- export default defineConfig({
126
- optimizeDeps: { exclude: ['@libraz/formulon'] },
127
- build: {
128
- rollupOptions: {
129
- external: [/^node:/],
130
- },
131
- },
132
- });
133
- ```
93
+ | Import | Threads | Hosting requirement |
94
+ | --- | --- | --- |
95
+ | `@libraz/formulon` | none; `recalcParallel` runs serially | none; loads in any page, worker, Electron `file://` page, or Node |
96
+ | `@libraz/formulon/threads` | up to 8 workers for `recalcParallel` | a browser page must be cross-origin isolated (COOP / COEP); bundlers need ES module workers |
134
97
 
135
- If your bundler errors on the `await import("node:...")` form rather
136
- than just warning, raise the build target to `es2022` so the
137
- async-function-scoped `await` lexes cleanly:
98
+ Bundler settings for Vite, webpack and esbuild are in [Bundler requirements](https://formulon.libraz.net/runtimes/wasm#bundler-requirements).
138
99
 
139
- ```ts
140
- // vite.config.ts
141
- export default defineConfig({
142
- build: { target: 'es2022' },
143
- });
144
- ```
100
+ ## Non-goals
145
101
 
146
- ### Parallel recalculation
147
-
148
- `Workbook.recalc()` remains the serial, caller-thread recalculation API.
149
- `Workbook.recalcParallel(threadCount)` starts workers only in the
150
- `@libraz/formulon/threads` build; it is synchronous and returns a
151
- `{ status, stats }` result after all workers have joined. A thread count of
152
- `0` selects automatic detection capped at 8, `1` keeps all evaluation on the
153
- caller thread and starts no workers, and `2..8` sets the maximum worker count.
154
- Values above 8 return a failed status with `kInvalidArgument`.
155
-
156
- The five 64-bit scheduler counters in `stats` are surfaced as JavaScript
157
- `number` values (not `bigint`) and are exact through `Number.MAX_SAFE_INTEGER`
158
- (`2^53 - 1`). `workerThreadsStarted` and `workerThreadsUsed` report actual
159
- worker telemetry; the scheduler may use fewer workers than requested.
160
-
161
- ## API reference
162
-
163
- The full TypeScript surface is shipped as `dist/formulon.d.ts` and is the
164
- authoritative reference. Highlights:
165
-
166
- - `createFormulon(opts?)` -- the default export. Returns a Promise
167
- resolving to a `FormulonModule`.
168
- - `Module.evalFormula(formula)` -- one-shot evaluation against a fresh
169
- workbook.
170
- - `Module.Workbook.createDefault() / createEmpty() / loadBytes(bytes)` --
171
- factory methods for building or loading a workbook.
172
- - `Workbook.setNumber / setBool / setText / setBlank / setFormula` --
173
- cell mutators.
174
- - `Workbook.recalc()` -- triggers a serial, full dependency-ordered
175
- recalculation.
176
- - `Workbook.recalcParallel(threadCount)` -- synchronously recalculates with
177
- the parallel SCC scheduler and returns status plus telemetry (serial
178
- outside the threads build).
179
- - `Workbook.getValue(sheet, row, col)` -- reads a cached cell value.
180
- - `Workbook.save()` -- serialises back to an in-memory `.xlsx` byte buffer.
181
-
182
- Workbook handles wrap a native pointer; always call `wb.delete()` (in a
183
- `finally` block) when done.
184
-
185
- Two C ABI capabilities are bound in the Python package but not exposed
186
- here: `fm_workbook_set_iterative_enabled` (toggling iterative calculation
187
- without re-supplying the existing iteration cap and residual threshold --
188
- `setIterative(enabled, maxIterations, maxChange)` here always takes all
189
- three) and `fm_styles_add_batch` (bulk style registration). This is a
190
- genuine gap, not an intentional exclusion.
191
-
192
- ## Memory when loading a workbook
193
-
194
- Both surfaces inflate each worksheet part into memory whole before
195
- parsing it (the zip reader caps this at 100 MiB per entry, 256 MiB per
196
- load); `loadBytes` here then always builds a DOM tree from that buffer.
197
- The native CLI switches to a streaming parser for worksheets past 256
198
- KiB instead, which skips building the DOM tree -- that implementation
199
- costs binary size the WASM budget does not have -- but still holds the
200
- same inflated XML buffer first. Sheets are read one at a time, so the
201
- peak is per worksheet, and the practical ceiling here is the 32-bit WASM
202
- address space. Results are identical either way.
203
-
204
- ## Project
205
-
206
- Documentation โ€” guides, compatibility notes, and the per-runtime API
207
- reference โ€” is at <https://formulon.libraz.net>. Source, design notes,
208
- and the oracle test suite live at <https://github.com/libraz/formulon>.
209
- [formulon-cell](https://github.com/libraz/formulon-cell) is a browser
210
- spreadsheet UI built on this package; it doubles as an integration test
211
- and a worked example of embedding the engine.
102
+ 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).
212
103
 
213
104
  ## License
214
105
 
215
- Apache License 2.0. See [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
106
+ [Apache License 2.0](./LICENSE). See also [NOTICE](./NOTICE).
package/dist/common.js CHANGED
@@ -95,6 +95,80 @@ export const ErrorCode = Object.freeze({
95
95
  });
96
96
  export const CalcMode = Object.freeze({ Auto: 0, Manual: 1, AutoNoTable: 2 });
97
97
  export const SheetVisibility = Object.freeze({ Visible: 0, Hidden: 1, VeryHidden: 2 });
98
+ export const GeometryMode = Object.freeze({ Display: 0, Print: 1 });
99
+ export const FilterKind = Object.freeze({ None: 0, Values: 1, Custom: 2, Top10: 3, Dynamic: 4, Color: 5, Icon: 6 });
100
+ export const FilterOperator = Object.freeze({
101
+ Equal: 0,
102
+ LessThan: 1,
103
+ LessThanOrEqual: 2,
104
+ NotEqual: 3,
105
+ GreaterThanOrEqual: 4,
106
+ GreaterThan: 5,
107
+ });
108
+ export const DynamicFilterType = Object.freeze({
109
+ Null: 0,
110
+ AboveAverage: 1,
111
+ BelowAverage: 2,
112
+ Tomorrow: 3,
113
+ Today: 4,
114
+ Yesterday: 5,
115
+ NextWeek: 6,
116
+ ThisWeek: 7,
117
+ LastWeek: 8,
118
+ NextMonth: 9,
119
+ ThisMonth: 10,
120
+ LastMonth: 11,
121
+ NextQuarter: 12,
122
+ ThisQuarter: 13,
123
+ LastQuarter: 14,
124
+ NextYear: 15,
125
+ ThisYear: 16,
126
+ LastYear: 17,
127
+ YearToDate: 18,
128
+ Q1: 19,
129
+ Q2: 20,
130
+ Q3: 21,
131
+ Q4: 22,
132
+ M1: 23,
133
+ M2: 24,
134
+ M3: 25,
135
+ M4: 26,
136
+ M5: 27,
137
+ M6: 28,
138
+ M7: 29,
139
+ M8: 30,
140
+ M9: 31,
141
+ M10: 32,
142
+ M11: 33,
143
+ M12: 34,
144
+ });
145
+ export const SortBy = Object.freeze({ Value: 0, CellColor: 1, FontColor: 2, Icon: 3 });
146
+ export const SortMethod = Object.freeze({ None: 0, PinYin: 1, Stroke: 2 });
147
+ export const DateTimeGrouping = Object.freeze({ Year: 0, Month: 1, Day: 2, Hour: 3, Minute: 4, Second: 5 });
148
+ export const ValidationErrorStyle = Object.freeze({ Stop: 0, Warning: 1, Information: 2 });
149
+ export const ColorContext = Object.freeze({ Font: 0, FillForeground: 1, FillBackground: 2, Border: 3 });
150
+ export const ColorResolution = Object.freeze({
151
+ Exact: 0,
152
+ DefaultTheme: 1,
153
+ IndexOutOfRange: 2,
154
+ ThemeUnparseable: 3,
155
+ AutoContext: 4,
156
+ });
157
+ export const ImageFormat = Object.freeze({ Unknown: 0, Png: 1, Jpeg: 2, Gif: 3, Bmp: 4 });
158
+ export const DrawingObjectKind = Object.freeze({
159
+ Picture: 0,
160
+ Shape: 1,
161
+ Chart: 2,
162
+ Group: 3,
163
+ Connector: 4,
164
+ GraphicFrame: 5,
165
+ Other: 6,
166
+ });
167
+ export const AnchorKind = Object.freeze({ OneCell: 0, TwoCell: 1, Absolute: 2 });
168
+ export const AnchorEditAs = Object.freeze({ TwoCell: 0, OneCell: 1, Absolute: 2 });
169
+ export const ThemeSource = Object.freeze({ Part: 0, Default: 1, Unparseable: 2 });
170
+ export const EffectiveStyleSource = Object.freeze({ Cell: 0, Row: 1, Column: 2, Default: 3 });
171
+ export const DisplayStatus = Object.freeze({ Ok: 0, Overflow: 1, InvalidFormat: 2 });
98
172
  export const ExternalLinkKind = Object.freeze({ Unknown: 0, ExternalBook: 1, Ole: 2, Dde: 3 });
99
173
  export const LogLevel = Object.freeze({ Debug: 0, Info: 1, Warn: 2, Error: 3, Off: 4 });
100
174
 
@@ -121,8 +195,8 @@ export const LogLevel = Object.freeze({ Debug: 0, Info: 1, Warn: 2, Error: 3, Of
121
195
  * `undefined`/`null` to leave `base` unchanged (signature/description
122
196
  * stay `undefined`).
123
197
  * @param {string} locale A BCP-47 display locale tag (e.g. `"fr-FR"`),
124
- * matching the keys in `aliases` / `localized`. Independent of the numeric
125
- * locale code passed to `functionMetadata()`.
198
+ * matching the keys in `aliases` / `localized`. Independent of the profile id
199
+ * passed to the engine locale calls.
126
200
  * @returns {object} The merged metadata (a new object), or `base` verbatim
127
201
  * when `entry` is absent.
128
202
  */