@web-ts-toolkit/pdf-reader 0.37.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 (5) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +253 -0
  3. package/index.d.mts +192 -0
  4. package/index.mjs +760 -0
  5. package/package.json +45 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Junmin Ahn
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,253 @@
1
+ # `@web-ts-toolkit/pdf-reader`
2
+
3
+ Resource-safe browser PDF rendering, text extraction, and best-effort embedded-image extraction built on PDF.js.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ pnpm add @web-ts-toolkit/pdf-reader pdfjs-dist
9
+ ```
10
+
11
+ `pdfjs-dist` is a peer dependency. This package is browser-oriented, ESM-only, and requires DOM canvas APIs.
12
+
13
+ Canonical imports use named exports from the package root. There is no default export, no supported deep import, and no supported CommonJS `require()` entry.
14
+
15
+ ## Unreleased Migration
16
+
17
+ This follow-up release keeps the small named-export API but intentionally does not preserve the older application-local `PDFReader` names and defaults.
18
+
19
+ | Area | Previous contract | New contract and migration |
20
+ | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
21
+ | Imports and worker setup | The application-local reader was typically imported as a default export and could hide PDF.js worker wiring inside app code. | Import named exports from `@web-ts-toolkit/pdf-reader` and call `configurePdfWorker(...)` in application code. There is no default export, no deep import, and no package-owned worker asset emission. |
22
+ | Load cancellation and teardown | Concurrent callers could accidentally tear down a shared load, and lifecycle states were mostly implicit. | Concurrent `load()` callers share one PDF.js task, but aborting one caller rejects only that caller. Use `reader.state` for `new` / `loading` / `loaded` / `iterating` / `failed` / `destroyed`, and call `destroy()` to tear down shared work explicitly. |
23
+ | Load options | `load()` previously accepted only an `AbortSignal`-style cancellation pattern. | `load()` still accepts an `AbortSignal`, and now also accepts `{ signal, deadlineMs }`. `deadlineMs` is caller-local and rejects with `DEADLINE_EXCEEDED` without cancelling unrelated waiters. |
24
+ | Page image results | Older code used top-level page result fields such as `dataURL`, `dataUrl`, `mimeType`, and `isPNG`. | Read `page.pageImage` instead. `pageImageOutput: 'data-url'` returns `{ kind: 'data-url', mimeType, dataUrl }`; `pageImageOutput: 'blob'` returns `{ kind: 'blob', mimeType, blob }`. |
25
+ | Convert option names | Older application-local option names included `getText`, `getDataURL`, `getImages`, and reader `config`. | Use `includeText`, `includePageImage`, `includeEmbeddedImages`, and constructor `options`. Unsupported legacy names are intentionally rejected by the type surface instead of being kept as aliases. |
26
+
27
+ The repository `CHANGELOG.md` contains the same release-level migration summary.
28
+
29
+ ## Worker Setup
30
+
31
+ Configure the PDF.js worker explicitly in your application. The package does not use bundler-specific `?url` imports and does not mutate PDF.js globals merely by being imported.
32
+
33
+ Vite example:
34
+
35
+ ```ts
36
+ import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
37
+ import { configurePdfWorker } from '@web-ts-toolkit/pdf-reader';
38
+
39
+ configurePdfWorker(workerUrl);
40
+ ```
41
+
42
+ Alternatively, pass an existing module `Worker`:
43
+
44
+ ```ts
45
+ import { configurePdfWorker } from '@web-ts-toolkit/pdf-reader';
46
+
47
+ configurePdfWorker(new Worker(new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url), { type: 'module' }));
48
+ ```
49
+
50
+ Worker URL emission differs by bundler. Keep this setup in application code where the bundler owns asset handling. Calling `configurePdfWorker(...)` again replaces the previous package-level worker configuration. If you pass an existing `Worker`, you still own terminating it.
51
+
52
+ ## Quick Start
53
+
54
+ ```ts
55
+ import { PDFReader } from '@web-ts-toolkit/pdf-reader';
56
+
57
+ const bytes = new Uint8Array(await file.arrayBuffer());
58
+ const reader = new PDFReader(bytes);
59
+
60
+ try {
61
+ await reader.load({ deadlineMs: 15_000 });
62
+
63
+ for await (const page of reader.pages({
64
+ includeText: true,
65
+ includePageImage: true,
66
+ pageImageOutput: 'blob',
67
+ imageFormat: 'image/jpeg',
68
+ jpegQuality: 0.85,
69
+ })) {
70
+ console.log(page.pageNumber, page.text, page.pageImage);
71
+ }
72
+ } finally {
73
+ await reader.destroy();
74
+ }
75
+ ```
76
+
77
+ Use `pages()` for large PDFs because it lets the caller consume and release each result incrementally. `convert(options)` provides the same results as an array for small documents.
78
+
79
+ For a remote PDF, use `pdfUrlSource(...)` to create constructor-ready PDF.js loading data:
80
+
81
+ ```ts
82
+ import { PDFReader, pdfUrlSource } from '@web-ts-toolkit/pdf-reader';
83
+
84
+ const reader = new PDFReader(
85
+ pdfUrlSource('https://static.example.com/document.pdf', {
86
+ withCredentials: false,
87
+ }),
88
+ );
89
+ ```
90
+
91
+ Call `load()` before `pages()` or `convert()`. Concurrent `load()` callers share one PDF.js loading task, but aborting one caller only rejects that caller; call `destroy()` to tear down the shared load. `destroy()` is idempotent, permanently closes the reader, cancels active renders, and causes in-flight lifecycle work to reject with `DESTROYED`.
92
+
93
+ ## Reader State And Ownership
94
+
95
+ `reader.state` exposes the public lifecycle:
96
+
97
+ | State | Meaning | Legal next states |
98
+ | ----------- | ------------------------------------------------------------------------------------ | ------------------------------- |
99
+ | `new` | Reader constructed but `load()` has not started. | `loading`, `destroyed` |
100
+ | `loading` | One shared PDF.js loading task is in flight. | `loaded`, `failed`, `destroyed` |
101
+ | `loaded` | The PDF.js document is loaded and no page work is active. | `iterating`, `destroyed` |
102
+ | `iterating` | `pages()` or `convert()` currently owns a page proxy, render task, or encoder step. | `loaded`, `destroyed` |
103
+ | `failed` | The most recent load attempt rejected. A later `load()` call starts a fresh attempt. | `loading`, `destroyed` |
104
+ | `destroyed` | `destroy()` completed or irrevocably won a race. The reader cannot be reused. | none |
105
+
106
+ Ownership and lifetime rules:
107
+
108
+ - Source bytes: the package passes your `PdfSource` to PDF.js unchanged after `sourcePolicy(...)` approval. PDF.js may transfer typed-array ownership to its worker during `load()`.
109
+ - Pages: `pages()` and `convert()` own the live `PDFPageProxy` only while processing that page. The package calls `page.cleanup()` before yielding the result and on every error path.
110
+ - Page canvases: the package owns temporary render/encode canvases and always zeroes their dimensions after each settle path.
111
+ - `Blob` page images: the returned `Blob` belongs to the caller. If you create an object URL, revoke it yourself.
112
+ - Data URLs: returned strings belong to the caller. They are copies; the package does not retain the temporary canvas after encoding.
113
+ - Embedded-image data URLs: these are best-effort PNG copies. Unsupported image operators/layouts are skipped with `logger.warn(...)` diagnostics.
114
+ - Documents and workers: the reader owns the loaded `PDFDocumentProxy` and the shared loading task it created. Call `destroy()` in your own `finally` block to terminate document-side resources. When `configurePdfWorker(...)` receives a worker URL, PDF.js owns any worker instances it creates from that URL. When `configurePdfWorker(...)` receives an existing `Worker`, the caller still owns terminating that worker.
115
+
116
+ ## Options
117
+
118
+ ```ts
119
+ const pages = await reader.convert({
120
+ pageRange: [2, 5],
121
+ viewportScale: (width, height) => (width > height ? 1 : 1.5),
122
+ imageFormat: 'image/png',
123
+ includePageImage: true,
124
+ includeText: true,
125
+ includeEmbeddedImages: false,
126
+ signal: abortController.signal,
127
+ });
128
+ ```
129
+
130
+ - `pageRange`: one 1-based page number or an inclusive tuple. Reversed tuples are accepted and normalized.
131
+ - `viewportScale`: positive number or page-size callback; defaults to `1.5`.
132
+ - `imageFormat`: `image/png` or `image/jpeg`; defaults to PNG.
133
+ - `jpegQuality`: finite number from `0` through `1`; defaults to `0.92`. It is applied only when `imageFormat` is `image/jpeg`; PNG output ignores it.
134
+ - `includePageImage`: render the complete page and include it under `page.pageImage`; defaults to `true`.
135
+ - `pageImageOutput`: `data-url` or `blob`; defaults to `data-url`.
136
+ - `includeText`: include PDF.js `TextContent`; defaults to `true`.
137
+ - `includeEmbeddedImages`: inspect the operator stream for raster images; defaults to `false`.
138
+ - `signal`: cancels active rendering and stops before subsequent expensive operations.
139
+
140
+ `pageImage` is a discriminated union so the output mode and payload cannot contradict each other:
141
+
142
+ ```ts
143
+ if (page.pageImage?.kind === 'blob') {
144
+ const objectUrl = URL.createObjectURL(page.pageImage.blob);
145
+ try {
146
+ preview.src = objectUrl;
147
+ } finally {
148
+ URL.revokeObjectURL(objectUrl);
149
+ }
150
+ }
151
+
152
+ if (page.pageImage?.kind === 'data-url') {
153
+ preview.src = page.pageImage.dataUrl;
154
+ }
155
+ ```
156
+
157
+ This package returns `Blob` objects directly rather than object URLs so callers keep explicit ownership of any `URL.createObjectURL(...)` lifecycle.
158
+
159
+ ## Performance And Concurrency
160
+
161
+ Page work remains serial in the runtime API. PDFR-07 adds a real-browser benchmark under `packages/pdf-reader/benchmark/` that compares the current `pages()` behavior against an external page-level scheduler with a hard concurrency bound of `2`, deterministic output ordering, and abort handling.
162
+
163
+ Run it with:
164
+
165
+ ```sh
166
+ pnpm --filter @web-ts-toolkit/pdf-reader benchmark
167
+ ```
168
+
169
+ The recorded local run on Headless Chromium `151.0.7922.34` showed bounded overlap materially improving the synthetic `long.pdf` (`207.1 ms` to `107.3 ms`) and `image-heavy.pdf` (`62.3 ms` to `39.3 ms`) fixtures, while `text-heavy.pdf` stayed effectively flat (`69.7 ms` to `72.5 ms`) and peak active pages/canvases deterministically doubled from `1/1` to `2/2`.
170
+
171
+ The package still does not expose a concurrency option because that evidence is not yet enough to set a safe browser memory/backpressure contract. See the benchmark README and the PDFR-07 completion evidence for the recorded browser/hardware context and full results.
172
+
173
+ ## Resource Limits
174
+
175
+ Defaults reject documents above 1,000 pages, rendered pages above 40 megapixels, and copied embedded images above 25 megapixels.
176
+
177
+ ```ts
178
+ import { PDFReader, PdfReaderError } from '@web-ts-toolkit/pdf-reader';
179
+
180
+ const reader = new PDFReader(bytes, {
181
+ limits: {
182
+ maxSourceBytes: 25_000_000,
183
+ maxDocumentPages: 250,
184
+ maxCanvasPixels: 20_000_000,
185
+ maxEmbeddedImagePixels: 10_000_000,
186
+ },
187
+ sourcePolicy(source) {
188
+ if (source.url && !source.url.startsWith('https://static.example.com/')) {
189
+ throw new PdfReaderError('SOURCE_POLICY_VIOLATION', 'Remote PDF source rejected by sourcePolicy.');
190
+ }
191
+ if (source.withCredentials || source.hasHttpHeaders) {
192
+ throw new PdfReaderError(
193
+ 'SOURCE_POLICY_VIOLATION',
194
+ 'Credentialed or header-bearing PDF sources are not allowed.',
195
+ );
196
+ }
197
+ },
198
+ logger: {
199
+ warn(message, error) {
200
+ reportWarning(message, error);
201
+ },
202
+ },
203
+ });
204
+ ```
205
+
206
+ Limits reduce accidental or malicious memory pressure but are not a complete sandbox. PDF parsing still occurs in PDF.js and its worker.
207
+
208
+ `maxSourceBytes` is enforced only when the package can know the byte length synchronously, including direct typed arrays, array buffers, number arrays, and `DocumentInitParameters.data`. It does not apply to remote downloads.
209
+
210
+ `sourcePolicy(source)` runs before `getDocument()` and can reject remote URLs, protocols, origins, credentials, headers, or any other caller-supplied loading parameters. The original source object still passes through unchanged when the policy allows it, so PDF.js passwords, CMap/font/WASM URLs, and caller-created workers remain available.
211
+
212
+ ## Security Notes
213
+
214
+ - Prefer trusted `Uint8Array` input. PDF.js may transfer ownership of typed-array data to its worker.
215
+ - Use `sourcePolicy` to reject remote URLs, protocols, origins, credentialed requests, or header-bearing sources before PDF.js starts network work.
216
+ - `configurePdfWorker(...)` mutates PDF.js global worker options only when you call it, not at module evaluation. Reconfiguring it clears the previous URL-or-port setting so stale worker globals do not win unexpectedly.
217
+ - Keep `withCredentials` disabled unless cross-origin credentials are explicitly required.
218
+ - Use `maxSourceBytes` for synchronously knowable in-memory sources. Remote response-byte limits still belong to application-controlled fetch/range transport because this package does not intercept PDF.js network I/O.
219
+ - Use `load({ deadlineMs })` or your own `AbortSignal` to bound load wait time. The package clears deadline timers and abort listeners on success, failure, caller abort, and destroy.
220
+ - Keep `pdfjs-dist` current because malformed-document defenses belong primarily to PDF.js.
221
+ - Treat extracted text and images as untrusted content. Do not inject text as HTML without escaping or sanitization.
222
+
223
+ ## Embedded Images
224
+
225
+ Embedded-image extraction stays on the package root as an opt-in convenience (`includeEmbeddedImages: true`), but the operator traversal now lives behind one private extractor boundary instead of mixing PDF.js internals into reader lifecycle code.
226
+
227
+ The real-browser fixture suite for the supported `pdfjs-dist` peer minor (`~5.7.284`) characterizes inline images, image XObjects, repeated references, nested save/restore transforms, mirrored transforms, grayscale, RGB, RGBA soft-mask images, browser `ImageBitmap`-backed image objects, and nested form XObjects with their own matrices.
228
+
229
+ Standalone image-mask operators, vector graphics, patterns, and unknown PDF.js image-object layouts remain unsupported. They are skipped with `logger.warn(...)` diagnostics rather than failing the entire page. The extractor never calls `ImageBitmap.close()` because PDF.js owns bitmap lifetime through `page.cleanup()` and document destruction.
230
+
231
+ Individual unsupported images are skipped. Supply `logger.warn` if those diagnostics matter to the application. Resource-limit and cancellation errors are never swallowed.
232
+
233
+ Image `x`, `y`, `width`, and `height` values are PDF user-space coordinates before viewport scaling. The full six-value graphics transform is included when consumers need custom coordinate conversion.
234
+
235
+ ## Errors And Cleanup
236
+
237
+ Validation and resource failures use `PdfReaderError` with stable codes:
238
+
239
+ - `ABORTED`
240
+ - `CANVAS_LIMIT_EXCEEDED`
241
+ - `DEADLINE_EXCEEDED`
242
+ - `DESTROYED`
243
+ - `DOCUMENT_NOT_LOADED`
244
+ - `IMAGE_LIMIT_EXCEEDED`
245
+ - `INVALID_OPTION`
246
+ - `PAGE_LIMIT_EXCEEDED`
247
+ - `SOURCE_LIMIT_EXCEEDED`
248
+ - `SOURCE_POLICY_VIOLATION`
249
+ - `UNSUPPORTED_ENVIRONMENT`
250
+
251
+ Package-owned errors cover invalid options, lifecycle cancellation/destroy/deadline states, resource limits, source-policy/known-byte rejections, and unsupported canvas/runtime features such as missing 2D contexts or missing `toBlob()` support.
252
+
253
+ PDF.js loading, password, malformed-document, response, and rendering errors pass through unchanged so callers can use PDF.js error classes. Abort and destroy races are normalized to package `PdfReaderError` codes rather than leaking PDF.js cancellation exceptions. Best-effort embedded-image skips do not throw; they call `logger.warn(...)` when a logger is supplied. Always call `destroy()` from your own `finally` block to terminate reader-owned document resources.
package/index.d.mts ADDED
@@ -0,0 +1,192 @@
1
+ import * as pdfjs_dist from 'pdfjs-dist';
2
+ import { PDFDocumentProxy, PDFPageProxy, PageViewport } from 'pdfjs-dist';
3
+
4
+ type PdfReaderErrorCode = 'ABORTED' | 'CANVAS_LIMIT_EXCEEDED' | 'DEADLINE_EXCEEDED' | 'DESTROYED' | 'DOCUMENT_NOT_LOADED' | 'IMAGE_LIMIT_EXCEEDED' | 'INVALID_OPTION' | 'PAGE_LIMIT_EXCEEDED' | 'SOURCE_LIMIT_EXCEEDED' | 'SOURCE_POLICY_VIOLATION' | 'UNSUPPORTED_ENVIRONMENT';
5
+ /** An actionable package error with a stable machine-readable code. */
6
+ declare class PdfReaderError extends Error {
7
+ readonly code: PdfReaderErrorCode;
8
+ constructor(code: PdfReaderErrorCode, message: string);
9
+ }
10
+
11
+ /**
12
+ * PDF.js `getDocument(...)` source accepted by the package root.
13
+ *
14
+ * Prefer trusted in-memory bytes when possible. PDF.js may transfer typed-array
15
+ * ownership to its worker during load.
16
+ */
17
+ type PdfSource = NonNullable<Parameters<typeof pdfjs_dist.getDocument>[0]>;
18
+ type TransformMatrix = readonly [number, number, number, number, number, number];
19
+ type PageRange = number | readonly [start: number, end: number];
20
+ type ViewportScale = number | ((pageWidth: number, pageHeight: number) => number);
21
+ type PageImageMimeType = 'image/png' | 'image/jpeg';
22
+ type PageImageOutputMode = 'data-url' | 'blob';
23
+ /**
24
+ * Public lifecycle states reported by `PDFReader.state`.
25
+ *
26
+ * `failed` means the most recent package- or PDF.js-owned load attempt
27
+ * rejected and a later `load()` call will start a fresh attempt.
28
+ */
29
+ type PdfReaderState = 'new' | 'loading' | 'loaded' | 'iterating' | 'failed' | 'destroyed';
30
+ /** PDF.js text output without requiring consumers to import PDF.js internals. */
31
+ type PdfTextContent = Awaited<ReturnType<PDFPageProxy['getTextContent']>>;
32
+ interface PdfReaderLimits {
33
+ /** Maximum known in-memory source bytes accepted before PDF.js starts loading. Unset by default. */
34
+ maxSourceBytes?: number;
35
+ /** Maximum number of document pages accepted after loading. Defaults to 1,000. */
36
+ maxDocumentPages?: number;
37
+ /** Maximum pixels allocated for one rendered page. Defaults to 40 megapixels. */
38
+ maxCanvasPixels?: number;
39
+ /** Maximum pixels allocated while copying one embedded image. Defaults to 25 megapixels. */
40
+ maxEmbeddedImagePixels?: number;
41
+ }
42
+ interface PdfReaderLogger {
43
+ warn(message: string, error?: unknown): void;
44
+ }
45
+ interface PdfReaderSourceInfo {
46
+ /** The original source value that will be passed to PDF.js if policy allows it. */
47
+ rawSource: PdfSource;
48
+ /** Broad source shape so callers can distinguish direct bytes from URL-based inputs. */
49
+ kind: 'bytes' | 'url' | 'document-init-parameters';
50
+ /** Normalized URL string when one is present on the source. */
51
+ url?: string;
52
+ /** Known byte length for direct byte sources and `DocumentInitParameters.data` when synchronously measurable. */
53
+ byteLength?: number;
54
+ /** True when the source carries any custom HTTP headers. */
55
+ hasHttpHeaders: boolean;
56
+ /** Shallow copy of recognized HTTP headers when the source uses a plain object. */
57
+ httpHeaders?: Readonly<Record<string, string>>;
58
+ /** Whether PDF.js would send credentials for URL-based loading. */
59
+ withCredentials: boolean;
60
+ }
61
+ type PdfReaderSourcePolicy = (source: PdfReaderSourceInfo) => void | Promise<void>;
62
+ interface PdfReaderOptions {
63
+ /** Canvas boundary injectable for tests or non-DOM canvas implementations. */
64
+ canvasFactory?: () => HTMLCanvasElement;
65
+ /** Optional warning sink. The package never writes directly to the console. */
66
+ logger?: PdfReaderLogger;
67
+ limits?: PdfReaderLimits;
68
+ /** Optional pre-load policy hook for rejecting sources before PDF.js starts work. */
69
+ sourcePolicy?: PdfReaderSourcePolicy;
70
+ }
71
+ interface LoadOptions {
72
+ /** Cancels only the current load caller, not other callers sharing the same underlying PDF.js task. */
73
+ signal?: AbortSignal;
74
+ /** Caller-local deadline in milliseconds for waiting on `load()`. */
75
+ deadlineMs?: number;
76
+ }
77
+ interface ConvertOptions {
78
+ pageRange?: PageRange;
79
+ viewportScale?: ViewportScale;
80
+ imageFormat?: PageImageMimeType;
81
+ jpegQuality?: number;
82
+ includePageImage?: boolean;
83
+ pageImageOutput?: PageImageOutputMode;
84
+ includeText?: boolean;
85
+ includeEmbeddedImages?: boolean;
86
+ /** Stops between expensive steps and cancels an active page render. */
87
+ signal?: AbortSignal;
88
+ }
89
+ interface DataUrlPageImage {
90
+ /** Inline base64 page image. The package owns the temporary canvas, not the returned string. */
91
+ kind: 'data-url';
92
+ mimeType: PageImageMimeType;
93
+ dataUrl: string;
94
+ }
95
+ interface BlobPageImage {
96
+ /** Binary page image. Callers own any object URL created from this blob. */
97
+ kind: 'blob';
98
+ mimeType: PageImageMimeType;
99
+ blob: Blob;
100
+ }
101
+ type PageImageResult = DataUrlPageImage | BlobPageImage;
102
+ interface ExtractedImage {
103
+ /** Best-effort PNG data URL copied from a PDF.js image object. */
104
+ dataUrl: string;
105
+ x: number;
106
+ y: number;
107
+ width: number;
108
+ height: number;
109
+ size: number;
110
+ mimeType: 'image/png';
111
+ pageWidth: number;
112
+ pageHeight: number;
113
+ transform: TransformMatrix;
114
+ }
115
+ interface PageResult {
116
+ /** Total document pages from the loaded PDF.js document proxy. */
117
+ numPages: number;
118
+ pageNumber: number;
119
+ pageIndex: number;
120
+ /** Optional full-page render owned by the caller after the page canvas is released. */
121
+ pageImage?: PageImageResult;
122
+ viewport: PageViewport;
123
+ /** Optional PDF.js text content. Treat extracted strings as untrusted input. */
124
+ text?: PdfTextContent;
125
+ /** Best-effort embedded raster images extracted from the current page. */
126
+ images: ExtractedImage[];
127
+ }
128
+ type LoadedPdfDocument = PDFDocumentProxy;
129
+ type LoadedPdfPage = PDFPageProxy;
130
+
131
+ /** Browser PDF reader with bounded canvas allocation and deterministic cleanup. */
132
+ declare class PDFReader {
133
+ #private;
134
+ constructor(source: PdfSource, options?: PdfReaderOptions);
135
+ get numPages(): number | undefined;
136
+ /** Current lifecycle state for load, iteration/rendering, retry, and teardown boundaries. */
137
+ get state(): PdfReaderState;
138
+ /** Loads once and returns the underlying PDF.js document proxy. */
139
+ load(signal?: AbortSignal): Promise<PDFDocumentProxy>;
140
+ load(options?: LoadOptions): Promise<PDFDocumentProxy>;
141
+ /** Streams page results so callers do not need to retain the entire document conversion in memory. */
142
+ pages(options?: ConvertOptions): AsyncGenerator<PageResult>;
143
+ /** Collects `pages()` into an array. Prefer `pages()` for large documents. */
144
+ convert(options?: ConvertOptions): Promise<PageResult[]>;
145
+ /** Terminates the loading task and document resources. The reader cannot be reused afterwards. */
146
+ destroy(): Promise<void>;
147
+ }
148
+
149
+ interface PdfUrlSourceOptions {
150
+ /** Basic authentication headers forwarded to PDF.js URL loading. */
151
+ httpHeaders?: Readonly<Record<string, string>>;
152
+ /** Whether PDF.js should send cross-origin credentials while loading the URL. */
153
+ withCredentials?: boolean;
154
+ /** Password for encrypted PDFs. */
155
+ password?: string;
156
+ /** Maximum bytes fetched per PDF.js range request. */
157
+ rangeChunkSize?: number;
158
+ /** Base URL used by PDF.js when resolving relative links in the document. */
159
+ docBaseUrl?: string;
160
+ /** URL where predefined Adobe CMaps are located. Include the trailing slash. */
161
+ cMapUrl?: string;
162
+ /** Whether CMaps are binary packed. */
163
+ cMapPacked?: boolean;
164
+ /** URL where PDF.js standard font data is located. Include the trailing slash. */
165
+ standardFontDataUrl?: string;
166
+ /** URL where PDF.js WASM assets are located. Include the trailing slash. */
167
+ wasmUrl?: string;
168
+ /** Disable HTTP range requests. */
169
+ disableRange?: boolean;
170
+ /** Disable streaming PDF data. */
171
+ disableStream?: boolean;
172
+ /** Disable automatic prefetching after the first range request. */
173
+ disableAutoFetch?: boolean;
174
+ /** PDF.js verbosity level. */
175
+ verbosity?: number;
176
+ }
177
+ type PdfUrlSource = PdfUrlSourceOptions & {
178
+ url: string | URL;
179
+ };
180
+ /** Creates a PDF.js URL source object that can be passed directly to `new PDFReader(...)`. */
181
+ declare function pdfUrlSource(url: string | URL, options?: PdfUrlSourceOptions): PdfUrlSource;
182
+
183
+ /**
184
+ * Configures PDF.js without bundler-specific imports or package-load side effects.
185
+ * Pass either a worker URL emitted by your bundler or an existing module Worker.
186
+ *
187
+ * Calling this again replaces the previous configuration. When passing an
188
+ * existing `Worker`, the caller retains ownership of terminating it.
189
+ */
190
+ declare function configurePdfWorker(worker: string | Worker): void;
191
+
192
+ export { type BlobPageImage, type ConvertOptions, type DataUrlPageImage, type ExtractedImage, type LoadOptions, type LoadedPdfDocument, type LoadedPdfPage, PDFReader, type PageImageMimeType, type PageImageOutputMode, type PageImageResult, type PageRange, type PageResult, PdfReaderError, type PdfReaderErrorCode, type PdfReaderLimits, type PdfReaderLogger, type PdfReaderOptions, type PdfReaderSourceInfo, type PdfReaderSourcePolicy, type PdfReaderState, type PdfSource, type PdfTextContent, type PdfUrlSource, type PdfUrlSourceOptions, type TransformMatrix, type ViewportScale, configurePdfWorker, pdfUrlSource };