pdfkit 0.20.1 → 0.21.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 (46) hide show
  1. package/README.md +35 -0
  2. package/js/pdfkit.browser.mjs +2418 -436
  3. package/js/pdfkit.browser.mjs.map +1 -1
  4. package/js/pdfkit.js +2460 -456
  5. package/js/pdfkit.js.map +1 -1
  6. package/js/pdfkit.node.mjs +2452 -452
  7. package/js/pdfkit.node.mjs.map +1 -1
  8. package/js/pdfkit.standalone.js +21578 -32704
  9. package/js/standard-fonts/Symbol.cjs +4 -3
  10. package/js/standard-fonts/Symbol.mjs +4 -3
  11. package/js/standard-fonts/ZapfDingbats.cjs +4 -3
  12. package/js/standard-fonts/ZapfDingbats.mjs +4 -3
  13. package/package.json +23 -23
  14. package/.yarn/install-state.gz +0 -0
  15. package/.yarn/releases/yarn-4.16.0.cjs +0 -944
  16. package/.yarnrc.yml +0 -10
  17. package/CHANGELOG.md +0 -192
  18. package/js/data/Courier-Bold.afm +0 -342
  19. package/js/data/Courier-BoldOblique.afm +0 -342
  20. package/js/data/Courier-Oblique.afm +0 -342
  21. package/js/data/Courier.afm +0 -342
  22. package/js/data/Helvetica-Bold.afm +0 -2827
  23. package/js/data/Helvetica-BoldOblique.afm +0 -2827
  24. package/js/data/Helvetica-Oblique.afm +0 -3051
  25. package/js/data/Helvetica.afm +0 -3051
  26. package/js/data/Symbol.afm +0 -213
  27. package/js/data/Times-Bold.afm +0 -2588
  28. package/js/data/Times-BoldItalic.afm +0 -2384
  29. package/js/data/Times-Italic.afm +0 -2667
  30. package/js/data/Times-Roman.afm +0 -2419
  31. package/js/data/ZapfDingbats.afm +0 -225
  32. package/js/pdfkit.browser.js +0 -7524
  33. package/js/pdfkit.browser.js.map +0 -1
  34. package/js/pdfkit.browser.old.js +0 -7517
  35. package/js/pdfkit.browser.old.mjs +0 -7342
  36. package/js/pdfkit.old.js +0 -7276
  37. package/jsconfig.json +0 -13
  38. package/rollup.config.mjs +0 -193
  39. package/tools/README.md +0 -124
  40. package/tools/afm-converter.js +0 -317
  41. package/tools/asset-plugin.mjs +0 -17
  42. package/tools/binary-plugin.mjs +0 -18
  43. package/tools/convert-afm-parsed.js +0 -8
  44. package/tools/convert-afm-runtime.js +0 -8
  45. package/types/jest.custom-matchers.d.ts +0 -28
  46. package/vitest.config.js +0 -13
@@ -1,15 +1,111 @@
1
1
  import { createRequire } from 'module';
2
2
  import stream from 'stream';
3
- import { bytesToHex, concatBytes } from '@noble/hashes/utils';
4
3
  import zlib$1 from 'zlib';
5
- import { cbc, ecb } from '@noble/ciphers/aes';
6
4
  import { statSync, readFileSync } from 'fs';
7
5
  import { create } from 'fontkit';
8
- import LineBreaker from 'linebreak';
6
+ import { LineBreaker } from 'linebreak';
9
7
  import PNG from 'png-js';
10
8
 
11
9
  var Readable = stream.Readable;
12
10
 
11
+ function isBytes$1(a) {
12
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array' && 'BYTES_PER_ELEMENT' in a && a.BYTES_PER_ELEMENT === 1;
13
+ }
14
+ const atitle$1 = title => title ? `"${title}" ` : '';
15
+ function abytes$1(value, length, title = '') {
16
+ if (isBytes$1(value) && (length === undefined)) return value;
17
+ const bytes = isBytes$1(value);
18
+ const ofLen = '';
19
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
20
+ const message = atitle$1(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
21
+ if (!bytes) throw new TypeError(message);
22
+ throw new RangeError(message);
23
+ }
24
+ const aobject = (value, label) => {
25
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);
26
+ };
27
+ const aopts = (value, label) => {
28
+ aobject(value, label);
29
+ const proto = Object.getPrototypeOf(value);
30
+ if (proto !== Object.prototype && proto !== null) throw new TypeError(`"${label}" expected plain object`);
31
+ if (Object.hasOwn(value, '__proto__')) throw new TypeError(`"${label}.__proto__" is not allowed`);
32
+ };
33
+ function aexists$1(instance, checkFinished = true) {
34
+ if (instance.destroyed) throw new Error('hash was destroyed');
35
+ if (checkFinished && instance.finished) throw new Error('digest() was already called');
36
+ }
37
+ function aoutput$1(out, instance) {
38
+ abytes$1(out, undefined, 'output');
39
+ const min = instance.outputLen;
40
+ if (!(out.length >= min)) {
41
+ throw new RangeError('"output" expected length >= ' + min);
42
+ }
43
+ }
44
+ function clean$1(...arrays) {
45
+ for (let i = 0; i < arrays.length; i++) {
46
+ arrays[i].fill(0);
47
+ }
48
+ }
49
+ function createView$1(arr) {
50
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
51
+ }
52
+ function rotr(word, shift) {
53
+ return word << 32 - shift | word >>> shift;
54
+ }
55
+ function rotl(word, shift) {
56
+ return word << shift | word >>> 32 - shift >>> 0;
57
+ }
58
+ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
59
+ const hasHexBuiltin = (() => typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
60
+ const hexes = Array.from({
61
+ length: 256
62
+ }, (_, i) => i.toString(16).padStart(2, '0'));
63
+ function bytesToHex(bytes) {
64
+ abytes$1(bytes);
65
+ if (hasHexBuiltin) return bytes.toHex();
66
+ let hex = '';
67
+ for (let i = 0; i < bytes.length; i++) {
68
+ hex += hexes[bytes[i]];
69
+ }
70
+ return hex;
71
+ }
72
+ function concatBytes$1(...arrays) {
73
+ let sum = 0;
74
+ for (let i = 0; i < arrays.length; i++) {
75
+ const a = arrays[i];
76
+ abytes$1(a);
77
+ sum += a.length;
78
+ }
79
+ const res = new Uint8Array(sum);
80
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
81
+ const a = arrays[i];
82
+ res.set(a, pad);
83
+ pad += a.length;
84
+ }
85
+ return res;
86
+ }
87
+ function checkOpts(defaults, opts, title = 'opts') {
88
+ aopts(defaults, 'defaults');
89
+ if (opts !== undefined) aopts(opts, title);
90
+ const merged = Object.assign(Object.create(null), defaults, opts);
91
+ return merged;
92
+ }
93
+ function createHasher(hashCons, info = {}) {
94
+ if (typeof hashCons !== 'function') throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
95
+ info = checkOpts({}, info, 'info');
96
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
97
+ const tmp = hashCons(undefined);
98
+ hashC.outputLen = tmp.outputLen;
99
+ hashC.blockLen = tmp.blockLen;
100
+ hashC.canXOF = tmp.canXOF;
101
+ hashC.create = opts => hashCons(opts);
102
+ Object.assign(hashC, info);
103
+ return Object.freeze(hashC);
104
+ }
105
+ const oidNist = suffix => ({
106
+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix])
107
+ });
108
+
13
109
  class PDFAbstractReference {
14
110
  toString() {
15
111
  throw new Error('Must be implemented by subclasses');
@@ -257,6 +353,12 @@ class PDFReference extends PDFAbstractReference {
257
353
  this.finalize();
258
354
  }
259
355
  finalize() {
356
+ const objectStreams = this.document._objectStreams;
357
+ if (objectStreams && !this.buffer.length) {
358
+ objectStreams.add(this);
359
+ this.document._refEnd(this);
360
+ return;
361
+ }
260
362
  this.offset = this.document._offset;
261
363
  const encryptFn = this.document._security ? this.document._security.getEncryptFn(this.id, this.gen) : null;
262
364
  if (this.buffer.length) {
@@ -365,7 +467,7 @@ const DEFAULT_MARGINS = {
365
467
  bottom: 72,
366
468
  right: 72
367
469
  };
368
- const SIZES = {
470
+ const PAGE_SIZES = {
369
471
  '4A0': [4767.87, 6740.79],
370
472
  '2A0': [3370.39, 4767.87],
371
473
  A0: [2383.94, 3370.39],
@@ -424,7 +526,7 @@ class PDFPage {
424
526
  this.size = options.size || 'letter';
425
527
  this.layout = options.layout || 'portrait';
426
528
  this.userUnit = options.userUnit || 1.0;
427
- const dimensions = Array.isArray(this.size) ? this.size : SIZES[this.size.toUpperCase()];
529
+ const dimensions = Array.isArray(this.size) ? this.size : PAGE_SIZES[this.size.toUpperCase()];
428
530
  this.width = dimensions[this.layout === 'portrait' ? 0 : 1];
429
531
  this.height = dimensions[this.layout === 'portrait' ? 1 : 0];
430
532
  this.content = this.document.ref();
@@ -501,7 +603,7 @@ class PDFPage {
501
603
 
502
604
  class PDFNameTree extends PDFTree {
503
605
  _compareKeys(a, b) {
504
- return a.localeCompare(b);
606
+ return a < b ? -1 : a > b ? 1 : 0;
505
607
  }
506
608
  _keysName() {
507
609
  return 'Names';
@@ -511,125 +613,119 @@ class PDFNameTree extends PDFTree {
511
613
  }
512
614
  }
513
615
 
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
- }
616
+ const U32_MASK64 = (() => BigInt(2 ** 32 - 1))();
617
+ const _32n = BigInt(32);
618
+ function fromBig(n, le = false) {
619
+ if (le) return {
620
+ h: Number(n & U32_MASK64),
621
+ l: Number(n >> _32n & U32_MASK64)
622
+ };
623
+ return {
624
+ h: Number(n >> _32n & U32_MASK64) | 0,
625
+ l: Number(n & U32_MASK64) | 0
626
+ };
531
627
  }
532
- function clean(...arrays) {
533
- for (let i = 0; i < arrays.length; i++) {
534
- arrays[i].fill(0);
628
+ function split(lst, le = false) {
629
+ const len = lst.length;
630
+ let Ah = new Uint32Array(len);
631
+ let Al = new Uint32Array(len);
632
+ for (let i = 0; i < len; i++) {
633
+ const {
634
+ h,
635
+ l
636
+ } = fromBig(lst[i], le);
637
+ [Ah[i], Al[i]] = [h, l];
535
638
  }
639
+ return [Ah, Al];
536
640
  }
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;
641
+ const fromNumH = n => n / 2 ** 32 | 0;
642
+ const fromNumL = n => n >>> 0;
643
+ function setU64FromNum(view, byteOffset, n, isLE) {
644
+ const h = fromNumH(n);
645
+ const l = fromNumL(n);
646
+ view.setUint32(byteOffset, isLE ? l : h, isLE);
647
+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
559
648
  }
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;
649
+ const shrSH = (h, _l, s) => h >>> s;
650
+ const shrSL = (h, l, s) => h << 32 - s | l >>> s;
651
+ const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
652
+ const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
653
+ const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
654
+ const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
655
+ function add(Ah, Al, Bh, Bl) {
656
+ const l = (Al >>> 0) + (Bl >>> 0);
657
+ return {
658
+ h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
659
+ l: l | 0
660
+ };
568
661
  }
662
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
663
+ const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
664
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
665
+ const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
666
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
667
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
569
668
 
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
669
  function Chi(a, b, c) {
582
670
  return a & b ^ ~a & c;
583
671
  }
584
672
  function Maj(a, b, c) {
585
673
  return a & b ^ a & c ^ b & c;
586
674
  }
587
- class HashMD extends Hash {
675
+ class HashMD {
676
+ blockLen;
677
+ outputLen;
678
+ canXOF = false;
679
+ padOffset;
680
+ isLE;
681
+ buffer;
682
+ view;
683
+ finished = false;
684
+ length = 0;
685
+ pos = 0;
686
+ destroyed = false;
588
687
  constructor(blockLen, outputLen, padOffset, isLE) {
589
- super();
590
- this.finished = false;
591
- this.length = 0;
592
- this.pos = 0;
593
- this.destroyed = false;
594
688
  this.blockLen = blockLen;
595
689
  this.outputLen = outputLen;
596
690
  this.padOffset = padOffset;
597
691
  this.isLE = isLE;
598
692
  this.buffer = new Uint8Array(blockLen);
599
- this.view = createView(this.buffer);
693
+ this.view = createView$1(this.buffer);
600
694
  }
601
695
  update(data) {
602
- aexists(this);
603
- data = toBytes(data);
604
- abytes(data);
696
+ aexists$1(this);
697
+ abytes$1(data);
605
698
  const {
606
699
  view,
607
700
  buffer,
608
701
  blockLen
609
702
  } = this;
610
703
  const len = data.length;
704
+ let processed = false;
611
705
  for (let pos = 0; pos < len;) {
612
706
  const take = Math.min(blockLen - this.pos, len - pos);
613
707
  if (take === blockLen) {
614
- const dataView = createView(data);
708
+ const dataView = createView$1(data);
615
709
  for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
710
+ processed = true;
616
711
  continue;
617
712
  }
618
- buffer.set(data.subarray(pos, pos + take), this.pos);
713
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
619
714
  this.pos += take;
620
715
  pos += take;
621
716
  if (this.pos === blockLen) {
622
717
  this.process(view, 0);
623
718
  this.pos = 0;
719
+ processed = true;
624
720
  }
625
721
  }
626
722
  this.length += data.length;
627
- this.roundClean();
723
+ if (processed) this.roundClean();
628
724
  return this;
629
725
  }
630
726
  digestInto(out) {
631
- aexists(this);
632
- aoutput(out, this);
727
+ aexists$1(this);
728
+ aoutput$1(out, this);
633
729
  this.finished = true;
634
730
  const {
635
731
  buffer,
@@ -641,20 +737,19 @@ class HashMD extends Hash {
641
737
  pos
642
738
  } = this;
643
739
  buffer[pos++] = 0b10000000;
644
- clean(this.buffer.subarray(pos));
740
+ buffer.fill(0, pos);
645
741
  if (this.padOffset > blockLen - pos) {
646
742
  this.process(view, 0);
647
- pos = 0;
743
+ buffer.fill(0);
648
744
  }
649
- for (let i = pos; i < blockLen; i++) buffer[i] = 0;
650
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
745
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
651
746
  this.process(view, 0);
652
- const oview = createView(out);
747
+ this.roundClean();
748
+ const oview = out === buffer ? view : createView$1(out);
653
749
  const len = this.outputLen;
654
- if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');
655
750
  const outLen = len / 4;
656
751
  const state = this.get();
657
- if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');
752
+ if (len % 4 || outLen > state.length) throw new Error('invalid outputLen');
658
753
  for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
659
754
  }
660
755
  digest() {
@@ -667,11 +762,8 @@ class HashMD extends Hash {
667
762
  this.destroy();
668
763
  return res;
669
764
  }
670
- _cloneInto(to) {
671
- to || (to = new this.constructor());
672
- to.set(...this.get());
765
+ _cloneIntoMeta(to) {
673
766
  const {
674
- blockLen,
675
767
  buffer,
676
768
  length,
677
769
  finished,
@@ -682,7 +774,7 @@ class HashMD extends Hash {
682
774
  to.finished = finished;
683
775
  to.length = length;
684
776
  to.pos = pos;
685
- if (length % blockLen) to.buffer.set(buffer);
777
+ if (pos) to.buffer.set(buffer);
686
778
  return to;
687
779
  }
688
780
  clone() {
@@ -696,14 +788,14 @@ const SHA512_IV = Uint32Array.from([0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa7
696
788
 
697
789
  const SHA1_IV = Uint32Array.from([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]);
698
790
  const SHA1_W = new Uint32Array(80);
699
- class SHA1 extends HashMD {
791
+ class _SHA1 extends HashMD {
792
+ A = SHA1_IV[0] | 0;
793
+ B = SHA1_IV[1] | 0;
794
+ C = SHA1_IV[2] | 0;
795
+ D = SHA1_IV[3] | 0;
796
+ E = SHA1_IV[4] | 0;
700
797
  constructor() {
701
798
  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
799
  }
708
800
  get() {
709
801
  const {
@@ -722,6 +814,10 @@ class SHA1 extends HashMD {
722
814
  this.D = D | 0;
723
815
  this.E = E | 0;
724
816
  }
817
+ _cloneInto(to) {
818
+ (to ||= new this.constructor()).set(...this.get());
819
+ return this._cloneIntoMeta(to);
820
+ }
725
821
  process(view, offset) {
726
822
  for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);
727
823
  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);
@@ -762,27 +858,34 @@ class SHA1 extends HashMD {
762
858
  this.set(A, B, C, D, E);
763
859
  }
764
860
  roundClean() {
765
- clean(SHA1_W);
861
+ clean$1(SHA1_W);
766
862
  }
767
863
  destroy() {
864
+ this.destroyed = true;
768
865
  this.set(0, 0, 0, 0, 0);
769
- clean(this.buffer);
866
+ clean$1(this.buffer);
770
867
  }
771
868
  }
772
- createHasher(() => new SHA1());
869
+ createHasher(() => new _SHA1());
773
870
  const p32 = Math.pow(2, 32);
774
871
  const K = Array.from({
775
872
  length: 64
776
873
  }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));
777
874
  const MD5_IV = SHA1_IV.slice(0, 4);
778
875
  const MD5_W = new Uint32Array(16);
779
- class MD5 extends HashMD {
876
+ const MD5_SHIFTS = (() => {
877
+ const S = [[7, 12, 17, 22], [5, 9, 14, 20], [4, 11, 16, 23], [6, 10, 15, 21]];
878
+ return Uint8Array.from({
879
+ length: 64
880
+ }, (_, i) => S[Math.floor(i / 16)][i % 4]);
881
+ })();
882
+ class _MD5 extends HashMD {
883
+ A = MD5_IV[0] | 0;
884
+ B = MD5_IV[1] | 0;
885
+ C = MD5_IV[2] | 0;
886
+ D = MD5_IV[3] | 0;
780
887
  constructor() {
781
888
  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
889
  }
787
890
  get() {
788
891
  const {
@@ -799,6 +902,10 @@ class MD5 extends HashMD {
799
902
  this.C = C | 0;
800
903
  this.D = D | 0;
801
904
  }
905
+ _cloneInto(to) {
906
+ (to ||= new this.constructor()).set(...this.get());
907
+ return this._cloneIntoMeta(to);
908
+ }
802
909
  process(view, offset) {
803
910
  for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);
804
911
  let {
@@ -808,29 +915,25 @@ class MD5 extends HashMD {
808
915
  D
809
916
  } = this;
810
917
  for (let i = 0; i < 64; i++) {
811
- let F, g, s;
918
+ let F, g;
812
919
  if (i < 16) {
813
920
  F = Chi(B, C, D);
814
921
  g = i;
815
- s = [7, 12, 17, 22];
816
922
  } else if (i < 32) {
817
923
  F = Chi(D, B, C);
818
924
  g = (5 * i + 1) % 16;
819
- s = [5, 9, 14, 20];
820
925
  } else if (i < 48) {
821
926
  F = B ^ C ^ D;
822
927
  g = (3 * i + 5) % 16;
823
- s = [4, 11, 16, 23];
824
928
  } else {
825
929
  F = C ^ (B | ~D);
826
930
  g = 7 * i % 16;
827
- s = [6, 10, 15, 21];
828
931
  }
829
932
  F = F + A + K[i] + MD5_W[g];
830
933
  A = D;
831
934
  D = C;
832
935
  C = B;
833
- B = B + rotl(F, s[i % 4]);
936
+ B = B + rotl(F, MD5_SHIFTS[i]);
834
937
  }
835
938
  A = A + this.A | 0;
836
939
  B = B + this.B | 0;
@@ -839,14 +942,15 @@ class MD5 extends HashMD {
839
942
  this.set(A, B, C, D);
840
943
  }
841
944
  roundClean() {
842
- clean(MD5_W);
945
+ clean$1(MD5_W);
843
946
  }
844
947
  destroy() {
948
+ this.destroyed = true;
845
949
  this.set(0, 0, 0, 0);
846
- clean(this.buffer);
950
+ clean$1(this.buffer);
847
951
  }
848
952
  }
849
- const md5 = createHasher(() => new MD5());
953
+ const md5 = createHasher(() => new _MD5());
850
954
  const Rho160 = Uint8Array.from([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);
851
955
  const Id160 = (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
852
956
  const Pi160 = (() => Id160.map(i => (9 * i + 5) % 16))();
@@ -872,14 +976,14 @@ function ripemd_f(group, x, y, z) {
872
976
  return x ^ (y | ~z);
873
977
  }
874
978
  const BUF_160 = new Uint32Array(16);
875
- class RIPEMD160 extends HashMD {
979
+ class _RIPEMD160 extends HashMD {
980
+ h0 = 0x67452301 | 0;
981
+ h1 = 0xefcdab89 | 0;
982
+ h2 = 0x98badcfe | 0;
983
+ h3 = 0x10325476 | 0;
984
+ h4 = 0xc3d2e1f0 | 0;
876
985
  constructor() {
877
986
  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
987
  }
884
988
  get() {
885
989
  const {
@@ -898,6 +1002,10 @@ class RIPEMD160 extends HashMD {
898
1002
  this.h3 = h3 | 0;
899
1003
  this.h4 = h4 | 0;
900
1004
  }
1005
+ _cloneInto(to) {
1006
+ (to ||= new this.constructor()).set(...this.get());
1007
+ return this._cloneIntoMeta(to);
1008
+ }
901
1009
  process(view, offset) {
902
1010
  for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);
903
1011
  let al = this.h0 | 0,
@@ -930,15 +1038,15 @@ class RIPEMD160 extends HashMD {
930
1038
  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
1039
  }
932
1040
  roundClean() {
933
- clean(BUF_160);
1041
+ clean$1(BUF_160);
934
1042
  }
935
1043
  destroy() {
936
1044
  this.destroyed = true;
937
- clean(this.buffer);
1045
+ clean$1(this.buffer);
938
1046
  this.set(0, 0, 0, 0, 0);
939
1047
  }
940
1048
  }
941
- createHasher(() => new RIPEMD160());
1049
+ createHasher(() => new _RIPEMD160());
942
1050
 
943
1051
  function md5Hash(data) {
944
1052
  return md5.create().update(data).digest();
@@ -947,64 +1055,27 @@ function md5Hex(data) {
947
1055
  return bytesToHex(md5Hash(data));
948
1056
  }
949
1057
 
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
1058
  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
1059
  const SHA256_W = new Uint32Array(64);
997
- class SHA256 extends HashMD {
998
- constructor(outputLen = 32) {
1060
+ class SHA2_32B extends HashMD {
1061
+ A = 0;
1062
+ B = 0;
1063
+ C = 0;
1064
+ D = 0;
1065
+ E = 0;
1066
+ F = 0;
1067
+ G = 0;
1068
+ H = 0;
1069
+ constructor(outputLen, IV) {
999
1070
  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;
1071
+ this.A = IV[0] | 0;
1072
+ this.B = IV[1] | 0;
1073
+ this.C = IV[2] | 0;
1074
+ this.D = IV[3] | 0;
1075
+ this.E = IV[4] | 0;
1076
+ this.F = IV[5] | 0;
1077
+ this.G = IV[6] | 0;
1078
+ this.H = IV[7] | 0;
1008
1079
  }
1009
1080
  get() {
1010
1081
  const {
@@ -1029,6 +1100,10 @@ class SHA256 extends HashMD {
1029
1100
  this.G = G | 0;
1030
1101
  this.H = H | 0;
1031
1102
  }
1103
+ _cloneInto(to) {
1104
+ (to ||= new this.constructor()).set(...this.get());
1105
+ return this._cloneIntoMeta(to);
1106
+ }
1032
1107
  process(view, offset) {
1033
1108
  for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
1034
1109
  for (let i = 16; i < 64; i++) {
@@ -1073,24 +1148,22 @@ class SHA256 extends HashMD {
1073
1148
  this.set(A, B, C, D, E, F, G, H);
1074
1149
  }
1075
1150
  roundClean() {
1076
- clean(SHA256_W);
1151
+ clean$1(SHA256_W);
1077
1152
  }
1078
1153
  destroy() {
1154
+ this.destroyed = true;
1079
1155
  this.set(0, 0, 0, 0, 0, 0, 0, 0);
1080
- clean(this.buffer);
1156
+ clean$1(this.buffer);
1081
1157
  }
1082
1158
  }
1083
- class SHA224 extends SHA256 {
1159
+ class _SHA256 extends SHA2_32B {
1084
1160
  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;
1161
+ super(32, SHA256_IV);
1162
+ }
1163
+ }
1164
+ class _SHA224 extends SHA2_32B {
1165
+ constructor() {
1166
+ super(28, SHA224_IV);
1094
1167
  }
1095
1168
  }
1096
1169
  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))))();
@@ -1098,25 +1171,41 @@ const SHA512_Kh = (() => K512[0])();
1098
1171
  const SHA512_Kl = (() => K512[1])();
1099
1172
  const SHA512_W_H = new Uint32Array(80);
1100
1173
  const SHA512_W_L = new Uint32Array(80);
1101
- class SHA512 extends HashMD {
1102
- constructor(outputLen = 64) {
1174
+ class SHA2_64B extends HashMD {
1175
+ Ah = 0;
1176
+ Al = 0;
1177
+ Bh = 0;
1178
+ Bl = 0;
1179
+ Ch = 0;
1180
+ Cl = 0;
1181
+ Dh = 0;
1182
+ Dl = 0;
1183
+ Eh = 0;
1184
+ El = 0;
1185
+ Fh = 0;
1186
+ Fl = 0;
1187
+ Gh = 0;
1188
+ Gl = 0;
1189
+ Hh = 0;
1190
+ Hl = 0;
1191
+ constructor(outputLen, IV) {
1103
1192
  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;
1193
+ this.Ah = IV[0] | 0;
1194
+ this.Al = IV[1] | 0;
1195
+ this.Bh = IV[2] | 0;
1196
+ this.Bl = IV[3] | 0;
1197
+ this.Ch = IV[4] | 0;
1198
+ this.Cl = IV[5] | 0;
1199
+ this.Dh = IV[6] | 0;
1200
+ this.Dl = IV[7] | 0;
1201
+ this.Eh = IV[8] | 0;
1202
+ this.El = IV[9] | 0;
1203
+ this.Fh = IV[10] | 0;
1204
+ this.Fl = IV[11] | 0;
1205
+ this.Gh = IV[12] | 0;
1206
+ this.Gl = IV[13] | 0;
1207
+ this.Hh = IV[14] | 0;
1208
+ this.Hl = IV[15] | 0;
1120
1209
  }
1121
1210
  get() {
1122
1211
  const {
@@ -1157,6 +1246,10 @@ class SHA512 extends HashMD {
1157
1246
  this.Hh = Hh | 0;
1158
1247
  this.Hl = Hl | 0;
1159
1248
  }
1249
+ _cloneInto(to) {
1250
+ (to ||= new this.constructor()).set(...this.get());
1251
+ return this._cloneIntoMeta(to);
1252
+ }
1160
1253
  process(view, offset) {
1161
1254
  for (let i = 0; i < 16; i++, offset += 4) {
1162
1255
  SHA512_W_H[i] = view.getUint32(offset);
@@ -1260,89 +1353,1569 @@ class SHA512 extends HashMD {
1260
1353
  } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1261
1354
  this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1262
1355
  }
1263
- roundClean() {
1264
- clean(SHA512_W_H, SHA512_W_L);
1356
+ roundClean() {
1357
+ clean$1(SHA512_W_H, SHA512_W_L);
1358
+ }
1359
+ destroy() {
1360
+ this.destroyed = true;
1361
+ clean$1(this.buffer);
1362
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1363
+ }
1364
+ }
1365
+ class _SHA512 extends SHA2_64B {
1366
+ constructor() {
1367
+ super(64, SHA512_IV);
1368
+ }
1369
+ }
1370
+ class _SHA384 extends SHA2_64B {
1371
+ constructor() {
1372
+ super(48, SHA384_IV);
1373
+ }
1374
+ }
1375
+ const T224_IV = Uint32Array.from([0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf, 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1]);
1376
+ const T256_IV = Uint32Array.from([0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd, 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2]);
1377
+ class _SHA512_224 extends SHA2_64B {
1378
+ constructor() {
1379
+ super(28, T224_IV);
1380
+ }
1381
+ }
1382
+ class _SHA512_256 extends SHA2_64B {
1383
+ constructor() {
1384
+ super(32, T256_IV);
1385
+ }
1386
+ }
1387
+ const sha256 = createHasher(() => new _SHA256(), oidNist(0x01));
1388
+ createHasher(() => new _SHA224(), oidNist(0x04));
1389
+ createHasher(() => new _SHA512(), oidNist(0x03));
1390
+ createHasher(() => new _SHA384(), oidNist(0x02));
1391
+ createHasher(() => new _SHA512_256(), oidNist(0x06));
1392
+ createHasher(() => new _SHA512_224(), oidNist(0x05));
1393
+
1394
+ function sha256Hash(data) {
1395
+ return sha256(data);
1396
+ }
1397
+
1398
+ function isBytes(a) {
1399
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array' && 'BYTES_PER_ELEMENT' in a && a.BYTES_PER_ELEMENT === 1;
1400
+ }
1401
+ const atitle = title => title ? `"${title}" ` : '';
1402
+ function abool(value, title = '') {
1403
+ if (typeof value !== 'boolean') throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);
1404
+ return value;
1405
+ }
1406
+ function anumber(n, title = '') {
1407
+ if (typeof n !== 'number') throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);
1408
+ if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);
1409
+ return n;
1410
+ }
1411
+ function abytes(value, length, title = '') {
1412
+ if (isBytes(value) && (length === undefined || value.length === length)) return value;
1413
+ if (length !== undefined) anumber(length, 'length');
1414
+ const bytes = isBytes(value);
1415
+ const ofLen = length !== undefined ? ` of length ${length}` : '';
1416
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
1417
+ const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
1418
+ if (!bytes) throw new TypeError(message);
1419
+ throw new RangeError(message);
1420
+ }
1421
+ function aexists(instance, checkFinished = true) {
1422
+ if (instance.destroyed) throw new Error('hash was destroyed');
1423
+ if (checkFinished && instance.finished) throw new Error('digest() was already called');
1424
+ }
1425
+ function aoutput(out, instance) {
1426
+ abytes(out, undefined, 'output');
1427
+ const min = instance.outputLen;
1428
+ if (!(out.length >= min)) {
1429
+ throw new RangeError('"output" expected length >= ' + min);
1430
+ }
1431
+ }
1432
+ function aoutput32(out, instance) {
1433
+ aoutput(out, instance);
1434
+ if (!isAligned32(out)) throw new Error('invalid output, must be aligned');
1435
+ }
1436
+ function u8(arr) {
1437
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
1438
+ }
1439
+ function u32(arr) {
1440
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
1441
+ }
1442
+ function clean(...arrays) {
1443
+ for (let i = 0; i < arrays.length; i++) {
1444
+ arrays[i].fill(0);
1445
+ }
1446
+ }
1447
+ function createView(arr) {
1448
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1449
+ }
1450
+ const isLE = (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
1451
+ function byteSwap(word) {
1452
+ return word << 24 & 0xff000000 | word << 8 & 0xff0000 | word >>> 8 & 0xff00 | word >>> 24 & 0xff;
1453
+ }
1454
+ const swap8IfBE = isLE ? n => n : n => byteSwap(n) >>> 0;
1455
+ function byteSwap32(arr) {
1456
+ for (let i = 0; i < arr.length; i++) {
1457
+ arr[i] = byteSwap(arr[i]);
1458
+ }
1459
+ return arr;
1460
+ }
1461
+ const swap32IfBE = isLE ? u => u : byteSwap32;
1462
+ (() => typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
1463
+ Array.from({
1464
+ length: 256
1465
+ }, (_, i) => i.toString(16).padStart(2, '0'));
1466
+ BigInt(0);
1467
+ function overlapBytes(a, b) {
1468
+ if (!a.byteLength || !b.byteLength) return false;
1469
+ return a.buffer === b.buffer && a.byteOffset < b.byteOffset + b.byteLength && b.byteOffset < a.byteOffset + a.byteLength;
1470
+ }
1471
+ function complexOverlapBytes(input, output) {
1472
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset) throw new Error('complex overlap of input and output is not supported');
1473
+ }
1474
+ function concatBytes(...arrays) {
1475
+ let sum = 0;
1476
+ for (let i = 0; i < arrays.length; i++) {
1477
+ const a = arrays[i];
1478
+ abytes(a);
1479
+ sum += a.length;
1480
+ }
1481
+ const res = new Uint8Array(sum);
1482
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
1483
+ const a = arrays[i];
1484
+ res.set(a, pad);
1485
+ pad += a.length;
1486
+ }
1487
+ return res;
1488
+ }
1489
+ function equalBytes(a, b) {
1490
+ a = abytes(a);
1491
+ b = abytes(b);
1492
+ if (a.length !== b.length) return false;
1493
+ let diff = 0;
1494
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
1495
+ return diff === 0;
1496
+ }
1497
+ function wrapMacConstructor(keyLen, macCons, fromMsg) {
1498
+ const mac = macCons;
1499
+ const getArgs = fromMsg || (() => []);
1500
+ const macC = (msg, key) => mac(key, ...getArgs(msg)).update(msg).digest();
1501
+ const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
1502
+ macC.outputLen = tmp.outputLen;
1503
+ macC.blockLen = tmp.blockLen;
1504
+ macC.create = (key, ...args) => mac(key, ...args);
1505
+ return macC;
1506
+ }
1507
+ const wrapCipher = (params, constructor) => {
1508
+ function wrappedCipher(key, ...args) {
1509
+ abytes(key, undefined, 'key');
1510
+ if (params.nonceLength !== undefined) {
1511
+ const nonce = args[0];
1512
+ abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');
1513
+ }
1514
+ const tagl = params.tagLength;
1515
+ const aadStart = params.nonceLength !== undefined ? 1 : 0;
1516
+ if (!params.withAAD) {
1517
+ for (let i = aadStart; i < args.length; i++) if (isBytes(args[i])) throw new Error('AAD not supported');
1518
+ }
1519
+ if (params.withAAD && args[aadStart] !== undefined) abytes(args[aadStart], undefined, 'AAD');
1520
+ const cipher = constructor(key, ...args);
1521
+ const checkOutput = (fnLength, output) => {
1522
+ if (output !== undefined) {
1523
+ if (fnLength !== 2) throw new Error('cipher output not supported');
1524
+ abytes(output, undefined, 'output');
1525
+ }
1526
+ };
1527
+ let called = false;
1528
+ const wrCipher = {
1529
+ encrypt(data, output) {
1530
+ if (called) throw new Error('cannot encrypt() twice with same key + nonce');
1531
+ called = true;
1532
+ abytes(data, undefined, 'data');
1533
+ checkOutput(cipher.encrypt.length, output);
1534
+ return cipher.encrypt(data, output);
1535
+ },
1536
+ decrypt(data, output) {
1537
+ abytes(data, undefined, 'data');
1538
+ if (tagl && data.length < tagl) throw new Error('"ciphertext" expected length >= tagLength=' + tagl);
1539
+ checkOutput(cipher.decrypt.length, output);
1540
+ return cipher.decrypt(data, output);
1541
+ }
1542
+ };
1543
+ return wrCipher;
1544
+ }
1545
+ Object.assign(wrappedCipher, params);
1546
+ return wrappedCipher;
1547
+ };
1548
+ function getOutput(expectedLength, out, onlyAligned = true) {
1549
+ if (out === undefined) return new Uint8Array(expectedLength);
1550
+ abytes(out, expectedLength, 'output');
1551
+ if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');
1552
+ return out;
1553
+ }
1554
+ function u64Lengths(dataLength, aadLength, isLE) {
1555
+ anumber(dataLength);
1556
+ anumber(aadLength);
1557
+ abool(isLE);
1558
+ const num = new Uint8Array(16);
1559
+ const view = createView(num);
1560
+ view.setBigUint64(0, BigInt(aadLength), isLE);
1561
+ view.setBigUint64(8, BigInt(dataLength), isLE);
1562
+ return num;
1563
+ }
1564
+ function isAligned32(bytes) {
1565
+ return bytes.byteOffset % 4 === 0;
1566
+ }
1567
+ function copyBytes(bytes) {
1568
+ return Uint8Array.from(abytes(bytes));
1569
+ }
1570
+
1571
+ const BLOCK_SIZE$1 = 16;
1572
+ const ZEROS16 = new Uint8Array(16);
1573
+ const ZEROS32 = u32(ZEROS16);
1574
+ const POLY$1 = 0xe1;
1575
+ const mul2$1 = (s0, s1, s2, s3) => {
1576
+ const hiBit = s3 & 1;
1577
+ return {
1578
+ s3: s2 << 31 | s3 >>> 1,
1579
+ s2: s1 << 31 | s2 >>> 1,
1580
+ s1: s0 << 31 | s1 >>> 1,
1581
+ s0: s0 >>> 1 ^ POLY$1 << 24 & -(hiBit & 1)
1582
+ };
1583
+ };
1584
+ const swapLE = n => (n >>> 0 & 0xff) << 24 | (n >>> 8 & 0xff) << 16 | (n >>> 16 & 0xff) << 8 | n >>> 24 & 0xff | 0;
1585
+ const swap8IfLE = n => swap8IfBE(swapLE(n));
1586
+ function _toGHASHKey(k) {
1587
+ k.reverse();
1588
+ const hiBit = k[15] & 1;
1589
+ let carry = 0;
1590
+ for (let i = 0; i < k.length; i++) {
1591
+ const t = k[i];
1592
+ k[i] = t >>> 1 | carry;
1593
+ carry = (t & 1) << 7;
1594
+ }
1595
+ k[0] ^= -hiBit & 0xe1;
1596
+ return k;
1597
+ }
1598
+ const estimateWindow = bytes => {
1599
+ if (bytes > 64 * 1024) return 8;
1600
+ if (bytes > 1024) return 4;
1601
+ return 2;
1602
+ };
1603
+ class GHASH {
1604
+ blockLen = BLOCK_SIZE$1;
1605
+ outputLen = BLOCK_SIZE$1;
1606
+ s0 = 0;
1607
+ s1 = 0;
1608
+ s2 = 0;
1609
+ s3 = 0;
1610
+ finished = false;
1611
+ destroyed = false;
1612
+ t;
1613
+ W;
1614
+ windowSize;
1615
+ constructor(key, expectedLength) {
1616
+ abytes(key, 16, 'key');
1617
+ key = copyBytes(key);
1618
+ const kView = createView(key);
1619
+ let k0 = kView.getUint32(0, false);
1620
+ let k1 = kView.getUint32(4, false);
1621
+ let k2 = kView.getUint32(8, false);
1622
+ let k3 = kView.getUint32(12, false);
1623
+ const doubles = [];
1624
+ for (let i = 0; i < 128; i++) {
1625
+ doubles.push({
1626
+ s0: swapLE(k0),
1627
+ s1: swapLE(k1),
1628
+ s2: swapLE(k2),
1629
+ s3: swapLE(k3)
1630
+ });
1631
+ ({
1632
+ s0: k0,
1633
+ s1: k1,
1634
+ s2: k2,
1635
+ s3: k3
1636
+ } = mul2$1(k0, k1, k2, k3));
1637
+ }
1638
+ const W = estimateWindow(expectedLength || 1024);
1639
+ if (![1, 2, 4, 8].includes(W)) throw new Error('ghash: invalid window size, expected 2, 4 or 8');
1640
+ this.W = W;
1641
+ const bits = 128;
1642
+ const windows = bits / W;
1643
+ const windowSize = this.windowSize = 2 ** W;
1644
+ const items = [];
1645
+ for (let w = 0; w < windows; w++) {
1646
+ for (let byte = 0; byte < windowSize; byte++) {
1647
+ let s0 = 0,
1648
+ s1 = 0,
1649
+ s2 = 0,
1650
+ s3 = 0;
1651
+ for (let j = 0; j < W; j++) {
1652
+ const bit = byte >>> W - j - 1 & 1;
1653
+ if (!bit) continue;
1654
+ const {
1655
+ s0: d0,
1656
+ s1: d1,
1657
+ s2: d2,
1658
+ s3: d3
1659
+ } = doubles[W * w + j];
1660
+ s0 ^= d0, s1 ^= d1, s2 ^= d2, s3 ^= d3;
1661
+ }
1662
+ items.push({
1663
+ s0,
1664
+ s1,
1665
+ s2,
1666
+ s3
1667
+ });
1668
+ }
1669
+ }
1670
+ this.t = items;
1671
+ }
1672
+ _updateBlock(s0, s1, s2, s3) {
1673
+ s0 ^= this.s0, s1 ^= this.s1, s2 ^= this.s2, s3 ^= this.s3;
1674
+ const {
1675
+ W,
1676
+ t,
1677
+ windowSize
1678
+ } = this;
1679
+ let o0 = 0,
1680
+ o1 = 0,
1681
+ o2 = 0,
1682
+ o3 = 0;
1683
+ const mask = (1 << W) - 1;
1684
+ let w = 0;
1685
+ for (const num of [s0, s1, s2, s3]) {
1686
+ for (let bytePos = 0; bytePos < 4; bytePos++) {
1687
+ const byte = num >>> 8 * bytePos & 0xff;
1688
+ for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
1689
+ const bit = byte >>> W * bitPos & mask;
1690
+ const {
1691
+ s0: e0,
1692
+ s1: e1,
1693
+ s2: e2,
1694
+ s3: e3
1695
+ } = t[w * windowSize + bit];
1696
+ o0 ^= e0, o1 ^= e1, o2 ^= e2, o3 ^= e3;
1697
+ w += 1;
1698
+ }
1699
+ }
1700
+ }
1701
+ this.s0 = o0;
1702
+ this.s1 = o1;
1703
+ this.s2 = o2;
1704
+ this.s3 = o3;
1705
+ }
1706
+ update(data) {
1707
+ aexists(this);
1708
+ abytes(data);
1709
+ data = copyBytes(data);
1710
+ const b32 = u32(data);
1711
+ const blocks = Math.floor(data.length / BLOCK_SIZE$1);
1712
+ const left = data.length % BLOCK_SIZE$1;
1713
+ for (let i = 0; i < blocks; i++) {
1714
+ this._updateBlock(swap8IfBE(b32[i * 4 + 0]), swap8IfBE(b32[i * 4 + 1]), swap8IfBE(b32[i * 4 + 2]), swap8IfBE(b32[i * 4 + 3]));
1715
+ }
1716
+ if (left) {
1717
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1));
1718
+ this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3]));
1719
+ clean(ZEROS32);
1720
+ }
1721
+ return this;
1722
+ }
1723
+ destroy() {
1724
+ this.destroyed = true;
1725
+ const {
1726
+ t
1727
+ } = this;
1728
+ for (const elm of t) {
1729
+ elm.s0 = 0, elm.s1 = 0, elm.s2 = 0, elm.s3 = 0;
1730
+ }
1731
+ }
1732
+ digestInto(out) {
1733
+ aexists(this);
1734
+ aoutput32(out, this);
1735
+ this.finished = true;
1736
+ const {
1737
+ s0,
1738
+ s1,
1739
+ s2,
1740
+ s3
1741
+ } = this;
1742
+ const o32 = u32(out);
1743
+ o32[0] = s0;
1744
+ o32[1] = s1;
1745
+ o32[2] = s2;
1746
+ o32[3] = s3;
1747
+ if (!isLE) swap32IfBE(o32.subarray(0, BLOCK_SIZE$1 / 4));
1748
+ }
1749
+ digest() {
1750
+ const res = new Uint8Array(BLOCK_SIZE$1);
1751
+ this.digestInto(res);
1752
+ this.destroy();
1753
+ return res;
1754
+ }
1755
+ }
1756
+ class Polyval extends GHASH {
1757
+ constructor(key, expectedLength) {
1758
+ abytes(key);
1759
+ const ghKey = _toGHASHKey(copyBytes(key));
1760
+ super(ghKey, expectedLength);
1761
+ clean(ghKey);
1762
+ }
1763
+ update(data) {
1764
+ aexists(this);
1765
+ abytes(data);
1766
+ data = copyBytes(data);
1767
+ const b32 = u32(data);
1768
+ const left = data.length % BLOCK_SIZE$1;
1769
+ const blocks = Math.floor(data.length / BLOCK_SIZE$1);
1770
+ for (let i = 0; i < blocks; i++) {
1771
+ this._updateBlock(swap8IfLE(b32[i * 4 + 3]), swap8IfLE(b32[i * 4 + 2]), swap8IfLE(b32[i * 4 + 1]), swap8IfLE(b32[i * 4 + 0]));
1772
+ }
1773
+ if (left) {
1774
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE$1));
1775
+ this._updateBlock(swap8IfLE(ZEROS32[3]), swap8IfLE(ZEROS32[2]), swap8IfLE(ZEROS32[1]), swap8IfLE(ZEROS32[0]));
1776
+ clean(ZEROS32);
1777
+ }
1778
+ return this;
1779
+ }
1780
+ digestInto(out) {
1781
+ aexists(this);
1782
+ aoutput32(out, this);
1783
+ this.finished = true;
1784
+ const view = out.subarray(0, this.outputLen);
1785
+ const {
1786
+ s0,
1787
+ s1,
1788
+ s2,
1789
+ s3
1790
+ } = this;
1791
+ const o32 = u32(view);
1792
+ o32[0] = s0;
1793
+ o32[1] = s1;
1794
+ o32[2] = s2;
1795
+ o32[3] = s3;
1796
+ swap32IfBE(o32);
1797
+ view.reverse();
1798
+ }
1799
+ }
1800
+ const ghash = wrapMacConstructor(16, (key, expectedLength) => new GHASH(key, expectedLength), msg => [msg.length]);
1801
+ const polyval = wrapMacConstructor(16, (key, expectedLength) => new Polyval(key, expectedLength), msg => [msg.length]);
1802
+
1803
+ const BLOCK_SIZE = 16;
1804
+ const BLOCK_SIZE32 = 4;
1805
+ const EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);
1806
+ const ONE_BLOCK = Uint8Array.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]);
1807
+ const POLY = 0x11b;
1808
+ function validateKeyLength(key) {
1809
+ if (![16, 24, 32].includes(key.length)) throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length=' + key.length);
1810
+ }
1811
+ function mul2(n) {
1812
+ return n << 1 ^ POLY & -(n >> 7);
1813
+ }
1814
+ function mul(a, b) {
1815
+ let res = 0;
1816
+ for (; b > 0; b >>= 1) {
1817
+ res ^= a & -(b & 1);
1818
+ a = mul2(a);
1819
+ }
1820
+ return res;
1821
+ }
1822
+ const sbox = (() => {
1823
+ const t = new Uint8Array(256);
1824
+ for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x;
1825
+ const box = new Uint8Array(256);
1826
+ box[0] = 0x63;
1827
+ for (let i = 0; i < 255; i++) {
1828
+ let x = t[255 - i];
1829
+ x |= x << 8;
1830
+ box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 0x63) & 0xff;
1831
+ }
1832
+ clean(t);
1833
+ return box;
1834
+ })();
1835
+ const invSbox = sbox.map((_, j) => sbox.indexOf(j));
1836
+ const rotr32_8 = n => n << 24 | n >>> 8;
1837
+ const rotl32_8 = n => n << 8 | n >>> 24;
1838
+ function genTtable(sbox, fn) {
1839
+ if (sbox.length !== 256) throw new Error('wrong sbox length');
1840
+ const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));
1841
+ const T1 = T0.map(rotl32_8);
1842
+ const T2 = T1.map(rotl32_8);
1843
+ const T3 = T2.map(rotl32_8);
1844
+ const T01 = new Uint32Array(256 * 256);
1845
+ const T23 = new Uint32Array(256 * 256);
1846
+ const sbox2 = new Uint16Array(256 * 256);
1847
+ for (let i = 0; i < 256; i++) {
1848
+ for (let j = 0; j < 256; j++) {
1849
+ const idx = i * 256 + j;
1850
+ T01[idx] = T0[i] ^ T1[j];
1851
+ T23[idx] = T2[i] ^ T3[j];
1852
+ sbox2[idx] = sbox[i] << 8 | sbox[j];
1853
+ }
1854
+ }
1855
+ return {
1856
+ sbox,
1857
+ sbox2,
1858
+ T0,
1859
+ T1,
1860
+ T2,
1861
+ T3,
1862
+ T01,
1863
+ T23
1864
+ };
1865
+ }
1866
+ const tableEncoding = genTtable(sbox, s => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
1867
+ const tableDecoding = genTtable(invSbox, s => mul(s, 11) << 24 | mul(s, 13) << 16 | mul(s, 9) << 8 | mul(s, 14));
1868
+ const xPowers = (() => {
1869
+ const p = new Uint8Array(16);
1870
+ for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) p[i] = x;
1871
+ return p;
1872
+ })();
1873
+ function expandKeyLE(key) {
1874
+ abytes(key);
1875
+ const len = key.length;
1876
+ validateKeyLength(key);
1877
+ const {
1878
+ sbox2
1879
+ } = tableEncoding;
1880
+ const toClean = [];
1881
+ if (!isLE || !isAligned32(key)) toClean.push(key = copyBytes(key));
1882
+ const k32 = swap32IfBE(u32(key));
1883
+ const Nk = k32.length;
1884
+ const subByte = n => applySbox(sbox2, n, n, n, n);
1885
+ const xk = new Uint32Array(len + 28);
1886
+ xk.set(k32);
1887
+ for (let i = Nk; i < xk.length; i++) {
1888
+ let t = xk[i - 1];
1889
+ if (i % Nk === 0) t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];else if (Nk > 6 && i % Nk === 4) t = subByte(t);
1890
+ xk[i] = xk[i - Nk] ^ t;
1891
+ }
1892
+ clean(...toClean);
1893
+ return xk;
1894
+ }
1895
+ function expandKeyDecLE(key) {
1896
+ const encKey = expandKeyLE(key);
1897
+ const xk = encKey.slice();
1898
+ const Nk = encKey.length;
1899
+ const {
1900
+ sbox2
1901
+ } = tableEncoding;
1902
+ const {
1903
+ T0,
1904
+ T1,
1905
+ T2,
1906
+ T3
1907
+ } = tableDecoding;
1908
+ for (let i = 0; i < Nk; i += 4) {
1909
+ for (let j = 0; j < 4; j++) xk[i + j] = encKey[Nk - i - 4 + j];
1910
+ }
1911
+ clean(encKey);
1912
+ for (let i = 4; i < Nk - 4; i++) {
1913
+ const x = xk[i];
1914
+ const w = applySbox(sbox2, x, x, x, x);
1915
+ xk[i] = T0[w & 0xff] ^ T1[w >>> 8 & 0xff] ^ T2[w >>> 16 & 0xff] ^ T3[w >>> 24];
1916
+ }
1917
+ return xk;
1918
+ }
1919
+ function apply0123(T01, T23, s0, s1, s2, s3) {
1920
+ return T01[s0 << 8 & 0xff00 | s1 >>> 8 & 0xff] ^ T23[s2 >>> 8 & 0xff00 | s3 >>> 24 & 0xff];
1921
+ }
1922
+ function applySbox(sbox2, s0, s1, s2, s3) {
1923
+ return sbox2[s0 & 0xff | s1 & 0xff00] | sbox2[s2 >>> 16 & 0xff | s3 >>> 16 & 0xff00] << 16;
1924
+ }
1925
+ function encrypt(xk, s0, s1, s2, s3) {
1926
+ const {
1927
+ sbox2,
1928
+ T01,
1929
+ T23
1930
+ } = tableEncoding;
1931
+ let k = 0;
1932
+ s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
1933
+ const rounds = xk.length / 4 - 2;
1934
+ for (let i = 0; i < rounds; i++) {
1935
+ const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
1936
+ const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
1937
+ const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
1938
+ const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
1939
+ s0 = t0, s1 = t1, s2 = t2, s3 = t3;
1940
+ }
1941
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
1942
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
1943
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
1944
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
1945
+ return {
1946
+ s0: t0,
1947
+ s1: t1,
1948
+ s2: t2,
1949
+ s3: t3
1950
+ };
1951
+ }
1952
+ function decrypt(xk, s0, s1, s2, s3) {
1953
+ const {
1954
+ sbox2,
1955
+ T01,
1956
+ T23
1957
+ } = tableDecoding;
1958
+ let k = 0;
1959
+ s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
1960
+ const rounds = xk.length / 4 - 2;
1961
+ for (let i = 0; i < rounds; i++) {
1962
+ const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
1963
+ const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
1964
+ const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
1965
+ const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
1966
+ s0 = t0, s1 = t1, s2 = t2, s3 = t3;
1967
+ }
1968
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
1969
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
1970
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
1971
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
1972
+ return {
1973
+ s0: t0,
1974
+ s1: t1,
1975
+ s2: t2,
1976
+ s3: t3
1977
+ };
1978
+ }
1979
+ function ctrCounter(xk, nonce, src, dst) {
1980
+ abytes(nonce, BLOCK_SIZE, 'nonce');
1981
+ abytes(src);
1982
+ const srcLen = src.length;
1983
+ dst = getOutput(srcLen, dst);
1984
+ complexOverlapBytes(src, dst);
1985
+ const ctr = nonce;
1986
+ const c32 = u32(ctr);
1987
+ const src32 = u32(src);
1988
+ const dst32 = u32(dst);
1989
+ for (let i = 0; i + 4 <= src32.length; i += 4) {
1990
+ const {
1991
+ s0,
1992
+ s1,
1993
+ s2,
1994
+ s3
1995
+ } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));
1996
+ dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);
1997
+ dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);
1998
+ dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);
1999
+ dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);
2000
+ for (let j = BLOCK_SIZE - 1, carry = 1; j >= 0; j--) {
2001
+ carry = carry + ctr[j] | 0;
2002
+ ctr[j] = carry & 0xff;
2003
+ carry >>>= 8;
2004
+ }
2005
+ }
2006
+ const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
2007
+ if (start < srcLen) {
2008
+ const {
2009
+ s0,
2010
+ s1,
2011
+ s2,
2012
+ s3
2013
+ } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));
2014
+ const b32 = new Uint32Array([s0, s1, s2, s3]);
2015
+ swap32IfBE(b32);
2016
+ const buf = u8(b32);
2017
+ for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];
2018
+ clean(b32);
2019
+ }
2020
+ return dst;
2021
+ }
2022
+ function ctr32(xk, isLE, nonce, src, dst) {
2023
+ abytes(nonce, BLOCK_SIZE, 'nonce');
2024
+ abytes(src);
2025
+ dst = getOutput(src.length, dst);
2026
+ const ctr = nonce;
2027
+ const c32 = u32(ctr);
2028
+ const view = createView(ctr);
2029
+ const src32 = u32(src);
2030
+ const dst32 = u32(dst);
2031
+ const ctrPos = isLE ? 0 : 12;
2032
+ const srcLen = src.length;
2033
+ let ctrNum = view.getUint32(ctrPos, isLE);
2034
+ for (let i = 0; i + 4 <= src32.length; i += 4) {
2035
+ const {
2036
+ s0,
2037
+ s1,
2038
+ s2,
2039
+ s3
2040
+ } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));
2041
+ dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);
2042
+ dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);
2043
+ dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);
2044
+ dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);
2045
+ ctrNum = ctrNum + 1 >>> 0;
2046
+ view.setUint32(ctrPos, ctrNum, isLE);
2047
+ }
2048
+ const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
2049
+ if (start < srcLen) {
2050
+ const {
2051
+ s0,
2052
+ s1,
2053
+ s2,
2054
+ s3
2055
+ } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));
2056
+ const b32 = new Uint32Array([s0, s1, s2, s3]);
2057
+ swap32IfBE(b32);
2058
+ const buf = u8(b32);
2059
+ for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];
2060
+ clean(b32);
2061
+ }
2062
+ return dst;
2063
+ }
2064
+ const ctr = wrapCipher({
2065
+ blockSize: 16,
2066
+ nonceLength: 16
2067
+ }, function aesctr(key, nonce) {
2068
+ function processCtr(buf, dst) {
2069
+ abytes(buf);
2070
+ if (dst !== undefined) {
2071
+ abytes(dst);
2072
+ if (!isAligned32(dst)) throw new Error('unaligned destination');
2073
+ }
2074
+ const xk = expandKeyLE(key);
2075
+ const n = copyBytes(nonce);
2076
+ const toClean = [xk, n];
2077
+ if (!isAligned32(buf)) toClean.push(buf = copyBytes(buf));
2078
+ const out = ctrCounter(xk, n, buf, dst);
2079
+ clean(...toClean);
2080
+ return out;
2081
+ }
2082
+ return {
2083
+ encrypt: (plaintext, dst) => processCtr(plaintext, dst),
2084
+ decrypt: (ciphertext, dst) => processCtr(ciphertext, dst)
2085
+ };
2086
+ });
2087
+ function validateBlockDecrypt(data, dst) {
2088
+ abytes(data);
2089
+ if (data.length % BLOCK_SIZE !== 0) {
2090
+ throw new Error('ciphertext must be multiple of ' + BLOCK_SIZE);
2091
+ }
2092
+ if (dst !== undefined) {
2093
+ getOutput(data.length, dst);
2094
+ complexOverlapBytes(data, dst);
2095
+ }
2096
+ }
2097
+ function validateBlockEncrypt(plaintext, pkcs5, dst) {
2098
+ abytes(plaintext);
2099
+ let outLen = plaintext.length;
2100
+ const remaining = outLen % BLOCK_SIZE;
2101
+ if (!pkcs5 && remaining !== 0) throw new Error('plaintext must be multiple of ' + BLOCK_SIZE);
2102
+ if (pkcs5) {
2103
+ let left = BLOCK_SIZE - remaining;
2104
+ if (!left) left = BLOCK_SIZE;
2105
+ outLen = outLen + left;
2106
+ }
2107
+ if (dst !== undefined) {
2108
+ getOutput(outLen, dst);
2109
+ complexOverlapBytes(plaintext, dst);
2110
+ }
2111
+ return outLen;
2112
+ }
2113
+ function prepareBlockEncrypt(plaintext, outLen, dst) {
2114
+ if (dst === undefined) dst = new Uint8Array(outLen);
2115
+ if (!isLE || !isAligned32(plaintext)) plaintext = copyBytes(plaintext);
2116
+ const o = u32(dst);
2117
+ return {
2118
+ b: plaintext,
2119
+ o,
2120
+ out: dst
2121
+ };
2122
+ }
2123
+ function validatePKCS(data, pkcs5) {
2124
+ if (!pkcs5) return data;
2125
+ const len = data.length;
2126
+ if (len === 0) throw new Error('pkcs7: empty ciphertext not allowed');
2127
+ const lastByte = data[len - 1];
2128
+ let valid = 1;
2129
+ valid &= lastByte - 1 >>> 31 ^ 1;
2130
+ valid &= 16 - lastByte >>> 31 ^ 1;
2131
+ for (let i = 0; i < 16; i++) {
2132
+ const shouldCheck = i - lastByte >>> 31;
2133
+ const eq = (data[len - 1 - i] ^ lastByte) === 0 ? 1 : 0;
2134
+ valid &= eq | shouldCheck ^ 1;
2135
+ }
2136
+ if (!valid) throw new Error('aes: bad decrypt');
2137
+ return data.subarray(0, len - lastByte);
2138
+ }
2139
+ function padPCKS(left) {
2140
+ const tmp = new Uint8Array(16);
2141
+ const tmp32 = u32(tmp);
2142
+ tmp.set(left);
2143
+ const paddingByte = BLOCK_SIZE - left.length;
2144
+ for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte;
2145
+ return tmp32;
2146
+ }
2147
+ const ecb = wrapCipher({
2148
+ blockSize: 16
2149
+ }, function aesecb(key, opts = {}) {
2150
+ const pkcs5 = !opts.disablePadding;
2151
+ return {
2152
+ encrypt(plaintext, dst) {
2153
+ const outLen = validateBlockEncrypt(plaintext, pkcs5, dst);
2154
+ const xk = expandKeyLE(key);
2155
+ const {
2156
+ b: input,
2157
+ o,
2158
+ out: _out
2159
+ } = prepareBlockEncrypt(plaintext, outLen, dst);
2160
+ const b = u32(input);
2161
+ swap32IfBE(b);
2162
+ let i = 0;
2163
+ for (; i + 4 <= b.length;) {
2164
+ const {
2165
+ s0,
2166
+ s1,
2167
+ s2,
2168
+ s3
2169
+ } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
2170
+ o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
2171
+ }
2172
+ if (pkcs5) {
2173
+ const tmp32 = padPCKS(plaintext.subarray(i * 4));
2174
+ swap32IfBE(tmp32);
2175
+ const {
2176
+ s0,
2177
+ s1,
2178
+ s2,
2179
+ s3
2180
+ } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);
2181
+ o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
2182
+ clean(tmp32);
2183
+ }
2184
+ swap32IfBE(o);
2185
+ clean(xk);
2186
+ if (input !== plaintext) clean(input);
2187
+ return _out;
2188
+ },
2189
+ decrypt(ciphertext, dst) {
2190
+ validateBlockDecrypt(ciphertext, dst);
2191
+ const xk = expandKeyDecLE(key);
2192
+ if (dst === undefined) dst = new Uint8Array(ciphertext.length);
2193
+ const toClean = [xk];
2194
+ if (!isLE || !isAligned32(ciphertext)) toClean.push(ciphertext = copyBytes(ciphertext));
2195
+ const b = u32(ciphertext);
2196
+ const o = u32(dst);
2197
+ swap32IfBE(b);
2198
+ for (let i = 0; i + 4 <= b.length;) {
2199
+ const {
2200
+ s0,
2201
+ s1,
2202
+ s2,
2203
+ s3
2204
+ } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
2205
+ o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
2206
+ }
2207
+ swap32IfBE(o);
2208
+ clean(...toClean);
2209
+ return validatePKCS(dst, pkcs5);
2210
+ }
2211
+ };
2212
+ });
2213
+ const cbc = wrapCipher({
2214
+ blockSize: 16,
2215
+ nonceLength: 16
2216
+ }, function aescbc(key, iv, opts = {}) {
2217
+ const pkcs5 = !opts.disablePadding;
2218
+ return {
2219
+ encrypt(plaintext, dst) {
2220
+ const outLen = validateBlockEncrypt(plaintext, pkcs5, dst);
2221
+ const xk = expandKeyLE(key);
2222
+ const {
2223
+ b: input,
2224
+ o,
2225
+ out: _out
2226
+ } = prepareBlockEncrypt(plaintext, outLen, dst);
2227
+ const b = u32(input);
2228
+ swap32IfBE(b);
2229
+ let _iv = iv;
2230
+ const toClean = [xk];
2231
+ if (!isLE || !isAligned32(_iv)) toClean.push(_iv = copyBytes(_iv));
2232
+ const n32 = u32(_iv);
2233
+ swap32IfBE(n32);
2234
+ let s0 = n32[0],
2235
+ s1 = n32[1],
2236
+ s2 = n32[2],
2237
+ s3 = n32[3];
2238
+ let i = 0;
2239
+ for (; i + 4 <= b.length;) {
2240
+ s0 ^= b[i + 0], s1 ^= b[i + 1], s2 ^= b[i + 2], s3 ^= b[i + 3];
2241
+ ({
2242
+ s0,
2243
+ s1,
2244
+ s2,
2245
+ s3
2246
+ } = encrypt(xk, s0, s1, s2, s3));
2247
+ o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
2248
+ }
2249
+ if (pkcs5) {
2250
+ const tmp32 = padPCKS(plaintext.subarray(i * 4));
2251
+ swap32IfBE(tmp32);
2252
+ s0 ^= tmp32[0], s1 ^= tmp32[1], s2 ^= tmp32[2], s3 ^= tmp32[3];
2253
+ ({
2254
+ s0,
2255
+ s1,
2256
+ s2,
2257
+ s3
2258
+ } = encrypt(xk, s0, s1, s2, s3));
2259
+ o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
2260
+ clean(tmp32);
2261
+ }
2262
+ swap32IfBE(o);
2263
+ clean(...toClean);
2264
+ if (input !== plaintext) clean(input);
2265
+ return _out;
2266
+ },
2267
+ decrypt(ciphertext, dst) {
2268
+ validateBlockDecrypt(ciphertext, dst);
2269
+ const xk = expandKeyDecLE(key);
2270
+ if (dst === undefined) dst = new Uint8Array(ciphertext.length);
2271
+ let _iv = iv;
2272
+ const toClean = [xk];
2273
+ if (!isLE || !isAligned32(_iv)) toClean.push(_iv = copyBytes(_iv));
2274
+ const n32 = u32(_iv);
2275
+ swap32IfBE(n32);
2276
+ if (!isLE || !isAligned32(ciphertext)) toClean.push(ciphertext = copyBytes(ciphertext));
2277
+ const b = u32(ciphertext);
2278
+ const o = u32(dst);
2279
+ swap32IfBE(b);
2280
+ let s0 = n32[0],
2281
+ s1 = n32[1],
2282
+ s2 = n32[2],
2283
+ s3 = n32[3];
2284
+ for (let i = 0; i + 4 <= b.length;) {
2285
+ const ps0 = s0,
2286
+ ps1 = s1,
2287
+ ps2 = s2,
2288
+ ps3 = s3;
2289
+ s0 = b[i + 0], s1 = b[i + 1], s2 = b[i + 2], s3 = b[i + 3];
2290
+ const {
2291
+ s0: o0,
2292
+ s1: o1,
2293
+ s2: o2,
2294
+ s3: o3
2295
+ } = decrypt(xk, s0, s1, s2, s3);
2296
+ o[i++] = o0 ^ ps0, o[i++] = o1 ^ ps1, o[i++] = o2 ^ ps2, o[i++] = o3 ^ ps3;
2297
+ }
2298
+ swap32IfBE(o);
2299
+ clean(...toClean);
2300
+ return validatePKCS(dst, pkcs5);
2301
+ }
2302
+ };
2303
+ });
2304
+ wrapCipher({
2305
+ blockSize: 16,
2306
+ nonceLength: 16
2307
+ }, function aescfb(key, iv) {
2308
+ function processCfb(src, isEncrypt, dst) {
2309
+ abytes(src);
2310
+ const srcLen = src.length;
2311
+ dst = getOutput(srcLen, dst);
2312
+ if (overlapBytes(src, dst)) throw new Error('overlapping src and dst not supported');
2313
+ const xk = expandKeyLE(key);
2314
+ let _iv = iv;
2315
+ const toClean = [xk];
2316
+ if (!isLE || !isAligned32(_iv)) toClean.push(_iv = copyBytes(_iv));
2317
+ if (!isLE || !isAligned32(src)) toClean.push(src = copyBytes(src));
2318
+ const src32 = u32(src);
2319
+ const dst32 = u32(dst);
2320
+ const next32 = isEncrypt ? dst32 : src32;
2321
+ const n32 = u32(_iv);
2322
+ swap32IfBE(src32);
2323
+ swap32IfBE(n32);
2324
+ let s0 = n32[0],
2325
+ s1 = n32[1],
2326
+ s2 = n32[2],
2327
+ s3 = n32[3];
2328
+ for (let i = 0; i + 4 <= src32.length;) {
2329
+ const {
2330
+ s0: e0,
2331
+ s1: e1,
2332
+ s2: e2,
2333
+ s3: e3
2334
+ } = encrypt(xk, s0, s1, s2, s3);
2335
+ dst32[i + 0] = src32[i + 0] ^ e0;
2336
+ dst32[i + 1] = src32[i + 1] ^ e1;
2337
+ dst32[i + 2] = src32[i + 2] ^ e2;
2338
+ dst32[i + 3] = src32[i + 3] ^ e3;
2339
+ s0 = next32[i++], s1 = next32[i++], s2 = next32[i++], s3 = next32[i++];
2340
+ }
2341
+ const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
2342
+ if (start < srcLen) {
2343
+ if (!isLE) swap32IfBE(src32.subarray(start / 4));
2344
+ ({
2345
+ s0,
2346
+ s1,
2347
+ s2,
2348
+ s3
2349
+ } = encrypt(xk, s0, s1, s2, s3));
2350
+ const tmp = new Uint32Array([s0, s1, s2, s3]);
2351
+ swap32IfBE(tmp);
2352
+ const buf = u8(tmp);
2353
+ for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];
2354
+ clean(buf);
2355
+ }
2356
+ if (!isLE) swap32IfBE(dst32.subarray(0, start / 4));
2357
+ clean(...toClean);
2358
+ return dst;
2359
+ }
2360
+ return {
2361
+ encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),
2362
+ decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst)
2363
+ };
2364
+ });
2365
+ function computeTag(fn, isLE, key, data, AAD) {
2366
+ const aadLength = AAD ? AAD.length : 0;
2367
+ const h = fn.create(key, data.length + aadLength);
2368
+ if (AAD) h.update(AAD);
2369
+ const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);
2370
+ h.update(data);
2371
+ h.update(num);
2372
+ const res = h.digest();
2373
+ clean(num);
2374
+ return res;
2375
+ }
2376
+ wrapCipher({
2377
+ blockSize: 16,
2378
+ nonceLength: 12,
2379
+ tagLength: 16,
2380
+ withAAD: true,
2381
+ varSizeNonce: true
2382
+ }, function aesgcm(key, nonce, AAD) {
2383
+ if (nonce.length < 8) throw new Error('aes/gcm: invalid nonce length');
2384
+ const tagLength = 16;
2385
+ function _computeTag(authKey, tagMask, data) {
2386
+ const tag = computeTag(ghash, false, authKey, data, AAD);
2387
+ for (let i = 0; i < tagMask.length; i++) tag[i] ^= tagMask[i];
2388
+ return tag;
2389
+ }
2390
+ function deriveKeys() {
2391
+ const xk = expandKeyLE(key);
2392
+ const authKey = EMPTY_BLOCK.slice();
2393
+ const counter = EMPTY_BLOCK.slice();
2394
+ ctr32(xk, false, counter, counter, authKey);
2395
+ if (nonce.length === 12) {
2396
+ counter.set(nonce);
2397
+ } else {
2398
+ const nonceLen = EMPTY_BLOCK.slice();
2399
+ const view = createView(nonceLen);
2400
+ view.setBigUint64(8, BigInt(nonce.length * 8), false);
2401
+ const g = ghash.create(authKey).update(nonce).update(nonceLen);
2402
+ g.digestInto(counter);
2403
+ g.destroy();
2404
+ }
2405
+ const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);
2406
+ return {
2407
+ xk,
2408
+ authKey,
2409
+ counter,
2410
+ tagMask
2411
+ };
2412
+ }
2413
+ return {
2414
+ encrypt(plaintext) {
2415
+ const {
2416
+ xk,
2417
+ authKey,
2418
+ counter,
2419
+ tagMask
2420
+ } = deriveKeys();
2421
+ const out = new Uint8Array(plaintext.length + tagLength);
2422
+ const toClean = [xk, authKey, counter, tagMask];
2423
+ if (!isAligned32(plaintext)) toClean.push(plaintext = copyBytes(plaintext));
2424
+ ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));
2425
+ const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));
2426
+ toClean.push(tag);
2427
+ out.set(tag, plaintext.length);
2428
+ clean(...toClean);
2429
+ return out;
2430
+ },
2431
+ decrypt(ciphertext) {
2432
+ const {
2433
+ xk,
2434
+ authKey,
2435
+ counter,
2436
+ tagMask
2437
+ } = deriveKeys();
2438
+ const toClean = [xk, authKey, tagMask, counter];
2439
+ if (!isAligned32(ciphertext)) toClean.push(ciphertext = copyBytes(ciphertext));
2440
+ const data = ciphertext.subarray(0, -tagLength);
2441
+ const passedTag = ciphertext.subarray(-tagLength);
2442
+ const tag = _computeTag(authKey, tagMask, data);
2443
+ toClean.push(tag);
2444
+ if (!equalBytes(tag, passedTag)) {
2445
+ clean(...toClean);
2446
+ throw new Error('aes-gcm: invalid tag');
2447
+ }
2448
+ const out = ctr32(xk, false, counter, data);
2449
+ clean(...toClean);
2450
+ return out;
2451
+ }
2452
+ };
2453
+ });
2454
+ const limit = (name, min, max) => value => {
2455
+ if (!Number.isSafeInteger(value) || min > value || value > max) {
2456
+ const minmax = '[' + min + '..' + max + ']';
2457
+ throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);
2458
+ }
2459
+ };
2460
+ wrapCipher({
2461
+ blockSize: 16,
2462
+ nonceLength: 12,
2463
+ tagLength: 16,
2464
+ withAAD: true,
2465
+ varSizeNonce: true
2466
+ }, function aessiv(key, nonce, AAD) {
2467
+ const tagLength = 16;
2468
+ const AAD_LIMIT = limit('AAD', 0, 2 ** 36);
2469
+ const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);
2470
+ const NONCE_LIMIT = limit('nonce', 12, 12);
2471
+ const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);
2472
+ abytes(key);
2473
+ validateKeyLength(key);
2474
+ NONCE_LIMIT(nonce.length);
2475
+ if (AAD !== undefined) AAD_LIMIT(AAD.length);
2476
+ function deriveKeys() {
2477
+ const xk = expandKeyLE(key);
2478
+ const encKey = new Uint8Array(key.length);
2479
+ const authKey = new Uint8Array(16);
2480
+ const toClean = [xk, encKey];
2481
+ let _nonce = nonce;
2482
+ if (!isLE || !isAligned32(_nonce)) toClean.push(_nonce = copyBytes(_nonce));
2483
+ const n32 = u32(_nonce);
2484
+ swap32IfBE(n32);
2485
+ let s0 = 0,
2486
+ s1 = n32[0],
2487
+ s2 = n32[1],
2488
+ s3 = n32[2];
2489
+ let counter = 0;
2490
+ for (const derivedKey of [authKey, encKey].map(u32)) {
2491
+ const d32 = u32(derivedKey);
2492
+ for (let i = 0; i < d32.length; i += 2) {
2493
+ const {
2494
+ s0: o0,
2495
+ s1: o1
2496
+ } = encrypt(xk, s0, s1, s2, s3);
2497
+ d32[i + 0] = o0;
2498
+ d32[i + 1] = o1;
2499
+ s0 = ++counter;
2500
+ }
2501
+ swap32IfBE(d32);
2502
+ }
2503
+ const res = {
2504
+ authKey,
2505
+ encKey: expandKeyLE(encKey)
2506
+ };
2507
+ clean(...toClean);
2508
+ return res;
2509
+ }
2510
+ function _computeTag(encKey, authKey, data) {
2511
+ const tag = computeTag(polyval, true, authKey, data, AAD);
2512
+ for (let i = 0; i < 12; i++) tag[i] ^= nonce[i];
2513
+ tag[15] &= 0x7f;
2514
+ const t32 = u32(tag);
2515
+ swap32IfBE(t32);
2516
+ let s0 = t32[0],
2517
+ s1 = t32[1],
2518
+ s2 = t32[2],
2519
+ s3 = t32[3];
2520
+ ({
2521
+ s0,
2522
+ s1,
2523
+ s2,
2524
+ s3
2525
+ } = encrypt(encKey, s0, s1, s2, s3));
2526
+ t32[0] = s0, t32[1] = s1, t32[2] = s2, t32[3] = s3;
2527
+ swap32IfBE(t32);
2528
+ return tag;
2529
+ }
2530
+ function processSiv(encKey, tag, input) {
2531
+ let block = copyBytes(tag);
2532
+ block[15] |= 0x80;
2533
+ const res = ctr32(encKey, true, block, input);
2534
+ clean(block);
2535
+ return res;
2536
+ }
2537
+ return {
2538
+ encrypt(plaintext) {
2539
+ PLAIN_LIMIT(plaintext.length);
2540
+ const {
2541
+ encKey,
2542
+ authKey
2543
+ } = deriveKeys();
2544
+ const tag = _computeTag(encKey, authKey, plaintext);
2545
+ const toClean = [encKey, authKey, tag];
2546
+ if (!isAligned32(plaintext)) toClean.push(plaintext = copyBytes(plaintext));
2547
+ const out = new Uint8Array(plaintext.length + tagLength);
2548
+ out.set(tag, plaintext.length);
2549
+ out.set(processSiv(encKey, tag, plaintext));
2550
+ clean(...toClean);
2551
+ return out;
2552
+ },
2553
+ decrypt(ciphertext) {
2554
+ CIPHER_LIMIT(ciphertext.length);
2555
+ const tag = ciphertext.subarray(-tagLength);
2556
+ const {
2557
+ encKey,
2558
+ authKey
2559
+ } = deriveKeys();
2560
+ const toClean = [encKey, authKey];
2561
+ if (!isAligned32(ciphertext)) toClean.push(ciphertext = copyBytes(ciphertext));
2562
+ const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));
2563
+ const expectedTag = _computeTag(encKey, authKey, plaintext);
2564
+ toClean.push(expectedTag);
2565
+ if (!equalBytes(tag, expectedTag)) {
2566
+ clean(plaintext, ...toClean);
2567
+ throw new Error('invalid polyval tag');
2568
+ }
2569
+ clean(...toClean);
2570
+ return plaintext;
2571
+ }
2572
+ };
2573
+ });
2574
+ function isBytes32(a) {
2575
+ return a instanceof Uint32Array || ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array';
2576
+ }
2577
+ function encryptBlock(xk, block) {
2578
+ abytes(block, 16, 'block');
2579
+ if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE');
2580
+ const b32 = u32(block);
2581
+ swap32IfBE(b32);
2582
+ let {
2583
+ s0,
2584
+ s1,
2585
+ s2,
2586
+ s3
2587
+ } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);
2588
+ b32[0] = s0, b32[1] = s1, b32[2] = s2, b32[3] = s3;
2589
+ swap32IfBE(b32);
2590
+ return block;
2591
+ }
2592
+ function decryptBlock(xk, block) {
2593
+ abytes(block, 16, 'block');
2594
+ if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE');
2595
+ const b32 = u32(block);
2596
+ swap32IfBE(b32);
2597
+ let {
2598
+ s0,
2599
+ s1,
2600
+ s2,
2601
+ s3
2602
+ } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);
2603
+ b32[0] = s0, b32[1] = s1, b32[2] = s2, b32[3] = s3;
2604
+ swap32IfBE(b32);
2605
+ return block;
2606
+ }
2607
+ const AESW = {
2608
+ encrypt(kek, out) {
2609
+ if (out.length >= 2 ** 32) throw new Error('plaintext should be less than 4gb');
2610
+ const xk = expandKeyLE(kek);
2611
+ if (out.length === 16) encryptBlock(xk, out);else {
2612
+ const o32 = u32(out);
2613
+ swap32IfBE(o32);
2614
+ let a0 = o32[0],
2615
+ a1 = o32[1];
2616
+ for (let j = 0, ctr = 1; j < 6; j++) {
2617
+ for (let pos = 2; pos < o32.length; pos += 2, ctr++) {
2618
+ const {
2619
+ s0,
2620
+ s1,
2621
+ s2,
2622
+ s3
2623
+ } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);
2624
+ a0 = s0, a1 = s1 ^ byteSwap(ctr), o32[pos] = s2, o32[pos + 1] = s3;
2625
+ }
2626
+ }
2627
+ o32[0] = a0, o32[1] = a1;
2628
+ swap32IfBE(o32);
2629
+ }
2630
+ xk.fill(0);
2631
+ },
2632
+ decrypt(kek, out) {
2633
+ if (out.length - 8 >= 2 ** 32) throw new Error('ciphertext should be less than 4gb');
2634
+ const xk = expandKeyDecLE(kek);
2635
+ const chunks = out.length / 8 - 1;
2636
+ if (chunks === 1) decryptBlock(xk, out);else {
2637
+ const o32 = u32(out);
2638
+ swap32IfBE(o32);
2639
+ let a0 = o32[0],
2640
+ a1 = o32[1];
2641
+ for (let j = 0, ctr = chunks * 6; j < 6; j++) {
2642
+ for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {
2643
+ a1 ^= byteSwap(ctr);
2644
+ const {
2645
+ s0,
2646
+ s1,
2647
+ s2,
2648
+ s3
2649
+ } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);
2650
+ a0 = s0, a1 = s1, o32[pos] = s2, o32[pos + 1] = s3;
2651
+ }
2652
+ }
2653
+ o32[0] = a0, o32[1] = a1;
2654
+ swap32IfBE(o32);
2655
+ }
2656
+ xk.fill(0);
2657
+ }
2658
+ };
2659
+ const AESKW_IV = new Uint8Array(8).fill(0xa6);
2660
+ wrapCipher({
2661
+ blockSize: 8
2662
+ }, kek => ({
2663
+ encrypt(plaintext) {
2664
+ if (!plaintext.length || plaintext.length % 8 !== 0) throw new Error('invalid plaintext length');
2665
+ if (plaintext.length === 8) throw new Error('8-byte keys not allowed, use AESKWP');
2666
+ const out = concatBytes(AESKW_IV, plaintext);
2667
+ AESW.encrypt(kek, out);
2668
+ return out;
2669
+ },
2670
+ decrypt(ciphertext) {
2671
+ if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8) throw new Error('invalid ciphertext length');
2672
+ const out = copyBytes(ciphertext);
2673
+ AESW.decrypt(kek, out);
2674
+ if (!equalBytes(out.subarray(0, 8), AESKW_IV)) throw new Error('integrity check failed');
2675
+ out.subarray(0, 8).fill(0);
2676
+ return out.subarray(8);
2677
+ }
2678
+ }));
2679
+ const AESKWP_IV = 0xa65959a6;
2680
+ wrapCipher({
2681
+ blockSize: 8
2682
+ }, kek => ({
2683
+ encrypt(plaintext) {
2684
+ if (!plaintext.length) throw new Error('invalid plaintext length');
2685
+ const padded = Math.ceil(plaintext.length / 8) * 8;
2686
+ const out = new Uint8Array(8 + padded);
2687
+ out.set(plaintext, 8);
2688
+ const out32 = u32(out);
2689
+ out32[0] = swap8IfBE(AESKWP_IV);
2690
+ out32[1] = swap8IfBE(byteSwap(plaintext.length));
2691
+ AESW.encrypt(kek, out);
2692
+ return out;
2693
+ },
2694
+ decrypt(ciphertext) {
2695
+ if (ciphertext.length < 16) throw new Error('invalid ciphertext length');
2696
+ const out = copyBytes(ciphertext);
2697
+ const o32 = u32(out);
2698
+ AESW.decrypt(kek, out);
2699
+ const len = byteSwap(swap8IfBE(o32[1])) >>> 0;
2700
+ const padded = Math.ceil(len / 8) * 8;
2701
+ if (swap8IfBE(o32[0]) !== AESKWP_IV || out.length - 8 !== padded) throw new Error('integrity check failed');
2702
+ for (let i = len; i < padded; i++) if (out[8 + i] !== 0) throw new Error('integrity check failed');
2703
+ out.subarray(0, 8).fill(0);
2704
+ return out.subarray(8, 8 + len);
2705
+ }
2706
+ }));
2707
+ function dbl(block) {
2708
+ let carry = 0;
2709
+ for (let i = BLOCK_SIZE - 1; i >= 0; i--) {
2710
+ const newCarry = (block[i] & 0x80) >>> 7;
2711
+ block[i] = block[i] << 1 | carry;
2712
+ carry = newCarry;
2713
+ }
2714
+ block[BLOCK_SIZE - 1] ^= 0x87 & -carry;
2715
+ return block;
2716
+ }
2717
+ function xorBlock(a, b) {
2718
+ if (a.length !== b.length) throw new Error('xorBlock: blocks must have same length');
2719
+ for (let i = 0; i < a.length; i++) {
2720
+ a[i] = a[i] ^ b[i];
1265
2721
  }
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);
2722
+ return a;
2723
+ }
2724
+ function xorend(a, b) {
2725
+ if (b.length > a.length) {
2726
+ throw new Error('xorend: expected len(B) <= len(A)');
2727
+ }
2728
+ const offset = a.length - b.length;
2729
+ for (let i = 0; i < b.length; i++) {
2730
+ a[offset + i] = a[offset + i] ^ b[i];
1269
2731
  }
2732
+ return a;
1270
2733
  }
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;
2734
+ class _CMAC {
2735
+ blockLen = BLOCK_SIZE;
2736
+ outputLen = BLOCK_SIZE;
2737
+ buffer;
2738
+ pos;
2739
+ finished;
2740
+ destroyed;
2741
+ k1;
2742
+ k2;
2743
+ x;
2744
+ x32;
2745
+ xk;
2746
+ constructor(key) {
2747
+ abytes(key);
2748
+ validateKeyLength(key);
2749
+ this.xk = expandKeyLE(key);
2750
+ this.buffer = new Uint8Array(BLOCK_SIZE);
2751
+ this.pos = 0;
2752
+ this.finished = false;
2753
+ this.destroyed = false;
2754
+ this.x = new Uint8Array(BLOCK_SIZE);
2755
+ this.x32 = u32(this.x);
2756
+ const L = new Uint8Array(BLOCK_SIZE);
2757
+ encryptBlock(this.xk, L);
2758
+ this.k1 = dbl(L);
2759
+ this.k2 = dbl(new Uint8Array(this.k1));
2760
+ }
2761
+ process(data, pos) {
2762
+ const {
2763
+ x,
2764
+ x32,
2765
+ xk
2766
+ } = this;
2767
+ for (let i = 0; i < BLOCK_SIZE; i++) x[i] ^= data[pos + i];
2768
+ swap32IfBE(x32);
2769
+ const {
2770
+ s0,
2771
+ s1,
2772
+ s2,
2773
+ s3
2774
+ } = encrypt(xk, x32[0], x32[1], x32[2], x32[3]);
2775
+ x32[0] = s0, x32[1] = s1, x32[2] = s2, x32[3] = s3;
2776
+ swap32IfBE(x32);
2777
+ }
2778
+ update(data) {
2779
+ aexists(this);
2780
+ abytes(data);
2781
+ let pos = 0;
2782
+ if (this.pos) {
2783
+ const take = Math.min(BLOCK_SIZE - this.pos, data.length);
2784
+ this.buffer.set(data.subarray(0, take), this.pos);
2785
+ this.pos += take;
2786
+ pos = take;
2787
+ if (this.pos === BLOCK_SIZE && pos < data.length) {
2788
+ this.process(this.buffer, 0);
2789
+ this.pos = 0;
2790
+ }
2791
+ }
2792
+ while (pos + BLOCK_SIZE < data.length) {
2793
+ this.process(data, pos);
2794
+ pos += BLOCK_SIZE;
2795
+ }
2796
+ if (pos < data.length) {
2797
+ this.buffer.set(data.subarray(pos), 0);
2798
+ this.pos = data.length - pos;
2799
+ }
2800
+ return this;
2801
+ }
2802
+ digestInto(out) {
2803
+ aexists(this);
2804
+ aoutput32(out, this);
2805
+ this.finished = true;
2806
+ const view = out.subarray(0, this.outputLen);
2807
+ let last = new Uint8Array(BLOCK_SIZE);
2808
+ if (this.pos === BLOCK_SIZE) {
2809
+ last.set(this.buffer);
2810
+ xorBlock(last, this.k1);
2811
+ } else {
2812
+ last.set(this.buffer.subarray(0, this.pos));
2813
+ last[this.pos] = 0x80;
2814
+ xorBlock(last, this.k2);
2815
+ }
2816
+ view.set(this.x);
2817
+ xorBlock(view, last);
2818
+ encryptBlock(this.xk, view);
2819
+ clean(last);
2820
+ }
2821
+ digest() {
2822
+ const {
2823
+ buffer,
2824
+ outputLen
2825
+ } = this;
2826
+ this.digestInto(buffer);
2827
+ const res = buffer.slice(0, outputLen);
2828
+ this.destroy();
2829
+ return res;
2830
+ }
2831
+ destroy() {
2832
+ const {
2833
+ buffer,
2834
+ destroyed,
2835
+ x,
2836
+ xk,
2837
+ k1,
2838
+ k2
2839
+ } = this;
2840
+ if (destroyed) return;
2841
+ this.destroyed = true;
2842
+ clean(buffer, x, xk, k1, k2);
1290
2843
  }
1291
2844
  }
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());
1342
-
1343
- function sha256Hash(data) {
1344
- return sha256(data);
2845
+ const cmac = wrapMacConstructor(16, key => new _CMAC(key));
2846
+ function s2v(key, strings) {
2847
+ validateKeyLength(key);
2848
+ const len = strings.length;
2849
+ if (len > 127) {
2850
+ throw new Error('s2v: expected <= 127 inputs');
2851
+ }
2852
+ if (len === 0) return cmac(ONE_BLOCK, key);
2853
+ let d = cmac(EMPTY_BLOCK, key);
2854
+ for (let i = 0; i < len - 1; i++) {
2855
+ dbl(d);
2856
+ const cmacResult = cmac(strings[i], key);
2857
+ xorBlock(d, cmacResult);
2858
+ clean(cmacResult);
2859
+ }
2860
+ const s_n = strings[len - 1];
2861
+ abytes(s_n);
2862
+ let t;
2863
+ if (s_n.byteLength >= BLOCK_SIZE) {
2864
+ t = xorend(Uint8Array.from(s_n), d);
2865
+ } else {
2866
+ const paddedSn = new Uint8Array(BLOCK_SIZE);
2867
+ paddedSn.set(s_n);
2868
+ paddedSn[s_n.length] = 0x80;
2869
+ t = xorBlock(dbl(d), paddedSn);
2870
+ clean(paddedSn);
2871
+ }
2872
+ const result = cmac(t, key);
2873
+ clean(d, t);
2874
+ return result;
1345
2875
  }
2876
+ wrapCipher({
2877
+ blockSize: 16,
2878
+ tagLength: 16,
2879
+ withAAD: true
2880
+ }, function aessiv(key, ...AAD) {
2881
+ const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 132);
2882
+ const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 132 + 16);
2883
+ if (AAD.length > 126) {
2884
+ throw new Error('"AAD" expected <= 126 items');
2885
+ }
2886
+ AAD.forEach(aad => abytes(aad));
2887
+ abytes(key);
2888
+ if (![32, 48, 64].includes(key.length)) throw new Error('"aes key" expected Uint8Array of length 32/48/64, got length=' + key.length);
2889
+ const k1 = key.subarray(0, key.length / 2);
2890
+ const k2 = key.subarray(key.length / 2);
2891
+ return {
2892
+ encrypt(plaintext) {
2893
+ PLAIN_LIMIT(plaintext.length);
2894
+ const v = s2v(k1, [...AAD, plaintext]);
2895
+ const q = Uint8Array.from(v);
2896
+ q[8] &= 0x7f;
2897
+ q[12] &= 0x7f;
2898
+ const c = ctr(k2, q).encrypt(plaintext);
2899
+ return concatBytes(v, c);
2900
+ },
2901
+ decrypt(ciphertext) {
2902
+ CIPHER_LIMIT(ciphertext.length);
2903
+ const v = ciphertext.subarray(0, BLOCK_SIZE);
2904
+ const c = ciphertext.subarray(BLOCK_SIZE);
2905
+ const q = Uint8Array.from(v);
2906
+ q[8] &= 0x7f;
2907
+ q[12] &= 0x7f;
2908
+ const p = ctr(k2, q).decrypt(c);
2909
+ const t = s2v(k1, [...AAD, p]);
2910
+ if (equalBytes(t, v)) {
2911
+ return p;
2912
+ } else {
2913
+ clean(p);
2914
+ throw new Error('invalid siv tag');
2915
+ }
2916
+ }
2917
+ };
2918
+ });
1346
2919
 
1347
2920
  function aesCbcEncrypt(data, key, iv, padding = true) {
1348
2921
  return cbc(key, iv, {
@@ -1479,7 +3052,7 @@ class PDFSecurity {
1479
3052
  }
1480
3053
  infoStr += `${key}: ${info[key].valueOf()}\n`;
1481
3054
  }
1482
- return md5Hash(infoStr);
3055
+ return md5Hash(new TextEncoder().encode(infoStr));
1483
3056
  }
1484
3057
  static generateRandomWordArray(bytes) {
1485
3058
  return randomBytes(bytes);
@@ -1614,7 +3187,7 @@ class PDFSecurity {
1614
3187
  let digest;
1615
3188
  if (this.version < 5) {
1616
3189
  const suffix = new Uint8Array([obj & 0xff, obj >> 8 & 0xff, obj >> 16 & 0xff, gen & 0xff, gen >> 8 & 0xff]);
1617
- digest = concatBytes(this.encryptionKey, suffix);
3190
+ digest = concatBytes$1(this.encryptionKey, suffix);
1618
3191
  }
1619
3192
  if (this.version === 1 || this.version === 2) {
1620
3193
  let key = md5Hash(digest);
@@ -1625,14 +3198,14 @@ class PDFSecurity {
1625
3198
  let key;
1626
3199
  if (this.version === 4) {
1627
3200
  const saltMarker = new Uint8Array([0x73, 0x41, 0x6c, 0x54]);
1628
- key = md5Hash(concatBytes(digest, saltMarker));
3201
+ key = md5Hash(concatBytes$1(digest, saltMarker));
1629
3202
  } else {
1630
3203
  key = this.encryptionKey;
1631
3204
  }
1632
3205
  const iv = PDFSecurity.generateRandomWordArray(16);
1633
3206
  return buffer => {
1634
3207
  const encrypted = aesCbcEncrypt(buffer, key, iv, true);
1635
- return concatBytes(iv, encrypted);
3208
+ return concatBytes$1(iv, encrypted);
1636
3209
  };
1637
3210
  }
1638
3211
  end() {
@@ -1688,7 +3261,7 @@ function getUserPasswordR2(encryptionKey) {
1688
3261
  }
1689
3262
  function getUserPasswordR3R4(documentId, encryptionKey) {
1690
3263
  const key = encryptionKey.slice();
1691
- let cipher = md5Hash(concatBytes(processPasswordR2R3R4(), new Uint8Array(documentId)));
3264
+ let cipher = md5Hash(concatBytes$1(processPasswordR2R3R4(), new Uint8Array(documentId)));
1692
3265
  for (let i = 0; i < 20; i++) {
1693
3266
  const xorKey = new Uint8Array(key.length);
1694
3267
  for (let j = 0; j < key.length; j++) {
@@ -1721,7 +3294,7 @@ function getOwnerPasswordR2R3R4(r, keyBits, paddedUserPassword, paddedOwnerPassw
1721
3294
  }
1722
3295
  function getEncryptionKeyR2R3R4(r, keyBits, documentId, paddedUserPassword, ownerPasswordEntry, permissions) {
1723
3296
  const permBytes = new Uint8Array([permissions & 0xff, permissions >> 8 & 0xff, permissions >> 16 & 0xff, permissions >> 24 & 0xff]);
1724
- let key = concatBytes(paddedUserPassword, ownerPasswordEntry, permBytes, new Uint8Array(documentId));
3297
+ let key = concatBytes$1(paddedUserPassword, ownerPasswordEntry, permBytes, new Uint8Array(documentId));
1725
3298
  const round = r >= 3 ? 51 : 1;
1726
3299
  const keyLen = keyBits / 8;
1727
3300
  for (let i = 0; i < round; i++) {
@@ -1733,22 +3306,22 @@ function getEncryptionKeyR2R3R4(r, keyBits, documentId, paddedUserPassword, owne
1733
3306
  function getUserPasswordR5(processedUserPassword, generateRandomWordArray) {
1734
3307
  const validationSalt = generateRandomWordArray(8);
1735
3308
  const keySalt = generateRandomWordArray(8);
1736
- const hash = sha256Hash(concatBytes(processedUserPassword, validationSalt));
1737
- return concatBytes(hash, validationSalt, keySalt);
3309
+ const hash = sha256Hash(concatBytes$1(processedUserPassword, validationSalt));
3310
+ return concatBytes$1(hash, validationSalt, keySalt);
1738
3311
  }
1739
3312
  function getUserEncryptionKeyR5(processedUserPassword, userKeySalt, encryptionKey) {
1740
- const key = sha256Hash(concatBytes(processedUserPassword, userKeySalt));
3313
+ const key = sha256Hash(concatBytes$1(processedUserPassword, userKeySalt));
1741
3314
  const iv = new Uint8Array(16);
1742
3315
  return aesCbcEncrypt(encryptionKey, key, iv, false);
1743
3316
  }
1744
3317
  function getOwnerPasswordR5(processedOwnerPassword, userPasswordEntry, generateRandomWordArray) {
1745
3318
  const validationSalt = generateRandomWordArray(8);
1746
3319
  const keySalt = generateRandomWordArray(8);
1747
- const hash = sha256Hash(concatBytes(processedOwnerPassword, validationSalt, userPasswordEntry));
1748
- return concatBytes(hash, validationSalt, keySalt);
3320
+ const hash = sha256Hash(concatBytes$1(processedOwnerPassword, validationSalt, userPasswordEntry));
3321
+ return concatBytes$1(hash, validationSalt, keySalt);
1749
3322
  }
1750
3323
  function getOwnerEncryptionKeyR5(processedOwnerPassword, ownerKeySalt, userPasswordEntry, encryptionKey) {
1751
- const key = sha256Hash(concatBytes(processedOwnerPassword, ownerKeySalt, userPasswordEntry));
3324
+ const key = sha256Hash(concatBytes$1(processedOwnerPassword, ownerKeySalt, userPasswordEntry));
1752
3325
  const iv = new Uint8Array(16);
1753
3326
  return aesCbcEncrypt(encryptionKey, key, iv, false);
1754
3327
  }
@@ -1802,6 +3375,104 @@ function processPasswordR5(password = '') {
1802
3375
  }
1803
3376
  const PASSWORD_PADDING = [0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08, 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80, 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a];
1804
3377
 
3378
+ const OBJECTS_PER_STREAM = 200;
3379
+ const ENTRY_WIDTHS = [1, 4, 2];
3380
+ const ENTRY_SIZE = 7;
3381
+ const FREE = 0;
3382
+ const UNCOMPRESSED = 1;
3383
+ const COMPRESSED = 2;
3384
+ class PDFObjectStreams {
3385
+ constructor(document, options) {
3386
+ if (document.version < 1.5) {
3387
+ throw new Error("The objectStreams option requires a pdfVersion of '1.5' or higher");
3388
+ }
3389
+ if (/^PDF\/A-1/.test(options.subset)) {
3390
+ throw new Error('PDF/A-1 does not allow object streams');
3391
+ }
3392
+ if (options.userPassword || options.ownerPassword) {
3393
+ throw new Error('The objectStreams option cannot be used with encryption');
3394
+ }
3395
+ this.document = document;
3396
+ this.pending = [];
3397
+ this.locations = new Map();
3398
+ }
3399
+ add(ref) {
3400
+ this.pending.push({
3401
+ id: ref.id,
3402
+ body: PDFObject.convert(ref.data)
3403
+ });
3404
+ if (this.pending.length >= OBJECTS_PER_STREAM) {
3405
+ this.flush();
3406
+ }
3407
+ }
3408
+ flush() {
3409
+ if (!this.pending.length) {
3410
+ return;
3411
+ }
3412
+ const objects = this.pending;
3413
+ this.pending = [];
3414
+ let offset = 0;
3415
+ const pairs = [];
3416
+ for (const {
3417
+ id,
3418
+ body
3419
+ } of objects) {
3420
+ pairs.push(id, offset);
3421
+ offset += body.length + 1;
3422
+ }
3423
+ const header = pairs.join(' ') + '\n';
3424
+ const stream = this.document.ref({
3425
+ Type: 'ObjStm',
3426
+ N: objects.length,
3427
+ First: header.length
3428
+ });
3429
+ stream.end(fromBinaryString(header + objects.map(o => o.body).join('\n')));
3430
+ objects.forEach(({
3431
+ id
3432
+ }, index) => {
3433
+ this.locations.set(id, [stream.id, index]);
3434
+ });
3435
+ }
3436
+ finalize() {
3437
+ const doc = this.document;
3438
+ this.flush();
3439
+ const xref = doc.ref({
3440
+ Type: 'XRef',
3441
+ Root: doc._root,
3442
+ Info: doc._info,
3443
+ ID: [doc._id, doc._id]
3444
+ });
3445
+ const xrefOffset = doc._offset;
3446
+ if (xrefOffset > 0xffffffff) {
3447
+ throw new Error('The objectStreams option cannot write files over 4 GB');
3448
+ }
3449
+ doc._offsets[xref.id - 1] = xrefOffset;
3450
+ const size = doc._offsets.length + 1;
3451
+ const table = new DataView(new ArrayBuffer(size * ENTRY_SIZE));
3452
+ const put = (id, type, field2, field3) => {
3453
+ const start = id * ENTRY_SIZE;
3454
+ table.setUint8(start, type);
3455
+ table.setUint32(start + 1, field2);
3456
+ table.setUint16(start + 5, field3);
3457
+ };
3458
+ put(0, FREE, 0, 0xffff);
3459
+ for (let id = 1; id < size; id++) {
3460
+ const location = this.locations.get(id);
3461
+ if (location) {
3462
+ put(id, COMPRESSED, ...location);
3463
+ } else {
3464
+ put(id, UNCOMPRESSED, doc._offsets[id - 1], 0);
3465
+ }
3466
+ }
3467
+ xref.data.Size = size;
3468
+ xref.data.W = ENTRY_WIDTHS;
3469
+ xref.end(new Uint8Array(table.buffer));
3470
+ doc._write('startxref');
3471
+ doc._write(`${xrefOffset}`);
3472
+ doc._write('%%EOF');
3473
+ }
3474
+ }
3475
+
1805
3476
  const {
1806
3477
  number: number$2
1807
3478
  } = PDFObject;
@@ -1840,16 +3511,16 @@ let PDFGradient$1 = class PDFGradient {
1840
3511
  }
1841
3512
  embed(m) {
1842
3513
  let fn;
1843
- const stopsLength = this.stops.length;
1844
- if (stopsLength === 0) {
3514
+ if (this.stops.length === 0) {
1845
3515
  return;
1846
3516
  }
1847
3517
  this.embedded = true;
1848
3518
  this.matrix = m;
1849
- const last = this.stops[stopsLength - 1];
3519
+ const last = this.stops[this.stops.length - 1];
1850
3520
  if (last[0] < 1) {
1851
3521
  this.stops.push([1, last[1], last[2]]);
1852
3522
  }
3523
+ const stopsLength = this.stops.length;
1853
3524
  const bounds = [];
1854
3525
  const encode = [];
1855
3526
  const stops = [];
@@ -2105,8 +3776,8 @@ var ColorMixin = {
2105
3776
  }
2106
3777
  const hex = parseInt(color.slice(1), 16);
2107
3778
  color = [hex >> 16, hex >> 8 & 0xff, hex & 0xff];
2108
- } else if (namedColors[color]) {
2109
- color = namedColors[color];
3779
+ } else if (namedColors[color.toLowerCase()]) {
3780
+ color = namedColors[color.toLowerCase()];
2110
3781
  } else if (this.spotColors[color]) {
2111
3782
  return this.spotColors[color];
2112
3783
  }
@@ -2633,18 +4304,15 @@ const runners = {
2633
4304
  return cy += a[3];
2634
4305
  },
2635
4306
  Q(doc, a) {
4307
+ doc.bezierCurveTo(cx + 2 / 3 * (a[0] - cx), cy + 2 / 3 * (a[1] - cy), a[2] + 2 / 3 * (a[0] - a[2]), a[3] + 2 / 3 * (a[1] - a[3]), a[2], a[3]);
2636
4308
  px = a[0];
2637
4309
  py = a[1];
2638
4310
  cx = a[2];
2639
4311
  cy = a[3];
2640
- return doc.quadraticCurveTo(a[0], a[1], cx, cy);
4312
+ return doc;
2641
4313
  },
2642
4314
  q(doc, a) {
2643
- doc.quadraticCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy);
2644
- px = cx + a[0];
2645
- py = cy + a[1];
2646
- cx += a[2];
2647
- return cy += a[3];
4315
+ return this.Q(doc, [a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy]);
2648
4316
  },
2649
4317
  T(doc, a) {
2650
4318
  if (px === null) {
@@ -2654,23 +4322,10 @@ const runners = {
2654
4322
  px = cx - (px - cx);
2655
4323
  py = cy - (py - cy);
2656
4324
  }
2657
- doc.quadraticCurveTo(px, py, a[0], a[1]);
2658
- px = cx - (px - cx);
2659
- py = cy - (py - cy);
2660
- cx = a[0];
2661
- return cy = a[1];
4325
+ return this.Q(doc, [px, py, a[0], a[1]]);
2662
4326
  },
2663
4327
  t(doc, a) {
2664
- if (px === null) {
2665
- px = cx;
2666
- py = cy;
2667
- } else {
2668
- px = cx - (px - cx);
2669
- py = cy - (py - cy);
2670
- }
2671
- doc.quadraticCurveTo(px, py, cx + a[0], cy + a[1]);
2672
- cx += a[0];
2673
- return cy += a[1];
4328
+ return this.T(doc, [cx + a[0], cy + a[1]]);
2674
4329
  },
2675
4330
  A(doc, a) {
2676
4331
  solveArc(doc, cx, cy, a);
@@ -3169,8 +4824,12 @@ const WIN_ANSI_MAP = {
3169
4824
  353: 154,
3170
4825
  376: 159,
3171
4826
  381: 142,
3172
- 382: 158
4827
+ 382: 158,
4828
+ 8208: 45,
4829
+ 8209: 45,
4830
+ 8239: 160
3173
4831
  };
4832
+ const outputCode = charCode => WIN_ANSI_MAP[charCode] || charCode;
3174
4833
  const characters = `\
3175
4834
  .notdef .notdef .notdef .notdef
3176
4835
  .notdef .notdef .notdef .notdef
@@ -3255,6 +4914,7 @@ class AFMFont {
3255
4914
  this.lineGap = this.bbox[3] - this.bbox[1] - (this.ascender - this.descender);
3256
4915
  const glyphNames = data.glyphNames.split(' ');
3257
4916
  this.glyphWidths = Object.fromEntries(glyphNames.map((name, index) => [name, data.glyphWidths[index]]));
4917
+ this.builtInEncoding = data.glyphCodes ? Object.fromEntries(data.glyphCodes.map((code, index) => [code, glyphNames[index]])) : null;
3258
4918
  this.kernPairs = {};
3259
4919
  for (let index = 0; index < data.kernPairs.length; index += 2) {
3260
4920
  const amount = data.kernPairs[index];
@@ -3269,23 +4929,31 @@ class AFMFont {
3269
4929
  }
3270
4930
  encodeText(text) {
3271
4931
  const res = [];
3272
- for (let i = 0, len = text.length; i < len; i++) {
3273
- let char = text.charCodeAt(i);
3274
- char = WIN_ANSI_MAP[char] || char;
3275
- res.push(char.toString(16));
4932
+ let i = 0;
4933
+ while (i < text.length) {
4934
+ const codePoint = text.codePointAt(i);
4935
+ const char = outputCode(codePoint);
4936
+ res.push(char.toString(16).padStart(2, '0'));
4937
+ i += codePoint > 0xffff ? 2 : 1;
3276
4938
  }
3277
4939
  return res;
3278
4940
  }
3279
4941
  glyphsForString(string) {
3280
4942
  const glyphs = [];
3281
- for (let i = 0, len = string.length; i < len; i++) {
3282
- const charCode = string.charCodeAt(i);
3283
- glyphs.push(this.characterToGlyph(charCode));
4943
+ let i = 0;
4944
+ while (i < string.length) {
4945
+ const codePoint = string.codePointAt(i);
4946
+ glyphs.push(this.characterToGlyph(codePoint));
4947
+ i += codePoint > 0xffff ? 2 : 1;
3284
4948
  }
3285
4949
  return glyphs;
3286
4950
  }
3287
4951
  characterToGlyph(character) {
3288
- return characters[WIN_ANSI_MAP[character] || character] || '.notdef';
4952
+ const code = outputCode(character);
4953
+ if (this.builtInEncoding) {
4954
+ return this.builtInEncoding[code] || '.notdef';
4955
+ }
4956
+ return characters[code] || '.notdef';
3289
4957
  }
3290
4958
  widthOfGlyph(glyph) {
3291
4959
  return this.glyphWidths[glyph] || 0;
@@ -3331,13 +4999,18 @@ class PDFFont {
3331
4999
  }
3332
5000
  }
3333
5001
 
5002
+ const afmFonts = new WeakMap();
3334
5003
  class StandardFont extends PDFFont {
3335
5004
  constructor(document, fontData, id) {
3336
5005
  super();
3337
5006
  this.document = document;
3338
5007
  this.name = fontData.name;
3339
5008
  this.id = id;
3340
- this.font = new AFMFont(fontData);
5009
+ this.font = afmFonts.get(fontData);
5010
+ if (!this.font) {
5011
+ this.font = new AFMFont(fontData);
5012
+ afmFonts.set(fontData, this.font);
5013
+ }
3341
5014
  ({
3342
5015
  ascender: this.ascender,
3343
5016
  descender: this.descender,
@@ -3388,6 +5061,23 @@ class StandardFont extends PDFFont {
3388
5061
  const toHex = function (num) {
3389
5062
  return `0000${num.toString(16)}`.slice(-4);
3390
5063
  };
5064
+ const WIN_ANSI_CODE_TO_UNICODE = Object.fromEntries(Object.entries(WIN_ANSI_MAP).map(([codePoint, code]) => [code, Number(codePoint)]));
5065
+ const UNDEFINED_WIN_ANSI_CODES = new Set([129, 141, 143, 144, 157]);
5066
+ const FIRST_WIN_ANSI_CHAR = 32;
5067
+ const LAST_WIN_ANSI_CHAR = 255;
5068
+ function unicodeForWinAnsiCode(code) {
5069
+ if (UNDEFINED_WIN_ANSI_CODES.has(code)) {
5070
+ return null;
5071
+ }
5072
+ return WIN_ANSI_CODE_TO_UNICODE[code] ?? code;
5073
+ }
5074
+ function completeSubsetOf(font) {
5075
+ const subset = font.createSubset();
5076
+ for (let gid = 0; gid < font.numGlyphs; gid++) {
5077
+ subset.includeGlyph(gid);
5078
+ }
5079
+ return subset;
5080
+ }
3391
5081
  class EmbeddedFont extends PDFFont {
3392
5082
  constructor(document, font, id) {
3393
5083
  super();
@@ -3485,13 +5175,31 @@ class EmbeddedFont extends PDFFont {
3485
5175
  const scale = size / 1000;
3486
5176
  return width * scale;
3487
5177
  }
3488
- embed() {
3489
- const isCFF = this.subset.cff != null;
5178
+ completeRef() {
5179
+ return this.completeDictionary != null ? this.completeDictionary : this.completeDictionary = this.document.ref();
5180
+ }
5181
+ finalize() {
5182
+ if (this.embedded) {
5183
+ return;
5184
+ }
5185
+ if (this.dictionary != null) {
5186
+ this.embed();
5187
+ }
5188
+ if (this.completeDictionary != null) {
5189
+ this.embedComplete();
5190
+ }
5191
+ this.embedded = true;
5192
+ }
5193
+ embedProgram(subset, complete) {
5194
+ const isCFF = subset.cff != null;
5195
+ const fontProgram = subset.encode();
3490
5196
  const fontFile = this.document.ref();
3491
5197
  if (isCFF) {
3492
5198
  fontFile.data.Subtype = 'CIDFontType0C';
5199
+ } else if (complete) {
5200
+ fontFile.data.Length1 = fontProgram.length;
3493
5201
  }
3494
- fontFile.end(this.subset.encode());
5202
+ fontFile.end(fontProgram);
3495
5203
  const familyClass = ((this.font['OS/2'] != null ? this.font['OS/2'].sFamilyClass : undefined) || 0) >> 8;
3496
5204
  let flags = 0;
3497
5205
  if (this.font.post.isFixedPitch) {
@@ -3507,8 +5215,9 @@ class EmbeddedFont extends PDFFont {
3507
5215
  if (this.font.head.macStyle.italic) {
3508
5216
  flags |= 1 << 6;
3509
5217
  }
5218
+ const postscriptName = this.font.postscriptName?.replaceAll(' ', '_');
3510
5219
  const tag = [1, 2, 3, 4, 5, 6].map(i => String.fromCharCode((this.id.charCodeAt(i) || 73) + 17)).join('');
3511
- const name = tag + '+' + this.font.postscriptName?.replaceAll(' ', '_');
5220
+ const name = complete ? postscriptName : `${tag}+${postscriptName}`;
3512
5221
  const {
3513
5222
  bbox
3514
5223
  } = this.font;
@@ -3529,7 +5238,7 @@ class EmbeddedFont extends PDFFont {
3529
5238
  } else {
3530
5239
  descriptor.data.FontFile2 = fontFile;
3531
5240
  }
3532
- if (this.document.subset && this.document.subset === 1) {
5241
+ if (!complete && this.document.subset && this.document.subset === 1) {
3533
5242
  const maxCID = this.widths.length - 1;
3534
5243
  const cidSetBuffer = new Uint8Array(Math.ceil((maxCID + 1) / 8));
3535
5244
  for (let cid = 0; cid <= maxCID; cid++) {
@@ -3543,6 +5252,18 @@ class EmbeddedFont extends PDFFont {
3543
5252
  descriptor.data.CIDSet = CIDSetRef;
3544
5253
  }
3545
5254
  descriptor.end();
5255
+ return {
5256
+ descriptor,
5257
+ name,
5258
+ isCFF
5259
+ };
5260
+ }
5261
+ embed() {
5262
+ const {
5263
+ descriptor,
5264
+ name,
5265
+ isCFF
5266
+ } = this.embedProgram(this.subset, false);
3546
5267
  const descendantFontData = {
3547
5268
  Type: 'Font',
3548
5269
  Subtype: 'CIDFontType0',
@@ -3571,6 +5292,84 @@ class EmbeddedFont extends PDFFont {
3571
5292
  };
3572
5293
  return this.dictionary.end();
3573
5294
  }
5295
+ embedComplete() {
5296
+ const {
5297
+ descriptor,
5298
+ name,
5299
+ isCFF
5300
+ } = this.embedProgram(completeSubsetOf(this.font), true);
5301
+ const widths = [];
5302
+ for (let gid = 0; gid < this.font.numGlyphs; gid++) {
5303
+ widths.push(this.font.getGlyph(gid).advanceWidth * this.scale);
5304
+ }
5305
+ const descendantFontData = {
5306
+ Type: 'Font',
5307
+ Subtype: isCFF ? 'CIDFontType0' : 'CIDFontType2',
5308
+ BaseFont: name,
5309
+ CIDSystemInfo: {
5310
+ Registry: new String('Adobe'),
5311
+ Ordering: new String('Identity'),
5312
+ Supplement: 0
5313
+ },
5314
+ FontDescriptor: descriptor,
5315
+ W: [0, widths]
5316
+ };
5317
+ if (!isCFF) {
5318
+ descendantFontData.CIDToGIDMap = 'Identity';
5319
+ }
5320
+ const descendantFont = this.document.ref(descendantFontData);
5321
+ descendantFont.end();
5322
+ this.completeDictionary.data = {
5323
+ Type: 'Font',
5324
+ Subtype: 'Type0',
5325
+ BaseFont: name,
5326
+ Encoding: this.winAnsiToGidCmap(),
5327
+ DescendantFonts: [descendantFont]
5328
+ };
5329
+ return this.completeDictionary.end();
5330
+ }
5331
+ winAnsiToGidCmap() {
5332
+ const cmap = this.document.ref();
5333
+ cmap.data.Type = 'CMap';
5334
+ const entries = [];
5335
+ for (let code = FIRST_WIN_ANSI_CHAR; code <= LAST_WIN_ANSI_CHAR; code++) {
5336
+ const codePoint = unicodeForWinAnsiCode(code);
5337
+ if (codePoint == null || !this.font.hasGlyphForCodePoint(codePoint)) {
5338
+ continue;
5339
+ }
5340
+ const gid = this.font.glyphForCodePoint(codePoint).id;
5341
+ entries.push(`<${code.toString(16).padStart(2, '0')}> ${gid}`);
5342
+ }
5343
+ const chunkSize = 100;
5344
+ const chunks = Math.ceil(entries.length / chunkSize);
5345
+ const ranges = [];
5346
+ for (let i = 0; i < chunks; i++) {
5347
+ const start = i * chunkSize;
5348
+ const end = Math.min((i + 1) * chunkSize, entries.length);
5349
+ ranges.push(`${end - start} begincidchar\n${entries.slice(start, end).join('\n')}\nendcidchar`);
5350
+ }
5351
+ cmap.end(`\
5352
+ /CIDInit /ProcSet findresource begin
5353
+ 12 dict begin
5354
+ begincmap
5355
+ /CIDSystemInfo <<
5356
+ /Registry (Adobe)
5357
+ /Ordering (Identity)
5358
+ /Supplement 0
5359
+ >> def
5360
+ /CMapName /Adobe-Identity-WinAnsi def
5361
+ /CMapType 1 def
5362
+ 1 begincodespacerange
5363
+ <20> <ff>
5364
+ endcodespacerange
5365
+ ${ranges.join('\n')}
5366
+ endcmap
5367
+ CMapName currentdict /CMap defineresource pop
5368
+ end
5369
+ end\
5370
+ `);
5371
+ return cmap;
5372
+ }
3574
5373
  toUnicodeCmap() {
3575
5374
  const cmap = this.document.ref();
3576
5375
  const entries = [];
@@ -3629,6 +5428,12 @@ const validateFontData = (fontData, expectedName) => {
3629
5428
  };
3630
5429
  const standardFonts = new Map();
3631
5430
  const isStandardFont = name => STANDARD_FONT_NAME_SET.has(name);
5431
+ const registerStdFonts = (...fontData) => {
5432
+ for (const data of fontData) {
5433
+ validateFontData(data);
5434
+ standardFonts.set(data.name, data);
5435
+ }
5436
+ };
3632
5437
  const registerStdFontLoaders = loaders => {
3633
5438
  for (const [name, loader] of Object.entries(loaders)) {
3634
5439
  if (!STANDARD_FONT_NAME_SET.has(name) || typeof loader !== 'function') {
@@ -3689,6 +5494,7 @@ const isEqualFont = (font1, font2) => {
3689
5494
  var FontsMixin = {
3690
5495
  initFonts(defaultFont = 'Helvetica', defaultFontFamily = null, defaultFontSize = 12) {
3691
5496
  this._fontFamilies = {};
5497
+ this._fontsBySource = new WeakMap();
3692
5498
  this._fontCount = 0;
3693
5499
  this._fontSource = defaultFont;
3694
5500
  this._fontFamily = defaultFontFamily;
@@ -3727,12 +5533,19 @@ var FontsMixin = {
3727
5533
  this._font = font;
3728
5534
  return this;
3729
5535
  }
5536
+ const bySource = !family && src !== null && typeof src === 'object';
5537
+ if (bySource && (font = this._fontsBySource.get(src))) {
5538
+ this._font = font;
5539
+ return this;
5540
+ }
3730
5541
  const id = `F${++this._fontCount}`;
3731
5542
  this._font = PDFFontFactory.open(this, src, family, id);
3732
5543
  if ((font = this._fontFamilies[this._font.name]) && isEqualFont(this._font, font)) {
3733
5544
  this._font = font;
5545
+ if (bySource) this._fontsBySource.set(src, font);
3734
5546
  return this;
3735
5547
  }
5548
+ if (bySource) this._fontsBySource.set(src, this._font);
3736
5549
  if (cacheKey) {
3737
5550
  this._fontFamilies[cacheKey] = this._font;
3738
5551
  }
@@ -3851,6 +5664,8 @@ class EventEmitter {
3851
5664
 
3852
5665
  const SOFT_HYPHEN = '\u00AD';
3853
5666
  const HYPHEN = '-';
5667
+ const WHITESPACE_BREAK = /[\s\u00AD\u200B]/;
5668
+ const isWhitespaceBreak = (text, bk) => bk.required || bk.position >= text.length || WHITESPACE_BREAK.test(text[bk.position - 1]);
3854
5669
  class LineWrapper extends EventEmitter {
3855
5670
  constructor(document, options) {
3856
5671
  super();
@@ -3868,6 +5683,7 @@ class LineWrapper extends EventEmitter {
3868
5683
  this.startY = this.document.y;
3869
5684
  this.column = 1;
3870
5685
  this.ellipsis = options.ellipsis;
5686
+ this.breakAtWhitespaceOnly = options.lineBreak === 'whitespace';
3871
5687
  this.continuedX = 0;
3872
5688
  this.indentApplied = false;
3873
5689
  this.features = options.features;
@@ -3936,6 +5752,9 @@ class LineWrapper extends EventEmitter {
3936
5752
  let last = null;
3937
5753
  const wordWidths = Object.create(null);
3938
5754
  while (bk = breaker.nextBreak()) {
5755
+ if (this.breakAtWhitespaceOnly && !isWhitespaceBreak(text, bk)) {
5756
+ continue;
5757
+ }
3939
5758
  var shouldContinue;
3940
5759
  let word = text.slice((last != null ? last.position : undefined) || 0, bk.position);
3941
5760
  let w = wordWidths[word] != null ? wordWidths[word] : wordWidths[word] = this.wordWidth(word);
@@ -3945,7 +5764,7 @@ class LineWrapper extends EventEmitter {
3945
5764
  while (word.length) {
3946
5765
  var l, mightGrow;
3947
5766
  if (w > this.spaceLeft) {
3948
- l = Math.ceil(this.spaceLeft / (w / word.length));
5767
+ l = Math.max(0, Math.ceil(this.spaceLeft / (w / word.length)));
3949
5768
  w = this.wordWidth(word.slice(0, l));
3950
5769
  mightGrow = w <= this.spaceLeft && l < word.length;
3951
5770
  } else {
@@ -4002,6 +5821,9 @@ class LineWrapper extends EventEmitter {
4002
5821
  if (options.ellipsis != null) {
4003
5822
  this.ellipsis = options.ellipsis;
4004
5823
  }
5824
+ if (options.lineBreak != null) {
5825
+ this.breakAtWhitespaceOnly = options.lineBreak === 'whitespace';
5826
+ }
4005
5827
  const nextY = document.y + document.currentLineHeight(true);
4006
5828
  if (document.y > this.maxY || nextY > this.maxY) {
4007
5829
  this.nextSection();
@@ -4171,7 +5993,7 @@ var TextMixin = {
4171
5993
  options = this._initOptions(x, y, options);
4172
5994
  text = text == null ? '' : `${text}`;
4173
5995
  if (options.wordSpacing) {
4174
- text = text.replace(/\s{2,}/g, ' ');
5996
+ text = text.replace(/[^\S\n]{2,}/g, ' ');
4175
5997
  }
4176
5998
  const addStructure = () => {
4177
5999
  if (options.structParent) {
@@ -4221,7 +6043,7 @@ var TextMixin = {
4221
6043
  let contentWidth = 0;
4222
6044
  string = String(string ?? '');
4223
6045
  if (options.wordSpacing) {
4224
- string = string.replace(/\s{2,}/g, ' ');
6046
+ string = string.replace(/[^\S\n]{2,}/g, ' ');
4225
6047
  }
4226
6048
  if (options.width) {
4227
6049
  let wrapper = new LineWrapper(this, options);
@@ -4237,13 +6059,18 @@ var TextMixin = {
4237
6059
  const spaceWidth = this.widthOfString(' ') + characterSpacing;
4238
6060
  wordSpacing = Math.max(0, (options.lineWidth - textWidth) / Math.max(1, words.length - 1) - spaceWidth);
4239
6061
  }
4240
- contentWidth = Math.max(contentWidth, options.textWidth + wordSpacing * (options.wordCount - 1) + characterSpacing * (text.length - 1));
6062
+ contentWidth = Math.max(contentWidth, this.widthOfString(text, options) + wordSpacing * (options.wordCount - 1));
4241
6063
  }
4242
6064
  });
4243
6065
  wrapper.wrap(string, options);
4244
6066
  } else {
4245
6067
  for (let line of string.split('\n')) {
4246
- const lineWidth = this.widthOfString(line, options);
6068
+ let lineWidth = this.widthOfString(line, options);
6069
+ if (options.wordSpacing) {
6070
+ const trimmed = line.trim();
6071
+ const space = /\s/g;
6072
+ while (space.test(trimmed)) lineWidth += options.wordSpacing;
6073
+ }
4247
6074
  this.y += lineHeight;
4248
6075
  contentWidth = Math.max(contentWidth, lineWidth);
4249
6076
  }
@@ -4310,6 +6137,7 @@ var TextMixin = {
4310
6137
  options = this._initOptions(options);
4311
6138
  options.height = Infinity;
4312
6139
  const lineGap = options.lineGap || this._lineGap || 0;
6140
+ if (!options.continued && options.width) this._wrapper = null;
4313
6141
  this._text(text, this.x, this.y, options, () => {
4314
6142
  this.y += this.currentLineHeight(true) + lineGap;
4315
6143
  });
@@ -4326,12 +6154,19 @@ var TextMixin = {
4326
6154
  const r = options.bulletRadius || unit / 3;
4327
6155
  const indent = options.textIndent || (listType === 'bullet' ? r * 5 : unit * 2);
4328
6156
  const itemIndent = options.bulletIndent || (listType === 'bullet' ? r * 8 : unit * 2);
6157
+ const {
6158
+ lineWidth,
6159
+ textWidth,
6160
+ wordCount,
6161
+ ...labelOptions
6162
+ } = options;
6163
+ labelOptions.align = 'left';
4329
6164
  let level = 1;
4330
6165
  const items = [];
4331
6166
  const levels = [];
4332
6167
  const numbers = [];
4333
6168
  var flatten = function (list) {
4334
- let n = 1;
6169
+ let n = level === 1 ? options.start ?? 1 : 1;
4335
6170
  for (let i = 0; i < list.length; i++) {
4336
6171
  const item = list[i];
4337
6172
  if (Array.isArray(item)) {
@@ -4385,7 +6220,7 @@ var TextMixin = {
4385
6220
  case 'numbered':
4386
6221
  case 'lettered':
4387
6222
  var text = formatListLabel(numbers[i - 1], listType);
4388
- this._fragment(text, this.x - indent, this.y, options);
6223
+ this._fragment(text, this.x - indent, this.y, labelOptions);
4389
6224
  break;
4390
6225
  }
4391
6226
  if (item && labelType && bodyType) {
@@ -4473,10 +6308,15 @@ var TextMixin = {
4473
6308
  switch (align) {
4474
6309
  case 'right':
4475
6310
  textWidth = this.widthOfString(text.replace(/\s+$/, ''), options);
6311
+ if (wordSpacing) {
6312
+ const gaps = text.trim().split(/\s+/).length - 1;
6313
+ textWidth += wordSpacing * gaps * horizontalScaling / 100;
6314
+ }
4476
6315
  x += options.lineWidth - textWidth;
4477
6316
  break;
4478
6317
  case 'center':
4479
- x += options.lineWidth / 2 - options.textWidth / 2;
6318
+ textWidth = options.textWidth - (characterSpacing + wordSpacing * options.wordCount) * horizontalScaling / 100;
6319
+ x += options.lineWidth / 2 - textWidth / 2;
4480
6320
  break;
4481
6321
  case 'justify':
4482
6322
  words = text.trim().split(/\s+/);
@@ -4518,16 +6358,19 @@ var TextMixin = {
4518
6358
  }
4519
6359
  dy = dy / 1000 * this._fontSize;
4520
6360
  }
4521
- const renderedWidth = options.textWidth + wordSpacing * (options.wordCount - 1) + characterSpacing * (text.length - 1);
6361
+ const lineTop = y + dy - this._font.ascender / 1000 * this._fontSize;
6362
+ const measuredWidth = this.widthOfString(text, options) - characterSpacing * (text.length - 1);
6363
+ const measuredWordCount = options.wordCount ?? (text.trim() ? text.trim().split(/\s+/).length : 0);
6364
+ const renderedWidth = measuredWidth + wordSpacing * (measuredWordCount - 1) + characterSpacing * (text.length - 1);
4522
6365
  if (options.link != null) {
4523
6366
  const linkOptions = {};
4524
6367
  if (this._currentStructureElement && this._currentStructureElement.dictionary.data.S === 'Link') {
4525
6368
  linkOptions.structParent = this._currentStructureElement;
4526
6369
  }
4527
- this.link(x, y, renderedWidth, this.currentLineHeight(), options.link, linkOptions);
6370
+ this.link(x, lineTop, renderedWidth, this.currentLineHeight(), options.link, linkOptions);
4528
6371
  }
4529
6372
  if (options.goTo != null) {
4530
- this.goTo(x, y, renderedWidth, this.currentLineHeight(), options.goTo);
6373
+ this.goTo(x, lineTop, renderedWidth, this.currentLineHeight(), options.goTo);
4531
6374
  }
4532
6375
  if (options.destination != null) {
4533
6376
  this.addNamedDestination(options.destination, 'XYZ', x, y, null);
@@ -4537,9 +6380,9 @@ var TextMixin = {
4537
6380
  if (!options.stroke) {
4538
6381
  this.strokeColor(...(this._fillColor || []));
4539
6382
  }
4540
- const lineWidth = this._fontSize < 10 ? 0.5 : Math.floor(this._fontSize / 10);
6383
+ const lineWidth = options.decorationThickness ?? (this._fontSize < 10 ? 0.5 : Math.floor(this._fontSize / 10));
4541
6384
  this.lineWidth(lineWidth);
4542
- let lineY = y + this.currentLineHeight() - lineWidth;
6385
+ let lineY = lineTop + this.currentLineHeight() - lineWidth + (options.underlineOffset ?? 0);
4543
6386
  this.moveTo(x, lineY);
4544
6387
  this.lineTo(x + renderedWidth, lineY);
4545
6388
  this.stroke();
@@ -4550,9 +6393,9 @@ var TextMixin = {
4550
6393
  if (!options.stroke) {
4551
6394
  this.strokeColor(...(this._fillColor || []));
4552
6395
  }
4553
- const lineWidth = this._fontSize < 10 ? 0.5 : Math.floor(this._fontSize / 10);
6396
+ const lineWidth = options.decorationThickness ?? (this._fontSize < 10 ? 0.5 : Math.floor(this._fontSize / 10));
4554
6397
  this.lineWidth(lineWidth);
4555
- let lineY = y + this.currentLineHeight() / 2;
6398
+ let lineY = lineTop + this.currentLineHeight() / 2;
4556
6399
  this.moveTo(x, lineY);
4557
6400
  this.lineTo(x + renderedWidth, lineY);
4558
6401
  this.stroke();
@@ -4813,12 +6656,11 @@ class PNGImage {
4813
6656
  }
4814
6657
  obj.data['Mask'] = mask;
4815
6658
  } else if (image.transparency.indexed) {
4816
- return this.loadIndexedAlphaChannel();
6659
+ this.loadIndexedAlphaChannel();
4817
6660
  } else if (hasAlphaChannel) {
4818
- return this.splitAlphaChannel();
4819
- }
4820
- if (isInterlaced && true) {
4821
- return this.decodeData();
6661
+ this.splitAlphaChannel();
6662
+ } else if (isInterlaced && true) {
6663
+ this.decodeData();
4822
6664
  }
4823
6665
  this.finalize();
4824
6666
  }
@@ -4839,52 +6681,46 @@ class PNGImage {
4839
6681
  }
4840
6682
  this.obj.end(this.imgData);
4841
6683
  this.image = null;
4842
- return this.imgData = null;
6684
+ this.imgData = null;
4843
6685
  }
4844
6686
  splitAlphaChannel() {
4845
- return this.image.decodePixels(pixels => {
4846
- let a, p;
4847
- const colorCount = this.image.colors;
4848
- const pixelCount = this.width * this.height;
4849
- const imgData = new Uint8Array(pixelCount * colorCount);
4850
- const alphaChannel = new Uint8Array(pixelCount);
4851
- let i = p = a = 0;
4852
- const len = pixels.length;
4853
- const skipByteCount = this.image.bits === 16 ? 1 : 0;
4854
- while (i < len) {
4855
- for (let colorIndex = 0; colorIndex < colorCount; colorIndex++) {
4856
- imgData[p++] = pixels[i++];
4857
- i += skipByteCount;
4858
- }
4859
- alphaChannel[a++] = pixels[i++];
6687
+ const pixels = this.image.decodePixelsSync();
6688
+ let a, p;
6689
+ const colorCount = this.image.colors;
6690
+ const pixelCount = this.width * this.height;
6691
+ const imgData = new Uint8Array(pixelCount * colorCount);
6692
+ const alphaChannel = new Uint8Array(pixelCount);
6693
+ let i = p = a = 0;
6694
+ const len = pixels.length;
6695
+ const skipByteCount = this.image.bits === 16 ? 1 : 0;
6696
+ while (i < len) {
6697
+ for (let colorIndex = 0; colorIndex < colorCount; colorIndex++) {
6698
+ imgData[p++] = pixels[i++];
4860
6699
  i += skipByteCount;
4861
6700
  }
4862
- this.imgData = zlib.deflateSync(imgData);
4863
- this.alphaChannel = zlib.deflateSync(alphaChannel);
4864
- return this.finalize();
4865
- });
6701
+ alphaChannel[a++] = pixels[i++];
6702
+ i += skipByteCount;
6703
+ }
6704
+ this.imgData = zlib.deflateSync(imgData);
6705
+ this.alphaChannel = zlib.deflateSync(alphaChannel);
4866
6706
  }
4867
6707
  loadIndexedAlphaChannel() {
4868
6708
  const transparency = this.image.transparency.indexed;
4869
6709
  const isInterlaced = this.image.interlaceMethod === 1;
4870
- return this.image.decodePixels(pixels => {
4871
- const alphaChannel = new Uint8Array(this.width * this.height);
4872
- let i = 0;
4873
- for (let j = 0, end = pixels.length; j < end; j++) {
4874
- alphaChannel[i++] = transparency[pixels[j]];
4875
- }
4876
- if (isInterlaced) {
4877
- this.imgData = zlib.deflateSync(pixels);
4878
- }
4879
- this.alphaChannel = zlib.deflateSync(alphaChannel);
4880
- return this.finalize();
4881
- });
6710
+ const pixels = this.image.decodePixelsSync();
6711
+ const alphaChannel = new Uint8Array(this.width * this.height);
6712
+ let i = 0;
6713
+ for (let j = 0, end = pixels.length; j < end; j++) {
6714
+ alphaChannel[i++] = transparency[pixels[j]];
6715
+ }
6716
+ if (isInterlaced) {
6717
+ this.imgData = zlib.deflateSync(pixels);
6718
+ }
6719
+ this.alphaChannel = zlib.deflateSync(alphaChannel);
4882
6720
  }
4883
6721
  decodeData() {
4884
- this.image.decodePixels(pixels => {
4885
- this.imgData = zlib.deflateSync(pixels);
4886
- this.finalize();
4887
- });
6722
+ const pixels = this.image.decodePixelsSync();
6723
+ this.imgData = zlib.deflateSync(pixels);
4888
6724
  }
4889
6725
  }
4890
6726
 
@@ -4967,11 +6803,14 @@ var ImagesMixin = {
4967
6803
  } else if (options.scale) {
4968
6804
  w = width * options.scale;
4969
6805
  h = height * options.scale;
4970
- } else if (options.fit) {
4971
- [bw, bh] = options.fit;
6806
+ } else if (options.fit || options.scaleDown) {
6807
+ [bw, bh] = options.fit || options.scaleDown;
4972
6808
  bp = bw / bh;
4973
6809
  ip = width / height;
4974
- if (ip > bp) {
6810
+ if (!options.fit && width <= bw && height <= bh) {
6811
+ w = width;
6812
+ h = height;
6813
+ } else if (ip > bp) {
4975
6814
  w = bw;
4976
6815
  h = bw / ip;
4977
6816
  } else {
@@ -4990,7 +6829,7 @@ var ImagesMixin = {
4990
6829
  h = bw / ip;
4991
6830
  }
4992
6831
  }
4993
- if (options.fit || options.cover) {
6832
+ if (options.fit || options.scaleDown || options.cover) {
4994
6833
  if (options.align === 'center') {
4995
6834
  x = x + bw / 2 - w / 2;
4996
6835
  } else if (options.align === 'right') {
@@ -5082,6 +6921,12 @@ var ImagesMixin = {
5082
6921
  if (options.opacity != null) {
5083
6922
  this._doOpacity(options.opacity, null);
5084
6923
  }
6924
+ if (options.flipH) {
6925
+ this.transform(-1, 0, 0, 1, 2 * x + w, 0);
6926
+ }
6927
+ if (options.flipV) {
6928
+ this.transform(1, 0, 0, -1, 0, 2 * y + h);
6929
+ }
5085
6930
  if (rotateAngle) {
5086
6931
  this.rotate(rotateAngle, {
5087
6932
  origin: [originX, originY]
@@ -5108,8 +6953,9 @@ var ImagesMixin = {
5108
6953
  };
5109
6954
 
5110
6955
  class PDFAnnotationReference {
5111
- constructor(annotationRef) {
6956
+ constructor(annotationRef, pageRef = annotationRef.document.page.dictionary) {
5112
6957
  this.annotationRef = annotationRef;
6958
+ this.pageRef = pageRef;
5113
6959
  }
5114
6960
  }
5115
6961
 
@@ -5137,7 +6983,7 @@ var AnnotationsMixin = {
5137
6983
  const ref = this.ref(annotations);
5138
6984
  this.page.annotations.push(ref);
5139
6985
  if (typeof structParent?.add === 'function') {
5140
- const annotRef = new PDFAnnotationReference(ref);
6986
+ const annotRef = new PDFAnnotationReference(ref, this.page.dictionary);
5141
6987
  structParent.add(annotRef);
5142
6988
  }
5143
6989
  ref.end();
@@ -5279,16 +7125,15 @@ var AnnotationsMixin = {
5279
7125
  }
5280
7126
  return this.annotate(x, y, w, h, annotationOptions);
5281
7127
  },
5282
- _convertRect(x1, y1, w, h) {
5283
- let y2 = y1;
5284
- y1 += h;
5285
- let x2 = x1 + w;
7128
+ _convertRect(x, y, w, h) {
5286
7129
  const [m0, m1, m2, m3, m4, m5] = this._ctm;
5287
- x1 = m0 * x1 + m2 * y1 + m4;
5288
- y1 = m1 * x1 + m3 * y1 + m5;
5289
- x2 = m0 * x2 + m2 * y2 + m4;
5290
- y2 = m1 * x2 + m3 * y2 + m5;
5291
- return [x1, y1, x2, y2];
7130
+ const ox = m0 * x + m2 * y + m4;
7131
+ const oy = m1 * x + m3 * y + m5;
7132
+ const wx = m0 * w;
7133
+ const wy = m1 * w;
7134
+ const hx = m2 * h;
7135
+ const hy = m3 * h;
7136
+ return [ox + (wx < 0 ? wx : 0) + (hx < 0 ? hx : 0), oy + (wy < 0 ? wy : 0) + (hy < 0 ? hy : 0), ox + (wx > 0 ? wx : 0) + (hx > 0 ? hx : 0), oy + (wy > 0 ? wy : 0) + (hy > 0 ? hy : 0)];
5292
7137
  }
5293
7138
  };
5294
7139
 
@@ -5571,11 +7416,10 @@ class PDFStructureElement {
5571
7416
  });
5572
7417
  }
5573
7418
  if (child instanceof PDFAnnotationReference) {
5574
- const pageRef = this.document.page.dictionary;
5575
7419
  const objr = {
5576
7420
  Type: 'OBJR',
5577
7421
  Obj: child.annotationRef,
5578
- Pg: pageRef
7422
+ Pg: child.pageRef
5579
7423
  };
5580
7424
  this.dictionary.data.K.push(objr);
5581
7425
  }
@@ -5776,7 +7620,8 @@ const FIELD_JUSTIFY = {
5776
7620
  };
5777
7621
  const VALUE_MAP = {
5778
7622
  value: 'V',
5779
- defaultValue: 'DV'
7623
+ defaultValue: 'DV',
7624
+ alternateName: 'TU'
5780
7625
  };
5781
7626
  const FORMAT_SPECIAL = {
5782
7627
  zip: '0',
@@ -5827,6 +7672,11 @@ function mapTypeAndFlags(type, userOptions, pdfObject) {
5827
7672
  pdfObject.Ff = flags;
5828
7673
  }
5829
7674
  }
7675
+ function mapVisibility(options, pdfObject) {
7676
+ if (options.hidden) {
7677
+ pdfObject.F = 6;
7678
+ }
7679
+ }
5830
7680
  function mapJustify(userOptions, pdfObject) {
5831
7681
  const result = FIELD_JUSTIFY[userOptions.align];
5832
7682
  if (typeof result === 'number' && result !== 0) {
@@ -5858,6 +7708,28 @@ function mapStrings(options, pdfObject) {
5858
7708
  pdfObject.MK.CA = new String(options.label);
5859
7709
  }
5860
7710
  }
7711
+ const ANNOTATION_ACTIONS = {
7712
+ onClick: 'U',
7713
+ onMouseDown: 'D',
7714
+ onMouseEnter: 'E',
7715
+ onMouseExit: 'X',
7716
+ onFocus: 'Fo',
7717
+ onBlur: 'Bl'
7718
+ };
7719
+ function mapActions(options, pdfObject) {
7720
+ for (const [option, key] of Object.entries(ANNOTATION_ACTIONS)) {
7721
+ const action = options[option];
7722
+ if (!action) {
7723
+ continue;
7724
+ }
7725
+ const js = typeof action === 'function' ? `(${action}).call(this);` : action;
7726
+ pdfObject.AA = pdfObject.AA ?? {};
7727
+ pdfObject.AA[key] = {
7728
+ S: 'JavaScript',
7729
+ JS: new String(js)
7730
+ };
7731
+ }
7732
+ }
5861
7733
  function mapFormat(options, pdfObject) {
5862
7734
  const f = options.format;
5863
7735
  if (f?.type) {
@@ -5897,16 +7769,20 @@ function mapFormat(options, pdfObject) {
5897
7769
  };
5898
7770
  }
5899
7771
  }
7772
+ function formFontRef(doc, font) {
7773
+ return doc._acroform.embedFonts && typeof font.completeRef === 'function' ? font.completeRef() : font.ref();
7774
+ }
5900
7775
  var AcroFormMixin = {
5901
- initForm() {
7776
+ initForm(options = {}) {
5902
7777
  if (!this._font) {
5903
7778
  throw new Error('Must set a font before calling initForm method');
5904
7779
  }
5905
7780
  this._acroform = {
5906
7781
  fonts: {},
5907
- defaultFont: this._font.name
7782
+ defaultFont: this._font.name,
7783
+ embedFonts: options.embedFonts === true
5908
7784
  };
5909
- this._acroform.fonts[this._font.id] = this._font.ref();
7785
+ this._acroform.fonts[this._font.id] = formFontRef(this, this._font);
5910
7786
  let data = {
5911
7787
  Fields: [],
5912
7788
  NeedAppearances: true,
@@ -5915,7 +7791,7 @@ var AcroFormMixin = {
5915
7791
  Font: {}
5916
7792
  }
5917
7793
  };
5918
- data.DR.Font[this._font.id] = this._font.ref();
7794
+ data.DR.Font[this._font.id] = formFontRef(this, this._font);
5919
7795
  const AcroForm = this.ref(data);
5920
7796
  this._root.data.AcroForm = AcroForm;
5921
7797
  return this;
@@ -5957,7 +7833,10 @@ var AcroFormMixin = {
5957
7833
  if (fieldDict.F === undefined) {
5958
7834
  fieldDict.F = 4;
5959
7835
  }
5960
- this.annotate(x, y, w, h, fieldDict);
7836
+ this.annotate(x, y, w, h, {
7837
+ ...fieldDict,
7838
+ structParent: options.structParent
7839
+ });
5961
7840
  let annotRef = this.page.annotations[this.page.annotations.length - 1];
5962
7841
  return this._addToParent(annotRef);
5963
7842
  },
@@ -5997,11 +7876,13 @@ var AcroFormMixin = {
5997
7876
  }
5998
7877
  const pdfObject = {};
5999
7878
  mapTypeAndFlags(type, options, pdfObject);
7879
+ mapVisibility(options, pdfObject);
6000
7880
  mapJustify(options, pdfObject);
6001
7881
  this._mapFont(options, pdfObject);
6002
7882
  mapStrings(options, pdfObject);
6003
7883
  this._mapColors(options, pdfObject);
6004
7884
  mapFormat(options, pdfObject);
7885
+ mapActions(options, pdfObject);
6005
7886
  pdfObject.T = new String(name);
6006
7887
  if (options.parent) {
6007
7888
  pdfObject.Parent = options.parent;
@@ -6028,14 +7909,17 @@ var AcroFormMixin = {
6028
7909
  _font
6029
7910
  } = this;
6030
7911
  if (_acroform.fonts[_font.id] == null) {
6031
- _acroform.fonts[_font.id] = _font.ref();
7912
+ _acroform.fonts[_font.id] = formFontRef(this, _font);
6032
7913
  }
6033
- if (_acroform.defaultFont !== _font.name) {
7914
+ const isDefaultFont = _acroform.defaultFont === _font.name;
7915
+ if (!isDefaultFont) {
6034
7916
  pdfObject.DR = {
6035
7917
  Font: {}
6036
7918
  };
7919
+ pdfObject.DR.Font[_font.id] = formFontRef(this, _font);
7920
+ }
7921
+ if (!isDefaultFont || options.fontSize != null) {
6037
7922
  const fontSize = options.fontSize || 0;
6038
- pdfObject.DR.Font[_font.id] = _font.ref();
6039
7923
  pdfObject.DA = new String(`/${_font.id} ${fontSize} Tf 0 g`);
6040
7924
  }
6041
7925
  }
@@ -6128,11 +8012,70 @@ var AttachmentsMixin = {
6128
8012
  }
6129
8013
  };
6130
8014
  function isEqual(a, b) {
6131
- 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());
8015
+ return a.Subtype === b.Subtype && a.Params.CheckSum.toString() === b.Params.CheckSum.toString() && a.Params.Size === b.Params.Size && isSameDate(a.Params.CreationDate, b.Params.CreationDate) && isSameDate(a.Params.ModDate, b.Params.ModDate);
8016
+ }
8017
+ function isSameDate(a, b) {
8018
+ if (a === undefined || b === undefined) return a === b;
8019
+ return a.getTime() === b.getTime();
6132
8020
  }
6133
8021
 
6134
- const ICC_PROFILE_PATH = new URL('./data/sRGB_IEC61966_2_1.icc', import.meta.url).href;
8022
+ const STYLES = {
8023
+ decimal: 'D',
8024
+ upperRoman: 'R',
8025
+ lowerRoman: 'r',
8026
+ upperAlpha: 'A',
8027
+ lowerAlpha: 'a'
8028
+ };
8029
+ var PageLabelsMixin = {
8030
+ addPageLabel(pageIndex, options = {}) {
8031
+ if (!Number.isInteger(pageIndex) || pageIndex < 0) {
8032
+ throw new Error(`addPageLabel(${pageIndex}) invalid, pageIndex must be a non-negative integer`);
8033
+ }
8034
+ const {
8035
+ style,
8036
+ prefix,
8037
+ start
8038
+ } = options;
8039
+ const label = {};
8040
+ if (style != null) {
8041
+ if (!Object.hasOwn(STYLES, style)) {
8042
+ throw new Error(`addPageLabel style ${style} invalid, must be one of ${Object.keys(STYLES).join(', ')}`);
8043
+ }
8044
+ label.S = STYLES[style];
8045
+ }
8046
+ if (prefix != null) {
8047
+ label.P = new String(prefix);
8048
+ }
8049
+ if (start != null) {
8050
+ if (!Number.isInteger(start) || start < 1) {
8051
+ throw new Error(`addPageLabel start ${start} invalid, must be a positive integer`);
8052
+ }
8053
+ label.St = start;
8054
+ }
8055
+ if (!this._root.data.PageLabels) {
8056
+ this._root.data.PageLabels = new PDFNumberTree({
8057
+ limits: false
8058
+ });
8059
+ this._root.data.PageLabels.add(0, {
8060
+ S: STYLES.decimal
8061
+ });
8062
+ }
8063
+ this._root.data.PageLabels.add(pageIndex, label);
8064
+ return this;
8065
+ }
8066
+ };
8067
+
8068
+ let iccProfilePath;
6135
8069
  let iccProfile;
8070
+ const getIccProfilePath = () => {
8071
+ if (iccProfilePath === undefined) {
8072
+ if (import.meta.url == null) {
8073
+ throw new Error('pdfkit cannot locate its sRGB ICC profile because import.meta.url ' + 'is not available in this build. Bundle pdfkit as ESM or mark it ' + 'as external in the bundler.');
8074
+ }
8075
+ iccProfilePath = new URL('./data/sRGB_IEC61966_2_1.icc', import.meta.url).href;
8076
+ }
8077
+ return iccProfilePath;
8078
+ };
6136
8079
  var PDFA = {
6137
8080
  initPDFA(pSubset) {
6138
8081
  if (pSubset.charAt(pSubset.length - 3) === '-') {
@@ -6149,7 +8092,7 @@ var PDFA = {
6149
8092
  },
6150
8093
  _addColorOutputIntent() {
6151
8094
  if (!iccProfile) {
6152
- iccProfile = fs.readFileSync(ICC_PROFILE_PATH);
8095
+ iccProfile = fs.readFileSync(getIccProfilePath());
6153
8096
  }
6154
8097
  const colorProfileRef = this.ref({
6155
8098
  Length: iccProfile.length,
@@ -6530,15 +8473,25 @@ function measure(row, rowIndex) {
6530
8473
  }
6531
8474
  this._rowHeights[rowIndex] = rowHeight;
6532
8475
  let newPage = false;
8476
+ let repeatHeaders = false;
6533
8477
  if (rowHeight > this.document.page.contentHeight) {
6534
8478
  console.warn(new Error(`Row ${rowIndex} requested more than the safe page height, row has been clamped`).stack.slice(7));
6535
8479
  this._rowHeights[rowIndex] = this.document.page.maxY() - this._rowYPos[rowIndex];
6536
8480
  } else if (this._rowYPos[rowIndex] + rowHeight >= this.document.page.maxY()) {
6537
- this._rowYPos[rowIndex] = this.document.page.margins.top;
8481
+ let top = this.document.page.margins.top;
8482
+ if (rowIndex >= this._headerRows) {
8483
+ const headerHeight = this._rowHeights.slice(0, this._headerRows).reduce((acc, height) => acc + height, 0);
8484
+ if (this._headerRows > 0 && rowHeight + headerHeight <= this.document.page.contentHeight) {
8485
+ top += headerHeight;
8486
+ repeatHeaders = true;
8487
+ }
8488
+ }
8489
+ this._rowYPos[rowIndex] = top;
6538
8490
  newPage = true;
6539
8491
  }
6540
8492
  return {
6541
8493
  newPage,
8494
+ repeatHeaders,
6542
8495
  toRender: toRender.map(cell => measureCell.call(this, cell, rowHeight))
6543
8496
  };
6544
8497
  }
@@ -6740,6 +8693,22 @@ function renderRow(row, rowIndex) {
6740
8693
  }
6741
8694
  return this._rowYPos[rowIndex] + this._rowHeights[rowIndex];
6742
8695
  }
8696
+ function renderHeaderRows(cells) {
8697
+ const doc = this.document;
8698
+ if (this._tableStruct) doc.markContent('Artifact', {
8699
+ type: 'Pagination'
8700
+ });
8701
+ cells.forEach(cell => {
8702
+ let y = doc.page.margins.top;
8703
+ for (let i = 0; i < cell.rowIndex; i++) y += this._rowHeights[i];
8704
+ renderCell.call(this, {
8705
+ ...cell,
8706
+ y,
8707
+ textY: y + cell.padding.top
8708
+ });
8709
+ });
8710
+ if (this._tableStruct) doc.endMarkedContent();
8711
+ }
6743
8712
  function renderCell(cell, rowStruct) {
6744
8713
  const cellRenderer = () => {
6745
8714
  if (cell.backgroundColor != null) {
@@ -6828,6 +8797,8 @@ class PDFTable {
6828
8797
  this.opts = Object.freeze(opts);
6829
8798
  normalizeTable.call(this);
6830
8799
  accommodateTable.call(this);
8800
+ this._headerRows = opts.headerRows ?? 0;
8801
+ this._headerCells = [];
6831
8802
  this._currRowIndex = 0;
6832
8803
  this._ended = false;
6833
8804
  if (opts.data) {
@@ -6844,9 +8815,14 @@ class PDFTable {
6844
8815
  if (this._currRowIndex === 0) ensure.call(this, row);
6845
8816
  const {
6846
8817
  newPage,
8818
+ repeatHeaders,
6847
8819
  toRender
6848
8820
  } = measure.call(this, row, this._currRowIndex);
6849
8821
  if (newPage) this.document.continueOnNewPage();
8822
+ if (repeatHeaders) renderHeaderRows.call(this, this._headerCells);
8823
+ if (this._currRowIndex < this._headerRows) {
8824
+ this._headerCells.push(...toRender);
8825
+ }
6850
8826
  const yPos = renderRow.call(this, toRender, this._currRowIndex);
6851
8827
  this.document.x = this._position.x;
6852
8828
  this.document.y = yPos;
@@ -6902,6 +8878,9 @@ class PDFMetadata {
6902
8878
  }
6903
8879
  }
6904
8880
 
8881
+ function escapeXML(value) {
8882
+ return String(value).replace(/[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu, '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;').replace(/\r/g, '&#xD;');
8883
+ }
6905
8884
  var MetadataMixin = {
6906
8885
  initMetadata() {
6907
8886
  this.metadata = new PDFMetadata();
@@ -6913,7 +8892,7 @@ var MetadataMixin = {
6913
8892
  this.appendXML(`
6914
8893
  <rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">
6915
8894
  <xmp:CreateDate>${this.info.CreationDate.toISOString().split('.')[0] + 'Z'}</xmp:CreateDate>
6916
- <xmp:CreatorTool>${this.info.Creator}</xmp:CreatorTool>
8895
+ <xmp:CreatorTool>${escapeXML(this.info.Creator)}</xmp:CreatorTool>
6917
8896
  </rdf:Description>
6918
8897
  `);
6919
8898
  if (this.info.Title || this.info.Author || this.info.Subject) {
@@ -6924,7 +8903,7 @@ var MetadataMixin = {
6924
8903
  this.appendXML(`
6925
8904
  <dc:title>
6926
8905
  <rdf:Alt>
6927
- <rdf:li xml:lang="x-default">${this.info.Title}</rdf:li>
8906
+ <rdf:li xml:lang="x-default">${escapeXML(this.info.Title)}</rdf:li>
6928
8907
  </rdf:Alt>
6929
8908
  </dc:title>
6930
8909
  `);
@@ -6933,7 +8912,7 @@ var MetadataMixin = {
6933
8912
  this.appendXML(`
6934
8913
  <dc:creator>
6935
8914
  <rdf:Seq>
6936
- <rdf:li>${this.info.Author}</rdf:li>
8915
+ <rdf:li>${escapeXML(this.info.Author)}</rdf:li>
6937
8916
  </rdf:Seq>
6938
8917
  </dc:creator>
6939
8918
  `);
@@ -6942,7 +8921,7 @@ var MetadataMixin = {
6942
8921
  this.appendXML(`
6943
8922
  <dc:description>
6944
8923
  <rdf:Alt>
6945
- <rdf:li xml:lang="x-default">${this.info.Subject}</rdf:li>
8924
+ <rdf:li xml:lang="x-default">${escapeXML(this.info.Subject)}</rdf:li>
6946
8925
  </rdf:Alt>
6947
8926
  </dc:description>
6948
8927
  `);
@@ -6953,10 +8932,10 @@ var MetadataMixin = {
6953
8932
  }
6954
8933
  this.appendXML(`
6955
8934
  <rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">
6956
- <pdf:Producer>${this.info.Producer}</pdf:Producer>`, false);
8935
+ <pdf:Producer>${escapeXML(this.info.Producer)}</pdf:Producer>`, false);
6957
8936
  if (this.info.Keywords) {
6958
8937
  this.appendXML(`
6959
- <pdf:Keywords>${this.info.Keywords}</pdf:Keywords>`, false);
8938
+ <pdf:Keywords>${escapeXML(this.info.Keywords)}</pdf:Keywords>`, false);
6960
8939
  }
6961
8940
  this.appendXML(`
6962
8941
  </rdf:Description>
@@ -7002,6 +8981,9 @@ class PDFDocument extends Readable {
7002
8981
  break;
7003
8982
  }
7004
8983
  this.compress = this.options.compress != null ? this.options.compress : true;
8984
+ if (options.objectStreams) {
8985
+ this._objectStreams = new PDFObjectStreams(this, options);
8986
+ }
7005
8987
  this._pageBuffer = [];
7006
8988
  this._pageBufferStart = 0;
7007
8989
  this._offsets = [];
@@ -7166,8 +9148,8 @@ class PDFDocument extends Readable {
7166
9148
  _refEnd(ref) {
7167
9149
  this._offsets[ref.id - 1] = ref.offset;
7168
9150
  if (--this._waiting === 0 && this._ended) {
7169
- this._finalize();
7170
9151
  this._ended = false;
9152
+ this._finalize();
7171
9153
  }
7172
9154
  }
7173
9155
  end() {
@@ -7210,6 +9192,11 @@ class PDFDocument extends Readable {
7210
9192
  }
7211
9193
  }
7212
9194
  _finalize() {
9195
+ if (this._objectStreams) {
9196
+ this._objectStreams.finalize();
9197
+ this.push(null);
9198
+ return;
9199
+ }
7213
9200
  const xRefOffset = this._offset;
7214
9201
  this._write('xref');
7215
9202
  this._write(`0 ${this._offsets.length + 1}`);
@@ -7252,26 +9239,39 @@ mixin(OutlineMixin);
7252
9239
  mixin(MarkingsMixin);
7253
9240
  mixin(AcroFormMixin);
7254
9241
  mixin(AttachmentsMixin);
9242
+ mixin(PageLabelsMixin);
7255
9243
  mixin(SubsetMixin);
7256
9244
  mixin(TableMixin);
7257
9245
 
7258
- const require$1 = createRequire(import.meta.url);
7259
- registerStdFontLoaders({
7260
- Courier: () => require$1('#standard-fonts/Courier'),
7261
- 'Courier-Bold': () => require$1('#standard-fonts/CourierBold'),
7262
- 'Courier-BoldOblique': () => require$1('#standard-fonts/CourierBoldOblique'),
7263
- 'Courier-Oblique': () => require$1('#standard-fonts/CourierOblique'),
7264
- Helvetica: () => require$1('#standard-fonts/Helvetica'),
7265
- 'Helvetica-Bold': () => require$1('#standard-fonts/HelveticaBold'),
7266
- 'Helvetica-BoldOblique': () => require$1('#standard-fonts/HelveticaBoldOblique'),
7267
- 'Helvetica-Oblique': () => require$1('#standard-fonts/HelveticaOblique'),
7268
- Symbol: () => require$1('#standard-fonts/Symbol'),
7269
- 'Times-Bold': () => require$1('#standard-fonts/TimesBold'),
7270
- 'Times-BoldItalic': () => require$1('#standard-fonts/TimesBoldItalic'),
7271
- 'Times-Italic': () => require$1('#standard-fonts/TimesItalic'),
7272
- 'Times-Roman': () => require$1('#standard-fonts/TimesRoman'),
7273
- ZapfDingbats: () => require$1('#standard-fonts/ZapfDingbats')
7274
- });
9246
+ const require$1 = createRequire(import.meta.url ?? '/');
9247
+ const loaders = {
9248
+ Courier: () => require$1('./standard-fonts/Courier.cjs'),
9249
+ 'Courier-Bold': () => require$1('./standard-fonts/CourierBold.cjs'),
9250
+ 'Courier-BoldOblique': () => require$1('./standard-fonts/CourierBoldOblique.cjs'),
9251
+ 'Courier-Oblique': () => require$1('./standard-fonts/CourierOblique.cjs'),
9252
+ Helvetica: () => require$1('./standard-fonts/Helvetica.cjs'),
9253
+ 'Helvetica-Bold': () => require$1('./standard-fonts/HelveticaBold.cjs'),
9254
+ 'Helvetica-BoldOblique': () => require$1('./standard-fonts/HelveticaBoldOblique.cjs'),
9255
+ 'Helvetica-Oblique': () => require$1('./standard-fonts/HelveticaOblique.cjs'),
9256
+ Symbol: () => require$1('./standard-fonts/Symbol.cjs'),
9257
+ 'Times-Bold': () => require$1('./standard-fonts/TimesBold.cjs'),
9258
+ 'Times-BoldItalic': () => require$1('./standard-fonts/TimesBoldItalic.cjs'),
9259
+ 'Times-Italic': () => require$1('./standard-fonts/TimesItalic.cjs'),
9260
+ 'Times-Roman': () => require$1('./standard-fonts/TimesRoman.cjs'),
9261
+ ZapfDingbats: () => require$1('./standard-fonts/ZapfDingbats.cjs')
9262
+ };
9263
+ registerStdFontLoaders(Object.fromEntries(Object.entries(loaders).map(([name, load]) => [name, () => {
9264
+ try {
9265
+ return load();
9266
+ } catch (error) {
9267
+ if (error?.code !== 'MODULE_NOT_FOUND') {
9268
+ throw error;
9269
+ }
9270
+ throw new Error(`Cannot load the standard font "${name}" from pdfkit's package ` + 'directory, which is not available once pdfkit is bundled ' + 'into another file. Either mark pdfkit as external in the ' + 'bundler, or import the fonts the document uses from ' + '"pdfkit/standard-fonts/<Name>" and pass them to ' + 'registerStdFonts() before creating the document.', {
9271
+ cause: error
9272
+ });
9273
+ }
9274
+ }])));
7275
9275
 
7276
- export { LineWrapper, PDFDocument, PDFDocument as default, registerFile };
9276
+ export { LineWrapper, PAGE_SIZES, PDFDocument, PDFDocument as default, registerFile, registerStdFonts };
7277
9277
  //# sourceMappingURL=pdfkit.node.mjs.map