Explorar el Código

PDF.js version 3.0.279 - See https://github.com/mozilla/pdf.js/releases/tag/v3.0.279

pdfjsbot hace 2 años
padre
commit
f6eefc6592
Se han modificado 100 ficheros con 914 adiciones y 7943 borrados
  1. 0 14
      bower.json
  2. 38 271
      build/pdf.js
  3. 0 0
      build/pdf.js.map
  4. 0 0
      build/pdf.min.js
  5. 15 34
      build/pdf.sandbox.js
  6. 0 0
      build/pdf.sandbox.js.map
  7. 0 0
      build/pdf.sandbox.min.js
  8. 40 243
      build/pdf.worker.js
  9. 0 0
      build/pdf.worker.js.map
  10. 0 0
      build/pdf.worker.min.js
  11. 17 252
      image_decoders/pdf.image_decoders.js
  12. 0 0
      image_decoders/pdf.image_decoders.js.map
  13. 0 0
      image_decoders/pdf.image_decoders.min.js
  14. 139 272
      legacy/build/pdf.js
  15. 0 0
      legacy/build/pdf.js.map
  16. 0 0
      legacy/build/pdf.min.js
  17. 16 40
      legacy/build/pdf.sandbox.js
  18. 0 0
      legacy/build/pdf.sandbox.js.map
  19. 0 0
      legacy/build/pdf.sandbox.min.js
  20. 56 248
      legacy/build/pdf.worker.js
  21. 0 0
      legacy/build/pdf.worker.js.map
  22. 0 0
      legacy/build/pdf.worker.min.js
  23. 134 266
      legacy/image_decoders/pdf.image_decoders.js
  24. 0 0
      legacy/image_decoders/pdf.image_decoders.js.map
  25. 0 0
      legacy/image_decoders/pdf.image_decoders.min.js
  26. 68 22
      legacy/web/pdf_viewer.css
  27. 41 250
      legacy/web/pdf_viewer.js
  28. 0 0
      legacy/web/pdf_viewer.js.map
  29. 3 228
      lib/core/annotation.js
  30. 1 18
      lib/core/arithmetic_decoder.js
  31. 0 23
      lib/core/ascii_85_stream.js
  32. 0 13
      lib/core/ascii_hex_stream.js
  33. 0 24
      lib/core/base_stream.js
  34. 0 64
      lib/core/bidi.js
  35. 21 264
      lib/core/catalog.js
  36. 0 173
      lib/core/ccitt.js
  37. 0 12
      lib/core/ccitt_stream.js
  38. 20 28
      lib/core/cff_font.js
  39. 0 4
      lib/core/cff_parser.js
  40. 6 140
      lib/core/chunked_stream.js
  41. 0 3
      lib/core/cleanup_helper.js
  42. 0 7
      lib/core/cmap.js
  43. 4 204
      lib/core/colorspace.js
  44. 4 118
      lib/core/core_utils.js
  45. 27 99
      lib/core/crypto.js
  46. 0 19
      lib/core/dataset_reader.js
  47. 0 46
      lib/core/decode_stream.js
  48. 5 18
      lib/core/decrypt_stream.js
  49. 1 29
      lib/core/default_appearance.js
  50. 22 244
      lib/core/document.js
  51. 0 8
      lib/core/encodings.js
  52. 11 243
      lib/core/evaluator.js
  53. 0 23
      lib/core/file_spec.js
  54. 0 3
      lib/core/flate_stream.js
  55. 8 187
      lib/core/font_renderer.js
  56. 11 234
      lib/core/fonts.js
  57. 0 5
      lib/core/fonts_utils.js
  58. 6 224
      lib/core/function.js
  59. 0 109
      lib/core/glyf.js
  60. 0 2
      lib/core/glyphlist.js
  61. 10 131
      lib/core/image.js
  62. 0 89
      lib/core/image_utils.js
  63. 20 224
      lib/core/jbig2.js
  64. 0 17
      lib/core/jbig2_stream.js
  65. 0 20
      lib/core/jpeg_stream.js
  66. 19 218
      lib/core/jpg.js
  67. 23 240
      lib/core/jpx.js
  68. 0 15
      lib/core/jpx_stream.js
  69. 1 24
      lib/core/lzw_stream.js
  70. 0 31
      lib/core/metadata_parser.js
  71. 0 2
      lib/core/metrics.js
  72. 3 42
      lib/core/name_number_tree.js
  73. 2 32
      lib/core/object_loader.js
  74. 3 27
      lib/core/opentype_file_builder.js
  75. 11 134
      lib/core/operator_list.js
  76. 19 250
      lib/core/parser.js
  77. 17 173
      lib/core/pattern.js
  78. 4 63
      lib/core/pdf_manager.js
  79. 6 57
      lib/core/predictor_stream.js
  80. 1 93
      lib/core/primitives.js
  81. 0 47
      lib/core/ps_parser.js
  82. 0 11
      lib/core/run_length_stream.js
  83. 18 4
      lib/core/standard_fonts.js
  84. 0 26
      lib/core/stream.js
  85. 0 81
      lib/core/struct_tree.js
  86. 0 23
      lib/core/to_unicode_map.js
  87. 7 87
      lib/core/type1_font.js
  88. 6 155
      lib/core/type1_parser.js
  89. 0 22
      lib/core/unicode.js
  90. 29 133
      lib/core/worker.js
  91. 0 31
      lib/core/worker_stream.js
  92. 0 60
      lib/core/writer.js
  93. 0 165
      lib/core/xfa/bind.js
  94. 0 56
      lib/core/xfa/builder.js
  95. 1 265
      lib/core/xfa/config.js
  96. 0 43
      lib/core/xfa/connection_set.js
  97. 0 18
      lib/core/xfa/data.js
  98. 0 17
      lib/core/xfa/datasets.js
  99. 0 45
      lib/core/xfa/factory.js
  100. 0 44
      lib/core/xfa/fonts.js

+ 0 - 14
bower.json

@@ -1,14 +0,0 @@
-{
-  "name": "pdfjs-dist",
-  "version": "2.16.105",
-  "main": [
-    "build/pdf.js",
-    "build/pdf.worker.js"
-  ],
-  "ignore": [],
-  "keywords": [
-    "Mozilla",
-    "pdf",
-    "pdf.js"
-  ]
-}

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 38 - 271
build/pdf.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
build/pdf.js.map


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
build/pdf.min.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 15 - 34
build/pdf.sandbox.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
build/pdf.sandbox.js.map


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
build/pdf.sandbox.min.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 40 - 243
build/pdf.worker.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
build/pdf.worker.js.map


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
build/pdf.worker.min.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 17 - 252
image_decoders/pdf.image_decoders.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
image_decoders/pdf.image_decoders.js.map


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
image_decoders/pdf.image_decoders.min.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 139 - 272
legacy/build/pdf.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
legacy/build/pdf.js.map


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
legacy/build/pdf.min.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 16 - 40
legacy/build/pdf.sandbox.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
legacy/build/pdf.sandbox.js.map


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
legacy/build/pdf.sandbox.min.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 56 - 248
legacy/build/pdf.worker.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
legacy/build/pdf.worker.js.map


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
legacy/build/pdf.worker.min.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 134 - 266
legacy/image_decoders/pdf.image_decoders.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
legacy/image_decoders/pdf.image_decoders.js.map


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
legacy/image_decoders/pdf.image_decoders.min.js


+ 68 - 22
legacy/web/pdf_viewer.css

@@ -21,7 +21,7 @@
   right: 0;
   bottom: 0;
   overflow: hidden;
-  opacity: 0.2;
+  opacity: 0.25;
   line-height: 1;
   -webkit-text-size-adjust: none;
      -moz-text-size-adjust: none;
@@ -73,11 +73,13 @@
 }
 
 .textLayer ::-moz-selection {
-  background: rgba(0, 0, 255, 1);
+  background: blue;
+  background: AccentColor;
 }
 
 .textLayer ::selection {
-  background: rgba(0, 0, 255, 1);
+  background: blue;
+  background: AccentColor;
 }
 
 /* Avoids https://github.com/mozilla/pdf.js/issues/13840 in Chrome */
@@ -109,9 +111,20 @@
 
 :root {
   --annotation-unfocused-field-background: url("data:image/svg+xml;charset=UTF-8,<svg width='1px' height='1px' xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' style='fill:rgba(0, 54, 255, 0.13);'/></svg>");
+  --input-focus-border-color: Highlight;
+  --input-focus-outline: 1px solid Canvas;
+  --input-unfocused-border-color: transparent;
+  --input-disabled-border-color: transparent;
+  --input-hover-border-color: black;
 }
 
 @media (forced-colors: active) {
+  :root {
+    --input-focus-border-color: CanvasText;
+    --input-unfocused-border-color: ActiveText;
+    --input-disabled-border-color: GrayText;
+    --input-hover-border-color: Highlight;
+  }
   .annotationLayer .textWidgetAnnotation input:required,
   .annotationLayer .textWidgetAnnotation textarea:required,
   .annotationLayer .choiceWidgetAnnotation select:required,
@@ -172,7 +185,7 @@
 .annotationLayer .buttonWidgetAnnotation.checkBox input,
 .annotationLayer .buttonWidgetAnnotation.radioButton input {
   background-image: var(--annotation-unfocused-field-background);
-  border: 1px solid transparent;
+  border: 2px solid var(--input-unfocused-border-color);
   box-sizing: border-box;
   font: calc(9px * var(--scale-factor)) sans-serif;
   height: 100%;
@@ -207,7 +220,7 @@
 .annotationLayer .buttonWidgetAnnotation.checkBox input[disabled],
 .annotationLayer .buttonWidgetAnnotation.radioButton input[disabled] {
   background: none;
-  border: 1px solid transparent;
+  border: 2px solid var(--input-disabled-border-color);
   cursor: not-allowed;
 }
 
@@ -216,24 +229,39 @@
 .annotationLayer .choiceWidgetAnnotation select:hover,
 .annotationLayer .buttonWidgetAnnotation.checkBox input:hover,
 .annotationLayer .buttonWidgetAnnotation.radioButton input:hover {
-  border: 1px solid rgba(0, 0, 0, 1);
+  border: 2px solid var(--input-hover-border-color);
+}
+.annotationLayer .textWidgetAnnotation input:hover,
+.annotationLayer .textWidgetAnnotation textarea:hover,
+.annotationLayer .choiceWidgetAnnotation select:hover,
+.annotationLayer .buttonWidgetAnnotation.checkBox input:hover {
+  border-radius: 2px;
 }
 
 .annotationLayer .textWidgetAnnotation input:focus,
 .annotationLayer .textWidgetAnnotation textarea:focus,
 .annotationLayer .choiceWidgetAnnotation select:focus {
   background: none;
-  border: 1px solid transparent;
+  border: 2px solid var(--input-focus-border-color);
+  border-radius: 2px;
+  outline: var(--input-focus-outline);
 }
 
-.annotationLayer .textWidgetAnnotation input :focus,
-.annotationLayer .textWidgetAnnotation textarea :focus,
-.annotationLayer .choiceWidgetAnnotation select :focus,
 .annotationLayer .buttonWidgetAnnotation.checkBox :focus,
 .annotationLayer .buttonWidgetAnnotation.radioButton :focus {
   background-image: none;
   background-color: transparent;
-  outline: auto;
+}
+
+.annotationLayer .buttonWidgetAnnotation.checkBox :focus {
+  border: 2px solid var(--input-focus-border-color);
+  border-radius: 2px;
+  outline: var(--input-focus-outline);
+}
+
+.annotationLayer .buttonWidgetAnnotation.radioButton :focus {
+  border: 2px solid var(--input-focus-border-color);
+  outline: var(--input-focus-outline);
 }
 
 .annotationLayer .buttonWidgetAnnotation.checkBox input:checked:before,
@@ -387,14 +415,22 @@
 
 :root {
   --xfa-unfocused-field-background: url("data:image/svg+xml;charset=UTF-8,<svg width='1px' height='1px' xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' style='fill:rgba(0, 54, 255, 0.13);'/></svg>");
+  --xfa-focus-outline: auto;
 }
 
 @media (forced-colors: active) {
+  :root {
+    --xfa-focus-outline: 2px solid CanvasText;
+  }
   .xfaLayer *:required {
     outline: 1.5px solid selectedItem;
   }
 }
 
+.xfaLayer {
+  background-color: transparent;
+}
+
 .xfaLayer .highlight {
   margin: -1px;
   padding: 1px;
@@ -422,14 +458,6 @@
   background-color: rgba(203, 223, 203, 1);
 }
 
-.xfaLayer ::-moz-selection {
-  background: rgba(0, 0, 255, 1);
-}
-
-.xfaLayer ::selection {
-  background: rgba(0, 0, 255, 1);
-}
-
 .xfaPage {
   overflow: hidden;
   position: relative;
@@ -572,13 +600,13 @@
 .xfaSelect:focus {
   background-image: none;
   background-color: transparent;
-  outline: auto;
+  outline: var(--xfa-focus-outline);
   outline-offset: -1px;
 }
 
 .xfaCheckbox:focus,
 .xfaRadio:focus {
-  outline: auto;
+  outline: var(--xfa-focus-outline);
 }
 
 .xfaTextfield,
@@ -591,6 +619,12 @@
   background-image: var(--xfa-unfocused-field-background);
 }
 
+.xfaSelect {
+  padding-left: 2px;
+  padding-right: 2px;
+  padding-inline: 2px;
+}
+
 .xfaTop > .xfaTextfield,
 .xfaTop > .xfaSelect,
 .xfaBottom > .xfaTextfield,
@@ -727,6 +761,7 @@
   --hover-outline: dashed 2px blue;
   --freetext-line-height: 1.35;
   --freetext-padding: 2px;
+  --editorFreeText-editing-cursor: text;
   --editorInk-editing-cursor: pointer;
 }
 
@@ -754,6 +789,16 @@
   left: 0;
   font-size: calc(100px * var(--scale-factor));
   transform-origin: 0 0;
+  cursor: auto;
+  z-index: 20000;
+}
+
+.annotationEditorLayer.freeTextEditing {
+  cursor: var(--editorFreeText-editing-cursor);
+}
+
+.annotationEditorLayer.inkEditing {
+  cursor: var(--editorInk-editing-cursor);
 }
 
 .annotationEditorLayer .selectedEditor {
@@ -772,6 +817,7 @@
   z-index: 1;
   transform-origin: 0 0;
   touch-action: none;
+  cursor: auto;
 }
 
 .annotationEditorLayer .freeTextEditor .internal {
@@ -836,7 +882,7 @@
 
 .annotationEditorLayer .inkEditor.editing {
   resize: none;
-  cursor: var(--editorInk-editing-cursor), pointer;
+  cursor: inherit;
 }
 
 .annotationEditorLayer .inkEditor .inkEditorCanvas {

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 41 - 250
legacy/web/pdf_viewer.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
legacy/web/pdf_viewer.js.map


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 3 - 228
lib/core/annotation.js


+ 1 - 18
lib/core/arithmetic_decoder.js

@@ -261,7 +261,6 @@ const QeTable = [{
   nlps: 46,
   switchFlag: 0
 }];
-
 class ArithmeticDecoder {
   constructor(data, start, end) {
     this.data = data;
@@ -275,11 +274,9 @@ class ArithmeticDecoder {
     this.ct -= 7;
     this.a = 0x8000;
   }
-
   byteIn() {
     const data = this.data;
     let bp = this.bp;
-
     if (data[bp] === 0xff) {
       if (data[bp + 1] > 0x8f) {
         this.clow += 0xff00;
@@ -296,21 +293,18 @@ class ArithmeticDecoder {
       this.ct = 8;
       this.bp = bp;
     }
-
     if (this.clow > 0xffff) {
       this.chigh += this.clow >> 16;
       this.clow &= 0xffff;
     }
   }
-
   readBit(contexts, pos) {
     let cx_index = contexts[pos] >> 1,
-        cx_mps = contexts[pos] & 1;
+      cx_mps = contexts[pos] & 1;
     const qeTableIcx = QeTable[cx_index];
     const qeIcx = qeTableIcx.qe;
     let d;
     let a = this.a - qeIcx;
-
     if (this.chigh < qeIcx) {
       if (a < qeIcx) {
         a = qeIcx;
@@ -319,51 +313,40 @@ class ArithmeticDecoder {
       } else {
         a = qeIcx;
         d = 1 ^ cx_mps;
-
         if (qeTableIcx.switchFlag === 1) {
           cx_mps = d;
         }
-
         cx_index = qeTableIcx.nlps;
       }
     } else {
       this.chigh -= qeIcx;
-
       if ((a & 0x8000) !== 0) {
         this.a = a;
         return cx_mps;
       }
-
       if (a < qeIcx) {
         d = 1 ^ cx_mps;
-
         if (qeTableIcx.switchFlag === 1) {
           cx_mps = d;
         }
-
         cx_index = qeTableIcx.nlps;
       } else {
         d = cx_mps;
         cx_index = qeTableIcx.nmps;
       }
     }
-
     do {
       if (this.ct === 0) {
         this.byteIn();
       }
-
       a <<= 1;
       this.chigh = this.chigh << 1 & 0xffff | this.clow >> 15 & 1;
       this.clow = this.clow << 1 & 0xffff;
       this.ct--;
     } while ((a & 0x8000) === 0);
-
     this.a = a;
     contexts[pos] = cx_index << 1 | cx_mps;
     return d;
   }
-
 }
-
 exports.ArithmeticDecoder = ArithmeticDecoder;

+ 0 - 23
lib/core/ascii_85_stream.js

@@ -25,92 +25,69 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.Ascii85Stream = void 0;
-
 var _decode_stream = require("./decode_stream.js");
-
 var _core_utils = require("./core_utils.js");
-
 class Ascii85Stream extends _decode_stream.DecodeStream {
   constructor(str, maybeLength) {
     if (maybeLength) {
       maybeLength *= 0.8;
     }
-
     super(maybeLength);
     this.str = str;
     this.dict = str.dict;
     this.input = new Uint8Array(5);
   }
-
   readBlock() {
     const TILDA_CHAR = 0x7e;
     const Z_LOWER_CHAR = 0x7a;
     const EOF = -1;
     const str = this.str;
     let c = str.getByte();
-
     while ((0, _core_utils.isWhiteSpace)(c)) {
       c = str.getByte();
     }
-
     if (c === EOF || c === TILDA_CHAR) {
       this.eof = true;
       return;
     }
-
     const bufferLength = this.bufferLength;
     let buffer, i;
-
     if (c === Z_LOWER_CHAR) {
       buffer = this.ensureBuffer(bufferLength + 4);
-
       for (i = 0; i < 4; ++i) {
         buffer[bufferLength + i] = 0;
       }
-
       this.bufferLength += 4;
     } else {
       const input = this.input;
       input[0] = c;
-
       for (i = 1; i < 5; ++i) {
         c = str.getByte();
-
         while ((0, _core_utils.isWhiteSpace)(c)) {
           c = str.getByte();
         }
-
         input[i] = c;
-
         if (c === EOF || c === TILDA_CHAR) {
           break;
         }
       }
-
       buffer = this.ensureBuffer(bufferLength + i - 1);
       this.bufferLength += i - 1;
-
       if (i < 5) {
         for (; i < 5; ++i) {
           input[i] = 0x21 + 84;
         }
-
         this.eof = true;
       }
-
       let t = 0;
-
       for (i = 0; i < 5; ++i) {
         t = t * 85 + (input[i] - 0x21);
       }
-
       for (i = 3; i >= 0; --i) {
         buffer[bufferLength + i] = t & 0xff;
         t >>= 8;
       }
     }
   }
-
 }
-
 exports.Ascii85Stream = Ascii85Stream;

+ 0 - 13
lib/core/ascii_hex_stream.js

@@ -25,38 +25,30 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.AsciiHexStream = void 0;
-
 var _decode_stream = require("./decode_stream.js");
-
 class AsciiHexStream extends _decode_stream.DecodeStream {
   constructor(str, maybeLength) {
     if (maybeLength) {
       maybeLength *= 0.5;
     }
-
     super(maybeLength);
     this.str = str;
     this.dict = str.dict;
     this.firstDigit = -1;
   }
-
   readBlock() {
     const UPSTREAM_BLOCK_SIZE = 8000;
     const bytes = this.str.getBytes(UPSTREAM_BLOCK_SIZE);
-
     if (!bytes.length) {
       this.eof = true;
       return;
     }
-
     const maxDecodeLength = bytes.length + 1 >> 1;
     const buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);
     let bufferLength = this.bufferLength;
     let firstDigit = this.firstDigit;
-
     for (const ch of bytes) {
       let digit;
-
       if (ch >= 0x30 && ch <= 0x39) {
         digit = ch & 0x0f;
       } else if (ch >= 0x41 && ch <= 0x46 || ch >= 0x61 && ch <= 0x66) {
@@ -67,7 +59,6 @@ class AsciiHexStream extends _decode_stream.DecodeStream {
       } else {
         continue;
       }
-
       if (firstDigit < 0) {
         firstDigit = digit;
       } else {
@@ -75,16 +66,12 @@ class AsciiHexStream extends _decode_stream.DecodeStream {
         firstDigit = -1;
       }
     }
-
     if (firstDigit >= 0 && this.eof) {
       buffer[bufferLength++] = firstDigit << 4;
       firstDigit = -1;
     }
-
     this.firstDigit = firstDigit;
     this.bufferLength = bufferLength;
   }
-
 }
-
 exports.AsciiHexStream = AsciiHexStream;

+ 0 - 24
lib/core/base_stream.js

@@ -25,63 +25,48 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.BaseStream = void 0;
-
 var _util = require("../shared/util.js");
-
 class BaseStream {
   constructor() {
     if (this.constructor === BaseStream) {
       (0, _util.unreachable)("Cannot initialize BaseStream.");
     }
   }
-
   get length() {
     (0, _util.unreachable)("Abstract getter `length` accessed");
   }
-
   get isEmpty() {
     (0, _util.unreachable)("Abstract getter `isEmpty` accessed");
   }
-
   get isDataLoaded() {
     return (0, _util.shadow)(this, "isDataLoaded", true);
   }
-
   getByte() {
     (0, _util.unreachable)("Abstract method `getByte` called");
   }
-
   getBytes(length) {
     (0, _util.unreachable)("Abstract method `getBytes` called");
   }
-
   peekByte() {
     const peekedByte = this.getByte();
-
     if (peekedByte !== -1) {
       this.pos--;
     }
-
     return peekedByte;
   }
-
   peekBytes(length) {
     const bytes = this.getBytes(length);
     this.pos -= bytes.length;
     return bytes;
   }
-
   getUint16() {
     const b0 = this.getByte();
     const b1 = this.getByte();
-
     if (b0 === -1 || b1 === -1) {
       return -1;
     }
-
     return (b0 << 8) + b1;
   }
-
   getInt32() {
     const b0 = this.getByte();
     const b1 = this.getByte();
@@ -89,35 +74,26 @@ class BaseStream {
     const b3 = this.getByte();
     return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
   }
-
   getByteRange(begin, end) {
     (0, _util.unreachable)("Abstract method `getByteRange` called");
   }
-
   getString(length) {
     return (0, _util.bytesToString)(this.getBytes(length));
   }
-
   skip(n) {
     this.pos += n || 1;
   }
-
   reset() {
     (0, _util.unreachable)("Abstract method `reset` called");
   }
-
   moveStart() {
     (0, _util.unreachable)("Abstract method `moveStart` called");
   }
-
   makeSubStream(start, length, dict = null) {
     (0, _util.unreachable)("Abstract method `makeSubStream` called");
   }
-
   getBaseStreams() {
     return null;
   }
-
 }
-
 exports.BaseStream = BaseStream;

+ 0 - 64
lib/core/bidi.js

@@ -25,38 +25,29 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.bidi = bidi;
-
 var _util = require("../shared/util.js");
-
 const baseTypes = ["BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "S", "B", "S", "WS", "B", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "B", "B", "B", "S", "WS", "ON", "ON", "ET", "ET", "ET", "ON", "ON", "ON", "ON", "ON", "ES", "CS", "ES", "CS", "CS", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "CS", "ON", "ON", "ON", "ON", "ON", "ON", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "ON", "ON", "ON", "ON", "ON", "ON", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "ON", "ON", "ON", "ON", "BN", "BN", "BN", "BN", "BN", "BN", "B", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "CS", "ON", "ET", "ET", "ET", "ET", "ON", "ON", "ON", "ON", "L", "ON", "ON", "BN", "ON", "ON", "ET", "ET", "EN", "EN", "ON", "L", "ON", "ON", "ON", "EN", "L", "ON", "ON", "ON", "ON", "ON", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "ON", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "ON", "L", "L", "L", "L", "L", "L", "L", "L"];
 const arabicTypes = ["AN", "AN", "AN", "AN", "AN", "AN", "ON", "ON", "AL", "ET", "ET", "AL", "CS", "AL", "ON", "ON", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "ET", "AN", "AN", "AL", "AL", "AL", "NSM", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AN", "ON", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "NSM", "NSM", "ON", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "AL", "AL", "AL", "AL", "AL", "AL"];
-
 function isOdd(i) {
   return (i & 1) !== 0;
 }
-
 function isEven(i) {
   return (i & 1) === 0;
 }
-
 function findUnequal(arr, start, value) {
   let j, jj;
-
   for (j = start, jj = arr.length; j < jj; ++j) {
     if (arr[j] !== value) {
       return j;
     }
   }
-
   return j;
 }
-
 function setValues(arr, start, end, value) {
   for (let j = start; j < end; ++j) {
     arr[j] = value;
   }
 }
-
 function reverseValues(arr, start, end) {
   for (let i = start, j = end - 1; i < j; ++i, --j) {
     const temp = arr[i];
@@ -64,69 +55,55 @@ function reverseValues(arr, start, end) {
     arr[j] = temp;
   }
 }
-
 function createBidiText(str, isLTR, vertical = false) {
   let dir = "ltr";
-
   if (vertical) {
     dir = "ttb";
   } else if (!isLTR) {
     dir = "rtl";
   }
-
   return {
     str,
     dir
   };
 }
-
 const chars = [];
 const types = [];
-
 function bidi(str, startLevel = -1, vertical = false) {
   let isLTR = true;
   const strLength = str.length;
-
   if (strLength === 0 || vertical) {
     return createBidiText(str, isLTR, vertical);
   }
-
   chars.length = strLength;
   types.length = strLength;
   let numBidi = 0;
   let i, ii;
-
   for (i = 0; i < strLength; ++i) {
     chars[i] = str.charAt(i);
     const charCode = str.charCodeAt(i);
     let charType = "L";
-
     if (charCode <= 0x00ff) {
       charType = baseTypes[charCode];
     } else if (0x0590 <= charCode && charCode <= 0x05f4) {
       charType = "R";
     } else if (0x0600 <= charCode && charCode <= 0x06ff) {
       charType = arabicTypes[charCode & 0xff];
-
       if (!charType) {
         (0, _util.warn)("Bidi: invalid Unicode character " + charCode.toString(16));
       }
     } else if (0x0700 <= charCode && charCode <= 0x08ac) {
       charType = "AL";
     }
-
     if (charType === "R" || charType === "AL" || charType === "AN") {
       numBidi++;
     }
-
     types[i] = charType;
   }
-
   if (numBidi === 0) {
     isLTR = true;
     return createBidiText(str, isLTR);
   }
-
   if (startLevel === -1) {
     if (numBidi / strLength < 0.3 && strLength > 4) {
       isLTR = true;
@@ -136,18 +113,14 @@ function bidi(str, startLevel = -1, vertical = false) {
       startLevel = 1;
     }
   }
-
   const levels = [];
-
   for (i = 0; i < strLength; ++i) {
     levels[i] = startLevel;
   }
-
   const e = isOdd(startLevel) ? "R" : "L";
   const sor = e;
   const eor = sor;
   let lastType = sor;
-
   for (i = 0; i < strLength; ++i) {
     if (types[i] === "NSM") {
       types[i] = lastType;
@@ -155,118 +128,91 @@ function bidi(str, startLevel = -1, vertical = false) {
       lastType = types[i];
     }
   }
-
   lastType = sor;
   let t;
-
   for (i = 0; i < strLength; ++i) {
     t = types[i];
-
     if (t === "EN") {
       types[i] = lastType === "AL" ? "AN" : "EN";
     } else if (t === "R" || t === "L" || t === "AL") {
       lastType = t;
     }
   }
-
   for (i = 0; i < strLength; ++i) {
     t = types[i];
-
     if (t === "AL") {
       types[i] = "R";
     }
   }
-
   for (i = 1; i < strLength - 1; ++i) {
     if (types[i] === "ES" && types[i - 1] === "EN" && types[i + 1] === "EN") {
       types[i] = "EN";
     }
-
     if (types[i] === "CS" && (types[i - 1] === "EN" || types[i - 1] === "AN") && types[i + 1] === types[i - 1]) {
       types[i] = types[i - 1];
     }
   }
-
   for (i = 0; i < strLength; ++i) {
     if (types[i] === "EN") {
       for (let j = i - 1; j >= 0; --j) {
         if (types[j] !== "ET") {
           break;
         }
-
         types[j] = "EN";
       }
-
       for (let j = i + 1; j < strLength; ++j) {
         if (types[j] !== "ET") {
           break;
         }
-
         types[j] = "EN";
       }
     }
   }
-
   for (i = 0; i < strLength; ++i) {
     t = types[i];
-
     if (t === "WS" || t === "ES" || t === "ET" || t === "CS") {
       types[i] = "ON";
     }
   }
-
   lastType = sor;
-
   for (i = 0; i < strLength; ++i) {
     t = types[i];
-
     if (t === "EN") {
       types[i] = lastType === "L" ? "L" : "EN";
     } else if (t === "R" || t === "L") {
       lastType = t;
     }
   }
-
   for (i = 0; i < strLength; ++i) {
     if (types[i] === "ON") {
       const end = findUnequal(types, i + 1, "ON");
       let before = sor;
-
       if (i > 0) {
         before = types[i - 1];
       }
-
       let after = eor;
-
       if (end + 1 < strLength) {
         after = types[end + 1];
       }
-
       if (before !== "L") {
         before = "R";
       }
-
       if (after !== "L") {
         after = "R";
       }
-
       if (before === after) {
         setValues(types, i, end, before);
       }
-
       i = end - 1;
     }
   }
-
   for (i = 0; i < strLength; ++i) {
     if (types[i] === "ON") {
       types[i] = e;
     }
   }
-
   for (i = 0; i < strLength; ++i) {
     t = types[i];
-
     if (isEven(levels[i])) {
       if (t === "R") {
         levels[i] += 1;
@@ -279,26 +225,20 @@ function bidi(str, startLevel = -1, vertical = false) {
       }
     }
   }
-
   let highestLevel = -1;
   let lowestOddLevel = 99;
   let level;
-
   for (i = 0, ii = levels.length; i < ii; ++i) {
     level = levels[i];
-
     if (highestLevel < level) {
       highestLevel = level;
     }
-
     if (lowestOddLevel > level && isOdd(level)) {
       lowestOddLevel = level;
     }
   }
-
   for (level = highestLevel; level >= lowestOddLevel; --level) {
     let start = -1;
-
     for (i = 0, ii = levels.length; i < ii; ++i) {
       if (levels[i] < level) {
         if (start >= 0) {
@@ -309,19 +249,15 @@ function bidi(str, startLevel = -1, vertical = false) {
         start = i;
       }
     }
-
     if (start >= 0) {
       reverseValues(chars, start, levels.length);
     }
   }
-
   for (i = 0, ii = chars.length; i < ii; ++i) {
     const ch = chars[i];
-
     if (ch === "<" || ch === ">") {
       chars[i] = "";
     }
   }
-
   return createBidiText(chars.join(""), isLTR);
 }

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 21 - 264
lib/core/catalog.js


+ 0 - 173
lib/core/ccitt.js

@@ -25,9 +25,7 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.CCITTFaxDecoder = void 0;
-
 var _util = require("../shared/util.js");
-
 const ccittEOL = -2;
 const ccittEOF = -1;
 const twoDimPass = 0;
@@ -45,13 +43,11 @@ const whiteTable2 = [[-1, -1], [-1, -1], [-1, -1], [-1, -1], [8, 29], [8, 29], [
 const blackTable1 = [[-1, -1], [-1, -1], [12, ccittEOL], [12, ccittEOL], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [11, 1792], [11, 1792], [11, 1792], [11, 1792], [12, 1984], [12, 1984], [12, 2048], [12, 2048], [12, 2112], [12, 2112], [12, 2176], [12, 2176], [12, 2240], [12, 2240], [12, 2304], [12, 2304], [11, 1856], [11, 1856], [11, 1856], [11, 1856], [11, 1920], [11, 1920], [11, 1920], [11, 1920], [12, 2368], [12, 2368], [12, 2432], [12, 2432], [12, 2496], [12, 2496], [12, 2560], [12, 2560], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [12, 52], [12, 52], [13, 640], [13, 704], [13, 768], [13, 832], [12, 55], [12, 55], [12, 56], [12, 56], [13, 1280], [13, 1344], [13, 1408], [13, 1472], [12, 59], [12, 59], [12, 60], [12, 60], [13, 1536], [13, 1600], [11, 24], [11, 24], [11, 24], [11, 24], [11, 25], [11, 25], [11, 25], [11, 25], [13, 1664], [13, 1728], [12, 320], [12, 320], [12, 384], [12, 384], [12, 448], [12, 448], [13, 512], [13, 576], [12, 53], [12, 53], [12, 54], [12, 54], [13, 896], [13, 960], [13, 1024], [13, 1088], [13, 1152], [13, 1216], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64]];
 const blackTable2 = [[8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [11, 23], [11, 23], [12, 50], [12, 51], [12, 44], [12, 45], [12, 46], [12, 47], [12, 57], [12, 58], [12, 61], [12, 256], [10, 16], [10, 16], [10, 16], [10, 16], [10, 17], [10, 17], [10, 17], [10, 17], [12, 48], [12, 49], [12, 62], [12, 63], [12, 30], [12, 31], [12, 32], [12, 33], [12, 40], [12, 41], [11, 22], [11, 22], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [12, 128], [12, 192], [12, 26], [12, 27], [12, 28], [12, 29], [11, 19], [11, 19], [11, 20], [11, 20], [12, 34], [12, 35], [12, 36], [12, 37], [12, 38], [12, 39], [11, 21], [11, 21], [12, 42], [12, 43], [10, 0], [10, 0], [10, 0], [10, 0], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12]];
 const blackTable3 = [[-1, -1], [-1, -1], [-1, -1], [-1, -1], [6, 9], [6, 8], [5, 7], [5, 7], [4, 6], [4, 6], [4, 6], [4, 6], [4, 5], [4, 5], [4, 5], [4, 5], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]];
-
 class CCITTFaxDecoder {
   constructor(source, options = {}) {
     if (!source || typeof source.next !== "function") {
       throw new Error('CCITTFaxDecoder - invalid "source" parameter.');
     }
-
     this.source = source;
     this.eof = false;
     this.encoding = options.K || 0;
@@ -60,11 +56,9 @@ class CCITTFaxDecoder {
     this.columns = options.Columns || 1728;
     this.rows = options.Rows || 0;
     let eoblock = options.EndOfBlock;
-
     if (eoblock === null || eoblock === undefined) {
       eoblock = true;
     }
-
     this.eoblock = eoblock;
     this.black = options.BlackIs1 || false;
     this.codingLine = new Uint32Array(this.columns + 1);
@@ -78,77 +72,59 @@ class CCITTFaxDecoder {
     this.outputBits = 0;
     this.rowsDone = false;
     let code1;
-
     while ((code1 = this._lookBits(12)) === 0) {
       this._eatBits(1);
     }
-
     if (code1 === 1) {
       this._eatBits(12);
     }
-
     if (this.encoding > 0) {
       this.nextLine2D = !this._lookBits(1);
-
       this._eatBits(1);
     }
   }
-
   readNextChar() {
     if (this.eof) {
       return -1;
     }
-
     const refLine = this.refLine;
     const codingLine = this.codingLine;
     const columns = this.columns;
     let refPos, blackPixels, bits, i;
-
     if (this.outputBits === 0) {
       if (this.rowsDone) {
         this.eof = true;
       }
-
       if (this.eof) {
         return -1;
       }
-
       this.err = false;
       let code1, code2, code3;
-
       if (this.nextLine2D) {
         for (i = 0; codingLine[i] < columns; ++i) {
           refLine[i] = codingLine[i];
         }
-
         refLine[i++] = columns;
         refLine[i] = columns;
         codingLine[0] = 0;
         this.codingPos = 0;
         refPos = 0;
         blackPixels = 0;
-
         while (codingLine[this.codingPos] < columns) {
           code1 = this._getTwoDimCode();
-
           switch (code1) {
             case twoDimPass:
               this._addPixels(refLine[refPos + 1], blackPixels);
-
               if (refLine[refPos + 1] < columns) {
                 refPos += 2;
               }
-
               break;
-
             case twoDimHoriz:
               code1 = code2 = 0;
-
               if (blackPixels) {
                 do {
                   code1 += code3 = this._getBlackCode();
                 } while (code3 >= 64);
-
                 do {
                   code2 += code3 = this._getWhiteCode();
                 } while (code3 >= 64);
@@ -156,152 +132,107 @@ class CCITTFaxDecoder {
                 do {
                   code1 += code3 = this._getWhiteCode();
                 } while (code3 >= 64);
-
                 do {
                   code2 += code3 = this._getBlackCode();
                 } while (code3 >= 64);
               }
-
               this._addPixels(codingLine[this.codingPos] + code1, blackPixels);
-
               if (codingLine[this.codingPos] < columns) {
                 this._addPixels(codingLine[this.codingPos] + code2, blackPixels ^ 1);
               }
-
               while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                 refPos += 2;
               }
-
               break;
-
             case twoDimVertR3:
               this._addPixels(refLine[refPos] + 3, blackPixels);
-
               blackPixels ^= 1;
-
               if (codingLine[this.codingPos] < columns) {
                 ++refPos;
-
                 while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                   refPos += 2;
                 }
               }
-
               break;
-
             case twoDimVertR2:
               this._addPixels(refLine[refPos] + 2, blackPixels);
-
               blackPixels ^= 1;
-
               if (codingLine[this.codingPos] < columns) {
                 ++refPos;
-
                 while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                   refPos += 2;
                 }
               }
-
               break;
-
             case twoDimVertR1:
               this._addPixels(refLine[refPos] + 1, blackPixels);
-
               blackPixels ^= 1;
-
               if (codingLine[this.codingPos] < columns) {
                 ++refPos;
-
                 while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                   refPos += 2;
                 }
               }
-
               break;
-
             case twoDimVert0:
               this._addPixels(refLine[refPos], blackPixels);
-
               blackPixels ^= 1;
-
               if (codingLine[this.codingPos] < columns) {
                 ++refPos;
-
                 while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                   refPos += 2;
                 }
               }
-
               break;
-
             case twoDimVertL3:
               this._addPixelsNeg(refLine[refPos] - 3, blackPixels);
-
               blackPixels ^= 1;
-
               if (codingLine[this.codingPos] < columns) {
                 if (refPos > 0) {
                   --refPos;
                 } else {
                   ++refPos;
                 }
-
                 while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                   refPos += 2;
                 }
               }
-
               break;
-
             case twoDimVertL2:
               this._addPixelsNeg(refLine[refPos] - 2, blackPixels);
-
               blackPixels ^= 1;
-
               if (codingLine[this.codingPos] < columns) {
                 if (refPos > 0) {
                   --refPos;
                 } else {
                   ++refPos;
                 }
-
                 while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                   refPos += 2;
                 }
               }
-
               break;
-
             case twoDimVertL1:
               this._addPixelsNeg(refLine[refPos] - 1, blackPixels);
-
               blackPixels ^= 1;
-
               if (codingLine[this.codingPos] < columns) {
                 if (refPos > 0) {
                   --refPos;
                 } else {
                   ++refPos;
                 }
-
                 while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                   refPos += 2;
                 }
               }
-
               break;
-
             case ccittEOF:
               this._addPixels(columns, 0);
-
               this.eof = true;
               break;
-
             default:
               (0, _util.info)("bad 2d code");
-
               this._addPixels(columns, 0);
-
               this.err = true;
           }
         }
@@ -309,10 +240,8 @@ class CCITTFaxDecoder {
         codingLine[0] = 0;
         this.codingPos = 0;
         blackPixels = 0;
-
         while (codingLine[this.codingPos] < columns) {
           code1 = 0;
-
           if (blackPixels) {
             do {
               code1 += code3 = this._getBlackCode();
@@ -322,125 +251,92 @@ class CCITTFaxDecoder {
               code1 += code3 = this._getWhiteCode();
             } while (code3 >= 64);
           }
-
           this._addPixels(codingLine[this.codingPos] + code1, blackPixels);
-
           blackPixels ^= 1;
         }
       }
-
       let gotEOL = false;
-
       if (this.byteAlign) {
         this.inputBits &= ~7;
       }
-
       if (!this.eoblock && this.row === this.rows - 1) {
         this.rowsDone = true;
       } else {
         code1 = this._lookBits(12);
-
         if (this.eoline) {
           while (code1 !== ccittEOF && code1 !== 1) {
             this._eatBits(1);
-
             code1 = this._lookBits(12);
           }
         } else {
           while (code1 === 0) {
             this._eatBits(1);
-
             code1 = this._lookBits(12);
           }
         }
-
         if (code1 === 1) {
           this._eatBits(12);
-
           gotEOL = true;
         } else if (code1 === ccittEOF) {
           this.eof = true;
         }
       }
-
       if (!this.eof && this.encoding > 0 && !this.rowsDone) {
         this.nextLine2D = !this._lookBits(1);
-
         this._eatBits(1);
       }
-
       if (this.eoblock && gotEOL && this.byteAlign) {
         code1 = this._lookBits(12);
-
         if (code1 === 1) {
           this._eatBits(12);
-
           if (this.encoding > 0) {
             this._lookBits(1);
-
             this._eatBits(1);
           }
-
           if (this.encoding >= 0) {
             for (i = 0; i < 4; ++i) {
               code1 = this._lookBits(12);
-
               if (code1 !== 1) {
                 (0, _util.info)("bad rtc code: " + code1);
               }
-
               this._eatBits(12);
-
               if (this.encoding > 0) {
                 this._lookBits(1);
-
                 this._eatBits(1);
               }
             }
           }
-
           this.eof = true;
         }
       } else if (this.err && this.eoline) {
         while (true) {
           code1 = this._lookBits(13);
-
           if (code1 === ccittEOF) {
             this.eof = true;
             return -1;
           }
-
           if (code1 >> 1 === 1) {
             break;
           }
-
           this._eatBits(1);
         }
-
         this._eatBits(12);
-
         if (this.encoding > 0) {
           this._eatBits(1);
-
           this.nextLine2D = !(code1 & 1);
         }
       }
-
       if (codingLine[0] > 0) {
         this.outputBits = codingLine[this.codingPos = 0];
       } else {
         this.outputBits = codingLine[this.codingPos = 1];
       }
-
       this.row++;
     }
-
     let c;
-
     if (this.outputBits >= 8) {
       c = this.codingPos & 1 ? 0 : 0xff;
       this.outputBits -= 8;
-
       if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {
         this.codingPos++;
         this.outputBits = codingLine[this.codingPos] - codingLine[this.codingPos - 1];
@@ -448,31 +344,24 @@ class CCITTFaxDecoder {
     } else {
       bits = 8;
       c = 0;
-
       do {
         if (typeof this.outputBits !== "number") {
           throw new _util.FormatError('Invalid /CCITTFaxDecode data, "outputBits" must be a number.');
         }
-
         if (this.outputBits > bits) {
           c <<= bits;
-
           if (!(this.codingPos & 1)) {
             c |= 0xff >> 8 - bits;
           }
-
           this.outputBits -= bits;
           bits = 0;
         } else {
           c <<= this.outputBits;
-
           if (!(this.codingPos & 1)) {
             c |= 0xff >> 8 - this.outputBits;
           }
-
           bits -= this.outputBits;
           this.outputBits = 0;
-
           if (codingLine[this.codingPos] < columns) {
             this.codingPos++;
             this.outputBits = codingLine[this.codingPos] - codingLine[this.codingPos - 1];
@@ -483,50 +372,39 @@ class CCITTFaxDecoder {
         }
       } while (bits);
     }
-
     if (this.black) {
       c ^= 0xff;
     }
-
     return c;
   }
-
   _addPixels(a1, blackPixels) {
     const codingLine = this.codingLine;
     let codingPos = this.codingPos;
-
     if (a1 > codingLine[codingPos]) {
       if (a1 > this.columns) {
         (0, _util.info)("row is wrong length");
         this.err = true;
         a1 = this.columns;
       }
-
       if (codingPos & 1 ^ blackPixels) {
         ++codingPos;
       }
-
       codingLine[codingPos] = a1;
     }
-
     this.codingPos = codingPos;
   }
-
   _addPixelsNeg(a1, blackPixels) {
     const codingLine = this.codingLine;
     let codingPos = this.codingPos;
-
     if (a1 > codingLine[codingPos]) {
       if (a1 > this.columns) {
         (0, _util.info)("row is wrong length");
         this.err = true;
         a1 = this.columns;
       }
-
       if (codingPos & 1 ^ blackPixels) {
         ++codingPos;
       }
-
       codingLine[codingPos] = a1;
     } else if (a1 < codingLine[codingPos]) {
       if (a1 < 0) {
@@ -534,123 +412,90 @@ class CCITTFaxDecoder {
         this.err = true;
         a1 = 0;
       }
-
       while (codingPos > 0 && a1 < codingLine[codingPos - 1]) {
         --codingPos;
       }
-
       codingLine[codingPos] = a1;
     }
-
     this.codingPos = codingPos;
   }
-
   _findTableCode(start, end, table, limit) {
     const limitValue = limit || 0;
-
     for (let i = start; i <= end; ++i) {
       let code = this._lookBits(i);
-
       if (code === ccittEOF) {
         return [true, 1, false];
       }
-
       if (i < end) {
         code <<= end - i;
       }
-
       if (!limitValue || code >= limitValue) {
         const p = table[code - limitValue];
-
         if (p[0] === i) {
           this._eatBits(i);
-
           return [true, p[1], true];
         }
       }
     }
-
     return [false, 0, false];
   }
-
   _getTwoDimCode() {
     let code = 0;
     let p;
-
     if (this.eoblock) {
       code = this._lookBits(7);
       p = twoDimTable[code];
-
       if (p && p[0] > 0) {
         this._eatBits(p[0]);
-
         return p[1];
       }
     } else {
       const result = this._findTableCode(1, 7, twoDimTable);
-
       if (result[0] && result[2]) {
         return result[1];
       }
     }
-
     (0, _util.info)("Bad two dim code");
     return ccittEOF;
   }
-
   _getWhiteCode() {
     let code = 0;
     let p;
-
     if (this.eoblock) {
       code = this._lookBits(12);
-
       if (code === ccittEOF) {
         return 1;
       }
-
       if (code >> 5 === 0) {
         p = whiteTable1[code];
       } else {
         p = whiteTable2[code >> 3];
       }
-
       if (p[0] > 0) {
         this._eatBits(p[0]);
-
         return p[1];
       }
     } else {
       let result = this._findTableCode(1, 9, whiteTable2);
-
       if (result[0]) {
         return result[1];
       }
-
       result = this._findTableCode(11, 12, whiteTable1);
-
       if (result[0]) {
         return result[1];
       }
     }
-
     (0, _util.info)("bad white code");
-
     this._eatBits(1);
-
     return 1;
   }
-
   _getBlackCode() {
     let code, p;
-
     if (this.eoblock) {
       code = this._lookBits(13);
-
       if (code === ccittEOF) {
         return 1;
       }
-
       if (code >> 7 === 0) {
         p = blackTable1[code];
       } else if (code >> 9 === 0 && code >> 7 !== 0) {
@@ -658,64 +503,46 @@ class CCITTFaxDecoder {
       } else {
         p = blackTable3[code >> 7];
       }
-
       if (p[0] > 0) {
         this._eatBits(p[0]);
-
         return p[1];
       }
     } else {
       let result = this._findTableCode(2, 6, blackTable3);
-
       if (result[0]) {
         return result[1];
       }
-
       result = this._findTableCode(7, 12, blackTable2, 64);
-
       if (result[0]) {
         return result[1];
       }
-
       result = this._findTableCode(10, 13, blackTable1);
-
       if (result[0]) {
         return result[1];
       }
     }
-
     (0, _util.info)("bad black code");
-
     this._eatBits(1);
-
     return 1;
   }
-
   _lookBits(n) {
     let c;
-
     while (this.inputBits < n) {
       if ((c = this.source.next()) === -1) {
         if (this.inputBits === 0) {
           return ccittEOF;
         }
-
         return this.inputBuf << n - this.inputBits & 0xffff >> 16 - n;
       }
-
       this.inputBuf = this.inputBuf << 8 | c;
       this.inputBits += 8;
     }
-
     return this.inputBuf >> this.inputBits - n & 0xffff >> 16 - n;
   }
-
   _eatBits(n) {
     if ((this.inputBits -= n) < 0) {
       this.inputBits = 0;
     }
   }
-
 }
-
 exports.CCITTFaxDecoder = CCITTFaxDecoder;

+ 0 - 12
lib/core/ccitt_stream.js

@@ -25,28 +25,21 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.CCITTFaxStream = void 0;
-
 var _ccitt = require("./ccitt.js");
-
 var _decode_stream = require("./decode_stream.js");
-
 var _primitives = require("./primitives.js");
-
 class CCITTFaxStream extends _decode_stream.DecodeStream {
   constructor(str, maybeLength, params) {
     super(maybeLength);
     this.str = str;
     this.dict = str.dict;
-
     if (!(params instanceof _primitives.Dict)) {
       params = _primitives.Dict.empty;
     }
-
     const source = {
       next() {
         return str.getByte();
       }
-
     };
     this.ccittFaxDecoder = new _ccitt.CCITTFaxDecoder(source, {
       K: params.get("K"),
@@ -58,21 +51,16 @@ class CCITTFaxStream extends _decode_stream.DecodeStream {
       BlackIs1: params.get("BlackIs1")
     });
   }
-
   readBlock() {
     while (!this.eof) {
       const c = this.ccittFaxDecoder.readNextChar();
-
       if (c === -1) {
         this.eof = true;
         return;
       }
-
       this.ensureBuffer(this.bufferLength + 1);
       this.buffer[this.bufferLength++] = c;
     }
   }
-
 }
-
 exports.CCITTFaxStream = CCITTFaxStream;

+ 20 - 28
lib/core/cff_font.js

@@ -25,13 +25,9 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.CFFFont = void 0;
-
 var _cff_parser = require("./cff_parser.js");
-
 var _fonts_utils = require("./fonts_utils.js");
-
 var _util = require("../shared/util.js");
-
 class CFFFont {
   constructor(file, properties) {
     this.properties = properties;
@@ -40,97 +36,93 @@ class CFFFont {
     this.cff.duplicateFirstGlyph();
     const compiler = new _cff_parser.CFFCompiler(this.cff);
     this.seacs = this.cff.seacs;
-
     try {
       this.data = compiler.compile();
     } catch (e) {
       (0, _util.warn)("Failed to compile font " + properties.loadedName);
       this.data = file;
     }
-
     this._createBuiltInEncoding();
   }
-
   get numGlyphs() {
     return this.cff.charStrings.count;
   }
-
   getCharset() {
     return this.cff.charset.charset;
   }
-
   getGlyphMapping() {
     const cff = this.cff;
     const properties = this.properties;
+    const {
+      cidToGidMap,
+      cMap
+    } = properties;
     const charsets = cff.charset.charset;
     let charCodeToGlyphId;
     let glyphId;
-
     if (properties.composite) {
+      let invCidToGidMap;
+      if (cidToGidMap && cidToGidMap.length > 0) {
+        invCidToGidMap = Object.create(null);
+        for (let i = 0, ii = cidToGidMap.length; i < ii; i++) {
+          const gid = cidToGidMap[i];
+          if (gid !== undefined) {
+            invCidToGidMap[gid] = i;
+          }
+        }
+      }
       charCodeToGlyphId = Object.create(null);
       let charCode;
-
       if (cff.isCIDFont) {
         for (glyphId = 0; glyphId < charsets.length; glyphId++) {
           const cid = charsets[glyphId];
-          charCode = properties.cMap.charCodeOf(cid);
+          charCode = cMap.charCodeOf(cid);
+          if (invCidToGidMap && invCidToGidMap[charCode] !== undefined) {
+            charCode = invCidToGidMap[charCode];
+          }
           charCodeToGlyphId[charCode] = glyphId;
         }
       } else {
         for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {
-          charCode = properties.cMap.charCodeOf(glyphId);
+          charCode = cMap.charCodeOf(glyphId);
           charCodeToGlyphId[charCode] = glyphId;
         }
       }
-
       return charCodeToGlyphId;
     }
-
     let encoding = cff.encoding ? cff.encoding.encoding : null;
-
     if (properties.isInternalFont) {
       encoding = properties.defaultEncoding;
     }
-
     charCodeToGlyphId = (0, _fonts_utils.type1FontGlyphMapping)(properties, encoding, charsets);
     return charCodeToGlyphId;
   }
-
   hasGlyphId(id) {
     return this.cff.hasGlyphId(id);
   }
-
   _createBuiltInEncoding() {
     const {
       charset,
       encoding
     } = this.cff;
-
     if (!charset || !encoding) {
       return;
     }
-
     const charsets = charset.charset,
-          encodings = encoding.encoding;
+      encodings = encoding.encoding;
     const map = [];
-
     for (const charCode in encodings) {
       const glyphId = encodings[charCode];
-
       if (glyphId >= 0) {
         const glyphName = charsets[glyphId];
-
         if (glyphName) {
           map[charCode] = glyphName;
         }
       }
     }
-
     if (map.length > 0) {
       this.properties.builtInEncoding = map;
     }
   }
-
 }
-
 exports.CFFFont = CFFFont;

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 4
lib/core/cff_parser.js


+ 6 - 140
lib/core/chunked_stream.js

@@ -25,13 +25,9 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.ChunkedStreamManager = exports.ChunkedStream = void 0;
-
 var _util = require("../shared/util.js");
-
 var _core_utils = require("./core_utils.js");
-
 var _stream = require("./stream.js");
-
 class ChunkedStream extends _stream.Stream {
   constructor(length, chunkSize, manager) {
     super(new Uint8Array(length), 0, length, null);
@@ -42,49 +38,37 @@ class ChunkedStream extends _stream.Stream {
     this.progressiveDataLength = 0;
     this.lastSuccessfulEnsureByteChunk = -1;
   }
-
   getMissingChunks() {
     const chunks = [];
-
     for (let chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
       if (!this._loadedChunks.has(chunk)) {
         chunks.push(chunk);
       }
     }
-
     return chunks;
   }
-
   get numChunksLoaded() {
     return this._loadedChunks.size;
   }
-
   get isDataLoaded() {
     return this.numChunksLoaded === this.numChunks;
   }
-
   onReceiveData(begin, chunk) {
     const chunkSize = this.chunkSize;
-
     if (begin % chunkSize !== 0) {
       throw new Error(`Bad begin offset: ${begin}`);
     }
-
     const end = begin + chunk.byteLength;
-
     if (end % chunkSize !== 0 && end !== this.bytes.length) {
       throw new Error(`Bad end offset: ${end}`);
     }
-
     this.bytes.set(new Uint8Array(chunk), begin);
     const beginChunk = Math.floor(begin / chunkSize);
     const endChunk = Math.floor((end - 1) / chunkSize) + 1;
-
     for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
       this._loadedChunks.add(curChunk);
     }
   }
-
   onReceiveProgressiveData(data) {
     let position = this.progressiveDataLength;
     const beginChunk = Math.floor(position / this.chunkSize);
@@ -92,133 +76,99 @@ class ChunkedStream extends _stream.Stream {
     position += data.byteLength;
     this.progressiveDataLength = position;
     const endChunk = position >= this.end ? this.numChunks : Math.floor(position / this.chunkSize);
-
     for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
       this._loadedChunks.add(curChunk);
     }
   }
-
   ensureByte(pos) {
     if (pos < this.progressiveDataLength) {
       return;
     }
-
     const chunk = Math.floor(pos / this.chunkSize);
-
     if (chunk > this.numChunks) {
       return;
     }
-
     if (chunk === this.lastSuccessfulEnsureByteChunk) {
       return;
     }
-
     if (!this._loadedChunks.has(chunk)) {
       throw new _core_utils.MissingDataException(pos, pos + 1);
     }
-
     this.lastSuccessfulEnsureByteChunk = chunk;
   }
-
   ensureRange(begin, end) {
     if (begin >= end) {
       return;
     }
-
     if (end <= this.progressiveDataLength) {
       return;
     }
-
     const beginChunk = Math.floor(begin / this.chunkSize);
-
     if (beginChunk > this.numChunks) {
       return;
     }
-
     const endChunk = Math.min(Math.floor((end - 1) / this.chunkSize) + 1, this.numChunks);
-
     for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
       if (!this._loadedChunks.has(chunk)) {
         throw new _core_utils.MissingDataException(begin, end);
       }
     }
   }
-
   nextEmptyChunk(beginChunk) {
     const numChunks = this.numChunks;
-
     for (let i = 0; i < numChunks; ++i) {
       const chunk = (beginChunk + i) % numChunks;
-
       if (!this._loadedChunks.has(chunk)) {
         return chunk;
       }
     }
-
     return null;
   }
-
   hasChunk(chunk) {
     return this._loadedChunks.has(chunk);
   }
-
   getByte() {
     const pos = this.pos;
-
     if (pos >= this.end) {
       return -1;
     }
-
     if (pos >= this.progressiveDataLength) {
       this.ensureByte(pos);
     }
-
     return this.bytes[this.pos++];
   }
-
   getBytes(length) {
     const bytes = this.bytes;
     const pos = this.pos;
     const strEnd = this.end;
-
     if (!length) {
       if (strEnd > this.progressiveDataLength) {
         this.ensureRange(pos, strEnd);
       }
-
       return bytes.subarray(pos, strEnd);
     }
-
     let end = pos + length;
-
     if (end > strEnd) {
       end = strEnd;
     }
-
     if (end > this.progressiveDataLength) {
       this.ensureRange(pos, end);
     }
-
     this.pos = end;
     return bytes.subarray(pos, end);
   }
-
   getByteRange(begin, end) {
     if (begin < 0) {
       begin = 0;
     }
-
     if (end > this.end) {
       end = this.end;
     }
-
     if (end > this.progressiveDataLength) {
       this.ensureRange(begin, end);
     }
-
     return this.bytes.subarray(begin, end);
   }
-
   makeSubStream(start, length, dict = null) {
     if (length) {
       if (start + length > this.progressiveDataLength) {
@@ -229,35 +179,27 @@ class ChunkedStream extends _stream.Stream {
         this.ensureByte(start);
       }
     }
-
     function ChunkedStreamSubstream() {}
-
     ChunkedStreamSubstream.prototype = Object.create(this);
-
     ChunkedStreamSubstream.prototype.getMissingChunks = function () {
       const chunkSize = this.chunkSize;
       const beginChunk = Math.floor(this.start / chunkSize);
       const endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
       const missingChunks = [];
-
       for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
         if (!this._loadedChunks.has(chunk)) {
           missingChunks.push(chunk);
         }
       }
-
       return missingChunks;
     };
-
     Object.defineProperty(ChunkedStreamSubstream.prototype, "isDataLoaded", {
       get() {
         if (this.numChunksLoaded === this.numChunks) {
           return true;
         }
-
         return this.getMissingChunks().length === 0;
       },
-
       configurable: true
     });
     const subStream = new ChunkedStreamSubstream();
@@ -266,15 +208,11 @@ class ChunkedStream extends _stream.Stream {
     subStream.dict = dict;
     return subStream;
   }
-
   getBaseStreams() {
     return [this];
   }
-
 }
-
 exports.ChunkedStream = ChunkedStream;
-
 class ChunkedStreamManager {
   constructor(pdfNetworkStream, args) {
     this.length = args.length;
@@ -291,20 +229,13 @@ class ChunkedStreamManager {
     this.aborted = false;
     this._loadedStreamCapability = (0, _util.createPromiseCapability)();
   }
-
-  onLoadedStream() {
-    return this._loadedStreamCapability.promise;
-  }
-
   sendRequest(begin, end) {
     const rangeReader = this.pdfNetworkStream.getRangeReader(begin, end);
-
     if (!rangeReader.isStreamingSupported) {
       rangeReader.onProgress = this.onProgress.bind(this);
     }
-
     let chunks = [],
-        loaded = 0;
+      loaded = 0;
     return new Promise((resolve, reject) => {
       const readChunk = chunk => {
         try {
@@ -312,17 +243,14 @@ class ChunkedStreamManager {
             const data = chunk.value;
             chunks.push(data);
             loaded += (0, _util.arrayByteLength)(data);
-
             if (rangeReader.isStreamingSupported) {
               this.onProgress({
                 loaded
               });
             }
-
             rangeReader.read().then(readChunk, reject);
             return;
           }
-
           const chunkData = (0, _util.arraysToBytes)(chunks);
           chunks = null;
           resolve(chunkData);
@@ -330,132 +258,101 @@ class ChunkedStreamManager {
           reject(e);
         }
       };
-
       rangeReader.read().then(readChunk, reject);
     }).then(data => {
       if (this.aborted) {
         return;
       }
-
       this.onReceiveData({
         chunk: data,
         begin
       });
     });
   }
-
-  requestAllChunks() {
-    const missingChunks = this.stream.getMissingChunks();
-
-    this._requestChunks(missingChunks);
-
+  requestAllChunks(noFetch = false) {
+    if (!noFetch) {
+      const missingChunks = this.stream.getMissingChunks();
+      this._requestChunks(missingChunks);
+    }
     return this._loadedStreamCapability.promise;
   }
-
   _requestChunks(chunks) {
     const requestId = this.currRequestId++;
     const chunksNeeded = new Set();
-
     this._chunksNeededByRequest.set(requestId, chunksNeeded);
-
     for (const chunk of chunks) {
       if (!this.stream.hasChunk(chunk)) {
         chunksNeeded.add(chunk);
       }
     }
-
     if (chunksNeeded.size === 0) {
       return Promise.resolve();
     }
-
     const capability = (0, _util.createPromiseCapability)();
-
     this._promisesByRequest.set(requestId, capability);
-
     const chunksToRequest = [];
-
     for (const chunk of chunksNeeded) {
       let requestIds = this._requestsByChunk.get(chunk);
-
       if (!requestIds) {
         requestIds = [];
-
         this._requestsByChunk.set(chunk, requestIds);
-
         chunksToRequest.push(chunk);
       }
-
       requestIds.push(requestId);
     }
-
     if (chunksToRequest.length > 0) {
       const groupedChunksToRequest = this.groupChunks(chunksToRequest);
-
       for (const groupedChunk of groupedChunksToRequest) {
         const begin = groupedChunk.beginChunk * this.chunkSize;
         const end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
         this.sendRequest(begin, end).catch(capability.reject);
       }
     }
-
     return capability.promise.catch(reason => {
       if (this.aborted) {
         return;
       }
-
       throw reason;
     });
   }
-
   getStream() {
     return this.stream;
   }
-
   requestRange(begin, end) {
     end = Math.min(end, this.length);
     const beginChunk = this.getBeginChunk(begin);
     const endChunk = this.getEndChunk(end);
     const chunks = [];
-
     for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
       chunks.push(chunk);
     }
-
     return this._requestChunks(chunks);
   }
-
   requestRanges(ranges = []) {
     const chunksToRequest = [];
-
     for (const range of ranges) {
       const beginChunk = this.getBeginChunk(range.begin);
       const endChunk = this.getEndChunk(range.end);
-
       for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
         if (!chunksToRequest.includes(chunk)) {
           chunksToRequest.push(chunk);
         }
       }
     }
-
     chunksToRequest.sort(function (a, b) {
       return a - b;
     });
     return this._requestChunks(chunksToRequest);
   }
-
   groupChunks(chunks) {
     const groupedChunks = [];
     let beginChunk = -1;
     let prevChunk = -1;
-
     for (let i = 0, ii = chunks.length; i < ii; ++i) {
       const chunk = chunks[i];
-
       if (beginChunk < 0) {
         beginChunk = chunk;
       }
-
       if (prevChunk >= 0 && prevChunk + 1 !== chunk) {
         groupedChunks.push({
           beginChunk,
@@ -463,27 +360,22 @@ class ChunkedStreamManager {
         });
         beginChunk = chunk;
       }
-
       if (i + 1 === chunks.length) {
         groupedChunks.push({
           beginChunk,
           endChunk: chunk + 1
         });
       }
-
       prevChunk = chunk;
     }
-
     return groupedChunks;
   }
-
   onProgress(args) {
     this.msgHandler.send("DocProgress", {
       loaded: this.stream.numChunksLoaded * this.chunkSize + args.loaded,
       total: this.length
     });
   }
-
   onReceiveData(args) {
     const chunk = args.chunk;
     const isProgressive = args.begin === undefined;
@@ -491,100 +383,74 @@ class ChunkedStreamManager {
     const end = begin + chunk.byteLength;
     const beginChunk = Math.floor(begin / this.chunkSize);
     const endChunk = end < this.length ? Math.floor(end / this.chunkSize) : Math.ceil(end / this.chunkSize);
-
     if (isProgressive) {
       this.stream.onReceiveProgressiveData(chunk);
       this.progressiveDataLength = end;
     } else {
       this.stream.onReceiveData(begin, chunk);
     }
-
     if (this.stream.isDataLoaded) {
       this._loadedStreamCapability.resolve(this.stream);
     }
-
     const loadedRequests = [];
-
     for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
       const requestIds = this._requestsByChunk.get(curChunk);
-
       if (!requestIds) {
         continue;
       }
-
       this._requestsByChunk.delete(curChunk);
-
       for (const requestId of requestIds) {
         const chunksNeeded = this._chunksNeededByRequest.get(requestId);
-
         if (chunksNeeded.has(curChunk)) {
           chunksNeeded.delete(curChunk);
         }
-
         if (chunksNeeded.size > 0) {
           continue;
         }
-
         loadedRequests.push(requestId);
       }
     }
-
     if (!this.disableAutoFetch && this._requestsByChunk.size === 0) {
       let nextEmptyChunk;
-
       if (this.stream.numChunksLoaded === 1) {
         const lastChunk = this.stream.numChunks - 1;
-
         if (!this.stream.hasChunk(lastChunk)) {
           nextEmptyChunk = lastChunk;
         }
       } else {
         nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
       }
-
       if (Number.isInteger(nextEmptyChunk)) {
         this._requestChunks([nextEmptyChunk]);
       }
     }
-
     for (const requestId of loadedRequests) {
       const capability = this._promisesByRequest.get(requestId);
-
       this._promisesByRequest.delete(requestId);
-
       capability.resolve();
     }
-
     this.msgHandler.send("DocProgress", {
       loaded: this.stream.numChunksLoaded * this.chunkSize,
       total: this.length
     });
   }
-
   onError(err) {
     this._loadedStreamCapability.reject(err);
   }
-
   getBeginChunk(begin) {
     return Math.floor(begin / this.chunkSize);
   }
-
   getEndChunk(end) {
     return Math.floor((end - 1) / this.chunkSize) + 1;
   }
-
   abort(reason) {
     this.aborted = true;
-
     if (this.pdfNetworkStream) {
       this.pdfNetworkStream.cancelAllRequests(reason);
     }
-
     for (const capability of this._promisesByRequest.values()) {
       capability.reject(reason);
     }
   }
-
 }
-
 exports.ChunkedStreamManager = ChunkedStreamManager;

+ 0 - 3
lib/core/cleanup_helper.js

@@ -25,11 +25,8 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.clearGlobalCaches = clearGlobalCaches;
-
 var _primitives = require("./primitives.js");
-
 var _unicode = require("./unicode.js");
-
 function clearGlobalCaches() {
   (0, _primitives.clearPrimitiveCaches)();
   (0, _unicode.clearUnicodeCaches)();

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 7
lib/core/cmap.js


+ 4 - 204
lib/core/colorspace.js

@@ -25,32 +25,24 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.ColorSpace = void 0;
-
 var _util = require("../shared/util.js");
-
 var _primitives = require("./primitives.js");
-
 var _base_stream = require("./base_stream.js");
-
 var _core_utils = require("./core_utils.js");
-
 function resizeRgbImage(src, dest, w1, h1, w2, h2, alpha01) {
   const COMPONENTS = 3;
   alpha01 = alpha01 !== 1 ? 0 : alpha01;
   const xRatio = w1 / w2;
   const yRatio = h1 / h2;
   let newIndex = 0,
-      oldIndex;
+    oldIndex;
   const xScaled = new Uint16Array(w2);
   const w1Scanline = w1 * COMPONENTS;
-
   for (let i = 0; i < w2; i++) {
     xScaled[i] = Math.floor(i * xRatio) * COMPONENTS;
   }
-
   for (let i = 0; i < h2; i++) {
     const py = Math.floor(i * yRatio) * w1Scanline;
-
     for (let j = 0; j < w2; j++) {
       oldIndex = py + xScaled[j];
       dest[newIndex++] = src[oldIndex++];
@@ -60,64 +52,50 @@ function resizeRgbImage(src, dest, w1, h1, w2, h2, alpha01) {
     }
   }
 }
-
 class ColorSpace {
   constructor(name, numComps) {
     if (this.constructor === ColorSpace) {
       (0, _util.unreachable)("Cannot initialize ColorSpace.");
     }
-
     this.name = name;
     this.numComps = numComps;
   }
-
   getRgb(src, srcOffset) {
     const rgb = new Uint8ClampedArray(3);
     this.getRgbItem(src, srcOffset, rgb, 0);
     return rgb;
   }
-
   getRgbItem(src, srcOffset, dest, destOffset) {
     (0, _util.unreachable)("Should not call ColorSpace.getRgbItem");
   }
-
   getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
     (0, _util.unreachable)("Should not call ColorSpace.getRgbBuffer");
   }
-
   getOutputLength(inputLength, alpha01) {
     (0, _util.unreachable)("Should not call ColorSpace.getOutputLength");
   }
-
   isPassthrough(bits) {
     return false;
   }
-
   isDefaultDecode(decodeMap, bpc) {
     return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
   }
-
   fillRgb(dest, originalWidth, originalHeight, width, height, actualHeight, bpc, comps, alpha01) {
     const count = originalWidth * originalHeight;
     let rgbBuf = null;
     const numComponentColors = 1 << bpc;
     const needsResizing = originalHeight !== height || originalWidth !== width;
-
     if (this.isPassthrough(bpc)) {
       rgbBuf = comps;
     } else if (this.numComps === 1 && count > numComponentColors && this.name !== "DeviceGray" && this.name !== "DeviceRGB") {
       const allColors = bpc <= 8 ? new Uint8Array(numComponentColors) : new Uint16Array(numComponentColors);
-
       for (let i = 0; i < numComponentColors; i++) {
         allColors[i] = i;
       }
-
       const colorMap = new Uint8ClampedArray(numComponentColors * 3);
       this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc, 0);
-
       if (!needsResizing) {
         let destPos = 0;
-
         for (let i = 0; i < count; ++i) {
           const key = comps[i] * 3;
           dest[destPos++] = colorMap[key];
@@ -128,7 +106,6 @@ class ColorSpace {
       } else {
         rgbBuf = new Uint8Array(count * 3);
         let rgbPos = 0;
-
         for (let i = 0; i < count; ++i) {
           const key = comps[i] * 3;
           rgbBuf[rgbPos++] = colorMap[key];
@@ -144,14 +121,12 @@ class ColorSpace {
         this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc, 0);
       }
     }
-
     if (rgbBuf) {
       if (needsResizing) {
         resizeRgbImage(rgbBuf, dest, originalWidth, originalHeight, width, height, alpha01);
       } else {
         let destPos = 0,
-            rgbPos = 0;
-
+          rgbPos = 0;
         for (let i = 0, ii = width * actualHeight; i < ii; i++) {
           dest[destPos++] = rgbBuf[rgbPos++];
           dest[destPos++] = rgbBuf[rgbPos++];
@@ -161,48 +136,37 @@ class ColorSpace {
       }
     }
   }
-
   get usesZeroToOneRange() {
     return (0, _util.shadow)(this, "usesZeroToOneRange", true);
   }
-
   static _cache(cacheKey, xref, localColorSpaceCache, parsedColorSpace) {
     if (!localColorSpaceCache) {
       throw new Error('ColorSpace._cache - expected "localColorSpaceCache" argument.');
     }
-
     if (!parsedColorSpace) {
       throw new Error('ColorSpace._cache - expected "parsedColorSpace" argument.');
     }
-
     let csName, csRef;
-
     if (cacheKey instanceof _primitives.Ref) {
       csRef = cacheKey;
       cacheKey = xref.fetch(cacheKey);
     }
-
     if (cacheKey instanceof _primitives.Name) {
       csName = cacheKey.name;
     }
-
     if (csName || csRef) {
       localColorSpaceCache.set(csName, csRef, parsedColorSpace);
     }
   }
-
   static getCached(cacheKey, xref, localColorSpaceCache) {
     if (!localColorSpaceCache) {
       throw new Error('ColorSpace.getCached - expected "localColorSpaceCache" argument.');
     }
-
     if (cacheKey instanceof _primitives.Ref) {
       const localColorSpace = localColorSpaceCache.getByRef(cacheKey);
-
       if (localColorSpace) {
         return localColorSpace;
       }
-
       try {
         cacheKey = xref.fetch(cacheKey);
       } catch (ex) {
@@ -211,18 +175,14 @@ class ColorSpace {
         }
       }
     }
-
     if (cacheKey instanceof _primitives.Name) {
       const localColorSpace = localColorSpaceCache.getByName(cacheKey.name);
-
       if (localColorSpace) {
         return localColorSpace;
       }
     }
-
     return null;
   }
-
   static async parseAsync({
     cs,
     xref,
@@ -231,12 +191,9 @@ class ColorSpace {
     localColorSpaceCache
   }) {
     const parsedColorSpace = this._parse(cs, xref, resources, pdfFunctionFactory);
-
     this._cache(cs, xref, localColorSpaceCache, parsedColorSpace);
-
     return parsedColorSpace;
   }
-
   static parse({
     cs,
     xref,
@@ -245,84 +202,64 @@ class ColorSpace {
     localColorSpaceCache
   }) {
     const cachedColorSpace = this.getCached(cs, xref, localColorSpaceCache);
-
     if (cachedColorSpace) {
       return cachedColorSpace;
     }
-
     const parsedColorSpace = this._parse(cs, xref, resources, pdfFunctionFactory);
-
     this._cache(cs, xref, localColorSpaceCache, parsedColorSpace);
-
     return parsedColorSpace;
   }
-
   static _parse(cs, xref, resources = null, pdfFunctionFactory) {
     cs = xref.fetchIfRef(cs);
-
     if (cs instanceof _primitives.Name) {
       switch (cs.name) {
         case "G":
         case "DeviceGray":
           return this.singletons.gray;
-
         case "RGB":
         case "DeviceRGB":
           return this.singletons.rgb;
-
         case "CMYK":
         case "DeviceCMYK":
           return this.singletons.cmyk;
-
         case "Pattern":
           return new PatternCS(null);
-
         default:
           if (resources instanceof _primitives.Dict) {
             const colorSpaces = resources.get("ColorSpace");
-
             if (colorSpaces instanceof _primitives.Dict) {
               const resourcesCS = colorSpaces.get(cs.name);
-
               if (resourcesCS) {
                 if (resourcesCS instanceof _primitives.Name) {
                   return this._parse(resourcesCS, xref, resources, pdfFunctionFactory);
                 }
-
                 cs = resourcesCS;
                 break;
               }
             }
           }
-
           throw new _util.FormatError(`Unrecognized ColorSpace: ${cs.name}`);
       }
     }
-
     if (Array.isArray(cs)) {
       const mode = xref.fetchIfRef(cs[0]).name;
       let params, numComps, baseCS, whitePoint, blackPoint, gamma;
-
       switch (mode) {
         case "G":
         case "DeviceGray":
           return this.singletons.gray;
-
         case "RGB":
         case "DeviceRGB":
           return this.singletons.rgb;
-
         case "CMYK":
         case "DeviceCMYK":
           return this.singletons.cmyk;
-
         case "CalGray":
           params = xref.fetchIfRef(cs[1]);
           whitePoint = params.getArray("WhitePoint");
           blackPoint = params.getArray("BlackPoint");
           gamma = params.get("Gamma");
           return new CalGrayCS(whitePoint, blackPoint, gamma);
-
         case "CalRGB":
           params = xref.fetchIfRef(cs[1]);
           whitePoint = params.getArray("WhitePoint");
@@ -330,23 +267,18 @@ class ColorSpace {
           gamma = params.getArray("Gamma");
           const matrix = params.getArray("Matrix");
           return new CalRGBCS(whitePoint, blackPoint, gamma, matrix);
-
         case "ICCBased":
           const stream = xref.fetchIfRef(cs[1]);
           const dict = stream.dict;
           numComps = dict.get("N");
           const alt = dict.get("Alternate");
-
           if (alt) {
             const altCS = this._parse(alt, xref, resources, pdfFunctionFactory);
-
             if (altCS.numComps === numComps) {
               return altCS;
             }
-
             (0, _util.warn)("ICCBased color space: Ignoring incorrect /Alternate entry.");
           }
-
           if (numComps === 1) {
             return this.singletons.gray;
           } else if (numComps === 3) {
@@ -354,25 +286,19 @@ class ColorSpace {
           } else if (numComps === 4) {
             return this.singletons.cmyk;
           }
-
           break;
-
         case "Pattern":
           baseCS = cs[1] || null;
-
           if (baseCS) {
             baseCS = this._parse(baseCS, xref, resources, pdfFunctionFactory);
           }
-
           return new PatternCS(baseCS);
-
         case "I":
         case "Indexed":
           baseCS = this._parse(cs[1], xref, resources, pdfFunctionFactory);
           const hiVal = xref.fetchIfRef(cs[2]) + 1;
           const lookup = xref.fetchIfRef(cs[3]);
           return new IndexedCS(baseCS, hiVal, lookup);
-
         case "Separation":
         case "DeviceN":
           const name = xref.fetchIfRef(cs[1]);
@@ -380,62 +306,48 @@ class ColorSpace {
           baseCS = this._parse(cs[2], xref, resources, pdfFunctionFactory);
           const tintFn = pdfFunctionFactory.create(cs[3]);
           return new AlternateCS(numComps, baseCS, tintFn);
-
         case "Lab":
           params = xref.fetchIfRef(cs[1]);
           whitePoint = params.getArray("WhitePoint");
           blackPoint = params.getArray("BlackPoint");
           const range = params.getArray("Range");
           return new LabCS(whitePoint, blackPoint, range);
-
         default:
           throw new _util.FormatError(`Unimplemented ColorSpace object: ${mode}`);
       }
     }
-
     throw new _util.FormatError(`Unrecognized ColorSpace object: ${cs}`);
   }
-
   static isDefaultDecode(decode, numComps) {
     if (!Array.isArray(decode)) {
       return true;
     }
-
     if (numComps * 2 !== decode.length) {
       (0, _util.warn)("The decode map is not the correct length");
       return true;
     }
-
     for (let i = 0, ii = decode.length; i < ii; i += 2) {
       if (decode[i] !== 0 || decode[i + 1] !== 1) {
         return false;
       }
     }
-
     return true;
   }
-
   static get singletons() {
     return (0, _util.shadow)(this, "singletons", {
       get gray() {
         return (0, _util.shadow)(this, "gray", new DeviceGrayCS());
       },
-
       get rgb() {
         return (0, _util.shadow)(this, "rgb", new DeviceRgbCS());
       },
-
       get cmyk() {
         return (0, _util.shadow)(this, "cmyk", new DeviceCmykCS());
       }
-
     });
   }
-
 }
-
 exports.ColorSpace = ColorSpace;
-
 class AlternateCS extends ColorSpace {
   constructor(numComps, base, tintFn) {
     super("Alternate", numComps);
@@ -443,13 +355,11 @@ class AlternateCS extends ColorSpace {
     this.tintFn = tintFn;
     this.tmpBuf = new Float32Array(base.numComps);
   }
-
   getRgbItem(src, srcOffset, dest, destOffset) {
     const tmpBuf = this.tmpBuf;
     this.tintFn(src, srcOffset, tmpBuf, 0);
     this.base.getRgbItem(tmpBuf, 0, dest, destOffset);
   }
-
   getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
     const tintFn = this.tintFn;
     const base = this.base;
@@ -463,14 +373,11 @@ class AlternateCS extends ColorSpace {
     const scaled = new Float32Array(numComps);
     const tinted = new Float32Array(baseNumComps);
     let i, j;
-
     for (i = 0; i < count; i++) {
       for (j = 0; j < numComps; j++) {
         scaled[j] = src[srcOffset++] * scale;
       }
-
       tintFn(scaled, 0, tinted, 0);
-
       if (usesZeroToOneRange) {
         for (j = 0; j < baseNumComps; j++) {
           baseBuf[pos++] = tinted[j] * 255;
@@ -480,30 +387,23 @@ class AlternateCS extends ColorSpace {
         pos += baseNumComps;
       }
     }
-
     if (!isPassthrough) {
       base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
     }
   }
-
   getOutputLength(inputLength, alpha01) {
     return this.base.getOutputLength(inputLength * this.base.numComps / this.numComps, alpha01);
   }
-
 }
-
 class PatternCS extends ColorSpace {
   constructor(baseCS) {
     super("Pattern", null);
     this.base = baseCS;
   }
-
   isDefaultDecode(decodeMap, bpc) {
     (0, _util.unreachable)("Should not call PatternCS.isDefaultDecode");
   }
-
 }
-
 class IndexedCS extends ColorSpace {
   constructor(base, highVal, lookup) {
     super("Indexed", 1);
@@ -511,7 +411,6 @@ class IndexedCS extends ColorSpace {
     this.highVal = highVal;
     const length = base.numComps * highVal;
     this.lookup = new Uint8Array(length);
-
     if (lookup instanceof _base_stream.BaseStream) {
       const bytes = lookup.getBytes(length);
       this.lookup.set(bytes);
@@ -523,65 +422,52 @@ class IndexedCS extends ColorSpace {
       throw new _util.FormatError(`IndexedCS - unrecognized lookup table: ${lookup}`);
     }
   }
-
   getRgbItem(src, srcOffset, dest, destOffset) {
     const numComps = this.base.numComps;
     const start = src[srcOffset] * numComps;
     this.base.getRgbBuffer(this.lookup, start, 1, dest, destOffset, 8, 0);
   }
-
   getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
     const base = this.base;
     const numComps = base.numComps;
     const outputDelta = base.getOutputLength(numComps, alpha01);
     const lookup = this.lookup;
-
     for (let i = 0; i < count; ++i) {
       const lookupPos = src[srcOffset++] * numComps;
       base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);
       destOffset += outputDelta;
     }
   }
-
   getOutputLength(inputLength, alpha01) {
     return this.base.getOutputLength(inputLength * this.base.numComps, alpha01);
   }
-
   isDefaultDecode(decodeMap, bpc) {
     if (!Array.isArray(decodeMap)) {
       return true;
     }
-
     if (decodeMap.length !== 2) {
       (0, _util.warn)("Decode map length is not correct");
       return true;
     }
-
     if (!Number.isInteger(bpc) || bpc < 1) {
       (0, _util.warn)("Bits per component is not correct");
       return true;
     }
-
     return decodeMap[0] === 0 && decodeMap[1] === (1 << bpc) - 1;
   }
-
 }
-
 class DeviceGrayCS extends ColorSpace {
   constructor() {
     super("DeviceGray", 1);
   }
-
   getRgbItem(src, srcOffset, dest, destOffset) {
     const c = src[srcOffset] * 255;
     dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;
   }
-
   getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
     const scale = 255 / ((1 << bits) - 1);
     let j = srcOffset,
-        q = destOffset;
-
+      q = destOffset;
     for (let i = 0; i < count; ++i) {
       const c = scale * src[j++];
       dest[q++] = c;
@@ -590,34 +476,27 @@ class DeviceGrayCS extends ColorSpace {
       q += alpha01;
     }
   }
-
   getOutputLength(inputLength, alpha01) {
     return inputLength * (3 + alpha01);
   }
-
 }
-
 class DeviceRgbCS extends ColorSpace {
   constructor() {
     super("DeviceRGB", 3);
   }
-
   getRgbItem(src, srcOffset, dest, destOffset) {
     dest[destOffset] = src[srcOffset] * 255;
     dest[destOffset + 1] = src[srcOffset + 1] * 255;
     dest[destOffset + 2] = src[srcOffset + 2] * 255;
   }
-
   getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
     if (bits === 8 && alpha01 === 0) {
       dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);
       return;
     }
-
     const scale = 255 / ((1 << bits) - 1);
     let j = srcOffset,
-        q = destOffset;
-
+      q = destOffset;
     for (let i = 0; i < count; ++i) {
       dest[q++] = scale * src[j++];
       dest[q++] = scale * src[j++];
@@ -625,17 +504,13 @@ class DeviceRgbCS extends ColorSpace {
       q += alpha01;
     }
   }
-
   getOutputLength(inputLength, alpha01) {
     return inputLength * (3 + alpha01) / 3 | 0;
   }
-
   isPassthrough(bits) {
     return bits === 8;
   }
-
 }
-
 const DeviceCmykCS = function DeviceCmykCSClosure() {
   function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {
     const c = src[srcOffset] * srcScale;
@@ -646,35 +521,27 @@ const DeviceCmykCS = function DeviceCmykCSClosure() {
     dest[destOffset + 1] = 255 + c * (8.841041422036149 * c + 60.118027045597366 * m + 6.871425592049007 * y + 31.159100130055922 * k + -79.2970844816548) + m * (-15.310361306967817 * m + 17.575251261109482 * y + 131.35250912493976 * k - 190.9453302588951) + y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) + k * (-20.737325471181034 * k - 187.80453709719578);
     dest[destOffset + 2] = 255 + c * (0.8842522430003296 * c + 8.078677503112928 * m + 30.89978309703729 * y - 0.23883238689178934 * k + -14.183576799673286) + m * (10.49593273432072 * m + 63.02378494754052 * y + 50.606957656360734 * k - 112.23884253719248) + y * (0.03296041114873217 * y + 115.60384449646641 * k + -193.58209356861505) + k * (-22.33816807309886 * k - 180.12613974708367);
   }
-
   class DeviceCmykCS extends ColorSpace {
     constructor() {
       super("DeviceCMYK", 4);
     }
-
     getRgbItem(src, srcOffset, dest, destOffset) {
       convertToRgb(src, srcOffset, 1, dest, destOffset);
     }
-
     getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
       const scale = 1 / ((1 << bits) - 1);
-
       for (let i = 0; i < count; i++) {
         convertToRgb(src, srcOffset, scale, dest, destOffset);
         srcOffset += 4;
         destOffset += 3 + alpha01;
       }
     }
-
     getOutputLength(inputLength, alpha01) {
       return inputLength / 4 * (3 + alpha01) | 0;
     }
-
   }
-
   return DeviceCmykCS;
 }();
-
 const CalGrayCS = function CalGrayCSClosure() {
   function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
     const A = src[srcOffset] * scale;
@@ -685,15 +552,12 @@ const CalGrayCS = function CalGrayCSClosure() {
     dest[destOffset + 1] = val;
     dest[destOffset + 2] = val;
   }
-
   class CalGrayCS extends ColorSpace {
     constructor(whitePoint, blackPoint, gamma) {
       super("CalGray", 1);
-
       if (!whitePoint) {
         throw new _util.FormatError("WhitePoint missing - required for color space CalGray");
       }
-
       blackPoint = blackPoint || [0, 0, 0];
       gamma = gamma || 1;
       this.XW = whitePoint[0];
@@ -703,49 +567,38 @@ const CalGrayCS = function CalGrayCSClosure() {
       this.YB = blackPoint[1];
       this.ZB = blackPoint[2];
       this.G = gamma;
-
       if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
         throw new _util.FormatError(`Invalid WhitePoint components for ${this.name}` + ", no fallback available");
       }
-
       if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
         (0, _util.info)(`Invalid BlackPoint for ${this.name}, falling back to default.`);
         this.XB = this.YB = this.ZB = 0;
       }
-
       if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
         (0, _util.warn)(`${this.name}, BlackPoint: XB: ${this.XB}, YB: ${this.YB}, ` + `ZB: ${this.ZB}, only default values are supported.`);
       }
-
       if (this.G < 1) {
         (0, _util.info)(`Invalid Gamma: ${this.G} for ${this.name}, ` + "falling back to default.");
         this.G = 1;
       }
     }
-
     getRgbItem(src, srcOffset, dest, destOffset) {
       convertToRgb(this, src, srcOffset, dest, destOffset, 1);
     }
-
     getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
       const scale = 1 / ((1 << bits) - 1);
-
       for (let i = 0; i < count; ++i) {
         convertToRgb(this, src, srcOffset, dest, destOffset, scale);
         srcOffset += 1;
         destOffset += 3 + alpha01;
       }
     }
-
     getOutputLength(inputLength, alpha01) {
       return inputLength * (3 + alpha01);
     }
-
   }
-
   return CalGrayCS;
 }();
-
 const CalRGBCS = function CalRGBCSClosure() {
   const BRADFORD_SCALE_MATRIX = new Float32Array([0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296]);
   const BRADFORD_SCALE_INVERSE_MATRIX = new Float32Array([0.9869929, -0.1470543, 0.1599627, 0.4323053, 0.5183603, 0.0492912, -0.0085287, 0.0400428, 0.9684867]);
@@ -755,19 +608,16 @@ const CalRGBCS = function CalRGBCSClosure() {
   const tempConvertMatrix1 = new Float32Array(3);
   const tempConvertMatrix2 = new Float32Array(3);
   const DECODE_L_CONSTANT = ((8 + 16) / 116) ** 3 / 8.0;
-
   function matrixProduct(a, b, result) {
     result[0] = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
     result[1] = a[3] * b[0] + a[4] * b[1] + a[5] * b[2];
     result[2] = a[6] * b[0] + a[7] * b[1] + a[8] * b[2];
   }
-
   function convertToFlat(sourceWhitePoint, LMS, result) {
     result[0] = LMS[0] * 1 / sourceWhitePoint[0];
     result[1] = LMS[1] * 1 / sourceWhitePoint[1];
     result[2] = LMS[2] * 1 / sourceWhitePoint[2];
   }
-
   function convertToD65(sourceWhitePoint, LMS, result) {
     const D65X = 0.95047;
     const D65Y = 1;
@@ -776,35 +626,27 @@ const CalRGBCS = function CalRGBCSClosure() {
     result[1] = LMS[1] * D65Y / sourceWhitePoint[1];
     result[2] = LMS[2] * D65Z / sourceWhitePoint[2];
   }
-
   function sRGBTransferFunction(color) {
     if (color <= 0.0031308) {
       return adjustToRange(0, 1, 12.92 * color);
     }
-
     if (color >= 0.99554525) {
       return 1;
     }
-
     return adjustToRange(0, 1, (1 + 0.055) * color ** (1 / 2.4) - 0.055);
   }
-
   function adjustToRange(min, max, value) {
     return Math.max(min, Math.min(max, value));
   }
-
   function decodeL(L) {
     if (L < 0) {
       return -decodeL(-L);
     }
-
     if (L > 8.0) {
       return ((L + 16) / 116) ** 3;
     }
-
     return L * DECODE_L_CONSTANT;
   }
-
   function compensateBlackPoint(sourceBlackPoint, XYZ_Flat, result) {
     if (sourceBlackPoint[0] === 0 && sourceBlackPoint[1] === 0 && sourceBlackPoint[2] === 0) {
       result[0] = XYZ_Flat[0];
@@ -812,7 +654,6 @@ const CalRGBCS = function CalRGBCSClosure() {
       result[2] = XYZ_Flat[2];
       return;
     }
-
     const zeroDecodeL = decodeL(0);
     const X_DST = zeroDecodeL;
     const X_SRC = decodeL(sourceBlackPoint[0]);
@@ -830,7 +671,6 @@ const CalRGBCS = function CalRGBCSClosure() {
     result[1] = XYZ_Flat[1] * Y_Scale + Y_Offset;
     result[2] = XYZ_Flat[2] * Z_Scale + Z_Offset;
   }
-
   function normalizeWhitePointToFlat(sourceWhitePoint, XYZ_In, result) {
     if (sourceWhitePoint[0] === 1 && sourceWhitePoint[2] === 1) {
       result[0] = XYZ_In[0];
@@ -838,14 +678,12 @@ const CalRGBCS = function CalRGBCSClosure() {
       result[2] = XYZ_In[2];
       return;
     }
-
     const LMS = result;
     matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
     const LMS_Flat = tempNormalizeMatrix;
     convertToFlat(sourceWhitePoint, LMS, LMS_Flat);
     matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_Flat, result);
   }
-
   function normalizeWhitePointToD65(sourceWhitePoint, XYZ_In, result) {
     const LMS = result;
     matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
@@ -853,7 +691,6 @@ const CalRGBCS = function CalRGBCSClosure() {
     convertToD65(sourceWhitePoint, LMS, LMS_D65);
     matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_D65, result);
   }
-
   function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
     const A = adjustToRange(0, 1, src[srcOffset] * scale);
     const B = adjustToRange(0, 1, src[srcOffset + 1] * scale);
@@ -880,15 +717,12 @@ const CalRGBCS = function CalRGBCSClosure() {
     dest[destOffset + 1] = sRGBTransferFunction(SRGB[1]) * 255;
     dest[destOffset + 2] = sRGBTransferFunction(SRGB[2]) * 255;
   }
-
   class CalRGBCS extends ColorSpace {
     constructor(whitePoint, blackPoint, gamma, matrix) {
       super("CalRGB", 3);
-
       if (!whitePoint) {
         throw new _util.FormatError("WhitePoint missing - required for color space CalRGB");
       }
-
       blackPoint = blackPoint || new Float32Array(3);
       gamma = gamma || new Float32Array([1, 1, 1]);
       matrix = matrix || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
@@ -912,85 +746,67 @@ const CalRGBCS = function CalRGBCSClosure() {
       this.MXC = matrix[6];
       this.MYC = matrix[7];
       this.MZC = matrix[8];
-
       if (XW < 0 || ZW < 0 || YW !== 1) {
         throw new _util.FormatError(`Invalid WhitePoint components for ${this.name}` + ", no fallback available");
       }
-
       if (XB < 0 || YB < 0 || ZB < 0) {
         (0, _util.info)(`Invalid BlackPoint for ${this.name} [${XB}, ${YB}, ${ZB}], ` + "falling back to default.");
         this.blackPoint = new Float32Array(3);
       }
-
       if (this.GR < 0 || this.GG < 0 || this.GB < 0) {
         (0, _util.info)(`Invalid Gamma [${this.GR}, ${this.GG}, ${this.GB}] for ` + `${this.name}, falling back to default.`);
         this.GR = this.GG = this.GB = 1;
       }
     }
-
     getRgbItem(src, srcOffset, dest, destOffset) {
       convertToRgb(this, src, srcOffset, dest, destOffset, 1);
     }
-
     getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
       const scale = 1 / ((1 << bits) - 1);
-
       for (let i = 0; i < count; ++i) {
         convertToRgb(this, src, srcOffset, dest, destOffset, scale);
         srcOffset += 3;
         destOffset += 3 + alpha01;
       }
     }
-
     getOutputLength(inputLength, alpha01) {
       return inputLength * (3 + alpha01) / 3 | 0;
     }
-
   }
-
   return CalRGBCS;
 }();
-
 const LabCS = function LabCSClosure() {
   function fn_g(x) {
     let result;
-
     if (x >= 6 / 29) {
       result = x ** 3;
     } else {
       result = 108 / 841 * (x - 4 / 29);
     }
-
     return result;
   }
-
   function decode(value, high1, low2, high2) {
     return low2 + value * (high2 - low2) / high1;
   }
-
   function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
     let Ls = src[srcOffset];
     let as = src[srcOffset + 1];
     let bs = src[srcOffset + 2];
-
     if (maxVal !== false) {
       Ls = decode(Ls, maxVal, 0, 100);
       as = decode(as, maxVal, cs.amin, cs.amax);
       bs = decode(bs, maxVal, cs.bmin, cs.bmax);
     }
-
     if (as > cs.amax) {
       as = cs.amax;
     } else if (as < cs.amin) {
       as = cs.amin;
     }
-
     if (bs > cs.bmax) {
       bs = cs.bmax;
     } else if (bs < cs.bmin) {
       bs = cs.bmin;
     }
-
     const M = (Ls + 16) / 116;
     const L = M + as / 500;
     const N = M - bs / 200;
@@ -998,7 +814,6 @@ const LabCS = function LabCSClosure() {
     const Y = cs.YW * fn_g(M);
     const Z = cs.ZW * fn_g(N);
     let r, g, b;
-
     if (cs.ZW < 1) {
       r = X * 3.1339 + Y * -1.617 + Z * -0.4906;
       g = X * -0.9785 + Y * 1.916 + Z * 0.0333;
@@ -1008,20 +823,16 @@ const LabCS = function LabCSClosure() {
       g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
       b = X * 0.0557 + Y * -0.204 + Z * 1.057;
     }
-
     dest[destOffset] = Math.sqrt(r) * 255;
     dest[destOffset + 1] = Math.sqrt(g) * 255;
     dest[destOffset + 2] = Math.sqrt(b) * 255;
   }
-
   class LabCS extends ColorSpace {
     constructor(whitePoint, blackPoint, range) {
       super("Lab", 3);
-
       if (!whitePoint) {
         throw new _util.FormatError("WhitePoint missing - required for color space Lab");
       }
-
       blackPoint = blackPoint || [0, 0, 0];
       range = range || [-100, 100, -100, 100];
       this.XW = whitePoint[0];
@@ -1034,16 +845,13 @@ const LabCS = function LabCSClosure() {
       this.XB = blackPoint[0];
       this.YB = blackPoint[1];
       this.ZB = blackPoint[2];
-
       if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
         throw new _util.FormatError("Invalid WhitePoint components, no fallback available");
       }
-
       if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
         (0, _util.info)("Invalid BlackPoint, falling back to default");
         this.XB = this.YB = this.ZB = 0;
       }
-
       if (this.amin > this.amax || this.bmin > this.bmax) {
         (0, _util.info)("Invalid Range, falling back to defaults");
         this.amin = -100;
@@ -1052,34 +860,26 @@ const LabCS = function LabCSClosure() {
         this.bmax = 100;
       }
     }
-
     getRgbItem(src, srcOffset, dest, destOffset) {
       convertToRgb(this, src, srcOffset, false, dest, destOffset);
     }
-
     getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
       const maxVal = (1 << bits) - 1;
-
       for (let i = 0; i < count; i++) {
         convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);
         srcOffset += 3;
         destOffset += 3 + alpha01;
       }
     }
-
     getOutputLength(inputLength, alpha01) {
       return inputLength * (3 + alpha01) / 3 | 0;
     }
-
     isDefaultDecode(decodeMap, bpc) {
       return true;
     }
-
     get usesZeroToOneRange() {
       return (0, _util.shadow)(this, "usesZeroToOneRange", false);
     }
-
   }
-
   return LabCS;
 }();

+ 4 - 118
lib/core/core_utils.js

@@ -24,7 +24,7 @@
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
-exports.XRefParseException = exports.XRefEntryException = exports.ParserEOFException = exports.MissingDataException = exports.DocStats = void 0;
+exports.XRefParseException = exports.XRefEntryException = exports.ParserEOFException = exports.PDF_VERSION_REGEXP = exports.MissingDataException = exports.DocStats = void 0;
 exports.collectActions = collectActions;
 exports.encodeToXmlString = encodeToXmlString;
 exports.escapePDFName = escapePDFName;
@@ -42,13 +42,11 @@ exports.readUint32 = readUint32;
 exports.recoverJsURL = recoverJsURL;
 exports.toRomanNumerals = toRomanNumerals;
 exports.validateCSSFont = validateCSSFont;
-
 var _util = require("../shared/util.js");
-
 var _primitives = require("./primitives.js");
-
 var _base_stream = require("./base_stream.js");
-
+const PDF_VERSION_REGEXP = /^[1-9]\.\d$/;
+exports.PDF_VERSION_REGEXP = PDF_VERSION_REGEXP;
 function getLookupTableFactory(initializer) {
   let lookup;
   return function () {
@@ -57,11 +55,9 @@ function getLookupTableFactory(initializer) {
       initializer(lookup);
       initializer = null;
     }
-
     return lookup;
   };
 }
-
 function getArrayLookupTableFactory(initializer) {
   let lookup;
   return function () {
@@ -69,105 +65,76 @@ function getArrayLookupTableFactory(initializer) {
       let arr = initializer();
       initializer = null;
       lookup = Object.create(null);
-
       for (let i = 0, ii = arr.length; i < ii; i += 2) {
         lookup[arr[i]] = arr[i + 1];
       }
-
       arr = null;
     }
-
     return lookup;
   };
 }
-
 class MissingDataException extends _util.BaseException {
   constructor(begin, end) {
     super(`Missing data [${begin}, ${end})`, "MissingDataException");
     this.begin = begin;
     this.end = end;
   }
-
 }
-
 exports.MissingDataException = MissingDataException;
-
 class ParserEOFException extends _util.BaseException {
   constructor(msg) {
     super(msg, "ParserEOFException");
   }
-
 }
-
 exports.ParserEOFException = ParserEOFException;
-
 class XRefEntryException extends _util.BaseException {
   constructor(msg) {
     super(msg, "XRefEntryException");
   }
-
 }
-
 exports.XRefEntryException = XRefEntryException;
-
 class XRefParseException extends _util.BaseException {
   constructor(msg) {
     super(msg, "XRefParseException");
   }
-
 }
-
 exports.XRefParseException = XRefParseException;
-
 class DocStats {
   constructor(handler) {
     this._handler = handler;
     this._streamTypes = new Set();
     this._fontTypes = new Set();
   }
-
   _send() {
     const streamTypes = Object.create(null),
-          fontTypes = Object.create(null);
-
+      fontTypes = Object.create(null);
     for (const type of this._streamTypes) {
       streamTypes[type] = true;
     }
-
     for (const type of this._fontTypes) {
       fontTypes[type] = true;
     }
-
     this._handler.send("DocStats", {
       streamTypes,
       fontTypes
     });
   }
-
   addStreamType(type) {
     if (this._streamTypes.has(type)) {
       return;
     }
-
     this._streamTypes.add(type);
-
     this._send();
   }
-
   addFontType(type) {
     if (this._fontTypes.has(type)) {
       return;
     }
-
     this._fontTypes.add(type);
-
     this._send();
   }
-
 }
-
 exports.DocStats = DocStats;
-
 function getInheritableProperty({
   dict,
   key,
@@ -176,44 +143,33 @@ function getInheritableProperty({
 }) {
   let values;
   const visited = new _primitives.RefSet();
-
   while (dict instanceof _primitives.Dict && !(dict.objId && visited.has(dict.objId))) {
     if (dict.objId) {
       visited.put(dict.objId);
     }
-
     const value = getArray ? dict.getArray(key) : dict.get(key);
-
     if (value !== undefined) {
       if (stopWhenFound) {
         return value;
       }
-
       if (!values) {
         values = [];
       }
-
       values.push(value);
     }
-
     dict = dict.get("Parent");
   }
-
   return values;
 }
-
 const ROMAN_NUMBER_MAP = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
-
 function toRomanNumerals(number, lowerCase = false) {
   (0, _util.assert)(Number.isInteger(number) && number > 0, "The number should be a positive integer.");
   const romanBuf = [];
   let pos;
-
   while (number >= 1000) {
     number -= 1000;
     romanBuf.push("M");
   }
-
   pos = number / 100 | 0;
   number %= 100;
   romanBuf.push(ROMAN_NUMBER_MAP[pos]);
@@ -224,95 +180,74 @@ function toRomanNumerals(number, lowerCase = false) {
   const romanStr = romanBuf.join("");
   return lowerCase ? romanStr.toLowerCase() : romanStr;
 }
-
 function log2(x) {
   if (x <= 0) {
     return 0;
   }
-
   return Math.ceil(Math.log2(x));
 }
-
 function readInt8(data, offset) {
   return data[offset] << 24 >> 24;
 }
-
 function readUint16(data, offset) {
   return data[offset] << 8 | data[offset + 1];
 }
-
 function readUint32(data, offset) {
   return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
 }
-
 function isWhiteSpace(ch) {
   return ch === 0x20 || ch === 0x09 || ch === 0x0d || ch === 0x0a;
 }
-
 function parseXFAPath(path) {
   const positionPattern = /(.+)\[(\d+)\]$/;
   return path.split(".").map(component => {
     const m = component.match(positionPattern);
-
     if (m) {
       return {
         name: m[1],
         pos: parseInt(m[2], 10)
       };
     }
-
     return {
       name: component,
       pos: 0
     };
   });
 }
-
 function escapePDFName(str) {
   const buffer = [];
   let start = 0;
-
   for (let i = 0, ii = str.length; i < ii; i++) {
     const char = str.charCodeAt(i);
-
     if (char < 0x21 || char > 0x7e || char === 0x23 || char === 0x28 || char === 0x29 || char === 0x3c || char === 0x3e || char === 0x5b || char === 0x5d || char === 0x7b || char === 0x7d || char === 0x2f || char === 0x25) {
       if (start < i) {
         buffer.push(str.substring(start, i));
       }
-
       buffer.push(`#${char.toString(16)}`);
       start = i + 1;
     }
   }
-
   if (buffer.length === 0) {
     return str;
   }
-
   if (start < str.length) {
     buffer.push(str.substring(start, str.length));
   }
-
   return buffer.join("");
 }
-
 function _collectJS(entry, xref, list, parents) {
   if (!entry) {
     return;
   }
-
   let parent = null;
-
   if (entry instanceof _primitives.Ref) {
     if (parents.has(entry)) {
       return;
     }
-
     parent = entry;
     parents.put(parent);
     entry = xref.fetch(entry);
   }
-
   if (Array.isArray(entry)) {
     for (const element of entry) {
       _collectJS(element, xref, list, parents);
@@ -321,28 +256,22 @@ function _collectJS(entry, xref, list, parents) {
     if ((0, _primitives.isName)(entry.get("S"), "JavaScript")) {
       const js = entry.get("JS");
       let code;
-
       if (js instanceof _base_stream.BaseStream) {
         code = js.getString();
       } else if (typeof js === "string") {
         code = js;
       }
-
       code = code && (0, _util.stringToPDFString)(code).replace(/\u0000/g, "");
-
       if (code) {
         list.push(code);
       }
     }
-
     _collectJS(entry.getRaw("Next"), xref, list, parents);
   }
-
   if (parent) {
     parents.remove(parent);
   }
 }
-
 function collectActions(xref, dict, eventType) {
   const actions = Object.create(null);
   const additionalActionsDicts = getInheritableProperty({
@@ -350,50 +279,38 @@ function collectActions(xref, dict, eventType) {
     key: "AA",
     stopWhenFound: false
   });
-
   if (additionalActionsDicts) {
     for (let i = additionalActionsDicts.length - 1; i >= 0; i--) {
       const additionalActions = additionalActionsDicts[i];
-
       if (!(additionalActions instanceof _primitives.Dict)) {
         continue;
       }
-
       for (const key of additionalActions.getKeys()) {
         const action = eventType[key];
-
         if (!action) {
           continue;
         }
-
         const actionDict = additionalActions.getRaw(key);
         const parents = new _primitives.RefSet();
         const list = [];
-
         _collectJS(actionDict, xref, list, parents);
-
         if (list.length > 0) {
           actions[action] = list;
         }
       }
     }
   }
-
   if (dict.has("A")) {
     const actionDict = dict.get("A");
     const parents = new _primitives.RefSet();
     const list = [];
-
     _collectJS(actionDict, xref, list, parents);
-
     if (list.length > 0) {
       actions.Action = list;
     }
   }
-
   return (0, _util.objectSize)(actions) > 0 ? actions : null;
 }
-
 const XMLEntities = {
   0x3c: "&lt;",
   0x3e: "&gt;",
@@ -401,22 +318,17 @@ const XMLEntities = {
   0x22: "&quot;",
   0x27: "&apos;"
 };
-
 function encodeToXmlString(str) {
   const buffer = [];
   let start = 0;
-
   for (let i = 0, ii = str.length; i < ii; i++) {
     const char = str.codePointAt(i);
-
     if (0x20 <= char && char <= 0x7e) {
       const entity = XMLEntities[char];
-
       if (entity) {
         if (start < i) {
           buffer.push(str.substring(start, i));
         }
-
         buffer.push(entity);
         start = i + 1;
       }
@@ -424,28 +336,21 @@ function encodeToXmlString(str) {
       if (start < i) {
         buffer.push(str.substring(start, i));
       }
-
       buffer.push(`&#x${char.toString(16).toUpperCase()};`);
-
       if (char > 0xd7ff && (char < 0xe000 || char > 0xfffd)) {
         i++;
       }
-
       start = i + 1;
     }
   }
-
   if (buffer.length === 0) {
     return str;
   }
-
   if (start < str.length) {
     buffer.push(str.substring(start, str.length));
   }
-
   return buffer.join("");
 }
-
 function validateCSSFont(cssFontInfo) {
   const DEFAULT_CSS_FONT_OBLIQUE = "14";
   const DEFAULT_CSS_FONT_WEIGHT = "400";
@@ -455,7 +360,6 @@ function validateCSSFont(cssFontInfo) {
     fontWeight,
     italicAngle
   } = cssFontInfo;
-
   if (/^".*"$/.test(fontFamily)) {
     if (/[^\\]"/.test(fontFamily.slice(1, fontFamily.length - 1))) {
       (0, _util.warn)(`XFA - FontFamily contains some unescaped ": ${fontFamily}.`);
@@ -474,75 +378,57 @@ function validateCSSFont(cssFontInfo) {
       }
     }
   }
-
   const weight = fontWeight ? fontWeight.toString() : "";
   cssFontInfo.fontWeight = CSS_FONT_WEIGHT_VALUES.has(weight) ? weight : DEFAULT_CSS_FONT_WEIGHT;
   const angle = parseFloat(italicAngle);
   cssFontInfo.italicAngle = isNaN(angle) || angle < -90 || angle > 90 ? DEFAULT_CSS_FONT_OBLIQUE : italicAngle.toString();
   return true;
 }
-
 function recoverJsURL(str) {
   const URL_OPEN_METHODS = ["app.launchURL", "window.open", "xfa.host.gotoURL"];
   const regex = new RegExp("^\\s*(" + URL_OPEN_METHODS.join("|").split(".").join("\\.") + ")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))", "i");
   const jsUrl = regex.exec(str);
-
   if (jsUrl && jsUrl[2]) {
     const url = jsUrl[2];
     let newWindow = false;
-
     if (jsUrl[3] === "true" && jsUrl[1] === "app.launchURL") {
       newWindow = true;
     }
-
     return {
       url,
       newWindow
     };
   }
-
   return null;
 }
-
 function numberToString(value) {
   if (Number.isInteger(value)) {
     return value.toString();
   }
-
   const roundedValue = Math.round(value * 100);
-
   if (roundedValue % 100 === 0) {
     return (roundedValue / 100).toString();
   }
-
   if (roundedValue % 10 === 0) {
     return value.toFixed(1);
   }
-
   return value.toFixed(2);
 }
-
 function getNewAnnotationsMap(annotationStorage) {
   if (!annotationStorage) {
     return null;
   }
-
   const newAnnotationsByPage = new Map();
-
   for (const [key, value] of annotationStorage) {
     if (!key.startsWith(_util.AnnotationEditorPrefix)) {
       continue;
     }
-
     let annotations = newAnnotationsByPage.get(value.pageIndex);
-
     if (!annotations) {
       annotations = [];
       newAnnotationsByPage.set(value.pageIndex, annotations);
     }
-
     annotations.push(value);
   }
-
   return newAnnotationsByPage.size > 0 ? newAnnotationsByPage : null;
 }

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 27 - 99
lib/core/crypto.js


+ 0 - 19
lib/core/dataset_reader.js

@@ -25,13 +25,9 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.DatasetReader = void 0;
-
 var _util = require("../shared/util.js");
-
 var _core_utils = require("./core_utils.js");
-
 var _xml_parser = require("./xml_parser.js");
-
 function decodeString(str) {
   try {
     return (0, _util.stringToUTF8String)(str);
@@ -40,24 +36,19 @@ function decodeString(str) {
     return str;
   }
 }
-
 class DatasetXMLParser extends _xml_parser.SimpleXMLParser {
   constructor(options) {
     super(options);
     this.node = null;
   }
-
   onEndElement(name) {
     const node = super.onEndElement(name);
-
     if (node && name === "xfa:datasets") {
       this.node = node;
       throw new Error("Aborting DatasetXMLParser.");
     }
   }
-
 }
-
 class DatasetReader {
   constructor(data) {
     if (data.datasets) {
@@ -68,35 +59,25 @@ class DatasetReader {
       const parser = new DatasetXMLParser({
         hasAttributes: true
       });
-
       try {
         parser.parseFromString(data["xdp:xdp"]);
       } catch (_) {}
-
       this.node = parser.node;
     }
   }
-
   getValue(path) {
     if (!this.node || !path) {
       return "";
     }
-
     const node = this.node.searchNode((0, _core_utils.parseXFAPath)(path), 0);
-
     if (!node) {
       return "";
     }
-
     const first = node.firstChild;
-
     if (first && first.nodeName === "value") {
       return node.children.map(child => decodeString(child.textContent));
     }
-
     return decodeString(node.textContent);
   }
-
 }
-
 exports.DatasetReader = DatasetReader;

+ 0 - 46
lib/core/decode_stream.js

@@ -25,13 +25,9 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.StreamsSequenceStream = exports.DecodeStream = void 0;
-
 var _base_stream = require("./base_stream.js");
-
 var _stream = require("./stream.js");
-
 const emptyBuffer = new Uint8Array(0);
-
 class DecodeStream extends _base_stream.BaseStream {
   constructor(maybeMinBufferLength) {
     super();
@@ -41,68 +37,51 @@ class DecodeStream extends _base_stream.BaseStream {
     this.eof = false;
     this.buffer = emptyBuffer;
     this.minBufferLength = 512;
-
     if (maybeMinBufferLength) {
       while (this.minBufferLength < maybeMinBufferLength) {
         this.minBufferLength *= 2;
       }
     }
   }
-
   get isEmpty() {
     while (!this.eof && this.bufferLength === 0) {
       this.readBlock();
     }
-
     return this.bufferLength === 0;
   }
-
   ensureBuffer(requested) {
     const buffer = this.buffer;
-
     if (requested <= buffer.byteLength) {
       return buffer;
     }
-
     let size = this.minBufferLength;
-
     while (size < requested) {
       size *= 2;
     }
-
     const buffer2 = new Uint8Array(size);
     buffer2.set(buffer);
     return this.buffer = buffer2;
   }
-
   getByte() {
     const pos = this.pos;
-
     while (this.bufferLength <= pos) {
       if (this.eof) {
         return -1;
       }
-
       this.readBlock();
     }
-
     return this.buffer[this.pos++];
   }
-
   getBytes(length) {
     const pos = this.pos;
     let end;
-
     if (length) {
       this.ensureBuffer(pos + length);
       end = pos + length;
-
       while (!this.eof && this.bufferLength < end) {
         this.readBlock();
       }
-
       const bufEnd = this.bufferLength;
-
       if (end > bufEnd) {
         end = bufEnd;
       }
@@ -110,18 +89,14 @@ class DecodeStream extends _base_stream.BaseStream {
       while (!this.eof) {
         this.readBlock();
       }
-
       end = this.bufferLength;
     }
-
     this.pos = end;
     return this.buffer.subarray(pos, end);
   }
-
   reset() {
     this.pos = 0;
   }
-
   makeSubStream(start, length, dict = null) {
     if (length === undefined) {
       while (!this.eof) {
@@ -129,80 +104,59 @@ class DecodeStream extends _base_stream.BaseStream {
       }
     } else {
       const end = start + length;
-
       while (this.bufferLength <= end && !this.eof) {
         this.readBlock();
       }
     }
-
     return new _stream.Stream(this.buffer, start, length, dict);
   }
-
   getBaseStreams() {
     return this.str ? this.str.getBaseStreams() : null;
   }
-
 }
-
 exports.DecodeStream = DecodeStream;
-
 class StreamsSequenceStream extends DecodeStream {
   constructor(streams, onError = null) {
     let maybeLength = 0;
-
     for (const stream of streams) {
       maybeLength += stream instanceof DecodeStream ? stream._rawMinBufferLength : stream.length;
     }
-
     super(maybeLength);
     this.streams = streams;
     this._onError = onError;
   }
-
   readBlock() {
     const streams = this.streams;
-
     if (streams.length === 0) {
       this.eof = true;
       return;
     }
-
     const stream = streams.shift();
     let chunk;
-
     try {
       chunk = stream.getBytes();
     } catch (reason) {
       if (this._onError) {
         this._onError(reason, stream.dict && stream.dict.objId);
-
         return;
       }
-
       throw reason;
     }
-
     const bufferLength = this.bufferLength;
     const newLength = bufferLength + chunk.length;
     const buffer = this.ensureBuffer(newLength);
     buffer.set(chunk, bufferLength);
     this.bufferLength = newLength;
   }
-
   getBaseStreams() {
     const baseStreamsBuf = [];
-
     for (const stream of this.streams) {
       const baseStreams = stream.getBaseStreams();
-
       if (baseStreams) {
         baseStreamsBuf.push(...baseStreams);
       }
     }
-
     return baseStreamsBuf.length > 0 ? baseStreamsBuf : null;
   }
-
 }
-
 exports.StreamsSequenceStream = StreamsSequenceStream;

+ 5 - 18
lib/core/decrypt_stream.js

@@ -25,11 +25,8 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.DecryptStream = void 0;
-
 var _decode_stream = require("./decode_stream.js");
-
 const chunkSize = 512;
-
 class DecryptStream extends _decode_stream.DecodeStream {
   constructor(str, maybeLength, decrypt) {
     super(maybeLength);
@@ -39,37 +36,27 @@ class DecryptStream extends _decode_stream.DecodeStream {
     this.nextChunk = null;
     this.initialized = false;
   }
-
   readBlock() {
     let chunk;
-
     if (this.initialized) {
       chunk = this.nextChunk;
     } else {
       chunk = this.str.getBytes(chunkSize);
       this.initialized = true;
     }
-
     if (!chunk || chunk.length === 0) {
       this.eof = true;
       return;
     }
-
     this.nextChunk = this.str.getBytes(chunkSize);
     const hasMoreData = this.nextChunk && this.nextChunk.length > 0;
     const decrypt = this.decrypt;
     chunk = decrypt(chunk, !hasMoreData);
-    let bufferLength = this.bufferLength;
-    const n = chunk.length,
-          buffer = this.ensureBuffer(bufferLength + n);
-
-    for (let i = 0; i < n; i++) {
-      buffer[bufferLength++] = chunk[i];
-    }
-
-    this.bufferLength = bufferLength;
+    const bufferLength = this.bufferLength,
+      newLength = bufferLength + chunk.length,
+      buffer = this.ensureBuffer(newLength);
+    buffer.set(chunk, bufferLength);
+    this.bufferLength = newLength;
   }
-
 }
-
 exports.DecryptStream = DecryptStream;

+ 1 - 29
lib/core/default_appearance.js

@@ -27,24 +27,16 @@ Object.defineProperty(exports, "__esModule", {
 exports.createDefaultAppearance = createDefaultAppearance;
 exports.getPdfColor = getPdfColor;
 exports.parseDefaultAppearance = parseDefaultAppearance;
-
 var _core_utils = require("./core_utils.js");
-
 var _util = require("../shared/util.js");
-
 var _colorspace = require("./colorspace.js");
-
 var _evaluator = require("./evaluator.js");
-
 var _primitives = require("./primitives.js");
-
 var _stream = require("./stream.js");
-
 class DefaultAppearanceEvaluator extends _evaluator.EvaluatorPreprocessor {
   constructor(str) {
     super(new _stream.StringStream(str));
   }
-
   parse() {
     const operation = {
       fn: 0,
@@ -55,76 +47,56 @@ class DefaultAppearanceEvaluator extends _evaluator.EvaluatorPreprocessor {
       fontName: "",
       fontColor: new Uint8ClampedArray(3)
     };
-
     try {
       while (true) {
         operation.args.length = 0;
-
         if (!this.read(operation)) {
           break;
         }
-
         if (this.savedStatesDepth !== 0) {
           continue;
         }
-
         const {
           fn,
           args
         } = operation;
-
         switch (fn | 0) {
           case _util.OPS.setFont:
             const [fontName, fontSize] = args;
-
             if (fontName instanceof _primitives.Name) {
               result.fontName = fontName.name;
             }
-
             if (typeof fontSize === "number" && fontSize > 0) {
               result.fontSize = fontSize;
             }
-
             break;
-
           case _util.OPS.setFillRGBColor:
             _colorspace.ColorSpace.singletons.rgb.getRgbItem(args, 0, result.fontColor, 0);
-
             break;
-
           case _util.OPS.setFillGray:
             _colorspace.ColorSpace.singletons.gray.getRgbItem(args, 0, result.fontColor, 0);
-
             break;
-
           case _util.OPS.setFillColorSpace:
             _colorspace.ColorSpace.singletons.cmyk.getRgbItem(args, 0, result.fontColor, 0);
-
             break;
         }
       }
     } catch (reason) {
       (0, _util.warn)(`parseDefaultAppearance - ignoring errors: "${reason}".`);
     }
-
     return result;
   }
-
 }
-
 function parseDefaultAppearance(str) {
   return new DefaultAppearanceEvaluator(str).parse();
 }
-
 function getPdfColor(color, isFill) {
   if (color[0] === color[1] && color[1] === color[2]) {
     const gray = color[0] / 255;
     return `${(0, _core_utils.numberToString)(gray)} ${isFill ? "g" : "G"}`;
   }
-
-  return Array.from(color).map(c => (0, _core_utils.numberToString)(c / 255)).join(" ") + ` ${isFill ? "rg" : "RG"}`;
+  return Array.from(color, c => (0, _core_utils.numberToString)(c / 255)).join(" ") + ` ${isFill ? "rg" : "RG"}`;
 }
-
 function createDefaultAppearance({
   fontSize,
   fontName,

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 22 - 244
lib/core/document.js


+ 0 - 8
lib/core/encodings.js

@@ -39,30 +39,22 @@ const SymbolSetEncoding = ["", "", "", "", "", "", "", "", "", "", "", "", "", "
 exports.SymbolSetEncoding = SymbolSetEncoding;
 const ZapfDingbatsEncoding = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "space", "a1", "a2", "a202", "a3", "a4", "a5", "a119", "a118", "a117", "a11", "a12", "a13", "a14", "a15", "a16", "a105", "a17", "a18", "a19", "a20", "a21", "a22", "a23", "a24", "a25", "a26", "a27", "a28", "a6", "a7", "a8", "a9", "a10", "a29", "a30", "a31", "a32", "a33", "a34", "a35", "a36", "a37", "a38", "a39", "a40", "a41", "a42", "a43", "a44", "a45", "a46", "a47", "a48", "a49", "a50", "a51", "a52", "a53", "a54", "a55", "a56", "a57", "a58", "a59", "a60", "a61", "a62", "a63", "a64", "a65", "a66", "a67", "a68", "a69", "a70", "a71", "a72", "a73", "a74", "a203", "a75", "a204", "a76", "a77", "a78", "a79", "a81", "a82", "a83", "a84", "a97", "a98", "a99", "a100", "", "a89", "a90", "a93", "a94", "a91", "a92", "a205", "a85", "a206", "a86", "a87", "a88", "a95", "a96", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "a101", "a102", "a103", "a104", "a106", "a107", "a108", "a112", "a111", "a110", "a109", "a120", "a121", "a122", "a123", "a124", "a125", "a126", "a127", "a128", "a129", "a130", "a131", "a132", "a133", "a134", "a135", "a136", "a137", "a138", "a139", "a140", "a141", "a142", "a143", "a144", "a145", "a146", "a147", "a148", "a149", "a150", "a151", "a152", "a153", "a154", "a155", "a156", "a157", "a158", "a159", "a160", "a161", "a163", "a164", "a196", "a165", "a192", "a166", "a167", "a168", "a169", "a170", "a171", "a172", "a173", "a162", "a174", "a175", "a176", "a177", "a178", "a179", "a193", "a180", "a199", "a181", "a200", "a182", "", "a201", "a183", "a184", "a197", "a185", "a194", "a198", "a186", "a195", "a187", "a188", "a189", "a190", "a191", ""];
 exports.ZapfDingbatsEncoding = ZapfDingbatsEncoding;
-
 function getEncoding(encodingName) {
   switch (encodingName) {
     case "WinAnsiEncoding":
       return WinAnsiEncoding;
-
     case "StandardEncoding":
       return StandardEncoding;
-
     case "MacRomanEncoding":
       return MacRomanEncoding;
-
     case "SymbolSetEncoding":
       return SymbolSetEncoding;
-
     case "ZapfDingbatsEncoding":
       return ZapfDingbatsEncoding;
-
     case "ExpertEncoding":
       return ExpertEncoding;
-
     case "MacExpertEncoding":
       return MacExpertEncoding;
-
     default:
       return null;
   }

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 11 - 243
lib/core/evaluator.js


+ 0 - 23
lib/core/file_spec.js

@@ -25,13 +25,9 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.FileSpec = void 0;
-
 var _util = require("../shared/util.js");
-
 var _base_stream = require("./base_stream.js");
-
 var _primitives = require("./primitives.js");
-
 function pickPlatformItem(dict) {
   if (dict.has("UF")) {
     return dict.get("UF");
@@ -44,60 +40,45 @@ function pickPlatformItem(dict) {
   } else if (dict.has("DOS")) {
     return dict.get("DOS");
   }
-
   return null;
 }
-
 class FileSpec {
   constructor(root, xref) {
     if (!(root instanceof _primitives.Dict)) {
       return;
     }
-
     this.xref = xref;
     this.root = root;
-
     if (root.has("FS")) {
       this.fs = root.get("FS");
     }
-
     this.description = root.has("Desc") ? (0, _util.stringToPDFString)(root.get("Desc")) : "";
-
     if (root.has("RF")) {
       (0, _util.warn)("Related file specifications are not supported");
     }
-
     this.contentAvailable = true;
-
     if (!root.has("EF")) {
       this.contentAvailable = false;
       (0, _util.warn)("Non-embedded file specifications are not supported");
     }
   }
-
   get filename() {
     if (!this._filename && this.root) {
       const filename = pickPlatformItem(this.root) || "unnamed";
       this._filename = (0, _util.stringToPDFString)(filename).replace(/\\\\/g, "\\").replace(/\\\//g, "/").replace(/\\/g, "/");
     }
-
     return this._filename;
   }
-
   get content() {
     if (!this.contentAvailable) {
       return null;
     }
-
     if (!this.contentRef && this.root) {
       this.contentRef = pickPlatformItem(this.root.get("EF"));
     }
-
     let content = null;
-
     if (this.contentRef) {
       const fileObj = this.xref.fetchIfRef(this.contentRef);
-
       if (fileObj instanceof _base_stream.BaseStream) {
         content = fileObj.getBytes();
       } else {
@@ -106,17 +87,13 @@ class FileSpec {
     } else {
       (0, _util.warn)("Embedded file specification does not have a content");
     }
-
     return content;
   }
-
   get serializable() {
     return {
       filename: this.filename,
       content: this.content
     };
   }
-
 }
-
 exports.FileSpec = FileSpec;

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 3
lib/core/flate_stream.js


+ 8 - 187
lib/core/font_renderer.js

@@ -25,98 +25,73 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.FontRendererFactory = void 0;
-
 var _util = require("../shared/util.js");
-
 var _cff_parser = require("./cff_parser.js");
-
 var _glyphlist = require("./glyphlist.js");
-
 var _encodings = require("./encodings.js");
-
 var _stream = require("./stream.js");
-
 function getUint32(data, offset) {
   return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
 }
-
 function getUint16(data, offset) {
   return data[offset] << 8 | data[offset + 1];
 }
-
 function getInt16(data, offset) {
   return (data[offset] << 24 | data[offset + 1] << 16) >> 16;
 }
-
 function getInt8(data, offset) {
   return data[offset] << 24 >> 24;
 }
-
 function getFloat214(data, offset) {
   return getInt16(data, offset) / 16384;
 }
-
 function getSubroutineBias(subrs) {
   const numSubrs = subrs.length;
   let bias = 32768;
-
   if (numSubrs < 1240) {
     bias = 107;
   } else if (numSubrs < 33900) {
     bias = 1131;
   }
-
   return bias;
 }
-
 function parseCmap(data, start, end) {
   const offset = getUint16(data, start + 2) === 1 ? getUint32(data, start + 8) : getUint32(data, start + 16);
   const format = getUint16(data, start + offset);
   let ranges, p, i;
-
   if (format === 4) {
     getUint16(data, start + offset + 2);
     const segCount = getUint16(data, start + offset + 6) >> 1;
     p = start + offset + 14;
     ranges = [];
-
     for (i = 0; i < segCount; i++, p += 2) {
       ranges[i] = {
         end: getUint16(data, p)
       };
     }
-
     p += 2;
-
     for (i = 0; i < segCount; i++, p += 2) {
       ranges[i].start = getUint16(data, p);
     }
-
     for (i = 0; i < segCount; i++, p += 2) {
       ranges[i].idDelta = getUint16(data, p);
     }
-
     for (i = 0; i < segCount; i++, p += 2) {
       let idOffset = getUint16(data, p);
-
       if (idOffset === 0) {
         continue;
       }
-
       ranges[i].ids = [];
-
       for (let j = 0, jj = ranges[i].end - ranges[i].start + 1; j < jj; j++) {
         ranges[i].ids[j] = getUint16(data, p + idOffset);
         idOffset += 2;
       }
     }
-
     return ranges;
   } else if (format === 12) {
     const groups = getUint32(data, start + offset + 12);
     p = start + offset + 16;
     ranges = [];
-
     for (i = 0; i < groups; i++) {
       start = getUint32(data, p);
       ranges.push({
@@ -126,13 +101,10 @@ function parseCmap(data, start, end) {
       });
       p += 12;
     }
-
     return ranges;
   }
-
   throw new _util.FormatError(`unsupported cmap: ${format}`);
 }
-
 function parseCff(data, start, end, seacAnalysisEnabled) {
   const properties = {};
   const parser = new _cff_parser.CFFParser(new _stream.Stream(data, start, end - start), properties, seacAnalysisEnabled);
@@ -146,57 +118,45 @@ function parseCff(data, start, end, seacAnalysisEnabled) {
     fdArray: cff.fdArray
   };
 }
-
 function parseGlyfTable(glyf, loca, isGlyphLocationsLong) {
   let itemSize, itemDecode;
-
   if (isGlyphLocationsLong) {
     itemSize = 4;
     itemDecode = getUint32;
   } else {
     itemSize = 2;
-
     itemDecode = (data, offset) => 2 * getUint16(data, offset);
   }
-
   const glyphs = [];
   let startOffset = itemDecode(loca, 0);
-
   for (let j = itemSize; j < loca.length; j += itemSize) {
     const endOffset = itemDecode(loca, j);
     glyphs.push(glyf.subarray(startOffset, endOffset));
     startOffset = endOffset;
   }
-
   return glyphs;
 }
-
 function lookupCmap(ranges, unicode) {
   const code = unicode.codePointAt(0);
   let gid = 0,
-      l = 0,
-      r = ranges.length - 1;
-
+    l = 0,
+    r = ranges.length - 1;
   while (l < r) {
     const c = l + r + 1 >> 1;
-
     if (code < ranges[c].start) {
       r = c - 1;
     } else {
       l = c;
     }
   }
-
   if (ranges[l].start <= code && code <= ranges[l].end) {
     gid = ranges[l].idDelta + (ranges[l].ids ? ranges[l].ids[code - ranges[l].start] : code) & 0xffff;
   }
-
   return {
     charCode: code,
     glyphId: gid
   };
 }
-
 function compileGlyf(code, cmds, font) {
   function moveTo(x, y) {
     cmds.push({
@@ -204,35 +164,30 @@ function compileGlyf(code, cmds, font) {
       args: [x, y]
     });
   }
-
   function lineTo(x, y) {
     cmds.push({
       cmd: "lineTo",
       args: [x, y]
     });
   }
-
   function quadraticCurveTo(xa, ya, x, y) {
     cmds.push({
       cmd: "quadraticCurveTo",
       args: [xa, ya, x, y]
     });
   }
-
   let i = 0;
   const numberOfContours = getInt16(code, i);
   let flags;
   let x = 0,
-      y = 0;
+    y = 0;
   i += 10;
-
   if (numberOfContours < 0) {
     do {
       flags = getUint16(code, i);
       const glyphIndex = getUint16(code, i + 2);
       i += 4;
       let arg1, arg2;
-
       if (flags & 0x01) {
         if (flags & 0x02) {
           arg1 = getInt16(code, i);
@@ -241,7 +196,6 @@ function compileGlyf(code, cmds, font) {
           arg1 = getUint16(code, i);
           arg2 = getUint16(code, i + 2);
         }
-
         i += 4;
       } else {
         if (flags & 0x02) {
@@ -252,7 +206,6 @@ function compileGlyf(code, cmds, font) {
           arg2 = code[i++];
         }
       }
-
       if (flags & 0x02) {
         x = arg1;
         y = arg2;
@@ -260,12 +213,10 @@ function compileGlyf(code, cmds, font) {
         x = 0;
         y = 0;
       }
-
       let scaleX = 1,
-          scaleY = 1,
-          scale01 = 0,
-          scale10 = 0;
-
+        scaleY = 1,
+        scale01 = 0,
+        scale10 = 0;
       if (flags & 0x08) {
         scaleX = scaleY = getFloat214(code, i);
         i += 2;
@@ -280,9 +231,7 @@ function compileGlyf(code, cmds, font) {
         scaleY = getFloat214(code, i + 6);
         i += 8;
       }
-
       const subglyph = font.glyphs[glyphIndex];
-
       if (subglyph) {
         cmds.push({
           cmd: "save"
@@ -290,9 +239,7 @@ function compileGlyf(code, cmds, font) {
           cmd: "transform",
           args: [scaleX, scale01, scale10, scaleY, x, y]
         });
-
         if (!(flags & 0x02)) {}
-
         compileGlyf(subglyph, cmds, font);
         cmds.push({
           cmd: "restore"
@@ -302,76 +249,60 @@ function compileGlyf(code, cmds, font) {
   } else {
     const endPtsOfContours = [];
     let j, jj;
-
     for (j = 0; j < numberOfContours; j++) {
       endPtsOfContours.push(getUint16(code, i));
       i += 2;
     }
-
     const instructionLength = getUint16(code, i);
     i += 2 + instructionLength;
     const numberOfPoints = endPtsOfContours.at(-1) + 1;
     const points = [];
-
     while (points.length < numberOfPoints) {
       flags = code[i++];
       let repeat = 1;
-
       if (flags & 0x08) {
         repeat += code[i++];
       }
-
       while (repeat-- > 0) {
         points.push({
           flags
         });
       }
     }
-
     for (j = 0; j < numberOfPoints; j++) {
       switch (points[j].flags & 0x12) {
         case 0x00:
           x += getInt16(code, i);
           i += 2;
           break;
-
         case 0x02:
           x -= code[i++];
           break;
-
         case 0x12:
           x += code[i++];
           break;
       }
-
       points[j].x = x;
     }
-
     for (j = 0; j < numberOfPoints; j++) {
       switch (points[j].flags & 0x24) {
         case 0x00:
           y += getInt16(code, i);
           i += 2;
           break;
-
         case 0x04:
           y -= code[i++];
           break;
-
         case 0x24:
           y += code[i++];
           break;
       }
-
       points[j].y = y;
     }
-
     let startPoint = 0;
-
     for (i = 0; i < numberOfContours; i++) {
       const endPoint = endPtsOfContours[i];
       const contour = points.slice(startPoint, endPoint + 1);
-
       if (contour[0].flags & 1) {
         contour.push(contour[0]);
       } else if (contour.at(-1).flags & 1) {
@@ -385,9 +316,7 @@ function compileGlyf(code, cmds, font) {
         contour.unshift(p);
         contour.push(p);
       }
-
       moveTo(contour[0].x, contour[0].y);
-
       for (j = 1, jj = contour.length; j < jj; j++) {
         if (contour[j].flags & 1) {
           lineTo(contour[j].x, contour[j].y);
@@ -398,12 +327,10 @@ function compileGlyf(code, cmds, font) {
           quadraticCurveTo(contour[j].x, contour[j].y, (contour[j].x + contour[j + 1].x) / 2, (contour[j].y + contour[j + 1].y) / 2);
         }
       }
-
       startPoint = endPoint + 1;
     }
   }
 }
-
 function compileCharString(charStringCode, cmds, font, glyphId) {
   function moveTo(x, y) {
     cmds.push({
@@ -411,90 +338,71 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
       args: [x, y]
     });
   }
-
   function lineTo(x, y) {
     cmds.push({
       cmd: "lineTo",
       args: [x, y]
     });
   }
-
   function bezierCurveTo(x1, y1, x2, y2, x, y) {
     cmds.push({
       cmd: "bezierCurveTo",
       args: [x1, y1, x2, y2, x, y]
     });
   }
-
   const stack = [];
   let x = 0,
-      y = 0;
+    y = 0;
   let stems = 0;
-
   function parse(code) {
     let i = 0;
-
     while (i < code.length) {
       let stackClean = false;
       let v = code[i++];
       let xa, xb, ya, yb, y1, y2, y3, n, subrCode;
-
       switch (v) {
         case 1:
           stems += stack.length >> 1;
           stackClean = true;
           break;
-
         case 3:
           stems += stack.length >> 1;
           stackClean = true;
           break;
-
         case 4:
           y += stack.pop();
           moveTo(x, y);
           stackClean = true;
           break;
-
         case 5:
           while (stack.length > 0) {
             x += stack.shift();
             y += stack.shift();
             lineTo(x, y);
           }
-
           break;
-
         case 6:
           while (stack.length > 0) {
             x += stack.shift();
             lineTo(x, y);
-
             if (stack.length === 0) {
               break;
             }
-
             y += stack.shift();
             lineTo(x, y);
           }
-
           break;
-
         case 7:
           while (stack.length > 0) {
             y += stack.shift();
             lineTo(x, y);
-
             if (stack.length === 0) {
               break;
             }
-
             x += stack.shift();
             lineTo(x, y);
           }
-
           break;
-
         case 8:
           while (stack.length > 0) {
             xa = x + stack.shift();
@@ -505,24 +413,18 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
             y = yb + stack.shift();
             bezierCurveTo(xa, ya, xb, yb, x, y);
           }
-
           break;
-
         case 10:
           n = stack.pop();
           subrCode = null;
-
           if (font.isCFFCIDFont) {
             const fdIndex = font.fdSelect.getFDIndex(glyphId);
-
             if (fdIndex >= 0 && fdIndex < font.fdArray.length) {
               const fontDict = font.fdArray[fdIndex];
               let subrs;
-
               if (fontDict.privateDict && fontDict.privateDict.subrsIndex) {
                 subrs = fontDict.privateDict.subrsIndex.objects;
               }
-
               if (subrs) {
                 n += getSubroutineBias(subrs);
                 subrCode = subrs[n];
@@ -533,19 +435,14 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
           } else {
             subrCode = font.subrs[n + font.subrsBias];
           }
-
           if (subrCode) {
             parse(subrCode);
           }
-
           break;
-
         case 11:
           return;
-
         case 12:
           v = code[i++];
-
           switch (v) {
             case 34:
               xa = x + stack.shift();
@@ -558,7 +455,6 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
               x = xb + stack.shift();
               bezierCurveTo(xa, y1, xb, y, x, y);
               break;
-
             case 35:
               xa = x + stack.shift();
               ya = y + stack.shift();
@@ -576,7 +472,6 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
               bezierCurveTo(xa, ya, xb, yb, x, y);
               stack.pop();
               break;
-
             case 36:
               xa = x + stack.shift();
               y1 = y + stack.shift();
@@ -590,10 +485,9 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
               x = xb + stack.shift();
               bezierCurveTo(xa, y2, xb, y3, x, y);
               break;
-
             case 37:
               const x0 = x,
-                    y0 = y;
+                y0 = y;
               xa = x + stack.shift();
               ya = y + stack.shift();
               xb = xa + stack.shift();
@@ -607,22 +501,17 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
               yb = ya + stack.shift();
               x = xb;
               y = yb;
-
               if (Math.abs(x - x0) > Math.abs(y - y0)) {
                 x += stack.shift();
               } else {
                 y += stack.shift();
               }
-
               bezierCurveTo(xa, ya, xb, yb, x, y);
               break;
-
             default:
               throw new _util.FormatError(`unknown operator: 12 ${v}`);
           }
-
           break;
-
         case 14:
           if (stack.length >= 4) {
             const achar = stack.pop();
@@ -643,44 +532,36 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
             cmap = lookupCmap(font.cmap, String.fromCharCode(font.glyphNameMap[_encodings.StandardEncoding[bchar]]));
             compileCharString(font.glyphs[cmap.glyphId], cmds, font, cmap.glyphId);
           }
-
           return;
-
         case 18:
           stems += stack.length >> 1;
           stackClean = true;
           break;
-
         case 19:
           stems += stack.length >> 1;
           i += stems + 7 >> 3;
           stackClean = true;
           break;
-
         case 20:
           stems += stack.length >> 1;
           i += stems + 7 >> 3;
           stackClean = true;
           break;
-
         case 21:
           y += stack.pop();
           x += stack.pop();
           moveTo(x, y);
           stackClean = true;
           break;
-
         case 22:
           x += stack.pop();
           moveTo(x, y);
           stackClean = true;
           break;
-
         case 23:
           stems += stack.length >> 1;
           stackClean = true;
           break;
-
         case 24:
           while (stack.length > 2) {
             xa = x + stack.shift();
@@ -691,19 +572,16 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
             y = yb + stack.shift();
             bezierCurveTo(xa, ya, xb, yb, x, y);
           }
-
           x += stack.shift();
           y += stack.shift();
           lineTo(x, y);
           break;
-
         case 25:
           while (stack.length > 6) {
             x += stack.shift();
             y += stack.shift();
             lineTo(x, y);
           }
-
           xa = x + stack.shift();
           ya = y + stack.shift();
           xb = xa + stack.shift();
@@ -712,12 +590,10 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
           y = yb + stack.shift();
           bezierCurveTo(xa, ya, xb, yb, x, y);
           break;
-
         case 26:
           if (stack.length % 2) {
             x += stack.shift();
           }
-
           while (stack.length > 0) {
             xa = x;
             ya = y + stack.shift();
@@ -727,14 +603,11 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
             y = yb + stack.shift();
             bezierCurveTo(xa, ya, xb, yb, x, y);
           }
-
           break;
-
         case 27:
           if (stack.length % 2) {
             y += stack.shift();
           }
-
           while (stack.length > 0) {
             xa = x + stack.shift();
             ya = y;
@@ -744,24 +617,18 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
             y = yb;
             bezierCurveTo(xa, ya, xb, yb, x, y);
           }
-
           break;
-
         case 28:
           stack.push((code[i] << 24 | code[i + 1] << 16) >> 16);
           i += 2;
           break;
-
         case 29:
           n = stack.pop() + font.gsubrsBias;
           subrCode = font.gsubrs[n];
-
           if (subrCode) {
             parse(subrCode);
           }
-
           break;
-
         case 30:
           while (stack.length > 0) {
             xa = x;
@@ -771,11 +638,9 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
             x = xb + stack.shift();
             y = yb + (stack.length === 1 ? stack.shift() : 0);
             bezierCurveTo(xa, ya, xb, yb, x, y);
-
             if (stack.length === 0) {
               break;
             }
-
             xa = x + stack.shift();
             ya = y;
             xb = xa + stack.shift();
@@ -784,9 +649,7 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
             x = xb + (stack.length === 1 ? stack.shift() : 0);
             bezierCurveTo(xa, ya, xb, yb, x, y);
           }
-
           break;
-
         case 31:
           while (stack.length > 0) {
             xa = x + stack.shift();
@@ -796,11 +659,9 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
             y = yb + stack.shift();
             x = xb + (stack.length === 1 ? stack.shift() : 0);
             bezierCurveTo(xa, ya, xb, yb, x, y);
-
             if (stack.length === 0) {
               break;
             }
-
             xa = x;
             ya = y + stack.shift();
             xb = xa + stack.shift();
@@ -809,14 +670,11 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
             y = yb + (stack.length === 1 ? stack.shift() : 0);
             bezierCurveTo(xa, ya, xb, yb, x, y);
           }
-
           break;
-
         default:
           if (v < 32) {
             throw new _util.FormatError(`unknown operator: ${v}`);
           }
-
           if (v < 247) {
             stack.push(v - 139);
           } else if (v < 251) {
@@ -827,71 +685,55 @@ function compileCharString(charStringCode, cmds, font, glyphId) {
             stack.push((code[i] << 24 | code[i + 1] << 16 | code[i + 2] << 8 | code[i + 3]) / 65536);
             i += 4;
           }
-
           break;
       }
-
       if (stackClean) {
         stack.length = 0;
       }
     }
   }
-
   parse(charStringCode);
 }
-
 const NOOP = [];
-
 class CompiledFont {
   constructor(fontMatrix) {
     if (this.constructor === CompiledFont) {
       (0, _util.unreachable)("Cannot initialize CompiledFont.");
     }
-
     this.fontMatrix = fontMatrix;
     this.compiledGlyphs = Object.create(null);
     this.compiledCharCodeToGlyphId = Object.create(null);
   }
-
   getPathJs(unicode) {
     const {
       charCode,
       glyphId
     } = lookupCmap(this.cmap, unicode);
     let fn = this.compiledGlyphs[glyphId];
-
     if (!fn) {
       try {
         fn = this.compileGlyph(this.glyphs[glyphId], glyphId);
         this.compiledGlyphs[glyphId] = fn;
       } catch (ex) {
         this.compiledGlyphs[glyphId] = NOOP;
-
         if (this.compiledCharCodeToGlyphId[charCode] === undefined) {
           this.compiledCharCodeToGlyphId[charCode] = glyphId;
         }
-
         throw ex;
       }
     }
-
     if (this.compiledCharCodeToGlyphId[charCode] === undefined) {
       this.compiledCharCodeToGlyphId[charCode] = glyphId;
     }
-
     return fn;
   }
-
   compileGlyph(code, glyphId) {
     if (!code || code.length === 0 || code[0] === 14) {
       return NOOP;
     }
-
     let fontMatrix = this.fontMatrix;
-
     if (this.isCFFCIDFont) {
       const fdIndex = this.fdSelect.getFDIndex(glyphId);
-
       if (fdIndex >= 0 && fdIndex < this.fdArray.length) {
         const fontDict = this.fdArray[fdIndex];
         fontMatrix = fontDict.getByName("FontMatrix") || _util.FONT_IDENTITY_MATRIX;
@@ -899,7 +741,6 @@ class CompiledFont {
         (0, _util.warn)("Invalid fd index for glyph index.");
       }
     }
-
     const cmds = [{
       cmd: "save"
     }, {
@@ -915,11 +756,9 @@ class CompiledFont {
     });
     return cmds;
   }
-
   compileGlyphImpl() {
     (0, _util.unreachable)("Children classes should implement this.");
   }
-
   hasBuiltPath(unicode) {
     const {
       charCode,
@@ -927,22 +766,17 @@ class CompiledFont {
     } = lookupCmap(this.cmap, unicode);
     return this.compiledGlyphs[glyphId] !== undefined && this.compiledCharCodeToGlyphId[charCode] !== undefined;
   }
-
 }
-
 class TrueTypeCompiled extends CompiledFont {
   constructor(glyphs, cmap, fontMatrix) {
     super(fontMatrix || [0.000488, 0, 0, 0.000488, 0, 0]);
     this.glyphs = glyphs;
     this.cmap = cmap;
   }
-
   compileGlyphImpl(code, cmds) {
     compileGlyf(code, cmds, this);
   }
-
 }
-
 class Type2Compiled extends CompiledFont {
   constructor(cffInfo, cmap, fontMatrix, glyphNameMap) {
     super(fontMatrix || [0.001, 0, 0, 0.001, 0, 0]);
@@ -957,56 +791,43 @@ class Type2Compiled extends CompiledFont {
     this.fdSelect = cffInfo.fdSelect;
     this.fdArray = cffInfo.fdArray;
   }
-
   compileGlyphImpl(code, cmds, glyphId) {
     compileCharString(code, cmds, this, glyphId);
   }
-
 }
-
 class FontRendererFactory {
   static create(font, seacAnalysisEnabled) {
     const data = new Uint8Array(font.data);
     let cmap, glyf, loca, cff, indexToLocFormat, unitsPerEm;
     const numTables = getUint16(data, 4);
-
     for (let i = 0, p = 12; i < numTables; i++, p += 16) {
       const tag = (0, _util.bytesToString)(data.subarray(p, p + 4));
       const offset = getUint32(data, p + 8);
       const length = getUint32(data, p + 12);
-
       switch (tag) {
         case "cmap":
           cmap = parseCmap(data, offset, offset + length);
           break;
-
         case "glyf":
           glyf = data.subarray(offset, offset + length);
           break;
-
         case "loca":
           loca = data.subarray(offset, offset + length);
           break;
-
         case "head":
           unitsPerEm = getUint16(data, offset + 18);
           indexToLocFormat = getUint16(data, offset + 50);
           break;
-
         case "CFF ":
           cff = parseCff(data, offset, offset + length, seacAnalysisEnabled);
           break;
       }
     }
-
     if (glyf) {
       const fontMatrix = !unitsPerEm ? font.fontMatrix : [1 / unitsPerEm, 0, 0, 1 / unitsPerEm, 0, 0];
       return new TrueTypeCompiled(parseGlyfTable(glyf, loca, indexToLocFormat), cmap, fontMatrix);
     }
-
     return new Type2Compiled(cff, cmap, font.fontMatrix, font.glyphNameMap);
   }
-
 }
-
 exports.FontRendererFactory = FontRendererFactory;

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 11 - 234
lib/core/fonts.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 5
lib/core/fonts_utils.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 6 - 224
lib/core/function.js


+ 0 - 109
lib/core/glyf.js

@@ -39,7 +39,6 @@ const MORE_COMPONENTS = 1 << 5;
 const WE_HAVE_AN_X_AND_Y_SCALE = 1 << 6;
 const WE_HAVE_A_TWO_BY_TWO = 1 << 7;
 const WE_HAVE_INSTRUCTIONS = 1 << 8;
-
 class GlyfTable {
   constructor({
     glyfTable,
@@ -53,74 +52,60 @@ class GlyfTable {
     const offsetSize = isGlyphLocationsLong ? 4 : 2;
     let prev = isGlyphLocationsLong ? loca.getUint32(0) : 2 * loca.getUint16(0);
     let pos = 0;
-
     for (let i = 0; i < numGlyphs; i++) {
       pos += offsetSize;
       const next = isGlyphLocationsLong ? loca.getUint32(pos) : 2 * loca.getUint16(pos);
-
       if (next === prev) {
         this.glyphs.push(new Glyph({}));
         continue;
       }
-
       const glyph = Glyph.parse(prev, glyf);
       this.glyphs.push(glyph);
       prev = next;
     }
   }
-
   getSize() {
     return this.glyphs.reduce((a, g) => {
       const size = g.getSize();
       return a + (size + 3 & ~3);
     }, 0);
   }
-
   write() {
     const totalSize = this.getSize();
     const glyfTable = new DataView(new ArrayBuffer(totalSize));
     const isLocationLong = totalSize > 0x1fffe;
     const offsetSize = isLocationLong ? 4 : 2;
     const locaTable = new DataView(new ArrayBuffer((this.glyphs.length + 1) * offsetSize));
-
     if (isLocationLong) {
       locaTable.setUint32(0, 0);
     } else {
       locaTable.setUint16(0, 0);
     }
-
     let pos = 0;
     let locaIndex = 0;
-
     for (const glyph of this.glyphs) {
       pos += glyph.write(pos, glyfTable);
       pos = pos + 3 & ~3;
       locaIndex += offsetSize;
-
       if (isLocationLong) {
         locaTable.setUint32(locaIndex, pos);
       } else {
         locaTable.setUint16(locaIndex, pos >> 1);
       }
     }
-
     return {
       isLocationLong,
       loca: new Uint8Array(locaTable.buffer),
       glyf: new Uint8Array(glyfTable.buffer)
     };
   }
-
   scale(factors) {
     for (let i = 0, ii = this.glyphs.length; i < ii; i++) {
       this.glyphs[i].scale(factors[i]);
     }
   }
-
 }
-
 exports.GlyfTable = GlyfTable;
-
 class Glyph {
   constructor({
     header = null,
@@ -131,54 +116,43 @@ class Glyph {
     this.simple = simple;
     this.composites = composites;
   }
-
   static parse(pos, glyf) {
     const [read, header] = GlyphHeader.parse(pos, glyf);
     pos += read;
-
     if (header.numberOfContours < 0) {
       const composites = [];
-
       while (true) {
         const [n, composite] = CompositeGlyph.parse(pos, glyf);
         pos += n;
         composites.push(composite);
-
         if (!(composite.flags & MORE_COMPONENTS)) {
           break;
         }
       }
-
       return new Glyph({
         header,
         composites
       });
     }
-
     const simple = SimpleGlyph.parse(pos, glyf, header.numberOfContours);
     return new Glyph({
       header,
       simple
     });
   }
-
   getSize() {
     if (!this.header) {
       return 0;
     }
-
     const size = this.simple ? this.simple.getSize() : this.composites.reduce((a, c) => a + c.getSize(), 0);
     return this.header.getSize() + size;
   }
-
   write(pos, buf) {
     if (!this.header) {
       return 0;
     }
-
     const spos = pos;
     pos += this.header.write(pos, buf);
-
     if (this.simple) {
       pos += this.simple.write(pos, buf);
     } else {
@@ -186,18 +160,14 @@ class Glyph {
         pos += composite.write(pos, buf);
       }
     }
-
     return pos - spos;
   }
-
   scale(factor) {
     if (!this.header) {
       return;
     }
-
     const xMiddle = (this.header.xMin + this.header.xMax) / 2;
     this.header.scale(xMiddle, factor);
-
     if (this.simple) {
       this.simple.scale(xMiddle, factor);
     } else {
@@ -206,9 +176,7 @@ class Glyph {
       }
     }
   }
-
 }
-
 class GlyphHeader {
   constructor({
     numberOfContours,
@@ -223,7 +191,6 @@ class GlyphHeader {
     this.xMax = xMax;
     this.yMax = yMax;
   }
-
   static parse(pos, glyf) {
     return [10, new GlyphHeader({
       numberOfContours: glyf.getInt16(pos),
@@ -233,11 +200,9 @@ class GlyphHeader {
       yMax: glyf.getInt16(pos + 8)
     })];
   }
-
   getSize() {
     return 10;
   }
-
   write(pos, buf) {
     buf.setInt16(pos, this.numberOfContours);
     buf.setInt16(pos + 2, this.xMin);
@@ -246,14 +211,11 @@ class GlyphHeader {
     buf.setInt16(pos + 8, this.yMax);
     return 10;
   }
-
   scale(x, factor) {
     this.xMin = Math.round(x + (this.xMin - x) * factor);
     this.xMax = Math.round(x + (this.xMax - x) * factor);
   }
-
 }
-
 class Contour {
   constructor({
     flags,
@@ -264,9 +226,7 @@ class Contour {
     this.yCoordinates = yCoordinates;
     this.flags = flags;
   }
-
 }
-
 class SimpleGlyph {
   constructor({
     contours,
@@ -275,39 +235,31 @@ class SimpleGlyph {
     this.contours = contours;
     this.instructions = instructions;
   }
-
   static parse(pos, glyf, numberOfContours) {
     const endPtsOfContours = [];
-
     for (let i = 0; i < numberOfContours; i++) {
       const endPt = glyf.getUint16(pos);
       pos += 2;
       endPtsOfContours.push(endPt);
     }
-
     const numberOfPt = endPtsOfContours[numberOfContours - 1] + 1;
     const instructionLength = glyf.getUint16(pos);
     pos += 2;
     const instructions = new Uint8Array(glyf).slice(pos, pos + instructionLength);
     pos += instructionLength;
     const flags = [];
-
     for (let i = 0; i < numberOfPt; pos++, i++) {
       let flag = glyf.getUint8(pos);
       flags.push(flag);
-
       if (flag & REPEAT_FLAG) {
         const count = glyf.getUint8(++pos);
         flag ^= REPEAT_FLAG;
-
         for (let m = 0; m < count; m++) {
           flags.push(flag);
         }
-
         i += count;
       }
     }
-
     const allXCoordinates = [];
     let xCoordinates = [];
     let yCoordinates = [];
@@ -315,10 +267,8 @@ class SimpleGlyph {
     const contours = [];
     let endPtsOfContoursIndex = 0;
     let lastCoordinate = 0;
-
     for (let i = 0; i < numberOfPt; i++) {
       const flag = flags[i];
-
       if (flag & X_SHORT_VECTOR) {
         const x = glyf.getUint8(pos++);
         lastCoordinate += flag & X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR ? x : -x;
@@ -330,20 +280,16 @@ class SimpleGlyph {
         pos += 2;
         xCoordinates.push(lastCoordinate);
       }
-
       if (endPtsOfContours[endPtsOfContoursIndex] === i) {
         endPtsOfContoursIndex++;
         allXCoordinates.push(xCoordinates);
         xCoordinates = [];
       }
     }
-
     lastCoordinate = 0;
     endPtsOfContoursIndex = 0;
-
     for (let i = 0; i < numberOfPt; i++) {
       const flag = flags[i];
-
       if (flag & Y_SHORT_VECTOR) {
         const y = glyf.getUint8(pos++);
         lastCoordinate += flag & Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR ? y : -y;
@@ -355,9 +301,7 @@ class SimpleGlyph {
         pos += 2;
         yCoordinates.push(lastCoordinate);
       }
-
       pointFlags.push(flag & ON_CURVE_POINT | flag & OVERLAP_SIMPLE);
-
       if (endPtsOfContours[endPtsOfContoursIndex] === i) {
         xCoordinates = allXCoordinates[endPtsOfContoursIndex];
         endPtsOfContoursIndex++;
@@ -370,48 +314,38 @@ class SimpleGlyph {
         pointFlags = [];
       }
     }
-
     return new SimpleGlyph({
       contours,
       instructions
     });
   }
-
   getSize() {
     let size = this.contours.length * 2 + 2 + this.instructions.length;
     let lastX = 0;
     let lastY = 0;
-
     for (const contour of this.contours) {
       size += contour.flags.length;
-
       for (let i = 0, ii = contour.xCoordinates.length; i < ii; i++) {
         const x = contour.xCoordinates[i];
         const y = contour.yCoordinates[i];
         let abs = Math.abs(x - lastX);
-
         if (abs > 255) {
           size += 2;
         } else if (abs > 0) {
           size += 1;
         }
-
         lastX = x;
         abs = Math.abs(y - lastY);
-
         if (abs > 255) {
           size += 2;
         } else if (abs > 0) {
           size += 1;
         }
-
         lastY = y;
       }
     }
-
     return size;
   }
-
   write(pos, buf) {
     const spos = pos;
     const xCoordinates = [];
@@ -419,19 +353,16 @@ class SimpleGlyph {
     const flags = [];
     let lastX = 0;
     let lastY = 0;
-
     for (const contour of this.contours) {
       for (let i = 0, ii = contour.xCoordinates.length; i < ii; i++) {
         let flag = contour.flags[i];
         const x = contour.xCoordinates[i];
         let delta = x - lastX;
-
         if (delta === 0) {
           flag |= X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR;
           xCoordinates.push(0);
         } else {
           const abs = Math.abs(delta);
-
           if (abs <= 255) {
             flag |= delta >= 0 ? X_SHORT_VECTOR | X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR : X_SHORT_VECTOR;
             xCoordinates.push(abs);
@@ -439,17 +370,14 @@ class SimpleGlyph {
             xCoordinates.push(delta);
           }
         }
-
         lastX = x;
         const y = contour.yCoordinates[i];
         delta = y - lastY;
-
         if (delta === 0) {
           flag |= Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR;
           yCoordinates.push(0);
         } else {
           const abs = Math.abs(delta);
-
           if (abs <= 255) {
             flag |= delta >= 0 ? Y_SHORT_VECTOR | Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR : Y_SHORT_VECTOR;
             yCoordinates.push(abs);
@@ -457,31 +385,24 @@ class SimpleGlyph {
             yCoordinates.push(delta);
           }
         }
-
         lastY = y;
         flags.push(flag);
       }
-
       buf.setUint16(pos, xCoordinates.length - 1);
       pos += 2;
     }
-
     buf.setUint16(pos, this.instructions.length);
     pos += 2;
-
     if (this.instructions.length) {
       new Uint8Array(buf.buffer, 0, buf.buffer.byteLength).set(this.instructions, pos);
       pos += this.instructions.length;
     }
-
     for (const flag of flags) {
       buf.setUint8(pos++, flag);
     }
-
     for (let i = 0, ii = xCoordinates.length; i < ii; i++) {
       const x = xCoordinates[i];
       const flag = flags[i];
-
       if (flag & X_SHORT_VECTOR) {
         buf.setUint8(pos++, x);
       } else if (!(flag & X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR)) {
@@ -489,11 +410,9 @@ class SimpleGlyph {
         pos += 2;
       }
     }
-
     for (let i = 0, ii = yCoordinates.length; i < ii; i++) {
       const y = yCoordinates[i];
       const flag = flags[i];
-
       if (flag & Y_SHORT_VECTOR) {
         buf.setUint8(pos++, y);
       } else if (!(flag & Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR)) {
@@ -501,24 +420,19 @@ class SimpleGlyph {
         pos += 2;
       }
     }
-
     return pos - spos;
   }
-
   scale(x, factor) {
     for (const contour of this.contours) {
       if (contour.xCoordinates.length === 0) {
         continue;
       }
-
       for (let i = 0, ii = contour.xCoordinates.length; i < ii; i++) {
         contour.xCoordinates[i] = Math.round(x + (contour.xCoordinates[i] - x) * factor);
       }
     }
   }
-
 }
-
 class CompositeGlyph {
   constructor({
     flags,
@@ -535,7 +449,6 @@ class CompositeGlyph {
     this.transf = transf;
     this.instructions = instructions;
   }
-
   static parse(pos, glyf) {
     const spos = pos;
     const transf = [];
@@ -543,7 +456,6 @@ class CompositeGlyph {
     const glyphIndex = glyf.getUint16(pos + 2);
     pos += 4;
     let argument1, argument2;
-
     if (flags & ARG_1_AND_2_ARE_WORDS) {
       if (flags & ARGS_ARE_XY_VALUES) {
         argument1 = glyf.getInt16(pos);
@@ -552,7 +464,6 @@ class CompositeGlyph {
         argument1 = glyf.getUint16(pos);
         argument2 = glyf.getUint16(pos + 2);
       }
-
       pos += 4;
       flags ^= ARG_1_AND_2_ARE_WORDS;
     } else {
@@ -563,10 +474,8 @@ class CompositeGlyph {
         argument1 = glyf.getUint8(pos);
         argument2 = glyf.getUint8(pos + 1);
       }
-
       pos += 2;
     }
-
     if (flags & WE_HAVE_A_SCALE) {
       transf.push(glyf.getUint16(pos));
       pos += 2;
@@ -577,16 +486,13 @@ class CompositeGlyph {
       transf.push(glyf.getUint16(pos), glyf.getUint16(pos + 2), glyf.getUint16(pos + 4), glyf.getUint16(pos + 6));
       pos += 8;
     }
-
     let instructions = null;
-
     if (flags & WE_HAVE_INSTRUCTIONS) {
       const instructionLength = glyf.getUint16(pos);
       pos += 2;
       instructions = new Uint8Array(glyf).slice(pos, pos + instructionLength);
       pos += instructionLength;
     }
-
     return [pos - spos, new CompositeGlyph({
       flags,
       glyphIndex,
@@ -596,16 +502,12 @@ class CompositeGlyph {
       instructions
     })];
   }
-
   getSize() {
     let size = 2 + 2 + this.transf.length * 2;
-
     if (this.flags & WE_HAVE_INSTRUCTIONS) {
       size += 2 + this.instructions.length;
     }
-
     size += 2;
-
     if (this.flags & 2) {
       if (!(this.argument1 >= -128 && this.argument1 <= 127 && this.argument2 >= -128 && this.argument2 <= 127)) {
         size += 2;
@@ -615,13 +517,10 @@ class CompositeGlyph {
         size += 2;
       }
     }
-
     return size;
   }
-
   write(pos, buf) {
     const spos = pos;
-
     if (this.flags & ARGS_ARE_XY_VALUES) {
       if (!(this.argument1 >= -128 && this.argument1 <= 127 && this.argument2 >= -128 && this.argument2 <= 127)) {
         this.flags |= ARG_1_AND_2_ARE_WORDS;
@@ -631,11 +530,9 @@ class CompositeGlyph {
         this.flags |= ARG_1_AND_2_ARE_WORDS;
       }
     }
-
     buf.setUint16(pos, this.flags);
     buf.setUint16(pos + 2, this.glyphIndex);
     pos += 4;
-
     if (this.flags & ARG_1_AND_2_ARE_WORDS) {
       if (this.flags & ARGS_ARE_XY_VALUES) {
         buf.setInt16(pos, this.argument1);
@@ -644,27 +541,21 @@ class CompositeGlyph {
         buf.setUint16(pos, this.argument1);
         buf.setUint16(pos + 2, this.argument2);
       }
-
       pos += 4;
     } else {
       buf.setUint8(pos, this.argument1);
       buf.setUint8(pos + 1, this.argument2);
       pos += 2;
     }
-
     if (this.flags & WE_HAVE_INSTRUCTIONS) {
       buf.setUint16(pos, this.instructions.length);
       pos += 2;
-
       if (this.instructions.length) {
         new Uint8Array(buf.buffer, 0, buf.buffer.byteLength).set(this.instructions, pos);
         pos += this.instructions.length;
       }
     }
-
     return pos - spos;
   }
-
   scale(x, factor) {}
-
 }

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 2
lib/core/glyphlist.js


+ 10 - 131
lib/core/image.js

@@ -25,39 +25,26 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.PDFImage = void 0;
-
 var _util = require("../shared/util.js");
-
 var _image_utils = require("../shared/image_utils.js");
-
 var _base_stream = require("./base_stream.js");
-
 var _colorspace = require("./colorspace.js");
-
 var _decode_stream = require("./decode_stream.js");
-
 var _jpeg_stream = require("./jpeg_stream.js");
-
 var _jpx = require("./jpx.js");
-
 var _primitives = require("./primitives.js");
-
 function decodeAndClamp(value, addend, coefficient, max) {
   value = addend + value * coefficient;
-
   if (value < 0) {
     value = 0;
   } else if (value > max) {
     value = max;
   }
-
   return value;
 }
-
 function resizeImageMask(src, bpc, w1, h1, w2, h2) {
   const length = w2 * h2;
   let dest;
-
   if (bpc <= 8) {
     dest = new Uint8Array(length);
   } else if (bpc <= 16) {
@@ -65,33 +52,27 @@ function resizeImageMask(src, bpc, w1, h1, w2, h2) {
   } else {
     dest = new Uint32Array(length);
   }
-
   const xRatio = w1 / w2;
   const yRatio = h1 / h2;
   let i,
-      j,
-      py,
-      newIndex = 0,
-      oldIndex;
+    j,
+    py,
+    newIndex = 0,
+    oldIndex;
   const xScaled = new Uint16Array(w2);
   const w1Scanline = w1;
-
   for (i = 0; i < w2; i++) {
     xScaled[i] = Math.floor(i * xRatio);
   }
-
   for (i = 0; i < h2; i++) {
     py = Math.floor(i * yRatio) * w1Scanline;
-
     for (j = 0; j < w2; j++) {
       oldIndex = py + xScaled[j];
       dest[newIndex++] = src[oldIndex];
     }
   }
-
   return dest;
 }
-
 class PDFImage {
   constructor({
     xref,
@@ -108,17 +89,14 @@ class PDFImage {
     const dict = image.dict;
     const filter = dict.get("F", "Filter");
     let filterName;
-
     if (filter instanceof _primitives.Name) {
       filterName = filter.name;
     } else if (Array.isArray(filter)) {
       const filterZero = xref.fetchIfRef(filter[0]);
-
       if (filterZero instanceof _primitives.Name) {
         filterName = filterZero.name;
       }
     }
-
     switch (filterName) {
       case "JPXDecode":
         const jpxImage = new _jpx.JpxImage();
@@ -129,36 +107,29 @@ class PDFImage {
         image.bitsPerComponent = jpxImage.bitsPerComponent;
         image.numComps = jpxImage.componentsCount;
         break;
-
       case "JBIG2Decode":
         image.bitsPerComponent = 1;
         image.numComps = 1;
         break;
     }
-
     let width = dict.get("W", "Width");
     let height = dict.get("H", "Height");
-
     if (Number.isInteger(image.width) && image.width > 0 && Number.isInteger(image.height) && image.height > 0 && (image.width !== width || image.height !== height)) {
       (0, _util.warn)("PDFImage - using the Width/Height of the image data, " + "rather than the image dictionary.");
       width = image.width;
       height = image.height;
     }
-
     if (width < 1 || height < 1) {
       throw new _util.FormatError(`Invalid image width: ${width} or height: ${height}`);
     }
-
     this.width = width;
     this.height = height;
     this.interpolate = dict.get("I", "Interpolate");
     this.imageMask = dict.get("IM", "ImageMask") || false;
     this.matte = dict.get("Matte") || false;
     let bitsPerComponent = image.bitsPerComponent;
-
     if (!bitsPerComponent) {
       bitsPerComponent = dict.get("BPC", "BitsPerComponent");
-
       if (!bitsPerComponent) {
         if (this.imageMask) {
           bitsPerComponent = 1;
@@ -167,33 +138,25 @@ class PDFImage {
         }
       }
     }
-
     this.bpc = bitsPerComponent;
-
     if (!this.imageMask) {
       let colorSpace = dict.getRaw("CS") || dict.getRaw("ColorSpace");
-
       if (!colorSpace) {
         (0, _util.info)("JPX images (which do not require color spaces)");
-
         switch (image.numComps) {
           case 1:
             colorSpace = _primitives.Name.get("DeviceGray");
             break;
-
           case 3:
             colorSpace = _primitives.Name.get("DeviceRGB");
             break;
-
           case 4:
             colorSpace = _primitives.Name.get("DeviceCMYK");
             break;
-
           default:
             throw new Error(`JPX images with ${image.numComps} color components not supported.`);
         }
       }
-
       this.colorSpace = _colorspace.ColorSpace.parse({
         cs: colorSpace,
         xref,
@@ -203,17 +166,14 @@ class PDFImage {
       });
       this.numComps = this.colorSpace.numComps;
     }
-
     this.decode = dict.getArray("D", "Decode");
     this.needsDecode = false;
-
     if (this.decode && (this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode, bitsPerComponent) || isMask && !_colorspace.ColorSpace.isDefaultDecode(this.decode, 1))) {
       this.needsDecode = true;
       const max = (1 << bitsPerComponent) - 1;
       this.decodeCoefficients = [];
       this.decodeAddends = [];
       const isIndexed = this.colorSpace && this.colorSpace.name === "Indexed";
-
       for (let i = 0, j = 0; i < this.decode.length; i += 2, ++j) {
         const dmin = this.decode[i];
         const dmax = this.decode[i + 1];
@@ -221,7 +181,6 @@ class PDFImage {
         this.decodeAddends[j] = isIndexed ? dmin : max * dmin;
       }
     }
-
     if (smask) {
       this.smask = new PDFImage({
         xref,
@@ -234,8 +193,7 @@ class PDFImage {
     } else if (mask) {
       if (mask instanceof _base_stream.BaseStream) {
         const maskDict = mask.dict,
-              imageMask = maskDict.get("IM", "ImageMask");
-
+          imageMask = maskDict.get("IM", "ImageMask");
         if (!imageMask) {
           (0, _util.warn)("Ignoring /Mask in image without /ImageMask.");
         } else {
@@ -254,7 +212,6 @@ class PDFImage {
       }
     }
   }
-
   static async buildImage({
     xref,
     res,
@@ -268,7 +225,6 @@ class PDFImage {
     let maskData = null;
     const smask = image.dict.get("SMask");
     const mask = image.dict.get("Mask");
-
     if (smask) {
       if (smask instanceof _base_stream.BaseStream) {
         smaskData = smask;
@@ -282,7 +238,6 @@ class PDFImage {
         (0, _util.warn)("Unsupported /Mask format.");
       }
     }
-
     return new PDFImage({
       xref,
       res,
@@ -294,7 +249,6 @@ class PDFImage {
       localColorSpaceCache
     });
   }
-
   static createRawMask({
     imgArray,
     width,
@@ -307,7 +261,6 @@ class PDFImage {
     const actualLength = imgArray.byteLength;
     const haveFullData = computedLength === actualLength;
     let data, i;
-
     if (imageIsFromDecodeStream && (!inverseDecode || haveFullData)) {
       data = imgArray;
     } else if (!inverseDecode) {
@@ -317,13 +270,11 @@ class PDFImage {
       data.set(imgArray);
       data.fill(0xff, actualLength);
     }
-
     if (inverseDecode) {
       for (i = 0; i < actualLength; i++) {
         data[i] ^= 0xff;
       }
     }
-
     return {
       data,
       width,
@@ -331,24 +282,22 @@ class PDFImage {
       interpolate
     };
   }
-
   static createMask({
     imgArray,
     width,
     height,
     imageIsFromDecodeStream,
     inverseDecode,
-    interpolate
+    interpolate,
+    isOffscreenCanvasSupported = true
   }) {
     const isSingleOpaquePixel = width === 1 && height === 1 && inverseDecode === (imgArray.length === 0 || !!(imgArray[0] & 128));
-
     if (isSingleOpaquePixel) {
       return {
         isSingleOpaquePixel
       };
     }
-
-    if (_util.FeatureTest.isOffscreenCanvasSupported) {
+    if (isOffscreenCanvasSupported && _util.FeatureTest.isOffscreenCanvasSupported) {
       const canvas = new OffscreenCanvas(width, height);
       const ctx = canvas.getContext("2d");
       const imgData = ctx.createImageData(width, height);
@@ -369,7 +318,6 @@ class PDFImage {
         bitmap
       };
     }
-
     return this.createRawMask({
       imgArray,
       width,
@@ -379,15 +327,12 @@ class PDFImage {
       interpolate
     });
   }
-
   get drawWidth() {
     return Math.max(this.width, this.smask && this.smask.width || 0, this.mask && this.mask.width || 0);
   }
-
   get drawHeight() {
     return Math.max(this.height, this.smask && this.smask.height || 0, this.mask && this.mask.height || 0);
   }
-
   decodeBuffer(buffer) {
     const bpc = this.bpc;
     const numComps = this.numComps;
@@ -395,17 +340,13 @@ class PDFImage {
     const decodeCoefficients = this.decodeCoefficients;
     const max = (1 << bpc) - 1;
     let i, ii;
-
     if (bpc === 1) {
       for (i = 0, ii = buffer.length; i < ii; i++) {
         buffer[i] = +!buffer[i];
       }
-
       return;
     }
-
     let index = 0;
-
     for (i = 0, ii = this.width * this.height; i < ii; i++) {
       for (let j = 0; j < numComps; j++) {
         buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j], decodeCoefficients[j], max);
@@ -413,21 +354,17 @@ class PDFImage {
       }
     }
   }
-
   getComponents(buffer) {
     const bpc = this.bpc;
-
     if (bpc === 8) {
       return buffer;
     }
-
     const width = this.width;
     const height = this.height;
     const numComps = this.numComps;
     const length = width * height * numComps;
     let bufferPos = 0;
     let output;
-
     if (bpc <= 8) {
       output = new Uint8Array(length);
     } else if (bpc <= 16) {
@@ -435,20 +372,16 @@ class PDFImage {
     } else {
       output = new Uint32Array(length);
     }
-
     const rowComps = width * numComps;
     const max = (1 << bpc) - 1;
     let i = 0,
-        ii,
-        buf;
-
+      ii,
+      buf;
     if (bpc === 1) {
       let mask, loop1End, loop2End;
-
       for (let j = 0; j < height; j++) {
         loop1End = i + (rowComps & ~7);
         loop2End = i + rowComps;
-
         while (i < loop1End) {
           buf = buffer[bufferPos++];
           output[i] = buf >> 7 & 1;
@@ -461,11 +394,9 @@ class PDFImage {
           output[i + 7] = buf & 1;
           i += 8;
         }
-
         if (i < loop2End) {
           buf = buffer[bufferPos++];
           mask = 128;
-
           while (i < loop2End) {
             output[i++] = +!!(buf & mask);
             mask >>= 1;
@@ -475,47 +406,38 @@ class PDFImage {
     } else {
       let bits = 0;
       buf = 0;
-
       for (i = 0, ii = length; i < ii; ++i) {
         if (i % rowComps === 0) {
           buf = 0;
           bits = 0;
         }
-
         while (bits < bpc) {
           buf = buf << 8 | buffer[bufferPos++];
           bits += 8;
         }
-
         const remainingBits = bits - bpc;
         let value = buf >> remainingBits;
-
         if (value < 0) {
           value = 0;
         } else if (value > max) {
           value = max;
         }
-
         output[i] = value;
         buf &= (1 << remainingBits) - 1;
         bits = remainingBits;
       }
     }
-
     return output;
   }
-
   fillOpacity(rgbaBuf, width, height, actualHeight, image) {
     const smask = this.smask;
     const mask = this.mask;
     let alphaBuf, sw, sh, i, ii, j;
-
     if (smask) {
       sw = smask.width;
       sh = smask.height;
       alphaBuf = new Uint8ClampedArray(sw * sh);
       smask.fillGrayBuffer(alphaBuf);
-
       if (sw !== width || sh !== height) {
         alphaBuf = resizeImageMask(alphaBuf, smask.bpc, sw, sh, width, height);
       }
@@ -526,39 +448,32 @@ class PDFImage {
         alphaBuf = new Uint8ClampedArray(sw * sh);
         mask.numComps = 1;
         mask.fillGrayBuffer(alphaBuf);
-
         for (i = 0, ii = sw * sh; i < ii; ++i) {
           alphaBuf[i] = 255 - alphaBuf[i];
         }
-
         if (sw !== width || sh !== height) {
           alphaBuf = resizeImageMask(alphaBuf, mask.bpc, sw, sh, width, height);
         }
       } else if (Array.isArray(mask)) {
         alphaBuf = new Uint8ClampedArray(width * height);
         const numComps = this.numComps;
-
         for (i = 0, ii = width * height; i < ii; ++i) {
           let opacity = 0;
           const imageOffset = i * numComps;
-
           for (j = 0; j < numComps; ++j) {
             const color = image[imageOffset + j];
             const maskOffset = j * 2;
-
             if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
               opacity = 255;
               break;
             }
           }
-
           alphaBuf[i] = opacity;
         }
       } else {
         throw new _util.FormatError("Unknown mask format.");
       }
     }
-
     if (alphaBuf) {
       for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
         rgbaBuf[j] = alphaBuf[i];
@@ -569,37 +484,30 @@ class PDFImage {
       }
     }
   }
-
   undoPreblend(buffer, width, height) {
     const matte = this.smask && this.smask.matte;
-
     if (!matte) {
       return;
     }
-
     const matteRgb = this.colorSpace.getRgb(matte, 0);
     const matteR = matteRgb[0];
     const matteG = matteRgb[1];
     const matteB = matteRgb[2];
     const length = width * height * 4;
-
     for (let i = 0; i < length; i += 4) {
       const alpha = buffer[i + 3];
-
       if (alpha === 0) {
         buffer[i] = 255;
         buffer[i + 1] = 255;
         buffer[i + 2] = 255;
         continue;
       }
-
       const k = 255 / alpha;
       buffer[i] = (buffer[i] - matteR) * k + matteR;
       buffer[i + 1] = (buffer[i + 1] - matteG) * k + matteG;
       buffer[i + 2] = (buffer[i + 2] - matteB) * k + matteB;
     }
   }
-
   createImageData(forceRGBA = false) {
     const drawWidth = this.drawWidth;
     const drawHeight = this.drawHeight;
@@ -615,39 +523,30 @@ class PDFImage {
     const originalHeight = this.height;
     const bpc = this.bpc;
     const rowBytes = originalWidth * numComps * bpc + 7 >> 3;
-
     if (!forceRGBA) {
       let kind;
-
       if (this.colorSpace.name === "DeviceGray" && bpc === 1) {
         kind = _util.ImageKind.GRAYSCALE_1BPP;
       } else if (this.colorSpace.name === "DeviceRGB" && bpc === 8 && !this.needsDecode) {
         kind = _util.ImageKind.RGB_24BPP;
       }
-
       if (kind && !this.smask && !this.mask && drawWidth === originalWidth && drawHeight === originalHeight) {
         imgData.kind = kind;
         imgData.data = this.getImageBytes(originalHeight * rowBytes, {});
-
         if (this.needsDecode) {
           (0, _util.assert)(kind === _util.ImageKind.GRAYSCALE_1BPP, "PDFImage.createImageData: The image must be grayscale.");
           const buffer = imgData.data;
-
           for (let i = 0, ii = buffer.length; i < ii; i++) {
             buffer[i] ^= 0xff;
           }
         }
-
         return imgData;
       }
-
       if (this.image instanceof _jpeg_stream.JpegStream && !this.smask && !this.mask) {
         let imageLength = originalHeight * rowBytes;
-
         switch (this.colorSpace.name) {
           case "DeviceGray":
             imageLength *= 3;
-
           case "DeviceRGB":
           case "DeviceCMYK":
             imgData.kind = _util.ImageKind.RGB_24BPP;
@@ -660,14 +559,12 @@ class PDFImage {
         }
       }
     }
-
     const imgArray = this.getImageBytes(originalHeight * rowBytes, {
       internal: true
     });
     const actualHeight = 0 | imgArray.length / rowBytes * drawHeight / originalHeight;
     const comps = this.getComponents(imgArray);
     let alpha01, maybeUndoPreblend;
-
     if (!forceRGBA && !this.smask && !this.mask) {
       imgData.kind = _util.ImageKind.RGB_24BPP;
       imgData.data = new Uint8ClampedArray(drawWidth * drawHeight * 3);
@@ -680,27 +577,20 @@ class PDFImage {
       maybeUndoPreblend = true;
       this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight, comps);
     }
-
     if (this.needsDecode) {
       this.decodeBuffer(comps);
     }
-
     this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight, drawWidth, drawHeight, actualHeight, bpc, comps, alpha01);
-
     if (maybeUndoPreblend) {
       this.undoPreblend(imgData.data, drawWidth, actualHeight);
     }
-
     return imgData;
   }
-
   fillGrayBuffer(buffer) {
     const numComps = this.numComps;
-
     if (numComps !== 1) {
       throw new _util.FormatError(`Reading gray scale from a color image: ${numComps}`);
     }
-
     const width = this.width;
     const height = this.height;
     const bpc = this.bpc;
@@ -710,10 +600,8 @@ class PDFImage {
     });
     const comps = this.getComponents(imgArray);
     let i, length;
-
     if (bpc === 1) {
       length = width * height;
-
       if (this.needsDecode) {
         for (i = 0; i < length; ++i) {
           buffer[i] = comps[i] - 1 & 255;
@@ -723,22 +611,17 @@ class PDFImage {
           buffer[i] = -comps[i] & 255;
         }
       }
-
       return;
     }
-
     if (this.needsDecode) {
       this.decodeBuffer(comps);
     }
-
     length = width * height;
     const scale = 255 / ((1 << bpc) - 1);
-
     for (i = 0; i < length; ++i) {
       buffer[i] = scale * comps[i];
     }
   }
-
   getImageBytes(length, {
     drawWidth,
     drawHeight,
@@ -750,15 +633,11 @@ class PDFImage {
     this.image.drawHeight = drawHeight || this.height;
     this.image.forceRGB = !!forceRGB;
     const imageBytes = this.image.getBytes(length);
-
     if (internal || this.image instanceof _decode_stream.DecodeStream) {
       return imageBytes;
     }
-
     (0, _util.assert)(imageBytes instanceof Uint8Array, 'PDFImage.getImageBytes: Unsupported "imageBytes" type.');
     return new Uint8Array(imageBytes);
   }
-
 }
-
 exports.PDFImage = PDFImage;

+ 0 - 89
lib/core/image_utils.js

@@ -25,314 +25,225 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.LocalTilingPatternCache = exports.LocalImageCache = exports.LocalGStateCache = exports.LocalFunctionCache = exports.LocalColorSpaceCache = exports.GlobalImageCache = void 0;
-
 var _util = require("../shared/util.js");
-
 var _primitives = require("./primitives.js");
-
 class BaseLocalCache {
   constructor(options) {
     if (this.constructor === BaseLocalCache) {
       (0, _util.unreachable)("Cannot initialize BaseLocalCache.");
     }
-
     this._onlyRefs = (options && options.onlyRefs) === true;
-
     if (!this._onlyRefs) {
       this._nameRefMap = new Map();
       this._imageMap = new Map();
     }
-
     this._imageCache = new _primitives.RefSetCache();
   }
-
   getByName(name) {
     if (this._onlyRefs) {
       (0, _util.unreachable)("Should not call `getByName` method.");
     }
-
     const ref = this._nameRefMap.get(name);
-
     if (ref) {
       return this.getByRef(ref);
     }
-
     return this._imageMap.get(name) || null;
   }
-
   getByRef(ref) {
     return this._imageCache.get(ref) || null;
   }
-
   set(name, ref, data) {
     (0, _util.unreachable)("Abstract method `set` called.");
   }
-
 }
-
 class LocalImageCache extends BaseLocalCache {
   set(name, ref = null, data) {
     if (typeof name !== "string") {
       throw new Error('LocalImageCache.set - expected "name" argument.');
     }
-
     if (ref) {
       if (this._imageCache.has(ref)) {
         return;
       }
-
       this._nameRefMap.set(name, ref);
-
       this._imageCache.put(ref, data);
-
       return;
     }
-
     if (this._imageMap.has(name)) {
       return;
     }
-
     this._imageMap.set(name, data);
   }
-
 }
-
 exports.LocalImageCache = LocalImageCache;
-
 class LocalColorSpaceCache extends BaseLocalCache {
   set(name = null, ref = null, data) {
     if (typeof name !== "string" && !ref) {
       throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');
     }
-
     if (ref) {
       if (this._imageCache.has(ref)) {
         return;
       }
-
       if (name !== null) {
         this._nameRefMap.set(name, ref);
       }
-
       this._imageCache.put(ref, data);
-
       return;
     }
-
     if (this._imageMap.has(name)) {
       return;
     }
-
     this._imageMap.set(name, data);
   }
-
 }
-
 exports.LocalColorSpaceCache = LocalColorSpaceCache;
-
 class LocalFunctionCache extends BaseLocalCache {
   constructor(options) {
     super({
       onlyRefs: true
     });
   }
-
   set(name = null, ref, data) {
     if (!ref) {
       throw new Error('LocalFunctionCache.set - expected "ref" argument.');
     }
-
     if (this._imageCache.has(ref)) {
       return;
     }
-
     this._imageCache.put(ref, data);
   }
-
 }
-
 exports.LocalFunctionCache = LocalFunctionCache;
-
 class LocalGStateCache extends BaseLocalCache {
   set(name, ref = null, data) {
     if (typeof name !== "string") {
       throw new Error('LocalGStateCache.set - expected "name" argument.');
     }
-
     if (ref) {
       if (this._imageCache.has(ref)) {
         return;
       }
-
       this._nameRefMap.set(name, ref);
-
       this._imageCache.put(ref, data);
-
       return;
     }
-
     if (this._imageMap.has(name)) {
       return;
     }
-
     this._imageMap.set(name, data);
   }
-
 }
-
 exports.LocalGStateCache = LocalGStateCache;
-
 class LocalTilingPatternCache extends BaseLocalCache {
   constructor(options) {
     super({
       onlyRefs: true
     });
   }
-
   set(name = null, ref, data) {
     if (!ref) {
       throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');
     }
-
     if (this._imageCache.has(ref)) {
       return;
     }
-
     this._imageCache.put(ref, data);
   }
-
 }
-
 exports.LocalTilingPatternCache = LocalTilingPatternCache;
-
 class GlobalImageCache {
   static get NUM_PAGES_THRESHOLD() {
     return (0, _util.shadow)(this, "NUM_PAGES_THRESHOLD", 2);
   }
-
   static get MIN_IMAGES_TO_CACHE() {
     return (0, _util.shadow)(this, "MIN_IMAGES_TO_CACHE", 10);
   }
-
   static get MAX_BYTE_SIZE() {
     return (0, _util.shadow)(this, "MAX_BYTE_SIZE", 40e6);
   }
-
   constructor() {
     this._refCache = new _primitives.RefSetCache();
     this._imageCache = new _primitives.RefSetCache();
   }
-
   get _byteSize() {
     let byteSize = 0;
-
     for (const imageData of this._imageCache) {
       byteSize += imageData.byteSize;
     }
-
     return byteSize;
   }
-
   get _cacheLimitReached() {
     if (this._imageCache.size < GlobalImageCache.MIN_IMAGES_TO_CACHE) {
       return false;
     }
-
     if (this._byteSize < GlobalImageCache.MAX_BYTE_SIZE) {
       return false;
     }
-
     return true;
   }
-
   shouldCache(ref, pageIndex) {
     const pageIndexSet = this._refCache.get(ref);
-
     const numPages = pageIndexSet ? pageIndexSet.size + (pageIndexSet.has(pageIndex) ? 0 : 1) : 1;
-
     if (numPages < GlobalImageCache.NUM_PAGES_THRESHOLD) {
       return false;
     }
-
     if (!this._imageCache.has(ref) && this._cacheLimitReached) {
       return false;
     }
-
     return true;
   }
-
   addPageIndex(ref, pageIndex) {
     let pageIndexSet = this._refCache.get(ref);
-
     if (!pageIndexSet) {
       pageIndexSet = new Set();
-
       this._refCache.put(ref, pageIndexSet);
     }
-
     pageIndexSet.add(pageIndex);
   }
-
   addByteSize(ref, byteSize) {
     const imageData = this._imageCache.get(ref);
-
     if (!imageData) {
       return;
     }
-
     if (imageData.byteSize) {
       return;
     }
-
     imageData.byteSize = byteSize;
   }
-
   getData(ref, pageIndex) {
     const pageIndexSet = this._refCache.get(ref);
-
     if (!pageIndexSet) {
       return null;
     }
-
     if (pageIndexSet.size < GlobalImageCache.NUM_PAGES_THRESHOLD) {
       return null;
     }
-
     const imageData = this._imageCache.get(ref);
-
     if (!imageData) {
       return null;
     }
-
     pageIndexSet.add(pageIndex);
     return imageData;
   }
-
   setData(ref, data) {
     if (!this._refCache.has(ref)) {
       throw new Error('GlobalImageCache.setData - expected "addPageIndex" to have been called.');
     }
-
     if (this._imageCache.has(ref)) {
       return;
     }
-
     if (this._cacheLimitReached) {
       (0, _util.warn)("GlobalImageCache.setData - cache limit reached.");
       return;
     }
-
     this._imageCache.put(ref, data);
   }
-
   clear(onlyData = false) {
     if (!onlyData) {
       this._refCache.clear();
     }
-
     this._imageCache.clear();
   }
-
 }
-
 exports.GlobalImageCache = GlobalImageCache;

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 20 - 224
lib/core/jbig2.js


+ 0 - 17
lib/core/jbig2_stream.js

@@ -25,17 +25,11 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.Jbig2Stream = void 0;
-
 var _base_stream = require("./base_stream.js");
-
 var _decode_stream = require("./decode_stream.js");
-
 var _primitives = require("./primitives.js");
-
 var _jbig = require("./jbig2.js");
-
 var _util = require("../shared/util.js");
-
 class Jbig2Stream extends _decode_stream.DecodeStream {
   constructor(stream, maybeLength, params) {
     super(maybeLength);
@@ -44,24 +38,18 @@ class Jbig2Stream extends _decode_stream.DecodeStream {
     this.maybeLength = maybeLength;
     this.params = params;
   }
-
   get bytes() {
     return (0, _util.shadow)(this, "bytes", this.stream.getBytes(this.maybeLength));
   }
-
   ensureBuffer(requested) {}
-
   readBlock() {
     if (this.eof) {
       return;
     }
-
     const jbig2Image = new _jbig.Jbig2Image();
     const chunks = [];
-
     if (this.params instanceof _primitives.Dict) {
       const globalsStream = this.params.get("JBIG2Globals");
-
       if (globalsStream instanceof _base_stream.BaseStream) {
         const globals = globalsStream.getBytes();
         chunks.push({
@@ -71,7 +59,6 @@ class Jbig2Stream extends _decode_stream.DecodeStream {
         });
       }
     }
-
     chunks.push({
       data: this.bytes,
       start: 0,
@@ -79,16 +66,12 @@ class Jbig2Stream extends _decode_stream.DecodeStream {
     });
     const data = jbig2Image.parseChunks(chunks);
     const dataLength = data.length;
-
     for (let i = 0; i < dataLength; i++) {
       data[i] ^= 0xff;
     }
-
     this.buffer = data;
     this.bufferLength = dataLength;
     this.eof = true;
   }
-
 }
-
 exports.Jbig2Stream = Jbig2Stream;

+ 0 - 20
lib/core/jpeg_stream.js

@@ -25,79 +25,61 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.JpegStream = void 0;
-
 var _decode_stream = require("./decode_stream.js");
-
 var _primitives = require("./primitives.js");
-
 var _jpg = require("./jpg.js");
-
 var _util = require("../shared/util.js");
-
 class JpegStream extends _decode_stream.DecodeStream {
   constructor(stream, maybeLength, params) {
     let ch;
-
     while ((ch = stream.getByte()) !== -1) {
       if (ch === 0xff) {
         stream.skip(-1);
         break;
       }
     }
-
     super(maybeLength);
     this.stream = stream;
     this.dict = stream.dict;
     this.maybeLength = maybeLength;
     this.params = params;
   }
-
   get bytes() {
     return (0, _util.shadow)(this, "bytes", this.stream.getBytes(this.maybeLength));
   }
-
   ensureBuffer(requested) {}
-
   readBlock() {
     if (this.eof) {
       return;
     }
-
     const jpegOptions = {
       decodeTransform: undefined,
       colorTransform: undefined
     };
     const decodeArr = this.dict.getArray("D", "Decode");
-
     if (this.forceRGB && Array.isArray(decodeArr)) {
       const bitsPerComponent = this.dict.get("BPC", "BitsPerComponent") || 8;
       const decodeArrLength = decodeArr.length;
       const transform = new Int32Array(decodeArrLength);
       let transformNeeded = false;
       const maxValue = (1 << bitsPerComponent) - 1;
-
       for (let i = 0; i < decodeArrLength; i += 2) {
         transform[i] = (decodeArr[i + 1] - decodeArr[i]) * 256 | 0;
         transform[i + 1] = decodeArr[i] * maxValue | 0;
-
         if (transform[i] !== 256 || transform[i + 1] !== 0) {
           transformNeeded = true;
         }
       }
-
       if (transformNeeded) {
         jpegOptions.decodeTransform = transform;
       }
     }
-
     if (this.params instanceof _primitives.Dict) {
       const colorTransform = this.params.get("ColorTransform");
-
       if (Number.isInteger(colorTransform)) {
         jpegOptions.colorTransform = colorTransform;
       }
     }
-
     const jpegImage = new _jpg.JpegImage(jpegOptions);
     jpegImage.parse(this.bytes);
     const data = jpegImage.getData({
@@ -110,7 +92,5 @@ class JpegStream extends _decode_stream.DecodeStream {
     this.bufferLength = data.length;
     this.eof = true;
   }
-
 }
-
 exports.JpegStream = JpegStream;

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 19 - 218
lib/core/jpg.js


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 23 - 240
lib/core/jpx.js


+ 0 - 15
lib/core/jpx_stream.js

@@ -25,13 +25,9 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.JpxStream = void 0;
-
 var _decode_stream = require("./decode_stream.js");
-
 var _jpx = require("./jpx.js");
-
 var _util = require("../shared/util.js");
-
 class JpxStream extends _decode_stream.DecodeStream {
   constructor(stream, maybeLength, params) {
     super(maybeLength);
@@ -40,30 +36,24 @@ class JpxStream extends _decode_stream.DecodeStream {
     this.maybeLength = maybeLength;
     this.params = params;
   }
-
   get bytes() {
     return (0, _util.shadow)(this, "bytes", this.stream.getBytes(this.maybeLength));
   }
-
   ensureBuffer(requested) {}
-
   readBlock() {
     if (this.eof) {
       return;
     }
-
     const jpxImage = new _jpx.JpxImage();
     jpxImage.parse(this.bytes);
     const width = jpxImage.width;
     const height = jpxImage.height;
     const componentsCount = jpxImage.componentsCount;
     const tileCount = jpxImage.tiles.length;
-
     if (tileCount === 1) {
       this.buffer = jpxImage.tiles[0].items;
     } else {
       const data = new Uint8ClampedArray(width * height * componentsCount);
-
       for (let k = 0; k < tileCount; k++) {
         const tileComponents = jpxImage.tiles[k];
         const tileWidth = tileComponents.width;
@@ -75,7 +65,6 @@ class JpxStream extends _decode_stream.DecodeStream {
         let dataPosition = (width * tileTop + tileLeft) * componentsCount;
         const imgRowSize = width * componentsCount;
         const tileRowSize = tileWidth * componentsCount;
-
         for (let j = 0; j < tileHeight; j++) {
           const rowBytes = src.subarray(srcPosition, srcPosition + tileRowSize);
           data.set(rowBytes, dataPosition);
@@ -83,14 +72,10 @@ class JpxStream extends _decode_stream.DecodeStream {
           dataPosition += imgRowSize;
         }
       }
-
       this.buffer = data;
     }
-
     this.bufferLength = this.buffer.length;
     this.eof = true;
   }
-
 }
-
 exports.JpxStream = JpxStream;

+ 1 - 24
lib/core/lzw_stream.js

@@ -25,9 +25,7 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.LZWStream = void 0;
-
 var _decode_stream = require("./decode_stream.js");
-
 class LZWStream extends _decode_stream.DecodeStream {
   constructor(str, maybeLength, earlyChange) {
     super(maybeLength);
@@ -46,48 +44,38 @@ class LZWStream extends _decode_stream.DecodeStream {
       currentSequence: new Uint8Array(maxLzwDictionarySize),
       currentSequenceLength: 0
     };
-
     for (let i = 0; i < 256; ++i) {
       lzwState.dictionaryValues[i] = i;
       lzwState.dictionaryLengths[i] = 1;
     }
-
     this.lzwState = lzwState;
   }
-
   readBits(n) {
     let bitsCached = this.bitsCached;
     let cachedData = this.cachedData;
-
     while (bitsCached < n) {
       const c = this.str.getByte();
-
       if (c === -1) {
         this.eof = true;
         return null;
       }
-
       cachedData = cachedData << 8 | c;
       bitsCached += 8;
     }
-
     this.bitsCached = bitsCached -= n;
     this.cachedData = cachedData;
     this.lastCode = null;
     return cachedData >>> bitsCached & (1 << n) - 1;
   }
-
   readBlock() {
     const blockSize = 512,
-          decodedSizeDelta = blockSize;
+      decodedSizeDelta = blockSize;
     let estimatedDecodedSize = blockSize * 2;
     let i, j, q;
     const lzwState = this.lzwState;
-
     if (!lzwState) {
       return;
     }
-
     const earlyChange = lzwState.earlyChange;
     let nextCode = lzwState.nextCode;
     const dictionaryValues = lzwState.dictionaryValues;
@@ -100,18 +88,15 @@ class LZWStream extends _decode_stream.DecodeStream {
     let decodedLength = 0;
     let currentBufferLength = this.bufferLength;
     let buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
-
     for (i = 0; i < blockSize; i++) {
       const code = this.readBits(codeLength);
       const hasPrev = currentSequenceLength > 0;
-
       if (code < 256) {
         currentSequence[0] = code;
         currentSequenceLength = 1;
       } else if (code >= 258) {
         if (code < nextCode) {
           currentSequenceLength = dictionaryLengths[code];
-
           for (j = currentSequenceLength - 1, q = code; j >= 0; j--) {
             currentSequence[j] = dictionaryValues[q];
             q = dictionaryPrevCodes[q];
@@ -129,7 +114,6 @@ class LZWStream extends _decode_stream.DecodeStream {
         delete this.lzwState;
         break;
       }
-
       if (hasPrev) {
         dictionaryPrevCodes[nextCode] = prevCode;
         dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1;
@@ -137,30 +121,23 @@ class LZWStream extends _decode_stream.DecodeStream {
         nextCode++;
         codeLength = nextCode + earlyChange & nextCode + earlyChange - 1 ? codeLength : Math.min(Math.log(nextCode + earlyChange) / 0.6931471805599453 + 1, 12) | 0;
       }
-
       prevCode = code;
       decodedLength += currentSequenceLength;
-
       if (estimatedDecodedSize < decodedLength) {
         do {
           estimatedDecodedSize += decodedSizeDelta;
         } while (estimatedDecodedSize < decodedLength);
-
         buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
       }
-
       for (j = 0; j < currentSequenceLength; j++) {
         buffer[currentBufferLength++] = currentSequence[j];
       }
     }
-
     lzwState.nextCode = nextCode;
     lzwState.codeLength = codeLength;
     lzwState.prevCode = prevCode;
     lzwState.currentSequenceLength = currentSequenceLength;
     this.bufferLength = currentBufferLength;
   }
-
 }
-
 exports.LZWStream = LZWStream;

+ 0 - 31
lib/core/metadata_parser.js

@@ -25,9 +25,7 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.MetadataParser = void 0;
-
 var _xml_parser = require("./xml_parser.js");
-
 class MetadataParser {
   constructor(data) {
     data = this._repair(data);
@@ -37,12 +35,10 @@ class MetadataParser {
     const xmlDocument = parser.parseFromString(data);
     this._metadataMap = new Map();
     this._data = data;
-
     if (xmlDocument) {
       this._parse(xmlDocument);
     }
   }
-
   _repair(data) {
     return data.replace(/^[^<]+/, "").replace(/>\\376\\377([^<]+)/g, function (all, codes) {
       const bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
@@ -51,105 +47,78 @@ class MetadataParser {
         switch (name) {
           case "amp":
             return "&";
-
           case "apos":
             return "'";
-
           case "gt":
             return ">";
-
           case "lt":
             return "<";
-
           case "quot":
             return '"';
         }
-
         throw new Error(`_repair: ${name} isn't defined.`);
       });
       const charBuf = [];
-
       for (let i = 0, ii = bytes.length; i < ii; i += 2) {
         const code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
-
         if (code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38) {
           charBuf.push(String.fromCharCode(code));
         } else {
           charBuf.push("&#x" + (0x10000 + code).toString(16).substring(1) + ";");
         }
       }
-
       return ">" + charBuf.join("");
     });
   }
-
   _getSequence(entry) {
     const name = entry.nodeName;
-
     if (name !== "rdf:bag" && name !== "rdf:seq" && name !== "rdf:alt") {
       return null;
     }
-
     return entry.childNodes.filter(node => node.nodeName === "rdf:li");
   }
-
   _parseArray(entry) {
     if (!entry.hasChildNodes()) {
       return;
     }
-
     const [seqNode] = entry.childNodes;
     const sequence = this._getSequence(seqNode) || [];
-
     this._metadataMap.set(entry.nodeName, sequence.map(node => node.textContent.trim()));
   }
-
   _parse(xmlDocument) {
     let rdf = xmlDocument.documentElement;
-
     if (rdf.nodeName !== "rdf:rdf") {
       rdf = rdf.firstChild;
-
       while (rdf && rdf.nodeName !== "rdf:rdf") {
         rdf = rdf.nextSibling;
       }
     }
-
     if (!rdf || rdf.nodeName !== "rdf:rdf" || !rdf.hasChildNodes()) {
       return;
     }
-
     for (const desc of rdf.childNodes) {
       if (desc.nodeName !== "rdf:description") {
         continue;
       }
-
       for (const entry of desc.childNodes) {
         const name = entry.nodeName;
-
         switch (name) {
           case "#text":
             continue;
-
           case "dc:creator":
           case "dc:subject":
             this._parseArray(entry);
-
             continue;
         }
-
         this._metadataMap.set(name, entry.textContent.trim());
       }
     }
   }
-
   get serializable() {
     return {
       parsedData: this._metadataMap,
       rawData: this._data
     };
   }
-
 }
-
 exports.MetadataParser = MetadataParser;

+ 0 - 2
lib/core/metrics.js

@@ -25,9 +25,7 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.getMetrics = exports.getFontBasicMetrics = void 0;
-
 var _core_utils = require("./core_utils.js");
-
 const getMetrics = (0, _core_utils.getLookupTableFactory)(function (t) {
   t.Courier = 600;
   t["Courier-Bold"] = 600;

+ 3 - 42
lib/core/name_number_tree.js

@@ -25,104 +25,78 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.NumberTree = exports.NameTree = void 0;
-
 var _primitives = require("./primitives.js");
-
 var _util = require("../shared/util.js");
-
 class NameOrNumberTree {
   constructor(root, xref, type) {
     if (this.constructor === NameOrNumberTree) {
       (0, _util.unreachable)("Cannot initialize NameOrNumberTree.");
     }
-
     this.root = root;
     this.xref = xref;
     this._type = type;
   }
-
   getAll() {
     const map = new Map();
-
     if (!this.root) {
       return map;
     }
-
     const xref = this.xref;
     const processed = new _primitives.RefSet();
     processed.put(this.root);
     const queue = [this.root];
-
     while (queue.length > 0) {
       const obj = xref.fetchIfRef(queue.shift());
-
       if (!(obj instanceof _primitives.Dict)) {
         continue;
       }
-
       if (obj.has("Kids")) {
         const kids = obj.get("Kids");
-
         if (!Array.isArray(kids)) {
           continue;
         }
-
         for (const kid of kids) {
           if (processed.has(kid)) {
             throw new _util.FormatError(`Duplicate entry in "${this._type}" tree.`);
           }
-
           queue.push(kid);
           processed.put(kid);
         }
-
         continue;
       }
-
       const entries = obj.get(this._type);
-
       if (!Array.isArray(entries)) {
         continue;
       }
-
       for (let i = 0, ii = entries.length; i < ii; i += 2) {
         map.set(xref.fetchIfRef(entries[i]), xref.fetchIfRef(entries[i + 1]));
       }
     }
-
     return map;
   }
-
   get(key) {
     if (!this.root) {
       return null;
     }
-
     const xref = this.xref;
     let kidsOrEntries = xref.fetchIfRef(this.root);
     let loopCount = 0;
     const MAX_LEVELS = 10;
-
     while (kidsOrEntries.has("Kids")) {
       if (++loopCount > MAX_LEVELS) {
         (0, _util.warn)(`Search depth limit reached for "${this._type}" tree.`);
         return null;
       }
-
       const kids = kidsOrEntries.get("Kids");
-
       if (!Array.isArray(kids)) {
         return null;
       }
-
       let l = 0,
-          r = kids.length - 1;
-
+        r = kids.length - 1;
       while (l <= r) {
         const m = l + r >> 1;
         const kid = xref.fetchIfRef(kids[m]);
         const limits = kid.get("Limits");
-
         if (key < xref.fetchIfRef(limits[0])) {
           r = m - 1;
         } else if (key > xref.fetchIfRef(limits[1])) {
@@ -132,23 +106,18 @@ class NameOrNumberTree {
           break;
         }
       }
-
       if (l > r) {
         return null;
       }
     }
-
     const entries = kidsOrEntries.get(this._type);
-
     if (Array.isArray(entries)) {
       let l = 0,
-          r = entries.length - 2;
-
+        r = entries.length - 2;
       while (l <= r) {
         const tmp = l + r >> 1,
-              m = tmp + (tmp & 1);
+          m = tmp + (tmp & 1);
         const currentKey = xref.fetchIfRef(entries[m]);
-
         if (key < currentKey) {
           r = m - 2;
         } else if (key > currentKey) {
@@ -158,26 +127,18 @@ class NameOrNumberTree {
         }
       }
     }
-
     return null;
   }
-
 }
-
 class NameTree extends NameOrNumberTree {
   constructor(root, xref) {
     super(root, xref, "Names");
   }
-
 }
-
 exports.NameTree = NameTree;
-
 class NumberTree extends NameOrNumberTree {
   constructor(root, xref) {
     super(root, xref, "Nums");
   }
-
 }
-
 exports.NumberTree = NumberTree;

+ 2 - 32
lib/core/object_loader.js

@@ -25,19 +25,13 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.ObjectLoader = void 0;
-
 var _primitives = require("./primitives.js");
-
 var _base_stream = require("./base_stream.js");
-
 var _core_utils = require("./core_utils.js");
-
 var _util = require("../shared/util.js");
-
 function mayHaveChildren(value) {
   return value instanceof _primitives.Ref || value instanceof _primitives.Dict || value instanceof _base_stream.BaseStream || Array.isArray(value);
 }
-
 function addChildren(node, nodesToVisit) {
   if (node instanceof _primitives.Dict) {
     node = node.getRawValues();
@@ -46,14 +40,12 @@ function addChildren(node, nodesToVisit) {
   } else if (!Array.isArray(node)) {
     return;
   }
-
   for (const rawValue of node) {
     if (mayHaveChildren(rawValue)) {
       nodesToVisit.push(rawValue);
     }
   }
 }
-
 class ObjectLoader {
   constructor(dict, keys, xref) {
     this.dict = dict;
@@ -61,42 +53,33 @@ class ObjectLoader {
     this.xref = xref;
     this.refSet = null;
   }
-
   async load() {
     if (this.xref.stream.isDataLoaded) {
       return undefined;
     }
-
     const {
       keys,
       dict
     } = this;
     this.refSet = new _primitives.RefSet();
     const nodesToVisit = [];
-
-    for (let i = 0, ii = keys.length; i < ii; i++) {
-      const rawValue = dict.getRaw(keys[i]);
-
+    for (const key of keys) {
+      const rawValue = dict.getRaw(key);
       if (rawValue !== undefined) {
         nodesToVisit.push(rawValue);
       }
     }
-
     return this._walk(nodesToVisit);
   }
-
   async _walk(nodesToVisit) {
     const nodesToRevisit = [];
     const pendingRequests = [];
-
     while (nodesToVisit.length) {
       let currentNode = nodesToVisit.pop();
-
       if (currentNode instanceof _primitives.Ref) {
         if (this.refSet.has(currentNode)) {
           continue;
         }
-
         try {
           this.refSet.put(currentNode);
           currentNode = this.xref.fetch(currentNode);
@@ -109,7 +92,6 @@ class ObjectLoader {
             } = this.xref.stream;
             return manager.requestAllChunks();
           }
-
           nodesToRevisit.push(currentNode);
           pendingRequests.push({
             begin: ex.begin,
@@ -117,50 +99,38 @@ class ObjectLoader {
           });
         }
       }
-
       if (currentNode instanceof _base_stream.BaseStream) {
         const baseStreams = currentNode.getBaseStreams();
-
         if (baseStreams) {
           let foundMissingData = false;
-
           for (const stream of baseStreams) {
             if (stream.isDataLoaded) {
               continue;
             }
-
             foundMissingData = true;
             pendingRequests.push({
               begin: stream.start,
               end: stream.end
             });
           }
-
           if (foundMissingData) {
             nodesToRevisit.push(currentNode);
           }
         }
       }
-
       addChildren(currentNode, nodesToVisit);
     }
-
     if (pendingRequests.length) {
       await this.xref.stream.manager.requestRanges(pendingRequests);
-
       for (const node of nodesToRevisit) {
         if (node instanceof _primitives.Ref) {
           this.refSet.remove(node);
         }
       }
-
       return this._walk(nodesToRevisit);
     }
-
     this.refSet = null;
     return undefined;
   }
-
 }
-
 exports.ObjectLoader = ObjectLoader;

+ 3 - 27
lib/core/opentype_file_builder.js

@@ -25,23 +25,18 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.OpenTypeFileBuilder = void 0;
-
 var _core_utils = require("./core_utils.js");
-
 var _util = require("../shared/util.js");
-
 function writeInt16(dest, offset, num) {
   dest[offset] = num >> 8 & 0xff;
   dest[offset + 1] = num & 0xff;
 }
-
 function writeInt32(dest, offset, num) {
   dest[offset] = num >> 24 & 0xff;
   dest[offset + 1] = num >> 16 & 0xff;
   dest[offset + 2] = num >> 8 & 0xff;
   dest[offset + 3] = num & 0xff;
 }
-
 function writeData(dest, offset, data) {
   if (data instanceof Uint8Array) {
     dest.set(data, offset);
@@ -50,30 +45,25 @@ function writeData(dest, offset, data) {
       dest[offset++] = data.charCodeAt(i) & 0xff;
     }
   } else {
-    for (let i = 0, ii = data.length; i < ii; i++) {
-      dest[offset++] = data[i] & 0xff;
+    for (const num of data) {
+      dest[offset++] = num & 0xff;
     }
   }
 }
-
 const OTF_HEADER_SIZE = 12;
 const OTF_TABLE_ENTRY_SIZE = 16;
-
 class OpenTypeFileBuilder {
   constructor(sfnt) {
     this.sfnt = sfnt;
     this.tables = Object.create(null);
   }
-
   static getSearchParams(entriesCount, entrySize) {
     let maxPower2 = 1,
-        log2 = 0;
-
+      log2 = 0;
     while ((maxPower2 ^ entriesCount) > maxPower2) {
       maxPower2 <<= 1;
       log2++;
     }
-
     const searchRange = maxPower2 * entrySize;
     return {
       range: searchRange,
@@ -81,7 +71,6 @@ class OpenTypeFileBuilder {
       rangeShift: entrySize * entriesCount - searchRange
     };
   }
-
   toArray() {
     let sfnt = this.sfnt;
     const tables = this.tables;
@@ -91,25 +80,20 @@ class OpenTypeFileBuilder {
     let i, j, jj, table, tableName;
     let offset = OTF_HEADER_SIZE + numTables * OTF_TABLE_ENTRY_SIZE;
     const tableOffsets = [offset];
-
     for (i = 0; i < numTables; i++) {
       table = tables[tablesNames[i]];
       const paddedLength = (table.length + 3 & ~3) >>> 0;
       offset += paddedLength;
       tableOffsets.push(offset);
     }
-
     const file = new Uint8Array(offset);
-
     for (i = 0; i < numTables; i++) {
       table = tables[tablesNames[i]];
       writeData(file, tableOffsets[i], table);
     }
-
     if (sfnt === "true") {
       sfnt = (0, _util.string32)(0x00010000);
     }
-
     file[0] = sfnt.charCodeAt(0) & 0xff;
     file[1] = sfnt.charCodeAt(1) & 0xff;
     file[2] = sfnt.charCodeAt(2) & 0xff;
@@ -120,7 +104,6 @@ class OpenTypeFileBuilder {
     writeInt16(file, 8, searchParams.entry);
     writeInt16(file, 10, searchParams.rangeShift);
     offset = OTF_HEADER_SIZE;
-
     for (i = 0; i < numTables; i++) {
       tableName = tablesNames[i];
       file[offset] = tableName.charCodeAt(0) & 0xff;
@@ -128,29 +111,22 @@ class OpenTypeFileBuilder {
       file[offset + 2] = tableName.charCodeAt(2) & 0xff;
       file[offset + 3] = tableName.charCodeAt(3) & 0xff;
       let checksum = 0;
-
       for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
         const quad = (0, _core_utils.readUint32)(file, j);
         checksum = checksum + quad >>> 0;
       }
-
       writeInt32(file, offset + 4, checksum);
       writeInt32(file, offset + 8, tableOffsets[i]);
       writeInt32(file, offset + 12, tables[tableName].length);
       offset += OTF_TABLE_ENTRY_SIZE;
     }
-
     return file;
   }
-
   addTable(tag, data) {
     if (tag in this.tables) {
       throw new Error("Table " + tag + " already exists");
     }
-
     this.tables[tag] = data;
   }
-
 }
-
 exports.OpenTypeFileBuilder = OpenTypeFileBuilder;

+ 11 - 134
lib/core/operator_list.js

@@ -25,44 +25,34 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.OperatorList = void 0;
-
 var _util = require("../shared/util.js");
-
 function addState(parentState, pattern, checkFn, iterateFn, processFn) {
   let state = parentState;
-
   for (let i = 0, ii = pattern.length - 1; i < ii; i++) {
     const item = pattern[i];
     state = state[item] || (state[item] = []);
   }
-
   state[pattern.at(-1)] = {
     checkFn,
     iterateFn,
     processFn
   };
 }
-
 const InitialState = [];
 addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintInlineImageXObject, _util.OPS.restore], null, function iterateInlineImageGroup(context, i) {
   const fnArray = context.fnArray;
   const iFirstSave = context.iCurr - 3;
   const pos = (i - iFirstSave) % 4;
-
   switch (pos) {
     case 0:
       return fnArray[i] === _util.OPS.save;
-
     case 1:
       return fnArray[i] === _util.OPS.transform;
-
     case 2:
       return fnArray[i] === _util.OPS.paintInlineImageXObject;
-
     case 3:
       return fnArray[i] === _util.OPS.restore;
   }
-
   throw new Error(`iterateInlineImageGroup - invalid pos: ${pos}`);
 }, function foundInlineImageGroup(context, i) {
   const MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
@@ -70,34 +60,29 @@ addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintInli
   const MAX_WIDTH = 1000;
   const IMAGE_PADDING = 1;
   const fnArray = context.fnArray,
-        argsArray = context.argsArray;
+    argsArray = context.argsArray;
   const curr = context.iCurr;
   const iFirstSave = curr - 3;
   const iFirstTransform = curr - 2;
   const iFirstPIIXO = curr - 1;
   const count = Math.min(Math.floor((i - iFirstSave) / 4), MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);
-
   if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {
     return i - (i - iFirstSave) % 4;
   }
-
   let maxX = 0;
   const map = [];
   let maxLineHeight = 0;
   let currentX = IMAGE_PADDING,
-      currentY = IMAGE_PADDING;
-
+    currentY = IMAGE_PADDING;
   for (let q = 0; q < count; q++) {
     const transform = argsArray[iFirstTransform + (q << 2)];
     const img = argsArray[iFirstPIIXO + (q << 2)][0];
-
     if (currentX + img.width > MAX_WIDTH) {
       maxX = Math.max(maxX, currentX);
       currentY += maxLineHeight + 2 * IMAGE_PADDING;
       currentX = 0;
       maxLineHeight = 0;
     }
-
     map.push({
       transform,
       x: currentX,
@@ -108,27 +93,22 @@ addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintInli
     currentX += img.width + 2 * IMAGE_PADDING;
     maxLineHeight = Math.max(maxLineHeight, img.height);
   }
-
   const imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;
   const imgHeight = currentY + maxLineHeight + IMAGE_PADDING;
   const imgData = new Uint8Array(imgWidth * imgHeight * 4);
   const imgRowSize = imgWidth << 2;
-
   for (let q = 0; q < count; q++) {
     const data = argsArray[iFirstPIIXO + (q << 2)][0].data;
     const rowSize = map[q].w << 2;
     let dataOffset = 0;
     let offset = map[q].x + map[q].y * imgWidth << 2;
     imgData.set(data.subarray(0, rowSize), offset - imgRowSize);
-
     for (let k = 0, kk = map[q].h; k < kk; k++) {
       imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);
       dataOffset += rowSize;
       offset += imgRowSize;
     }
-
     imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);
-
     while (offset >= 0) {
       data[offset - 4] = data[offset];
       data[offset - 3] = data[offset + 1];
@@ -141,7 +121,6 @@ addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintInli
       offset -= imgRowSize;
     }
   }
-
   fnArray.splice(iFirstSave, count * 4, _util.OPS.paintInlineImageXObjectGroup);
   argsArray.splice(iFirstSave, count * 4, [{
     width: imgWidth,
@@ -155,83 +134,68 @@ addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImag
   const fnArray = context.fnArray;
   const iFirstSave = context.iCurr - 3;
   const pos = (i - iFirstSave) % 4;
-
   switch (pos) {
     case 0:
       return fnArray[i] === _util.OPS.save;
-
     case 1:
       return fnArray[i] === _util.OPS.transform;
-
     case 2:
       return fnArray[i] === _util.OPS.paintImageMaskXObject;
-
     case 3:
       return fnArray[i] === _util.OPS.restore;
   }
-
   throw new Error(`iterateImageMaskGroup - invalid pos: ${pos}`);
 }, function foundImageMaskGroup(context, i) {
   const MIN_IMAGES_IN_MASKS_BLOCK = 10;
   const MAX_IMAGES_IN_MASKS_BLOCK = 100;
   const MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;
   const fnArray = context.fnArray,
-        argsArray = context.argsArray;
+    argsArray = context.argsArray;
   const curr = context.iCurr;
   const iFirstSave = curr - 3;
   const iFirstTransform = curr - 2;
   const iFirstPIMXO = curr - 1;
   let count = Math.floor((i - iFirstSave) / 4);
-
   if (count < MIN_IMAGES_IN_MASKS_BLOCK) {
     return i - (i - iFirstSave) % 4;
   }
-
   let isSameImage = false;
   let iTransform, transformArgs;
   const firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
   const firstTransformArg0 = argsArray[iFirstTransform][0],
-        firstTransformArg1 = argsArray[iFirstTransform][1],
-        firstTransformArg2 = argsArray[iFirstTransform][2],
-        firstTransformArg3 = argsArray[iFirstTransform][3];
-
+    firstTransformArg1 = argsArray[iFirstTransform][1],
+    firstTransformArg2 = argsArray[iFirstTransform][2],
+    firstTransformArg3 = argsArray[iFirstTransform][3];
   if (firstTransformArg1 === firstTransformArg2) {
     isSameImage = true;
     iTransform = iFirstTransform + 4;
     let iPIMXO = iFirstPIMXO + 4;
-
     for (let q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) {
       transformArgs = argsArray[iTransform];
-
       if (argsArray[iPIMXO][0] !== firstPIMXOArg0 || transformArgs[0] !== firstTransformArg0 || transformArgs[1] !== firstTransformArg1 || transformArgs[2] !== firstTransformArg2 || transformArgs[3] !== firstTransformArg3) {
         if (q < MIN_IMAGES_IN_MASKS_BLOCK) {
           isSameImage = false;
         } else {
           count = q;
         }
-
         break;
       }
     }
   }
-
   if (isSameImage) {
     count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);
     const positions = new Float32Array(count * 2);
     iTransform = iFirstTransform;
-
     for (let q = 0; q < count; q++, iTransform += 4) {
       transformArgs = argsArray[iTransform];
       positions[q << 1] = transformArgs[4];
       positions[(q << 1) + 1] = transformArgs[5];
     }
-
     fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageMaskXObjectRepeat);
     argsArray.splice(iFirstSave, count * 4, [firstPIMXOArg0, firstTransformArg0, firstTransformArg1, firstTransformArg2, firstTransformArg3, positions]);
   } else {
     count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);
     const images = [];
-
     for (let q = 0; q < count; q++) {
       transformArgs = argsArray[iFirstTransform + (q << 2)];
       const maskParams = argsArray[iFirstPIMXO + (q << 2)][0];
@@ -244,11 +208,9 @@ addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImag
         transform: transformArgs
       });
     }
-
     fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageMaskXObjectGroup);
     argsArray.splice(iFirstSave, count * 4, [images]);
   }
-
   return iFirstSave + 1;
 });
 addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImageXObject, _util.OPS.restore], function (context) {
@@ -257,53 +219,42 @@ addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImag
   return argsArray[iFirstTransform][1] === 0 && argsArray[iFirstTransform][2] === 0;
 }, function iterateImageGroup(context, i) {
   const fnArray = context.fnArray,
-        argsArray = context.argsArray;
+    argsArray = context.argsArray;
   const iFirstSave = context.iCurr - 3;
   const pos = (i - iFirstSave) % 4;
-
   switch (pos) {
     case 0:
       return fnArray[i] === _util.OPS.save;
-
     case 1:
       if (fnArray[i] !== _util.OPS.transform) {
         return false;
       }
-
       const iFirstTransform = context.iCurr - 2;
       const firstTransformArg0 = argsArray[iFirstTransform][0];
       const firstTransformArg3 = argsArray[iFirstTransform][3];
-
       if (argsArray[i][0] !== firstTransformArg0 || argsArray[i][1] !== 0 || argsArray[i][2] !== 0 || argsArray[i][3] !== firstTransformArg3) {
         return false;
       }
-
       return true;
-
     case 2:
       if (fnArray[i] !== _util.OPS.paintImageXObject) {
         return false;
       }
-
       const iFirstPIXO = context.iCurr - 1;
       const firstPIXOArg0 = argsArray[iFirstPIXO][0];
-
       if (argsArray[i][0] !== firstPIXOArg0) {
         return false;
       }
-
       return true;
-
     case 3:
       return fnArray[i] === _util.OPS.restore;
   }
-
   throw new Error(`iterateImageGroup - invalid pos: ${pos}`);
 }, function (context, i) {
   const MIN_IMAGES_IN_BLOCK = 3;
   const MAX_IMAGES_IN_BLOCK = 1000;
   const fnArray = context.fnArray,
-        argsArray = context.argsArray;
+    argsArray = context.argsArray;
   const curr = context.iCurr;
   const iFirstSave = curr - 3;
   const iFirstTransform = curr - 2;
@@ -312,20 +263,16 @@ addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImag
   const firstTransformArg0 = argsArray[iFirstTransform][0];
   const firstTransformArg3 = argsArray[iFirstTransform][3];
   const count = Math.min(Math.floor((i - iFirstSave) / 4), MAX_IMAGES_IN_BLOCK);
-
   if (count < MIN_IMAGES_IN_BLOCK) {
     return i - (i - iFirstSave) % 4;
   }
-
   const positions = new Float32Array(count * 2);
   let iTransform = iFirstTransform;
-
   for (let q = 0; q < count; q++, iTransform += 4) {
     const transformArgs = argsArray[iTransform];
     positions[q << 1] = transformArgs[4];
     positions[(q << 1) + 1] = transformArgs[5];
   }
-
   const args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3, positions];
   fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageXObjectRepeat);
   argsArray.splice(iFirstSave, count * 4, args);
@@ -333,45 +280,36 @@ addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImag
 });
 addState(InitialState, [_util.OPS.beginText, _util.OPS.setFont, _util.OPS.setTextMatrix, _util.OPS.showText, _util.OPS.endText], null, function iterateShowTextGroup(context, i) {
   const fnArray = context.fnArray,
-        argsArray = context.argsArray;
+    argsArray = context.argsArray;
   const iFirstSave = context.iCurr - 4;
   const pos = (i - iFirstSave) % 5;
-
   switch (pos) {
     case 0:
       return fnArray[i] === _util.OPS.beginText;
-
     case 1:
       return fnArray[i] === _util.OPS.setFont;
-
     case 2:
       return fnArray[i] === _util.OPS.setTextMatrix;
-
     case 3:
       if (fnArray[i] !== _util.OPS.showText) {
         return false;
       }
-
       const iFirstSetFont = context.iCurr - 3;
       const firstSetFontArg0 = argsArray[iFirstSetFont][0];
       const firstSetFontArg1 = argsArray[iFirstSetFont][1];
-
       if (argsArray[i][0] !== firstSetFontArg0 || argsArray[i][1] !== firstSetFontArg1) {
         return false;
       }
-
       return true;
-
     case 4:
       return fnArray[i] === _util.OPS.endText;
   }
-
   throw new Error(`iterateShowTextGroup - invalid pos: ${pos}`);
 }, function (context, i) {
   const MIN_CHARS_IN_BLOCK = 3;
   const MAX_CHARS_IN_BLOCK = 1000;
   const fnArray = context.fnArray,
-        argsArray = context.argsArray;
+    argsArray = context.argsArray;
   const curr = context.iCurr;
   const iFirstBeginText = curr - 4;
   const iFirstSetFont = curr - 3;
@@ -381,49 +319,35 @@ addState(InitialState, [_util.OPS.beginText, _util.OPS.setFont, _util.OPS.setTex
   const firstSetFontArg0 = argsArray[iFirstSetFont][0];
   const firstSetFontArg1 = argsArray[iFirstSetFont][1];
   let count = Math.min(Math.floor((i - iFirstBeginText) / 5), MAX_CHARS_IN_BLOCK);
-
   if (count < MIN_CHARS_IN_BLOCK) {
     return i - (i - iFirstBeginText) % 5;
   }
-
   let iFirst = iFirstBeginText;
-
   if (iFirstBeginText >= 4 && fnArray[iFirstBeginText - 4] === fnArray[iFirstSetFont] && fnArray[iFirstBeginText - 3] === fnArray[iFirstSetTextMatrix] && fnArray[iFirstBeginText - 2] === fnArray[iFirstShowText] && fnArray[iFirstBeginText - 1] === fnArray[iFirstEndText] && argsArray[iFirstBeginText - 4][0] === firstSetFontArg0 && argsArray[iFirstBeginText - 4][1] === firstSetFontArg1) {
     count++;
     iFirst -= 5;
   }
-
   let iEndText = iFirst + 4;
-
   for (let q = 1; q < count; q++) {
     fnArray.splice(iEndText, 3);
     argsArray.splice(iEndText, 3);
     iEndText += 2;
   }
-
   return iEndText + 1;
 });
-
 class NullOptimizer {
   constructor(queue) {
     this.queue = queue;
   }
-
   _optimize() {}
-
   push(fn, args) {
     this.queue.fnArray.push(fn);
     this.queue.argsArray.push(args);
-
     this._optimize();
   }
-
   flush() {}
-
   reset() {}
-
 }
-
 class QueueOptimizer extends NullOptimizer {
   constructor(queue) {
     super(queue);
@@ -436,125 +360,98 @@ class QueueOptimizer extends NullOptimizer {
     this.match = null;
     this.lastProcessed = 0;
   }
-
   _optimize() {
     const fnArray = this.queue.fnArray;
     let i = this.lastProcessed,
-        ii = fnArray.length;
+      ii = fnArray.length;
     let state = this.state;
     let match = this.match;
-
     if (!state && !match && i + 1 === ii && !InitialState[fnArray[i]]) {
       this.lastProcessed = ii;
       return;
     }
-
     const context = this.context;
-
     while (i < ii) {
       if (match) {
         const iterate = (0, match.iterateFn)(context, i);
-
         if (iterate) {
           i++;
           continue;
         }
-
         i = (0, match.processFn)(context, i + 1);
         ii = fnArray.length;
         match = null;
         state = null;
-
         if (i >= ii) {
           break;
         }
       }
-
       state = (state || InitialState)[fnArray[i]];
-
       if (!state || Array.isArray(state)) {
         i++;
         continue;
       }
-
       context.iCurr = i;
       i++;
-
       if (state.checkFn && !(0, state.checkFn)(context)) {
         state = null;
         continue;
       }
-
       match = state;
       state = null;
     }
-
     this.state = state;
     this.match = match;
     this.lastProcessed = i;
   }
-
   flush() {
     while (this.match) {
       const length = this.queue.fnArray.length;
       this.lastProcessed = (0, this.match.processFn)(this.context, length);
       this.match = null;
       this.state = null;
-
       this._optimize();
     }
   }
-
   reset() {
     this.state = null;
     this.match = null;
     this.lastProcessed = 0;
   }
-
 }
-
 class OperatorList {
   static get CHUNK_SIZE() {
     return (0, _util.shadow)(this, "CHUNK_SIZE", 1000);
   }
-
   static get CHUNK_SIZE_ABOUT() {
     return (0, _util.shadow)(this, "CHUNK_SIZE_ABOUT", this.CHUNK_SIZE - 5);
   }
-
   constructor(intent = 0, streamSink) {
     this._streamSink = streamSink;
     this.fnArray = [];
     this.argsArray = [];
-
     if (streamSink && !(intent & _util.RenderingIntentFlag.OPLIST)) {
       this.optimizer = new QueueOptimizer(this);
     } else {
       this.optimizer = new NullOptimizer(this);
     }
-
     this.dependencies = new Set();
     this._totalLength = 0;
     this.weight = 0;
     this._resolved = streamSink ? null : Promise.resolve();
   }
-
   get length() {
     return this.argsArray.length;
   }
-
   get ready() {
     return this._resolved || this._streamSink.ready;
   }
-
   get totalLength() {
     return this._totalLength + this.length;
   }
-
   addOp(fn, args) {
     this.optimizer.push(fn, args);
     this.weight++;
-
     if (this._streamSink) {
       if (this.weight >= OperatorList.CHUNK_SIZE) {
         this.flush();
@@ -563,49 +460,39 @@ class OperatorList {
       }
     }
   }
-
   addImageOps(fn, args, optionalContent) {
     if (optionalContent !== undefined) {
       this.addOp(_util.OPS.beginMarkedContentProps, ["OC", optionalContent]);
     }
-
     this.addOp(fn, args);
-
     if (optionalContent !== undefined) {
       this.addOp(_util.OPS.endMarkedContent, []);
     }
   }
-
   addDependency(dependency) {
     if (this.dependencies.has(dependency)) {
       return;
     }
-
     this.dependencies.add(dependency);
     this.addOp(_util.OPS.dependency, [dependency]);
   }
-
   addDependencies(dependencies) {
     for (const dependency of dependencies) {
       this.addDependency(dependency);
     }
   }
-
   addOpList(opList) {
     if (!(opList instanceof OperatorList)) {
       (0, _util.warn)('addOpList - ignoring invalid "opList" parameter.');
       return;
     }
-
     for (const dependency of opList.dependencies) {
       this.dependencies.add(dependency);
     }
-
     for (let i = 0, ii = opList.length; i < ii; i++) {
       this.addOp(opList.fnArray[i], opList.argsArray[i]);
     }
   }
-
   getIR() {
     return {
       fnArray: this.fnArray,
@@ -613,7 +500,6 @@ class OperatorList {
       length: this.length
     };
   }
-
   get _transfers() {
     const transfers = [];
     const {
@@ -621,30 +507,24 @@ class OperatorList {
       argsArray,
       length
     } = this;
-
     for (let i = 0; i < length; i++) {
       switch (fnArray[i]) {
         case _util.OPS.paintInlineImageXObject:
         case _util.OPS.paintInlineImageXObjectGroup:
         case _util.OPS.paintImageMaskXObject:
           const arg = argsArray[i][0];
-
           if (!arg.cached && arg.data && arg.data.buffer instanceof ArrayBuffer) {
             transfers.push(arg.data.buffer);
           }
-
           break;
       }
     }
-
     return transfers;
   }
-
   flush(lastChunk = false, separateAnnots = null) {
     this.optimizer.flush();
     const length = this.length;
     this._totalLength += length;
-
     this._streamSink.enqueue({
       fnArray: this.fnArray,
       argsArray: this.argsArray,
@@ -652,14 +532,11 @@ class OperatorList {
       separateAnnots,
       length
     }, 1, this._transfers);
-
     this.dependencies.clear();
     this.fnArray.length = 0;
     this.argsArray.length = 0;
     this.weight = 0;
     this.optimizer.reset();
   }
-
 }
-
 exports.OperatorList = OperatorList;

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 19 - 250
lib/core/parser.js


+ 17 - 173
lib/core/pattern.js

@@ -26,15 +26,10 @@ Object.defineProperty(exports, "__esModule", {
 });
 exports.Pattern = void 0;
 exports.getTilingPatternIR = getTilingPatternIR;
-
 var _util = require("../shared/util.js");
-
 var _base_stream = require("./base_stream.js");
-
 var _colorspace = require("./colorspace.js");
-
 var _core_utils = require("./core_utils.js");
-
 const ShadingType = {
   FUNCTION_BASED: 1,
   AXIAL: 2,
@@ -44,28 +39,23 @@ const ShadingType = {
   COONS_PATCH_MESH: 6,
   TENSOR_PATCH_MESH: 7
 };
-
 class Pattern {
   constructor() {
     (0, _util.unreachable)("Cannot initialize Pattern.");
   }
-
   static parseShading(shading, xref, res, handler, pdfFunctionFactory, localColorSpaceCache) {
     const dict = shading instanceof _base_stream.BaseStream ? shading.dict : shading;
     const type = dict.get("ShadingType");
-
     try {
       switch (type) {
         case ShadingType.AXIAL:
         case ShadingType.RADIAL:
           return new RadialAxialShading(dict, xref, res, pdfFunctionFactory, localColorSpaceCache);
-
         case ShadingType.FREE_FORM_MESH:
         case ShadingType.LATTICE_FORM_MESH:
         case ShadingType.COONS_PATCH_MESH:
         case ShadingType.TENSOR_PATCH_MESH:
           return new MeshShading(shading, xref, res, pdfFunctionFactory, localColorSpaceCache);
-
         default:
           throw new _util.FormatError("Unsupported ShadingType: " + type);
       }
@@ -73,7 +63,6 @@ class Pattern {
       if (ex instanceof _core_utils.MissingDataException) {
         throw ex;
       }
-
       handler.send("UnsupportedFeature", {
         featureId: _util.UNSUPPORTED_FEATURES.shadingPattern
       });
@@ -81,34 +70,26 @@ class Pattern {
       return new DummyShading();
     }
   }
-
 }
-
 exports.Pattern = Pattern;
-
 class BaseShading {
   static get SMALL_NUMBER() {
     return (0, _util.shadow)(this, "SMALL_NUMBER", 1e-6);
   }
-
   constructor() {
     if (this.constructor === BaseShading) {
       (0, _util.unreachable)("Cannot initialize BaseShading.");
     }
   }
-
   getIR() {
     (0, _util.unreachable)("Abstract method `getIR` called.");
   }
-
 }
-
 class RadialAxialShading extends BaseShading {
   constructor(dict, xref, resources, pdfFunctionFactory, localColorSpaceCache) {
     super();
     this.coordsArr = dict.getArray("Coords");
     this.shadingType = dict.get("ShadingType");
-
     const cs = _colorspace.ColorSpace.parse({
       cs: dict.getRaw("CS") || dict.getRaw("ColorSpace"),
       xref,
@@ -116,42 +97,33 @@ class RadialAxialShading extends BaseShading {
       pdfFunctionFactory,
       localColorSpaceCache
     });
-
     const bbox = dict.getArray("BBox");
-
     if (Array.isArray(bbox) && bbox.length === 4) {
       this.bbox = _util.Util.normalizeRect(bbox);
     } else {
       this.bbox = null;
     }
-
     let t0 = 0.0,
-        t1 = 1.0;
-
+      t1 = 1.0;
     if (dict.has("Domain")) {
       const domainArr = dict.getArray("Domain");
       t0 = domainArr[0];
       t1 = domainArr[1];
     }
-
     let extendStart = false,
-        extendEnd = false;
-
+      extendEnd = false;
     if (dict.has("Extend")) {
       const extendArr = dict.getArray("Extend");
       extendStart = extendArr[0];
       extendEnd = extendArr[1];
     }
-
     if (this.shadingType === ShadingType.RADIAL && (!extendStart || !extendEnd)) {
       const [x1, y1, r1, x2, y2, r2] = this.coordsArr;
       const distance = Math.hypot(x1 - x2, y1 - y2);
-
       if (r1 <= r2 + distance && r2 <= r1 + distance) {
         (0, _util.warn)("Unsupported radial gradient.");
       }
     }
-
     this.extendStart = extendStart;
     this.extendEnd = extendEnd;
     const fnObj = dict.getRaw("Function");
@@ -159,51 +131,39 @@ class RadialAxialShading extends BaseShading {
     const NUMBER_OF_SAMPLES = 10;
     const step = (t1 - t0) / NUMBER_OF_SAMPLES;
     const colorStops = this.colorStops = [];
-
     if (t0 >= t1 || step <= 0) {
       (0, _util.info)("Bad shading domain.");
       return;
     }
-
     const color = new Float32Array(cs.numComps),
-          ratio = new Float32Array(1);
+      ratio = new Float32Array(1);
     let rgbColor;
-
     for (let i = 0; i <= NUMBER_OF_SAMPLES; i++) {
       ratio[0] = t0 + i * step;
       fn(ratio, 0, color, 0);
       rgbColor = cs.getRgb(color, 0);
-
       const cssColor = _util.Util.makeHexColor(rgbColor[0], rgbColor[1], rgbColor[2]);
-
       colorStops.push([i / NUMBER_OF_SAMPLES, cssColor]);
     }
-
     let background = "transparent";
-
     if (dict.has("Background")) {
       rgbColor = cs.getRgb(dict.get("Background"), 0);
       background = _util.Util.makeHexColor(rgbColor[0], rgbColor[1], rgbColor[2]);
     }
-
     if (!extendStart) {
       colorStops.unshift([0, background]);
       colorStops[1][0] += BaseShading.SMALL_NUMBER;
     }
-
     if (!extendEnd) {
       colorStops.at(-1)[0] -= BaseShading.SMALL_NUMBER;
       colorStops.push([1, background]);
     }
-
     this.colorStops = colorStops;
   }
-
   getIR() {
     const coordsArr = this.coordsArr;
     const shadingType = this.shadingType;
     let type, p0, p1, r0, r1;
-
     if (shadingType === ShadingType.AXIAL) {
       p0 = [coordsArr[0], coordsArr[1]];
       p1 = [coordsArr[2], coordsArr[3]];
@@ -219,12 +179,9 @@ class RadialAxialShading extends BaseShading {
     } else {
       (0, _util.unreachable)(`getPattern type unknown: ${shadingType}`);
     }
-
     return ["RadialAxial", type, this.bbox, this.colorStops, p0, p1, r0, r1];
   }
-
 }
-
 class MeshStreamReader {
   constructor(stream, context) {
     this.stream = stream;
@@ -236,66 +193,52 @@ class MeshStreamReader {
     const csNumComps = context.colorSpace.numComps;
     this.tmpCsCompsBuf = context.colorFn ? new Float32Array(csNumComps) : this.tmpCompsBuf;
   }
-
   get hasData() {
     if (this.stream.end) {
       return this.stream.pos < this.stream.end;
     }
-
     if (this.bufferLength > 0) {
       return true;
     }
-
     const nextByte = this.stream.getByte();
-
     if (nextByte < 0) {
       return false;
     }
-
     this.buffer = nextByte;
     this.bufferLength = 8;
     return true;
   }
-
   readBits(n) {
     let buffer = this.buffer;
     let bufferLength = this.bufferLength;
-
     if (n === 32) {
       if (bufferLength === 0) {
         return (this.stream.getByte() << 24 | this.stream.getByte() << 16 | this.stream.getByte() << 8 | this.stream.getByte()) >>> 0;
       }
-
       buffer = buffer << 24 | this.stream.getByte() << 16 | this.stream.getByte() << 8 | this.stream.getByte();
       const nextByte = this.stream.getByte();
       this.buffer = nextByte & (1 << bufferLength) - 1;
       return (buffer << 8 - bufferLength | (nextByte & 0xff) >> bufferLength) >>> 0;
     }
-
     if (n === 8 && bufferLength === 0) {
       return this.stream.getByte();
     }
-
     while (bufferLength < n) {
       buffer = buffer << 8 | this.stream.getByte();
       bufferLength += 8;
     }
-
     bufferLength -= n;
     this.bufferLength = bufferLength;
     this.buffer = buffer & (1 << bufferLength) - 1;
     return buffer >> bufferLength;
   }
-
   align() {
     this.buffer = 0;
     this.bufferLength = 0;
   }
-
   readFlag() {
     return this.readBits(this.context.bitsPerFlag);
   }
-
   readCoordinate() {
     const bitsPerCoordinate = this.context.bitsPerCoordinate;
     const xi = this.readBits(bitsPerCoordinate);
@@ -304,83 +247,64 @@ class MeshStreamReader {
     const scale = bitsPerCoordinate < 32 ? 1 / ((1 << bitsPerCoordinate) - 1) : 2.3283064365386963e-10;
     return [xi * scale * (decode[1] - decode[0]) + decode[0], yi * scale * (decode[3] - decode[2]) + decode[2]];
   }
-
   readComponents() {
     const numComps = this.context.numComps;
     const bitsPerComponent = this.context.bitsPerComponent;
     const scale = bitsPerComponent < 32 ? 1 / ((1 << bitsPerComponent) - 1) : 2.3283064365386963e-10;
     const decode = this.context.decode;
     const components = this.tmpCompsBuf;
-
     for (let i = 0, j = 4; i < numComps; i++, j += 2) {
       const ci = this.readBits(bitsPerComponent);
       components[i] = ci * scale * (decode[j + 1] - decode[j]) + decode[j];
     }
-
     const color = this.tmpCsCompsBuf;
-
     if (this.context.colorFn) {
       this.context.colorFn(components, 0, color, 0);
     }
-
     return this.context.colorSpace.getRgb(color, 0);
   }
-
 }
-
 const getB = function getBClosure() {
   function buildB(count) {
     const lut = [];
-
     for (let i = 0; i <= count; i++) {
       const t = i / count,
-            t_ = 1 - t;
+        t_ = 1 - t;
       lut.push(new Float32Array([t_ * t_ * t_, 3 * t * t_ * t_, 3 * t * t * t_, t * t * t]));
     }
-
     return lut;
   }
-
   const cache = [];
   return function (count) {
     if (!cache[count]) {
       cache[count] = buildB(count);
     }
-
     return cache[count];
   };
 }();
-
 class MeshShading extends BaseShading {
   static get MIN_SPLIT_PATCH_CHUNKS_AMOUNT() {
     return (0, _util.shadow)(this, "MIN_SPLIT_PATCH_CHUNKS_AMOUNT", 3);
   }
-
   static get MAX_SPLIT_PATCH_CHUNKS_AMOUNT() {
     return (0, _util.shadow)(this, "MAX_SPLIT_PATCH_CHUNKS_AMOUNT", 20);
   }
-
   static get TRIANGLE_DENSITY() {
     return (0, _util.shadow)(this, "TRIANGLE_DENSITY", 20);
   }
-
   constructor(stream, xref, resources, pdfFunctionFactory, localColorSpaceCache) {
     super();
-
     if (!(stream instanceof _base_stream.BaseStream)) {
       throw new _util.FormatError("Mesh data is not a stream");
     }
-
     const dict = stream.dict;
     this.shadingType = dict.get("ShadingType");
     const bbox = dict.getArray("BBox");
-
     if (Array.isArray(bbox) && bbox.length === 4) {
       this.bbox = _util.Util.normalizeRect(bbox);
     } else {
       this.bbox = null;
     }
-
     const cs = _colorspace.ColorSpace.parse({
       cs: dict.getRaw("CS") || dict.getRaw("ColorSpace"),
       xref,
@@ -388,7 +312,6 @@ class MeshShading extends BaseShading {
       pdfFunctionFactory,
       localColorSpaceCache
     });
-
     this.background = dict.has("Background") ? cs.getRgb(dict.get("Background"), 0) : null;
     const fnObj = dict.getRaw("Function");
     const fn = fnObj ? pdfFunctionFactory.createFromArray(fnObj) : null;
@@ -406,109 +329,83 @@ class MeshShading extends BaseShading {
     };
     const reader = new MeshStreamReader(stream, decodeContext);
     let patchMesh = false;
-
     switch (this.shadingType) {
       case ShadingType.FREE_FORM_MESH:
         this._decodeType4Shading(reader);
-
         break;
-
       case ShadingType.LATTICE_FORM_MESH:
         const verticesPerRow = dict.get("VerticesPerRow") | 0;
-
         if (verticesPerRow < 2) {
           throw new _util.FormatError("Invalid VerticesPerRow");
         }
-
         this._decodeType5Shading(reader, verticesPerRow);
-
         break;
-
       case ShadingType.COONS_PATCH_MESH:
         this._decodeType6Shading(reader);
-
         patchMesh = true;
         break;
-
       case ShadingType.TENSOR_PATCH_MESH:
         this._decodeType7Shading(reader);
-
         patchMesh = true;
         break;
-
       default:
         (0, _util.unreachable)("Unsupported mesh type.");
         break;
     }
-
     if (patchMesh) {
       this._updateBounds();
-
       for (let i = 0, ii = this.figures.length; i < ii; i++) {
         this._buildFigureFromPatch(i);
       }
     }
-
     this._updateBounds();
-
     this._packData();
   }
-
   _decodeType4Shading(reader) {
     const coords = this.coords;
     const colors = this.colors;
     const operators = [];
     const ps = [];
     let verticesLeft = 0;
-
     while (reader.hasData) {
       const f = reader.readFlag();
       const coord = reader.readCoordinate();
       const color = reader.readComponents();
-
       if (verticesLeft === 0) {
         if (!(0 <= f && f <= 2)) {
           throw new _util.FormatError("Unknown type4 flag");
         }
-
         switch (f) {
           case 0:
             verticesLeft = 3;
             break;
-
           case 1:
             ps.push(ps.at(-2), ps.at(-1));
             verticesLeft = 1;
             break;
-
           case 2:
             ps.push(ps.at(-3), ps.at(-1));
             verticesLeft = 1;
             break;
         }
-
         operators.push(f);
       }
-
       ps.push(coords.length);
       coords.push(coord);
       colors.push(color);
       verticesLeft--;
       reader.align();
     }
-
     this.figures.push({
       type: "triangles",
       coords: new Int32Array(ps),
       colors: new Int32Array(ps)
     });
   }
-
   _decodeType5Shading(reader, verticesPerRow) {
     const coords = this.coords;
     const colors = this.colors;
     const ps = [];
-
     while (reader.hasData) {
       const coord = reader.readCoordinate();
       const color = reader.readComponents();
@@ -516,7 +413,6 @@ class MeshShading extends BaseShading {
       coords.push(coord);
       colors.push(color);
     }
-
     this.figures.push({
       type: "lattice",
       coords: new Int32Array(ps),
@@ -524,34 +420,25 @@ class MeshShading extends BaseShading {
       verticesPerRow
     });
   }
-
   _decodeType6Shading(reader) {
     const coords = this.coords;
     const colors = this.colors;
     const ps = new Int32Array(16);
     const cs = new Int32Array(4);
-
     while (reader.hasData) {
       const f = reader.readFlag();
-
       if (!(0 <= f && f <= 3)) {
         throw new _util.FormatError("Unknown type6 flag");
       }
-
       const pi = coords.length;
-
       for (let i = 0, ii = f !== 0 ? 8 : 12; i < ii; i++) {
         coords.push(reader.readCoordinate());
       }
-
       const ci = colors.length;
-
       for (let i = 0, ii = f !== 0 ? 2 : 4; i < ii; i++) {
         colors.push(reader.readComponents());
       }
-
       let tmp1, tmp2, tmp3, tmp4;
-
       switch (f) {
         case 0:
           ps[12] = pi + 3;
@@ -571,7 +458,6 @@ class MeshShading extends BaseShading {
           cs[0] = ci;
           cs[1] = ci + 3;
           break;
-
         case 1:
           tmp1 = ps[12];
           tmp2 = ps[13];
@@ -596,7 +482,6 @@ class MeshShading extends BaseShading {
           cs[0] = tmp1;
           cs[1] = ci + 1;
           break;
-
         case 2:
           tmp1 = ps[15];
           tmp2 = ps[11];
@@ -618,7 +503,6 @@ class MeshShading extends BaseShading {
           cs[0] = tmp1;
           cs[1] = ci + 1;
           break;
-
         case 3:
           ps[12] = ps[0];
           ps[13] = pi + 0;
@@ -638,7 +522,6 @@ class MeshShading extends BaseShading {
           cs[1] = ci + 1;
           break;
       }
-
       ps[5] = coords.length;
       coords.push([(-4 * coords[ps[0]][0] - coords[ps[15]][0] + 6 * (coords[ps[4]][0] + coords[ps[1]][0]) - 2 * (coords[ps[12]][0] + coords[ps[3]][0]) + 3 * (coords[ps[13]][0] + coords[ps[7]][0])) / 9, (-4 * coords[ps[0]][1] - coords[ps[15]][1] + 6 * (coords[ps[4]][1] + coords[ps[1]][1]) - 2 * (coords[ps[12]][1] + coords[ps[3]][1]) + 3 * (coords[ps[13]][1] + coords[ps[7]][1])) / 9]);
       ps[6] = coords.length;
@@ -654,34 +537,25 @@ class MeshShading extends BaseShading {
       });
     }
   }
-
   _decodeType7Shading(reader) {
     const coords = this.coords;
     const colors = this.colors;
     const ps = new Int32Array(16);
     const cs = new Int32Array(4);
-
     while (reader.hasData) {
       const f = reader.readFlag();
-
       if (!(0 <= f && f <= 3)) {
         throw new _util.FormatError("Unknown type7 flag");
       }
-
       const pi = coords.length;
-
       for (let i = 0, ii = f !== 0 ? 12 : 16; i < ii; i++) {
         coords.push(reader.readCoordinate());
       }
-
       const ci = colors.length;
-
       for (let i = 0, ii = f !== 0 ? 2 : 4; i < ii; i++) {
         colors.push(reader.readComponents());
       }
-
       let tmp1, tmp2, tmp3, tmp4;
-
       switch (f) {
         case 0:
           ps[12] = pi + 3;
@@ -705,7 +579,6 @@ class MeshShading extends BaseShading {
           cs[0] = ci;
           cs[1] = ci + 3;
           break;
-
         case 1:
           tmp1 = ps[12];
           tmp2 = ps[13];
@@ -734,7 +607,6 @@ class MeshShading extends BaseShading {
           cs[0] = tmp1;
           cs[1] = ci + 1;
           break;
-
         case 2:
           tmp1 = ps[15];
           tmp2 = ps[11];
@@ -760,7 +632,6 @@ class MeshShading extends BaseShading {
           cs[0] = tmp1;
           cs[1] = ci + 1;
           break;
-
         case 3:
           ps[12] = ps[0];
           ps[13] = pi + 0;
@@ -784,7 +655,6 @@ class MeshShading extends BaseShading {
           cs[1] = ci + 1;
           break;
       }
-
       this.figures.push({
         type: "patch",
         coords: new Int32Array(ps),
@@ -792,12 +662,11 @@ class MeshShading extends BaseShading {
       });
     }
   }
-
   _buildFigureFromPatch(index) {
     const figure = this.figures[index];
     (0, _util.assert)(figure.type === "patch", "Unexpected patch mesh figure");
     const coords = this.coords,
-          colors = this.colors;
+      colors = this.colors;
     const pi = figure.coords;
     const ci = figure.colors;
     const figureMinX = Math.min(coords[pi[0]][0], coords[pi[3]][0], coords[pi[12]][0], coords[pi[15]][0]);
@@ -813,14 +682,13 @@ class MeshShading extends BaseShading {
     const figureColors = new Int32Array((splitYBy + 1) * verticesPerRow);
     let k = 0;
     const cl = new Uint8Array(3),
-          cr = new Uint8Array(3);
+      cr = new Uint8Array(3);
     const c0 = colors[ci[0]],
-          c1 = colors[ci[1]],
-          c2 = colors[ci[2]],
-          c3 = colors[ci[3]];
+      c1 = colors[ci[1]],
+      c2 = colors[ci[2]],
+      c3 = colors[ci[3]];
     const bRow = getB(splitYBy),
-          bCol = getB(splitXBy);
-
+      bCol = getB(splitXBy);
     for (let row = 0; row <= splitYBy; row++) {
       cl[0] = (c0[0] * (splitYBy - row) + c2[0] * row) / splitYBy | 0;
       cl[1] = (c0[1] * (splitYBy - row) + c2[1] * row) / splitYBy | 0;
@@ -828,16 +696,13 @@ class MeshShading extends BaseShading {
       cr[0] = (c1[0] * (splitYBy - row) + c3[0] * row) / splitYBy | 0;
       cr[1] = (c1[1] * (splitYBy - row) + c3[1] * row) / splitYBy | 0;
       cr[2] = (c1[2] * (splitYBy - row) + c3[2] * row) / splitYBy | 0;
-
       for (let col = 0; col <= splitXBy; col++, k++) {
         if ((row === 0 || row === splitYBy) && (col === 0 || col === splitXBy)) {
           continue;
         }
-
         let x = 0,
-            y = 0;
+          y = 0;
         let q = 0;
-
         for (let i = 0; i <= 3; i++) {
           for (let j = 0; j <= 3; j++, q++) {
             const m = bRow[row][i] * bCol[col][j];
@@ -845,7 +710,6 @@ class MeshShading extends BaseShading {
             y += coords[pi[q]][1] * m;
           }
         }
-
         figureCoords[k] = coords.length;
         coords.push([x, y]);
         figureColors[k] = colors.length;
@@ -856,7 +720,6 @@ class MeshShading extends BaseShading {
         colors.push(newColor);
       }
     }
-
     figureCoords[0] = pi[0];
     figureColors[0] = ci[0];
     figureCoords[splitXBy] = pi[3];
@@ -872,88 +735,69 @@ class MeshShading extends BaseShading {
       verticesPerRow
     };
   }
-
   _updateBounds() {
     let minX = this.coords[0][0],
-        minY = this.coords[0][1],
-        maxX = minX,
-        maxY = minY;
-
+      minY = this.coords[0][1],
+      maxX = minX,
+      maxY = minY;
     for (let i = 1, ii = this.coords.length; i < ii; i++) {
       const x = this.coords[i][0],
-            y = this.coords[i][1];
+        y = this.coords[i][1];
       minX = minX > x ? x : minX;
       minY = minY > y ? y : minY;
       maxX = maxX < x ? x : maxX;
       maxY = maxY < y ? y : maxY;
     }
-
     this.bounds = [minX, minY, maxX, maxY];
   }
-
   _packData() {
     let i, ii, j, jj;
     const coords = this.coords;
     const coordsPacked = new Float32Array(coords.length * 2);
-
     for (i = 0, j = 0, ii = coords.length; i < ii; i++) {
       const xy = coords[i];
       coordsPacked[j++] = xy[0];
       coordsPacked[j++] = xy[1];
     }
-
     this.coords = coordsPacked;
     const colors = this.colors;
     const colorsPacked = new Uint8Array(colors.length * 3);
-
     for (i = 0, j = 0, ii = colors.length; i < ii; i++) {
       const c = colors[i];
       colorsPacked[j++] = c[0];
       colorsPacked[j++] = c[1];
       colorsPacked[j++] = c[2];
     }
-
     this.colors = colorsPacked;
     const figures = this.figures;
-
     for (i = 0, ii = figures.length; i < ii; i++) {
       const figure = figures[i],
-            ps = figure.coords,
-            cs = figure.colors;
-
+        ps = figure.coords,
+        cs = figure.colors;
       for (j = 0, jj = ps.length; j < jj; j++) {
         ps[j] *= 2;
         cs[j] *= 3;
       }
     }
   }
-
   getIR() {
     return ["Mesh", this.shadingType, this.coords, this.colors, this.figures, this.bounds, this.bbox, this.background];
   }
-
 }
-
 class DummyShading extends BaseShading {
   getIR() {
     return ["Dummy"];
   }
-
 }
-
 function getTilingPatternIR(operatorList, dict, color) {
   const matrix = dict.getArray("Matrix");
-
   const bbox = _util.Util.normalizeRect(dict.getArray("BBox"));
-
   const xstep = dict.get("XStep");
   const ystep = dict.get("YStep");
   const paintType = dict.get("PaintType");
   const tilingType = dict.get("TilingType");
-
   if (bbox[2] - bbox[0] === 0 || bbox[3] - bbox[1] === 0) {
     throw new _util.FormatError(`Invalid getTilingPatternIR /BBox array: [${bbox}].`);
   }
-
   return ["TilingPattern", color, operatorList, matrix, bbox, xstep, ystep, paintType, tilingType];
 }

+ 4 - 63
lib/core/pdf_manager.js

@@ -25,117 +25,83 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.NetworkPdfManager = exports.LocalPdfManager = void 0;
-
 var _util = require("../shared/util.js");
-
 var _chunked_stream = require("./chunked_stream.js");
-
 var _core_utils = require("./core_utils.js");
-
 var _document = require("./document.js");
-
 var _stream = require("./stream.js");
-
 function parseDocBaseUrl(url) {
   if (url) {
     const absoluteUrl = (0, _util.createValidAbsoluteUrl)(url);
-
     if (absoluteUrl) {
       return absoluteUrl.href;
     }
-
     (0, _util.warn)(`Invalid absolute docBaseUrl: "${url}".`);
   }
-
   return null;
 }
-
 class BasePdfManager {
   constructor() {
     if (this.constructor === BasePdfManager) {
       (0, _util.unreachable)("Cannot initialize BasePdfManager.");
     }
   }
-
   get docId() {
     return this._docId;
   }
-
   get password() {
     return this._password;
   }
-
   get docBaseUrl() {
     const catalog = this.pdfDocument.catalog;
     return (0, _util.shadow)(this, "docBaseUrl", catalog.baseUrl || this._docBaseUrl);
   }
-
-  onLoadedStream() {
-    (0, _util.unreachable)("Abstract method `onLoadedStream` called");
-  }
-
   ensureDoc(prop, args) {
     return this.ensure(this.pdfDocument, prop, args);
   }
-
   ensureXRef(prop, args) {
     return this.ensure(this.pdfDocument.xref, prop, args);
   }
-
   ensureCatalog(prop, args) {
     return this.ensure(this.pdfDocument.catalog, prop, args);
   }
-
   getPage(pageIndex) {
     return this.pdfDocument.getPage(pageIndex);
   }
-
   fontFallback(id, handler) {
     return this.pdfDocument.fontFallback(id, handler);
   }
-
   loadXfaFonts(handler, task) {
     return this.pdfDocument.loadXfaFonts(handler, task);
   }
-
   loadXfaImages() {
     return this.pdfDocument.loadXfaImages();
   }
-
   serializeXfaData(annotationStorage) {
     return this.pdfDocument.serializeXfaData(annotationStorage);
   }
-
   cleanup(manuallyTriggered = false) {
     return this.pdfDocument.cleanup(manuallyTriggered);
   }
-
   async ensure(obj, prop, args) {
     (0, _util.unreachable)("Abstract method `ensure` called");
   }
-
   requestRange(begin, end) {
     (0, _util.unreachable)("Abstract method `requestRange` called");
   }
-
-  requestLoadedStream() {
+  requestLoadedStream(noFetch = false) {
     (0, _util.unreachable)("Abstract method `requestLoadedStream` called");
   }
-
   sendProgressiveData(chunk) {
     (0, _util.unreachable)("Abstract method `sendProgressiveData` called");
   }
-
   updatePassword(password) {
     this._password = password;
   }
-
   terminate(reason) {
     (0, _util.unreachable)("Abstract method `terminate` called");
   }
-
 }
-
 class LocalPdfManager extends BasePdfManager {
   constructor(docId, data, password, msgHandler, evaluatorOptions, enableXfa, docBaseUrl) {
     super();
@@ -149,33 +115,22 @@ class LocalPdfManager extends BasePdfManager {
     this.pdfDocument = new _document.PDFDocument(this, stream);
     this._loadedStreamPromise = Promise.resolve(stream);
   }
-
   async ensure(obj, prop, args) {
     const value = obj[prop];
-
     if (typeof value === "function") {
       return value.apply(obj, args);
     }
-
     return value;
   }
-
   requestRange(begin, end) {
     return Promise.resolve();
   }
-
-  requestLoadedStream() {}
-
-  onLoadedStream() {
+  requestLoadedStream(noFetch = false) {
     return this._loadedStreamPromise;
   }
-
   terminate(reason) {}
-
 }
-
 exports.LocalPdfManager = LocalPdfManager;
-
 class NetworkPdfManager extends BasePdfManager {
   constructor(docId, pdfNetworkStream, args, evaluatorOptions, enableXfa, docBaseUrl) {
     super();
@@ -193,48 +148,34 @@ class NetworkPdfManager extends BasePdfManager {
     });
     this.pdfDocument = new _document.PDFDocument(this, this.streamManager.getStream());
   }
-
   async ensure(obj, prop, args) {
     try {
       const value = obj[prop];
-
       if (typeof value === "function") {
         return value.apply(obj, args);
       }
-
       return value;
     } catch (ex) {
       if (!(ex instanceof _core_utils.MissingDataException)) {
         throw ex;
       }
-
       await this.requestRange(ex.begin, ex.end);
       return this.ensure(obj, prop, args);
     }
   }
-
   requestRange(begin, end) {
     return this.streamManager.requestRange(begin, end);
   }
-
-  requestLoadedStream() {
-    this.streamManager.requestAllChunks();
+  requestLoadedStream(noFetch = false) {
+    return this.streamManager.requestAllChunks(noFetch);
   }
-
   sendProgressiveData(chunk) {
     this.streamManager.onReceiveData({
       chunk
     });
   }
-
-  onLoadedStream() {
-    return this.streamManager.onLoadedStream();
-  }
-
   terminate(reason) {
     this.streamManager.abort(reason);
   }
-
 }
-
 exports.NetworkPdfManager = NetworkPdfManager;

+ 6 - 57
lib/core/predictor_stream.js

@@ -25,37 +25,27 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.PredictorStream = void 0;
-
 var _decode_stream = require("./decode_stream.js");
-
 var _primitives = require("./primitives.js");
-
 var _util = require("../shared/util.js");
-
 class PredictorStream extends _decode_stream.DecodeStream {
   constructor(str, maybeLength, params) {
     super(maybeLength);
-
     if (!(params instanceof _primitives.Dict)) {
       return str;
     }
-
     const predictor = this.predictor = params.get("Predictor") || 1;
-
     if (predictor <= 1) {
       return str;
     }
-
     if (predictor !== 2 && (predictor < 10 || predictor > 15)) {
       throw new _util.FormatError(`Unsupported predictor: ${predictor}`);
     }
-
     if (predictor === 2) {
       this.readBlock = this.readBlockTiff;
     } else {
       this.readBlock = this.readBlockPng;
     }
-
     this.str = str;
     this.dict = str.dict;
     const colors = this.colors = params.get("Colors") || 1;
@@ -65,7 +55,6 @@ class PredictorStream extends _decode_stream.DecodeStream {
     this.rowBytes = columns * colors * bits + 7 >> 3;
     return this;
   }
-
   readBlockTiff() {
     const rowBytes = this.rowBytes;
     const bufferLength = this.bufferLength;
@@ -74,18 +63,15 @@ class PredictorStream extends _decode_stream.DecodeStream {
     const colors = this.colors;
     const rawBytes = this.str.getBytes(rowBytes);
     this.eof = !rawBytes.length;
-
     if (this.eof) {
       return;
     }
-
     let inbuf = 0,
-        outbuf = 0;
+      outbuf = 0;
     let inbits = 0,
-        outbits = 0;
+      outbits = 0;
     let pos = bufferLength;
     let i;
-
     if (bits === 1 && colors === 1) {
       for (i = 0; i < rowBytes; ++i) {
         let c = rawBytes[i] ^ inbuf;
@@ -99,18 +85,15 @@ class PredictorStream extends _decode_stream.DecodeStream {
       for (i = 0; i < colors; ++i) {
         buffer[pos++] = rawBytes[i];
       }
-
       for (; i < rowBytes; ++i) {
         buffer[pos] = buffer[pos - colors] + rawBytes[i];
         pos++;
       }
     } else if (bits === 16) {
       const bytesPerPixel = colors * 2;
-
       for (i = 0; i < bytesPerPixel; ++i) {
         buffer[pos++] = rawBytes[i];
       }
-
       for (; i < rowBytes; i += 2) {
         const sum = ((rawBytes[i] & 0xff) << 8) + (rawBytes[i + 1] & 0xff) + ((buffer[pos - bytesPerPixel] & 0xff) << 8) + (buffer[pos - bytesPerPixel + 1] & 0xff);
         buffer[pos++] = sum >> 8 & 0xff;
@@ -120,131 +103,102 @@ class PredictorStream extends _decode_stream.DecodeStream {
       const compArray = new Uint8Array(colors + 1);
       const bitMask = (1 << bits) - 1;
       let j = 0,
-          k = bufferLength;
+        k = bufferLength;
       const columns = this.columns;
-
       for (i = 0; i < columns; ++i) {
         for (let kk = 0; kk < colors; ++kk) {
           if (inbits < bits) {
             inbuf = inbuf << 8 | rawBytes[j++] & 0xff;
             inbits += 8;
           }
-
           compArray[kk] = compArray[kk] + (inbuf >> inbits - bits) & bitMask;
           inbits -= bits;
           outbuf = outbuf << bits | compArray[kk];
           outbits += bits;
-
           if (outbits >= 8) {
             buffer[k++] = outbuf >> outbits - 8 & 0xff;
             outbits -= 8;
           }
         }
       }
-
       if (outbits > 0) {
         buffer[k++] = (outbuf << 8 - outbits) + (inbuf & (1 << 8 - outbits) - 1);
       }
     }
-
     this.bufferLength += rowBytes;
   }
-
   readBlockPng() {
     const rowBytes = this.rowBytes;
     const pixBytes = this.pixBytes;
     const predictor = this.str.getByte();
     const rawBytes = this.str.getBytes(rowBytes);
     this.eof = !rawBytes.length;
-
     if (this.eof) {
       return;
     }
-
     const bufferLength = this.bufferLength;
     const buffer = this.ensureBuffer(bufferLength + rowBytes);
     let prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength);
-
     if (prevRow.length === 0) {
       prevRow = new Uint8Array(rowBytes);
     }
-
     let i,
-        j = bufferLength,
-        up,
-        c;
-
+      j = bufferLength,
+      up,
+      c;
     switch (predictor) {
       case 0:
         for (i = 0; i < rowBytes; ++i) {
           buffer[j++] = rawBytes[i];
         }
-
         break;
-
       case 1:
         for (i = 0; i < pixBytes; ++i) {
           buffer[j++] = rawBytes[i];
         }
-
         for (; i < rowBytes; ++i) {
           buffer[j] = buffer[j - pixBytes] + rawBytes[i] & 0xff;
           j++;
         }
-
         break;
-
       case 2:
         for (i = 0; i < rowBytes; ++i) {
           buffer[j++] = prevRow[i] + rawBytes[i] & 0xff;
         }
-
         break;
-
       case 3:
         for (i = 0; i < pixBytes; ++i) {
           buffer[j++] = (prevRow[i] >> 1) + rawBytes[i];
         }
-
         for (; i < rowBytes; ++i) {
           buffer[j] = (prevRow[i] + buffer[j - pixBytes] >> 1) + rawBytes[i] & 0xff;
           j++;
         }
-
         break;
-
       case 4:
         for (i = 0; i < pixBytes; ++i) {
           up = prevRow[i];
           c = rawBytes[i];
           buffer[j++] = up + c;
         }
-
         for (; i < rowBytes; ++i) {
           up = prevRow[i];
           const upLeft = prevRow[i - pixBytes];
           const left = buffer[j - pixBytes];
           const p = left + up - upLeft;
           let pa = p - left;
-
           if (pa < 0) {
             pa = -pa;
           }
-
           let pb = p - up;
-
           if (pb < 0) {
             pb = -pb;
           }
-
           let pc = p - upLeft;
-
           if (pc < 0) {
             pc = -pc;
           }
-
           c = rawBytes[i];
-
           if (pa <= pb && pa <= pc) {
             buffer[j++] = left + c;
           } else if (pb <= pc) {
@@ -253,16 +207,11 @@ class PredictorStream extends _decode_stream.DecodeStream {
             buffer[j++] = upLeft + c;
           }
         }
-
         break;
-
       default:
         throw new _util.FormatError(`Unsupported predictor: ${predictor}`);
     }
-
     this.bufferLength += rowBytes;
   }
-
 }
-
 exports.PredictorStream = PredictorStream;

+ 1 - 93
lib/core/primitives.js

@@ -30,64 +30,46 @@ exports.isCmd = isCmd;
 exports.isDict = isDict;
 exports.isName = isName;
 exports.isRefsEqual = isRefsEqual;
-
 var _util = require("../shared/util.js");
-
 const CIRCULAR_REF = Symbol("CIRCULAR_REF");
 exports.CIRCULAR_REF = CIRCULAR_REF;
 const EOF = Symbol("EOF");
 exports.EOF = EOF;
-
 const Name = function NameClosure() {
   let nameCache = Object.create(null);
-
   class Name {
     constructor(name) {
       this.name = name;
     }
-
     static get(name) {
       return nameCache[name] || (nameCache[name] = new Name(name));
     }
-
     static _clearCache() {
       nameCache = Object.create(null);
     }
-
   }
-
   return Name;
 }();
-
 exports.Name = Name;
-
 const Cmd = function CmdClosure() {
   let cmdCache = Object.create(null);
-
   class Cmd {
     constructor(cmd) {
       this.cmd = cmd;
     }
-
     static get(cmd) {
       return cmdCache[cmd] || (cmdCache[cmd] = new Cmd(cmd));
     }
-
     static _clearCache() {
       cmdCache = Object.create(null);
     }
-
   }
-
   return Cmd;
 }();
-
 exports.Cmd = Cmd;
-
 const nonSerializable = function nonSerializableClosure() {
   return nonSerializable;
 };
-
 class Dict {
   constructor(xref = null) {
     this._map = Object.create(null);
@@ -96,150 +78,114 @@ class Dict {
     this.suppressEncryption = false;
     this.__nonSerializable__ = nonSerializable;
   }
-
   assignXref(newXref) {
     this.xref = newXref;
   }
-
   get size() {
     return Object.keys(this._map).length;
   }
-
   get(key1, key2, key3) {
     let value = this._map[key1];
-
     if (value === undefined && key2 !== undefined) {
       value = this._map[key2];
-
       if (value === undefined && key3 !== undefined) {
         value = this._map[key3];
       }
     }
-
     if (value instanceof Ref && this.xref) {
       return this.xref.fetch(value, this.suppressEncryption);
     }
-
     return value;
   }
-
   async getAsync(key1, key2, key3) {
     let value = this._map[key1];
-
     if (value === undefined && key2 !== undefined) {
       value = this._map[key2];
-
       if (value === undefined && key3 !== undefined) {
         value = this._map[key3];
       }
     }
-
     if (value instanceof Ref && this.xref) {
       return this.xref.fetchAsync(value, this.suppressEncryption);
     }
-
     return value;
   }
-
   getArray(key1, key2, key3) {
     let value = this._map[key1];
-
     if (value === undefined && key2 !== undefined) {
       value = this._map[key2];
-
       if (value === undefined && key3 !== undefined) {
         value = this._map[key3];
       }
     }
-
     if (value instanceof Ref && this.xref) {
       value = this.xref.fetch(value, this.suppressEncryption);
     }
-
     if (Array.isArray(value)) {
       value = value.slice();
-
       for (let i = 0, ii = value.length; i < ii; i++) {
         if (value[i] instanceof Ref && this.xref) {
           value[i] = this.xref.fetch(value[i], this.suppressEncryption);
         }
       }
     }
-
     return value;
   }
-
   getRaw(key) {
     return this._map[key];
   }
-
   getKeys() {
     return Object.keys(this._map);
   }
-
   getRawValues() {
     return Object.values(this._map);
   }
-
   set(key, value) {
     this._map[key] = value;
   }
-
   has(key) {
     return this._map[key] !== undefined;
   }
-
   forEach(callback) {
     for (const key in this._map) {
       callback(key, this.get(key));
     }
   }
-
   static get empty() {
     const emptyDict = new Dict(null);
-
     emptyDict.set = (key, value) => {
       (0, _util.unreachable)("Should not call `set` on the empty dictionary.");
     };
-
     return (0, _util.shadow)(this, "empty", emptyDict);
   }
-
   static merge({
     xref,
     dictArray,
     mergeSubDicts = false
   }) {
     const mergedDict = new Dict(xref),
-          properties = new Map();
-
+      properties = new Map();
     for (const dict of dictArray) {
       if (!(dict instanceof Dict)) {
         continue;
       }
-
       for (const [key, value] of Object.entries(dict._map)) {
         let property = properties.get(key);
-
         if (property === undefined) {
           property = [];
           properties.set(key, property);
         } else if (!mergeSubDicts || !(value instanceof Dict)) {
           continue;
         }
-
         property.push(value);
       }
     }
-
     for (const [name, values] of properties) {
       if (values.length === 1 || !(values[0] instanceof Dict)) {
         mergedDict._map[name] = values[0];
         continue;
       }
-
       const subDict = new Dict(xref);
-
       for (const dict of values) {
         for (const [key, value] of Object.entries(dict._map)) {
           if (subDict._map[key] === undefined) {
@@ -247,139 +193,101 @@ class Dict {
           }
         }
       }
-
       if (subDict.size > 0) {
         mergedDict._map[name] = subDict;
       }
     }
-
     properties.clear();
     return mergedDict.size > 0 ? mergedDict : Dict.empty;
   }
-
 }
-
 exports.Dict = Dict;
-
 const Ref = function RefClosure() {
   let refCache = Object.create(null);
-
   class Ref {
     constructor(num, gen) {
       this.num = num;
       this.gen = gen;
     }
-
     toString() {
       if (this.gen === 0) {
         return `${this.num}R`;
       }
-
       return `${this.num}R${this.gen}`;
     }
-
     static get(num, gen) {
       const key = gen === 0 ? `${num}R` : `${num}R${gen}`;
       return refCache[key] || (refCache[key] = new Ref(num, gen));
     }
-
     static _clearCache() {
       refCache = Object.create(null);
     }
-
   }
-
   return Ref;
 }();
-
 exports.Ref = Ref;
-
 class RefSet {
   constructor(parent = null) {
     this._set = new Set(parent && parent._set);
   }
-
   has(ref) {
     return this._set.has(ref.toString());
   }
-
   put(ref) {
     this._set.add(ref.toString());
   }
-
   remove(ref) {
     this._set.delete(ref.toString());
   }
-
   [Symbol.iterator]() {
     return this._set.values();
   }
-
   clear() {
     this._set.clear();
   }
-
 }
-
 exports.RefSet = RefSet;
-
 class RefSetCache {
   constructor() {
     this._map = new Map();
   }
-
   get size() {
     return this._map.size;
   }
-
   get(ref) {
     return this._map.get(ref.toString());
   }
-
   has(ref) {
     return this._map.has(ref.toString());
   }
-
   put(ref, obj) {
     this._map.set(ref.toString(), obj);
   }
-
   putAlias(ref, aliasRef) {
     this._map.set(ref.toString(), this.get(aliasRef));
   }
-
   [Symbol.iterator]() {
     return this._map.values();
   }
-
   clear() {
     this._map.clear();
   }
-
 }
-
 exports.RefSetCache = RefSetCache;
-
 function isName(v, name) {
   return v instanceof Name && (name === undefined || v.name === name);
 }
-
 function isCmd(v, cmd) {
   return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
 }
-
 function isDict(v, type) {
   return v instanceof Dict && (type === undefined || isName(v.get("Type"), type));
 }
-
 function isRefsEqual(v1, v2) {
   return v1.num === v2.num && v1.gen === v2.gen;
 }
-
 function clearPrimitiveCaches() {
   Cmd._clearCache();
-
   Name._clearCache();
-
   Ref._clearCache();
 }

+ 0 - 47
lib/core/ps_parser.js

@@ -25,13 +25,9 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.PostScriptParser = exports.PostScriptLexer = void 0;
-
 var _util = require("../shared/util.js");
-
 var _primitives = require("./primitives.js");
-
 var _core_utils = require("./core_utils.js");
-
 class PostScriptParser {
   constructor(lexer) {
     this.lexer = lexer;
@@ -39,29 +35,23 @@ class PostScriptParser {
     this.token = null;
     this.prev = null;
   }
-
   nextToken() {
     this.prev = this.token;
     this.token = this.lexer.getToken();
   }
-
   accept(type) {
     if (this.token.type === type) {
       this.nextToken();
       return true;
     }
-
     return false;
   }
-
   expect(type) {
     if (this.accept(type)) {
       return true;
     }
-
     throw new _util.FormatError(`Unexpected symbol: found ${this.token.type} expected ${type}.`);
   }
-
   parse() {
     this.nextToken();
     this.expect(PostScriptTokenTypes.LBRACE);
@@ -69,7 +59,6 @@ class PostScriptParser {
     this.expect(PostScriptTokenTypes.RBRACE);
     return this.operators;
   }
-
   parseBlock() {
     while (true) {
       if (this.accept(PostScriptTokenTypes.NUMBER)) {
@@ -83,13 +72,11 @@ class PostScriptParser {
       }
     }
   }
-
   parseCondition() {
     const conditionLocation = this.operators.length;
     this.operators.push(null, null);
     this.parseBlock();
     this.expect(PostScriptTokenTypes.RBRACE);
-
     if (this.accept(PostScriptTokenTypes.IF)) {
       this.operators[conditionLocation] = this.operators.length;
       this.operators[conditionLocation + 1] = "jz";
@@ -108,9 +95,7 @@ class PostScriptParser {
       throw new _util.FormatError("PS Function: error parsing conditional.");
     }
   }
-
 }
-
 exports.PostScriptParser = PostScriptParser;
 const PostScriptTokenTypes = {
   LBRACE: 0,
@@ -120,65 +105,50 @@ const PostScriptTokenTypes = {
   IF: 4,
   IFELSE: 5
 };
-
 class PostScriptToken {
   static get opCache() {
     return (0, _util.shadow)(this, "opCache", Object.create(null));
   }
-
   constructor(type, value) {
     this.type = type;
     this.value = value;
   }
-
   static getOperator(op) {
     const opValue = PostScriptToken.opCache[op];
-
     if (opValue) {
       return opValue;
     }
-
     return PostScriptToken.opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);
   }
-
   static get LBRACE() {
     return (0, _util.shadow)(this, "LBRACE", new PostScriptToken(PostScriptTokenTypes.LBRACE, "{"));
   }
-
   static get RBRACE() {
     return (0, _util.shadow)(this, "RBRACE", new PostScriptToken(PostScriptTokenTypes.RBRACE, "}"));
   }
-
   static get IF() {
     return (0, _util.shadow)(this, "IF", new PostScriptToken(PostScriptTokenTypes.IF, "IF"));
   }
-
   static get IFELSE() {
     return (0, _util.shadow)(this, "IFELSE", new PostScriptToken(PostScriptTokenTypes.IFELSE, "IFELSE"));
   }
-
 }
-
 class PostScriptLexer {
   constructor(stream) {
     this.stream = stream;
     this.nextChar();
     this.strBuf = [];
   }
-
   nextChar() {
     return this.currentChar = this.stream.getByte();
   }
-
   getToken() {
     let comment = false;
     let ch = this.currentChar;
-
     while (true) {
       if (ch < 0) {
         return _primitives.EOF;
       }
-
       if (comment) {
         if (ch === 0x0a || ch === 0x0d) {
           comment = false;
@@ -188,10 +158,8 @@ class PostScriptLexer {
       } else if (!(0, _core_utils.isWhiteSpace)(ch)) {
         break;
       }
-
       ch = this.nextChar();
     }
-
     switch (ch | 0) {
       case 0x30:
       case 0x31:
@@ -207,44 +175,34 @@ class PostScriptLexer {
       case 0x2d:
       case 0x2e:
         return new PostScriptToken(PostScriptTokenTypes.NUMBER, this.getNumber());
-
       case 0x7b:
         this.nextChar();
         return PostScriptToken.LBRACE;
-
       case 0x7d:
         this.nextChar();
         return PostScriptToken.RBRACE;
     }
-
     const strBuf = this.strBuf;
     strBuf.length = 0;
     strBuf[0] = String.fromCharCode(ch);
-
     while ((ch = this.nextChar()) >= 0 && (ch >= 0x41 && ch <= 0x5a || ch >= 0x61 && ch <= 0x7a)) {
       strBuf.push(String.fromCharCode(ch));
     }
-
     const str = strBuf.join("");
-
     switch (str.toLowerCase()) {
       case "if":
         return PostScriptToken.IF;
-
       case "ifelse":
         return PostScriptToken.IFELSE;
-
       default:
         return PostScriptToken.getOperator(str);
     }
   }
-
   getNumber() {
     let ch = this.currentChar;
     const strBuf = this.strBuf;
     strBuf.length = 0;
     strBuf[0] = String.fromCharCode(ch);
-
     while ((ch = this.nextChar()) >= 0) {
       if (ch >= 0x30 && ch <= 0x39 || ch === 0x2d || ch === 0x2e) {
         strBuf.push(String.fromCharCode(ch));
@@ -252,16 +210,11 @@ class PostScriptLexer {
         break;
       }
     }
-
     const value = parseFloat(strBuf.join(""));
-
     if (isNaN(value)) {
       throw new _util.FormatError(`Invalid floating point number: ${value}`);
     }
-
     return value;
   }
-
 }
-
 exports.PostScriptLexer = PostScriptLexer;

+ 0 - 11
lib/core/run_length_stream.js

@@ -25,32 +25,25 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.RunLengthStream = void 0;
-
 var _decode_stream = require("./decode_stream.js");
-
 class RunLengthStream extends _decode_stream.DecodeStream {
   constructor(str, maybeLength) {
     super(maybeLength);
     this.str = str;
     this.dict = str.dict;
   }
-
   readBlock() {
     const repeatHeader = this.str.getBytes(2);
-
     if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] === 128) {
       this.eof = true;
       return;
     }
-
     let buffer;
     let bufferLength = this.bufferLength;
     let n = repeatHeader[0];
-
     if (n < 128) {
       buffer = this.ensureBuffer(bufferLength + n + 1);
       buffer[bufferLength++] = repeatHeader[1];
-
       if (n > 0) {
         const source = this.str.getBytes(n);
         buffer.set(source, bufferLength);
@@ -60,15 +53,11 @@ class RunLengthStream extends _decode_stream.DecodeStream {
       n = 257 - n;
       const b = repeatHeader[1];
       buffer = this.ensureBuffer(bufferLength + n + 1);
-
       for (let i = 0; i < n; i++) {
         buffer[bufferLength++] = b;
       }
     }
-
     this.bufferLength = bufferLength;
   }
-
 }
-
 exports.RunLengthStream = RunLengthStream;

+ 18 - 4
lib/core/standard_fonts.js

@@ -27,11 +27,8 @@ Object.defineProperty(exports, "__esModule", {
 exports.getSerifFonts = exports.getNonStdFontMap = exports.getGlyphMapForStandardFonts = exports.getFontNameToFileMap = void 0;
 exports.getStandardFontName = getStandardFontName;
 exports.getSymbolsFonts = exports.getSupplementalGlyphMapForCalibri = exports.getSupplementalGlyphMapForArialBlack = exports.getStdFontMap = void 0;
-
 var _core_utils = require("./core_utils.js");
-
 var _fonts_utils = require("./fonts_utils.js");
-
 const getStdFontMap = (0, _core_utils.getLookupTableFactory)(function (t) {
   t["Times-Roman"] = "Times-Roman";
   t.Helvetica = "Helvetica";
@@ -483,6 +480,10 @@ const getGlyphMapForStandardFonts = (0, _core_utils.getLookupTableFactory)(funct
   t[169] = 171;
   t[170] = 187;
   t[171] = 8230;
+  t[179] = 8220;
+  t[180] = 8221;
+  t[181] = 8216;
+  t[182] = 8217;
   t[200] = 193;
   t[203] = 205;
   t[210] = 218;
@@ -752,18 +753,22 @@ exports.getSupplementalGlyphMapForArialBlack = getSupplementalGlyphMapForArialBl
 const getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)(function (t) {
   t[1] = 32;
   t[4] = 65;
+  t[5] = 192;
   t[6] = 193;
+  t[9] = 196;
   t[17] = 66;
   t[18] = 67;
   t[21] = 268;
   t[24] = 68;
   t[28] = 69;
+  t[29] = 200;
   t[30] = 201;
   t[32] = 282;
   t[38] = 70;
   t[39] = 71;
   t[44] = 72;
   t[47] = 73;
+  t[48] = 204;
   t[49] = 205;
   t[58] = 74;
   t[60] = 75;
@@ -771,6 +776,8 @@ const getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)
   t[68] = 77;
   t[69] = 78;
   t[75] = 79;
+  t[76] = 210;
+  t[80] = 214;
   t[87] = 80;
   t[89] = 81;
   t[90] = 82;
@@ -779,6 +786,7 @@ const getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)
   t[97] = 352;
   t[100] = 84;
   t[104] = 85;
+  t[109] = 220;
   t[115] = 86;
   t[116] = 87;
   t[121] = 88;
@@ -787,7 +795,9 @@ const getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)
   t[127] = 90;
   t[129] = 381;
   t[258] = 97;
+  t[259] = 224;
   t[260] = 225;
+  t[263] = 228;
   t[268] = 261;
   t[271] = 98;
   t[272] = 99;
@@ -795,6 +805,7 @@ const getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)
   t[275] = 269;
   t[282] = 100;
   t[286] = 101;
+  t[287] = 232;
   t[288] = 233;
   t[290] = 283;
   t[295] = 281;
@@ -802,6 +813,7 @@ const getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)
   t[336] = 103;
   t[346] = 104;
   t[349] = 105;
+  t[350] = 236;
   t[351] = 237;
   t[361] = 106;
   t[364] = 107;
@@ -810,7 +822,9 @@ const getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)
   t[373] = 109;
   t[374] = 110;
   t[381] = 111;
+  t[382] = 242;
   t[383] = 243;
+  t[386] = 246;
   t[393] = 112;
   t[395] = 113;
   t[396] = 114;
@@ -820,6 +834,7 @@ const getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)
   t[403] = 353;
   t[410] = 116;
   t[437] = 117;
+  t[442] = 252;
   t[448] = 118;
   t[449] = 119;
   t[454] = 120;
@@ -854,7 +869,6 @@ const getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)
   t[1086] = 45;
 });
 exports.getSupplementalGlyphMapForCalibri = getSupplementalGlyphMapForCalibri;
-
 function getStandardFontName(name) {
   const fontName = (0, _fonts_utils.normalizeFontName)(name);
   const stdFontMap = getStdFontMap();

+ 0 - 26
lib/core/stream.js

@@ -25,11 +25,8 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.StringStream = exports.Stream = exports.NullStream = void 0;
-
 var _base_stream = require("./base_stream.js");
-
 var _util = require("../shared/util.js");
-
 class Stream extends _base_stream.BaseStream {
   constructor(arrayBuffer, start, length, dict) {
     super();
@@ -39,84 +36,61 @@ class Stream extends _base_stream.BaseStream {
     this.end = start + length || this.bytes.length;
     this.dict = dict;
   }
-
   get length() {
     return this.end - this.start;
   }
-
   get isEmpty() {
     return this.length === 0;
   }
-
   getByte() {
     if (this.pos >= this.end) {
       return -1;
     }
-
     return this.bytes[this.pos++];
   }
-
   getBytes(length) {
     const bytes = this.bytes;
     const pos = this.pos;
     const strEnd = this.end;
-
     if (!length) {
       return bytes.subarray(pos, strEnd);
     }
-
     let end = pos + length;
-
     if (end > strEnd) {
       end = strEnd;
     }
-
     this.pos = end;
     return bytes.subarray(pos, end);
   }
-
   getByteRange(begin, end) {
     if (begin < 0) {
       begin = 0;
     }
-
     if (end > this.end) {
       end = this.end;
     }
-
     return this.bytes.subarray(begin, end);
   }
-
   reset() {
     this.pos = this.start;
   }
-
   moveStart() {
     this.start = this.pos;
   }
-
   makeSubStream(start, length, dict = null) {
     return new Stream(this.bytes.buffer, start, length, dict);
   }
-
 }
-
 exports.Stream = Stream;
-
 class StringStream extends Stream {
   constructor(str) {
     super((0, _util.stringToBytes)(str));
   }
-
 }
-
 exports.StringStream = StringStream;
-
 class NullStream extends Stream {
   constructor() {
     super(new Uint8Array(0));
   }
-
 }
-
 exports.NullStream = NullStream;

+ 0 - 81
lib/core/struct_tree.js

@@ -25,13 +25,9 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.StructTreeRoot = exports.StructTreePage = void 0;
-
 var _primitives = require("./primitives.js");
-
 var _util = require("../shared/util.js");
-
 var _name_number_tree = require("./name_number_tree.js");
-
 const MAX_DEPTH = 40;
 const StructElementType = {
   PAGE_CONTENT: "PAGE_CONTENT",
@@ -39,37 +35,28 @@ const StructElementType = {
   OBJECT: "OBJECT",
   ELEMENT: "ELEMENT"
 };
-
 class StructTreeRoot {
   constructor(rootDict) {
     this.dict = rootDict;
     this.roleMap = new Map();
   }
-
   init() {
     this.readRoleMap();
   }
-
   readRoleMap() {
     const roleMapDict = this.dict.get("RoleMap");
-
     if (!(roleMapDict instanceof _primitives.Dict)) {
       return;
     }
-
     roleMapDict.forEach((key, value) => {
       if (!(value instanceof _primitives.Name)) {
         return;
       }
-
       this.roleMap.set(key, value.name);
     });
   }
-
 }
-
 exports.StructTreeRoot = StructTreeRoot;
-
 class StructElementNode {
   constructor(tree, dict) {
     this.tree = tree;
@@ -77,86 +64,67 @@ class StructElementNode {
     this.kids = [];
     this.parseKids();
   }
-
   get role() {
     const nameObj = this.dict.get("S");
     const name = nameObj instanceof _primitives.Name ? nameObj.name : "";
     const {
       root
     } = this.tree;
-
     if (root.roleMap.has(name)) {
       return root.roleMap.get(name);
     }
-
     return name;
   }
-
   parseKids() {
     let pageObjId = null;
     const objRef = this.dict.getRaw("Pg");
-
     if (objRef instanceof _primitives.Ref) {
       pageObjId = objRef.toString();
     }
-
     const kids = this.dict.get("K");
-
     if (Array.isArray(kids)) {
       for (const kid of kids) {
         const element = this.parseKid(pageObjId, kid);
-
         if (element) {
           this.kids.push(element);
         }
       }
     } else {
       const element = this.parseKid(pageObjId, kids);
-
       if (element) {
         this.kids.push(element);
       }
     }
   }
-
   parseKid(pageObjId, kid) {
     if (Number.isInteger(kid)) {
       if (this.tree.pageDict.objId !== pageObjId) {
         return null;
       }
-
       return new StructElement({
         type: StructElementType.PAGE_CONTENT,
         mcid: kid,
         pageObjId
       });
     }
-
     let kidDict = null;
-
     if (kid instanceof _primitives.Ref) {
       kidDict = this.dict.xref.fetch(kid);
     } else if (kid instanceof _primitives.Dict) {
       kidDict = kid;
     }
-
     if (!kidDict) {
       return null;
     }
-
     const pageRef = kidDict.getRaw("Pg");
-
     if (pageRef instanceof _primitives.Ref) {
       pageObjId = pageRef.toString();
     }
-
     const type = kidDict.get("Type") instanceof _primitives.Name ? kidDict.get("Type").name : null;
-
     if (type === "MCR") {
       if (this.tree.pageDict.objId !== pageObjId) {
         return null;
       }
-
       return new StructElement({
         type: StructElementType.STREAM_CONTENT,
         refObjId: kidDict.getRaw("Stm") instanceof _primitives.Ref ? kidDict.getRaw("Stm").toString() : null,
@@ -164,27 +132,22 @@ class StructElementNode {
         mcid: kidDict.get("MCID")
       });
     }
-
     if (type === "OBJR") {
       if (this.tree.pageDict.objId !== pageObjId) {
         return null;
       }
-
       return new StructElement({
         type: StructElementType.OBJECT,
         refObjId: kidDict.getRaw("Obj") instanceof _primitives.Ref ? kidDict.getRaw("Obj").toString() : null,
         pageObjId
       });
     }
-
     return new StructElement({
       type: StructElementType.ELEMENT,
       dict: kidDict
     });
   }
-
 }
-
 class StructElement {
   constructor({
     type,
@@ -200,9 +163,7 @@ class StructElement {
     this.refObjId = refObjId;
     this.parentNode = null;
   }
-
 }
-
 class StructTreePage {
   constructor(structTreeRoot, pageDict) {
     this.root = structTreeRoot;
@@ -210,144 +171,108 @@ class StructTreePage {
     this.pageDict = pageDict;
     this.nodes = [];
   }
-
   parse() {
     if (!this.root || !this.rootDict) {
       return;
     }
-
     const parentTree = this.rootDict.get("ParentTree");
-
     if (!parentTree) {
       return;
     }
-
     const id = this.pageDict.get("StructParents");
-
     if (!Number.isInteger(id)) {
       return;
     }
-
     const numberTree = new _name_number_tree.NumberTree(parentTree, this.rootDict.xref);
     const parentArray = numberTree.get(id);
-
     if (!Array.isArray(parentArray)) {
       return;
     }
-
     const map = new Map();
-
     for (const ref of parentArray) {
       if (ref instanceof _primitives.Ref) {
         this.addNode(this.rootDict.xref.fetch(ref), map);
       }
     }
   }
-
   addNode(dict, map, level = 0) {
     if (level > MAX_DEPTH) {
       (0, _util.warn)("StructTree MAX_DEPTH reached.");
       return null;
     }
-
     if (map.has(dict)) {
       return map.get(dict);
     }
-
     const element = new StructElementNode(this, dict);
     map.set(dict, element);
     const parent = dict.get("P");
-
     if (!parent || (0, _primitives.isName)(parent.get("Type"), "StructTreeRoot")) {
       if (!this.addTopLevelNode(dict, element)) {
         map.delete(dict);
       }
-
       return element;
     }
-
     const parentNode = this.addNode(parent, map, level + 1);
-
     if (!parentNode) {
       return element;
     }
-
     let save = false;
-
     for (const kid of parentNode.kids) {
       if (kid.type === StructElementType.ELEMENT && kid.dict === dict) {
         kid.parentNode = element;
         save = true;
       }
     }
-
     if (!save) {
       map.delete(dict);
     }
-
     return element;
   }
-
   addTopLevelNode(dict, element) {
     const obj = this.rootDict.get("K");
-
     if (!obj) {
       return false;
     }
-
     if (obj instanceof _primitives.Dict) {
       if (obj.objId !== dict.objId) {
         return false;
       }
-
       this.nodes[0] = element;
       return true;
     }
-
     if (!Array.isArray(obj)) {
       return true;
     }
-
     let save = false;
-
     for (let i = 0; i < obj.length; i++) {
       const kidRef = obj[i];
-
       if (kidRef && kidRef.toString() === dict.objId) {
         this.nodes[i] = element;
         save = true;
       }
     }
-
     return save;
   }
-
   get serializable() {
     function nodeToSerializable(node, parent, level = 0) {
       if (level > MAX_DEPTH) {
         (0, _util.warn)("StructTree too deep to be fully serialized.");
         return;
       }
-
       const obj = Object.create(null);
       obj.role = node.role;
       obj.children = [];
       parent.children.push(obj);
       const alt = node.dict.get("Alt");
-
       if (typeof alt === "string") {
         obj.alt = (0, _util.stringToPDFString)(alt);
       }
-
       const lang = node.dict.get("Lang");
-
       if (typeof lang === "string") {
         obj.lang = (0, _util.stringToPDFString)(lang);
       }
-
       for (const kid of node.kids) {
         const kidElement = kid.type === StructElementType.ELEMENT ? kid.parentNode : null;
-
         if (kidElement) {
           nodeToSerializable(kidElement, obj, level + 1);
           continue;
@@ -364,22 +289,16 @@ class StructTreePage {
         }
       }
     }
-
     const root = Object.create(null);
     root.children = [];
     root.role = "Root";
-
     for (const child of this.nodes) {
       if (!child) {
         continue;
       }
-
       nodeToSerializable(child, root);
     }
-
     return root;
   }
-
 }
-
 exports.StructTreePage = StructTreePage;

+ 0 - 23
lib/core/to_unicode_map.js

@@ -25,94 +25,71 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.ToUnicodeMap = exports.IdentityToUnicodeMap = void 0;
-
 var _util = require("../shared/util.js");
-
 class ToUnicodeMap {
   constructor(cmap = []) {
     this._map = cmap;
   }
-
   get length() {
     return this._map.length;
   }
-
   forEach(callback) {
     for (const charCode in this._map) {
       callback(charCode, this._map[charCode].charCodeAt(0));
     }
   }
-
   has(i) {
     return this._map[i] !== undefined;
   }
-
   get(i) {
     return this._map[i];
   }
-
   charCodeOf(value) {
     const map = this._map;
-
     if (map.length <= 0x10000) {
       return map.indexOf(value);
     }
-
     for (const charCode in map) {
       if (map[charCode] === value) {
         return charCode | 0;
       }
     }
-
     return -1;
   }
-
   amend(map) {
     for (const charCode in map) {
       this._map[charCode] = map[charCode];
     }
   }
-
 }
-
 exports.ToUnicodeMap = ToUnicodeMap;
-
 class IdentityToUnicodeMap {
   constructor(firstChar, lastChar) {
     this.firstChar = firstChar;
     this.lastChar = lastChar;
   }
-
   get length() {
     return this.lastChar + 1 - this.firstChar;
   }
-
   forEach(callback) {
     for (let i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
       callback(i, i);
     }
   }
-
   has(i) {
     return this.firstChar <= i && i <= this.lastChar;
   }
-
   get(i) {
     if (this.firstChar <= i && i <= this.lastChar) {
       return String.fromCharCode(i);
     }
-
     return undefined;
   }
-
   charCodeOf(v) {
     return Number.isInteger(v) && v >= this.firstChar && v <= this.lastChar ? v : -1;
   }
-
   amend(map) {
     (0, _util.unreachable)("Should not call amend()");
   }
-
 }
-
 exports.IdentityToUnicodeMap = IdentityToUnicodeMap;

+ 7 - 87
lib/core/type1_font.js

@@ -25,66 +25,48 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.Type1Font = void 0;
-
 var _cff_parser = require("./cff_parser.js");
-
+var _util = require("../shared/util.js");
 var _fonts_utils = require("./fonts_utils.js");
-
 var _core_utils = require("./core_utils.js");
-
 var _stream = require("./stream.js");
-
 var _type1_parser = require("./type1_parser.js");
-
-var _util = require("../shared/util.js");
-
 function findBlock(streamBytes, signature, startIndex) {
   const streamBytesLength = streamBytes.length;
   const signatureLength = signature.length;
   const scanLength = streamBytesLength - signatureLength;
   let i = startIndex,
-      found = false;
-
+    found = false;
   while (i < scanLength) {
     let j = 0;
-
     while (j < signatureLength && streamBytes[i + j] === signature[j]) {
       j++;
     }
-
     if (j >= signatureLength) {
       i += j;
-
       while (i < streamBytesLength && (0, _core_utils.isWhiteSpace)(streamBytes[i])) {
         i++;
       }
-
       found = true;
       break;
     }
-
     i++;
   }
-
   return {
     found,
     length: i
   };
 }
-
 function getHeaderBlock(stream, suggestedLength) {
   const EEXEC_SIGNATURE = [0x65, 0x65, 0x78, 0x65, 0x63];
   const streamStartPos = stream.pos;
   let headerBytes, headerBytesLength, block;
-
   try {
     headerBytes = stream.getBytes(suggestedLength);
     headerBytesLength = headerBytes.length;
   } catch (ex) {}
-
   if (headerBytesLength === suggestedLength) {
     block = findBlock(headerBytes, EEXEC_SIGNATURE, suggestedLength - 2 * EEXEC_SIGNATURE.length);
-
     if (block.found && block.length === suggestedLength) {
       return {
         stream: new _stream.Stream(headerBytes),
@@ -92,52 +74,45 @@ function getHeaderBlock(stream, suggestedLength) {
       };
     }
   }
-
   (0, _util.warn)('Invalid "Length1" property in Type1 font -- trying to recover.');
   stream.pos = streamStartPos;
   const SCAN_BLOCK_LENGTH = 2048;
   let actualLength;
-
   while (true) {
     const scanBytes = stream.peekBytes(SCAN_BLOCK_LENGTH);
     block = findBlock(scanBytes, EEXEC_SIGNATURE, 0);
-
     if (block.length === 0) {
       break;
     }
-
     stream.pos += block.length;
-
     if (block.found) {
       actualLength = stream.pos - streamStartPos;
       break;
     }
   }
-
   stream.pos = streamStartPos;
-
   if (actualLength) {
     return {
       stream: new _stream.Stream(stream.getBytes(actualLength)),
       length: actualLength
     };
   }
-
   (0, _util.warn)('Unable to recover "Length1" property in Type1 font -- using as is.');
   return {
     stream: new _stream.Stream(stream.getBytes(suggestedLength)),
     length: suggestedLength
   };
 }
-
 function getEexecBlock(stream, suggestedLength) {
   const eexecBytes = stream.getBytes();
+  if (eexecBytes.length === 0) {
+    throw new _util.FormatError("getEexecBlock - no font program found.");
+  }
   return {
     stream: new _stream.Stream(eexecBytes),
     length: eexecBytes.length
   };
 }
-
 class Type1Font {
   constructor(name, file, properties) {
     const PFB_HEADER_SIZE = 6;
@@ -145,29 +120,23 @@ class Type1Font {
     let eexecBlockLength = properties.length2;
     let pfbHeader = file.peekBytes(PFB_HEADER_SIZE);
     const pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01;
-
     if (pfbHeaderPresent) {
       file.skip(PFB_HEADER_SIZE);
       headerBlockLength = pfbHeader[5] << 24 | pfbHeader[4] << 16 | pfbHeader[3] << 8 | pfbHeader[2];
     }
-
     const headerBlock = getHeaderBlock(file, headerBlockLength);
     const headerBlockParser = new _type1_parser.Type1Parser(headerBlock.stream, false, _fonts_utils.SEAC_ANALYSIS_ENABLED);
     headerBlockParser.extractFontHeader(properties);
-
     if (pfbHeaderPresent) {
       pfbHeader = file.getBytes(PFB_HEADER_SIZE);
       eexecBlockLength = pfbHeader[5] << 24 | pfbHeader[4] << 16 | pfbHeader[3] << 8 | pfbHeader[2];
     }
-
     const eexecBlock = getEexecBlock(file, eexecBlockLength);
     const eexecBlockParser = new _type1_parser.Type1Parser(eexecBlock.stream, true, _fonts_utils.SEAC_ANALYSIS_ENABLED);
     const data = eexecBlockParser.extractFontProgram(properties);
-
     for (const key in data.properties) {
       properties[key] = data.properties[key];
     }
-
     const charstrings = data.charstrings;
     const type2Charstrings = this.getType2Charstrings(charstrings);
     const subrs = this.getType2Subrs(data.subrs);
@@ -175,102 +144,75 @@ class Type1Font {
     this.data = this.wrap(name, type2Charstrings, this.charstrings, subrs, properties);
     this.seacs = this.getSeacs(data.charstrings);
   }
-
   get numGlyphs() {
     return this.charstrings.length + 1;
   }
-
   getCharset() {
     const charset = [".notdef"];
-
     for (const {
       glyphName
     } of this.charstrings) {
       charset.push(glyphName);
     }
-
     return charset;
   }
-
   getGlyphMapping(properties) {
     const charstrings = this.charstrings;
-
     if (properties.composite) {
       const charCodeToGlyphId = Object.create(null);
-
       for (let glyphId = 0, charstringsLen = charstrings.length; glyphId < charstringsLen; glyphId++) {
         const charCode = properties.cMap.charCodeOf(glyphId);
         charCodeToGlyphId[charCode] = glyphId + 1;
       }
-
       return charCodeToGlyphId;
     }
-
     const glyphNames = [".notdef"];
     let builtInEncoding, glyphId;
-
     for (glyphId = 0; glyphId < charstrings.length; glyphId++) {
       glyphNames.push(charstrings[glyphId].glyphName);
     }
-
     const encoding = properties.builtInEncoding;
-
     if (encoding) {
       builtInEncoding = Object.create(null);
-
       for (const charCode in encoding) {
         glyphId = glyphNames.indexOf(encoding[charCode]);
-
         if (glyphId >= 0) {
           builtInEncoding[charCode] = glyphId;
         }
       }
     }
-
     return (0, _fonts_utils.type1FontGlyphMapping)(properties, builtInEncoding, glyphNames);
   }
-
   hasGlyphId(id) {
     if (id < 0 || id >= this.numGlyphs) {
       return false;
     }
-
     if (id === 0) {
       return true;
     }
-
     const glyph = this.charstrings[id - 1];
     return glyph.charstring.length > 0;
   }
-
   getSeacs(charstrings) {
     const seacMap = [];
-
     for (let i = 0, ii = charstrings.length; i < ii; i++) {
       const charstring = charstrings[i];
-
       if (charstring.seac) {
         seacMap[i + 1] = charstring.seac;
       }
     }
-
     return seacMap;
   }
-
   getType2Charstrings(type1Charstrings) {
     const type2Charstrings = [];
-
-    for (let i = 0, ii = type1Charstrings.length; i < ii; i++) {
-      type2Charstrings.push(type1Charstrings[i].charstring);
+    for (const type1Charstring of type1Charstrings) {
+      type2Charstrings.push(type1Charstring.charstring);
     }
-
     return type2Charstrings;
   }
-
   getType2Subrs(type1Subrs) {
     let bias = 0;
     const count = type1Subrs.length;
-
     if (count < 1133) {
       bias = 107;
     } else if (count < 33769) {
@@ -278,21 +220,16 @@ class Type1Font {
     } else {
       bias = 32768;
     }
-
     const type2Subrs = [];
     let i;
-
     for (i = 0; i < bias; i++) {
       type2Subrs.push([0x0b]);
     }
-
     for (i = 0; i < count; i++) {
       type2Subrs.push(type1Subrs[i]);
     }
-
     return type2Subrs;
   }
-
   wrap(name, glyphs, charstrings, subrs, properties) {
     const cff = new _cff_parser.CFF();
     cff.header = new _cff_parser.CFFHeader(1, 0, 4, 4);
@@ -321,62 +258,45 @@ class Type1Font {
     const count = glyphs.length;
     const charsetArray = [".notdef"];
     let i, ii;
-
     for (i = 0; i < count; i++) {
       const glyphName = charstrings[i].glyphName;
-
       const index = _cff_parser.CFFStandardStrings.indexOf(glyphName);
-
       if (index === -1) {
         strings.add(glyphName);
       }
-
       charsetArray.push(glyphName);
     }
-
     cff.charset = new _cff_parser.CFFCharset(false, 0, charsetArray);
     const charStringsIndex = new _cff_parser.CFFIndex();
     charStringsIndex.add([0x8b, 0x0e]);
-
     for (i = 0; i < count; i++) {
       charStringsIndex.add(glyphs[i]);
     }
-
     cff.charStrings = charStringsIndex;
     const privateDict = new _cff_parser.CFFPrivateDict();
     privateDict.setByName("Subrs", null);
     const fields = ["BlueValues", "OtherBlues", "FamilyBlues", "FamilyOtherBlues", "StemSnapH", "StemSnapV", "BlueShift", "BlueFuzz", "BlueScale", "LanguageGroup", "ExpansionFactor", "ForceBold", "StdHW", "StdVW"];
-
     for (i = 0, ii = fields.length; i < ii; i++) {
       const field = fields[i];
-
       if (!(field in properties.privateData)) {
         continue;
       }
-
       const value = properties.privateData[field];
-
       if (Array.isArray(value)) {
         for (let j = value.length - 1; j > 0; j--) {
           value[j] -= value[j - 1];
         }
       }
-
       privateDict.setByName(field, value);
     }
-
     cff.topDict.privateDict = privateDict;
     const subrIndex = new _cff_parser.CFFIndex();
-
     for (i = 0, ii = subrs.length; i < ii; i++) {
       subrIndex.add(subrs[i]);
     }
-
     privateDict.subrsIndex = subrIndex;
     const compiler = new _cff_parser.CFFCompiler(cff);
     return compiler.compile();
   }
-
 }
-
 exports.Type1Font = Type1Font;

+ 6 - 155
lib/core/type1_parser.js

@@ -25,15 +25,10 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.Type1Parser = void 0;
-
 var _encodings = require("./encodings.js");
-
 var _core_utils = require("./core_utils.js");
-
 var _stream = require("./stream.js");
-
 var _util = require("../shared/util.js");
-
 const HINTING_ENABLED = false;
 const COMMAND_MAP = {
   hstem: [1],
@@ -52,7 +47,6 @@ const COMMAND_MAP = {
   vhcurveto: [30],
   hvcurveto: [31]
 };
-
 class Type1CharString {
   constructor() {
     this.width = 0;
@@ -61,99 +55,77 @@ class Type1CharString {
     this.output = [];
     this.stack = [];
   }
-
   convert(encoded, subrs, seacAnalysisEnabled) {
     const count = encoded.length;
     let error = false;
     let wx, sbx, subrNumber;
-
     for (let i = 0; i < count; i++) {
       let value = encoded[i];
-
       if (value < 32) {
         if (value === 12) {
           value = (value << 8) + encoded[++i];
         }
-
         switch (value) {
           case 1:
             if (!HINTING_ENABLED) {
               this.stack = [];
               break;
             }
-
             error = this.executeCommand(2, COMMAND_MAP.hstem);
             break;
-
           case 3:
             if (!HINTING_ENABLED) {
               this.stack = [];
               break;
             }
-
             error = this.executeCommand(2, COMMAND_MAP.vstem);
             break;
-
           case 4:
             if (this.flexing) {
               if (this.stack.length < 1) {
                 error = true;
                 break;
               }
-
               const dy = this.stack.pop();
               this.stack.push(0, dy);
               break;
             }
-
             error = this.executeCommand(1, COMMAND_MAP.vmoveto);
             break;
-
           case 5:
             error = this.executeCommand(2, COMMAND_MAP.rlineto);
             break;
-
           case 6:
             error = this.executeCommand(1, COMMAND_MAP.hlineto);
             break;
-
           case 7:
             error = this.executeCommand(1, COMMAND_MAP.vlineto);
             break;
-
           case 8:
             error = this.executeCommand(6, COMMAND_MAP.rrcurveto);
             break;
-
           case 9:
             this.stack = [];
             break;
-
           case 10:
             if (this.stack.length < 1) {
               error = true;
               break;
             }
-
             subrNumber = this.stack.pop();
-
             if (!subrs[subrNumber]) {
               error = true;
               break;
             }
-
             error = this.convert(subrs[subrNumber], subrs, seacAnalysisEnabled);
             break;
-
           case 11:
             return error;
-
           case 13:
             if (this.stack.length < 2) {
               error = true;
               break;
             }
-
             wx = this.stack.pop();
             sbx = this.stack.pop();
             this.lsb = sbx;
@@ -161,58 +133,45 @@ class Type1CharString {
             this.stack.push(wx, sbx);
             error = this.executeCommand(2, COMMAND_MAP.hmoveto);
             break;
-
           case 14:
             this.output.push(COMMAND_MAP.endchar[0]);
             break;
-
           case 21:
             if (this.flexing) {
               break;
             }
-
             error = this.executeCommand(2, COMMAND_MAP.rmoveto);
             break;
-
           case 22:
             if (this.flexing) {
               this.stack.push(0);
               break;
             }
-
             error = this.executeCommand(1, COMMAND_MAP.hmoveto);
             break;
-
           case 30:
             error = this.executeCommand(4, COMMAND_MAP.vhcurveto);
             break;
-
           case 31:
             error = this.executeCommand(4, COMMAND_MAP.hvcurveto);
             break;
-
           case (12 << 8) + 0:
             this.stack = [];
             break;
-
           case (12 << 8) + 1:
             if (!HINTING_ENABLED) {
               this.stack = [];
               break;
             }
-
             error = this.executeCommand(2, COMMAND_MAP.vstem);
             break;
-
           case (12 << 8) + 2:
             if (!HINTING_ENABLED) {
               this.stack = [];
               break;
             }
-
             error = this.executeCommand(2, COMMAND_MAP.hstem);
             break;
-
           case (12 << 8) + 6:
             if (seacAnalysisEnabled) {
               const asb = this.stack.at(-5);
@@ -222,15 +181,12 @@ class Type1CharString {
             } else {
               error = this.executeCommand(4, COMMAND_MAP.endchar);
             }
-
             break;
-
           case (12 << 8) + 7:
             if (this.stack.length < 4) {
               error = true;
               break;
             }
-
             this.stack.pop();
             wx = this.stack.pop();
             const sby = this.stack.pop();
@@ -240,27 +196,22 @@ class Type1CharString {
             this.stack.push(wx, sbx, sby);
             error = this.executeCommand(3, COMMAND_MAP.rmoveto);
             break;
-
           case (12 << 8) + 12:
             if (this.stack.length < 2) {
               error = true;
               break;
             }
-
             const num2 = this.stack.pop();
             const num1 = this.stack.pop();
             this.stack.push(num1 / num2);
             break;
-
           case (12 << 8) + 16:
             if (this.stack.length < 2) {
               error = true;
               break;
             }
-
             subrNumber = this.stack.pop();
             const numArgs = this.stack.pop();
-
             if (subrNumber === 0 && numArgs === 3) {
               const flexArgs = this.stack.splice(this.stack.length - 17, 17);
               this.stack.push(flexArgs[2] + flexArgs[0], flexArgs[3] + flexArgs[1], flexArgs[4], flexArgs[5], flexArgs[6], flexArgs[7], flexArgs[8], flexArgs[9], flexArgs[10], flexArgs[11], flexArgs[12], flexArgs[13], flexArgs[14]);
@@ -270,25 +221,19 @@ class Type1CharString {
             } else if (subrNumber === 1 && numArgs === 0) {
               this.flexing = true;
             }
-
             break;
-
           case (12 << 8) + 17:
             break;
-
           case (12 << 8) + 33:
             this.stack = [];
             break;
-
           default:
             (0, _util.warn)('Unknown type 1 charstring command of "' + value + '"');
             break;
         }
-
         if (error) {
           break;
         }
-
         continue;
       } else if (value <= 246) {
         value -= 139;
@@ -299,25 +244,18 @@ class Type1CharString {
       } else {
         value = (encoded[++i] & 0xff) << 24 | (encoded[++i] & 0xff) << 16 | (encoded[++i] & 0xff) << 8 | (encoded[++i] & 0xff) << 0;
       }
-
       this.stack.push(value);
     }
-
     return error;
   }
-
   executeCommand(howManyArgs, command, keepStack) {
     const stackLength = this.stack.length;
-
     if (howManyArgs > stackLength) {
       return true;
     }
-
     const start = stackLength - howManyArgs;
-
     for (let i = start; i < stackLength; i++) {
       let value = this.stack[i];
-
       if (Number.isInteger(value)) {
         this.output.push(28, value >> 8 & 0xff, value & 0xff);
       } else {
@@ -325,91 +263,70 @@ class Type1CharString {
         this.output.push(255, value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
       }
     }
-
     this.output.push(...command);
-
     if (keepStack) {
       this.stack.splice(start, howManyArgs);
     } else {
       this.stack.length = 0;
     }
-
     return false;
   }
-
 }
-
 const EEXEC_ENCRYPT_KEY = 55665;
 const CHAR_STRS_ENCRYPT_KEY = 4330;
-
 function isHexDigit(code) {
   return code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102;
 }
-
 function decrypt(data, key, discardNumber) {
   if (discardNumber >= data.length) {
     return new Uint8Array(0);
   }
-
   const c1 = 52845,
-        c2 = 22719;
+    c2 = 22719;
   let r = key | 0,
-      i,
-      j;
-
+    i,
+    j;
   for (i = 0; i < discardNumber; i++) {
     r = (data[i] + r) * c1 + c2 & (1 << 16) - 1;
   }
-
   const count = data.length - discardNumber;
   const decrypted = new Uint8Array(count);
-
   for (i = discardNumber, j = 0; j < count; i++, j++) {
     const value = data[i];
     decrypted[j] = value ^ r >> 8;
     r = (value + r) * c1 + c2 & (1 << 16) - 1;
   }
-
   return decrypted;
 }
-
 function decryptAscii(data, key, discardNumber) {
   const c1 = 52845,
-        c2 = 22719;
+    c2 = 22719;
   let r = key | 0;
   const count = data.length,
-        maybeLength = count >>> 1;
+    maybeLength = count >>> 1;
   const decrypted = new Uint8Array(maybeLength);
   let i, j;
-
   for (i = 0, j = 0; i < count; i++) {
     const digit1 = data[i];
-
     if (!isHexDigit(digit1)) {
       continue;
     }
-
     i++;
     let digit2;
-
     while (i < count && !isHexDigit(digit2 = data[i])) {
       i++;
     }
-
     if (i < count) {
       const value = parseInt(String.fromCharCode(digit1, digit2), 16);
       decrypted[j++] = value ^ r >> 8;
       r = (value + r) * c1 + c2 & (1 << 16) - 1;
     }
   }
-
   return decrypted.slice(discardNumber, j);
 }
-
 function isSpecial(c) {
   return c === 0x2f || c === 0x5b || c === 0x5d || c === 0x7b || c === 0x7d || c === 0x28 || c === 0x29;
 }
-
 class Type1Parser {
   constructor(stream, encrypted, seacAnalysisEnabled) {
     if (encrypted) {
@@ -417,62 +334,48 @@ class Type1Parser {
       const isBinary = !((isHexDigit(data[0]) || (0, _core_utils.isWhiteSpace)(data[0])) && isHexDigit(data[1]) && isHexDigit(data[2]) && isHexDigit(data[3]) && isHexDigit(data[4]) && isHexDigit(data[5]) && isHexDigit(data[6]) && isHexDigit(data[7]));
       stream = new _stream.Stream(isBinary ? decrypt(data, EEXEC_ENCRYPT_KEY, 4) : decryptAscii(data, EEXEC_ENCRYPT_KEY, 4));
     }
-
     this.seacAnalysisEnabled = !!seacAnalysisEnabled;
     this.stream = stream;
     this.nextChar();
   }
-
   readNumberArray() {
     this.getToken();
     const array = [];
-
     while (true) {
       const token = this.getToken();
-
       if (token === null || token === "]" || token === "}") {
         break;
       }
-
       array.push(parseFloat(token || 0));
     }
-
     return array;
   }
-
   readNumber() {
     const token = this.getToken();
     return parseFloat(token || 0);
   }
-
   readInt() {
     const token = this.getToken();
     return parseInt(token || 0, 10) | 0;
   }
-
   readBoolean() {
     const token = this.getToken();
     return token === "true" ? 1 : 0;
   }
-
   nextChar() {
     return this.currentChar = this.stream.getByte();
   }
-
   prevChar() {
     this.stream.skip(-2);
     return this.currentChar = this.stream.getByte();
   }
-
   getToken() {
     let comment = false;
     let ch = this.currentChar;
-
     while (true) {
       if (ch === -1) {
         return null;
       }
-
       if (comment) {
         if (ch === 0x0a || ch === 0x0d) {
           comment = false;
@@ -482,37 +385,29 @@ class Type1Parser {
       } else if (!(0, _core_utils.isWhiteSpace)(ch)) {
         break;
       }
-
       ch = this.nextChar();
     }
-
     if (isSpecial(ch)) {
       this.nextChar();
       return String.fromCharCode(ch);
     }
-
     let token = "";
-
     do {
       token += String.fromCharCode(ch);
       ch = this.nextChar();
     } while (ch >= 0 && !(0, _core_utils.isWhiteSpace)(ch) && !isSpecial(ch));
-
     return token;
   }
-
   readCharStrings(bytes, lenIV) {
     if (lenIV === -1) {
       return bytes;
     }
-
     return decrypt(bytes, CHAR_STRS_ENCRYPT_KEY, lenIV);
   }
-
   extractFontProgram(properties) {
     const stream = this.stream;
     const subrs = [],
-          charstrings = [];
+      charstrings = [];
     const privateData = Object.create(null);
     privateData.lenIV = 4;
     const program = {
@@ -523,32 +418,25 @@ class Type1Parser {
       }
     };
     let token, length, data, lenIV;
-
     while ((token = this.getToken()) !== null) {
       if (token !== "/") {
         continue;
       }
-
       token = this.getToken();
-
       switch (token) {
         case "CharStrings":
           this.getToken();
           this.getToken();
           this.getToken();
           this.getToken();
-
           while (true) {
             token = this.getToken();
-
             if (token === null || token === "end") {
               break;
             }
-
             if (token !== "/") {
               continue;
             }
-
             const glyph = this.getToken();
             length = this.readInt();
             this.getToken();
@@ -557,25 +445,20 @@ class Type1Parser {
             const encoded = this.readCharStrings(data, lenIV);
             this.nextChar();
             token = this.getToken();
-
             if (token === "noaccess") {
               this.getToken();
             } else if (token === "/") {
               this.prevChar();
             }
-
             charstrings.push({
               glyph,
               encoded
             });
           }
-
           break;
-
         case "Subrs":
           this.readInt();
           this.getToken();
-
           while (this.getToken() === "dup") {
             const index = this.readInt();
             length = this.readInt();
@@ -585,38 +468,29 @@ class Type1Parser {
             const encoded = this.readCharStrings(data, lenIV);
             this.nextChar();
             token = this.getToken();
-
             if (token === "noaccess") {
               this.getToken();
             }
-
             subrs[index] = encoded;
           }
-
           break;
-
         case "BlueValues":
         case "OtherBlues":
         case "FamilyBlues":
         case "FamilyOtherBlues":
           const blueArray = this.readNumberArray();
-
           if (blueArray.length > 0 && blueArray.length % 2 === 0 && HINTING_ENABLED) {
             program.properties.privateData[token] = blueArray;
           }
-
           break;
-
         case "StemSnapH":
         case "StemSnapV":
           program.properties.privateData[token] = this.readNumberArray();
           break;
-
         case "StdHW":
         case "StdVW":
           program.properties.privateData[token] = this.readNumberArray()[0];
           break;
-
         case "BlueShift":
         case "lenIV":
         case "BlueFuzz":
@@ -625,13 +499,11 @@ class Type1Parser {
         case "ExpansionFactor":
           program.properties.privateData[token] = this.readNumber();
           break;
-
         case "ForceBold":
           program.properties.privateData[token] = this.readBoolean();
           break;
       }
     }
-
     for (const {
       encoded,
       glyph
@@ -639,11 +511,9 @@ class Type1Parser {
       const charString = new Type1CharString();
       const error = charString.convert(encoded, subrs, this.seacAnalysisEnabled);
       let output = charString.output;
-
       if (error) {
         output = [14];
       }
-
       const charStringObject = {
         glyphName: glyph,
         charstring: output,
@@ -651,67 +521,52 @@ class Type1Parser {
         lsb: charString.lsb,
         seac: charString.seac
       };
-
       if (glyph === ".notdef") {
         program.charstrings.unshift(charStringObject);
       } else {
         program.charstrings.push(charStringObject);
       }
-
       if (properties.builtInEncoding) {
         const index = properties.builtInEncoding.indexOf(glyph);
-
         if (index > -1 && properties.widths[index] === undefined && index >= properties.firstChar && index <= properties.lastChar) {
           properties.widths[index] = charString.width;
         }
       }
     }
-
     return program;
   }
-
   extractFontHeader(properties) {
     let token;
-
     while ((token = this.getToken()) !== null) {
       if (token !== "/") {
         continue;
       }
-
       token = this.getToken();
-
       switch (token) {
         case "FontMatrix":
           const matrix = this.readNumberArray();
           properties.fontMatrix = matrix;
           break;
-
         case "Encoding":
           const encodingArg = this.getToken();
           let encoding;
-
           if (!/^\d+$/.test(encodingArg)) {
             encoding = (0, _encodings.getEncoding)(encodingArg);
           } else {
             encoding = [];
             const size = parseInt(encodingArg, 10) | 0;
             this.getToken();
-
             for (let j = 0; j < size; j++) {
               token = this.getToken();
-
               while (token !== "dup" && token !== "def") {
                 token = this.getToken();
-
                 if (token === null) {
                   return;
                 }
               }
-
               if (token === "def") {
                 break;
               }
-
               const index = this.readInt();
               this.getToken();
               const glyph = this.getToken();
@@ -719,10 +574,8 @@ class Type1Parser {
               this.getToken();
             }
           }
-
           properties.builtInEncoding = encoding;
           break;
-
         case "FontBBox":
           const fontBBox = this.readNumberArray();
           properties.ascent = Math.max(fontBBox[3], fontBBox[1]);
@@ -732,7 +585,5 @@ class Type1Parser {
       }
     }
   }
-
 }
-
 exports.Type1Parser = Type1Parser;

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 22
lib/core/unicode.js


+ 29 - 133
lib/core/worker.js

@@ -25,54 +25,37 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.WorkerTask = exports.WorkerMessageHandler = void 0;
-
 var _util = require("../shared/util.js");
-
 var _primitives = require("./primitives.js");
-
 var _core_utils = require("./core_utils.js");
-
 var _pdf_manager = require("./pdf_manager.js");
-
 var _cleanup_helper = require("./cleanup_helper.js");
-
 var _writer = require("./writer.js");
-
 var _is_node = require("../shared/is_node.js");
-
 var _message_handler = require("../shared/message_handler.js");
-
 var _worker_stream = require("./worker_stream.js");
-
 class WorkerTask {
   constructor(name) {
     this.name = name;
     this.terminated = false;
     this._capability = (0, _util.createPromiseCapability)();
   }
-
   get finished() {
     return this._capability.promise;
   }
-
   finish() {
     this._capability.resolve();
   }
-
   terminate() {
     this.terminated = true;
   }
-
   ensureNotTerminated() {
     if (this.terminated) {
       throw new Error("Worker task was terminated");
     }
   }
-
 }
-
 exports.WorkerTask = WorkerTask;
-
 class WorkerMessageHandler {
   static setup(handler, port) {
     let testMessageProcessed = false;
@@ -80,7 +63,6 @@ class WorkerMessageHandler {
       if (testMessageProcessed) {
         return;
       }
-
       testMessageProcessed = true;
       handler.send("test", data instanceof Uint8Array);
     });
@@ -91,61 +73,49 @@ class WorkerMessageHandler {
       return WorkerMessageHandler.createDocumentHandler(data, port);
     });
   }
-
   static createDocumentHandler(docParams, port) {
     let pdfManager;
     let terminated = false;
     let cancelXHRs = null;
     const WorkerTasks = [];
     const verbosity = (0, _util.getVerbosityLevel)();
-    const apiVersion = docParams.apiVersion;
-    const workerVersion = '2.16.105';
-
+    const {
+      docId,
+      apiVersion
+    } = docParams;
+    const workerVersion = '3.0.279';
     if (apiVersion !== workerVersion) {
       throw new Error(`The API version "${apiVersion}" does not match ` + `the Worker version "${workerVersion}".`);
     }
-
     const enumerableProperties = [];
-
     for (const property in []) {
       enumerableProperties.push(property);
     }
-
     if (enumerableProperties.length) {
       throw new Error("The `Array.prototype` contains unexpected enumerable properties: " + enumerableProperties.join(", ") + "; thus breaking e.g. `for...in` iteration of `Array`s.");
     }
-
     if (typeof ReadableStream === "undefined") {
       const partialMsg = "The browser/environment lacks native support for critical " + "functionality used by the PDF.js library (e.g. `ReadableStream`); ";
-
       if (_is_node.isNodeJS) {
         throw new Error(partialMsg + "please use a `legacy`-build instead.");
       }
-
       throw new Error(partialMsg + "please update to a supported browser.");
     }
-
-    const docId = docParams.docId;
-    const docBaseUrl = docParams.docBaseUrl;
-    const workerHandlerName = docParams.docId + "_worker";
+    const workerHandlerName = docId + "_worker";
     let handler = new _message_handler.MessageHandler(workerHandlerName, docId, port);
-
     function ensureNotTerminated() {
       if (terminated) {
         throw new Error("Worker was terminated");
       }
     }
-
     function startWorkerTask(task) {
       WorkerTasks.push(task);
     }
-
     function finishWorkerTask(task) {
       task.finish();
       const i = WorkerTasks.indexOf(task);
       WorkerTasks.splice(i, 1);
     }
-
     async function loadDocument(recoveryMode) {
       await pdfManager.ensureDoc("checkHeader");
       await pdfManager.ensureDoc("parseStartXRef");
@@ -153,13 +123,11 @@ class WorkerMessageHandler {
       await pdfManager.ensureDoc("checkFirstPage", [recoveryMode]);
       await pdfManager.ensureDoc("checkLastPage", [recoveryMode]);
       const isPureXfa = await pdfManager.ensureDoc("isPureXfa");
-
       if (isPureXfa) {
         const task = new WorkerTask("loadXfaFonts");
         startWorkerTask(task);
         await Promise.all([pdfManager.loadXfaFonts(handler, task).catch(reason => {}).then(() => finishWorkerTask(task)), pdfManager.loadXfaImages()]);
       }
-
       const [numPages, fingerprints] = await Promise.all([pdfManager.ensureDoc("numPages"), pdfManager.ensureDoc("fingerprints")]);
       const htmlForXfa = isPureXfa ? await pdfManager.ensureDoc("htmlForXfa") : null;
       return {
@@ -168,52 +136,51 @@ class WorkerMessageHandler {
         htmlForXfa
       };
     }
-
-    function getPdfManager(data, evaluatorOptions, enableXfa) {
+    function getPdfManager({
+      data,
+      password,
+      disableAutoFetch,
+      rangeChunkSize,
+      length,
+      docBaseUrl,
+      enableXfa,
+      evaluatorOptions
+    }) {
       const pdfManagerCapability = (0, _util.createPromiseCapability)();
       let newPdfManager;
-      const source = data.source;
-
-      if (source.data) {
+      if (data) {
         try {
-          newPdfManager = new _pdf_manager.LocalPdfManager(docId, source.data, source.password, handler, evaluatorOptions, enableXfa, docBaseUrl);
+          newPdfManager = new _pdf_manager.LocalPdfManager(docId, data, password, handler, evaluatorOptions, enableXfa, docBaseUrl);
           pdfManagerCapability.resolve(newPdfManager);
         } catch (ex) {
           pdfManagerCapability.reject(ex);
         }
-
         return pdfManagerCapability.promise;
       }
-
       let pdfStream,
-          cachedChunks = [];
-
+        cachedChunks = [];
       try {
         pdfStream = new _worker_stream.PDFWorkerStream(handler);
       } catch (ex) {
         pdfManagerCapability.reject(ex);
         return pdfManagerCapability.promise;
       }
-
       const fullRequest = pdfStream.getFullReader();
       fullRequest.headersReady.then(function () {
         if (!fullRequest.isRangeSupported) {
           return;
         }
-
-        const disableAutoFetch = source.disableAutoFetch || fullRequest.isStreamingSupported;
+        disableAutoFetch = disableAutoFetch || fullRequest.isStreamingSupported;
         newPdfManager = new _pdf_manager.NetworkPdfManager(docId, pdfStream, {
           msgHandler: handler,
-          password: source.password,
+          password,
           length: fullRequest.contentLength,
           disableAutoFetch,
-          rangeChunkSize: source.rangeChunkSize
+          rangeChunkSize
         }, evaluatorOptions, enableXfa, docBaseUrl);
-
         for (const chunk of cachedChunks) {
           newPdfManager.sendProgressiveData(chunk);
         }
-
         cachedChunks = [];
         pdfManagerCapability.resolve(newPdfManager);
         cancelXHRs = null;
@@ -222,24 +189,19 @@ class WorkerMessageHandler {
         cancelXHRs = null;
       });
       let loaded = 0;
-
       const flushChunks = function () {
         const pdfFile = (0, _util.arraysToBytes)(cachedChunks);
-
-        if (source.length && pdfFile.length !== source.length) {
+        if (length && pdfFile.length !== length) {
           (0, _util.warn)("reported HTTP length is different from actual");
         }
-
         try {
-          newPdfManager = new _pdf_manager.LocalPdfManager(docId, pdfFile, source.password, handler, evaluatorOptions, enableXfa, docBaseUrl);
+          newPdfManager = new _pdf_manager.LocalPdfManager(docId, pdfFile, password, handler, evaluatorOptions, enableXfa, docBaseUrl);
           pdfManagerCapability.resolve(newPdfManager);
         } catch (ex) {
           pdfManagerCapability.reject(ex);
         }
-
         cachedChunks = [];
       };
-
       const readPromise = new Promise(function (resolve, reject) {
         const readChunk = function ({
           value,
@@ -247,51 +209,41 @@ class WorkerMessageHandler {
         }) {
           try {
             ensureNotTerminated();
-
             if (done) {
               if (!newPdfManager) {
                 flushChunks();
               }
-
               cancelXHRs = null;
               return;
             }
-
             loaded += (0, _util.arrayByteLength)(value);
-
             if (!fullRequest.isStreamingSupported) {
               handler.send("DocProgress", {
                 loaded,
                 total: Math.max(loaded, fullRequest.contentLength || 0)
               });
             }
-
             if (newPdfManager) {
               newPdfManager.sendProgressiveData(value);
             } else {
               cachedChunks.push(value);
             }
-
             fullRequest.read().then(readChunk, reject);
           } catch (e) {
             reject(e);
           }
         };
-
         fullRequest.read().then(readChunk, reject);
       });
       readPromise.catch(function (e) {
         pdfManagerCapability.reject(e);
         cancelXHRs = null;
       });
-
       cancelXHRs = function (reason) {
         pdfStream.cancelAllRequests(reason);
       };
-
       return pdfManagerCapability.promise;
     }
-
     function setupDoc(data) {
       function onSuccess(doc) {
         ensureNotTerminated();
@@ -299,10 +251,8 @@ class WorkerMessageHandler {
           pdfInfo: doc
         });
       }
-
       function onFailure(ex) {
         ensureNotTerminated();
-
         if (ex instanceof _util.PasswordException) {
           const task = new WorkerTask(`PasswordException: response ${ex.code}`);
           startWorkerTask(task);
@@ -322,51 +272,34 @@ class WorkerMessageHandler {
           handler.send("DocException", new _util.UnknownErrorException(ex.message, ex.toString()));
         }
       }
-
       function pdfManagerReady() {
         ensureNotTerminated();
         loadDocument(false).then(onSuccess, function (reason) {
           ensureNotTerminated();
-
           if (!(reason instanceof _core_utils.XRefParseException)) {
             onFailure(reason);
             return;
           }
-
-          pdfManager.requestLoadedStream();
-          pdfManager.onLoadedStream().then(function () {
+          pdfManager.requestLoadedStream().then(function () {
             ensureNotTerminated();
             loadDocument(true).then(onSuccess, onFailure);
           });
         });
       }
-
       ensureNotTerminated();
-      const evaluatorOptions = {
-        maxImageSize: data.maxImageSize,
-        disableFontFace: data.disableFontFace,
-        ignoreErrors: data.ignoreErrors,
-        isEvalSupported: data.isEvalSupported,
-        fontExtraProperties: data.fontExtraProperties,
-        useSystemFonts: data.useSystemFonts,
-        cMapUrl: data.cMapUrl,
-        standardFontDataUrl: data.standardFontDataUrl
-      };
-      getPdfManager(data, evaluatorOptions, data.enableXfa).then(function (newPdfManager) {
+      getPdfManager(data).then(function (newPdfManager) {
         if (terminated) {
           newPdfManager.terminate(new _util.AbortException("Worker was terminated."));
           throw new Error("Worker was terminated");
         }
-
         pdfManager = newPdfManager;
-        pdfManager.onLoadedStream().then(function (stream) {
+        pdfManager.requestLoadedStream(true).then(stream => {
           handler.send("DataLoaded", {
             length: stream.bytes.byteLength
           });
         });
       }).then(pdfManagerReady, onFailure);
     }
-
     handler.on("GetPage", function wphSetupGetPage(data) {
       return pdfManager.getPage(data.pageIndex).then(function (page) {
         return Promise.all([pdfManager.ensure(page, "rotate"), pdfManager.ensure(page, "ref"), pdfManager.ensure(page, "userUnit"), pdfManager.ensure(page, "view")]).then(function ([rotate, ref, userUnit, view]) {
@@ -381,7 +314,6 @@ class WorkerMessageHandler {
     });
     handler.on("GetPageIndex", function wphSetupGetPageIndex(data) {
       const pageRef = _primitives.Ref.get(data.num, data.gen);
-
       return pdfManager.ensureCatalog("getPageIndex", [pageRef]);
     });
     handler.on("GetDestinations", function wphSetupGetDestinations(data) {
@@ -437,8 +369,7 @@ class WorkerMessageHandler {
       return pdfManager.ensureCatalog("markInfo");
     });
     handler.on("GetData", function wphSetupGetData(data) {
-      pdfManager.requestLoadedStream();
-      return pdfManager.onLoadedStream().then(function (stream) {
+      return pdfManager.requestLoadedStream().then(function (stream) {
         return stream.bytes;
       });
     });
@@ -472,10 +403,8 @@ class WorkerMessageHandler {
       annotationStorage,
       filename
     }) {
-      pdfManager.requestLoadedStream();
+      const promises = [pdfManager.requestLoadedStream(), pdfManager.ensureCatalog("acroForm"), pdfManager.ensureCatalog("acroFormRef"), pdfManager.ensureDoc("xref"), pdfManager.ensureDoc("startXRef")];
       const newAnnotationsByPage = !isPureXfa ? (0, _core_utils.getNewAnnotationsMap)(annotationStorage) : null;
-      const promises = [pdfManager.onLoadedStream(), pdfManager.ensureCatalog("acroForm"), pdfManager.ensureCatalog("acroFormRef"), pdfManager.ensureDoc("xref"), pdfManager.ensureDoc("startXRef")];
-
       if (newAnnotationsByPage) {
         for (const [pageIndex, annotations] of newAnnotationsByPage) {
           promises.push(pdfManager.getPage(pageIndex).then(page => {
@@ -486,7 +415,6 @@ class WorkerMessageHandler {
           }));
         }
       }
-
       if (isPureXfa) {
         promises.push(pdfManager.serializeXfaData(annotationStorage));
       } else {
@@ -499,29 +427,23 @@ class WorkerMessageHandler {
           }));
         }
       }
-
       return Promise.all(promises).then(function ([stream, acroForm, acroFormRef, xref, startXRef, ...refs]) {
         let newRefs = [];
         let xfaData = null;
-
         if (isPureXfa) {
           xfaData = refs[0];
-
           if (!xfaData) {
             return stream.bytes;
           }
         } else {
           newRefs = refs.flat(2);
-
           if (newRefs.length === 0) {
             return stream.bytes;
           }
         }
-
         const xfa = acroForm instanceof _primitives.Dict && acroForm.get("XFA") || null;
         let xfaDatasetsRef = null;
         let hasXfaDatasetsEntry = false;
-
         if (Array.isArray(xfa)) {
           for (let i = 0, ii = xfa.length; i < ii; i += 2) {
             if (xfa[i] === "datasets") {
@@ -530,7 +452,6 @@ class WorkerMessageHandler {
               hasXfaDatasetsEntry = true;
             }
           }
-
           if (xfaDatasetsRef === null) {
             xfaDatasetsRef = xref.getNewRef();
           }
@@ -538,13 +459,10 @@ class WorkerMessageHandler {
           acroFormRef = null;
           (0, _util.warn)("Unsupported XFA type.");
         }
-
         let newXrefInfo = Object.create(null);
-
         if (xref.trailer) {
           const infoObj = Object.create(null);
           const xrefInfo = xref.trailer.get("Info") || null;
-
           if (xrefInfo instanceof _primitives.Dict) {
             xrefInfo.forEach((key, value) => {
               if (typeof value === "string") {
@@ -552,7 +470,6 @@ class WorkerMessageHandler {
               }
             });
           }
-
           newXrefInfo = {
             rootRef: xref.trailer.getRaw("Root") || null,
             encryptRef: xref.trailer.getRaw("Encrypt") || null,
@@ -564,7 +481,6 @@ class WorkerMessageHandler {
             filename
           };
         }
-
         xref.resetNewRef();
         return (0, _writer.incrementalUpdate)({
           originalData: stream.bytes,
@@ -595,22 +511,15 @@ class WorkerMessageHandler {
           annotationStorage: data.annotationStorage
         }).then(function (operatorListInfo) {
           finishWorkerTask(task);
-
           if (start) {
             (0, _util.info)(`page=${pageIndex + 1} - getOperatorList: time=` + `${Date.now() - start}ms, len=${operatorListInfo.length}`);
           }
-
           sink.close();
         }, function (reason) {
           finishWorkerTask(task);
-
           if (task.terminated) {
             return;
           }
-
-          handler.send("UnsupportedFeature", {
-            featureId: _util.UNSUPPORTED_FEATURES.errorOperatorList
-          });
           sink.error(reason);
         });
       });
@@ -629,19 +538,15 @@ class WorkerMessageHandler {
           combineTextItems: data.combineTextItems
         }).then(function () {
           finishWorkerTask(task);
-
           if (start) {
             (0, _util.info)(`page=${pageIndex + 1} - getTextContent: time=` + `${Date.now() - start}ms`);
           }
-
           sink.close();
         }, function (reason) {
           finishWorkerTask(task);
-
           if (task.terminated) {
             return;
           }
-
           sink.error(reason);
         });
       });
@@ -660,7 +565,6 @@ class WorkerMessageHandler {
     handler.on("Terminate", function wphTerminate(data) {
       terminated = true;
       const waitOn = [];
-
       if (pdfManager) {
         pdfManager.terminate(new _util.AbortException("Worker was terminated."));
         const cleanupPromise = pdfManager.cleanup();
@@ -669,16 +573,13 @@ class WorkerMessageHandler {
       } else {
         (0, _cleanup_helper.clearGlobalCaches)();
       }
-
       if (cancelXHRs) {
         cancelXHRs(new _util.AbortException("Worker was terminated."));
       }
-
       for (const task of WorkerTasks) {
         waitOn.push(task.finished);
         task.terminate();
       }
-
       return Promise.all(waitOn).then(function () {
         handler.destroy();
         handler = null;
@@ -690,21 +591,16 @@ class WorkerMessageHandler {
     });
     return workerHandlerName;
   }
-
   static initializeFromPort(port) {
     const handler = new _message_handler.MessageHandler("worker", "main", port);
     WorkerMessageHandler.setup(handler, port);
     handler.send("ready", null);
   }
-
 }
-
 exports.WorkerMessageHandler = WorkerMessageHandler;
-
 function isMessagePort(maybePort) {
   return typeof maybePort.postMessage === "function" && "onmessage" in maybePort;
 }
-
 if (typeof window === "undefined" && !_is_node.isNodeJS && typeof self !== "undefined" && isMessagePort(self)) {
   WorkerMessageHandler.initializeFromPort(self);
 }

+ 0 - 31
lib/core/worker_stream.js

@@ -25,9 +25,7 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.PDFWorkerStream = void 0;
-
 var _util = require("../shared/util.js");
-
 class PDFWorkerStream {
   constructor(msgHandler) {
     this._msgHandler = msgHandler;
@@ -35,35 +33,26 @@ class PDFWorkerStream {
     this._fullRequestReader = null;
     this._rangeRequestReaders = [];
   }
-
   getFullReader() {
     (0, _util.assert)(!this._fullRequestReader, "PDFWorkerStream.getFullReader can only be called once.");
     this._fullRequestReader = new PDFWorkerStreamReader(this._msgHandler);
     return this._fullRequestReader;
   }
-
   getRangeReader(begin, end) {
     const reader = new PDFWorkerStreamRangeReader(begin, end, this._msgHandler);
-
     this._rangeRequestReaders.push(reader);
-
     return reader;
   }
-
   cancelAllRequests(reason) {
     if (this._fullRequestReader) {
       this._fullRequestReader.cancel(reason);
     }
-
     for (const reader of this._rangeRequestReaders.slice(0)) {
       reader.cancel(reason);
     }
   }
-
 }
-
 exports.PDFWorkerStream = PDFWorkerStream;
-
 class PDFWorkerStreamReader {
   constructor(msgHandler) {
     this._msgHandler = msgHandler;
@@ -71,9 +60,7 @@ class PDFWorkerStreamReader {
     this._contentLength = null;
     this._isRangeSupported = false;
     this._isStreamingSupported = false;
-
     const readableStream = this._msgHandler.sendWithStream("GetReader");
-
     this._reader = readableStream.getReader();
     this._headersReady = this._msgHandler.sendWithPromise("ReaderHeadersReady").then(data => {
       this._isStreamingSupported = data.isStreamingSupported;
@@ -81,86 +68,68 @@ class PDFWorkerStreamReader {
       this._contentLength = data.contentLength;
     });
   }
-
   get headersReady() {
     return this._headersReady;
   }
-
   get contentLength() {
     return this._contentLength;
   }
-
   get isStreamingSupported() {
     return this._isStreamingSupported;
   }
-
   get isRangeSupported() {
     return this._isRangeSupported;
   }
-
   async read() {
     const {
       value,
       done
     } = await this._reader.read();
-
     if (done) {
       return {
         value: undefined,
         done: true
       };
     }
-
     return {
       value: value.buffer,
       done: false
     };
   }
-
   cancel(reason) {
     this._reader.cancel(reason);
   }
-
 }
-
 class PDFWorkerStreamRangeReader {
   constructor(begin, end, msgHandler) {
     this._msgHandler = msgHandler;
     this.onProgress = null;
-
     const readableStream = this._msgHandler.sendWithStream("GetRangeReader", {
       begin,
       end
     });
-
     this._reader = readableStream.getReader();
   }
-
   get isStreamingSupported() {
     return false;
   }
-
   async read() {
     const {
       value,
       done
     } = await this._reader.read();
-
     if (done) {
       return {
         value: undefined,
         done: true
       };
     }
-
     return {
       value: value.buffer,
       done: false
     };
   }
-
   cancel(reason) {
     this._reader.cancel(reason);
   }
-
 }

+ 0 - 60
lib/core/writer.js

@@ -27,71 +27,51 @@ Object.defineProperty(exports, "__esModule", {
 exports.incrementalUpdate = incrementalUpdate;
 exports.writeDict = writeDict;
 exports.writeObject = writeObject;
-
 var _util = require("../shared/util.js");
-
 var _primitives = require("./primitives.js");
-
 var _core_utils = require("./core_utils.js");
-
 var _xml_parser = require("./xml_parser.js");
-
 var _base_stream = require("./base_stream.js");
-
 var _crypto = require("./crypto.js");
-
 function writeObject(ref, obj, buffer, transform) {
   buffer.push(`${ref.num} ${ref.gen} obj\n`);
-
   if (obj instanceof _primitives.Dict) {
     writeDict(obj, buffer, transform);
   } else if (obj instanceof _base_stream.BaseStream) {
     writeStream(obj, buffer, transform);
   }
-
   buffer.push("\nendobj\n");
 }
-
 function writeDict(dict, buffer, transform) {
   buffer.push("<<");
-
   for (const key of dict.getKeys()) {
     buffer.push(` /${(0, _core_utils.escapePDFName)(key)} `);
     writeValue(dict.getRaw(key), buffer, transform);
   }
-
   buffer.push(">>");
 }
-
 function writeStream(stream, buffer, transform) {
   writeDict(stream.dict, buffer, transform);
   buffer.push(" stream\n");
   let string = stream.getString();
-
   if (transform !== null) {
     string = transform.encryptString(string);
   }
-
   buffer.push(string, "\nendstream\n");
 }
-
 function writeArray(array, buffer, transform) {
   buffer.push("[");
   let first = true;
-
   for (const val of array) {
     if (!first) {
       buffer.push(" ");
     } else {
       first = false;
     }
-
     writeValue(val, buffer, transform);
   }
-
   buffer.push("]");
 }
-
 function writeValue(value, buffer, transform) {
   if (value instanceof _primitives.Name) {
     buffer.push(`/${(0, _core_utils.escapePDFName)(value.name)}`);
@@ -103,7 +83,6 @@ function writeValue(value, buffer, transform) {
     if (transform !== null) {
       value = transform.encryptString(value);
     }
-
     buffer.push(`(${(0, _util.escapeString)(value)})`);
   } else if (typeof value === "number") {
     buffer.push((0, _core_utils.numberToString)(value));
@@ -119,67 +98,53 @@ function writeValue(value, buffer, transform) {
     (0, _util.warn)(`Unhandled value in writer: ${typeof value}, please file a bug.`);
   }
 }
-
 function writeInt(number, size, offset, buffer) {
   for (let i = size + offset - 1; i > offset - 1; i--) {
     buffer[i] = number & 0xff;
     number >>= 8;
   }
-
   return offset + size;
 }
-
 function writeString(string, offset, buffer) {
   for (let i = 0, len = string.length; i < len; i++) {
     buffer[offset + i] = string.charCodeAt(i) & 0xff;
   }
 }
-
 function computeMD5(filesize, xrefInfo) {
   const time = Math.floor(Date.now() / 1000);
   const filename = xrefInfo.filename || "";
   const md5Buffer = [time.toString(), filename, filesize.toString()];
   let md5BufferLen = md5Buffer.reduce((a, str) => a + str.length, 0);
-
   for (const value of Object.values(xrefInfo.info)) {
     md5Buffer.push(value);
     md5BufferLen += value.length;
   }
-
   const array = new Uint8Array(md5BufferLen);
   let offset = 0;
-
   for (const str of md5Buffer) {
     writeString(str, offset, array);
     offset += str.length;
   }
-
   return (0, _util.bytesToString)((0, _crypto.calculateMD5)(array));
 }
-
 function writeXFADataForAcroform(str, newRefs) {
   const xml = new _xml_parser.SimpleXMLParser({
     hasAttributes: true
   }).parseFromString(str);
-
   for (const {
     xfa
   } of newRefs) {
     if (!xfa) {
       continue;
     }
-
     const {
       path,
       value
     } = xfa;
-
     if (!path) {
       continue;
     }
-
     const node = xml.documentElement.searchNode((0, _core_utils.parseXFAPath)(path), 0);
-
     if (node) {
       if (Array.isArray(value)) {
         node.childNodes = value.map(val => new _xml_parser.SimpleDOMNode("value", val));
@@ -190,12 +155,10 @@ function writeXFADataForAcroform(str, newRefs) {
       (0, _util.warn)(`Node not found for path: ${path}`);
     }
   }
-
   const buffer = [];
   xml.documentElement.dump(buffer);
   return buffer.join("");
 }
-
 function updateXFA({
   xfaData,
   xfaDatasetsRef,
@@ -209,13 +172,11 @@ function updateXFA({
   if (xref === null) {
     return;
   }
-
   if (!hasXfaDatasetsEntry) {
     if (!acroFormRef) {
       (0, _util.warn)("XFA - Cannot save it");
       return;
     }
-
     const oldXfa = acroForm.get("XFA");
     const newXfa = oldXfa.slice();
     newXfa.splice(2, 0, "datasets");
@@ -223,11 +184,9 @@ function updateXFA({
     acroForm.set("XFA", newXfa);
     const encrypt = xref.encrypt;
     let transform = null;
-
     if (encrypt) {
       transform = encrypt.createCipherTransform(acroFormRef.num, acroFormRef.gen);
     }
-
     const buffer = [`${acroFormRef.num} ${acroFormRef.gen} obj\n`];
     writeDict(acroForm, buffer, transform);
     buffer.push("\n");
@@ -237,26 +196,21 @@ function updateXFA({
       data: buffer.join("")
     });
   }
-
   if (xfaData === null) {
     const datasets = xref.fetchIfRef(xfaDatasetsRef);
     xfaData = writeXFADataForAcroform(datasets.getString(), newRefs);
   }
-
   const encrypt = xref.encrypt;
-
   if (encrypt) {
     const transform = encrypt.createCipherTransform(xfaDatasetsRef.num, xfaDatasetsRef.gen);
     xfaData = transform.encryptString(xfaData);
   }
-
   const data = `${xfaDatasetsRef.num} ${xfaDatasetsRef.gen} obj\n` + `<< /Type /EmbeddedFile /Length ${xfaData.length}>>\nstream\n` + xfaData + "\nendstream\nendobj\n";
   newRefs.push({
     ref: xfaDatasetsRef,
     data
   });
 }
-
 function incrementalUpdate({
   originalData,
   xrefInfo,
@@ -281,12 +235,10 @@ function incrementalUpdate({
       xrefInfo
     });
   }
-
   const newXref = new _primitives.Dict(null);
   const refForXrefTable = xrefInfo.newRef;
   let buffer, baseOffset;
   const lastByte = originalData.at(-1);
-
   if (lastByte === 0x0a || lastByte === 0x0d) {
     buffer = [];
     baseOffset = originalData.length;
@@ -294,23 +246,18 @@ function incrementalUpdate({
     buffer = ["\n"];
     baseOffset = originalData.length + 1;
   }
-
   newXref.set("Size", refForXrefTable.num + 1);
   newXref.set("Prev", xrefInfo.startXRef);
   newXref.set("Type", _primitives.Name.get("XRef"));
-
   if (xrefInfo.rootRef !== null) {
     newXref.set("Root", xrefInfo.rootRef);
   }
-
   if (xrefInfo.infoRef !== null) {
     newXref.set("Info", xrefInfo.infoRef);
   }
-
   if (xrefInfo.encryptRef !== null) {
     newXref.set("Encrypt", xrefInfo.encryptRef);
   }
-
   newRefs.push({
     ref: refForXrefTable,
     data: ""
@@ -321,7 +268,6 @@ function incrementalUpdate({
   const xrefTableData = [[0, 1, 0xffff]];
   const indexes = [0, 1];
   let maxOffset = 0;
-
   for (const {
     ref,
     data
@@ -332,14 +278,11 @@ function incrementalUpdate({
     indexes.push(ref.num, 1);
     buffer.push(data);
   }
-
   newXref.set("Index", indexes);
-
   if (Array.isArray(xrefInfo.fileIds) && xrefInfo.fileIds.length > 0) {
     const md5 = computeMD5(baseOffset, xrefInfo);
     newXref.set("ID", [xrefInfo.fileIds[0], md5]);
   }
-
   const offsetSize = Math.ceil(Math.log2(maxOffset) / 8);
   const sizes = [1, offsetSize, 2];
   const structSize = sizes[0] + sizes[1] + sizes[2];
@@ -354,18 +297,15 @@ function incrementalUpdate({
   const array = new Uint8Array(originalData.length + bufferLen + tableLength + footer.length);
   array.set(originalData);
   let offset = originalData.length;
-
   for (const str of buffer) {
     writeString(str, offset, array);
     offset += str.length;
   }
-
   for (const [type, objOffset, gen] of xrefTableData) {
     offset = writeInt(type, sizes[0], offset, array);
     offset = writeInt(objOffset, sizes[1], offset, array);
     offset = writeInt(gen, sizes[2], offset, array);
   }
-
   writeString(footer, offset, array);
   return array;
 }

+ 0 - 165
lib/core/xfa/bind.js

@@ -25,69 +25,50 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.Binder = void 0;
-
 var _xfa_object = require("./xfa_object.js");
-
 var _template = require("./template.js");
-
 var _som = require("./som.js");
-
 var _namespaces = require("./namespaces.js");
-
 var _util = require("../../shared/util.js");
-
 const NS_DATASETS = _namespaces.NamespaceIds.datasets.id;
-
 function createText(content) {
   const node = new _template.Text({});
   node[_xfa_object.$content] = content;
   return node;
 }
-
 class Binder {
   constructor(root) {
     this.root = root;
     this.datasets = root.datasets;
-
     if (root.datasets && root.datasets.data) {
       this.data = root.datasets.data;
     } else {
       this.data = new _xfa_object.XmlObject(_namespaces.NamespaceIds.datasets.id, "data");
     }
-
     this.emptyMerge = this.data[_xfa_object.$getChildren]().length === 0;
     this.root.form = this.form = root.template[_xfa_object.$clone]();
   }
-
   _isConsumeData() {
     return !this.emptyMerge && this._mergeMode;
   }
-
   _isMatchTemplate() {
     return !this._isConsumeData();
   }
-
   bind() {
     this._bindElement(this.form, this.data);
-
     return this.form;
   }
-
   getData() {
     return this.data;
   }
-
   _bindValue(formNode, data, picture) {
     formNode[_xfa_object.$data] = data;
-
     if (formNode[_xfa_object.$hasSettableValue]()) {
       if (data[_xfa_object.$isDataValue]()) {
         const value = data[_xfa_object.$getDataValue]();
-
         formNode[_xfa_object.$setValue](createText(value));
       } else if (formNode instanceof _template.Field && formNode.ui && formNode.ui.choiceList && formNode.ui.choiceList.open === "multiSelect") {
         const value = data[_xfa_object.$getChildren]().map(child => child[_xfa_object.$content].trim()).join("\n");
-
         formNode[_xfa_object.$setValue](createText(value));
       } else if (this._isConsumeData()) {
         (0, _util.warn)(`XFA - Nodes haven't the same type.`);
@@ -98,62 +79,46 @@ class Binder {
       (0, _util.warn)(`XFA - Nodes haven't the same type.`);
     }
   }
-
   _findDataByNameToConsume(name, isValue, dataNode, global) {
     if (!name) {
       return null;
     }
-
     let generator, match;
-
     for (let i = 0; i < 3; i++) {
       generator = dataNode[_xfa_object.$getRealChildrenByNameIt](name, false, true);
-
       while (true) {
         match = generator.next().value;
-
         if (!match) {
           break;
         }
-
         if (isValue === match[_xfa_object.$isDataValue]()) {
           return match;
         }
       }
-
       if (dataNode[_xfa_object.$namespaceId] === _namespaces.NamespaceIds.datasets.id && dataNode[_xfa_object.$nodeName] === "data") {
         break;
       }
-
       dataNode = dataNode[_xfa_object.$getParent]();
     }
-
     if (!global) {
       return null;
     }
-
     generator = this.data[_xfa_object.$getRealChildrenByNameIt](name, true, false);
     match = generator.next().value;
-
     if (match) {
       return match;
     }
-
     generator = this.data[_xfa_object.$getAttributeIt](name, true);
     match = generator.next().value;
-
     if (match && match[_xfa_object.$isDataValue]()) {
       return match;
     }
-
     return null;
   }
-
   _setProperties(formNode, dataNode) {
     if (!formNode.hasOwnProperty("setProperty")) {
       return;
     }
-
     for (const {
       ref,
       target,
@@ -162,55 +127,40 @@ class Binder {
       if (connection) {
         continue;
       }
-
       if (!ref) {
         continue;
       }
-
       const nodes = (0, _som.searchNode)(this.root, dataNode, ref, false, false);
-
       if (!nodes) {
         (0, _util.warn)(`XFA - Invalid reference: ${ref}.`);
         continue;
       }
-
       const [node] = nodes;
-
       if (!node[_xfa_object.$isDescendent](this.data)) {
         (0, _util.warn)(`XFA - Invalid node: must be a data node.`);
         continue;
       }
-
       const targetNodes = (0, _som.searchNode)(this.root, formNode, target, false, false);
-
       if (!targetNodes) {
         (0, _util.warn)(`XFA - Invalid target: ${target}.`);
         continue;
       }
-
       const [targetNode] = targetNodes;
-
       if (!targetNode[_xfa_object.$isDescendent](formNode)) {
         (0, _util.warn)(`XFA - Invalid target: must be a property or subproperty.`);
         continue;
       }
-
       const targetParent = targetNode[_xfa_object.$getParent]();
-
       if (targetNode instanceof _template.SetProperty || targetParent instanceof _template.SetProperty) {
         (0, _util.warn)(`XFA - Invalid target: cannot be a setProperty or one of its properties.`);
         continue;
       }
-
       if (targetNode instanceof _template.BindItems || targetParent instanceof _template.BindItems) {
         (0, _util.warn)(`XFA - Invalid target: cannot be a bindItems or one of its properties.`);
         continue;
       }
-
       const content = node[_xfa_object.$text]();
-
       const name = targetNode[_xfa_object.$nodeName];
-
       if (targetNode instanceof _xfa_object.XFAAttribute) {
         const attrs = Object.create(null);
         attrs[name] = content;
@@ -218,40 +168,29 @@ class Binder {
         targetParent[name] = obj[name];
         continue;
       }
-
       if (!targetNode.hasOwnProperty(_xfa_object.$content)) {
         (0, _util.warn)(`XFA - Invalid node to use in setProperty`);
         continue;
       }
-
       targetNode[_xfa_object.$data] = node;
       targetNode[_xfa_object.$content] = content;
-
       targetNode[_xfa_object.$finalize]();
     }
   }
-
   _bindItems(formNode, dataNode) {
     if (!formNode.hasOwnProperty("items") || !formNode.hasOwnProperty("bindItems") || formNode.bindItems.isEmpty()) {
       return;
     }
-
     for (const item of formNode.items.children) {
       formNode[_xfa_object.$removeChild](item);
     }
-
     formNode.items.clear();
     const labels = new _template.Items({});
     const values = new _template.Items({});
-
     formNode[_xfa_object.$appendChild](labels);
-
     formNode.items.push(labels);
-
     formNode[_xfa_object.$appendChild](values);
-
     formNode.items.push(values);
-
     for (const {
       ref,
       labelRef,
@@ -261,284 +200,198 @@ class Binder {
       if (connection) {
         continue;
       }
-
       if (!ref) {
         continue;
       }
-
       const nodes = (0, _som.searchNode)(this.root, dataNode, ref, false, false);
-
       if (!nodes) {
         (0, _util.warn)(`XFA - Invalid reference: ${ref}.`);
         continue;
       }
-
       for (const node of nodes) {
         if (!node[_xfa_object.$isDescendent](this.datasets)) {
           (0, _util.warn)(`XFA - Invalid ref (${ref}): must be a datasets child.`);
           continue;
         }
-
         const labelNodes = (0, _som.searchNode)(this.root, node, labelRef, true, false);
-
         if (!labelNodes) {
           (0, _util.warn)(`XFA - Invalid label: ${labelRef}.`);
           continue;
         }
-
         const [labelNode] = labelNodes;
-
         if (!labelNode[_xfa_object.$isDescendent](this.datasets)) {
           (0, _util.warn)(`XFA - Invalid label: must be a datasets child.`);
           continue;
         }
-
         const valueNodes = (0, _som.searchNode)(this.root, node, valueRef, true, false);
-
         if (!valueNodes) {
           (0, _util.warn)(`XFA - Invalid value: ${valueRef}.`);
           continue;
         }
-
         const [valueNode] = valueNodes;
-
         if (!valueNode[_xfa_object.$isDescendent](this.datasets)) {
           (0, _util.warn)(`XFA - Invalid value: must be a datasets child.`);
           continue;
         }
-
         const label = createText(labelNode[_xfa_object.$text]());
         const value = createText(valueNode[_xfa_object.$text]());
-
         labels[_xfa_object.$appendChild](label);
-
         labels.text.push(label);
-
         values[_xfa_object.$appendChild](value);
-
         values.text.push(value);
       }
     }
   }
-
   _bindOccurrences(formNode, matches, picture) {
     let baseClone;
-
     if (matches.length > 1) {
       baseClone = formNode[_xfa_object.$clone]();
-
       baseClone[_xfa_object.$removeChild](baseClone.occur);
-
       baseClone.occur = null;
     }
-
     this._bindValue(formNode, matches[0], picture);
-
     this._setProperties(formNode, matches[0]);
-
     this._bindItems(formNode, matches[0]);
-
     if (matches.length === 1) {
       return;
     }
-
     const parent = formNode[_xfa_object.$getParent]();
-
     const name = formNode[_xfa_object.$nodeName];
-
     const pos = parent[_xfa_object.$indexOf](formNode);
-
     for (let i = 1, ii = matches.length; i < ii; i++) {
       const match = matches[i];
-
       const clone = baseClone[_xfa_object.$clone]();
-
       parent[name].push(clone);
-
       parent[_xfa_object.$insertAt](pos + i, clone);
-
       this._bindValue(clone, match, picture);
-
       this._setProperties(clone, match);
-
       this._bindItems(clone, match);
     }
   }
-
   _createOccurrences(formNode) {
     if (!this.emptyMerge) {
       return;
     }
-
     const {
       occur
     } = formNode;
-
     if (!occur || occur.initial <= 1) {
       return;
     }
-
     const parent = formNode[_xfa_object.$getParent]();
-
     const name = formNode[_xfa_object.$nodeName];
-
     if (!(parent[name] instanceof _xfa_object.XFAObjectArray)) {
       return;
     }
-
     let currentNumber;
-
     if (formNode.name) {
       currentNumber = parent[name].children.filter(e => e.name === formNode.name).length;
     } else {
       currentNumber = parent[name].children.length;
     }
-
     const pos = parent[_xfa_object.$indexOf](formNode) + 1;
     const ii = occur.initial - currentNumber;
-
     if (ii) {
       const nodeClone = formNode[_xfa_object.$clone]();
-
       nodeClone[_xfa_object.$removeChild](nodeClone.occur);
-
       nodeClone.occur = null;
       parent[name].push(nodeClone);
-
       parent[_xfa_object.$insertAt](pos, nodeClone);
-
       for (let i = 1; i < ii; i++) {
         const clone = nodeClone[_xfa_object.$clone]();
-
         parent[name].push(clone);
-
         parent[_xfa_object.$insertAt](pos + i, clone);
       }
     }
   }
-
   _getOccurInfo(formNode) {
     const {
       name,
       occur
     } = formNode;
-
     if (!occur || !name) {
       return [1, 1];
     }
-
     const max = occur.max === -1 ? Infinity : occur.max;
     return [occur.min, max];
   }
-
   _setAndBind(formNode, dataNode) {
     this._setProperties(formNode, dataNode);
-
     this._bindItems(formNode, dataNode);
-
     this._bindElement(formNode, dataNode);
   }
-
   _bindElement(formNode, dataNode) {
     const uselessNodes = [];
-
     this._createOccurrences(formNode);
-
     for (const child of formNode[_xfa_object.$getChildren]()) {
       if (child[_xfa_object.$data]) {
         continue;
       }
-
       if (this._mergeMode === undefined && child[_xfa_object.$nodeName] === "subform") {
         this._mergeMode = child.mergeMode === "consumeData";
-
         const dataChildren = dataNode[_xfa_object.$getChildren]();
-
         if (dataChildren.length > 0) {
           this._bindOccurrences(child, [dataChildren[0]], null);
         } else if (this.emptyMerge) {
           const nsId = dataNode[_xfa_object.$namespaceId] === NS_DATASETS ? -1 : dataNode[_xfa_object.$namespaceId];
           const dataChild = child[_xfa_object.$data] = new _xfa_object.XmlObject(nsId, child.name || "root");
-
           dataNode[_xfa_object.$appendChild](dataChild);
-
           this._bindElement(child, dataChild);
         }
-
         continue;
       }
-
       if (!child[_xfa_object.$isBindable]()) {
         continue;
       }
-
       let global = false;
       let picture = null;
       let ref = null;
       let match = null;
-
       if (child.bind) {
         switch (child.bind.match) {
           case "none":
             this._setAndBind(child, dataNode);
-
             continue;
-
           case "global":
             global = true;
             break;
-
           case "dataRef":
             if (!child.bind.ref) {
               (0, _util.warn)(`XFA - ref is empty in node ${child[_xfa_object.$nodeName]}.`);
-
               this._setAndBind(child, dataNode);
-
               continue;
             }
-
             ref = child.bind.ref;
             break;
-
           default:
             break;
         }
-
         if (child.bind.picture) {
           picture = child.bind.picture[_xfa_object.$content];
         }
       }
-
       const [min, max] = this._getOccurInfo(child);
-
       if (ref) {
         match = (0, _som.searchNode)(this.root, dataNode, ref, true, false);
-
         if (match === null) {
           match = (0, _som.createDataNode)(this.data, dataNode, ref);
-
           if (!match) {
             continue;
           }
-
           if (this._isConsumeData()) {
             match[_xfa_object.$consumed] = true;
           }
-
           this._setAndBind(child, match);
-
           continue;
         } else {
           if (this._isConsumeData()) {
             match = match.filter(node => !node[_xfa_object.$consumed]);
           }
-
           if (match.length > max) {
             match = match.slice(0, max);
           } else if (match.length === 0) {
             match = null;
           }
-
           if (match && this._isConsumeData()) {
             match.forEach(node => {
               node[_xfa_object.$consumed] = true;
@@ -548,56 +401,41 @@ class Binder {
       } else {
         if (!child.name) {
           this._setAndBind(child, dataNode);
-
           continue;
         }
-
         if (this._isConsumeData()) {
           const matches = [];
-
           while (matches.length < max) {
             const found = this._findDataByNameToConsume(child.name, child[_xfa_object.$hasSettableValue](), dataNode, global);
-
             if (!found) {
               break;
             }
-
             found[_xfa_object.$consumed] = true;
             matches.push(found);
           }
-
           match = matches.length > 0 ? matches : null;
         } else {
           match = dataNode[_xfa_object.$getRealChildrenByNameIt](child.name, false, this.emptyMerge).next().value;
-
           if (!match) {
             if (min === 0) {
               uselessNodes.push(child);
               continue;
             }
-
             const nsId = dataNode[_xfa_object.$namespaceId] === NS_DATASETS ? -1 : dataNode[_xfa_object.$namespaceId];
             match = child[_xfa_object.$data] = new _xfa_object.XmlObject(nsId, child.name);
-
             if (this.emptyMerge) {
               match[_xfa_object.$consumed] = true;
             }
-
             dataNode[_xfa_object.$appendChild](match);
-
             this._setAndBind(child, match);
-
             continue;
           }
-
           if (this.emptyMerge) {
             match[_xfa_object.$consumed] = true;
           }
-
           match = [match];
         }
       }
-
       if (match) {
         this._bindOccurrences(child, match, picture);
       } else if (min > 0) {
@@ -606,10 +444,7 @@ class Binder {
         uselessNodes.push(child);
       }
     }
-
     uselessNodes.forEach(node => node[_xfa_object.$getParent]()[_xfa_object.$removeChild](node));
   }
-
 }
-
 exports.Binder = Binder;

+ 0 - 56
lib/core/xfa/builder.js

@@ -25,56 +25,39 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.Builder = void 0;
-
 var _namespaces = require("./namespaces.js");
-
 var _xfa_object = require("./xfa_object.js");
-
 var _setup = require("./setup.js");
-
 var _template = require("./template.js");
-
 var _unknown = require("./unknown.js");
-
 var _util = require("../../shared/util.js");
-
 class Root extends _xfa_object.XFAObject {
   constructor(ids) {
     super(-1, "root", Object.create(null));
     this.element = null;
     this[_xfa_object.$ids] = ids;
   }
-
   [_xfa_object.$onChild](child) {
     this.element = child;
     return true;
   }
-
   [_xfa_object.$finalize]() {
     super[_xfa_object.$finalize]();
-
     if (this.element.template instanceof _template.Template) {
       this[_xfa_object.$ids].set(_xfa_object.$root, this.element);
-
       this.element.template[_xfa_object.$resolvePrototypes](this[_xfa_object.$ids]);
-
       this.element.template[_xfa_object.$ids] = this[_xfa_object.$ids];
     }
   }
-
 }
-
 class Empty extends _xfa_object.XFAObject {
   constructor() {
     super(-1, "", Object.create(null));
   }
-
   [_xfa_object.$onChild](_) {
     return false;
   }
-
 }
-
 class Builder {
   constructor(rootNameSpace = null) {
     this._namespaceStack = [];
@@ -86,11 +69,9 @@ class Builder {
     }) => id));
     this._currentNamespace = rootNameSpace || new _unknown.UnknownNamespace(++this._nextNsId);
   }
-
   buildRoot(ids) {
     return new Root(ids);
   }
-
   build({
     nsPrefix,
     name,
@@ -99,25 +80,19 @@ class Builder {
     prefixes
   }) {
     const hasNamespaceDef = namespace !== null;
-
     if (hasNamespaceDef) {
       this._namespaceStack.push(this._currentNamespace);
-
       this._currentNamespace = this._searchNamespace(namespace);
     }
-
     if (prefixes) {
       this._addNamespacePrefix(prefixes);
     }
-
     if (attributes.hasOwnProperty(_xfa_object.$nsAttributes)) {
       const dataTemplate = _setup.NamespaceSetUp.datasets;
       const nsAttrs = attributes[_xfa_object.$nsAttributes];
       let xfaAttrs = null;
-
       for (const [ns, attrs] of Object.entries(nsAttrs)) {
         const nsToUse = this._getNamespaceToUse(ns);
-
         if (nsToUse === dataTemplate) {
           xfaAttrs = {
             xfa: attrs
@@ -125,22 +100,17 @@ class Builder {
           break;
         }
       }
-
       if (xfaAttrs) {
         attributes[_xfa_object.$nsAttributes] = xfaAttrs;
       } else {
         delete attributes[_xfa_object.$nsAttributes];
       }
     }
-
     const namespaceToUse = this._getNamespaceToUse(nsPrefix);
-
     const node = namespaceToUse && namespaceToUse[_namespaces.$buildXFAObject](name, attributes) || new Empty();
-
     if (node[_xfa_object.$isNsAgnostic]()) {
       this._nsAgnosticLevel++;
     }
-
     if (hasNamespaceDef || prefixes || node[_xfa_object.$isNsAgnostic]()) {
       node[_xfa_object.$cleanup] = {
         hasNamespace: hasNamespaceDef,
@@ -148,89 +118,66 @@ class Builder {
         nsAgnostic: node[_xfa_object.$isNsAgnostic]()
       };
     }
-
     return node;
   }
-
   isNsAgnostic() {
     return this._nsAgnosticLevel > 0;
   }
-
   _searchNamespace(nsName) {
     let ns = this._namespaces.get(nsName);
-
     if (ns) {
       return ns;
     }
-
     for (const [name, {
       check
     }] of Object.entries(_namespaces.NamespaceIds)) {
       if (check(nsName)) {
         ns = _setup.NamespaceSetUp[name];
-
         if (ns) {
           this._namespaces.set(nsName, ns);
-
           return ns;
         }
-
         break;
       }
     }
-
     ns = new _unknown.UnknownNamespace(++this._nextNsId);
-
     this._namespaces.set(nsName, ns);
-
     return ns;
   }
-
   _addNamespacePrefix(prefixes) {
     for (const {
       prefix,
       value
     } of prefixes) {
       const namespace = this._searchNamespace(value);
-
       let prefixStack = this._namespacePrefixes.get(prefix);
-
       if (!prefixStack) {
         prefixStack = [];
-
         this._namespacePrefixes.set(prefix, prefixStack);
       }
-
       prefixStack.push(namespace);
     }
   }
-
   _getNamespaceToUse(prefix) {
     if (!prefix) {
       return this._currentNamespace;
     }
-
     const prefixStack = this._namespacePrefixes.get(prefix);
-
     if (prefixStack && prefixStack.length > 0) {
       return prefixStack.at(-1);
     }
-
     (0, _util.warn)(`Unknown namespace prefix: ${prefix}.`);
     return null;
   }
-
   clean(data) {
     const {
       hasNamespace,
       prefixes,
       nsAgnostic
     } = data;
-
     if (hasNamespace) {
       this._currentNamespace = this._namespaceStack.pop();
     }
-
     if (prefixes) {
       prefixes.forEach(({
         prefix
@@ -238,12 +185,9 @@ class Builder {
         this._namespacePrefixes.get(prefix).pop();
       });
     }
-
     if (nsAgnostic) {
       this._nsAgnosticLevel--;
     }
   }
-
 }
-
 exports.Builder = Builder;

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 1 - 265
lib/core/xfa/config.js


+ 0 - 43
lib/core/xfa/connection_set.js

@@ -25,13 +25,9 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.ConnectionSetNamespace = void 0;
-
 var _namespaces = require("./namespaces.js");
-
 var _xfa_object = require("./xfa_object.js");
-
 const CONNECTION_SET_NS_ID = _namespaces.NamespaceIds.connectionSet.id;
-
 class ConnectionSet extends _xfa_object.XFAObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "connectionSet", true);
@@ -39,9 +35,7 @@ class ConnectionSet extends _xfa_object.XFAObject {
     this.xmlConnection = new _xfa_object.XFAObjectArray();
     this.xsdConnection = new _xfa_object.XFAObjectArray();
   }
-
 }
-
 class EffectiveInputPolicy extends _xfa_object.XFAObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "effectiveInputPolicy");
@@ -50,9 +44,7 @@ class EffectiveInputPolicy extends _xfa_object.XFAObject {
     this.use = attributes.use || "";
     this.usehref = attributes.usehref || "";
   }
-
 }
-
 class EffectiveOutputPolicy extends _xfa_object.XFAObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "effectiveOutputPolicy");
@@ -61,9 +53,7 @@ class EffectiveOutputPolicy extends _xfa_object.XFAObject {
     this.use = attributes.use || "";
     this.usehref = attributes.usehref || "";
   }
-
 }
-
 class Operation extends _xfa_object.StringObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "operation");
@@ -74,9 +64,7 @@ class Operation extends _xfa_object.StringObject {
     this.use = attributes.use || "";
     this.usehref = attributes.usehref || "";
   }
-
 }
-
 class RootElement extends _xfa_object.StringObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "rootElement");
@@ -85,9 +73,7 @@ class RootElement extends _xfa_object.StringObject {
     this.use = attributes.use || "";
     this.usehref = attributes.usehref || "";
   }
-
 }
-
 class SoapAction extends _xfa_object.StringObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "soapAction");
@@ -96,9 +82,7 @@ class SoapAction extends _xfa_object.StringObject {
     this.use = attributes.use || "";
     this.usehref = attributes.usehref || "";
   }
-
 }
-
 class SoapAddress extends _xfa_object.StringObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "soapAddress");
@@ -107,9 +91,7 @@ class SoapAddress extends _xfa_object.StringObject {
     this.use = attributes.use || "";
     this.usehref = attributes.usehref || "";
   }
-
 }
-
 class Uri extends _xfa_object.StringObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "uri");
@@ -118,9 +100,7 @@ class Uri extends _xfa_object.StringObject {
     this.use = attributes.use || "";
     this.usehref = attributes.usehref || "";
   }
-
 }
-
 class WsdlAddress extends _xfa_object.StringObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "wsdlAddress");
@@ -129,9 +109,7 @@ class WsdlAddress extends _xfa_object.StringObject {
     this.use = attributes.use || "";
     this.usehref = attributes.usehref || "";
   }
-
 }
-
 class WsdlConnection extends _xfa_object.XFAObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "wsdlConnection", true);
@@ -144,9 +122,7 @@ class WsdlConnection extends _xfa_object.XFAObject {
     this.soapAddress = null;
     this.wsdlAddress = null;
   }
-
 }
-
 class XmlConnection extends _xfa_object.XFAObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "xmlConnection", true);
@@ -154,9 +130,7 @@ class XmlConnection extends _xfa_object.XFAObject {
     this.name = attributes.name || "";
     this.uri = null;
   }
-
 }
-
 class XsdConnection extends _xfa_object.XFAObject {
   constructor(attributes) {
     super(CONNECTION_SET_NS_ID, "xsdConnection", true);
@@ -165,66 +139,49 @@ class XsdConnection extends _xfa_object.XFAObject {
     this.rootElement = null;
     this.uri = null;
   }
-
 }
-
 class ConnectionSetNamespace {
   static [_namespaces.$buildXFAObject](name, attributes) {
     if (ConnectionSetNamespace.hasOwnProperty(name)) {
       return ConnectionSetNamespace[name](attributes);
     }
-
     return undefined;
   }
-
   static connectionSet(attrs) {
     return new ConnectionSet(attrs);
   }
-
   static effectiveInputPolicy(attrs) {
     return new EffectiveInputPolicy(attrs);
   }
-
   static effectiveOutputPolicy(attrs) {
     return new EffectiveOutputPolicy(attrs);
   }
-
   static operation(attrs) {
     return new Operation(attrs);
   }
-
   static rootElement(attrs) {
     return new RootElement(attrs);
   }
-
   static soapAction(attrs) {
     return new SoapAction(attrs);
   }
-
   static soapAddress(attrs) {
     return new SoapAddress(attrs);
   }
-
   static uri(attrs) {
     return new Uri(attrs);
   }
-
   static wsdlAddress(attrs) {
     return new WsdlAddress(attrs);
   }
-
   static wsdlConnection(attrs) {
     return new WsdlConnection(attrs);
   }
-
   static xmlConnection(attrs) {
     return new XmlConnection(attrs);
   }
-
   static xsdConnection(attrs) {
     return new XsdConnection(attrs);
   }
-
 }
-
 exports.ConnectionSetNamespace = ConnectionSetNamespace;

+ 0 - 18
lib/core/xfa/data.js

@@ -25,55 +25,41 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.DataHandler = void 0;
-
 var _xfa_object = require("./xfa_object.js");
-
 class DataHandler {
   constructor(root, data) {
     this.data = data;
     this.dataset = root.datasets || null;
   }
-
   serialize(storage) {
     const stack = [[-1, this.data[_xfa_object.$getChildren]()]];
-
     while (stack.length > 0) {
       const last = stack.at(-1);
       const [i, children] = last;
-
       if (i + 1 === children.length) {
         stack.pop();
         continue;
       }
-
       const child = children[++last[0]];
       const storageEntry = storage.get(child[_xfa_object.$uid]);
-
       if (storageEntry) {
         child[_xfa_object.$setValue](storageEntry);
       } else {
         const attributes = child[_xfa_object.$getAttributes]();
-
         for (const value of attributes.values()) {
           const entry = storage.get(value[_xfa_object.$uid]);
-
           if (entry) {
             value[_xfa_object.$setValue](entry);
-
             break;
           }
         }
       }
-
       const nodes = child[_xfa_object.$getChildren]();
-
       if (nodes.length > 0) {
         stack.push([-1, nodes]);
       }
     }
-
     const buf = [`<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">`];
-
     if (this.dataset) {
       for (const child of this.dataset[_xfa_object.$getChildren]()) {
         if (child[_xfa_object.$nodeName] !== "data") {
@@ -81,13 +67,9 @@ class DataHandler {
         }
       }
     }
-
     this.data[_xfa_object.$toString](buf);
-
     buf.push("</xfa:datasets>");
     return buf.join("");
   }
-
 }
-
 exports.DataHandler = DataHandler;

+ 0 - 17
lib/core/xfa/datasets.js

@@ -25,60 +25,43 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.DatasetsNamespace = void 0;
-
 var _xfa_object = require("./xfa_object.js");
-
 var _namespaces = require("./namespaces.js");
-
 const DATASETS_NS_ID = _namespaces.NamespaceIds.datasets.id;
-
 class Data extends _xfa_object.XmlObject {
   constructor(attributes) {
     super(DATASETS_NS_ID, "data", attributes);
   }
-
   [_xfa_object.$isNsAgnostic]() {
     return true;
   }
-
 }
-
 class Datasets extends _xfa_object.XFAObject {
   constructor(attributes) {
     super(DATASETS_NS_ID, "datasets", true);
     this.data = null;
     this.Signature = null;
   }
-
   [_xfa_object.$onChild](child) {
     const name = child[_xfa_object.$nodeName];
-
     if (name === "data" && child[_xfa_object.$namespaceId] === DATASETS_NS_ID || name === "Signature" && child[_xfa_object.$namespaceId] === _namespaces.NamespaceIds.signature.id) {
       this[name] = child;
     }
-
     this[_xfa_object.$appendChild](child);
   }
-
 }
-
 class DatasetsNamespace {
   static [_namespaces.$buildXFAObject](name, attributes) {
     if (DatasetsNamespace.hasOwnProperty(name)) {
       return DatasetsNamespace[name](attributes);
     }
-
     return undefined;
   }
-
   static datasets(attributes) {
     return new Datasets(attributes);
   }
-
   static data(attributes) {
     return new Data(attributes);
   }
-
 }
-
 exports.DatasetsNamespace = DatasetsNamespace;

+ 0 - 45
lib/core/xfa/factory.js

@@ -25,23 +25,14 @@ Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.XFAFactory = void 0;
-
 var _xfa_object = require("./xfa_object.js");
-
 var _bind = require("./bind.js");
-
 var _data = require("./data.js");
-
 var _fonts = require("./fonts.js");
-
 var _utils = require("./utils.js");
-
 var _util = require("../../shared/util.js");
-
 var _parser = require("./parser.js");
-
 var _xhtml = require("./xhtml.js");
-
 class XFAFactory {
   constructor(data) {
     try {
@@ -54,19 +45,15 @@ class XFAFactory {
       (0, _util.warn)(`XFA - an error occurred during parsing and binding: ${e}`);
     }
   }
-
   isValid() {
     return this.root && this.form;
   }
-
   _createPagesHelper() {
     const iterator = this.form[_xfa_object.$toPages]();
-
     return new Promise((resolve, reject) => {
       const nextIteration = () => {
         try {
           const value = iterator.next();
-
           if (value.done) {
             resolve(value.value);
           } else {
@@ -76,11 +63,9 @@ class XFAFactory {
           reject(e);
         }
       };
-
       setTimeout(nextIteration, 0);
     });
   }
-
   async _createPages() {
     try {
       this.pages = await this._createPagesHelper();
@@ -95,107 +80,80 @@ class XFAFactory {
       (0, _util.warn)(`XFA - an error occurred during layout: ${e}`);
     }
   }
-
   getBoundingBox(pageIndex) {
     return this.dims[pageIndex];
   }
-
   async getNumPages() {
     if (!this.pages) {
       await this._createPages();
     }
-
     return this.dims.length;
   }
-
   setImages(images) {
     this.form[_xfa_object.$globalData].images = images;
   }
-
   setFonts(fonts) {
     this.form[_xfa_object.$globalData].fontFinder = new _fonts.FontFinder(fonts);
     const missingFonts = [];
-
     for (let typeface of this.form[_xfa_object.$globalData].usedTypefaces) {
       typeface = (0, _utils.stripQuotes)(typeface);
-
       const font = this.form[_xfa_object.$globalData].fontFinder.find(typeface);
-
       if (!font) {
         missingFonts.push(typeface);
       }
     }
-
     if (missingFonts.length > 0) {
       return missingFonts;
     }
-
     return null;
   }
-
   appendFonts(fonts, reallyMissingFonts) {
     this.form[_xfa_object.$globalData].fontFinder.add(fonts, reallyMissingFonts);
   }
-
   async getPages() {
     if (!this.pages) {
       await this._createPages();
     }
-
     const pages = this.pages;
     this.pages = null;
     return pages;
   }
-
   serializeData(storage) {
     return this.dataHandler.serialize(storage);
   }
-
   static _createDocument(data) {
     if (!data["/xdp:xdp"]) {
       return data["xdp:xdp"];
     }
-
     return Object.values(data).join("");
   }
-
   static getRichTextAsHtml(rc) {
     if (!rc || typeof rc !== "string") {
       return null;
     }
-
     try {
       let root = new _parser.XFAParser(_xhtml.XhtmlNamespace, true).parse(rc);
-
       if (!["body", "xhtml"].includes(root[_xfa_object.$nodeName])) {
         const newRoot = _xhtml.XhtmlNamespace.body({});
-
         newRoot[_xfa_object.$appendChild](root);
-
         root = newRoot;
       }
-
       const result = root[_xfa_object.$toHTML]();
-
       if (!result.success) {
         return null;
       }
-
       const {
         html
       } = result;
       const {
         attributes
       } = html;
-
       if (attributes) {
         if (attributes.class) {
           attributes.class = attributes.class.filter(attr => !attr.startsWith("xfa"));
         }
-
         attributes.dir = "auto";
       }
-
       return {
         html,
         str: root[_xfa_object.$text]()
@@ -203,10 +161,7 @@ class XFAFactory {
     } catch (e) {
       (0, _util.warn)(`XFA - an error occurred during parsing of rich text: ${e}`);
     }
-
     return null;
   }
-
 }
-
 exports.XFAFactory = XFAFactory;

+ 0 - 44
lib/core/xfa/fonts.js

@@ -27,13 +27,9 @@ Object.defineProperty(exports, "__esModule", {
 exports.FontFinder = void 0;
 exports.getMetrics = getMetrics;
 exports.selectFont = selectFont;
-
 var _xfa_object = require("./xfa_object.js");
-
 var _utils = require("./utils.js");
-
 var _util = require("../../shared/util.js");
-
 class FontFinder {
   constructor(pdfFonts) {
     this.fonts = new Map();
@@ -42,98 +38,76 @@ class FontFinder {
     this.defaultFont = null;
     this.add(pdfFonts);
   }
-
   add(pdfFonts, reallyMissingFonts = null) {
     for (const pdfFont of pdfFonts) {
       this.addPdfFont(pdfFont);
     }
-
     for (const pdfFont of this.fonts.values()) {
       if (!pdfFont.regular) {
         pdfFont.regular = pdfFont.italic || pdfFont.bold || pdfFont.bolditalic;
       }
     }
-
     if (!reallyMissingFonts || reallyMissingFonts.size === 0) {
       return;
     }
-
     const myriad = this.fonts.get("PdfJS-Fallback-PdfJS-XFA");
-
     for (const missing of reallyMissingFonts) {
       this.fonts.set(missing, myriad);
     }
   }
-
   addPdfFont(pdfFont) {
     const cssFontInfo = pdfFont.cssFontInfo;
     const name = cssFontInfo.fontFamily;
     let font = this.fonts.get(name);
-
     if (!font) {
       font = Object.create(null);
       this.fonts.set(name, font);
-
       if (!this.defaultFont) {
         this.defaultFont = font;
       }
     }
-
     let property = "";
     const fontWeight = parseFloat(cssFontInfo.fontWeight);
-
     if (parseFloat(cssFontInfo.italicAngle) !== 0) {
       property = fontWeight >= 700 ? "bolditalic" : "italic";
     } else if (fontWeight >= 700) {
       property = "bold";
     }
-
     if (!property) {
       if (pdfFont.name.includes("Bold") || pdfFont.psName && pdfFont.psName.includes("Bold")) {
         property = "bold";
       }
-
       if (pdfFont.name.includes("Italic") || pdfFont.name.endsWith("It") || pdfFont.psName && (pdfFont.psName.includes("Italic") || pdfFont.psName.endsWith("It"))) {
         property += "italic";
       }
     }
-
     if (!property) {
       property = "regular";
     }
-
     font[property] = pdfFont;
   }
-
   getDefault() {
     return this.defaultFont;
   }
-
   find(fontName, mustWarn = true) {
     let font = this.fonts.get(fontName) || this.cache.get(fontName);
-
     if (font) {
       return font;
     }
-
     const pattern = /,|-|_| |bolditalic|bold|italic|regular|it/gi;
     let name = fontName.replace(pattern, "");
     font = this.fonts.get(name);
-
     if (font) {
       this.cache.set(fontName, font);
       return font;
     }
-
     name = name.toLowerCase();
     const maybe = [];
-
     for (const [family, pdfFont] of this.fonts.entries()) {
       if (family.replace(pattern, "").toLowerCase().startsWith(name)) {
         maybe.push(pdfFont);
       }
     }
-
     if (maybe.length === 0) {
       for (const [, pdfFont] of this.fonts.entries()) {
         if (pdfFont.regular.name && pdfFont.regular.name.replace(pattern, "").toLowerCase().startsWith(name)) {
@@ -141,17 +115,14 @@ class FontFinder {
         }
       }
     }
-
     if (maybe.length === 0) {
       name = name.replace(/psmt|mt/gi, "");
-
       for (const [family, pdfFont] of this.fonts.entries()) {
         if (family.replace(pattern, "").toLowerCase().startsWith(name)) {
           maybe.push(pdfFont);
         }
       }
     }
-
     if (maybe.length === 0) {
       for (const pdfFont of this.fonts.values()) {
         if (pdfFont.regular.name && pdfFont.regular.name.replace(pattern, "").toLowerCase().startsWith(name)) {
@@ -159,53 +130,39 @@ class FontFinder {
         }
       }
     }
-
     if (maybe.length >= 1) {
       if (maybe.length !== 1 && mustWarn) {
         (0, _util.warn)(`XFA - Too many choices to guess the correct font: ${fontName}`);
       }
-
       this.cache.set(fontName, maybe[0]);
       return maybe[0];
     }
-
     if (mustWarn && !this.warned.has(fontName)) {
       this.warned.add(fontName);
       (0, _util.warn)(`XFA - Cannot find the font: ${fontName}`);
     }
-
     return null;
   }
-
 }
-
 exports.FontFinder = FontFinder;
-
 function selectFont(xfaFont, typeface) {
   if (xfaFont.posture === "italic") {
     if (xfaFont.weight === "bold") {
       return typeface.bolditalic;
     }
-
     return typeface.italic;
   } else if (xfaFont.weight === "bold") {
     return typeface.bold;
   }
-
   return typeface.regular;
 }
-
 function getMetrics(xfaFont, real = false) {
   let pdfFont = null;
-
   if (xfaFont) {
     const name = (0, _utils.stripQuotes)(xfaFont.typeface);
-
     const typeface = xfaFont[_xfa_object.$globalData].fontFinder.find(name);
-
     pdfFont = selectFont(xfaFont, typeface);
   }
-
   if (!pdfFont) {
     return {
       lineHeight: 12,
@@ -213,7 +170,6 @@ function getMetrics(xfaFont, real = false) {
       lineNoGap: 10
     };
   }
-
   const size = xfaFont.size || 10;
   const lineHeight = pdfFont.lineHeight ? Math.max(real ? 0 : 1.2, pdfFont.lineHeight) : 1.2;
   const lineGap = pdfFont.lineGap === undefined ? 0.2 : pdfFont.lineGap;

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio