llm-large-files 0.5.0 → 0.8.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.
Files changed (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
package/src/xlsx.ts ADDED
@@ -0,0 +1,478 @@
1
+ import { officeReader, openOffice, type OfficeParts } from "./office.js";
2
+ import { sliceWhole } from "./text.js";
3
+ import type { Extractor } from "./types.js";
4
+ import { readRelationships, readXml, XmlStream, type XmlAttributes } from "./xml-stream.js";
5
+
6
+ /**
7
+ * Excel workbooks (XLSX, XLSM). Each sheet, in the order of the workbook, is a section:
8
+ *
9
+ * ## Sheet 1: Sales
10
+ * Columns: | A | B | C |
11
+ * Row 1: | Region | Q1 | Q2 |
12
+ * Row 2: | East | 1200 | 1350.5 |
13
+ *
14
+ * A row is written with its number in the sheet, so an answer can name the row a person finds in
15
+ * Excel, and as `| cell | cell |`, its empty cells kept up to its last value, as tables of other
16
+ * files are. A cell holds the value Excel last computed for it (a formula without one is written
17
+ * as `=` and the formula); a date as 2026-11-10 (with the time when it has one), an elapsed time
18
+ * as its hours in total (36:00), a percentage as 12.5%, a number as Excel stores it, to 15
19
+ * significant digits. Empty rows are left out. Nothing is cut short: every row of every sheet is
20
+ * written, within the limits on text that every file has.
21
+ */
22
+
23
+ /** The shared strings of a workbook, at most: Excel's rows (1,048,576) times two. */
24
+ const MAX_SHARED_STRINGS = 2_097_152;
25
+ /** Columns of a sheet listed in its `Columns:` line, at most: past it, the line gives the range. */
26
+ const MAX_LISTED_COLUMNS = 52;
27
+ /** A sheet's name is kept up to this many characters. */
28
+ const MAX_SHEET_NAME = 100;
29
+ /** The longest part name looked up: no part of a workbook has a name near it. */
30
+ const MAX_PART_NAME = 1_024;
31
+ /** Excel's last date, 9999-12-31, as a serial. */
32
+ const LAST_SERIAL = 2_958_465.99999;
33
+ /** Excel's last column, XFD. */
34
+ const MAX_COLUMN = 16_384;
35
+ /** Written under the heading of a sheet with no value. */
36
+ const NO_VALUES = "[No values on this sheet]";
37
+
38
+ /** Number formats Excel has built in that show a date, a time, or both. */
39
+ const BUILT_IN_DATES = new Set([14, 15, 16, 17, 22, 27, 28, 29, 30, 31, 34, 35, 36, 50, 51, 52, 53, 54, 57, 58]);
40
+ const BUILT_IN_TIMES = new Set([18, 19, 20, 21, 32, 33, 45, 47, 55, 56]);
41
+ /** Built-in format 46 is `[h]:mm:ss`: the hours elapsed, past 24. */
42
+ const BUILT_IN_DURATIONS = new Set([46]);
43
+ const BUILT_IN_PERCENT = new Set([9, 10]);
44
+
45
+ type ValueKind = "date" | "time" | "duration" | "percent" | "number";
46
+
47
+ /** What a number format shows, from its code: a date, a time of day, an elapsed time, a percentage, or a number. */
48
+ export function formatKind(code: string): ValueKind {
49
+ // Quoted text, escaped characters, colours and locales ([Red], [$-409]) hold no date part; the
50
+ // brackets of elapsed time ([h], [mm], [ss]) are kept. A format of Excel has at most 255
51
+ // characters; a bracket body stops at the next bracket, so an unclosed "[" costs no scan to the
52
+ // end of the code.
53
+ const bare = code.slice(0, 255).replace(/"[^"]*"/g, "").replace(/\\./g, "").replace(/\[(?!(?:h+|m+|s+)\])[^[\]]*\]/gi, "").toLowerCase();
54
+ if (bare === "general" || bare === "") return "number";
55
+ // Hours, minutes or seconds in total, which go on past a day: 1.5 is 36 hours, not a date.
56
+ if (/\[(?:h+|m+|s+)\]/.test(bare)) return "duration";
57
+ if (/[yd]/.test(bare) || /(^|[^a-z])m{3,}/.test(bare)) return "date";
58
+ if (/[hs]/.test(bare)) return "time";
59
+ if (bare.includes("%")) return "percent";
60
+ return "number";
61
+ }
62
+
63
+ /** The letters of a column number: 1 is A, 27 is AA. */
64
+ export function columnName(column: number): string {
65
+ let name = "";
66
+ for (let rest = column; rest > 0; rest = Math.floor((rest - 1) / 26)) name = String.fromCharCode(65 + ((rest - 1) % 26)) + name;
67
+ return name;
68
+ }
69
+
70
+ /** The column and row of a cell reference ("AB12"), or undefined. */
71
+ function cellAt(reference: string | undefined): { column: number; row: number } | undefined {
72
+ const match = /^\$?([A-Z]{1,3})\$?(\d+)$/i.exec(reference ?? "");
73
+ if (!match) return undefined;
74
+ let column = 0;
75
+ for (const letter of match[1]!.toUpperCase()) column = column * 26 + letter.charCodeAt(0) - 64;
76
+ return { column, row: Number(match[2]) };
77
+ }
78
+
79
+ const pad = (value: number) => String(value).padStart(2, "0");
80
+
81
+ /**
82
+ * An Excel date serial as text. In the 1900 date system Excel counts 29 February 1900, which did
83
+ * not exist, so serials from 61 on are one day off a plain count from 30 December 1899. In the
84
+ * 1904 system (`date1904`) days count from 1 January 1904.
85
+ */
86
+ export function excelDate(serial: number, kind: "date" | "time", date1904 = false): string {
87
+ // Rounded to the second first, then split into days and seconds: 23:59:59.6 is the next day's 00:00.
88
+ const total = Math.round(serial * 86_400);
89
+ const whole = Math.floor(total / 86_400);
90
+ const seconds = total - whole * 86_400;
91
+ const time = `${pad(Math.floor(seconds / 3600))}:${pad(Math.floor(seconds / 60) % 60)}${seconds % 60 !== 0 ? `:${pad(seconds % 60)}` : ""}`;
92
+ // A time of day alone, as a format that shows no date writes it: 23:59:59.7 rounds to 00:00. So
93
+ // is what float arithmetic leaves of a difference of equal times (-1.1e-16): it rounds to day 0.
94
+ if (kind === "time" && (whole === 0 || Math.floor(serial) === 0)) return whole === 0 ? time : "00:00";
95
+ const base = date1904 ? Date.UTC(1904, 0, 1) : Date.UTC(1899, 11, whole >= 61 ? 30 : 31);
96
+ const date = new Date(base + whole * 86_400_000);
97
+ if (Number.isNaN(date.getTime())) return String(serial);
98
+ const day = `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
99
+ return seconds === 0 && kind === "date" ? day : `${day} ${time}`;
100
+ }
101
+
102
+ /**
103
+ * An elapsed time, as a format of `[h]`, `[m]` or `[s]` shows it: its hours in total, and no date,
104
+ * so 1.5 days is 36:00. As a time of day, it is rounded to the second, and its seconds are written
105
+ * when there are some.
106
+ */
107
+ function excelDuration(serial: number): string {
108
+ // Past Excel's last day (9999-12-31) a duration is a number Excel cannot show: written as it is.
109
+ if (!Number.isFinite(serial) || Math.abs(serial) > LAST_SERIAL) return numberText(serial);
110
+ const total = Math.round(Math.abs(serial) * 86_400);
111
+ const seconds = total % 60;
112
+ return `${serial < 0 && total > 0 ? "-" : ""}${Math.floor(total / 3600)}:${pad(Math.floor(total / 60) % 60)}${seconds !== 0 ? `:${pad(seconds)}` : ""}`;
113
+ }
114
+
115
+ /**
116
+ * Excel writes a character that XML cannot hold as `_xHHHH_`: a carriage return of pasted text is
117
+ * `_x000D_`. An underscore that would start such an escape is written `_x005F_`, so the text
118
+ * `_x0041_` is `_x005F_x0041_`; read from left to right, each comes back as it was.
119
+ */
120
+ function decodeEscapes(text: string): string {
121
+ let at = text.indexOf("_x");
122
+ if (at === -1) return text;
123
+ // One pass with indexOf and slices: a replace with a callback kept a string and its parts for
124
+ // each of millions of escapes, and a 405 KB workbook took 890 MB.
125
+ const pieces: string[] = [];
126
+ let kept = 0;
127
+ for (; at !== -1; at = text.indexOf("_x", at + 1)) {
128
+ if (at < kept || text.charCodeAt(at + 6) !== 95 || !HEX4.test(text.slice(at + 2, at + 6))) continue;
129
+ pieces.push(text.slice(kept, at), String.fromCharCode(Number.parseInt(text.slice(at + 2, at + 6), 16)));
130
+ kept = at + 7;
131
+ at = kept - 1;
132
+ }
133
+ if (pieces.length === 0) return text;
134
+ pieces.push(text.slice(kept));
135
+ return pieces.join("");
136
+ }
137
+
138
+ const HEX4 = /^[0-9A-Fa-f]{4}$/;
139
+
140
+ /**
141
+ * The text of a cell as a cell of a `| cell | cell |` row: on one line, its pipes escaped, as the
142
+ * tables of other files are written. Only white space that changes is matched (a run of it, a tab,
143
+ * a line break): the single spaces between words, most of a text, are not each replaced.
144
+ */
145
+ function cellText(text: string): string {
146
+ return text.replace(/\s{2,}|[^\S ]/g, " ").replace(/\|/g, "\\|").trim();
147
+ }
148
+
149
+ /** A number as Excel stores it, to the 15 significant digits Excel keeps: 0.30000000000000004 is 0.3. */
150
+ function numberText(value: number): string {
151
+ if (Number.isInteger(value) && Math.abs(value) < 1e15) return String(value);
152
+ return String(Number.parseFloat(value.toPrecision(15)));
153
+ }
154
+
155
+ /**
156
+ * What a workbook says of itself: its sheets in order, the part of its shared strings, the 1904
157
+ * date system, and how each cell style shows a number.
158
+ */
159
+ type Workbook = {
160
+ sheets: Array<{ name: string; part: string; hidden: boolean }>;
161
+ sharedStrings: string | undefined;
162
+ date1904: boolean;
163
+ /** The kind of value each cell style (`s`) shows, by its index. */
164
+ styles: ValueKind[];
165
+ };
166
+
167
+ /**
168
+ * The kind of sheet a relationship of the workbook names, at the end of its type. Only a worksheet
169
+ * holds cells of data: a chart sheet, a dialog sheet or a macro sheet does not.
170
+ */
171
+ const SHEET_KIND = /\/(worksheet|chartsheet|dialogsheet|xlMacrosheet|xlIntlMacrosheet)$/i;
172
+
173
+ async function readWorkbook(read: OfficeParts, names: string[]): Promise<Workbook> {
174
+ const workbookXml = await read.small("xl/workbook.xml");
175
+ if (!workbookXml) throw new Error("This XLSX does not contain xl/workbook.xml.");
176
+ const relationships = readRelationships(await read.small("xl/_rels/workbook.xml.rels"), "xl");
177
+ // Letter case does not count in the names of the parts of a package, as it does in a ZIP: a
178
+ // relationship to worksheets/Sheet1.xml names the part xl/worksheets/sheet1.xml.
179
+ const parts = new Set(names);
180
+ let byLowerCase: Map<string, string> | undefined;
181
+ /** Each relationship's part, worked out once: a workbook can name one relationship in 400,000 sheets. */
182
+ const resolved = new Map<string, string | undefined>();
183
+ const partOf = (target: string): string | undefined => {
184
+ if (parts.has(target)) return target;
185
+ if (resolved.has(target)) return resolved.get(target);
186
+ byLowerCase ??= new Map(names.map((name) => [name.toLowerCase(), name]));
187
+ const part = target.length > MAX_PART_NAME ? undefined : byLowerCase.get(target.toLowerCase());
188
+ resolved.set(target, part);
189
+ return part;
190
+ };
191
+ /** The part that a relationship of this type names, or else the part where Excel puts it, when the file has it. */
192
+ const related = (type: string, usual: string): string | undefined => {
193
+ for (const relationship of relationships.values()) {
194
+ const part = !relationship.external && relationship.type.endsWith(`/${type}`) ? partOf(relationship.target) : undefined;
195
+ if (part) return part;
196
+ }
197
+ return partOf(usual);
198
+ };
199
+ const sheets: Workbook["sheets"] = [];
200
+ const listed = new Set<string>();
201
+ let date1904 = false;
202
+ readXml(workbookXml, {
203
+ open(name, attributes) {
204
+ if (name === "workbookPr" || name.endsWith(":workbookPr")) date1904 = attributes.date1904 === "1" || attributes.date1904 === "true";
205
+ if (name !== "sheet" && !name.endsWith(":sheet")) return;
206
+ const id = attributes["r:id"] ?? Object.entries(attributes).find(([key]) => key.endsWith(":id"))?.[1];
207
+ const relationship = id ? relationships.get(id) : undefined;
208
+ // A sheet whose part is missing has nothing to read.
209
+ const part = relationship && !relationship.external ? partOf(relationship.target) : undefined;
210
+ if (!relationship || !part) return;
211
+ // The type of the relationship tells a worksheet, wherever its part is, from a chart sheet,
212
+ // which has no cells. A relationship that names no kind of sheet is told by the folder that
213
+ // Excel puts worksheets in.
214
+ const kind = SHEET_KIND.exec(relationship.type)?.[1];
215
+ if (kind ? kind.toLowerCase() !== "worksheet" : !/worksheets\//i.test(part)) return;
216
+ // A part listed again is not read again: a workbook can list one sheet 300,000 times.
217
+ if (listed.has(part)) return;
218
+ listed.add(part);
219
+ // Excel's names have at most 31 characters, LibreOffice's a few more: a name of thousands is cut.
220
+ sheets.push({ name: sliceWhole(decodeEscapes(attributes.name ?? `Sheet ${sheets.length + 1}`), MAX_SHEET_NAME), part, hidden: attributes.state === "hidden" || attributes.state === "veryHidden" });
221
+ },
222
+ });
223
+ const styles = related("styles", "xl/styles.xml");
224
+ return { sheets, sharedStrings: related("sharedStrings", "xl/sharedStrings.xml"), date1904, styles: readCellStyles(styles ? await read.small(styles) : undefined) };
225
+ }
226
+
227
+ /** The kind of value each cell style shows, from the number format it names. */
228
+ function readCellStyles(xml: string | undefined): ValueKind[] {
229
+ if (!xml) return [];
230
+ /** The kind of each custom format, worked out once: a workbook may name one in thousands of styles. */
231
+ const custom = new Map<number, ValueKind>();
232
+ const styles: ValueKind[] = [];
233
+ let inCellStyles = false;
234
+ readXml(xml, {
235
+ open(name, attributes) {
236
+ const local = name.slice(name.indexOf(":") + 1);
237
+ if (local === "numFmt") custom.set(Number(attributes.numFmtId), formatKind(attributes.formatCode ?? ""));
238
+ else if (local === "cellXfs") inCellStyles = true;
239
+ else if (inCellStyles && local === "xf") {
240
+ const id = Number(attributes.numFmtId ?? 0);
241
+ const kind = custom.get(id);
242
+ styles.push(kind !== undefined ? kind
243
+ : BUILT_IN_DATES.has(id) ? "date"
244
+ : BUILT_IN_TIMES.has(id) ? "time"
245
+ : BUILT_IN_DURATIONS.has(id) ? "duration"
246
+ : BUILT_IN_PERCENT.has(id) ? "percent" : "number");
247
+ }
248
+ },
249
+ close(name) {
250
+ if (name.slice(name.indexOf(":") + 1) === "cellXfs") inCellStyles = false;
251
+ },
252
+ });
253
+ return styles;
254
+ }
255
+
256
+ /**
257
+ * The shared strings of a workbook, read a piece at a time; the text of phonetic runs (`rPh`) is
258
+ * left out. Each is kept as a cell is written (`cellText`), made so once: a row can name one string
259
+ * thousands of times.
260
+ */
261
+ async function readSharedStrings(read: OfficeParts, part: string): Promise<string[]> {
262
+ const strings: string[] = [];
263
+ let current: string[] | undefined;
264
+ let inText = false;
265
+ let inPhonetic = 0;
266
+ let characters = 0;
267
+ const xml = new XmlStream({
268
+ open(name, _attributes, empty) {
269
+ const local = name.slice(name.indexOf(":") + 1);
270
+ if (local === "si" && !empty) current = [];
271
+ else if (local === "si") {
272
+ if (strings.length >= MAX_SHARED_STRINGS) throw new Error(`This XLSX has more than ${MAX_SHARED_STRINGS.toLocaleString("en-US")} different texts, more than a workbook holds. It may be built to exhaust the server, so it is not read.`);
273
+ strings.push("");
274
+ }
275
+ else if (local === "rPh" && !empty) inPhonetic++;
276
+ else if (local === "t" && !empty) inText = true;
277
+ },
278
+ close(name) {
279
+ const local = name.slice(name.indexOf(":") + 1);
280
+ if (local === "t") inText = false;
281
+ else if (local === "rPh" && inPhonetic > 0) inPhonetic--;
282
+ else if (local === "si" && current) {
283
+ if (strings.length >= MAX_SHARED_STRINGS) throw new Error(`This XLSX has more than ${MAX_SHARED_STRINGS.toLocaleString("en-US")} different texts, more than a workbook holds. It may be built to exhaust the server, so it is not read.`);
284
+ const text = cellText(decodeEscapes(current.join("")));
285
+ strings.push(text.length < 13 ? text : (" " + text).slice(1));
286
+ current = undefined;
287
+ }
288
+ },
289
+ text(text) {
290
+ if (!current || !inText || inPhonetic > 0) return;
291
+ characters += text.length;
292
+ if (characters > read.limits.maxCharacters) throw new Error("This XLSX holds more text than is kept from one file. Split it, and attach the part you need.");
293
+ current.push(text);
294
+ },
295
+ });
296
+ await read.stream(part, (piece) => xml.write(piece));
297
+ return strings;
298
+ }
299
+
300
+ /** A cell as it is read: its type (`t`), style (`s`), cached value and formula. */
301
+ type CellReading = { column: number; type: string; style: number; value: string[]; formula: string[]; inline: string[] };
302
+
303
+ /**
304
+ * Reads the rows of one sheet, a piece at a time, and gives each line of its section to `line`:
305
+ * the `Columns:` line first (from the sheet's `dimension`, when it has one), then a line per row
306
+ * that has a value. `holding` is told, as the row grows, how many characters the row being read
307
+ * holds, to refuse it before it ends.
308
+ */
309
+ function sheetReader(workbook: Workbook, strings: string[], line: (text: string) => void, holding: (characters: number) => void): XmlStream {
310
+ let firstColumn = 1;
311
+ let wroteColumns = false;
312
+ let row: Map<number, string> | undefined;
313
+ let rowNumber = 0;
314
+ /** The characters of the row being read: the text of its cells in the XML, and the shared strings they name. */
315
+ let held = 0;
316
+ const hold = (characters: number) => {
317
+ held += characters;
318
+ holding(held);
319
+ };
320
+ let nextColumn = 1;
321
+ let cell: CellReading | undefined;
322
+ /** Which text of the cell is being read: its value, its formula, or the text of an inline string. */
323
+ let reading: "value" | "formula" | "inline" | undefined;
324
+ let inInline = false;
325
+ let inPhonetic = 0;
326
+ const columns = (last: number) => {
327
+ if (wroteColumns) return;
328
+ wroteColumns = true;
329
+ const count = last - firstColumn + 1;
330
+ if (count <= 0) return;
331
+ line(count <= MAX_LISTED_COLUMNS
332
+ ? `Columns: | ${Array.from({ length: count }, (_, index) => columnName(firstColumn + index)).join(" | ")} |`
333
+ : `Columns: ${columnName(firstColumn)} to ${columnName(last)}`);
334
+ };
335
+ /** The value of a cell other than a shared string, as Excel shows it. */
336
+ const valueOf = (reading: CellReading): string => {
337
+ const raw = reading.value.join("");
338
+ switch (reading.type) {
339
+ case "inlineStr": return decodeEscapes(reading.inline.join(""));
340
+ case "str": return decodeEscapes(raw);
341
+ case "b": return raw === "1" ? "TRUE" : raw === "0" ? "FALSE" : raw;
342
+ case "e": return raw;
343
+ case "d": return raw.replace("T", " ").replace(/(?::00)?(?:\.0+)?Z?$/, "");
344
+ }
345
+ if (raw === "") {
346
+ const formula = reading.formula.join("");
347
+ return formula ? `=${decodeEscapes(formula)}` : "";
348
+ }
349
+ const number = Number(raw);
350
+ if (!Number.isFinite(number)) return raw;
351
+ const kind = workbook.styles[reading.style] ?? "number";
352
+ if (kind === "date" || kind === "time") return excelDate(number, kind, workbook.date1904);
353
+ if (kind === "duration") return excelDuration(number);
354
+ if (kind === "percent") return `${numberText(number * 100)}%`;
355
+ return numberText(number);
356
+ };
357
+ const local = (name: string) => name.slice(name.indexOf(":") + 1);
358
+ return new XmlStream({
359
+ open(name, attributes: XmlAttributes, empty) {
360
+ const tag = local(name);
361
+ if (tag === "dimension") {
362
+ const [from, to] = (attributes.ref ?? "").split(":");
363
+ const start = cellAt(from);
364
+ const end = cellAt(to ?? from);
365
+ if (start && end && start.column <= end.column && end.column <= MAX_COLUMN) {
366
+ firstColumn = start.column;
367
+ columns(end.column);
368
+ }
369
+ } else if (tag === "row") {
370
+ rowNumber = Number(attributes.r) || rowNumber + 1;
371
+ nextColumn = firstColumn;
372
+ held = 0;
373
+ row = new Map();
374
+ if (empty) row = undefined;
375
+ } else if (tag === "c" && row) {
376
+ const at = cellAt(attributes.r);
377
+ const column = at ? at.column : nextColumn;
378
+ nextColumn = column + 1;
379
+ // Past Excel's last column there is no cell: a row of millions of them is not kept.
380
+ cell = empty || column > MAX_COLUMN ? undefined : { column, type: attributes.t ?? "n", style: Number(attributes.s ?? 0), value: [], formula: [], inline: [] };
381
+ } else if (cell) {
382
+ if (tag === "v" && !empty) reading = "value";
383
+ else if (tag === "f" && !empty) reading = "formula";
384
+ else if (tag === "is" && !empty) inInline = true;
385
+ else if (tag === "rPh" && !empty) inPhonetic++;
386
+ else if (tag === "t" && inInline && !empty) reading = "inline";
387
+ }
388
+ },
389
+ close(name) {
390
+ const tag = local(name);
391
+ if (tag === "v" || tag === "f" || tag === "t") {
392
+ reading = undefined;
393
+ } else if (tag === "is") {
394
+ inInline = false;
395
+ } else if (tag === "rPh") {
396
+ if (inPhonetic > 0) inPhonetic--;
397
+ } else if (tag === "c" && cell && row) {
398
+ let text: string;
399
+ if (cell.type === "s") {
400
+ // A shared string counts at its length each time a cell names it, before the row keeps
401
+ // it: in a few bytes each, one row can name a string of a million characters thousands
402
+ // of times. It was made a cell's text when it was read, and is kept, not copied.
403
+ text = strings[Number(cell.value.join(""))] ?? "";
404
+ hold(text.length);
405
+ } else {
406
+ text = cellText(valueOf(cell));
407
+ }
408
+ if (text !== "") row.set(cell.column, text);
409
+ cell = undefined;
410
+ } else if (tag === "row" && row) {
411
+ if (row.size > 0) {
412
+ if (!wroteColumns) columns(Math.max(...row.keys()));
413
+ let last = 0;
414
+ for (const column of row.keys()) if (column > last) last = column;
415
+ const cells: string[] = [];
416
+ for (let column = Math.min(firstColumn, ...row.keys()); column <= last; column++) cells.push(row.get(column) ?? "");
417
+ line(`Row ${rowNumber}: | ${cells.join(" | ")} |`);
418
+ }
419
+ row = undefined;
420
+ }
421
+ },
422
+ text(text) {
423
+ if (!cell || reading === undefined) return;
424
+ // What a row holds is counted before the row ends: one cell can be megabytes of text.
425
+ hold(text.length);
426
+ if (reading === "inline") {
427
+ if (inPhonetic === 0) cell.inline.push(text);
428
+ } else {
429
+ cell[reading].push(text);
430
+ }
431
+ },
432
+ });
433
+ }
434
+
435
+ export const xlsx: Extractor = async (bytes, input) => {
436
+ input?.signal?.throwIfAborted();
437
+ const archive = await openOffice(bytes, "XLSX");
438
+ input?.signal?.throwIfAborted();
439
+ const read = officeReader(archive, "XLSX", bytes.byteLength, input);
440
+ const workbook = await readWorkbook(read, Object.keys(archive.files));
441
+ if (workbook.sheets.length === 0) throw new Error("This XLSX does not contain any sheets with cells.");
442
+ const strings = workbook.sharedStrings ? await readSharedStrings(read, workbook.sharedStrings) : [];
443
+ const sections: string[] = [];
444
+ const tooMuch = () => new Error(read.limits.byTextLimit
445
+ ? "This XLSX holds more text than is kept from one file. Split it, and attach the part you need."
446
+ : "This XLSX holds more text than is read from one file. Split it, and attach the part you need.");
447
+ /** Counts a line of the text kept, and refuses the file past the limit. */
448
+ const kept = (text: string) => {
449
+ read.count.characters += text.length + 1;
450
+ if (read.count.characters > read.limits.maxCharacters) throw tooMuch();
451
+ };
452
+ for (const [index, sheet] of workbook.sheets.entries()) {
453
+ // The heading is text kept, as a row is: a workbook can have thousands of empty sheets.
454
+ const heading = `## Sheet ${index + 1}: ${sheet.name.replace(/\s+/g, " ")}${sheet.hidden ? " (hidden sheet)" : ""}`;
455
+ kept(heading);
456
+ const lines: string[] = [];
457
+ const reader = sheetReader(workbook, strings, (text) => {
458
+ kept(text);
459
+ lines.push(text);
460
+ }, (characters) => {
461
+ if (read.count.characters + characters > read.limits.maxCharacters) throw tooMuch();
462
+ });
463
+ await read.stream(sheet.part, (piece) => reader.write(piece));
464
+ // A sheet with no value says so, rather than leaving its heading alone, or with its columns.
465
+ if (!lines.some((text) => text.startsWith("Row "))) {
466
+ for (const text of lines) read.count.characters -= text.length + 1;
467
+ lines.length = 0;
468
+ lines.push(NO_VALUES);
469
+ kept(NO_VALUES);
470
+ }
471
+ sections.push(`${heading}\n${lines.join("\n")}`);
472
+ input?.onProgress?.({ done: index + 1, total: workbook.sheets.length, unit: "parts" });
473
+ }
474
+ return { text: sections.join("\n\n"), pages: workbook.sheets.length };
475
+ };
476
+
477
+ /** `decodeEscapes`, for tests. */
478
+ export const decodeEscapesForTest = decodeEscapes;