dsh-pdf-mineru 0.2.1 → 0.2.2
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 +14 -1
- package/lib/client.js +112 -104
- package/lib/client.js.map +1 -1
- package/lib/index.js +144 -63
- package/lib/pdfjs-worker.mjs +38 -16
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -1352,56 +1352,99 @@ function resolveProviderUrl(baseUrl, path) {
|
|
|
1352
1352
|
const normalizedPath = path ? path.startsWith("/") ? path : `/${path}` : "";
|
|
1353
1353
|
return `${parsed.origin}${basePath}${normalizedPath}`;
|
|
1354
1354
|
}
|
|
1355
|
+
const UPSTREAM_CODE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;
|
|
1356
|
+
function nonEmptyString(value) {
|
|
1357
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
1358
|
+
}
|
|
1355
1359
|
/**
|
|
1356
|
-
*
|
|
1357
|
-
*
|
|
1358
|
-
*
|
|
1360
|
+
* Describes a MinerU 4.x V1 error object `{ type, code, message, param }`. API servers and Routers use
|
|
1361
|
+
* it for HTTP error bodies (under `error`) and for per-file job errors. The code leads the diagnostic
|
|
1362
|
+
* because it names the cause (`engine_dead`, `quality_tier_unavailable`, `file_not_found`) more
|
|
1363
|
+
* precisely than the HTTP status. `fallbackMessage` stands in for a missing message.
|
|
1359
1364
|
*/
|
|
1360
|
-
function
|
|
1361
|
-
|
|
1365
|
+
function describeV1Error(value, fallbackMessage) {
|
|
1366
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
1367
|
+
const record = value;
|
|
1368
|
+
const code = nonEmptyString(record.code);
|
|
1369
|
+
const text = nonEmptyString(record.message) ?? (code === void 0 ? void 0 : nonEmptyString(fallbackMessage));
|
|
1370
|
+
if (code === void 0 && text === void 0) return void 0;
|
|
1371
|
+
const param = nonEmptyString(record.param);
|
|
1372
|
+
return {
|
|
1373
|
+
message: [code, text].filter((part) => part !== void 0).join(": ") + (param === void 0 ? "" : ` (param: ${param})`),
|
|
1374
|
+
...code !== void 0 && UPSTREAM_CODE_PATTERN.test(code) ? { code } : {}
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
/** Keeps an upstream code as `providerCode` only when it is a plain token carrying none of the secrets. */
|
|
1378
|
+
function safeProviderCode(code, secrets = []) {
|
|
1379
|
+
if (code === void 0 || !UPSTREAM_CODE_PATTERN.test(code)) return void 0;
|
|
1380
|
+
return sanitizeDiagnostic(code, secrets) === code ? code : void 0;
|
|
1381
|
+
}
|
|
1382
|
+
/**
|
|
1383
|
+
* Extracts the diagnostic of an API error response body. A self-hosted V1 body is read as the V1
|
|
1384
|
+
* error envelope first; otherwise the JSON fields detail, message, error and msg are inspected
|
|
1385
|
+
* (msg first for official-v4, detail first for self-hosted). Non-JSON bodies fall back to their
|
|
1386
|
+
* truncated raw text.
|
|
1387
|
+
*/
|
|
1388
|
+
function extractErrorDetail(bodyText, provider) {
|
|
1389
|
+
let parsed;
|
|
1362
1390
|
try {
|
|
1363
|
-
|
|
1364
|
-
if (typeof parsed === "object" && parsed !== null) {
|
|
1365
|
-
const json = parsed;
|
|
1366
|
-
if (provider === "official-v4") {
|
|
1367
|
-
if (typeof json.msg === "string") parsedError = json.msg;
|
|
1368
|
-
else if (typeof json.message === "string") parsedError = json.message;
|
|
1369
|
-
else if (typeof json.detail === "string") parsedError = json.detail;
|
|
1370
|
-
else if (typeof json.error === "string") parsedError = json.error;
|
|
1371
|
-
} else if (typeof json.detail === "string") parsedError = json.detail;
|
|
1372
|
-
else if (typeof json.message === "string") parsedError = json.message;
|
|
1373
|
-
else if (typeof json.error === "string") parsedError = json.error;
|
|
1374
|
-
else if (typeof json.msg === "string") parsedError = json.msg;
|
|
1375
|
-
}
|
|
1391
|
+
parsed = JSON.parse(bodyText);
|
|
1376
1392
|
} catch {
|
|
1377
|
-
|
|
1393
|
+
const raw = bodyText.slice(0, 500);
|
|
1394
|
+
return raw === "" ? {} : { message: raw };
|
|
1395
|
+
}
|
|
1396
|
+
if (typeof parsed !== "object" || parsed === null) return {};
|
|
1397
|
+
const json = parsed;
|
|
1398
|
+
if (provider === "self-hosted-v1") {
|
|
1399
|
+
const envelope = describeV1Error(json.error);
|
|
1400
|
+
if (envelope !== void 0) return envelope;
|
|
1401
|
+
}
|
|
1402
|
+
const fields = provider === "official-v4" ? [
|
|
1403
|
+
"msg",
|
|
1404
|
+
"message",
|
|
1405
|
+
"detail",
|
|
1406
|
+
"error"
|
|
1407
|
+
] : [
|
|
1408
|
+
"detail",
|
|
1409
|
+
"message",
|
|
1410
|
+
"error",
|
|
1411
|
+
"msg"
|
|
1412
|
+
];
|
|
1413
|
+
for (const field of fields) {
|
|
1414
|
+
const value = json[field];
|
|
1415
|
+
if (typeof value === "string") return { message: value };
|
|
1378
1416
|
}
|
|
1379
|
-
return
|
|
1417
|
+
return {};
|
|
1380
1418
|
}
|
|
1381
1419
|
/**
|
|
1382
1420
|
* Maps HTTP error status codes to typed MinerUError instances with provider-specific diagnostic phrasing.
|
|
1421
|
+
* `providerCode` records the upstream error code when the body carried one.
|
|
1383
1422
|
*/
|
|
1384
|
-
function createHttpStatusError(provider, status, diagnostic, retryAfterMs) {
|
|
1423
|
+
function createHttpStatusError(provider, status, diagnostic, retryAfterMs, providerCode) {
|
|
1385
1424
|
const options = { http: {
|
|
1386
1425
|
status,
|
|
1387
1426
|
retryAfterMs
|
|
1388
1427
|
} };
|
|
1428
|
+
const details = {
|
|
1429
|
+
provider,
|
|
1430
|
+
...providerCode === void 0 ? {} : { providerCode }
|
|
1431
|
+
};
|
|
1389
1432
|
let err;
|
|
1390
1433
|
if (provider === "official-v4") {
|
|
1391
|
-
if (status === 401 || status === 403) err = new MinerUError(failure("AUTHENTICATION_FAILED", `Official MinerU authentication failed (${String(status)})${diagnostic}`, false,
|
|
1392
|
-
else if (status === 404) err = new MinerUError(failure("JOB_NOT_FOUND", `Official MinerU resource not found (${String(status)})${diagnostic}`, false,
|
|
1393
|
-
else if (status === 413) err = new MinerUError(failure("FILE_TOO_LARGE", `File exceeds size limit (${String(status)})${diagnostic}`, false,
|
|
1394
|
-
else if (status === 429) err = new MinerUError(failure("PROVIDER_RATE_LIMITED", `Official MinerU rate limit exceeded (${String(status)})${diagnostic}`, true,
|
|
1395
|
-
else if (status === 408) err = new MinerUError(failure("PROVIDER_UNAVAILABLE", `Official MinerU request timeout (${String(status)})${diagnostic}`, true,
|
|
1396
|
-
else if (status >= 500) err = new MinerUError(failure("PROVIDER_UNAVAILABLE", `Official MinerU server error (${String(status)})${diagnostic}`, true,
|
|
1397
|
-
else err = new MinerUError(failure("REMOTE_PARSE_FAILED", `Official MinerU returned status ${String(status)}${diagnostic}`, false,
|
|
1398
|
-
} else if (status === 401 || status === 403) err = new MinerUError(failure("AUTHENTICATION_FAILED", `Authentication failed (${String(status)})${diagnostic}`, false,
|
|
1399
|
-
else if (status === 404) err = new MinerUError(failure("JOB_NOT_FOUND", `Resource not found (${String(status)})${diagnostic}`, false,
|
|
1400
|
-
else if (status === 413) err = new MinerUError(failure("FILE_TOO_LARGE", `Uploaded file is too large (${String(status)})${diagnostic}`, false,
|
|
1401
|
-
else if (status === 429) err = new MinerUError(failure("PROVIDER_RATE_LIMITED", `Provider rate limit exceeded (${String(status)})${diagnostic}`, true,
|
|
1402
|
-
else if (status === 408) err = new MinerUError(failure("PROVIDER_UNAVAILABLE", `MinerU server request timeout (${String(status)})${diagnostic}`, true,
|
|
1403
|
-
else if (status >= 500) err = new MinerUError(failure("PROVIDER_UNAVAILABLE", `MinerU server error (${String(status)})${diagnostic}`, true,
|
|
1404
|
-
else err = new MinerUError(failure("REMOTE_PARSE_FAILED", `MinerU returned unexpected status ${String(status)}${diagnostic}`, false,
|
|
1434
|
+
if (status === 401 || status === 403) err = new MinerUError(failure("AUTHENTICATION_FAILED", `Official MinerU authentication failed (${String(status)})${diagnostic}`, false, details), options);
|
|
1435
|
+
else if (status === 404) err = new MinerUError(failure("JOB_NOT_FOUND", `Official MinerU resource not found (${String(status)})${diagnostic}`, false, details), options);
|
|
1436
|
+
else if (status === 413) err = new MinerUError(failure("FILE_TOO_LARGE", `File exceeds size limit (${String(status)})${diagnostic}`, false, details), options);
|
|
1437
|
+
else if (status === 429) err = new MinerUError(failure("PROVIDER_RATE_LIMITED", `Official MinerU rate limit exceeded (${String(status)})${diagnostic}`, true, details), options);
|
|
1438
|
+
else if (status === 408) err = new MinerUError(failure("PROVIDER_UNAVAILABLE", `Official MinerU request timeout (${String(status)})${diagnostic}`, true, details), options);
|
|
1439
|
+
else if (status >= 500) err = new MinerUError(failure("PROVIDER_UNAVAILABLE", `Official MinerU server error (${String(status)})${diagnostic}`, true, details), options);
|
|
1440
|
+
else err = new MinerUError(failure("REMOTE_PARSE_FAILED", `Official MinerU returned status ${String(status)}${diagnostic}`, false, details), options);
|
|
1441
|
+
} else if (status === 401 || status === 403) err = new MinerUError(failure("AUTHENTICATION_FAILED", `Authentication failed (${String(status)})${diagnostic}`, false, details), options);
|
|
1442
|
+
else if (status === 404) err = new MinerUError(failure("JOB_NOT_FOUND", `Resource not found (${String(status)})${diagnostic}`, false, details), options);
|
|
1443
|
+
else if (status === 413) err = new MinerUError(failure("FILE_TOO_LARGE", `Uploaded file is too large (${String(status)})${diagnostic}`, false, details), options);
|
|
1444
|
+
else if (status === 429) err = new MinerUError(failure("PROVIDER_RATE_LIMITED", `Provider rate limit exceeded (${String(status)})${diagnostic}`, true, details), options);
|
|
1445
|
+
else if (status === 408) err = new MinerUError(failure("PROVIDER_UNAVAILABLE", `MinerU server request timeout (${String(status)})${diagnostic}`, true, details), options);
|
|
1446
|
+
else if (status >= 500) err = new MinerUError(failure("PROVIDER_UNAVAILABLE", `MinerU server error (${String(status)})${diagnostic}`, true, details), options);
|
|
1447
|
+
else err = new MinerUError(failure("REMOTE_PARSE_FAILED", `MinerU returned unexpected status ${String(status)}${diagnostic}`, false, details), options);
|
|
1405
1448
|
return err;
|
|
1406
1449
|
}
|
|
1407
1450
|
/**
|
|
@@ -1469,10 +1512,11 @@ var ProviderHttpClient = class {
|
|
|
1469
1512
|
await response.body.cancel();
|
|
1470
1513
|
} catch {}
|
|
1471
1514
|
}
|
|
1472
|
-
const
|
|
1473
|
-
const
|
|
1515
|
+
const secrets = [reqContext.credential ?? ""];
|
|
1516
|
+
const detail = extractErrorDetail(errorBody, this.provider);
|
|
1517
|
+
const diagnostic = detail.message ? `: ${sanitizeDiagnostic(detail.message, secrets)}` : "";
|
|
1474
1518
|
const retryAfterMs = parseRetryAfter(response.headers.get("retry-after"));
|
|
1475
|
-
throw createHttpStatusError(this.provider, status, diagnostic, retryAfterMs);
|
|
1519
|
+
throw createHttpStatusError(this.provider, status, diagnostic, retryAfterMs, safeProviderCode(detail.code, secrets));
|
|
1476
1520
|
}
|
|
1477
1521
|
const contentType = response.headers.get("content-type") ?? "";
|
|
1478
1522
|
if (!contentType.toLowerCase().includes("application/json")) {
|
|
@@ -2001,7 +2045,14 @@ var SelfHostedV1Uploader = class {
|
|
|
2001
2045
|
await response.body.cancel();
|
|
2002
2046
|
} catch {}
|
|
2003
2047
|
}
|
|
2004
|
-
|
|
2048
|
+
const secrets = [context.credential ?? ""];
|
|
2049
|
+
const detail = extractErrorDetail(errorBody, "self-hosted-v1");
|
|
2050
|
+
const providerCode = safeProviderCode(detail.code, secrets);
|
|
2051
|
+
const diagnostic = detail.message || errorBody;
|
|
2052
|
+
throw uploadFailed(`Upload failed with HTTP status ${String(response.status)}${diagnostic === "" ? "" : `: ${sanitizeDiagnostic(diagnostic, secrets)}`}`, isRetryableHttpStatus(response.status), {
|
|
2053
|
+
fileId: source.fileId,
|
|
2054
|
+
...providerCode === void 0 ? {} : { providerCode }
|
|
2055
|
+
}, {
|
|
2005
2056
|
status: response.status,
|
|
2006
2057
|
retryAfterMs: parseRetryAfter(response.headers.get("retry-after"))
|
|
2007
2058
|
});
|
|
@@ -3619,6 +3670,23 @@ async function extractSafeZip(options) {
|
|
|
3619
3670
|
}
|
|
3620
3671
|
return results;
|
|
3621
3672
|
}
|
|
3673
|
+
/** Upper bound for reading the error body of a failed result download. */
|
|
3674
|
+
const DOWNLOAD_ERROR_BODY_BYTES = 2048;
|
|
3675
|
+
/**
|
|
3676
|
+
* Per-file failure carrying the upstream V1 error code and message. A job failed by a latched engine
|
|
3677
|
+
* (`engine_dead`) or lost by a Router worker (`upstream_job_lost`) is told apart from a document the
|
|
3678
|
+
* engine could not parse (`parse_failed`).
|
|
3679
|
+
*/
|
|
3680
|
+
function remoteFileFailure(jobFile, fileId, credential) {
|
|
3681
|
+
const secrets = [credential ?? ""];
|
|
3682
|
+
const detail = describeV1Error(jobFile.error, "Remote document extraction failed");
|
|
3683
|
+
const providerCode = safeProviderCode(detail?.code, secrets);
|
|
3684
|
+
return failure("REMOTE_PARSE_FAILED", sanitizeDiagnostic(detail?.message ?? "Remote document extraction failed", secrets), false, {
|
|
3685
|
+
provider: "self-hosted-v1",
|
|
3686
|
+
fileId,
|
|
3687
|
+
...providerCode === void 0 ? {} : { providerCode }
|
|
3688
|
+
});
|
|
3689
|
+
}
|
|
3622
3690
|
function archiveInvalid(message, fileId) {
|
|
3623
3691
|
return new MinerUError(failure("REMOTE_PARSE_FAILED", message, false, {
|
|
3624
3692
|
provider: "self-hosted-v1",
|
|
@@ -3886,10 +3954,7 @@ var SelfHostedV1Provider = class {
|
|
|
3886
3954
|
fileId: file.fileId,
|
|
3887
3955
|
name: file.name,
|
|
3888
3956
|
artifacts: [],
|
|
3889
|
-
failure:
|
|
3890
|
-
provider: "self-hosted-v1",
|
|
3891
|
-
fileId: file.fileId
|
|
3892
|
-
})
|
|
3957
|
+
failure: remoteFileFailure(jobFile, file.fileId, context.credential)
|
|
3893
3958
|
});
|
|
3894
3959
|
continue;
|
|
3895
3960
|
}
|
|
@@ -3965,10 +4030,7 @@ var SelfHostedV1Provider = class {
|
|
|
3965
4030
|
fileId: file.fileId,
|
|
3966
4031
|
state: fileState,
|
|
3967
4032
|
rawState: typeof jobFile.status === "string" ? jobFile.status : void 0,
|
|
3968
|
-
...fileState === "failed" ? { failure:
|
|
3969
|
-
provider: "self-hosted-v1",
|
|
3970
|
-
fileId: file.fileId
|
|
3971
|
-
}) } : {}
|
|
4033
|
+
...fileState === "failed" ? { failure: remoteFileFailure(jobFile, file.fileId, context.credential) } : {}
|
|
3972
4034
|
});
|
|
3973
4035
|
if (fileState !== "completed" && fileState !== "failed") hasNonTerminal = true;
|
|
3974
4036
|
if (fileState !== "queued") everyQueued = false;
|
|
@@ -4022,10 +4084,21 @@ var SelfHostedV1Provider = class {
|
|
|
4022
4084
|
throw new MinerUError(failure("RESULT_DOWNLOAD_FAILED", `Failed to download result archive: ${error instanceof Error ? error.message : String(error)}`, true, { provider: "self-hosted-v1" }));
|
|
4023
4085
|
}
|
|
4024
4086
|
if (response.status !== 200) {
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4087
|
+
let errorBody = "";
|
|
4088
|
+
try {
|
|
4089
|
+
errorBody = await readBoundedResponseText(response, DOWNLOAD_ERROR_BODY_BYTES, controller.signal);
|
|
4090
|
+
} catch {
|
|
4091
|
+
if (response.body) try {
|
|
4092
|
+
await response.body.cancel();
|
|
4093
|
+
} catch {}
|
|
4094
|
+
}
|
|
4095
|
+
const secrets = [context.credential ?? ""];
|
|
4096
|
+
const detail = extractErrorDetail(errorBody, "self-hosted-v1");
|
|
4097
|
+
const providerCode = safeProviderCode(detail.code, secrets);
|
|
4098
|
+
throw new MinerUError(failure("RESULT_DOWNLOAD_FAILED", `Failed to download result archive, HTTP status ${String(response.status)}${detail.message ? `: ${sanitizeDiagnostic(detail.message, secrets)}` : ""}`, isRetryableHttpStatus(response.status), {
|
|
4099
|
+
provider: "self-hosted-v1",
|
|
4100
|
+
...providerCode === void 0 ? {} : { providerCode }
|
|
4101
|
+
}), { http: {
|
|
4029
4102
|
status: response.status,
|
|
4030
4103
|
retryAfterMs: parseRetryAfter(response.headers.get("retry-after"))
|
|
4031
4104
|
} });
|
|
@@ -5674,6 +5747,19 @@ function killChild(child) {
|
|
|
5674
5747
|
child.kill("SIGKILL");
|
|
5675
5748
|
} catch {}
|
|
5676
5749
|
}
|
|
5750
|
+
/**
|
|
5751
|
+
* Allow-listed renderer environment. `TZ=UTC` keeps Poppler's localized time-zone
|
|
5752
|
+
* names (printed in the system code page on Windows, which ignores LC_ALL) out of
|
|
5753
|
+
* pdfinfo date fields; no other host variable is inherited besides PATH.
|
|
5754
|
+
*/
|
|
5755
|
+
function rendererEnvironment(path = process.env.PATH) {
|
|
5756
|
+
return {
|
|
5757
|
+
PATH: path ?? "",
|
|
5758
|
+
LANG: "C",
|
|
5759
|
+
LC_ALL: "C",
|
|
5760
|
+
TZ: "UTC"
|
|
5761
|
+
};
|
|
5762
|
+
}
|
|
5677
5763
|
/** Spawn a fixed local renderer command without a shell; settle only after child close/reaping. */
|
|
5678
5764
|
const runPdfPageProcess = (request) => new Promise((resolvePromise, rejectPromise) => {
|
|
5679
5765
|
request.signal.throwIfAborted();
|
|
@@ -5681,11 +5767,7 @@ const runPdfPageProcess = (request) => new Promise((resolvePromise, rejectPromis
|
|
|
5681
5767
|
try {
|
|
5682
5768
|
child = spawn(request.command === "pdfjs" ? process.execPath : request.command, [...request.args], {
|
|
5683
5769
|
cwd: request.cwd,
|
|
5684
|
-
env:
|
|
5685
|
-
PATH: process.env.PATH ?? "",
|
|
5686
|
-
LANG: "C",
|
|
5687
|
-
LC_ALL: "C"
|
|
5688
|
-
},
|
|
5770
|
+
env: rendererEnvironment(),
|
|
5689
5771
|
shell: false,
|
|
5690
5772
|
stdio: [
|
|
5691
5773
|
"ignore",
|
|
@@ -5881,14 +5963,13 @@ function parsePdfjsPageCount(result) {
|
|
|
5881
5963
|
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$1("PDF.js returned invalid page metadata");
|
|
5882
5964
|
return parsed.page_count;
|
|
5883
5965
|
}
|
|
5966
|
+
/**
|
|
5967
|
+
* Only the ASCII `Pages:` line is consumed. Latin-1 maps every byte to one
|
|
5968
|
+
* character and cannot fail, so unrelated fields in a local code page (for
|
|
5969
|
+
* example a CreationDate time-zone name on non-English Windows) are inert.
|
|
5970
|
+
*/
|
|
5884
5971
|
function parsePageCount(stdout) {
|
|
5885
|
-
|
|
5886
|
-
try {
|
|
5887
|
-
text = new TextDecoder("utf-8", { fatal: true }).decode(stdout);
|
|
5888
|
-
} catch (error) {
|
|
5889
|
-
throw invalid$1("pdfinfo returned invalid UTF-8 output", error);
|
|
5890
|
-
}
|
|
5891
|
-
const matches = [...text.matchAll(/^Pages:\s+([1-9][0-9]{0,6})\s*$/gm)];
|
|
5972
|
+
const matches = [...Buffer.from(stdout.buffer, stdout.byteOffset, stdout.byteLength).toString("latin1").matchAll(/^Pages:\s+([1-9][0-9]{0,6})\s*$/gm)];
|
|
5892
5973
|
if (matches.length !== 1) throw invalid$1("pdfinfo did not return one valid physical page count");
|
|
5893
5974
|
const pages = Number(matches[0][1]);
|
|
5894
5975
|
if (!Number.isSafeInteger(pages) || pages < 1 || pages > MAX_PAGE_COUNT) throw invalid$1("PDF physical page count is outside the supported range");
|
package/lib/pdfjs-worker.mjs
CHANGED
|
@@ -8,8 +8,9 @@ import http2 from 'node:http2'
|
|
|
8
8
|
import https from 'node:https'
|
|
9
9
|
import { createRequire } from 'node:module'
|
|
10
10
|
import net from 'node:net'
|
|
11
|
-
import { dirname, join
|
|
11
|
+
import { dirname, join } from 'node:path'
|
|
12
12
|
import tls from 'node:tls'
|
|
13
|
+
import { pathToFileURL } from 'node:url'
|
|
13
14
|
|
|
14
15
|
const EXIT_UNAVAILABLE = 20
|
|
15
16
|
const EXIT_INVALID_PDF = 21
|
|
@@ -109,25 +110,39 @@ async function assertDirectory(path) {
|
|
|
109
110
|
if (!info.isDirectory()) throw new Error('resource unavailable')
|
|
110
111
|
}
|
|
111
112
|
|
|
113
|
+
/**
|
|
114
|
+
* PDF.js requires its resource URL parameters to end with "/" on every
|
|
115
|
+
* platform; native directory paths end with "\\" on Windows. The bounded
|
|
116
|
+
* BinaryDataFactory reads from the native directories, so these URLs only
|
|
117
|
+
* satisfy PDF.js parameter validation and are never fetched.
|
|
118
|
+
*/
|
|
119
|
+
function resourceDirectoryUrl(directory) {
|
|
120
|
+
const href = pathToFileURL(directory).href
|
|
121
|
+
return href.endsWith('/') ? href : href + '/'
|
|
122
|
+
}
|
|
123
|
+
|
|
112
124
|
async function loadDependencies() {
|
|
113
125
|
try {
|
|
114
126
|
const require = createRequire(import.meta.url)
|
|
115
127
|
const packageRoot = dirname(require.resolve('pdfjs-dist/package.json'))
|
|
116
|
-
const
|
|
117
|
-
cMapUrl: join(packageRoot, 'cmaps')
|
|
118
|
-
iccUrl: join(packageRoot, 'iccs')
|
|
119
|
-
standardFontDataUrl: join(packageRoot, 'standard_fonts')
|
|
120
|
-
wasmUrl: join(packageRoot, 'wasm')
|
|
128
|
+
const resourceDirs = {
|
|
129
|
+
cMapUrl: join(packageRoot, 'cmaps'),
|
|
130
|
+
iccUrl: join(packageRoot, 'iccs'),
|
|
131
|
+
standardFontDataUrl: join(packageRoot, 'standard_fonts'),
|
|
132
|
+
wasmUrl: join(packageRoot, 'wasm'),
|
|
121
133
|
}
|
|
134
|
+
const resourceUrls = Object.fromEntries(
|
|
135
|
+
Object.entries(resourceDirs).map(([kind, directory]) => [kind, resourceDirectoryUrl(directory)]),
|
|
136
|
+
)
|
|
122
137
|
|
|
123
|
-
await Promise.all(Object.values(
|
|
138
|
+
await Promise.all(Object.values(resourceDirs).map(assertDirectory))
|
|
124
139
|
await Promise.all([
|
|
125
|
-
access(join(
|
|
126
|
-
access(join(
|
|
127
|
-
access(join(
|
|
128
|
-
access(join(
|
|
129
|
-
access(join(
|
|
130
|
-
access(join(
|
|
140
|
+
access(join(resourceDirs.cMapUrl, 'Adobe-CNS1-UCS2.bcmap'), constants.R_OK),
|
|
141
|
+
access(join(resourceDirs.iccUrl, 'CGATS001Compat-v2-micro.icc'), constants.R_OK),
|
|
142
|
+
access(join(resourceDirs.standardFontDataUrl, 'LiberationSans-Regular.ttf'), constants.R_OK),
|
|
143
|
+
access(join(resourceDirs.wasmUrl, 'jbig2.wasm'), constants.R_OK),
|
|
144
|
+
access(join(resourceDirs.wasmUrl, 'openjpeg.wasm'), constants.R_OK),
|
|
145
|
+
access(join(resourceDirs.wasmUrl, 'qcms_bg.wasm'), constants.R_OK),
|
|
131
146
|
access(join(packageRoot, 'legacy', 'build', 'pdf.worker.mjs'), constants.R_OK),
|
|
132
147
|
])
|
|
133
148
|
|
|
@@ -144,7 +159,8 @@ async function loadDependencies() {
|
|
|
144
159
|
return {
|
|
145
160
|
createCanvas: canvasModule.createCanvas,
|
|
146
161
|
pdfjs,
|
|
147
|
-
|
|
162
|
+
resourceDirs,
|
|
163
|
+
resourceUrls,
|
|
148
164
|
}
|
|
149
165
|
} catch {
|
|
150
166
|
fail(EXIT_UNAVAILABLE)
|
|
@@ -329,6 +345,8 @@ function isImageLimitFailure(error) {
|
|
|
329
345
|
async function loadDocument(pdfjs, CanvasFactory, BinaryDataFactory, resourceState, resourceUrls, data) {
|
|
330
346
|
let loadingTask
|
|
331
347
|
try {
|
|
348
|
+
// getDocument validates its parameters synchronously. A throw here is a
|
|
349
|
+
// worker/dependency configuration fault, never evidence of an invalid PDF.
|
|
332
350
|
loadingTask = pdfjs.getDocument({
|
|
333
351
|
data,
|
|
334
352
|
cMapUrl: resourceUrls.cMapUrl,
|
|
@@ -356,6 +374,10 @@ async function loadDocument(pdfjs, CanvasFactory, BinaryDataFactory, resourceSta
|
|
|
356
374
|
// stable maxImageSize signal and emits no diagnostic text.
|
|
357
375
|
verbosity: pdfjs.VerbosityLevel.WARNINGS,
|
|
358
376
|
})
|
|
377
|
+
} catch {
|
|
378
|
+
fail(EXIT_FAILURE)
|
|
379
|
+
}
|
|
380
|
+
try {
|
|
359
381
|
return { document: await loadingTask.promise, loadingTask }
|
|
360
382
|
} catch {
|
|
361
383
|
if (loadingTask) {
|
|
@@ -368,11 +390,11 @@ async function loadDocument(pdfjs, CanvasFactory, BinaryDataFactory, resourceSta
|
|
|
368
390
|
|
|
369
391
|
async function render() {
|
|
370
392
|
const { snapshotPath, outputPath, pageNumber, maxFileBytes } = parseArguments()
|
|
371
|
-
const { createCanvas, pdfjs, resourceUrls } = await loadDependencies()
|
|
393
|
+
const { createCanvas, pdfjs, resourceDirs, resourceUrls } = await loadDependencies()
|
|
372
394
|
const data = await readSnapshot(snapshotPath, maxFileBytes)
|
|
373
395
|
const CanvasFactory = makeCanvasFactory(createCanvas)
|
|
374
396
|
const resourceState = { unavailable: false, invalidRequest: false }
|
|
375
|
-
const BinaryDataFactory = makeBinaryDataFactory(
|
|
397
|
+
const BinaryDataFactory = makeBinaryDataFactory(resourceDirs, resourceState)
|
|
376
398
|
const loaded = await loadDocument(
|
|
377
399
|
pdfjs, CanvasFactory, BinaryDataFactory, resourceState, resourceUrls, data,
|
|
378
400
|
)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-pdf-mineru",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Read PDFs in DeepSeek Harness with MinerU (official cloud or self-hosted): bounded evidence reading, background parsing jobs, and local page verification.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh-plugin",
|