dsh-pdf-mineru 0.0.14 → 0.0.15
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 +22 -0
- package/README.md +15 -4
- package/lib/index.js +189 -53
- package/lib/pdfjs-worker.mjs +457 -0
- package/lib/types/service/mineru-service.d.ts +1 -0
- package/lib/types/service/page-renderer.d.ts +3 -2
- package/lib/types/service/pdfjs-backend.d.ts +5 -0
- package/lib/types/service/result-presenter.d.ts +3 -1
- package/package.json +5 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.0.15
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Added a local PDF.js 6.3.289 + @napi-rs/canvas 1.0.9 subprocess fallback for original-page rendering. Normal installation includes renderer dependencies and package-local font/CMap/WASM resources; no system Poppler installation is required on supported native platforms.
|
|
8
|
+
- Added explicit original-page renderer identity to result types, strict tool output schemas, Native text and presentation metadata; physical page-count provenance distinguishes pdfinfo from pdfjs.
|
|
9
|
+
- Added deterministic backend-selection regressions, isolated PDF.js worker tests, full-tool offline auto/fallback smoke modes and an installed-package smoke from an unrelated working directory.
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- Keep Poppler preferred; fall back only when an executable is missing or explicitly unavailable in the execution environment, never for PDF failures, page/hash validation, cancellation, timeout or resource limits.
|
|
14
|
+
- Both backends share one checked snapshot, concurrency slot and total deadline. PDF.js parsing and Canvas allocation run only in a fixed child process with bounded output and local package resources; cancellation waits for process reaping before cleanup.
|
|
15
|
+
- Ship the unbundled PDF.js subprocess entry explicitly and keep native/PDF runtime dependencies external to host/client bundles. Document native-platform installation conditions, resource controls and fidelity differences without claiming OS sandbox isolation or pixel equivalence.
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- Preserve cancellation and the shared deadline when temporary cleanup completes late; cleanup failures cannot replace an already determined primary error.
|
|
20
|
+
- Distinguish Poppler output I/O failures and abnormal process termination from invalid PDFs without retrying another backend.
|
|
21
|
+
- Reject truncated/corrupt PNG containers with bounded chunk, checksum and end-marker validation before attachment delivery.
|
|
22
|
+
|
|
23
|
+
Reader cursor v3, index v2, Provider contracts and parsed cache formats remain unchanged.
|
|
24
|
+
|
|
3
25
|
## 0.0.14
|
|
4
26
|
|
|
5
27
|
This release includes the bounded-reader work recorded under 0.0.13; the previous published release is 0.0.12.
|
package/README.md
CHANGED
|
@@ -54,6 +54,16 @@ dsh plugin --profile web add dsh-pdf-mineru
|
|
|
54
54
|
|
|
55
55
|
> 本地开发或测试源码时,可使用:`dsh plugin --profile web add link:/absolute/path/to/dsh-pdf-mineru`
|
|
56
56
|
|
|
57
|
+
### 本地原页渲染的安装条件
|
|
58
|
+
|
|
59
|
+
正常安装插件会安装固定版本的 [pdfjs-dist 6.3.289](https://www.npmjs.com/package/pdfjs-dist/v/6.3.289)(Apache-2.0)和 [@napi-rs/canvas 1.0.9](https://www.npmjs.com/package/@napi-rs/canvas/v/1.0.9)(MIT)。在支持的平台且未禁用平台可选依赖时,**无需系统安装 Poppler 即可使用原有原页接口**;字体、CMap、WASM 都从安装包本地加载,无 CDN。
|
|
60
|
+
|
|
61
|
+
这并非“纯 JavaScript、无原生依赖”:Canvas 使用预编译 Skia/N-API 平台二进制,包管理器通过 optionalDependencies 选择平台包,无安装期编译脚本。上游提供 Linux x64/arm64(glibc、musl)、Linux armv7(glibc)、Linux riscv64(glibc)、macOS x64/arm64、Windows x64/arm64 和 Android arm64 包;仍要求匹配的系统 ABI/运行库和本插件 Node 版本;Canvas上游文档要求glibc ≥2.18、Linux arm64为Cortex-A57或更新、armv7为Cortex-A7或更新,Node自身的系统要求仍须同时满足。实际验收平台为 Linux x64 glibc(Node 22.19.0 与26.8.2的独立生产安装包),其它平台有上游二进制不等于本仓库逐一验收。不要使用会删掉平台包的 --no-optional 安装选项。两后端均不可用时会提示安装 Poppler,或在支持平台重新安装插件及其平台可选依赖;不会使普通文本阅读失效。
|
|
62
|
+
|
|
63
|
+
PDF.js 包解压约34.8 MB,Canvas JS 约0.13 MB,Linux x64 glibc 二进制约34.8 MB(十进制,其他平台不同),这是安装依赖体积,不是插件 tarball 体积。PDF.js 的 Node 要求覆盖本插件现有 Node.js `^22.19.0 || >=24.0.0` 范围。
|
|
64
|
+
|
|
65
|
+
只对依赖/执行环境不可用自动切换:损坏、加密、解析失败、页码越界、源摘要不匹配、取消、资源超限或超时不会通过换后端重试。后端间可能存在字体、抗锯齿、透明度和裁切保真差异,不承诺像素相同;详见[阅读指南](docs/model-reading.md)。
|
|
66
|
+
|
|
57
67
|
### 2. 配置与连接
|
|
58
68
|
|
|
59
69
|
打开 DSH 界面中的 **Settings → Plugins → MinerU**,根据您的使用场景选择 Provider:
|
|
@@ -117,8 +127,8 @@ Agent 会自动根据文档长度和指令意图,智能选择同步返回或
|
|
|
117
127
|
|
|
118
128
|
- 默认响应预算12,000个UTF-16单元、正文每块最多8,000;JSON和Native文本各最多48,000字节。默认不重复返回缓存路径;导出用focus: artifacts。
|
|
119
129
|
- `inline_images` 首次省略默认true,续读省略继承,显式布尔值覆盖;模型能力和图像预算始终构成上限。
|
|
120
|
-
- **0.0.14
|
|
121
|
-
-
|
|
130
|
+
- **0.0.14起使用v3游标,0.0.15保持该协议及索引v2;旧v1/v2游标需重新开始,解析缓存无需迁移。** 续读不会在缓存丢失时偷偷重新上传。
|
|
131
|
+
- 原页模式优先使用 PATH 中的 Poppler(pdfinfo/pdftoppm),命令缺失或明确不可执行时自动回退到 PDF.js + Node Canvas 子进程;仍需图像模型、附件服务及大于0的图像预算。结果以 `renderer: "poppler" | "pdfjs"` 标明后端,不会上传PDF或要求模型重新调用。它是本地有界执行,不是OS级隔离沙箱。
|
|
122
132
|
|
|
123
133
|
字段语义、完整示例、来源/索引版本、预算、安全边界、错误恢复和离线验收见 **[PDF阅读指南](docs/model-reading.md)**。更新插件后需要让宿主重新加载工具定义;只构建源码或刷新Web页面不等于后端已重载。
|
|
124
134
|
|
|
@@ -305,8 +315,9 @@ pnpm run build
|
|
|
305
315
|
# 4. 在运行中的 DSH Web 中验证前端设置组件
|
|
306
316
|
pnpm run verify:gui
|
|
307
317
|
|
|
308
|
-
# 5.
|
|
309
|
-
pnpm run smoke:reader-local -- /path/to/sample.pdf 1
|
|
318
|
+
# 5. (可选)本地原页验证,无上传;第二条用空PATH验证PDF.js自动回退
|
|
319
|
+
pnpm run smoke:reader-local -- /path/to/sample.pdf 1 --backend=auto
|
|
320
|
+
pnpm run smoke:reader-local -- /path/to/sample.pdf 1 .vitest-cache/pdfjs --backend=pdfjs
|
|
310
321
|
|
|
311
322
|
# 6. (显式选择)使用真实 Token 运行在线解析,会上传文档
|
|
312
323
|
MINERU_API_KEY=<token> pnpm run smoke:official-v4 -- /path/to/sample.pdf
|
package/lib/index.js
CHANGED
|
@@ -10,6 +10,8 @@ import { Readable, Transform, Writable } from "node:stream";
|
|
|
10
10
|
import { pipeline } from "node:stream/promises";
|
|
11
11
|
import { TextDecoder as TextDecoder$1 } from "node:util";
|
|
12
12
|
import { spawn } from "node:child_process";
|
|
13
|
+
import { crc32 } from "node:zlib";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
13
15
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
14
16
|
//#region \0rolldown/runtime.js
|
|
15
17
|
var __create = Object.create;
|
|
@@ -4270,7 +4272,7 @@ function formatResultProse(value) {
|
|
|
4270
4272
|
if (value.diagnostics?.length) lines.push("", "Diagnostics:", ...value.diagnostics.map((d) => `- [${d.code}] (${d.scope})${d.block_id ? " [" + d.block_id + "]" : ""}${d.page === void 0 ? "" : " Page " + d.page}: ${d.message}`));
|
|
4271
4273
|
if (value.verification_hints?.length) lines.push("", "Formula verification suggested (advisory, not a detected error):", ...value.verification_hints.map((hint) => `- [${hint.block_id}]${hint.page === void 0 ? "" : " Page " + hint.page}: inspect the original page before relying on formula symbols.`));
|
|
4272
4274
|
if (value.metadata_shortened?.length) lines.push("", "Metadata shortened to fit: " + value.metadata_shortened.join(", ") + ". Narrow the selection to inspect omitted details.");
|
|
4273
|
-
if (value.view === "page") lines.push("", "Original PDF page rendered locally; no Provider parsing was performed.");
|
|
4275
|
+
if (value.view === "page") lines.push("", "Original PDF page rendered locally" + (value.renderer ? " (" + value.renderer + ")" : "") + "; no Provider parsing was performed.");
|
|
4274
4276
|
if (value.visuals) lines.push("", `Visuals in this chunk: ${value.visuals.attached}/${value.visuals.listed} attached, ${value.visuals.omitted} not attached.`);
|
|
4275
4277
|
if (value.continuation_block) lines.push("", "Continuing block [" + value.continuation_block.block_id + "]" + (value.continuation_block.page ? " (Page " + value.continuation_block.page + ")" : ""));
|
|
4276
4278
|
lines.push(footer);
|
|
@@ -4968,6 +4970,35 @@ function deliverReadChunk(options) {
|
|
|
4968
4970
|
}
|
|
4969
4971
|
}
|
|
4970
4972
|
//#endregion
|
|
4973
|
+
//#region src/service/pdfjs-backend.ts
|
|
4974
|
+
const PDFJS_WORKER_URL = new URL("./pdfjs-worker.mjs", import.meta.url);
|
|
4975
|
+
const PDFJS_MAX_OLD_SPACE_MIB = 512;
|
|
4976
|
+
const MAX_PAGE_NUMBER = 1e6;
|
|
4977
|
+
function positiveInteger(value, name, maximum = Number.MAX_SAFE_INTEGER) {
|
|
4978
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > maximum) throw new TypeError(name + " must be a positive safe integer");
|
|
4979
|
+
return String(value);
|
|
4980
|
+
}
|
|
4981
|
+
function pathArgument(value, name) {
|
|
4982
|
+
if (typeof value !== "string" || value.length === 0 || value.includes("\0")) throw new TypeError(name + " must be a non-empty path");
|
|
4983
|
+
return value;
|
|
4984
|
+
}
|
|
4985
|
+
/**
|
|
4986
|
+
* Build fixed Node arguments for the local PDF.js renderer. The final four
|
|
4987
|
+
* arguments are the worker protocol: snapshot, output, page, and byte limit.
|
|
4988
|
+
*/
|
|
4989
|
+
function buildPdfjsArgs(snapshotPath, outputPath, page, maxFileBytes) {
|
|
4990
|
+
return [
|
|
4991
|
+
"--max-old-space-size=" + String(PDFJS_MAX_OLD_SPACE_MIB),
|
|
4992
|
+
"--disallow-code-generation-from-strings",
|
|
4993
|
+
"--no-warnings",
|
|
4994
|
+
fileURLToPath(PDFJS_WORKER_URL),
|
|
4995
|
+
pathArgument(snapshotPath, "snapshotPath"),
|
|
4996
|
+
pathArgument(outputPath, "outputPath"),
|
|
4997
|
+
positiveInteger(page, "page", MAX_PAGE_NUMBER),
|
|
4998
|
+
positiveInteger(maxFileBytes, "maxFileBytes")
|
|
4999
|
+
];
|
|
5000
|
+
}
|
|
5001
|
+
//#endregion
|
|
4971
5002
|
//#region src/service/page-renderer.ts
|
|
4972
5003
|
/** Aspect-preserving Poppler target: the longer page edge is capped at 1600 pixels. */
|
|
4973
5004
|
const PDF_PAGE_MAX_LONG_EDGE = 1600;
|
|
@@ -5047,12 +5078,12 @@ function killChild(child) {
|
|
|
5047
5078
|
child.kill("SIGKILL");
|
|
5048
5079
|
} catch {}
|
|
5049
5080
|
}
|
|
5050
|
-
/** Spawn
|
|
5081
|
+
/** Spawn a fixed local renderer command without a shell; settle only after child close/reaping. */
|
|
5051
5082
|
const runPdfPageProcess = (request) => new Promise((resolvePromise, rejectPromise) => {
|
|
5052
5083
|
request.signal.throwIfAborted();
|
|
5053
5084
|
let child;
|
|
5054
5085
|
try {
|
|
5055
|
-
child = spawn(request.command, [...request.args], {
|
|
5086
|
+
child = spawn(request.command === "pdfjs" ? process.execPath : request.command, [...request.args], {
|
|
5056
5087
|
cwd: request.cwd,
|
|
5057
5088
|
env: {
|
|
5058
5089
|
PATH: process.env.PATH ?? "",
|
|
@@ -5109,7 +5140,7 @@ const runPdfPageProcess = (request) => new Promise((resolvePromise, rejectPromis
|
|
|
5109
5140
|
stat(request.watchedOutput.path).then((info) => {
|
|
5110
5141
|
if (info.size > request.watchedOutput.maxBytes) failAndKill(new ProcessFailure("output-limit", "Rendered PNG exceeded its byte limit"));
|
|
5111
5142
|
}, (error) => {
|
|
5112
|
-
if (errorCode(error) !== "ENOENT") failAndKill(error);
|
|
5143
|
+
if (errorCode(error) !== "ENOENT") failAndKill(new ProcessFailure("output-io", "Failed to inspect rendered output", { cause: error }));
|
|
5113
5144
|
}).finally(() => {
|
|
5114
5145
|
watching = false;
|
|
5115
5146
|
});
|
|
@@ -5226,14 +5257,40 @@ async function invokeProcess(runProcess, request) {
|
|
|
5226
5257
|
try {
|
|
5227
5258
|
return boundedProcessResult(await runProcess(request), request);
|
|
5228
5259
|
} catch (error) {
|
|
5229
|
-
if (error instanceof MinerUError) throw error;
|
|
5230
5260
|
if (request.signal.aborted) throw request.signal.reason;
|
|
5231
|
-
if (
|
|
5261
|
+
if (error instanceof MinerUError) throw error;
|
|
5262
|
+
if ([
|
|
5263
|
+
"ENOENT",
|
|
5264
|
+
"EACCES",
|
|
5265
|
+
"EPERM",
|
|
5266
|
+
"ENOEXEC",
|
|
5267
|
+
"ENOSYS"
|
|
5268
|
+
].includes(errorCode(error) ?? "")) throw new RendererUnavailable();
|
|
5232
5269
|
if (error instanceof ProcessFailure && error.kind === "output-limit") throw new MinerUError(failure("RESULT_TOO_LARGE", request.command + " output exceeded its byte limit"), { cause: error });
|
|
5233
5270
|
if (error instanceof ProcessFailure && error.kind === "timeout") throw new MinerUError(failure("PROVIDER_UNAVAILABLE", request.command + " exceeded its runtime limit", true), { cause: error });
|
|
5234
5271
|
throw new MinerUError(failure("PROVIDER_UNAVAILABLE", "Failed to execute local " + request.command, true), { cause: error });
|
|
5235
5272
|
}
|
|
5236
5273
|
}
|
|
5274
|
+
/** Only dependency/execution-environment failures qualify for backend selection. */
|
|
5275
|
+
var RendererUnavailable = class extends Error {};
|
|
5276
|
+
function unavailableRenderers() {
|
|
5277
|
+
return new MinerUError(failure("UNSUPPORTED_OPTION", "Local PDF page rendering is unavailable: install Poppler (pdfinfo and pdftoppm) or reinstall the plugin with PDF.js and @napi-rs/canvas platform optional dependencies enabled on a supported Node/platform combination."));
|
|
5278
|
+
}
|
|
5279
|
+
function parsePdfjsPageCount(result) {
|
|
5280
|
+
if (result.signal !== null) throw new MinerUError(failure("PROVIDER_UNAVAILABLE", "PDF.js page renderer exited unexpectedly", true));
|
|
5281
|
+
if (result.exitCode === 20) throw unavailableRenderers();
|
|
5282
|
+
if (result.exitCode === 22) throw new MinerUError(failure("RESULT_TOO_LARGE", "PDF.js page rendering exceeded a resource limit"));
|
|
5283
|
+
if (result.exitCode === 21) throw invalid("PDF.js could not inspect or render the requested PDF page (invalid, encrypted, unsupported PDF, or page out of range)");
|
|
5284
|
+
if (result.exitCode !== 0) throw new MinerUError(failure("PROVIDER_UNAVAILABLE", "PDF.js page renderer exited unexpectedly", true));
|
|
5285
|
+
let parsed;
|
|
5286
|
+
try {
|
|
5287
|
+
parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(result.stdout));
|
|
5288
|
+
} catch {
|
|
5289
|
+
throw invalid("PDF.js returned invalid page metadata");
|
|
5290
|
+
}
|
|
5291
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || Object.keys(parsed).length !== 1 || !("page_count" in parsed) || !Number.isSafeInteger(parsed.page_count) || typeof parsed.page_count !== "number" || parsed.page_count < 1 || parsed.page_count > MAX_PAGE_COUNT) throw invalid("PDF.js returned invalid page metadata");
|
|
5292
|
+
return parsed.page_count;
|
|
5293
|
+
}
|
|
5237
5294
|
function parsePageCount(stdout) {
|
|
5238
5295
|
let text;
|
|
5239
5296
|
try {
|
|
@@ -5273,10 +5330,30 @@ async function readBoundedFile(path, maxBytes) {
|
|
|
5273
5330
|
}
|
|
5274
5331
|
function pngDimensions(data) {
|
|
5275
5332
|
const bytes = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
5276
|
-
if (bytes.byteLength < 24 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE) || bytes.readUInt32BE(8) !== 13 || bytes.toString("ascii", 12, 16) !== "IHDR") throw invalid("
|
|
5333
|
+
if (bytes.byteLength < 24 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE) || bytes.readUInt32BE(8) !== 13 || bytes.toString("ascii", 12, 16) !== "IHDR") throw invalid("Page renderer returned an invalid PNG");
|
|
5277
5334
|
const width = bytes.readUInt32BE(16);
|
|
5278
5335
|
const height = bytes.readUInt32BE(20);
|
|
5279
|
-
if (width < 1 || height < 1 || width > 1600 || height > 2e3 || width * height > 32e5) throw new MinerUError(failure("RESULT_TOO_LARGE", "Rendered PNG dimensions exceed the page-rendering limit"));
|
|
5336
|
+
if (width < 1 || height < 1 || width > 1600 || height > 2e3 || Math.max(width, height) > 1600 || width * height > 32e5) throw new MinerUError(failure("RESULT_TOO_LARGE", "Rendered PNG dimensions exceed the page-rendering limit"));
|
|
5337
|
+
let offset = 8;
|
|
5338
|
+
let imageData = false;
|
|
5339
|
+
let ended = false;
|
|
5340
|
+
let chunks = 0;
|
|
5341
|
+
while (offset < bytes.length) {
|
|
5342
|
+
if (++chunks > 65536 || bytes.length - offset < 12) throw invalid("Page renderer returned a malformed PNG");
|
|
5343
|
+
const length = bytes.readUInt32BE(offset);
|
|
5344
|
+
if (length > bytes.length - offset - 12) throw invalid("Page renderer returned a truncated PNG");
|
|
5345
|
+
const type = bytes.toString("ascii", offset + 4, offset + 8);
|
|
5346
|
+
if (!/^[A-Za-z]{4}$/.test(type) || offset !== 8 && type === "IHDR") throw invalid("Page renderer returned a malformed PNG");
|
|
5347
|
+
if (crc32(bytes.subarray(offset + 4, offset + 8 + length)) !== bytes.readUInt32BE(offset + 8 + length)) throw invalid("Page renderer returned a PNG with an invalid checksum");
|
|
5348
|
+
if (type === "IDAT") imageData ||= length > 0;
|
|
5349
|
+
offset += length + 12;
|
|
5350
|
+
if (type === "IEND") {
|
|
5351
|
+
if (length !== 0 || !imageData || offset !== bytes.length) throw invalid("Page renderer returned a malformed PNG");
|
|
5352
|
+
ended = true;
|
|
5353
|
+
break;
|
|
5354
|
+
}
|
|
5355
|
+
}
|
|
5356
|
+
if (!ended) throw invalid("Page renderer returned an incomplete PNG");
|
|
5280
5357
|
return {
|
|
5281
5358
|
width,
|
|
5282
5359
|
height
|
|
@@ -5310,6 +5387,7 @@ function createPdfPageRenderer(dependencies = {}) {
|
|
|
5310
5387
|
const sourcePath = resolve(input.cwd ?? process.cwd(), input.file_path.trim());
|
|
5311
5388
|
const sourceName = basename(sourcePath);
|
|
5312
5389
|
if (extname(sourceName).toLowerCase() !== ".pdf") throw new MinerUError(failure("UNSUPPORTED_OPTION", "Original-page rendering supports PDF files only"));
|
|
5390
|
+
const expiresAt = performance.now() + runtimeMs;
|
|
5313
5391
|
let timedOut = false;
|
|
5314
5392
|
const operation = new AbortController();
|
|
5315
5393
|
const onAbort = () => operation.abort(new DOMException("PDF page rendering was cancelled", "AbortError"));
|
|
@@ -5321,6 +5399,16 @@ function createPdfPageRenderer(dependencies = {}) {
|
|
|
5321
5399
|
operation.abort(new DOMException("PDF page rendering timed out", "TimeoutError"));
|
|
5322
5400
|
}, runtimeMs);
|
|
5323
5401
|
deadline.unref();
|
|
5402
|
+
const remainingMs = (cap = runtimeMs) => {
|
|
5403
|
+
operation.signal.throwIfAborted();
|
|
5404
|
+
const remaining = Math.ceil(expiresAt - performance.now());
|
|
5405
|
+
if (remaining <= 0) {
|
|
5406
|
+
timedOut = true;
|
|
5407
|
+
operation.abort(new DOMException("PDF page rendering timed out", "TimeoutError"));
|
|
5408
|
+
operation.signal.throwIfAborted();
|
|
5409
|
+
}
|
|
5410
|
+
return Math.min(cap, remaining);
|
|
5411
|
+
};
|
|
5324
5412
|
let release;
|
|
5325
5413
|
let temporaryDirectory;
|
|
5326
5414
|
let outcome;
|
|
@@ -5335,59 +5423,94 @@ function createPdfPageRenderer(dependencies = {}) {
|
|
|
5335
5423
|
const outputPath = outputPrefix + ".png";
|
|
5336
5424
|
const sha256 = await snapshotSource(sourcePath, snapshotPath, sourceName, input.maxFileBytes, operation.signal);
|
|
5337
5425
|
if (input.expectedSha256 !== void 0 && sha256 !== input.expectedSha256.toLowerCase()) throw invalid("PDF source hash does not match expectedSha256: " + sourceName);
|
|
5338
|
-
|
|
5339
|
-
|
|
5340
|
-
|
|
5341
|
-
|
|
5342
|
-
"
|
|
5343
|
-
|
|
5344
|
-
|
|
5345
|
-
|
|
5346
|
-
|
|
5347
|
-
|
|
5348
|
-
|
|
5349
|
-
|
|
5350
|
-
|
|
5351
|
-
|
|
5352
|
-
|
|
5353
|
-
|
|
5354
|
-
|
|
5355
|
-
|
|
5356
|
-
|
|
5357
|
-
|
|
5358
|
-
|
|
5359
|
-
|
|
5360
|
-
"
|
|
5361
|
-
|
|
5362
|
-
|
|
5363
|
-
|
|
5364
|
-
|
|
5365
|
-
|
|
5366
|
-
|
|
5367
|
-
|
|
5368
|
-
|
|
5369
|
-
|
|
5370
|
-
|
|
5371
|
-
|
|
5372
|
-
|
|
5373
|
-
|
|
5374
|
-
|
|
5375
|
-
|
|
5376
|
-
|
|
5426
|
+
let renderer = "poppler";
|
|
5427
|
+
let pageCount;
|
|
5428
|
+
try {
|
|
5429
|
+
const info = await invokeProcess(runProcess, {
|
|
5430
|
+
command: "pdfinfo",
|
|
5431
|
+
args: [
|
|
5432
|
+
"-enc",
|
|
5433
|
+
"UTF-8",
|
|
5434
|
+
snapshotPath
|
|
5435
|
+
],
|
|
5436
|
+
cwd: temporaryDirectory,
|
|
5437
|
+
signal: operation.signal,
|
|
5438
|
+
timeoutMs: remainingMs(1e4),
|
|
5439
|
+
maxStdoutBytes: MAX_PDFINFO_STDOUT_BYTES,
|
|
5440
|
+
maxStderrBytes: MAX_PROCESS_STDERR_BYTES
|
|
5441
|
+
});
|
|
5442
|
+
remainingMs();
|
|
5443
|
+
if (info.signal !== null || info.exitCode === 2) throw new MinerUError(failure("PROVIDER_UNAVAILABLE", "pdfinfo exited unexpectedly or encountered local output I/O failure", true));
|
|
5444
|
+
if (info.exitCode !== 0) throw invalid("pdfinfo could not inspect the PDF");
|
|
5445
|
+
pageCount = parsePageCount(info.stdout);
|
|
5446
|
+
if (input.page > pageCount) throw invalid("PDF page " + String(input.page) + " is outside the physical page range 1-" + String(pageCount));
|
|
5447
|
+
const rendered = await invokeProcess(runProcess, {
|
|
5448
|
+
command: "pdftoppm",
|
|
5449
|
+
args: [
|
|
5450
|
+
"-f",
|
|
5451
|
+
String(input.page),
|
|
5452
|
+
"-l",
|
|
5453
|
+
String(input.page),
|
|
5454
|
+
"-singlefile",
|
|
5455
|
+
"-png",
|
|
5456
|
+
"-scale-to",
|
|
5457
|
+
String(PDF_PAGE_MAX_LONG_EDGE),
|
|
5458
|
+
snapshotPath,
|
|
5459
|
+
outputPrefix
|
|
5460
|
+
],
|
|
5461
|
+
cwd: temporaryDirectory,
|
|
5462
|
+
signal: operation.signal,
|
|
5463
|
+
timeoutMs: remainingMs(3e4),
|
|
5464
|
+
maxStdoutBytes: MAX_RENDER_STDOUT_BYTES,
|
|
5465
|
+
maxStderrBytes: MAX_PROCESS_STDERR_BYTES,
|
|
5466
|
+
watchedOutput: {
|
|
5467
|
+
path: outputPath,
|
|
5468
|
+
maxBytes: MAX_RENDERED_PNG_BYTES
|
|
5469
|
+
}
|
|
5470
|
+
});
|
|
5471
|
+
remainingMs();
|
|
5472
|
+
if (rendered.signal !== null || rendered.exitCode === 2) throw new MinerUError(failure("PROVIDER_UNAVAILABLE", "pdftoppm exited unexpectedly or encountered local output I/O failure", true));
|
|
5473
|
+
if (rendered.exitCode !== 0) throw invalid("pdftoppm could not render the requested PDF page");
|
|
5474
|
+
} catch (error) {
|
|
5475
|
+
remainingMs();
|
|
5476
|
+
if (!(error instanceof RendererUnavailable)) throw error;
|
|
5477
|
+
renderer = "pdfjs";
|
|
5478
|
+
let rendered;
|
|
5479
|
+
try {
|
|
5480
|
+
rendered = await invokeProcess(runProcess, {
|
|
5481
|
+
command: "pdfjs",
|
|
5482
|
+
args: buildPdfjsArgs(snapshotPath, outputPath, input.page, input.maxFileBytes),
|
|
5483
|
+
cwd: temporaryDirectory,
|
|
5484
|
+
signal: operation.signal,
|
|
5485
|
+
timeoutMs: remainingMs(),
|
|
5486
|
+
maxStdoutBytes: MAX_RENDER_STDOUT_BYTES,
|
|
5487
|
+
maxStderrBytes: MAX_PROCESS_STDERR_BYTES,
|
|
5488
|
+
watchedOutput: {
|
|
5489
|
+
path: outputPath,
|
|
5490
|
+
maxBytes: MAX_RENDERED_PNG_BYTES
|
|
5491
|
+
}
|
|
5492
|
+
});
|
|
5493
|
+
} catch (fallbackError) {
|
|
5494
|
+
remainingMs();
|
|
5495
|
+
if (fallbackError instanceof RendererUnavailable) throw unavailableRenderers();
|
|
5496
|
+
throw fallbackError;
|
|
5377
5497
|
}
|
|
5378
|
-
|
|
5379
|
-
|
|
5498
|
+
remainingMs();
|
|
5499
|
+
pageCount = parsePdfjsPageCount(rendered);
|
|
5500
|
+
if (input.page > pageCount) throw invalid("PDF page is outside the physical page range");
|
|
5501
|
+
}
|
|
5380
5502
|
operation.signal.throwIfAborted();
|
|
5381
5503
|
let data;
|
|
5382
5504
|
try {
|
|
5383
5505
|
data = await readBoundedFile(outputPath, MAX_RENDERED_PNG_BYTES);
|
|
5384
5506
|
} catch (error) {
|
|
5385
|
-
if (errorCode(error) === "ENOENT") throw invalid("
|
|
5507
|
+
if (errorCode(error) === "ENOENT") throw invalid("Page renderer did not produce the requested PNG", error);
|
|
5386
5508
|
throw error;
|
|
5387
5509
|
}
|
|
5388
5510
|
const dimensions = pngDimensions(data);
|
|
5389
|
-
|
|
5511
|
+
remainingMs();
|
|
5390
5512
|
outcome = {
|
|
5513
|
+
renderer,
|
|
5391
5514
|
name: outputName(sourceName, input.page),
|
|
5392
5515
|
page: input.page,
|
|
5393
5516
|
page_count: pageCount,
|
|
@@ -5417,6 +5540,11 @@ function createPdfPageRenderer(dependencies = {}) {
|
|
|
5417
5540
|
}
|
|
5418
5541
|
}
|
|
5419
5542
|
if (primaryFailure !== void 0) throw primaryFailure;
|
|
5543
|
+
try {
|
|
5544
|
+
remainingMs();
|
|
5545
|
+
} catch (error) {
|
|
5546
|
+
throw normalizeFailure(error, timedOut);
|
|
5547
|
+
}
|
|
5420
5548
|
if (cleanupFailed) throw new MinerUError(failure("PROVIDER_UNAVAILABLE", "Failed to remove temporary PDF page-rendering data", true));
|
|
5421
5549
|
if (outcome === void 0) throw new MinerUError(failure("PROVIDER_UNAVAILABLE", "Local PDF page rendering produced no result", true));
|
|
5422
5550
|
return outcome;
|
|
@@ -8605,6 +8733,10 @@ const parseOutputSchema = {
|
|
|
8605
8733
|
type: "string",
|
|
8606
8734
|
enum: ["content", "page"]
|
|
8607
8735
|
},
|
|
8736
|
+
renderer: {
|
|
8737
|
+
type: "string",
|
|
8738
|
+
enum: ["poppler", "pdfjs"]
|
|
8739
|
+
},
|
|
8608
8740
|
visuals: {
|
|
8609
8741
|
type: "object",
|
|
8610
8742
|
properties: {
|
|
@@ -8649,7 +8781,8 @@ const parseOutputSchema = {
|
|
|
8649
8781
|
enum: [
|
|
8650
8782
|
"layout",
|
|
8651
8783
|
"content-list-lower-bound",
|
|
8652
|
-
"pdfinfo"
|
|
8784
|
+
"pdfinfo",
|
|
8785
|
+
"pdfjs"
|
|
8653
8786
|
]
|
|
8654
8787
|
},
|
|
8655
8788
|
table_count: { type: "integer" },
|
|
@@ -9214,6 +9347,7 @@ function registerTools(ctx, getService, accessGate, getOutputConfig = () => DEFA
|
|
|
9214
9347
|
const single = value;
|
|
9215
9348
|
return {
|
|
9216
9349
|
result_id: single.result_id,
|
|
9350
|
+
...single.renderer === void 0 ? {} : { renderer: single.renderer },
|
|
9217
9351
|
source: single.source,
|
|
9218
9352
|
cache_hit: single.cache_hit,
|
|
9219
9353
|
...single.manifest_path === void 0 ? {} : { manifest_path: single.manifest_path },
|
|
@@ -9246,6 +9380,7 @@ function registerTools(ctx, getService, accessGate, getOutputConfig = () => DEFA
|
|
|
9246
9380
|
})) } : {},
|
|
9247
9381
|
...single.summary !== void 0 ? { summary: {
|
|
9248
9382
|
...single.summary.page_count !== void 0 ? { page_count: single.summary.page_count } : {},
|
|
9383
|
+
...single.summary.page_count_source !== void 0 ? { page_count_source: single.summary.page_count_source } : {},
|
|
9249
9384
|
...single.summary.table_count !== void 0 ? { table_count: single.summary.table_count } : {},
|
|
9250
9385
|
...single.summary.image_count !== void 0 ? { image_count: single.summary.image_count } : {},
|
|
9251
9386
|
...single.summary.equation_count !== void 0 ? { equation_count: single.summary.equation_count } : {},
|
|
@@ -9302,6 +9437,7 @@ function registerTools(ctx, getService, accessGate, getOutputConfig = () => DEFA
|
|
|
9302
9437
|
cache_hit: false,
|
|
9303
9438
|
result_id: page.result_id,
|
|
9304
9439
|
view: "page",
|
|
9440
|
+
renderer: page.renderer,
|
|
9305
9441
|
files: [{
|
|
9306
9442
|
file_id: page.file_id,
|
|
9307
9443
|
name: page.name,
|
|
@@ -9314,7 +9450,7 @@ function registerTools(ctx, getService, accessGate, getOutputConfig = () => DEFA
|
|
|
9314
9450
|
pages: String(page.page),
|
|
9315
9451
|
summary: {
|
|
9316
9452
|
page_count: page.page_count,
|
|
9317
|
-
page_count_source: "pdfinfo"
|
|
9453
|
+
page_count_source: page.renderer === "pdfjs" ? "pdfjs" : "pdfinfo"
|
|
9318
9454
|
},
|
|
9319
9455
|
inlined_images: [{
|
|
9320
9456
|
attachment_id: String(ref.attachmentId),
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
import dgram from 'node:dgram'
|
|
2
|
+
import { constants, writeSync } from 'node:fs'
|
|
3
|
+
import { access, open, stat } from 'node:fs/promises'
|
|
4
|
+
import http from 'node:http'
|
|
5
|
+
import http2 from 'node:http2'
|
|
6
|
+
import https from 'node:https'
|
|
7
|
+
import { createRequire } from 'node:module'
|
|
8
|
+
import net from 'node:net'
|
|
9
|
+
import { dirname, join, sep } from 'node:path'
|
|
10
|
+
import tls from 'node:tls'
|
|
11
|
+
|
|
12
|
+
const EXIT_UNAVAILABLE = 20
|
|
13
|
+
const EXIT_INVALID_PDF = 21
|
|
14
|
+
const EXIT_RESOURCE_LIMIT = 22
|
|
15
|
+
const EXIT_FAILURE = 23
|
|
16
|
+
|
|
17
|
+
const MAX_PAGE_COUNT = 1_000_000
|
|
18
|
+
const MAX_RAW_PAGE_EDGE_POINTS = 1_000_000
|
|
19
|
+
const MAX_RENDER_EDGE_PIXELS = 1600
|
|
20
|
+
const MAX_CANVAS_PIXELS = 1600 * 2000
|
|
21
|
+
const MAX_TOTAL_CANVAS_PIXELS = MAX_CANVAS_PIXELS * 4
|
|
22
|
+
const MAX_PNG_BYTES = 8 * 1024 * 1024
|
|
23
|
+
const MAX_SNAPSHOT_BYTES = 200 * 1024 * 1024
|
|
24
|
+
const MAX_PACKAGE_RESOURCE_BYTES = 16 * 1024 * 1024
|
|
25
|
+
const PDFJS_VERSION = '6.3.289'
|
|
26
|
+
|
|
27
|
+
// @napi-rs/canvas loads system fonts as an import side effect unless this is set.
|
|
28
|
+
process.env.DISABLE_SYSTEM_FONTS_LOAD = '1'
|
|
29
|
+
|
|
30
|
+
function denyNetwork() {
|
|
31
|
+
throw new Error('Network access is disabled in the PDF.js worker')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// The renderer receives bytes, never a URL. Keep a second line of defence in
|
|
35
|
+
// case a dependency or malformed document attempts any outbound connection.
|
|
36
|
+
for (const [module, methods] of [
|
|
37
|
+
[http, ['get', 'request']],
|
|
38
|
+
[https, ['get', 'request']],
|
|
39
|
+
[http2, ['connect']],
|
|
40
|
+
[net, ['connect', 'createConnection']],
|
|
41
|
+
[tls, ['connect']],
|
|
42
|
+
[dgram, ['createSocket']],
|
|
43
|
+
]) {
|
|
44
|
+
for (const method of methods) {
|
|
45
|
+
try { module[method] = denyNetwork } catch {}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
try { globalThis.fetch = async () => denyNetwork() } catch {}
|
|
49
|
+
try { globalThis.WebSocket = class DisabledWebSocket { constructor() { denyNetwork() } } } catch {}
|
|
50
|
+
|
|
51
|
+
// PDF.js diagnostics can otherwise corrupt stdout's one-JSON protocol or reveal
|
|
52
|
+
// private paths on stderr. Failures are communicated only through exit status.
|
|
53
|
+
let imageLimitObserved = false
|
|
54
|
+
for (const method of ['debug', 'error', 'info', 'log', 'warn']) {
|
|
55
|
+
try {
|
|
56
|
+
console[method] = method === 'warn'
|
|
57
|
+
? message => {
|
|
58
|
+
if (typeof message === 'string' && message.includes('Image exceeded maximum allowed size')) {
|
|
59
|
+
imageLimitObserved = true
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
: () => {}
|
|
63
|
+
} catch {}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
class WorkerFailure extends Error {
|
|
67
|
+
constructor(exitCode) {
|
|
68
|
+
super('PDF.js worker failure')
|
|
69
|
+
this.exitCode = exitCode
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
class ResourceLimitError extends WorkerFailure {
|
|
74
|
+
constructor() {
|
|
75
|
+
super(EXIT_RESOURCE_LIMIT)
|
|
76
|
+
this.name = 'PdfjsResourceLimit'
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function fail(exitCode) {
|
|
81
|
+
throw new WorkerFailure(exitCode)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function parsePositiveInteger(text, maximum = Number.MAX_SAFE_INTEGER) {
|
|
85
|
+
if (!/^[1-9][0-9]*$/.test(text)) fail(EXIT_INVALID_PDF)
|
|
86
|
+
const value = Number(text)
|
|
87
|
+
if (!Number.isSafeInteger(value) || value > maximum) fail(EXIT_INVALID_PDF)
|
|
88
|
+
return value
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function parseArguments() {
|
|
92
|
+
const args = process.argv.slice(2)
|
|
93
|
+
if (args.length !== 4 || args[0].length === 0 || args[1].length === 0
|
|
94
|
+
|| args[0].includes('\0') || args[1].includes('\0')) {
|
|
95
|
+
fail(EXIT_INVALID_PDF)
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
snapshotPath: args[0],
|
|
99
|
+
outputPath: args[1],
|
|
100
|
+
pageNumber: parsePositiveInteger(args[2], MAX_PAGE_COUNT),
|
|
101
|
+
maxFileBytes: parsePositiveInteger(args[3]),
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function assertDirectory(path) {
|
|
106
|
+
const info = await stat(path)
|
|
107
|
+
if (!info.isDirectory()) throw new Error('resource unavailable')
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function loadDependencies() {
|
|
111
|
+
try {
|
|
112
|
+
const require = createRequire(import.meta.url)
|
|
113
|
+
const packageRoot = dirname(require.resolve('pdfjs-dist/package.json'))
|
|
114
|
+
const resources = {
|
|
115
|
+
cMapUrl: join(packageRoot, 'cmaps') + sep,
|
|
116
|
+
iccUrl: join(packageRoot, 'iccs') + sep,
|
|
117
|
+
standardFontDataUrl: join(packageRoot, 'standard_fonts') + sep,
|
|
118
|
+
wasmUrl: join(packageRoot, 'wasm') + sep,
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
await Promise.all(Object.values(resources).map(assertDirectory))
|
|
122
|
+
await Promise.all([
|
|
123
|
+
access(join(resources.cMapUrl, 'Adobe-CNS1-UCS2.bcmap'), constants.R_OK),
|
|
124
|
+
access(join(resources.iccUrl, 'CGATS001Compat-v2-micro.icc'), constants.R_OK),
|
|
125
|
+
access(join(resources.standardFontDataUrl, 'LiberationSans-Regular.ttf'), constants.R_OK),
|
|
126
|
+
access(join(resources.wasmUrl, 'jbig2.wasm'), constants.R_OK),
|
|
127
|
+
access(join(resources.wasmUrl, 'openjpeg.wasm'), constants.R_OK),
|
|
128
|
+
access(join(resources.wasmUrl, 'qcms_bg.wasm'), constants.R_OK),
|
|
129
|
+
access(join(packageRoot, 'legacy', 'build', 'pdf.worker.mjs'), constants.R_OK),
|
|
130
|
+
])
|
|
131
|
+
|
|
132
|
+
const [canvasModule, pdfjs] = await Promise.all([
|
|
133
|
+
import('@napi-rs/canvas'),
|
|
134
|
+
import('pdfjs-dist/legacy/build/pdf.mjs'),
|
|
135
|
+
])
|
|
136
|
+
if (pdfjs.version !== PDFJS_VERSION || typeof pdfjs.getDocument !== 'function'
|
|
137
|
+
|| typeof canvasModule.createCanvas !== 'function'
|
|
138
|
+
|| typeof pdfjs.AnnotationMode?.ENABLE !== 'number') {
|
|
139
|
+
throw new Error('incompatible rendering dependency')
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
createCanvas: canvasModule.createCanvas,
|
|
144
|
+
pdfjs,
|
|
145
|
+
resourceUrls: resources,
|
|
146
|
+
}
|
|
147
|
+
} catch {
|
|
148
|
+
fail(EXIT_UNAVAILABLE)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function checkedCanvasDimensions(width, height) {
|
|
153
|
+
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height)
|
|
154
|
+
|| width < 1 || height < 1 || width > MAX_RENDER_EDGE_PIXELS
|
|
155
|
+
|| height > MAX_RENDER_EDGE_PIXELS || width * height > MAX_CANVAS_PIXELS) {
|
|
156
|
+
throw new ResourceLimitError()
|
|
157
|
+
}
|
|
158
|
+
return width * height
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function makeCanvasFactory(createCanvas) {
|
|
162
|
+
return class BoundedCanvasFactory {
|
|
163
|
+
constructor() {
|
|
164
|
+
this.allocations = new Map()
|
|
165
|
+
this.totalPixels = 0
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
create(width, height) {
|
|
169
|
+
const pixels = checkedCanvasDimensions(width, height)
|
|
170
|
+
if (this.totalPixels + pixels > MAX_TOTAL_CANVAS_PIXELS) throw new ResourceLimitError()
|
|
171
|
+
const canvas = createCanvas(width, height)
|
|
172
|
+
const context = canvas.getContext('2d', { willReadFrequently: true })
|
|
173
|
+
if (!context) fail(EXIT_FAILURE)
|
|
174
|
+
this.allocations.set(canvas, pixels)
|
|
175
|
+
this.totalPixels += pixels
|
|
176
|
+
return { canvas, context }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
reset(canvasAndContext, width, height) {
|
|
180
|
+
if (!canvasAndContext?.canvas) fail(EXIT_FAILURE)
|
|
181
|
+
const pixels = checkedCanvasDimensions(width, height)
|
|
182
|
+
const previous = this.allocations.get(canvasAndContext.canvas) ?? 0
|
|
183
|
+
if (this.totalPixels - previous + pixels > MAX_TOTAL_CANVAS_PIXELS) throw new ResourceLimitError()
|
|
184
|
+
canvasAndContext.canvas.width = width
|
|
185
|
+
canvasAndContext.canvas.height = height
|
|
186
|
+
this.allocations.set(canvasAndContext.canvas, pixels)
|
|
187
|
+
this.totalPixels += pixels - previous
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
destroy(canvasAndContext) {
|
|
191
|
+
if (!canvasAndContext?.canvas) return
|
|
192
|
+
const canvas = canvasAndContext.canvas
|
|
193
|
+
this.totalPixels -= this.allocations.get(canvas) ?? 0
|
|
194
|
+
this.allocations.delete(canvas)
|
|
195
|
+
canvas.width = 0
|
|
196
|
+
canvas.height = 0
|
|
197
|
+
canvasAndContext.canvas = null
|
|
198
|
+
canvasAndContext.context = null
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function readSnapshot(snapshotPath, maxFileBytes) {
|
|
204
|
+
let handle
|
|
205
|
+
let primaryFailure
|
|
206
|
+
try {
|
|
207
|
+
handle = await open(snapshotPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
|
|
208
|
+
const info = await handle.stat()
|
|
209
|
+
if (!info.isFile()) fail(EXIT_FAILURE)
|
|
210
|
+
if (info.size > maxFileBytes || info.size > MAX_SNAPSHOT_BYTES) throw new ResourceLimitError()
|
|
211
|
+
const data = await handle.readFile()
|
|
212
|
+
if (data.byteLength > maxFileBytes || data.byteLength > MAX_SNAPSHOT_BYTES) throw new ResourceLimitError()
|
|
213
|
+
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
|
|
214
|
+
} catch (error) {
|
|
215
|
+
primaryFailure = error
|
|
216
|
+
throw error
|
|
217
|
+
} finally {
|
|
218
|
+
if (handle) {
|
|
219
|
+
try { await handle.close() } catch (error) { if (!primaryFailure) throw error }
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function validResourceFilename(kind, filename) {
|
|
225
|
+
if (typeof filename !== 'string' || filename.length < 1 || filename.length > 128
|
|
226
|
+
|| !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(filename) || filename.includes('..')) {
|
|
227
|
+
return false
|
|
228
|
+
}
|
|
229
|
+
switch (kind) {
|
|
230
|
+
case 'cMapUrl': return filename.endsWith('.bcmap')
|
|
231
|
+
case 'iccUrl': return filename.endsWith('.icc')
|
|
232
|
+
case 'standardFontDataUrl': return filename.endsWith('.pfb') || filename.endsWith('.ttf')
|
|
233
|
+
case 'wasmUrl':
|
|
234
|
+
return filename.endsWith('.wasm') || filename.endsWith('_nowasm_fallback.js')
|
|
235
|
+
default: return false
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function readPackageResource(path) {
|
|
240
|
+
let handle
|
|
241
|
+
let primaryFailure
|
|
242
|
+
try {
|
|
243
|
+
handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
|
|
244
|
+
const info = await handle.stat()
|
|
245
|
+
if (!info.isFile() || info.size < 1 || info.size > MAX_PACKAGE_RESOURCE_BYTES) {
|
|
246
|
+
throw new Error('package resource unavailable')
|
|
247
|
+
}
|
|
248
|
+
const data = await handle.readFile()
|
|
249
|
+
if (data.byteLength > MAX_PACKAGE_RESOURCE_BYTES) throw new Error('package resource unavailable')
|
|
250
|
+
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
|
|
251
|
+
} catch (error) {
|
|
252
|
+
primaryFailure = error
|
|
253
|
+
throw error
|
|
254
|
+
} finally {
|
|
255
|
+
if (handle) {
|
|
256
|
+
try { await handle.close() } catch (error) { if (!primaryFailure) throw error }
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function makeBinaryDataFactory(resourcePaths, resourceState) {
|
|
262
|
+
return class BoundedBinaryDataFactory {
|
|
263
|
+
async fetch({ kind, filename }) {
|
|
264
|
+
if (!validResourceFilename(kind, filename)) {
|
|
265
|
+
resourceState.invalidRequest = true
|
|
266
|
+
throw new Error('invalid package resource request')
|
|
267
|
+
}
|
|
268
|
+
try {
|
|
269
|
+
return await readPackageResource(join(resourcePaths[kind], filename))
|
|
270
|
+
} catch {
|
|
271
|
+
resourceState.unavailable = true
|
|
272
|
+
throw new Error('package resource unavailable')
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function rawPageViewport(page) {
|
|
279
|
+
if (!Array.isArray(page.view) || page.view.length !== 4
|
|
280
|
+
|| !page.view.every(Number.isFinite) || !Number.isFinite(page.userUnit) || page.userUnit <= 0) {
|
|
281
|
+
throw new ResourceLimitError()
|
|
282
|
+
}
|
|
283
|
+
const rawWidth = Math.abs(page.view[2] - page.view[0]) * page.userUnit
|
|
284
|
+
const rawHeight = Math.abs(page.view[3] - page.view[1]) * page.userUnit
|
|
285
|
+
if (!Number.isFinite(rawWidth) || !Number.isFinite(rawHeight) || rawWidth <= 0 || rawHeight <= 0
|
|
286
|
+
|| rawWidth > MAX_RAW_PAGE_EDGE_POINTS || rawHeight > MAX_RAW_PAGE_EDGE_POINTS) {
|
|
287
|
+
throw new ResourceLimitError()
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const viewport = page.getViewport({ scale: 1 })
|
|
291
|
+
if (!Number.isFinite(viewport.width) || !Number.isFinite(viewport.height)
|
|
292
|
+
|| viewport.width <= 0 || viewport.height <= 0
|
|
293
|
+
|| viewport.width > MAX_RAW_PAGE_EDGE_POINTS || viewport.height > MAX_RAW_PAGE_EDGE_POINTS
|
|
294
|
+
|| !Array.isArray(viewport.transform) || !viewport.transform.every(Number.isFinite)) {
|
|
295
|
+
throw new ResourceLimitError()
|
|
296
|
+
}
|
|
297
|
+
return viewport
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function scaledViewport(page, rawViewport) {
|
|
301
|
+
const rawLongEdge = Math.max(rawViewport.width, rawViewport.height)
|
|
302
|
+
// A tiny margin avoids floating-point ceil producing 1601 on the target edge.
|
|
303
|
+
const scale = (MAX_RENDER_EDGE_PIXELS - 1e-6) / rawLongEdge
|
|
304
|
+
if (!Number.isFinite(scale) || scale <= 0) throw new ResourceLimitError()
|
|
305
|
+
const viewport = page.getViewport({ scale })
|
|
306
|
+
if (!Number.isFinite(viewport.width) || !Number.isFinite(viewport.height)
|
|
307
|
+
|| !Array.isArray(viewport.transform) || !viewport.transform.every(Number.isFinite)) {
|
|
308
|
+
throw new ResourceLimitError()
|
|
309
|
+
}
|
|
310
|
+
const width = Math.max(1, Math.ceil(viewport.width))
|
|
311
|
+
const height = Math.max(1, Math.ceil(viewport.height))
|
|
312
|
+
checkedCanvasDimensions(width, height)
|
|
313
|
+
return { viewport, width, height }
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function isImageLimitFailure(error) {
|
|
317
|
+
const seen = new Set()
|
|
318
|
+
for (let current = error; current && typeof current === 'object' && !seen.has(current); current = current.cause) {
|
|
319
|
+
seen.add(current)
|
|
320
|
+
if (current instanceof ResourceLimitError || current.name === 'PdfjsResourceLimit') return true
|
|
321
|
+
if (typeof current.message === 'string'
|
|
322
|
+
&& current.message.includes('Image exceeded maximum allowed size')) return true
|
|
323
|
+
}
|
|
324
|
+
return false
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function loadDocument(pdfjs, CanvasFactory, BinaryDataFactory, resourceState, resourceUrls, data) {
|
|
328
|
+
let loadingTask
|
|
329
|
+
try {
|
|
330
|
+
loadingTask = pdfjs.getDocument({
|
|
331
|
+
data,
|
|
332
|
+
cMapUrl: resourceUrls.cMapUrl,
|
|
333
|
+
cMapPacked: true,
|
|
334
|
+
iccUrl: resourceUrls.iccUrl,
|
|
335
|
+
standardFontDataUrl: resourceUrls.standardFontDataUrl,
|
|
336
|
+
wasmUrl: resourceUrls.wasmUrl,
|
|
337
|
+
useWorkerFetch: false,
|
|
338
|
+
useWasm: true,
|
|
339
|
+
// PDF.js 6.3 turns strict operator-list failures into an empty list; its
|
|
340
|
+
// permissive path emits the stable oversized-image warning that we trap.
|
|
341
|
+
stopAtErrors: false,
|
|
342
|
+
maxImageSize: MAX_CANVAS_PIXELS,
|
|
343
|
+
canvasMaxAreaInBytes: MAX_CANVAS_PIXELS * 4,
|
|
344
|
+
isOffscreenCanvasSupported: false,
|
|
345
|
+
isImageDecoderSupported: false,
|
|
346
|
+
disableFontFace: true,
|
|
347
|
+
useSystemFonts: false,
|
|
348
|
+
enableXfa: false,
|
|
349
|
+
enableHWA: false,
|
|
350
|
+
pdfBug: false,
|
|
351
|
+
CanvasFactory,
|
|
352
|
+
BinaryDataFactory,
|
|
353
|
+
// Warnings remain process-private; the controlled hook detects only the
|
|
354
|
+
// stable maxImageSize signal and emits no diagnostic text.
|
|
355
|
+
verbosity: pdfjs.VerbosityLevel.WARNINGS,
|
|
356
|
+
})
|
|
357
|
+
return { document: await loadingTask.promise, loadingTask }
|
|
358
|
+
} catch {
|
|
359
|
+
if (loadingTask) {
|
|
360
|
+
try { await loadingTask.destroy() } catch {}
|
|
361
|
+
}
|
|
362
|
+
if (resourceState.unavailable) fail(EXIT_UNAVAILABLE)
|
|
363
|
+
fail(EXIT_INVALID_PDF)
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
async function render() {
|
|
368
|
+
const { snapshotPath, outputPath, pageNumber, maxFileBytes } = parseArguments()
|
|
369
|
+
const { createCanvas, pdfjs, resourceUrls } = await loadDependencies()
|
|
370
|
+
const data = await readSnapshot(snapshotPath, maxFileBytes)
|
|
371
|
+
const CanvasFactory = makeCanvasFactory(createCanvas)
|
|
372
|
+
const resourceState = { unavailable: false, invalidRequest: false }
|
|
373
|
+
const BinaryDataFactory = makeBinaryDataFactory(resourceUrls, resourceState)
|
|
374
|
+
const loaded = await loadDocument(
|
|
375
|
+
pdfjs, CanvasFactory, BinaryDataFactory, resourceState, resourceUrls, data,
|
|
376
|
+
)
|
|
377
|
+
const document = loaded.document
|
|
378
|
+
let primaryFailure
|
|
379
|
+
let pageCount
|
|
380
|
+
try {
|
|
381
|
+
pageCount = document.numPages
|
|
382
|
+
if (!Number.isSafeInteger(pageCount) || pageCount < 1 || pageCount > MAX_PAGE_COUNT
|
|
383
|
+
|| pageNumber > pageCount) {
|
|
384
|
+
fail(EXIT_INVALID_PDF)
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
let page
|
|
388
|
+
try { page = await document.getPage(pageNumber) } catch { fail(EXIT_INVALID_PDF) }
|
|
389
|
+
const rawViewport = rawPageViewport(page)
|
|
390
|
+
const { viewport, width, height } = scaledViewport(page, rawViewport)
|
|
391
|
+
const factory = document.canvasFactory
|
|
392
|
+
const canvasAndContext = factory.create(width, height)
|
|
393
|
+
let pageFailure
|
|
394
|
+
try {
|
|
395
|
+
try {
|
|
396
|
+
await page.render({
|
|
397
|
+
canvas: canvasAndContext.canvas,
|
|
398
|
+
viewport,
|
|
399
|
+
intent: 'display',
|
|
400
|
+
// Canvas rendering includes embedded annotation appearances only. No
|
|
401
|
+
// viewer/scripting layer or document action API is ever invoked.
|
|
402
|
+
annotationMode: pdfjs.AnnotationMode.ENABLE,
|
|
403
|
+
background: '#ffffff',
|
|
404
|
+
isEditing: false,
|
|
405
|
+
recordImages: false,
|
|
406
|
+
recordOperations: false,
|
|
407
|
+
}).promise
|
|
408
|
+
if (resourceState.unavailable) fail(EXIT_UNAVAILABLE)
|
|
409
|
+
if (resourceState.invalidRequest) fail(EXIT_INVALID_PDF)
|
|
410
|
+
if (imageLimitObserved) throw new ResourceLimitError()
|
|
411
|
+
} catch (error) {
|
|
412
|
+
if (resourceState.unavailable) fail(EXIT_UNAVAILABLE)
|
|
413
|
+
if (resourceState.invalidRequest) fail(EXIT_INVALID_PDF)
|
|
414
|
+
if (isImageLimitFailure(error)) throw new ResourceLimitError()
|
|
415
|
+
throw error
|
|
416
|
+
}
|
|
417
|
+
const png = await canvasAndContext.canvas.encode('png')
|
|
418
|
+
if (!(png instanceof Uint8Array)) fail(EXIT_FAILURE)
|
|
419
|
+
if (png.byteLength > MAX_PNG_BYTES) throw new ResourceLimitError()
|
|
420
|
+
await open(outputPath, 'wx').then(async handle => {
|
|
421
|
+
let writeFailure
|
|
422
|
+
try { await handle.writeFile(png) } catch (error) { writeFailure = error; throw error }
|
|
423
|
+
finally { try { await handle.close() } catch (error) { if (!writeFailure) throw error } }
|
|
424
|
+
})
|
|
425
|
+
} catch (error) {
|
|
426
|
+
pageFailure = error
|
|
427
|
+
} finally {
|
|
428
|
+
try { factory.destroy(canvasAndContext) } catch (error) { if (!pageFailure) pageFailure = error }
|
|
429
|
+
try { page.cleanup() } catch (error) { if (!pageFailure) pageFailure = error }
|
|
430
|
+
}
|
|
431
|
+
if (pageFailure) throw pageFailure
|
|
432
|
+
} catch (error) {
|
|
433
|
+
primaryFailure = error
|
|
434
|
+
throw error
|
|
435
|
+
} finally {
|
|
436
|
+
try { await loaded.loadingTask.destroy() } catch (error) { if (!primaryFailure) throw error }
|
|
437
|
+
}
|
|
438
|
+
return pageCount
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function exitCode(error) {
|
|
442
|
+
if (error instanceof WorkerFailure) return error.exitCode
|
|
443
|
+
if (isImageLimitFailure(error)) return EXIT_RESOURCE_LIMIT
|
|
444
|
+
return EXIT_FAILURE
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
render().then(
|
|
448
|
+
pageCount => {
|
|
449
|
+
try {
|
|
450
|
+
const payload = JSON.stringify({ page_count: pageCount })
|
|
451
|
+
if (writeSync(1, payload) !== Buffer.byteLength(payload)) throw new Error('short protocol write')
|
|
452
|
+
} catch {
|
|
453
|
+
process.exitCode = EXIT_FAILURE
|
|
454
|
+
}
|
|
455
|
+
},
|
|
456
|
+
error => { process.exitCode = exitCode(error) },
|
|
457
|
+
)
|
|
@@ -17,6 +17,7 @@ export interface RenderPdfPageInput {
|
|
|
17
17
|
readonly expectedSha256?: string;
|
|
18
18
|
}
|
|
19
19
|
export interface RenderedPdfPage {
|
|
20
|
+
readonly renderer: 'poppler' | 'pdfjs';
|
|
20
21
|
readonly name: string;
|
|
21
22
|
readonly page: number;
|
|
22
23
|
readonly page_count: number;
|
|
@@ -28,7 +29,7 @@ export interface RenderedPdfPage {
|
|
|
28
29
|
readonly height?: number;
|
|
29
30
|
}
|
|
30
31
|
export interface PdfPageProcessRequest {
|
|
31
|
-
readonly command: 'pdfinfo' | 'pdftoppm';
|
|
32
|
+
readonly command: 'pdfinfo' | 'pdftoppm' | 'pdfjs';
|
|
32
33
|
readonly args: readonly string[];
|
|
33
34
|
readonly cwd: string;
|
|
34
35
|
readonly signal: AbortSignal;
|
|
@@ -57,7 +58,7 @@ export interface PdfPageRendererDependencies {
|
|
|
57
58
|
readonly removeTemporaryDirectory?: (path: string) => Promise<void>;
|
|
58
59
|
readonly diagnostics?: MinerUDiagnosticSink;
|
|
59
60
|
}
|
|
60
|
-
/** Spawn
|
|
61
|
+
/** Spawn a fixed local renderer command without a shell; settle only after child close/reaping. */
|
|
61
62
|
export declare const runPdfPageProcess: PdfPageProcessRunner;
|
|
62
63
|
export declare function createPdfPageRenderer(dependencies?: PdfPageRendererDependencies): (input: RenderPdfPageInput) => Promise<RenderedPdfPage>;
|
|
63
64
|
export declare const renderPdfPage: (input: RenderPdfPageInput) => Promise<RenderedPdfPage>;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build fixed Node arguments for the local PDF.js renderer. The final four
|
|
3
|
+
* arguments are the worker protocol: snapshot, output, page, and byte limit.
|
|
4
|
+
*/
|
|
5
|
+
export declare function buildPdfjsArgs(snapshotPath: string, outputPath: string, page: number, maxFileBytes: number): string[];
|
|
@@ -24,7 +24,7 @@ export interface DocumentHeading {
|
|
|
24
24
|
}
|
|
25
25
|
export interface DocumentSummary {
|
|
26
26
|
readonly page_count?: number;
|
|
27
|
-
readonly page_count_source?: 'layout' | 'content-list-lower-bound' | 'pdfinfo';
|
|
27
|
+
readonly page_count_source?: 'layout' | 'content-list-lower-bound' | 'pdfinfo' | 'pdfjs';
|
|
28
28
|
readonly table_count?: number;
|
|
29
29
|
readonly image_count?: number;
|
|
30
30
|
readonly equation_count?: number;
|
|
@@ -103,6 +103,8 @@ export interface ResultView {
|
|
|
103
103
|
readonly metadata_shortened?: readonly ShortenedMetadata[];
|
|
104
104
|
readonly source_sha256?: string;
|
|
105
105
|
readonly view?: 'content' | 'page';
|
|
106
|
+
/** Present only for local original-page rendering. */
|
|
107
|
+
readonly renderer?: 'poppler' | 'pdfjs';
|
|
106
108
|
readonly continuation_block?: {
|
|
107
109
|
readonly block_id: string;
|
|
108
110
|
readonly page?: number;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-pdf-mineru",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.15",
|
|
4
4
|
"description": "Provider-independent DSH document parsing powered by MinerU, with native background jobs, immutable results, and safe request coalescing.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh-plugin"
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
},
|
|
39
39
|
"files": [
|
|
40
40
|
"lib/index.js",
|
|
41
|
+
"lib/pdfjs-worker.mjs",
|
|
41
42
|
"lib/client.js",
|
|
42
43
|
"lib/client.js.map",
|
|
43
44
|
"lib/types/**/*.d.ts",
|
|
@@ -59,6 +60,8 @@
|
|
|
59
60
|
}
|
|
60
61
|
},
|
|
61
62
|
"dependencies": {
|
|
63
|
+
"@napi-rs/canvas": "1.0.9",
|
|
64
|
+
"pdfjs-dist": "6.3.289",
|
|
62
65
|
"yauzl": "^3.4.0"
|
|
63
66
|
},
|
|
64
67
|
"peerDependencies": {
|
|
@@ -126,7 +129,7 @@
|
|
|
126
129
|
"yazl": "^3.3.1"
|
|
127
130
|
},
|
|
128
131
|
"scripts": {
|
|
129
|
-
"build": "pnpm run clean && pnpm run build:types && tsdown --config tsdown.config.ts",
|
|
132
|
+
"build": "pnpm run clean && pnpm run build:types && tsdown --config tsdown.config.ts && node scripts/copy-page-worker.mjs",
|
|
130
133
|
"build:types": "tsc -b tsconfig.host.json tsconfig.client.json",
|
|
131
134
|
"clean": "tsc -b tsconfig.host.json tsconfig.client.json --clean && node scripts/clean.mjs",
|
|
132
135
|
"typecheck": "tsc -b tsconfig.host.json tsconfig.client.json --pretty false",
|