@inkvero/pdf-tools 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +10 -0
- package/README.md +262 -2
- package/dist/index.d.mts +161 -0
- package/dist/index.mjs +3665 -0
- package/package.json +64 -4
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,3665 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHash } from "node:crypto";
|
|
2
|
+
import { constants, inflateSync } from "node:zlib";
|
|
3
|
+
// src/values.ts
|
|
4
|
+
var PdfName = class {
|
|
5
|
+
/** The name with every `#xx` escape decoded, as a string of byte values (Latin-1). */
|
|
6
|
+
name;
|
|
7
|
+
constructor(name) {
|
|
8
|
+
this.name = name;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
/** A literal or hex string; its bytes are decoded only when they are needed (metadata). */
|
|
12
|
+
var PdfString = class {
|
|
13
|
+
decode;
|
|
14
|
+
constructor(decode) {
|
|
15
|
+
this.decode = decode;
|
|
16
|
+
}
|
|
17
|
+
bytes() {
|
|
18
|
+
return this.decode();
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
/** A word that is not a name, number or keyword of the syntax (`foo`, `{`): pdf.js keeps it as a value. */
|
|
22
|
+
var PdfKeyword = class {
|
|
23
|
+
word;
|
|
24
|
+
constructor(word) {
|
|
25
|
+
this.word = word;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
var PdfRef = class {
|
|
29
|
+
num;
|
|
30
|
+
gen;
|
|
31
|
+
constructor(num, gen) {
|
|
32
|
+
this.num = num;
|
|
33
|
+
this.gen = gen;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
var PdfDict = class {
|
|
37
|
+
/** Every entry in file order, repeated keys included. */
|
|
38
|
+
entries;
|
|
39
|
+
/**
|
|
40
|
+
* For a stream: its data (still encoded), the `/Length` the dictionary declares if it is a number, and
|
|
41
|
+
* where the data starts in the buffer it was read from.
|
|
42
|
+
*/
|
|
43
|
+
stream;
|
|
44
|
+
constructor(entries) {
|
|
45
|
+
this.entries = entries;
|
|
46
|
+
this.stream = void 0;
|
|
47
|
+
}
|
|
48
|
+
/** The last value of `key` (what a reader that keeps one value per key ends up with). */
|
|
49
|
+
get(key) {
|
|
50
|
+
for (let i = this.entries.length - 1; i >= 0; i -= 1) if (this.entries[i][0] === key) return this.entries[i][1];
|
|
51
|
+
}
|
|
52
|
+
/** Every value of `key`. */
|
|
53
|
+
all(key) {
|
|
54
|
+
const out = [];
|
|
55
|
+
for (const [k, v] of this.entries) if (k === key) out.push(v);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
has(key) {
|
|
59
|
+
for (const [k] of this.entries) if (k === key) return true;
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const isName = (v, name) => v instanceof PdfName && (name === void 0 || v.name === name);
|
|
64
|
+
// src/active.ts
|
|
65
|
+
/** The names that decide a kind, each a bit. */
|
|
66
|
+
const BIT = {
|
|
67
|
+
JavaScript: 1,
|
|
68
|
+
Launch: 2,
|
|
69
|
+
URI: 4,
|
|
70
|
+
SubmitForm: 8,
|
|
71
|
+
ImportData: 16,
|
|
72
|
+
GoToR: 32,
|
|
73
|
+
GoToE: 64,
|
|
74
|
+
Sound: 128,
|
|
75
|
+
Movie: 256,
|
|
76
|
+
Rendition: 512,
|
|
77
|
+
RichMediaExecute: 1024,
|
|
78
|
+
RichMedia: 2048,
|
|
79
|
+
"3D": 4096,
|
|
80
|
+
U3D: 8192,
|
|
81
|
+
PRC: 16384,
|
|
82
|
+
Screen: 32768,
|
|
83
|
+
EmbeddedFile: 65536,
|
|
84
|
+
GoTo3DView: 1 << 17,
|
|
85
|
+
Filespec: 1 << 18,
|
|
86
|
+
Annot: 1 << 19
|
|
87
|
+
};
|
|
88
|
+
const MEDIA_ACTIONS = BIT.Sound | BIT.Movie | BIT.Rendition;
|
|
89
|
+
const MEDIA_ANNOTATIONS = BIT.Sound | BIT.Movie | BIT.Screen;
|
|
90
|
+
const THREE_D = BIT["3D"] | BIT.U3D | BIT.PRC;
|
|
91
|
+
/**
|
|
92
|
+
* Action types that are active content. GoTo, Named, Thread, SetOCGState, Hide, Trans and ResetForm only move
|
|
93
|
+
* within the document or change what it shows, and an unknown type does nothing in a reader: none counts.
|
|
94
|
+
*/
|
|
95
|
+
const ACTIVE_ACTIONS = BIT.JavaScript | BIT.Launch | BIT.URI | BIT.SubmitForm | BIT.ImportData | BIT.GoToR | BIT.GoToE | MEDIA_ACTIONS | BIT.RichMediaExecute | BIT.GoTo3DView;
|
|
96
|
+
/** Keys whose value decides whether something is active: a reference there that leads nowhere is counted. */
|
|
97
|
+
const DECIDING = /* @__PURE__ */ new Set([
|
|
98
|
+
"S",
|
|
99
|
+
"A",
|
|
100
|
+
"AA",
|
|
101
|
+
"OpenAction",
|
|
102
|
+
"Next",
|
|
103
|
+
"JS",
|
|
104
|
+
"EF",
|
|
105
|
+
"XFA",
|
|
106
|
+
"AcroForm",
|
|
107
|
+
"RichMediaContent",
|
|
108
|
+
"3DA",
|
|
109
|
+
"FS"
|
|
110
|
+
]);
|
|
111
|
+
/** Keys of a stream dictionary that decide how its data is read. */
|
|
112
|
+
const STRUCTURAL = /* @__PURE__ */ new Set([
|
|
113
|
+
"Length",
|
|
114
|
+
"Filter",
|
|
115
|
+
"DecodeParms",
|
|
116
|
+
"DP",
|
|
117
|
+
"N",
|
|
118
|
+
"First",
|
|
119
|
+
"W",
|
|
120
|
+
"Index",
|
|
121
|
+
"Size",
|
|
122
|
+
"Prev",
|
|
123
|
+
"XRefStm",
|
|
124
|
+
"Extends"
|
|
125
|
+
]);
|
|
126
|
+
const none = () => ({
|
|
127
|
+
mask: 0,
|
|
128
|
+
dict: false,
|
|
129
|
+
nonNull: false,
|
|
130
|
+
unresolved: false,
|
|
131
|
+
dangling: false,
|
|
132
|
+
undecodable: false
|
|
133
|
+
});
|
|
134
|
+
const merge = (a, b) => {
|
|
135
|
+
a.mask |= b.mask;
|
|
136
|
+
a.dict ||= b.dict;
|
|
137
|
+
a.nonNull ||= b.nonNull;
|
|
138
|
+
a.unresolved ||= b.unresolved;
|
|
139
|
+
a.dangling ||= b.dangling;
|
|
140
|
+
a.undecodable ||= b.undecodable;
|
|
141
|
+
};
|
|
142
|
+
const hole = (s) => s.unresolved || s.dangling || s.undecodable;
|
|
143
|
+
const emptyCounts = () => ({
|
|
144
|
+
javascript: 0,
|
|
145
|
+
launch: 0,
|
|
146
|
+
uri: 0,
|
|
147
|
+
submitForm: 0,
|
|
148
|
+
importData: 0,
|
|
149
|
+
embeddedFile: 0,
|
|
150
|
+
xfa: 0,
|
|
151
|
+
richMedia: 0,
|
|
152
|
+
openAction: 0,
|
|
153
|
+
additionalActions: 0,
|
|
154
|
+
goToRemote: 0,
|
|
155
|
+
goToEmbedded: 0,
|
|
156
|
+
media: 0,
|
|
157
|
+
threeD: 0,
|
|
158
|
+
unresolved: 0
|
|
159
|
+
});
|
|
160
|
+
/** Nodes visited between two yields. */
|
|
161
|
+
const STEP = 256;
|
|
162
|
+
/** Counts the active content of every definition the reader holds. */
|
|
163
|
+
function* countActive(reader) {
|
|
164
|
+
const { work } = reader;
|
|
165
|
+
const maxDepth = work.limits.maxDepth;
|
|
166
|
+
const counts = emptyCounts();
|
|
167
|
+
let expanded = 0;
|
|
168
|
+
const tick = () => {
|
|
169
|
+
expanded += 1;
|
|
170
|
+
if ((expanded & 1023) === 0) work.checkpoint();
|
|
171
|
+
};
|
|
172
|
+
const summaries = /* @__PURE__ */ new Map();
|
|
173
|
+
const open = /* @__PURE__ */ new Set();
|
|
174
|
+
const ofRef = (num, depth) => {
|
|
175
|
+
const known = summaries.get(num);
|
|
176
|
+
if (known) return known;
|
|
177
|
+
if (open.has(num) || depth > maxDepth) return {
|
|
178
|
+
...none(),
|
|
179
|
+
unresolved: true
|
|
180
|
+
};
|
|
181
|
+
open.add(num);
|
|
182
|
+
const s = none();
|
|
183
|
+
const defs = reader.definitionsOf(num);
|
|
184
|
+
if (defs.length === 0) s.dangling = true;
|
|
185
|
+
for (const d of defs) {
|
|
186
|
+
tick();
|
|
187
|
+
if (d.undecodable) s.undecodable = true;
|
|
188
|
+
merge(s, ofValue(d.value, depth + 1));
|
|
189
|
+
}
|
|
190
|
+
open.delete(num);
|
|
191
|
+
summaries.set(num, s);
|
|
192
|
+
return s;
|
|
193
|
+
};
|
|
194
|
+
const ofValue = (v, depth) => {
|
|
195
|
+
if (v instanceof PdfRef) return ofRef(v.num, depth);
|
|
196
|
+
if (v === null || v === void 0) return none();
|
|
197
|
+
if (v instanceof PdfName) return {
|
|
198
|
+
...none(),
|
|
199
|
+
mask: BIT[v.name] ?? 0,
|
|
200
|
+
nonNull: true
|
|
201
|
+
};
|
|
202
|
+
return {
|
|
203
|
+
...none(),
|
|
204
|
+
dict: v instanceof PdfDict,
|
|
205
|
+
nonNull: true
|
|
206
|
+
};
|
|
207
|
+
};
|
|
208
|
+
const ofKey = (d, key) => {
|
|
209
|
+
const s = none();
|
|
210
|
+
for (const [k, v] of d.entries) if (k === key) merge(s, ofValue(v, 0));
|
|
211
|
+
return s;
|
|
212
|
+
};
|
|
213
|
+
/** Memoises `ask` per object over every definition of it; a loop or too deep a chain answers `whenOpen`. */
|
|
214
|
+
const memo = (ask, whenOpen) => {
|
|
215
|
+
const known = /* @__PURE__ */ new Map();
|
|
216
|
+
const asking = /* @__PURE__ */ new Set();
|
|
217
|
+
const viaRef = (num, depth) => {
|
|
218
|
+
const k = known.get(num);
|
|
219
|
+
if (k !== void 0) return k;
|
|
220
|
+
if (asking.has(num) || depth > maxDepth) return whenOpen;
|
|
221
|
+
asking.add(num);
|
|
222
|
+
let answer = false;
|
|
223
|
+
for (const d of reader.definitionsOf(num)) {
|
|
224
|
+
tick();
|
|
225
|
+
if (value(d.value, depth + 1)) {
|
|
226
|
+
answer = true;
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
asking.delete(num);
|
|
231
|
+
known.set(num, answer);
|
|
232
|
+
return answer;
|
|
233
|
+
};
|
|
234
|
+
const value = (v, depth) => v instanceof PdfRef ? viaRef(v.num, depth) : ask(v, depth);
|
|
235
|
+
return value;
|
|
236
|
+
};
|
|
237
|
+
/** Whether an action (with its /Next chain) is active: an active type, a script, or a type that cannot be followed. */
|
|
238
|
+
const activeAction = memo((v, depth) => {
|
|
239
|
+
if (Array.isArray(v)) return v.some((x) => activeAction(x, depth + 1));
|
|
240
|
+
if (!(v instanceof PdfDict)) return false;
|
|
241
|
+
const s = ofKey(v, "S");
|
|
242
|
+
if (s.mask & ACTIVE_ACTIONS || hole(s) || v.has("JS")) return true;
|
|
243
|
+
return v.all("Next").some((n) => activeAction(n, depth + 1));
|
|
244
|
+
}, false);
|
|
245
|
+
/** Whether an additional-actions dictionary holds an active action. */
|
|
246
|
+
const activeAA = memo((v) => v instanceof PdfDict && v.entries.some(([, x]) => activeAction(x, 0)), false);
|
|
247
|
+
/** Whether an additional-actions dictionary holds an entry that cannot be followed. */
|
|
248
|
+
const holeInAA = memo((v) => v instanceof PdfDict && v.entries.some(([, x]) => hole(ofValue(x, 0))), true);
|
|
249
|
+
/** Whether a name tree (/JavaScript, /EmbeddedFiles) has a node or value that cannot be followed. */
|
|
250
|
+
const holeInTree = memo((v, depth) => {
|
|
251
|
+
if (!(v instanceof PdfDict)) return false;
|
|
252
|
+
for (const key of ["Kids", "Names"]) for (const list of v.all(key)) {
|
|
253
|
+
const items = list instanceof PdfRef ? [list] : Array.isArray(list) ? list : [];
|
|
254
|
+
for (const x of items) {
|
|
255
|
+
if (hole(ofValue(x, 0))) return true;
|
|
256
|
+
if (key === "Kids" && holeInTree(x, depth + 1)) return true;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return false;
|
|
260
|
+
}, true);
|
|
261
|
+
const files = /* @__PURE__ */ new Set();
|
|
262
|
+
let anonymous = 0;
|
|
263
|
+
const followed = /* @__PURE__ */ new Set();
|
|
264
|
+
const addFiles = (v, depth, key) => {
|
|
265
|
+
if (v instanceof PdfRef) {
|
|
266
|
+
if (followed.has(v.num)) return;
|
|
267
|
+
followed.add(v.num);
|
|
268
|
+
if (depth > maxDepth) {
|
|
269
|
+
files.add(`u${v.num}`);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
reader.definitionsOf(v.num).forEach((d, i) => {
|
|
273
|
+
tick();
|
|
274
|
+
addFiles(d.value, depth + 1, `${v.num}:${i}`);
|
|
275
|
+
});
|
|
276
|
+
} else if (v instanceof PdfDict) v.entries.forEach(([, f], i) => {
|
|
277
|
+
tick();
|
|
278
|
+
if (f === null) return;
|
|
279
|
+
files.add(f instanceof PdfRef ? `n${f.num}` : `a${key}:${i}`);
|
|
280
|
+
});
|
|
281
|
+
else if (v !== null) files.add(`x${key}`);
|
|
282
|
+
};
|
|
283
|
+
const visitDict = (d, owner, c) => {
|
|
284
|
+
const s = ofKey(d, "S");
|
|
285
|
+
const sub = ofKey(d, "Subtype");
|
|
286
|
+
const type = ofKey(d, "Type");
|
|
287
|
+
const S = s.mask;
|
|
288
|
+
if (S & BIT.JavaScript || d.has("JS")) c.javascript += 1;
|
|
289
|
+
if (S & BIT.Launch) c.launch += 1;
|
|
290
|
+
if (S & BIT.URI) c.uri += 1;
|
|
291
|
+
if (S & BIT.SubmitForm) c.submitForm += 1;
|
|
292
|
+
if (S & BIT.ImportData) c.importData += 1;
|
|
293
|
+
if (S & BIT.GoToR) c.goToRemote += 1;
|
|
294
|
+
if (S & BIT.GoToE) c.goToEmbedded += 1;
|
|
295
|
+
if (S & MEDIA_ACTIONS || sub.mask & MEDIA_ANNOTATIONS) c.media += 1;
|
|
296
|
+
if (sub.mask & BIT.RichMedia || S & BIT.RichMediaExecute) c.richMedia += 1;
|
|
297
|
+
if (sub.mask & THREE_D || S & BIT.GoTo3DView || d.has("OnInstantiate")) c.threeD += 1;
|
|
298
|
+
if (d.has("XFA")) c.xfa += 1;
|
|
299
|
+
if (d.has("OpenAction") && d.all("OpenAction").some((v) => activeAction(v, 0))) c.openAction += 1;
|
|
300
|
+
if (d.has("AA") && d.all("AA").some((v) => activeAA(v, 0))) c.additionalActions += 1;
|
|
301
|
+
if (d.stream && type.mask & BIT.EmbeddedFile) files.add(`n${owner.num}`);
|
|
302
|
+
for (const v of d.all("EF")) addFiles(v, 0, `e${anonymous += 1}`);
|
|
303
|
+
const annotation = type.mask & BIT.Annot || d.has("Rect");
|
|
304
|
+
const filespec = type.mask & BIT.Filespec || d.has("EF") || d.has("UF");
|
|
305
|
+
let unresolved = false;
|
|
306
|
+
for (const [k, v] of d.entries) {
|
|
307
|
+
if (v === null || typeof v !== "object") continue;
|
|
308
|
+
if ((DECIDING.has(k) || k === "Subtype" && annotation || k === "F" && filespec || d.stream !== void 0 && STRUCTURAL.has(k)) && hole(ofValue(v, 0))) unresolved = true;
|
|
309
|
+
if (k === "AA" && holeInAA(v, 0)) unresolved = true;
|
|
310
|
+
if ((k === "JavaScript" || k === "EmbeddedFiles") && (hole(ofValue(v, 0)) || holeInTree(v, 0))) unresolved = true;
|
|
311
|
+
}
|
|
312
|
+
if (unresolved) c.unresolved += 1;
|
|
313
|
+
};
|
|
314
|
+
for (const def of reader.defs) if (def.undecodable && !def.container?.undecodable) counts.unresolved += 1;
|
|
315
|
+
counts.unresolved += reader.unreadableEntries() + reader.unaccountedObj + reader.ambiguousObj;
|
|
316
|
+
for (const t of reader.trailerDicts()) for (const key of [
|
|
317
|
+
"Root",
|
|
318
|
+
"Encrypt",
|
|
319
|
+
"Prev",
|
|
320
|
+
"XRefStm"
|
|
321
|
+
]) for (const v of t.all(key)) if (v instanceof PdfRef && hole(ofValue(v, 0))) counts.unresolved += 1;
|
|
322
|
+
const byDefinition = /* @__PURE__ */ new Map();
|
|
323
|
+
let nodes = 0;
|
|
324
|
+
for (const def of reader.defs) {
|
|
325
|
+
yield;
|
|
326
|
+
const c = emptyCounts();
|
|
327
|
+
const stack = [def.value];
|
|
328
|
+
while (stack.length > 0) {
|
|
329
|
+
nodes += 1;
|
|
330
|
+
if (nodes % STEP === 0) yield;
|
|
331
|
+
const v = stack.pop();
|
|
332
|
+
if (Array.isArray(v)) {
|
|
333
|
+
for (const x of v) if (x !== null && typeof x === "object") stack.push(x);
|
|
334
|
+
} else if (v instanceof PdfDict) {
|
|
335
|
+
visitDict(v, def, c);
|
|
336
|
+
for (const [, x] of v.entries) if (x !== null && typeof x === "object") stack.push(x);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
const first = def.alternateOf ? byDefinition.get(def.alternateOf) : void 0;
|
|
340
|
+
for (const k of Object.keys(c)) counts[k] += first ? Math.max(0, c[k] - first[k]) : c[k];
|
|
341
|
+
if (!def.alternateOf) byDefinition.set(def, c);
|
|
342
|
+
}
|
|
343
|
+
counts.embeddedFile = files.size;
|
|
344
|
+
return counts;
|
|
345
|
+
}
|
|
346
|
+
// src/bytes.ts
|
|
347
|
+
/** NUL, TAB, LF, FF, CR, SPACE, and VT, which some readers also take as whitespace. */
|
|
348
|
+
const isWhite = (c) => c === 32 || c === 10 || c === 13 || c === 9 || c === 12 || c === 0 || c === 11;
|
|
349
|
+
/** ( ) < > [ ] { } / % */
|
|
350
|
+
const isDelimiter = (c) => c === 40 || c === 41 || c === 60 || c === 62 || c === 91 || c === 93 || c === 123 || c === 125 || c === 47 || c === 37;
|
|
351
|
+
const isDigit = (c) => c !== void 0 && c >= 48 && c <= 57;
|
|
352
|
+
/** The end of a token: end of data, whitespace or a delimiter. */
|
|
353
|
+
const endsToken = (c) => c === void 0 || isWhite(c) || isDelimiter(c);
|
|
354
|
+
/** The offset after whitespace and comments from `at`. */
|
|
355
|
+
function skipSpace(bytes, at) {
|
|
356
|
+
let i = at;
|
|
357
|
+
for (;;) {
|
|
358
|
+
while (i < bytes.length && isWhite(bytes[i])) i += 1;
|
|
359
|
+
if (bytes[i] !== 37) return i;
|
|
360
|
+
i = commentEnd(bytes, i);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
/** How much of the data one step of a comment search covers. */
|
|
364
|
+
const COMMENT_WINDOW = 65536;
|
|
365
|
+
/**
|
|
366
|
+
* Where the comment at `at` ends: at the first CR or LF, or at the end of the data. The search runs window
|
|
367
|
+
* by window, so it reads no further than the comment: the whole file is read once however many comments it
|
|
368
|
+
* holds.
|
|
369
|
+
*/
|
|
370
|
+
function commentEnd(bytes, at) {
|
|
371
|
+
const near = Math.min(bytes.length, at + 256);
|
|
372
|
+
for (let i = at; i < near; i += 1) if (bytes[i] === 10 || bytes[i] === 13) return i;
|
|
373
|
+
if (near === bytes.length) return near;
|
|
374
|
+
const view = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
375
|
+
for (let w = near; w < view.length; w += COMMENT_WINDOW) {
|
|
376
|
+
const part = view.subarray(w, Math.min(view.length, w + COMMENT_WINDOW));
|
|
377
|
+
const lf = part.indexOf(10);
|
|
378
|
+
const cr = part.indexOf(13);
|
|
379
|
+
if (lf >= 0 || cr >= 0) return w + (lf < 0 ? cr : cr < 0 ? lf : Math.min(lf, cr));
|
|
380
|
+
}
|
|
381
|
+
return view.length;
|
|
382
|
+
}
|
|
383
|
+
/** Whether `word` is at `at`, followed by the end of a token. */
|
|
384
|
+
function keywordAt(bytes, at, word) {
|
|
385
|
+
if (at + word.length > bytes.length) return false;
|
|
386
|
+
for (let k = 0; k < word.length; k += 1) if (bytes[at + k] !== word.charCodeAt(k)) return false;
|
|
387
|
+
return endsToken(bytes[at + word.length]);
|
|
388
|
+
}
|
|
389
|
+
/** A non-negative integer of at most `maxDigits` digits at `at`, or undefined. */
|
|
390
|
+
function intAt(bytes, at, maxDigits) {
|
|
391
|
+
let i = at;
|
|
392
|
+
let value = 0;
|
|
393
|
+
while (i < bytes.length && isDigit(bytes[i])) {
|
|
394
|
+
if (i - at >= maxDigits) return void 0;
|
|
395
|
+
value = value * 10 + (bytes[i] - 48);
|
|
396
|
+
i += 1;
|
|
397
|
+
}
|
|
398
|
+
return i === at ? void 0 : {
|
|
399
|
+
value,
|
|
400
|
+
end: i
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
/** Every offset of `word` in `bytes`, in order. */
|
|
404
|
+
function allOffsets(bytes, word) {
|
|
405
|
+
const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
406
|
+
const out = [];
|
|
407
|
+
for (let i = buffer.indexOf(word, 0, "latin1"); i >= 0; i = buffer.indexOf(word, i + 1, "latin1")) out.push(i);
|
|
408
|
+
return out;
|
|
409
|
+
}
|
|
410
|
+
/** How much of the file one search step covers before it gives way. */
|
|
411
|
+
const WINDOW = 1 << 20;
|
|
412
|
+
/** Every offset of `word` in `bytes`, in order, searched one window at a time with a yield between windows. */
|
|
413
|
+
function* offsetsOf(bytes, word, out) {
|
|
414
|
+
const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
415
|
+
for (let w = 0; w < buffer.length; w += WINDOW) {
|
|
416
|
+
const end = Math.min(buffer.length, w + WINDOW + word.length - 1);
|
|
417
|
+
const view = buffer.subarray(w, end);
|
|
418
|
+
for (let i = view.indexOf(word, 0, "latin1"); i >= 0; i = view.indexOf(word, i + 1, "latin1")) if (out.length === 0 || out[out.length - 1] < w + i) out.push(w + i);
|
|
419
|
+
yield;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
/** The first value in a sorted list that is at least `at`, or undefined. */
|
|
423
|
+
function firstAtLeast(sorted, at) {
|
|
424
|
+
let lo = 0;
|
|
425
|
+
let hi = sorted.length;
|
|
426
|
+
while (lo < hi) {
|
|
427
|
+
const mid = lo + hi >>> 1;
|
|
428
|
+
if (sorted[mid] < at) lo = mid + 1;
|
|
429
|
+
else hi = mid;
|
|
430
|
+
}
|
|
431
|
+
return lo < sorted.length ? sorted[lo] : void 0;
|
|
432
|
+
}
|
|
433
|
+
/** The text of a byte range as Latin-1. */
|
|
434
|
+
const latin1 = (bytes) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
|
|
435
|
+
// src/errors.ts
|
|
436
|
+
/** The error thrown (as a rejection) for every problem this library reports. */
|
|
437
|
+
var PdfToolsError = class extends Error {
|
|
438
|
+
code;
|
|
439
|
+
details;
|
|
440
|
+
constructor(code, message, details = {}) {
|
|
441
|
+
super(message);
|
|
442
|
+
this.name = "PdfToolsError";
|
|
443
|
+
this.code = code;
|
|
444
|
+
this.details = details;
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
/** A `LIMIT_EXCEEDED` error for `limit`. */
|
|
448
|
+
const limitError = (limit, value, what) => new PdfToolsError("LIMIT_EXCEEDED", `${what} (limit ${limit} = ${value})`, {
|
|
449
|
+
limit,
|
|
450
|
+
value
|
|
451
|
+
});
|
|
452
|
+
/** A `DAMAGED` error with a reason from a fixed list. */
|
|
453
|
+
const damaged = (reason, offset) => new PdfToolsError("DAMAGED", `the file is damaged: ${reason}${offset === void 0 ? "" : ` at byte ${offset}`}`, offset === void 0 ? { reason } : {
|
|
454
|
+
reason,
|
|
455
|
+
offset
|
|
456
|
+
});
|
|
457
|
+
// src/crypt.ts
|
|
458
|
+
const concat = (...parts) => new Uint8Array(Buffer.concat(parts));
|
|
459
|
+
const equal = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
460
|
+
const md5 = (data) => new Uint8Array(createHash("md5").update(data).digest());
|
|
461
|
+
const sha = (alg, ...parts) => {
|
|
462
|
+
const h = createHash(alg);
|
|
463
|
+
for (const p of parts) h.update(p);
|
|
464
|
+
return new Uint8Array(h.digest());
|
|
465
|
+
};
|
|
466
|
+
/** RC4 (encryption and decryption are the same). OpenSSL 3 no longer offers it by default. */
|
|
467
|
+
function rc4(key, data) {
|
|
468
|
+
const s = /* @__PURE__ */ new Uint8Array(256);
|
|
469
|
+
for (let i = 0; i < 256; i += 1) s[i] = i;
|
|
470
|
+
for (let i = 0, j = 0; i < 256; i += 1) {
|
|
471
|
+
j = j + s[i] + key[i % key.length] & 255;
|
|
472
|
+
const t = s[i];
|
|
473
|
+
s[i] = s[j];
|
|
474
|
+
s[j] = t;
|
|
475
|
+
}
|
|
476
|
+
const out = new Uint8Array(data.length);
|
|
477
|
+
for (let k = 0, i = 0, j = 0; k < data.length; k += 1) {
|
|
478
|
+
i = i + 1 & 255;
|
|
479
|
+
j = j + s[i] & 255;
|
|
480
|
+
const t = s[i];
|
|
481
|
+
s[i] = s[j];
|
|
482
|
+
s[j] = t;
|
|
483
|
+
out[k] = data[k] ^ s[s[i] + s[j] & 255];
|
|
484
|
+
}
|
|
485
|
+
return out;
|
|
486
|
+
}
|
|
487
|
+
function aesNoPad(encrypt, key, iv, data) {
|
|
488
|
+
const alg = key.length === 32 ? "aes-256-cbc" : "aes-128-cbc";
|
|
489
|
+
const c = encrypt ? createCipheriv(alg, key, iv) : createDecipheriv(alg, key, iv);
|
|
490
|
+
c.setAutoPadding(false);
|
|
491
|
+
return new Uint8Array(Buffer.concat([c.update(data), c.final()]));
|
|
492
|
+
}
|
|
493
|
+
/** PDF AES: a 16-byte IV, then CBC with PKCS#5 padding. Tolerates truncated or badly padded data. */
|
|
494
|
+
function aesDecrypt(key, data) {
|
|
495
|
+
if (data.length < 32) return /* @__PURE__ */ new Uint8Array(0);
|
|
496
|
+
const raw = aesNoPad(false, key, data.subarray(0, 16), data.subarray(16, 16 + Math.floor((data.length - 16) / 16) * 16));
|
|
497
|
+
const p = raw[raw.length - 1];
|
|
498
|
+
return p >= 1 && p <= 16 && raw.subarray(raw.length - p).every((x) => x === p) ? raw.subarray(0, raw.length - p) : raw;
|
|
499
|
+
}
|
|
500
|
+
/** Padding string of Algorithm 2 (7.6.4.3.2). */
|
|
501
|
+
const PASSWORD_PAD = new Uint8Array([
|
|
502
|
+
40,
|
|
503
|
+
191,
|
|
504
|
+
78,
|
|
505
|
+
94,
|
|
506
|
+
78,
|
|
507
|
+
117,
|
|
508
|
+
138,
|
|
509
|
+
65,
|
|
510
|
+
100,
|
|
511
|
+
0,
|
|
512
|
+
78,
|
|
513
|
+
86,
|
|
514
|
+
255,
|
|
515
|
+
250,
|
|
516
|
+
1,
|
|
517
|
+
8,
|
|
518
|
+
46,
|
|
519
|
+
46,
|
|
520
|
+
0,
|
|
521
|
+
182,
|
|
522
|
+
208,
|
|
523
|
+
104,
|
|
524
|
+
62,
|
|
525
|
+
128,
|
|
526
|
+
47,
|
|
527
|
+
12,
|
|
528
|
+
169,
|
|
529
|
+
254,
|
|
530
|
+
100,
|
|
531
|
+
83,
|
|
532
|
+
105,
|
|
533
|
+
122
|
|
534
|
+
]);
|
|
535
|
+
const padPassword = (pw) => concat(pw.subarray(0, 32), PASSWORD_PAD.subarray(0, 32 - Math.min(32, pw.length)));
|
|
536
|
+
const xorKey = (key, x) => key.map((b) => b ^ x);
|
|
537
|
+
/** PDFDocEncoding differs from Latin-1 only in a few places; the rest becomes "?" (revisions 2 to 4). */
|
|
538
|
+
const PDFDOC$1 = {
|
|
539
|
+
"•": 128,
|
|
540
|
+
"†": 129,
|
|
541
|
+
"‡": 130,
|
|
542
|
+
"…": 131,
|
|
543
|
+
"—": 132,
|
|
544
|
+
"–": 133,
|
|
545
|
+
"ƒ": 134,
|
|
546
|
+
"⁄": 135,
|
|
547
|
+
"‹": 136,
|
|
548
|
+
"›": 137,
|
|
549
|
+
"−": 138,
|
|
550
|
+
"‰": 139,
|
|
551
|
+
"„": 140,
|
|
552
|
+
"“": 141,
|
|
553
|
+
"”": 142,
|
|
554
|
+
"‘": 143,
|
|
555
|
+
"’": 144,
|
|
556
|
+
"‚": 145,
|
|
557
|
+
"™": 146,
|
|
558
|
+
"fi": 147,
|
|
559
|
+
"fl": 148,
|
|
560
|
+
"Ł": 149,
|
|
561
|
+
"Œ": 150,
|
|
562
|
+
"Š": 151,
|
|
563
|
+
"Ÿ": 152,
|
|
564
|
+
"Ž": 153,
|
|
565
|
+
"ı": 154,
|
|
566
|
+
"ł": 155,
|
|
567
|
+
"œ": 156,
|
|
568
|
+
"š": 157,
|
|
569
|
+
"ž": 158,
|
|
570
|
+
"€": 160
|
|
571
|
+
};
|
|
572
|
+
/** Password bytes: PDFDocEncoding, at most 32 bytes (R2 to R4); UTF-8 after NFKC (standing in for SASLprep), at most 127 bytes (R5, R6). */
|
|
573
|
+
function passwordBytes(pw, revision) {
|
|
574
|
+
if (revision >= 5) return new Uint8Array(Buffer.from(pw.normalize("NFKC"), "utf8")).subarray(0, 127);
|
|
575
|
+
return Uint8Array.from([...pw].slice(0, 32), (c) => PDFDOC$1[c] ?? (c.charCodeAt(0) < 256 ? c.charCodeAt(0) : 63));
|
|
576
|
+
}
|
|
577
|
+
/** Algorithm 2: the file key from a user password (R2 to R4). `n` is the key length in bytes. */
|
|
578
|
+
function legacyFileKey(pw, o, p, id0, r, n, encryptMetadata) {
|
|
579
|
+
const pb = /* @__PURE__ */ new Uint8Array(4);
|
|
580
|
+
new DataView(pb.buffer).setInt32(0, p, true);
|
|
581
|
+
let h = md5(concat(padPassword(pw), o.subarray(0, 32), pb, id0, r >= 4 && !encryptMetadata ? new Uint8Array([
|
|
582
|
+
255,
|
|
583
|
+
255,
|
|
584
|
+
255,
|
|
585
|
+
255
|
|
586
|
+
]) : /* @__PURE__ */ new Uint8Array(0)));
|
|
587
|
+
if (r >= 3) for (let i = 0; i < 50; i += 1) h = md5(h.subarray(0, n));
|
|
588
|
+
return h.slice(0, r === 2 ? 5 : n);
|
|
589
|
+
}
|
|
590
|
+
/** Algorithms 4 and 5: the /U value for a file key (R2: 32 bytes; R3 and later: the 16 bytes compared). */
|
|
591
|
+
function legacyU(key, r, id0) {
|
|
592
|
+
if (r === 2) return rc4(key, PASSWORD_PAD);
|
|
593
|
+
let x = rc4(key, md5(concat(PASSWORD_PAD, id0)));
|
|
594
|
+
for (let i = 1; i <= 19; i += 1) x = rc4(xorKey(key, i), x);
|
|
595
|
+
return x;
|
|
596
|
+
}
|
|
597
|
+
/** Algorithm 3 steps a to d: the RC4 key made from the owner password. */
|
|
598
|
+
function ownerRc4Key(ownerPw, r, n) {
|
|
599
|
+
let h = md5(padPassword(ownerPw));
|
|
600
|
+
if (r >= 3) for (let i = 0; i < 50; i += 1) h = md5(h.subarray(0, n));
|
|
601
|
+
return h.slice(0, r === 2 ? 5 : n);
|
|
602
|
+
}
|
|
603
|
+
/** Algorithm 7, first half: the padded user password recovered from /O with an owner password. */
|
|
604
|
+
function userFromOwner(ownerPw, o, r, n) {
|
|
605
|
+
const k = ownerRc4Key(ownerPw, r, n);
|
|
606
|
+
let x = o.slice(0, 32);
|
|
607
|
+
if (r === 2) return rc4(k, x);
|
|
608
|
+
for (let i = 19; i >= 0; i -= 1) x = rc4(xorKey(k, i), x);
|
|
609
|
+
return x;
|
|
610
|
+
}
|
|
611
|
+
/** Algorithm 1: the key of one object (RC4 and AES-128). */
|
|
612
|
+
function objectKey(fileKey, num, gen, aes) {
|
|
613
|
+
const b = new Uint8Array([
|
|
614
|
+
num & 255,
|
|
615
|
+
num >> 8 & 255,
|
|
616
|
+
num >> 16 & 255,
|
|
617
|
+
gen & 255,
|
|
618
|
+
gen >> 8 & 255
|
|
619
|
+
]);
|
|
620
|
+
return md5(concat(fileKey, b, aes ? new Uint8Array([
|
|
621
|
+
115,
|
|
622
|
+
65,
|
|
623
|
+
108,
|
|
624
|
+
84
|
|
625
|
+
]) : /* @__PURE__ */ new Uint8Array(0))).subarray(0, Math.min(fileKey.length + 5, 16));
|
|
626
|
+
}
|
|
627
|
+
/** Algorithm 2.B (R6): the hardened hash. `udata` is the 48-byte /U for owner checks, empty for user checks. */
|
|
628
|
+
function hashR6(pw, salt, udata) {
|
|
629
|
+
let k = sha("sha256", pw, salt, udata);
|
|
630
|
+
for (let i = 0;;) {
|
|
631
|
+
const k1 = concat(pw, k, udata);
|
|
632
|
+
const block = new Uint8Array(k1.length * 64);
|
|
633
|
+
for (let j = 0; j < 64; j += 1) block.set(k1, j * k1.length);
|
|
634
|
+
const e = aesNoPad(true, k.subarray(0, 16), k.subarray(16, 32), block);
|
|
635
|
+
let sum = 0;
|
|
636
|
+
for (let j = 0; j < 16; j += 1) sum += e[j];
|
|
637
|
+
k = sha([
|
|
638
|
+
"sha256",
|
|
639
|
+
"sha384",
|
|
640
|
+
"sha512"
|
|
641
|
+
][sum % 3], e);
|
|
642
|
+
i += 1;
|
|
643
|
+
if (i >= 64 && e[e.length - 1] <= i - 32) break;
|
|
644
|
+
}
|
|
645
|
+
return k.slice(0, 32);
|
|
646
|
+
}
|
|
647
|
+
const hashR5 = (pw, salt, udata) => sha("sha256", pw, salt, udata).slice(0, 32);
|
|
648
|
+
const unsupported = (reason, revision) => new PdfToolsError("UNSUPPORTED_SECURITY", `the file is encrypted in a way this library does not read (${reason})`, revision === void 0 ? { reason } : {
|
|
649
|
+
reason,
|
|
650
|
+
revision
|
|
651
|
+
});
|
|
652
|
+
const nameOf = (v) => v instanceof PdfName ? v.name : void 0;
|
|
653
|
+
const numOf = (v) => typeof v === "number" ? v : void 0;
|
|
654
|
+
const bytesOf = (v) => v instanceof PdfString ? v.bytes() : void 0;
|
|
655
|
+
function methodOf(cf, name, resolve) {
|
|
656
|
+
if (!name || name === "Identity") return "none";
|
|
657
|
+
const d = resolve(cf?.get(name));
|
|
658
|
+
const cfm = d instanceof PdfDict ? nameOf(resolve(d.get("CFM"))) ?? "None" : "None";
|
|
659
|
+
if (cfm === "V2") return "rc4";
|
|
660
|
+
if (cfm === "AESV2") return "aes128";
|
|
661
|
+
if (cfm === "AESV3") return "aes256";
|
|
662
|
+
if (cfm === "None") return "none";
|
|
663
|
+
throw unsupported("method");
|
|
664
|
+
}
|
|
665
|
+
/** The revision a file's encryption dictionary declares, for reports. */
|
|
666
|
+
const revisionOf = (enc, resolve) => numOf(resolve(enc.get("R"))) ?? 0;
|
|
667
|
+
/**
|
|
668
|
+
* Opens the standard security handler with `password`; null when the password does not fit. Throws
|
|
669
|
+
* `UNSUPPORTED_SECURITY` for certificate security and for revisions or methods it does not read.
|
|
670
|
+
*/
|
|
671
|
+
function openSecurity(enc, id0, password, resolve) {
|
|
672
|
+
const filter = nameOf(resolve(enc.get("Filter")));
|
|
673
|
+
const r = numOf(resolve(enc.get("R"))) ?? 0;
|
|
674
|
+
if (filter !== "Standard") {
|
|
675
|
+
const certificate = filter === "Adobe.PubSec" || enc.has("Recipients") || /^adbe\.pkcs7/.test(nameOf(resolve(enc.get("SubFilter"))) ?? "");
|
|
676
|
+
throw unsupported(certificate ? "certificate" : "handler", r || void 0);
|
|
677
|
+
}
|
|
678
|
+
const v = numOf(resolve(enc.get("V"))) ?? 0;
|
|
679
|
+
const o = bytesOf(resolve(enc.get("O")));
|
|
680
|
+
const u = bytesOf(resolve(enc.get("U")));
|
|
681
|
+
const p = numOf(resolve(enc.get("P"))) ?? -4;
|
|
682
|
+
const encryptMetadata = resolve(enc.get("EncryptMetadata")) !== false;
|
|
683
|
+
if (![
|
|
684
|
+
1,
|
|
685
|
+
2,
|
|
686
|
+
4,
|
|
687
|
+
5
|
|
688
|
+
].includes(v) || r < 2 || r > 6 || !o || !u) throw unsupported("revision", r);
|
|
689
|
+
const cfValue = resolve(enc.get("CF"));
|
|
690
|
+
const cf = cfValue instanceof PdfDict ? cfValue : void 0;
|
|
691
|
+
let strings;
|
|
692
|
+
let streams;
|
|
693
|
+
let embeddedFiles;
|
|
694
|
+
const filters = /* @__PURE__ */ new Map();
|
|
695
|
+
if (v >= 4) {
|
|
696
|
+
for (const [k] of cf?.entries ?? []) filters.set(k, methodOf(cf, k, resolve));
|
|
697
|
+
strings = methodOf(cf, nameOf(resolve(enc.get("StrF"))), resolve);
|
|
698
|
+
streams = methodOf(cf, nameOf(resolve(enc.get("StmF"))), resolve);
|
|
699
|
+
const eff = nameOf(resolve(enc.get("EFF")));
|
|
700
|
+
embeddedFiles = eff ? methodOf(cf, eff, resolve) : streams;
|
|
701
|
+
} else strings = streams = embeddedFiles = "rc4";
|
|
702
|
+
const pw = passwordBytes(password, r);
|
|
703
|
+
let key = null;
|
|
704
|
+
if (r >= 5) {
|
|
705
|
+
if (o.length < 48 || u.length < 48) throw unsupported("revision", r);
|
|
706
|
+
const hash = r === 6 ? hashR6 : hashR5;
|
|
707
|
+
const ue = bytesOf(resolve(enc.get("UE")));
|
|
708
|
+
const oe = bytesOf(resolve(enc.get("OE")));
|
|
709
|
+
const u48 = u.subarray(0, 48);
|
|
710
|
+
if (oe && oe.length >= 32 && equal(hash(pw, o.subarray(32, 40), u48), o.subarray(0, 32))) key = aesNoPad(false, hash(pw, o.subarray(40, 48), u48), /* @__PURE__ */ new Uint8Array(16), oe.subarray(0, 32));
|
|
711
|
+
else if (ue && ue.length >= 32 && equal(hash(pw, u.subarray(32, 40), /* @__PURE__ */ new Uint8Array(0)), u.subarray(0, 32))) key = aesNoPad(false, hash(pw, u.subarray(40, 48), /* @__PURE__ */ new Uint8Array(0)), /* @__PURE__ */ new Uint8Array(16), ue.subarray(0, 32));
|
|
712
|
+
} else {
|
|
713
|
+
let bits = v === 1 ? 40 : numOf(resolve(enc.get("Length"))) ?? (v === 4 ? 0 : 40);
|
|
714
|
+
if (v === 4 && bits < 40) {
|
|
715
|
+
const std = resolve(cf?.get(nameOf(resolve(enc.get("StmF"))) ?? "StdCF"));
|
|
716
|
+
const l = std instanceof PdfDict ? numOf(resolve(std.get("Length"))) : void 0;
|
|
717
|
+
bits = l ? l <= 32 ? l * 8 : l : 128;
|
|
718
|
+
}
|
|
719
|
+
if (strings === "aes128" || streams === "aes128") bits = 128;
|
|
720
|
+
const n = Math.max(5, Math.min(16, Math.floor(bits / 8)));
|
|
721
|
+
const tryUser = (upw) => {
|
|
722
|
+
const k = legacyFileKey(upw, o, p, id0, r, n, encryptMetadata);
|
|
723
|
+
const check = legacyU(k, r, id0);
|
|
724
|
+
return equal(check, u.subarray(0, check.length === 32 ? 32 : 16)) ? k : null;
|
|
725
|
+
};
|
|
726
|
+
key = tryUser(pw) ?? tryUser(userFromOwner(pw, o, r, n));
|
|
727
|
+
}
|
|
728
|
+
return key && {
|
|
729
|
+
revision: r,
|
|
730
|
+
key,
|
|
731
|
+
strings,
|
|
732
|
+
streams,
|
|
733
|
+
embeddedFiles,
|
|
734
|
+
filters,
|
|
735
|
+
encryptMetadata
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
function crypt(h, method, num, gen, data) {
|
|
739
|
+
switch (method) {
|
|
740
|
+
case "none": return data;
|
|
741
|
+
case "rc4": return rc4(objectKey(h.key, num, gen, false), data);
|
|
742
|
+
case "aes128": return aesDecrypt(objectKey(h.key, num, gen, true), data);
|
|
743
|
+
case "aes256": return aesDecrypt(h.key, data);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
/** A string of object `num gen`, decrypted. */
|
|
747
|
+
const decryptString = (h, num, gen, data) => crypt(h, h.strings, num, gen, data);
|
|
748
|
+
/**
|
|
749
|
+
* The data of stream object `num gen`, decrypted, and the filters still to apply: a leading /Crypt filter
|
|
750
|
+
* chooses the crypt filter and is removed.
|
|
751
|
+
*/
|
|
752
|
+
function decryptStream(h, num, gen, dict, data, names, parms, resolve) {
|
|
753
|
+
const type = nameOf(resolve(dict.get("Type")));
|
|
754
|
+
let method = type === "EmbeddedFile" ? h.embeddedFiles : h.streams;
|
|
755
|
+
if (type === "Metadata" && !h.encryptMetadata) method = "none";
|
|
756
|
+
if (names[0] === "Crypt") {
|
|
757
|
+
const name = nameOf(resolve(parms[0]?.get("Name")));
|
|
758
|
+
method = name && name !== "Identity" ? h.filters.get(name) ?? "none" : "none";
|
|
759
|
+
names = names.slice(1);
|
|
760
|
+
parms = parms.slice(1);
|
|
761
|
+
}
|
|
762
|
+
return {
|
|
763
|
+
data: crypt(h, method, num, gen, data),
|
|
764
|
+
names,
|
|
765
|
+
parms
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
// src/filters.ts
|
|
769
|
+
/** The most filters one stream may chain. */
|
|
770
|
+
const MAX_FILTERS = 8;
|
|
771
|
+
/** Output that stops at the room the budget leaves. */
|
|
772
|
+
var Out = class {
|
|
773
|
+
buf;
|
|
774
|
+
length = 0;
|
|
775
|
+
room;
|
|
776
|
+
limit;
|
|
777
|
+
work;
|
|
778
|
+
constructor(work, guess) {
|
|
779
|
+
const { room, limit } = work.inflateRoom();
|
|
780
|
+
this.room = room;
|
|
781
|
+
this.limit = limit;
|
|
782
|
+
this.work = work;
|
|
783
|
+
this.buf = new Uint8Array(Math.max(16, Math.min(guess, room)));
|
|
784
|
+
}
|
|
785
|
+
grow(need) {
|
|
786
|
+
if (need > this.room) throw limitError(this.limit, this.work.limits[this.limit], "a stream decompresses to too many bytes");
|
|
787
|
+
let size = this.buf.length;
|
|
788
|
+
while (size < need) size *= 2;
|
|
789
|
+
const next = new Uint8Array(Math.min(size, Math.max(need, this.room)));
|
|
790
|
+
next.set(this.buf.subarray(0, this.length));
|
|
791
|
+
this.buf = next;
|
|
792
|
+
}
|
|
793
|
+
push(byte) {
|
|
794
|
+
if (this.length >= this.buf.length) this.grow(this.length + 1);
|
|
795
|
+
this.buf[this.length] = byte;
|
|
796
|
+
this.length += 1;
|
|
797
|
+
}
|
|
798
|
+
/** Repeats `count` bytes starting at `from` of the output so far (LZW). */
|
|
799
|
+
copyWithin(from, count) {
|
|
800
|
+
if (this.length + count > this.buf.length) this.grow(this.length + count);
|
|
801
|
+
this.buf.copyWithin(this.length, from, from + count);
|
|
802
|
+
this.length += count;
|
|
803
|
+
}
|
|
804
|
+
byteAt(i) {
|
|
805
|
+
return this.buf[i];
|
|
806
|
+
}
|
|
807
|
+
done() {
|
|
808
|
+
this.work.inflate(this.length);
|
|
809
|
+
return this.buf.length === this.length ? this.buf : this.buf.slice(0, this.length);
|
|
810
|
+
}
|
|
811
|
+
};
|
|
812
|
+
function inflate(data, work) {
|
|
813
|
+
if (data.length === 0) return data;
|
|
814
|
+
const { room, limit } = work.inflateRoom();
|
|
815
|
+
let out;
|
|
816
|
+
try {
|
|
817
|
+
out = inflateSync(data, {
|
|
818
|
+
maxOutputLength: Math.max(1, room),
|
|
819
|
+
finishFlush: constants.Z_SYNC_FLUSH
|
|
820
|
+
});
|
|
821
|
+
} catch (error) {
|
|
822
|
+
if (error.code === "ERR_BUFFER_TOO_LARGE" || error instanceof RangeError) throw limitError(limit, work.limits[limit], "a stream decompresses to too many bytes");
|
|
823
|
+
throw damaged("compressed data");
|
|
824
|
+
}
|
|
825
|
+
if (out.length > room) throw limitError(limit, work.limits[limit], "a stream decompresses to too many bytes");
|
|
826
|
+
work.inflate(out.length);
|
|
827
|
+
return out.byteOffset === 0 && out.buffer.byteLength === out.length ? new Uint8Array(out.buffer) : new Uint8Array(out);
|
|
828
|
+
}
|
|
829
|
+
function lzw(data, earlyChange, work) {
|
|
830
|
+
const out = new Out(work, data.length * 3);
|
|
831
|
+
const start = /* @__PURE__ */ new Int32Array(4096);
|
|
832
|
+
const size = /* @__PURE__ */ new Int32Array(4096);
|
|
833
|
+
let next = 258;
|
|
834
|
+
let width = 9;
|
|
835
|
+
let previous = -1;
|
|
836
|
+
let acc = 0;
|
|
837
|
+
let bits = 0;
|
|
838
|
+
for (let i = 0; i < data.length; i += 1) {
|
|
839
|
+
acc = (acc << 8 | data[i]) >>> 0;
|
|
840
|
+
bits += 8;
|
|
841
|
+
while (bits >= width) {
|
|
842
|
+
const code = acc >>> bits - width & (1 << width) - 1;
|
|
843
|
+
bits -= width;
|
|
844
|
+
acc &= (1 << bits) - 1;
|
|
845
|
+
if (code === 256) {
|
|
846
|
+
next = 258;
|
|
847
|
+
width = 9;
|
|
848
|
+
previous = -1;
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
851
|
+
if (code === 257) return out.done();
|
|
852
|
+
const at = out.length;
|
|
853
|
+
if (code < 256) out.push(code);
|
|
854
|
+
else if (code < next) out.copyWithin(start[code], size[code]);
|
|
855
|
+
else if (code === next && previous >= 0) {
|
|
856
|
+
if (previous < 256) out.push(previous);
|
|
857
|
+
else out.copyWithin(start[previous], size[previous]);
|
|
858
|
+
out.push(out.byteAt(at));
|
|
859
|
+
} else throw damaged("LZW data");
|
|
860
|
+
if (previous >= 0 && next < 4096) {
|
|
861
|
+
const prevLen = previous < 256 ? 1 : size[previous];
|
|
862
|
+
start[next] = at - prevLen;
|
|
863
|
+
size[next] = prevLen + 1;
|
|
864
|
+
next += 1;
|
|
865
|
+
}
|
|
866
|
+
if (next + earlyChange >= 1 << width && width < 12) width += 1;
|
|
867
|
+
previous = code;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
return out.done();
|
|
871
|
+
}
|
|
872
|
+
function asciiHex(data, work) {
|
|
873
|
+
const out = new Out(work, data.length / 2 + 1);
|
|
874
|
+
let high = -1;
|
|
875
|
+
for (const c of data) {
|
|
876
|
+
if (c === 62) break;
|
|
877
|
+
if (isWhite(c)) continue;
|
|
878
|
+
const v = c >= 48 && c <= 57 ? c - 48 : c >= 65 && c <= 70 ? c - 55 : c >= 97 && c <= 102 ? c - 87 : -1;
|
|
879
|
+
if (v < 0) throw damaged("ASCIIHex data");
|
|
880
|
+
if (high < 0) high = v;
|
|
881
|
+
else {
|
|
882
|
+
out.push(high * 16 + v);
|
|
883
|
+
high = -1;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
if (high >= 0) out.push(high * 16);
|
|
887
|
+
return out.done();
|
|
888
|
+
}
|
|
889
|
+
function ascii85(data, work) {
|
|
890
|
+
const out = new Out(work, data.length);
|
|
891
|
+
const group = [];
|
|
892
|
+
const flush = (count) => {
|
|
893
|
+
let n = 0;
|
|
894
|
+
for (let k = 0; k < 5; k += 1) n = n * 85 + (k < group.length ? group[k] : 84);
|
|
895
|
+
for (let k = 0; k < count; k += 1) out.push(n >>> 24 - 8 * k & 255);
|
|
896
|
+
};
|
|
897
|
+
for (let i = 0; i < data.length; i += 1) {
|
|
898
|
+
const c = data[i];
|
|
899
|
+
if (isWhite(c)) continue;
|
|
900
|
+
if (c === 126) break;
|
|
901
|
+
if (c === 122 && group.length === 0) {
|
|
902
|
+
for (let k = 0; k < 4; k += 1) out.push(0);
|
|
903
|
+
continue;
|
|
904
|
+
}
|
|
905
|
+
if (c < 33 || c > 117) throw damaged("ASCII85 data");
|
|
906
|
+
group.push(c - 33);
|
|
907
|
+
if (group.length === 5) {
|
|
908
|
+
flush(4);
|
|
909
|
+
group.length = 0;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
if (group.length === 1) throw damaged("ASCII85 data");
|
|
913
|
+
if (group.length > 1) flush(group.length - 1);
|
|
914
|
+
return out.done();
|
|
915
|
+
}
|
|
916
|
+
function runLength(data, work) {
|
|
917
|
+
const out = new Out(work, data.length * 2);
|
|
918
|
+
for (let i = 0; i < data.length;) {
|
|
919
|
+
const n = data[i];
|
|
920
|
+
i += 1;
|
|
921
|
+
if (n === 128) break;
|
|
922
|
+
if (n < 128) for (let k = 0; k <= n && i < data.length; k += 1, i += 1) out.push(data[i]);
|
|
923
|
+
else {
|
|
924
|
+
if (i >= data.length) break;
|
|
925
|
+
const b = data[i];
|
|
926
|
+
i += 1;
|
|
927
|
+
for (let k = 0; k < 257 - n; k += 1) out.push(b);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
return out.done();
|
|
931
|
+
}
|
|
932
|
+
const num = (v, fallback) => typeof v === "number" && Number.isSafeInteger(v) ? v : fallback;
|
|
933
|
+
function predict(data, parms, work) {
|
|
934
|
+
if (!parms) return data;
|
|
935
|
+
const predictor = num(parms.get("Predictor"), 1);
|
|
936
|
+
if (predictor <= 1) return data;
|
|
937
|
+
const colors = num(parms.get("Colors"), 1);
|
|
938
|
+
const bpc = num(parms.get("BitsPerComponent"), 8);
|
|
939
|
+
const columns = num(parms.get("Columns"), 1);
|
|
940
|
+
if (colors < 1 || colors > 32 || ![
|
|
941
|
+
1,
|
|
942
|
+
2,
|
|
943
|
+
4,
|
|
944
|
+
8,
|
|
945
|
+
16
|
|
946
|
+
].includes(bpc) || columns < 1 || columns > 1 << 24) throw damaged("predictor");
|
|
947
|
+
const rowBytes = Math.ceil(columns * colors * bpc / 8);
|
|
948
|
+
const bpp = Math.max(1, Math.ceil(colors * bpc / 8));
|
|
949
|
+
if (predictor === 2) {
|
|
950
|
+
if (bpc !== 8) throw damaged("predictor");
|
|
951
|
+
const out = data.slice();
|
|
952
|
+
for (let r = 0; r + rowBytes <= out.length; r += rowBytes) for (let i = colors; i < rowBytes; i += 1) out[r + i] = out[r + i] + out[r + i - colors] & 255;
|
|
953
|
+
work.checkpoint();
|
|
954
|
+
return out;
|
|
955
|
+
}
|
|
956
|
+
if (predictor < 10 || predictor > 15) throw damaged("predictor");
|
|
957
|
+
const rows = Math.floor(data.length / (rowBytes + 1));
|
|
958
|
+
const out = new Uint8Array(rows * rowBytes);
|
|
959
|
+
for (let r = 0; r < rows; r += 1) {
|
|
960
|
+
const type = data[r * (rowBytes + 1)];
|
|
961
|
+
const src = r * (rowBytes + 1) + 1;
|
|
962
|
+
const dst = r * rowBytes;
|
|
963
|
+
for (let i = 0; i < rowBytes; i += 1) {
|
|
964
|
+
const raw = data[src + i];
|
|
965
|
+
const left = i >= bpp ? out[dst + i - bpp] : 0;
|
|
966
|
+
const up = r > 0 ? out[dst - rowBytes + i] : 0;
|
|
967
|
+
const upLeft = r > 0 && i >= bpp ? out[dst - rowBytes + i - bpp] : 0;
|
|
968
|
+
let v;
|
|
969
|
+
switch (type) {
|
|
970
|
+
case 0:
|
|
971
|
+
v = raw;
|
|
972
|
+
break;
|
|
973
|
+
case 1:
|
|
974
|
+
v = raw + left;
|
|
975
|
+
break;
|
|
976
|
+
case 2:
|
|
977
|
+
v = raw + up;
|
|
978
|
+
break;
|
|
979
|
+
case 3:
|
|
980
|
+
v = raw + (left + up >> 1);
|
|
981
|
+
break;
|
|
982
|
+
case 4: {
|
|
983
|
+
const p = left + up - upLeft;
|
|
984
|
+
const pa = Math.abs(p - left);
|
|
985
|
+
const pb = Math.abs(p - up);
|
|
986
|
+
const pc = Math.abs(p - upLeft);
|
|
987
|
+
v = raw + (pa <= pb && pa <= pc ? left : pb <= pc ? up : upLeft);
|
|
988
|
+
break;
|
|
989
|
+
}
|
|
990
|
+
default: throw damaged("predictor");
|
|
991
|
+
}
|
|
992
|
+
out[dst + i] = v & 255;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
work.checkpoint();
|
|
996
|
+
return out;
|
|
997
|
+
}
|
|
998
|
+
/** The filter names and parameters of a stream, resolved. */
|
|
999
|
+
function filtersOf(dict, resolve) {
|
|
1000
|
+
const f = resolve(dict.get("Filter"));
|
|
1001
|
+
const p = resolve(dict.get("DecodeParms") ?? dict.get("DP"));
|
|
1002
|
+
const list = f === null || f === void 0 ? [] : Array.isArray(f) ? f.map((x) => resolve(x)) : [f];
|
|
1003
|
+
if (list.length > MAX_FILTERS) throw damaged("too many filters");
|
|
1004
|
+
const names = list.map((x) => {
|
|
1005
|
+
if (!(x instanceof PdfName)) throw damaged("filter");
|
|
1006
|
+
return x.name;
|
|
1007
|
+
});
|
|
1008
|
+
const plist = Array.isArray(p) ? p.map((x) => resolve(x)) : [p];
|
|
1009
|
+
return {
|
|
1010
|
+
names,
|
|
1011
|
+
parms: names.map((_, i) => {
|
|
1012
|
+
const v = plist[i];
|
|
1013
|
+
return v instanceof PdfDict ? v : void 0;
|
|
1014
|
+
})
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
/** Decodes `data` through `names` (in order), within the budget. */
|
|
1018
|
+
function decode(data, names, parms, work) {
|
|
1019
|
+
let out = data;
|
|
1020
|
+
names.forEach((name, i) => {
|
|
1021
|
+
const parm = parms[i];
|
|
1022
|
+
switch (name) {
|
|
1023
|
+
case "FlateDecode":
|
|
1024
|
+
case "Fl":
|
|
1025
|
+
out = predict(inflate(out, work), parm, work);
|
|
1026
|
+
break;
|
|
1027
|
+
case "LZWDecode":
|
|
1028
|
+
case "LZW":
|
|
1029
|
+
out = predict(lzw(out, num(parm?.get("EarlyChange"), 1) === 0 ? 0 : 1, work), parm, work);
|
|
1030
|
+
break;
|
|
1031
|
+
case "ASCIIHexDecode":
|
|
1032
|
+
case "AHx":
|
|
1033
|
+
out = asciiHex(out, work);
|
|
1034
|
+
break;
|
|
1035
|
+
case "ASCII85Decode":
|
|
1036
|
+
case "A85":
|
|
1037
|
+
out = ascii85(out, work);
|
|
1038
|
+
break;
|
|
1039
|
+
case "RunLengthDecode":
|
|
1040
|
+
case "RL":
|
|
1041
|
+
out = runLength(out, work);
|
|
1042
|
+
break;
|
|
1043
|
+
case "Crypt": {
|
|
1044
|
+
const crypt = parm?.get("Name");
|
|
1045
|
+
if (crypt instanceof PdfName && crypt.name !== "Identity") throw damaged("filter");
|
|
1046
|
+
break;
|
|
1047
|
+
}
|
|
1048
|
+
default: throw damaged("filter");
|
|
1049
|
+
}
|
|
1050
|
+
});
|
|
1051
|
+
return out;
|
|
1052
|
+
}
|
|
1053
|
+
// src/lexer.ts
|
|
1054
|
+
/** The longest number token read in an object header. */
|
|
1055
|
+
/** The longest keyword pdf.js reads; a longer one is an error there. */
|
|
1056
|
+
const MAX_KEYWORD = 128;
|
|
1057
|
+
/** How many bytes a scan reads between two checks of the time limit. */
|
|
1058
|
+
const SCAN_CHECK = 1 << 20;
|
|
1059
|
+
/** A syntax error found while parsing. Its message never holds text from the file. */
|
|
1060
|
+
var ParseError = class extends Error {};
|
|
1061
|
+
const CLASS = /* @__PURE__ */ new Uint8Array(256);
|
|
1062
|
+
for (const c of [
|
|
1063
|
+
0,
|
|
1064
|
+
9,
|
|
1065
|
+
10,
|
|
1066
|
+
12,
|
|
1067
|
+
13,
|
|
1068
|
+
32
|
|
1069
|
+
]) CLASS[c] = 1;
|
|
1070
|
+
for (const c of [
|
|
1071
|
+
40,
|
|
1072
|
+
41,
|
|
1073
|
+
60,
|
|
1074
|
+
62,
|
|
1075
|
+
91,
|
|
1076
|
+
93,
|
|
1077
|
+
123,
|
|
1078
|
+
125,
|
|
1079
|
+
47,
|
|
1080
|
+
37
|
|
1081
|
+
]) CLASS[c] = 2;
|
|
1082
|
+
const CLASS_QPDF = CLASS.slice();
|
|
1083
|
+
CLASS_QPDF[11] = 1;
|
|
1084
|
+
function hexDigit(c) {
|
|
1085
|
+
if (c === void 0) return -1;
|
|
1086
|
+
if (c >= 48 && c <= 57) return c - 48;
|
|
1087
|
+
if (c >= 65 && c <= 70) return c - 55;
|
|
1088
|
+
if (c >= 97 && c <= 102) return c - 87;
|
|
1089
|
+
return -1;
|
|
1090
|
+
}
|
|
1091
|
+
/** The value of a number token as pdf.js reads it (Lexer.getNumber), or NaN when pdf.js would refuse it. */
|
|
1092
|
+
function pdfNumber(bytes, at) {
|
|
1093
|
+
let i = at;
|
|
1094
|
+
let ch = bytes[i];
|
|
1095
|
+
let sign = 1;
|
|
1096
|
+
let divideBy = 0;
|
|
1097
|
+
if (ch === 45) {
|
|
1098
|
+
sign = -1;
|
|
1099
|
+
ch = bytes[++i];
|
|
1100
|
+
if (ch === 45) ch = bytes[++i];
|
|
1101
|
+
} else if (ch === 43) ch = bytes[++i];
|
|
1102
|
+
while (ch === 10 || ch === 13) ch = bytes[++i];
|
|
1103
|
+
if (ch === 46) {
|
|
1104
|
+
divideBy = 10;
|
|
1105
|
+
ch = bytes[++i];
|
|
1106
|
+
}
|
|
1107
|
+
if (ch === void 0 || ch < 48 || ch > 57) {
|
|
1108
|
+
if (ch === void 0 || ch === 32 || ch === 9 || ch === 13 || ch === 10 || ch === 40 || ch === 60) return {
|
|
1109
|
+
value: 0,
|
|
1110
|
+
end: i
|
|
1111
|
+
};
|
|
1112
|
+
return {
|
|
1113
|
+
value: NaN,
|
|
1114
|
+
end: i
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
let value = ch - 48;
|
|
1118
|
+
for (i += 1; i < bytes.length; i += 1) {
|
|
1119
|
+
const c = bytes[i];
|
|
1120
|
+
if (c >= 48 && c <= 57) {
|
|
1121
|
+
if (divideBy !== 0) divideBy *= 10;
|
|
1122
|
+
value = value * 10 + (c - 48);
|
|
1123
|
+
} else if (c === 46) {
|
|
1124
|
+
if (divideBy === 0) divideBy = 1;
|
|
1125
|
+
else break;
|
|
1126
|
+
} else if (c !== 45) break;
|
|
1127
|
+
}
|
|
1128
|
+
if (divideBy !== 0) value /= divideBy;
|
|
1129
|
+
return {
|
|
1130
|
+
value: sign * value,
|
|
1131
|
+
end: i
|
|
1132
|
+
};
|
|
1133
|
+
}
|
|
1134
|
+
/** Whether a byte can start a number token, as pdf.js's lexer reads it. */
|
|
1135
|
+
const isNumberStart = (c) => c !== void 0 && (c >= 48 && c <= 57 || c === 43 || c === 45 || c === 46);
|
|
1136
|
+
/** The bytes of a literal string, decoded as pdf.js decodes them (Lexer.getString). */
|
|
1137
|
+
function decodeString(raw) {
|
|
1138
|
+
const out = [];
|
|
1139
|
+
for (let i = 0; i < raw.length; i += 1) {
|
|
1140
|
+
const c = raw[i];
|
|
1141
|
+
if (c !== 92) {
|
|
1142
|
+
out.push(c);
|
|
1143
|
+
continue;
|
|
1144
|
+
}
|
|
1145
|
+
const e = raw[++i];
|
|
1146
|
+
if (e === void 0) break;
|
|
1147
|
+
switch (e) {
|
|
1148
|
+
case 110:
|
|
1149
|
+
out.push(10);
|
|
1150
|
+
break;
|
|
1151
|
+
case 114:
|
|
1152
|
+
out.push(13);
|
|
1153
|
+
break;
|
|
1154
|
+
case 116:
|
|
1155
|
+
out.push(9);
|
|
1156
|
+
break;
|
|
1157
|
+
case 98:
|
|
1158
|
+
out.push(8);
|
|
1159
|
+
break;
|
|
1160
|
+
case 102:
|
|
1161
|
+
out.push(12);
|
|
1162
|
+
break;
|
|
1163
|
+
case 13:
|
|
1164
|
+
if (raw[i + 1] === 10) i += 1;
|
|
1165
|
+
break;
|
|
1166
|
+
case 10: break;
|
|
1167
|
+
default: if (e >= 48 && e <= 55) {
|
|
1168
|
+
let x = e & 15;
|
|
1169
|
+
if (raw[i + 1] >= 48 && raw[i + 1] <= 55) {
|
|
1170
|
+
x = (x << 3) + (raw[++i] & 15);
|
|
1171
|
+
if (raw[i + 1] >= 48 && raw[i + 1] <= 55) x = (x << 3) + (raw[++i] & 15);
|
|
1172
|
+
}
|
|
1173
|
+
out.push(x & 255);
|
|
1174
|
+
} else out.push(e);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
return new Uint8Array(out);
|
|
1178
|
+
}
|
|
1179
|
+
/** The bytes of a hex string, decoded as pdf.js decodes them: other characters ignored, an odd digit padded. */
|
|
1180
|
+
function decodeHex(raw) {
|
|
1181
|
+
const out = [];
|
|
1182
|
+
let first = -1;
|
|
1183
|
+
for (const c of raw) {
|
|
1184
|
+
const d = hexDigit(c);
|
|
1185
|
+
if (d < 0) continue;
|
|
1186
|
+
if (first < 0) first = d;
|
|
1187
|
+
else {
|
|
1188
|
+
out.push(first << 4 | d);
|
|
1189
|
+
first = -1;
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
if (first >= 0) out.push(first << 4);
|
|
1193
|
+
return new Uint8Array(out);
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* The ends of stream data pdf.js accepts, in order: every `endstream`, and `endsteam` or `endstrea` before SP, HT,
|
|
1197
|
+
* CR or LF. The three lists are sorted and do not overlap (`endstrea` before whitespace is never `endstream`):
|
|
1198
|
+
* merged in one pass.
|
|
1199
|
+
*/
|
|
1200
|
+
function mergeEnds(b, exact, steam, strea) {
|
|
1201
|
+
const whitespace = (c) => c === 32 || c === 9 || c === 13 || c === 10;
|
|
1202
|
+
const s1 = steam.filter((o) => whitespace(b[o + 8]));
|
|
1203
|
+
const s2 = strea.filter((o) => whitespace(b[o + 8]));
|
|
1204
|
+
const out = [];
|
|
1205
|
+
let i = 0;
|
|
1206
|
+
let j = 0;
|
|
1207
|
+
let k = 0;
|
|
1208
|
+
while (i < exact.length || j < s1.length || k < s2.length) {
|
|
1209
|
+
const x = i < exact.length ? exact[i] : 1e400;
|
|
1210
|
+
const y = j < s1.length ? s1[j] : 1e400;
|
|
1211
|
+
const z = k < s2.length ? s2[k] : 1e400;
|
|
1212
|
+
if (x <= y && x <= z) out.push(exact[i++]);
|
|
1213
|
+
else if (y <= z) out.push(s1[j++]);
|
|
1214
|
+
else out.push(s2[k++]);
|
|
1215
|
+
}
|
|
1216
|
+
return out;
|
|
1217
|
+
}
|
|
1218
|
+
const EOF = 0;
|
|
1219
|
+
const NUM = 1;
|
|
1220
|
+
const NAME = 2;
|
|
1221
|
+
const STR = 3;
|
|
1222
|
+
const HEX = 4;
|
|
1223
|
+
const CMD = 5;
|
|
1224
|
+
const LIT = 6;
|
|
1225
|
+
const isCmd = (t, v) => t.k === CMD && t.v === v;
|
|
1226
|
+
/** A parser over one buffer: the file, or the decompressed data of an object stream. */
|
|
1227
|
+
var Lexer = class {
|
|
1228
|
+
bytes;
|
|
1229
|
+
work;
|
|
1230
|
+
pos = 0;
|
|
1231
|
+
buf1;
|
|
1232
|
+
buf2;
|
|
1233
|
+
depth = 0;
|
|
1234
|
+
objectValues = 0;
|
|
1235
|
+
odd = false;
|
|
1236
|
+
/** Whether the value holds syntax pdf.js and qpdf read differently, so that it is read the qpdf way too. */
|
|
1237
|
+
ambiguous = false;
|
|
1238
|
+
/** Read the way qpdf reads: VT is whitespace, dictionary items pair up in order. */
|
|
1239
|
+
qpdf = false;
|
|
1240
|
+
/** How streams are read in this reading (see ReadOptions). */
|
|
1241
|
+
options = {};
|
|
1242
|
+
nestedStream = false;
|
|
1243
|
+
indirectLength = false;
|
|
1244
|
+
lengthCandidates = 0;
|
|
1245
|
+
/** Where the last token used ends. */
|
|
1246
|
+
consumedEnd = 0;
|
|
1247
|
+
cls = CLASS;
|
|
1248
|
+
endstreams;
|
|
1249
|
+
/** Where the string opened by the parenthesis at each offset closes, plus one (0: not known). */
|
|
1250
|
+
closes;
|
|
1251
|
+
/** The last hex string scanned: no `>` lies between its start and its end. */
|
|
1252
|
+
lastHex = {
|
|
1253
|
+
start: -1,
|
|
1254
|
+
end: -1
|
|
1255
|
+
};
|
|
1256
|
+
constructor(bytes, work) {
|
|
1257
|
+
this.bytes = bytes;
|
|
1258
|
+
this.work = work;
|
|
1259
|
+
}
|
|
1260
|
+
/** Points this lexer at another buffer (the data of the next object stream). */
|
|
1261
|
+
reset(bytes) {
|
|
1262
|
+
this.bytes = bytes;
|
|
1263
|
+
this.endstreams = void 0;
|
|
1264
|
+
this.closes = void 0;
|
|
1265
|
+
this.lastHex = {
|
|
1266
|
+
start: -1,
|
|
1267
|
+
end: -1
|
|
1268
|
+
};
|
|
1269
|
+
}
|
|
1270
|
+
token() {
|
|
1271
|
+
const odd = { flag: false };
|
|
1272
|
+
const t = this.readToken(odd);
|
|
1273
|
+
if (odd.flag) t.odd = true;
|
|
1274
|
+
return t;
|
|
1275
|
+
}
|
|
1276
|
+
readToken(odd) {
|
|
1277
|
+
const b = this.bytes;
|
|
1278
|
+
const CLASS = this.cls;
|
|
1279
|
+
let i = this.pos;
|
|
1280
|
+
for (;;) {
|
|
1281
|
+
while (i < b.length && CLASS[b[i]] === 1) i += 1;
|
|
1282
|
+
if (b[i] !== 37) break;
|
|
1283
|
+
const end = commentEnd(b, i);
|
|
1284
|
+
if (end - i >= SCAN_CHECK) this.work.checkpoint();
|
|
1285
|
+
i = end;
|
|
1286
|
+
}
|
|
1287
|
+
const start = i;
|
|
1288
|
+
if (i >= b.length) {
|
|
1289
|
+
this.pos = i;
|
|
1290
|
+
return {
|
|
1291
|
+
k: EOF,
|
|
1292
|
+
start,
|
|
1293
|
+
end: i
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
const ch = b[i];
|
|
1297
|
+
if (ch >= 48 && ch <= 57 || ch === 43 || ch === 45 || ch === 46) {
|
|
1298
|
+
const n = pdfNumber(b, i);
|
|
1299
|
+
this.pos = n.end;
|
|
1300
|
+
if (Number.isNaN(n.value)) {
|
|
1301
|
+
odd.flag = true;
|
|
1302
|
+
return {
|
|
1303
|
+
k: NUM,
|
|
1304
|
+
v: 0,
|
|
1305
|
+
start,
|
|
1306
|
+
end: n.end
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
return {
|
|
1310
|
+
k: NUM,
|
|
1311
|
+
v: n.value,
|
|
1312
|
+
start,
|
|
1313
|
+
end: n.end
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
switch (ch) {
|
|
1317
|
+
case 40: return this.string(i);
|
|
1318
|
+
case 47: return this.name(i);
|
|
1319
|
+
case 91:
|
|
1320
|
+
this.pos = i + 1;
|
|
1321
|
+
return {
|
|
1322
|
+
k: CMD,
|
|
1323
|
+
v: "[",
|
|
1324
|
+
start,
|
|
1325
|
+
end: i + 1
|
|
1326
|
+
};
|
|
1327
|
+
case 93:
|
|
1328
|
+
this.pos = i + 1;
|
|
1329
|
+
return {
|
|
1330
|
+
k: CMD,
|
|
1331
|
+
v: "]",
|
|
1332
|
+
start,
|
|
1333
|
+
end: i + 1
|
|
1334
|
+
};
|
|
1335
|
+
case 60:
|
|
1336
|
+
if (b[i + 1] === 60) {
|
|
1337
|
+
this.pos = i + 2;
|
|
1338
|
+
return {
|
|
1339
|
+
k: CMD,
|
|
1340
|
+
v: "<<",
|
|
1341
|
+
start,
|
|
1342
|
+
end: i + 2
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
return this.hex(i);
|
|
1346
|
+
case 62:
|
|
1347
|
+
if (b[i + 1] === 62) {
|
|
1348
|
+
this.pos = i + 2;
|
|
1349
|
+
return {
|
|
1350
|
+
k: CMD,
|
|
1351
|
+
v: ">>",
|
|
1352
|
+
start,
|
|
1353
|
+
end: i + 2
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
this.pos = i + 1;
|
|
1357
|
+
return {
|
|
1358
|
+
k: CMD,
|
|
1359
|
+
v: ">",
|
|
1360
|
+
start,
|
|
1361
|
+
end: i + 1
|
|
1362
|
+
};
|
|
1363
|
+
case 123:
|
|
1364
|
+
this.pos = i + 1;
|
|
1365
|
+
return {
|
|
1366
|
+
k: CMD,
|
|
1367
|
+
v: "{",
|
|
1368
|
+
start,
|
|
1369
|
+
end: i + 1
|
|
1370
|
+
};
|
|
1371
|
+
case 125:
|
|
1372
|
+
this.pos = i + 1;
|
|
1373
|
+
return {
|
|
1374
|
+
k: CMD,
|
|
1375
|
+
v: "}",
|
|
1376
|
+
start,
|
|
1377
|
+
end: i + 1
|
|
1378
|
+
};
|
|
1379
|
+
case 41:
|
|
1380
|
+
odd.flag = true;
|
|
1381
|
+
this.pos = i + 1;
|
|
1382
|
+
return {
|
|
1383
|
+
k: CMD,
|
|
1384
|
+
v: ")",
|
|
1385
|
+
start,
|
|
1386
|
+
end: i + 1
|
|
1387
|
+
};
|
|
1388
|
+
}
|
|
1389
|
+
if ((ch < 32 || ch > 127) && b[i + 1] >= 32 && b[i + 1] <= 127) {
|
|
1390
|
+
if (ch === 11) this.ambiguous = true;
|
|
1391
|
+
this.pos = i + 1;
|
|
1392
|
+
return {
|
|
1393
|
+
k: CMD,
|
|
1394
|
+
v: String.fromCharCode(ch),
|
|
1395
|
+
start,
|
|
1396
|
+
end: i + 1
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
let j = i + 1;
|
|
1400
|
+
while (j < b.length && CLASS[b[j]] === 0) j += 1;
|
|
1401
|
+
if (!this.qpdf && b.subarray(i, j).includes(11)) this.ambiguous = true;
|
|
1402
|
+
if (j - i > MAX_KEYWORD) odd.flag = true;
|
|
1403
|
+
this.pos = j;
|
|
1404
|
+
const word = latin1(b.subarray(i, Math.min(j, i + MAX_KEYWORD + 1)));
|
|
1405
|
+
if (word === "true") return {
|
|
1406
|
+
k: LIT,
|
|
1407
|
+
v: true,
|
|
1408
|
+
start,
|
|
1409
|
+
end: j
|
|
1410
|
+
};
|
|
1411
|
+
if (word === "false") return {
|
|
1412
|
+
k: LIT,
|
|
1413
|
+
v: false,
|
|
1414
|
+
start,
|
|
1415
|
+
end: j
|
|
1416
|
+
};
|
|
1417
|
+
if (word === "null") return {
|
|
1418
|
+
k: LIT,
|
|
1419
|
+
v: null,
|
|
1420
|
+
start,
|
|
1421
|
+
end: j
|
|
1422
|
+
};
|
|
1423
|
+
return {
|
|
1424
|
+
k: CMD,
|
|
1425
|
+
v: word,
|
|
1426
|
+
start,
|
|
1427
|
+
end: j
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
/** A name, `#xx` escapes decoded as pdf.js decodes them (Lexer.getName). */
|
|
1431
|
+
name(at) {
|
|
1432
|
+
const b = this.bytes;
|
|
1433
|
+
const CLASS = this.cls;
|
|
1434
|
+
const special = (c) => c === void 0 || CLASS[c] !== 0;
|
|
1435
|
+
let i = at + 1;
|
|
1436
|
+
let out = "";
|
|
1437
|
+
while (i < b.length && !special(b[i])) {
|
|
1438
|
+
const c = b[i];
|
|
1439
|
+
i += 1;
|
|
1440
|
+
if (c !== 35) {
|
|
1441
|
+
out += String.fromCharCode(c);
|
|
1442
|
+
continue;
|
|
1443
|
+
}
|
|
1444
|
+
const c1 = b[i];
|
|
1445
|
+
if (special(c1)) {
|
|
1446
|
+
out += "#";
|
|
1447
|
+
break;
|
|
1448
|
+
}
|
|
1449
|
+
const x = hexDigit(c1);
|
|
1450
|
+
if (x < 0) {
|
|
1451
|
+
out += "#" + String.fromCharCode(c1);
|
|
1452
|
+
i += 1;
|
|
1453
|
+
continue;
|
|
1454
|
+
}
|
|
1455
|
+
const c2 = b[i + 1];
|
|
1456
|
+
const x2 = hexDigit(c2);
|
|
1457
|
+
if (x2 < 0) {
|
|
1458
|
+
out += "#" + String.fromCharCode(c1);
|
|
1459
|
+
i += 1;
|
|
1460
|
+
if (special(c2)) break;
|
|
1461
|
+
out += String.fromCharCode(c2);
|
|
1462
|
+
i += 1;
|
|
1463
|
+
continue;
|
|
1464
|
+
}
|
|
1465
|
+
out += String.fromCharCode(x << 4 | x2);
|
|
1466
|
+
i += 2;
|
|
1467
|
+
}
|
|
1468
|
+
if (!this.qpdf && out.includes("\v")) this.ambiguous = true;
|
|
1469
|
+
this.pos = i;
|
|
1470
|
+
return {
|
|
1471
|
+
k: NAME,
|
|
1472
|
+
v: out,
|
|
1473
|
+
start: at,
|
|
1474
|
+
end: i
|
|
1475
|
+
};
|
|
1476
|
+
}
|
|
1477
|
+
/**
|
|
1478
|
+
* A literal string: balanced parentheses, backslash escapes; it may end at the end of data. While it
|
|
1479
|
+
* scans, it notes where every inner parenthesis closes, so that a string that starts at one of them later
|
|
1480
|
+
* (an object header inside this string, read by the header scan) ends without a second scan.
|
|
1481
|
+
*/
|
|
1482
|
+
string(at) {
|
|
1483
|
+
const b = this.bytes;
|
|
1484
|
+
let end = this.closes && this.closes[at] > 0 ? this.closes[at] - 1 : -1;
|
|
1485
|
+
if (end < 0) {
|
|
1486
|
+
const open = [];
|
|
1487
|
+
let checked = at;
|
|
1488
|
+
for (let i = at; i < b.length; i += 1) {
|
|
1489
|
+
const c = b[i];
|
|
1490
|
+
if (c === 92) i += 1;
|
|
1491
|
+
else if (c === 40) open.push(i);
|
|
1492
|
+
else if (c === 41) {
|
|
1493
|
+
const o = open.pop();
|
|
1494
|
+
if (open.length === 0) {
|
|
1495
|
+
end = i;
|
|
1496
|
+
break;
|
|
1497
|
+
}
|
|
1498
|
+
this.closes ??= new Int32Array(b.length + 1);
|
|
1499
|
+
this.closes[o] = i + 1;
|
|
1500
|
+
}
|
|
1501
|
+
if (i - checked >= SCAN_CHECK) {
|
|
1502
|
+
this.work.checkpoint();
|
|
1503
|
+
checked = i;
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
if (end < 0) {
|
|
1507
|
+
this.closes ??= new Int32Array(b.length + 1);
|
|
1508
|
+
for (const o of open) this.closes[o] = b.length + 1;
|
|
1509
|
+
end = b.length;
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
if (end >= b.length) {
|
|
1513
|
+
this.pos = b.length;
|
|
1514
|
+
return {
|
|
1515
|
+
k: STR,
|
|
1516
|
+
a: at + 1,
|
|
1517
|
+
b: b.length,
|
|
1518
|
+
start: at,
|
|
1519
|
+
end: b.length
|
|
1520
|
+
};
|
|
1521
|
+
}
|
|
1522
|
+
this.pos = end + 1;
|
|
1523
|
+
return {
|
|
1524
|
+
k: STR,
|
|
1525
|
+
a: at + 1,
|
|
1526
|
+
b: end,
|
|
1527
|
+
start: at,
|
|
1528
|
+
end: end + 1
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
/** A hex string, up to `>` or the end of data. */
|
|
1532
|
+
hex(at) {
|
|
1533
|
+
const b = this.bytes;
|
|
1534
|
+
let end = at > this.lastHex.start && at < this.lastHex.end ? this.lastHex.end : b.indexOf(62, at + 1);
|
|
1535
|
+
if (end < 0) end = b.length;
|
|
1536
|
+
if (end - at >= SCAN_CHECK) this.work.checkpoint();
|
|
1537
|
+
this.lastHex = {
|
|
1538
|
+
start: at,
|
|
1539
|
+
end
|
|
1540
|
+
};
|
|
1541
|
+
this.pos = Math.min(b.length, end + 1);
|
|
1542
|
+
return {
|
|
1543
|
+
k: HEX,
|
|
1544
|
+
a: at + 1,
|
|
1545
|
+
b: end,
|
|
1546
|
+
start: at,
|
|
1547
|
+
end: this.pos
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
/** Uses up `buf1`. */
|
|
1551
|
+
shift() {
|
|
1552
|
+
if (this.buf1.odd) this.odd = true;
|
|
1553
|
+
this.consumedEnd = this.buf1.end;
|
|
1554
|
+
this.buf1 = this.buf2;
|
|
1555
|
+
this.buf2 = this.token();
|
|
1556
|
+
}
|
|
1557
|
+
refill(at) {
|
|
1558
|
+
this.pos = at;
|
|
1559
|
+
this.buf1 = this.token();
|
|
1560
|
+
this.buf2 = this.token();
|
|
1561
|
+
}
|
|
1562
|
+
enter() {
|
|
1563
|
+
this.depth += 1;
|
|
1564
|
+
if (this.depth > this.work.limits.maxDepth) throw limitError("maxDepth", this.work.limits.maxDepth, "arrays or dictionaries nest too deeply");
|
|
1565
|
+
}
|
|
1566
|
+
countValue() {
|
|
1567
|
+
this.work.value();
|
|
1568
|
+
this.objectValues += 1;
|
|
1569
|
+
if (this.objectValues > this.work.limits.maxObjectValues) throw limitError("maxObjectValues", this.work.limits.maxObjectValues, "an object has too many values");
|
|
1570
|
+
}
|
|
1571
|
+
getObj() {
|
|
1572
|
+
this.countValue();
|
|
1573
|
+
const t = this.buf1;
|
|
1574
|
+
this.shift();
|
|
1575
|
+
switch (t.k) {
|
|
1576
|
+
case EOF:
|
|
1577
|
+
this.odd = true;
|
|
1578
|
+
return null;
|
|
1579
|
+
case NUM:
|
|
1580
|
+
if (Number.isInteger(t.v) && this.buf1.k === NUM && Number.isInteger(this.buf1.v) && isCmd(this.buf2, "R")) {
|
|
1581
|
+
const gen = this.buf1.v;
|
|
1582
|
+
this.shift();
|
|
1583
|
+
this.shift();
|
|
1584
|
+
if (t.v < 0 || gen < 0 || !Number.isSafeInteger(t.v) || !Number.isSafeInteger(gen)) {
|
|
1585
|
+
this.odd = true;
|
|
1586
|
+
return null;
|
|
1587
|
+
}
|
|
1588
|
+
return new PdfRef(t.v, gen);
|
|
1589
|
+
}
|
|
1590
|
+
return t.v;
|
|
1591
|
+
case NAME: return new PdfName(t.v);
|
|
1592
|
+
case STR: {
|
|
1593
|
+
const raw = this.bytes.subarray(t.a, t.b);
|
|
1594
|
+
return new PdfString(() => decodeString(raw));
|
|
1595
|
+
}
|
|
1596
|
+
case HEX: {
|
|
1597
|
+
const raw = this.bytes.subarray(t.a, t.b);
|
|
1598
|
+
return new PdfString(() => decodeHex(raw));
|
|
1599
|
+
}
|
|
1600
|
+
case LIT: return t.v;
|
|
1601
|
+
case CMD:
|
|
1602
|
+
if (t.v === "[") return this.array();
|
|
1603
|
+
if (t.v === "<<") return this.dict();
|
|
1604
|
+
return new PdfKeyword(t.v);
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
array() {
|
|
1608
|
+
this.enter();
|
|
1609
|
+
try {
|
|
1610
|
+
const out = [];
|
|
1611
|
+
while (!isCmd(this.buf1, "]") && this.buf1.k !== EOF) out.push(this.getObj());
|
|
1612
|
+
if (this.buf1.k === EOF) {
|
|
1613
|
+
this.odd = true;
|
|
1614
|
+
return out;
|
|
1615
|
+
}
|
|
1616
|
+
this.shift();
|
|
1617
|
+
return out;
|
|
1618
|
+
} finally {
|
|
1619
|
+
this.depth -= 1;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
dict() {
|
|
1623
|
+
this.enter();
|
|
1624
|
+
try {
|
|
1625
|
+
const entries = [];
|
|
1626
|
+
if (this.qpdf) {
|
|
1627
|
+
const items = [];
|
|
1628
|
+
while (!isCmd(this.buf1, ">>") && this.buf1.k !== EOF) items.push(this.getObj());
|
|
1629
|
+
for (let i = 0; i < items.length; i += 2) {
|
|
1630
|
+
const k = items[i];
|
|
1631
|
+
if (k instanceof PdfName) entries.push([k.name, i + 1 < items.length ? items[i + 1] : null]);
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
while (!this.qpdf && !isCmd(this.buf1, ">>") && this.buf1.k !== EOF) {
|
|
1635
|
+
if (this.buf1.k !== NAME) {
|
|
1636
|
+
this.ambiguous = true;
|
|
1637
|
+
this.countValue();
|
|
1638
|
+
this.shift();
|
|
1639
|
+
continue;
|
|
1640
|
+
}
|
|
1641
|
+
const key = this.buf1.v;
|
|
1642
|
+
this.shift();
|
|
1643
|
+
if (this.buf1.k === EOF) break;
|
|
1644
|
+
if (isCmd(this.buf1, ">>")) this.ambiguous = true;
|
|
1645
|
+
entries.push([key, this.getObj()]);
|
|
1646
|
+
}
|
|
1647
|
+
const d = new PdfDict(entries);
|
|
1648
|
+
if (this.buf1.k === EOF) {
|
|
1649
|
+
this.odd = true;
|
|
1650
|
+
return d;
|
|
1651
|
+
}
|
|
1652
|
+
if (isCmd(this.buf2, "stream")) {
|
|
1653
|
+
const nested = this.depth > 1;
|
|
1654
|
+
if (nested) this.nestedStream = true;
|
|
1655
|
+
if (!(nested && this.options.mode === "noNested")) {
|
|
1656
|
+
this.stream(d);
|
|
1657
|
+
return d;
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
this.shift();
|
|
1661
|
+
return d;
|
|
1662
|
+
} finally {
|
|
1663
|
+
this.depth -= 1;
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
/** The data of a stream whose dictionary just ended: pdf.js Parser.makeStream. */
|
|
1667
|
+
stream(d) {
|
|
1668
|
+
const b = this.bytes;
|
|
1669
|
+
let start = commentEnd(b, this.buf2.end);
|
|
1670
|
+
if (b[start] === 13) start += b[start + 1] === 10 ? 2 : 1;
|
|
1671
|
+
else if (b[start] === 10) start += 1;
|
|
1672
|
+
const declared = d.get("Length");
|
|
1673
|
+
let wanted;
|
|
1674
|
+
if (typeof declared === "number") wanted = declared;
|
|
1675
|
+
else if (declared instanceof PdfRef) {
|
|
1676
|
+
this.indirectLength = true;
|
|
1677
|
+
const candidates = this.options.lengths?.(declared) ?? [];
|
|
1678
|
+
if (candidates.length > 1) this.lengthCandidates = Math.max(this.lengthCandidates, candidates.length);
|
|
1679
|
+
wanted = candidates[this.options.lengthChoice ?? 0];
|
|
1680
|
+
}
|
|
1681
|
+
if (this.options.mode === "first") wanted = void 0;
|
|
1682
|
+
let length = -1;
|
|
1683
|
+
if (wanted !== void 0 && Number.isSafeInteger(wanted) && wanted >= 0 && start + wanted <= b.length) {
|
|
1684
|
+
this.pos = start + wanted;
|
|
1685
|
+
const next = this.token();
|
|
1686
|
+
if (isCmd(next, "endstream")) {
|
|
1687
|
+
length = wanted;
|
|
1688
|
+
this.pos = next.end;
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
if (length < 0) {
|
|
1692
|
+
const at = this.endstreamAt(start);
|
|
1693
|
+
if (at === void 0) {
|
|
1694
|
+
this.odd = true;
|
|
1695
|
+
d.stream = {
|
|
1696
|
+
data: b.subarray(start, start),
|
|
1697
|
+
declaredLength: typeof declared === "number" ? declared : void 0,
|
|
1698
|
+
source: b,
|
|
1699
|
+
start
|
|
1700
|
+
};
|
|
1701
|
+
this.consumedEnd = start;
|
|
1702
|
+
this.refill(start);
|
|
1703
|
+
return;
|
|
1704
|
+
}
|
|
1705
|
+
if (at.offset >= b.length - 9) this.odd = true;
|
|
1706
|
+
length = at.offset - start;
|
|
1707
|
+
this.pos = at.offset;
|
|
1708
|
+
this.pos = this.token().end;
|
|
1709
|
+
}
|
|
1710
|
+
d.stream = {
|
|
1711
|
+
data: b.subarray(start, start + length),
|
|
1712
|
+
declaredLength: typeof declared === "number" ? declared : void 0,
|
|
1713
|
+
source: b,
|
|
1714
|
+
start
|
|
1715
|
+
};
|
|
1716
|
+
this.consumedEnd = this.pos;
|
|
1717
|
+
this.refill(this.pos);
|
|
1718
|
+
}
|
|
1719
|
+
/**
|
|
1720
|
+
* The next end of stream data from `from`, as pdf.js finds it (#findStreamLength): `end` followed by
|
|
1721
|
+
* `stream`, or by `steam` or `strea` and then SP, HT, CR or LF.
|
|
1722
|
+
*/
|
|
1723
|
+
endstreamAt(from) {
|
|
1724
|
+
if (!this.endstreams) {
|
|
1725
|
+
const b = this.bytes;
|
|
1726
|
+
const lists = [
|
|
1727
|
+
"endstream",
|
|
1728
|
+
"endsteam",
|
|
1729
|
+
"endstrea"
|
|
1730
|
+
].map((w) => allOffsets(b, w));
|
|
1731
|
+
this.work.checkpoint();
|
|
1732
|
+
this.endstreams = mergeEnds(b, lists[0], lists[1], lists[2]);
|
|
1733
|
+
}
|
|
1734
|
+
const at = firstAtLeast(this.endstreams, from);
|
|
1735
|
+
return at === void 0 ? void 0 : { offset: at };
|
|
1736
|
+
}
|
|
1737
|
+
/** The ends of stream data in this buffer, found by the caller (the reader finds them while it gives way). */
|
|
1738
|
+
presetEnds(ends) {
|
|
1739
|
+
this.endstreams = ends;
|
|
1740
|
+
}
|
|
1741
|
+
/**
|
|
1742
|
+
* The value at `offset`, how far it reaches, whether pdf.js would give up on it, and, when pdf.js and qpdf
|
|
1743
|
+
* read its syntax differently, the value as qpdf reads it (`alternate`).
|
|
1744
|
+
*/
|
|
1745
|
+
valueAt(offset, options = {}) {
|
|
1746
|
+
const first = this.readValue(offset, false, options);
|
|
1747
|
+
if (!first.ambiguous) return first;
|
|
1748
|
+
const second = this.readValue(offset, true, options);
|
|
1749
|
+
return {
|
|
1750
|
+
...first,
|
|
1751
|
+
alternate: second.value
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
readValue(offset, qpdf, options) {
|
|
1755
|
+
this.depth = 0;
|
|
1756
|
+
this.objectValues = 0;
|
|
1757
|
+
this.odd = false;
|
|
1758
|
+
this.ambiguous = false;
|
|
1759
|
+
this.nestedStream = false;
|
|
1760
|
+
this.indirectLength = false;
|
|
1761
|
+
this.lengthCandidates = 0;
|
|
1762
|
+
this.qpdf = qpdf;
|
|
1763
|
+
this.cls = qpdf ? CLASS_QPDF : CLASS;
|
|
1764
|
+
this.options = options;
|
|
1765
|
+
try {
|
|
1766
|
+
this.refill(offset);
|
|
1767
|
+
return {
|
|
1768
|
+
value: this.getObj(),
|
|
1769
|
+
end: this.buf1.start,
|
|
1770
|
+
valueEnd: this.consumedEnd,
|
|
1771
|
+
odd: this.odd,
|
|
1772
|
+
ambiguous: this.ambiguous,
|
|
1773
|
+
nestedStream: this.nestedStream,
|
|
1774
|
+
indirectLength: this.indirectLength,
|
|
1775
|
+
lengthCandidates: this.lengthCandidates,
|
|
1776
|
+
values: this.objectValues
|
|
1777
|
+
};
|
|
1778
|
+
} finally {
|
|
1779
|
+
this.qpdf = false;
|
|
1780
|
+
this.cls = CLASS;
|
|
1781
|
+
this.options = {};
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
/**
|
|
1785
|
+
* The header `num gen obj` at `offset`, after any whitespace and comments: undefined when there is none.
|
|
1786
|
+
* Each number is read as a number token, as PDF readers do (`+4`, `4.0`, `00004`, `-0`); a header whose
|
|
1787
|
+
* tokens are numbers but not a valid object number and generation has `valid` false.
|
|
1788
|
+
*/
|
|
1789
|
+
headerAt(offset) {
|
|
1790
|
+
const b = this.bytes;
|
|
1791
|
+
const start = skipSpace(b, offset);
|
|
1792
|
+
if (!isNumberStart(b[start])) return void 0;
|
|
1793
|
+
const n = pdfNumber(b, start);
|
|
1794
|
+
if (Number.isNaN(n.value)) return void 0;
|
|
1795
|
+
const at = skipSpace(b, n.end);
|
|
1796
|
+
if (!isNumberStart(b[at])) return void 0;
|
|
1797
|
+
const g = pdfNumber(b, at);
|
|
1798
|
+
if (Number.isNaN(g.value)) return void 0;
|
|
1799
|
+
const o = skipSpace(b, g.end);
|
|
1800
|
+
if (!(b[o] === 111 && b[o + 1] === 98 && b[o + 2] === 106)) return void 0;
|
|
1801
|
+
const next = b[o + 3];
|
|
1802
|
+
if (!(next === void 0 || CLASS[next] !== 0 || next === 11 || isDigit(next))) return void 0;
|
|
1803
|
+
const valid = Number.isSafeInteger(n.value) && n.value >= 0 && Number.isSafeInteger(g.value) && g.value >= 0;
|
|
1804
|
+
return {
|
|
1805
|
+
num: n.value + 0,
|
|
1806
|
+
gen: g.value + 0,
|
|
1807
|
+
start,
|
|
1808
|
+
after: o + 3,
|
|
1809
|
+
valid
|
|
1810
|
+
};
|
|
1811
|
+
}
|
|
1812
|
+
/** The indirect object at `offset`, or undefined when there is no object header there. */
|
|
1813
|
+
objectAt(offset, options = {}) {
|
|
1814
|
+
const header = this.headerAt(offset);
|
|
1815
|
+
if (!header) return void 0;
|
|
1816
|
+
return this.objectWith(header, options);
|
|
1817
|
+
}
|
|
1818
|
+
/** The indirect object whose header is `header` (read or given): the value after its `obj`. */
|
|
1819
|
+
objectWith(header, options = {}) {
|
|
1820
|
+
if (!header.valid) throw new ParseError("object number");
|
|
1821
|
+
const b = this.bytes;
|
|
1822
|
+
const start = skipSpace(b, header.after);
|
|
1823
|
+
const none = {
|
|
1824
|
+
nestedStream: false,
|
|
1825
|
+
indirectLength: false,
|
|
1826
|
+
lengthCandidates: 0,
|
|
1827
|
+
values: 0
|
|
1828
|
+
};
|
|
1829
|
+
const objAt = header.after - 3;
|
|
1830
|
+
if (keywordAt(b, start, "endobj")) return {
|
|
1831
|
+
num: header.num,
|
|
1832
|
+
gen: header.gen,
|
|
1833
|
+
value: null,
|
|
1834
|
+
end: start + 6,
|
|
1835
|
+
endobj: true,
|
|
1836
|
+
odd: false,
|
|
1837
|
+
objAt,
|
|
1838
|
+
...none
|
|
1839
|
+
};
|
|
1840
|
+
if (start >= b.length) return {
|
|
1841
|
+
num: header.num,
|
|
1842
|
+
gen: header.gen,
|
|
1843
|
+
value: null,
|
|
1844
|
+
end: start,
|
|
1845
|
+
endobj: false,
|
|
1846
|
+
odd: false,
|
|
1847
|
+
objAt,
|
|
1848
|
+
...none
|
|
1849
|
+
};
|
|
1850
|
+
const r = this.valueAt(start, options);
|
|
1851
|
+
const after = skipSpace(b, r.end);
|
|
1852
|
+
const endobj = keywordAt(b, after, "endobj");
|
|
1853
|
+
return {
|
|
1854
|
+
num: header.num,
|
|
1855
|
+
gen: header.gen,
|
|
1856
|
+
value: r.value,
|
|
1857
|
+
end: endobj ? after + 6 : Math.max(r.end, start + 1),
|
|
1858
|
+
endobj,
|
|
1859
|
+
odd: r.odd,
|
|
1860
|
+
nestedStream: r.nestedStream,
|
|
1861
|
+
indirectLength: r.indirectLength,
|
|
1862
|
+
lengthCandidates: r.lengthCandidates,
|
|
1863
|
+
values: r.values,
|
|
1864
|
+
objAt,
|
|
1865
|
+
...r.alternate !== void 0 ? { alternate: r.alternate } : {}
|
|
1866
|
+
};
|
|
1867
|
+
}
|
|
1868
|
+
};
|
|
1869
|
+
// src/reader.ts
|
|
1870
|
+
/** Whether `c` can be part of a number token. */
|
|
1871
|
+
const isNumberChar = (c) => isDigit(c) || c === 43 || c === 45 || c === 46;
|
|
1872
|
+
/** The most readings of one `obj` that become definitions; an `obj` with more counts as unresolved. */
|
|
1873
|
+
const MAX_READINGS = 16;
|
|
1874
|
+
const isEol = (c) => c === 10 || c === 13;
|
|
1875
|
+
/** NUL, HT, VT, FF and SP: whitespace for some reader, within a line. */
|
|
1876
|
+
const isLineSpace = (c) => c === 0 || c === 9 || c === 11 || c === 12 || c === 32;
|
|
1877
|
+
/** Offsets of the keywords that start a cross-reference section or trailer (not inside a longer word). */
|
|
1878
|
+
function* keywordOffsets(bytes, out) {
|
|
1879
|
+
const starts = (at) => at === 0 || isWhite(bytes[at - 1]) || isDelimiter(bytes[at - 1]);
|
|
1880
|
+
for (const word of [
|
|
1881
|
+
"xref",
|
|
1882
|
+
"trailer",
|
|
1883
|
+
"startxref"
|
|
1884
|
+
]) {
|
|
1885
|
+
const found = [];
|
|
1886
|
+
yield* offsetsOf(bytes, word, found);
|
|
1887
|
+
for (const at of found) if (starts(at) && endsToken(bytes[at + word.length])) out.push(at);
|
|
1888
|
+
}
|
|
1889
|
+
out.sort((a, b) => a - b);
|
|
1890
|
+
}
|
|
1891
|
+
var Reader = class {
|
|
1892
|
+
bytes;
|
|
1893
|
+
work;
|
|
1894
|
+
headerOffset;
|
|
1895
|
+
lexer;
|
|
1896
|
+
defs = [];
|
|
1897
|
+
defsAt = /* @__PURE__ */ new Map();
|
|
1898
|
+
byNum = /* @__PURE__ */ new Map();
|
|
1899
|
+
tried = /* @__PURE__ */ new Set();
|
|
1900
|
+
sections = [];
|
|
1901
|
+
sectionAt = /* @__PURE__ */ new Map();
|
|
1902
|
+
standaloneTrailers = [];
|
|
1903
|
+
startxrefs = [];
|
|
1904
|
+
readXrefStreamDefs = /* @__PURE__ */ new Set();
|
|
1905
|
+
readObjectStreamDefs = /* @__PURE__ */ new Set();
|
|
1906
|
+
/** How far each step has looked at `defs` and `sections`, so every round only looks at what is new. */
|
|
1907
|
+
xrefCursor = 0;
|
|
1908
|
+
sectionCursor = 0;
|
|
1909
|
+
targetCursor = 0;
|
|
1910
|
+
/** Offsets that lead to a cross-reference section: the last startxref, every /Prev and /XRefStm. */
|
|
1911
|
+
targets = [];
|
|
1912
|
+
targetSeen = /* @__PURE__ */ new Set();
|
|
1913
|
+
trailersRead = /* @__PURE__ */ new Set();
|
|
1914
|
+
firstReading = /* @__PURE__ */ new Map();
|
|
1915
|
+
/** Definitions with a stream whose extent depends on a referenced /Length, or a nested stream. */
|
|
1916
|
+
rereads = [];
|
|
1917
|
+
headers = [];
|
|
1918
|
+
/** Every `obj` that stands as a keyword, in order. */
|
|
1919
|
+
objWords = [];
|
|
1920
|
+
/** Object numbers whose in-use cross-reference entry led to no definition of them. */
|
|
1921
|
+
claimed = /* @__PURE__ */ new Set();
|
|
1922
|
+
/** Where the `obj` of every definition read with its header is: those are accounted for. */
|
|
1923
|
+
objOfDefinitions = /* @__PURE__ */ new Set();
|
|
1924
|
+
/** The byte ranges the sequence of objects skipped as junk, in order. */
|
|
1925
|
+
junk = [];
|
|
1926
|
+
/** `obj` keywords not accounted for that may begin an object a reader reads (see classifyObjWords). */
|
|
1927
|
+
unaccountedObj = 0;
|
|
1928
|
+
/** Readings of headers from the backward enumeration, read as definitions by readScannedHeaders. */
|
|
1929
|
+
readings = [];
|
|
1930
|
+
/** `obj` keywords whose header has more than one reading, or a `%` among its lines: each counts. */
|
|
1931
|
+
ambiguousObj = 0;
|
|
1932
|
+
/** (objAt, num, gen) of every definition read with its header, for the `obj` keywords in `readings`. */
|
|
1933
|
+
readKeys = /* @__PURE__ */ new Set();
|
|
1934
|
+
readingObjs = /* @__PURE__ */ new Set();
|
|
1935
|
+
keywords = [];
|
|
1936
|
+
entries = /* @__PURE__ */ new Map();
|
|
1937
|
+
/** One lexer for the data of every object stream, pointed at each in turn. */
|
|
1938
|
+
streamLexer;
|
|
1939
|
+
chainLength = 0;
|
|
1940
|
+
chainBroken = false;
|
|
1941
|
+
inForceCache = /* @__PURE__ */ new Map();
|
|
1942
|
+
/** Object numbers that have a definition which could not be parsed. */
|
|
1943
|
+
undecodable = /* @__PURE__ */ new Set();
|
|
1944
|
+
repaired = false;
|
|
1945
|
+
objectStreams = false;
|
|
1946
|
+
xrefStreams = false;
|
|
1947
|
+
trailer = {};
|
|
1948
|
+
security;
|
|
1949
|
+
encryptNum;
|
|
1950
|
+
constructor(bytes, work, headerOffset) {
|
|
1951
|
+
this.bytes = bytes;
|
|
1952
|
+
this.work = work;
|
|
1953
|
+
this.headerOffset = headerOffset;
|
|
1954
|
+
this.lexer = new Lexer(bytes, work);
|
|
1955
|
+
}
|
|
1956
|
+
addDefinition(d) {
|
|
1957
|
+
this.defs.push(d);
|
|
1958
|
+
this.inForceCache.delete(d.num);
|
|
1959
|
+
let list = this.byNum.get(d.num);
|
|
1960
|
+
if (!list) this.byNum.set(d.num, list = []);
|
|
1961
|
+
list.push(d);
|
|
1962
|
+
}
|
|
1963
|
+
addParsed(parsed, offset, hidden, keyed = true) {
|
|
1964
|
+
this.objOfDefinitions.add(parsed.objAt);
|
|
1965
|
+
if (this.readingObjs.has(parsed.objAt)) this.readKeys.add(`${parsed.objAt}:${parsed.num}:${parsed.gen}`);
|
|
1966
|
+
const d = {
|
|
1967
|
+
num: parsed.num,
|
|
1968
|
+
gen: parsed.gen,
|
|
1969
|
+
value: parsed.value,
|
|
1970
|
+
offset,
|
|
1971
|
+
order: offset,
|
|
1972
|
+
hidden
|
|
1973
|
+
};
|
|
1974
|
+
if (parsed.odd) {
|
|
1975
|
+
d.undecodable = true;
|
|
1976
|
+
this.undecodable.add(parsed.num);
|
|
1977
|
+
this.repaired = true;
|
|
1978
|
+
}
|
|
1979
|
+
if (parsed.nestedStream) {
|
|
1980
|
+
d.undecodable = true;
|
|
1981
|
+
this.undecodable.add(parsed.num);
|
|
1982
|
+
}
|
|
1983
|
+
if (parsed.nestedStream || parsed.indirectLength) this.rereads.push(d);
|
|
1984
|
+
if (keyed || !this.defsAt.has(offset)) this.defsAt.set(offset, d);
|
|
1985
|
+
this.addDefinition(d);
|
|
1986
|
+
if (parsed.alternate !== void 0) this.addDefinition({
|
|
1987
|
+
...d,
|
|
1988
|
+
value: parsed.alternate,
|
|
1989
|
+
hidden: true,
|
|
1990
|
+
undecodable: false,
|
|
1991
|
+
alternateOf: d
|
|
1992
|
+
});
|
|
1993
|
+
const s = parsed.value instanceof PdfDict ? parsed.value.stream : void 0;
|
|
1994
|
+
if (s && s.declaredLength !== void 0 && s.declaredLength !== s.data.length) this.repaired = true;
|
|
1995
|
+
}
|
|
1996
|
+
addUndecodable(header, offset, hidden, keyed = true) {
|
|
1997
|
+
this.objOfDefinitions.add(header.after - 3);
|
|
1998
|
+
if (this.readingObjs.has(header.after - 3)) this.readKeys.add(`${header.after - 3}:${header.num}:${header.gen}`);
|
|
1999
|
+
const d = {
|
|
2000
|
+
num: header.num,
|
|
2001
|
+
gen: header.gen,
|
|
2002
|
+
value: null,
|
|
2003
|
+
offset,
|
|
2004
|
+
order: offset,
|
|
2005
|
+
hidden,
|
|
2006
|
+
undecodable: true
|
|
2007
|
+
};
|
|
2008
|
+
if (keyed || !this.defsAt.has(offset)) this.defsAt.set(offset, d);
|
|
2009
|
+
this.addDefinition(d);
|
|
2010
|
+
this.undecodable.add(header.num);
|
|
2011
|
+
this.repaired = true;
|
|
2012
|
+
}
|
|
2013
|
+
/**
|
|
2014
|
+
* For each `obj` that stands as a keyword (followed by a delimiter, whitespace, a digit or the end of data;
|
|
2015
|
+
* preceded by whitespace, a number character or a delimiter), every reading of the bytes before it as
|
|
2016
|
+
* `<number> [separators] <number> [separators] obj`, without choosing a tokenisation: separators are
|
|
2017
|
+
* whitespace and comments, and a comment may start at any `%` (so a number after a `%` may be a token, or
|
|
2018
|
+
* comment content). Every number start is read forwards by the lexer, exactly as pdf.js tokenises, and kept
|
|
2019
|
+
* in `starts` when it reaches this `obj`; every reading is also kept for readScannedHeaders, which reads the
|
|
2020
|
+
* value after `obj` under each number. An `obj` with more than one reading, or with a `%` on the lines its
|
|
2021
|
+
* header spans, counts as ambiguous. See docs/syntax.md, "Which number a header defines".
|
|
2022
|
+
*
|
|
2023
|
+
* Cost: the walk from an `obj` goes back over its own line and up over lines that may be only separators
|
|
2024
|
+
* (blank, or whose first byte that is not whitespace is `%`) to the first that may not; that line holds an
|
|
2025
|
+
* `obj` of no other walk, so every byte is walked a bounded number of times, and the readings are capped.
|
|
2026
|
+
*/
|
|
2027
|
+
*headerReadings(starts) {
|
|
2028
|
+
const b = this.bytes;
|
|
2029
|
+
const found = [];
|
|
2030
|
+
yield* offsetsOf(b, "obj", found);
|
|
2031
|
+
const last = [
|
|
2032
|
+
-1,
|
|
2033
|
+
-1,
|
|
2034
|
+
-1
|
|
2035
|
+
];
|
|
2036
|
+
const nextOf = [
|
|
2037
|
+
10,
|
|
2038
|
+
13,
|
|
2039
|
+
37
|
|
2040
|
+
].map((c) => b.indexOf(c));
|
|
2041
|
+
const lastBefore = (k, at) => {
|
|
2042
|
+
const c = [
|
|
2043
|
+
10,
|
|
2044
|
+
13,
|
|
2045
|
+
37
|
|
2046
|
+
][k];
|
|
2047
|
+
while (nextOf[k] >= 0 && nextOf[k] < at) {
|
|
2048
|
+
last[k] = nextOf[k];
|
|
2049
|
+
nextOf[k] = b.indexOf(c, nextOf[k] + 1);
|
|
2050
|
+
}
|
|
2051
|
+
return last[k];
|
|
2052
|
+
};
|
|
2053
|
+
let seen = 0;
|
|
2054
|
+
for (const at of found) {
|
|
2055
|
+
if ((seen += 1) % 4096 === 0) {
|
|
2056
|
+
this.work.checkpoint();
|
|
2057
|
+
yield;
|
|
2058
|
+
}
|
|
2059
|
+
const next = b[at + 3];
|
|
2060
|
+
if (!(next === void 0 || endsToken(next) || isDigit(next))) continue;
|
|
2061
|
+
const before = b[at - 1];
|
|
2062
|
+
if (!(at === 0 || isWhite(before) || isNumberChar(before) || isDelimiter(before))) continue;
|
|
2063
|
+
this.objWords.push(at);
|
|
2064
|
+
let j = at - 1;
|
|
2065
|
+
let triedAt = -1;
|
|
2066
|
+
let tried;
|
|
2067
|
+
for (let runs = 0; runs < 2 && j >= 0; runs += 1) {
|
|
2068
|
+
while (j >= 0 && isWhite(b[j])) j -= 1;
|
|
2069
|
+
const end = j;
|
|
2070
|
+
while (j >= 0 && isNumberChar(b[j])) j -= 1;
|
|
2071
|
+
if (j === end) break;
|
|
2072
|
+
const h = this.lexer.headerAt(j + 1);
|
|
2073
|
+
triedAt = j + 1;
|
|
2074
|
+
tried = h;
|
|
2075
|
+
if (h && h.after === at + 3 && starts[starts.length - 1] !== h.start) starts.push(h.start);
|
|
2076
|
+
}
|
|
2077
|
+
const { list, pct, over } = this.readingsOf(at);
|
|
2078
|
+
if (list.length === 0) continue;
|
|
2079
|
+
let others;
|
|
2080
|
+
for (const r of list) {
|
|
2081
|
+
const h = r.start === triedAt ? tried : this.lexer.headerAt(r.start);
|
|
2082
|
+
const confirmed = h !== void 0 && h.after === at + 3 && h.num === r.num && h.gen === r.gen;
|
|
2083
|
+
if (h && h.after === at + 3 && starts[starts.length - 1] !== h.start) starts.push(h.start);
|
|
2084
|
+
if (!confirmed) (others ??= []).push(r);
|
|
2085
|
+
}
|
|
2086
|
+
if (others) {
|
|
2087
|
+
this.readings.push({
|
|
2088
|
+
objAt: at,
|
|
2089
|
+
list: others
|
|
2090
|
+
});
|
|
2091
|
+
this.readingObjs.add(at);
|
|
2092
|
+
}
|
|
2093
|
+
let percent = pct;
|
|
2094
|
+
if (!percent) percent = lastBefore(2, at) > Math.max(lastBefore(0, at), lastBefore(1, at));
|
|
2095
|
+
let distinct = false;
|
|
2096
|
+
for (const r of list) if (r.num !== list[0].num || r.gen !== list[0].gen) distinct = true;
|
|
2097
|
+
if (distinct || percent || over) {
|
|
2098
|
+
this.ambiguousObj += 1;
|
|
2099
|
+
for (let i = 1; i < list.length; i += 1) this.work.object();
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
/** The readings of the header before the `obj` at `at`, whether a `%` was on the lines walked, and whether the cap was hit. */
|
|
2104
|
+
readingsOf(at) {
|
|
2105
|
+
const b = this.bytes;
|
|
2106
|
+
const list = [];
|
|
2107
|
+
let pct = false;
|
|
2108
|
+
let over = false;
|
|
2109
|
+
const gens = [];
|
|
2110
|
+
let k = at - 1;
|
|
2111
|
+
while (k >= 0 && isLineSpace(b[k])) k -= 1;
|
|
2112
|
+
if (k >= 0 && isNumberChar(b[k])) gens.push(this.runEndingAt(k));
|
|
2113
|
+
else if (k < 0 || isEol(b[k])) {
|
|
2114
|
+
const w = this.walkUp(k + 1, gens);
|
|
2115
|
+
pct ||= w.pct;
|
|
2116
|
+
over ||= w.over;
|
|
2117
|
+
}
|
|
2118
|
+
for (const g of gens) {
|
|
2119
|
+
const gt = this.lastTokens(g);
|
|
2120
|
+
if (gt.length === 0) continue;
|
|
2121
|
+
const gen = gt[gt.length - 1];
|
|
2122
|
+
const nums = [];
|
|
2123
|
+
if (gt.length >= 2) nums.push(gt[gt.length - 2]);
|
|
2124
|
+
else {
|
|
2125
|
+
const runs = [];
|
|
2126
|
+
let j = g.start - 1;
|
|
2127
|
+
while (j >= 0 && isLineSpace(b[j])) j -= 1;
|
|
2128
|
+
if (j >= 0 && isNumberChar(b[j])) runs.push(this.runEndingAt(j));
|
|
2129
|
+
else if (j < 0 || isEol(b[j])) {
|
|
2130
|
+
const w = this.walkUp(j + 1, runs);
|
|
2131
|
+
pct ||= w.pct;
|
|
2132
|
+
over ||= w.over;
|
|
2133
|
+
}
|
|
2134
|
+
for (const r of runs) {
|
|
2135
|
+
const t = this.lastTokens(r);
|
|
2136
|
+
if (t.length > 0) nums.push(t[t.length - 1]);
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
for (const n of nums) {
|
|
2140
|
+
if (!(Number.isSafeInteger(n.value) && n.value >= 0 && Number.isSafeInteger(gen.value) && gen.value >= 0)) continue;
|
|
2141
|
+
let dup = false;
|
|
2142
|
+
for (const r of list) if (r.num === n.value && r.gen === gen.value && r.start === n.start) dup = true;
|
|
2143
|
+
if (dup) continue;
|
|
2144
|
+
if (list.length >= MAX_READINGS) {
|
|
2145
|
+
over = true;
|
|
2146
|
+
break;
|
|
2147
|
+
}
|
|
2148
|
+
list.push({
|
|
2149
|
+
num: n.value + 0,
|
|
2150
|
+
gen: gen.value + 0,
|
|
2151
|
+
start: n.start
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
return {
|
|
2156
|
+
list,
|
|
2157
|
+
pct,
|
|
2158
|
+
over
|
|
2159
|
+
};
|
|
2160
|
+
}
|
|
2161
|
+
/** The run of number characters that ends at `k` (inclusive). */
|
|
2162
|
+
runEndingAt(k) {
|
|
2163
|
+
let s = k;
|
|
2164
|
+
while (s > 0 && isNumberChar(this.bytes[s - 1])) s -= 1;
|
|
2165
|
+
return {
|
|
2166
|
+
start: s,
|
|
2167
|
+
end: k + 1
|
|
2168
|
+
};
|
|
2169
|
+
}
|
|
2170
|
+
/** The last two number tokens of a run, as pdf.js splits it (`+4+0` is 4 then 0). */
|
|
2171
|
+
lastTokens(r) {
|
|
2172
|
+
const out = [];
|
|
2173
|
+
let i = r.start;
|
|
2174
|
+
while (i < r.end) {
|
|
2175
|
+
const n = pdfNumber(this.bytes, i);
|
|
2176
|
+
if (n.end <= i) break;
|
|
2177
|
+
if (!Number.isNaN(n.value)) {
|
|
2178
|
+
out.push({
|
|
2179
|
+
value: n.value,
|
|
2180
|
+
start: i
|
|
2181
|
+
});
|
|
2182
|
+
if (out.length > 2) out.shift();
|
|
2183
|
+
}
|
|
2184
|
+
i = n.end;
|
|
2185
|
+
}
|
|
2186
|
+
return out;
|
|
2187
|
+
}
|
|
2188
|
+
/**
|
|
2189
|
+
* The lines above the line that starts at `lineStart`: on each, every number run followed by only whitespace
|
|
2190
|
+
* up to the line end or up to some `%` (a number that may end the line) goes to `out`; the walk goes on while
|
|
2191
|
+
* the line may be only separators and stops after the first line that may not.
|
|
2192
|
+
*/
|
|
2193
|
+
walkUp(lineStart, out) {
|
|
2194
|
+
const b = this.bytes;
|
|
2195
|
+
let pct = false;
|
|
2196
|
+
let over = false;
|
|
2197
|
+
const mid = [];
|
|
2198
|
+
const top = [];
|
|
2199
|
+
let end = lineStart - 1;
|
|
2200
|
+
while (end >= 0) {
|
|
2201
|
+
let s = end;
|
|
2202
|
+
while (s > 0 && !isEol(b[s - 1])) s -= 1;
|
|
2203
|
+
let first = -1;
|
|
2204
|
+
const line = [];
|
|
2205
|
+
for (let i = s; i < end;) {
|
|
2206
|
+
const c = b[i];
|
|
2207
|
+
if (first < 0 && !isLineSpace(c)) first = c;
|
|
2208
|
+
if (c === 37) pct = true;
|
|
2209
|
+
if (isNumberChar(c)) {
|
|
2210
|
+
const rs = i;
|
|
2211
|
+
while (i < end && isNumberChar(b[i])) i += 1;
|
|
2212
|
+
let q = i;
|
|
2213
|
+
while (q < end && isLineSpace(b[q])) q += 1;
|
|
2214
|
+
if (q === end || b[q] === 37) {
|
|
2215
|
+
if (line.length < MAX_READINGS) line.push({
|
|
2216
|
+
start: rs,
|
|
2217
|
+
end: i
|
|
2218
|
+
});
|
|
2219
|
+
else over = true;
|
|
2220
|
+
}
|
|
2221
|
+
continue;
|
|
2222
|
+
}
|
|
2223
|
+
i += 1;
|
|
2224
|
+
}
|
|
2225
|
+
if (!(first < 0 || first === 37)) {
|
|
2226
|
+
top.push(...line);
|
|
2227
|
+
break;
|
|
2228
|
+
}
|
|
2229
|
+
for (const r of line) if (mid.length < MAX_READINGS) mid.push(r);
|
|
2230
|
+
else over = true;
|
|
2231
|
+
end = s - 1;
|
|
2232
|
+
}
|
|
2233
|
+
out.push(...top, ...mid.reverse());
|
|
2234
|
+
return {
|
|
2235
|
+
pct,
|
|
2236
|
+
over
|
|
2237
|
+
};
|
|
2238
|
+
}
|
|
2239
|
+
/** Finds every object header and structure keyword in the file (the scan gives way as it goes). */
|
|
2240
|
+
*scan() {
|
|
2241
|
+
const starts = [];
|
|
2242
|
+
yield* this.headerReadings(starts);
|
|
2243
|
+
yield;
|
|
2244
|
+
starts.sort((a, b) => a - b);
|
|
2245
|
+
for (let i = 0; i < starts.length; i += 1) if (i === 0 || starts[i] !== starts[i - 1]) this.headers.push(starts[i]);
|
|
2246
|
+
const ends = [
|
|
2247
|
+
[],
|
|
2248
|
+
[],
|
|
2249
|
+
[]
|
|
2250
|
+
];
|
|
2251
|
+
const words = [
|
|
2252
|
+
"endstream",
|
|
2253
|
+
"endsteam",
|
|
2254
|
+
"endstrea"
|
|
2255
|
+
];
|
|
2256
|
+
for (let w = 0; w < 3; w += 1) yield* offsetsOf(this.bytes, words[w], ends[w]);
|
|
2257
|
+
yield;
|
|
2258
|
+
this.lexer.presetEnds(mergeEnds(this.bytes, ends[0], ends[1], ends[2]));
|
|
2259
|
+
yield;
|
|
2260
|
+
yield* keywordOffsets(this.bytes, this.keywords);
|
|
2261
|
+
}
|
|
2262
|
+
/** Reads the file front to back. An object that does not parse is `DAMAGED`; junk between objects is skipped. */
|
|
2263
|
+
*walk() {
|
|
2264
|
+
const { bytes } = this;
|
|
2265
|
+
let pos = this.headerOffset;
|
|
2266
|
+
while (pos < bytes.length) {
|
|
2267
|
+
yield;
|
|
2268
|
+
pos = skipSpace(bytes, pos);
|
|
2269
|
+
if (pos >= bytes.length) break;
|
|
2270
|
+
const header = isNumberChar(bytes[pos]) ? this.lexer.headerAt(pos) : void 0;
|
|
2271
|
+
if (header) {
|
|
2272
|
+
if (!header.valid) throw damaged("an object header has no valid object number", pos);
|
|
2273
|
+
this.work.object();
|
|
2274
|
+
this.tried.add(pos);
|
|
2275
|
+
let parsed;
|
|
2276
|
+
try {
|
|
2277
|
+
parsed = this.lexer.objectAt(pos);
|
|
2278
|
+
} catch (error) {
|
|
2279
|
+
if (error instanceof PdfToolsError) throw error;
|
|
2280
|
+
this.addUndecodable(header, pos, false);
|
|
2281
|
+
pos = Math.min(firstAtLeast(this.headers, pos + 1) ?? 1e400, firstAtLeast(this.keywords, pos + 1) ?? 1e400);
|
|
2282
|
+
if (pos === 1e400) break;
|
|
2283
|
+
continue;
|
|
2284
|
+
}
|
|
2285
|
+
this.addParsed(parsed, pos, false);
|
|
2286
|
+
if (!parsed.endobj) this.repaired = true;
|
|
2287
|
+
pos = Math.max(parsed.end, pos + 1);
|
|
2288
|
+
continue;
|
|
2289
|
+
}
|
|
2290
|
+
if (keywordAt(bytes, pos, "xref")) {
|
|
2291
|
+
pos = this.readTable(pos);
|
|
2292
|
+
continue;
|
|
2293
|
+
}
|
|
2294
|
+
if (keywordAt(bytes, pos, "trailer")) {
|
|
2295
|
+
pos = this.readTrailer(pos);
|
|
2296
|
+
continue;
|
|
2297
|
+
}
|
|
2298
|
+
if (keywordAt(bytes, pos, "startxref")) {
|
|
2299
|
+
const n = intAt(bytes, skipSpace(bytes, pos + 9), 12);
|
|
2300
|
+
if (n) this.startxrefs.push(n.value);
|
|
2301
|
+
pos = n ? n.end : pos + 9;
|
|
2302
|
+
continue;
|
|
2303
|
+
}
|
|
2304
|
+
const next = Math.min(firstAtLeast(this.headers, pos + 1) ?? 1e400, firstAtLeast(this.keywords, pos + 1) ?? 1e400);
|
|
2305
|
+
if (next === 1e400) break;
|
|
2306
|
+
this.repaired = true;
|
|
2307
|
+
this.junk.push([pos, next]);
|
|
2308
|
+
pos = next;
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
/** A cross-reference table at `at` (the `xref` keyword); returns the offset after it. */
|
|
2312
|
+
readTable(at) {
|
|
2313
|
+
const { bytes } = this;
|
|
2314
|
+
const entries = /* @__PURE__ */ new Map();
|
|
2315
|
+
let i = skipSpace(bytes, at + 4);
|
|
2316
|
+
let count = 0;
|
|
2317
|
+
for (;;) {
|
|
2318
|
+
const first = intAt(bytes, i, 10);
|
|
2319
|
+
if (!first) break;
|
|
2320
|
+
const n = intAt(bytes, skipSpace(bytes, first.end), 10);
|
|
2321
|
+
if (!n) break;
|
|
2322
|
+
let j = skipSpace(bytes, n.end);
|
|
2323
|
+
let k = 0;
|
|
2324
|
+
for (; k < n.value; k += 1) {
|
|
2325
|
+
const offset = intAt(bytes, j, 10);
|
|
2326
|
+
if (!offset) break;
|
|
2327
|
+
const gen = intAt(bytes, skipSpace(bytes, offset.end), 5);
|
|
2328
|
+
if (!gen) break;
|
|
2329
|
+
const t = skipSpace(bytes, gen.end);
|
|
2330
|
+
const type = bytes[t];
|
|
2331
|
+
if (type !== 110 && type !== 102 || !endsToken(bytes[t + 1])) break;
|
|
2332
|
+
count += 1;
|
|
2333
|
+
if ((count & 4095) === 0) this.work.xrefEntries(4096);
|
|
2334
|
+
const num = first.value + k;
|
|
2335
|
+
if (!entries.has(num)) entries.set(num, type === 110 ? {
|
|
2336
|
+
type: 1,
|
|
2337
|
+
offset: offset.value
|
|
2338
|
+
} : { type: 0 });
|
|
2339
|
+
j = skipSpace(bytes, t + 1);
|
|
2340
|
+
}
|
|
2341
|
+
if (k < n.value) {
|
|
2342
|
+
this.repaired = true;
|
|
2343
|
+
i = j;
|
|
2344
|
+
break;
|
|
2345
|
+
}
|
|
2346
|
+
i = j;
|
|
2347
|
+
}
|
|
2348
|
+
this.work.xrefEntries(count & 4095);
|
|
2349
|
+
this.work.section();
|
|
2350
|
+
const section = {
|
|
2351
|
+
kind: "table",
|
|
2352
|
+
offset: at,
|
|
2353
|
+
entries,
|
|
2354
|
+
trailer: void 0
|
|
2355
|
+
};
|
|
2356
|
+
this.sections.push(section);
|
|
2357
|
+
this.sectionAt.set(at, section);
|
|
2358
|
+
return Math.max(i, at + 4);
|
|
2359
|
+
}
|
|
2360
|
+
/** A trailer dictionary at `at` (the `trailer` keyword); returns the offset after it. */
|
|
2361
|
+
readTrailer(at, standalone = false) {
|
|
2362
|
+
this.trailersRead.add(at);
|
|
2363
|
+
try {
|
|
2364
|
+
const { value, end } = this.lexer.valueAt(skipSpace(this.bytes, at + 7));
|
|
2365
|
+
if (value instanceof PdfDict) {
|
|
2366
|
+
const table = this.sections.at(-1);
|
|
2367
|
+
if (!standalone && table && table.kind === "table" && !table.trailer && table.offset < at) table.trailer = value;
|
|
2368
|
+
else this.standaloneTrailers.push({
|
|
2369
|
+
offset: at,
|
|
2370
|
+
dict: value
|
|
2371
|
+
});
|
|
2372
|
+
this.addTargets(value);
|
|
2373
|
+
return end;
|
|
2374
|
+
}
|
|
2375
|
+
} catch (error) {
|
|
2376
|
+
if (error instanceof PdfToolsError) throw error;
|
|
2377
|
+
}
|
|
2378
|
+
this.repaired = true;
|
|
2379
|
+
return at + 7;
|
|
2380
|
+
}
|
|
2381
|
+
/**
|
|
2382
|
+
* Every in-use cross-reference entry must lead to a definition of its object: one read already, or one read
|
|
2383
|
+
* now (a hidden definition). An entry that leads to no object header, to another object, or to an object
|
|
2384
|
+
* that cannot be parsed is `DAMAGED`. Returns how many hidden definitions were found.
|
|
2385
|
+
*/
|
|
2386
|
+
*checkXrefOffsets() {
|
|
2387
|
+
let found = 0;
|
|
2388
|
+
for (; this.sectionCursor < this.sections.length; this.sectionCursor += 1) {
|
|
2389
|
+
const section = this.sections[this.sectionCursor];
|
|
2390
|
+
for (const [num, e] of section.entries) {
|
|
2391
|
+
if (e.type !== 1) continue;
|
|
2392
|
+
yield;
|
|
2393
|
+
let header;
|
|
2394
|
+
let other;
|
|
2395
|
+
for (const offset of this.headerOffset > 0 ? [e.offset, e.offset + this.headerOffset] : [e.offset]) {
|
|
2396
|
+
if (offset < 0 || offset >= this.bytes.length) continue;
|
|
2397
|
+
const h = this.lexer.headerAt(offset);
|
|
2398
|
+
if (h && (!h.valid || h.num === num)) {
|
|
2399
|
+
header = h;
|
|
2400
|
+
break;
|
|
2401
|
+
}
|
|
2402
|
+
if (h) other ??= h;
|
|
2403
|
+
}
|
|
2404
|
+
if (header && !header.valid) throw damaged("an object header has no valid object number", header.start);
|
|
2405
|
+
if (!header) {
|
|
2406
|
+
this.repaired = true;
|
|
2407
|
+
this.claimed.add(num);
|
|
2408
|
+
if (other && other.valid) {
|
|
2409
|
+
if (!this.defsAt.has(other.start)) found += this.readHidden(other.start, true);
|
|
2410
|
+
const target = this.defsAt.get(other.start);
|
|
2411
|
+
if (target) this.addDefinition({
|
|
2412
|
+
...target,
|
|
2413
|
+
num,
|
|
2414
|
+
hidden: true
|
|
2415
|
+
});
|
|
2416
|
+
}
|
|
2417
|
+
continue;
|
|
2418
|
+
}
|
|
2419
|
+
if (this.defsAt.has(header.start)) continue;
|
|
2420
|
+
found += this.readHidden(header.start, true);
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
return found;
|
|
2424
|
+
}
|
|
2425
|
+
/**
|
|
2426
|
+
* Reads every object header found by the scan that is not read yet, wherever it is (also inside a string
|
|
2427
|
+
* or another object's stream data, where a reader that rebuilds a broken file may find it). A header that
|
|
2428
|
+
* is not valid, or an object that does not parse, is `DAMAGED`.
|
|
2429
|
+
*/
|
|
2430
|
+
*readScannedHeaders() {
|
|
2431
|
+
let found = 0;
|
|
2432
|
+
for (const offset of this.headers) {
|
|
2433
|
+
if (this.tried.has(offset) || this.defsAt.has(offset)) continue;
|
|
2434
|
+
yield;
|
|
2435
|
+
const h = this.lexer.headerAt(offset);
|
|
2436
|
+
if (!h) continue;
|
|
2437
|
+
if (!h.valid) throw damaged("an object header has no valid object number", offset);
|
|
2438
|
+
if (this.defsAt.has(h.start)) continue;
|
|
2439
|
+
found += this.readHidden(h.start);
|
|
2440
|
+
}
|
|
2441
|
+
for (const { objAt, list } of this.readings) {
|
|
2442
|
+
const missing = list.filter((r) => !this.readKeys.has(`${objAt}:${r.num}:${r.gen}`));
|
|
2443
|
+
if (missing.length === 0) continue;
|
|
2444
|
+
yield;
|
|
2445
|
+
const header = (r) => ({
|
|
2446
|
+
num: r.num,
|
|
2447
|
+
gen: r.gen,
|
|
2448
|
+
start: r.start,
|
|
2449
|
+
after: objAt + 3,
|
|
2450
|
+
valid: true
|
|
2451
|
+
});
|
|
2452
|
+
let parsed;
|
|
2453
|
+
try {
|
|
2454
|
+
this.work.object();
|
|
2455
|
+
parsed = this.lexer.objectWith(header(missing[0]));
|
|
2456
|
+
} catch (error) {
|
|
2457
|
+
if (error instanceof PdfToolsError) throw error;
|
|
2458
|
+
}
|
|
2459
|
+
for (const r of missing) {
|
|
2460
|
+
if (parsed) this.addParsed({
|
|
2461
|
+
...parsed,
|
|
2462
|
+
num: r.num,
|
|
2463
|
+
gen: r.gen
|
|
2464
|
+
}, r.start, true, false);
|
|
2465
|
+
else this.addUndecodable(header(r), r.start, true, false);
|
|
2466
|
+
found += 1;
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
return found;
|
|
2470
|
+
}
|
|
2471
|
+
/** Reads the trailer dictionary at every `trailer` keyword in the file not read yet (also inside other data). */
|
|
2472
|
+
readAllTrailers() {
|
|
2473
|
+
for (const at of this.keywords) {
|
|
2474
|
+
if (this.trailersRead.has(at) || !keywordAt(this.bytes, at, "trailer")) continue;
|
|
2475
|
+
this.readTrailer(at, true);
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
/** Reads a definition at `offset` that the sequence of objects did not reach. */
|
|
2479
|
+
readHidden(offset, pointed = false) {
|
|
2480
|
+
if (this.tried.has(offset)) return 0;
|
|
2481
|
+
this.tried.add(offset);
|
|
2482
|
+
this.work.object();
|
|
2483
|
+
let parsed;
|
|
2484
|
+
try {
|
|
2485
|
+
parsed = this.lexer.objectAt(offset);
|
|
2486
|
+
} catch (error) {
|
|
2487
|
+
if (error instanceof PdfToolsError) throw error;
|
|
2488
|
+
const h = this.lexer.headerAt(offset);
|
|
2489
|
+
if (!pointed || !h) throw damaged("an object cannot be read", offset);
|
|
2490
|
+
this.addUndecodable(h, offset, true);
|
|
2491
|
+
return 1;
|
|
2492
|
+
}
|
|
2493
|
+
if (!parsed) return 0;
|
|
2494
|
+
this.addParsed(parsed, offset, true);
|
|
2495
|
+
return 1;
|
|
2496
|
+
}
|
|
2497
|
+
/** The candidate values of a referenced /Length: the one in force first, then the others. */
|
|
2498
|
+
lengthsOf = (ref) => {
|
|
2499
|
+
const out = [];
|
|
2500
|
+
const inForce = this.resolve(ref);
|
|
2501
|
+
if (typeof inForce === "number") out.push(inForce);
|
|
2502
|
+
for (const n of this.numbers(ref)) if (!out.includes(n)) out.push(n);
|
|
2503
|
+
return out.slice(0, 4);
|
|
2504
|
+
};
|
|
2505
|
+
/**
|
|
2506
|
+
* Reads again, now that every definition is known, each object whose stream extent depends on a referenced
|
|
2507
|
+
* /Length (as pdf.js resolves it: through the cross-reference table, so it may lie later in the file) or
|
|
2508
|
+
* that has a nested stream: once for each candidate length, and, for a nested stream, also as qpdf reads it
|
|
2509
|
+
* (the dictionary ends in the data) and with every stream ending at the first `endstream`. Each reading is
|
|
2510
|
+
* a further candidate definition of the object.
|
|
2511
|
+
*/
|
|
2512
|
+
*rereadStreams() {
|
|
2513
|
+
for (const d of this.rereads) {
|
|
2514
|
+
yield;
|
|
2515
|
+
const readings = [];
|
|
2516
|
+
const first = this.lexer.objectAt(d.offset, { lengths: this.lengthsOf });
|
|
2517
|
+
const choices = Math.max(1, first?.lengthCandidates ?? 1);
|
|
2518
|
+
for (let k = 0; k < choices; k += 1) readings.push({
|
|
2519
|
+
lengths: this.lengthsOf,
|
|
2520
|
+
lengthChoice: k
|
|
2521
|
+
});
|
|
2522
|
+
if (d.undecodable) readings.push({ mode: "noNested" }, { mode: "first" });
|
|
2523
|
+
this.work.reserveValues((first?.values ?? 0) * readings.length);
|
|
2524
|
+
for (const options of readings) {
|
|
2525
|
+
this.work.object();
|
|
2526
|
+
let parsed;
|
|
2527
|
+
try {
|
|
2528
|
+
parsed = this.lexer.objectAt(d.offset, options);
|
|
2529
|
+
} catch (error) {
|
|
2530
|
+
if (error instanceof PdfToolsError) throw error;
|
|
2531
|
+
continue;
|
|
2532
|
+
}
|
|
2533
|
+
if (!parsed) continue;
|
|
2534
|
+
this.addDefinition({
|
|
2535
|
+
...d,
|
|
2536
|
+
value: parsed.value,
|
|
2537
|
+
hidden: true,
|
|
2538
|
+
undecodable: false,
|
|
2539
|
+
alternateOf: d
|
|
2540
|
+
});
|
|
2541
|
+
if (parsed.alternate !== void 0) this.addDefinition({
|
|
2542
|
+
...d,
|
|
2543
|
+
value: parsed.alternate,
|
|
2544
|
+
hidden: true,
|
|
2545
|
+
undecodable: false,
|
|
2546
|
+
alternateOf: d
|
|
2547
|
+
});
|
|
2548
|
+
if (parsed.nestedStream && !d.undecodable) {
|
|
2549
|
+
d.undecodable = true;
|
|
2550
|
+
this.undecodable.add(d.num);
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
}
|
|
2554
|
+
}
|
|
2555
|
+
/** Every number `v` can be, following references through every definition of each object (at most 8). */
|
|
2556
|
+
numbers(v) {
|
|
2557
|
+
const out = [];
|
|
2558
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2559
|
+
const visit = (x, depth) => {
|
|
2560
|
+
if (out.length >= 8) return;
|
|
2561
|
+
if (typeof x === "number") {
|
|
2562
|
+
if (!out.includes(x)) out.push(x);
|
|
2563
|
+
} else if (x instanceof PdfRef && depth < this.work.limits.maxDepth && !seen.has(x.num)) {
|
|
2564
|
+
seen.add(x.num);
|
|
2565
|
+
for (const d of this.definitionsOf(x.num)) visit(d.value, depth + 1);
|
|
2566
|
+
}
|
|
2567
|
+
};
|
|
2568
|
+
visit(v, 0);
|
|
2569
|
+
return out;
|
|
2570
|
+
}
|
|
2571
|
+
/**
|
|
2572
|
+
* Every `obj` keyword in the file (in strings, comments, stream data and junk alike) that is not the header
|
|
2573
|
+
* of a definition read is classified once, without choosing how the bytes before it are tokenised. It counts
|
|
2574
|
+
* as unresolved when it lies in bytes skipped as junk, or when there is any way to read the bytes before it
|
|
2575
|
+
* as `<number> [separators] obj`, where separators are whitespace bytes of any reader (NUL, HT, LF, VT, FF,
|
|
2576
|
+
* CR, SP) and comments, and a comment may start at ANY `%` and runs to the end of its line:
|
|
2577
|
+
*
|
|
2578
|
+
* - on its own line, the last byte before it that is not whitespace is a number character (`0-9 + - .`);
|
|
2579
|
+
* - or only whitespace precedes it on its line, and going up, past lines that may be only whitespace and
|
|
2580
|
+
* comment (blank, or whose first non-whitespace byte is `%`), some line on the way, or the first line that
|
|
2581
|
+
* may not, may end in a number: a number character followed by only whitespace up to the line end or up
|
|
2582
|
+
* to some `%`.
|
|
2583
|
+
*
|
|
2584
|
+
* Otherwise it is ignored: on its own line the byte before it is something no number ends with (a `%` there
|
|
2585
|
+
* puts the `obj` itself in a comment for every reader). One forward pass keeps, for the line above, whether
|
|
2586
|
+
* such a number may end it or the lines above it; each `obj` costs O(1).
|
|
2587
|
+
*/
|
|
2588
|
+
*classifyObjWords() {
|
|
2589
|
+
const loose = this.objWords.filter((at) => !this.objOfDefinitions.has(at));
|
|
2590
|
+
if (loose.length === 0) return;
|
|
2591
|
+
const b = this.bytes;
|
|
2592
|
+
let next = 0;
|
|
2593
|
+
let r = 0;
|
|
2594
|
+
let blankSoFar = true;
|
|
2595
|
+
let firstIsPercent = false;
|
|
2596
|
+
let last = 0;
|
|
2597
|
+
let pending = false;
|
|
2598
|
+
let mayEnd = false;
|
|
2599
|
+
let above = false;
|
|
2600
|
+
for (let i = 0; i <= b.length && next < loose.length; i += 1) {
|
|
2601
|
+
if ((i & 0xfffff) === 0xfffff) {
|
|
2602
|
+
this.work.checkpoint();
|
|
2603
|
+
yield;
|
|
2604
|
+
}
|
|
2605
|
+
if (i === loose[next]) {
|
|
2606
|
+
const at = i;
|
|
2607
|
+
next += 1;
|
|
2608
|
+
while (r < this.junk.length && this.junk[r][1] <= at) r += 1;
|
|
2609
|
+
if (r < this.junk.length && this.junk[r][0] <= at || last === 1 || last === 0 && above) this.unaccountedObj += 1;
|
|
2610
|
+
}
|
|
2611
|
+
if (i === b.length) break;
|
|
2612
|
+
const c = b[i];
|
|
2613
|
+
if (c === 10 || c === 13) {
|
|
2614
|
+
if (pending) mayEnd = true;
|
|
2615
|
+
above = blankSoFar || firstIsPercent ? mayEnd || above : mayEnd;
|
|
2616
|
+
blankSoFar = true;
|
|
2617
|
+
firstIsPercent = false;
|
|
2618
|
+
last = 0;
|
|
2619
|
+
pending = false;
|
|
2620
|
+
mayEnd = false;
|
|
2621
|
+
} else if (isLineSpace(c)) {} else if (isNumberChar(c)) {
|
|
2622
|
+
if (blankSoFar) blankSoFar = false;
|
|
2623
|
+
last = 1;
|
|
2624
|
+
pending = true;
|
|
2625
|
+
} else {
|
|
2626
|
+
if (blankSoFar) {
|
|
2627
|
+
blankSoFar = false;
|
|
2628
|
+
firstIsPercent = c === 37;
|
|
2629
|
+
}
|
|
2630
|
+
if (c === 37 && pending) mayEnd = true;
|
|
2631
|
+
last = 2;
|
|
2632
|
+
pending = false;
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
/** In-use entries whose object is defined nowhere: each counts as unresolved. */
|
|
2637
|
+
unreadableEntries() {
|
|
2638
|
+
let n = 0;
|
|
2639
|
+
for (const num of this.claimed) if (this.definitionsOf(num).length === 0) n += 1;
|
|
2640
|
+
return n;
|
|
2641
|
+
}
|
|
2642
|
+
/** Every trailer dictionary read: of tables, cross-reference streams, and those found by the scan. */
|
|
2643
|
+
trailerDicts() {
|
|
2644
|
+
const out = [];
|
|
2645
|
+
for (const section of this.sections) if (section.trailer) out.push(section.trailer);
|
|
2646
|
+
for (const t of this.standaloneTrailers) out.push(t.dict);
|
|
2647
|
+
return out;
|
|
2648
|
+
}
|
|
2649
|
+
/** Every definition of object `num`, in every revision, hidden ones and those in object streams too. */
|
|
2650
|
+
definitionsOf(num) {
|
|
2651
|
+
return this.byNum.get(num) ?? [];
|
|
2652
|
+
}
|
|
2653
|
+
/**
|
|
2654
|
+
* Reads, among the definitions not looked at yet, every stream that may be a cross-reference stream: typed
|
|
2655
|
+
* /XRef, or with /W (some readers do not look at /Type). Then every offset that leads to a section (the last
|
|
2656
|
+
* startxref, every /Prev and /XRefStm): a table or a stream there is read whatever its type, and an offset
|
|
2657
|
+
* that leads to nothing readable is `DAMAGED`. Returns how many sections were added.
|
|
2658
|
+
*/
|
|
2659
|
+
*readXrefStreams() {
|
|
2660
|
+
const before = this.sections.length;
|
|
2661
|
+
for (; this.xrefCursor < this.defs.length; this.xrefCursor += 1) {
|
|
2662
|
+
const d = this.defs[this.xrefCursor];
|
|
2663
|
+
const dict = d.value;
|
|
2664
|
+
if (!(dict instanceof PdfDict) || !dict.stream || d.container) continue;
|
|
2665
|
+
if (isName(this.resolve(dict.get("Type")), "XRef") || dict.has("W")) {
|
|
2666
|
+
yield;
|
|
2667
|
+
this.readXrefStreamOnce(d, dict);
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
if (this.targetCursor === 0 && this.startxrefs.length > 0) this.addTarget(this.startxrefs.at(-1));
|
|
2671
|
+
for (; this.targetCursor < this.targets.length; this.targetCursor += 1) {
|
|
2672
|
+
yield;
|
|
2673
|
+
this.readTarget(this.targets[this.targetCursor]);
|
|
2674
|
+
}
|
|
2675
|
+
return this.sections.length - before;
|
|
2676
|
+
}
|
|
2677
|
+
readXrefStreamOnce(d, dict) {
|
|
2678
|
+
if (this.readXrefStreamDefs.has(d)) return;
|
|
2679
|
+
this.readXrefStreamDefs.add(d);
|
|
2680
|
+
this.xrefStreams = true;
|
|
2681
|
+
for (const v of this.variants(d, dict)) try {
|
|
2682
|
+
this.readXrefStream(d, dict, v.data);
|
|
2683
|
+
} catch (error) {
|
|
2684
|
+
if (v.required || !(error instanceof PdfToolsError) || error.code !== "DAMAGED") throw error;
|
|
2685
|
+
}
|
|
2686
|
+
this.addTargets(dict);
|
|
2687
|
+
}
|
|
2688
|
+
addTarget(offset) {
|
|
2689
|
+
if (this.targetSeen.has(offset)) return;
|
|
2690
|
+
this.targetSeen.add(offset);
|
|
2691
|
+
this.targets.push(offset);
|
|
2692
|
+
}
|
|
2693
|
+
/** The /Prev and /XRefStm of a trailer or cross-reference stream dictionary. */
|
|
2694
|
+
addTargets(dict) {
|
|
2695
|
+
for (const key of ["Prev", "XRefStm"]) for (const v of dict.all(key)) for (const at of this.numbers(v)) {
|
|
2696
|
+
if (!Number.isSafeInteger(at) || at < 0) throw damaged("a cross-reference offset is not a valid offset");
|
|
2697
|
+
this.addTarget(at);
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
/** What is at an offset that leads to a cross-reference section: a table, or a stream read as one. */
|
|
2701
|
+
readTarget(target) {
|
|
2702
|
+
for (const offset of this.headerOffset > 0 ? [target, target + this.headerOffset] : [target]) {
|
|
2703
|
+
if (offset < 0 || offset >= this.bytes.length) continue;
|
|
2704
|
+
if (this.sectionAt.has(offset)) return;
|
|
2705
|
+
const at = skipSpace(this.bytes, offset);
|
|
2706
|
+
if (this.sectionAt.has(at)) return;
|
|
2707
|
+
if (keywordAt(this.bytes, at, "xref")) {
|
|
2708
|
+
const end = skipSpace(this.bytes, this.readTable(at));
|
|
2709
|
+
if (keywordAt(this.bytes, end, "trailer")) this.readTrailer(end);
|
|
2710
|
+
return;
|
|
2711
|
+
}
|
|
2712
|
+
const h = this.lexer.headerAt(offset);
|
|
2713
|
+
if (!h) continue;
|
|
2714
|
+
if (!h.valid) throw damaged("an object header has no valid object number", h.start);
|
|
2715
|
+
if (!this.defsAt.has(h.start)) this.readHidden(h.start, true);
|
|
2716
|
+
const d = this.defsAt.get(h.start);
|
|
2717
|
+
if (d && d.value instanceof PdfDict && d.value.stream) {
|
|
2718
|
+
this.readXrefStreamOnce(d, d.value);
|
|
2719
|
+
return;
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
this.repaired = true;
|
|
2723
|
+
}
|
|
2724
|
+
/**
|
|
2725
|
+
* The data of a structural stream (a cross-reference or object stream), each way it can be read: as found
|
|
2726
|
+
* (up to `endstream`, or as long as a direct /Length says), and, when /Length is a reference to another
|
|
2727
|
+
* length, as long as that says, which is what a reader that resolves the reference reads. Each reading that
|
|
2728
|
+
* is `required` must succeed; when the referenced length gives a reading, that one is required and the
|
|
2729
|
+
* reading as found (which no such reader makes) is read too but may fail.
|
|
2730
|
+
*/
|
|
2731
|
+
variants(d, dict) {
|
|
2732
|
+
const s = dict.stream;
|
|
2733
|
+
const length = dict.get("Length");
|
|
2734
|
+
if (length instanceof PdfRef && s.source === this.bytes && !d.container) {
|
|
2735
|
+
const n = this.lengthsOf(length)[0];
|
|
2736
|
+
if (typeof n === "number" && Number.isSafeInteger(n) && n >= 0 && n !== s.data.length && s.start + n <= this.bytes.length) {
|
|
2737
|
+
const fits = keywordAt(this.bytes, skipSpace(this.bytes, s.start + n), "endstream");
|
|
2738
|
+
const byLength = this.bytes.subarray(s.start, s.start + n);
|
|
2739
|
+
return fits ? [{
|
|
2740
|
+
data: byLength,
|
|
2741
|
+
required: true
|
|
2742
|
+
}, {
|
|
2743
|
+
data: s.data,
|
|
2744
|
+
required: false
|
|
2745
|
+
}] : [{
|
|
2746
|
+
data: s.data,
|
|
2747
|
+
required: true
|
|
2748
|
+
}, {
|
|
2749
|
+
data: byLength,
|
|
2750
|
+
required: false
|
|
2751
|
+
}];
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
return [{
|
|
2755
|
+
data: s.data,
|
|
2756
|
+
required: true
|
|
2757
|
+
}];
|
|
2758
|
+
}
|
|
2759
|
+
/** Runs `read`; when the reading is not required, a `DAMAGED` from it is dropped (limits still stop the call). */
|
|
2760
|
+
*optional(required, read) {
|
|
2761
|
+
if (required) return yield* read();
|
|
2762
|
+
try {
|
|
2763
|
+
yield* read();
|
|
2764
|
+
} catch (error) {
|
|
2765
|
+
if (!(error instanceof PdfToolsError) || error.code !== "DAMAGED") throw error;
|
|
2766
|
+
}
|
|
2767
|
+
}
|
|
2768
|
+
readXrefStream(d, dict, raw) {
|
|
2769
|
+
const int = (v) => {
|
|
2770
|
+
const x = this.resolve(v);
|
|
2771
|
+
return typeof x === "number" && Number.isSafeInteger(x) && x >= 0 ? x : void 0;
|
|
2772
|
+
};
|
|
2773
|
+
this.work.section();
|
|
2774
|
+
const w = this.resolve(dict.get("W"));
|
|
2775
|
+
if (w === null || w === void 0) {
|
|
2776
|
+
this.repaired = true;
|
|
2777
|
+
return;
|
|
2778
|
+
}
|
|
2779
|
+
if (!Array.isArray(w) || w.length < 3) throw damaged("a cross-reference stream has no field widths", d.offset);
|
|
2780
|
+
const widths = w.slice(0, 3).map(int);
|
|
2781
|
+
if (widths.some((x) => x === void 0 || x > 8)) throw damaged("a cross-reference stream has wrong field widths", d.offset);
|
|
2782
|
+
const [w0, w1, w2] = widths;
|
|
2783
|
+
const rowWidth = w0 + w1 + w2;
|
|
2784
|
+
if (rowWidth === 0) throw damaged("a cross-reference stream has wrong field widths", d.offset);
|
|
2785
|
+
const index = this.resolve(dict.get("Index"));
|
|
2786
|
+
const size = int(dict.get("Size")) ?? 0;
|
|
2787
|
+
const ranges = [];
|
|
2788
|
+
if (Array.isArray(index)) for (let i = 0; i + 1 < index.length; i += 2) {
|
|
2789
|
+
const a = int(index[i]);
|
|
2790
|
+
const b = int(index[i + 1]);
|
|
2791
|
+
if (a === void 0 || b === void 0) throw damaged("a cross-reference stream has a wrong index", d.offset);
|
|
2792
|
+
ranges.push([a, b]);
|
|
2793
|
+
}
|
|
2794
|
+
else ranges.push([0, size]);
|
|
2795
|
+
const total = ranges.reduce((n, [, c]) => n + c, 0);
|
|
2796
|
+
const { names, parms } = filtersOf(dict, (v) => this.resolve(v));
|
|
2797
|
+
const data = decode(raw, names, parms, this.work);
|
|
2798
|
+
const rows = Math.floor(data.length / rowWidth);
|
|
2799
|
+
if (rows < total) this.repaired = true;
|
|
2800
|
+
this.work.xrefEntries(Math.min(rows, total));
|
|
2801
|
+
const field = (at, width) => {
|
|
2802
|
+
let v = 0;
|
|
2803
|
+
for (let k = 0; k < width; k += 1) v = v * 256 + data[at + k];
|
|
2804
|
+
return v;
|
|
2805
|
+
};
|
|
2806
|
+
const entries = /* @__PURE__ */ new Map();
|
|
2807
|
+
let row = 0;
|
|
2808
|
+
for (const [first, count] of ranges) for (let k = 0; k < count && row < rows; k += 1, row += 1) {
|
|
2809
|
+
const at = row * rowWidth;
|
|
2810
|
+
const type = w0 === 0 ? 1 : field(at, w0);
|
|
2811
|
+
const second = field(at + w0, w1);
|
|
2812
|
+
const third = field(at + w0 + w1, w2);
|
|
2813
|
+
const num = first + k;
|
|
2814
|
+
if ((row & 65535) === 65535) this.work.checkpoint();
|
|
2815
|
+
if (entries.has(num)) continue;
|
|
2816
|
+
if (type === 0) entries.set(num, { type: 0 });
|
|
2817
|
+
else if (type === 1) entries.set(num, {
|
|
2818
|
+
type: 1,
|
|
2819
|
+
offset: second
|
|
2820
|
+
});
|
|
2821
|
+
else if (type === 2) entries.set(num, {
|
|
2822
|
+
type: 2,
|
|
2823
|
+
stream: second,
|
|
2824
|
+
index: third
|
|
2825
|
+
});
|
|
2826
|
+
}
|
|
2827
|
+
const section = {
|
|
2828
|
+
kind: "stream",
|
|
2829
|
+
offset: d.offset,
|
|
2830
|
+
entries,
|
|
2831
|
+
trailer: dict
|
|
2832
|
+
};
|
|
2833
|
+
this.sections.push(section);
|
|
2834
|
+
if (!this.sectionAt.has(d.offset)) this.sectionAt.set(d.offset, section);
|
|
2835
|
+
}
|
|
2836
|
+
findSection(offset) {
|
|
2837
|
+
for (const o of this.headerOffset > 0 ? [offset, offset + this.headerOffset] : [offset]) {
|
|
2838
|
+
if (o < 0 || o >= this.bytes.length) continue;
|
|
2839
|
+
const s = this.sectionAt.get(o) ?? this.sectionAt.get(skipSpace(this.bytes, o));
|
|
2840
|
+
if (s) return s;
|
|
2841
|
+
const h = this.lexer.headerAt(o);
|
|
2842
|
+
if (h && this.sectionAt.has(h.start)) return this.sectionAt.get(h.start);
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
/** Follows the last `startxref` and every /Prev, and settles the trailer and the entries in force. */
|
|
2846
|
+
buildChain() {
|
|
2847
|
+
const chain = [];
|
|
2848
|
+
const visited = /* @__PURE__ */ new Set();
|
|
2849
|
+
let at = this.startxrefs.at(-1);
|
|
2850
|
+
while (at !== void 0) {
|
|
2851
|
+
const s = this.findSection(at);
|
|
2852
|
+
if (!s || visited.has(s)) {
|
|
2853
|
+
this.chainBroken = true;
|
|
2854
|
+
break;
|
|
2855
|
+
}
|
|
2856
|
+
visited.add(s);
|
|
2857
|
+
chain.push(s);
|
|
2858
|
+
if (s.kind === "table") {
|
|
2859
|
+
const x = this.resolve(s.trailer?.get("XRefStm"));
|
|
2860
|
+
const hybrid = typeof x === "number" ? this.findSection(x) : void 0;
|
|
2861
|
+
if (hybrid && hybrid.kind === "stream" && !visited.has(hybrid)) {
|
|
2862
|
+
s.hybrid = hybrid;
|
|
2863
|
+
visited.add(hybrid);
|
|
2864
|
+
}
|
|
2865
|
+
}
|
|
2866
|
+
const prev = this.resolve(s.trailer?.get("Prev"));
|
|
2867
|
+
at = typeof prev === "number" && Number.isSafeInteger(prev) ? prev : void 0;
|
|
2868
|
+
}
|
|
2869
|
+
if (chain.length === 0) this.chainBroken = true;
|
|
2870
|
+
if (this.chainBroken) this.repaired = true;
|
|
2871
|
+
this.inForceCache.clear();
|
|
2872
|
+
for (const s of chain) for (const part of s.hybrid ? [s, s.hybrid] : [s]) for (const [num, e] of part.entries) if (!this.entries.has(num)) this.entries.set(num, e);
|
|
2873
|
+
this.chainLength = chain.length;
|
|
2874
|
+
const dicts = chain.length > 0 && !this.chainBroken ? chain.map((s) => s.trailer).filter((t) => t !== void 0) : [...this.sections.filter((s) => s.trailer).map((s) => ({
|
|
2875
|
+
offset: s.offset,
|
|
2876
|
+
dict: s.trailer
|
|
2877
|
+
})), ...this.standaloneTrailers].sort((a, b) => b.offset - a.offset).map((t) => t.dict);
|
|
2878
|
+
for (const key of [
|
|
2879
|
+
"Root",
|
|
2880
|
+
"Info",
|
|
2881
|
+
"Encrypt",
|
|
2882
|
+
"ID"
|
|
2883
|
+
]) for (const t of dicts) {
|
|
2884
|
+
const v = t.get(key);
|
|
2885
|
+
if (v !== void 0 && v !== null) {
|
|
2886
|
+
this.trailer[key] = v;
|
|
2887
|
+
break;
|
|
2888
|
+
}
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
/** Revisions: the sections of the chain (a linearised file's first-page section is not one). */
|
|
2892
|
+
revisions(linearized) {
|
|
2893
|
+
let n = this.chainLength;
|
|
2894
|
+
if (this.chainBroken || n === 0) {
|
|
2895
|
+
const hybrids = new Set(this.sections.map((s) => s.hybrid).filter(Boolean));
|
|
2896
|
+
n = this.sections.filter((s) => !hybrids.has(s)).length;
|
|
2897
|
+
}
|
|
2898
|
+
if (linearized && n >= 2) n -= 1;
|
|
2899
|
+
return Math.max(1, n);
|
|
2900
|
+
}
|
|
2901
|
+
/**
|
|
2902
|
+
* Opens the security handler of an encrypted file. Without a password only the empty password is tried.
|
|
2903
|
+
* Returns null for a file that is not encrypted.
|
|
2904
|
+
*/
|
|
2905
|
+
openEncryption(password) {
|
|
2906
|
+
const encValue = this.trailer.Encrypt;
|
|
2907
|
+
if (encValue === void 0 || encValue === null) return null;
|
|
2908
|
+
let enc = encValue;
|
|
2909
|
+
if (encValue instanceof PdfRef) {
|
|
2910
|
+
this.encryptNum = encValue.num;
|
|
2911
|
+
if (this.definitionsOf(encValue.num).length === 0) return null;
|
|
2912
|
+
enc = this.inForce(encValue.num)?.value;
|
|
2913
|
+
}
|
|
2914
|
+
if (!(enc instanceof PdfDict)) throw damaged("the encryption dictionary is missing");
|
|
2915
|
+
const ids = this.resolve(this.trailer.ID);
|
|
2916
|
+
const first = Array.isArray(ids) ? this.resolve(ids[0]) : void 0;
|
|
2917
|
+
const id0 = first instanceof PdfString ? first.bytes() : /* @__PURE__ */ new Uint8Array(0);
|
|
2918
|
+
const resolve = (v) => this.resolve(v);
|
|
2919
|
+
const revision = revisionOf(enc, resolve);
|
|
2920
|
+
const empty = openSecurity(enc, id0, "", resolve);
|
|
2921
|
+
let handler = empty;
|
|
2922
|
+
if (password !== void 0 && password !== "") {
|
|
2923
|
+
handler = openSecurity(enc, id0, password, resolve) ?? empty;
|
|
2924
|
+
if (!handler) throw new PdfToolsError("WRONG_PASSWORD", "the password does not open the file", { revision });
|
|
2925
|
+
}
|
|
2926
|
+
if (!handler) throw new PdfToolsError("ENCRYPTED", "the file needs a password", { revision });
|
|
2927
|
+
this.security = handler;
|
|
2928
|
+
return {
|
|
2929
|
+
revision: handler.revision,
|
|
2930
|
+
userPassword: !empty
|
|
2931
|
+
};
|
|
2932
|
+
}
|
|
2933
|
+
/** Whether the strings and streams of definition `d` are encrypted. */
|
|
2934
|
+
encrypted(d) {
|
|
2935
|
+
if (!this.security || d.container) return false;
|
|
2936
|
+
if (d.num === this.encryptNum) return false;
|
|
2937
|
+
return !(d.value instanceof PdfDict && isName(d.value.get("Type"), "XRef"));
|
|
2938
|
+
}
|
|
2939
|
+
/** The decoded data of stream `dict` of definition `d`, decrypted when the file is encrypted. */
|
|
2940
|
+
streamData(d, dict, raw) {
|
|
2941
|
+
const resolve = (v) => this.resolve(v);
|
|
2942
|
+
let { names, parms } = filtersOf(dict, resolve);
|
|
2943
|
+
let data = raw ?? dict.stream.data;
|
|
2944
|
+
if (d && this.security && this.encrypted(d)) ({data, names, parms} = decryptStream(this.security, d.num, d.gen, dict, data, names, parms, resolve));
|
|
2945
|
+
return decode(data, names, parms, this.work);
|
|
2946
|
+
}
|
|
2947
|
+
/**
|
|
2948
|
+
* Reads every stream that may be an object stream, whatever its /Type, also those found inside object
|
|
2949
|
+
* streams: typed /ObjStm, pointed into by a compressed-object entry of any section, or with /N and /First
|
|
2950
|
+
* (resolved through references). Some readers do not look at /Type, so a stream typed otherwise (even
|
|
2951
|
+
* /XRef) is read as an object stream too when it could be one. Then every compressed-object entry must
|
|
2952
|
+
* lead to an object read from its object stream at its index; one that does not is `DAMAGED`.
|
|
2953
|
+
*/
|
|
2954
|
+
*readObjectStreams() {
|
|
2955
|
+
const containers = /* @__PURE__ */ new Set();
|
|
2956
|
+
for (const section of this.sections) for (const e of section.entries.values()) if (e.type === 2) containers.add(e.stream);
|
|
2957
|
+
for (let i = 0; i < this.defs.length; i += 1) {
|
|
2958
|
+
const d = this.defs[i];
|
|
2959
|
+
if (this.readObjectStreamDefs.has(d)) continue;
|
|
2960
|
+
this.readObjectStreamDefs.add(d);
|
|
2961
|
+
const dict = d.value;
|
|
2962
|
+
if (!(dict instanceof PdfDict) || !dict.stream) continue;
|
|
2963
|
+
const n = this.resolve(dict.get("N"));
|
|
2964
|
+
const first = this.resolve(dict.get("First"));
|
|
2965
|
+
const combos = [];
|
|
2966
|
+
if (typeof n === "number" && typeof first === "number") combos.push([n, first]);
|
|
2967
|
+
for (const cn of this.numbers(dict.get("N"))) for (const cf of this.numbers(dict.get("First"))) if (combos.length < 4 && !combos.some(([a, b]) => a === cn && b === cf)) combos.push([cn, cf]);
|
|
2968
|
+
if (!(isName(this.resolve(dict.get("Type")), "ObjStm") || containers.has(d.num)) && combos.length === 0) continue;
|
|
2969
|
+
if (combos.length === 0) throw damaged("an object stream has a wrong header", d.offset);
|
|
2970
|
+
yield;
|
|
2971
|
+
this.objectStreams = true;
|
|
2972
|
+
const variants = this.variants(d, dict);
|
|
2973
|
+
for (let c = 0; c < combos.length; c += 1) for (let v = 0; v < variants.length; v += 1) {
|
|
2974
|
+
const required = variants[v].required && c === 0 && !d.alternateOf;
|
|
2975
|
+
yield* this.optional(required, () => this.readObjectStream(d, dict, variants[v].data, !required, combos[c][0], combos[c][1]));
|
|
2976
|
+
}
|
|
2977
|
+
}
|
|
2978
|
+
const held = /* @__PURE__ */ new Map();
|
|
2979
|
+
for (const d of this.defs) {
|
|
2980
|
+
if (!d.container) continue;
|
|
2981
|
+
const key = `${d.container.num} ${d.index}`;
|
|
2982
|
+
const list = held.get(key);
|
|
2983
|
+
if (list) list.push(d);
|
|
2984
|
+
else held.set(key, [d]);
|
|
2985
|
+
}
|
|
2986
|
+
for (const section of this.sections) for (const [num, e] of section.entries) {
|
|
2987
|
+
if (e.type !== 2) continue;
|
|
2988
|
+
for (const member of held.get(`${e.stream} ${e.index}`) ?? []) if (member.num !== num && !this.definitionsOf(num).some((x) => x.container === member.container && x.index === member.index)) this.addDefinition({
|
|
2989
|
+
...member,
|
|
2990
|
+
num
|
|
2991
|
+
});
|
|
2992
|
+
}
|
|
2993
|
+
for (const section of this.sections) for (const [, e] of section.entries) if (e.type === 2 && !held.has(`${e.stream} ${e.index}`)) throw damaged("a compressed-object entry leads to no object", section.offset);
|
|
2994
|
+
this.inForceCache.clear();
|
|
2995
|
+
}
|
|
2996
|
+
*readObjectStream(d, dict, raw, alternate, n, first) {
|
|
2997
|
+
if (!Number.isSafeInteger(n) || n < 0 || !Number.isSafeInteger(first) || first < 0) throw damaged("an object stream has a wrong header", d.offset);
|
|
2998
|
+
this.work.announce(n);
|
|
2999
|
+
const data = this.streamData(d, dict, raw);
|
|
3000
|
+
const pairs = [];
|
|
3001
|
+
let at = 0;
|
|
3002
|
+
for (let i = 0; i < n; i += 1) {
|
|
3003
|
+
const num = intAt(data, skipSpace(data, at), 10);
|
|
3004
|
+
const off = num && intAt(data, skipSpace(data, num.end), 10);
|
|
3005
|
+
if (!num || !off) throw damaged("an object stream has a wrong header", d.offset);
|
|
3006
|
+
pairs.push([num.value, off.value]);
|
|
3007
|
+
at = off.end;
|
|
3008
|
+
if ((i & 4095) === 4095) this.work.checkpoint();
|
|
3009
|
+
}
|
|
3010
|
+
const lexer = this.streamLexer ??= new Lexer(data, this.work);
|
|
3011
|
+
lexer.reset(data);
|
|
3012
|
+
for (let i = 0; i < pairs.length; i += 1) {
|
|
3013
|
+
yield;
|
|
3014
|
+
this.work.object();
|
|
3015
|
+
const [num, off] = pairs[i];
|
|
3016
|
+
const offset = first + off;
|
|
3017
|
+
if (offset >= data.length) throw damaged("an object stream has a wrong offset", d.offset);
|
|
3018
|
+
let value;
|
|
3019
|
+
let odd;
|
|
3020
|
+
let alternateValue;
|
|
3021
|
+
try {
|
|
3022
|
+
const r = lexer.valueAt(offset, { lengths: this.lengthsOf });
|
|
3023
|
+
({value, alternate: alternateValue} = r);
|
|
3024
|
+
const slotEnd = i + 1 < pairs.length ? first + pairs[i + 1][1] : data.length;
|
|
3025
|
+
odd = r.odd || r.nestedStream || r.valueEnd > slotEnd;
|
|
3026
|
+
} catch (error) {
|
|
3027
|
+
if (error instanceof PdfToolsError) throw error;
|
|
3028
|
+
throw damaged("an object in an object stream cannot be read", d.offset);
|
|
3029
|
+
}
|
|
3030
|
+
if (odd && alternate) continue;
|
|
3031
|
+
const earlier = alternate ? this.firstReading.get(`${d.num} ${d.offset} ${i}`) : void 0;
|
|
3032
|
+
const member = {
|
|
3033
|
+
num,
|
|
3034
|
+
gen: 0,
|
|
3035
|
+
value,
|
|
3036
|
+
offset: d.offset,
|
|
3037
|
+
order: d.order + (i + 1) / (pairs.length + 2),
|
|
3038
|
+
hidden: d.hidden || alternate,
|
|
3039
|
+
container: d,
|
|
3040
|
+
index: i,
|
|
3041
|
+
...odd ? { undecodable: true } : {},
|
|
3042
|
+
...earlier ? { alternateOf: earlier } : {}
|
|
3043
|
+
};
|
|
3044
|
+
this.addDefinition(member);
|
|
3045
|
+
if (!alternate) this.firstReading.set(`${d.num} ${d.offset} ${i}`, member);
|
|
3046
|
+
if (alternateValue !== void 0) this.addDefinition({
|
|
3047
|
+
...member,
|
|
3048
|
+
value: alternateValue,
|
|
3049
|
+
hidden: true,
|
|
3050
|
+
undecodable: false,
|
|
3051
|
+
alternateOf: member
|
|
3052
|
+
});
|
|
3053
|
+
if (odd) {
|
|
3054
|
+
this.undecodable.add(num);
|
|
3055
|
+
this.repaired = true;
|
|
3056
|
+
}
|
|
3057
|
+
}
|
|
3058
|
+
}
|
|
3059
|
+
/** The definition of object `num` in force: the one the cross-reference chain gives, else the latest in file order. */
|
|
3060
|
+
inForce(num) {
|
|
3061
|
+
const cached = this.inForceCache.get(num);
|
|
3062
|
+
if (cached !== void 0) return cached ?? void 0;
|
|
3063
|
+
const found = this.findInForce(num);
|
|
3064
|
+
this.inForceCache.set(num, found ?? null);
|
|
3065
|
+
return found;
|
|
3066
|
+
}
|
|
3067
|
+
findInForce(num) {
|
|
3068
|
+
const list = this.byNum.get(num) ?? [];
|
|
3069
|
+
const e = this.entries.get(num);
|
|
3070
|
+
if (e) {
|
|
3071
|
+
if (e.type === 0) return void 0;
|
|
3072
|
+
if (e.type === 1) {
|
|
3073
|
+
const d = this.defsAt.get(e.offset) ?? (this.headerOffset > 0 ? this.defsAt.get(e.offset + this.headerOffset) : void 0);
|
|
3074
|
+
if (d && d.num === num) return d;
|
|
3075
|
+
} else {
|
|
3076
|
+
const members = list.filter((d) => d.container && d.container.num === e.stream && d.index === e.index);
|
|
3077
|
+
if (members.length > 0) return members.reduce((a, b) => b.container.order > a.container.order ? b : a);
|
|
3078
|
+
}
|
|
3079
|
+
if (list.length > 0) this.repaired = true;
|
|
3080
|
+
}
|
|
3081
|
+
const visible = list.filter((d) => !d.hidden);
|
|
3082
|
+
const pool = visible.length > 0 ? visible : list;
|
|
3083
|
+
return pool.length > 0 ? pool.reduce((a, b) => b.order >= a.order ? b : a) : void 0;
|
|
3084
|
+
}
|
|
3085
|
+
/** `v` with references followed to the definitions in force; null for a missing object, a loop or a chain longer than maxDepth. */
|
|
3086
|
+
resolve(v) {
|
|
3087
|
+
return this.resolveWithDefinition(v).value;
|
|
3088
|
+
}
|
|
3089
|
+
resolveWithDefinition(v) {
|
|
3090
|
+
let definition;
|
|
3091
|
+
let value = v ?? null;
|
|
3092
|
+
for (let hops = 0; value instanceof PdfRef; hops += 1) {
|
|
3093
|
+
if (hops >= this.work.limits.maxDepth) return {
|
|
3094
|
+
value: null,
|
|
3095
|
+
definition: void 0
|
|
3096
|
+
};
|
|
3097
|
+
definition = this.inForce(value.num);
|
|
3098
|
+
value = definition ? definition.value : null;
|
|
3099
|
+
}
|
|
3100
|
+
return {
|
|
3101
|
+
value,
|
|
3102
|
+
definition
|
|
3103
|
+
};
|
|
3104
|
+
}
|
|
3105
|
+
/** Definitions that a later definition of the same object replaces (hidden ones are not counted). */
|
|
3106
|
+
shadowedCount() {
|
|
3107
|
+
let n = 0;
|
|
3108
|
+
for (const list of this.byNum.values()) {
|
|
3109
|
+
const visible = list.filter((d) => !d.hidden).length;
|
|
3110
|
+
if (visible > 1) n += visible - 1;
|
|
3111
|
+
}
|
|
3112
|
+
return n;
|
|
3113
|
+
}
|
|
3114
|
+
};
|
|
3115
|
+
// src/document.ts
|
|
3116
|
+
const INFO_FIELDS = [
|
|
3117
|
+
"Title",
|
|
3118
|
+
"Author",
|
|
3119
|
+
"Subject",
|
|
3120
|
+
"Keywords",
|
|
3121
|
+
"Creator",
|
|
3122
|
+
"Producer",
|
|
3123
|
+
"CreationDate",
|
|
3124
|
+
"ModDate",
|
|
3125
|
+
"Trapped"
|
|
3126
|
+
];
|
|
3127
|
+
/** The `%PDF-x.y` header within the first 1024 bytes: its offset and version. */
|
|
3128
|
+
function findHeader(bytes) {
|
|
3129
|
+
const offset = Buffer.from(bytes.buffer, bytes.byteOffset, Math.min(bytes.length, 1029)).indexOf("%PDF-", 0, "latin1");
|
|
3130
|
+
if (offset < 0 || offset > 1024) throw new PdfToolsError("NOT_PDF", "the input is not a PDF file (no %PDF- header)");
|
|
3131
|
+
const major = intAt(bytes, offset + 5, 2);
|
|
3132
|
+
if (!major || bytes[major.end] !== 46 || !isDigit(bytes[major.end + 1])) throw new PdfToolsError("NOT_PDF", "the input is not a PDF file (no version in the header)");
|
|
3133
|
+
return {
|
|
3134
|
+
offset,
|
|
3135
|
+
version: `${major.value}.${bytes[major.end + 1] - 48}`
|
|
3136
|
+
};
|
|
3137
|
+
}
|
|
3138
|
+
const versionValue = (v) => {
|
|
3139
|
+
const [a, b] = v.split(".").map(Number);
|
|
3140
|
+
return a * 10 + b;
|
|
3141
|
+
};
|
|
3142
|
+
function* readPages(reader, catalog) {
|
|
3143
|
+
const { work } = reader;
|
|
3144
|
+
const root = reader.resolve(catalog.get("Pages"));
|
|
3145
|
+
if (!(root instanceof PdfDict)) throw damaged("the page tree is missing");
|
|
3146
|
+
const sizes = [];
|
|
3147
|
+
const stack = [{
|
|
3148
|
+
node: root,
|
|
3149
|
+
box: void 0,
|
|
3150
|
+
rotate: 0
|
|
3151
|
+
}];
|
|
3152
|
+
const open = /* @__PURE__ */ new Set();
|
|
3153
|
+
let nodes = 0;
|
|
3154
|
+
const boxOf = (v) => {
|
|
3155
|
+
const a = reader.resolve(v);
|
|
3156
|
+
if (!Array.isArray(a) || a.length < 4) return void 0;
|
|
3157
|
+
const n = a.slice(0, 4).map((x) => reader.resolve(x));
|
|
3158
|
+
return n.every((x) => typeof x === "number" && Number.isFinite(x)) ? n : void 0;
|
|
3159
|
+
};
|
|
3160
|
+
while (stack.length > 0) {
|
|
3161
|
+
const frame = stack.pop();
|
|
3162
|
+
if ("exit" in frame) {
|
|
3163
|
+
open.delete(frame.exit);
|
|
3164
|
+
continue;
|
|
3165
|
+
}
|
|
3166
|
+
yield;
|
|
3167
|
+
nodes += 1;
|
|
3168
|
+
if (nodes > work.limits.maxObjects) throw limitError("maxObjects", work.limits.maxObjects, "the page tree is too large");
|
|
3169
|
+
const { node } = frame;
|
|
3170
|
+
if (open.has(node)) throw damaged("page tree loop");
|
|
3171
|
+
const box = boxOf(node.get("MediaBox")) ?? frame.box;
|
|
3172
|
+
const r = reader.resolve(node.get("Rotate"));
|
|
3173
|
+
const rotate = typeof r === "number" && Number.isFinite(r) ? r : frame.rotate;
|
|
3174
|
+
const kids = reader.resolve(node.get("Kids"));
|
|
3175
|
+
if (!isName(reader.resolve(node.get("Type")), "Page") && Array.isArray(kids)) {
|
|
3176
|
+
open.add(node);
|
|
3177
|
+
stack.push({ exit: node });
|
|
3178
|
+
for (let i = kids.length - 1; i >= 0; i -= 1) {
|
|
3179
|
+
const kid = reader.resolve(kids[i]);
|
|
3180
|
+
if (kid instanceof PdfDict) stack.push({
|
|
3181
|
+
node: kid,
|
|
3182
|
+
box,
|
|
3183
|
+
rotate
|
|
3184
|
+
});
|
|
3185
|
+
else reader.repaired = true;
|
|
3186
|
+
}
|
|
3187
|
+
continue;
|
|
3188
|
+
}
|
|
3189
|
+
if (sizes.length >= work.limits.maxPages) throw limitError("maxPages", work.limits.maxPages, "too many pages");
|
|
3190
|
+
const [x1, y1, x2, y2] = box ?? [
|
|
3191
|
+
0,
|
|
3192
|
+
0,
|
|
3193
|
+
612,
|
|
3194
|
+
792
|
|
3195
|
+
];
|
|
3196
|
+
const turn = rotate % 90 === 0 ? (rotate % 360 + 360) % 360 : 0;
|
|
3197
|
+
sizes.push({
|
|
3198
|
+
w: Math.abs(x2 - x1),
|
|
3199
|
+
h: Math.abs(y2 - y1),
|
|
3200
|
+
rotate: turn
|
|
3201
|
+
});
|
|
3202
|
+
}
|
|
3203
|
+
return sizes;
|
|
3204
|
+
}
|
|
3205
|
+
/** PDFDocEncoding bytes 0x18 to 0x1f and 0x80 to 0xad that differ from Latin-1. */
|
|
3206
|
+
const PDFDOC = {
|
|
3207
|
+
24: "˘",
|
|
3208
|
+
25: "ˇ",
|
|
3209
|
+
26: "ˆ",
|
|
3210
|
+
27: "˙",
|
|
3211
|
+
28: "˝",
|
|
3212
|
+
29: "˛",
|
|
3213
|
+
30: "˚",
|
|
3214
|
+
31: "˜",
|
|
3215
|
+
128: "•",
|
|
3216
|
+
129: "†",
|
|
3217
|
+
130: "‡",
|
|
3218
|
+
131: "…",
|
|
3219
|
+
132: "—",
|
|
3220
|
+
133: "–",
|
|
3221
|
+
134: "ƒ",
|
|
3222
|
+
135: "⁄",
|
|
3223
|
+
136: "‹",
|
|
3224
|
+
137: "›",
|
|
3225
|
+
138: "−",
|
|
3226
|
+
139: "‰",
|
|
3227
|
+
140: "„",
|
|
3228
|
+
141: "“",
|
|
3229
|
+
142: "”",
|
|
3230
|
+
143: "‘",
|
|
3231
|
+
144: "’",
|
|
3232
|
+
145: "‚",
|
|
3233
|
+
146: "™",
|
|
3234
|
+
147: "fi",
|
|
3235
|
+
148: "fl",
|
|
3236
|
+
149: "Ł",
|
|
3237
|
+
150: "Œ",
|
|
3238
|
+
151: "Š",
|
|
3239
|
+
152: "Ÿ",
|
|
3240
|
+
153: "Ž",
|
|
3241
|
+
154: "ı",
|
|
3242
|
+
155: "ł",
|
|
3243
|
+
156: "œ",
|
|
3244
|
+
157: "š",
|
|
3245
|
+
158: "ž",
|
|
3246
|
+
160: "€"
|
|
3247
|
+
};
|
|
3248
|
+
/** A text string: UTF-16BE or UTF-8 with a byte order mark, else PDFDocEncoding. */
|
|
3249
|
+
function textOf(b) {
|
|
3250
|
+
if (b[0] === 254 && b[1] === 255) {
|
|
3251
|
+
let s = "";
|
|
3252
|
+
for (let i = 2; i + 1 < b.length; i += 2) s += String.fromCharCode(b[i] << 8 | b[i + 1]);
|
|
3253
|
+
return s;
|
|
3254
|
+
}
|
|
3255
|
+
if (b[0] === 239 && b[1] === 187 && b[2] === 191) return new TextDecoder("utf-8").decode(b.subarray(3));
|
|
3256
|
+
let s = "";
|
|
3257
|
+
for (const c of b) s += PDFDOC[c] ?? String.fromCharCode(c);
|
|
3258
|
+
return s;
|
|
3259
|
+
}
|
|
3260
|
+
/** The PDF/A part and conformance an XMP packet declares (any prefix bound to the pdfaid namespace). */
|
|
3261
|
+
function pdfaClaim(xmp) {
|
|
3262
|
+
const prefixes = /* @__PURE__ */ new Set();
|
|
3263
|
+
for (const m of xmp.matchAll(/xmlns:([A-Za-z_][\w.-]*)\s*=\s*["']http:\/\/www\.aiim\.org\/pdfa\/ns\/id\/["']/g)) prefixes.add(m[1]);
|
|
3264
|
+
const field = (p, name) => {
|
|
3265
|
+
const esc = p.replace(/[.]/g, "\\.");
|
|
3266
|
+
const attr = new RegExp(`${esc}:${name}\\s*=\\s*["']\\s*([^"'<]*?)\\s*["']`).exec(xmp);
|
|
3267
|
+
if (attr) return attr[1];
|
|
3268
|
+
return new RegExp(`<${esc}:${name}>\\s*([^<]*?)\\s*</${esc}:${name}>`).exec(xmp)?.[1];
|
|
3269
|
+
};
|
|
3270
|
+
for (const p of prefixes) {
|
|
3271
|
+
const part = field(p, "part");
|
|
3272
|
+
if (part === void 0) continue;
|
|
3273
|
+
if (!/^[1-4]$/.test(part)) return null;
|
|
3274
|
+
const c = field(p, "conformance");
|
|
3275
|
+
if (c === void 0 || c === "") return {
|
|
3276
|
+
part: Number(part),
|
|
3277
|
+
conformance: null
|
|
3278
|
+
};
|
|
3279
|
+
const upper = c.toUpperCase();
|
|
3280
|
+
if (!/^[ABUFE]$/.test(upper)) return null;
|
|
3281
|
+
return {
|
|
3282
|
+
part: Number(part),
|
|
3283
|
+
conformance: upper
|
|
3284
|
+
};
|
|
3285
|
+
}
|
|
3286
|
+
return null;
|
|
3287
|
+
}
|
|
3288
|
+
function readInfo(reader) {
|
|
3289
|
+
const { value: info, definition } = reader.resolveWithDefinition(reader.trailer.Info);
|
|
3290
|
+
const out = {
|
|
3291
|
+
fields: [],
|
|
3292
|
+
custom: 0,
|
|
3293
|
+
values: {}
|
|
3294
|
+
};
|
|
3295
|
+
if (!(info instanceof PdfDict)) return out;
|
|
3296
|
+
const keys = new Set(info.entries.map(([k]) => k));
|
|
3297
|
+
for (const field of INFO_FIELDS) {
|
|
3298
|
+
if (!keys.has(field)) continue;
|
|
3299
|
+
const { value, definition: own } = reader.resolveWithDefinition(info.get(field));
|
|
3300
|
+
if (value === null) continue;
|
|
3301
|
+
out.fields.push(field);
|
|
3302
|
+
if (value instanceof PdfName) out.values[field] = value.name;
|
|
3303
|
+
else if (value instanceof PdfString) {
|
|
3304
|
+
const holder = own ?? definition;
|
|
3305
|
+
let bytes = value.bytes();
|
|
3306
|
+
if (holder && reader.security && reader.encrypted(holder)) bytes = decryptString(reader.security, holder.num, holder.gen, bytes);
|
|
3307
|
+
out.values[field] = textOf(bytes);
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
for (const k of keys) if (!INFO_FIELDS.includes(k)) out.custom += 1;
|
|
3311
|
+
return out;
|
|
3312
|
+
}
|
|
3313
|
+
function readXmp(reader, catalog) {
|
|
3314
|
+
const { value, definition } = reader.resolveWithDefinition(catalog.get("Metadata"));
|
|
3315
|
+
if (!(value instanceof PdfDict) || !value.stream) return null;
|
|
3316
|
+
let bytes;
|
|
3317
|
+
try {
|
|
3318
|
+
bytes = reader.streamData(definition, value);
|
|
3319
|
+
} catch (error) {
|
|
3320
|
+
if (!(error instanceof PdfToolsError) || error.code !== "DAMAGED") throw error;
|
|
3321
|
+
reader.repaired = true;
|
|
3322
|
+
return null;
|
|
3323
|
+
}
|
|
3324
|
+
if (bytes[0] === 254 && bytes[1] === 255) return textOf(bytes);
|
|
3325
|
+
if (bytes[0] === 255 && bytes[1] === 254) return new TextDecoder("utf-16le").decode(bytes.subarray(2));
|
|
3326
|
+
return new TextDecoder("utf-8").decode(bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191 ? bytes.subarray(3) : bytes);
|
|
3327
|
+
}
|
|
3328
|
+
/** The catalog: the trailer's /Root, or else the latest catalog in force. */
|
|
3329
|
+
function findCatalog(reader) {
|
|
3330
|
+
const { value: root, definition } = reader.resolveWithDefinition(reader.trailer.Root);
|
|
3331
|
+
if (root instanceof PdfDict && root.has("Pages")) return root;
|
|
3332
|
+
if (definition?.undecodable) throw damaged("the catalog cannot be read");
|
|
3333
|
+
reader.repaired = true;
|
|
3334
|
+
let best;
|
|
3335
|
+
for (const d of reader.defs) {
|
|
3336
|
+
if (!(d.value instanceof PdfDict) || !isName(d.value.get("Type"), "Catalog") || reader.inForce(d.num) !== d) continue;
|
|
3337
|
+
if (!best || d.order > best.order) best = d;
|
|
3338
|
+
}
|
|
3339
|
+
if (!best) throw damaged("there is no catalog");
|
|
3340
|
+
return best.value;
|
|
3341
|
+
}
|
|
3342
|
+
function* analyse(snapshot, work) {
|
|
3343
|
+
const { bytes } = snapshot;
|
|
3344
|
+
const header = findHeader(bytes);
|
|
3345
|
+
const reader = new Reader(bytes, work, header.offset);
|
|
3346
|
+
yield* reader.scan();
|
|
3347
|
+
yield* reader.walk();
|
|
3348
|
+
yield* reader.readXrefStreams();
|
|
3349
|
+
yield* reader.readScannedHeaders();
|
|
3350
|
+
reader.readAllTrailers();
|
|
3351
|
+
for (;;) {
|
|
3352
|
+
const found = yield* reader.checkXrefOffsets();
|
|
3353
|
+
const sections = yield* reader.readXrefStreams();
|
|
3354
|
+
if (found === 0 && sections === 0) break;
|
|
3355
|
+
}
|
|
3356
|
+
yield* reader.rereadStreams();
|
|
3357
|
+
yield* reader.classifyObjWords();
|
|
3358
|
+
reader.buildChain();
|
|
3359
|
+
const encrypted = reader.openEncryption(snapshot.password);
|
|
3360
|
+
yield* reader.readObjectStreams();
|
|
3361
|
+
const catalog = findCatalog(reader);
|
|
3362
|
+
const pageSizes = yield* readPages(reader, catalog);
|
|
3363
|
+
const info = readInfo(reader);
|
|
3364
|
+
const xmp = readXmp(reader, catalog);
|
|
3365
|
+
const active = yield* countActive(reader);
|
|
3366
|
+
let version = header.version;
|
|
3367
|
+
const catalogVersion = reader.resolve(catalog.get("Version"));
|
|
3368
|
+
if (catalogVersion instanceof PdfName && /^\d\.\d$/.test(catalogVersion.name) && versionValue(catalogVersion.name) > versionValue(version)) version = catalogVersion.name;
|
|
3369
|
+
const first = reader.defs.filter((d) => !d.container && !d.hidden).reduce((a, d) => !a || d.offset < a.offset ? d : a, void 0);
|
|
3370
|
+
const linearized = first !== void 0 && first.value instanceof PdfDict && first.value.has("Linearized");
|
|
3371
|
+
return {
|
|
3372
|
+
inspection: {
|
|
3373
|
+
version,
|
|
3374
|
+
pages: pageSizes.length,
|
|
3375
|
+
pageSizes,
|
|
3376
|
+
encrypted,
|
|
3377
|
+
pdfa: xmp === null ? null : pdfaClaim(xmp),
|
|
3378
|
+
structure: {
|
|
3379
|
+
revisions: reader.revisions(linearized),
|
|
3380
|
+
xrefStreams: reader.xrefStreams,
|
|
3381
|
+
objectStreams: reader.objectStreams,
|
|
3382
|
+
linearized,
|
|
3383
|
+
shadowedObjects: reader.shadowedCount(),
|
|
3384
|
+
hiddenObjects: reader.defs.filter((d) => d.hidden && !d.container && !d.alternateOf).length,
|
|
3385
|
+
repaired: reader.repaired
|
|
3386
|
+
},
|
|
3387
|
+
metadata: {
|
|
3388
|
+
infoFields: info.fields,
|
|
3389
|
+
customInfoFields: info.custom,
|
|
3390
|
+
xmp: xmp !== null
|
|
3391
|
+
},
|
|
3392
|
+
active
|
|
3393
|
+
},
|
|
3394
|
+
metadata: {
|
|
3395
|
+
info: info.values,
|
|
3396
|
+
xmp
|
|
3397
|
+
}
|
|
3398
|
+
};
|
|
3399
|
+
}
|
|
3400
|
+
// src/options.ts
|
|
3401
|
+
const DEFAULT_LIMITS = Object.freeze({
|
|
3402
|
+
maxBytes: 2e7,
|
|
3403
|
+
maxPages: 2e3,
|
|
3404
|
+
maxObjects: 25e4,
|
|
3405
|
+
maxValues: 2e6,
|
|
3406
|
+
maxObjectValues: 1e5,
|
|
3407
|
+
maxSections: 1e4,
|
|
3408
|
+
maxInflateBytes: 1e8,
|
|
3409
|
+
maxStreamBytes: 2e7,
|
|
3410
|
+
maxDepth: 64,
|
|
3411
|
+
timeoutMs: 1e4
|
|
3412
|
+
});
|
|
3413
|
+
const invalid = (path, message) => new PdfToolsError("INVALID_ARGUMENT", `${path}: ${message}`, { path });
|
|
3414
|
+
/** Runs `get`; whatever it throws that is not a `PdfToolsError` (a getter, a proxy trap) is `INVALID_ARGUMENT` at `path`. */
|
|
3415
|
+
function read(path, get) {
|
|
3416
|
+
try {
|
|
3417
|
+
return get();
|
|
3418
|
+
} catch (error) {
|
|
3419
|
+
if (error instanceof PdfToolsError) throw error;
|
|
3420
|
+
throw invalid(path, "cannot be read");
|
|
3421
|
+
}
|
|
3422
|
+
}
|
|
3423
|
+
/** A plain object: not an array, with `Object.prototype` or no prototype. */
|
|
3424
|
+
const isPlain = (value) => {
|
|
3425
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
3426
|
+
const prototype = Object.getPrototypeOf(value);
|
|
3427
|
+
return prototype === Object.prototype || prototype === null;
|
|
3428
|
+
};
|
|
3429
|
+
const TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
3430
|
+
const builtIn = (name) => Object.getOwnPropertyDescriptor(TypedArrayPrototype, name);
|
|
3431
|
+
const kindOf = builtIn(Symbol.toStringTag).get;
|
|
3432
|
+
const lengthOf = builtIn("byteLength").get;
|
|
3433
|
+
const copyInto = builtIn("set").value;
|
|
3434
|
+
/**
|
|
3435
|
+
* A private copy of the input (a `Uint8Array`, a `Buffer` or another subclass), after its length is checked
|
|
3436
|
+
* against `maxBytes`. The length is read with the built-in accessor, so an own `byteLength` cannot hide bytes.
|
|
3437
|
+
*/
|
|
3438
|
+
function copyBytes(value, maxBytes) {
|
|
3439
|
+
let kind;
|
|
3440
|
+
try {
|
|
3441
|
+
kind = kindOf.call(value);
|
|
3442
|
+
} catch {
|
|
3443
|
+
kind = void 0;
|
|
3444
|
+
}
|
|
3445
|
+
if (kind !== "Uint8Array") throw invalid("bytes", "must be a Uint8Array");
|
|
3446
|
+
const length = lengthOf.call(value);
|
|
3447
|
+
if (length > maxBytes) throw new PdfToolsError("LIMIT_EXCEEDED", `the input is larger than ${maxBytes} bytes (limit maxBytes)`, {
|
|
3448
|
+
limit: "maxBytes",
|
|
3449
|
+
value: maxBytes
|
|
3450
|
+
});
|
|
3451
|
+
const copy = new Uint8Array(length);
|
|
3452
|
+
try {
|
|
3453
|
+
copyInto.call(copy, value);
|
|
3454
|
+
} catch {
|
|
3455
|
+
throw invalid("bytes", "cannot be read");
|
|
3456
|
+
}
|
|
3457
|
+
return copy;
|
|
3458
|
+
}
|
|
3459
|
+
/** Whether a signal is aborted. A signal whose `aborted` cannot be read counts as aborted. */
|
|
3460
|
+
function isAborted(signal) {
|
|
3461
|
+
try {
|
|
3462
|
+
return signal.aborted === true;
|
|
3463
|
+
} catch {
|
|
3464
|
+
return true;
|
|
3465
|
+
}
|
|
3466
|
+
}
|
|
3467
|
+
function readSignal(value) {
|
|
3468
|
+
if (value === void 0) return void 0;
|
|
3469
|
+
if (!read("options.signal", () => {
|
|
3470
|
+
const signal = value;
|
|
3471
|
+
return typeof signal === "object" && signal !== null && typeof signal.addEventListener === "function";
|
|
3472
|
+
})) throw invalid("options.signal", "must be an AbortSignal");
|
|
3473
|
+
let aborted;
|
|
3474
|
+
try {
|
|
3475
|
+
aborted = value.aborted;
|
|
3476
|
+
} catch {
|
|
3477
|
+
aborted = true;
|
|
3478
|
+
}
|
|
3479
|
+
if (aborted === true) throw new PdfToolsError("ABORTED", "the call was aborted");
|
|
3480
|
+
if (aborted !== false) throw invalid("options.signal", "must be an AbortSignal");
|
|
3481
|
+
return value;
|
|
3482
|
+
}
|
|
3483
|
+
function readLimits(value) {
|
|
3484
|
+
const limits = { ...DEFAULT_LIMITS };
|
|
3485
|
+
if (value === void 0) return limits;
|
|
3486
|
+
const keys = read("options.limits", () => isPlain(value) ? Object.keys(value) : void 0);
|
|
3487
|
+
if (keys === void 0) throw invalid("options.limits", "must be a plain object");
|
|
3488
|
+
for (const key of keys) {
|
|
3489
|
+
if (!Object.hasOwn(DEFAULT_LIMITS, key)) throw invalid(`options.limits.${key}`, "unknown limit");
|
|
3490
|
+
const limit = read(`options.limits.${key}`, () => value[key]);
|
|
3491
|
+
if (limit === void 0) continue;
|
|
3492
|
+
const least = key === "timeoutMs" ? 1 : 0;
|
|
3493
|
+
if (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < least) throw invalid(`options.limits.${key}`, `must be a whole number of at least ${least}`);
|
|
3494
|
+
limits[key] = limit;
|
|
3495
|
+
}
|
|
3496
|
+
return limits;
|
|
3497
|
+
}
|
|
3498
|
+
const OPTION_KEYS = [
|
|
3499
|
+
"limits",
|
|
3500
|
+
"signal",
|
|
3501
|
+
"password"
|
|
3502
|
+
];
|
|
3503
|
+
/** Reads and checks the arguments of `open` and `inspect`, and copies the input. */
|
|
3504
|
+
function readArguments(bytes, options) {
|
|
3505
|
+
let limits = { ...DEFAULT_LIMITS };
|
|
3506
|
+
let signal;
|
|
3507
|
+
let password;
|
|
3508
|
+
if (options !== void 0) {
|
|
3509
|
+
const keys = read("options", () => isPlain(options) ? Object.keys(options) : void 0);
|
|
3510
|
+
if (keys === void 0) throw invalid("options", "must be a plain object");
|
|
3511
|
+
for (const key of keys) if (!OPTION_KEYS.includes(key)) throw invalid(`options.${key}`, "unknown option");
|
|
3512
|
+
const o = options;
|
|
3513
|
+
limits = readLimits(read("options.limits", () => o.limits));
|
|
3514
|
+
signal = readSignal(read("options.signal", () => o.signal));
|
|
3515
|
+
const p = read("options.password", () => o.password);
|
|
3516
|
+
if (p !== void 0 && typeof p !== "string") throw invalid("options.password", "must be a string");
|
|
3517
|
+
password = p;
|
|
3518
|
+
}
|
|
3519
|
+
return {
|
|
3520
|
+
bytes: copyBytes(bytes, limits.maxBytes),
|
|
3521
|
+
limits,
|
|
3522
|
+
signal,
|
|
3523
|
+
password
|
|
3524
|
+
};
|
|
3525
|
+
}
|
|
3526
|
+
// src/work.ts
|
|
3527
|
+
/**
|
|
3528
|
+
* The budget of one call: the limits, the counters that are checked against them, the time limit and the
|
|
3529
|
+
* abort signal. Every loop over the file calls `checkpoint` (through the counters or directly), so no step
|
|
3530
|
+
* runs long unchecked.
|
|
3531
|
+
*/
|
|
3532
|
+
var Work = class {
|
|
3533
|
+
limits;
|
|
3534
|
+
signal;
|
|
3535
|
+
started;
|
|
3536
|
+
objects = 0;
|
|
3537
|
+
values = 0;
|
|
3538
|
+
inflated = 0;
|
|
3539
|
+
entries = 0;
|
|
3540
|
+
sections = 0;
|
|
3541
|
+
constructor(limits, signal) {
|
|
3542
|
+
this.limits = limits;
|
|
3543
|
+
this.signal = signal;
|
|
3544
|
+
this.started = performance.now();
|
|
3545
|
+
}
|
|
3546
|
+
/** Throws `ABORTED` when the signal is aborted and `TIMEOUT` when the time limit has passed. */
|
|
3547
|
+
checkpoint() {
|
|
3548
|
+
if (this.signal && isAborted(this.signal)) throw new PdfToolsError("ABORTED", "the call was aborted");
|
|
3549
|
+
if (performance.now() - this.started > this.limits.timeoutMs) {
|
|
3550
|
+
const value = this.limits.timeoutMs;
|
|
3551
|
+
throw new PdfToolsError("TIMEOUT", `the call took longer than ${value} ms (limit timeoutMs)`, {
|
|
3552
|
+
limit: "timeoutMs",
|
|
3553
|
+
value
|
|
3554
|
+
});
|
|
3555
|
+
}
|
|
3556
|
+
}
|
|
3557
|
+
/** One more object definition read, or tried. */
|
|
3558
|
+
object() {
|
|
3559
|
+
this.objects += 1;
|
|
3560
|
+
if (this.objects > this.limits.maxObjects) throw limitError("maxObjects", this.limits.maxObjects, "too many objects");
|
|
3561
|
+
if ((this.objects & 255) === 0) this.checkpoint();
|
|
3562
|
+
}
|
|
3563
|
+
/** `n` more object definitions announced (an object stream's /N), before any of them is read. */
|
|
3564
|
+
announce(n) {
|
|
3565
|
+
if (this.objects + n > this.limits.maxObjects) throw limitError("maxObjects", this.limits.maxObjects, "too many objects");
|
|
3566
|
+
}
|
|
3567
|
+
/** `n` more cross-reference entries, in all tables and streams together; they count against maxObjects. */
|
|
3568
|
+
xrefEntries(n) {
|
|
3569
|
+
this.entries += n;
|
|
3570
|
+
if (this.entries > this.limits.maxObjects) throw limitError("maxObjects", this.limits.maxObjects, "too many cross-reference entries");
|
|
3571
|
+
this.checkpoint();
|
|
3572
|
+
}
|
|
3573
|
+
/** One more cross-reference section (a table or a stream). */
|
|
3574
|
+
section() {
|
|
3575
|
+
this.sections += 1;
|
|
3576
|
+
if (this.sections > this.limits.maxSections) throw limitError("maxSections", this.limits.maxSections, "too many cross-reference sections");
|
|
3577
|
+
if ((this.sections & 255) === 0) this.checkpoint();
|
|
3578
|
+
}
|
|
3579
|
+
/** Throws `LIMIT_EXCEEDED` (maxValues) when `n` more values would pass the limit; nothing is counted. */
|
|
3580
|
+
reserveValues(n) {
|
|
3581
|
+
if (this.values + n > this.limits.maxValues) throw limitError("maxValues", this.limits.maxValues, "too many values");
|
|
3582
|
+
}
|
|
3583
|
+
/** One more value parsed. */
|
|
3584
|
+
value() {
|
|
3585
|
+
this.values += 1;
|
|
3586
|
+
if (this.values > this.limits.maxValues) throw limitError("maxValues", this.limits.maxValues, "too many values");
|
|
3587
|
+
if ((this.values & 1023) === 0) this.checkpoint();
|
|
3588
|
+
}
|
|
3589
|
+
/** The most bytes the next decompression may produce, and the limit that bounds it. */
|
|
3590
|
+
inflateRoom() {
|
|
3591
|
+
const total = this.limits.maxInflateBytes - this.inflated;
|
|
3592
|
+
return total < this.limits.maxStreamBytes ? {
|
|
3593
|
+
room: Math.max(0, total),
|
|
3594
|
+
limit: "maxInflateBytes"
|
|
3595
|
+
} : {
|
|
3596
|
+
room: this.limits.maxStreamBytes,
|
|
3597
|
+
limit: "maxStreamBytes"
|
|
3598
|
+
};
|
|
3599
|
+
}
|
|
3600
|
+
/** `n` more bytes produced by decompression. */
|
|
3601
|
+
inflate(n) {
|
|
3602
|
+
if (n > this.limits.maxStreamBytes) throw limitError("maxStreamBytes", this.limits.maxStreamBytes, "a stream decompresses to too many bytes");
|
|
3603
|
+
this.inflated += n;
|
|
3604
|
+
if (this.inflated > this.limits.maxInflateBytes) throw limitError("maxInflateBytes", this.limits.maxInflateBytes, "the streams decompress to too many bytes");
|
|
3605
|
+
this.checkpoint();
|
|
3606
|
+
}
|
|
3607
|
+
};
|
|
3608
|
+
/** A macrotask, so that timers, I/O and the abort signal's events run before the work continues. */
|
|
3609
|
+
const nextTurn = () => new Promise((resolve) => setImmediate(resolve));
|
|
3610
|
+
/** Time the work runs between two turns given to the event loop. */
|
|
3611
|
+
const SLICE_MS = 8;
|
|
3612
|
+
/**
|
|
3613
|
+
* Runs a generator to the end and returns its result. It yields between small steps; after each slice of
|
|
3614
|
+
* `SLICE_MS` it gives the event loop a turn (so an abort can arrive) and checks the budget.
|
|
3615
|
+
*/
|
|
3616
|
+
async function drive(steps, work) {
|
|
3617
|
+
let slice = performance.now();
|
|
3618
|
+
for (;;) {
|
|
3619
|
+
const step = steps.next();
|
|
3620
|
+
if (step.done) return step.value;
|
|
3621
|
+
if (performance.now() - slice > SLICE_MS) {
|
|
3622
|
+
await nextTurn();
|
|
3623
|
+
work.checkpoint();
|
|
3624
|
+
slice = performance.now();
|
|
3625
|
+
}
|
|
3626
|
+
}
|
|
3627
|
+
}
|
|
3628
|
+
// src/index.ts
|
|
3629
|
+
/** The default limits, for untrusted uploads of up to 20 MB. */
|
|
3630
|
+
const defaultLimits = DEFAULT_LIMITS;
|
|
3631
|
+
var OpenedDoc = class {
|
|
3632
|
+
#analysis;
|
|
3633
|
+
pageCount;
|
|
3634
|
+
constructor(analysis) {
|
|
3635
|
+
this.#analysis = analysis;
|
|
3636
|
+
this.pageCount = analysis.inspection.pages;
|
|
3637
|
+
}
|
|
3638
|
+
inspect() {
|
|
3639
|
+
return structuredClone(this.#analysis.inspection);
|
|
3640
|
+
}
|
|
3641
|
+
readMetadata() {
|
|
3642
|
+
return structuredClone(this.#analysis.metadata);
|
|
3643
|
+
}
|
|
3644
|
+
};
|
|
3645
|
+
/**
|
|
3646
|
+
* Opens a PDF under the limits and reads everything `inspect` and `readMetadata` report. Rejects with
|
|
3647
|
+
* `PdfToolsError` for every problem; anything that cannot be read within the limits is an error, never an
|
|
3648
|
+
* empty report.
|
|
3649
|
+
*/
|
|
3650
|
+
async function open(bytes, options) {
|
|
3651
|
+
const snapshot = readArguments(bytes, options);
|
|
3652
|
+
const work = new Work(snapshot.limits, snapshot.signal);
|
|
3653
|
+
try {
|
|
3654
|
+
work.checkpoint();
|
|
3655
|
+
return new OpenedDoc(await drive(analyse(snapshot, work), work));
|
|
3656
|
+
} catch (error) {
|
|
3657
|
+
if (error instanceof PdfToolsError) throw error;
|
|
3658
|
+
throw new PdfToolsError("INTERNAL", "an internal error occurred; please report it", { reason: error instanceof Error ? error.constructor.name : typeof error });
|
|
3659
|
+
}
|
|
3660
|
+
}
|
|
3661
|
+
/** `open(bytes, options)`, then `inspect()`. */
|
|
3662
|
+
async function inspect(bytes, options) {
|
|
3663
|
+
return (await open(bytes, options)).inspect();
|
|
3664
|
+
}
|
|
3665
|
+
export { PdfToolsError, defaultLimits, inspect, open };
|