Browse Source

PDF.js version 1.8.524 - See mozilla/pdf.js@7b4887dd211c44d5ef852ad019921fb41fa3709b

pdfjsbot 7 years ago
parent
commit
5268873b71

+ 1 - 1
bower.json

@@ -1,6 +1,6 @@
 {
   "name": "pdfjs-dist",
-  "version": "1.8.522",
+  "version": "1.8.524",
   "main": [
     "build/pdf.js",
     "build/pdf.worker.js"

File diff suppressed because it is too large
+ 136 - 138
build/pdf.combined.js


File diff suppressed because it is too large
+ 0 - 0
build/pdf.combined.js.map


+ 39 - 45
build/pdf.js

@@ -101,7 +101,7 @@ return /******/ (function(modules) { // webpackBootstrap
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
-exports.warn = exports.utf8StringToString = exports.stringToUTF8String = exports.stringToPDFString = exports.stringToBytes = exports.string32 = exports.shadow = exports.setVerbosityLevel = exports.ReadableStream = exports.removeNullCharacters = exports.readUint32 = exports.readUint16 = exports.readInt8 = exports.log2 = exports.loadJpegStream = exports.isEvalSupported = exports.isLittleEndian = exports.createValidAbsoluteUrl = exports.isSameOrigin = exports.isNodeJS = exports.isSpace = exports.isString = exports.isNum = exports.isInt = exports.isEmptyObj = exports.isBool = exports.isArrayBuffer = exports.isArray = exports.info = exports.globalScope = exports.getVerbosityLevel = exports.getLookupTableFactory = exports.error = exports.deprecated = exports.createObjectURL = exports.createPromiseCapability = exports.createBlob = exports.bytesToString = exports.assert = exports.arraysToBytes = exports.arrayByteLength = exports.XRefParseException = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.StatTimer = exports.PasswordResponses = exports.PasswordException = exports.PageViewport = exports.NotImplementedException = exports.NativeImageDecoding = exports.MissingPDFException = exports.MissingDataException = exports.MessageHandler = exports.InvalidPDFException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VERBOSITY_LEVELS = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = undefined;
+exports.unreachable = exports.warn = exports.utf8StringToString = exports.stringToUTF8String = exports.stringToPDFString = exports.stringToBytes = exports.string32 = exports.shadow = exports.setVerbosityLevel = exports.ReadableStream = exports.removeNullCharacters = exports.readUint32 = exports.readUint16 = exports.readInt8 = exports.log2 = exports.loadJpegStream = exports.isEvalSupported = exports.isLittleEndian = exports.createValidAbsoluteUrl = exports.isSameOrigin = exports.isNodeJS = exports.isSpace = exports.isString = exports.isNum = exports.isInt = exports.isEmptyObj = exports.isBool = exports.isArrayBuffer = exports.isArray = exports.info = exports.globalScope = exports.getVerbosityLevel = exports.getLookupTableFactory = exports.deprecated = exports.createObjectURL = exports.createPromiseCapability = exports.createBlob = exports.bytesToString = exports.assert = exports.arraysToBytes = exports.arrayByteLength = exports.FormatError = exports.XRefParseException = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.StatTimer = exports.PasswordResponses = exports.PasswordException = exports.PageViewport = exports.NotImplementedException = exports.NativeImageDecoding = exports.MissingPDFException = exports.MissingDataException = exports.MessageHandler = exports.InvalidPDFException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VERBOSITY_LEVELS = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = undefined;
 
 var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
 
@@ -349,23 +349,12 @@ function warn(msg) {
 function deprecated(details) {
   console.log('Deprecated API usage: ' + details);
 }
-function error(msg) {
-  if (verbosity >= VERBOSITY_LEVELS.errors) {
-    console.log('Error: ' + msg);
-    console.log(backtrace());
-  }
+function unreachable(msg) {
   throw new Error(msg);
 }
-function backtrace() {
-  try {
-    throw new Error();
-  } catch (e) {
-    return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
-  }
-}
 function assert(cond, msg) {
   if (!cond) {
-    error(msg);
+    unreachable(msg);
   }
 }
 var UNSUPPORTED_FEATURES = {
@@ -516,6 +505,15 @@ var XRefParseException = function XRefParseExceptionClosure() {
   XRefParseException.constructor = XRefParseException;
   return XRefParseException;
 }();
+var FormatError = function FormatErrorClosure() {
+  function FormatError(msg) {
+    this.message = msg;
+  }
+  FormatError.prototype = new Error();
+  FormatError.prototype.name = 'FormatError';
+  FormatError.constructor = FormatError;
+  return FormatError;
+}();
 var NullCharactersRegExp = /\x00/g;
 function removeNullCharacters(str) {
   if (typeof str !== 'string') {
@@ -1052,7 +1050,7 @@ function MessageHandler(sourceName, targetName, comObj) {
           callback.resolve(data.data);
         }
       } else {
-        error('Cannot resolve callback ' + callbackId);
+        throw new Error('Cannot resolve callback ' + callbackId);
       }
     } else if (data.action in ah) {
       var action = ah[data.action];
@@ -1087,7 +1085,7 @@ function MessageHandler(sourceName, targetName, comObj) {
         action[0].call(action[1], data.data);
       }
     } else {
-      error('Unknown action from worker: ' + data.action);
+      throw new Error('Unknown action from worker: ' + data.action);
     }
   };
   comObj.addEventListener('message', this._onComObjOnMessage);
@@ -1096,7 +1094,7 @@ MessageHandler.prototype = {
   on: function on(actionName, handler, scope) {
     var ah = this.actionHandler;
     if (ah[actionName]) {
-      error('There is already an actionName called "' + actionName + '"');
+      throw new Error('There is already an actionName called "' + actionName + '"');
     }
     ah[actionName] = [handler, scope];
   },
@@ -1404,6 +1402,7 @@ exports.UnexpectedResponseException = UnexpectedResponseException;
 exports.UnknownErrorException = UnknownErrorException;
 exports.Util = Util;
 exports.XRefParseException = XRefParseException;
+exports.FormatError = FormatError;
 exports.arrayByteLength = arrayByteLength;
 exports.arraysToBytes = arraysToBytes;
 exports.assert = assert;
@@ -1412,7 +1411,6 @@ exports.createBlob = createBlob;
 exports.createPromiseCapability = createPromiseCapability;
 exports.createObjectURL = createObjectURL;
 exports.deprecated = deprecated;
-exports.error = error;
 exports.getLookupTableFactory = getLookupTableFactory;
 exports.getVerbosityLevel = getVerbosityLevel;
 exports.globalScope = globalScope;
@@ -1445,6 +1443,7 @@ exports.stringToPDFString = stringToPDFString;
 exports.stringToUTF8String = stringToUTF8String;
 exports.utf8StringToString = utf8StringToString;
 exports.warn = warn;
+exports.unreachable = unreachable;
 /* WEBPACK VAR INJECTION */}.call(exports, __w_pdfjs_require__(6)))
 
 /***/ }),
@@ -2470,10 +2469,10 @@ function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallb
     source = { range: src };
   } else {
     if ((typeof src === 'undefined' ? 'undefined' : _typeof(src)) !== 'object') {
-      (0, _util.error)('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object');
+      throw new Error('Invalid parameter in getDocument, ' + 'need either Uint8Array, string or a parameter object');
     }
     if (!src.url && !src.data && !src.range) {
-      (0, _util.error)('Invalid parameter object: need either .data, .range or .url');
+      throw new Error('Invalid parameter object: need either .data, .range or .url');
     }
     source = src;
   }
@@ -2500,7 +2499,7 @@ function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallb
       } else if ((0, _util.isArrayBuffer)(pdfBytes)) {
         params[key] = new Uint8Array(pdfBytes);
       } else {
-        (0, _util.error)('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.');
+        throw new Error('Invalid PDF binary data: either typed array, ' + 'string or array-like object is expected in the ' + 'data property.');
       }
       continue;
     } else if (key === 'CMapReaderFactory') {
@@ -3072,7 +3071,7 @@ var PDFWorker = function PDFWorkerClosure() {
     if (pdfjsFilePath) {
       return pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, '.worker$1$2');
     }
-    (0, _util.error)('No PDFJS.workerSrc specified');
+    throw new Error('No PDFJS.workerSrc specified');
   }
   var fakeWorkerFilesLoadedCapability = void 0;
   function setupFakeWorkerGlobal() {
@@ -3435,7 +3434,7 @@ var WorkerTransport = function WorkerTransportClosure() {
             this.commonObjs.resolve(id, data[2]);
             break;
           default:
-            (0, _util.error)('Got unknown common object type ' + type);
+            throw new Error('Got unknown common object type ' + type);
         }
       }, this);
       messageHandler.on('obj', function transportObj(data) {
@@ -3464,7 +3463,7 @@ var WorkerTransport = function WorkerTransportClosure() {
             }
             break;
           default:
-            (0, _util.error)('Got unknown object type ' + type);
+            throw new Error('Got unknown object type ' + type);
         }
       }, this);
       messageHandler.on('DocProgress', function transportDocProgress(data) {
@@ -3488,7 +3487,7 @@ var WorkerTransport = function WorkerTransportClosure() {
         if (intentState.displayReadyCapability) {
           intentState.displayReadyCapability.reject(data.error);
         } else {
-          (0, _util.error)(data.error);
+          throw new Error(data.error);
         }
         if (intentState.operatorList) {
           intentState.operatorList.lastChunk = true;
@@ -3670,7 +3669,7 @@ var PDFObjects = function PDFObjectsClosure() {
       }
       var obj = this.objs[objId];
       if (!obj || !obj.resolved) {
-        (0, _util.error)('Requesting object that isn\'t resolved yet ' + objId);
+        throw new Error('Requesting object that isn\'t resolved yet ' + objId);
       }
       return obj.data;
     },
@@ -3854,8 +3853,8 @@ var _UnsupportedManager = function UnsupportedManagerClosure() {
 }();
 var version, build;
 {
-  exports.version = version = '1.8.522';
-  exports.build = build = 'ac980280';
+  exports.version = version = '1.8.524';
+  exports.build = build = '7b4887dd';
 }
 exports.getDocument = getDocument;
 exports.LoopbackPort = LoopbackPort;
@@ -5439,10 +5438,6 @@ module.exports = g;
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
-exports.Metadata = undefined;
-
-var _util = __w_pdfjs_require__(0);
-
 function fixMetadata(meta) {
   return meta.replace(/>\\376\\377([^<]+)/g, function (all, codes) {
     var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
@@ -5462,7 +5457,7 @@ function Metadata(meta) {
     var parser = new DOMParser();
     meta = parser.parseFromString(meta, 'application/xml');
   } else if (!(meta instanceof Document)) {
-    (0, _util.error)('Metadata: Invalid metadata object');
+    throw new Error('Metadata: Invalid metadata object');
   }
   this.metaDocument = meta;
   this.metadata = Object.create(null);
@@ -5912,8 +5907,8 @@ if (!_util.globalScope.PDFJS) {
 }
 var PDFJS = _util.globalScope.PDFJS;
 {
-  PDFJS.version = '1.8.522';
-  PDFJS.build = 'ac980280';
+  PDFJS.version = '1.8.524';
+  PDFJS.build = '7b4887dd';
 }
 PDFJS.pdfBug = false;
 if (PDFJS.verbosity !== undefined) {
@@ -9469,7 +9464,7 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
         ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
       }
     } else {
-      (0, _util.error)('bad image kind: ' + imgData.kind);
+      throw new Error('bad image kind: ' + imgData.kind);
     }
   }
   function putBinaryImageMask(ctx, imgData) {
@@ -10050,7 +10045,7 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
       var fontObj = this.commonObjs.get(fontRefName);
       var current = this.current;
       if (!fontObj) {
-        (0, _util.error)('Can\'t find font for ' + fontRefName);
+        throw new Error('Can\'t find font for ' + fontRefName);
       }
       current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : _util.FONT_IDENTITY_MATRIX;
       if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
@@ -10386,10 +10381,10 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
       this.restore();
     },
     beginInlineImage: function CanvasGraphics_beginInlineImage() {
-      (0, _util.error)('Should not call beginInlineImage');
+      throw new Error('Should not call beginInlineImage');
     },
     beginImageData: function CanvasGraphics_beginImageData() {
-      (0, _util.error)('Should not call beginImageData');
+      throw new Error('Should not call beginImageData');
     },
     paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) {
       this.save();
@@ -11224,8 +11219,7 @@ var createMeshCanvas = function createMeshCanvasClosure() {
         }
         break;
       default:
-        (0, _util.error)('illigal figure');
-        break;
+        throw new Error('illegal figure');
     }
   }
   function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) {
@@ -11333,7 +11327,7 @@ ShadingIRs.Dummy = {
 function getShadingPatternFromIR(raw) {
   var shadingIR = ShadingIRs[raw[0]];
   if (!shadingIR) {
-    (0, _util.error)('Unknown IR type: ' + raw[0]);
+    throw new Error('Unknown IR type: ' + raw[0]);
   }
   return shadingIR.fromIR(raw);
 }
@@ -11428,7 +11422,7 @@ var TilingPattern = function TilingPatternClosure() {
           context.strokeStyle = cssColor;
           break;
         default:
-          (0, _util.error)('Unsupported paint type: ' + paintType);
+          throw new _util.FormatError('Unsupported paint type: ' + paintType);
       }
     },
     getPattern: function TilingPattern_getPattern(ctx, owner) {
@@ -11452,8 +11446,8 @@ exports.TilingPattern = TilingPattern;
 "use strict";
 
 
-var pdfjsVersion = '1.8.522';
-var pdfjsBuild = 'ac980280';
+var pdfjsVersion = '1.8.524';
+var pdfjsBuild = '7b4887dd';
 var pdfjsSharedUtil = __w_pdfjs_require__(0);
 var pdfjsDisplayGlobal = __w_pdfjs_require__(9);
 var pdfjsDisplayAPI = __w_pdfjs_require__(3);

File diff suppressed because it is too large
+ 0 - 0
build/pdf.js.map


File diff suppressed because it is too large
+ 0 - 0
build/pdf.min.js


File diff suppressed because it is too large
+ 138 - 136
build/pdf.worker.js


File diff suppressed because it is too large
+ 0 - 0
build/pdf.worker.js.map


File diff suppressed because it is too large
+ 0 - 0
build/pdf.worker.min.js


+ 12 - 14
lib/core/cff_parser.js

@@ -305,8 +305,9 @@ var CFFParser = function CFFParserClosure() {
         ++offset;
       }
       if (offset >= bytesLength) {
-        (0, _util.error)('Invalid CFF header');
-      } else if (offset !== 0) {
+        throw new _util.FormatError('Invalid CFF header');
+      }
+      if (offset !== 0) {
         (0, _util.info)('cff data is shifted');
         bytes = bytes.subarray(offset);
         this.bytes = bytes;
@@ -716,7 +717,7 @@ var CFFParser = function CFFParserClosure() {
           }
           break;
         default:
-          (0, _util.error)('Unknown charset format');
+          throw new _util.FormatError('Unknown charset format');
       }
       var end = pos;
       var raw = bytes.subarray(start, end);
@@ -768,8 +769,7 @@ var CFFParser = function CFFParserClosure() {
             }
             break;
           default:
-            (0, _util.error)('Unknown encoding format: ' + format + ' in CFF');
-            break;
+            throw new _util.FormatError('Unknown encoding format: ' + format + ' in CFF');
         }
         var dataEnd = pos;
         if (format & 0x80) {
@@ -819,8 +819,7 @@ var CFFParser = function CFFParserClosure() {
           }
           break;
         default:
-          (0, _util.error)('parseFDSelect: Unknown format "' + format + '".');
-          break;
+          throw new _util.FormatError('parseFDSelect: Unknown format "' + format + '".');
       }
       (0, _util.assert)(fdSelect.length === length, 'parseFDSelect: Invalid font data.');
       return new CFFFDSelect(fdSelect, rawBytes);
@@ -934,7 +933,7 @@ var CFFDict = function CFFDictClosure() {
     },
     setByName: function CFFDict_setByName(name, value) {
       if (!(name in this.nameToKeyMap)) {
-        (0, _util.error)('Invalid dictionary name "' + name + '"');
+        throw new _util.FormatError('Invalid dictionary name "' + name + '"');
       }
       this.values[this.nameToKeyMap[name]] = value;
     },
@@ -943,7 +942,7 @@ var CFFDict = function CFFDictClosure() {
     },
     getByName: function CFFDict_getByName(name) {
       if (!(name in this.nameToKeyMap)) {
-        (0, _util.error)('Invalid dictionary name "' + name + '"');
+        throw new _util.FormatError('Invalid dictionary name ' + name + '"');
       }
       var key = this.nameToKeyMap[name];
       if (!(key in this.values)) {
@@ -1052,7 +1051,7 @@ var CFFOffsetTracker = function CFFOffsetTrackerClosure() {
     },
     track: function CFFOffsetTracker_track(key, location) {
       if (key in this.offsets) {
-        (0, _util.error)('Already tracking location of ' + key);
+        throw new _util.FormatError('Already tracking location of ' + key);
       }
       this.offsets[key] = location;
     },
@@ -1063,7 +1062,7 @@ var CFFOffsetTracker = function CFFOffsetTrackerClosure() {
     },
     setEntryLocation: function CFFOffsetTracker_setEntryLocation(key, values, output) {
       if (!(key in this.offsets)) {
-        (0, _util.error)('Not tracking location of ' + key);
+        throw new _util.FormatError('Not tracking location of ' + key);
       }
       var data = output.data;
       var dataOffset = this.offsets[key];
@@ -1075,7 +1074,7 @@ var CFFOffsetTracker = function CFFOffsetTrackerClosure() {
         var offset3 = offset0 + 3;
         var offset4 = offset0 + 4;
         if (data[offset0] !== 0x1d || data[offset1] !== 0 || data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
-          (0, _util.error)('writing to an offset that is not empty');
+          throw new _util.FormatError('writing to an offset that is not empty');
         }
         var value = values[i];
         data[offset0] = 0x1d;
@@ -1311,8 +1310,7 @@ var CFFCompiler = function CFFCompilerClosure() {
               }
               break;
             default:
-              (0, _util.error)('Unknown data type of ' + type);
-              break;
+              throw new _util.FormatError('Unknown data type of ' + type);
           }
         }
         out = out.concat(dict.opcodes[key]);

+ 11 - 11
lib/core/cmap.js

@@ -153,16 +153,16 @@ var IdentityCMap = function IdentityCMapClosure() {
   IdentityCMap.prototype = {
     addCodespaceRange: CMap.prototype.addCodespaceRange,
     mapCidRange: function mapCidRange(low, high, dstLow) {
-      (0, _util.error)('should not call mapCidRange');
+      throw new Error('should not call mapCidRange');
     },
     mapBfRange: function mapBfRange(low, high, dstLow) {
-      (0, _util.error)('should not call mapBfRange');
+      throw new Error('should not call mapBfRange');
     },
     mapBfRangeToArray: function mapBfRangeToArray(low, high, array) {
-      (0, _util.error)('should not call mapBfRangeToArray');
+      throw new Error('should not call mapBfRangeToArray');
     },
     mapOne: function mapOne(src, dst) {
-      (0, _util.error)('should not call mapCidOne');
+      throw new Error('should not call mapCidOne');
     },
     lookup: function lookup(code) {
       return (0, _util.isInt)(code) && code <= 0xffff ? code : undefined;
@@ -191,7 +191,7 @@ var IdentityCMap = function IdentityCMapClosure() {
       return 0x10000;
     },
     get isIdentityCMap() {
-      (0, _util.error)('should not access .isIdentityCMap');
+      throw new Error('should not access .isIdentityCMap');
     }
   };
   return IdentityCMap;
@@ -250,7 +250,7 @@ var BinaryCMapReader = function BinaryCMapReaderClosure() {
       do {
         var b = this.readByte();
         if (b < 0) {
-          (0, _util.error)('unexpected EOF in bcmap');
+          throw new _util.FormatError('unexpected EOF in bcmap');
         }
         last = !(b & 0x80);
         n = n << 7 | b & 0x7F;
@@ -272,7 +272,7 @@ var BinaryCMapReader = function BinaryCMapReaderClosure() {
       do {
         var b = this.readByte();
         if (b < 0) {
-          (0, _util.error)('unexpected EOF in bcmap');
+          throw new _util.FormatError('unexpected EOF in bcmap');
         }
         last = !(b & 0x80);
         stack[sp++] = b & 0x7F;
@@ -466,12 +466,12 @@ var CMapFactory = function CMapFactoryClosure() {
   }
   function expectString(obj) {
     if (!(0, _util.isString)(obj)) {
-      (0, _util.error)('Malformed CMap: expected string.');
+      throw new _util.FormatError('Malformed CMap: expected string.');
     }
   }
   function expectInt(obj) {
     if (!(0, _util.isInt)(obj)) {
-      (0, _util.error)('Malformed CMap: expected int.');
+      throw new _util.FormatError('Malformed CMap: expected int.');
     }
   }
   function parseBfChar(cMap, lexer) {
@@ -521,7 +521,7 @@ var CMapFactory = function CMapFactoryClosure() {
         break;
       }
     }
-    (0, _util.error)('Invalid bf range.');
+    throw new _util.FormatError('Invalid bf range.');
   }
   function parseCidChar(cMap, lexer) {
     while (true) {
@@ -580,7 +580,7 @@ var CMapFactory = function CMapFactoryClosure() {
       var high = strToInt(obj);
       cMap.addCodespaceRange(obj.length, low, high);
     }
-    (0, _util.error)('Invalid codespace range.');
+    throw new _util.FormatError('Invalid codespace range.');
   }
   function parseWMode(cMap, lexer) {
     var obj = lexer.getObj();

+ 17 - 19
lib/core/colorspace.js

@@ -53,7 +53,7 @@ var ColorSpace = function ColorSpaceClosure() {
     }
   }
   function ColorSpace() {
-    (0, _util.error)('should not call ColorSpace constructor');
+    throw new Error('should not call ColorSpace constructor');
   }
   ColorSpace.prototype = {
     getRgb: function ColorSpace_getRgb(src, srcOffset) {
@@ -62,13 +62,13 @@ var ColorSpace = function ColorSpaceClosure() {
       return rgb;
     },
     getRgbItem: function ColorSpace_getRgbItem(src, srcOffset, dest, destOffset) {
-      (0, _util.error)('Should not call ColorSpace.getRgbItem');
+      throw new Error('Should not call ColorSpace.getRgbItem');
     },
     getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
-      (0, _util.error)('Should not call ColorSpace.getRgbBuffer');
+      throw new Error('Should not call ColorSpace.getRgbBuffer');
     },
     getOutputLength: function ColorSpace_getOutputLength(inputLength, alpha01) {
-      (0, _util.error)('Should not call ColorSpace.getOutputLength');
+      throw new Error('Should not call ColorSpace.getOutputLength');
     },
     isPassthrough: function ColorSpace_isPassthrough(bits) {
       return false;
@@ -184,9 +184,8 @@ var ColorSpace = function ColorSpaceClosure() {
         var range = IR[3];
         return new LabCS(whitePoint, blackPoint, range);
       default:
-        (0, _util.error)('Unknown name ' + name);
+        throw new _util.FormatError('Unknown colorspace name: ' + name);
     }
-    return null;
   };
   ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
     if ((0, _primitives.isName)(cs)) {
@@ -213,9 +212,10 @@ var ColorSpace = function ColorSpaceClosure() {
         case 'Pattern':
           return ['PatternCS', null];
         default:
-          (0, _util.error)('unrecognized colorspace ' + cs.name);
+          throw new _util.FormatError('unrecognized colorspace ' + cs.name);
       }
-    } else if ((0, _util.isArray)(cs)) {
+    }
+    if ((0, _util.isArray)(cs)) {
       var mode = xref.fetchIfRef(cs[0]).name;
       var numComps, params, alt, whitePoint, blackPoint, gamma;
       switch (mode) {
@@ -291,12 +291,10 @@ var ColorSpace = function ColorSpaceClosure() {
           var range = params.getArray('Range');
           return ['LabCS', whitePoint, blackPoint, range];
         default:
-          (0, _util.error)('unimplemented color space object "' + mode + '"');
+          throw new _util.FormatError('unimplemented color space object "' + mode + '"');
       }
-    } else {
-      (0, _util.error)('unrecognized color space object: "' + cs + '"');
     }
-    return null;
+    throw new _util.FormatError('unrecognized color space object: "' + cs + '"');
   };
   ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {
     if (!(0, _util.isArray)(decode)) {
@@ -417,7 +415,7 @@ var IndexedCS = function IndexedCSClosure() {
     } else if (lookup instanceof Uint8Array || lookup instanceof Array) {
       this.lookup = lookup;
     } else {
-      (0, _util.error)('Unrecognized lookup table: ' + lookup);
+      throw new _util.FormatError('Unrecognized lookup table: ' + lookup);
     }
   }
   IndexedCS.prototype = {
@@ -582,7 +580,7 @@ var CalGrayCS = function CalGrayCSClosure() {
     this.numComps = 1;
     this.defaultColor = new Float32Array(this.numComps);
     if (!whitePoint) {
-      (0, _util.error)('WhitePoint missing - required for color space CalGray');
+      throw new _util.FormatError('WhitePoint missing - required for color space CalGray');
     }
     blackPoint = blackPoint || [0, 0, 0];
     gamma = gamma || 1;
@@ -594,7 +592,7 @@ var CalGrayCS = function CalGrayCSClosure() {
     this.ZB = blackPoint[2];
     this.G = gamma;
     if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
-      (0, _util.error)('Invalid WhitePoint components for ' + this.name + ', no fallback available');
+      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');
@@ -656,7 +654,7 @@ var CalRGBCS = function CalRGBCSClosure() {
     this.numComps = 3;
     this.defaultColor = new Float32Array(this.numComps);
     if (!whitePoint) {
-      (0, _util.error)('WhitePoint missing - required for color space CalRGB');
+      throw new _util.FormatError('WhitePoint missing - required for color space CalRGB');
     }
     blackPoint = blackPoint || new Float32Array(3);
     gamma = gamma || new Float32Array([1, 1, 1]);
@@ -682,7 +680,7 @@ var CalRGBCS = function CalRGBCSClosure() {
     this.MYC = matrix[7];
     this.MZC = matrix[8];
     if (XW < 0 || ZW < 0 || YW !== 1) {
-      (0, _util.error)('Invalid WhitePoint components for ' + this.name + ', no fallback available');
+      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');
@@ -842,7 +840,7 @@ var LabCS = function LabCSClosure() {
     this.numComps = 3;
     this.defaultColor = new Float32Array(this.numComps);
     if (!whitePoint) {
-      (0, _util.error)('WhitePoint missing - required for color space Lab');
+      throw new _util.FormatError('WhitePoint missing - required for color space Lab');
     }
     blackPoint = blackPoint || [0, 0, 0];
     range = range || [-100, 100, -100, 100];
@@ -857,7 +855,7 @@ var LabCS = function LabCSClosure() {
     this.YB = blackPoint[1];
     this.ZB = blackPoint[2];
     if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
-      (0, _util.error)('Invalid WhitePoint components, no fallback available');
+      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');

+ 4 - 4
lib/core/crypto.js

@@ -1442,12 +1442,12 @@ var CipherTransformFactory = function CipherTransformFactoryClosure() {
   function CipherTransformFactory(dict, fileId, password) {
     var filter = dict.get('Filter');
     if (!(0, _primitives.isName)(filter, 'Standard')) {
-      (0, _util.error)('unknown encryption method');
+      throw new _util.FormatError('unknown encryption method');
     }
     this.dict = dict;
     var algorithm = dict.get('V');
     if (!(0, _util.isInt)(algorithm) || algorithm !== 1 && algorithm !== 2 && algorithm !== 4 && algorithm !== 5) {
-      (0, _util.error)('unsupported encryption algorithm');
+      throw new _util.FormatError('unsupported encryption algorithm');
     }
     this.algorithm = algorithm;
     var keyLength = dict.get('Length');
@@ -1468,7 +1468,7 @@ var CipherTransformFactory = function CipherTransformFactoryClosure() {
       }
     }
     if (!(0, _util.isInt)(keyLength) || keyLength < 40 || keyLength % 8 !== 0) {
-      (0, _util.error)('invalid key length');
+      throw new _util.FormatError('invalid key length');
     }
     var ownerPassword = (0, _util.stringToBytes)(dict.get('O')).subarray(0, 32);
     var userPassword = (0, _util.stringToBytes)(dict.get('U')).subarray(0, 32);
@@ -1571,7 +1571,7 @@ var CipherTransformFactory = function CipherTransformFactoryClosure() {
         return new AES256Cipher(key);
       };
     }
-    (0, _util.error)('Unknown crypto method');
+    throw new _util.FormatError('Unknown crypto method');
   }
   CipherTransformFactory.prototype = {
     createCipherTransform: function CipherTransformFactory_createCipherTransform(num, gen) {

+ 1 - 1
lib/core/document.js

@@ -312,7 +312,7 @@ var PDFDocument = function PDFDocumentClosure() {
     } else if ((0, _util.isArrayBuffer)(arg)) {
       stream = new _stream.Stream(arg);
     } else {
-      (0, _util.error)('PDFDocument: Unknown argument type');
+      throw new Error('PDFDocument: Unknown argument type');
     }
     (0, _util.assert)(stream.length > 0, 'stream must have data');
     this.pdfManager = pdfManager;

+ 3 - 3
lib/core/evaluator.js

@@ -779,7 +779,7 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
                   (0, _util.info)('Ignored XObject subtype PS');
                   continue;
                 } else {
-                  (0, _util.error)('Unhandled XObject subtype ' + type.name);
+                  throw new _util.FormatError('Unhandled XObject subtype ' + type.name);
                 }
               }
               break;
@@ -1513,14 +1513,14 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
               } else if ((0, _primitives.isName)(data)) {
                 differences[index++] = data.name;
               } else {
-                (0, _util.error)('Invalid entry in \'Differences\' array: ' + data);
+                throw new _util.FormatError('Invalid entry in \'Differences\' array: ' + data);
               }
             }
           }
         } else if ((0, _primitives.isName)(encoding)) {
           baseEncodingName = encoding.name;
         } else {
-          (0, _util.error)('Encoding is not a Name nor a Dict');
+          throw new _util.FormatError('Encoding is not a Name nor a Dict');
         }
         if (baseEncodingName !== 'MacRomanEncoding' && baseEncodingName !== 'MacExpertEncoding' && baseEncodingName !== 'WinAnsiEncoding') {
           baseEncodingName = null;

+ 4 - 4
lib/core/font_renderer.js

@@ -82,7 +82,7 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
       }
       return ranges;
     }
-    (0, _util.error)('not supported cmap: ' + format);
+    throw new _util.FormatError('unsupported cmap: ' + format);
   }
   function parseCff(data, start, end, seacAnalysisEnabled) {
     var properties = {};
@@ -455,7 +455,7 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
                 bezierCurveTo(xa, ya, xb, yb, x, y);
                 break;
               default:
-                (0, _util.error)('unknown operator: 12 ' + v);
+                throw new _util.FormatError('unknown operator: 12 ' + v);
             }
             break;
           case 14:
@@ -616,7 +616,7 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
             break;
           default:
             if (v < 32) {
-              (0, _util.error)('unknown operator: ' + v);
+              throw new _util.FormatError('unknown operator: ' + v);
             }
             if (v < 247) {
               stack.push(v - 139);
@@ -675,7 +675,7 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
       return cmds;
     },
     compileGlyphImpl: function compileGlyphImpl() {
-      (0, _util.error)('Children classes should implement this.');
+      throw new Error('Children classes should implement this.');
     },
     hasBuiltPath: function hasBuiltPath(unicode) {
       var cmap = lookupCmap(this.cmap, unicode);

+ 7 - 8
lib/core/fonts.js

@@ -209,7 +209,7 @@ var IdentityToUnicodeMap = function IdentityToUnicodeMapClosure() {
       return (0, _util.isInt)(v) && v >= this.firstChar && v <= this.lastChar ? v : -1;
     },
     amend: function amend(map) {
-      (0, _util.error)('Should not call amend()');
+      throw new Error('Should not call amend()');
     }
   };
   return IdentityToUnicodeMap;
@@ -474,8 +474,7 @@ var Font = function FontClosure() {
         }
         break;
       default:
-        (0, _util.error)('Font ' + type + ' is not supported');
-        break;
+        throw new _util.FormatError('Font ' + type + ' is not supported');
     }
     this.data = data;
     this.fontType = getFontType(type, subtype);
@@ -767,7 +766,7 @@ var Font = function FontClosure() {
         } else if (position < 123) {
           ulUnicodeRange4 |= 1 << position - 96;
         } else {
-          (0, _util.error)('Unicode ranges Bits > 123 are reserved for internal usage');
+          throw new _util.FormatError('Unicode ranges Bits > 123 are reserved for internal usage');
         }
       }
     } else {
@@ -1608,7 +1607,7 @@ var Font = function FontClosure() {
         this.isOpenType = true;
       } else {
         if (!tables['loca']) {
-          (0, _util.error)('Required "loca" table is not found');
+          throw new _util.FormatError('Required "loca" table is not found');
         }
         if (!tables['glyf']) {
           (0, _util.warn)('Required "glyf" table is not found -- trying to recover.');
@@ -1620,7 +1619,7 @@ var Font = function FontClosure() {
         this.isOpenType = false;
       }
       if (!tables['maxp']) {
-        (0, _util.error)('Required "maxp" table is not found');
+        throw new _util.FormatError('Required "maxp" table is not found');
       }
       font.pos = (font.start || 0) + tables['maxp'].offset;
       var version = font.getInt32();
@@ -1651,7 +1650,7 @@ var Font = function FontClosure() {
       }
       sanitizeMetrics(font, tables['hhea'], tables['hmtx'], numGlyphs);
       if (!tables['head']) {
-        (0, _util.error)('Required "head" table is not found');
+        throw new _util.FormatError('Required "head" table is not found');
       }
       sanitizeHead(tables['head'], numGlyphs, isTrueType ? tables['loca'].length : 0);
       var missingGlyphs = Object.create(null);
@@ -1660,7 +1659,7 @@ var Font = function FontClosure() {
         missingGlyphs = sanitizeGlyphLocations(tables['loca'], tables['glyf'], numGlyphs, isGlyphLocationsLong, hintsValid, dupFirstEntry);
       }
       if (!tables['hhea']) {
-        (0, _util.error)('Required "hhea" table is not found');
+        throw new _util.FormatError('Required "hhea" table is not found');
       }
       if (tables['hhea'].data[10] === 0 && tables['hhea'].data[11] === 0) {
         tables['hhea'].data[10] = 0xFF;

+ 11 - 12
lib/core/function.js

@@ -67,7 +67,7 @@ var PDFFunction = function PDFFunctionClosure() {
       var typeNum = dict.get('FunctionType');
       var typeFn = types[typeNum];
       if (!typeFn) {
-        (0, _util.error)('Unknown type of function');
+        throw new _util.FormatError('Unknown type of function');
       }
       return typeFn.call(this, fn, dict, xref);
     },
@@ -117,7 +117,7 @@ var PDFFunction = function PDFFunctionClosure() {
       var domain = dict.getArray('Domain');
       var range = dict.getArray('Range');
       if (!domain || !range) {
-        (0, _util.error)('No domain or range');
+        throw new _util.FormatError('No domain or range');
       }
       var inputSize = domain.length / 2;
       var outputSize = range.length / 2;
@@ -208,7 +208,7 @@ var PDFFunction = function PDFFunctionClosure() {
       var c1 = dict.getArray('C1') || [1];
       var n = dict.get('N');
       if (!(0, _util.isArray)(c0) || !(0, _util.isArray)(c1)) {
-        (0, _util.error)('Illegal dictionary for interpolated function');
+        throw new _util.FormatError('Illegal dictionary for interpolated function');
       }
       var length = c0.length;
       var diff = [];
@@ -232,11 +232,11 @@ var PDFFunction = function PDFFunctionClosure() {
     constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {
       var domain = dict.getArray('Domain');
       if (!domain) {
-        (0, _util.error)('No domain');
+        throw new _util.FormatError('No domain');
       }
       var inputSize = domain.length / 2;
       if (inputSize !== 1) {
-        (0, _util.error)('Bad domain for stiched function');
+        throw new _util.FormatError('Bad domain for stiched function');
       }
       var fnRefs = dict.get('Functions');
       var fns = [];
@@ -290,10 +290,10 @@ var PDFFunction = function PDFFunctionClosure() {
       var domain = dict.getArray('Domain');
       var range = dict.getArray('Range');
       if (!domain) {
-        (0, _util.error)('No domain.');
+        throw new _util.FormatError('No domain.');
       }
       if (!range) {
-        (0, _util.error)('No range.');
+        throw new _util.FormatError('No range.');
       }
       var lexer = new _ps_parser.PostScriptLexer(fn);
       var parser = new _ps_parser.PostScriptParser(lexer);
@@ -376,19 +376,19 @@ var PostScriptStack = function PostScriptStackClosure() {
   PostScriptStack.prototype = {
     push: function PostScriptStack_push(value) {
       if (this.stack.length >= MAX_STACK_SIZE) {
-        (0, _util.error)('PostScript function stack overflow.');
+        throw new Error('PostScript function stack overflow.');
       }
       this.stack.push(value);
     },
     pop: function PostScriptStack_pop() {
       if (this.stack.length <= 0) {
-        (0, _util.error)('PostScript function stack underflow.');
+        throw new Error('PostScript function stack underflow.');
       }
       return this.stack.pop();
     },
     copy: function PostScriptStack_copy(n) {
       if (this.stack.length + n >= MAX_STACK_SIZE) {
-        (0, _util.error)('PostScript function stack overflow.');
+        throw new Error('PostScript function stack overflow.');
       }
       var stack = this.stack;
       for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
@@ -647,8 +647,7 @@ var PostScriptEvaluator = function PostScriptEvaluatorClosure() {
             }
             break;
           default:
-            (0, _util.error)('Unknown operator ' + operator);
-            break;
+            throw new _util.FormatError('Unknown operator ' + operator);
         }
       }
       return stack.stack;

+ 5 - 5
lib/core/image.js

@@ -83,7 +83,7 @@ var PDFImage = function PDFImageClosure() {
     this.width = dict.get('Width', 'W');
     this.height = dict.get('Height', 'H');
     if (this.width < 1 || this.height < 1) {
-      (0, _util.error)('Invalid image width: ' + this.width + ' or height: ' + this.height);
+      throw new _util.FormatError('Invalid image width: ' + this.width + ' or ' + ('height: ' + this.height));
     }
     this.interpolate = dict.get('Interpolate', 'I') || false;
     this.imageMask = dict.get('ImageMask', 'IM') || false;
@@ -95,7 +95,7 @@ var PDFImage = function PDFImageClosure() {
         if (this.imageMask) {
           bitsPerComponent = 1;
         } else {
-          (0, _util.error)('Bits per component missing in image: ' + this.imageMask);
+          throw new _util.FormatError('Bits per component missing in image: ' + this.imageMask);
         }
       }
     }
@@ -115,7 +115,7 @@ var PDFImage = function PDFImageClosure() {
             colorSpace = _primitives.Name.get('DeviceCMYK');
             break;
           default:
-            (0, _util.error)('JPX images with ' + this.numComps + ' color components not supported.');
+            throw new Error('JPX images with ' + this.numComps + ' ' + 'color components not supported.');
         }
       }
       this.colorSpace = _colorspace.ColorSpace.parse(colorSpace, xref, res);
@@ -343,7 +343,7 @@ var PDFImage = function PDFImageClosure() {
             alphaBuf[i] = opacity;
           }
         } else {
-          (0, _util.error)('Unknown mask format.');
+          throw new _util.FormatError('Unknown mask format.');
         }
       }
       if (alphaBuf) {
@@ -457,7 +457,7 @@ var PDFImage = function PDFImageClosure() {
     fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) {
       var numComps = this.numComps;
       if (numComps !== 1) {
-        (0, _util.error)('Reading gray scale from a color image: ' + numComps);
+        throw new _util.FormatError('Reading gray scale from a color image: ' + numComps);
       }
       var width = this.width;
       var height = this.height;

+ 25 - 16
lib/core/jbig2.js

@@ -23,6 +23,15 @@ var _util = require('../shared/util');
 
 var _arithmetic_decoder = require('./arithmetic_decoder');
 
+var Jbig2Error = function Jbig2ErrorClosure() {
+  function Jbig2Error(msg) {
+    this.message = 'JBIG2 error: ' + msg;
+  }
+  Jbig2Error.prototype = new Error();
+  Jbig2Error.prototype.name = 'Jbig2Error';
+  Jbig2Error.constructor = Jbig2Error;
+  return Jbig2Error;
+}();
 var Jbig2Image = function Jbig2ImageClosure() {
   function ContextCache() {}
   ContextCache.prototype = {
@@ -302,7 +311,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
   }
   function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at, decodingContext) {
     if (mmr) {
-      (0, _util.error)('JBIG2 error: MMR encoding is not supported');
+      throw new Jbig2Error('MMR encoding is not supported');
     }
     if (templateIndex === 0 && !skip && !prediction && at.length === 4 && at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 && at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) {
       return decodeBitmapTemplate0(width, height, decodingContext);
@@ -443,7 +452,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
         var sltp = decoder.readBit(contexts, pseudoPixelContext);
         ltp ^= sltp;
         if (ltp) {
-          (0, _util.error)('JBIG2 error: prediction is not supported');
+          throw new Jbig2Error('prediction is not supported');
         }
       }
       var row = new Uint8Array(width);
@@ -477,7 +486,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
   }
   function decodeSymbolDictionary(huffman, refinement, symbols, numberOfNewSymbols, numberOfExportedSymbols, huffmanTables, templateIndex, at, refinementTemplateIndex, refinementAt, decodingContext) {
     if (huffman) {
-      (0, _util.error)('JBIG2 error: huffman is not supported');
+      throw new Jbig2Error('huffman is not supported');
     }
     var newSymbols = [];
     var currentHeight = 0;
@@ -537,7 +546,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
   }
   function decodeTextRegion(huffman, refinement, width, height, defaultPixelValue, numberOfSymbolInstances, stripSize, inputSymbols, symbolCodeLength, transposed, dsOffset, referenceCorner, combinationOperator, huffmanTables, refinementTemplateIndex, refinementAt, decodingContext) {
     if (huffman) {
-      (0, _util.error)('JBIG2 error: huffman is not supported');
+      throw new Jbig2Error('huffman is not supported');
     }
     var bitmap = [];
     var i, row;
@@ -601,7 +610,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
                 }
                 break;
               default:
-                (0, _util.error)('JBIG2 error: operator ' + combinationOperator + ' is not supported');
+                throw new Jbig2Error('operator ' + combinationOperator + ' is not supported');
             }
           }
           currentS += symbolHeight - 1;
@@ -624,7 +633,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
                 }
                 break;
               default:
-                (0, _util.error)('JBIG2 error: operator ' + combinationOperator + ' is not supported');
+                throw new Jbig2Error('operator ' + combinationOperator + ' is not supported');
             }
           }
           currentS += symbolWidth - 1;
@@ -645,7 +654,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
     var flags = data[start + 4];
     var segmentType = flags & 0x3F;
     if (!SegmentTypes[segmentType]) {
-      (0, _util.error)('JBIG2 error: invalid segment type: ' + segmentType);
+      throw new Jbig2Error('invalid segment type: ' + segmentType);
     }
     segmentHeader.type = segmentType;
     segmentHeader.typeName = SegmentTypes[segmentType];
@@ -664,7 +673,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
         retainBits.push(data[position++]);
       }
     } else if (referredFlags === 5 || referredFlags === 6) {
-      (0, _util.error)('JBIG2 error: invalid referred-to flags');
+      throw new Jbig2Error('invalid referred-to flags');
     }
     segmentHeader.retainBits = retainBits;
     var referredToSegmentNumberSize = segmentHeader.number <= 256 ? 1 : segmentHeader.number <= 65536 ? 2 : 4;
@@ -710,10 +719,10 @@ var Jbig2Image = function Jbig2ImageClosure() {
           }
         }
         if (segmentHeader.length === 0xFFFFFFFF) {
-          (0, _util.error)('JBIG2 error: segment end was not found');
+          throw new Jbig2Error('segment end was not found');
         }
       } else {
-        (0, _util.error)('JBIG2 error: invalid unknown segment length');
+        throw new Jbig2Error('invalid unknown segment length');
       }
     }
     segmentHeader.headerEnd = position;
@@ -850,7 +859,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
         textRegion.numberOfSymbolInstances = (0, _util.readUint32)(data, position);
         position += 4;
         if (textRegion.huffman) {
-          (0, _util.error)('JBIG2 error: huffman is not supported');
+          throw new Jbig2Error('huffman is not supported');
         }
         args = [textRegion, header.referredTo, data, position, end];
         break;
@@ -906,7 +915,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
       case 62:
         break;
       default:
-        (0, _util.error)('JBIG2 error: segment type ' + header.typeName + '(' + header.type + ') is not implemented');
+        throw new Jbig2Error('segment type ' + header.typeName + '(' + header.type + ')' + ' is not implemented');
     }
     var callbackName = 'on' + header.typeName;
     if (callbackName in visitor) {
@@ -921,7 +930,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
   function parseJbig2(data, start, end) {
     var position = start;
     if (data[position] !== 0x97 || data[position + 1] !== 0x4A || data[position + 2] !== 0x42 || data[position + 3] !== 0x32 || data[position + 4] !== 0x0D || data[position + 5] !== 0x0A || data[position + 6] !== 0x1A || data[position + 7] !== 0x0A) {
-      (0, _util.error)('JBIG2 error: invalid header');
+      throw new Jbig2Error('invalid header');
     }
     var header = {};
     position += 8;
@@ -932,7 +941,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
       position += 4;
     }
     readSegments(header, data, position, end);
-    (0, _util.error)('Not implemented');
+    throw new Error('Not implemented');
   }
   function parseJbig2Chunks(chunks) {
     var visitor = new SimpleSegmentVisitor();
@@ -1002,7 +1011,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
           }
           break;
         default:
-          (0, _util.error)('JBIG2 error: operator ' + combinationOperator + ' is not supported');
+          throw new Jbig2Error('operator ' + combinationOperator + ' is not supported');
       }
     },
     onImmediateGenericRegion: function SimpleSegmentVisitor_onImmediateGenericRegion(region, data, start, end) {
@@ -1017,7 +1026,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
     onSymbolDictionary: function SimpleSegmentVisitor_onSymbolDictionary(dictionary, currentSegment, referredSegments, data, start, end) {
       var huffmanTables;
       if (dictionary.huffman) {
-        (0, _util.error)('JBIG2 error: huffman is not supported');
+        throw new Jbig2Error('huffman is not supported');
       }
       var symbols = this.symbols;
       if (!symbols) {

+ 19 - 10
lib/core/jpg.js

@@ -23,6 +23,15 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
 
 var _util = require('../shared/util');
 
+var JpegError = function JpegErrorClosure() {
+  function JpegError(msg) {
+    this.message = 'JPEG error: ' + msg;
+  }
+  JpegError.prototype = new Error();
+  JpegError.prototype.name = 'JpegError';
+  JpegError.constructor = JpegError;
+  return JpegError;
+}();
 var JpegImage = function JpegImageClosure() {
   var dctZigZag = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]);
   var dctCos1 = 4017;
@@ -100,7 +109,7 @@ var JpegImage = function JpegImageClosure() {
       if (bitsData === 0xFF) {
         var nextByte = data[offset++];
         if (nextByte) {
-          (0, _util.error)('JPEG error: unexpected marker ' + (bitsData << 8 | nextByte).toString(16));
+          throw new JpegError('unexpected marker ' + (bitsData << 8 | nextByte).toString(16));
         }
       }
       bitsCount = 7;
@@ -114,7 +123,7 @@ var JpegImage = function JpegImageClosure() {
           return node;
         }
         if ((typeof node === 'undefined' ? 'undefined' : _typeof(node)) !== 'object') {
-          (0, _util.error)('JPEG error: invalid huffman sequence');
+          throw new JpegError('invalid huffman sequence');
         }
       }
     }
@@ -217,7 +226,7 @@ var JpegImage = function JpegImageClosure() {
               }
             } else {
               if (s !== 1) {
-                (0, _util.error)('JPEG error: invalid ACn encoding');
+                throw new JpegError('invalid ACn encoding');
               }
               successiveACNextValue = receiveAndExtend(s);
               successiveACState = r ? 2 : 3;
@@ -327,7 +336,7 @@ var JpegImage = function JpegImageClosure() {
       }
       var marker = fileMarker && fileMarker.marker;
       if (!marker || marker <= 0xFF00) {
-        (0, _util.error)('JPEG error: marker was not found');
+        throw new JpegError('marker was not found');
       }
       if (marker >= 0xFFD0 && marker <= 0xFFD7) {
         offset += 2;
@@ -349,7 +358,7 @@ var JpegImage = function JpegImageClosure() {
     var p0, p1, p2, p3, p4, p5, p6, p7;
     var t;
     if (!qt) {
-      (0, _util.error)('JPEG error: missing required Quantization Table.');
+      throw new JpegError('missing required Quantization Table.');
     }
     for (var row = 0; row < 64; row += 8) {
       p0 = blockData[blockBufferOffset + row];
@@ -581,7 +590,7 @@ var JpegImage = function JpegImageClosure() {
           huffmanTablesDC = [];
       var fileMarker = readUint16();
       if (fileMarker !== 0xFFD8) {
-        (0, _util.error)('JPEG error: SOI not found');
+        throw new JpegError('SOI not found');
       }
       fileMarker = readUint16();
       while (fileMarker !== 0xFFD9) {
@@ -650,7 +659,7 @@ var JpegImage = function JpegImageClosure() {
                   tableData[z] = readUint16();
                 }
               } else {
-                (0, _util.error)('JPEG error: DQT - invalid table spec');
+                throw new JpegError('DQT - invalid table spec');
               }
               quantizationTables[quantizationTableSpec & 15] = tableData;
             }
@@ -659,7 +668,7 @@ var JpegImage = function JpegImageClosure() {
           case 0xFFC1:
           case 0xFFC2:
             if (frame) {
-              (0, _util.error)('JPEG error: Only single frame JPEGs supported');
+              throw new JpegError('Only single frame JPEGs supported');
             }
             readUint16();
             frame = {};
@@ -748,7 +757,7 @@ var JpegImage = function JpegImageClosure() {
               offset -= 3;
               break;
             }
-            (0, _util.error)('JPEG error: unknown marker ' + fileMarker.toString(16));
+            throw new JpegError('unknown marker ' + fileMarker.toString(16));
         }
         fileMarker = readUint16();
       }
@@ -892,7 +901,7 @@ var JpegImage = function JpegImageClosure() {
     },
     getData: function getData(width, height, forceRGBoutput) {
       if (this.numComponents > 4) {
-        (0, _util.error)('JPEG error: Unsupported color mode');
+        throw new JpegError('Unsupported color mode');
       }
       var data = this._getLinearizedBlockData(width, height);
       if (this.numComponents === 1 && forceRGBoutput) {

+ 19 - 10
lib/core/jpx.js

@@ -23,6 +23,15 @@ var _util = require('../shared/util');
 
 var _arithmetic_decoder = require('./arithmetic_decoder');
 
+var JpxError = function JpxErrorClosure() {
+  function JpxError(msg) {
+    this.message = 'JPX error: ' + msg;
+  }
+  JpxError.prototype = new Error();
+  JpxError.prototype.name = 'JpxError';
+  JpxError.constructor = JpxError;
+  return JpxError;
+}();
 var JpxImage = function JpxImageClosure() {
   var SubbandsGainLog2 = {
     'LL': 0,
@@ -56,7 +65,7 @@ var JpxImage = function JpxImageClosure() {
           lbox = length - position + headerSize;
         }
         if (lbox < headerSize) {
-          (0, _util.error)('JPX Error: Invalid box field size');
+          throw new JpxError('Invalid box field size');
         }
         var dataLength = lbox - headerSize;
         var jumpDataLength = true;
@@ -126,7 +135,7 @@ var JpxImage = function JpxImageClosure() {
           return;
         }
       }
-      (0, _util.error)('JPX Error: No size marker found in JPX stream');
+      throw new JpxError('No size marker found in JPX stream');
     },
     parseCodestream: function JpxImage_parseCodestream(data, start, end) {
       var context = {};
@@ -378,7 +387,7 @@ var JpxImage = function JpxImageClosure() {
         }
       } catch (e) {
         if (doNotRecover || this.failOnCorruptedImage) {
-          (0, _util.error)('JPX Error: ' + e.message);
+          throw new JpxError(e.message);
         } else {
           (0, _util.warn)('JPX: Trying to recover from: ' + e.message);
         }
@@ -589,7 +598,7 @@ var JpxImage = function JpxImageClosure() {
         }
         r = 0;
       }
-      (0, _util.error)('JPX Error: Out of packets');
+      throw new JpxError('Out of packets');
     };
   }
   function ResolutionLayerComponentPositionIterator(context) {
@@ -627,7 +636,7 @@ var JpxImage = function JpxImageClosure() {
         }
         l = 0;
       }
-      (0, _util.error)('JPX Error: Out of packets');
+      throw new JpxError('Out of packets');
     };
   }
   function ResolutionPositionComponentLayerIterator(context) {
@@ -681,7 +690,7 @@ var JpxImage = function JpxImageClosure() {
         }
         p = 0;
       }
-      (0, _util.error)('JPX Error: Out of packets');
+      throw new JpxError('Out of packets');
     };
   }
   function PositionComponentResolutionLayerIterator(context) {
@@ -723,7 +732,7 @@ var JpxImage = function JpxImageClosure() {
         }
         px = 0;
       }
-      (0, _util.error)('JPX Error: Out of packets');
+      throw new JpxError('Out of packets');
     };
   }
   function ComponentPositionResolutionLayerIterator(context) {
@@ -765,7 +774,7 @@ var JpxImage = function JpxImageClosure() {
         }
         py = 0;
       }
-      (0, _util.error)('JPX Error: Out of packets');
+      throw new JpxError('Out of packets');
     };
   }
   function getPrecinctIndexIfExist(pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
@@ -917,7 +926,7 @@ var JpxImage = function JpxImageClosure() {
         tile.packetsIterator = new ComponentPositionResolutionLayerIterator(context);
         break;
       default:
-        (0, _util.error)('JPX Error: Unsupported progression order ' + progressionOrder);
+        throw new JpxError('Unsupported progression order ' + progressionOrder);
     }
   }
   function parseTilePackets(context, data, offset, dataLength) {
@@ -1737,7 +1746,7 @@ var JpxImage = function JpxImageClosure() {
         var contexts = this.contexts;
         var symbol = decoder.readBit(contexts, UNIFORM_CONTEXT) << 3 | decoder.readBit(contexts, UNIFORM_CONTEXT) << 2 | decoder.readBit(contexts, UNIFORM_CONTEXT) << 1 | decoder.readBit(contexts, UNIFORM_CONTEXT);
         if (symbol !== 0xA) {
-          (0, _util.error)('JPX Error: Invalid segmentation symbol');
+          throw new JpxError('Invalid segmentation symbol');
         }
       }
     };

+ 21 - 21
lib/core/obj.js

@@ -488,7 +488,7 @@ var Catalog = function CatalogClosure() {
             }));
           }
           if (!found) {
-            (0, _util.error)('kid ref not found in parents kids');
+            throw new _util.FormatError('kid ref not found in parents kids');
           }
           return Promise.all(kidPromises).then(function () {
             return [total, parentRef];
@@ -665,7 +665,7 @@ var XRef = function XRefClosure() {
         this.encrypt = new _crypto.CipherTransformFactory(encrypt, fileId, this.pdfManager.password);
       }
       if (!(this.root = trailerDict.get('Root'))) {
-        (0, _util.error)('Invalid root reference');
+        throw new _util.FormatError('Invalid root reference');
       }
     },
     processXRefTable: function XRef_processXRefTable(parser) {
@@ -679,14 +679,14 @@ var XRef = function XRefClosure() {
       }
       var obj = this.readXRefTable(parser);
       if (!(0, _primitives.isCmd)(obj, 'trailer')) {
-        (0, _util.error)('Invalid XRef table: could not find trailer dictionary');
+        throw new _util.FormatError('Invalid XRef table: could not find trailer dictionary');
       }
       var dict = parser.getObj();
       if (!(0, _primitives.isDict)(dict) && dict.dict) {
         dict = dict.dict;
       }
       if (!(0, _primitives.isDict)(dict)) {
-        (0, _util.error)('Invalid XRef table: could not parse trailer dictionary');
+        throw new _util.FormatError('Invalid XRef table: could not parse trailer dictionary');
       }
       delete this.tableState;
       return dict;
@@ -709,7 +709,7 @@ var XRef = function XRefClosure() {
         var first = tableState.firstEntryNum;
         var count = tableState.entryCount;
         if (!(0, _util.isInt)(first) || !(0, _util.isInt)(count)) {
-          (0, _util.error)('Invalid XRef table: wrong types in subsection header');
+          throw new _util.FormatError('Invalid XRef table: wrong types in subsection header');
         }
         for (var i = tableState.entryNum; i < count; i++) {
           tableState.streamPos = stream.pos;
@@ -726,7 +726,7 @@ var XRef = function XRefClosure() {
             entry.uncompressed = true;
           }
           if (!(0, _util.isInt)(entry.offset) || !(0, _util.isInt)(entry.gen) || !(entry.free || entry.uncompressed)) {
-            (0, _util.error)('Invalid entry in XRef subsection: ' + first + ', ' + count);
+            throw new _util.FormatError('Invalid entry in XRef subsection: ' + first + ', ' + count);
           }
           if (i === 0 && entry.free && first === 1) {
             first = 0;
@@ -743,7 +743,7 @@ var XRef = function XRefClosure() {
         delete tableState.entryCount;
       }
       if (this.entries[0] && !this.entries[0].free) {
-        (0, _util.error)('Invalid XRef table: unexpected first object');
+        throw new _util.FormatError('Invalid XRef table: unexpected first object');
       }
       return obj;
     },
@@ -779,10 +779,10 @@ var XRef = function XRefClosure() {
         var first = entryRanges[0];
         var n = entryRanges[1];
         if (!(0, _util.isInt)(first) || !(0, _util.isInt)(n)) {
-          (0, _util.error)('Invalid XRef range fields: ' + first + ', ' + n);
+          throw new _util.FormatError('Invalid XRef range fields: ' + first + ', ' + n);
         }
         if (!(0, _util.isInt)(typeFieldWidth) || !(0, _util.isInt)(offsetFieldWidth) || !(0, _util.isInt)(generationFieldWidth)) {
-          (0, _util.error)('Invalid XRef entry fields length: ' + first + ', ' + n);
+          throw new _util.FormatError('Invalid XRef entry fields length: ' + first + ', ' + n);
         }
         for (i = streamState.entryNum; i < n; ++i) {
           streamState.entryNum = i;
@@ -815,7 +815,7 @@ var XRef = function XRefClosure() {
             case 2:
               break;
             default:
-              (0, _util.error)('Invalid XRef entry type: ' + type);
+              throw new _util.FormatError('Invalid XRef entry type: ' + type);
           }
           if (!this.entries[first + i]) {
             this.entries[first + i] = entry;
@@ -970,17 +970,17 @@ var XRef = function XRefClosure() {
             }
           } else if ((0, _util.isInt)(obj)) {
             if (!(0, _util.isInt)(parser.getObj()) || !(0, _primitives.isCmd)(parser.getObj(), 'obj') || !(0, _primitives.isStream)(obj = parser.getObj())) {
-              (0, _util.error)('Invalid XRef stream');
+              throw new _util.FormatError('Invalid XRef stream');
             }
             dict = this.processXRefStream(obj);
             if (!this.topDict) {
               this.topDict = dict;
             }
             if (!dict) {
-              (0, _util.error)('Failed to read XRef stream');
+              throw new _util.FormatError('Failed to read XRef stream');
             }
           } else {
-            (0, _util.error)('Invalid XRef stream header');
+            throw new _util.FormatError('Invalid XRef stream header');
           }
           obj = dict.get('Prev');
           if ((0, _util.isInt)(obj)) {
@@ -1045,7 +1045,7 @@ var XRef = function XRefClosure() {
       var gen = ref.gen;
       var num = ref.num;
       if (xrefEntry.gen !== gen) {
-        (0, _util.error)('inconsistent generation in XRef');
+        throw new _util.FormatError('inconsistent generation in XRef');
       }
       var stream = this.stream.makeSubStream(xrefEntry.offset + this.stream.start);
       var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
@@ -1053,7 +1053,7 @@ var XRef = function XRefClosure() {
       var obj2 = parser.getObj();
       var obj3 = parser.getObj();
       if (!(0, _util.isInt)(obj1) || parseInt(obj1, 10) !== num || !(0, _util.isInt)(obj2) || parseInt(obj2, 10) !== gen || !(0, _primitives.isCmd)(obj3)) {
-        (0, _util.error)('bad XRef entry');
+        throw new _util.FormatError('bad XRef entry');
       }
       if (!(0, _primitives.isCmd)(obj3, 'obj')) {
         if (obj3.cmd.indexOf('obj') === 0) {
@@ -1062,7 +1062,7 @@ var XRef = function XRefClosure() {
             return num;
           }
         }
-        (0, _util.error)('bad XRef entry');
+        throw new _util.FormatError('bad XRef entry');
       }
       if (this.encrypt && !suppressEncryption) {
         xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
@@ -1078,12 +1078,12 @@ var XRef = function XRefClosure() {
       var tableOffset = xrefEntry.offset;
       var stream = this.fetch(new _primitives.Ref(tableOffset, 0));
       if (!(0, _primitives.isStream)(stream)) {
-        (0, _util.error)('bad ObjStm stream');
+        throw new _util.FormatError('bad ObjStm stream');
       }
       var first = stream.dict.get('First');
       var n = stream.dict.get('N');
       if (!(0, _util.isInt)(first) || !(0, _util.isInt)(n)) {
-        (0, _util.error)('invalid first and n parameters for ObjStm stream');
+        throw new _util.FormatError('invalid first and n parameters for ObjStm stream');
       }
       var parser = new _parser.Parser(new _parser.Lexer(stream), false, this);
       parser.allowStreams = true;
@@ -1094,12 +1094,12 @@ var XRef = function XRefClosure() {
       for (i = 0; i < n; ++i) {
         num = parser.getObj();
         if (!(0, _util.isInt)(num)) {
-          (0, _util.error)('invalid object number in the ObjStm stream: ' + num);
+          throw new _util.FormatError('invalid object number in the ObjStm stream: ' + num);
         }
         nums.push(num);
         var offset = parser.getObj();
         if (!(0, _util.isInt)(offset)) {
-          (0, _util.error)('invalid object offset in the ObjStm stream: ' + offset);
+          throw new _util.FormatError('invalid object offset in the ObjStm stream: ' + offset);
         }
       }
       for (i = 0; i < n; ++i) {
@@ -1115,7 +1115,7 @@ var XRef = function XRefClosure() {
       }
       xrefEntry = entries[xrefEntry.gen];
       if (xrefEntry === undefined) {
-        (0, _util.error)('bad XRef entry for compressed object');
+        throw new _util.FormatError('bad XRef entry for compressed object');
       }
       return xrefEntry;
     },

+ 8 - 9
lib/core/parser.js

@@ -74,7 +74,7 @@ var Parser = function ParserClosure() {
             }
             if ((0, _primitives.isEOF)(this.buf1)) {
               if (!this.recoveryMode) {
-                (0, _util.error)('End of file inside array');
+                throw new _util.FormatError('End of file inside array');
               }
               return array;
             }
@@ -97,7 +97,7 @@ var Parser = function ParserClosure() {
             }
             if ((0, _primitives.isEOF)(this.buf1)) {
               if (!this.recoveryMode) {
-                (0, _util.error)('End of file inside dictionary');
+                throw new _util.FormatError('End of file inside dictionary');
               }
               return dict;
             }
@@ -307,7 +307,7 @@ var Parser = function ParserClosure() {
       var dict = new _primitives.Dict(this.xref);
       while (!(0, _primitives.isCmd)(this.buf1, 'ID') && !(0, _primitives.isEOF)(this.buf1)) {
         if (!(0, _primitives.isName)(this.buf1)) {
-          (0, _util.error)('Dictionary key must be a name object');
+          throw new _util.FormatError('Dictionary key must be a name object');
         }
         var key = this.buf1.name;
         this.shift();
@@ -422,7 +422,7 @@ var Parser = function ParserClosure() {
           stream.pos += scanLength;
         }
         if (!found) {
-          (0, _util.error)('Missing endstream');
+          throw new _util.FormatError('Missing endstream');
         }
         length = skipped;
         lexer.nextChar();
@@ -454,7 +454,7 @@ var Parser = function ParserClosure() {
         for (var i = 0, ii = filterArray.length; i < ii; ++i) {
           filter = this.xref.fetchIfRef(filterArray[i]);
           if (!(0, _primitives.isName)(filter)) {
-            (0, _util.error)('Bad filter name: ' + filter);
+            throw new _util.FormatError('Bad filter name: ' + filter);
           }
           params = null;
           if ((0, _util.isArray)(paramsArray) && i in paramsArray) {
@@ -580,7 +580,7 @@ var Lexer = function LexerClosure() {
         } while (ch === 0x0A || ch === 0x0D);
       }
       if (ch < 0x30 || ch > 0x39) {
-        (0, _util.error)('Invalid number: ' + String.fromCharCode(ch) + ' (charCode ' + ch + ')');
+        throw new _util.FormatError('Invalid number: ' + String.fromCharCode(ch) + ' (charCode ' + ch + ')');
       }
       var baseValue = ch - 0x30;
       var powerValue = 0;
@@ -867,8 +867,7 @@ var Lexer = function LexerClosure() {
           return _primitives.Cmd.get('}');
         case 0x29:
           this.nextChar();
-          (0, _util.error)('Illegal character: ' + ch);
-          break;
+          throw new _util.FormatError('Illegal character: ' + ch);
       }
       var str = String.fromCharCode(ch);
       var knownCommands = this.knownCommands;
@@ -879,7 +878,7 @@ var Lexer = function LexerClosure() {
           break;
         }
         if (str.length === 128) {
-          (0, _util.error)('Command token too long: ' + str.length);
+          throw new _util.FormatError('Command token too long: ' + str.length);
         }
         str = possibleCommand;
         knownCommandFound = knownCommands && knownCommands[str] !== undefined;

+ 6 - 6
lib/core/pattern.js

@@ -38,11 +38,11 @@ var ShadingType = {
 };
 var Pattern = function PatternClosure() {
   function Pattern() {
-    (0, _util.error)('should not call Pattern constructor');
+    throw new Error('should not call Pattern constructor');
   }
   Pattern.prototype = {
     getPattern: function Pattern_getPattern(ctx) {
-      (0, _util.error)('Should not call Pattern.getStyle: ' + ctx);
+      throw new Error('Should not call Pattern.getStyle: ' + ctx);
     }
   };
   Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref, res, handler) {
@@ -59,7 +59,7 @@ var Pattern = function PatternClosure() {
         case ShadingType.TENSOR_PATCH_MESH:
           return new Shadings.Mesh(shading, matrix, xref, res);
         default:
-          throw new Error('Unsupported ShadingType: ' + type);
+          throw new _util.FormatError('Unsupported ShadingType: ' + type);
       }
     } catch (ex) {
       if (ex instanceof _util.MissingDataException) {
@@ -163,7 +163,7 @@ Shadings.RadialAxial = function RadialAxialClosure() {
         r1 = coordsArr[5];
         type = 'radial';
       } else {
-        (0, _util.error)('getPattern type unknown: ' + shadingType);
+        (0, _util.unreachable)('getPattern type unknown: ' + shadingType);
       }
       var matrix = this.matrix;
       if (matrix) {
@@ -744,7 +744,7 @@ Shadings.Mesh = function MeshClosure() {
         patchMesh = true;
         break;
       default:
-        (0, _util.error)('Unsupported mesh type.');
+        (0, _util.unreachable)('Unsupported mesh type.');
         break;
     }
     if (patchMesh) {
@@ -782,7 +782,7 @@ function getTilingPatternIR(operatorList, dict, args) {
   var paintType = dict.get('PaintType');
   var tilingType = dict.get('TilingType');
   if (bbox[2] - bbox[0] === 0 || bbox[3] - bbox[1] === 0) {
-    throw new Error('getTilingPatternIR - invalid /BBox array: [' + bbox + '].');
+    throw new _util.FormatError('Invalid getTilingPatternIR /BBox array: [' + bbox + '].');
   }
   return ['TilingPattern', args, operatorList, matrix, bbox, xstep, ystep, paintType, tilingType];
 }

+ 3 - 3
lib/core/ps_parser.js

@@ -46,7 +46,7 @@ var PostScriptParser = function PostScriptParserClosure() {
       if (this.accept(type)) {
         return true;
       }
-      (0, _util.error)('Unexpected symbol: found ' + this.token.type + ' expected ' + type + '.');
+      throw new _util.FormatError('Unexpected symbol: found ' + this.token.type + ' expected ' + type + '.');
     },
     parse: function PostScriptParser_parse() {
       this.nextToken();
@@ -88,7 +88,7 @@ var PostScriptParser = function PostScriptParserClosure() {
         this.operators[conditionLocation] = endOfTrue;
         this.operators[conditionLocation + 1] = 'jz';
       } else {
-        (0, _util.error)('PS Function: error parsing conditional.');
+        throw new _util.FormatError('PS Function: error parsing conditional.');
       }
     }
   };
@@ -201,7 +201,7 @@ var PostScriptLexer = function PostScriptLexerClosure() {
       }
       var value = parseFloat(strBuf.join(''));
       if (isNaN(value)) {
-        (0, _util.error)('Invalid floating point number: ' + value);
+        throw new _util.FormatError('Invalid floating point number: ' + value);
       }
       return value;
     }

+ 14 - 14
lib/core/stream.js

@@ -279,16 +279,16 @@ var FlateStream = function FlateStreamClosure() {
     var cmf = str.getByte();
     var flg = str.getByte();
     if (cmf === -1 || flg === -1) {
-      (0, _util.error)('Invalid header in flate stream: ' + cmf + ', ' + flg);
+      throw new _util.FormatError('Invalid header in flate stream: ' + cmf + ', ' + flg);
     }
     if ((cmf & 0x0f) !== 0x08) {
-      (0, _util.error)('Unknown compression method in flate stream: ' + cmf + ', ' + flg);
+      throw new _util.FormatError('Unknown compression method in flate stream: ' + cmf + ', ' + flg);
     }
     if (((cmf << 8) + flg) % 31 !== 0) {
-      (0, _util.error)('Bad FCHECK in flate stream: ' + cmf + ', ' + flg);
+      throw new _util.FormatError('Bad FCHECK in flate stream: ' + cmf + ', ' + flg);
     }
     if (flg & 0x20) {
-      (0, _util.error)('FDICT bit set in flate stream: ' + cmf + ', ' + flg);
+      throw new _util.FormatError('FDICT bit set in flate stream: ' + cmf + ', ' + flg);
     }
     this.codeSize = 0;
     this.codeBuf = 0;
@@ -302,7 +302,7 @@ var FlateStream = function FlateStreamClosure() {
     var b;
     while (codeSize < bits) {
       if ((b = str.getByte()) === -1) {
-        (0, _util.error)('Bad encoding in flate stream');
+        throw new _util.FormatError('Bad encoding in flate stream');
       }
       codeBuf |= b << codeSize;
       codeSize += 8;
@@ -330,7 +330,7 @@ var FlateStream = function FlateStreamClosure() {
     var codeLen = code >> 16;
     var codeVal = code & 0xffff;
     if (codeLen < 1 || codeSize < codeLen) {
-      (0, _util.error)('Bad encoding in flate stream');
+      throw new _util.FormatError('Bad encoding in flate stream');
     }
     this.codeBuf = codeBuf >> codeLen;
     this.codeSize = codeSize - codeLen;
@@ -376,23 +376,23 @@ var FlateStream = function FlateStreamClosure() {
     if (hdr === 0) {
       var b;
       if ((b = str.getByte()) === -1) {
-        (0, _util.error)('Bad block header in flate stream');
+        throw new _util.FormatError('Bad block header in flate stream');
       }
       var blockLen = b;
       if ((b = str.getByte()) === -1) {
-        (0, _util.error)('Bad block header in flate stream');
+        throw new _util.FormatError('Bad block header in flate stream');
       }
       blockLen |= b << 8;
       if ((b = str.getByte()) === -1) {
-        (0, _util.error)('Bad block header in flate stream');
+        throw new _util.FormatError('Bad block header in flate stream');
       }
       var check = b;
       if ((b = str.getByte()) === -1) {
-        (0, _util.error)('Bad block header in flate stream');
+        throw new _util.FormatError('Bad block header in flate stream');
       }
       check |= b << 8;
       if (check !== (~blockLen & 0xffff) && (blockLen !== 0 || check !== 0)) {
-        (0, _util.error)('Bad uncompressed block length in flate stream');
+        throw new _util.FormatError('Bad uncompressed block length in flate stream');
       }
       this.codeBuf = 0;
       this.codeSize = 0;
@@ -461,7 +461,7 @@ var FlateStream = function FlateStreamClosure() {
       litCodeTable = this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes));
       distCodeTable = this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes));
     } else {
-      (0, _util.error)('Unknown block type in flate stream');
+      throw new _util.FormatError('Unknown block type in flate stream');
     }
     buffer = this.buffer;
     var limit = buffer ? buffer.length : 0;
@@ -515,7 +515,7 @@ var PredictorStream = function PredictorStreamClosure() {
       return str;
     }
     if (predictor !== 2 && (predictor < 10 || predictor > 15)) {
-      (0, _util.error)('Unsupported predictor: ' + predictor);
+      throw new _util.FormatError('Unsupported predictor: ' + predictor);
     }
     if (predictor === 2) {
       this.readBlock = this.readBlockTiff;
@@ -677,7 +677,7 @@ var PredictorStream = function PredictorStreamClosure() {
         }
         break;
       default:
-        (0, _util.error)('Unsupported predictor: ' + predictor);
+        throw new _util.FormatError('Unsupported predictor: ' + predictor);
     }
     this.bufferLength += rowBytes;
   };

+ 10 - 10
lib/display/api.js

@@ -96,10 +96,10 @@ function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallb
     source = { range: src };
   } else {
     if ((typeof src === 'undefined' ? 'undefined' : _typeof(src)) !== 'object') {
-      (0, _util.error)('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object');
+      throw new Error('Invalid parameter in getDocument, ' + 'need either Uint8Array, string or a parameter object');
     }
     if (!src.url && !src.data && !src.range) {
-      (0, _util.error)('Invalid parameter object: need either .data, .range or .url');
+      throw new Error('Invalid parameter object: need either .data, .range or .url');
     }
     source = src;
   }
@@ -126,7 +126,7 @@ function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallb
       } else if ((0, _util.isArrayBuffer)(pdfBytes)) {
         params[key] = new Uint8Array(pdfBytes);
       } else {
-        (0, _util.error)('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.');
+        throw new Error('Invalid PDF binary data: either typed array, ' + 'string or array-like object is expected in the ' + 'data property.');
       }
       continue;
     } else if (key === 'CMapReaderFactory') {
@@ -698,7 +698,7 @@ var PDFWorker = function PDFWorkerClosure() {
     if (pdfjsFilePath) {
       return pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, '.worker$1$2');
     }
-    (0, _util.error)('No PDFJS.workerSrc specified');
+    throw new Error('No PDFJS.workerSrc specified');
   }
   var fakeWorkerFilesLoadedCapability = void 0;
   function setupFakeWorkerGlobal() {
@@ -1061,7 +1061,7 @@ var WorkerTransport = function WorkerTransportClosure() {
             this.commonObjs.resolve(id, data[2]);
             break;
           default:
-            (0, _util.error)('Got unknown common object type ' + type);
+            throw new Error('Got unknown common object type ' + type);
         }
       }, this);
       messageHandler.on('obj', function transportObj(data) {
@@ -1090,7 +1090,7 @@ var WorkerTransport = function WorkerTransportClosure() {
             }
             break;
           default:
-            (0, _util.error)('Got unknown object type ' + type);
+            throw new Error('Got unknown object type ' + type);
         }
       }, this);
       messageHandler.on('DocProgress', function transportDocProgress(data) {
@@ -1114,7 +1114,7 @@ var WorkerTransport = function WorkerTransportClosure() {
         if (intentState.displayReadyCapability) {
           intentState.displayReadyCapability.reject(data.error);
         } else {
-          (0, _util.error)(data.error);
+          throw new Error(data.error);
         }
         if (intentState.operatorList) {
           intentState.operatorList.lastChunk = true;
@@ -1296,7 +1296,7 @@ var PDFObjects = function PDFObjectsClosure() {
       }
       var obj = this.objs[objId];
       if (!obj || !obj.resolved) {
-        (0, _util.error)('Requesting object that isn\'t resolved yet ' + objId);
+        throw new Error('Requesting object that isn\'t resolved yet ' + objId);
       }
       return obj.data;
     },
@@ -1480,8 +1480,8 @@ var _UnsupportedManager = function UnsupportedManagerClosure() {
 }();
 var version, build;
 {
-  exports.version = version = '1.8.522';
-  exports.build = build = 'ac980280';
+  exports.version = version = '1.8.524';
+  exports.build = build = '7b4887dd';
 }
 exports.getDocument = getDocument;
 exports.LoopbackPort = LoopbackPort;

+ 4 - 4
lib/display/canvas.js

@@ -437,7 +437,7 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
         ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
       }
     } else {
-      (0, _util.error)('bad image kind: ' + imgData.kind);
+      throw new Error('bad image kind: ' + imgData.kind);
     }
   }
   function putBinaryImageMask(ctx, imgData) {
@@ -1018,7 +1018,7 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
       var fontObj = this.commonObjs.get(fontRefName);
       var current = this.current;
       if (!fontObj) {
-        (0, _util.error)('Can\'t find font for ' + fontRefName);
+        throw new Error('Can\'t find font for ' + fontRefName);
       }
       current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : _util.FONT_IDENTITY_MATRIX;
       if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
@@ -1354,10 +1354,10 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
       this.restore();
     },
     beginInlineImage: function CanvasGraphics_beginInlineImage() {
-      (0, _util.error)('Should not call beginInlineImage');
+      throw new Error('Should not call beginInlineImage');
     },
     beginImageData: function CanvasGraphics_beginImageData() {
-      (0, _util.error)('Should not call beginImageData');
+      throw new Error('Should not call beginImageData');
     },
     paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) {
       this.save();

+ 2 - 2
lib/display/global.js

@@ -39,8 +39,8 @@ if (!_util.globalScope.PDFJS) {
 }
 var PDFJS = _util.globalScope.PDFJS;
 {
-  PDFJS.version = '1.8.522';
-  PDFJS.build = 'ac980280';
+  PDFJS.version = '1.8.524';
+  PDFJS.build = '7b4887dd';
 }
 PDFJS.pdfBug = false;
 if (PDFJS.verbosity !== undefined) {

+ 1 - 5
lib/display/metadata.js

@@ -17,10 +17,6 @@
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
-exports.Metadata = undefined;
-
-var _util = require('../shared/util');
-
 function fixMetadata(meta) {
   return meta.replace(/>\\376\\377([^<]+)/g, function (all, codes) {
     var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
@@ -40,7 +36,7 @@ function Metadata(meta) {
     var parser = new DOMParser();
     meta = parser.parseFromString(meta, 'application/xml');
   } else if (!(meta instanceof Document)) {
-    (0, _util.error)('Metadata: Invalid metadata object');
+    throw new Error('Metadata: Invalid metadata object');
   }
   this.metaDocument = meta;
   this.metadata = Object.create(null);

+ 3 - 4
lib/display/pattern_helper.js

@@ -159,8 +159,7 @@ var createMeshCanvas = function createMeshCanvasClosure() {
         }
         break;
       default:
-        (0, _util.error)('illigal figure');
-        break;
+        throw new Error('illegal figure');
     }
   }
   function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) {
@@ -268,7 +267,7 @@ ShadingIRs.Dummy = {
 function getShadingPatternFromIR(raw) {
   var shadingIR = ShadingIRs[raw[0]];
   if (!shadingIR) {
-    (0, _util.error)('Unknown IR type: ' + raw[0]);
+    throw new Error('Unknown IR type: ' + raw[0]);
   }
   return shadingIR.fromIR(raw);
 }
@@ -363,7 +362,7 @@ var TilingPattern = function TilingPatternClosure() {
           context.strokeStyle = cssColor;
           break;
         default:
-          (0, _util.error)('Unsupported paint type: ' + paintType);
+          throw new _util.FormatError('Unsupported paint type: ' + paintType);
       }
     },
     getPattern: function TilingPattern_getPattern(ctx, owner) {

+ 2 - 2
lib/pdf.js

@@ -14,8 +14,8 @@
  */
 'use strict';
 
-var pdfjsVersion = '1.8.522';
-var pdfjsBuild = 'ac980280';
+var pdfjsVersion = '1.8.524';
+var pdfjsBuild = '7b4887dd';
 var pdfjsSharedUtil = require('./shared/util.js');
 var pdfjsDisplayGlobal = require('./display/global.js');
 var pdfjsDisplayAPI = require('./display/api.js');

+ 2 - 2
lib/pdf.worker.js

@@ -14,8 +14,8 @@
  */
 'use strict';
 
-var pdfjsVersion = '1.8.522';
-var pdfjsBuild = 'ac980280';
+var pdfjsVersion = '1.8.524';
+var pdfjsBuild = '7b4887dd';
 var pdfjsCoreWorker = require('./core/worker.js');
 {
   require('./core/network.js');

+ 18 - 19
lib/shared/util.js

@@ -17,7 +17,7 @@
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
-exports.warn = exports.utf8StringToString = exports.stringToUTF8String = exports.stringToPDFString = exports.stringToBytes = exports.string32 = exports.shadow = exports.setVerbosityLevel = exports.ReadableStream = exports.removeNullCharacters = exports.readUint32 = exports.readUint16 = exports.readInt8 = exports.log2 = exports.loadJpegStream = exports.isEvalSupported = exports.isLittleEndian = exports.createValidAbsoluteUrl = exports.isSameOrigin = exports.isNodeJS = exports.isSpace = exports.isString = exports.isNum = exports.isInt = exports.isEmptyObj = exports.isBool = exports.isArrayBuffer = exports.isArray = exports.info = exports.globalScope = exports.getVerbosityLevel = exports.getLookupTableFactory = exports.error = exports.deprecated = exports.createObjectURL = exports.createPromiseCapability = exports.createBlob = exports.bytesToString = exports.assert = exports.arraysToBytes = exports.arrayByteLength = exports.XRefParseException = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.StatTimer = exports.PasswordResponses = exports.PasswordException = exports.PageViewport = exports.NotImplementedException = exports.NativeImageDecoding = exports.MissingPDFException = exports.MissingDataException = exports.MessageHandler = exports.InvalidPDFException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VERBOSITY_LEVELS = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = undefined;
+exports.unreachable = exports.warn = exports.utf8StringToString = exports.stringToUTF8String = exports.stringToPDFString = exports.stringToBytes = exports.string32 = exports.shadow = exports.setVerbosityLevel = exports.ReadableStream = exports.removeNullCharacters = exports.readUint32 = exports.readUint16 = exports.readInt8 = exports.log2 = exports.loadJpegStream = exports.isEvalSupported = exports.isLittleEndian = exports.createValidAbsoluteUrl = exports.isSameOrigin = exports.isNodeJS = exports.isSpace = exports.isString = exports.isNum = exports.isInt = exports.isEmptyObj = exports.isBool = exports.isArrayBuffer = exports.isArray = exports.info = exports.globalScope = exports.getVerbosityLevel = exports.getLookupTableFactory = exports.deprecated = exports.createObjectURL = exports.createPromiseCapability = exports.createBlob = exports.bytesToString = exports.assert = exports.arraysToBytes = exports.arrayByteLength = exports.FormatError = exports.XRefParseException = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.StatTimer = exports.PasswordResponses = exports.PasswordException = exports.PageViewport = exports.NotImplementedException = exports.NativeImageDecoding = exports.MissingPDFException = exports.MissingDataException = exports.MessageHandler = exports.InvalidPDFException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VERBOSITY_LEVELS = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = undefined;
 
 var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
 
@@ -265,23 +265,12 @@ function warn(msg) {
 function deprecated(details) {
   console.log('Deprecated API usage: ' + details);
 }
-function error(msg) {
-  if (verbosity >= VERBOSITY_LEVELS.errors) {
-    console.log('Error: ' + msg);
-    console.log(backtrace());
-  }
+function unreachable(msg) {
   throw new Error(msg);
 }
-function backtrace() {
-  try {
-    throw new Error();
-  } catch (e) {
-    return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
-  }
-}
 function assert(cond, msg) {
   if (!cond) {
-    error(msg);
+    unreachable(msg);
   }
 }
 var UNSUPPORTED_FEATURES = {
@@ -432,6 +421,15 @@ var XRefParseException = function XRefParseExceptionClosure() {
   XRefParseException.constructor = XRefParseException;
   return XRefParseException;
 }();
+var FormatError = function FormatErrorClosure() {
+  function FormatError(msg) {
+    this.message = msg;
+  }
+  FormatError.prototype = new Error();
+  FormatError.prototype.name = 'FormatError';
+  FormatError.constructor = FormatError;
+  return FormatError;
+}();
 var NullCharactersRegExp = /\x00/g;
 function removeNullCharacters(str) {
   if (typeof str !== 'string') {
@@ -968,7 +966,7 @@ function MessageHandler(sourceName, targetName, comObj) {
           callback.resolve(data.data);
         }
       } else {
-        error('Cannot resolve callback ' + callbackId);
+        throw new Error('Cannot resolve callback ' + callbackId);
       }
     } else if (data.action in ah) {
       var action = ah[data.action];
@@ -1003,7 +1001,7 @@ function MessageHandler(sourceName, targetName, comObj) {
         action[0].call(action[1], data.data);
       }
     } else {
-      error('Unknown action from worker: ' + data.action);
+      throw new Error('Unknown action from worker: ' + data.action);
     }
   };
   comObj.addEventListener('message', this._onComObjOnMessage);
@@ -1012,7 +1010,7 @@ MessageHandler.prototype = {
   on: function on(actionName, handler, scope) {
     var ah = this.actionHandler;
     if (ah[actionName]) {
-      error('There is already an actionName called "' + actionName + '"');
+      throw new Error('There is already an actionName called "' + actionName + '"');
     }
     ah[actionName] = [handler, scope];
   },
@@ -1320,6 +1318,7 @@ exports.UnexpectedResponseException = UnexpectedResponseException;
 exports.UnknownErrorException = UnknownErrorException;
 exports.Util = Util;
 exports.XRefParseException = XRefParseException;
+exports.FormatError = FormatError;
 exports.arrayByteLength = arrayByteLength;
 exports.arraysToBytes = arraysToBytes;
 exports.assert = assert;
@@ -1328,7 +1327,6 @@ exports.createBlob = createBlob;
 exports.createPromiseCapability = createPromiseCapability;
 exports.createObjectURL = createObjectURL;
 exports.deprecated = deprecated;
-exports.error = error;
 exports.getLookupTableFactory = getLookupTableFactory;
 exports.getVerbosityLevel = getVerbosityLevel;
 exports.globalScope = globalScope;
@@ -1360,4 +1358,5 @@ exports.stringToBytes = stringToBytes;
 exports.stringToPDFString = stringToPDFString;
 exports.stringToUTF8String = stringToUTF8String;
 exports.utf8StringToString = utf8StringToString;
-exports.warn = warn;
+exports.warn = warn;
+exports.unreachable = unreachable;

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "pdfjs-dist",
-  "version": "1.8.522",
+  "version": "1.8.524",
   "main": "build/pdf.js",
   "description": "Generic build of Mozilla's PDF.js library.",
   "keywords": [

Some files were not shown because too many files changed in this diff