llm-large-files 0.7.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 (184) hide show
  1. package/CHANGELOG.md +319 -1
  2. package/README.md +10 -8
  3. package/dist/analyze.d.ts +3 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +109 -14
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts.map +1 -1
  8. package/dist/anthropic/adapter.js +4 -1
  9. package/dist/anthropic/adapter.js.map +1 -1
  10. package/dist/ask.d.ts +3 -3
  11. package/dist/ask.d.ts.map +1 -1
  12. package/dist/ask.js +72 -17
  13. package/dist/ask.js.map +1 -1
  14. package/dist/decode.d.ts +19 -0
  15. package/dist/decode.d.ts.map +1 -0
  16. package/dist/decode.js +97 -0
  17. package/dist/decode.js.map +1 -0
  18. package/dist/errors.d.ts +55 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +65 -0
  21. package/dist/errors.js.map +1 -1
  22. package/dist/events.d.ts +6 -0
  23. package/dist/events.d.ts.map +1 -1
  24. package/dist/events.js +5 -1
  25. package/dist/events.js.map +1 -1
  26. package/dist/evidence.d.ts.map +1 -1
  27. package/dist/evidence.js +6 -0
  28. package/dist/evidence.js.map +1 -1
  29. package/dist/extract.d.ts +7 -20
  30. package/dist/extract.d.ts.map +1 -1
  31. package/dist/extract.js +49 -751
  32. package/dist/extract.js.map +1 -1
  33. package/dist/gemini/adapter.d.ts.map +1 -1
  34. package/dist/gemini/adapter.js +9 -5
  35. package/dist/gemini/adapter.js.map +1 -1
  36. package/dist/gemini/endpoints.d.ts +5 -1
  37. package/dist/gemini/endpoints.d.ts.map +1 -1
  38. package/dist/gemini/endpoints.js +11 -2
  39. package/dist/gemini/endpoints.js.map +1 -1
  40. package/dist/gemini/generate.d.ts.map +1 -1
  41. package/dist/gemini/generate.js +20 -3
  42. package/dist/gemini/generate.js.map +1 -1
  43. package/dist/groups.d.ts +54 -0
  44. package/dist/groups.d.ts.map +1 -0
  45. package/dist/groups.js +136 -0
  46. package/dist/groups.js.map +1 -0
  47. package/dist/html.d.ts +11 -0
  48. package/dist/html.d.ts.map +1 -0
  49. package/dist/html.js +1112 -0
  50. package/dist/html.js.map +1 -0
  51. package/dist/index.d.ts +2 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +1 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/library.d.ts.map +1 -1
  56. package/dist/library.js +48 -12
  57. package/dist/library.js.map +1 -1
  58. package/dist/limiter.d.ts +2 -1
  59. package/dist/limiter.d.ts.map +1 -1
  60. package/dist/limiter.js +3 -2
  61. package/dist/limiter.js.map +1 -1
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +8 -1
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts.map +1 -1
  66. package/dist/node/handlers.js +69 -15
  67. package/dist/node/handlers.js.map +1 -1
  68. package/dist/node/index.d.ts +2 -0
  69. package/dist/node/index.d.ts.map +1 -1
  70. package/dist/node/index.js +1 -0
  71. package/dist/node/index.js.map +1 -1
  72. package/dist/node/ingest-child.d.ts +38 -0
  73. package/dist/node/ingest-child.d.ts.map +1 -0
  74. package/dist/node/ingest-child.js +42 -0
  75. package/dist/node/ingest-child.js.map +1 -0
  76. package/dist/node/isolated.d.ts +88 -0
  77. package/dist/node/isolated.d.ts.map +1 -0
  78. package/dist/node/isolated.js +381 -0
  79. package/dist/node/isolated.js.map +1 -0
  80. package/dist/office.d.ts +105 -0
  81. package/dist/office.d.ts.map +1 -0
  82. package/dist/office.js +1092 -0
  83. package/dist/office.js.map +1 -0
  84. package/dist/openai/adapter.d.ts.map +1 -1
  85. package/dist/openai/adapter.js +15 -1
  86. package/dist/openai/adapter.js.map +1 -1
  87. package/dist/pdf-pages.d.ts.map +1 -1
  88. package/dist/pdf-pages.js +2 -6
  89. package/dist/pdf-pages.js.map +1 -1
  90. package/dist/peers.d.ts +8 -0
  91. package/dist/peers.d.ts.map +1 -0
  92. package/dist/peers.js +32 -0
  93. package/dist/peers.js.map +1 -0
  94. package/dist/plan.d.ts.map +1 -1
  95. package/dist/plan.js +1 -1
  96. package/dist/plan.js.map +1 -1
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +4 -2
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/search.d.ts +99 -22
  101. package/dist/search.d.ts.map +1 -1
  102. package/dist/search.js +744 -140
  103. package/dist/search.js.map +1 -1
  104. package/dist/text-index.d.ts +3 -1
  105. package/dist/text-index.d.ts.map +1 -1
  106. package/dist/text-index.js +3 -1
  107. package/dist/text-index.js.map +1 -1
  108. package/dist/text.d.ts +27 -3
  109. package/dist/text.d.ts.map +1 -1
  110. package/dist/text.js +225 -23
  111. package/dist/text.js.map +1 -1
  112. package/dist/tools.d.ts.map +1 -1
  113. package/dist/tools.js +200 -12
  114. package/dist/tools.js.map +1 -1
  115. package/dist/types.d.ts +3 -3
  116. package/dist/types.d.ts.map +1 -1
  117. package/dist/word-styles.d.ts +102 -0
  118. package/dist/word-styles.d.ts.map +1 -0
  119. package/dist/word-styles.js +419 -0
  120. package/dist/word-styles.js.map +1 -0
  121. package/dist/xlsx.d.ts +23 -0
  122. package/dist/xlsx.d.ts.map +1 -0
  123. package/dist/xlsx.js +511 -0
  124. package/dist/xlsx.js.map +1 -0
  125. package/dist/xml-stream.d.ts +55 -0
  126. package/dist/xml-stream.d.ts.map +1 -0
  127. package/dist/xml-stream.js +235 -0
  128. package/dist/xml-stream.js.map +1 -0
  129. package/docs/README.md +8 -8
  130. package/docs/getting-started.md +1 -1
  131. package/docs/guides/costs-and-limits.md +7 -5
  132. package/docs/guides/deployment.md +95 -29
  133. package/docs/guides/errors-and-reliability.md +23 -10
  134. package/docs/guides/pdfs.md +127 -74
  135. package/docs/guides/storage.md +1 -1
  136. package/docs/guides/testing.md +5 -1
  137. package/docs/guides/web-app.md +10 -9
  138. package/docs/how-it-works.md +73 -50
  139. package/docs/reference/ask.md +26 -8
  140. package/docs/reference/errors-and-retries.md +5 -3
  141. package/docs/reference/events.md +14 -6
  142. package/docs/reference/gemini.md +6 -2
  143. package/docs/reference/library.md +205 -74
  144. package/docs/reference/node.md +200 -22
  145. package/docs/reference/openai.md +1 -1
  146. package/docs/reference/tools.md +170 -22
  147. package/docs/security.md +114 -69
  148. package/docs/troubleshooting.md +40 -20
  149. package/package.json +6 -2
  150. package/src/analyze.ts +117 -13
  151. package/src/anthropic/adapter.ts +4 -1
  152. package/src/ask.ts +73 -17
  153. package/src/decode.ts +89 -0
  154. package/src/errors.ts +108 -0
  155. package/src/events.ts +10 -1
  156. package/src/evidence.ts +6 -0
  157. package/src/extract.ts +52 -709
  158. package/src/gemini/adapter.ts +9 -5
  159. package/src/gemini/endpoints.ts +12 -2
  160. package/src/gemini/generate.ts +19 -3
  161. package/src/groups.ts +162 -0
  162. package/src/html.ts +1071 -0
  163. package/src/index.ts +2 -1
  164. package/src/library.ts +43 -12
  165. package/src/limiter.ts +6 -1
  166. package/src/model.ts +8 -1
  167. package/src/node/handlers.ts +66 -16
  168. package/src/node/index.ts +2 -0
  169. package/src/node/ingest-child.ts +61 -0
  170. package/src/node/isolated.ts +464 -0
  171. package/src/office.ts +1047 -0
  172. package/src/openai/adapter.ts +14 -1
  173. package/src/pdf-pages.ts +2 -5
  174. package/src/peers.ts +29 -0
  175. package/src/plan.ts +2 -0
  176. package/src/ranged.ts +4 -2
  177. package/src/search.ts +738 -146
  178. package/src/text-index.ts +4 -2
  179. package/src/text.ts +214 -23
  180. package/src/tools.ts +192 -12
  181. package/src/types.ts +3 -3
  182. package/src/word-styles.ts +420 -0
  183. package/src/xlsx.ts +478 -0
  184. package/src/xml-stream.ts +224 -0
package/dist/office.js ADDED
@@ -0,0 +1,1092 @@
1
+ import { LEGACY_OFFICE } from "./decode.js";
2
+ import { importPeer } from "./peers.js";
3
+ import { TimeSlicer } from "./pause.js";
4
+ import { formatBytes } from "./plan.js";
5
+ import { MAX_LINE_CHARACTERS, sliceWhole } from "./text.js";
6
+ import { WordNumbering } from "./word-styles.js";
7
+ import { parseAttributes, readRelationships, readXml } from "./xml-stream.js";
8
+ import { readZipDirectory } from "./zip-directory.js";
9
+ // Office files are ZIP archives of XML: Word (DOCX) and PowerPoint (PPTX) are read here, and the
10
+ // parts are streamed for the spreadsheet reader (xlsx.ts) too. No XML parser is used: each part is
11
+ // read a piece at a time as it is unpacked, under limits a hostile file cannot get past.
12
+ function decodeXmlEntities(value) {
13
+ return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (match, entity) => {
14
+ const lower = entity.toLowerCase();
15
+ if (lower === "amp")
16
+ return "&";
17
+ if (lower === "lt")
18
+ return "<";
19
+ if (lower === "gt")
20
+ return ">";
21
+ if (lower === "quot")
22
+ return "\"";
23
+ if (lower === "apos")
24
+ return "'";
25
+ const code = lower.startsWith("#x") ? Number.parseInt(lower.slice(2), 16) : Number.parseInt(lower.slice(1), 10);
26
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
27
+ });
28
+ }
29
+ /** A tag name is read up to this many characters: the names that matter here are short. */
30
+ const MAX_TAG_NAME = 64;
31
+ /** Paragraphs inside paragraphs, at most. Real files nest two or three: a text box in a paragraph. */
32
+ const MAX_PARAGRAPH_DEPTH = 32;
33
+ /** Paragraphs with text read from one Office file, at most: a document of 10,000 pages has about 300,000. */
34
+ const MAX_OFFICE_PARAGRAPHS = 1_000_000;
35
+ /** Characters of text kept from one Office file, at most, whatever `maxTextBytes` allows: about 10,000 dense pages. */
36
+ const MAX_OFFICE_CHARACTERS = 32_000_000;
37
+ /**
38
+ * The text of an open paragraph is counted as written in the XML, where `&quot;` is six characters
39
+ * for one: past this many times the limit, it is refused before the paragraph closes.
40
+ */
41
+ const MAX_ENTITY_GROWTH = 6;
42
+ /** Below this length V8 copies a slice of a string; from it on, a slice keeps the whole string it was cut from. */
43
+ const SLICE_COPIED_BELOW = 13;
44
+ /** The attributes of a tag are read up to this many characters: the few that are read are short. */
45
+ const MAX_RAW_TAG = 1_024;
46
+ /** Grid columns one table cell may span (`w:gridSpan`); Word allows 63 columns in a table. */
47
+ const MAX_CELL_SPAN = 63;
48
+ /** Tags whose attributes are read, beside `w:vanish` and `p:sld`. */
49
+ const WORD_ATTRIBUTE_TAGS = new Set(["w:pStyle", "w:numId", "w:ilvl", "w:outlineLvl", "w:gridSpan", "w:gridBefore", "w:gridAfter", "w:sym"]);
50
+ const DRAWING_ATTRIBUTE_TAGS = new Set(["p:ph"]);
51
+ /** The properties of a Word table row and cell, and those of them that are read. */
52
+ const TABLE_PROPERTY_TAGS = new Set(["w:trPr", "/w:trPr", "w:tcPr", "/w:tcPr", "w:gridSpan", "w:gridBefore", "w:gridAfter"]);
53
+ /**
54
+ * The placeholders of a notes page whose text is not the speaker's notes: the slide number, the
55
+ * date, the header and the footer (Header & Footer, Notes and Handouts), and the picture of the
56
+ * slide. The notes are in the body placeholder; a text box the presenter added is kept too.
57
+ */
58
+ const NOTES_PAGE_PLACEHOLDERS = new Set(["sldNum", "dt", "hdr", "ftr", "sldImg"]);
59
+ /** A table cell's text as a cell of a `| cell | cell |` row: one line, its pipes escaped, as the PDF extractor writes them. */
60
+ function cellText(text) {
61
+ return text.replace(/\s+/g, " ").replace(/\|/g, "\\|").trim();
62
+ }
63
+ /**
64
+ * Written before each line of the text that Word hides (a run marked `<w:vanish/>`), after the text
65
+ * of its paragraph that shows: a person reading the document does not see it. Each line is marked,
66
+ * so hidden text cannot end the mark and pass for text that shows.
67
+ */
68
+ export const HIDDEN_TEXT = "[Hidden text, not shown in the document]";
69
+ /** Added to the heading of a slide that the slide show skips (`<p:sld show="0">`). */
70
+ export const HIDDEN_SLIDE = "(hidden, not shown in the slide show)";
71
+ /**
72
+ * The one attribute read of `w:vanish` and of `p:sld`, and the values that count:
73
+ * `<w:vanish w:val="0"/>` turns hiding off (`<w:vanish/>` and any other value turn it on), and a
74
+ * slide with `show="0"` is hidden. Letter case counts in the value of `show`, and not in that of
75
+ * `w:val`. It counts in names, as in XML: `W:VAL` is another attribute.
76
+ */
77
+ const VANISH_OFF = { name: "w:val", values: ["0", "false", "off"], anyCase: true };
78
+ const SLIDE_NOT_SHOWN = { name: "show", values: ["0", "false"], anyCase: false };
79
+ /** Characters kept of an attribute's name and of the value wanted: more than the longest of those above. */
80
+ const MAX_ATTRIBUTE_PART = 6;
81
+ /**
82
+ * A line of hidden text longer than this is cut into pieces, each marked. A mark and its piece then
83
+ * fit on one line, which ingest does not cut: past `MAX_LINE_CHARACTERS` it would put the rest of
84
+ * the hidden line on a line of its own, without the mark.
85
+ */
86
+ // A tenth is kept free: ingest composes the text (NFC) and bounds runs of marks after it is cut,
87
+ // which can lengthen a line, and a line past the wrap limit would leave its rest without a mark.
88
+ const HIDDEN_PIECE = Math.floor((MAX_LINE_CHARACTERS - HIDDEN_TEXT.length - 1) * 0.9);
89
+ /**
90
+ * What ends a line of hidden text: a line break, a carriage return (ingest makes it one), a U+0085
91
+ * (ingest makes it one in a text with no other line break), or a line or paragraph separator
92
+ * (U+2028, U+2029), which a model may take for one. A new marked line where ingest removes the
93
+ * U+0085 instead does no harm.
94
+ */
95
+ const HIDDEN_LINE_END = /[\r\n\x85\u2028\u2029]/g;
96
+ /** Where a line of hidden text starts: at a character that is not white space, nor a U+0085. */
97
+ const NOT_SPACE = /[^\s\x85]/g;
98
+ /**
99
+ * Reads one attribute of a tag as the tag goes past, a character at a time, in whatever pieces the
100
+ * XML comes: whether its value is one of those wanted. It keeps a few characters, whatever the
101
+ * length of the tag, and looks at names and values apart, so a value that holds `w:val="0"` is not
102
+ * read as the attribute.
103
+ */
104
+ class AttributeReader {
105
+ wanted;
106
+ /** The name being read, or the last one read, cut after `MAX_ATTRIBUTE_PART` characters. */
107
+ name = "";
108
+ /** Whether the next character of a name starts a new one. */
109
+ ended = true;
110
+ /** Whether "=" came after the name wanted, so the next value is its value. */
111
+ assigned = false;
112
+ /** The value of the attribute wanted, while it is read. */
113
+ value;
114
+ /** Whether the attribute wanted has one of the values wanted. */
115
+ found = false;
116
+ constructor(wanted) {
117
+ this.wanted = wanted;
118
+ }
119
+ /** A character of the tag after its name, outside a value. A quote that opens a value is not one. */
120
+ outside(code) {
121
+ if (code === 32 || code === 9 || code === 10 || code === 13) {
122
+ this.ended = true;
123
+ }
124
+ else if (code === 61) {
125
+ this.assigned = this.name === this.wanted.name;
126
+ this.name = "";
127
+ this.ended = true;
128
+ }
129
+ else {
130
+ if (this.ended) {
131
+ this.name = "";
132
+ this.ended = false;
133
+ this.assigned = false;
134
+ }
135
+ if (this.name.length < MAX_ATTRIBUTE_PART)
136
+ this.name += String.fromCharCode(code);
137
+ }
138
+ }
139
+ /** A quote opens a value. */
140
+ open() {
141
+ if (this.assigned)
142
+ this.value = "";
143
+ this.assigned = false;
144
+ }
145
+ /** A character of a value. */
146
+ inValue(code) {
147
+ if (this.value !== undefined && this.value.length < MAX_ATTRIBUTE_PART)
148
+ this.value += String.fromCharCode(code);
149
+ }
150
+ /** The quote that closes a value. */
151
+ close() {
152
+ if (this.value !== undefined) {
153
+ this.found = this.wanted.values.includes(this.wanted.anyCase ? this.value.toLowerCase() : this.value);
154
+ this.value = undefined;
155
+ }
156
+ this.name = "";
157
+ this.ended = true;
158
+ }
159
+ }
160
+ const NO_OFFICE_LIMITS = { kind: "file", maxCharacters: MAX_OFFICE_CHARACTERS, byTextLimit: false };
161
+ /**
162
+ * Collects the text of each paragraph of Office XML (`<w:p>` in Word, `<a:p>` in PowerPoint) in one
163
+ * pass, with no XML parser. The XML can come in pieces, as it is unpacked: a tag cut between two
164
+ * pieces is read whole. Every character is looked at once, so the time follows the length of the
165
+ * XML whatever its shape: a file of unclosed tags costs what a file of closed ones does.
166
+ *
167
+ * - A paragraph inside another one (the text box of a shape anchored in a paragraph) is a paragraph
168
+ * of its own, after the one it is anchored in, which keeps its text before and after the box.
169
+ * - `mc:Fallback` repeats `mc:Choice` for older programs, so it is skipped: a text box is read once.
170
+ * - Paragraph properties hold no text. Their tab stops are not tabs.
171
+ * - In Word, the text of a hidden run (`<w:vanish/>` in the run's own properties) comes after the
172
+ * text of its paragraph that shows, each line marked with `HIDDEN_TEXT`. Text hidden by a style
173
+ * is not told apart. In PowerPoint, `hiddenSlide` says whether the slide show skips the slide.
174
+ *
175
+ * What it keeps in memory is bounded by the text, not by the XML: a paragraph becomes one string
176
+ * when it closes, an empty one is dropped, and a file that nests paragraphs past
177
+ * `MAX_PARAGRAPH_DEPTH`, or has more text or paragraphs than one document holds, is refused.
178
+ */
179
+ class OfficeText {
180
+ limits;
181
+ count;
182
+ paragraphTag;
183
+ paragraphEnd;
184
+ textTag;
185
+ textEnd;
186
+ propertiesTag;
187
+ propertiesEnd;
188
+ tabTag;
189
+ breakTags;
190
+ /** Word marks hidden runs; PowerPoint hides whole slides. */
191
+ word;
192
+ /** The one tag whose attributes are read: `w:vanish` in Word, the slide's `p:sld` in PowerPoint. */
193
+ attributesTag;
194
+ /** The attribute read of `attributesTag`, and the values that count. */
195
+ attribute;
196
+ /** The text of each paragraph, in the order the paragraphs start: null while it is open, "" when empty. */
197
+ paragraphs = [];
198
+ /**
199
+ * The paragraphs that are open, the innermost last: where each goes in `paragraphs` (-1: into
200
+ * the table cell that is open), its text so far (that which shows, and that which Word hides),
201
+ * and its length. In Word, also how many runs are open (a ruby's runs are inside a run), how deep
202
+ * the outermost hidden one is (0: none is hidden), how deep in run properties the reading is, and
203
+ * its style and numbering.
204
+ */
205
+ open = [];
206
+ /**
207
+ * The table being read, and how deep in tables (a table in a cell is read as text of that cell).
208
+ * Its rows so far, the row and the cell open, and in Word: how many grid columns the cell open
209
+ * spans, how many empty columns end the row open (`w:gridAfter`), and how deep in the properties
210
+ * of the row or cell the reading is (those of a change they record are one level deeper).
211
+ */
212
+ table;
213
+ tableTag;
214
+ rowTag;
215
+ cellTag;
216
+ /** Tags whose attributes are read (see `read`). */
217
+ attributeTags;
218
+ /** Characters held in the paragraphs that are open, as written in the XML. */
219
+ pending = 0;
220
+ inText = false;
221
+ inProperties = 0;
222
+ inFallback = 0;
223
+ /**
224
+ * The tag being read, from its "<": its name so far, the quote of a value it is in, its last
225
+ * character, and for `attributesTag` the reader of its attribute.
226
+ */
227
+ tag;
228
+ /** A PowerPoint slide that the slide show skips (`<p:sld show="0">`). */
229
+ hiddenSlide = false;
230
+ /** Word's styles and lists, to write headings as `#` lines and each paragraph with its list number. */
231
+ numbering;
232
+ /** On a notes page, the placeholders whose text is left out (`NOTES_PAGE_PLACEHOLDERS`). */
233
+ leftOut;
234
+ /** In PowerPoint, whether a shape (`p:sp`) is open, and whether it is a placeholder left out. */
235
+ inShape = false;
236
+ inLeftOut = false;
237
+ /** `count`: what the other parts of the same file held, shared with them. */
238
+ constructor(prefix, limits = NO_OFFICE_LIMITS, count = { characters: 0, paragraphs: 0 }, options = {}) {
239
+ this.limits = limits;
240
+ this.count = count;
241
+ this.numbering = options.numbering;
242
+ this.leftOut = options.notesPage ? NOTES_PAGE_PLACEHOLDERS : undefined;
243
+ this.paragraphTag = `${prefix}:p`;
244
+ this.paragraphEnd = `/${prefix}:p`;
245
+ this.textTag = `${prefix}:t`;
246
+ this.textEnd = `/${prefix}:t`;
247
+ this.propertiesTag = `${prefix}:pPr`;
248
+ this.propertiesEnd = `/${prefix}:pPr`;
249
+ this.tabTag = `${prefix}:tab`;
250
+ this.breakTags = new Set([`${prefix}:br`, `${prefix}:cr`]);
251
+ this.word = prefix === "w";
252
+ this.attributesTag = this.word ? "w:vanish" : "p:sld";
253
+ this.attribute = this.word ? VANISH_OFF : SLIDE_NOT_SHOWN;
254
+ this.tableTag = `${prefix}:tbl`;
255
+ this.rowTag = `${prefix}:tr`;
256
+ this.cellTag = `${prefix}:tc`;
257
+ this.attributeTags = this.word ? WORD_ATTRIBUTE_TAGS : DRAWING_ATTRIBUTE_TAGS;
258
+ }
259
+ write(xml) {
260
+ const length = xml.length;
261
+ let at = 0;
262
+ while (at < length) {
263
+ const tag = this.tag;
264
+ if (!tag) {
265
+ const start = xml.indexOf("<", at);
266
+ const end = start === -1 ? length : start;
267
+ if (end > at && this.inText && this.inProperties === 0 && this.inFallback === 0)
268
+ this.add(xml.slice(at, end));
269
+ if (start === -1)
270
+ return;
271
+ this.tag = { name: "", named: false, quote: 0, last: 0, attributes: undefined, raw: undefined };
272
+ at = start + 1;
273
+ continue;
274
+ }
275
+ for (; at < length; at++) {
276
+ const code = xml.charCodeAt(at);
277
+ if (tag.quote !== 0) {
278
+ if (tag.raw !== undefined && tag.raw.length < MAX_RAW_TAG)
279
+ tag.raw += xml[at];
280
+ if (code === tag.quote) {
281
+ tag.quote = 0;
282
+ tag.attributes?.close();
283
+ }
284
+ else {
285
+ tag.attributes?.inValue(code);
286
+ }
287
+ continue;
288
+ }
289
+ if (!tag.named) {
290
+ // A name ends at white space, at ">", or at the "/" of "<w:br/>". "</w:p>" starts with one.
291
+ if (code === 62 || code === 32 || code === 9 || code === 10 || code === 13 || (code === 47 && tag.name !== "")) {
292
+ tag.named = true;
293
+ if (tag.name === this.attributesTag)
294
+ tag.attributes = new AttributeReader(this.attribute);
295
+ if (this.attributeTags.has(tag.name))
296
+ tag.raw = "";
297
+ }
298
+ else {
299
+ if (tag.name.length < MAX_TAG_NAME)
300
+ tag.name += xml[at];
301
+ continue;
302
+ }
303
+ }
304
+ if (code === 62)
305
+ break;
306
+ if (tag.raw !== undefined && tag.raw.length < MAX_RAW_TAG)
307
+ tag.raw += xml[at];
308
+ if (code === 34 || code === 39) {
309
+ tag.quote = code;
310
+ tag.attributes?.open();
311
+ }
312
+ else {
313
+ tag.attributes?.outside(code);
314
+ if (code !== 32 && code !== 9 && code !== 10 && code !== 13)
315
+ tag.last = code;
316
+ }
317
+ }
318
+ if (at === length)
319
+ return; // The tag goes on in the next piece.
320
+ this.tag = undefined;
321
+ this.read(tag.name, tag.last === 47, tag.attributes?.found ?? false, tag.raw);
322
+ at++;
323
+ }
324
+ }
325
+ /** The text of each paragraph that has some, in the order the paragraphs start. A table is one, of a line a row. */
326
+ texts() {
327
+ // A paragraph never closed keeps the text it has, as when the file ends inside it; so does a table.
328
+ while (this.open.length > 0)
329
+ this.close();
330
+ while (this.table)
331
+ this.closeTable();
332
+ return this.paragraphs.filter((text) => !!text);
333
+ }
334
+ /** Adds text to the innermost open paragraph. */
335
+ add(piece) {
336
+ const paragraph = this.open.at(-1);
337
+ if (!paragraph || this.inLeftOut)
338
+ return;
339
+ this.pending += piece.length;
340
+ paragraph.length += piece.length;
341
+ // The decoded text is counted when its paragraph closes. Until then, what is held is bounded too.
342
+ if (this.pending > this.limits.maxCharacters * MAX_ENTITY_GROWTH)
343
+ throw this.tooMuchText();
344
+ if (paragraph.hiddenFrom !== 0)
345
+ (paragraph.hidden ??= []).push(piece);
346
+ else
347
+ paragraph.pieces.push(piece);
348
+ }
349
+ tooMuchText() {
350
+ const { kind, maxCharacters, byTextLimit } = this.limits;
351
+ return new Error(byTextLimit
352
+ ? `This ${kind} holds more than ${formatBytes(maxCharacters)} of text, more than is kept from one file. Split it, and attach the part you need.`
353
+ : `This ${kind} holds more than ${Math.round(maxCharacters / 1_000_000)} million characters of text, more than is read from one file. Split it, and attach the part you need.`);
354
+ }
355
+ /** Closes the innermost open paragraph: its text becomes one string, or it is dropped when empty. */
356
+ close() {
357
+ const paragraph = this.open.pop();
358
+ if (!paragraph)
359
+ return;
360
+ this.pending -= paragraph.length;
361
+ let shown = decodeXmlEntities(paragraph.pieces.join(""));
362
+ if (this.numbering && paragraph.style) {
363
+ // An empty paragraph is counted in its list too, as Word shows its number there. The number
364
+ // is written only before text: empty paragraphs count toward no limit, and a file of them
365
+ // would have its numbers written, at up to 64 characters each, only to be thrown away.
366
+ const counted = this.numbering.count(paragraph.style);
367
+ if (shown.trim()) {
368
+ const label = counted && this.numbering.labelOf(counted);
369
+ const level = paragraph.slot !== -1 ? this.numbering.headingLevel(paragraph.style) : undefined;
370
+ shown = `${level ? `${"#".repeat(level)} ` : ""}${label ? `${label} ` : ""}${shown}`;
371
+ }
372
+ }
373
+ const text = paragraph.hidden ? this.withHiddenText(shown, decodeXmlEntities(paragraph.hidden.join(""))) : shown;
374
+ if (paragraph.slot === -1) {
375
+ // A paragraph of a table cell: its text goes into the cell, counted as any paragraph's.
376
+ if (text.trim()) {
377
+ this.count.characters += text.length;
378
+ if (this.count.characters > this.limits.maxCharacters)
379
+ throw this.tooMuchText();
380
+ this.table?.cell?.push(text);
381
+ }
382
+ return;
383
+ }
384
+ if (text.trim()) {
385
+ this.count.characters += text.length;
386
+ if (this.count.characters > this.limits.maxCharacters)
387
+ throw this.tooMuchText();
388
+ if (++this.count.paragraphs > MAX_OFFICE_PARAGRAPHS) {
389
+ throw new Error(`This ${this.limits.kind} has more than ${MAX_OFFICE_PARAGRAPHS.toLocaleString("en-US")} paragraphs, more than a document holds. It may be built to exhaust the server, so it is not read.`);
390
+ }
391
+ // A copy, not a slice of the piece of XML it came from: a slice would keep all that XML in memory.
392
+ this.paragraphs[paragraph.slot] = text.length < SLICE_COPIED_BELOW ? text : (" " + text).slice(1);
393
+ }
394
+ else if (paragraph.slot === this.paragraphs.length - 1) {
395
+ this.paragraphs.pop();
396
+ }
397
+ else {
398
+ this.paragraphs[paragraph.slot] = "";
399
+ }
400
+ }
401
+ /**
402
+ * A paragraph's text that shows, then each line of its hidden text, marked with `HIDDEN_TEXT`. A
403
+ * long hidden line is cut into pieces of `HIDDEN_PIECE` characters at most, each marked. The marks
404
+ * make the text longer than the XML it came from, so it is refused as soon as it holds more than
405
+ * the room left under the limit, not once it is built.
406
+ */
407
+ withHiddenText(shown, hidden) {
408
+ const room = this.limits.maxCharacters - this.count.characters;
409
+ const lines = shown.trim() ? [shown] : [];
410
+ // The length of the lines joined with line breaks.
411
+ let length = lines.length > 0 ? shown.length : -1;
412
+ let marked = 0;
413
+ // Where the line being marked ends, found once a line: each of its pieces starts before it, as
414
+ // `NOT_SPACE` never stops at a line end. Searched again from each piece, it took seconds.
415
+ let lineEnd = -1;
416
+ // Line by line, without splitting the text first: a run can hold millions of empty lines.
417
+ for (let at = 0;;) {
418
+ NOT_SPACE.lastIndex = at;
419
+ const first = NOT_SPACE.exec(hidden);
420
+ if (!first)
421
+ break;
422
+ const start = first.index;
423
+ if (start >= lineEnd) {
424
+ HIDDEN_LINE_END.lastIndex = start;
425
+ lineEnd = HIDDEN_LINE_END.exec(hidden)?.index ?? hidden.length;
426
+ }
427
+ let end = lineEnd;
428
+ if (end - start > HIDDEN_PIECE) {
429
+ // Cut after a space near the end of the piece, and never between the two halves of an emoji.
430
+ const window = sliceWhole(hidden.slice(start, lineEnd), HIDDEN_PIECE);
431
+ const space = window.lastIndexOf(" ");
432
+ end = start + (space > HIDDEN_PIECE * 0.8 ? space + 1 : window.length);
433
+ }
434
+ const line = `${HIDDEN_TEXT} ${hidden.slice(start, end)}`;
435
+ length += 1 + line.length;
436
+ if (length > room)
437
+ throw this.tooMuchText();
438
+ lines.push(line);
439
+ marked++;
440
+ at = end;
441
+ }
442
+ return marked === 0 ? shown : lines.join("\n");
443
+ }
444
+ /**
445
+ * Acts on a tag that has been read. `empty` is a tag that closes itself, as `<w:br/>`.
446
+ * `found`: whether the tag is `attributesTag`, and its attribute has one of the values wanted.
447
+ */
448
+ read(name, empty, found, raw) {
449
+ if (name === "mc:Fallback") {
450
+ if (!empty)
451
+ this.inFallback++;
452
+ return;
453
+ }
454
+ if (name === "/mc:Fallback") {
455
+ if (this.inFallback > 0)
456
+ this.inFallback--;
457
+ return;
458
+ }
459
+ if (this.inFallback > 0)
460
+ return;
461
+ if (name === this.paragraphTag) {
462
+ if (!empty) {
463
+ if (this.open.length >= MAX_PARAGRAPH_DEPTH) {
464
+ throw new Error(`This ${this.limits.kind} nests paragraphs more than ${MAX_PARAGRAPH_DEPTH} deep, which no document does. It may be built to exhaust the server, so it is not read.`);
465
+ }
466
+ const inCell = this.table?.cell !== undefined;
467
+ this.open.push({ slot: inCell ? -1 : this.paragraphs.length, pieces: [], hidden: undefined, length: 0, runs: 0, hiddenFrom: 0, runProperties: 0, style: undefined });
468
+ if (!inCell)
469
+ this.paragraphs.push(null);
470
+ }
471
+ }
472
+ else if (name === this.tableTag || name === this.rowTag || name === this.cellTag || name === `/${this.tableTag}` || name === `/${this.rowTag}` || name === `/${this.cellTag}`) {
473
+ this.readTable(name, empty);
474
+ }
475
+ else if (name === this.paragraphEnd) {
476
+ this.close();
477
+ this.inText = false;
478
+ this.inProperties = 0;
479
+ }
480
+ else if (name === this.textTag) {
481
+ this.inText = !empty;
482
+ }
483
+ else if (name === this.textEnd) {
484
+ this.inText = false;
485
+ }
486
+ else if (name === this.propertiesTag) {
487
+ if (!empty)
488
+ this.inProperties++;
489
+ }
490
+ else if (name === this.propertiesEnd) {
491
+ if (this.inProperties > 0)
492
+ this.inProperties--;
493
+ }
494
+ else if (this.inProperties === 0) {
495
+ if (name === this.tabTag)
496
+ this.add("\t");
497
+ else if (this.breakTags.has(name))
498
+ this.add("\n");
499
+ else if (this.word && name === "w:noBreakHyphen")
500
+ this.add("-");
501
+ else if (this.word && name === "w:sym")
502
+ this.addSymbol(raw);
503
+ else if (this.word && TABLE_PROPERTY_TAGS.has(name))
504
+ this.readTableProperty(name, empty, raw);
505
+ else if (this.word)
506
+ this.readRun(name, empty, found);
507
+ else if (name === "p:sld" && found)
508
+ this.hiddenSlide = true;
509
+ else if (name === "p:sp" || name === "/p:sp") {
510
+ this.inShape = name === "p:sp" && !empty;
511
+ this.inLeftOut = false;
512
+ }
513
+ else if (name === "p:ph" && this.inShape && this.leftOut?.has(parseAttributes(raw ?? "").type ?? "")) {
514
+ // The placeholder of the shape comes before its text (`p:nvSpPr`, then `p:txBody`).
515
+ this.inLeftOut = true;
516
+ }
517
+ }
518
+ else if (this.inProperties === 1 && this.word && raw !== undefined) {
519
+ // The paragraph's own properties; those of a change it records (`w:pPrChange`) are one level deeper.
520
+ this.readParagraphProperty(name, raw);
521
+ }
522
+ }
523
+ /** `w:pStyle`, `w:numId`, `w:ilvl` and `w:outlineLvl` of the innermost open paragraph. */
524
+ readParagraphProperty(name, raw) {
525
+ const paragraph = this.open.at(-1);
526
+ if (!paragraph)
527
+ return;
528
+ const value = parseAttributes(raw)["w:val"];
529
+ if (value === undefined)
530
+ return;
531
+ const style = (paragraph.style ??= {});
532
+ if (name === "w:pStyle")
533
+ style.styleId = value;
534
+ else if (name === "w:numId")
535
+ style.numId = value;
536
+ else if (name === "w:ilvl")
537
+ style.ilvl = Number.parseInt(value, 10) || 0;
538
+ else if (name === "w:outlineLvl")
539
+ style.outlineLevel = Number.parseInt(value, 10);
540
+ }
541
+ /**
542
+ * A symbol of a symbol font (`<w:sym w:char="F0B7"/>`). Those fonts put their characters in the
543
+ * private-use area: one that stands for a printable ASCII character is written as it, others are
544
+ * left out.
545
+ */
546
+ addSymbol(raw) {
547
+ const code = Number.parseInt(parseAttributes(raw ?? "")["w:char"] ?? "", 16);
548
+ if (!Number.isFinite(code))
549
+ return;
550
+ const plain = code >= 0xf000 ? code - 0xf000 : code;
551
+ if (plain >= 0x20 && plain <= 0x7e)
552
+ this.add(String.fromCharCode(plain));
553
+ }
554
+ /**
555
+ * The properties of the Word table row and cell that are open: `w:gridSpan` of a cell, and
556
+ * `w:gridBefore` and `w:gridAfter` of a row, the grid columns that the row leaves empty before its
557
+ * first cell and after its last. Those of a change the properties record (`w:tcPrChange`,
558
+ * `w:trPrChange`) are the properties before the change, one level deeper, and are not read.
559
+ */
560
+ readTableProperty(name, empty, raw) {
561
+ const table = this.table;
562
+ if (!table || table.depth !== 1)
563
+ return;
564
+ if (name === "w:trPr" || name === "w:tcPr") {
565
+ if (!empty)
566
+ table.properties++;
567
+ return;
568
+ }
569
+ if (name === "/w:trPr" || name === "/w:tcPr") {
570
+ if (table.properties > 0)
571
+ table.properties--;
572
+ return;
573
+ }
574
+ if (table.properties > 1)
575
+ return;
576
+ const columns = Math.min(MAX_CELL_SPAN, Math.max(0, Number.parseInt(parseAttributes(raw ?? "")["w:val"] ?? "", 10) || 0));
577
+ if (name === "w:gridSpan") {
578
+ if (table.cell)
579
+ table.span = Math.max(1, columns);
580
+ }
581
+ else if (name === "w:gridBefore") {
582
+ // Once, before the row's first cell.
583
+ if (table.row?.length === 0 && !table.cell)
584
+ for (let index = 0; index < columns; index++)
585
+ this.addCell(table.row, "");
586
+ }
587
+ else if (table.row && !table.cell) {
588
+ table.after = columns;
589
+ }
590
+ }
591
+ /**
592
+ * The start and end of tables, rows and cells. A table becomes one paragraph, written when it
593
+ * closes: a line for each row, as `| cell | cell | |`, with its empty cells, as the PDF extractor
594
+ * writes rows. A Word cell that spans grid columns is followed by an empty cell for each column
595
+ * past the first, and a row that leaves grid columns empty before its first cell or after its
596
+ * last has an empty cell for each, so that every row keeps its columns. A cell that continues a
597
+ * merged cell (`w:vMerge` in Word; in PowerPoint, where the cells a merged cell covers are in the
598
+ * XML already, `hMerge` and `vMerge`) is written in its column: Word and PowerPoint leave it
599
+ * empty, and the text another program left in it is kept. A table inside a cell is read as text
600
+ * of that cell.
601
+ */
602
+ readTable(name, empty) {
603
+ if (name === this.tableTag) {
604
+ if (empty)
605
+ return;
606
+ if (this.table) {
607
+ this.table.depth++;
608
+ return;
609
+ }
610
+ // Inside a paragraph of a cell of no table (a malformed file): the table is that paragraph's.
611
+ this.table = { slot: this.paragraphs.length, depth: 1, rows: [], row: undefined, cell: undefined, span: 1, after: 0, properties: 0 };
612
+ this.paragraphs.push(null);
613
+ return;
614
+ }
615
+ const table = this.table;
616
+ if (!table)
617
+ return;
618
+ if (name === `/${this.tableTag}`) {
619
+ if (table.depth > 1)
620
+ table.depth--;
621
+ else
622
+ this.closeTable();
623
+ return;
624
+ }
625
+ if (table.depth !== 1)
626
+ return;
627
+ if (name === this.rowTag) {
628
+ this.closeRow();
629
+ table.row = empty ? undefined : [];
630
+ table.properties = 0;
631
+ }
632
+ else if (name === `/${this.rowTag}`) {
633
+ this.closeRow();
634
+ }
635
+ else if (name === this.cellTag) {
636
+ this.closeCell();
637
+ table.span = 1;
638
+ table.properties = 0;
639
+ table.cell = [];
640
+ if (empty)
641
+ this.closeCell();
642
+ }
643
+ else if (name === `/${this.cellTag}`) {
644
+ this.closeCell();
645
+ }
646
+ }
647
+ /**
648
+ * Adds a cell to a row. Each cell is counted as a paragraph, empty or not, and its separator as
649
+ * text: a table of millions of empty cells is bounded as a document of millions of paragraphs is.
650
+ */
651
+ addCell(row, text) {
652
+ if (++this.count.paragraphs > MAX_OFFICE_PARAGRAPHS) {
653
+ throw new Error(`This ${this.limits.kind} has more than ${MAX_OFFICE_PARAGRAPHS.toLocaleString("en-US")} paragraphs and table cells, more than a document holds. It may be built to exhaust the server, so it is not read.`);
654
+ }
655
+ this.count.characters += 3;
656
+ if (this.count.characters > this.limits.maxCharacters)
657
+ throw this.tooMuchText();
658
+ row.push(text);
659
+ }
660
+ /** Ends the table cell that is open, if any: its paragraphs become one cell of the row. */
661
+ closeCell() {
662
+ const table = this.table;
663
+ if (!table?.cell)
664
+ return;
665
+ // Paragraphs of the cell left open (a malformed file) give their text to it first.
666
+ while (this.open.length > 0 && this.open.at(-1).slot === -1)
667
+ this.close();
668
+ const text = cellText(table.cell.join(" "));
669
+ table.cell = undefined;
670
+ const row = (table.row ??= []);
671
+ const cells = this.word ? table.span : 1;
672
+ for (let index = 0; index < cells; index++)
673
+ this.addCell(row, index === 0 ? text : "");
674
+ }
675
+ /** Ends the table row that is open, if any, with an empty cell for each grid column it leaves empty after its last cell. */
676
+ closeRow() {
677
+ const table = this.table;
678
+ if (!table)
679
+ return;
680
+ this.closeCell();
681
+ const row = table.row;
682
+ if (row && row.length > 0) {
683
+ for (let index = 0; index < table.after; index++)
684
+ this.addCell(row, "");
685
+ table.rows.push(row);
686
+ }
687
+ table.row = undefined;
688
+ table.after = 0;
689
+ }
690
+ /** Ends the table: its rows become the text of its paragraph. Also when the file ends inside it. */
691
+ closeTable() {
692
+ const table = this.table;
693
+ if (!table)
694
+ return;
695
+ this.closeRow();
696
+ this.table = undefined;
697
+ if (table.rows.some((row) => row.some((cell) => cell !== ""))) {
698
+ const text = table.rows.map((row) => `| ${row.join(" | ")} |`).join("\n");
699
+ this.paragraphs[table.slot] = text;
700
+ }
701
+ else if (table.slot === this.paragraphs.length - 1) {
702
+ this.paragraphs.pop();
703
+ }
704
+ else {
705
+ this.paragraphs[table.slot] = "";
706
+ }
707
+ }
708
+ /**
709
+ * Follows the runs of a Word paragraph, to tell the text of a hidden run: `<w:vanish/>` in the
710
+ * run's own properties, not in those of a change it records (`w:rPrChange`), one level deeper.
711
+ * A run inside a hidden run (the text of a ruby) is hidden too, and the run around it stays
712
+ * hidden after it. `off`: the `w:vanish` turns hiding off.
713
+ */
714
+ readRun(name, empty, off) {
715
+ const paragraph = this.open.at(-1);
716
+ if (!paragraph)
717
+ return;
718
+ if (name === "w:r") {
719
+ if (empty)
720
+ return;
721
+ paragraph.runs++;
722
+ paragraph.runProperties = 0;
723
+ }
724
+ else if (name === "/w:r") {
725
+ if (paragraph.runs > 0) {
726
+ if (paragraph.hiddenFrom === paragraph.runs)
727
+ paragraph.hiddenFrom = 0;
728
+ paragraph.runs--;
729
+ }
730
+ paragraph.runProperties = 0;
731
+ }
732
+ else if (name === "w:rPr") {
733
+ if (!empty && paragraph.runs > 0)
734
+ paragraph.runProperties++;
735
+ }
736
+ else if (name === "/w:rPr") {
737
+ if (paragraph.runProperties > 0)
738
+ paragraph.runProperties--;
739
+ }
740
+ else if (name === "w:vanish" && paragraph.runProperties === 1) {
741
+ if (!off) {
742
+ if (paragraph.hiddenFrom === 0)
743
+ paragraph.hiddenFrom = paragraph.runs;
744
+ }
745
+ else if (paragraph.hiddenFrom === paragraph.runs) {
746
+ paragraph.hiddenFrom = 0;
747
+ }
748
+ }
749
+ }
750
+ }
751
+ /**
752
+ * Text of each paragraph of Office XML, in the order the paragraphs start. See `OfficeText`. The
753
+ * XML may be given in pieces, as it is unpacked.
754
+ */
755
+ export function officeXmlParagraphs(xml, prefix) {
756
+ const text = new OfficeText(prefix);
757
+ for (const piece of typeof xml === "string" ? [xml] : xml)
758
+ text.write(piece);
759
+ return text.texts();
760
+ }
761
+ /** The most XML read from one DOCX or PPTX, whatever its size: a document of thousands of pages. */
762
+ const MAX_OFFICE_XML = 128 * 1024 * 1024;
763
+ /**
764
+ * The parts read from an Office file unpack to less than its size: pictures, fonts and styles stay
765
+ * packed. A generated report that repeats one paragraph 50,000 times unpacks to 90 times its size.
766
+ * A file that unpacks to more than this many times its size, past the first 16 MB, is taken for a
767
+ * zip bomb, as Apache POI does.
768
+ */
769
+ const MAX_OFFICE_EXPANSION = 100;
770
+ const OFFICE_ALLOWANCE = 16 * 1024 * 1024;
771
+ const megabytes = (size) => `${Math.round(size / 1024 / 1024)} MB`;
772
+ /** The most a small part (`OfficeParts.small`) may hold. Styles of a large document take about 1 MB. */
773
+ const MAX_SMALL_PART = 8 * 1024 * 1024;
774
+ /** Thrown inside `small` when a part is larger than it may be: the part is then left out. */
775
+ class PartTooLarge extends Error {
776
+ }
777
+ /**
778
+ * Reads the parts of one Office file, each a piece at a time as it is unpacked, counting what is
779
+ * unpacked: a file that grows far past its size is refused as it grows, before that much is in
780
+ * memory. The parsing is paused every few milliseconds, and other requests get a turn. The
781
+ * unpacking is not: JSZip inflates and decodes a whole deflated block (up to about 16 MB of XML)
782
+ * in one turn before any of it is handed out, and what it hands out once paused is held, and
783
+ * written in the slices after the pause, which costs memory for that block. Reading a file in a
784
+ * child process (`createIsolatedExtractors`) is what bounds both for files from users.
785
+ */
786
+ export function officeReader(archive, kind, size, input) {
787
+ const limit = Math.min(MAX_OFFICE_XML, Math.max(OFFICE_ALLOWANCE, size * MAX_OFFICE_EXPANSION));
788
+ const refusal = limit === MAX_OFFICE_XML
789
+ ? `This ${kind} unpacks to more than ${megabytes(limit)} of XML, more than is read from one file. Save it as text or PDF, and attach that.`
790
+ : `This ${kind} unpacks to more than ${megabytes(limit)}, over ${MAX_OFFICE_EXPANSION} times its size. A file that grows that much is not read: it may be a zip bomb. Save it as text or PDF, and attach that.`;
791
+ const maxTextBytes = input?.maxTextBytes ?? Number.POSITIVE_INFINITY;
792
+ // A character is at least one byte: a text with more characters than the limit is past it.
793
+ const limits = {
794
+ kind,
795
+ maxCharacters: Math.min(MAX_OFFICE_CHARACTERS, maxTextBytes),
796
+ byTextLimit: maxTextBytes < MAX_OFFICE_CHARACTERS,
797
+ };
798
+ // One count for the whole file, across its parts.
799
+ const count = { characters: 0, paragraphs: 0 };
800
+ const slicer = new TimeSlicer(input?.signal);
801
+ let unpacked = 0;
802
+ /** Feeds a part to `write`, then calls `done`; false when the part is missing. */
803
+ const stream = (name, write, done = () => undefined) => new Promise((resolve, reject) => {
804
+ const file = archive.file(name);
805
+ if (!file) {
806
+ resolve(false);
807
+ return;
808
+ }
809
+ let stopped = false;
810
+ let pausing = false;
811
+ let ended = false;
812
+ /**
813
+ * The pieces that came while the stream was paused, and the next one to write. Pausing JSZip
814
+ * does not stop the block it is unpacking: it hands out the rest of it, up to 16 MB of XML from
815
+ * 16 KB of a deflated part, in the same turn. Those pieces wait for the next slice.
816
+ */
817
+ let waiting = [];
818
+ let next = 0;
819
+ const unzip = file.internalStream("string");
820
+ const stop = (error) => {
821
+ if (stopped)
822
+ return;
823
+ stopped = true;
824
+ waiting = [];
825
+ unzip.pause();
826
+ reject(error);
827
+ };
828
+ const finish = () => {
829
+ try {
830
+ done();
831
+ resolve(true);
832
+ }
833
+ catch (error) {
834
+ stop(error);
835
+ }
836
+ };
837
+ /** Pauses, then writes the pieces that came meanwhile, a slice at a time, and goes on with the stream. */
838
+ const pauseThenGoOn = async () => {
839
+ try {
840
+ do {
841
+ await slicer.pauseNow();
842
+ while (!stopped && next < waiting.length && !slicer.due)
843
+ write(waiting[next++]);
844
+ if (stopped)
845
+ return;
846
+ } while (next < waiting.length);
847
+ }
848
+ catch (error) {
849
+ stop(error);
850
+ return;
851
+ }
852
+ waiting = [];
853
+ next = 0;
854
+ pausing = false;
855
+ if (ended)
856
+ finish();
857
+ else
858
+ unzip.resume();
859
+ };
860
+ unzip
861
+ .on("data", (chunk) => {
862
+ if (stopped)
863
+ return;
864
+ if (input?.signal?.aborted) {
865
+ stop(input.signal.reason);
866
+ return;
867
+ }
868
+ // Counted as it comes, written or not: a file that grows past the limit is refused at once.
869
+ unpacked += chunk.length;
870
+ if (unpacked > limit) {
871
+ stop(new Error(refusal));
872
+ return;
873
+ }
874
+ if (pausing) {
875
+ waiting.push(chunk);
876
+ return;
877
+ }
878
+ try {
879
+ write(chunk);
880
+ }
881
+ catch (error) {
882
+ stop(error);
883
+ return;
884
+ }
885
+ if (slicer.due) {
886
+ pausing = true;
887
+ unzip.pause();
888
+ void pauseThenGoOn();
889
+ }
890
+ })
891
+ .on("error", stop)
892
+ .on("end", () => {
893
+ ended = true;
894
+ if (!stopped && !pausing)
895
+ finish();
896
+ })
897
+ .resume();
898
+ });
899
+ return {
900
+ limits,
901
+ count,
902
+ stream: (name, write) => stream(name, write),
903
+ async paragraphs(name, prefix, options) {
904
+ const text = new OfficeText(prefix, limits, count, options);
905
+ let result = { paragraphs: [], hiddenSlide: false };
906
+ await stream(name, (piece) => text.write(piece), () => {
907
+ result = { paragraphs: text.texts(), hiddenSlide: text.hiddenSlide };
908
+ });
909
+ return result;
910
+ },
911
+ async small(name, maxCharacters = MAX_SMALL_PART) {
912
+ const pieces = [];
913
+ let length = 0;
914
+ try {
915
+ const found = await stream(name, (piece) => {
916
+ length += piece.length;
917
+ if (length > maxCharacters)
918
+ throw new PartTooLarge();
919
+ pieces.push(piece);
920
+ });
921
+ return found ? pieces.join("") : undefined;
922
+ }
923
+ catch (error) {
924
+ if (error instanceof PartTooLarge)
925
+ return undefined;
926
+ throw error;
927
+ }
928
+ },
929
+ };
930
+ }
931
+ /**
932
+ * The parts an Office file may have, at most. A deck of 2,000 slides with notes and pictures has
933
+ * about 12,000. JSZip reads the header of every part into memory before any part is unpacked:
934
+ * about 2 KB each, and 300,000 empty parts took over 500 MB.
935
+ */
936
+ const MAX_ZIP_ENTRIES = 20_000;
937
+ /**
938
+ * The extra fields the parts of an Office file may have, together. Office writes none, other ZIP
939
+ * programs one to three for each part. JSZip keeps about 250 bytes for each field of 4 bytes: a
940
+ * file of 4 MB made only of them took 250 MB.
941
+ */
942
+ const MAX_ZIP_EXTRA_FIELDS = 4 * MAX_ZIP_ENTRIES;
943
+ /**
944
+ * The bytes JSZip may turn into text, or go through one by one, from the directory of an Office
945
+ * file: names, comments, and the data of three kinds of extra field (see ZipDirectory). The Office
946
+ * files we tried had at most 68 KB. A name can be decoded from the same bytes for many parts, and
947
+ * the data of a field can run over the records after it, so the size of the file does not bound
948
+ * them: 2,000 parts of a 0.17 MB file took JSZip over 256 MB. A file just under this limit and the
949
+ * two above took JSZip under 0.5 s and 140 MB.
950
+ */
951
+ const MAX_ZIP_TEXT_BYTES = 8 * 1024 * 1024;
952
+ export async function loadZip(bytes, kind) {
953
+ const JSZip = (await importPeer("jszip", () => import("jszip"), "Reading DOCX, PPTX and XLSX files needs the optional dependency \"jszip\".")).default;
954
+ // The directory is read first, as JSZip will read it: the count of parts it gives may say
955
+ // anything.
956
+ const directory = readZipDirectory(bytes, { parts: MAX_ZIP_ENTRIES, extraFields: MAX_ZIP_EXTRA_FIELDS, textBytes: MAX_ZIP_TEXT_BYTES });
957
+ if (directory?.endless) {
958
+ throw new Error(`This ${kind} ends with a ZIP64 record that cannot be read, and reading it could hold the server without end. It may be built to exhaust the server, so it is not read.`);
959
+ }
960
+ if (directory && directory.parts > MAX_ZIP_ENTRIES) {
961
+ throw new Error(`This ${kind} has more than ${MAX_ZIP_ENTRIES.toLocaleString("en-US")} parts, more than an Office document has. It may be built to exhaust the server, so it is not read.`);
962
+ }
963
+ // A mass of extra fields, or of names, comments and field data: no Office program writes either.
964
+ if (directory && (directory.extraFields > MAX_ZIP_EXTRA_FIELDS || directory.textBytes > MAX_ZIP_TEXT_BYTES)) {
965
+ throw new Error(`This ${kind} lists its parts in a way that no Office program does: reading the list would take far more memory or time than an Office document needs. It may be built to exhaust the server, so it is not read.`);
966
+ }
967
+ return JSZip.loadAsync(bytes);
968
+ }
969
+ /**
970
+ * Opens an Office file, or refuses it in words for its user: an Office file of before 2007, or one
971
+ * protected by a password, is not a ZIP archive but a compound file, and JSZip says only that it
972
+ * found no ZIP in it.
973
+ */
974
+ export async function openOffice(bytes, kind) {
975
+ if (bytes[0] === 0xd0 && bytes[1] === 0xcf && bytes[2] === 0x11 && bytes[3] === 0xe0)
976
+ throw new Error(LEGACY_OFFICE);
977
+ return loadZip(bytes, kind);
978
+ }
979
+ /** The parts of a DOCX read after the document itself, in this order, each under a heading of its own. */
980
+ const WORD_SECTIONS = [
981
+ { part: /^word\/footnotes\.xml$/i, title: "Footnotes" },
982
+ { part: /^word\/endnotes\.xml$/i, title: "Endnotes" },
983
+ { part: /^word\/comments\.xml$/i, title: "Comments" },
984
+ { part: /^word\/header\d+\.xml$/i, title: "Header" },
985
+ { part: /^word\/footer\d+\.xml$/i, title: "Footer" },
986
+ ];
987
+ /** A part's number, for an order that follows it: header2.xml before header10.xml. */
988
+ const partNumber = (name) => Number(/(\d+)\.xml$/i.exec(name)?.[1] ?? 0);
989
+ /**
990
+ * Word files. The document's paragraphs come first: a heading as a Markdown heading ("## 2.1
991
+ * Scope"), each paragraph with the list number Word shows before it, and each table as rows of
992
+ * `| cell | cell |`, empty cells kept. Then the footnotes, endnotes, comments, headers and footers,
993
+ * each under a heading of its own; a header or footer that repeats one already read is left out.
994
+ */
995
+ export const docx = async (bytes, input) => {
996
+ input?.signal?.throwIfAborted();
997
+ const archive = await openOffice(bytes, "DOCX");
998
+ input?.signal?.throwIfAborted();
999
+ if (!archive.file("word/document.xml"))
1000
+ throw new Error("This DOCX does not contain word/document.xml.");
1001
+ const parts = Object.keys(archive.files);
1002
+ const extra = WORD_SECTIONS.flatMap(({ part, title }) => parts.filter((name) => part.test(name)).sort((left, right) => partNumber(left) - partNumber(right)).map((name) => ({ name, title })));
1003
+ const read = officeReader(archive, "DOCX", bytes.byteLength, input);
1004
+ const numbering = new WordNumbering(await read.small("word/styles.xml"), await read.small("word/numbering.xml"));
1005
+ const total = 1 + extra.length;
1006
+ const sections = [(await read.paragraphs("word/document.xml", "w", { numbering })).paragraphs.join("\n")];
1007
+ input?.onProgress?.({ done: 1, total, unit: "parts" });
1008
+ const seen = new Set();
1009
+ for (const [index, { name, title }] of extra.entries()) {
1010
+ const text = (await read.paragraphs(name, "w")).paragraphs.join("\n");
1011
+ input?.onProgress?.({ done: index + 2, total, unit: "parts" });
1012
+ if (!text.trim() || seen.has(text))
1013
+ continue;
1014
+ seen.add(text);
1015
+ sections.push(`# ${title}\n${text}`);
1016
+ }
1017
+ return { text: sections.filter(Boolean).join("\n\n") };
1018
+ };
1019
+ /** Speaker notes of a slide are written after this line. */
1020
+ export const SPEAKER_NOTES = "[Speaker notes]";
1021
+ /**
1022
+ * The slide parts of a deck, in the order of the slide show: the list in `ppt/presentation.xml`,
1023
+ * through its relationships. A deck reordered by a tool that does not rename the parts has them in
1024
+ * another order than their names. Without that list, the parts in the order of their numbers.
1025
+ */
1026
+ async function slideOrder(read, parts) {
1027
+ const byName = parts.filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name)).sort((left, right) => partNumber(left) - partNumber(right));
1028
+ const [presentation, relationshipsXml] = [await read.small("ppt/presentation.xml"), await read.small("ppt/_rels/presentation.xml.rels")];
1029
+ if (!presentation || !relationshipsXml)
1030
+ return byName;
1031
+ const relationships = readRelationships(relationshipsXml, "ppt");
1032
+ const ordered = [];
1033
+ const listed = new Set();
1034
+ const existing = new Set(parts);
1035
+ let inList = false;
1036
+ readXml(presentation, {
1037
+ open(name, attributes) {
1038
+ if (name === "p:sldIdLst")
1039
+ inList = true;
1040
+ else if (inList && name === "p:sldId") {
1041
+ const target = relationships.get(attributes["r:id"] ?? "")?.target;
1042
+ if (target && existing.has(target) && !listed.has(target)) {
1043
+ listed.add(target);
1044
+ ordered.push(target);
1045
+ }
1046
+ }
1047
+ },
1048
+ close(name) {
1049
+ if (name === "p:sldIdLst")
1050
+ inList = false;
1051
+ },
1052
+ });
1053
+ return ordered.length > 0 ? ordered : byName;
1054
+ }
1055
+ /** The notes part of a slide, from the slide's relationships, or undefined. */
1056
+ async function notesOf(read, slide) {
1057
+ const folder = slide.slice(0, slide.lastIndexOf("/"));
1058
+ const file = slide.slice(slide.lastIndexOf("/") + 1);
1059
+ const relationships = readRelationships(await read.small(`${folder}/_rels/${file}.rels`), folder);
1060
+ for (const { target, type, external } of relationships.values())
1061
+ if (!external && type.endsWith("/notesSlide"))
1062
+ return target;
1063
+ return undefined;
1064
+ }
1065
+ /**
1066
+ * PowerPoint files: a "## Slide N" section for each slide, numbered in the order of the slide show,
1067
+ * with its text, its tables as rows of `| cell | cell |`, and its speaker notes after
1068
+ * `SPEAKER_NOTES`. A slide the slide show skips says so in its heading.
1069
+ */
1070
+ export const pptx = async (bytes, input) => {
1071
+ input?.signal?.throwIfAborted();
1072
+ const archive = await openOffice(bytes, "PPTX");
1073
+ input?.signal?.throwIfAborted();
1074
+ const read = officeReader(archive, "PPTX", bytes.byteLength, input);
1075
+ const names = await slideOrder(read, Object.keys(archive.files));
1076
+ if (names.length === 0)
1077
+ throw new Error("This PPTX does not contain any slides.");
1078
+ const slides = [];
1079
+ for (const [index, name] of names.entries()) {
1080
+ const { paragraphs, hiddenSlide } = await read.paragraphs(name, "a");
1081
+ const notesPart = await notesOf(read, name);
1082
+ // The notes page holds the slide's number, and may hold the date, a header and a footer, as
1083
+ // text of placeholders of their own: those are left out, and a note that is only a number is kept.
1084
+ const notes = notesPart ? (await read.paragraphs(notesPart, "a", { notesPage: true })).paragraphs : [];
1085
+ const text = paragraphs.join("\n");
1086
+ // A hidden slide keeps its text, and says that the slide show skips it.
1087
+ slides.push(`## Slide ${index + 1}${hiddenSlide ? ` ${HIDDEN_SLIDE}` : ""}\n${text || "[No text on this slide]"}${notes.length > 0 ? `\n${SPEAKER_NOTES}\n${notes.join("\n")}` : ""}`);
1088
+ input?.onProgress?.({ done: index + 1, total: names.length, unit: "parts" });
1089
+ }
1090
+ return { text: slides.join("\n\n"), pages: names.length };
1091
+ };
1092
+ //# sourceMappingURL=office.js.map