@shuji-bonji/pdf-reader-mcp 0.13.0 → 0.14.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.
- package/CHANGELOG.md +144 -4
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/services/page-renderer.d.ts +25 -0
- package/dist/services/page-renderer.d.ts.map +1 -1
- package/dist/services/page-renderer.js +160 -62
- package/dist/services/page-renderer.js.map +1 -1
- package/dist/services/page-renderer.worker.mjs +104 -0
- package/dist/services/reading-scope.d.ts +115 -0
- package/dist/services/reading-scope.d.ts.map +1 -0
- package/dist/services/reading-scope.js +123 -0
- package/dist/services/reading-scope.js.map +1 -0
- package/dist/services/validation-service.d.ts.map +1 -1
- package/dist/services/validation-service.js +78 -15
- package/dist/services/validation-service.js.map +1 -1
- package/dist/tools/tier1/read-text.d.ts.map +1 -1
- package/dist/tools/tier1/read-text.js +49 -34
- package/dist/tools/tier1/read-text.js.map +1 -1
- package/dist/tools/tier1/read-url.d.ts.map +1 -1
- package/dist/tools/tier1/read-url.js +62 -38
- package/dist/tools/tier1/read-url.js.map +1 -1
- package/dist/tools/tier1/render-page.d.ts.map +1 -1
- package/dist/tools/tier1/render-page.js +2 -0
- package/dist/tools/tier1/render-page.js.map +1 -1
- package/dist/tools/tier1/search-text.d.ts.map +1 -1
- package/dist/tools/tier1/search-text.js +66 -55
- package/dist/tools/tier1/search-text.js.map +1 -1
- package/dist/tools/tier1/summarize.d.ts.map +1 -1
- package/dist/tools/tier1/summarize.js +71 -37
- package/dist/tools/tier1/summarize.js.map +1 -1
- package/dist/tools/tier2/extract-structured-text.d.ts.map +1 -1
- package/dist/tools/tier2/extract-structured-text.js +38 -28
- package/dist/tools/tier2/extract-structured-text.js.map +1 -1
- package/dist/tools/tier3/compare-structure.d.ts.map +1 -1
- package/dist/tools/tier3/compare-structure.js +2 -0
- package/dist/tools/tier3/compare-structure.js.map +1 -1
- package/dist/tools/tier3/validate-tagged.d.ts.map +1 -1
- package/dist/tools/tier3/validate-tagged.js +2 -0
- package/dist/tools/tier3/validate-tagged.js.map +1 -1
- package/dist/types.d.ts +56 -13
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/error-handler.d.ts.map +1 -1
- package/dist/utils/error-handler.js +15 -2
- package/dist/utils/error-handler.js.map +1 -1
- package/dist/utils/formatter.d.ts.map +1 -1
- package/dist/utils/formatter.js +41 -17
- package/dist/utils/formatter.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,142 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [0.14.0] - 2026-08-30
|
|
9
|
+
|
|
10
|
+
Text-returning tools now say which of the readings behind their answer were
|
|
11
|
+
actually done. Output shapes change — read **Changed** before upgrading.
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- **`read_url` returned an error for every input.** The bytes fetched from the
|
|
16
|
+
URL were handed to pdfjs and then, concurrently, to the extractability
|
|
17
|
+
observation. pdfjs takes ownership of the `Uint8Array` it is given and moves
|
|
18
|
+
its buffer to a worker, so the second reader saw zero bytes and reported
|
|
19
|
+
`Failed to parse PDF document (line:0 col:0 offset=0): No PDF header found`.
|
|
20
|
+
Measured over the 40-specimen smoke set: 40 of 40 calls were `isError`. Each
|
|
21
|
+
reader now gets its own copy of the bytes.
|
|
22
|
+
|
|
23
|
+
- **The error a caller received for an unreadable file was decided by a race.**
|
|
24
|
+
`read_text`, `read_url`, `search_text`, `summarize` and
|
|
25
|
+
`extract_structured_text` each ran two readings inside `Promise.all`, which
|
|
26
|
+
rejects with whichever rejected first. Twelve calls with the same file
|
|
27
|
+
returned `INVALID_PDF` ten times and `INTERNAL_ERROR` twice, with different
|
|
28
|
+
`hint` and `next_actions` each way. Taking the same golden twice, with
|
|
29
|
+
nothing changed, produced three differences.
|
|
30
|
+
|
|
31
|
+
- **A damaged file was reported as this server's fault.** pdf-lib's parse
|
|
32
|
+
failures (`Failed to parse ...`, `No PDF header found`,
|
|
33
|
+
`Expected instance of PDF...`) fell through to `INTERNAL_ERROR`; they are
|
|
34
|
+
`INVALID_PDF`.
|
|
35
|
+
|
|
36
|
+
- **A 3.4 KB file could stop the server for good.** `render_page` called PDFium
|
|
37
|
+
on the main thread, and PDFium runs synchronously inside WebAssembly. Two
|
|
38
|
+
files in the veraPDF corpus (`TWG test suite A018-pdfa2-pass-b.pdf` and
|
|
39
|
+
`-fail-b.pdf`) never came back: twenty minutes in, the process still had to be
|
|
40
|
+
killed. A timer set to fire every second during the call fired zero times —
|
|
41
|
+
the event loop was blocked, so no timeout written in JavaScript could have
|
|
42
|
+
interrupted it.
|
|
43
|
+
|
|
44
|
+
The cause is in the file, and it is not a violation. The page is filled with a
|
|
45
|
+
tiling pattern (ISO 32000-2 §8.7.3.1) whose `/YStep` is `-1.175e-38`. Table 74
|
|
46
|
+
says `XStep` and `YStep` "may be either positive or negative but shall not be
|
|
47
|
+
zero"; this is not zero. It is the smallest magnitude a float32 can hold, so
|
|
48
|
+
tiling 500 points at that step asks for more than 10^38 tiles.
|
|
49
|
+
|
|
50
|
+
Rendering now runs in a worker thread with a **20-second budget per page**
|
|
51
|
+
(`PDF_READER_RENDER_TIMEOUT_MS` overrides it, or `pageTimeoutMs` in-process).
|
|
52
|
+
`worker.terminate()` does stop a wedged PDFium — measured. Pages rendered
|
|
53
|
+
before the stuck one are still returned; the stuck page is named in `omitted`
|
|
54
|
+
with the reason; pages after it are reported separately as `not attempted`,
|
|
55
|
+
because "could not be rendered" and "never started" are different answers.
|
|
56
|
+
|
|
57
|
+
The worker is `src/services/page-renderer.worker.mjs` — plain JavaScript, not
|
|
58
|
+
TypeScript, and it imports nothing from `src`. Node runs it as it is: Node 20
|
|
59
|
+
has no type stripping and Node 22 does not enable it in every release, so a
|
|
60
|
+
`.ts` worker fails with `Unknown file extension ".ts"` (it did, on both CI Node
|
|
61
|
+
versions). For the same reason the worker only produces pixels; the BGRA-to-RGB
|
|
62
|
+
conversion, the downscale and the encoding stay on the calling side, with the
|
|
63
|
+
bitmap handed over as a transferable so nothing is copied. `npm run build`
|
|
64
|
+
copies the worker into `dist` (`scripts/copy-worker.mjs`), and a test fails if
|
|
65
|
+
that coupling is broken.
|
|
66
|
+
|
|
67
|
+
### Changed
|
|
68
|
+
|
|
69
|
+
- **Two readings, reported separately (#26).** Taking the characters off a page
|
|
70
|
+
(pdfjs) and observing whether those characters have a route to Unicode
|
|
71
|
+
(ISO 32000-2 §9.10.1, pdf-lib) are separate questions that fail separately.
|
|
72
|
+
Over 2,931 corpus files: 2,927 both succeeded, 3 had the text but not the
|
|
73
|
+
observation, and 1 had neither. In those 3 the tool returned an error and
|
|
74
|
+
**threw away text it had already extracted** — 13, 0 and 86 characters.
|
|
75
|
+
|
|
76
|
+
Every text-returning tool now carries `scope`:
|
|
77
|
+
|
|
78
|
+
```jsonc
|
|
79
|
+
{ "scope": { "textExtraction": { "status": "read" },
|
|
80
|
+
"extractabilityObservation": {
|
|
81
|
+
"status": "failed", "code": "INVALID_PDF", "reason": "..." } },
|
|
82
|
+
"pages": [ … ] }
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Only when *neither* reading could be done is the call an error, and it then
|
|
86
|
+
names both reasons in `detail.cause`.
|
|
87
|
+
|
|
88
|
+
- **Output shapes.** `read_text` and `read_url` return `{ scope, pages }` where
|
|
89
|
+
they returned a bare array of pages. `search_text`,
|
|
90
|
+
`extract_structured_text` and `summarize` gain `scope`.
|
|
91
|
+
|
|
92
|
+
- **`null` where a reading did not happen — never `0`, `false` or `""`.**
|
|
93
|
+
"Not read" and "read and found nothing" are different answers.
|
|
94
|
+
|
|
95
|
+
| Field | `null` means | The observed answer |
|
|
96
|
+
| --- | --- | --- |
|
|
97
|
+
| `PageText.text` | the extraction did not run | `""` — it ran and produced no characters |
|
|
98
|
+
| `SearchResult.totalMatches` / `matches` | the search did not run | `0` / `[]` — searched, nothing found |
|
|
99
|
+
| `StructuredTextResult.isTagged` / `elements` | the structure tree was not read | `false` / `[]` — read, no tags |
|
|
100
|
+
| `PdfSummary.metadata` / `textPreview` / `imageCount` / `hasText` / `textExtractability` / `unreadablePages` | that reading did not run | the value it measured |
|
|
101
|
+
|
|
102
|
+
When the observation could not run, pages carry no `extractability` field at
|
|
103
|
+
all rather than one filled with zeros: `0` fonts observed and "not observed"
|
|
104
|
+
are different answers.
|
|
105
|
+
|
|
106
|
+
- **`summarize.next` stays silent about a premise it did not observe.** It used
|
|
107
|
+
to derive its suggestions from metadata; with metadata unread it now suggests
|
|
108
|
+
nothing rather than reasoning from absence.
|
|
109
|
+
|
|
110
|
+
- **`validate_tagged` no longer passes a check it could not make.** TAG-005
|
|
111
|
+
judges Figure tags against the number of images the page draws. When that
|
|
112
|
+
count could not be observed, the check previously fell into the branch for
|
|
113
|
+
"no images", which counted as a pass. It is now excluded from `totalChecks`
|
|
114
|
+
and listed in the new `notChecked` field with the reason.
|
|
115
|
+
|
|
116
|
+
- **`compare_structure` names which file it could not read.** The comparison
|
|
117
|
+
still needs both files, but the error says which of the two failed, and that
|
|
118
|
+
the other one was fine.
|
|
119
|
+
|
|
120
|
+
- **The message for a password-protected file describes what happened.** It
|
|
121
|
+
said "pdf-reader-mcp does not support encrypted PDFs"; the text cannot be
|
|
122
|
+
extracted because the file encryption key is derived from the user password
|
|
123
|
+
(ISO 32000-2 §7.6.4.3.2), while the structure observation continues over what
|
|
124
|
+
is not encrypted.
|
|
125
|
+
|
|
126
|
+
### Added
|
|
127
|
+
|
|
128
|
+
- `src/services/reading-scope.ts` — the shared shape for the above.
|
|
129
|
+
- `tests/e2e/15-reading-scope.test.ts` — 15 tests pinning all four combinations
|
|
130
|
+
of the two readings, including that twelve identical calls return one code.
|
|
131
|
+
- `scripts/probe-read-halves.mjs` — runs the two readings separately and counts
|
|
132
|
+
the four combinations over a corpus.
|
|
133
|
+
- `scripts/golden-specimens-halves.mjs` — one specimen per combination. The
|
|
134
|
+
`fail/ok` case did not exist anywhere in the 2,931-file corpus; it needs a
|
|
135
|
+
document with a non-empty user password, so it is built with qpdf under
|
|
136
|
+
`--static-id` to keep the bytes identical run to run.
|
|
137
|
+
- `scripts/golden.mjs` — freezes the output of all 19 tools across 23 calls, so
|
|
138
|
+
the pdf-lib removal that follows can be attributed difference by difference.
|
|
139
|
+
- `scripts/golden-specimens-render.mjs` and
|
|
140
|
+
`tests/e2e/16-render-timeout.test.ts` — a three-page specimen whose second
|
|
141
|
+
page never finishes rasterising, built from the clause rather than copied from
|
|
142
|
+
the corpus, plus the four tests that pin the behaviour above.
|
|
143
|
+
|
|
8
144
|
## [0.13.0] - 2026-08-27
|
|
9
145
|
|
|
10
146
|
Infrastructure only: no tool gained or lost a capability, and no tool's output
|
|
@@ -31,10 +167,14 @@ changed. Four things reach callers — read **Changed** before upgrading.
|
|
|
31
167
|
- **`inputSchema` in `tools/list`**: `$schema` is now
|
|
32
168
|
`https://json-schema.org/draft/2020-12/schema` (was draft-07) for all 19
|
|
33
169
|
tools. `additionalProperties: false` is unchanged in the response — what
|
|
34
|
-
changed is that it is now true of the running server.
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
170
|
+
changed is that it is now true of the running server. One bound moved:
|
|
171
|
+
`locate_objects`' `object_numbers` items now carry
|
|
172
|
+
`maximum: 9007199254740991` alongside `minimum: 1` — zod 4 writes the safe
|
|
173
|
+
integer bound that zod 3 left out. It is the only property in the 19 tools
|
|
174
|
+
whose schema body changed. Tool names, descriptions and `required` are
|
|
175
|
+
unchanged — measured tool by tool against 0.12.0 with
|
|
176
|
+
`scripts/tools-list-snapshot.mjs`, which speaks raw JSON-RPC over stdio
|
|
177
|
+
rather than using an SDK client.
|
|
38
178
|
- `zod` moves from `^3.23.8` to `^4.2.0` — the version all four servers in the
|
|
39
179
|
family now share. `typescript` moves to `^7.0.2` (a devDependency).
|
|
40
180
|
|
package/dist/index.js
CHANGED
|
@@ -45,6 +45,12 @@ What it does NOT do:
|
|
|
45
45
|
therefore never on its own evidence that a page has no text. When a page cannot be read as
|
|
46
46
|
text, render_page rasterises it (PDFium-WASM, optional dependency) so a vision model can
|
|
47
47
|
read the pixels instead.
|
|
48
|
+
- No collapsing of two readings into one verdict. Taking the characters off a page and
|
|
49
|
+
observing whether those characters have a route to Unicode are separate readings that
|
|
50
|
+
can fail separately, so every text-returning tool reports which of them were done under
|
|
51
|
+
\`scope\`, and a field whose reading did not happen is \`null\` — never zero, false or an
|
|
52
|
+
empty string. "Not read" and "read and found nothing" are different answers, and this
|
|
53
|
+
server keeps them apart.
|
|
48
54
|
|
|
49
55
|
It DOES map content to coordinates: locate_objects turns an object number into a page and a
|
|
50
56
|
rectangle, and extract_structured_text with include_bbox does the same for a structure element.
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;;GAKG;AAEH,8CAA8C;AAC9C,sEAAsE;AACtE,sEAAsE;AACtE,MAAM,mBAAmB,GAAG,OAAO,CAAC,GAAG,CAAC;AACxC,MAAM,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC;AAC1C,OAAO,CAAC,GAAG,GAAG,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;AACtE,OAAO,CAAC,IAAI,GAAG,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,IAAI,CAAC,CAAC;AAExE,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AACzD,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,cAAc,E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AM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,KAAK,CAAC,GAAG,WAAW,KAAK,cAAc,oBAAoB,CAAC,CAAC;AACvE,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;IACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
|
|
@@ -21,6 +21,19 @@
|
|
|
21
21
|
* is stated in the tool description rather than hidden: a rendering difference
|
|
22
22
|
* between the two is possible, and pretending one engine produced both outputs
|
|
23
23
|
* would misattribute any such difference.
|
|
24
|
+
*
|
|
25
|
+
* 🔴 描画そのものは Worker で走る(#27)。PDFium は WASM の中で同期に走るので、
|
|
26
|
+
* 終わらない文書があるとイベントループごと止まり、サーバは応答を返さなくなる。
|
|
27
|
+
* JavaScript 側の時限では割り込めない(タイマーの印が 1 つも出ないことを実測)。
|
|
28
|
+
* `worker.terminate()` は止まった PDFium を実際に止められるので、そこに移した。
|
|
29
|
+
* 詳細と実例は `page-renderer.worker.mjs` の冒頭にある。
|
|
30
|
+
*
|
|
31
|
+
* 🔴 **Worker が作るのは画素までで、符号化はこちら側で行う。** worker は
|
|
32
|
+
* `src` の module を 1 つも import できない —— TypeScript で書くと Node 20 には
|
|
33
|
+
* 型剥がしが無く、Node 22 でも版によっては既定で有効ではないので
|
|
34
|
+
* `Unknown file extension ".ts"` で落ちる(CI の Node 20 / 22 で実際に落とした)。
|
|
35
|
+
* だから worker は `.mjs` で、PDFium 以外に依存を持たない。画素は転送可能
|
|
36
|
+
* オブジェクトとして受け取るので、複製は起きない。
|
|
24
37
|
*/
|
|
25
38
|
/** One rendered page, as an encoded image file. */
|
|
26
39
|
export interface RenderedPage {
|
|
@@ -50,6 +63,12 @@ export interface RenderResult {
|
|
|
50
63
|
export interface RenderOptions {
|
|
51
64
|
/** Rasterisation density. Default 150 — text is legible, files stay small. */
|
|
52
65
|
dpi?: number;
|
|
66
|
+
/**
|
|
67
|
+
* 1 ページの描画に許す時間(ミリ秒)。既定 20,000。
|
|
68
|
+
* 越えたページは描画を止め、`omitted` に理由を書いて次へ進む。
|
|
69
|
+
* 環境変数 `PDF_READER_RENDER_TIMEOUT_MS` でも変えられる。
|
|
70
|
+
*/
|
|
71
|
+
pageTimeoutMs?: number;
|
|
53
72
|
/** Cap on the rendered width in pixels; overrides dpi when smaller. */
|
|
54
73
|
maxWidth?: number;
|
|
55
74
|
format?: 'png' | 'jpeg';
|
|
@@ -58,6 +77,12 @@ export interface RenderOptions {
|
|
|
58
77
|
maxTotalBytes?: number;
|
|
59
78
|
}
|
|
60
79
|
export declare const DEFAULT_RENDER_DPI = 150;
|
|
80
|
+
/**
|
|
81
|
+
* 1 ページの描画に許す時間。20 秒。
|
|
82
|
+
* 大きいページを高い dpi で描くのは正当に数秒かかるので、それより十分長く取る。
|
|
83
|
+
* 越えたページは「時間内に描画できなかった」として申告し、次のページへ進む。
|
|
84
|
+
*/
|
|
85
|
+
export declare const DEFAULT_PAGE_TIMEOUT_MS = 20000;
|
|
61
86
|
/** True when the renderer is available in this installation. */
|
|
62
87
|
export declare function rendererAvailable(): Promise<boolean>;
|
|
63
88
|
export declare const RENDERER_MISSING_MESSAGE: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"page-renderer.d.ts","sourceRoot":"","sources":["../../src/services/page-renderer.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"page-renderer.d.ts","sourceRoot":"","sources":["../../src/services/page-renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAQH,mDAAmD;AACnD,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,wCAA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
21
|
* is stated in the tool description rather than hidden: a rendering difference
|
|
22
22
|
* between the two is possible, and pretending one engine produced both outputs
|
|
23
23
|
* would misattribute any such difference.
|
|
24
|
+
*
|
|
25
|
+
* 🔴 描画そのものは Worker で走る(#27)。PDFium は WASM の中で同期に走るので、
|
|
26
|
+
* 終わらない文書があるとイベントループごと止まり、サーバは応答を返さなくなる。
|
|
27
|
+
* JavaScript 側の時限では割り込めない(タイマーの印が 1 つも出ないことを実測)。
|
|
28
|
+
* `worker.terminate()` は止まった PDFium を実際に止められるので、そこに移した。
|
|
29
|
+
* 詳細と実例は `page-renderer.worker.mjs` の冒頭にある。
|
|
30
|
+
*
|
|
31
|
+
* 🔴 **Worker が作るのは画素までで、符号化はこちら側で行う。** worker は
|
|
32
|
+
* `src` の module を 1 つも import できない —— TypeScript で書くと Node 20 には
|
|
33
|
+
* 型剥がしが無く、Node 22 でも版によっては既定で有効ではないので
|
|
34
|
+
* `Unknown file extension ".ts"` で落ちる(CI の Node 20 / 22 で実際に落とした)。
|
|
35
|
+
* だから worker は `.mjs` で、PDFium 以外に依存を持たない。画素は転送可能
|
|
36
|
+
* オブジェクトとして受け取るので、複製は起きない。
|
|
24
37
|
*/
|
|
38
|
+
import { Worker } from 'node:worker_threads';
|
|
25
39
|
import { DEFAULT_IMAGE_QUALITY, MAX_IMAGE_PIXELS, MAX_IMAGE_RESPONSE_BYTES } from '../constants.js';
|
|
26
40
|
import { readPdfFile, resolvePageNumbers } from '../utils/pdf-helpers.js';
|
|
27
41
|
import { encodeJpeg, encodePng } from './image-encoder.js';
|
|
28
42
|
import { downscale } from './image-resampler.js';
|
|
29
43
|
export const DEFAULT_RENDER_DPI = 150;
|
|
44
|
+
/**
|
|
45
|
+
* 1 ページの描画に許す時間。20 秒。
|
|
46
|
+
* 大きいページを高い dpi で描くのは正当に数秒かかるので、それより十分長く取る。
|
|
47
|
+
* 越えたページは「時間内に描画できなかった」として申告し、次のページへ進む。
|
|
48
|
+
*/
|
|
49
|
+
export const DEFAULT_PAGE_TIMEOUT_MS = 20_000;
|
|
30
50
|
/** The pdfium module, loaded once. `null` after a failed attempt. */
|
|
31
51
|
let pdfiumLibrary;
|
|
32
52
|
/**
|
|
@@ -76,72 +96,150 @@ function bgraToRgb(width, height, bgra) {
|
|
|
76
96
|
* reported in `omitted` with the reason, mirroring `read_images` (#22).
|
|
77
97
|
*/
|
|
78
98
|
export async function renderPages(filePath, pages, options = {}) {
|
|
79
|
-
|
|
80
|
-
if (!library)
|
|
99
|
+
if (!(await rendererAvailable()))
|
|
81
100
|
throw new Error(RENDERER_MISSING_MESSAGE);
|
|
82
|
-
const dpi = options.dpi ?? DEFAULT_RENDER_DPI;
|
|
83
101
|
const format = options.format ?? 'png';
|
|
84
102
|
const quality = options.quality ?? DEFAULT_IMAGE_QUALITY;
|
|
85
103
|
const budget = options.maxTotalBytes ?? MAX_IMAGE_RESPONSE_BYTES;
|
|
86
|
-
const
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
104
|
+
const fromEnv = Number(process.env.PDF_READER_RENDER_TIMEOUT_MS);
|
|
105
|
+
const timeoutMs = options.pageTimeoutMs ??
|
|
106
|
+
(Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : DEFAULT_PAGE_TIMEOUT_MS);
|
|
107
|
+
// 🔴 ページ番号の解決とファイルの読み込みは、ここで済ませる。Worker は
|
|
108
|
+
// 型剥がしで動くので、`enum` を持つ constants.js に届く module を import できない。
|
|
109
|
+
const bytes = await readPdfFile(filePath);
|
|
110
|
+
// 🔴 拡張子は .mjs 固定。src からも dist からも、Node がそのまま実行できる形。
|
|
111
|
+
const workerUrl = new URL('./page-renderer.worker.mjs', import.meta.url);
|
|
112
|
+
const rendered = [];
|
|
113
|
+
const omitted = [];
|
|
114
|
+
let totalEncodedBytes = 0;
|
|
115
|
+
let planned = null;
|
|
116
|
+
let inFlight = null;
|
|
117
|
+
await new Promise((resolve, reject) => {
|
|
118
|
+
const worker = new Worker(workerUrl, {
|
|
119
|
+
workerData: {
|
|
120
|
+
bytes,
|
|
121
|
+
dpi: options.dpi ?? DEFAULT_RENDER_DPI,
|
|
122
|
+
maxWidth: options.maxWidth,
|
|
123
|
+
maxPixels: MAX_IMAGE_PIXELS,
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
let timer;
|
|
127
|
+
let settled = false;
|
|
128
|
+
const finish = (error) => {
|
|
129
|
+
if (settled)
|
|
130
|
+
return;
|
|
131
|
+
settled = true;
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
void worker.terminate();
|
|
134
|
+
if (error)
|
|
135
|
+
reject(error);
|
|
136
|
+
else
|
|
137
|
+
resolve();
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* 🔴 時限はメッセージが届くたびに引き直す。1 ページごとの予算であって、
|
|
141
|
+
* 呼び出し全体の予算ではない —— 10 ページを 5 秒ずつ描くのは正常な仕事である。
|
|
142
|
+
*/
|
|
143
|
+
const arm = () => {
|
|
144
|
+
clearTimeout(timer);
|
|
145
|
+
timer = setTimeout(() => {
|
|
146
|
+
// 止まったページと、まだ始まっていないページを、理由付きで申告する。
|
|
147
|
+
// 🔴 黙って落とすと「描画するものが無かった」と見分けが付かなくなる。
|
|
148
|
+
const stuck = inFlight;
|
|
149
|
+
if (stuck !== null) {
|
|
150
|
+
omitted.push({
|
|
151
|
+
page: stuck,
|
|
152
|
+
reason: `rendering did not finish within ${timeoutMs} ms and was stopped. ` +
|
|
153
|
+
'A page can take unbounded time to rasterise — for example a tiling ' +
|
|
154
|
+
'pattern (ISO 32000-2 §8.7.3.1) whose /XStep or /YStep is a near-zero ' +
|
|
155
|
+
'magnitude, which asks for an astronomical number of tiles. Lower dpi ' +
|
|
156
|
+
'or pass max_width if the page is merely large; otherwise this page ' +
|
|
157
|
+
'cannot be rasterised here.',
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
for (const page of planned ?? []) {
|
|
161
|
+
if (stuck !== null && page > stuck) {
|
|
162
|
+
omitted.push({
|
|
163
|
+
page,
|
|
164
|
+
reason: `not attempted — rendering stopped at page ${stuck}.`,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
finish();
|
|
169
|
+
}, timeoutMs);
|
|
170
|
+
};
|
|
171
|
+
arm();
|
|
172
|
+
worker.on('message', (message) => {
|
|
173
|
+
arm();
|
|
174
|
+
switch (message.t) {
|
|
175
|
+
case 'pagecount': {
|
|
176
|
+
try {
|
|
177
|
+
planned = resolvePageNumbers(pages, message.pageCount);
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
worker.postMessage({ pageNumbers: planned });
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
case 'plan':
|
|
187
|
+
planned = message.pageNumbers;
|
|
188
|
+
return;
|
|
189
|
+
case 'start':
|
|
190
|
+
inFlight = message.page;
|
|
191
|
+
return;
|
|
192
|
+
case 'bitmap': {
|
|
193
|
+
// 画素を受け取ってから符号化する。ここは有界な仕事なので、
|
|
194
|
+
// 止まる心配があるのは worker の側だけ。
|
|
195
|
+
inFlight = null;
|
|
196
|
+
const pageNumber = message.page;
|
|
197
|
+
const pointWidth = message.pointWidth;
|
|
198
|
+
let samples = bgraToRgb(message.width, message.height, message.data);
|
|
199
|
+
if (options.maxWidth && samples.width > options.maxWidth) {
|
|
200
|
+
samples = downscale(samples, options.maxWidth);
|
|
201
|
+
}
|
|
202
|
+
const encoded = format === 'jpeg'
|
|
203
|
+
? encodeJpeg(samples.width, samples.height, 3, samples.data, quality)
|
|
204
|
+
: encodePng(samples.width, samples.height, 2, 8, samples.data);
|
|
205
|
+
if (totalEncodedBytes + encoded.length > budget) {
|
|
206
|
+
omitted.push({
|
|
207
|
+
page: pageNumber,
|
|
208
|
+
reason: `${encoded.length.toLocaleString()} bytes would take the response past the ` +
|
|
209
|
+
`${budget.toLocaleString()}-byte budget. Render fewer pages per call, ` +
|
|
210
|
+
'lower dpi, or pass format: "jpeg".',
|
|
211
|
+
});
|
|
212
|
+
arm();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
totalEncodedBytes += encoded.length;
|
|
216
|
+
rendered.push({
|
|
217
|
+
page: pageNumber,
|
|
218
|
+
width: samples.width,
|
|
219
|
+
height: samples.height,
|
|
220
|
+
pointWidth: Math.round(pointWidth),
|
|
221
|
+
pointHeight: Math.round(message.pointHeight),
|
|
222
|
+
effectiveDpi: Math.round((samples.width / pointWidth) * 72),
|
|
223
|
+
mimeType: format === 'jpeg' ? 'image/jpeg' : 'image/png',
|
|
224
|
+
encodedBytes: encoded.length,
|
|
225
|
+
dataBase64: encoded.toString('base64'),
|
|
226
|
+
});
|
|
227
|
+
// 🔴 符号化のあとで時限を引き直す。符号化の時間を worker の予算から引かない。
|
|
228
|
+
arm();
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
case 'omit':
|
|
232
|
+
inFlight = null;
|
|
233
|
+
omitted.push({ page: message.page, reason: message.reason });
|
|
234
|
+
return;
|
|
235
|
+
case 'done':
|
|
236
|
+
finish();
|
|
237
|
+
return;
|
|
100
238
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
'Lower dpi or pass max_width.',
|
|
107
|
-
});
|
|
108
|
-
continue;
|
|
109
|
-
}
|
|
110
|
-
const bitmap = await page.render({ scale, render: 'bitmap' });
|
|
111
|
-
let samples = bgraToRgb(bitmap.width, bitmap.height, bitmap.data);
|
|
112
|
-
if (options.maxWidth && samples.width > options.maxWidth) {
|
|
113
|
-
samples = downscale(samples, options.maxWidth);
|
|
114
|
-
}
|
|
115
|
-
const bytes = format === 'jpeg'
|
|
116
|
-
? encodeJpeg(samples.width, samples.height, 3, samples.data, quality)
|
|
117
|
-
: encodePng(samples.width, samples.height, 2, 8, samples.data);
|
|
118
|
-
const mimeType = format === 'jpeg' ? 'image/jpeg' : 'image/png';
|
|
119
|
-
if (totalEncodedBytes + bytes.length > budget) {
|
|
120
|
-
omitted.push({
|
|
121
|
-
page: pageNumber,
|
|
122
|
-
reason: `${bytes.length.toLocaleString()} bytes would take the response past the ` +
|
|
123
|
-
`${budget.toLocaleString()}-byte budget. Render fewer pages per call, lower dpi, ` +
|
|
124
|
-
'or pass format: "jpeg".',
|
|
125
|
-
});
|
|
126
|
-
continue;
|
|
127
|
-
}
|
|
128
|
-
totalEncodedBytes += bytes.length;
|
|
129
|
-
rendered.push({
|
|
130
|
-
page: pageNumber,
|
|
131
|
-
width: samples.width,
|
|
132
|
-
height: samples.height,
|
|
133
|
-
pointWidth: Math.round(originalWidth),
|
|
134
|
-
pointHeight: Math.round(originalHeight),
|
|
135
|
-
effectiveDpi: Math.round((samples.width / originalWidth) * 72),
|
|
136
|
-
mimeType,
|
|
137
|
-
encodedBytes: bytes.length,
|
|
138
|
-
dataBase64: bytes.toString('base64'),
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
return { pages: rendered, omitted, totalEncodedBytes };
|
|
142
|
-
}
|
|
143
|
-
finally {
|
|
144
|
-
document.destroy();
|
|
145
|
-
}
|
|
239
|
+
});
|
|
240
|
+
worker.on('error', (error) => finish(error));
|
|
241
|
+
worker.on('exit', () => finish());
|
|
242
|
+
});
|
|
243
|
+
return { pages: rendered, omitted, totalEncodedBytes };
|
|
146
244
|
}
|
|
147
245
|
//# sourceMappingURL=page-renderer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"page-renderer.js","sourceRoot":"","sources":["../../src/services/page-renderer.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"page-renderer.js","sourceRoot":"","sources":["../../src/services/page-renderer.ts"],"names":[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;oBACjF,OAAO;gBACT,KAAK,MAAM;oBACT,MAAM,EAAE,CAAC;oBACT,OAAO;YACX,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QAC7C,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;IAEH,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC;AACzD,CAAC"}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `render_page` のラスタライズをこのスレッドで行う(#27)。
|
|
3
|
+
*
|
|
4
|
+
* ## なぜ別スレッドか
|
|
5
|
+
*
|
|
6
|
+
* PDFium は WASM の中で**同期に**走る。描画が終わらない文書があると、その間
|
|
7
|
+
* イベントループごと止まり、サーバは応答を返さなくなる。1 秒ごとに印を出す
|
|
8
|
+
* タイマーを仕掛けて描画を呼び、印が 1 つも出ないことを実測した。
|
|
9
|
+
* JavaScript 側に時限を置いても割り込めない、ということである。
|
|
10
|
+
*
|
|
11
|
+
* 実例(veraPDF コーパス・TWG test suite A018-pdfa2-pass-b.pdf・3,461 バイト):
|
|
12
|
+
* タイリングパターン(ISO 32000-2 §8.7.3.1)の `/YStep` が **-1.175e-38**。
|
|
13
|
+
* Table 74 は XStep / YStep について「正でも負でもよいが 0 であってはならない」と
|
|
14
|
+
* 書いており、この値は 0 ではないので条文には反しない。ただし 1.175e-38 は
|
|
15
|
+
* float32 で表せる最小の大きさで、その間隔で敷き詰めると 10^38 枚のタイルになる。
|
|
16
|
+
* 500×500 ポイントの 1 ページで、20 分待っても返らなかった。
|
|
17
|
+
*
|
|
18
|
+
* `worker.terminate()` は止まった PDFium を実際に止められる(3 秒で exit を実測)。
|
|
19
|
+
*
|
|
20
|
+
* ## 🔴 なぜ .mjs で、なぜ何も import しないか
|
|
21
|
+
*
|
|
22
|
+
* このファイルは Node が**そのまま**実行する。TypeScript で書くと、Node 20 には
|
|
23
|
+
* 型剥がしが無く、Node 22 でも版によっては既定で有効ではないため
|
|
24
|
+
* `Unknown file extension ".ts"` で落ちる(CI の Node 20 / 22 で実際に落とした)。
|
|
25
|
+
*
|
|
26
|
+
* 同じ理由で、この worker は `src` の module を 1 つも import しない。
|
|
27
|
+
* import すると、試験では `.ts` を読むことになり同じ壁に当たる。
|
|
28
|
+
* だからここでやるのは **PDFium で画素を作るところまで**で、
|
|
29
|
+
* BGRA から RGB への変換・縮小・符号化は呼び出し側で行う。
|
|
30
|
+
* 画素は転送可能オブジェクトとして渡すので、複製は起きない。
|
|
31
|
+
*
|
|
32
|
+
* `package.json` の `build` がこのファイルを `dist/services/` へ複製する。
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
36
|
+
|
|
37
|
+
const post = (message, transfer) => parentPort?.postMessage(message, transfer);
|
|
38
|
+
|
|
39
|
+
/** 呼び出し側がページ番号を解決して送り返してくるのを待つ。 */
|
|
40
|
+
function awaitPageNumbers() {
|
|
41
|
+
return new Promise((resolve) => {
|
|
42
|
+
parentPort?.once('message', (message) => resolve(message.pageNumbers));
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// 🔴 パッケージ名を変数にするのは、バンドラにここを解決させないため。
|
|
47
|
+
// @hyzyla/pdfium は optionalDependencies にあり、無くてもサーバは起動する。
|
|
48
|
+
const specifier = '@hyzyla/pdfium';
|
|
49
|
+
const module_ = await import(specifier);
|
|
50
|
+
const library = await module_.PDFiumLibrary.init();
|
|
51
|
+
const document_ = await library.loadDocument(new Uint8Array(workerData.bytes));
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
post({ t: 'pagecount', pageCount: document_.getPageCount() });
|
|
55
|
+
const pageNumbers = await awaitPageNumbers();
|
|
56
|
+
post({ t: 'plan', pageNumbers });
|
|
57
|
+
|
|
58
|
+
for (const pageNumber of pageNumbers) {
|
|
59
|
+
// 🔴 描画を始める前に名乗る。返らなくなったとき、どのページで止まったかを
|
|
60
|
+
// 呼び出し側が言えるようにするため。
|
|
61
|
+
post({ t: 'start', page: pageNumber });
|
|
62
|
+
|
|
63
|
+
const page = document_.getPage(pageNumber - 1);
|
|
64
|
+
const { originalWidth, originalHeight } = page.getOriginalSize();
|
|
65
|
+
|
|
66
|
+
// dpi → scale: PDF points are 1/72 inch (ISO 32000-2 §8.3.2.3).
|
|
67
|
+
let scale = workerData.dpi / 72;
|
|
68
|
+
if (workerData.maxWidth && originalWidth * scale > workerData.maxWidth) {
|
|
69
|
+
scale = workerData.maxWidth / originalWidth;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (originalWidth * scale * originalHeight * scale > workerData.maxPixels) {
|
|
73
|
+
post({
|
|
74
|
+
t: 'omit',
|
|
75
|
+
page: pageNumber,
|
|
76
|
+
reason:
|
|
77
|
+
`${Math.round(originalWidth * scale)}×${Math.round(originalHeight * scale)} at ` +
|
|
78
|
+
`${workerData.dpi} dpi exceeds the ${workerData.maxPixels.toLocaleString()} pixel ` +
|
|
79
|
+
'limit. Lower dpi or pass max_width.',
|
|
80
|
+
});
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const bitmap = await page.render({ scale, render: 'bitmap' });
|
|
85
|
+
// 画素は転送する(複製しない)。BGRA のまま渡し、変換は呼び出し側で行う。
|
|
86
|
+
const data = new Uint8Array(bitmap.data);
|
|
87
|
+
post(
|
|
88
|
+
{
|
|
89
|
+
t: 'bitmap',
|
|
90
|
+
page: pageNumber,
|
|
91
|
+
width: bitmap.width,
|
|
92
|
+
height: bitmap.height,
|
|
93
|
+
pointWidth: originalWidth,
|
|
94
|
+
pointHeight: originalHeight,
|
|
95
|
+
data,
|
|
96
|
+
},
|
|
97
|
+
[data.buffer],
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
post({ t: 'done' });
|
|
102
|
+
} finally {
|
|
103
|
+
document_.destroy();
|
|
104
|
+
}
|