@file-viewer/renderer-spreadsheet 3.2.1 → 3.3.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.
@@ -0,0 +1,412 @@
1
+ import { utils } from 'styled-exceljs';
2
+ const MAX_STEPS = 2000000;
3
+ const MAX_DEPTH = 128;
4
+ const ADDRESS = /^\$?([A-Z]{1,3})\$?([1-9][0-9]*)$/i;
5
+ const unavailable = () => {
6
+ throw new Error('Formula value unavailable');
7
+ };
8
+ function tokenize(formula) {
9
+ if (formula.length > 8192)
10
+ return unavailable();
11
+ const tokens = [];
12
+ let rest = formula.replace(/^=/, '');
13
+ while (rest.length) {
14
+ const space = /^\s+/.exec(rest);
15
+ if (space) {
16
+ rest = rest.slice(space[0].length);
17
+ continue;
18
+ }
19
+ const match = /^(?:"(?:[^"]|"")*"|'(?:[^']|'')*'|(?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][+-]?\d+)?|[\p{L}_$\\][\p{L}\p{N}_.$\\]*|<>|<=|>=|[+\-*/^&=<>%(),!:])/u.exec(rest);
20
+ if (!match || tokens.length >= 4096)
21
+ return unavailable();
22
+ const text = match[0];
23
+ tokens.push({
24
+ kind: text[0] === '"'
25
+ ? 'string'
26
+ : text[0] === "'"
27
+ ? 'quoted'
28
+ : /^[\d.]/.test(text)
29
+ ? 'number'
30
+ : /^[\p{L}_$\\]/u.test(text)
31
+ ? 'name'
32
+ : text,
33
+ text
34
+ });
35
+ rest = rest.slice(text.length);
36
+ }
37
+ tokens.push({ kind: 'eof', text: '' });
38
+ return tokens;
39
+ }
40
+ class FormulaParser {
41
+ constructor(tokens) {
42
+ this.tokens = tokens;
43
+ this.index = 0;
44
+ this.depth = 0;
45
+ }
46
+ current() {
47
+ return this.tokens[this.index];
48
+ }
49
+ take(kind) {
50
+ if (this.current().kind !== kind)
51
+ return false;
52
+ this.index++;
53
+ return true;
54
+ }
55
+ parse() {
56
+ const result = this.expression();
57
+ if (this.current().kind !== 'eof')
58
+ return unavailable();
59
+ return result;
60
+ }
61
+ expression(minimum = 0) {
62
+ var _a;
63
+ if (++this.depth > MAX_DEPTH)
64
+ return unavailable();
65
+ let left = this.primary();
66
+ const precedence = {
67
+ '=': 1,
68
+ '<>': 1,
69
+ '<': 1,
70
+ '>': 1,
71
+ '<=': 1,
72
+ '>=': 1,
73
+ '&': 2,
74
+ '+': 3,
75
+ '-': 3,
76
+ '*': 4,
77
+ '/': 4,
78
+ '^': 5
79
+ };
80
+ while (((_a = precedence[this.current().kind]) !== null && _a !== void 0 ? _a : -1) >= minimum) {
81
+ const op = this.tokens[this.index++].kind;
82
+ left = { kind: 'binary', op, left, right: this.expression(precedence[op] + 1) };
83
+ }
84
+ this.depth--;
85
+ return left;
86
+ }
87
+ primary() {
88
+ const token = this.tokens[this.index++];
89
+ let result;
90
+ if (token.kind === '+' || token.kind === '-') {
91
+ result = { kind: 'unary', op: token.kind, value: this.expression(6) };
92
+ }
93
+ else if (token.kind === 'number') {
94
+ const value = Number(token.text);
95
+ if (!Number.isFinite(value))
96
+ return unavailable();
97
+ result = { kind: 'value', value };
98
+ }
99
+ else if (token.kind === 'string') {
100
+ result = { kind: 'value', value: token.text.slice(1, -1).replace(/""/g, '"') };
101
+ }
102
+ else if (token.kind === '(') {
103
+ result = this.expression();
104
+ if (!this.take(')'))
105
+ return unavailable();
106
+ }
107
+ else if (token.kind === 'name' || token.kind === 'quoted') {
108
+ if (token.kind === 'name' && this.take('(')) {
109
+ const args = [];
110
+ if (!this.take(')')) {
111
+ do {
112
+ args.push(this.expression());
113
+ } while (this.take(','));
114
+ if (!this.take(')'))
115
+ return unavailable();
116
+ }
117
+ result = { kind: 'call', name: token.text.toUpperCase(), args };
118
+ }
119
+ else {
120
+ let address = token.text;
121
+ let sheet;
122
+ if (this.take('!')) {
123
+ sheet = token.kind === 'quoted' ? token.text.slice(1, -1).replace(/''/g, "'") : token.text;
124
+ address = this.tokens[this.index++].text;
125
+ }
126
+ else if (/^(TRUE|FALSE)$/i.test(address)) {
127
+ return { kind: 'value', value: address.toUpperCase() === 'TRUE' };
128
+ }
129
+ if (!ADDRESS.test(address))
130
+ return unavailable();
131
+ let end;
132
+ if (this.take(':')) {
133
+ end = this.tokens[this.index++].text;
134
+ if (!ADDRESS.test(end))
135
+ return unavailable();
136
+ }
137
+ result = { kind: 'ref', sheet, address, end };
138
+ }
139
+ }
140
+ else
141
+ return unavailable();
142
+ while (this.take('%'))
143
+ result = { kind: 'unary', op: '%', value: result };
144
+ return result;
145
+ }
146
+ }
147
+ const position = (address) => {
148
+ const match = ADDRESS.exec(address);
149
+ if (!match)
150
+ return unavailable();
151
+ let col = 0;
152
+ for (const char of match[1].toUpperCase())
153
+ col = col * 26 + char.charCodeAt(0) - 64;
154
+ const row = Number(match[2]);
155
+ if (col > 16384 || row > 1048576)
156
+ return unavailable();
157
+ return { row: row - 1, col: col - 1 };
158
+ };
159
+ const key = (row, col) => `${row}:${col}`;
160
+ const numeric = (value) => {
161
+ if (value === null)
162
+ return 0;
163
+ if (typeof value === 'boolean')
164
+ return value ? 1 : 0;
165
+ if (typeof value === 'string' &&
166
+ !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][+-]?\d+)?$/.test(value.trim()))
167
+ return unavailable();
168
+ const number = typeof value === 'string' ? Number(value.trim()) : value;
169
+ if (!Number.isFinite(number))
170
+ return unavailable();
171
+ return number;
172
+ };
173
+ const scalar = (value) => (Array.isArray(value) ? unavailable() : value);
174
+ const textValue = (value) => typeof value === 'boolean' ? (value ? 'TRUE' : 'FALSE') : String(value !== null && value !== void 0 ? value : '');
175
+ const needsValue = (cell) => !!cell.f && (cell.t === 'z' || cell.v === undefined || cell.v === null);
176
+ function cellsOf(sheet) {
177
+ const result = new Map();
178
+ const data = Array.isArray(sheet)
179
+ ? sheet
180
+ : sheet['!data'];
181
+ if (data) {
182
+ for (const rowKey of Object.keys(data)) {
183
+ const row = Number(rowKey);
184
+ if (!Number.isInteger(row) || row < 0 || !Array.isArray(data[row]))
185
+ continue;
186
+ for (const colKey of Object.keys(data[row])) {
187
+ const col = Number(colKey), cell = data[row][col];
188
+ if (Number.isInteger(col) && col >= 0 && cell && needsValue(cell))
189
+ result.set(key(row, col), cell);
190
+ }
191
+ }
192
+ }
193
+ else {
194
+ for (const address of Object.keys(sheet)) {
195
+ if (!ADDRESS.test(address))
196
+ continue;
197
+ const { row, col } = position(address);
198
+ if (sheet[address] && needsValue(sheet[address]))
199
+ result.set(key(row, col), sheet[address]);
200
+ }
201
+ }
202
+ return result;
203
+ }
204
+ export function recoverUncachedFormulaValues(workbook) {
205
+ var _a;
206
+ const sheets = new Map(workbook.SheetNames.map((name) => [
207
+ name.toLowerCase(),
208
+ { name, sheet: workbook.Sheets[name], cells: cellsOf(workbook.Sheets[name]) }
209
+ ]));
210
+ const results = new Map();
211
+ const failed = new Set();
212
+ const visiting = new Set();
213
+ let steps = 0;
214
+ const tick = () => {
215
+ if (++steps > MAX_STEPS)
216
+ return unavailable();
217
+ };
218
+ const resolveSheet = (name) => { var _a; return (_a = sheets.get(name.toLowerCase())) !== null && _a !== void 0 ? _a : unavailable(); };
219
+ const readCell = (name, row, col, depth) => {
220
+ var _a, _b;
221
+ tick();
222
+ if (depth > MAX_DEPTH)
223
+ return unavailable();
224
+ const { sheet } = resolveSheet(name);
225
+ const data = Array.isArray(sheet)
226
+ ? sheet
227
+ : sheet['!data'];
228
+ const cell = data
229
+ ? (_a = data[row]) === null || _a === void 0 ? void 0 : _a[col]
230
+ : sheet[utils.encode_cell({ r: row, c: col })];
231
+ if (!cell)
232
+ return null;
233
+ if (results.has(cell))
234
+ return results.get(cell);
235
+ if (failed.has(cell) || visiting.has(cell) || cell.t === 'e')
236
+ return unavailable();
237
+ if (!needsValue(cell)) {
238
+ if (cell.v instanceof Date)
239
+ return unavailable();
240
+ const value = (_b = cell.v) !== null && _b !== void 0 ? _b : null;
241
+ return typeof value === 'number' && !Number.isFinite(value) ? unavailable() : value;
242
+ }
243
+ visiting.add(cell);
244
+ try {
245
+ const tree = new FormulaParser(tokenize(cell.f)).parse();
246
+ const value = scalar(evaluate(tree, name, row, depth + 1));
247
+ if (typeof value === 'number' && !Number.isFinite(value))
248
+ return unavailable();
249
+ results.set(cell, value);
250
+ return value;
251
+ }
252
+ catch {
253
+ failed.add(cell);
254
+ return unavailable();
255
+ }
256
+ finally {
257
+ visiting.delete(cell);
258
+ }
259
+ };
260
+ const evaluate = (node, sheet, row, depth) => {
261
+ var _a, _b;
262
+ tick();
263
+ if (depth > MAX_DEPTH)
264
+ return unavailable();
265
+ const run = (child) => evaluate(child, sheet, row, depth + 1);
266
+ if (node.kind === 'value')
267
+ return node.value;
268
+ if (node.kind === 'ref') {
269
+ const start = position(node.address);
270
+ if (!node.end)
271
+ return readCell((_a = node.sheet) !== null && _a !== void 0 ? _a : sheet, start.row, start.col, depth + 1);
272
+ const end = position(node.end);
273
+ const minRow = Math.min(start.row, end.row), maxRow = Math.max(start.row, end.row);
274
+ const minCol = Math.min(start.col, end.col), maxCol = Math.max(start.col, end.col);
275
+ if ((maxRow - minRow + 1) * (maxCol - minCol + 1) > MAX_STEPS - steps)
276
+ return unavailable();
277
+ const values = [];
278
+ for (let r = minRow; r <= maxRow; r++)
279
+ for (let c = minCol; c <= maxCol; c++)
280
+ values.push(readCell((_b = node.sheet) !== null && _b !== void 0 ? _b : sheet, r, c, depth + 1));
281
+ return values;
282
+ }
283
+ if (node.kind === 'unary') {
284
+ const number = numeric(scalar(run(node.value)));
285
+ return node.op === '-' ? -number : node.op === '%' ? number / 100 : number;
286
+ }
287
+ if (node.kind === 'binary') {
288
+ const left = scalar(run(node.left)), right = scalar(run(node.right));
289
+ if (node.op === '&')
290
+ return textValue(left) + textValue(right);
291
+ if (['=', '<>', '<', '>', '<=', '>='].includes(node.op)) {
292
+ const normalize = (value, other) => value === null
293
+ ? typeof other === 'string'
294
+ ? ''
295
+ : typeof other === 'boolean'
296
+ ? false
297
+ : 0
298
+ : typeof value === 'string'
299
+ ? value.toUpperCase()
300
+ : value;
301
+ const a = normalize(left, right), b = normalize(right, left);
302
+ const rank = (value) => typeof value === 'number' ? 0 : typeof value === 'string' ? 1 : 2;
303
+ const comparison = typeof a === typeof b ? (a === b ? 0 : a < b ? -1 : 1) : rank(a) - rank(b);
304
+ return node.op === '='
305
+ ? comparison === 0
306
+ : node.op === '<>'
307
+ ? comparison !== 0
308
+ : node.op === '<'
309
+ ? comparison < 0
310
+ : node.op === '>'
311
+ ? comparison > 0
312
+ : node.op === '<='
313
+ ? comparison <= 0
314
+ : comparison >= 0;
315
+ }
316
+ const a = numeric(left), b = numeric(right);
317
+ if (node.op === '/' && b === 0)
318
+ return unavailable();
319
+ if (node.op === '^' && a === 0 && b === 0)
320
+ return unavailable();
321
+ const value = node.op === '+'
322
+ ? a + b
323
+ : node.op === '-'
324
+ ? a - b
325
+ : node.op === '*'
326
+ ? a * b
327
+ : node.op === '/'
328
+ ? a / b
329
+ : a ** b;
330
+ return Number.isFinite(value) ? value : unavailable();
331
+ }
332
+ if (node.name === 'IF' && (node.args.length === 2 || node.args.length === 3)) {
333
+ const condition = scalar(run(node.args[0]));
334
+ if (typeof condition === 'string' && !/^(TRUE|FALSE)$/i.test(condition))
335
+ return unavailable();
336
+ const truthy = typeof condition === 'string' ? condition.toUpperCase() === 'TRUE' : !!condition;
337
+ return truthy ? run(node.args[1]) : node.args[2] ? run(node.args[2]) : false;
338
+ }
339
+ if (node.name === 'ROW' && node.args.length <= 1) {
340
+ if (!node.args.length)
341
+ return row + 1;
342
+ const ref = node.args[0];
343
+ if (ref.kind !== 'ref')
344
+ return unavailable();
345
+ if (ref.sheet)
346
+ resolveSheet(ref.sheet);
347
+ return position(ref.address).row + 1;
348
+ }
349
+ if (node.name === 'ROUND' && node.args.length === 2) {
350
+ const value = numeric(scalar(run(node.args[0])));
351
+ const digits = Math.trunc(numeric(scalar(run(node.args[1]))));
352
+ if (Math.abs(digits) > 100)
353
+ return unavailable();
354
+ const scale = 10 ** digits, magnitude = Math.abs(value) * scale;
355
+ const rounded = Math.floor(magnitude + 0.5 + Number.EPSILON * magnitude) / scale;
356
+ return Number.isFinite(rounded) ? Math.sign(value) * rounded : unavailable();
357
+ }
358
+ if (node.name === 'SUM' && node.args.length > 0) {
359
+ let total = 0;
360
+ for (const arg of node.args) {
361
+ const value = run(arg);
362
+ if (Array.isArray(value)) {
363
+ for (const entry of value)
364
+ if (typeof entry === 'number')
365
+ total += entry;
366
+ }
367
+ else if (arg.kind === 'ref') {
368
+ if (typeof value === 'number')
369
+ total += value;
370
+ }
371
+ else
372
+ total += numeric(value);
373
+ }
374
+ return Number.isFinite(total) ? total : unavailable();
375
+ }
376
+ return unavailable();
377
+ };
378
+ let calculated = 0, unavailableCount = 0;
379
+ for (const { name, cells } of sheets.values())
380
+ for (const [location, cell] of cells) {
381
+ if (!needsValue(cell))
382
+ continue;
383
+ const [row, col] = location.split(':').map(Number);
384
+ try {
385
+ readCell(name, row, col, 0);
386
+ }
387
+ catch {
388
+ }
389
+ }
390
+ for (const { cells } of sheets.values())
391
+ for (const cell of cells.values()) {
392
+ if (!needsValue(cell))
393
+ continue;
394
+ if (results.has(cell)) {
395
+ const value = (_a = results.get(cell)) !== null && _a !== void 0 ? _a : 0;
396
+ cell.v = value;
397
+ cell.t = typeof value === 'boolean' ? 'b' : typeof value === 'string' ? 's' : 'n';
398
+ delete cell.w;
399
+ try {
400
+ cell.w = utils.format_cell(cell);
401
+ }
402
+ catch {
403
+ }
404
+ calculated++;
405
+ }
406
+ else {
407
+ cell.w = `=${cell.f}`;
408
+ unavailableCount++;
409
+ }
410
+ }
411
+ return { calculated, unavailable: unavailableCount };
412
+ }
@@ -3,6 +3,7 @@ import SheetJsModel, { formatCellValue } from './SheetJsModel.js';
3
3
  import { parseSpreadsheetCharts } from './chartParser.js';
4
4
  import { prepareSpreadsheetReadInput, } from './textEncoding.js';
5
5
  import { parseSpreadsheetCellImages } from './richDataParser.js';
6
+ import { recoverUncachedFormulaValues } from './formulaValues.js';
6
7
  const readOptions = {
7
8
  type: 'array',
8
9
  dense: true,
@@ -147,10 +148,49 @@ const EMPTY_RANGE_COLUMN_LIMIT = 256;
147
148
  const RANGE_ROW_SLACK = 256;
148
149
  const RANGE_COLUMN_SLACK = 64;
149
150
  const RANGE_GROWTH_FACTOR = 4;
151
+ const CONTENT_GAP_ROW_MULTIPLIER = 4;
152
+ const CONTENT_GAP_COL_MULTIPLIER = 4;
153
+ const compactSparseExtent = (indices, slack, gapMultiplier, contentExtent) => {
154
+ if (indices.length === 0)
155
+ return 0;
156
+ const sorted = [...new Set(indices)].sort((a, b) => a - b);
157
+ const originThreshold = Math.max(slack * gapMultiplier, RANGE_GROWTH_FACTOR);
158
+ if (!contentExtent && sorted[0] > originThreshold)
159
+ return 0;
160
+ let end = Math.max(sorted[0], contentExtent - 1);
161
+ for (let i = 1; i < sorted.length; i += 1) {
162
+ const current = sorted[i];
163
+ if (current <= end)
164
+ continue;
165
+ const currentExtent = end + 1;
166
+ const gap = current - end;
167
+ const threshold = Math.max(slack * gapMultiplier, currentExtent * RANGE_GROWTH_FACTOR);
168
+ if (gap > threshold)
169
+ break;
170
+ end = current;
171
+ }
172
+ return end + 1;
173
+ };
150
174
  const getCellBounds = (worksheet) => {
151
175
  const bounds = { rowCount: 0, colCount: 0 };
152
176
  if (!worksheet)
153
177
  return bounds;
178
+ const rowIndices = [];
179
+ const colIndices = [];
180
+ let contentRows = 0;
181
+ let contentCols = 0;
182
+ const observe = (row, col, value) => {
183
+ rowIndices.push(row);
184
+ colIndices.push(col);
185
+ const cell = value;
186
+ const meaningful = typeof value !== 'object' || cell.v != null || cell.f != null
187
+ || cell.F != null || !!cell.w || !!cell.r || !!cell.h || !!cell.l
188
+ || (Array.isArray(cell.c) && cell.c.length > 0);
189
+ if (meaningful) {
190
+ contentRows = Math.max(contentRows, row + 1);
191
+ contentCols = Math.max(contentCols, col + 1);
192
+ }
193
+ };
154
194
  const denseRows = Array.isArray(worksheet)
155
195
  ? worksheet
156
196
  : worksheet['!data'];
@@ -164,23 +204,24 @@ const getCellBounds = (worksheet) => {
164
204
  const colIndex = Number(colKey);
165
205
  if (!Number.isInteger(colIndex) || colIndex < 0 || row[colIndex] == null)
166
206
  continue;
167
- bounds.rowCount = Math.max(bounds.rowCount, rowIndex + 1);
168
- bounds.colCount = Math.max(bounds.colCount, colIndex + 1);
207
+ observe(rowIndex, colIndex, row[colIndex]);
169
208
  }
170
209
  }
171
- return bounds;
172
210
  }
173
- for (const key of Object.keys(worksheet)) {
174
- if (key.startsWith('!') || !/^[A-Z]+[1-9][0-9]*$/i.test(key) || worksheet[key] == null)
175
- continue;
176
- try {
177
- const cell = utils.decode_cell(key);
178
- bounds.rowCount = Math.max(bounds.rowCount, cell.r + 1);
179
- bounds.colCount = Math.max(bounds.colCount, cell.c + 1);
180
- }
181
- catch {
211
+ else {
212
+ for (const key of Object.keys(worksheet)) {
213
+ if (key.startsWith('!') || !/^[A-Z]+[1-9][0-9]*$/i.test(key) || worksheet[key] == null)
214
+ continue;
215
+ try {
216
+ const cell = utils.decode_cell(key);
217
+ observe(cell.r, cell.c, worksheet[key]);
218
+ }
219
+ catch {
220
+ }
182
221
  }
183
222
  }
223
+ bounds.rowCount = compactSparseExtent(rowIndices, RANGE_ROW_SLACK, CONTENT_GAP_ROW_MULTIPLIER, contentRows);
224
+ bounds.colCount = compactSparseExtent(colIndices, RANGE_COLUMN_SLACK, CONTENT_GAP_COL_MULTIPLIER, contentCols);
184
225
  return bounds;
185
226
  };
186
227
  const getMergeBounds = (worksheet) => {
@@ -222,8 +263,14 @@ export const getWorksheetDisplayBounds = (worksheet, charts) => {
222
263
  const chartBounds = getChartBounds(charts);
223
264
  const observedRowCount = Math.max(cellBounds.rowCount, mergeBounds.rowCount, drawingBounds.rowCount, chartBounds.rowCount);
224
265
  const observedColCount = Math.max(cellBounds.colCount, mergeBounds.colCount, drawingBounds.colCount, chartBounds.colCount);
225
- const rowCount = reconcileDeclaredRange(declaredRowCount, observedRowCount, RANGE_ROW_SLACK, EMPTY_RANGE_ROW_LIMIT);
226
- const colCount = reconcileDeclaredRange(declaredColCount, observedColCount, RANGE_COLUMN_SLACK, EMPTY_RANGE_COLUMN_LIMIT);
266
+ const reconciledRowCount = reconcileDeclaredRange(declaredRowCount, observedRowCount, RANGE_ROW_SLACK, EMPTY_RANGE_ROW_LIMIT);
267
+ const reconciledColCount = reconcileDeclaredRange(declaredColCount, observedColCount, RANGE_COLUMN_SLACK, EMPTY_RANGE_COLUMN_LIMIT);
268
+ const rowCount = reconciledRowCount;
269
+ const colCount = reconciledColCount;
270
+ const trimmed = (rowCount < declaredRowCount
271
+ || colCount < declaredColCount
272
+ || rowCount < reconciledRowCount
273
+ || colCount < reconciledColCount);
227
274
  return {
228
275
  rowCount,
229
276
  colCount,
@@ -231,7 +278,7 @@ export const getWorksheetDisplayBounds = (worksheet, charts) => {
231
278
  declaredColCount,
232
279
  observedRowCount,
233
280
  observedColCount,
234
- trimmed: rowCount < declaredRowCount || colCount < declaredColCount,
281
+ trimmed,
235
282
  };
236
283
  };
237
284
  const parseSheets = (context, includeEmptySheets = false) => {
@@ -268,6 +315,7 @@ export const parseSpreadsheetWorkbook = async (context, data, source = {}) => {
268
315
  try {
269
316
  const input = prepareSpreadsheetReadInput(data, source);
270
317
  context.workbook = readWorkbookWithMergeRecovery(input);
318
+ recoverUncachedFormulaValues(context.workbook);
271
319
  const signature = data.byteLength >= 2 ? new DataView(data).getUint16(0, false) : 0;
272
320
  if (signature === 0x504b) {
273
321
  const [charts, cellImages] = await Promise.all([