llm-large-files 0.2.0 → 0.3.5

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 (81) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +52 -6
  3. package/dist/extract.d.ts +13 -6
  4. package/dist/extract.d.ts.map +1 -1
  5. package/dist/extract.js +27 -6
  6. package/dist/extract.js.map +1 -1
  7. package/dist/gemini/chat.d.ts +48 -4
  8. package/dist/gemini/chat.d.ts.map +1 -1
  9. package/dist/gemini/chat.js +108 -24
  10. package/dist/gemini/chat.js.map +1 -1
  11. package/dist/gemini/endpoints.d.ts +17 -0
  12. package/dist/gemini/endpoints.d.ts.map +1 -1
  13. package/dist/gemini/endpoints.js +16 -2
  14. package/dist/gemini/endpoints.js.map +1 -1
  15. package/dist/gemini/generate.d.ts +34 -4
  16. package/dist/gemini/generate.d.ts.map +1 -1
  17. package/dist/gemini/generate.js +47 -7
  18. package/dist/gemini/generate.js.map +1 -1
  19. package/dist/gemini/index.d.ts +3 -3
  20. package/dist/gemini/index.d.ts.map +1 -1
  21. package/dist/gemini/index.js +2 -2
  22. package/dist/gemini/index.js.map +1 -1
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +1 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/library.d.ts +31 -1
  28. package/dist/library.d.ts.map +1 -1
  29. package/dist/library.js +44 -6
  30. package/dist/library.js.map +1 -1
  31. package/dist/pdf-layout.d.ts +7 -0
  32. package/dist/pdf-layout.d.ts.map +1 -1
  33. package/dist/pdf-layout.js +32 -2
  34. package/dist/pdf-layout.js.map +1 -1
  35. package/dist/pdf-pages.d.ts +45 -0
  36. package/dist/pdf-pages.d.ts.map +1 -0
  37. package/dist/pdf-pages.js +336 -0
  38. package/dist/pdf-pages.js.map +1 -0
  39. package/dist/pdf-pictures.d.ts +20 -0
  40. package/dist/pdf-pictures.d.ts.map +1 -0
  41. package/dist/pdf-pictures.js +336 -0
  42. package/dist/pdf-pictures.js.map +1 -0
  43. package/dist/plan.d.ts +13 -3
  44. package/dist/plan.d.ts.map +1 -1
  45. package/dist/plan.js +22 -17
  46. package/dist/plan.js.map +1 -1
  47. package/dist/search.d.ts +9 -0
  48. package/dist/search.d.ts.map +1 -1
  49. package/dist/search.js +41 -0
  50. package/dist/search.js.map +1 -1
  51. package/dist/stores.d.ts +7 -1
  52. package/dist/stores.d.ts.map +1 -1
  53. package/dist/stores.js +37 -5
  54. package/dist/stores.js.map +1 -1
  55. package/dist/tools.d.ts +11 -0
  56. package/dist/tools.d.ts.map +1 -1
  57. package/dist/tools.js +145 -13
  58. package/dist/tools.js.map +1 -1
  59. package/dist/types.d.ts +57 -3
  60. package/dist/types.d.ts.map +1 -1
  61. package/docs/api.md +59 -17
  62. package/docs/configuration.md +351 -5
  63. package/docs/getting-started.md +50 -3
  64. package/docs/how-it-works.md +73 -4
  65. package/docs/security.md +39 -4
  66. package/package.json +7 -2
  67. package/src/extract.ts +34 -8
  68. package/src/gemini/chat.ts +145 -30
  69. package/src/gemini/endpoints.ts +34 -2
  70. package/src/gemini/generate.ts +63 -9
  71. package/src/gemini/index.ts +3 -3
  72. package/src/index.ts +2 -2
  73. package/src/library.ts +74 -7
  74. package/src/pdf-layout.ts +37 -1
  75. package/src/pdf-pages.ts +315 -0
  76. package/src/pdf-pictures.ts +324 -0
  77. package/src/plan.ts +36 -16
  78. package/src/search.ts +37 -0
  79. package/src/stores.ts +39 -6
  80. package/src/tools.ts +147 -13
  81. package/src/types.ts +57 -3
package/src/library.ts CHANGED
@@ -41,6 +41,18 @@ export type LargeFilesOptions = {
41
41
  maxUploadBytes?: number;
42
42
  /** Override or add text extractors per format. */
43
43
  extractors?: Partial<Record<DocumentFormat, Extractor>>;
44
+ /**
45
+ * Formats whose uploaded file is kept in the store next to its text, for example `["pdf"]`.
46
+ * Empty by default: a kept file takes disk space, up to the upload limit, until the document
47
+ * expires. A store without `putOriginal` keeps none.
48
+ */
49
+ keepOriginals?: DocumentFormat[];
50
+ /**
51
+ * A PDF without any text (a scan) has nothing to search, and was always refused. When its
52
+ * original is kept, its pages can be shown to the model instead, so one of up to this many pages
53
+ * is accepted. Defaults to 30. 0 refuses every PDF without text, as before.
54
+ */
55
+ scannedPdfPages?: number;
44
56
  /** How many parsed documents to keep in memory for repeated tool calls. Defaults to 6. */
45
57
  cacheSize?: number;
46
58
  /** Clock override, for tests. */
@@ -58,12 +70,29 @@ export type IngestInput = {
58
70
  /** Access options. When a document has an owner, only that owner can use it. */
59
71
  export type AccessOptions = { owner?: string };
60
72
 
73
+ export type PrepareOptions = AccessOptions & {
74
+ /**
75
+ * Say that your tool loop can pass files to the model (see `ToolOptions.viewPages`). The result
76
+ * then lists the PDFs whose pages can be shown in `viewable`, and the instruction and the cards
77
+ * tell the model about `view_pages`. Without it, the result is that of 0.2.0.
78
+ */
79
+ viewPages?: boolean;
80
+ };
81
+
61
82
  export type ToolOptions = {
62
83
  /** Enables `analyze_whole_document`, which reads the entire file in parts. */
63
84
  generate?: GenerateText;
64
85
  /** Progress of whole-document reads, for status messages. */
65
86
  onProgress?: ProgressListener;
66
87
  signal?: AbortSignal;
88
+ /**
89
+ * Offers `view_pages`, which hands the model real pages of a PDF whose original file is kept
90
+ * (see `keepOriginals`). The pages come back as a file, so turn this on only when your loop
91
+ * runs tools with `executeWithFiles` and sends the files to the model. `true` offers it for the
92
+ * documents passed to `tools`; a list offers it for exactly those documents, which may include
93
+ * PDFs that are not searched because their text is already in the prompt.
94
+ */
95
+ viewPages?: boolean | DocumentMeta[];
67
96
  };
68
97
 
69
98
  export interface LargeFiles {
@@ -73,6 +102,8 @@ export interface LargeFiles {
73
102
  /** Extracts, normalizes, profiles, and stores a file. Throws a user-readable Error on bad input. */
74
103
  ingest(input: IngestInput): Promise<DocumentMeta>;
75
104
  getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
105
+ /** The uploaded file itself, when it was kept (see `keepOriginals`). Treat the bytes as read-only. */
106
+ getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>;
76
107
  delete(id: string, access?: AccessOptions): Promise<boolean>;
77
108
  /** Removes expired documents from the store. Returns how many were removed. */
78
109
  sweep(): Promise<number>;
@@ -80,7 +111,7 @@ export interface LargeFiles {
80
111
  * Plans one model request: which documents go in whole and which become searchable cards.
81
112
  * `base` is the size of everything else in the request (messages, system prompt, other files).
82
113
  */
83
- prepare(ids: string[], base: { tokens: number; bytes: number }, access?: AccessOptions): Promise<PreparedContext>;
114
+ prepare(ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext>;
84
115
  /** Tools scoped to these documents. Pass `generate` to enable whole-document analysis. */
85
116
  tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
86
117
  }
@@ -130,6 +161,10 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
130
161
  const now = options.now ?? (() => new Date());
131
162
  const cacheSize = Math.max(1, options.cacheSize ?? 6);
132
163
  const cache = new Map<string, SearchableDocument>();
164
+ const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
165
+ const scannedPdfPages = Math.max(0, Math.trunc(options.scannedPdfPages ?? 30));
166
+ /** Whether the uploaded file of a document of this format is kept. */
167
+ const keeps = (format: DocumentFormat) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
133
168
 
134
169
  async function load(id: string): Promise<SearchableDocument | undefined> {
135
170
  const cached = cache.get(id);
@@ -168,13 +203,20 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
168
203
  throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
169
204
  }
170
205
  let format = detectFormat(name, mimeType);
171
- const extracted = await extractText(input.bytes, { name, mimeType, format }, options.extractors);
206
+ const extracted = await extractText(input.bytes, {
207
+ name,
208
+ mimeType,
209
+ format,
210
+ // A scan is worth storing only if its pages can be shown later: that needs the file itself.
211
+ ...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
212
+ }, options.extractors);
172
213
  const { text, wrapped } = wrapLongLines(normalizeText(extracted.text));
173
214
  if (!text.trim()) throw new Error(`${name} did not contain any text.`);
174
215
  const lines = text.split("\n");
175
216
  if (text.endsWith("\n")) lines.pop();
176
217
  if (format === "text" && looksLikeLog(lines)) format = "log";
177
218
  const created = now();
219
+ const keepOriginal = keeps(format);
178
220
  const meta: DocumentMeta = {
179
221
  id: `doc_${randomUUID().replaceAll("-", "")}`,
180
222
  ...(input.owner !== undefined ? { owner: input.owner } : {}),
@@ -188,17 +230,31 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
188
230
  estimatedTokens: estimateTokens(text),
189
231
  wrappedLines: wrapped,
190
232
  ...(extracted.pages ? { pages: extracted.pages } : {}),
233
+ ...(keepOriginal ? { originalKept: true } : {}),
191
234
  outline: buildOutline(lines, format),
192
235
  ...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
193
236
  createdAt: created.toISOString(),
194
237
  expiresAt: new Date(created.getTime() + ttlMs).toISOString(),
195
238
  };
196
- await options.store.put({ meta, text });
239
+ try {
240
+ // The file first, the document last: a document is there once its metadata is.
241
+ if (keepOriginal) await options.store.putOriginal!(meta.id, input.bytes);
242
+ await options.store.put({ meta, text });
243
+ } catch (error) {
244
+ // Do not leave a file of up to the upload limit behind for a document that does not exist.
245
+ if (keepOriginal) await options.store.delete(meta.id).catch(() => undefined);
246
+ throw error;
247
+ }
197
248
  return meta;
198
249
  },
199
250
 
200
251
  getMeta: metaFor,
201
252
 
253
+ async getOriginal(id, access) {
254
+ const meta = await metaFor(id, access);
255
+ return meta?.originalKept ? options.store.getOriginal?.(id) : undefined;
256
+ },
257
+
202
258
  async delete(id, access) {
203
259
  if (!await metaFor(id, access)) return false;
204
260
  cache.delete(id);
@@ -221,20 +277,31 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
221
277
  }
222
278
  const plan = planDocuments(documents.map((document) => document.meta), budget, base);
223
279
  const inline = new Set(plan.inline.map((meta) => meta.id));
280
+ // Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
281
+ const viewable = access?.viewPages && options.store.getOriginal
282
+ ? documents.map((document) => document.meta).filter((meta) => meta.format === "pdf" && meta.originalKept)
283
+ : [];
284
+ const shown = new Set(viewable.map((meta) => meta.id));
224
285
  const blocks = new Map<string, string>();
225
286
  for (const document of documents) {
226
- blocks.set(document.meta.id, inline.has(document.meta.id) ? renderInline(document) : renderCard(document));
287
+ const { id } = document.meta;
288
+ blocks.set(id, inline.has(id) ? renderInline(document) : renderCard(document, shown.has(id)));
227
289
  }
228
- return { plan, blocks, instruction: documentToolsInstruction(plan.searchable), missing };
290
+ return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable), missing, viewable };
229
291
  },
230
292
 
231
293
  tools(documents, toolOptions = {}) {
294
+ const { viewPages, ...rest } = toolOptions;
295
+ const loadOriginal = options.store.getOriginal?.bind(options.store);
296
+ const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
297
+ .filter((meta) => meta.format === "pdf" && meta.originalKept);
232
298
  return createDocumentTools({
233
299
  load,
234
300
  documentIds: documents.map((meta) => meta.id),
235
- names: Object.fromEntries(documents.map((meta) => [meta.id, meta.name])),
301
+ names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, meta.name])),
236
302
  budget,
237
- ...toolOptions,
303
+ ...(loadOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal } : {}),
304
+ ...rest,
238
305
  });
239
306
  },
240
307
  };
package/src/pdf-layout.ts CHANGED
@@ -719,6 +719,37 @@ function tablesInLines(lines: Line[], depth: number): Table[] {
719
719
 
720
720
  // ---------- The page ----------
721
721
 
722
+ /** `[left, top, right, bottom]` in the coordinates the viewport transform gives. */
723
+ export type LayoutBox = [number, number, number, number];
724
+
725
+ /** Where a table lies on the page: the box around its text, widened by about one line for the padding of its cells. */
726
+ function tableBox(table: Table, items: readonly PdfTextItem[], viewport: readonly number[]): LayoutBox {
727
+ const box: LayoutBox = [Infinity, Infinity, -Infinity, -Infinity];
728
+ let padding = 0;
729
+ for (const index of table.indexes) {
730
+ const item = items[index]!;
731
+ const matrix = item.transform;
732
+ const a = viewport[0]! * matrix[0]! + viewport[2]! * matrix[1]!;
733
+ const b = viewport[1]! * matrix[0]! + viewport[3]! * matrix[1]!;
734
+ const x = viewport[0]! * matrix[4]! + viewport[2]! * matrix[5]! + viewport[4]!;
735
+ const y = viewport[1]! * matrix[4]! + viewport[3]! * matrix[5]! + viewport[5]!;
736
+ const scale = Math.hypot(a, b) || 1;
737
+ const size = item.height > 0 ? item.height : scale;
738
+ const width = item.width > 0 ? item.width : item.str.length * size * 0.5;
739
+ // Along the text, and from the baseline up to the top of the letters.
740
+ const along = [a / scale * width, b / scale * width];
741
+ const up = [b / scale * size, -a / scale * size];
742
+ for (const [px, py] of [[x, y], [x + along[0]!, y + along[1]!], [x + up[0]!, y + up[1]!], [x + along[0]! + up[0]!, y + along[1]! + up[1]!]]) {
743
+ box[0] = Math.min(box[0], px!);
744
+ box[1] = Math.min(box[1], py!);
745
+ box[2] = Math.max(box[2], px!);
746
+ box[3] = Math.max(box[3], py!);
747
+ }
748
+ padding = Math.max(padding, size);
749
+ }
750
+ return [box[0] - padding, box[1] - padding, box[2] + padding, box[3] + padding];
751
+ }
752
+
722
753
  /**
723
754
  * The text of one PDF page, with tables written as `| cell | cell |` rows.
724
755
  *
@@ -727,6 +758,11 @@ function tablesInLines(lines: Line[], depth: number): Table[] {
727
758
  * rotation. Without it, the page is assumed to be upright.
728
759
  */
729
760
  export function layoutPageText(items: readonly PdfTextItem[], viewportTransform: readonly number[] = FLIP_Y): string {
761
+ return layoutPage(items, viewportTransform).text;
762
+ }
763
+
764
+ /** As `layoutPageText`, and also where the tables it found lie on the page. */
765
+ export function layoutPage(items: readonly PdfTextItem[], viewportTransform: readonly number[] = FLIP_Y): { text: string; tables: LayoutBox[] } {
730
766
  const tableOf = new Map<number, Table>();
731
767
  const pieceOf = new Map<number, Piece>();
732
768
  for (const group of toPieces(items, viewportTransform)) {
@@ -767,5 +803,5 @@ export function layoutPageText(items: readonly PdfTextItem[], viewportTransform:
767
803
  text += item.str + (item.hasEOL ? "\n" : "");
768
804
  last = piece && !item.hasEOL && item.str.trim() ? piece : undefined;
769
805
  });
770
- return text;
806
+ return { text, tables: [...new Set(tableOf.values())].map((table) => tableBox(table, items, viewportTransform)) };
771
807
  }
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Cuts pages out of a PDF into a small PDF of their own, so a model can be shown the real pages.
3
+ * Needs the optional dependency "@cantoo/pdf-lib".
4
+ *
5
+ * Copying pages the way a PDF library offers it is not enough. A link to another page takes that
6
+ * page's content along, and a resource dictionary that pages share takes along every image it
7
+ * lists: the contents page of a report came out at 89% of its file. So, before copying:
8
+ * - every page that is not wanted is replaced by an empty one, so a reference to it costs nothing;
9
+ * - a wanted page gets its own resource dictionary, without the images it does not paint.
10
+ */
11
+ import { getHeapStatistics } from "node:v8";
12
+ import type { PDFContext, PDFDict, PDFObject, PDFPage, PDFPageLeaf } from "@cantoo/pdf-lib";
13
+ import { formatBytes } from "./plan.js";
14
+
15
+ type PdfLibrary = typeof import("@cantoo/pdf-lib");
16
+
17
+ export type PageCut = {
18
+ /** A PDF with pages `from` to `to` of the original. */
19
+ bytes: Uint8Array;
20
+ from: number;
21
+ /** The last page in the cut. Lower than the page asked for when the pages did not all fit. */
22
+ to: number;
23
+ /** How many pages the original has. */
24
+ pageCount: number;
25
+ };
26
+
27
+ /** Objects parsed between two pauses that let other work on the server run. */
28
+ const OBJECTS_PER_TICK = 4_000;
29
+ /** Memory one parsed object takes, measured on files of 300,000 objects (1.0 to 1.6 KB). */
30
+ const BYTES_PER_OBJECT = 1_700;
31
+ /** At 13 microseconds an object, a file past this takes over 13 seconds to parse. */
32
+ const MAX_OBJECTS = 1_000_000;
33
+ /** Content streams larger than this are not read to find out which images a page paints. */
34
+ const MAX_CONTENT_BYTES = 4 * 1024 * 1024;
35
+ /** Not needed to show a page, and able to hold a lot: editor data, article threads, actions, a thumbnail. */
36
+ const DROPPED_PAGE_ENTRIES = ["PieceInfo", "B", "AA", "Thumb"];
37
+ const UNREADABLE = "This PDF could not be read to cut pages from it. It may be damaged.";
38
+
39
+ /** Bytes as a string of the same length: each byte becomes the character with that code. */
40
+ export function latin1(bytes: Uint8Array): string {
41
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
42
+ }
43
+
44
+ export async function loadPdfLibrary(): Promise<PdfLibrary> {
45
+ try {
46
+ return await import("@cantoo/pdf-lib");
47
+ } catch {
48
+ throw new Error("Showing PDF pages needs the optional dependency \"@cantoo/pdf-lib\".");
49
+ }
50
+ }
51
+
52
+ /**
53
+ * The content of a stream as text, one character per byte, or undefined when it cannot be had:
54
+ * the stream is larger than `maxBytes`, uses a filter the library does not undo, or is damaged.
55
+ */
56
+ export function decodeContent(library: PdfLibrary, context: PDFContext, stream: PDFObject | undefined, maxBytes: number): string | undefined {
57
+ const { PDFArray, PDFDict, PDFName, PDFRawStream, decodePDFRawStream } = library;
58
+ if (!(stream instanceof PDFRawStream) || stream.contents.length > maxBytes) return undefined;
59
+ // The library does not undo a predictor, and would hand back bytes that are not the content.
60
+ const parameters = stream.dict.lookup(PDFName.of("DecodeParms"));
61
+ const list = parameters instanceof PDFArray ? parameters.asArray().map((entry) => context.lookup(entry)) : [parameters];
62
+ if (list.some((entry) => entry instanceof PDFDict && entry.has(PDFName.of("Predictor")))) return undefined;
63
+ try {
64
+ return latin1(decodePDFRawStream(stream).decode());
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * How many objects the file says it has: the largest /Size in its trailer or in its
72
+ * cross-reference stream. Undefined when neither is found where a well-formed file has it.
73
+ */
74
+ export function declaredObjectCount(bytes: Uint8Array): number | undefined {
75
+ const text = (start: number, end: number) => latin1(bytes.subarray(Math.max(0, start), Math.min(bytes.length, end)));
76
+ let found = 0;
77
+ const read = (chunk: string) => {
78
+ for (const match of chunk.matchAll(/\/Size[\s\0]+(\d{1,12})/g)) found = Math.max(found, Number(match[1]));
79
+ };
80
+ const tail = text(bytes.length - 2048, bytes.length);
81
+ read(tail);
82
+ // A cross-reference stream keeps /Size in its own dictionary, which can be far from the end.
83
+ const start = [...tail.matchAll(/startxref[\s\0]+(\d{1,15})/g)].at(-1);
84
+ if (start) {
85
+ const offset = Number(start[1]);
86
+ if (offset < bytes.length) read(text(offset, offset + 2048));
87
+ }
88
+ return found > 0 ? found : undefined;
89
+ }
90
+
91
+ /**
92
+ * The library reads the whole file into objects before anything can be done with a page. The
93
+ * number of objects a file declares, when that is more than `most` or more than this process can
94
+ * hold; undefined when the file can be read.
95
+ */
96
+ export function tooManyObjects(original: Uint8Array, most = MAX_OBJECTS): number | undefined {
97
+ const objects = declaredObjectCount(original);
98
+ if (objects === undefined) return undefined;
99
+ const heap = getHeapStatistics();
100
+ const free = heap.heap_size_limit - heap.used_heap_size;
101
+ return objects > most || objects * BYTES_PER_OBJECT > free * 0.6 ? objects : undefined;
102
+ }
103
+
104
+ /** A PDF name as the characters it stands for, so that "#20" and a space are the same name. */
105
+ export function canonicalName(raw: string): string {
106
+ let name = raw;
107
+ // Until nothing changes: a library may keep an escape it did not decode as literal characters.
108
+ for (;;) {
109
+ const next = name.replace(/#([0-9a-fA-F]{2})/g, (_match, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)));
110
+ if (next === name) return name;
111
+ name = next;
112
+ }
113
+ }
114
+
115
+ const REGULAR_CHARACTER = "[^\\x00\\t\\n\\f\\r /\\[\\]<>(){}%]";
116
+ /** `/Name Do`: the operator that paints an image or a form. */
117
+ const PAINTED = new RegExp(`/(${REGULAR_CHARACTER}*)[\\x00\\t\\n\\f\\r ]+Do(?!${REGULAR_CHARACTER})`, "g");
118
+
119
+ /**
120
+ * Gives a page its own resource dictionary without the images it does not paint. FPDF, TCPDF,
121
+ * jsPDF and others list every image of the file in one dictionary that all pages share.
122
+ *
123
+ * It only keeps more than is needed, never less: a name found anywhere in the content counts as
124
+ * painted, and nothing is dropped unless every stream that can name an image of this dictionary
125
+ * was read.
126
+ */
127
+ function dropUnusedImages(library: PdfLibrary, context: PDFContext, page: PDFPageLeaf): void {
128
+ const { PDFArray, PDFDict, PDFName, PDFStream } = library;
129
+ const key = (value: string) => PDFName.of(value);
130
+ const resources = page.Resources();
131
+ if (!resources) return;
132
+ const xobjects = resources.lookup(key("XObject"));
133
+ if (!(xobjects instanceof PDFDict)) return;
134
+ const entries = xobjects.entries();
135
+ if (entries.length < 2) return;
136
+ const byName = new Map(entries.map(([name, value]) => [canonicalName(name.asString().slice(1)), value]));
137
+
138
+ let readable = true;
139
+ /** Names found in content that looks them up in this page's dictionary, still to be followed. */
140
+ const found: string[] = [];
141
+ const decode = (stream: PDFObject | undefined) => decodeContent(library, context, stream, MAX_CONTENT_BYTES);
142
+ const read = (text: string) => {
143
+ for (const match of text.matchAll(PAINTED)) found.push(canonicalName(match[1]!));
144
+ };
145
+ const readStream = (stream: PDFObject | undefined) => {
146
+ const text = decode(stream);
147
+ if (text === undefined) readable = false;
148
+ else read(text);
149
+ };
150
+ // A form, a pattern, a Type 3 glyph or an annotation's appearance that has no resource dictionary
151
+ // of its own (old PDFs allow that), or has this page's, takes its names from this page's
152
+ // dictionary: read it. One with its own dictionary is independent, but can hold more content of
153
+ // the first kind: look inside.
154
+ const seen = new Set<PDFDict>();
155
+ const content = (object: PDFObject | undefined) => {
156
+ if (!(object instanceof PDFStream)) return;
157
+ const own = object.dict.lookup(key("Resources"));
158
+ if (own instanceof PDFDict && own !== resources) inside(own);
159
+ else readStream(object);
160
+ };
161
+ const patternsAndFonts = (dictionary: PDFDict) => {
162
+ const patterns = dictionary.lookup(key("Pattern"));
163
+ if (patterns instanceof PDFDict) for (const [, value] of patterns.entries()) content(context.lookup(value));
164
+ const fonts = dictionary.lookup(key("Font"));
165
+ if (!(fonts instanceof PDFDict)) return;
166
+ for (const [, value] of fonts.entries()) {
167
+ const font = context.lookup(value);
168
+ if (!(font instanceof PDFDict) || font.lookup(key("Subtype")) !== key("Type3")) continue;
169
+ const own = font.lookup(key("Resources"));
170
+ if (own instanceof PDFDict && own !== resources) {
171
+ inside(own);
172
+ continue;
173
+ }
174
+ const glyphs = font.lookup(key("CharProcs"));
175
+ if (glyphs instanceof PDFDict) for (const [, glyph] of glyphs.entries()) readStream(context.lookup(glyph));
176
+ }
177
+ };
178
+ const inside = (dictionary: PDFDict) => {
179
+ if (seen.has(dictionary)) return;
180
+ seen.add(dictionary);
181
+ const forms = dictionary.lookup(key("XObject"));
182
+ if (forms instanceof PDFDict) {
183
+ for (const [, value] of forms.entries()) {
184
+ const object = context.lookup(value);
185
+ if (object instanceof PDFStream && object.dict.lookup(key("Subtype")) === key("Form")) content(object);
186
+ }
187
+ }
188
+ patternsAndFonts(dictionary);
189
+ };
190
+
191
+ // 1. The page's own content. Split over several streams it is still one text: "/Im1" may end one
192
+ // stream and "Do" start the next.
193
+ const contents = page.Contents();
194
+ const streams = contents instanceof PDFArray ? contents.asArray().map((entry) => context.lookup(entry)) : contents ? [contents] : [];
195
+ const parts = streams.map(decode);
196
+ if (parts.includes(undefined)) readable = false;
197
+ else read(parts.join(" "));
198
+ // 2. The page's patterns and Type 3 fonts, and what its annotations show. Which of them the page
199
+ // uses is not worked out: all count.
200
+ patternsAndFonts(resources);
201
+ const annotations = page.Annots();
202
+ if (annotations) {
203
+ for (const entry of annotations.asArray()) {
204
+ const annotation = context.lookup(entry);
205
+ const appearances = annotation instanceof PDFDict ? annotation.lookup(key("AP")) : undefined;
206
+ if (!(appearances instanceof PDFDict)) continue;
207
+ for (const [, value] of appearances.entries()) {
208
+ const appearance = context.lookup(value);
209
+ if (appearance instanceof PDFStream) content(appearance);
210
+ else if (appearance instanceof PDFDict) for (const [, state] of appearance.entries()) content(context.lookup(state));
211
+ }
212
+ }
213
+ }
214
+ // 3. Follow what is painted: a form that is painted paints more.
215
+ const painted = new Set<string>();
216
+ while (found.length > 0) {
217
+ const next = found.pop()!;
218
+ if (painted.has(next)) continue;
219
+ painted.add(next);
220
+ const value = byName.get(next);
221
+ const object = value ? context.lookup(value) : undefined;
222
+ if (object instanceof PDFStream && object.dict.lookup(key("Subtype")) === key("Form")) content(object);
223
+ }
224
+ if (!readable) return;
225
+
226
+ const kept = entries.filter(([name]) => painted.has(canonicalName(name.asString().slice(1))));
227
+ if (kept.length === entries.length) return;
228
+ const fewer = context.obj({});
229
+ for (const [name, value] of kept) fewer.set(name, value);
230
+ const own = resources.clone(context);
231
+ own.set(key("XObject"), fewer);
232
+ page.set(key("Resources"), own);
233
+ }
234
+
235
+ /** A PDF with pages `from` to `last` of `source`. Changes `source`: use it only for smaller cuts afterwards. */
236
+ async function copyPages(library: PdfLibrary, source: import("@cantoo/pdf-lib").PDFDocument, pages: PDFPage[], from: number, last: number): Promise<Uint8Array> {
237
+ const { PDFDocument, PDFName, PDFNull, PDFObjectCopier, PDFPage: Page, PDFPageLeaf: Leaf } = library;
238
+ const { context } = source;
239
+ const wanted = pages.slice(from - 1, last);
240
+ const wantedReferences = new Set(wanted.map((page) => page.ref));
241
+ // Every other page becomes nothing, so a link, a form field or a thread that leads to it copies
242
+ // a few bytes and not the page. (Null, not an empty page: the cut must not hold objects that
243
+ // call themselves pages and are not among its pages.)
244
+ for (const page of pages) {
245
+ if (!wantedReferences.has(page.ref)) context.assign(page.ref, PDFNull);
246
+ }
247
+ for (const page of wanted) {
248
+ for (const entry of DROPPED_PAGE_ENTRIES) page.node.delete(PDFName.of(entry));
249
+ try {
250
+ dropUnusedImages(library, context, page.node);
251
+ } catch {
252
+ // An unusual resource dictionary: the page is copied with everything it lists.
253
+ }
254
+ }
255
+ const target = await PDFDocument.create({ updateMetadata: false });
256
+ // One copier for everything, and each page copied through its reference: an annotation's /P then
257
+ // points at the copied page, and the layer settings below name the layers the pages use.
258
+ const copier = PDFObjectCopier.for(context, target.context);
259
+ for (const page of wanted) {
260
+ const reference = copier.copy(page.ref);
261
+ const node = target.context.lookup(reference);
262
+ if (!(node instanceof Leaf)) throw new Error("A page of this PDF is not a page object.");
263
+ target.addPage(Page.of(node, reference, target));
264
+ }
265
+ // Without these, a layer that the file hides would be shown.
266
+ const layers = source.catalog.get(PDFName.of("OCProperties"));
267
+ if (layers) target.catalog.set(PDFName.of("OCProperties"), copier.copy(layers));
268
+ return target.save();
269
+ }
270
+
271
+ /**
272
+ * Cuts pages `from` to `to` (1-based, inclusive) out of a PDF. When the cut is larger than
273
+ * `maxBytes`, pages are left off the end until it fits; `to` in the result says where it stopped.
274
+ * Throws an Error whose message can be shown to a model: for a file that cannot be opened, a page
275
+ * that does not exist, and a first page that does not fit by itself.
276
+ *
277
+ * `expectedPages` is the page count the text of the file was extracted with. The text came from
278
+ * another PDF reader; if the two do not count the same pages, a page number may not mean the same
279
+ * page in both, and showing the wrong page is worse than showing none.
280
+ */
281
+ export async function cutPdfPages(original: Uint8Array, from: number, to: number, maxBytes: number, expectedPages?: number): Promise<PageCut> {
282
+ const library = await loadPdfLibrary();
283
+ // Refuse a file that says it has more objects than this process can hold, instead of running out of memory.
284
+ const objects = tooManyObjects(original);
285
+ if (objects !== undefined) throw new Error(`This PDF has ${objects.toLocaleString("en-US")} objects, too many to cut pages from it in memory.`);
286
+ let source: import("@cantoo/pdf-lib").PDFDocument;
287
+ let pages: PDFPage[];
288
+ try {
289
+ // An empty password opens the many PDFs that are encrypted only to restrict printing or copying.
290
+ source = await library.PDFDocument.load(original, { updateMetadata: false, parseSpeed: OBJECTS_PER_TICK, password: "" });
291
+ pages = source.getPages();
292
+ } catch (error) {
293
+ const needsPassword = /password/i.test(error instanceof Error ? error.message : String(error));
294
+ throw new Error(needsPassword ? "This PDF needs a password to open, so its pages cannot be shown." : UNREADABLE);
295
+ }
296
+ const pageCount = pages.length;
297
+ // A damaged file can be read as a file without pages: the library skips what it cannot parse.
298
+ if (pageCount === 0) throw new Error(UNREADABLE);
299
+ if (expectedPages !== undefined && pageCount !== expectedPages) {
300
+ throw new Error(`The pages of this PDF could not be matched to its text (${pageCount} pages against ${expectedPages}), so they cannot be shown.`);
301
+ }
302
+ if (from < 1 || from > pageCount) throw new Error(`There is no page ${from}: the file has ${pageCount} ${pageCount === 1 ? "page" : "pages"}.`);
303
+ let smallest = 0;
304
+ for (let last = Math.min(Math.max(to, from), pageCount); last >= from; last--) {
305
+ let bytes: Uint8Array;
306
+ try {
307
+ bytes = await copyPages(library, source, pages, from, last);
308
+ } catch {
309
+ throw new Error("The pages could not be cut out of this PDF. It may be damaged.");
310
+ }
311
+ if (bytes.length <= maxBytes) return { bytes, from, to: last, pageCount };
312
+ smallest = bytes.length;
313
+ }
314
+ throw new Error(`Page ${from} is ${formatBytes(smallest)} as a file, more than the ${formatBytes(Math.max(0, maxBytes))} that fit in this request.`);
315
+ }