dislop 0.9.0 → 1.0.1
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/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +2 -2
- package/.codex-plugin/plugin.json +7 -8
- package/.cursor-plugin/plugin.json +2 -3
- package/.pre-commit-hooks.yaml +5 -12
- package/PRODUCT.md +19 -57
- package/README.md +360 -252
- package/README.zh-CN.md +390 -240
- package/action.yml +30 -39
- package/bin/dislop-mcp.mjs +3 -4
- package/bin/dislop.mjs +4 -4582
- package/gemini-extension.json +2 -2
- package/llms-install.md +68 -0
- package/package.json +17 -55
- package/packs/common/artifact-qa/pack.json +5 -0
- package/packs/common/artifact-qa/prompts/rules.md +11 -0
- package/packs/common/artifact-qa/scripts/index.mjs +173 -0
- package/packs/common/slide-deck/pack.json +6 -0
- package/packs/common/slide-deck/prompts/rules.md +11 -0
- package/packs/common/slide-deck/scripts/index.mjs +62 -0
- package/packs/common/web-ui/pack.json +6 -0
- package/packs/common/web-ui/prompts/rules.md +11 -0
- package/packs/common/web-ui/scripts/index.mjs +80 -0
- package/packs/en/artifact-qa/pack.json +6 -0
- package/packs/en/artifact-qa/prompts/rules.md +14 -0
- package/packs/en/artifact-qa/scripts/index.mjs +90 -0
- package/packs/en/prose/pack.json +7 -0
- package/packs/en/prose/prompts/rules.md +26 -0
- package/packs/en/prose/scripts/index.mjs +290 -0
- package/packs/en/slide-deck/pack.json +7 -0
- package/packs/en/slide-deck/prompts/rules.md +17 -0
- package/packs/en/slide-deck/scripts/index.mjs +81 -0
- package/packs/en/web-ui/pack.json +7 -0
- package/packs/en/web-ui/prompts/rules.md +20 -0
- package/packs/en/web-ui/scripts/index.mjs +103 -0
- package/packs/zh/artifact-qa/pack.json +6 -0
- package/packs/zh/artifact-qa/prompts/rules.md +14 -0
- package/packs/zh/artifact-qa/scripts/index.mjs +89 -0
- package/packs/zh/prose/pack.json +7 -0
- package/packs/zh/prose/prompts/rules.md +26 -0
- package/packs/zh/prose/scripts/index.mjs +305 -0
- package/packs/zh/slide-deck/pack.json +7 -0
- package/packs/zh/slide-deck/prompts/rules.md +17 -0
- package/packs/zh/slide-deck/scripts/index.mjs +75 -0
- package/packs/zh/web-ui/pack.json +7 -0
- package/packs/zh/web-ui/prompts/rules.md +20 -0
- package/packs/zh/web-ui/scripts/index.mjs +98 -0
- package/plugin.json +5 -6
- package/server.json +8 -2
- package/skills/deslop-docs/SKILL.md +10 -8
- package/skills/deslop-slides-docx/SKILL.md +7 -8
- package/skills/deslop-verify/SKILL.md +7 -8
- package/skills/deslop-web-ui/SKILL.md +7 -8
- package/skills/dislop/SKILL.md +16 -28
- package/skills/dislop/references/essay.md +1 -1
- package/skills/dislop/references/essay.zh-CN.md +1 -1
- package/skills/dislop/references/office.md +1 -1
- package/skills/dislop/references/office.zh-CN.md +1 -1
- package/skills/dislop/references/web-ui.md +1 -1
- package/skills/dislop/references/web-ui.zh-CN.md +1 -1
- package/skills/dislop/references/work-docs.md +1 -1
- package/skills/dislop/references/work-docs.zh-CN.md +1 -1
- package/src/cli-main.mjs +210 -0
- package/src/commands/check-fix.mjs +169 -0
- package/src/commands/doctor.mjs +110 -0
- package/src/commands/init.mjs +49 -0
- package/src/commands/login.mjs +82 -0
- package/src/commands/model.mjs +130 -0
- package/src/commands/packs.mjs +44 -0
- package/src/commands/verify.mjs +133 -0
- package/src/commands/voice.mjs +84 -0
- package/src/kernel/config.mjs +232 -0
- package/src/kernel/document-model.mjs +1412 -0
- package/src/kernel/fact-gate.mjs +615 -0
- package/src/kernel/file-discovery.mjs +139 -0
- package/src/{binary-node.mjs → kernel/ooxml-binary.mjs} +532 -893
- package/src/kernel/pack-loader.mjs +715 -0
- package/src/kernel/patcher.mjs +341 -0
- package/src/kernel/pipeline.mjs +267 -0
- package/src/kernel/prompt-assembler.mjs +307 -0
- package/src/kernel/voice-profile.mjs +177 -0
- package/src/mcp/stdio-server.mjs +372 -0
- package/src/runners/auto-fix.mjs +59 -0
- package/src/runners/interactive-tty.mjs +461 -0
- package/src/runners/reporters.mjs +256 -0
- package/src/runtime/chunker.mjs +87 -0
- package/src/runtime/json-extract.mjs +144 -0
- package/src/runtime/privacy-gate.mjs +97 -0
- package/src/runtime/providers/anthropic.mjs +65 -0
- package/src/runtime/providers/cloud.mjs +136 -0
- package/src/runtime/providers/gemini.mjs +91 -0
- package/src/runtime/providers/local-model.mjs +139 -0
- package/src/runtime/providers/openai-compat.mjs +130 -0
- package/src/runtime/router.mjs +315 -0
- package/src/sdk/index.mjs +137 -0
- package/models/manifest.json +0 -90
- package/models/pocket-slop-v1.json +0 -1
- package/packs/business-brief/pack.json +0 -937
- package/packs/core/pack.json +0 -209
- package/packs/deck-and-ui/pack.json +0 -539
- package/packs/engineering-spec/pack.json +0 -144
- package/packs/executive-deck/pack.json +0 -98
- package/packs/literary-essay/pack.json +0 -344
- package/packs/regulated-comms/pack.json +0 -99
- package/patterns/ai-tic-rubric.json +0 -252
- package/patterns/banks/composite-fusion.json +0 -48
- package/patterns/banks/discourse-rhythm.json +0 -95
- package/patterns/banks/lexical-signals.json +0 -92
- package/patterns/banks/syntactic-frames.json +0 -52
- package/patterns/banks/visual-deck.json +0 -44
- package/patterns/dimensions/artifacts.json +0 -121
- package/patterns/dimensions/discourse.json +0 -438
- package/patterns/dimensions/lexical.json +0 -198
- package/patterns/dimensions/rhythm.json +0 -258
- package/patterns/dimensions/syntactic.json +0 -285
- package/patterns/dimensions/visual-and-deck.json +0 -530
- package/patterns/taxonomy.json +0 -112
- package/src/core.mjs +0 -5497
- package/src/dislop/review-picker.vim +0 -114
- package/src/local-model.mjs +0 -997
- package/src/pattern-engine.mjs +0 -1003
- package/src/pocket-model.mjs +0 -729
- package/src/review-apply.mjs +0 -151
- package/src/review-client.mjs +0 -1073
|
@@ -1,20 +1,50 @@
|
|
|
1
|
-
import { inflateRawSync, inflateSync } from "node:zlib";
|
|
1
|
+
import { deflateRawSync, inflateRawSync, inflateSync } from "node:zlib";
|
|
2
2
|
|
|
3
3
|
const MAX_ZIP_ENTRIES = 3000;
|
|
4
|
-
const MAX_UNCOMPRESSED_BYTES = 120 * 1024 * 1024; // 120 MB zip-bomb
|
|
5
|
-
|
|
6
|
-
const
|
|
4
|
+
const MAX_UNCOMPRESSED_BYTES = 120 * 1024 * 1024; // 120 MB zip-bomb guard
|
|
5
|
+
|
|
6
|
+
const CRC32_TABLE = (() => {
|
|
7
|
+
const table = new Uint32Array(256);
|
|
8
|
+
for (let i = 0; i < 256; i += 1) {
|
|
9
|
+
let c = i;
|
|
10
|
+
for (let k = 0; k < 8; k += 1) {
|
|
11
|
+
c = (c & 1) !== 0 ? (0xedb88320 ^ (c >>> 1)) >>> 0 : c >>> 1;
|
|
12
|
+
}
|
|
13
|
+
table[i] = c >>> 0;
|
|
14
|
+
}
|
|
15
|
+
return table;
|
|
16
|
+
})();
|
|
17
|
+
|
|
18
|
+
export function crc32Buffer(buf) {
|
|
19
|
+
let crc = 0xffffffff;
|
|
20
|
+
for (let i = 0; i < buf.length; i += 1) {
|
|
21
|
+
crc = CRC32_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
|
|
22
|
+
}
|
|
23
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function assertSafeEntryName(name) {
|
|
27
|
+
if (!name || name.includes("\0") || name.startsWith("/") || name.startsWith("\\")) {
|
|
28
|
+
throw new Error(`Unsafe ZIP entry path: ${JSON.stringify(name)}`);
|
|
29
|
+
}
|
|
30
|
+
const parts = name.replace(/\\/g, "/").split("/");
|
|
31
|
+
if (parts.some((p) => p === "..")) {
|
|
32
|
+
throw new Error(`Path traversal detected in ZIP entry: ${JSON.stringify(name)}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
7
35
|
|
|
8
36
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
37
|
+
* Parse all entries in a PKZIP / OOXML archive buffer.
|
|
38
|
+
* Returns ordered entry records including raw compressed bytes and decoded UTF-8 XML strings for `.xml`/`.rels`.
|
|
11
39
|
*/
|
|
12
|
-
export function
|
|
13
|
-
if (buffer.length < 22 || buffer[0] !== 0x50 || buffer[1] !== 0x4b) {
|
|
40
|
+
export function readZipArchive(buffer) {
|
|
41
|
+
if (!Buffer.isBuffer(buffer) || buffer.length < 22 || buffer[0] !== 0x50 || buffer[1] !== 0x4b) {
|
|
14
42
|
throw new Error("Invalid OOXML ZIP header");
|
|
15
43
|
}
|
|
44
|
+
if (buffer[2] === 0x05 && buffer[3] === 0x06 && buffer.readUInt16LE(10) === 0) {
|
|
45
|
+
return { entries: [], xmlEntries: {} };
|
|
46
|
+
}
|
|
16
47
|
|
|
17
|
-
// Locate EOCD signature 0x06054b50 within last 65 KB
|
|
18
48
|
const minOffset = Math.max(0, buffer.length - 65557);
|
|
19
49
|
let eocdOffset = -1;
|
|
20
50
|
for (let i = buffer.length - 22; i >= minOffset; i -= 1) {
|
|
@@ -38,677 +68,264 @@ export function readZipXmlEntries(buffer) {
|
|
|
38
68
|
throw new Error("Truncated ZIP central directory");
|
|
39
69
|
}
|
|
40
70
|
|
|
41
|
-
const entries =
|
|
71
|
+
const entries = [];
|
|
72
|
+
const xmlEntries = {};
|
|
42
73
|
let totalUncompressed = 0;
|
|
43
74
|
let ptr = cdOffset;
|
|
44
75
|
|
|
45
76
|
for (let i = 0; i < totalEntries && ptr + 46 <= cdOffset + cdSize; i += 1) {
|
|
46
|
-
if (buffer.readUInt32LE(ptr) !== 0x02014b50)
|
|
77
|
+
if (buffer.readUInt32LE(ptr) !== 0x02014b50) {
|
|
78
|
+
throw new Error("Corrupted ZIP central directory entry signature");
|
|
79
|
+
}
|
|
80
|
+
const versionNeeded = buffer.readUInt16LE(ptr + 6);
|
|
81
|
+
const flags = buffer.readUInt16LE(ptr + 8);
|
|
47
82
|
const method = buffer.readUInt16LE(ptr + 10);
|
|
83
|
+
const modTime = buffer.readUInt16LE(ptr + 12);
|
|
84
|
+
const modDate = buffer.readUInt16LE(ptr + 14);
|
|
85
|
+
const crc32 = buffer.readUInt32LE(ptr + 16);
|
|
48
86
|
const compSize = buffer.readUInt32LE(ptr + 20);
|
|
49
87
|
const uncompSize = buffer.readUInt32LE(ptr + 24);
|
|
50
88
|
const nameLen = buffer.readUInt16LE(ptr + 28);
|
|
51
89
|
const extraLen = buffer.readUInt16LE(ptr + 30);
|
|
52
90
|
const commentLen = buffer.readUInt16LE(ptr + 32);
|
|
91
|
+
const externalAttrs = buffer.readUInt32LE(ptr + 38);
|
|
53
92
|
const localHeaderOffset = buffer.readUInt32LE(ptr + 42);
|
|
54
93
|
|
|
55
94
|
const name = buffer.subarray(ptr + 46, ptr + 46 + nameLen).toString("utf8");
|
|
95
|
+
assertSafeEntryName(name);
|
|
56
96
|
ptr += 46 + nameLen + extraLen + commentLen;
|
|
57
97
|
|
|
58
|
-
if (
|
|
59
|
-
|
|
60
|
-
totalUncompressed += uncompSize;
|
|
61
|
-
if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) {
|
|
62
|
-
throw new Error("OOXML uncompressed XML payload exceeds 120 MB safety ceiling");
|
|
98
|
+
if ((flags & 0x01) !== 0) {
|
|
99
|
+
throw new Error("Encrypted OOXML archives are not supported");
|
|
63
100
|
}
|
|
64
101
|
|
|
65
102
|
if (localHeaderOffset + 30 > buffer.length || buffer.readUInt32LE(localHeaderOffset) !== 0x04034b50) {
|
|
66
|
-
|
|
103
|
+
throw new Error(`Invalid local file header for ZIP entry '${name}'`);
|
|
67
104
|
}
|
|
68
105
|
const localNameLen = buffer.readUInt16LE(localHeaderOffset + 26);
|
|
69
106
|
const localExtraLen = buffer.readUInt16LE(localHeaderOffset + 28);
|
|
70
107
|
const dataStart = localHeaderOffset + 30 + localNameLen + localExtraLen;
|
|
71
108
|
const dataEnd = dataStart + compSize;
|
|
72
|
-
if (dataEnd > buffer.length)
|
|
73
|
-
|
|
74
|
-
const rawSlice = buffer.subarray(dataStart, dataEnd);
|
|
75
|
-
let outBuf;
|
|
76
|
-
if (method === 0) {
|
|
77
|
-
outBuf = rawSlice;
|
|
78
|
-
} else if (method === 8) {
|
|
79
|
-
outBuf = inflateRawSync(rawSlice, { maxOutputLength: MAX_UNCOMPRESSED_BYTES });
|
|
80
|
-
} else {
|
|
81
|
-
continue;
|
|
109
|
+
if (dataEnd > buffer.length) {
|
|
110
|
+
throw new Error(`Truncated compressed payload for ZIP entry '${name}'`);
|
|
82
111
|
}
|
|
83
|
-
entries[name] = outBuf.toString("utf8");
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
return entries;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// ---------- Shared Color & Math Helpers (100% parity with Python) ----------
|
|
90
|
-
|
|
91
|
-
function rgbToHslNormalized(r, g, b) {
|
|
92
|
-
const rn = r / 255;
|
|
93
|
-
const gn = g / 255;
|
|
94
|
-
const bn = b / 255;
|
|
95
|
-
const max = Math.max(rn, gn, bn);
|
|
96
|
-
const min = Math.min(rn, gn, bn);
|
|
97
|
-
const l = (max + min) / 2;
|
|
98
|
-
if (max === min) return [0, 0, l];
|
|
99
|
-
const d = max - min;
|
|
100
|
-
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
|
101
|
-
let h = 0;
|
|
102
|
-
if (max === rn) h = (gn - bn) / d + (gn < bn ? 6 : 0);
|
|
103
|
-
else if (max === gn) h = (bn - rn) / d + 2;
|
|
104
|
-
else h = (rn - gn) / d + 4;
|
|
105
|
-
return [h * 60, s, l];
|
|
106
|
-
}
|
|
107
112
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const pb = Math.abs(p - b);
|
|
112
|
-
const pc = Math.abs(p - c);
|
|
113
|
-
if (pa <= pb && pa <= pc) return a;
|
|
114
|
-
if (pb <= pc) return b;
|
|
115
|
-
return c;
|
|
116
|
-
}
|
|
113
|
+
const compressedSlice = buffer.subarray(dataStart, dataEnd);
|
|
114
|
+
const isXml = /\.(?:xml|rels)$/i.test(name);
|
|
115
|
+
let text = null;
|
|
117
116
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
function computePixelMetrics(width, height, getRgba) {
|
|
123
|
-
const stepX = Math.max(1, Math.floor(width / 160));
|
|
124
|
-
const stepY = Math.max(1, Math.floor(height / 160));
|
|
125
|
-
const startX = width >= 3 ? 1 : 0;
|
|
126
|
-
const endX = width >= 3 ? width - 1 : width;
|
|
127
|
-
const startY = height >= 3 ? 1 : 0;
|
|
128
|
-
const endY = height >= 3 ? height - 1 : height;
|
|
129
|
-
|
|
130
|
-
let opaquePixels = 0;
|
|
131
|
-
let neonPurpleCount = 0;
|
|
132
|
-
let neonCyanCount = 0;
|
|
133
|
-
let darkBgCount = 0;
|
|
134
|
-
let highSatCount = 0;
|
|
135
|
-
let smoothHighSatCount = 0;
|
|
136
|
-
let neutralCount = 0;
|
|
137
|
-
const quantized = new Set();
|
|
138
|
-
|
|
139
|
-
for (let y = startY; y < endY; y += stepY) {
|
|
140
|
-
for (let x = startX; x < endX; x += stepX) {
|
|
141
|
-
const [r, g, b, a] = getRgba(x, y);
|
|
142
|
-
if (a < 32) continue;
|
|
143
|
-
opaquePixels += 1;
|
|
144
|
-
quantized.add(((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4));
|
|
145
|
-
const [h, s, l] = rgbToHslNormalized(r, g, b);
|
|
146
|
-
if (l <= 0.14) darkBgCount += 1;
|
|
147
|
-
if (s <= 0.12) neutralCount += 1;
|
|
148
|
-
if (s >= 0.40 && l >= 0.15 && l <= 0.85 && h >= 235 && h <= 335) {
|
|
149
|
-
neonPurpleCount += 1;
|
|
117
|
+
if (isXml) {
|
|
118
|
+
totalUncompressed += uncompSize;
|
|
119
|
+
if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) {
|
|
120
|
+
throw new Error("OOXML uncompressed XML payload exceeds 120 MB safety ceiling");
|
|
150
121
|
}
|
|
151
|
-
|
|
152
|
-
|
|
122
|
+
let uncompBuf;
|
|
123
|
+
if (method === 0) {
|
|
124
|
+
uncompBuf = compressedSlice;
|
|
125
|
+
} else if (method === 8) {
|
|
126
|
+
uncompBuf = inflateRawSync(compressedSlice, { maxOutputLength: MAX_UNCOMPRESSED_BYTES });
|
|
127
|
+
} else {
|
|
128
|
+
throw new Error(`Unsupported ZIP compression method ${method} in '${name}'`);
|
|
153
129
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
const right = getRgba(Math.min(width - 1, x + 1), y);
|
|
158
|
-
const up = getRgba(x, Math.max(0, y - 1));
|
|
159
|
-
const down = getRgba(x, Math.min(height - 1, y + 1));
|
|
160
|
-
const diffSum =
|
|
161
|
-
Math.abs(r - left[0]) + Math.abs(g - left[1]) + Math.abs(b - left[2]) +
|
|
162
|
-
Math.abs(r - right[0]) + Math.abs(g - right[1]) + Math.abs(b - right[2]) +
|
|
163
|
-
Math.abs(r - up[0]) + Math.abs(g - up[1]) + Math.abs(b - up[2]) +
|
|
164
|
-
Math.abs(r - down[0]) + Math.abs(g - down[1]) + Math.abs(b - down[2]);
|
|
165
|
-
if (diffSum / 4 < 18) {
|
|
166
|
-
smoothHighSatCount += 1;
|
|
167
|
-
}
|
|
130
|
+
text = uncompBuf.toString("utf8");
|
|
131
|
+
if (/<!DOCTYPE\b/i.test(text) || /<!ENTITY\b/i.test(text)) {
|
|
132
|
+
throw new Error(`Blocked XML DOCTYPE/ENTITY declaration in '${name}'`);
|
|
168
133
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
134
|
+
xmlEntries[name] = text;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
entries.push({
|
|
138
|
+
name,
|
|
139
|
+
versionNeeded,
|
|
140
|
+
flags: flags & ~0x08, // normalize away streaming data-descriptor bit on repack
|
|
141
|
+
method,
|
|
142
|
+
modTime,
|
|
143
|
+
modDate,
|
|
144
|
+
crc32,
|
|
145
|
+
compSize,
|
|
146
|
+
uncompSize,
|
|
147
|
+
externalAttrs,
|
|
148
|
+
compressedData: compressedSlice,
|
|
149
|
+
text,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return { entries, xmlEntries };
|
|
183
154
|
}
|
|
184
155
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
const
|
|
190
|
-
const
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
for (let y = 0; y < height; y += 1) {
|
|
211
|
-
const rowIn = y * (1 + stride);
|
|
212
|
-
const filterType = raw[rowIn];
|
|
213
|
-
const rowOut = y * stride;
|
|
214
|
-
const prevOut = (y - 1) * stride;
|
|
215
|
-
for (let x = 0; x < stride; x += 1) {
|
|
216
|
-
const filt = raw[rowIn + 1 + x];
|
|
217
|
-
const a = x >= bpp ? pixels[rowOut + x - bpp] : 0;
|
|
218
|
-
const b = y > 0 ? pixels[prevOut + x] : 0;
|
|
219
|
-
const c = y > 0 && x >= bpp ? pixels[prevOut + x - bpp] : 0;
|
|
220
|
-
let val = filt;
|
|
221
|
-
if (filterType === 1) val = (filt + a) & 0xff;
|
|
222
|
-
else if (filterType === 2) val = (filt + b) & 0xff;
|
|
223
|
-
else if (filterType === 3) val = (filt + ((a + b) >> 1)) & 0xff;
|
|
224
|
-
else if (filterType === 4) val = (filt + paethPredictor(a, b, c)) & 0xff;
|
|
225
|
-
pixels[rowOut + x] = val;
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
function getRgba(x, y) {
|
|
230
|
-
const off = y * stride + x * bpp;
|
|
231
|
-
if (colorType === 2) return [pixels[off], pixels[off + 1], pixels[off + 2], 255];
|
|
232
|
-
if (colorType === 6) return [pixels[off], pixels[off + 1], pixels[off + 2], pixels[off + 3]];
|
|
233
|
-
if (colorType === 0) {
|
|
234
|
-
const g = pixels[off];
|
|
235
|
-
return [g, g, g, 255];
|
|
236
|
-
}
|
|
237
|
-
if (colorType === 4) {
|
|
238
|
-
const g = pixels[off];
|
|
239
|
-
return [g, g, g, pixels[off + 1]];
|
|
240
|
-
}
|
|
241
|
-
const idx = pixels[off];
|
|
242
|
-
const pal = palette[idx] || [0, 0, 0];
|
|
243
|
-
return [pal[0], pal[1], pal[2], 255];
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
return computePixelMetrics(width, height, getRgba);
|
|
156
|
+
/**
|
|
157
|
+
* Build a PKZIP archive buffer from a `{ [entryName]: Buffer | string }` map (used by tests & repack).
|
|
158
|
+
*/
|
|
159
|
+
export function buildZipArchive(entryMap) {
|
|
160
|
+
const names = Object.keys(entryMap);
|
|
161
|
+
const records = names.map((name) => {
|
|
162
|
+
assertSafeEntryName(name);
|
|
163
|
+
const raw = Buffer.isBuffer(entryMap[name]) ? entryMap[name] : Buffer.from(String(entryMap[name]), "utf8");
|
|
164
|
+
const compressed = raw.length > 0 ? deflateRawSync(raw) : Buffer.alloc(0);
|
|
165
|
+
const method = raw.length > 0 ? 8 : 0;
|
|
166
|
+
return {
|
|
167
|
+
name,
|
|
168
|
+
versionNeeded: 20,
|
|
169
|
+
flags: 0,
|
|
170
|
+
method,
|
|
171
|
+
modTime: 0,
|
|
172
|
+
modDate: 0x21,
|
|
173
|
+
crc32: crc32Buffer(raw),
|
|
174
|
+
compSize: compressed.length,
|
|
175
|
+
uncompSize: raw.length,
|
|
176
|
+
externalAttrs: 0,
|
|
177
|
+
compressedData: compressed,
|
|
178
|
+
};
|
|
179
|
+
});
|
|
180
|
+
return serializeZipRecords(records);
|
|
247
181
|
}
|
|
248
182
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
const
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
if (bitCount < codeSize) return -1;
|
|
275
|
-
const code = bitBuf & ((1 << codeSize) - 1);
|
|
276
|
-
bitBuf >>= codeSize;
|
|
277
|
-
bitCount -= codeSize;
|
|
278
|
-
return code;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
function resetTable() {
|
|
282
|
-
for (let i = 0; i < clearCode; i += 1) {
|
|
283
|
-
prefixes[i] = -1;
|
|
284
|
-
suffixes[i] = i;
|
|
285
|
-
firstChars[i] = i;
|
|
286
|
-
}
|
|
287
|
-
codeSize = minCodeSize + 1;
|
|
288
|
-
nextCode = eoiCode + 1;
|
|
289
|
-
prevCode = -1;
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
resetTable();
|
|
293
|
-
|
|
294
|
-
while (outPos < expectedLen) {
|
|
295
|
-
const code = readCode();
|
|
296
|
-
if (code < 0 || code === eoiCode) break;
|
|
297
|
-
if (code === clearCode) {
|
|
298
|
-
resetTable();
|
|
299
|
-
continue;
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
let inCode = code;
|
|
303
|
-
let stackLen = 0;
|
|
304
|
-
if (code === nextCode) {
|
|
305
|
-
if (prevCode < 0) break;
|
|
306
|
-
stack[stackLen++] = firstChars[prevCode];
|
|
307
|
-
inCode = prevCode;
|
|
308
|
-
} else if (code > nextCode) {
|
|
309
|
-
break;
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
let walk = inCode;
|
|
313
|
-
while (walk >= clearCode && stackLen < 4096) {
|
|
314
|
-
stack[stackLen++] = suffixes[walk];
|
|
315
|
-
walk = prefixes[walk];
|
|
316
|
-
}
|
|
317
|
-
if (walk < 0 || stackLen >= 4096) break;
|
|
318
|
-
const baseChar = firstChars[walk];
|
|
319
|
-
stack[stackLen++] = baseChar;
|
|
320
|
-
|
|
321
|
-
for (let i = stackLen - 1; i >= 0 && outPos < expectedLen; i -= 1) {
|
|
322
|
-
out[outPos++] = stack[i];
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
if (prevCode >= 0 && nextCode < 4096) {
|
|
326
|
-
prefixes[nextCode] = prevCode;
|
|
327
|
-
suffixes[nextCode] = baseChar;
|
|
328
|
-
firstChars[nextCode] = firstChars[prevCode];
|
|
329
|
-
nextCode += 1;
|
|
330
|
-
if (nextCode === (1 << codeSize) && codeSize < 12) {
|
|
331
|
-
codeSize += 1;
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
prevCode = code;
|
|
335
|
-
}
|
|
183
|
+
/**
|
|
184
|
+
* Repack an existing ZIP archive, replacing only modified UTF-8 XML entries while preserving
|
|
185
|
+
* all unmodified binary entries byte-for-byte.
|
|
186
|
+
*/
|
|
187
|
+
export function repackZipArchive(originalBuffer, updatedXmlMap) {
|
|
188
|
+
const { entries } = readZipArchive(originalBuffer);
|
|
189
|
+
const records = entries.map((entry) => {
|
|
190
|
+
if (!Object.prototype.hasOwnProperty.call(updatedXmlMap, entry.name)) {
|
|
191
|
+
return entry;
|
|
192
|
+
}
|
|
193
|
+
const raw = Buffer.from(String(updatedXmlMap[entry.name]), "utf8");
|
|
194
|
+
const compressed = raw.length > 0 ? deflateRawSync(raw) : Buffer.alloc(0);
|
|
195
|
+
return {
|
|
196
|
+
...entry,
|
|
197
|
+
versionNeeded: 20,
|
|
198
|
+
flags: entry.flags & ~0x08,
|
|
199
|
+
method: raw.length > 0 ? 8 : 0,
|
|
200
|
+
crc32: crc32Buffer(raw),
|
|
201
|
+
compSize: compressed.length,
|
|
202
|
+
uncompSize: raw.length,
|
|
203
|
+
compressedData: compressed,
|
|
204
|
+
};
|
|
205
|
+
});
|
|
206
|
+
return serializeZipRecords(records);
|
|
207
|
+
}
|
|
336
208
|
|
|
337
|
-
|
|
209
|
+
function serializeZipRecords(records) {
|
|
210
|
+
const localChunks = [];
|
|
211
|
+
const cdChunks = [];
|
|
212
|
+
let offset = 0;
|
|
213
|
+
|
|
214
|
+
for (const rec of records) {
|
|
215
|
+
const nameBuf = Buffer.from(rec.name, "utf8");
|
|
216
|
+
const localHeader = Buffer.alloc(30);
|
|
217
|
+
localHeader.writeUInt32LE(0x04034b50, 0);
|
|
218
|
+
localHeader.writeUInt16LE(rec.versionNeeded || 20, 4);
|
|
219
|
+
localHeader.writeUInt16LE(rec.flags || 0, 6);
|
|
220
|
+
localHeader.writeUInt16LE(rec.method, 8);
|
|
221
|
+
localHeader.writeUInt16LE(rec.modTime || 0, 10);
|
|
222
|
+
localHeader.writeUInt16LE(rec.modDate || 0x21, 12);
|
|
223
|
+
localHeader.writeUInt32LE(rec.crc32 >>> 0, 14);
|
|
224
|
+
localHeader.writeUInt32LE(rec.compSize >>> 0, 18);
|
|
225
|
+
localHeader.writeUInt32LE(rec.uncompSize >>> 0, 22);
|
|
226
|
+
localHeader.writeUInt16LE(nameBuf.length, 26);
|
|
227
|
+
localHeader.writeUInt16LE(0, 28);
|
|
228
|
+
|
|
229
|
+
const localOffset = offset;
|
|
230
|
+
localChunks.push(localHeader, nameBuf, rec.compressedData);
|
|
231
|
+
offset += localHeader.length + nameBuf.length + rec.compressedData.length;
|
|
232
|
+
|
|
233
|
+
const cdHeader = Buffer.alloc(46);
|
|
234
|
+
cdHeader.writeUInt32LE(0x02014b50, 0);
|
|
235
|
+
cdHeader.writeUInt16LE(20, 4);
|
|
236
|
+
cdHeader.writeUInt16LE(rec.versionNeeded || 20, 6);
|
|
237
|
+
cdHeader.writeUInt16LE(rec.flags || 0, 8);
|
|
238
|
+
cdHeader.writeUInt16LE(rec.method, 10);
|
|
239
|
+
cdHeader.writeUInt16LE(rec.modTime || 0, 12);
|
|
240
|
+
cdHeader.writeUInt16LE(rec.modDate || 0x21, 14);
|
|
241
|
+
cdHeader.writeUInt32LE(rec.crc32 >>> 0, 16);
|
|
242
|
+
cdHeader.writeUInt32LE(rec.compSize >>> 0, 20);
|
|
243
|
+
cdHeader.writeUInt32LE(rec.uncompSize >>> 0, 24);
|
|
244
|
+
cdHeader.writeUInt16LE(nameBuf.length, 28);
|
|
245
|
+
cdHeader.writeUInt16LE(0, 30);
|
|
246
|
+
cdHeader.writeUInt16LE(0, 32);
|
|
247
|
+
cdHeader.writeUInt16LE(0, 34);
|
|
248
|
+
cdHeader.writeUInt16LE(0, 36);
|
|
249
|
+
cdHeader.writeUInt32LE(rec.externalAttrs || 0, 38);
|
|
250
|
+
cdHeader.writeUInt32LE(localOffset >>> 0, 42);
|
|
251
|
+
|
|
252
|
+
cdChunks.push(cdHeader, nameBuf);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const cdBuf = Buffer.concat(cdChunks);
|
|
256
|
+
const eocd = Buffer.alloc(22);
|
|
257
|
+
eocd.writeUInt32LE(0x06054b50, 0);
|
|
258
|
+
eocd.writeUInt16LE(0, 4);
|
|
259
|
+
eocd.writeUInt16LE(0, 6);
|
|
260
|
+
eocd.writeUInt16LE(records.length, 8);
|
|
261
|
+
eocd.writeUInt16LE(records.length, 10);
|
|
262
|
+
eocd.writeUInt32LE(cdBuf.length, 12);
|
|
263
|
+
eocd.writeUInt32LE(offset >>> 0, 16);
|
|
264
|
+
eocd.writeUInt16LE(0, 20);
|
|
265
|
+
|
|
266
|
+
return Buffer.concat([...localChunks, cdBuf, eocd]);
|
|
338
267
|
}
|
|
339
268
|
|
|
340
269
|
/**
|
|
341
|
-
*
|
|
342
|
-
* Extracts container dimensions, embedded workflow/provenance metadata, and PNG pixel heuristics.
|
|
270
|
+
* Extract lightweight metadata from PNG/JPEG/WebP/GIF images without external dependencies.
|
|
343
271
|
*/
|
|
344
|
-
export function
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
let width = 0;
|
|
359
|
-
let height = 0;
|
|
360
|
-
let bitDepth = 0;
|
|
361
|
-
let colorType = 0;
|
|
362
|
-
let interlace = 0;
|
|
363
|
-
let hasIhdr = false;
|
|
364
|
-
let palette = null;
|
|
365
|
-
const idatChunks = [];
|
|
366
|
-
let idatBytes = 0;
|
|
367
|
-
|
|
368
|
-
while (offset + 12 <= buffer.length) {
|
|
369
|
-
const length = buffer.readUInt32BE(offset);
|
|
370
|
-
const type = buffer.subarray(offset + 4, offset + 8).toString("latin1");
|
|
371
|
-
const dataStart = offset + 8;
|
|
372
|
-
const dataEnd = dataStart + length;
|
|
272
|
+
export function inspectImageBuffer(buffer, format) {
|
|
273
|
+
const metaTexts = [];
|
|
274
|
+
let width = 0;
|
|
275
|
+
let height = 0;
|
|
276
|
+
|
|
277
|
+
if (format === "png" && buffer.length >= 24 && buffer.readUInt32BE(0) === 0x89504e47) {
|
|
278
|
+
width = buffer.readUInt32BE(16);
|
|
279
|
+
height = buffer.readUInt32BE(20);
|
|
280
|
+
let pos = 8;
|
|
281
|
+
while (pos + 12 <= buffer.length) {
|
|
282
|
+
const len = buffer.readUInt32BE(pos);
|
|
283
|
+
const type = buffer.subarray(pos + 4, pos + 8).toString("latin1");
|
|
284
|
+
const dataStart = pos + 8;
|
|
285
|
+
const dataEnd = dataStart + len;
|
|
373
286
|
if (dataEnd + 4 > buffer.length) break;
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
if (type === "IHDR" && data.length >= 13) {
|
|
378
|
-
hasIhdr = true;
|
|
379
|
-
width = data.readUInt32BE(0);
|
|
380
|
-
height = data.readUInt32BE(4);
|
|
381
|
-
bitDepth = data[8];
|
|
382
|
-
colorType = data[9];
|
|
383
|
-
interlace = data[12];
|
|
384
|
-
} else if (type === "PLTE") {
|
|
385
|
-
palette = [];
|
|
386
|
-
for (let i = 0; i + 2 < data.length; i += 3) {
|
|
387
|
-
palette.push([data[i], data[i + 1], data[i + 2]]);
|
|
388
|
-
}
|
|
389
|
-
} else if (type === "tEXt") {
|
|
390
|
-
const nul = data.indexOf(0);
|
|
391
|
-
if (nul >= 0) {
|
|
392
|
-
const key = data.subarray(0, nul).toString("latin1");
|
|
393
|
-
const value = data.subarray(nul + 1).toString("latin1");
|
|
394
|
-
metadataTexts.push({ key, value });
|
|
395
|
-
}
|
|
287
|
+
if (type === "tEXt" || type === "iTXt") {
|
|
288
|
+
metaTexts.push(buffer.subarray(dataStart, dataEnd).toString("utf8"));
|
|
396
289
|
} else if (type === "zTXt") {
|
|
397
|
-
const nul =
|
|
398
|
-
if (nul
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
metadataTexts.push({ key, value });
|
|
405
|
-
} catch {}
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
} else if (type === "iTXt") {
|
|
409
|
-
const nul1 = data.indexOf(0);
|
|
410
|
-
if (nul1 >= 0 && nul1 + 3 <= data.length) {
|
|
411
|
-
const key = data.subarray(0, nul1).toString("latin1");
|
|
412
|
-
const compFlag = data[nul1 + 1];
|
|
413
|
-
const compMethod = data[nul1 + 2];
|
|
414
|
-
const nul2 = data.indexOf(0, nul1 + 3);
|
|
415
|
-
const nul3 = nul2 >= 0 ? data.indexOf(0, nul2 + 1) : -1;
|
|
416
|
-
if (nul3 >= 0) {
|
|
417
|
-
const payload = data.subarray(nul3 + 1);
|
|
418
|
-
try {
|
|
419
|
-
const value =
|
|
420
|
-
compFlag === 1 && compMethod === 0
|
|
421
|
-
? inflateSync(payload, { maxOutputLength: 4 * 1024 * 1024 }).toString("utf8")
|
|
422
|
-
: payload.toString("utf8");
|
|
423
|
-
metadataTexts.push({ key, value });
|
|
424
|
-
} catch {}
|
|
290
|
+
const nul = buffer.indexOf(0, dataStart);
|
|
291
|
+
if (nul !== -1 && nul + 2 < dataEnd) {
|
|
292
|
+
try {
|
|
293
|
+
const inf = inflateSync(buffer.subarray(nul + 2, dataEnd), { maxOutputLength: 1024 * 1024 });
|
|
294
|
+
metaTexts.push(inf.toString("utf8"));
|
|
295
|
+
} catch {
|
|
296
|
+
// ignore malformed zTXt
|
|
425
297
|
}
|
|
426
298
|
}
|
|
427
|
-
} else if (type === "eXIf") {
|
|
428
|
-
metadataTexts.push({ key: "exif", value: data.toString("latin1").replace(/\x00+/g, " ") });
|
|
429
299
|
} else if (type === "caBX") {
|
|
430
|
-
|
|
431
|
-
metadataTexts.push({ key: "c2pa", value: data.toString("latin1").replace(/\x00+/g, " ") });
|
|
432
|
-
} else if (type === "IDAT") {
|
|
433
|
-
idatBytes += data.length;
|
|
434
|
-
if (idatBytes <= 24 * 1024 * 1024) {
|
|
435
|
-
idatChunks.push(data);
|
|
436
|
-
}
|
|
437
|
-
} else if (type === "IEND") {
|
|
438
|
-
break;
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
if (!hasIhdr || width <= 0 || height <= 0) {
|
|
443
|
-
throw new Error("Invalid PNG missing valid IHDR chunk");
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
for (const m of metadataTexts) {
|
|
447
|
-
if (/(?:c2pa|trainedAlgorithmicMedia|jumbf)/i.test(`${m.key} ${m.value}`)) {
|
|
448
|
-
hasC2pa = true;
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
const pixelMetrics = decodePngScanlinesAndMetrics(
|
|
453
|
-
idatChunks,
|
|
454
|
-
width,
|
|
455
|
-
height,
|
|
456
|
-
bitDepth,
|
|
457
|
-
colorType,
|
|
458
|
-
interlace,
|
|
459
|
-
palette
|
|
460
|
-
);
|
|
461
|
-
|
|
462
|
-
return { format: "png", width, height, metadataTexts, hasC2pa, pixelMetrics };
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
// 2. JPEG
|
|
466
|
-
if (buffer[0] === 0xff && buffer[1] === 0xd8) {
|
|
467
|
-
let pos = 2;
|
|
468
|
-
let width = 0;
|
|
469
|
-
let height = 0;
|
|
470
|
-
while (pos < buffer.length) {
|
|
471
|
-
while (pos < buffer.length && buffer[pos] === 0xff) pos += 1;
|
|
472
|
-
if (pos >= buffer.length) break;
|
|
473
|
-
const marker = buffer[pos];
|
|
474
|
-
pos += 1;
|
|
475
|
-
if (marker === 0xd9 || marker === 0xda) break;
|
|
476
|
-
if (marker === 0x00 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
|
|
477
|
-
if (pos + 2 > buffer.length) break;
|
|
478
|
-
const segLen = buffer.readUInt16BE(pos);
|
|
479
|
-
if (segLen < 2 || pos + segLen > buffer.length) break;
|
|
480
|
-
const payload = buffer.subarray(pos + 2, pos + segLen);
|
|
481
|
-
pos += segLen;
|
|
482
|
-
|
|
483
|
-
if ((marker === 0xc0 || marker === 0xc1 || marker === 0xc2) && payload.length >= 5) {
|
|
484
|
-
height = payload.readUInt16BE(1);
|
|
485
|
-
width = payload.readUInt16BE(3);
|
|
486
|
-
} else if (marker === 0xe1) {
|
|
487
|
-
const s = payload.toString("latin1");
|
|
488
|
-
if (s.startsWith("http://ns.adobe.com/xap/1.0/\x00")) {
|
|
489
|
-
metadataTexts.push({ key: "xmp", value: payload.subarray(29).toString("utf8") });
|
|
490
|
-
} else if (s.startsWith("Exif\x00\x00")) {
|
|
491
|
-
metadataTexts.push({ key: "exif", value: s.slice(6).replace(/\x00+/g, " ") });
|
|
492
|
-
}
|
|
493
|
-
} else if (marker === 0xeb) {
|
|
494
|
-
const s = payload.toString("latin1").replace(/\x00+/g, " ");
|
|
495
|
-
if (/c2pa|jumb/i.test(s)) {
|
|
496
|
-
hasC2pa = true;
|
|
497
|
-
metadataTexts.push({ key: "c2pa", value: s });
|
|
498
|
-
}
|
|
499
|
-
} else if (marker === 0xfe) {
|
|
500
|
-
metadataTexts.push({ key: "comment", value: payload.toString("utf8") });
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
for (const m of metadataTexts) {
|
|
505
|
-
if (/(?:c2pa|trainedAlgorithmicMedia|jumbf)/i.test(`${m.key} ${m.value}`)) {
|
|
506
|
-
hasC2pa = true;
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
return { format: "jpeg", width, height, metadataTexts, hasC2pa, pixelMetrics: null };
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
// 3. WebP (RIFF....WEBP)
|
|
513
|
-
if (
|
|
514
|
-
buffer.subarray(0, 4).toString("ascii") === "RIFF" &&
|
|
515
|
-
buffer.subarray(8, 12).toString("ascii") === "WEBP"
|
|
516
|
-
) {
|
|
517
|
-
let pos = 12;
|
|
518
|
-
let width = 0;
|
|
519
|
-
let height = 0;
|
|
520
|
-
while (pos + 8 <= buffer.length) {
|
|
521
|
-
const fourcc = buffer.subarray(pos, pos + 4).toString("ascii");
|
|
522
|
-
const size = buffer.readUInt32LE(pos + 4);
|
|
523
|
-
const dataStart = pos + 8;
|
|
524
|
-
if (dataStart + size > buffer.length) break;
|
|
525
|
-
const data = buffer.subarray(dataStart, dataStart + size);
|
|
526
|
-
pos = dataStart + size + (size % 2);
|
|
527
|
-
|
|
528
|
-
if (fourcc === "VP8 " && data.length >= 10 && data[3] === 0x9d && data[4] === 0x01 && data[5] === 0x2a) {
|
|
529
|
-
width = data.readUInt16LE(6) & 0x3fff;
|
|
530
|
-
height = data.readUInt16LE(8) & 0x3fff;
|
|
531
|
-
} else if (fourcc === "VP8L" && data.length >= 5 && data[0] === 0x2f) {
|
|
532
|
-
const bits = data.readUInt32LE(1);
|
|
533
|
-
width = (bits & 0x3fff) + 1;
|
|
534
|
-
height = ((bits >> 14) & 0x3fff) + 1;
|
|
535
|
-
} else if (fourcc === "VP8X" && data.length >= 10) {
|
|
536
|
-
width = (data[4] | (data[5] << 8) | (data[6] << 16)) + 1;
|
|
537
|
-
height = (data[7] | (data[8] << 8) | (data[9] << 16)) + 1;
|
|
538
|
-
} else if (fourcc === "EXIF") {
|
|
539
|
-
metadataTexts.push({ key: "exif", value: data.toString("latin1").replace(/\x00+/g, " ") });
|
|
540
|
-
} else if (fourcc === "XMP ") {
|
|
541
|
-
metadataTexts.push({ key: "xmp", value: data.toString("utf8") });
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
if (width <= 0 || height <= 0) {
|
|
546
|
-
throw new Error("Invalid WebP missing dimension chunk");
|
|
547
|
-
}
|
|
548
|
-
for (const m of metadataTexts) {
|
|
549
|
-
if (/(?:c2pa|trainedAlgorithmicMedia|jumbf)/i.test(`${m.key} ${m.value}`)) {
|
|
550
|
-
hasC2pa = true;
|
|
300
|
+
metaTexts.push("c2pa");
|
|
551
301
|
}
|
|
302
|
+
pos = dataEnd + 4;
|
|
303
|
+
if (type === "IEND") break;
|
|
552
304
|
}
|
|
553
|
-
|
|
305
|
+
} else if (format === "gif" && buffer.length >= 10 && buffer.subarray(0, 3).toString("ascii") === "GIF") {
|
|
306
|
+
width = buffer.readUInt16LE(6);
|
|
307
|
+
height = buffer.readUInt16LE(8);
|
|
308
|
+
} else {
|
|
309
|
+
const asciiScan = buffer.subarray(0, Math.min(buffer.length, 262144)).toString("latin1");
|
|
310
|
+
metaTexts.push(asciiScan);
|
|
554
311
|
}
|
|
555
312
|
|
|
556
|
-
|
|
557
|
-
const
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
throw new Error("Invalid GIF missing valid screen dimensions");
|
|
563
|
-
}
|
|
564
|
-
const packed = buffer[10];
|
|
565
|
-
const hasGct = (packed & 0x80) !== 0;
|
|
566
|
-
const gctSize = hasGct ? 1 << ((packed & 0x07) + 1) : 0;
|
|
567
|
-
let pos = 13;
|
|
568
|
-
let gct = null;
|
|
569
|
-
if (hasGct) {
|
|
570
|
-
if (pos + gctSize * 3 > buffer.length) {
|
|
571
|
-
throw new Error("Truncated GIF global color table");
|
|
572
|
-
}
|
|
573
|
-
gct = [];
|
|
574
|
-
for (let i = 0; i < gctSize; i += 1) {
|
|
575
|
-
gct.push([buffer[pos + i * 3], buffer[pos + i * 3 + 1], buffer[pos + i * 3 + 2]]);
|
|
576
|
-
}
|
|
577
|
-
pos += gctSize * 3;
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
let transparentIdx = -1;
|
|
581
|
-
let frame0Decoded = false;
|
|
582
|
-
let pixelMetrics = null;
|
|
583
|
-
|
|
584
|
-
while (pos < buffer.length) {
|
|
585
|
-
const blockId = buffer[pos++];
|
|
586
|
-
if (blockId === 0x3b) break; // Trailer
|
|
587
|
-
if (blockId === 0x21) {
|
|
588
|
-
if (pos >= buffer.length) break;
|
|
589
|
-
const label = buffer[pos++];
|
|
590
|
-
const chunks = [];
|
|
591
|
-
while (pos < buffer.length) {
|
|
592
|
-
const sz = buffer[pos++];
|
|
593
|
-
if (sz === 0) break;
|
|
594
|
-
const end = Math.min(buffer.length, pos + sz);
|
|
595
|
-
chunks.push(buffer.subarray(pos, end));
|
|
596
|
-
pos = end;
|
|
597
|
-
}
|
|
598
|
-
const payload = chunks.length > 0 ? Buffer.concat(chunks) : Buffer.alloc(0);
|
|
599
|
-
if (label === 0xf9 && payload.length >= 4 && !frame0Decoded) {
|
|
600
|
-
transparentIdx = (payload[0] & 0x01) !== 0 ? payload[3] : -1;
|
|
601
|
-
} else if (label === 0xfe && payload.length > 0) {
|
|
602
|
-
metadataTexts.push({ key: "comment", value: payload.toString("utf8") });
|
|
603
|
-
} else if (label === 0xff && payload.length >= 11) {
|
|
604
|
-
const appId = payload.subarray(0, 11).toString("latin1");
|
|
605
|
-
if (appId !== "NETSCAPE2.0" && appId !== "ANIMEXTS1.0") {
|
|
606
|
-
const text = payload.subarray(11).toString("utf8").replace(/\x00+/g, " ").trim();
|
|
607
|
-
if (text) {
|
|
608
|
-
const key = /xmp/i.test(appId) ? "xmp" : /c2pa|jumb/i.test(appId + text) ? "c2pa" : "app";
|
|
609
|
-
metadataTexts.push({ key, value: text });
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
} else if (blockId === 0x2c) {
|
|
614
|
-
if (pos + 9 > buffer.length) break;
|
|
615
|
-
const left = buffer.readUInt16LE(pos);
|
|
616
|
-
const top = buffer.readUInt16LE(pos + 2);
|
|
617
|
-
const imgW = buffer.readUInt16LE(pos + 4);
|
|
618
|
-
const imgH = buffer.readUInt16LE(pos + 6);
|
|
619
|
-
const imgPacked = buffer[pos + 8];
|
|
620
|
-
pos += 9;
|
|
621
|
-
const hasLct = (imgPacked & 0x80) !== 0;
|
|
622
|
-
const interlaced = (imgPacked & 0x40) !== 0;
|
|
623
|
-
const lctSize = hasLct ? 1 << ((imgPacked & 0x07) + 1) : 0;
|
|
624
|
-
let palette = gct;
|
|
625
|
-
if (hasLct) {
|
|
626
|
-
if (pos + lctSize * 3 > buffer.length) break;
|
|
627
|
-
palette = [];
|
|
628
|
-
for (let i = 0; i < lctSize; i += 1) {
|
|
629
|
-
palette.push([buffer[pos + i * 3], buffer[pos + i * 3 + 1], buffer[pos + i * 3 + 2]]);
|
|
630
|
-
}
|
|
631
|
-
pos += lctSize * 3;
|
|
632
|
-
}
|
|
633
|
-
if (pos >= buffer.length) break;
|
|
634
|
-
const minCodeSize = buffer[pos++];
|
|
635
|
-
const dataChunks = [];
|
|
636
|
-
while (pos < buffer.length) {
|
|
637
|
-
const sz = buffer[pos++];
|
|
638
|
-
if (sz === 0) break;
|
|
639
|
-
const end = Math.min(buffer.length, pos + sz);
|
|
640
|
-
if (!frame0Decoded) dataChunks.push(buffer.subarray(pos, end));
|
|
641
|
-
pos = end;
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
if (!frame0Decoded) {
|
|
645
|
-
frame0Decoded = true;
|
|
646
|
-
if (palette && imgW > 0 && imgH > 0 && width * height <= MAX_PNG_PIXELS) {
|
|
647
|
-
const lzwBytes = Buffer.concat(dataChunks);
|
|
648
|
-
const indices = decodeGifLzw(lzwBytes, minCodeSize, imgW * imgH);
|
|
649
|
-
if (indices) {
|
|
650
|
-
const rowMap = new Int32Array(imgH);
|
|
651
|
-
if (interlaced) {
|
|
652
|
-
let srcRow = 0;
|
|
653
|
-
for (const [start, step] of [[0, 8], [4, 8], [2, 4], [1, 2]]) {
|
|
654
|
-
for (let y = start; y < imgH; y += step) {
|
|
655
|
-
rowMap[y] = srcRow++;
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
} else {
|
|
659
|
-
for (let y = 0; y < imgH; y += 1) rowMap[y] = y;
|
|
660
|
-
}
|
|
661
|
-
const rgba = new Uint8Array(width * height * 4);
|
|
662
|
-
const bgRgb = gct && gct[0] ? gct[0] : [0, 0, 0];
|
|
663
|
-
if (transparentIdx === -1) {
|
|
664
|
-
for (let i = 0; i < width * height; i += 1) {
|
|
665
|
-
rgba[i * 4] = bgRgb[0];
|
|
666
|
-
rgba[i * 4 + 1] = bgRgb[1];
|
|
667
|
-
rgba[i * 4 + 2] = bgRgb[2];
|
|
668
|
-
rgba[i * 4 + 3] = 255;
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
for (let iy = 0; iy < imgH; iy += 1) {
|
|
672
|
-
const cy = top + iy;
|
|
673
|
-
if (cy < 0 || cy >= height) continue;
|
|
674
|
-
const srcOff = rowMap[iy] * imgW;
|
|
675
|
-
for (let ix = 0; ix < imgW; ix += 1) {
|
|
676
|
-
const cx = left + ix;
|
|
677
|
-
if (cx < 0 || cx >= width) continue;
|
|
678
|
-
const cIdx = indices[srcOff + ix];
|
|
679
|
-
if (cIdx === transparentIdx) continue;
|
|
680
|
-
const rgb = palette[cIdx] || [0, 0, 0];
|
|
681
|
-
const dst = (cy * width + cx) * 4;
|
|
682
|
-
rgba[dst] = rgb[0];
|
|
683
|
-
rgba[dst + 1] = rgb[1];
|
|
684
|
-
rgba[dst + 2] = rgb[2];
|
|
685
|
-
rgba[dst + 3] = 255;
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
pixelMetrics = computePixelMetrics(width, height, (x, y) => {
|
|
689
|
-
const off = (y * width + x) * 4;
|
|
690
|
-
return [rgba[off], rgba[off + 1], rgba[off + 2], rgba[off + 3]];
|
|
691
|
-
});
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
}
|
|
695
|
-
} else {
|
|
696
|
-
break;
|
|
697
|
-
}
|
|
698
|
-
}
|
|
313
|
+
const joined = metaTexts.join("\n");
|
|
314
|
+
const aiWorkflowResidue =
|
|
315
|
+
/\bSteps:\s*\d+,\s*Sampler:/i.test(joined) ||
|
|
316
|
+
/"class_type"\s*:\s*"KSampler"/i.test(joined) ||
|
|
317
|
+
/\bComfyUI\b/i.test(joined);
|
|
318
|
+
const c2paPresent = /\bc2pa\b|urn:c2pa/i.test(joined);
|
|
699
319
|
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
}
|
|
707
|
-
|
|
708
|
-
throw new Error("Unsupported or corrupted image header (expected PNG, JPEG, WebP, or GIF)");
|
|
320
|
+
return {
|
|
321
|
+
width,
|
|
322
|
+
height,
|
|
323
|
+
aiWorkflowResidue,
|
|
324
|
+
c2paPresent,
|
|
325
|
+
};
|
|
709
326
|
}
|
|
710
327
|
|
|
711
|
-
|
|
328
|
+
const MAX_STREAM_UNCOMPRESSED_BYTES = 16 * 1024 * 1024;
|
|
712
329
|
|
|
713
330
|
function decodeUtf16BeHex(hexRaw) {
|
|
714
331
|
const clean = hexRaw.replace(/[^0-9a-fA-F]/g, "");
|
|
@@ -723,17 +340,14 @@ function decodeUtf16BeHex(hexRaw) {
|
|
|
723
340
|
if (i + 7 < padded.length) {
|
|
724
341
|
const low = parseInt(padded.slice(i + 4, i + 8), 16);
|
|
725
342
|
if (low >= 0xdc00 && low <= 0xdfff) {
|
|
726
|
-
|
|
727
|
-
out += String.fromCodePoint(cp);
|
|
343
|
+
out += String.fromCodePoint(0x10000 + (((code - 0xd800) << 10) | (low - 0xdc00)));
|
|
728
344
|
i += 4;
|
|
729
345
|
continue;
|
|
730
346
|
}
|
|
731
347
|
}
|
|
732
|
-
continue;
|
|
733
|
-
}
|
|
734
|
-
if (code >= 0xdc00 && code <= 0xdfff) {
|
|
735
|
-
continue; // Drop unpaired low surrogate
|
|
348
|
+
continue;
|
|
736
349
|
}
|
|
350
|
+
if (code >= 0xdc00 && code <= 0xdfff) continue;
|
|
737
351
|
out += String.fromCharCode(code);
|
|
738
352
|
}
|
|
739
353
|
return out;
|
|
@@ -804,7 +418,7 @@ const AGL_GLYPH_MAP = {
|
|
|
804
418
|
three: "3", four: "4", five: "5", six: "6", seven: "7", eight: "8", nine: "9",
|
|
805
419
|
colon: ":", semicolon: ";", less: "<", equal: "=", greater: ">", question: "?", at: "@",
|
|
806
420
|
bracketleft: "[", backslash: "\\", bracketright: "]", underscore: "_", braceleft: "{",
|
|
807
|
-
bar: "|", braceright: "}", asciitilde: "~", endash: "
|
|
421
|
+
bar: "|", braceright: "}", asciitilde: "~", endash: "\u2013", emdash: "\u2014", bullet: "\u2022",
|
|
808
422
|
};
|
|
809
423
|
|
|
810
424
|
function parseToUnicodeCMap(cmapText) {
|
|
@@ -848,8 +462,7 @@ function parseToUnicodeCMap(cmapText) {
|
|
|
848
462
|
const startCode = parseInt(startHex, 16);
|
|
849
463
|
const endCode = parseInt(endHex, 16);
|
|
850
464
|
if (!(endCode >= startCode)) continue;
|
|
851
|
-
const
|
|
852
|
-
const byteLen = hexWidth / 2;
|
|
465
|
+
const byteLen = startHex.length / 2;
|
|
853
466
|
lenSet.add(byteLen);
|
|
854
467
|
|
|
855
468
|
if (rm[3] !== undefined) {
|
|
@@ -858,9 +471,14 @@ function parseToUnicodeCMap(cmapText) {
|
|
|
858
471
|
} else if (rm[4] !== undefined) {
|
|
859
472
|
const dstBaseHex = rm[4];
|
|
860
473
|
if (dstBaseHex.length < 4) continue;
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
474
|
+
ranges.push({
|
|
475
|
+
startCode,
|
|
476
|
+
endCode,
|
|
477
|
+
byteLen,
|
|
478
|
+
items: null,
|
|
479
|
+
prefixHex: dstBaseHex.slice(0, -4),
|
|
480
|
+
baseLastUnit: parseInt(dstBaseHex.slice(-4), 16),
|
|
481
|
+
});
|
|
864
482
|
}
|
|
865
483
|
}
|
|
866
484
|
}
|
|
@@ -874,9 +492,7 @@ function glyphNameToChar(rawName) {
|
|
|
874
492
|
if (Object.hasOwn(AGL_GLYPH_MAP, name)) return AGL_GLYPH_MAP[name];
|
|
875
493
|
if (name.length === 1 && /[A-Za-z0-9]/.test(name)) return name;
|
|
876
494
|
const uni = name.match(/^uni((?:[0-9a-fA-F]{4})+)$/);
|
|
877
|
-
if (uni)
|
|
878
|
-
return decodeUtf16BeHex(uni[1]);
|
|
879
|
-
}
|
|
495
|
+
if (uni) return decodeUtf16BeHex(uni[1]);
|
|
880
496
|
const uhex = name.match(/^u([0-9a-fA-F]{4,6})$/);
|
|
881
497
|
if (uhex) {
|
|
882
498
|
const cp = parseInt(uhex[1], 16);
|
|
@@ -916,9 +532,7 @@ function lookupRangeCMap(ranges, code, byteLen) {
|
|
|
916
532
|
if (r.byteLen !== byteLen) continue;
|
|
917
533
|
if (code < r.startCode || code > r.endCode) continue;
|
|
918
534
|
const offset = code - r.startCode;
|
|
919
|
-
if (r.items)
|
|
920
|
-
return offset < r.items.length ? r.items[offset] : "";
|
|
921
|
-
}
|
|
535
|
+
if (r.items) return offset < r.items.length ? r.items[offset] : "";
|
|
922
536
|
const unitHex = ((r.baseLastUnit + offset) & 0xffff).toString(16).padStart(4, "0");
|
|
923
537
|
return decodeUtf16BeHex(r.prefixHex + unitHex);
|
|
924
538
|
}
|
|
@@ -941,11 +555,8 @@ function decodeHexViaToUnicode(hexLower, toUnicode) {
|
|
|
941
555
|
const key = hexLower.slice(pos, pos + hLen);
|
|
942
556
|
const codeVal = parseInt(key, 16);
|
|
943
557
|
if (codeVal >= cs.start && codeVal <= cs.end) {
|
|
944
|
-
if (toUnicode.map.has(key))
|
|
945
|
-
|
|
946
|
-
} else if (toUnicode.ranges && toUnicode.ranges.length > 0) {
|
|
947
|
-
out += lookupRangeCMap(toUnicode.ranges, codeVal, cs.byteLen);
|
|
948
|
-
}
|
|
558
|
+
if (toUnicode.map.has(key)) out += toUnicode.map.get(key);
|
|
559
|
+
else if (toUnicode.ranges?.length > 0) out += lookupRangeCMap(toUnicode.ranges, codeVal, cs.byteLen);
|
|
949
560
|
pos += hLen;
|
|
950
561
|
consumed = hLen;
|
|
951
562
|
csMatched = true;
|
|
@@ -955,7 +566,6 @@ function decodeHexViaToUnicode(hexLower, toUnicode) {
|
|
|
955
566
|
}
|
|
956
567
|
if (csMatched) continue;
|
|
957
568
|
}
|
|
958
|
-
|
|
959
569
|
let matched = false;
|
|
960
570
|
for (const bLen of byteLens) {
|
|
961
571
|
const hLen = bLen * 2;
|
|
@@ -967,7 +577,7 @@ function decodeHexViaToUnicode(hexLower, toUnicode) {
|
|
|
967
577
|
matched = true;
|
|
968
578
|
break;
|
|
969
579
|
}
|
|
970
|
-
if (toUnicode.ranges
|
|
580
|
+
if (toUnicode.ranges?.length > 0) {
|
|
971
581
|
const rVal = lookupRangeCMap(toUnicode.ranges, parseInt(key, 16), bLen);
|
|
972
582
|
if (rVal) {
|
|
973
583
|
out += rVal;
|
|
@@ -987,9 +597,7 @@ function decodePdfHexWithFont(hexRaw, fontEntry) {
|
|
|
987
597
|
const clean = hexRaw.replace(/[^0-9a-fA-F]/g, "");
|
|
988
598
|
if (!clean) return "";
|
|
989
599
|
const padded = (clean.length % 2 === 1 ? `${clean}0` : clean).toLowerCase();
|
|
990
|
-
if (/^feff/.test(padded) && padded.length >= 8)
|
|
991
|
-
return decodeUtf16BeHex(padded);
|
|
992
|
-
}
|
|
600
|
+
if (/^feff/.test(padded) && padded.length >= 8) return decodeUtf16BeHex(padded);
|
|
993
601
|
if (fontEntry?.toUnicode && (fontEntry.toUnicode.map.size > 0 || (fontEntry.toUnicode.ranges?.length || 0) > 0)) {
|
|
994
602
|
return decodeHexViaToUnicode(padded, fontEntry.toUnicode);
|
|
995
603
|
}
|
|
@@ -1056,6 +664,93 @@ function parseMediaBoxRect(dictText) {
|
|
|
1056
664
|
return [w, h];
|
|
1057
665
|
}
|
|
1058
666
|
|
|
667
|
+
function decodeAsciiHex(buf) {
|
|
668
|
+
const bytes = [];
|
|
669
|
+
let hi = -1;
|
|
670
|
+
for (let i = 0; i < buf.length; i += 1) {
|
|
671
|
+
const c = buf[i];
|
|
672
|
+
if (c === 0x3e) break; // '>'
|
|
673
|
+
let v = -1;
|
|
674
|
+
if (c >= 0x30 && c <= 0x39) v = c - 0x30;
|
|
675
|
+
else if (c >= 0x41 && c <= 0x46) v = c - 0x37;
|
|
676
|
+
else if (c >= 0x61 && c <= 0x66) v = c - 0x57;
|
|
677
|
+
else continue;
|
|
678
|
+
if (hi === -1) hi = v;
|
|
679
|
+
else {
|
|
680
|
+
bytes.push((hi << 4) | v);
|
|
681
|
+
hi = -1;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
if (hi !== -1) bytes.push(hi << 4);
|
|
685
|
+
return Buffer.from(bytes);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function decodeAscii85(buf) {
|
|
689
|
+
const out = [];
|
|
690
|
+
const tuple = [];
|
|
691
|
+
for (let i = 0; i < buf.length; i += 1) {
|
|
692
|
+
const c = buf[i];
|
|
693
|
+
if (c === 0x7e && buf[i + 1] === 0x3e) break; // '~>'
|
|
694
|
+
if (c <= 0x20) continue;
|
|
695
|
+
if (c === 0x7a && tuple.length === 0) {
|
|
696
|
+
out.push(0, 0, 0, 0);
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
if (c < 0x21 || c > 0x75) continue;
|
|
700
|
+
tuple.push(c - 0x21);
|
|
701
|
+
if (tuple.length === 5) {
|
|
702
|
+
const val =
|
|
703
|
+
(((tuple[0] * 85 + tuple[1]) * 85 + tuple[2]) * 85 + tuple[3]) * 85 + tuple[4];
|
|
704
|
+
out.push((val >>> 24) & 0xff, (val >>> 16) & 0xff, (val >>> 8) & 0xff, val & 0xff);
|
|
705
|
+
tuple.length = 0;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
if (tuple.length >= 2) {
|
|
709
|
+
const k = tuple.length;
|
|
710
|
+
while (tuple.length < 5) tuple.push(84);
|
|
711
|
+
const val =
|
|
712
|
+
(((tuple[0] * 85 + tuple[1]) * 85 + tuple[2]) * 85 + tuple[3]) * 85 + tuple[4];
|
|
713
|
+
const extra = [(val >>> 24) & 0xff, (val >>> 16) & 0xff, (val >>> 8) & 0xff, val & 0xff];
|
|
714
|
+
for (let j = 0; j < k - 1; j += 1) out.push(extra[j]);
|
|
715
|
+
}
|
|
716
|
+
return Buffer.from(out);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
function extractPdfFilterList(dictRaw) {
|
|
720
|
+
const arrM = dictRaw.match(/\/Filter\s*\[([\s\S]*?)\]/);
|
|
721
|
+
if (arrM) {
|
|
722
|
+
return [...arrM[1].matchAll(/\/([A-Za-z0-9]+)/g)].map((m) => m[1]);
|
|
723
|
+
}
|
|
724
|
+
const singleM = dictRaw.match(/\/Filter\s*\/([A-Za-z0-9]+)/);
|
|
725
|
+
return singleM ? [singleM[1]] : [];
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
function decodeObjectStream(obj) {
|
|
729
|
+
if (!obj || !obj.streamBytes) return "";
|
|
730
|
+
let bytes = obj.streamBytes;
|
|
731
|
+
const filters = extractPdfFilterList(obj.dictRaw || "");
|
|
732
|
+
for (const fName of filters) {
|
|
733
|
+
if (fName === "ASCII85Decode" || fName === "A85") {
|
|
734
|
+
bytes = decodeAscii85(bytes);
|
|
735
|
+
} else if (fName === "ASCIIHexDecode" || fName === "AHx") {
|
|
736
|
+
bytes = decodeAsciiHex(bytes);
|
|
737
|
+
} else if (fName === "FlateDecode" || fName === "Fl") {
|
|
738
|
+
try {
|
|
739
|
+
bytes = inflateSync(bytes, { maxOutputLength: MAX_STREAM_UNCOMPRESSED_BYTES });
|
|
740
|
+
} catch {
|
|
741
|
+
try {
|
|
742
|
+
bytes = inflateRawSync(bytes, { maxOutputLength: MAX_STREAM_UNCOMPRESSED_BYTES });
|
|
743
|
+
} catch {
|
|
744
|
+
return "";
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
} else {
|
|
748
|
+
return "";
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
return bytes.toString("latin1");
|
|
752
|
+
}
|
|
753
|
+
|
|
1059
754
|
function extractPdfObjects(buffer) {
|
|
1060
755
|
const latin = buffer.toString("latin1");
|
|
1061
756
|
const objects = new Map();
|
|
@@ -1101,9 +796,7 @@ function extractPdfObjects(buffer) {
|
|
|
1101
796
|
if (realEndObj !== -1) nextPos = realEndObj + 6;
|
|
1102
797
|
}
|
|
1103
798
|
}
|
|
1104
|
-
if (sEnd >= sStart)
|
|
1105
|
-
streamBytes = buffer.subarray(sStart, sEnd);
|
|
1106
|
-
}
|
|
799
|
+
if (sEnd >= sStart) streamBytes = buffer.subarray(sStart, sEnd);
|
|
1107
800
|
} else {
|
|
1108
801
|
dictPart = latin.slice(bodyStart, endObjIdx);
|
|
1109
802
|
}
|
|
@@ -1112,12 +805,7 @@ function extractPdfObjects(buffer) {
|
|
|
1112
805
|
objRe.lastIndex = nextPos;
|
|
1113
806
|
}
|
|
1114
807
|
|
|
1115
|
-
// Extract PDF 1.5+ /Type /ObjStm compressed object streams
|
|
1116
|
-
let hasCompressedStreams = false;
|
|
1117
808
|
for (const obj of Array.from(objects.values())) {
|
|
1118
|
-
if (obj.streamBytes && /\/FlateDecode\b/.test(obj.dictRaw)) {
|
|
1119
|
-
hasCompressedStreams = true;
|
|
1120
|
-
}
|
|
1121
809
|
if (!obj.streamBytes || !/\/Type\s*\/ObjStm\b/.test(obj.dictRaw)) continue;
|
|
1122
810
|
const nMatch = obj.dictRaw.match(/\/N\s+(\d+)/);
|
|
1123
811
|
const firstMatch = obj.dictRaw.match(/\/First\s+(\d+)/);
|
|
@@ -1143,29 +831,7 @@ function extractPdfObjects(buffer) {
|
|
|
1143
831
|
}
|
|
1144
832
|
}
|
|
1145
833
|
|
|
1146
|
-
return { latin, objects
|
|
1147
|
-
}
|
|
1148
|
-
|
|
1149
|
-
function decodeObjectStream(obj) {
|
|
1150
|
-
if (!obj || !obj.streamBytes) return "";
|
|
1151
|
-
let bytes = obj.streamBytes;
|
|
1152
|
-
if (/\/FlateDecode\b/.test(obj.dictRaw)) {
|
|
1153
|
-
try {
|
|
1154
|
-
bytes = inflateSync(bytes, { maxOutputLength: MAX_STREAM_UNCOMPRESSED_BYTES });
|
|
1155
|
-
} catch {
|
|
1156
|
-
return "";
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
return bytes.toString("latin1");
|
|
1160
|
-
}
|
|
1161
|
-
|
|
1162
|
-
function collectRgbStopsFromDict(dictText, outColors) {
|
|
1163
|
-
for (const m of dictText.matchAll(/\/C[01]\s*\[\s*([\d.]+)\s+([\d.]+)\s+([\d.]+)\s*\]/g)) {
|
|
1164
|
-
const r = Math.min(255, Math.max(0, Math.round(Number(m[1]) * 255)));
|
|
1165
|
-
const g = Math.min(255, Math.max(0, Math.round(Number(m[2]) * 255)));
|
|
1166
|
-
const b = Math.min(255, Math.max(0, Math.round(Number(m[3]) * 255)));
|
|
1167
|
-
outColors.push([r, g, b]);
|
|
1168
|
-
}
|
|
834
|
+
return { latin, objects };
|
|
1169
835
|
}
|
|
1170
836
|
|
|
1171
837
|
function readPdfDictAt(src, openIdx) {
|
|
@@ -1236,7 +902,6 @@ function readPdfOpAt(str, pos) {
|
|
|
1236
902
|
}
|
|
1237
903
|
|
|
1238
904
|
function stripInlineImagesLinear(streamText) {
|
|
1239
|
-
let imageCount = 0;
|
|
1240
905
|
const out = [];
|
|
1241
906
|
let pos = 0;
|
|
1242
907
|
const len = streamText.length;
|
|
@@ -1277,45 +942,107 @@ function stripInlineImagesLinear(streamText) {
|
|
|
1277
942
|
pos = biIdx + 2;
|
|
1278
943
|
continue;
|
|
1279
944
|
}
|
|
1280
|
-
out.push(streamText.slice(pos, biIdx));
|
|
1281
|
-
out.push(" ");
|
|
1282
|
-
imageCount += 1;
|
|
945
|
+
out.push(streamText.slice(pos, biIdx), " ");
|
|
1283
946
|
pos = eiIdx + 2;
|
|
1284
947
|
}
|
|
1285
|
-
return
|
|
948
|
+
return out.join("");
|
|
1286
949
|
}
|
|
1287
950
|
|
|
1288
|
-
function
|
|
1289
|
-
const
|
|
1290
|
-
const
|
|
1291
|
-
|
|
1292
|
-
|
|
951
|
+
function resolvePageFontMap(resText, objects, fontCache) {
|
|
952
|
+
const fontMap = new Map();
|
|
953
|
+
const fontRefs = [];
|
|
954
|
+
for (const inlineM of resText.matchAll(/\/Font\s*<<([\s\S]*?)>>/g)) {
|
|
955
|
+
for (const fm of inlineM[1].matchAll(/\/([A-Za-z0-9_+.-]+)\s+(\d+)\s+\d+\s+R/g)) {
|
|
956
|
+
fontRefs.push([fm[1], Number(fm[2])]);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
for (const refM of resText.matchAll(/\/Font\s+(\d+)\s+\d+\s+R/g)) {
|
|
960
|
+
const fDictObj = objects.get(Number(refM[1]));
|
|
961
|
+
if (fDictObj) {
|
|
962
|
+
for (const fm of fDictObj.dictRaw.matchAll(/\/([A-Za-z0-9_+.-]+)\s+(\d+)\s+\d+\s+R/g)) {
|
|
963
|
+
fontRefs.push([fm[1], Number(fm[2])]);
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
1293
967
|
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
968
|
+
for (const [alias, fObjNum] of fontRefs) {
|
|
969
|
+
if (fontCache.has(fObjNum)) {
|
|
970
|
+
fontMap.set(alias, fontCache.get(fObjNum));
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
const fObj = objects.get(fObjNum);
|
|
974
|
+
if (!fObj) continue;
|
|
975
|
+
let fullDict = fObj.dictRaw || "";
|
|
976
|
+
const descM = fullDict.match(/\/DescendantFonts\s*\[\s*(\d+)\s+\d+\s+R/);
|
|
977
|
+
if (descM && objects.has(Number(descM[1]))) {
|
|
978
|
+
fullDict += `\n${objects.get(Number(descM[1])).dictRaw || ""}`;
|
|
979
|
+
}
|
|
980
|
+
let toUnicode = null;
|
|
981
|
+
const tuM = fullDict.match(/\/ToUnicode\s+(\d+)\s+\d+\s+R/);
|
|
982
|
+
if (tuM && objects.has(Number(tuM[1]))) {
|
|
983
|
+
const cmapStr = decodeObjectStream(objects.get(Number(tuM[1])));
|
|
984
|
+
const parsed = parseToUnicodeCMap(cmapStr);
|
|
985
|
+
if (parsed.map.size > 0 || parsed.ranges.length > 0) toUnicode = parsed;
|
|
986
|
+
}
|
|
987
|
+
const differences = parseEncodingDifferences(fullDict, objects);
|
|
988
|
+
const hasStdBaseEnc = /\/BaseEncoding\s*\/(?:WinAnsiEncoding|MacRomanEncoding|StandardEncoding)\b/.test(fullDict);
|
|
989
|
+
const isCustomGlyph =
|
|
990
|
+
(/\/Subtype\s*\/(?:Type3|Type0)\b|\/Identity-[HV]\b/.test(fullDict) || Boolean(toUnicode)) &&
|
|
991
|
+
!hasStdBaseEnc;
|
|
992
|
+
const baseFontMatch = fullDict.match(/\/BaseFont\s*\/([^\s/[\]()<>]+)/);
|
|
993
|
+
const baseFont = baseFontMatch ? baseFontMatch[1] : "";
|
|
994
|
+
const isMono = /(?:Courier|Menlo|Monaco|Consolas|Mono|FiraCode|JetBrainsMono|Inconsolata|SFMono)/i.test(baseFont);
|
|
995
|
+
const entry = { toUnicode, differences, isCustomGlyph, isMono };
|
|
996
|
+
fontCache.set(fObjNum, entry);
|
|
997
|
+
fontMap.set(alias, entry);
|
|
998
|
+
}
|
|
999
|
+
return fontMap;
|
|
1000
|
+
}
|
|
1297
1001
|
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1002
|
+
function resolvePageXObjectMap(resText, objects) {
|
|
1003
|
+
const xObjMap = new Map();
|
|
1004
|
+
for (const inlineM of resText.matchAll(/\/XObject\s*<<([\s\S]*?)>>/g)) {
|
|
1005
|
+
for (const xm of inlineM[1].matchAll(/\/([A-Za-z0-9_+.-]+)\s+(\d+)\s+\d+\s+R/g)) {
|
|
1006
|
+
xObjMap.set(xm[1], Number(xm[2]));
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
for (const refM of resText.matchAll(/\/XObject\s+(\d+)\s+\d+\s+R/g)) {
|
|
1010
|
+
const xDictObj = objects.get(Number(refM[1]));
|
|
1011
|
+
if (xDictObj) {
|
|
1012
|
+
for (const xm of xDictObj.dictRaw.matchAll(/\/([A-Za-z0-9_+.-]+)\s+(\d+)\s+\d+\s+R/g)) {
|
|
1013
|
+
xObjMap.set(xm[1], Number(xm[2]));
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1304
1016
|
}
|
|
1017
|
+
return xObjMap;
|
|
1018
|
+
}
|
|
1305
1019
|
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1020
|
+
function extractOwnResourcesText(dictRaw, objects) {
|
|
1021
|
+
let out = dictRaw || "";
|
|
1022
|
+
for (const resRef of out.matchAll(/\/Resources\s+(\d+)\s+\d+\s+R/g)) {
|
|
1023
|
+
if (objects.has(Number(resRef[1]))) {
|
|
1024
|
+
out += `\n${objects.get(Number(resRef[1])).dictRaw}`;
|
|
1309
1025
|
}
|
|
1310
1026
|
}
|
|
1027
|
+
return out;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
function parsePdfContentStream(
|
|
1031
|
+
streamText,
|
|
1032
|
+
fontMap = new Map(),
|
|
1033
|
+
{ xObjectMap = new Map(), objects = new Map(), fontCache = new Map(), visitedForms = new Set(), depth = 0 } = {},
|
|
1034
|
+
) {
|
|
1035
|
+
const cleaned = stripInlineImagesLinear(streamText);
|
|
1036
|
+
const textParts = [];
|
|
1037
|
+
const nonMonoParts = [];
|
|
1311
1038
|
|
|
1312
|
-
// Scan text operators, active fonts, effective scaled sizes, /ActualText marked-content spans, and coordinate-aware line breaks
|
|
1313
1039
|
let i = 0;
|
|
1314
1040
|
let currentLine = "";
|
|
1041
|
+
let currentNonMonoLine = "";
|
|
1315
1042
|
let activeFont = null;
|
|
1316
|
-
let rawFontSize = 0;
|
|
1317
1043
|
let lastName = null;
|
|
1318
1044
|
let curY = null;
|
|
1045
|
+
let curX = null;
|
|
1319
1046
|
let tm = [1, 0, 0, 1, 0, 0];
|
|
1320
1047
|
let noArrayClose = false;
|
|
1321
1048
|
const numStack = [];
|
|
@@ -1325,23 +1052,18 @@ function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
|
1325
1052
|
const flushLine = () => {
|
|
1326
1053
|
const t = currentLine.trim();
|
|
1327
1054
|
if (t) textParts.push(t);
|
|
1055
|
+
const nm = currentNonMonoLine.trim();
|
|
1056
|
+
if (nm) nonMonoParts.push(nm);
|
|
1328
1057
|
currentLine = "";
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
const recordEffectiveFontSize = () => {
|
|
1332
|
-
if (!(rawFontSize > 0)) return;
|
|
1333
|
-
const scaleY = Math.hypot(tm[2], tm[3]);
|
|
1334
|
-
const eff = Math.abs(rawFontSize) * (scaleY > 0 ? scaleY : 1);
|
|
1335
|
-
const rounded = Math.round(eff * 100) / 100;
|
|
1336
|
-
if (rounded >= 0.05 && rounded <= 300) {
|
|
1337
|
-
fontSizes.push(rounded);
|
|
1338
|
-
}
|
|
1058
|
+
currentNonMonoLine = "";
|
|
1339
1059
|
};
|
|
1340
1060
|
|
|
1341
1061
|
const emitChunk = (str) => {
|
|
1342
1062
|
if (!str) return;
|
|
1343
|
-
if (str.trim()) textOpCount += 1;
|
|
1344
1063
|
currentLine += str;
|
|
1064
|
+
if (!activeFont?.isMono) {
|
|
1065
|
+
currentNonMonoLine += str;
|
|
1066
|
+
}
|
|
1345
1067
|
};
|
|
1346
1068
|
|
|
1347
1069
|
while (i < cleaned.length) {
|
|
@@ -1359,7 +1081,6 @@ function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
|
1359
1081
|
const { raw, endIdx } = readPdfLiteralAt(cleaned, i);
|
|
1360
1082
|
const { op, endIdx: afterOp } = readPdfOpAt(cleaned, endIdx);
|
|
1361
1083
|
if (op === "Tj" || op === "'" || op === '"') {
|
|
1362
|
-
recordEffectiveFontSize();
|
|
1363
1084
|
if (actualTextDepth === 0) {
|
|
1364
1085
|
if (op === "'" || op === '"') flushLine();
|
|
1365
1086
|
emitChunk(decodePdfLiteralWithFont(raw, activeFont));
|
|
@@ -1377,9 +1098,7 @@ function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
|
1377
1098
|
if (op === "BDC") {
|
|
1378
1099
|
const actual = extractActualTextFromPropDict(dictRaw);
|
|
1379
1100
|
if (actual !== null) {
|
|
1380
|
-
if (mcStack.length > 0)
|
|
1381
|
-
mcStack[mcStack.length - 1].hasChildActual = true;
|
|
1382
|
-
}
|
|
1101
|
+
if (mcStack.length > 0) mcStack[mcStack.length - 1].hasChildActual = true;
|
|
1383
1102
|
mcStack.push({ actualText: actual, hasChildActual: false });
|
|
1384
1103
|
actualTextDepth += 1;
|
|
1385
1104
|
} else {
|
|
@@ -1397,7 +1116,6 @@ function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
|
1397
1116
|
if (closeIdx !== -1) {
|
|
1398
1117
|
const { op, endIdx: afterOp } = readPdfOpAt(cleaned, closeIdx + 1);
|
|
1399
1118
|
if (op === "Tj" || op === "'" || op === '"') {
|
|
1400
|
-
recordEffectiveFontSize();
|
|
1401
1119
|
if (actualTextDepth === 0) {
|
|
1402
1120
|
if (op === "'" || op === '"') flushLine();
|
|
1403
1121
|
emitChunk(decodePdfHexWithFont(cleaned.slice(i + 1, closeIdx), activeFont));
|
|
@@ -1474,9 +1192,7 @@ function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
|
1474
1192
|
}
|
|
1475
1193
|
break;
|
|
1476
1194
|
}
|
|
1477
|
-
if (cj === "[" || j - i > 262144)
|
|
1478
|
-
break;
|
|
1479
|
-
}
|
|
1195
|
+
if (cj === "[" || j - i > 262144) break;
|
|
1480
1196
|
if ((cj >= "0" && cj <= "9") || cj === "-" || cj === "+" || cj === ".") {
|
|
1481
1197
|
curNumStr += cj;
|
|
1482
1198
|
sawNum = true;
|
|
@@ -1487,10 +1203,7 @@ function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
|
1487
1203
|
}
|
|
1488
1204
|
if (j >= cleaned.length && !valid) noArrayClose = true;
|
|
1489
1205
|
if (valid) {
|
|
1490
|
-
|
|
1491
|
-
if (actualTextDepth === 0) {
|
|
1492
|
-
emitChunk(seg);
|
|
1493
|
-
}
|
|
1206
|
+
if (actualTextDepth === 0) emitChunk(seg);
|
|
1494
1207
|
i = j;
|
|
1495
1208
|
numStack.length = 0;
|
|
1496
1209
|
continue;
|
|
@@ -1503,7 +1216,6 @@ function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
|
1503
1216
|
i = j;
|
|
1504
1217
|
continue;
|
|
1505
1218
|
}
|
|
1506
|
-
// Read word/number token
|
|
1507
1219
|
let endTok = i;
|
|
1508
1220
|
while (endTok < cleaned.length && !isPdfDelimiter(cleaned[endTok])) endTok += 1;
|
|
1509
1221
|
const tok = cleaned.slice(i, endTok);
|
|
@@ -1513,15 +1225,8 @@ function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
|
1513
1225
|
} else {
|
|
1514
1226
|
if (tok === "Tf") {
|
|
1515
1227
|
activeFont = (lastName && fontMap.get(lastName)) || null;
|
|
1516
|
-
if (numStack.length >= 1) {
|
|
1517
|
-
rawFontSize = Math.abs(numStack[numStack.length - 1]);
|
|
1518
|
-
}
|
|
1519
1228
|
} else if (tok === "BT") {
|
|
1520
|
-
curY = null;
|
|
1521
1229
|
tm = [1, 0, 0, 1, 0, 0];
|
|
1522
|
-
} else if (tok === "ET") {
|
|
1523
|
-
flushLine();
|
|
1524
|
-
curY = null;
|
|
1525
1230
|
} else if (tok === "T*") {
|
|
1526
1231
|
flushLine();
|
|
1527
1232
|
} else if (tok === "Td" || tok === "TD") {
|
|
@@ -1529,16 +1234,63 @@ function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
|
1529
1234
|
const ty = numStack.length >= 2 ? numStack[numStack.length - 1] : 0;
|
|
1530
1235
|
tm[4] += tx;
|
|
1531
1236
|
tm[5] += ty;
|
|
1532
|
-
if (Math.abs(ty) > 2.0)
|
|
1533
|
-
|
|
1237
|
+
if (curY !== null && Math.abs(ty) > 2.0) {
|
|
1238
|
+
flushLine();
|
|
1239
|
+
} else if (
|
|
1240
|
+
tx > 4 &&
|
|
1241
|
+
currentLine.length > 0 &&
|
|
1242
|
+
!/\s$/.test(currentLine) &&
|
|
1243
|
+
curX !== null &&
|
|
1244
|
+
tm[4] > curX + 4
|
|
1245
|
+
) {
|
|
1246
|
+
emitChunk(" ");
|
|
1247
|
+
}
|
|
1248
|
+
curX = tm[4];
|
|
1249
|
+
curY = tm[5];
|
|
1534
1250
|
} else if (tok === "Tm") {
|
|
1535
1251
|
if (numStack.length >= 6) {
|
|
1536
1252
|
const vals = numStack.slice(-6);
|
|
1537
|
-
const
|
|
1538
|
-
|
|
1539
|
-
curY
|
|
1253
|
+
const nx = vals[4];
|
|
1254
|
+
const ny = vals[5];
|
|
1255
|
+
if (curY !== null && Math.abs(ny - curY) > 2.0) {
|
|
1256
|
+
flushLine();
|
|
1257
|
+
} else if (curX !== null && nx > curX + 4 && currentLine.length > 0 && !/\s$/.test(currentLine)) {
|
|
1258
|
+
emitChunk(" ");
|
|
1259
|
+
}
|
|
1260
|
+
curX = nx;
|
|
1261
|
+
curY = ny;
|
|
1540
1262
|
tm = vals;
|
|
1541
1263
|
}
|
|
1264
|
+
} else if (tok === "Do") {
|
|
1265
|
+
if (lastName && depth < 8 && xObjectMap.has(lastName)) {
|
|
1266
|
+
const xObjNum = xObjectMap.get(lastName);
|
|
1267
|
+
if (!visitedForms.has(xObjNum)) {
|
|
1268
|
+
const formObj = objects.get(xObjNum);
|
|
1269
|
+
if (formObj && /\/Subtype\s*\/Form\b/.test(formObj.dictRaw || "")) {
|
|
1270
|
+
flushLine();
|
|
1271
|
+
const formStream = decodeObjectStream(formObj);
|
|
1272
|
+
if (formStream) {
|
|
1273
|
+
const formResText = extractOwnResourcesText(formObj.dictRaw, objects);
|
|
1274
|
+
const ownFonts = resolvePageFontMap(formResText, objects, fontCache);
|
|
1275
|
+
const mergedFonts = new Map([...fontMap, ...ownFonts]);
|
|
1276
|
+
const ownXObjs = resolvePageXObjectMap(formResText, objects);
|
|
1277
|
+
const mergedXObjs = new Map([...xObjectMap, ...ownXObjs]);
|
|
1278
|
+
const nextVisited = new Set(visitedForms);
|
|
1279
|
+
nextVisited.add(xObjNum);
|
|
1280
|
+
const nested = parsePdfContentStream(formStream, mergedFonts, {
|
|
1281
|
+
xObjectMap: mergedXObjs,
|
|
1282
|
+
objects,
|
|
1283
|
+
fontCache,
|
|
1284
|
+
visitedForms: nextVisited,
|
|
1285
|
+
depth: depth + 1,
|
|
1286
|
+
});
|
|
1287
|
+
if (nested.text) textParts.push(nested.text);
|
|
1288
|
+
if (nested.nonMonoText) nonMonoParts.push(nested.nonMonoText);
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
lastName = null;
|
|
1542
1294
|
} else if (tok === "BMC" || tok === "BDC") {
|
|
1543
1295
|
mcStack.push({ actualText: null, hasChildActual: false });
|
|
1544
1296
|
} else if (tok === "EMC") {
|
|
@@ -1556,132 +1308,40 @@ function parseContentStream(streamText, imageXObjNames, fontMap = new Map()) {
|
|
|
1556
1308
|
}
|
|
1557
1309
|
flushLine();
|
|
1558
1310
|
|
|
1559
|
-
if (fontSizes.length === 0 && rawFontSize > 0) {
|
|
1560
|
-
recordEffectiveFontSize();
|
|
1561
|
-
}
|
|
1562
|
-
|
|
1563
1311
|
return {
|
|
1564
1312
|
text: textParts.join("\n"),
|
|
1565
|
-
|
|
1566
|
-
rgbColors,
|
|
1567
|
-
imageCount,
|
|
1568
|
-
textOpCount,
|
|
1313
|
+
nonMonoText: nonMonoParts.join("\n"),
|
|
1569
1314
|
};
|
|
1570
1315
|
}
|
|
1571
1316
|
|
|
1572
|
-
function resolvePageFontMap(resText, objects, fontCache) {
|
|
1573
|
-
const fontMap = new Map();
|
|
1574
|
-
const fontRefs = [];
|
|
1575
|
-
const inlineM = resText.match(/\/Font\s*<<([\s\S]*?)>>/);
|
|
1576
|
-
if (inlineM) {
|
|
1577
|
-
for (const fm of inlineM[1].matchAll(/\/([A-Za-z0-9_+.-]+)\s+(\d+)\s+\d+\s+R/g)) {
|
|
1578
|
-
fontRefs.push([fm[1], Number(fm[2])]);
|
|
1579
|
-
}
|
|
1580
|
-
}
|
|
1581
|
-
for (const refM of resText.matchAll(/\/Font\s+(\d+)\s+\d+\s+R/g)) {
|
|
1582
|
-
const fDictObj = objects.get(Number(refM[1]));
|
|
1583
|
-
if (fDictObj) {
|
|
1584
|
-
for (const fm of fDictObj.dictRaw.matchAll(/\/([A-Za-z0-9_+.-]+)\s+(\d+)\s+\d+\s+R/g)) {
|
|
1585
|
-
fontRefs.push([fm[1], Number(fm[2])]);
|
|
1586
|
-
}
|
|
1587
|
-
}
|
|
1588
|
-
}
|
|
1589
|
-
|
|
1590
|
-
for (const [alias, fObjNum] of fontRefs) {
|
|
1591
|
-
if (fontCache.has(fObjNum)) {
|
|
1592
|
-
fontMap.set(alias, fontCache.get(fObjNum));
|
|
1593
|
-
continue;
|
|
1594
|
-
}
|
|
1595
|
-
const fObj = objects.get(fObjNum);
|
|
1596
|
-
if (!fObj) continue;
|
|
1597
|
-
let fullDict = fObj.dictRaw || "";
|
|
1598
|
-
const descM = fullDict.match(/\/DescendantFonts\s*\[\s*(\d+)\s+\d+\s+R/);
|
|
1599
|
-
if (descM && objects.has(Number(descM[1]))) {
|
|
1600
|
-
fullDict += "\n" + (objects.get(Number(descM[1])).dictRaw || "");
|
|
1601
|
-
}
|
|
1602
|
-
let toUnicode = null;
|
|
1603
|
-
const tuM = fullDict.match(/\/ToUnicode\s+(\d+)\s+\d+\s+R/);
|
|
1604
|
-
if (tuM && objects.has(Number(tuM[1]))) {
|
|
1605
|
-
const cmapStr = decodeObjectStream(objects.get(Number(tuM[1])));
|
|
1606
|
-
const parsed = parseToUnicodeCMap(cmapStr);
|
|
1607
|
-
if (parsed.map.size > 0 || parsed.ranges.length > 0) toUnicode = parsed;
|
|
1608
|
-
}
|
|
1609
|
-
const differences = parseEncodingDifferences(fullDict, objects);
|
|
1610
|
-
const hasStdBaseEnc = /\/BaseEncoding\s*\/(?:WinAnsiEncoding|MacRomanEncoding|StandardEncoding)\b/.test(fullDict);
|
|
1611
|
-
const isCustomGlyph =
|
|
1612
|
-
(/\/Subtype\s*\/(?:Type3|Type0)\b|\/Identity-[HV]\b/.test(fullDict) || Boolean(toUnicode)) &&
|
|
1613
|
-
!hasStdBaseEnc;
|
|
1614
|
-
const entry = { toUnicode, differences, isCustomGlyph };
|
|
1615
|
-
fontCache.set(fObjNum, entry);
|
|
1616
|
-
fontMap.set(alias, entry);
|
|
1617
|
-
}
|
|
1618
|
-
return fontMap;
|
|
1619
|
-
}
|
|
1620
|
-
|
|
1621
1317
|
/**
|
|
1622
|
-
*
|
|
1623
|
-
* Supports FlateDecode streams, PDF 1.5+ /ObjStm, /
|
|
1318
|
+
* Extract page count, geometry, and decoded text spans from PDF buffers without external dependencies.
|
|
1319
|
+
* Supports FlateDecode streams, PDF 1.5+ /ObjStm, /ToUnicode CMaps, UTF-16BE, TJ arrays, and /ActualText.
|
|
1624
1320
|
*/
|
|
1625
|
-
export function
|
|
1321
|
+
export function inspectPdfBuffer(buffer) {
|
|
1626
1322
|
if (!Buffer.isBuffer(buffer) || buffer.length < 8) {
|
|
1627
1323
|
throw new Error("Invalid or truncated PDF buffer");
|
|
1628
1324
|
}
|
|
1629
1325
|
const head = buffer.subarray(0, Math.min(1024, buffer.length)).toString("latin1");
|
|
1630
1326
|
if (!head.includes("%PDF-")) {
|
|
1631
|
-
throw new Error("Invalid PDF header
|
|
1327
|
+
throw new Error("Invalid PDF header");
|
|
1632
1328
|
}
|
|
1633
1329
|
|
|
1634
|
-
const { latin, objects
|
|
1635
|
-
|
|
1636
|
-
// Detect encrypted PDFs honestly: check trailer & non-stream dicts for /Encrypt
|
|
1330
|
+
const { latin, objects } = extractPdfObjects(buffer);
|
|
1637
1331
|
const trailerMatch = latin.match(/trailer\s*<<[\s\S]*?>>/);
|
|
1638
1332
|
if (trailerMatch && /\/Encrypt\b/.test(trailerMatch[0])) {
|
|
1639
|
-
return { encrypted: true, pageCount: 0,
|
|
1333
|
+
return { encrypted: true, pageCount: 0, pages: [], extractedText: "" };
|
|
1640
1334
|
}
|
|
1641
1335
|
for (const obj of objects.values()) {
|
|
1642
1336
|
if (!obj.streamBytes && /\/Encrypt\b/.test(obj.dictRaw)) {
|
|
1643
|
-
return { encrypted: true, pageCount: 0,
|
|
1644
|
-
}
|
|
1645
|
-
}
|
|
1646
|
-
|
|
1647
|
-
// Extract Producer/Creator metadata from /Info or XMP
|
|
1648
|
-
let producer = "";
|
|
1649
|
-
let creator = "";
|
|
1650
|
-
let hasFonts = false;
|
|
1651
|
-
for (const obj of objects.values()) {
|
|
1652
|
-
if (/\/Type\s*\/Font\b|\/Subtype\s*\/(?:Type0|Type1|Type3|TrueType|CIDFontType[02])\b/.test(obj.dictRaw)) {
|
|
1653
|
-
hasFonts = true;
|
|
1654
|
-
}
|
|
1655
|
-
if (!obj.streamBytes && (/\/Producer\b/.test(obj.dictRaw) || /\/Creator\b/.test(obj.dictRaw))) {
|
|
1656
|
-
const pm = obj.dictRaw.match(/\/Producer\s*\(([^)]*)\)/);
|
|
1657
|
-
if (pm) producer = decodePdfLiteralString(pm[1]);
|
|
1658
|
-
const cm = obj.dictRaw.match(/\/Creator\s*\(([^)]*)\)/);
|
|
1659
|
-
if (cm) creator = decodePdfLiteralString(cm[1]);
|
|
1660
|
-
}
|
|
1661
|
-
}
|
|
1662
|
-
|
|
1663
|
-
// Collect global image XObject numbers and shading RGB stops
|
|
1664
|
-
const imageObjNums = new Set();
|
|
1665
|
-
const shadingObjColors = new Map();
|
|
1666
|
-
for (const obj of objects.values()) {
|
|
1667
|
-
if (/\/Subtype\s*\/Image\b/.test(obj.dictRaw)) {
|
|
1668
|
-
imageObjNums.add(obj.objNum);
|
|
1337
|
+
return { encrypted: true, pageCount: 0, pages: [], extractedText: "" };
|
|
1669
1338
|
}
|
|
1670
|
-
const cols = [];
|
|
1671
|
-
collectRgbStopsFromDict(obj.dictRaw, cols);
|
|
1672
|
-
if (cols.length > 0) shadingObjColors.set(obj.objNum, cols);
|
|
1673
1339
|
}
|
|
1674
1340
|
|
|
1675
|
-
function
|
|
1676
|
-
|
|
1677
|
-
const resRef = out.match(/\/Resources\s+(\d+)\s+\d+\s+R/);
|
|
1678
|
-
if (resRef && objects.has(Number(resRef[1]))) {
|
|
1679
|
-
out += "\n" + objects.get(Number(resRef[1])).dictRaw;
|
|
1680
|
-
}
|
|
1681
|
-
return out;
|
|
1341
|
+
function extractOwnRes(dictRaw) {
|
|
1342
|
+
return extractOwnResourcesText(dictRaw, objects);
|
|
1682
1343
|
}
|
|
1683
1344
|
|
|
1684
|
-
// Order pages via /Catalog -> /Pages -> /Kids tree (iterative + inherited MediaBox & Resources)
|
|
1685
1345
|
const orderedPageObjs = [];
|
|
1686
1346
|
const inheritedMediaBox = new Map();
|
|
1687
1347
|
const inheritedResources = new Map();
|
|
@@ -1697,7 +1357,7 @@ export function parsePdfBuffer(buffer) {
|
|
|
1697
1357
|
if (!obj) continue;
|
|
1698
1358
|
const ownBox = parseMediaBoxRect(obj.dictRaw) || parentBox;
|
|
1699
1359
|
const hasOwnRes = /\/Resources(?:\s|\n|<<)/.test(obj.dictRaw);
|
|
1700
|
-
const combinedRes = hasOwnRes ? `${parentRes}\n${
|
|
1360
|
+
const combinedRes = hasOwnRes ? `${parentRes}\n${extractOwnRes(obj.dictRaw)}` : parentRes;
|
|
1701
1361
|
if (/\/Type\s*\/Pages\b/.test(obj.dictRaw)) {
|
|
1702
1362
|
const kidsMatch = obj.dictRaw.match(/\/Kids\s*\[([^\]]*)\]/);
|
|
1703
1363
|
if (kidsMatch) {
|
|
@@ -1710,7 +1370,7 @@ export function parsePdfBuffer(buffer) {
|
|
|
1710
1370
|
}
|
|
1711
1371
|
if (/\/Type\s*\/Page(?![a-zA-Z])/.test(obj.dictRaw)) {
|
|
1712
1372
|
inheritedMediaBox.set(objNum, ownBox || [612, 792]);
|
|
1713
|
-
inheritedResources.set(objNum, combinedRes ||
|
|
1373
|
+
inheritedResources.set(objNum, combinedRes || extractOwnRes(obj.dictRaw));
|
|
1714
1374
|
orderedPageObjs.push(obj);
|
|
1715
1375
|
}
|
|
1716
1376
|
}
|
|
@@ -1725,7 +1385,7 @@ export function parsePdfBuffer(buffer) {
|
|
|
1725
1385
|
for (const obj of Array.from(objects.values()).sort((a, b) => a.objNum - b.objNum)) {
|
|
1726
1386
|
if (/\/Type\s*\/Page(?![a-zA-Z])/.test(obj.dictRaw)) {
|
|
1727
1387
|
inheritedMediaBox.set(obj.objNum, parseMediaBoxRect(obj.dictRaw) || [612, 792]);
|
|
1728
|
-
inheritedResources.set(obj.objNum,
|
|
1388
|
+
inheritedResources.set(obj.objNum, extractOwnRes(obj.dictRaw));
|
|
1729
1389
|
orderedPageObjs.push(obj);
|
|
1730
1390
|
}
|
|
1731
1391
|
}
|
|
@@ -1734,35 +1394,10 @@ export function parsePdfBuffer(buffer) {
|
|
|
1734
1394
|
const fontCache = new Map();
|
|
1735
1395
|
const pages = orderedPageObjs.map((pageObj, idx) => {
|
|
1736
1396
|
const [width, height] = inheritedMediaBox.get(pageObj.objNum) || [612, 792];
|
|
1737
|
-
const
|
|
1738
|
-
const resText = inheritedResources.get(pageObj.objNum) || extractOwnResourcesText(pageObj.dictRaw);
|
|
1739
|
-
|
|
1397
|
+
const resText = inheritedResources.get(pageObj.objNum) || extractOwnRes(pageObj.dictRaw);
|
|
1740
1398
|
const fontMap = resolvePageFontMap(resText, objects, fontCache);
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
const imageXObjNames = new Set();
|
|
1744
|
-
for (const xm of resText.matchAll(/\/([A-Za-z0-9_+.-]+)\s+(\d+)\s+\d+\s+R/g)) {
|
|
1745
|
-
if (imageObjNums.has(Number(xm[2]))) {
|
|
1746
|
-
imageXObjNames.add(xm[1]);
|
|
1747
|
-
}
|
|
1748
|
-
}
|
|
1749
|
-
|
|
1750
|
-
const resourceColors = [];
|
|
1751
|
-
collectRgbStopsFromDict(resText, resourceColors);
|
|
1752
|
-
for (const rm of resText.matchAll(/(\d+)\s+\d+\s+R/g)) {
|
|
1753
|
-
const refNum = Number(rm[1]);
|
|
1754
|
-
const cols = shadingObjColors.get(refNum);
|
|
1755
|
-
if (cols) resourceColors.push(...cols);
|
|
1756
|
-
const refObj = objects.get(refNum);
|
|
1757
|
-
if (refObj) {
|
|
1758
|
-
for (const subRef of refObj.dictRaw.matchAll(/(\d+)\s+\d+\s+R/g)) {
|
|
1759
|
-
const subCols = shadingObjColors.get(Number(subRef[1]));
|
|
1760
|
-
if (subCols) resourceColors.push(...subCols);
|
|
1761
|
-
}
|
|
1762
|
-
}
|
|
1763
|
-
}
|
|
1399
|
+
const xObjectMap = resolvePageXObjectMap(resText, objects);
|
|
1764
1400
|
|
|
1765
|
-
// Resolve /Contents stream(s)
|
|
1766
1401
|
const contentRefs = [];
|
|
1767
1402
|
const arrMatch = pageObj.dictRaw.match(/\/Contents\s*\[([^\]]*)\]/);
|
|
1768
1403
|
if (arrMatch) {
|
|
@@ -1773,28 +1408,32 @@ export function parsePdfBuffer(buffer) {
|
|
|
1773
1408
|
}
|
|
1774
1409
|
|
|
1775
1410
|
const joinedStream = contentRefs.map((id) => decodeObjectStream(objects.get(id))).join("\n");
|
|
1776
|
-
const parsed =
|
|
1411
|
+
const parsed = parsePdfContentStream(joinedStream, fontMap, {
|
|
1412
|
+
xObjectMap,
|
|
1413
|
+
objects,
|
|
1414
|
+
fontCache,
|
|
1415
|
+
visitedForms: new Set(),
|
|
1416
|
+
depth: 0,
|
|
1417
|
+
});
|
|
1418
|
+
const wordCount = parsed.text.trim() ? parsed.text.trim().split(/\s+/).length : 0;
|
|
1419
|
+
const cjkCount = (parsed.text.match(/[\u4e00-\u9fff]/g) || []).length;
|
|
1777
1420
|
|
|
1778
1421
|
return {
|
|
1779
|
-
|
|
1422
|
+
index: idx + 1,
|
|
1780
1423
|
width: Math.round(width * 100) / 100,
|
|
1781
1424
|
height: Math.round(height * 100) / 100,
|
|
1782
|
-
isLandscape,
|
|
1783
1425
|
text: parsed.text,
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
imageCount: parsed.imageCount,
|
|
1788
|
-
textOpCount: parsed.textOpCount,
|
|
1426
|
+
nonMonoText: parsed.nonMonoText,
|
|
1427
|
+
wordCount,
|
|
1428
|
+
cjkCount,
|
|
1789
1429
|
};
|
|
1790
1430
|
});
|
|
1791
1431
|
|
|
1432
|
+
const fallbackPageCount = pages.length || (latin.match(/\/Type\s*\/Page\b/g) || []).length || 1;
|
|
1792
1433
|
return {
|
|
1793
1434
|
encrypted: false,
|
|
1794
|
-
pageCount:
|
|
1795
|
-
hasFonts,
|
|
1796
|
-
hasCompressedStreams,
|
|
1797
|
-
metadata: { producer, creator },
|
|
1435
|
+
pageCount: fallbackPageCount,
|
|
1798
1436
|
pages,
|
|
1437
|
+
extractedText: pages.map((p) => p.text).filter(Boolean).join("\n\n"),
|
|
1799
1438
|
};
|
|
1800
1439
|
}
|