@patrickdk77/xfa-flatten 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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +14 -0
  4. package/README.md +112 -2
  5. package/dist/barcode-paint.d.ts +11 -0
  6. package/dist/barcode-paint.js +135 -0
  7. package/dist/barcode.d.ts +45 -0
  8. package/dist/barcode.js +750 -0
  9. package/dist/canvas.d.ts +59 -0
  10. package/dist/canvas.js +179 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +34 -0
  13. package/dist/css.d.ts +48 -0
  14. package/dist/css.js +288 -0
  15. package/dist/deadline.d.ts +6 -0
  16. package/dist/deadline.js +18 -0
  17. package/dist/filters.d.ts +21 -0
  18. package/dist/filters.js +296 -0
  19. package/dist/flatten.d.ts +25 -0
  20. package/dist/flatten.js +319 -0
  21. package/dist/font-metrics.d.ts +9 -0
  22. package/dist/font-metrics.js +215 -0
  23. package/dist/fonts.d.ts +36 -0
  24. package/dist/fonts.js +144 -0
  25. package/dist/images.d.ts +23 -0
  26. package/dist/images.js +519 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.js +5 -0
  29. package/dist/index.mjs +3 -0
  30. package/dist/layout.d.ts +64 -0
  31. package/dist/layout.js +779 -0
  32. package/dist/limits.d.ts +2 -0
  33. package/dist/limits.js +6 -0
  34. package/dist/locale.d.ts +29 -0
  35. package/dist/locale.js +97 -0
  36. package/dist/paint.d.ts +15 -0
  37. package/dist/paint.js +533 -0
  38. package/dist/pdf-crypt.d.ts +35 -0
  39. package/dist/pdf-crypt.js +261 -0
  40. package/dist/pdf-read.d.ts +140 -0
  41. package/dist/pdf-read.js +1026 -0
  42. package/dist/pdf417-table.d.ts +2 -0
  43. package/dist/pdf417-table.js +146 -0
  44. package/dist/pdfjs-repair.d.ts +13 -0
  45. package/dist/pdfjs-repair.js +257 -0
  46. package/dist/pdfjs.d.ts +16 -0
  47. package/dist/pdfjs.js +62 -0
  48. package/dist/picture.d.ts +40 -0
  49. package/dist/picture.js +678 -0
  50. package/dist/saslprep.d.ts +11 -0
  51. package/dist/saslprep.js +178 -0
  52. package/dist/style.d.ts +29 -0
  53. package/dist/style.js +178 -0
  54. package/dist/text.d.ts +44 -0
  55. package/dist/text.js +199 -0
  56. package/dist/tiff.d.ts +3 -0
  57. package/dist/tiff.js +270 -0
  58. package/dist/tree.d.ts +23 -0
  59. package/dist/tree.js +54 -0
  60. package/dist/types.d.ts +31 -0
  61. package/dist/types.js +2 -0
  62. package/dist/writer.d.ts +38 -0
  63. package/dist/writer.js +145 -0
  64. package/dist/xfa-apply.d.ts +49 -0
  65. package/dist/xfa-apply.js +617 -0
  66. package/dist/xfa-model.d.ts +42 -0
  67. package/dist/xfa-model.js +227 -0
  68. package/dist/xfa-paint.d.ts +24 -0
  69. package/dist/xfa-paint.js +275 -0
  70. package/dist/xfa-spec.d.ts +47 -0
  71. package/dist/xfa-spec.js +3 -0
  72. package/dist/xml.d.ts +30 -0
  73. package/dist/xml.js +211 -0
  74. package/package.json +83 -4
@@ -0,0 +1,1026 @@
1
+ "use strict";
2
+ // A small PDF object reader with one job: return the XFA packets (template, datasets, config, localeSet) from a
3
+ // PDF's /AcroForm /XFA entry, decrypted and decoded. pdf.js lays the form out but hands out none of the XML.
4
+ // It reads cross-reference tables and streams, object streams, the common filters and the standard security
5
+ // handler, and rebuilds the object table by scanning when the cross-references are broken.
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.PdfReader = exports.Meter = exports.PStream = exports.PString = exports.PRef = exports.PName = exports.XFA_LIMIT = exports.DECODE_LIMIT = void 0;
8
+ exports.isDict = isDict;
9
+ exports.readXfa = readXfa;
10
+ exports.openingPassword = openingPassword;
11
+ exports.inspectPdf = inspectPdf;
12
+ exports.readXfaPackets = readXfaPackets;
13
+ exports.readPackets = readPackets;
14
+ exports.joinPackets = joinPackets;
15
+ const deadline_1 = require("./deadline");
16
+ const filters_1 = require("./filters");
17
+ const pdf_crypt_1 = require("./pdf-crypt");
18
+ /**
19
+ * The most bytes the stream filters may produce for one reader, over all the streams it decodes: 64 MiB. The XFA
20
+ * packets of the largest form in the test corpus decode to 2.4 MB in all. A stream past the limit reads as
21
+ * undecodable.
22
+ */
23
+ exports.DECODE_LIMIT = 64 * 1024 * 1024;
24
+ /**
25
+ * The most the XFA packets may decode to, all together: 16 MiB, about seven times the largest form in the test
26
+ * corpus. pdf.js holds several copies of the XFA while it lays a form out, so this also bounds its memory; a larger
27
+ * form is not handed to pdf.js at all.
28
+ */
29
+ exports.XFA_LIMIT = 16 * 1024 * 1024;
30
+ /** The parsing budget is this many times the file's length (plus PARSE_SLACK) in bytes walked by the lexers. */
31
+ const PARSE_FACTOR = 16;
32
+ const PARSE_SLACK = 8 * 1024 * 1024;
33
+ class PName {
34
+ name;
35
+ constructor(name) {
36
+ this.name = name;
37
+ }
38
+ }
39
+ exports.PName = PName;
40
+ class PRef {
41
+ num;
42
+ gen;
43
+ constructor(num, gen) {
44
+ this.num = num;
45
+ this.gen = gen;
46
+ }
47
+ }
48
+ exports.PRef = PRef;
49
+ class PString {
50
+ bytes;
51
+ constructor(bytes) {
52
+ this.bytes = bytes;
53
+ }
54
+ }
55
+ exports.PString = PString;
56
+ class PStream {
57
+ dict;
58
+ raw;
59
+ constructor(dict, raw) {
60
+ this.dict = dict;
61
+ this.raw = raw;
62
+ }
63
+ }
64
+ exports.PStream = PStream;
65
+ const WS = new Set([0, 9, 10, 12, 13, 32]);
66
+ const DELIM = new Set([0x28, 0x29, 0x3c, 0x3e, 0x5b, 0x5d, 0x7b, 0x7d, 0x2f, 0x25]);
67
+ function isDict(v) {
68
+ return v instanceof Map;
69
+ }
70
+ /** Thrown once a reader has spent its parsing budget; every later parse fails at once. */
71
+ class BudgetError extends Error {
72
+ }
73
+ /**
74
+ * Counts the bytes a reader's lexers walk. A hostile file can make each of many parses run to the end of the file (an
75
+ * unclosed string after every 'trailer', say); the budget turns that quadratic walk into a failure after a bounded
76
+ * amount of work. A well-formed file walks about its own length.
77
+ */
78
+ class Meter {
79
+ limit;
80
+ deadline;
81
+ used = 0;
82
+ /** Set once the budget has run out. */
83
+ exhausted = false;
84
+ constructor(limit, deadline) {
85
+ this.limit = limit;
86
+ this.deadline = deadline;
87
+ }
88
+ spend(n) {
89
+ this.used += n;
90
+ this.check();
91
+ }
92
+ check() {
93
+ if (this.used > this.limit) {
94
+ this.exhausted = true;
95
+ throw new BudgetError('the PDF needs too much parsing');
96
+ }
97
+ if (this.deadline !== undefined && Date.now() > this.deadline)
98
+ throw new deadline_1.DeadlineError();
99
+ }
100
+ }
101
+ exports.Meter = Meter;
102
+ class Lexer {
103
+ b;
104
+ meter;
105
+ pos;
106
+ constructor(b, start, meter) {
107
+ this.b = b;
108
+ this.meter = meter;
109
+ this.pos = start;
110
+ }
111
+ skipSpace() {
112
+ const b = this.b;
113
+ while (this.pos < b.length) {
114
+ const c = b[this.pos];
115
+ if (WS.has(c))
116
+ this.pos++;
117
+ else if (c === 0x25) {
118
+ while (this.pos < b.length && b[this.pos] !== 10 && b[this.pos] !== 13)
119
+ this.pos++;
120
+ }
121
+ else
122
+ break;
123
+ }
124
+ }
125
+ /** Reads a regular token (keyword or number) at pos, without consuming delimiters. */
126
+ word() {
127
+ const b = this.b;
128
+ const start = this.pos;
129
+ while (this.pos < b.length && !WS.has(b[this.pos]) && !DELIM.has(b[this.pos]))
130
+ this.pos++;
131
+ return Buffer.from(b.subarray(start, this.pos)).toString('latin1');
132
+ }
133
+ peekWord() {
134
+ const save = this.pos;
135
+ this.skipSpace();
136
+ const w = this.word();
137
+ this.pos = save;
138
+ return w;
139
+ }
140
+ value(depth = 0) {
141
+ if (depth > 0 || !this.meter)
142
+ return this.parseValue(depth);
143
+ this.meter.check();
144
+ const start = this.pos;
145
+ try {
146
+ return this.parseValue(depth);
147
+ }
148
+ finally {
149
+ this.meter.spend(Math.max(0, this.pos - start));
150
+ }
151
+ }
152
+ parseValue(depth) {
153
+ if (depth > 100)
154
+ throw new Error('nesting too deep');
155
+ this.skipSpace();
156
+ const b = this.b;
157
+ if (this.pos >= b.length)
158
+ throw new Error('unexpected end');
159
+ const c = b[this.pos];
160
+ if (c === 0x2f) {
161
+ this.pos++;
162
+ const raw = this.word();
163
+ return new PName(raw.replace(/#([0-9a-fA-F]{2})/g, (_m, h) => String.fromCharCode(Number.parseInt(h, 16))));
164
+ }
165
+ if (c === 0x28)
166
+ return this.literal();
167
+ if (c === 0x3c) {
168
+ if (b[this.pos + 1] === 0x3c) {
169
+ this.pos += 2;
170
+ const d = new Map();
171
+ while (true) {
172
+ this.skipSpace();
173
+ if (this.pos >= b.length)
174
+ throw new Error('unterminated dictionary');
175
+ if (b[this.pos] === 0x3e && b[this.pos + 1] === 0x3e) {
176
+ this.pos += 2;
177
+ break;
178
+ }
179
+ const k = this.value(depth + 1);
180
+ if (!(k instanceof PName)) {
181
+ if (typeof k === 'string' && k === 'endobj')
182
+ throw new Error('unterminated dictionary');
183
+ continue;
184
+ }
185
+ const v = this.value(depth + 1);
186
+ d.set(k.name, v);
187
+ }
188
+ return d;
189
+ }
190
+ this.pos++;
191
+ const start = this.pos;
192
+ while (this.pos < b.length && b[this.pos] !== 0x3e)
193
+ this.pos++;
194
+ const s = (0, filters_1.asciiHexDecode)(b.subarray(start, this.pos));
195
+ this.pos++;
196
+ return new PString(s);
197
+ }
198
+ if (c === 0x5b) {
199
+ this.pos++;
200
+ const arr = [];
201
+ while (true) {
202
+ this.skipSpace();
203
+ if (this.pos >= b.length)
204
+ throw new Error('unterminated array');
205
+ if (b[this.pos] === 0x5d) {
206
+ this.pos++;
207
+ break;
208
+ }
209
+ arr.push(this.value(depth + 1));
210
+ }
211
+ return arr;
212
+ }
213
+ if (c === 0x5d || c === 0x3e || c === 0x29 || c === 0x7b || c === 0x7d) {
214
+ this.pos++;
215
+ return null;
216
+ }
217
+ const w = this.word();
218
+ if (w === '') {
219
+ this.pos++;
220
+ return null;
221
+ }
222
+ if (/^[+-]?(\d+\.?\d*|\.\d+)$/.test(w)) {
223
+ // An integer followed by an integer and R is a reference.
224
+ if (/^\d+$/.test(w)) {
225
+ const save = this.pos;
226
+ this.skipSpace();
227
+ const g = this.word();
228
+ if (/^\d+$/.test(g)) {
229
+ this.skipSpace();
230
+ const r = this.word();
231
+ if (r === 'R')
232
+ return new PRef(Number(w), Number(g));
233
+ }
234
+ this.pos = save;
235
+ }
236
+ return Number(w);
237
+ }
238
+ if (w === 'true')
239
+ return true;
240
+ if (w === 'false')
241
+ return false;
242
+ if (w === 'null')
243
+ return null;
244
+ return w;
245
+ }
246
+ literal() {
247
+ const b = this.b;
248
+ this.pos++;
249
+ const out = [];
250
+ let depth = 1;
251
+ while (this.pos < b.length) {
252
+ const c = b[this.pos++];
253
+ if (c === 0x5c) {
254
+ const e = b[this.pos++];
255
+ if (e === 0x6e)
256
+ out.push(10);
257
+ else if (e === 0x72)
258
+ out.push(13);
259
+ else if (e === 0x74)
260
+ out.push(9);
261
+ else if (e === 0x62)
262
+ out.push(8);
263
+ else if (e === 0x66)
264
+ out.push(12);
265
+ else if (e === 13) {
266
+ if (b[this.pos] === 10)
267
+ this.pos++;
268
+ }
269
+ else if (e === 10) {
270
+ // line continuation
271
+ }
272
+ else if (e >= 0x30 && e <= 0x37) {
273
+ let v = e - 0x30;
274
+ for (let k = 0; k < 2 && b[this.pos] >= 0x30 && b[this.pos] <= 0x37; k++)
275
+ v = v * 8 + (b[this.pos++] - 0x30);
276
+ out.push(v & 255);
277
+ }
278
+ else if (e !== undefined)
279
+ out.push(e);
280
+ }
281
+ else if (c === 0x28) {
282
+ depth++;
283
+ out.push(c);
284
+ }
285
+ else if (c === 0x29) {
286
+ depth--;
287
+ if (depth === 0)
288
+ break;
289
+ out.push(c);
290
+ }
291
+ else
292
+ out.push(c);
293
+ }
294
+ return new PString(Uint8Array.from(out));
295
+ }
296
+ }
297
+ function indexOf(b, needle, from) {
298
+ return Buffer.from(b.buffer, b.byteOffset, b.byteLength).indexOf(needle, from, 'latin1');
299
+ }
300
+ function lastIndexOf(b, needle, from) {
301
+ return Buffer.from(b.buffer, b.byteOffset, b.byteLength).lastIndexOf(needle, from, 'latin1');
302
+ }
303
+ function numberOf(v, fallback = 0) {
304
+ return typeof v === 'number' && Number.isFinite(v) ? v : fallback;
305
+ }
306
+ class PdfReader {
307
+ b;
308
+ xref = new Map();
309
+ trailer = new Map();
310
+ decryptor = null;
311
+ encryptRef = null;
312
+ cache = new Map();
313
+ objStmCache = new Map();
314
+ resolving = new Set();
315
+ /** The offset the final startxref gives, whether or not a cross-reference section is there; null without one. */
316
+ lastXref = null;
317
+ wasRebuilt = false;
318
+ meter;
319
+ /** Bytes the stream filters may still produce, over all streams this reader decodes. */
320
+ decodeBudget = exports.DECODE_LIMIT;
321
+ /** Set when a stream or the XFA as a whole was refused for its decoded size. */
322
+ oversize = false;
323
+ /** True once reading this file has spent its parsing budget: a damaged or crafted structure. */
324
+ get overBudget() {
325
+ return this.meter.exhausted;
326
+ }
327
+ constructor(b, deadline) {
328
+ this.b = b;
329
+ this.meter = new Meter(PARSE_FACTOR * b.length + PARSE_SLACK, deadline);
330
+ }
331
+ /** A trailer entry as written, not decrypted. */
332
+ trailerEntry(key) {
333
+ return this.trailer.get(key);
334
+ }
335
+ /** The offset a new cross-reference section's /Prev points at. */
336
+ get previousXref() {
337
+ return this.lastXref;
338
+ }
339
+ /** True when the cross-references could not be read and the object table was rebuilt by scanning. */
340
+ get rebuilt() {
341
+ return this.wasRebuilt;
342
+ }
343
+ /** Every object written at an offset: number, offset and generation. Null when some object is in an object stream. */
344
+ offsetEntries() {
345
+ const out = [];
346
+ for (const [n, e] of this.xref) {
347
+ if (e.kind !== 'offset')
348
+ return null;
349
+ if (e.offset > 0)
350
+ out.push([n, e.offset, e.gen]);
351
+ }
352
+ return out;
353
+ }
354
+ /** The highest object number in use plus one. */
355
+ get size() {
356
+ let max = numberOf(this.trailer.get('Size'));
357
+ for (const n of this.xref.keys())
358
+ max = Math.max(max, n + 1);
359
+ return max;
360
+ }
361
+ /** The generation of an object written at an offset; 0 for one in an object stream or not in the table. */
362
+ generation(n) {
363
+ const e = this.xref.get(n);
364
+ return e && e.kind === 'offset' ? e.gen : 0;
365
+ }
366
+ /** The decryptor once a password has opened the file; null when the file is not encrypted. */
367
+ get security() {
368
+ return this.decryptor;
369
+ }
370
+ /** Opens the file; null when it cannot be parsed or no password decrypts it. */
371
+ static open(bytes, passwords, deadline) {
372
+ return PdfReader.attempt(bytes, passwords, deadline).reader;
373
+ }
374
+ /** open, also telling whether the file spent the parsing budget (whether or not it opened). */
375
+ static attempt(bytes, passwords, deadline) {
376
+ const r = new PdfReader(bytes, deadline);
377
+ let ok = false;
378
+ try {
379
+ ok = r.init(passwords);
380
+ }
381
+ catch (e) {
382
+ if (e instanceof deadline_1.DeadlineError)
383
+ throw e;
384
+ }
385
+ return { reader: ok ? r : null, overBudget: r.overBudget };
386
+ }
387
+ init(passwords) {
388
+ let ok = false;
389
+ try {
390
+ ok = this.readXrefChain();
391
+ }
392
+ catch {
393
+ ok = false;
394
+ }
395
+ if (!ok || !(this.trailer.get('Root') instanceof PRef)) {
396
+ this.wasRebuilt = true;
397
+ this.xref.clear();
398
+ this.trailer = new Map();
399
+ this.rebuild();
400
+ }
401
+ if (!this.trailer.get('Root'))
402
+ return false;
403
+ const enc = this.trailer.get('Encrypt');
404
+ if (enc === undefined || enc === null)
405
+ return true;
406
+ if (enc instanceof PRef)
407
+ this.encryptRef = enc;
408
+ const info = this.encryptInfo(this.resolve(enc));
409
+ if (!info)
410
+ return false;
411
+ this.decryptor = pdf_crypt_1.Decryptor.open(info, passwords);
412
+ return this.decryptor !== null;
413
+ }
414
+ encryptInfo(v) {
415
+ if (!isDict(v))
416
+ return null;
417
+ const filter = v.get('Filter');
418
+ if (!(filter instanceof PName) || filter.name !== 'Standard')
419
+ return null;
420
+ const bytesOf = (x) => (x instanceof PString ? x.bytes : null);
421
+ const o = bytesOf(this.resolve(v.get('O') ?? null));
422
+ const u = bytesOf(this.resolve(v.get('U') ?? null));
423
+ if (!o || !u)
424
+ return null;
425
+ const ids = this.resolve(this.trailer.get('ID') ?? null);
426
+ const id0 = Array.isArray(ids) && ids[0] instanceof PString ? ids[0].bytes : new Uint8Array(0);
427
+ const vv = numberOf(this.resolve(v.get('V') ?? null));
428
+ const r = numberOf(this.resolve(v.get('R') ?? null), 2);
429
+ const methodOf = (key) => {
430
+ if (vv < 4)
431
+ return 'rc4';
432
+ const name = v.get(key);
433
+ const cfName = name instanceof PName ? name.name : 'Identity';
434
+ if (cfName === 'Identity')
435
+ return 'none';
436
+ const cf = this.resolve(v.get('CF') ?? null);
437
+ const entry = isDict(cf) ? this.resolve(cf.get(cfName) ?? null) : null;
438
+ const cfm = isDict(entry) ? entry.get('CFM') : null;
439
+ const m = cfm instanceof PName ? cfm.name : 'None';
440
+ if (m === 'AESV2')
441
+ return 'aes128';
442
+ if (m === 'AESV3')
443
+ return 'aes256';
444
+ if (m === 'V2')
445
+ return 'rc4';
446
+ return 'none';
447
+ };
448
+ // Key length: /Length for V1 to V3 (40 by default). For V4 and up, pdf.js and the spec take the stream crypt
449
+ // filter's /Length (in bytes when under 40), defaulting to 128 bits; the top-level /Length is optional there.
450
+ const keyBits = () => {
451
+ if (vv < 4)
452
+ return numberOf(this.resolve(v.get('Length') ?? null), 40);
453
+ const cf = this.resolve(v.get('CF') ?? null);
454
+ const stmF = v.get('StmF');
455
+ const entry = isDict(cf) && stmF instanceof PName ? this.resolve(cf.get(stmF.name) ?? null) : null;
456
+ const n = isDict(entry) ? numberOf(this.resolve(entry.get('Length') ?? null), 0) : 0;
457
+ if (n <= 0)
458
+ return 128;
459
+ return n < 40 ? n * 8 : n;
460
+ };
461
+ const em = v.get('EncryptMetadata');
462
+ return {
463
+ v: vv,
464
+ r,
465
+ lengthBits: keyBits(),
466
+ o,
467
+ u,
468
+ oe: bytesOf(this.resolve(v.get('OE') ?? null)),
469
+ ue: bytesOf(this.resolve(v.get('UE') ?? null)),
470
+ p: numberOf(this.resolve(v.get('P') ?? null)) | 0,
471
+ id0,
472
+ encryptMetadata: em !== false,
473
+ strMethod: methodOf('StrF'),
474
+ stmMethod: methodOf('StmF'),
475
+ };
476
+ }
477
+ readXrefChain() {
478
+ const sx = lastIndexOf(this.b, 'startxref');
479
+ if (sx < 0)
480
+ return false;
481
+ const lx = new Lexer(this.b, sx + 9, this.meter);
482
+ lx.skipSpace();
483
+ let offset = Number(lx.word());
484
+ if (Number.isInteger(offset) && offset >= 0)
485
+ this.lastXref = offset;
486
+ const seen = new Set();
487
+ let first = true;
488
+ while (Number.isFinite(offset) && offset > 0 && offset < this.b.length && !seen.has(offset)) {
489
+ seen.add(offset);
490
+ const trailer = this.readXrefAt(offset);
491
+ if (!trailer)
492
+ return !first;
493
+ if (first)
494
+ this.trailer = trailer;
495
+ first = false;
496
+ const stm = trailer.get('XRefStm');
497
+ if (typeof stm === 'number' && !seen.has(stm)) {
498
+ seen.add(stm);
499
+ this.readXrefAt(stm);
500
+ }
501
+ const prev = trailer.get('Prev');
502
+ offset = typeof prev === 'number' ? prev : -1;
503
+ }
504
+ return !first;
505
+ }
506
+ setEntry(n, e) {
507
+ if (!this.xref.has(n))
508
+ this.xref.set(n, e);
509
+ }
510
+ readXrefAt(offset) {
511
+ const lx = new Lexer(this.b, offset, this.meter);
512
+ lx.skipSpace();
513
+ const save = lx.pos;
514
+ if (lx.word() === 'xref') {
515
+ // Every pass either returns or consumes at least the start and count words, so the loop ends at the end of
516
+ // the file at the latest; a table that runs out before its trailer is unreadable.
517
+ while (true) {
518
+ lx.skipSpace();
519
+ if (lx.pos >= this.b.length)
520
+ return null;
521
+ this.meter.check();
522
+ const w = lx.peekWord();
523
+ if (w === 'trailer') {
524
+ lx.skipSpace();
525
+ lx.word();
526
+ const t = lx.value();
527
+ return isDict(t) ? t : null;
528
+ }
529
+ const startWord = lx.word();
530
+ lx.skipSpace();
531
+ const countWord = lx.word();
532
+ if (startWord === '' || countWord === '')
533
+ return null;
534
+ const start = Number(startWord);
535
+ const count = Number(countWord);
536
+ if (!Number.isInteger(start) || !Number.isInteger(count) || count < 0)
537
+ return null;
538
+ for (let i = 0; i < count; i++) {
539
+ lx.skipSpace();
540
+ if (lx.pos >= this.b.length)
541
+ return null;
542
+ const offWord = lx.word();
543
+ if (offWord === '')
544
+ return null;
545
+ const off = Number(offWord);
546
+ lx.skipSpace();
547
+ const gen = Number(lx.word());
548
+ lx.skipSpace();
549
+ const kind = lx.word();
550
+ if (kind === 'n' && off > 0)
551
+ this.setEntry(start + i, { kind: 'offset', offset: off, gen });
552
+ else if (kind === 'f')
553
+ this.setEntry(start + i, { kind: 'offset', offset: 0, gen });
554
+ }
555
+ }
556
+ }
557
+ lx.pos = save;
558
+ const obj = this.parseObjectAt(offset, null);
559
+ if (!(obj instanceof PStream))
560
+ return null;
561
+ const d = obj.dict;
562
+ const type = d.get('Type');
563
+ if (!(type instanceof PName) || type.name !== 'XRef')
564
+ return null;
565
+ const data = this.decodeStream(obj, null);
566
+ if (!data)
567
+ return null;
568
+ const wArr = d.get('W');
569
+ if (!Array.isArray(wArr) || wArr.length < 3)
570
+ return null;
571
+ const w = wArr.map(x => numberOf(x));
572
+ const size = numberOf(d.get('Size'));
573
+ const idx = d.get('Index');
574
+ const ranges = Array.isArray(idx) ? idx.map(x => numberOf(x)) : [0, size];
575
+ // Each field is 0 to 8 bytes; a row of no bytes would let the Index ranges run without reading anything.
576
+ if (w.some(x => !Number.isInteger(x) || x < 0 || x > 8))
577
+ return null;
578
+ const rowLen = w[0] + w[1] + w[2];
579
+ if (rowLen === 0)
580
+ return null;
581
+ let p = 0;
582
+ const field = (len, dflt) => {
583
+ if (len === 0)
584
+ return dflt;
585
+ let v = 0;
586
+ for (let i = 0; i < len; i++)
587
+ v = v * 256 + (data[p++] ?? 0);
588
+ return v;
589
+ };
590
+ for (let r = 0; r + 1 < ranges.length && p + rowLen <= data.length; r += 2) {
591
+ for (let i = 0; i < ranges[r + 1]; i++) {
592
+ if (p + rowLen > data.length)
593
+ break;
594
+ const t = field(w[0], 1);
595
+ const a = field(w[1], 0);
596
+ const c = field(w[2], 0);
597
+ const n = ranges[r] + i;
598
+ if (t === 1)
599
+ this.setEntry(n, { kind: 'offset', offset: a, gen: c });
600
+ else if (t === 2)
601
+ this.setEntry(n, { kind: 'packed', container: a, index: c });
602
+ else
603
+ this.setEntry(n, { kind: 'offset', offset: 0, gen: 0 });
604
+ }
605
+ }
606
+ return d;
607
+ }
608
+ /** Rebuilds the object table by scanning for "N G obj", later definitions winning, and finds a trailer. */
609
+ rebuild() {
610
+ const s = Buffer.from(this.b.buffer, this.b.byteOffset, this.b.byteLength).toString('latin1');
611
+ const re = /(?:^|[\s>\]])(\d{1,10})\s+(\d{1,5})\s+obj\b/g;
612
+ const found = new Map();
613
+ for (const m of s.matchAll(re)) {
614
+ const start = (m.index ?? 0) + m[0].length - m[0].trimStart().length;
615
+ found.set(Number(m[1]), { kind: 'offset', offset: start, gen: Number(m[2]) });
616
+ }
617
+ for (const [n, e] of found)
618
+ this.xref.set(n, e);
619
+ let pos = s.lastIndexOf('trailer');
620
+ while (pos >= 0) {
621
+ try {
622
+ const t = new Lexer(this.b, pos + 7, this.meter).value();
623
+ if (isDict(t) && t.get('Root')) {
624
+ this.trailer = t;
625
+ break;
626
+ }
627
+ }
628
+ catch (e) {
629
+ if (e instanceof deadline_1.DeadlineError)
630
+ throw e;
631
+ if (e instanceof BudgetError)
632
+ break;
633
+ // keep looking
634
+ }
635
+ pos = s.lastIndexOf('trailer', pos - 1);
636
+ }
637
+ if (!this.trailer.get('Root')) {
638
+ for (const [n] of found) {
639
+ if (this.meter.exhausted)
640
+ break;
641
+ const o = this.objectOrNull(n);
642
+ if (o instanceof PStream) {
643
+ const t = o.dict.get('Type');
644
+ if (t instanceof PName && t.name === 'XRef' && o.dict.get('Root')) {
645
+ this.trailer = o.dict;
646
+ break;
647
+ }
648
+ }
649
+ }
650
+ }
651
+ if (!this.trailer.get('Root')) {
652
+ // Objects packed in object streams: index them too, then look for a catalog.
653
+ for (const [n] of found) {
654
+ if (this.meter.exhausted)
655
+ break;
656
+ const o = this.objectOrNull(n);
657
+ if (o instanceof PStream) {
658
+ const t = o.dict.get('Type');
659
+ if (t instanceof PName && t.name === 'ObjStm') {
660
+ const st = this.objStm(n);
661
+ st?.offsets.forEach((objNum, i) => {
662
+ if (i % 2 === 0 && !this.xref.has(objNum))
663
+ this.xref.set(objNum, { kind: 'packed', container: n, index: i / 2 });
664
+ });
665
+ }
666
+ }
667
+ }
668
+ for (const n of this.xref.keys()) {
669
+ if (this.meter.exhausted)
670
+ break;
671
+ const o = this.objectOrNull(n);
672
+ if (isDict(o)) {
673
+ const t = o.get('Type');
674
+ if (t instanceof PName && t.name === 'Catalog') {
675
+ this.trailer = new Map([['Root', new PRef(n, 0)]]);
676
+ break;
677
+ }
678
+ }
679
+ }
680
+ }
681
+ }
682
+ objectOrNull(n) {
683
+ try {
684
+ return this.object(n);
685
+ }
686
+ catch (e) {
687
+ if (e instanceof deadline_1.DeadlineError)
688
+ throw e;
689
+ return null;
690
+ }
691
+ }
692
+ parseObjectAt(offset, expect) {
693
+ const lx = new Lexer(this.b, offset, this.meter);
694
+ lx.skipSpace();
695
+ const n = Number(lx.word());
696
+ lx.skipSpace();
697
+ const g = Number(lx.word());
698
+ lx.skipSpace();
699
+ if (lx.word() !== 'obj')
700
+ throw new Error('not an object');
701
+ if (expect !== null && n !== expect)
702
+ throw new Error('object number mismatch');
703
+ const v = lx.value();
704
+ if (!isDict(v))
705
+ return this.decryptValue(v, n, g);
706
+ lx.skipSpace();
707
+ const save = lx.pos;
708
+ if (lx.word() !== 'stream') {
709
+ lx.pos = save;
710
+ return this.decryptValue(v, n, g);
711
+ }
712
+ let start = lx.pos;
713
+ if (this.b[start] === 13)
714
+ start++;
715
+ if (this.b[start] === 10)
716
+ start++;
717
+ let len = -1;
718
+ const lenV = v.get('Length');
719
+ if (typeof lenV === 'number')
720
+ len = lenV;
721
+ else if (lenV instanceof PRef && !this.resolving.has(lenV.num)) {
722
+ const r = this.resolve(lenV);
723
+ if (typeof r === 'number')
724
+ len = r;
725
+ }
726
+ let end = start + len;
727
+ const check = len >= 0 && end <= this.b.length ? this.find('endstream', end) : -1;
728
+ if (len < 0 || check < 0 || check - end > 4) {
729
+ const e = this.find('endstream', start);
730
+ end = e < 0 ? this.b.length : e;
731
+ while (end > start && (this.b[end - 1] === 10 || this.b[end - 1] === 13))
732
+ end--;
733
+ }
734
+ const dict = this.decryptValue(v, n, g);
735
+ if (!isDict(dict))
736
+ throw new Error('bad stream dictionary');
737
+ let raw = this.b.subarray(start, end);
738
+ if (this.decryptor && !this.isXrefStream(dict) && !(this.encryptRef && this.encryptRef.num === n))
739
+ raw = this.decryptor.streamBytes(n, g, raw);
740
+ return new PStream(dict, raw);
741
+ }
742
+ /** indexOf on the file, charged to the parsing budget for the bytes it passes over. */
743
+ find(needle, from) {
744
+ this.meter.check();
745
+ const at = indexOf(this.b, needle, from);
746
+ this.meter.spend((at < 0 ? this.b.length : at) - from);
747
+ return at;
748
+ }
749
+ isXrefStream(d) {
750
+ const t = d.get('Type');
751
+ return t instanceof PName && t.name === 'XRef';
752
+ }
753
+ decryptValue(v, n, g) {
754
+ if (!this.decryptor || (this.encryptRef && this.encryptRef.num === n))
755
+ return v;
756
+ const dec = this.decryptor;
757
+ const walk = (x) => {
758
+ if (x instanceof PString)
759
+ return new PString(dec.string(n, g, x.bytes));
760
+ if (Array.isArray(x))
761
+ return x.map(walk);
762
+ if (isDict(x)) {
763
+ const out = new Map();
764
+ for (const [k, val] of x)
765
+ out.set(k, walk(val));
766
+ return out;
767
+ }
768
+ return x;
769
+ };
770
+ return walk(v);
771
+ }
772
+ objStm(n) {
773
+ const cached = this.objStmCache.get(n);
774
+ if (cached)
775
+ return cached;
776
+ const s = this.object(n);
777
+ if (!(s instanceof PStream))
778
+ return null;
779
+ const data = this.decodeStream(s, n);
780
+ if (!data)
781
+ return null;
782
+ const count = numberOf(s.dict.get('N'));
783
+ const first = numberOf(s.dict.get('First'));
784
+ // The decoded data is parsed as well, so it widens the budget by its own size.
785
+ this.meter.limit += PARSE_FACTOR * data.length;
786
+ const lx = new Lexer(data, 0, this.meter);
787
+ const offsets = [];
788
+ for (let i = 0; i < count * 2 && lx.pos < data.length; i++) {
789
+ lx.skipSpace();
790
+ offsets.push(Number(lx.word()));
791
+ }
792
+ const out = { offsets, data, first };
793
+ this.objStmCache.set(n, out);
794
+ return out;
795
+ }
796
+ object(n) {
797
+ if (this.cache.has(n))
798
+ return this.cache.get(n) ?? null;
799
+ const e = this.xref.get(n);
800
+ if (!e)
801
+ return null;
802
+ if (this.resolving.has(n))
803
+ return null;
804
+ this.resolving.add(n);
805
+ try {
806
+ let v = null;
807
+ if (e.kind === 'offset') {
808
+ if (e.offset <= 0)
809
+ return null;
810
+ v = this.parseObjectAt(e.offset, n);
811
+ }
812
+ else {
813
+ const st = this.objStm(e.container);
814
+ if (!st)
815
+ return null;
816
+ const off = st.offsets[e.index * 2 + 1];
817
+ if (st.offsets[e.index * 2] !== n || !Number.isFinite(off))
818
+ return null;
819
+ v = new Lexer(st.data, st.first + off, this.meter).value();
820
+ }
821
+ this.cache.set(n, v);
822
+ return v;
823
+ }
824
+ finally {
825
+ this.resolving.delete(n);
826
+ }
827
+ }
828
+ resolve(v) {
829
+ let x = v ?? null;
830
+ for (let i = 0; i < 10 && x instanceof PRef; i++)
831
+ x = this.object(x.num);
832
+ return x;
833
+ }
834
+ get root() {
835
+ return this.resolve(this.trailer.get('Root') ?? null);
836
+ }
837
+ /** Decodes a stream through its filters; null when a filter is not supported. */
838
+ decodeStream(s, _objNum) {
839
+ const fl = this.resolve(s.dict.get('Filter') ?? null);
840
+ const filters = fl instanceof PName ? [fl] : Array.isArray(fl) ? fl.map(x => this.resolve(x)) : [];
841
+ const pr = this.resolve(s.dict.get('DecodeParms') ?? s.dict.get('DP') ?? null);
842
+ const parms = Array.isArray(pr) ? pr.map(x => this.resolve(x)) : [pr];
843
+ try {
844
+ return this.runFilters(s.raw, filters, parms);
845
+ }
846
+ catch (e) {
847
+ if (e instanceof filters_1.OutputLimitError) {
848
+ this.oversize = true;
849
+ return null;
850
+ }
851
+ throw e;
852
+ }
853
+ }
854
+ runFilters(raw, filters, parms) {
855
+ let data = raw;
856
+ for (let i = 0; i < filters.length; i++) {
857
+ const limit = this.decodeBudget;
858
+ const f = filters[i];
859
+ if (!(f instanceof PName))
860
+ return null;
861
+ const p = parms[i];
862
+ const dp = isDict(p) ? p : new Map();
863
+ switch (f.name) {
864
+ case 'FlateDecode':
865
+ case 'Fl':
866
+ data = predict((0, filters_1.inflate)(data, limit), dp);
867
+ break;
868
+ case 'LZWDecode':
869
+ case 'LZW':
870
+ data = predict((0, filters_1.lzwDecode)(data, numberOf(dp.get('EarlyChange'), 1), limit), dp);
871
+ break;
872
+ case 'ASCIIHexDecode':
873
+ case 'AHx':
874
+ data = (0, filters_1.asciiHexDecode)(data);
875
+ break;
876
+ case 'ASCII85Decode':
877
+ case 'A85':
878
+ data = (0, filters_1.ascii85Decode)(data);
879
+ break;
880
+ case 'RunLengthDecode':
881
+ case 'RL':
882
+ data = (0, filters_1.runLengthDecode)(data, limit);
883
+ break;
884
+ case 'Crypt':
885
+ break;
886
+ default:
887
+ return null;
888
+ }
889
+ this.decodeBudget -= data.length;
890
+ if (this.decodeBudget < 0) {
891
+ this.oversize = true;
892
+ return null;
893
+ }
894
+ }
895
+ return data;
896
+ }
897
+ }
898
+ exports.PdfReader = PdfReader;
899
+ function predict(data, dp) {
900
+ const p = numberOf(dp.get('Predictor'), 1);
901
+ if (p < 2)
902
+ return data;
903
+ const columns = numberOf(dp.get('Columns'), 1);
904
+ const colors = numberOf(dp.get('Colors'), 1);
905
+ const bits = numberOf(dp.get('BitsPerComponent'), 8);
906
+ if (p === 2)
907
+ return (0, filters_1.tiffUnpredict)(new Uint8Array(data), columns, colors, bits);
908
+ return (0, filters_1.pngUnpredict)(data, columns, colors, bits);
909
+ }
910
+ const PACKET_NAMES = ['xdp:xdp', 'template', 'datasets', 'config', 'connectionSet', 'localeSet', 'stylesheet', '/xdp:xdp'];
911
+ function nameTreeKeys(r, node, out, depth) {
912
+ const n = r.resolve(node);
913
+ if (!isDict(n) || depth > 20)
914
+ return;
915
+ const names = r.resolve(n.get('Names'));
916
+ if (Array.isArray(names)) {
917
+ for (let i = 0; i < names.length; i += 2) {
918
+ const k = r.resolve(names[i]);
919
+ if (k instanceof PString)
920
+ out.add(Buffer.from(k.bytes).toString('latin1'));
921
+ }
922
+ }
923
+ const kids = r.resolve(n.get('Kids'));
924
+ if (Array.isArray(kids))
925
+ for (const k of kids)
926
+ nameTreeKeys(r, k, out, depth + 1);
927
+ }
928
+ /** Reads the XFA packets and the XFAImages names. Null when there is no XFA or it cannot be read. */
929
+ function readXfa(bytes, passwords, deadline) {
930
+ const r = PdfReader.open(bytes, passwords.length ? passwords : [''], deadline);
931
+ if (!r)
932
+ return null;
933
+ const packets = readPackets(r);
934
+ if (!packets)
935
+ return null;
936
+ const imageNames = new Set();
937
+ const root = r.root;
938
+ if (isDict(root)) {
939
+ const names = r.resolve(root.get('Names'));
940
+ if (isDict(names))
941
+ nameTreeKeys(r, names.get('XFAImages') ?? null, imageNames, 0);
942
+ }
943
+ return { packets, imageNames };
944
+ }
945
+ /**
946
+ * The password that opens the file, in the prepared form that worked (a revision 6 password after SASLprep, say);
947
+ * null when the file is not encrypted, cannot be read, or no password opens it.
948
+ */
949
+ function openingPassword(bytes, passwords, deadline) {
950
+ const r = PdfReader.open(bytes, passwords.length ? passwords : [''], deadline);
951
+ return r?.security?.password ?? null;
952
+ }
953
+ /**
954
+ * What flattenXfa checks before pdf.js sees the file: the password that opens it (see openingPassword), and whether
955
+ * its XFA decodes past XFA_LIMIT (or a stream it needs past DECODE_LIMIT).
956
+ */
957
+ function inspectPdf(bytes, passwords, deadline) {
958
+ const { reader: r, overBudget } = PdfReader.attempt(bytes, passwords.length ? passwords : [''], deadline);
959
+ if (!r)
960
+ return { password: null, oversize: false, overBudget };
961
+ readPackets(r);
962
+ return { password: r.security?.password ?? null, oversize: r.oversize, overBudget: r.overBudget };
963
+ }
964
+ /** Reads the /AcroForm /XFA streams the way pdf.js picks them. Null when there is no XFA or it cannot be read. */
965
+ function readXfaPackets(bytes, passwords) {
966
+ const r = PdfReader.open(bytes, passwords.length ? passwords : ['']);
967
+ return r ? readPackets(r) : null;
968
+ }
969
+ /** The packets of an open reader; see readXfaPackets. */
970
+ function readPackets(r) {
971
+ const root = r.root;
972
+ if (!isDict(root))
973
+ return null;
974
+ const af = r.resolve(root.get('AcroForm'));
975
+ if (!isDict(af))
976
+ return null;
977
+ const xfa = r.resolve(af.get('XFA'));
978
+ const out = new Map();
979
+ let total = 0;
980
+ const text = (v) => {
981
+ const s = r.resolve(v);
982
+ if (!(s instanceof PStream))
983
+ return null;
984
+ const ref = v instanceof PRef ? v.num : null;
985
+ const d = r.decodeStream(s, ref);
986
+ total += d?.length ?? 0;
987
+ if (total > exports.XFA_LIMIT) {
988
+ r.oversize = true;
989
+ return null;
990
+ }
991
+ return d?.length ? Buffer.from(d).toString('utf8') : null;
992
+ };
993
+ if (xfa instanceof PStream) {
994
+ const t = text(af.get('XFA') ?? null);
995
+ if (t)
996
+ out.set('xdp:xdp', t);
997
+ return out.size && !r.oversize ? out : null;
998
+ }
999
+ if (!Array.isArray(xfa) || xfa.length === 0)
1000
+ return null;
1001
+ for (let i = 0; i + 1 < xfa.length; i += 2) {
1002
+ let name;
1003
+ if (i === 0)
1004
+ name = 'xdp:xdp';
1005
+ else if (i === xfa.length - 2)
1006
+ name = '/xdp:xdp';
1007
+ else {
1008
+ const n = r.resolve(xfa[i]);
1009
+ name = n instanceof PString ? Buffer.from(n.bytes).toString('latin1') : '';
1010
+ }
1011
+ if (!PACKET_NAMES.includes(name))
1012
+ continue;
1013
+ const t = text(xfa[i + 1]);
1014
+ if (r.oversize)
1015
+ return null;
1016
+ if (t)
1017
+ out.set(name, t);
1018
+ }
1019
+ return out.size ? out : null;
1020
+ }
1021
+ /** All packets joined in pdf.js's order into one XDP document. */
1022
+ function joinPackets(p) {
1023
+ if (!p.get('/xdp:xdp'))
1024
+ return p.get('xdp:xdp') ?? '';
1025
+ return PACKET_NAMES.map(n => p.get(n) ?? '').join('');
1026
+ }