llm-large-files 0.8.0 → 0.8.1

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,651 @@
1
+ import { scanSource } from "./search.js";
2
+ import { composed, foldCase, sliceWhole } from "./text.js";
3
+ /**
4
+ * `aggregate_table`: counts, sums, averages, minimums and maximums over the rows of one table of a
5
+ * document, with filters and groups, exactly, without code and without the model reading the rows.
6
+ * A model that adds up 50,000 rows by reading them needs hundreds of calls and gets it wrong; this
7
+ * reads them once. Every group says the lines of its first rows, so an answer can cite them.
8
+ *
9
+ * The tables it reads:
10
+ * - a CSV or TSV file (format "csv"): the whole file, its first line the header; the separator is
11
+ * found from the first lines (comma, semicolon, tab or "|"), and quoted fields may hold separators,
12
+ * quotes and line breaks;
13
+ * - a sheet of an Excel workbook (format "xlsx"), as the XLSX extractor writes it: `## Sheet 2:
14
+ * name`, `Columns: …`, then `Row 7: | a | b |` lines; its first row is the header unless every
15
+ * value of it is a number, and then the columns are named by their letters;
16
+ * - any run of `| cell | cell |` lines in another document: the tables of DOCX, PPTX, PDF, HTML and
17
+ * Markdown files, numbered in the order of the file. A Markdown separator row (`|---|`) is skipped.
18
+ */
19
+ /** The most groups counted one by one; rows of further groups are counted together. */
20
+ export const MAX_AGGREGATE_GROUPS = 10_000;
21
+ /** The most groups shown in a result. */
22
+ export const MAX_SHOWN_GROUPS = 200;
23
+ /** Distinct values `count_distinct` holds, across all groups: past it, values are no longer told apart. */
24
+ export const MAX_DISTINCT_VALUES = 1_000_000;
25
+ /** Lines of the first rows kept for each group, to cite. */
26
+ const CITED_LINES = 3;
27
+ /** Columns a row may have, at most: past it, the rest are left out. */
28
+ const MAX_COLUMNS = 1_024;
29
+ /** A CSV record may span this many lines, at most (a quoted field with line breaks). */
30
+ const MAX_RECORD_LINES = 1_000;
31
+ /** A value is compared and grouped by its first this many characters. */
32
+ const MAX_VALUE = 500;
33
+ export const AGGREGATE_OPS = ["count", "sum", "avg", "min", "max", "count_distinct"];
34
+ export const FILTER_OPS = ["=", "!=", ">", ">=", "<", "<=", "contains", "not_contains", "starts_with", "empty", "not_empty"];
35
+ /**
36
+ * A number as a person writes it in a table: "1,234.5", "-12", "(1,200)" for a negative, "₪4,750",
37
+ * "$ 12.00", "12%" (12), "1.5e3", "1 234" with a space or a no-break space between thousands.
38
+ * A value with a comma and no dot is taken for thousands when the comma is followed by three digits
39
+ * ("4,750"), and for a decimal comma otherwise ("12,5"). Undefined for anything else.
40
+ */
41
+ export function parseNumber(raw) {
42
+ let text = raw.trim();
43
+ if (!text || text.length > 64)
44
+ return undefined;
45
+ let negative = false;
46
+ if (/^\(.*\)$/.test(text)) {
47
+ negative = true;
48
+ text = text.slice(1, -1).trim();
49
+ }
50
+ // Currency signs and codes, before or after, and a percent sign after.
51
+ text = text.replace(/^[-+]?\s*(?:[$€£¥₪₹]|USD|EUR|GBP|ILS|NIS|ש"ח|ש״ח)\s*/i, (found) => (found.trim().startsWith("-") ? "-" : ""))
52
+ .replace(/\s*(?:[$€£¥₪₹%]|USD|EUR|GBP|ILS|NIS|ש"ח|ש״ח)$/i, "");
53
+ if (text.startsWith("-")) {
54
+ negative = !negative;
55
+ text = text.slice(1).trim();
56
+ }
57
+ else if (text.startsWith("+")) {
58
+ text = text.slice(1).trim();
59
+ }
60
+ text = text.replace(/[\s  ']/g, "");
61
+ if (/^\d{1,3}(?:,\d{3})+(?:\.\d+)?$/.test(text))
62
+ text = text.replace(/,/g, "");
63
+ else if (/^\d{1,3}(?:\.\d{3})+,\d+$/.test(text))
64
+ text = text.replace(/\./g, "").replace(",", ".");
65
+ else if (/^\d+,\d+$/.test(text))
66
+ text = text.replace(",", ".");
67
+ if (!/^(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?$/i.test(text))
68
+ return undefined;
69
+ const value = Number(text);
70
+ return Number.isFinite(value) ? (negative ? -value : value) : undefined;
71
+ }
72
+ /** A value as it is compared and grouped: composed, case folded, white space collapsed, cut long. */
73
+ const valueKey = (value) => sliceWhole(foldCase(composed(value.replace(/\s+/g, " ").trim())), MAX_VALUE);
74
+ /** An ISO date at the start of a value: what `Date:month` and comparisons of dates read. */
75
+ const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})/;
76
+ /** Splits a `| a | b |` row into its cells, honouring `\|` inside a cell. */
77
+ export function pipeCells(line) {
78
+ const body = line.trim().replace(/^\|/, "").replace(/\|$/, "");
79
+ const cells = [];
80
+ let current = "";
81
+ for (let at = 0; at < body.length; at++) {
82
+ const character = body[at];
83
+ if (character === "\\" && body[at + 1] === "|") {
84
+ current += "|";
85
+ at++;
86
+ }
87
+ else if (character === "|") {
88
+ cells.push(current.trim());
89
+ current = "";
90
+ if (cells.length >= MAX_COLUMNS)
91
+ return cells;
92
+ }
93
+ else {
94
+ current += character;
95
+ }
96
+ }
97
+ cells.push(current.trim());
98
+ return cells;
99
+ }
100
+ /** A Markdown separator row: `| --- | :---: |`. */
101
+ const SEPARATOR_ROW = /^\|(?:\s*:?-{3,}:?\s*\|)+\s*$/;
102
+ /** The separator of a CSV file, from its first lines: the one found the same number of times (above 0) on most of them. */
103
+ export function csvSeparator(lines) {
104
+ let best = ",";
105
+ let bestScore = -1;
106
+ for (const separator of [",", ";", "\t", "|"]) {
107
+ const counts = lines.map((line) => splitCsvLine(line, separator).fields.length - 1).filter((count) => count > 0);
108
+ if (counts.length === 0)
109
+ continue;
110
+ const common = mode(counts);
111
+ const score = counts.filter((count) => count === common).length * 1_000 + common;
112
+ if (score > bestScore) {
113
+ best = separator;
114
+ bestScore = score;
115
+ }
116
+ }
117
+ return best;
118
+ }
119
+ function mode(values) {
120
+ const counts = new Map();
121
+ let best = values[0];
122
+ for (const value of values) {
123
+ const count = (counts.get(value) ?? 0) + 1;
124
+ counts.set(value, count);
125
+ if (count > (counts.get(best) ?? 0))
126
+ best = value;
127
+ }
128
+ return best;
129
+ }
130
+ /**
131
+ * The fields of a CSV line. `open`: the line ends inside a quoted field, which goes on on the next
132
+ * line; `carry` is the field so far, to be joined with it.
133
+ */
134
+ function splitCsvLine(line, separator, carry) {
135
+ const fields = carry ? [...carry.fields] : [];
136
+ let field = carry ? `${carry.field}\n` : "";
137
+ let quoted = carry !== undefined;
138
+ for (let at = 0; at < line.length; at++) {
139
+ const character = line[at];
140
+ if (quoted) {
141
+ if (character === "\"") {
142
+ if (line[at + 1] === "\"") {
143
+ field += "\"";
144
+ at++;
145
+ }
146
+ else {
147
+ quoted = false;
148
+ }
149
+ }
150
+ else {
151
+ field += character;
152
+ }
153
+ }
154
+ else if (character === "\"" && field.trim() === "") {
155
+ quoted = true;
156
+ field = "";
157
+ }
158
+ else if (character === separator) {
159
+ fields.push(field.trim());
160
+ field = "";
161
+ if (fields.length >= MAX_COLUMNS)
162
+ return { fields, open: false, field: "" };
163
+ }
164
+ else {
165
+ field += character;
166
+ }
167
+ }
168
+ if (quoted)
169
+ return { fields, open: true, field };
170
+ fields.push(field.trim());
171
+ return { fields, open: false, field: "" };
172
+ }
173
+ /** Finds a column by its header name (ignoring case and spaces), its letter ("C"), or its number ("3"). */
174
+ function columnOf(header, given, letters) {
175
+ let name = given.trim();
176
+ let datePart;
177
+ const part = /:(year|month|day)$/i.exec(name);
178
+ if (part) {
179
+ datePart = part[1].toLowerCase();
180
+ name = name.slice(0, part.index).trim();
181
+ }
182
+ const wanted = valueKey(name);
183
+ let index = header.findIndex((column) => valueKey(column) === wanted);
184
+ // A header of two rows joins its names ("Q2 / מאי"): the lower name alone finds the column when only one has it.
185
+ if (index === -1) {
186
+ const lower = header.flatMap((column, at) => (valueKey(column.split(" / ").at(-1) ?? "") === wanted ? [at] : []));
187
+ if (lower.length === 1)
188
+ index = lower[0];
189
+ else if (lower.length > 1) {
190
+ throw new Error(`${JSON.stringify(sliceWhole(name, 80))} names ${lower.length} columns of this table: ${lower.map((at) => JSON.stringify(header[at])).join(", ")}. Name one of them in full.`);
191
+ }
192
+ }
193
+ if (index === -1 && letters && /^[A-Z]{1,3}$/i.test(name)) {
194
+ let number = 0;
195
+ for (const letter of name.toUpperCase())
196
+ number = number * 26 + letter.charCodeAt(0) - 64;
197
+ if (number <= header.length)
198
+ index = number - 1;
199
+ }
200
+ if (index === -1 && /^\d+$/.test(name) && Number(name) >= 1 && Number(name) <= header.length)
201
+ index = Number(name) - 1;
202
+ if (index === -1) {
203
+ const listed = header.slice(0, 40).map((column) => JSON.stringify(column)).join(", ");
204
+ throw new Error(`No column ${JSON.stringify(sliceWhole(name, 80))} in this table. Its columns are: ${listed}${header.length > 40 ? ", …" : ""}.`);
205
+ }
206
+ return { index, name: header[index], ...(datePart ? { datePart } : {}) };
207
+ }
208
+ /** The value of a cell for comparing: a number when it is one, a date as written, or folded text. */
209
+ function compare(cell, filter) {
210
+ const key = valueKey(cell);
211
+ switch (filter.op) {
212
+ case "empty": return key === "";
213
+ case "not_empty": return key !== "";
214
+ case "contains": return key.includes(filter.key);
215
+ case "not_contains": return !key.includes(filter.key);
216
+ case "starts_with": return key.startsWith(filter.key);
217
+ }
218
+ const number = parseNumber(cell);
219
+ // A cell that is not a number is neither more nor less than a number: "n/a" is not >= 900.
220
+ if (filter.number !== undefined && number === undefined && filter.op !== "=" && filter.op !== "!=")
221
+ return false;
222
+ // Two numbers compare as numbers; two ISO dates, and anything else, as text.
223
+ const order = number !== undefined && filter.number !== undefined
224
+ ? Math.sign(number - filter.number)
225
+ : key === filter.key ? 0 : key < filter.key ? -1 : 1;
226
+ switch (filter.op) {
227
+ case "=": return order === 0;
228
+ case "!=": return order !== 0;
229
+ case ">": return order > 0;
230
+ case ">=": return order >= 0;
231
+ case "<": return order < 0;
232
+ case "<=": return order <= 0;
233
+ }
234
+ return false;
235
+ }
236
+ /** A number of a result, without the noise of binary fractions: 0.1 + 0.2 is 0.3. */
237
+ const tidy = (value) => Number(value.toPrecision(15));
238
+ /**
239
+ * Reads the rows of one table and aggregates them. Throws an error the model can act on: no table,
240
+ * a table that does not exist, an unknown column or operation.
241
+ */
242
+ export async function aggregateTable(source, request, signal) {
243
+ const format = source.meta.format;
244
+ const kind = format === "csv" ? "csv" : format === "xlsx" ? "sheets" : "pipes";
245
+ const wantedTable = request.table;
246
+ const metricsGiven = request.metrics && request.metrics.length > 0 ? request.metrics : ["count"];
247
+ const limit = Math.min(MAX_SHOWN_GROUPS, Math.max(1, Math.trunc(request.limit ?? 50)));
248
+ if ((request.groupBy?.length ?? 0) > 3)
249
+ throw new Error("group_by takes at most 3 columns.");
250
+ // The table being read: its number, its title, its header, and what the request resolved against it.
251
+ let tableNumber = 0;
252
+ let tableTitle = "";
253
+ let chosenTitle = "";
254
+ let chosen = false;
255
+ /** Pipe tables: whether the lines read are rows of a table (a new table starts after other lines). */
256
+ let inPipeTable = false;
257
+ let header;
258
+ let headerLine = 0;
259
+ let letters = false;
260
+ let filters = [];
261
+ let groupColumns = [];
262
+ let metrics = [];
263
+ const groups = new Map();
264
+ let rowsRead = 0;
265
+ let rowsMatched = 0;
266
+ let otherRows = 0;
267
+ // The first rows of the chosen table, held until its header is known.
268
+ const pending = [];
269
+ let headerCount = 0;
270
+ let title;
271
+ let lastHeaderKey;
272
+ let repeatedHeaders = 0;
273
+ let irregularRows = 0;
274
+ let distinctValues = 0;
275
+ let distinctCapped = false;
276
+ let notNumbers = [];
277
+ // CSV: the separator, the first lines read to find it, and a record that spans lines.
278
+ let separator;
279
+ const firstLines = [];
280
+ let open;
281
+ const isWanted = (number, title) => {
282
+ if (wantedTable === undefined || wantedTable === "")
283
+ return number === 1;
284
+ const given = String(wantedTable).trim();
285
+ if (/^\d+$/.test(given))
286
+ return Number(given) === number;
287
+ const name = valueKey(given.replace(/^sheet\s*\d*\s*:?\s*/i, ""));
288
+ return valueKey(title) === name || valueKey(title).includes(name) && name.length >= 3;
289
+ };
290
+ const resolve = (row) => {
291
+ header = row.map((cell, index) => cell || (letters ? columnLetter(index + 1) : `Column ${index + 1}`));
292
+ const columns = header;
293
+ filters = (request.filters ?? []).map((filter) => {
294
+ if (!FILTER_OPS.includes(filter.op))
295
+ throw new Error(`A filter's op must be one of ${FILTER_OPS.map((op) => `"${op}"`).join(", ")}.`);
296
+ const value = filter.value === undefined || filter.value === null ? "" : String(filter.value);
297
+ if (value === "" && filter.op !== "empty" && filter.op !== "not_empty" && filter.op !== "=" && filter.op !== "!=")
298
+ throw new Error(`The filter on ${JSON.stringify(filter.column)} needs a value.`);
299
+ return { column: columnOf(columns, String(filter.column ?? ""), letters), op: filter.op, value, number: parseNumber(value), key: valueKey(value) };
300
+ });
301
+ groupColumns = (request.groupBy ?? []).map((name) => columnOf(columns, String(name), letters));
302
+ metrics = metricsGiven.map((given) => {
303
+ const text = String(given).trim();
304
+ const [rawOp, ...rest] = text.split(":");
305
+ const op = (rawOp ?? "").trim().toLowerCase();
306
+ if (!AGGREGATE_OPS.includes(op))
307
+ throw new Error(`A metric must be "count", or one of ${AGGREGATE_OPS.filter((name) => name !== "count").map((name) => `"${name}:<column>"`).join(", ")}.`);
308
+ const columnName = rest.join(":").trim();
309
+ if (op === "count")
310
+ return { name: "count", op };
311
+ if (!columnName)
312
+ throw new Error(`The metric "${op}" needs a column: "${op}:<column>".`);
313
+ const column = columnOf(columns, columnName, letters);
314
+ return { name: `${op}:${column.name}`, op, column };
315
+ });
316
+ notNumbers = metrics.map(() => 0);
317
+ };
318
+ const groupValue = (cell, column) => {
319
+ if (!column.datePart)
320
+ return cell;
321
+ const date = ISO_DATE.exec(cell.trim());
322
+ if (!date)
323
+ return cell;
324
+ return column.datePart === "year" ? date[1] : column.datePart === "month" ? `${date[1]}-${date[2]}` : `${date[1]}-${date[2]}-${date[3]}`;
325
+ };
326
+ /** Whether a row holds a value that is a number: a row of data. A year (1900-2100) in a header row is a name, not data. */
327
+ const hasNumber = (row, first) => row.some((cell) => {
328
+ const number = parseNumber(cell);
329
+ return number !== undefined && !(first && Number.isInteger(number) && number >= 1900 && number <= 2100 && /^\d{4}$/.test(cell.trim()));
330
+ });
331
+ const filled = (row) => row.filter((cell) => cell.trim() !== "").length;
332
+ /**
333
+ * Decides the header from the first rows of the table, and reads the rest as data:
334
+ * - a first row with one value over a table of more (a title, "Sales 2026") is left out;
335
+ * - a CSV file has one header row;
336
+ * - a sheet or a `| cell |` table has as header the rows above its first row with a number, up
337
+ * to 3 (a header of two rows: "Q1" over "January | February"); a first row with numbers means
338
+ * no header. The header rows are joined column by column with " / ", a header cell left empty
339
+ * by a merged cell taking the one to its left.
340
+ * `header_rows` says how many rows the header has, below a title row if there is one.
341
+ */
342
+ const decideHeader = () => {
343
+ let start = 0;
344
+ if (pending.length > 1 && filled(pending[0].row) === 1 && filled(pending[1].row) > 1) {
345
+ title = pending[0].row.find((cell) => cell.trim() !== "").trim();
346
+ start = 1;
347
+ }
348
+ if (request.headerRows !== undefined) {
349
+ headerCount = Math.min(5, Math.max(0, Math.trunc(request.headerRows)));
350
+ }
351
+ else if (kind === "csv") {
352
+ headerCount = 1;
353
+ }
354
+ else {
355
+ const firstData = pending.findIndex((entry, index) => index >= start && hasNumber(entry.row, index === start));
356
+ headerCount = firstData === -1 ? 1 : Math.min(3, firstData - start);
357
+ }
358
+ headerCount = Math.min(headerCount, pending.length - start);
359
+ const rows = pending.slice(start, start + headerCount).map((entry) => entry.row);
360
+ if (rows.length === 0) {
361
+ letters = kind === "sheets";
362
+ resolve((pending[start]?.row ?? []).map(() => ""));
363
+ }
364
+ else {
365
+ const width = Math.max(...rows.map((row) => row.length));
366
+ const upper = rows.slice(0, -1).map((row) => {
367
+ let left = "";
368
+ return Array.from({ length: width }, (_, index) => {
369
+ const cell = (row[index] ?? "").trim();
370
+ if (cell)
371
+ left = cell;
372
+ return cell || left;
373
+ });
374
+ });
375
+ const names = Array.from({ length: width }, (_, index) => {
376
+ const parts = [...upper.map((row) => row[index]), (rows.at(-1)[index] ?? "").trim()].filter(Boolean);
377
+ return [...new Set(parts)].join(" / ");
378
+ });
379
+ headerLine = pending[start + headerCount - 1].line;
380
+ lastHeaderKey = rows.at(-1).map(valueKey).join("\u0000");
381
+ resolve(names);
382
+ }
383
+ const rest = pending.splice(0).slice(start + headerCount);
384
+ for (const entry of rest)
385
+ addRow(entry.row, entry.line);
386
+ };
387
+ const addRow = (row, line) => {
388
+ if (!header) {
389
+ pending.push({ row, line });
390
+ // The header is known once a row of data is seen, or enough rows are held to say there is none.
391
+ // A title row is told by the row after it, so at least two rows are held, also when header_rows is given.
392
+ if ((kind !== "csv" && hasNumber(row, pending.length === 1)) || kind === "csv" || pending.length >= 20) {
393
+ if (pending.length < 2 && (kind === "csv" || request.headerRows !== undefined))
394
+ return;
395
+ decideHeader();
396
+ }
397
+ return;
398
+ }
399
+ // A header repeated inside the table (on each page of a PDF) is not a row.
400
+ if (lastHeaderKey !== undefined && row.map(valueKey).join("\u0000") === lastHeaderKey) {
401
+ repeatedHeaders++;
402
+ return;
403
+ }
404
+ // A value past the header's columns, or a CSV record of another length: the table is not as its header says.
405
+ if (row.slice(header.length).some((cell) => cell !== "") || (kind === "csv" && row.length !== header.length))
406
+ irregularRows++;
407
+ rowsRead++;
408
+ const cell = (column) => row[column.index] ?? "";
409
+ for (const filter of filters)
410
+ if (!compare(cell(filter.column), filter))
411
+ return;
412
+ rowsMatched++;
413
+ const values = groupColumns.map((column) => groupValue(cell(column), column));
414
+ const key = values.map(valueKey).join("\u0000");
415
+ let group = groups.get(key);
416
+ if (!group) {
417
+ if (groups.size >= MAX_AGGREGATE_GROUPS) {
418
+ otherRows++;
419
+ return;
420
+ }
421
+ group = {
422
+ key: Object.fromEntries(groupColumns.map((column, index) => [column.datePart ? `${column.name}:${column.datePart}` : column.name, values[index]])),
423
+ count: 0,
424
+ sums: metrics.map(() => 0),
425
+ numbers: metrics.map(() => 0),
426
+ minimums: metrics.map(() => undefined),
427
+ maximums: metrics.map(() => undefined),
428
+ distinct: metrics.map((metric) => (metric.op === "count_distinct" ? new Set() : undefined)),
429
+ lines: [],
430
+ };
431
+ groups.set(key, group);
432
+ }
433
+ group.count++;
434
+ if (group.lines.length < CITED_LINES)
435
+ group.lines.push(line);
436
+ metrics.forEach((metric, index) => {
437
+ if (!metric.column)
438
+ return;
439
+ const raw = cell(metric.column);
440
+ if (metric.op === "count_distinct") {
441
+ const distinct = group.distinct[index];
442
+ if (!raw.trim())
443
+ return;
444
+ const value = valueKey(raw);
445
+ if (distinct.has(value))
446
+ return;
447
+ // Bounded across every group: 10,000 groups of 10,000 values each would be 100 million strings.
448
+ if (distinctValues >= MAX_DISTINCT_VALUES) {
449
+ distinctCapped = true;
450
+ return;
451
+ }
452
+ distinct.add(value);
453
+ distinctValues++;
454
+ return;
455
+ }
456
+ if (!raw.trim())
457
+ return;
458
+ const number = parseNumber(raw);
459
+ if (number === undefined) {
460
+ // min and max of dates (or of any text) compare as text; sums and averages need numbers.
461
+ if ((metric.op === "min" || metric.op === "max") && ISO_DATE.test(raw.trim())) {
462
+ const current = metric.op === "min" ? group.minimums[index] : group.maximums[index];
463
+ const text = raw.trim();
464
+ if (current === undefined || (typeof current === "string" && (metric.op === "min" ? text < current : text > current))) {
465
+ if (metric.op === "min")
466
+ group.minimums[index] = text;
467
+ else
468
+ group.maximums[index] = text;
469
+ }
470
+ return;
471
+ }
472
+ notNumbers[index]++;
473
+ return;
474
+ }
475
+ group.sums[index] += number;
476
+ group.numbers[index]++;
477
+ const minimum = group.minimums[index];
478
+ const maximum = group.maximums[index];
479
+ if (minimum === undefined || (typeof minimum === "number" && number < minimum))
480
+ group.minimums[index] = number;
481
+ if (maximum === undefined || (typeof maximum === "number" && number > maximum))
482
+ group.maximums[index] = number;
483
+ });
484
+ };
485
+ // Every table is gone through, to count them; only the one asked for is read.
486
+ const pipeLine = (text, line) => {
487
+ const trimmed = text.trim();
488
+ const isRow = trimmed.startsWith("|") && trimmed.endsWith("|") && trimmed.length > 1;
489
+ if (!isRow) {
490
+ inPipeTable = false;
491
+ chosen = false;
492
+ return;
493
+ }
494
+ if (!inPipeTable) {
495
+ inPipeTable = true;
496
+ tableNumber++;
497
+ chosen = !header && isWanted(tableNumber, `table ${tableNumber}`);
498
+ if (chosen)
499
+ chosenTitle = `table ${tableNumber}`;
500
+ }
501
+ if (!chosen || SEPARATOR_ROW.test(trimmed))
502
+ return;
503
+ addRow(pipeCells(trimmed), line);
504
+ };
505
+ const sheetLine = (text, line) => {
506
+ const sheet = /^## Sheet (\d+): (.*?)(?: \(hidden sheet\))?$/.exec(text);
507
+ if (sheet) {
508
+ tableNumber = Number(sheet[1]);
509
+ tableTitle = `Sheet ${tableNumber}: ${sheet[2]}`;
510
+ chosen = !header && isWanted(tableNumber, sheet[2]);
511
+ if (chosen)
512
+ chosenTitle = tableTitle;
513
+ return;
514
+ }
515
+ if (!chosen)
516
+ return;
517
+ const row = /^Row (\d+): (\|.*\|)\s*$/.exec(text);
518
+ if (row)
519
+ addRow(pipeCells(row[2]), line);
520
+ };
521
+ const csvLine = (text, line) => {
522
+ if (separator === undefined) {
523
+ if (text.trim())
524
+ firstLines.push({ line, text });
525
+ if (firstLines.length < 20)
526
+ return;
527
+ startCsv();
528
+ return;
529
+ }
530
+ readCsv(text, line);
531
+ };
532
+ const startCsv = () => {
533
+ separator = csvSeparator(firstLines.map((entry) => entry.text));
534
+ tableNumber = 1;
535
+ chosenTitle = "the CSV file";
536
+ chosen = true;
537
+ for (const entry of firstLines.splice(0))
538
+ readCsv(entry.text, entry.line);
539
+ };
540
+ const readCsv = (text, line) => {
541
+ if (open) {
542
+ const split = splitCsvLine(text, separator, open);
543
+ if (split.open && open.lines < MAX_RECORD_LINES) {
544
+ open = { fields: split.fields, field: split.field, line: open.line, lines: open.lines + 1 };
545
+ return;
546
+ }
547
+ const started = open.line;
548
+ open = undefined;
549
+ addRow(split.fields, started);
550
+ return;
551
+ }
552
+ if (!text.trim())
553
+ return;
554
+ const split = splitCsvLine(text, separator);
555
+ if (split.open) {
556
+ open = { fields: split.fields, field: split.field, line, lines: 1 };
557
+ return;
558
+ }
559
+ addRow(split.fields, line);
560
+ };
561
+ const feedLine = kind === "csv" ? csvLine : kind === "sheets" ? sheetLine : pipeLine;
562
+ await scanSource(source, (chunk) => {
563
+ const count = chunk.lines.lineCount;
564
+ for (let local = 1; local <= count; local++)
565
+ feedLine(chunk.lines.line(local), chunk.firstLine + local - 1);
566
+ }, signal);
567
+ if (kind === "csv" && separator === undefined && firstLines.length > 0)
568
+ startCsv();
569
+ if (kind === "csv" && open) {
570
+ const started = open.line;
571
+ const fields = [...open.fields, open.field];
572
+ open = undefined;
573
+ addRow(fields, started);
574
+ }
575
+ // A table that ended before its header was decided (no row of data, fewer than 20 rows).
576
+ if (!header && pending.length > 0)
577
+ decideHeader();
578
+ if (!header) {
579
+ if (tableNumber === 0)
580
+ throw new Error("This file has no table to aggregate: aggregate_table reads CSV and TSV files, Excel sheets, and tables written as | cell | cell | rows. Use search_document instead.");
581
+ throw new Error(wantedTable !== undefined
582
+ ? `No table ${JSON.stringify(String(wantedTable))} in this file: it has ${tableNumber} ${kind === "sheets" ? (tableNumber === 1 ? "sheet" : "sheets") : tableNumber === 1 ? "table" : "tables"}. Name a sheet or give a number from 1 to ${tableNumber}.`
583
+ : "The table is empty.");
584
+ }
585
+ const results = [...groups.values()].map((group) => ({
586
+ key: group.key,
587
+ count: group.count,
588
+ values: Object.fromEntries(metrics.map((metric, index) => {
589
+ if (metric.op === "count")
590
+ return [metric.name, group.count];
591
+ if (metric.op === "count_distinct")
592
+ return [metric.name, group.distinct[index].size];
593
+ if (metric.op === "sum")
594
+ return [metric.name, group.numbers[index] > 0 ? tidy(group.sums[index]) : null];
595
+ if (metric.op === "avg")
596
+ return [metric.name, group.numbers[index] > 0 ? tidy(group.sums[index] / group.numbers[index]) : null];
597
+ const extreme = metric.op === "min" ? group.minimums[index] : group.maximums[index];
598
+ return [metric.name, extreme === undefined ? null : typeof extreme === "number" ? tidy(extreme) : extreme];
599
+ })),
600
+ lines: group.lines,
601
+ }));
602
+ const first = metrics[0];
603
+ const valueOf = (group) => {
604
+ const value = group.values[first.name];
605
+ return typeof value === "number" ? value : Number.NEGATIVE_INFINITY;
606
+ };
607
+ if (request.orderBy === "key") {
608
+ results.sort((left, right) => compareKeys(Object.values(left.key), Object.values(right.key)));
609
+ }
610
+ else {
611
+ results.sort((left, right) => valueOf(right) - valueOf(left) || (left.lines[0] ?? 0) - (right.lines[0] ?? 0));
612
+ }
613
+ return {
614
+ table: kind === "pipes" ? `${chosenTitle} of ${tableNumber}` : chosenTitle,
615
+ tables: tableNumber,
616
+ columns: header,
617
+ headerLine,
618
+ rowsRead,
619
+ rowsMatched,
620
+ groups: results.slice(0, limit),
621
+ totalGroups: groups.size,
622
+ otherRows,
623
+ headerRows: headerCount,
624
+ ...(title !== undefined ? { title } : {}),
625
+ repeatedHeaders,
626
+ irregularRows,
627
+ distinctCapped,
628
+ notNumbers: Object.fromEntries(metrics.flatMap((metric, index) => (notNumbers[index] > 0 && (metric.op === "sum" || metric.op === "avg" || metric.op === "min" || metric.op === "max") ? [[metric.name, notNumbers[index]]] : []))),
629
+ };
630
+ }
631
+ /** Group keys in order: numbers as numbers, the rest as text. */
632
+ function compareKeys(left, right) {
633
+ for (let index = 0; index < Math.max(left.length, right.length); index++) {
634
+ const a = left[index] ?? "";
635
+ const b = right[index] ?? "";
636
+ const x = parseNumber(a);
637
+ const y = parseNumber(b);
638
+ const order = x !== undefined && y !== undefined ? x - y : valueKey(a) < valueKey(b) ? -1 : valueKey(a) > valueKey(b) ? 1 : 0;
639
+ if (order !== 0)
640
+ return order;
641
+ }
642
+ return 0;
643
+ }
644
+ /** The letters of a column number: 1 is A, 27 is AA. */
645
+ function columnLetter(column) {
646
+ let name = "";
647
+ for (let rest = column; rest > 0; rest = Math.floor((rest - 1) / 26))
648
+ name = String.fromCharCode(65 + ((rest - 1) % 26)) + name;
649
+ return name;
650
+ }
651
+ //# sourceMappingURL=aggregate.js.map