pdfkit 0.19.1 → 0.20.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 (56) hide show
  1. package/.yarn/install-state.gz +0 -0
  2. package/CHANGELOG.md +19 -0
  3. package/README.md +97 -25
  4. package/js/output.cjs +53 -0
  5. package/js/output.mjs +50 -0
  6. package/js/pdfkit.browser.js +7524 -0
  7. package/js/pdfkit.browser.js.map +1 -0
  8. package/js/pdfkit.browser.mjs +7344 -0
  9. package/js/pdfkit.browser.mjs.map +1 -0
  10. package/js/pdfkit.browser.old.js +7517 -0
  11. package/js/pdfkit.browser.old.mjs +7342 -0
  12. package/js/pdfkit.js +1417 -487
  13. package/js/pdfkit.js.map +1 -1
  14. package/js/{pdfkit.es.js → pdfkit.old.js} +1423 -502
  15. package/js/pdfkit.standalone.js +23432 -35943
  16. package/js/standard-fonts/Courier.cjs +17 -0
  17. package/js/standard-fonts/Courier.mjs +15 -0
  18. package/js/standard-fonts/CourierBold.cjs +17 -0
  19. package/js/standard-fonts/CourierBold.mjs +15 -0
  20. package/js/standard-fonts/CourierBoldOblique.cjs +17 -0
  21. package/js/standard-fonts/CourierBoldOblique.mjs +15 -0
  22. package/js/standard-fonts/CourierOblique.cjs +17 -0
  23. package/js/standard-fonts/CourierOblique.mjs +15 -0
  24. package/js/standard-fonts/Helvetica.cjs +17 -0
  25. package/js/standard-fonts/Helvetica.mjs +15 -0
  26. package/js/standard-fonts/HelveticaBold.cjs +17 -0
  27. package/js/standard-fonts/HelveticaBold.mjs +15 -0
  28. package/js/standard-fonts/HelveticaBoldOblique.cjs +17 -0
  29. package/js/standard-fonts/HelveticaBoldOblique.mjs +15 -0
  30. package/js/standard-fonts/HelveticaOblique.cjs +17 -0
  31. package/js/standard-fonts/HelveticaOblique.mjs +15 -0
  32. package/js/standard-fonts/Symbol.cjs +15 -0
  33. package/js/standard-fonts/Symbol.mjs +13 -0
  34. package/js/standard-fonts/TimesBold.cjs +17 -0
  35. package/js/standard-fonts/TimesBold.mjs +15 -0
  36. package/js/standard-fonts/TimesBoldItalic.cjs +17 -0
  37. package/js/standard-fonts/TimesBoldItalic.mjs +15 -0
  38. package/js/standard-fonts/TimesItalic.cjs +17 -0
  39. package/js/standard-fonts/TimesItalic.mjs +15 -0
  40. package/js/standard-fonts/TimesRoman.cjs +17 -0
  41. package/js/standard-fonts/TimesRoman.mjs +15 -0
  42. package/js/standard-fonts/ZapfDingbats.cjs +15 -0
  43. package/js/standard-fonts/ZapfDingbats.mjs +13 -0
  44. package/js/standard-fonts/chunks/standardGlyphNames-DNHAb7rp.cjs +5 -0
  45. package/js/standard-fonts/chunks/standardGlyphNames-w3QlG7PW.mjs +3 -0
  46. package/package.json +109 -28
  47. package/rollup.config.mjs +111 -50
  48. package/tools/README.md +124 -0
  49. package/tools/afm-converter.js +317 -0
  50. package/tools/asset-plugin.mjs +17 -0
  51. package/tools/binary-plugin.mjs +18 -0
  52. package/tools/convert-afm-parsed.js +8 -0
  53. package/tools/convert-afm-runtime.js +8 -0
  54. package/vitest.config.js +2 -0
  55. package/js/pdfkit.es.js.map +0 -1
  56. package/js/virtual-fs.js +0 -49
@@ -1,13 +1,16 @@
1
- import stream from 'stream';
2
- import zlib from 'zlib';
3
- import { concatBytes } from '@noble/hashes/utils';
4
- import md5 from 'js-md5';
5
- import { sha256 } from '@noble/hashes/sha2';
6
- import { cbc, ecb } from '@noble/ciphers/aes';
7
- import fs from 'fs';
8
- import { create } from 'fontkit';
9
- import LineBreaker from 'linebreak';
10
- import PNG from 'png-js';
1
+ 'use strict';
2
+
3
+ var stream = require('stream');
4
+ var utils = require('@noble/hashes/utils');
5
+ var zlib$1 = require('zlib');
6
+ var aes = require('@noble/ciphers/aes');
7
+ var fs$1 = require('fs');
8
+ var fontkit = require('fontkit');
9
+ var LineBreaker = require('linebreak');
10
+ var PNG = require('png-js');
11
+
12
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
13
+ var Readable = stream.Readable;
11
14
 
12
15
  class PDFAbstractReference {
13
16
  toString() {
@@ -73,6 +76,57 @@ class SpotColor {
73
76
  }
74
77
  }
75
78
 
79
+ const toBinaryString = bytes => {
80
+ const chunkSize = 0x8000;
81
+ let out = '';
82
+ for (let i = 0; i < bytes.length; i += chunkSize) {
83
+ const end = Math.min(i + chunkSize, bytes.length);
84
+ out += String.fromCharCode.apply(null, bytes.subarray(i, end));
85
+ }
86
+ return out;
87
+ };
88
+ const fromBinaryString = str => {
89
+ const out = new Uint8Array(str.length);
90
+ for (let i = 0; i < str.length; i++) {
91
+ out[i] = str.charCodeAt(i) & 0xff;
92
+ }
93
+ return out;
94
+ };
95
+ const fromBase64 = b64 => {
96
+ const binary = atob(b64);
97
+ const out = new Uint8Array(binary.length);
98
+ for (let i = 0; i < binary.length; i++) {
99
+ out[i] = binary.charCodeAt(i);
100
+ }
101
+ return out;
102
+ };
103
+ const concat = chunks => {
104
+ let length = 0;
105
+ for (const chunk of chunks) length += chunk.length;
106
+ const out = new Uint8Array(length);
107
+ let offset = 0;
108
+ for (const chunk of chunks) {
109
+ out.set(chunk, offset);
110
+ offset += chunk.length;
111
+ }
112
+ return out;
113
+ };
114
+ const toUTF16BE = str => {
115
+ const out = new Uint8Array((str.length + 1) * 2);
116
+ out[0] = 0xfe;
117
+ out[1] = 0xff;
118
+ for (let i = 0; i < str.length; i++) {
119
+ const code = str.charCodeAt(i);
120
+ out[i * 2 + 2] = code >> 8;
121
+ out[i * 2 + 3] = code & 0xff;
122
+ }
123
+ return out;
124
+ };
125
+ const readUInt16BE = (bytes, offset = 0) => (bytes[offset] << 8 | bytes[offset + 1]) >>> 0;
126
+ const readUInt16LE = (bytes, offset = 0) => (bytes[offset + 1] << 8 | bytes[offset]) >>> 0;
127
+ const readUInt32BE = (bytes, offset = 0) => bytes[offset] * 0x1000000 + (bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
128
+ const readUInt32LE = (bytes, offset = 0) => (bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16) + bytes[offset + 3] * 0x1000000 >>> 0;
129
+
76
130
  const pad = (str, length) => (Array(length + 1).join('0') + str).slice(-length);
77
131
  const isSafeCharCode = code => {
78
132
  if (code > 0x7f) return true;
@@ -101,19 +155,6 @@ const escapeName = function (name) {
101
155
  }
102
156
  return escapedName;
103
157
  };
104
- const swapBytes = function (buff) {
105
- const l = buff.length;
106
- if (l & 0x01) {
107
- throw new Error('Buffer length must be even');
108
- } else {
109
- for (let i = 0, end = l - 1; i < end; i += 2) {
110
- const a = buff[i];
111
- buff[i] = buff[i + 1];
112
- buff[i + 1] = a;
113
- }
114
- }
115
- return buff;
116
- };
117
158
  class PDFObject {
118
159
  static convert(object, encryptFn = null) {
119
160
  if (typeof object === 'string') {
@@ -127,37 +168,41 @@ class PDFObject {
127
168
  break;
128
169
  }
129
170
  }
130
- let stringBuffer;
171
+ let stringBytes;
131
172
  if (isUnicode) {
132
- stringBuffer = swapBytes(Buffer.from(`\ufeff${string}`, 'utf16le'));
173
+ stringBytes = toUTF16BE(string.valueOf());
133
174
  } else {
134
- stringBuffer = Buffer.from(string.valueOf(), 'ascii');
175
+ stringBytes = fromBinaryString(string.valueOf());
135
176
  }
136
177
  if (encryptFn) {
137
- string = encryptFn(stringBuffer).toString('binary');
138
- } else {
139
- string = stringBuffer.toString('binary');
178
+ stringBytes = encryptFn(stringBytes);
140
179
  }
180
+ string = toBinaryString(stringBytes);
141
181
  string = string.replace(escapableRe, c => escapable[c]);
142
182
  return `(${string})`;
143
- } else if (Buffer.isBuffer(object)) {
144
- return `<${object.toString('hex')}>`;
183
+ } else if (object instanceof Uint8Array) {
184
+ return `<${utils.bytesToHex(object)}>`;
145
185
  } else if (object instanceof PDFAbstractReference || object instanceof PDFTree || object instanceof SpotColor) {
146
186
  return object.toString();
147
187
  } else if (object instanceof Date) {
148
188
  let string = `D:${pad(object.getUTCFullYear(), 4)}` + pad(object.getUTCMonth() + 1, 2) + pad(object.getUTCDate(), 2) + pad(object.getUTCHours(), 2) + pad(object.getUTCMinutes(), 2) + pad(object.getUTCSeconds(), 2) + 'Z';
149
189
  if (encryptFn) {
150
- string = encryptFn(Buffer.from(string, 'ascii')).toString('binary');
190
+ string = toBinaryString(encryptFn(fromBinaryString(string)));
151
191
  string = string.replace(escapableRe, c => escapable[c]);
152
192
  }
153
193
  return `(${string})`;
154
194
  } else if (Array.isArray(object)) {
155
- const items = object.map(e => PDFObject.convert(e, encryptFn)).join(' ');
156
- return `[${items}]`;
195
+ const items = [];
196
+ for (let i = 0; i < object.length; i++) {
197
+ const e = object[i];
198
+ items.push(PDFObject.convert(e === undefined ? null : e, encryptFn));
199
+ }
200
+ return `[${items.join(' ')}]`;
157
201
  } else if ({}.toString.call(object) === '[object Object]') {
158
202
  const out = ['<<'];
159
203
  for (let key in object) {
160
204
  const val = object[key];
205
+ if (val === undefined) continue;
161
206
  out.push(`/${key} ${PDFObject.convert(val, encryptFn)}`);
162
207
  }
163
208
  out.push('>>');
@@ -176,6 +221,10 @@ class PDFObject {
176
221
  }
177
222
  }
178
223
 
224
+ var zlib = {
225
+ deflateSync: data => zlib$1.deflateSync(data)
226
+ };
227
+
179
228
  class PDFReference extends PDFAbstractReference {
180
229
  constructor(document, id, data = {}) {
181
230
  super();
@@ -189,7 +238,7 @@ class PDFReference extends PDFAbstractReference {
189
238
  }
190
239
  write(chunk) {
191
240
  if (!(chunk instanceof Uint8Array)) {
192
- chunk = Buffer.from(chunk + '\n', 'binary');
241
+ chunk = fromBinaryString(chunk + '\n');
193
242
  }
194
243
  this.uncompressedLength += chunk.length;
195
244
  if (this.data.Length == null) {
@@ -211,7 +260,7 @@ class PDFReference extends PDFAbstractReference {
211
260
  this.offset = this.document._offset;
212
261
  const encryptFn = this.document._security ? this.document._security.getEncryptFn(this.id, this.gen) : null;
213
262
  if (this.buffer.length) {
214
- this.buffer = Buffer.concat(this.buffer);
263
+ this.buffer = concat(this.buffer);
215
264
  if (this.compress) {
216
265
  this.buffer = zlib.deflateSync(this.buffer);
217
266
  }
@@ -369,7 +418,7 @@ const SIZES = {
369
418
  TABLOID: [792.0, 1224.0]
370
419
  };
371
420
  class PDFPage {
372
- constructor(document, options = {}) {
421
+ constructor(document, options) {
373
422
  this.document = document;
374
423
  this._options = options;
375
424
  this.size = options.size || 'letter';
@@ -379,8 +428,6 @@ class PDFPage {
379
428
  this.width = dimensions[this.layout === 'portrait' ? 0 : 1];
380
429
  this.height = dimensions[this.layout === 'portrait' ? 1 : 0];
381
430
  this.content = this.document.ref();
382
- if (options.font) document.font(options.font, options.fontFamily);
383
- if (options.fontSize) document.fontSize(options.fontSize);
384
431
  this.margins = normalizeSides(options.margin ?? options.margins, DEFAULT_MARGINS, x => document.sizeToPoint(x, 0, this));
385
432
  this.resources = this.document.ref({
386
433
  ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI']
@@ -464,24 +511,846 @@ class PDFNameTree extends PDFTree {
464
511
  }
465
512
  }
466
513
 
514
+ function isBytes(a) {
515
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array';
516
+ }
517
+ function abytes(b, ...lengths) {
518
+ if (!isBytes(b)) throw new Error('Uint8Array expected');
519
+ if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
520
+ }
521
+ function aexists(instance, checkFinished = true) {
522
+ if (instance.destroyed) throw new Error('Hash instance has been destroyed');
523
+ if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');
524
+ }
525
+ function aoutput(out, instance) {
526
+ abytes(out);
527
+ const min = instance.outputLen;
528
+ if (out.length < min) {
529
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
530
+ }
531
+ }
532
+ function clean(...arrays) {
533
+ for (let i = 0; i < arrays.length; i++) {
534
+ arrays[i].fill(0);
535
+ }
536
+ }
537
+ function createView(arr) {
538
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
539
+ }
540
+ function rotr(word, shift) {
541
+ return word << 32 - shift | word >>> shift;
542
+ }
543
+ function rotl(word, shift) {
544
+ return word << shift | word >>> 32 - shift >>> 0;
545
+ }
546
+ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
547
+ (() => typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
548
+ Array.from({
549
+ length: 256
550
+ }, (_, i) => i.toString(16).padStart(2, '0'));
551
+ function utf8ToBytes(str) {
552
+ if (typeof str !== 'string') throw new Error('string expected');
553
+ return new Uint8Array(new TextEncoder().encode(str));
554
+ }
555
+ function toBytes(data) {
556
+ if (typeof data === 'string') data = utf8ToBytes(data);
557
+ abytes(data);
558
+ return data;
559
+ }
560
+ class Hash {}
561
+ function createHasher(hashCons) {
562
+ const hashC = msg => hashCons().update(toBytes(msg)).digest();
563
+ const tmp = hashCons();
564
+ hashC.outputLen = tmp.outputLen;
565
+ hashC.blockLen = tmp.blockLen;
566
+ hashC.create = () => hashCons();
567
+ return hashC;
568
+ }
569
+
570
+ function setBigUint64(view, byteOffset, value, isLE) {
571
+ if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);
572
+ const _32n = BigInt(32);
573
+ const _u32_max = BigInt(0xffffffff);
574
+ const wh = Number(value >> _32n & _u32_max);
575
+ const wl = Number(value & _u32_max);
576
+ const h = isLE ? 4 : 0;
577
+ const l = isLE ? 0 : 4;
578
+ view.setUint32(byteOffset + h, wh, isLE);
579
+ view.setUint32(byteOffset + l, wl, isLE);
580
+ }
581
+ function Chi(a, b, c) {
582
+ return a & b ^ ~a & c;
583
+ }
584
+ function Maj(a, b, c) {
585
+ return a & b ^ a & c ^ b & c;
586
+ }
587
+ class HashMD extends Hash {
588
+ constructor(blockLen, outputLen, padOffset, isLE) {
589
+ super();
590
+ this.finished = false;
591
+ this.length = 0;
592
+ this.pos = 0;
593
+ this.destroyed = false;
594
+ this.blockLen = blockLen;
595
+ this.outputLen = outputLen;
596
+ this.padOffset = padOffset;
597
+ this.isLE = isLE;
598
+ this.buffer = new Uint8Array(blockLen);
599
+ this.view = createView(this.buffer);
600
+ }
601
+ update(data) {
602
+ aexists(this);
603
+ data = toBytes(data);
604
+ abytes(data);
605
+ const {
606
+ view,
607
+ buffer,
608
+ blockLen
609
+ } = this;
610
+ const len = data.length;
611
+ for (let pos = 0; pos < len;) {
612
+ const take = Math.min(blockLen - this.pos, len - pos);
613
+ if (take === blockLen) {
614
+ const dataView = createView(data);
615
+ for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
616
+ continue;
617
+ }
618
+ buffer.set(data.subarray(pos, pos + take), this.pos);
619
+ this.pos += take;
620
+ pos += take;
621
+ if (this.pos === blockLen) {
622
+ this.process(view, 0);
623
+ this.pos = 0;
624
+ }
625
+ }
626
+ this.length += data.length;
627
+ this.roundClean();
628
+ return this;
629
+ }
630
+ digestInto(out) {
631
+ aexists(this);
632
+ aoutput(out, this);
633
+ this.finished = true;
634
+ const {
635
+ buffer,
636
+ view,
637
+ blockLen,
638
+ isLE
639
+ } = this;
640
+ let {
641
+ pos
642
+ } = this;
643
+ buffer[pos++] = 0b10000000;
644
+ clean(this.buffer.subarray(pos));
645
+ if (this.padOffset > blockLen - pos) {
646
+ this.process(view, 0);
647
+ pos = 0;
648
+ }
649
+ for (let i = pos; i < blockLen; i++) buffer[i] = 0;
650
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
651
+ this.process(view, 0);
652
+ const oview = createView(out);
653
+ const len = this.outputLen;
654
+ if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');
655
+ const outLen = len / 4;
656
+ const state = this.get();
657
+ if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');
658
+ for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
659
+ }
660
+ digest() {
661
+ const {
662
+ buffer,
663
+ outputLen
664
+ } = this;
665
+ this.digestInto(buffer);
666
+ const res = buffer.slice(0, outputLen);
667
+ this.destroy();
668
+ return res;
669
+ }
670
+ _cloneInto(to) {
671
+ to || (to = new this.constructor());
672
+ to.set(...this.get());
673
+ const {
674
+ blockLen,
675
+ buffer,
676
+ length,
677
+ finished,
678
+ destroyed,
679
+ pos
680
+ } = this;
681
+ to.destroyed = destroyed;
682
+ to.finished = finished;
683
+ to.length = length;
684
+ to.pos = pos;
685
+ if (length % blockLen) to.buffer.set(buffer);
686
+ return to;
687
+ }
688
+ clone() {
689
+ return this._cloneInto();
690
+ }
691
+ }
692
+ const SHA256_IV = Uint32Array.from([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
693
+ const SHA224_IV = Uint32Array.from([0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]);
694
+ const SHA384_IV = Uint32Array.from([0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4]);
695
+ const SHA512_IV = Uint32Array.from([0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179]);
696
+
697
+ const SHA1_IV = Uint32Array.from([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]);
698
+ const SHA1_W = new Uint32Array(80);
699
+ class SHA1 extends HashMD {
700
+ constructor() {
701
+ super(64, 20, 8, false);
702
+ this.A = SHA1_IV[0] | 0;
703
+ this.B = SHA1_IV[1] | 0;
704
+ this.C = SHA1_IV[2] | 0;
705
+ this.D = SHA1_IV[3] | 0;
706
+ this.E = SHA1_IV[4] | 0;
707
+ }
708
+ get() {
709
+ const {
710
+ A,
711
+ B,
712
+ C,
713
+ D,
714
+ E
715
+ } = this;
716
+ return [A, B, C, D, E];
717
+ }
718
+ set(A, B, C, D, E) {
719
+ this.A = A | 0;
720
+ this.B = B | 0;
721
+ this.C = C | 0;
722
+ this.D = D | 0;
723
+ this.E = E | 0;
724
+ }
725
+ process(view, offset) {
726
+ for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);
727
+ for (let i = 16; i < 80; i++) SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
728
+ let {
729
+ A,
730
+ B,
731
+ C,
732
+ D,
733
+ E
734
+ } = this;
735
+ for (let i = 0; i < 80; i++) {
736
+ let F, K;
737
+ if (i < 20) {
738
+ F = Chi(B, C, D);
739
+ K = 0x5a827999;
740
+ } else if (i < 40) {
741
+ F = B ^ C ^ D;
742
+ K = 0x6ed9eba1;
743
+ } else if (i < 60) {
744
+ F = Maj(B, C, D);
745
+ K = 0x8f1bbcdc;
746
+ } else {
747
+ F = B ^ C ^ D;
748
+ K = 0xca62c1d6;
749
+ }
750
+ const T = rotl(A, 5) + F + E + K + SHA1_W[i] | 0;
751
+ E = D;
752
+ D = C;
753
+ C = rotl(B, 30);
754
+ B = A;
755
+ A = T;
756
+ }
757
+ A = A + this.A | 0;
758
+ B = B + this.B | 0;
759
+ C = C + this.C | 0;
760
+ D = D + this.D | 0;
761
+ E = E + this.E | 0;
762
+ this.set(A, B, C, D, E);
763
+ }
764
+ roundClean() {
765
+ clean(SHA1_W);
766
+ }
767
+ destroy() {
768
+ this.set(0, 0, 0, 0, 0);
769
+ clean(this.buffer);
770
+ }
771
+ }
772
+ createHasher(() => new SHA1());
773
+ const p32 = Math.pow(2, 32);
774
+ const K = Array.from({
775
+ length: 64
776
+ }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));
777
+ const MD5_IV = SHA1_IV.slice(0, 4);
778
+ const MD5_W = new Uint32Array(16);
779
+ class MD5 extends HashMD {
780
+ constructor() {
781
+ super(64, 16, 8, true);
782
+ this.A = MD5_IV[0] | 0;
783
+ this.B = MD5_IV[1] | 0;
784
+ this.C = MD5_IV[2] | 0;
785
+ this.D = MD5_IV[3] | 0;
786
+ }
787
+ get() {
788
+ const {
789
+ A,
790
+ B,
791
+ C,
792
+ D
793
+ } = this;
794
+ return [A, B, C, D];
795
+ }
796
+ set(A, B, C, D) {
797
+ this.A = A | 0;
798
+ this.B = B | 0;
799
+ this.C = C | 0;
800
+ this.D = D | 0;
801
+ }
802
+ process(view, offset) {
803
+ for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);
804
+ let {
805
+ A,
806
+ B,
807
+ C,
808
+ D
809
+ } = this;
810
+ for (let i = 0; i < 64; i++) {
811
+ let F, g, s;
812
+ if (i < 16) {
813
+ F = Chi(B, C, D);
814
+ g = i;
815
+ s = [7, 12, 17, 22];
816
+ } else if (i < 32) {
817
+ F = Chi(D, B, C);
818
+ g = (5 * i + 1) % 16;
819
+ s = [5, 9, 14, 20];
820
+ } else if (i < 48) {
821
+ F = B ^ C ^ D;
822
+ g = (3 * i + 5) % 16;
823
+ s = [4, 11, 16, 23];
824
+ } else {
825
+ F = C ^ (B | ~D);
826
+ g = 7 * i % 16;
827
+ s = [6, 10, 15, 21];
828
+ }
829
+ F = F + A + K[i] + MD5_W[g];
830
+ A = D;
831
+ D = C;
832
+ C = B;
833
+ B = B + rotl(F, s[i % 4]);
834
+ }
835
+ A = A + this.A | 0;
836
+ B = B + this.B | 0;
837
+ C = C + this.C | 0;
838
+ D = D + this.D | 0;
839
+ this.set(A, B, C, D);
840
+ }
841
+ roundClean() {
842
+ clean(MD5_W);
843
+ }
844
+ destroy() {
845
+ this.set(0, 0, 0, 0);
846
+ clean(this.buffer);
847
+ }
848
+ }
849
+ const md5 = createHasher(() => new MD5());
850
+ const Rho160 = Uint8Array.from([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);
851
+ const Id160 = (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
852
+ const Pi160 = (() => Id160.map(i => (9 * i + 5) % 16))();
853
+ const idxLR = (() => {
854
+ const L = [Id160];
855
+ const R = [Pi160];
856
+ const res = [L, R];
857
+ for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map(k => Rho160[k]));
858
+ return res;
859
+ })();
860
+ const idxL = (() => idxLR[0])();
861
+ const idxR = (() => idxLR[1])();
862
+ const shifts160 = [[11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5]].map(i => Uint8Array.from(i));
863
+ const shiftsL160 = idxL.map((idx, i) => idx.map(j => shifts160[i][j]));
864
+ const shiftsR160 = idxR.map((idx, i) => idx.map(j => shifts160[i][j]));
865
+ const Kl160 = Uint32Array.from([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]);
866
+ const Kr160 = Uint32Array.from([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]);
867
+ function ripemd_f(group, x, y, z) {
868
+ if (group === 0) return x ^ y ^ z;
869
+ if (group === 1) return x & y | ~x & z;
870
+ if (group === 2) return (x | ~y) ^ z;
871
+ if (group === 3) return x & z | y & ~z;
872
+ return x ^ (y | ~z);
873
+ }
874
+ const BUF_160 = new Uint32Array(16);
875
+ class RIPEMD160 extends HashMD {
876
+ constructor() {
877
+ super(64, 20, 8, true);
878
+ this.h0 = 0x67452301 | 0;
879
+ this.h1 = 0xefcdab89 | 0;
880
+ this.h2 = 0x98badcfe | 0;
881
+ this.h3 = 0x10325476 | 0;
882
+ this.h4 = 0xc3d2e1f0 | 0;
883
+ }
884
+ get() {
885
+ const {
886
+ h0,
887
+ h1,
888
+ h2,
889
+ h3,
890
+ h4
891
+ } = this;
892
+ return [h0, h1, h2, h3, h4];
893
+ }
894
+ set(h0, h1, h2, h3, h4) {
895
+ this.h0 = h0 | 0;
896
+ this.h1 = h1 | 0;
897
+ this.h2 = h2 | 0;
898
+ this.h3 = h3 | 0;
899
+ this.h4 = h4 | 0;
900
+ }
901
+ process(view, offset) {
902
+ for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);
903
+ let al = this.h0 | 0,
904
+ ar = al,
905
+ bl = this.h1 | 0,
906
+ br = bl,
907
+ cl = this.h2 | 0,
908
+ cr = cl,
909
+ dl = this.h3 | 0,
910
+ dr = dl,
911
+ el = this.h4 | 0,
912
+ er = el;
913
+ for (let group = 0; group < 5; group++) {
914
+ const rGroup = 4 - group;
915
+ const hbl = Kl160[group],
916
+ hbr = Kr160[group];
917
+ const rl = idxL[group],
918
+ rr = idxR[group];
919
+ const sl = shiftsL160[group],
920
+ sr = shiftsR160[group];
921
+ for (let i = 0; i < 16; i++) {
922
+ const tl = rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el | 0;
923
+ al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl;
924
+ }
925
+ for (let i = 0; i < 16; i++) {
926
+ const tr = rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er | 0;
927
+ ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr;
928
+ }
929
+ }
930
+ this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0);
931
+ }
932
+ roundClean() {
933
+ clean(BUF_160);
934
+ }
935
+ destroy() {
936
+ this.destroyed = true;
937
+ clean(this.buffer);
938
+ this.set(0, 0, 0, 0, 0);
939
+ }
940
+ }
941
+ createHasher(() => new RIPEMD160());
942
+
467
943
  function md5Hash(data) {
468
- return new Uint8Array(md5.arrayBuffer(data));
944
+ return md5.create().update(data).digest();
469
945
  }
470
946
  function md5Hex(data) {
471
- return md5(data);
947
+ return utils.bytesToHex(md5Hash(data));
948
+ }
949
+
950
+ const U32_MASK64 = BigInt(2 ** 32 - 1);
951
+ const _32n = BigInt(32);
952
+ function fromBig(n, le = false) {
953
+ if (le) return {
954
+ h: Number(n & U32_MASK64),
955
+ l: Number(n >> _32n & U32_MASK64)
956
+ };
957
+ return {
958
+ h: Number(n >> _32n & U32_MASK64) | 0,
959
+ l: Number(n & U32_MASK64) | 0
960
+ };
961
+ }
962
+ function split(lst, le = false) {
963
+ const len = lst.length;
964
+ let Ah = new Uint32Array(len);
965
+ let Al = new Uint32Array(len);
966
+ for (let i = 0; i < len; i++) {
967
+ const {
968
+ h,
969
+ l
970
+ } = fromBig(lst[i], le);
971
+ [Ah[i], Al[i]] = [h, l];
972
+ }
973
+ return [Ah, Al];
974
+ }
975
+ const shrSH = (h, _l, s) => h >>> s;
976
+ const shrSL = (h, l, s) => h << 32 - s | l >>> s;
977
+ const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
978
+ const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
979
+ const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
980
+ const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
981
+ function add(Ah, Al, Bh, Bl) {
982
+ const l = (Al >>> 0) + (Bl >>> 0);
983
+ return {
984
+ h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
985
+ l: l | 0
986
+ };
987
+ }
988
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
989
+ const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
990
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
991
+ const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
992
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
993
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
994
+
995
+ const SHA256_K = Uint32Array.from([0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]);
996
+ const SHA256_W = new Uint32Array(64);
997
+ class SHA256 extends HashMD {
998
+ constructor(outputLen = 32) {
999
+ super(64, outputLen, 8, false);
1000
+ this.A = SHA256_IV[0] | 0;
1001
+ this.B = SHA256_IV[1] | 0;
1002
+ this.C = SHA256_IV[2] | 0;
1003
+ this.D = SHA256_IV[3] | 0;
1004
+ this.E = SHA256_IV[4] | 0;
1005
+ this.F = SHA256_IV[5] | 0;
1006
+ this.G = SHA256_IV[6] | 0;
1007
+ this.H = SHA256_IV[7] | 0;
1008
+ }
1009
+ get() {
1010
+ const {
1011
+ A,
1012
+ B,
1013
+ C,
1014
+ D,
1015
+ E,
1016
+ F,
1017
+ G,
1018
+ H
1019
+ } = this;
1020
+ return [A, B, C, D, E, F, G, H];
1021
+ }
1022
+ set(A, B, C, D, E, F, G, H) {
1023
+ this.A = A | 0;
1024
+ this.B = B | 0;
1025
+ this.C = C | 0;
1026
+ this.D = D | 0;
1027
+ this.E = E | 0;
1028
+ this.F = F | 0;
1029
+ this.G = G | 0;
1030
+ this.H = H | 0;
1031
+ }
1032
+ process(view, offset) {
1033
+ for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
1034
+ for (let i = 16; i < 64; i++) {
1035
+ const W15 = SHA256_W[i - 15];
1036
+ const W2 = SHA256_W[i - 2];
1037
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
1038
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
1039
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
1040
+ }
1041
+ let {
1042
+ A,
1043
+ B,
1044
+ C,
1045
+ D,
1046
+ E,
1047
+ F,
1048
+ G,
1049
+ H
1050
+ } = this;
1051
+ for (let i = 0; i < 64; i++) {
1052
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
1053
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
1054
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
1055
+ const T2 = sigma0 + Maj(A, B, C) | 0;
1056
+ H = G;
1057
+ G = F;
1058
+ F = E;
1059
+ E = D + T1 | 0;
1060
+ D = C;
1061
+ C = B;
1062
+ B = A;
1063
+ A = T1 + T2 | 0;
1064
+ }
1065
+ A = A + this.A | 0;
1066
+ B = B + this.B | 0;
1067
+ C = C + this.C | 0;
1068
+ D = D + this.D | 0;
1069
+ E = E + this.E | 0;
1070
+ F = F + this.F | 0;
1071
+ G = G + this.G | 0;
1072
+ H = H + this.H | 0;
1073
+ this.set(A, B, C, D, E, F, G, H);
1074
+ }
1075
+ roundClean() {
1076
+ clean(SHA256_W);
1077
+ }
1078
+ destroy() {
1079
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
1080
+ clean(this.buffer);
1081
+ }
1082
+ }
1083
+ class SHA224 extends SHA256 {
1084
+ constructor() {
1085
+ super(28);
1086
+ this.A = SHA224_IV[0] | 0;
1087
+ this.B = SHA224_IV[1] | 0;
1088
+ this.C = SHA224_IV[2] | 0;
1089
+ this.D = SHA224_IV[3] | 0;
1090
+ this.E = SHA224_IV[4] | 0;
1091
+ this.F = SHA224_IV[5] | 0;
1092
+ this.G = SHA224_IV[6] | 0;
1093
+ this.H = SHA224_IV[7] | 0;
1094
+ }
1095
+ }
1096
+ const K512 = (() => split(['0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'].map(n => BigInt(n))))();
1097
+ const SHA512_Kh = (() => K512[0])();
1098
+ const SHA512_Kl = (() => K512[1])();
1099
+ const SHA512_W_H = new Uint32Array(80);
1100
+ const SHA512_W_L = new Uint32Array(80);
1101
+ class SHA512 extends HashMD {
1102
+ constructor(outputLen = 64) {
1103
+ super(128, outputLen, 16, false);
1104
+ this.Ah = SHA512_IV[0] | 0;
1105
+ this.Al = SHA512_IV[1] | 0;
1106
+ this.Bh = SHA512_IV[2] | 0;
1107
+ this.Bl = SHA512_IV[3] | 0;
1108
+ this.Ch = SHA512_IV[4] | 0;
1109
+ this.Cl = SHA512_IV[5] | 0;
1110
+ this.Dh = SHA512_IV[6] | 0;
1111
+ this.Dl = SHA512_IV[7] | 0;
1112
+ this.Eh = SHA512_IV[8] | 0;
1113
+ this.El = SHA512_IV[9] | 0;
1114
+ this.Fh = SHA512_IV[10] | 0;
1115
+ this.Fl = SHA512_IV[11] | 0;
1116
+ this.Gh = SHA512_IV[12] | 0;
1117
+ this.Gl = SHA512_IV[13] | 0;
1118
+ this.Hh = SHA512_IV[14] | 0;
1119
+ this.Hl = SHA512_IV[15] | 0;
1120
+ }
1121
+ get() {
1122
+ const {
1123
+ Ah,
1124
+ Al,
1125
+ Bh,
1126
+ Bl,
1127
+ Ch,
1128
+ Cl,
1129
+ Dh,
1130
+ Dl,
1131
+ Eh,
1132
+ El,
1133
+ Fh,
1134
+ Fl,
1135
+ Gh,
1136
+ Gl,
1137
+ Hh,
1138
+ Hl
1139
+ } = this;
1140
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1141
+ }
1142
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1143
+ this.Ah = Ah | 0;
1144
+ this.Al = Al | 0;
1145
+ this.Bh = Bh | 0;
1146
+ this.Bl = Bl | 0;
1147
+ this.Ch = Ch | 0;
1148
+ this.Cl = Cl | 0;
1149
+ this.Dh = Dh | 0;
1150
+ this.Dl = Dl | 0;
1151
+ this.Eh = Eh | 0;
1152
+ this.El = El | 0;
1153
+ this.Fh = Fh | 0;
1154
+ this.Fl = Fl | 0;
1155
+ this.Gh = Gh | 0;
1156
+ this.Gl = Gl | 0;
1157
+ this.Hh = Hh | 0;
1158
+ this.Hl = Hl | 0;
1159
+ }
1160
+ process(view, offset) {
1161
+ for (let i = 0; i < 16; i++, offset += 4) {
1162
+ SHA512_W_H[i] = view.getUint32(offset);
1163
+ SHA512_W_L[i] = view.getUint32(offset += 4);
1164
+ }
1165
+ for (let i = 16; i < 80; i++) {
1166
+ const W15h = SHA512_W_H[i - 15] | 0;
1167
+ const W15l = SHA512_W_L[i - 15] | 0;
1168
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1169
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1170
+ const W2h = SHA512_W_H[i - 2] | 0;
1171
+ const W2l = SHA512_W_L[i - 2] | 0;
1172
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1173
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1174
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1175
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1176
+ SHA512_W_H[i] = SUMh | 0;
1177
+ SHA512_W_L[i] = SUMl | 0;
1178
+ }
1179
+ let {
1180
+ Ah,
1181
+ Al,
1182
+ Bh,
1183
+ Bl,
1184
+ Ch,
1185
+ Cl,
1186
+ Dh,
1187
+ Dl,
1188
+ Eh,
1189
+ El,
1190
+ Fh,
1191
+ Fl,
1192
+ Gh,
1193
+ Gl,
1194
+ Hh,
1195
+ Hl
1196
+ } = this;
1197
+ for (let i = 0; i < 80; i++) {
1198
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1199
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1200
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
1201
+ const CHIl = El & Fl ^ ~El & Gl;
1202
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1203
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1204
+ const T1l = T1ll | 0;
1205
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1206
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1207
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1208
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1209
+ Hh = Gh | 0;
1210
+ Hl = Gl | 0;
1211
+ Gh = Fh | 0;
1212
+ Gl = Fl | 0;
1213
+ Fh = Eh | 0;
1214
+ Fl = El | 0;
1215
+ ({
1216
+ h: Eh,
1217
+ l: El
1218
+ } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1219
+ Dh = Ch | 0;
1220
+ Dl = Cl | 0;
1221
+ Ch = Bh | 0;
1222
+ Cl = Bl | 0;
1223
+ Bh = Ah | 0;
1224
+ Bl = Al | 0;
1225
+ const All = add3L(T1l, sigma0l, MAJl);
1226
+ Ah = add3H(All, T1h, sigma0h, MAJh);
1227
+ Al = All | 0;
1228
+ }
1229
+ ({
1230
+ h: Ah,
1231
+ l: Al
1232
+ } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1233
+ ({
1234
+ h: Bh,
1235
+ l: Bl
1236
+ } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1237
+ ({
1238
+ h: Ch,
1239
+ l: Cl
1240
+ } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1241
+ ({
1242
+ h: Dh,
1243
+ l: Dl
1244
+ } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1245
+ ({
1246
+ h: Eh,
1247
+ l: El
1248
+ } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1249
+ ({
1250
+ h: Fh,
1251
+ l: Fl
1252
+ } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1253
+ ({
1254
+ h: Gh,
1255
+ l: Gl
1256
+ } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1257
+ ({
1258
+ h: Hh,
1259
+ l: Hl
1260
+ } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1261
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1262
+ }
1263
+ roundClean() {
1264
+ clean(SHA512_W_H, SHA512_W_L);
1265
+ }
1266
+ destroy() {
1267
+ clean(this.buffer);
1268
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1269
+ }
1270
+ }
1271
+ class SHA384 extends SHA512 {
1272
+ constructor() {
1273
+ super(48);
1274
+ this.Ah = SHA384_IV[0] | 0;
1275
+ this.Al = SHA384_IV[1] | 0;
1276
+ this.Bh = SHA384_IV[2] | 0;
1277
+ this.Bl = SHA384_IV[3] | 0;
1278
+ this.Ch = SHA384_IV[4] | 0;
1279
+ this.Cl = SHA384_IV[5] | 0;
1280
+ this.Dh = SHA384_IV[6] | 0;
1281
+ this.Dl = SHA384_IV[7] | 0;
1282
+ this.Eh = SHA384_IV[8] | 0;
1283
+ this.El = SHA384_IV[9] | 0;
1284
+ this.Fh = SHA384_IV[10] | 0;
1285
+ this.Fl = SHA384_IV[11] | 0;
1286
+ this.Gh = SHA384_IV[12] | 0;
1287
+ this.Gl = SHA384_IV[13] | 0;
1288
+ this.Hh = SHA384_IV[14] | 0;
1289
+ this.Hl = SHA384_IV[15] | 0;
1290
+ }
472
1291
  }
1292
+ const T224_IV = Uint32Array.from([0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf, 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1]);
1293
+ const T256_IV = Uint32Array.from([0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd, 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2]);
1294
+ class SHA512_224 extends SHA512 {
1295
+ constructor() {
1296
+ super(28);
1297
+ this.Ah = T224_IV[0] | 0;
1298
+ this.Al = T224_IV[1] | 0;
1299
+ this.Bh = T224_IV[2] | 0;
1300
+ this.Bl = T224_IV[3] | 0;
1301
+ this.Ch = T224_IV[4] | 0;
1302
+ this.Cl = T224_IV[5] | 0;
1303
+ this.Dh = T224_IV[6] | 0;
1304
+ this.Dl = T224_IV[7] | 0;
1305
+ this.Eh = T224_IV[8] | 0;
1306
+ this.El = T224_IV[9] | 0;
1307
+ this.Fh = T224_IV[10] | 0;
1308
+ this.Fl = T224_IV[11] | 0;
1309
+ this.Gh = T224_IV[12] | 0;
1310
+ this.Gl = T224_IV[13] | 0;
1311
+ this.Hh = T224_IV[14] | 0;
1312
+ this.Hl = T224_IV[15] | 0;
1313
+ }
1314
+ }
1315
+ class SHA512_256 extends SHA512 {
1316
+ constructor() {
1317
+ super(32);
1318
+ this.Ah = T256_IV[0] | 0;
1319
+ this.Al = T256_IV[1] | 0;
1320
+ this.Bh = T256_IV[2] | 0;
1321
+ this.Bl = T256_IV[3] | 0;
1322
+ this.Ch = T256_IV[4] | 0;
1323
+ this.Cl = T256_IV[5] | 0;
1324
+ this.Dh = T256_IV[6] | 0;
1325
+ this.Dl = T256_IV[7] | 0;
1326
+ this.Eh = T256_IV[8] | 0;
1327
+ this.El = T256_IV[9] | 0;
1328
+ this.Fh = T256_IV[10] | 0;
1329
+ this.Fl = T256_IV[11] | 0;
1330
+ this.Gh = T256_IV[12] | 0;
1331
+ this.Gl = T256_IV[13] | 0;
1332
+ this.Hh = T256_IV[14] | 0;
1333
+ this.Hl = T256_IV[15] | 0;
1334
+ }
1335
+ }
1336
+ const sha256 = createHasher(() => new SHA256());
1337
+ createHasher(() => new SHA224());
1338
+ createHasher(() => new SHA512());
1339
+ createHasher(() => new SHA384());
1340
+ createHasher(() => new SHA512_256());
1341
+ createHasher(() => new SHA512_224());
473
1342
 
474
1343
  function sha256Hash(data) {
475
1344
  return sha256(data);
476
1345
  }
477
1346
 
478
1347
  function aesCbcEncrypt(data, key, iv, padding = true) {
479
- return cbc(key, iv, {
1348
+ return aes.cbc(key, iv, {
480
1349
  disablePadding: !padding
481
1350
  }).encrypt(data);
482
1351
  }
483
1352
  function aesEcbEncrypt(data, key) {
484
- return ecb(key, {
1353
+ return aes.ecb(key, {
485
1354
  disablePadding: true
486
1355
  }).encrypt(data);
487
1356
  }
@@ -610,7 +1479,7 @@ class PDFSecurity {
610
1479
  }
611
1480
  infoStr += `${key}: ${info[key].valueOf()}\n`;
612
1481
  }
613
- return Buffer.from(md5Hash(infoStr));
1482
+ return md5Hash(infoStr);
614
1483
  }
615
1484
  static generateRandomWordArray(bytes) {
616
1485
  return randomBytes(bytes);
@@ -705,8 +1574,8 @@ class PDFSecurity {
705
1574
  encDict.StrF = 'StdCF';
706
1575
  }
707
1576
  encDict.R = r;
708
- encDict.O = Buffer.from(ownerPasswordEntry);
709
- encDict.U = Buffer.from(userPasswordEntry);
1577
+ encDict.O = ownerPasswordEntry;
1578
+ encDict.U = userPasswordEntry;
710
1579
  encDict.P = permissions;
711
1580
  }
712
1581
  _setupEncryptionV5(encDict, options) {
@@ -734,36 +1603,36 @@ class PDFSecurity {
734
1603
  encDict.StmF = 'StdCF';
735
1604
  encDict.StrF = 'StdCF';
736
1605
  encDict.R = 5;
737
- encDict.O = Buffer.from(ownerPasswordEntry);
738
- encDict.OE = Buffer.from(ownerEncryptionKeyEntry);
739
- encDict.U = Buffer.from(userPasswordEntry);
740
- encDict.UE = Buffer.from(userEncryptionKeyEntry);
1606
+ encDict.O = ownerPasswordEntry;
1607
+ encDict.OE = ownerEncryptionKeyEntry;
1608
+ encDict.U = userPasswordEntry;
1609
+ encDict.UE = userEncryptionKeyEntry;
741
1610
  encDict.P = permissions;
742
- encDict.Perms = Buffer.from(permsEntry);
1611
+ encDict.Perms = permsEntry;
743
1612
  }
744
1613
  getEncryptFn(obj, gen) {
745
1614
  let digest;
746
1615
  if (this.version < 5) {
747
1616
  const suffix = new Uint8Array([obj & 0xff, obj >> 8 & 0xff, obj >> 16 & 0xff, gen & 0xff, gen >> 8 & 0xff]);
748
- digest = concatBytes(this.encryptionKey, suffix);
1617
+ digest = utils.concatBytes(this.encryptionKey, suffix);
749
1618
  }
750
1619
  if (this.version === 1 || this.version === 2) {
751
1620
  let key = md5Hash(digest);
752
1621
  const keyLen = Math.min(16, this.keyBits / 8 + 5);
753
1622
  key = key.slice(0, keyLen);
754
- return buffer => Buffer.from(rc4(new Uint8Array(buffer), key));
1623
+ return buffer => rc4(buffer, key);
755
1624
  }
756
1625
  let key;
757
1626
  if (this.version === 4) {
758
1627
  const saltMarker = new Uint8Array([0x73, 0x41, 0x6c, 0x54]);
759
- key = md5Hash(concatBytes(digest, saltMarker));
1628
+ key = md5Hash(utils.concatBytes(digest, saltMarker));
760
1629
  } else {
761
1630
  key = this.encryptionKey;
762
1631
  }
763
1632
  const iv = PDFSecurity.generateRandomWordArray(16);
764
1633
  return buffer => {
765
- const encrypted = aesCbcEncrypt(new Uint8Array(buffer), key, iv, true);
766
- return Buffer.from(concatBytes(iv, encrypted));
1634
+ const encrypted = aesCbcEncrypt(buffer, key, iv, true);
1635
+ return utils.concatBytes(iv, encrypted);
767
1636
  };
768
1637
  }
769
1638
  end() {
@@ -819,7 +1688,7 @@ function getUserPasswordR2(encryptionKey) {
819
1688
  }
820
1689
  function getUserPasswordR3R4(documentId, encryptionKey) {
821
1690
  const key = encryptionKey.slice();
822
- let cipher = md5Hash(concatBytes(processPasswordR2R3R4(), new Uint8Array(documentId)));
1691
+ let cipher = md5Hash(utils.concatBytes(processPasswordR2R3R4(), new Uint8Array(documentId)));
823
1692
  for (let i = 0; i < 20; i++) {
824
1693
  const xorKey = new Uint8Array(key.length);
825
1694
  for (let j = 0; j < key.length; j++) {
@@ -852,7 +1721,7 @@ function getOwnerPasswordR2R3R4(r, keyBits, paddedUserPassword, paddedOwnerPassw
852
1721
  }
853
1722
  function getEncryptionKeyR2R3R4(r, keyBits, documentId, paddedUserPassword, ownerPasswordEntry, permissions) {
854
1723
  const permBytes = new Uint8Array([permissions & 0xff, permissions >> 8 & 0xff, permissions >> 16 & 0xff, permissions >> 24 & 0xff]);
855
- let key = concatBytes(paddedUserPassword, ownerPasswordEntry, permBytes, new Uint8Array(documentId));
1724
+ let key = utils.concatBytes(paddedUserPassword, ownerPasswordEntry, permBytes, new Uint8Array(documentId));
856
1725
  const round = r >= 3 ? 51 : 1;
857
1726
  const keyLen = keyBits / 8;
858
1727
  for (let i = 0; i < round; i++) {
@@ -864,22 +1733,22 @@ function getEncryptionKeyR2R3R4(r, keyBits, documentId, paddedUserPassword, owne
864
1733
  function getUserPasswordR5(processedUserPassword, generateRandomWordArray) {
865
1734
  const validationSalt = generateRandomWordArray(8);
866
1735
  const keySalt = generateRandomWordArray(8);
867
- const hash = sha256Hash(concatBytes(processedUserPassword, validationSalt));
868
- return concatBytes(hash, validationSalt, keySalt);
1736
+ const hash = sha256Hash(utils.concatBytes(processedUserPassword, validationSalt));
1737
+ return utils.concatBytes(hash, validationSalt, keySalt);
869
1738
  }
870
1739
  function getUserEncryptionKeyR5(processedUserPassword, userKeySalt, encryptionKey) {
871
- const key = sha256Hash(concatBytes(processedUserPassword, userKeySalt));
1740
+ const key = sha256Hash(utils.concatBytes(processedUserPassword, userKeySalt));
872
1741
  const iv = new Uint8Array(16);
873
1742
  return aesCbcEncrypt(encryptionKey, key, iv, false);
874
1743
  }
875
1744
  function getOwnerPasswordR5(processedOwnerPassword, userPasswordEntry, generateRandomWordArray) {
876
1745
  const validationSalt = generateRandomWordArray(8);
877
1746
  const keySalt = generateRandomWordArray(8);
878
- const hash = sha256Hash(concatBytes(processedOwnerPassword, validationSalt, userPasswordEntry));
879
- return concatBytes(hash, validationSalt, keySalt);
1747
+ const hash = sha256Hash(utils.concatBytes(processedOwnerPassword, validationSalt, userPasswordEntry));
1748
+ return utils.concatBytes(hash, validationSalt, keySalt);
880
1749
  }
881
1750
  function getOwnerEncryptionKeyR5(processedOwnerPassword, ownerKeySalt, userPasswordEntry, encryptionKey) {
882
- const key = sha256Hash(concatBytes(processedOwnerPassword, ownerKeySalt, userPasswordEntry));
1751
+ const key = sha256Hash(utils.concatBytes(processedOwnerPassword, ownerKeySalt, userPasswordEntry));
883
1752
  const iv = new Uint8Array(16);
884
1753
  return aesCbcEncrypt(encryptionKey, key, iv, false);
885
1754
  }
@@ -2219,6 +3088,60 @@ var VectorMixin = {
2219
3088
  }
2220
3089
  };
2221
3090
 
3091
+ const registeredFiles = new Map();
3092
+ const toNativePath = path => typeof path === 'string' && path.startsWith('file:') ? new URL(path) : path;
3093
+ const getTimestamp = (value, name, defaultValue) => {
3094
+ if (value === undefined) {
3095
+ return defaultValue;
3096
+ }
3097
+ if (!(value instanceof Date) || Number.isNaN(value.getTime())) {
3098
+ throw new TypeError(`Expected options.${name} to be a valid Date`);
3099
+ }
3100
+ return value.getTime();
3101
+ };
3102
+ function registerFile(path, data, options = {}) {
3103
+ if (typeof path !== 'string') {
3104
+ throw new TypeError(`Expected a string for path, got ${typeof path}`);
3105
+ }
3106
+ if (data === undefined) {
3107
+ registeredFiles.delete(path);
3108
+ return;
3109
+ }
3110
+ if (!(data instanceof Uint8Array)) {
3111
+ throw new TypeError(`Expected a Uint8Array or undefined for data, got ${typeof data}`);
3112
+ }
3113
+ if (options === null || typeof options !== 'object') {
3114
+ throw new TypeError(`Expected options to be an object`);
3115
+ }
3116
+ const registeredAt = Date.now();
3117
+ registeredFiles.set(path, {
3118
+ data,
3119
+ birthtime: getTimestamp(options.birthtime, 'birthtime', registeredAt),
3120
+ ctime: getTimestamp(options.ctime, 'ctime', registeredAt)
3121
+ });
3122
+ }
3123
+ var fs = {
3124
+ readFileSync(path) {
3125
+ if (registeredFiles.has(path)) {
3126
+ return registeredFiles.get(path).data;
3127
+ }
3128
+ return fs$1.readFileSync(toNativePath(path));
3129
+ },
3130
+ statSync(path) {
3131
+ if (registeredFiles.has(path)) {
3132
+ const {
3133
+ birthtime,
3134
+ ctime
3135
+ } = registeredFiles.get(path);
3136
+ return {
3137
+ birthtime: new Date(birthtime),
3138
+ ctime: new Date(ctime)
3139
+ };
3140
+ }
3141
+ return fs$1.statSync(toNativePath(path));
3142
+ }
3143
+ };
3144
+
2222
3145
  const WIN_ANSI_MAP = {
2223
3146
  402: 131,
2224
3147
  8211: 150,
@@ -2322,58 +3245,25 @@ oslash ugrave uacute ucircumflex
2322
3245
  udieresis yacute thorn ydieresis\
2323
3246
  `.split(/\s+/);
2324
3247
  class AFMFont {
2325
- constructor(contents) {
2326
- this.attributes = {};
2327
- this.glyphWidths = {};
2328
- this.boundingBoxes = {};
2329
- this.kernPairs = {};
2330
- this.parse(contents);
2331
- this.bbox = this.attributes['FontBBox'].split(/\s+/).map(e => +e);
2332
- this.ascender = +(this.attributes['Ascender'] || 0);
2333
- this.descender = +(this.attributes['Descender'] || 0);
2334
- this.xHeight = +(this.attributes['XHeight'] || 0);
2335
- this.capHeight = +(this.attributes['CapHeight'] || 0);
3248
+ constructor(data) {
3249
+ this.name = data.name;
3250
+ this.bbox = data.bbox.slice();
3251
+ this.ascender = data.ascender;
3252
+ this.descender = data.descender;
3253
+ this.xHeight = data.xHeight;
3254
+ this.capHeight = data.capHeight;
2336
3255
  this.lineGap = this.bbox[3] - this.bbox[1] - (this.ascender - this.descender);
2337
- }
2338
- parse(contents) {
2339
- let section = '';
2340
- for (let line of contents.split('\n')) {
2341
- var match;
2342
- var a;
2343
- if (match = line.match(/^Start(\w+)/)) {
2344
- section = match[1];
2345
- continue;
2346
- } else if (line.match(/^End(\w+)/)) {
2347
- section = '';
2348
- continue;
2349
- }
2350
- switch (section) {
2351
- case 'FontMetrics':
2352
- match = line.match(/(^\w+)\s+(.*)/);
2353
- var key = match[1];
2354
- var value = match[2];
2355
- if (a = this.attributes[key]) {
2356
- if (!Array.isArray(a)) {
2357
- a = this.attributes[key] = [a];
2358
- }
2359
- a.push(value);
2360
- } else {
2361
- this.attributes[key] = value;
2362
- }
2363
- break;
2364
- case 'CharMetrics':
2365
- if (!/^CH?\s/.test(line)) {
2366
- continue;
2367
- }
2368
- var name = line.match(/\bN\s+(\.?\w+)\s*;/)[1];
2369
- this.glyphWidths[name] = +line.match(/\bWX\s+(\d+)\s*;/)[1];
2370
- break;
2371
- case 'KernPairs':
2372
- match = line.match(/^KPX\s+(\.?\w+)\s+(\.?\w+)\s+(-?\d+)/);
2373
- if (match) {
2374
- this.kernPairs[match[1] + '\0' + match[2]] = parseInt(match[3]);
2375
- }
2376
- break;
3256
+ const glyphNames = data.glyphNames.split(' ');
3257
+ this.glyphWidths = Object.fromEntries(glyphNames.map((name, index) => [name, data.glyphWidths[index]]));
3258
+ this.kernPairs = {};
3259
+ for (let index = 0; index < data.kernPairs.length; index += 2) {
3260
+ const amount = data.kernPairs[index];
3261
+ let pairId = 0;
3262
+ for (const delta of data.kernPairs[index + 1]) {
3263
+ pairId += delta;
3264
+ const left = Math.floor(pairId / glyphNames.length);
3265
+ const right = pairId % glyphNames.length;
3266
+ this.kernPairs[`${glyphNames[left]}\0${glyphNames[right]}`] = amount;
2377
3267
  }
2378
3268
  }
2379
3269
  }
@@ -2441,57 +3331,13 @@ class PDFFont {
2441
3331
  }
2442
3332
  }
2443
3333
 
2444
- const STANDARD_FONTS = {
2445
- Courier() {
2446
- return fs.readFileSync(__dirname + '/data/Courier.afm', 'utf8');
2447
- },
2448
- 'Courier-Bold'() {
2449
- return fs.readFileSync(__dirname + '/data/Courier-Bold.afm', 'utf8');
2450
- },
2451
- 'Courier-Oblique'() {
2452
- return fs.readFileSync(__dirname + '/data/Courier-Oblique.afm', 'utf8');
2453
- },
2454
- 'Courier-BoldOblique'() {
2455
- return fs.readFileSync(__dirname + '/data/Courier-BoldOblique.afm', 'utf8');
2456
- },
2457
- Helvetica() {
2458
- return fs.readFileSync(__dirname + '/data/Helvetica.afm', 'utf8');
2459
- },
2460
- 'Helvetica-Bold'() {
2461
- return fs.readFileSync(__dirname + '/data/Helvetica-Bold.afm', 'utf8');
2462
- },
2463
- 'Helvetica-Oblique'() {
2464
- return fs.readFileSync(__dirname + '/data/Helvetica-Oblique.afm', 'utf8');
2465
- },
2466
- 'Helvetica-BoldOblique'() {
2467
- return fs.readFileSync(__dirname + '/data/Helvetica-BoldOblique.afm', 'utf8');
2468
- },
2469
- 'Times-Roman'() {
2470
- return fs.readFileSync(__dirname + '/data/Times-Roman.afm', 'utf8');
2471
- },
2472
- 'Times-Bold'() {
2473
- return fs.readFileSync(__dirname + '/data/Times-Bold.afm', 'utf8');
2474
- },
2475
- 'Times-Italic'() {
2476
- return fs.readFileSync(__dirname + '/data/Times-Italic.afm', 'utf8');
2477
- },
2478
- 'Times-BoldItalic'() {
2479
- return fs.readFileSync(__dirname + '/data/Times-BoldItalic.afm', 'utf8');
2480
- },
2481
- Symbol() {
2482
- return fs.readFileSync(__dirname + '/data/Symbol.afm', 'utf8');
2483
- },
2484
- ZapfDingbats() {
2485
- return fs.readFileSync(__dirname + '/data/ZapfDingbats.afm', 'utf8');
2486
- }
2487
- };
2488
3334
  class StandardFont extends PDFFont {
2489
- constructor(document, name, id) {
3335
+ constructor(document, fontData, id) {
2490
3336
  super();
2491
3337
  this.document = document;
2492
- this.name = name;
3338
+ this.name = fontData.name;
2493
3339
  this.id = id;
2494
- this.font = new AFMFont(STANDARD_FONTS[this.name]());
3340
+ this.font = new AFMFont(fontData);
2495
3341
  ({
2496
3342
  ascender: this.ascender,
2497
3343
  descender: this.descender,
@@ -2537,9 +3383,6 @@ class StandardFont extends PDFFont {
2537
3383
  const scale = size / 1000;
2538
3384
  return width * scale;
2539
3385
  }
2540
- static isStandardFont(name) {
2541
- return name in STANDARD_FONTS;
2542
- }
2543
3386
  }
2544
3387
 
2545
3388
  const toHex = function (num) {
@@ -2688,7 +3531,7 @@ class EmbeddedFont extends PDFFont {
2688
3531
  }
2689
3532
  if (this.document.subset && this.document.subset === 1) {
2690
3533
  const maxCID = this.widths.length - 1;
2691
- const cidSetBuffer = Buffer.alloc(Math.ceil((maxCID + 1) / 8), 0);
3534
+ const cidSetBuffer = new Uint8Array(Math.ceil((maxCID + 1) / 8));
2692
3535
  for (let cid = 0; cid <= maxCID; cid++) {
2693
3536
  if (this.widths[cid] != null) {
2694
3537
  cidSetBuffer[Math.floor(cid / 8)] |= 0x80 >> cid % 8;
@@ -2777,19 +3620,53 @@ end\
2777
3620
  }
2778
3621
  }
2779
3622
 
3623
+ const STANDARD_FONT_NAMES = ['Courier', 'Courier-Bold', 'Courier-BoldOblique', 'Courier-Oblique', 'Helvetica', 'Helvetica-Bold', 'Helvetica-BoldOblique', 'Helvetica-Oblique', 'Symbol', 'Times-Bold', 'Times-BoldItalic', 'Times-Italic', 'Times-Roman', 'ZapfDingbats'];
3624
+ const STANDARD_FONT_NAME_SET = new Set(STANDARD_FONT_NAMES);
3625
+ const validateFontData = (fontData, expectedName) => {
3626
+ if (fontData == null || typeof fontData !== 'object' || !STANDARD_FONT_NAME_SET.has(fontData.name) || expectedName != null && fontData.name !== expectedName) {
3627
+ throw new TypeError('Invalid standard font data.');
3628
+ }
3629
+ };
3630
+ const standardFonts = new Map();
3631
+ const isStandardFont = name => STANDARD_FONT_NAME_SET.has(name);
3632
+ const registerStdFontLoaders = loaders => {
3633
+ for (const [name, loader] of Object.entries(loaders)) {
3634
+ if (!STANDARD_FONT_NAME_SET.has(name) || typeof loader !== 'function') {
3635
+ throw new TypeError('Invalid standard font loader.');
3636
+ }
3637
+ standardFonts.set(name, loader);
3638
+ }
3639
+ };
3640
+ const getStandardFont = name => {
3641
+ if (!STANDARD_FONT_NAME_SET.has(name)) {
3642
+ return null;
3643
+ }
3644
+ const font = standardFonts.get(name);
3645
+ if (font == null) {
3646
+ throw new Error(`Standard font "${name}" is not registered. ` + 'Call registerStdFonts() before using it.');
3647
+ }
3648
+ if (typeof font !== 'function') {
3649
+ return font;
3650
+ }
3651
+ const data = font();
3652
+ validateFontData(data, name);
3653
+ standardFonts.set(name, data);
3654
+ return data;
3655
+ };
3656
+
2780
3657
  class PDFFontFactory {
2781
3658
  static open(document, src, family, id) {
2782
3659
  let font;
2783
3660
  if (typeof src === 'string') {
2784
- if (StandardFont.isStandardFont(src)) {
2785
- return new StandardFont(document, src, id);
3661
+ if (isStandardFont(src)) {
3662
+ return new StandardFont(document, getStandardFont(src), id);
2786
3663
  }
2787
3664
  src = fs.readFileSync(src);
2788
3665
  }
2789
3666
  if (src instanceof Uint8Array) {
2790
- font = create(src, family);
3667
+ font = fontkit.create(src, family);
2791
3668
  } else if (src instanceof ArrayBuffer) {
2792
- font = create(new Uint8Array(src), family);
3669
+ font = fontkit.create(new Uint8Array(src), family);
2793
3670
  }
2794
3671
  if (font == null) {
2795
3672
  throw new Error('Not a supported font format or standard PDF font.');
@@ -2939,11 +3816,42 @@ var FontsMixin = {
2939
3816
  }
2940
3817
  };
2941
3818
 
3819
+ class EventEmitter {
3820
+ constructor() {
3821
+ this._listeners = Object.create(null);
3822
+ }
3823
+ on(event, listener) {
3824
+ (this._listeners[event] || (this._listeners[event] = [])).push(listener);
3825
+ return this;
3826
+ }
3827
+ once(event, listener) {
3828
+ const wrapper = (...args) => {
3829
+ this.off(event, wrapper);
3830
+ listener(...args);
3831
+ };
3832
+ return this.on(event, wrapper);
3833
+ }
3834
+ off(event, listener) {
3835
+ const listeners = this._listeners[event];
3836
+ if (listeners) {
3837
+ const index = listeners.indexOf(listener);
3838
+ if (index !== -1) listeners.splice(index, 1);
3839
+ }
3840
+ return this;
3841
+ }
3842
+ emit(event, ...args) {
3843
+ const listeners = this._listeners[event];
3844
+ if (!listeners) return false;
3845
+ for (const listener of listeners.slice()) listener(...args);
3846
+ return listeners.length > 0;
3847
+ }
3848
+ }
3849
+
2942
3850
  const SOFT_HYPHEN = '\u00AD';
2943
3851
  const HYPHEN = '-';
2944
- class LineWrapper {
3852
+ class LineWrapper extends EventEmitter {
2945
3853
  constructor(document, options) {
2946
- this._listeners = Object.create(null);
3854
+ super();
2947
3855
  this.document = document;
2948
3856
  this.horizontalScaling = options.horizontalScaling || 100;
2949
3857
  this.indent = (options.indent || 0) * this.horizontalScaling / 100;
@@ -2959,6 +3867,7 @@ class LineWrapper {
2959
3867
  this.column = 1;
2960
3868
  this.ellipsis = options.ellipsis;
2961
3869
  this.continuedX = 0;
3870
+ this.indentApplied = false;
2962
3871
  this.features = options.features;
2963
3872
  if (options.height != null) {
2964
3873
  this.height = options.height;
@@ -2967,15 +3876,26 @@ class LineWrapper {
2967
3876
  this.maxY = PDFNumber(this.document.page.maxY());
2968
3877
  }
2969
3878
  this.on('firstLine', options => {
2970
- const indent = this.continuedX || this.indent;
2971
- this.document.x += indent;
2972
- this.lineWidth -= indent;
3879
+ const continuation = this.continuedX;
3880
+ const indent = continuation || this.indent;
3881
+ if (continuation || !this.indentApplied) {
3882
+ this.document.x += indent;
3883
+ this.lineWidth -= indent;
3884
+ this.indentApplied = true;
3885
+ }
2973
3886
  if (options.indentAllLines) {
3887
+ if (continuation) {
3888
+ this.once('line', () => {
3889
+ this.document.x -= continuation;
3890
+ this.lineWidth += continuation;
3891
+ });
3892
+ }
2974
3893
  return;
2975
3894
  }
2976
3895
  this.once('line', () => {
2977
3896
  this.document.x -= indent;
2978
3897
  this.lineWidth += indent;
3898
+ this.indentApplied = false;
2979
3899
  if (options.continued && !this.continuedX) {
2980
3900
  this.continuedX = this.indent;
2981
3901
  }
@@ -2999,22 +3919,6 @@ class LineWrapper {
2999
3919
  });
3000
3920
  });
3001
3921
  }
3002
- on(event, listener) {
3003
- (this._listeners[event] || (this._listeners[event] = [])).push(listener);
3004
- }
3005
- once(event, listener) {
3006
- const wrapper = (...args) => {
3007
- const listeners = this._listeners[event];
3008
- listeners.splice(listeners.indexOf(wrapper), 1);
3009
- listener(...args);
3010
- };
3011
- this.on(event, wrapper);
3012
- }
3013
- emit(event, ...args) {
3014
- const listeners = this._listeners[event];
3015
- if (!listeners) return;
3016
- for (const listener of listeners.slice()) listener(...args);
3017
- }
3018
3922
  wordWidth(word) {
3019
3923
  return PDFNumber(this.document.widthOfString(word, this) + this.characterSpacing + this.wordSpacing);
3020
3924
  }
@@ -3205,9 +4109,9 @@ class LineWrapper {
3205
4109
  this.startY = this.document.page.margins.top;
3206
4110
  this.maxY = this.document.page.maxY();
3207
4111
  if (this.indentAllLines) {
3208
- const indent = this.continuedX || this.indent;
3209
- this.document.x += indent;
3210
- this.lineWidth -= indent;
4112
+ if (this.indentApplied) {
4113
+ this.document.x += this.continuedX || this.indent;
4114
+ }
3211
4115
  } else {
3212
4116
  this.document.x = this.startX;
3213
4117
  }
@@ -3747,20 +4651,6 @@ var TextMixin = {
3747
4651
  }
3748
4652
  };
3749
4653
 
3750
- const toBinaryString = bytes => {
3751
- const chunkSize = 0x8000;
3752
- let out = '';
3753
- for (let i = 0; i < bytes.length; i += chunkSize) {
3754
- const end = Math.min(i + chunkSize, bytes.length);
3755
- out += String.fromCharCode.apply(null, bytes.subarray(i, end));
3756
- }
3757
- return out;
3758
- };
3759
- const readUInt16BE = (bytes, offset = 0) => (bytes[offset] << 8 | bytes[offset + 1]) >>> 0;
3760
- const readUInt16LE = (bytes, offset = 0) => (bytes[offset + 1] << 8 | bytes[offset]) >>> 0;
3761
- const readUInt32BE = (bytes, offset = 0) => bytes[offset] * 0x1000000 + (bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
3762
- const readUInt32LE = (bytes, offset = 0) => (bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16) + bytes[offset + 3] * 0x1000000 >>> 0;
3763
-
3764
4654
  const parseExifOrientation = data => {
3765
4655
  if (!data || data.length < 20) return null;
3766
4656
  let pos = 2;
@@ -3813,7 +4703,7 @@ class JPEG {
3813
4703
  let marker;
3814
4704
  this.data = data;
3815
4705
  this.label = label;
3816
- if (this.data.readUInt16BE(0) !== 0xffd8) {
4706
+ if (readUInt16BE(this.data, 0) !== 0xffd8) {
3817
4707
  throw 'SOI not found in JPEG';
3818
4708
  }
3819
4709
  this.orientation = parseExifOrientation(this.data) || 1;
@@ -3821,21 +4711,21 @@ class JPEG {
3821
4711
  while (pos < this.data.length) {
3822
4712
  while (pos < this.data.length && this.data[pos] !== 0xff) pos++;
3823
4713
  if (pos >= this.data.length) break;
3824
- marker = this.data.readUInt16BE(pos);
4714
+ marker = readUInt16BE(this.data, pos);
3825
4715
  pos += 2;
3826
4716
  if (MARKERS.includes(marker)) {
3827
4717
  break;
3828
4718
  }
3829
- pos += this.data.readUInt16BE(pos);
4719
+ pos += readUInt16BE(this.data, pos);
3830
4720
  }
3831
4721
  if (!MARKERS.includes(marker)) {
3832
4722
  throw 'Invalid JPEG.';
3833
4723
  }
3834
4724
  pos += 2;
3835
4725
  this.bits = this.data[pos++];
3836
- this.height = this.data.readUInt16BE(pos);
4726
+ this.height = readUInt16BE(this.data, pos);
3837
4727
  pos += 2;
3838
- this.width = this.data.readUInt16BE(pos);
4728
+ this.width = readUInt16BE(this.data, pos);
3839
4729
  pos += 2;
3840
4730
  const channels = this.data[pos];
3841
4731
  this.colorSpace = COLOR_SPACE_MAP[channels];
@@ -3905,7 +4795,7 @@ class PNGImage {
3905
4795
  obj.data['ColorSpace'] = image.colorSpace;
3906
4796
  } else {
3907
4797
  const palette = document.ref();
3908
- palette.end(Buffer.from(image.palette));
4798
+ palette.end(new Uint8Array(image.palette));
3909
4799
  obj.data['ColorSpace'] = ['Indexed', 'DeviceRGB', image.palette.length / 3 - 1, palette];
3910
4800
  }
3911
4801
  if (image.transparency.grayscale != null) {
@@ -3954,8 +4844,8 @@ class PNGImage {
3954
4844
  let a, p;
3955
4845
  const colorCount = this.image.colors;
3956
4846
  const pixelCount = this.width * this.height;
3957
- const imgData = Buffer.alloc(pixelCount * colorCount);
3958
- const alphaChannel = Buffer.alloc(pixelCount);
4847
+ const imgData = new Uint8Array(pixelCount * colorCount);
4848
+ const alphaChannel = new Uint8Array(pixelCount);
3959
4849
  let i = p = a = 0;
3960
4850
  const len = pixels.length;
3961
4851
  const skipByteCount = this.image.bits === 16 ? 1 : 0;
@@ -3976,13 +4866,13 @@ class PNGImage {
3976
4866
  const transparency = this.image.transparency.indexed;
3977
4867
  const isInterlaced = this.image.interlaceMethod === 1;
3978
4868
  return this.image.decodePixels(pixels => {
3979
- const alphaChannel = Buffer.alloc(this.width * this.height);
4869
+ const alphaChannel = new Uint8Array(this.width * this.height);
3980
4870
  let i = 0;
3981
4871
  for (let j = 0, end = pixels.length; j < end; j++) {
3982
4872
  alphaChannel[i++] = transparency[pixels[j]];
3983
4873
  }
3984
4874
  if (isInterlaced) {
3985
- this.imgData = zlib.deflateSync(Buffer.from(pixels));
4875
+ this.imgData = zlib.deflateSync(pixels);
3986
4876
  }
3987
4877
  this.alphaChannel = zlib.deflateSync(alphaChannel);
3988
4878
  return this.finalize();
@@ -3999,14 +4889,14 @@ class PNGImage {
3999
4889
  class PDFImage {
4000
4890
  static open(src, label) {
4001
4891
  let data;
4002
- if (Buffer.isBuffer(src)) {
4892
+ if (src instanceof Uint8Array) {
4003
4893
  data = src;
4004
4894
  } else if (src instanceof ArrayBuffer) {
4005
- data = Buffer.from(new Uint8Array(src));
4895
+ data = new Uint8Array(src);
4006
4896
  } else {
4007
4897
  const match = /^data:.+?;base64,(.*)$/.exec(src);
4008
4898
  if (match) {
4009
- data = Buffer.from(match[1], 'base64');
4899
+ data = fromBase64(match[1]);
4010
4900
  } else {
4011
4901
  data = fs.readFileSync(src);
4012
4902
  if (!data) {
@@ -4223,136 +5113,169 @@ class PDFAnnotationReference {
4223
5113
 
4224
5114
  var AnnotationsMixin = {
4225
5115
  annotate(x, y, w, h, options) {
4226
- options.Type = 'Annot';
4227
- options.Rect = this._convertRect(x, y, w, h);
4228
- options.Border = [0, 0, 0];
4229
- if (options.Subtype === 'Link' && typeof options.F === 'undefined') {
4230
- options.F = 1 << 2;
5116
+ const {
5117
+ structParent,
5118
+ color,
5119
+ ...annotations
5120
+ } = options;
5121
+ annotations.Type = 'Annot';
5122
+ annotations.Rect = this._convertRect(x, y, w, h);
5123
+ annotations.Border = [0, 0, 0];
5124
+ if (annotations.Subtype === 'Link' && typeof annotations.F === 'undefined') {
5125
+ annotations.F = 1 << 2;
4231
5126
  }
4232
- if (options.Subtype !== 'Link') {
4233
- if (options.C == null) {
4234
- options.C = this._normalizeColor(options.color || [0, 0, 0]);
5127
+ if (annotations.Subtype !== 'Link') {
5128
+ if (annotations.C == null) {
5129
+ annotations.C = this._normalizeColor(color || [0, 0, 0]);
4235
5130
  }
4236
5131
  }
4237
- delete options.color;
4238
- if (typeof options.Dest === 'string') {
4239
- options.Dest = new String(options.Dest);
4240
- }
4241
- const structParent = options.structParent;
4242
- delete options.structParent;
4243
- for (let key in options) {
4244
- const val = options[key];
4245
- options[key[0].toUpperCase() + key.slice(1)] = val;
5132
+ if (typeof annotations.Dest === 'string') {
5133
+ annotations.Dest = new String(annotations.Dest);
4246
5134
  }
4247
- const ref = this.ref(options);
5135
+ const ref = this.ref(annotations);
4248
5136
  this.page.annotations.push(ref);
4249
- if (structParent && typeof structParent.add === 'function') {
5137
+ if (typeof structParent?.add === 'function') {
4250
5138
  const annotRef = new PDFAnnotationReference(ref);
4251
5139
  structParent.add(annotRef);
4252
5140
  }
4253
5141
  ref.end();
4254
5142
  return this;
4255
5143
  },
4256
- note(x, y, w, h, contents, options = {}) {
4257
- options.Subtype = 'Text';
4258
- options.Contents = new String(contents);
4259
- if (options.Name == null) {
4260
- options.Name = 'Comment';
5144
+ note(x, y, w, h, contents, options) {
5145
+ const annotationOptions = {
5146
+ ...options,
5147
+ Subtype: 'Text',
5148
+ Contents: new String(contents)
5149
+ };
5150
+ if (annotationOptions.Name == null) {
5151
+ annotationOptions.Name = 'Comment';
4261
5152
  }
4262
- if (options.color == null) {
4263
- options.color = [243, 223, 92];
5153
+ if (annotationOptions.color == null) {
5154
+ annotationOptions.color = [243, 223, 92];
4264
5155
  }
4265
- return this.annotate(x, y, w, h, options);
5156
+ return this.annotate(x, y, w, h, annotationOptions);
4266
5157
  },
4267
- goTo(x, y, w, h, name, options = {}) {
4268
- options.Subtype = 'Link';
4269
- options.A = this.ref({
4270
- S: 'GoTo',
4271
- D: new String(name)
4272
- });
4273
- options.A.end();
4274
- return this.annotate(x, y, w, h, options);
5158
+ goTo(x, y, w, h, name, options) {
5159
+ const annotateOptions = {
5160
+ ...options,
5161
+ Subtype: 'Link',
5162
+ A: this.ref({
5163
+ S: 'GoTo',
5164
+ D: new String(name)
5165
+ })
5166
+ };
5167
+ annotateOptions.A.end();
5168
+ return this.annotate(x, y, w, h, annotateOptions);
4275
5169
  },
4276
- link(x, y, w, h, url, options = {}) {
4277
- options.Subtype = 'Link';
5170
+ link(x, y, w, h, url, options) {
5171
+ const annotateOptions = {
5172
+ ...options,
5173
+ Subtype: 'Link'
5174
+ };
4278
5175
  if (typeof url === 'number') {
4279
5176
  const pages = this._root.data.Pages.data;
4280
5177
  if (url >= 0 && url < pages.Kids.length) {
4281
- options.A = this.ref({
5178
+ annotateOptions.A = this.ref({
4282
5179
  S: 'GoTo',
4283
5180
  D: [pages.Kids[url], 'XYZ', null, null, null]
4284
5181
  });
4285
- options.A.end();
5182
+ annotateOptions.A.end();
4286
5183
  } else {
4287
5184
  throw new Error(`The document has no page ${url}`);
4288
5185
  }
4289
5186
  } else {
4290
- options.A = this.ref({
5187
+ annotateOptions.A = this.ref({
4291
5188
  S: 'URI',
4292
5189
  URI: new String(url)
4293
5190
  });
4294
- options.A.end();
5191
+ annotateOptions.A.end();
4295
5192
  }
4296
- if (options.structParent && !options.Contents) {
4297
- options.Contents = new String('');
5193
+ if (annotateOptions.structParent && !annotateOptions.Contents) {
5194
+ annotateOptions.Contents = new String('');
4298
5195
  }
4299
- return this.annotate(x, y, w, h, options);
5196
+ return this.annotate(x, y, w, h, annotateOptions);
4300
5197
  },
4301
- _markup(x, y, w, h, options = {}) {
5198
+ _markup(x, y, w, h, options) {
4302
5199
  const [x1, y1, x2, y2] = this._convertRect(x, y, w, h);
4303
- options.QuadPoints = [x1, y2, x2, y2, x1, y1, x2, y1];
4304
- options.Contents = new String();
4305
- return this.annotate(x, y, w, h, options);
4306
- },
4307
- highlight(x, y, w, h, options = {}) {
4308
- options.Subtype = 'Highlight';
4309
- if (options.color == null) {
4310
- options.color = [241, 238, 148];
4311
- }
4312
- return this._markup(x, y, w, h, options);
4313
- },
4314
- underline(x, y, w, h, options = {}) {
4315
- options.Subtype = 'Underline';
4316
- return this._markup(x, y, w, h, options);
4317
- },
4318
- strike(x, y, w, h, options = {}) {
4319
- options.Subtype = 'StrikeOut';
4320
- return this._markup(x, y, w, h, options);
4321
- },
4322
- lineAnnotation(x1, y1, x2, y2, options = {}) {
4323
- options.Subtype = 'Line';
4324
- options.Contents = new String();
4325
- options.L = [x1, this.page.height - y1, x2, this.page.height - y2];
4326
- return this.annotate(x1, y1, x2, y2, options);
4327
- },
4328
- rectAnnotation(x, y, w, h, options = {}) {
4329
- options.Subtype = 'Square';
4330
- options.Contents = new String();
4331
- return this.annotate(x, y, w, h, options);
4332
- },
4333
- ellipseAnnotation(x, y, w, h, options = {}) {
4334
- options.Subtype = 'Circle';
4335
- options.Contents = new String();
4336
- return this.annotate(x, y, w, h, options);
4337
- },
4338
- textAnnotation(x, y, w, h, text, options = {}) {
4339
- options.Subtype = 'FreeText';
4340
- options.Contents = new String(text);
4341
- options.DA = new String();
4342
- return this.annotate(x, y, w, h, options);
4343
- },
4344
- fileAnnotation(x, y, w, h, file = {}, options = {}) {
5200
+ return this.annotate(x, y, w, h, {
5201
+ ...options,
5202
+ QuadPoints: [x1, y2, x2, y2, x1, y1, x2, y1],
5203
+ Contents: new String()
5204
+ });
5205
+ },
5206
+ highlight(x, y, w, h, options) {
5207
+ const annotationOptions = {
5208
+ ...options,
5209
+ Subtype: 'Highlight'
5210
+ };
5211
+ if (annotationOptions.color == null) {
5212
+ annotationOptions.color = [241, 238, 148];
5213
+ }
5214
+ return this._markup(x, y, w, h, annotationOptions);
5215
+ },
5216
+ underline(x, y, w, h, options) {
5217
+ const annotationOptions = {
5218
+ ...options,
5219
+ Subtype: 'Underline'
5220
+ };
5221
+ return this._markup(x, y, w, h, annotationOptions);
5222
+ },
5223
+ strike(x, y, w, h, options) {
5224
+ const annotationOptions = {
5225
+ ...options,
5226
+ Subtype: 'StrikeOut'
5227
+ };
5228
+ return this._markup(x, y, w, h, annotationOptions);
5229
+ },
5230
+ lineAnnotation(x1, y1, x2, y2, options) {
5231
+ const annotationOptions = {
5232
+ ...options,
5233
+ Subtype: 'Line',
5234
+ Contents: new String(),
5235
+ L: [x1, this.page.height - y1, x2, this.page.height - y2]
5236
+ };
5237
+ return this.annotate(x1, y1, x2, y2, annotationOptions);
5238
+ },
5239
+ rectAnnotation(x, y, w, h, options) {
5240
+ const annotationOptions = {
5241
+ ...options,
5242
+ Subtype: 'Square',
5243
+ Contents: new String()
5244
+ };
5245
+ return this.annotate(x, y, w, h, annotationOptions);
5246
+ },
5247
+ ellipseAnnotation(x, y, w, h, options) {
5248
+ const annotationOptions = {
5249
+ ...options,
5250
+ Subtype: 'Circle',
5251
+ Contents: new String()
5252
+ };
5253
+ return this.annotate(x, y, w, h, annotationOptions);
5254
+ },
5255
+ textAnnotation(x, y, w, h, text, options) {
5256
+ const annotationOptions = {
5257
+ ...options,
5258
+ Subtype: 'FreeText',
5259
+ Contents: new String(text),
5260
+ DA: new String()
5261
+ };
5262
+ return this.annotate(x, y, w, h, annotationOptions);
5263
+ },
5264
+ fileAnnotation(x, y, w, h, file = {}, options) {
4345
5265
  const filespec = this.file(file.src, Object.assign({
4346
5266
  hidden: true
4347
5267
  }, file));
4348
- options.Subtype = 'FileAttachment';
4349
- options.FS = filespec;
4350
- if (options.Contents) {
4351
- options.Contents = new String(options.Contents);
5268
+ const annotationOptions = {
5269
+ ...options,
5270
+ Subtype: 'FileAttachment',
5271
+ FS: filespec
5272
+ };
5273
+ if (annotationOptions.Contents) {
5274
+ annotationOptions.Contents = new String(annotationOptions.Contents);
4352
5275
  } else if (filespec.data.Desc) {
4353
- options.Contents = filespec.data.Desc;
5276
+ annotationOptions.Contents = new String(filespec.data.Desc);
4354
5277
  }
4355
- return this.annotate(x, y, w, h, options);
5278
+ return this.annotate(x, y, w, h, annotationOptions);
4356
5279
  },
4357
5280
  _convertRect(x1, y1, w, h) {
4358
5281
  let y2 = y1;
@@ -4873,6 +5796,105 @@ const FORMAT_DEFAULT = {
4873
5796
  sepComma: false
4874
5797
  }
4875
5798
  };
5799
+ function mapTypeAndFlags(type, userOptions, pdfObject) {
5800
+ let flags = userOptions.Ff ?? 0;
5801
+ if (type === 'text') {
5802
+ pdfObject.FT = 'Tx';
5803
+ } else if (type === 'pushButton') {
5804
+ pdfObject.FT = 'Btn';
5805
+ flags |= FIELD_FLAGS.pushButton;
5806
+ } else if (type === 'radioButton') {
5807
+ pdfObject.FT = 'Btn';
5808
+ flags |= FIELD_FLAGS.radioButton;
5809
+ } else if (type === 'checkbox') {
5810
+ pdfObject.FT = 'Btn';
5811
+ } else if (type === 'combo') {
5812
+ pdfObject.FT = 'Ch';
5813
+ flags |= FIELD_FLAGS.combo;
5814
+ } else if (type === 'list') {
5815
+ pdfObject.FT = 'Ch';
5816
+ } else if (type) {
5817
+ throw new Error(`Invalid form annotation type '${type}'`);
5818
+ }
5819
+ Object.keys(userOptions).forEach(key => {
5820
+ if (FIELD_FLAGS[key] && userOptions[key]) {
5821
+ flags |= FIELD_FLAGS[key];
5822
+ }
5823
+ });
5824
+ if (flags !== 0) {
5825
+ pdfObject.Ff = flags;
5826
+ }
5827
+ }
5828
+ function mapJustify(userOptions, pdfObject) {
5829
+ const result = FIELD_JUSTIFY[userOptions.align];
5830
+ if (typeof result === 'number' && result !== 0) {
5831
+ pdfObject.Q = result;
5832
+ }
5833
+ }
5834
+ function mapStrings(options, pdfObject) {
5835
+ if (Array.isArray(options.select) && options.select.length) {
5836
+ pdfObject.Opt = options.select.map(s => {
5837
+ if (typeof s === 'string') {
5838
+ return new String(s);
5839
+ }
5840
+ return s;
5841
+ });
5842
+ }
5843
+ Object.keys(VALUE_MAP).forEach(key => {
5844
+ if (key in options) {
5845
+ const value = options[key] ?? '';
5846
+ pdfObject[VALUE_MAP[key]] = typeof value === 'string' ? new String(value) : value;
5847
+ }
5848
+ });
5849
+ if (options.MK?.CA) {
5850
+ pdfObject.MK = {
5851
+ CA: new String(options.MK.CA)
5852
+ };
5853
+ }
5854
+ if (options.label) {
5855
+ pdfObject.MK = options.MK ?? {};
5856
+ pdfObject.MK.CA = new String(options.label);
5857
+ }
5858
+ }
5859
+ function mapFormat(options, pdfObject) {
5860
+ const f = options.format;
5861
+ if (f?.type) {
5862
+ let fnKeystroke;
5863
+ let fnFormat;
5864
+ let params = '';
5865
+ if (FORMAT_SPECIAL[f.type] !== undefined) {
5866
+ fnKeystroke = `AFSpecial_Keystroke`;
5867
+ fnFormat = `AFSpecial_Format`;
5868
+ params = FORMAT_SPECIAL[f.type];
5869
+ } else {
5870
+ let format = f.type.charAt(0).toUpperCase() + f.type.slice(1);
5871
+ fnKeystroke = `AF${format}_Keystroke`;
5872
+ fnFormat = `AF${format}_Format`;
5873
+ if (f.type === 'date') {
5874
+ fnKeystroke += 'Ex';
5875
+ fnFormat += 'Ex';
5876
+ params = '"' + String(f.param) + '"';
5877
+ } else if (f.type === 'time') {
5878
+ params = String(f.param);
5879
+ } else if (f.type === 'number') {
5880
+ let p = Object.assign({}, FORMAT_DEFAULT.number, f);
5881
+ params = String([String(p.nDec), p.sepComma ? '0' : '1', '"' + p.negStyle + '"', 'null', '"' + p.currency + '"', String(p.currencyPrepend)].join(','));
5882
+ } else if (f.type === 'percent') {
5883
+ let p = Object.assign({}, FORMAT_DEFAULT.percent, f);
5884
+ params = String([String(p.nDec), p.sepComma ? '0' : '1'].join(','));
5885
+ }
5886
+ }
5887
+ pdfObject.AA = options.AA ?? {};
5888
+ pdfObject.AA.K = {
5889
+ S: 'JavaScript',
5890
+ JS: new String(`${fnKeystroke}(${params});`)
5891
+ };
5892
+ pdfObject.AA.F = {
5893
+ S: 'JavaScript',
5894
+ JS: new String(`${fnFormat}(${params});`)
5895
+ };
5896
+ }
5897
+ }
4876
5898
  var AcroFormMixin = {
4877
5899
  initForm() {
4878
5900
  if (!this._font) {
@@ -4971,187 +5993,49 @@ var AcroFormMixin = {
4971
5993
  if (!this._acroform) {
4972
5994
  throw new Error('Call document.initForm() method before adding form elements to document');
4973
5995
  }
4974
- let opts = Object.assign({}, options);
4975
- if (type !== null) {
4976
- opts = this._resolveType(type, options);
4977
- }
4978
- opts = this._resolveFlags(opts);
4979
- opts = this._resolveJustify(opts);
4980
- opts = this._resolveFont(opts);
4981
- opts = this._resolveStrings(opts);
4982
- opts = this._resolveColors(opts);
4983
- opts = this._resolveFormat(opts);
4984
- opts.T = new String(name);
4985
- if (opts.parent) {
4986
- opts.Parent = opts.parent;
4987
- delete opts.parent;
4988
- }
4989
- return opts;
4990
- },
4991
- _resolveType(type, opts) {
4992
- if (type === 'text') {
4993
- opts.FT = 'Tx';
4994
- } else if (type === 'pushButton') {
4995
- opts.FT = 'Btn';
4996
- opts.pushButton = true;
4997
- } else if (type === 'radioButton') {
4998
- opts.FT = 'Btn';
4999
- opts.radioButton = true;
5000
- } else if (type === 'checkbox') {
5001
- opts.FT = 'Btn';
5002
- } else if (type === 'combo') {
5003
- opts.FT = 'Ch';
5004
- opts.combo = true;
5005
- } else if (type === 'list') {
5006
- opts.FT = 'Ch';
5007
- } else {
5008
- throw new Error(`Invalid form annotation type '${type}'`);
5009
- }
5010
- return opts;
5011
- },
5012
- _resolveFormat(opts) {
5013
- const f = opts.format;
5014
- if (f && f.type) {
5015
- let fnKeystroke;
5016
- let fnFormat;
5017
- let params = '';
5018
- if (FORMAT_SPECIAL[f.type] !== undefined) {
5019
- fnKeystroke = `AFSpecial_Keystroke`;
5020
- fnFormat = `AFSpecial_Format`;
5021
- params = FORMAT_SPECIAL[f.type];
5022
- } else {
5023
- let format = f.type.charAt(0).toUpperCase() + f.type.slice(1);
5024
- fnKeystroke = `AF${format}_Keystroke`;
5025
- fnFormat = `AF${format}_Format`;
5026
- if (f.type === 'date') {
5027
- fnKeystroke += 'Ex';
5028
- params = String(f.param);
5029
- } else if (f.type === 'time') {
5030
- params = String(f.param);
5031
- } else if (f.type === 'number') {
5032
- let p = Object.assign({}, FORMAT_DEFAULT.number, f);
5033
- params = String([String(p.nDec), p.sepComma ? '0' : '1', '"' + p.negStyle + '"', 'null', '"' + p.currency + '"', String(p.currencyPrepend)].join(','));
5034
- } else if (f.type === 'percent') {
5035
- let p = Object.assign({}, FORMAT_DEFAULT.percent, f);
5036
- params = String([String(p.nDec), p.sepComma ? '0' : '1'].join(','));
5037
- }
5038
- }
5039
- opts.AA = opts.AA ? opts.AA : {};
5040
- opts.AA.K = {
5041
- S: 'JavaScript',
5042
- JS: new String(`${fnKeystroke}(${params});`)
5043
- };
5044
- opts.AA.F = {
5045
- S: 'JavaScript',
5046
- JS: new String(`${fnFormat}(${params});`)
5047
- };
5048
- }
5049
- delete opts.format;
5050
- return opts;
5051
- },
5052
- _resolveColors(opts) {
5053
- let color = this._normalizeColor(opts.backgroundColor);
5996
+ const pdfObject = {};
5997
+ mapTypeAndFlags(type, options, pdfObject);
5998
+ mapJustify(options, pdfObject);
5999
+ this._mapFont(options, pdfObject);
6000
+ mapStrings(options, pdfObject);
6001
+ this._mapColors(options, pdfObject);
6002
+ mapFormat(options, pdfObject);
6003
+ pdfObject.T = new String(name);
6004
+ if (options.parent) {
6005
+ pdfObject.Parent = options.parent;
6006
+ }
6007
+ return pdfObject;
6008
+ },
6009
+ _mapColors(options, pdfObject) {
6010
+ let color = this._normalizeColor(options.backgroundColor);
5054
6011
  if (color) {
5055
- if (!opts.MK) {
5056
- opts.MK = {};
5057
- }
5058
- opts.MK.BG = color;
6012
+ pdfObject.MK = pdfObject.MK ? pdfObject.MK : {};
6013
+ pdfObject.MK.BG = color;
5059
6014
  }
5060
- color = this._normalizeColor(opts.borderColor);
6015
+ color = this._normalizeColor(options.borderColor);
5061
6016
  if (color) {
5062
- if (!opts.MK) {
5063
- opts.MK = {};
5064
- }
5065
- opts.MK.BC = color;
5066
- }
5067
- delete opts.backgroundColor;
5068
- delete opts.borderColor;
5069
- return opts;
5070
- },
5071
- _resolveFlags(options) {
5072
- let result = 0;
5073
- Object.keys(options).forEach(key => {
5074
- if (FIELD_FLAGS[key]) {
5075
- if (options[key]) {
5076
- result |= FIELD_FLAGS[key];
5077
- }
5078
- delete options[key];
6017
+ if (!pdfObject.MK) {
6018
+ pdfObject.MK = {};
5079
6019
  }
5080
- });
5081
- if (result !== 0) {
5082
- options.Ff = options.Ff ? options.Ff : 0;
5083
- options.Ff |= result;
5084
- }
5085
- return options;
5086
- },
5087
- _resolveJustify(options) {
5088
- let result = 0;
5089
- if (options.align !== undefined) {
5090
- if (typeof FIELD_JUSTIFY[options.align] === 'number') {
5091
- result = FIELD_JUSTIFY[options.align];
5092
- }
5093
- delete options.align;
5094
- }
5095
- if (result !== 0) {
5096
- options.Q = result;
6020
+ pdfObject.MK.BC = color;
5097
6021
  }
5098
- return options;
5099
6022
  },
5100
- _resolveFont(options) {
5101
- if (this._acroform.fonts[this._font.id] == null) {
5102
- this._acroform.fonts[this._font.id] = this._font.ref();
6023
+ _mapFont(options, pdfObject) {
6024
+ const {
6025
+ _acroform,
6026
+ _font
6027
+ } = this;
6028
+ if (_acroform.fonts[_font.id] == null) {
6029
+ _acroform.fonts[_font.id] = _font.ref();
5103
6030
  }
5104
- if (this._acroform.defaultFont !== this._font.name) {
5105
- options.DR = {
6031
+ if (_acroform.defaultFont !== _font.name) {
6032
+ pdfObject.DR = {
5106
6033
  Font: {}
5107
6034
  };
5108
6035
  const fontSize = options.fontSize || 0;
5109
- options.DR.Font[this._font.id] = this._font.ref();
5110
- options.DA = new String(`/${this._font.id} ${fontSize} Tf 0 g`);
5111
- }
5112
- return options;
5113
- },
5114
- _resolveStrings(options) {
5115
- let select = [];
5116
- function appendChoices(a) {
5117
- if (Array.isArray(a)) {
5118
- for (let idx = 0; idx < a.length; idx++) {
5119
- if (typeof a[idx] === 'string') {
5120
- select.push(new String(a[idx]));
5121
- } else {
5122
- select.push(a[idx]);
5123
- }
5124
- }
5125
- }
6036
+ pdfObject.DR.Font[_font.id] = _font.ref();
6037
+ pdfObject.DA = new String(`/${_font.id} ${fontSize} Tf 0 g`);
5126
6038
  }
5127
- appendChoices(options.Opt);
5128
- if (options.select) {
5129
- appendChoices(options.select);
5130
- delete options.select;
5131
- }
5132
- if (select.length) {
5133
- options.Opt = select;
5134
- }
5135
- Object.keys(VALUE_MAP).forEach(key => {
5136
- if (options[key] !== undefined) {
5137
- options[VALUE_MAP[key]] = options[key];
5138
- delete options[key];
5139
- }
5140
- });
5141
- ['V', 'DV'].forEach(key => {
5142
- if (typeof options[key] === 'string') {
5143
- options[key] = new String(options[key]);
5144
- }
5145
- });
5146
- if (options.MK && options.MK.CA) {
5147
- options.MK.CA = new String(options.MK.CA);
5148
- }
5149
- if (options.label) {
5150
- options.MK = options.MK ? options.MK : {};
5151
- options.MK.CA = new String(options.label);
5152
- delete options.label;
5153
- }
5154
- return options;
5155
6039
  }
5156
6040
  };
5157
6041
 
@@ -5167,17 +6051,17 @@ var AttachmentsMixin = {
5167
6051
  if (!src) {
5168
6052
  throw new Error('No src specified');
5169
6053
  }
5170
- if (Buffer.isBuffer(src)) {
6054
+ if (src instanceof Uint8Array) {
5171
6055
  data = src;
5172
6056
  } else if (src instanceof ArrayBuffer) {
5173
- data = Buffer.from(new Uint8Array(src));
6057
+ data = new Uint8Array(src);
5174
6058
  } else {
5175
6059
  const match = /^data:(.*?);base64,(.*)$/.exec(src);
5176
6060
  if (match) {
5177
6061
  if (match[1]) {
5178
6062
  refBody.Subtype = escapeName(match[1]);
5179
6063
  }
5180
- data = Buffer.from(match[2], 'base64');
6064
+ data = fromBase64(match[2]);
5181
6065
  } else {
5182
6066
  data = fs.readFileSync(src);
5183
6067
  if (!data) {
@@ -5245,6 +6129,8 @@ function isEqual(a, b) {
5245
6129
  return a.Subtype === b.Subtype && a.Params.CheckSum.toString() === b.Params.CheckSum.toString() && a.Params.Size === b.Params.Size && a.Params.CreationDate.getTime() === b.Params.CreationDate.getTime() && (a.Params.ModDate === undefined && b.Params.ModDate === undefined || a.Params.ModDate.getTime() === b.Params.ModDate.getTime());
5246
6130
  }
5247
6131
 
6132
+ const ICC_PROFILE_PATH = new URL('./data/sRGB_IEC61966_2_1.icc', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('pdfkit.js', document.baseURI).href))).href;
6133
+ let iccProfile;
5248
6134
  var PDFA = {
5249
6135
  initPDFA(pSubset) {
5250
6136
  if (pSubset.charAt(pSubset.length - 3) === '-') {
@@ -5260,7 +6146,9 @@ var PDFA = {
5260
6146
  this._addColorOutputIntent();
5261
6147
  },
5262
6148
  _addColorOutputIntent() {
5263
- const iccProfile = fs.readFileSync(`${__dirname}/data/sRGB_IEC61966_2_1.icc`);
6149
+ if (!iccProfile) {
6150
+ iccProfile = fs.readFileSync(ICC_PROFILE_PATH);
6151
+ }
5264
6152
  const colorProfileRef = this.ref({
5265
6153
  Length: iccProfile.length,
5266
6154
  N: 3
@@ -5494,7 +6382,17 @@ function normalizeText(text) {
5494
6382
  function normalizeCell(cell, rowIndex, colIndex) {
5495
6383
  const colStyle = this._colStyle(colIndex);
5496
6384
  let rowStyle = this._rowStyle(rowIndex);
5497
- const font = deepMerge({}, colStyle.font, rowStyle.font, cell.font);
6385
+ const font = {};
6386
+ for (const level of [colStyle.font, rowStyle.font, cell.font]) {
6387
+ if (level == null) continue;
6388
+ if (level.src != null) {
6389
+ font.src = level.src;
6390
+ font.family = level.family;
6391
+ } else if (level.family != null) {
6392
+ font.family = level.family;
6393
+ }
6394
+ if (level.size != null) font.size = level.size;
6395
+ }
5498
6396
  const customFont = Object.values(font).filter(v => v != null).length > 0;
5499
6397
  const doc = this.document;
5500
6398
  const rollbackFont = doc._fontSource;
@@ -6072,14 +6970,14 @@ var MetadataMixin = {
6072
6970
  Subtype: 'XML'
6073
6971
  });
6074
6972
  this.metadataRef.compress = false;
6075
- this.metadataRef.write(Buffer.from(this.metadata.getXML(), 'utf-8'));
6973
+ this.metadataRef.write(new TextEncoder().encode(this.metadata.getXML()));
6076
6974
  this.metadataRef.end();
6077
6975
  this._root.data.Metadata = this.metadataRef;
6078
6976
  }
6079
6977
  }
6080
6978
  };
6081
6979
 
6082
- class PDFDocument extends stream.Readable {
6980
+ class PDFDocument extends Readable {
6083
6981
  constructor(options = {}) {
6084
6982
  super(options);
6085
6983
  this.options = options;
@@ -6164,15 +7062,17 @@ class PDFDocument extends stream.Readable {
6164
7062
  }
6165
7063
  }
6166
7064
  addPage(options) {
6167
- if (options == null) {
6168
- ({
6169
- options
6170
- } = this);
6171
- }
6172
- if (!this.options.bufferPages) {
7065
+ const documentOptions = this.options;
7066
+ if (!documentOptions.bufferPages) {
6173
7067
  this.flushPages();
6174
7068
  }
6175
- this.page = new PDFPage(this, options);
7069
+ const font = options?.font;
7070
+ if (font) {
7071
+ this.font(font, options.fontFamily);
7072
+ }
7073
+ const fontSize = options?.fontSize;
7074
+ if (fontSize) this.fontSize(fontSize);
7075
+ this.page = new PDFPage(this, options || documentOptions);
6176
7076
  this._pageBuffer.push(this.page);
6177
7077
  const pages = this._root.data.Pages.data;
6178
7078
  pages.Kids.push(this.page.dictionary);
@@ -6223,6 +7123,9 @@ class PDFDocument extends stream.Readable {
6223
7123
  this._root.data.Names.data.Dests.add(name, args);
6224
7124
  }
6225
7125
  addNamedEmbeddedFile(name, ref) {
7126
+ if (!ref) {
7127
+ throw new Error(`No ref specified for embedded file ${name}`);
7128
+ }
6226
7129
  if (!this._root.data.Names.data.EmbeddedFiles) {
6227
7130
  this._root.data.Names.data.EmbeddedFiles = new PDFNameTree({
6228
7131
  limits: false
@@ -6248,8 +7151,8 @@ class PDFDocument extends stream.Readable {
6248
7151
  }
6249
7152
  _read() {}
6250
7153
  _write(data) {
6251
- if (!Buffer.isBuffer(data)) {
6252
- data = Buffer.from(data + '\n', 'binary');
7154
+ if (!(data instanceof Uint8Array)) {
7155
+ data = fromBinaryString(data + '\n');
6253
7156
  }
6254
7157
  this.push(data);
6255
7158
  this._offset += data.length;
@@ -6351,5 +7254,23 @@ mixin(SubsetMixin);
6351
7254
  mixin(TableMixin);
6352
7255
  PDFDocument.LineWrapper = LineWrapper;
6353
7256
 
6354
- export { PDFDocument as default };
6355
- //# sourceMappingURL=pdfkit.es.js.map
7257
+ registerStdFontLoaders({
7258
+ Courier: () => require('#standard-fonts/Courier'),
7259
+ 'Courier-Bold': () => require('#standard-fonts/CourierBold'),
7260
+ 'Courier-BoldOblique': () => require('#standard-fonts/CourierBoldOblique'),
7261
+ 'Courier-Oblique': () => require('#standard-fonts/CourierOblique'),
7262
+ Helvetica: () => require('#standard-fonts/Helvetica'),
7263
+ 'Helvetica-Bold': () => require('#standard-fonts/HelveticaBold'),
7264
+ 'Helvetica-BoldOblique': () => require('#standard-fonts/HelveticaBoldOblique'),
7265
+ 'Helvetica-Oblique': () => require('#standard-fonts/HelveticaOblique'),
7266
+ Symbol: () => require('#standard-fonts/Symbol'),
7267
+ 'Times-Bold': () => require('#standard-fonts/TimesBold'),
7268
+ 'Times-BoldItalic': () => require('#standard-fonts/TimesBoldItalic'),
7269
+ 'Times-Italic': () => require('#standard-fonts/TimesItalic'),
7270
+ 'Times-Roman': () => require('#standard-fonts/TimesRoman'),
7271
+ ZapfDingbats: () => require('#standard-fonts/ZapfDingbats')
7272
+ });
7273
+ PDFDocument.registerFile = registerFile;
7274
+
7275
+ module.exports = PDFDocument;
7276
+ //# sourceMappingURL=pdfkit.js.map