Browse Source

PDF.js version 1.8.286 - See mozilla/pdf.js@00d67371eca336574038c4b18bb649e7e8c31bf7

master v1.8.286
pdfjsbot 8 years ago
parent
commit
ca98d54093
  1. 2
      bower.json
  2. 12
      build/pdf.combined.js
  3. 12
      build/pdf.js
  4. 4
      build/pdf.min.js
  5. 4
      build/pdf.worker.js
  6. 4
      lib/display/api.js
  7. 4
      lib/display/global.js
  8. 4
      lib/pdf.js
  9. 4
      lib/pdf.worker.js
  10. 549
      lib/test/unit/annotation_spec.js
  11. 166
      lib/test/unit/api_spec.js
  12. 8
      lib/test/unit/bidi_spec.js
  13. 47
      lib/test/unit/cff_parser_spec.js
  14. 96
      lib/test/unit/cmap_spec.js
  15. 144
      lib/test/unit/crypto_spec.js
  16. 8
      lib/test/unit/document_spec.js
  17. 30
      lib/test/unit/dom_utils_spec.js
  18. 161
      lib/test/unit/evaluator_spec.js
  19. 20
      lib/test/unit/fonts_spec.js
  20. 34
      lib/test/unit/function_spec.js
  21. 6
      lib/test/unit/metadata_spec.js
  22. 22
      lib/test/unit/murmurhash3_spec.js
  23. 10
      lib/test/unit/network_spec.js
  24. 83
      lib/test/unit/parser_spec.js
  25. 131
      lib/test/unit/primitives_spec.js
  26. 15
      lib/test/unit/stream_spec.js
  27. 39
      lib/test/unit/test_utils.js
  28. 56
      lib/test/unit/type1_parser_spec.js
  29. 103
      lib/test/unit/ui_utils_spec.js
  30. 59
      lib/test/unit/unicode_spec.js
  31. 17
      lib/test/unit/util_spec.js
  32. 2
      package.json

2
bower.json

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

12
build/pdf.combined.js

@ -12726,8 +12726,8 @@ var _UnsupportedManager = function UnsupportedManagerClosure() {
}(); }();
var version, build; var version, build;
{ {
exports.version = version = '1.8.284'; exports.version = version = '1.8.286';
exports.build = build = '06c93d8f'; exports.build = build = '00d67371';
} }
exports.getDocument = getDocument; exports.getDocument = getDocument;
exports.PDFDataRangeTransport = PDFDataRangeTransport; exports.PDFDataRangeTransport = PDFDataRangeTransport;
@ -28024,8 +28024,8 @@ if (!_util.globalScope.PDFJS) {
} }
var PDFJS = _util.globalScope.PDFJS; var PDFJS = _util.globalScope.PDFJS;
{ {
PDFJS.version = '1.8.284'; PDFJS.version = '1.8.286';
PDFJS.build = '06c93d8f'; PDFJS.build = '00d67371';
} }
PDFJS.pdfBug = false; PDFJS.pdfBug = false;
if (PDFJS.verbosity !== undefined) { if (PDFJS.verbosity !== undefined) {
@ -43550,8 +43550,8 @@ exports.TilingPattern = TilingPattern;
"use strict"; "use strict";
var pdfjsVersion = '1.8.284'; var pdfjsVersion = '1.8.286';
var pdfjsBuild = '06c93d8f'; var pdfjsBuild = '00d67371';
var pdfjsSharedUtil = __w_pdfjs_require__(0); var pdfjsSharedUtil = __w_pdfjs_require__(0);
var pdfjsDisplayGlobal = __w_pdfjs_require__(26); var pdfjsDisplayGlobal = __w_pdfjs_require__(26);
var pdfjsDisplayAPI = __w_pdfjs_require__(10); var pdfjsDisplayAPI = __w_pdfjs_require__(10);

12
build/pdf.js

@ -3435,8 +3435,8 @@ var _UnsupportedManager = function UnsupportedManagerClosure() {
}(); }();
var version, build; var version, build;
{ {
exports.version = version = '1.8.284'; exports.version = version = '1.8.286';
exports.build = build = '06c93d8f'; exports.build = build = '00d67371';
} }
exports.getDocument = getDocument; exports.getDocument = getDocument;
exports.PDFDataRangeTransport = PDFDataRangeTransport; exports.PDFDataRangeTransport = PDFDataRangeTransport;
@ -5403,8 +5403,8 @@ if (!_util.globalScope.PDFJS) {
} }
var PDFJS = _util.globalScope.PDFJS; var PDFJS = _util.globalScope.PDFJS;
{ {
PDFJS.version = '1.8.284'; PDFJS.version = '1.8.286';
PDFJS.build = '06c93d8f'; PDFJS.build = '00d67371';
} }
PDFJS.pdfBug = false; PDFJS.pdfBug = false;
if (PDFJS.verbosity !== undefined) { if (PDFJS.verbosity !== undefined) {
@ -7898,8 +7898,8 @@ exports.TilingPattern = TilingPattern;
"use strict"; "use strict";
var pdfjsVersion = '1.8.284'; var pdfjsVersion = '1.8.286';
var pdfjsBuild = '06c93d8f'; var pdfjsBuild = '00d67371';
var pdfjsSharedUtil = __w_pdfjs_require__(0); var pdfjsSharedUtil = __w_pdfjs_require__(0);
var pdfjsDisplayGlobal = __w_pdfjs_require__(9); var pdfjsDisplayGlobal = __w_pdfjs_require__(9);
var pdfjsDisplayAPI = __w_pdfjs_require__(3); var pdfjsDisplayAPI = __w_pdfjs_require__(3);

4
build/pdf.min.js vendored

File diff suppressed because one or more lines are too long

4
build/pdf.worker.js vendored

@ -36963,8 +36963,8 @@ exports.Type1Parser = Type1Parser;
"use strict"; "use strict";
var pdfjsVersion = '1.8.284'; var pdfjsVersion = '1.8.286';
var pdfjsBuild = '06c93d8f'; var pdfjsBuild = '00d67371';
var pdfjsCoreWorker = __w_pdfjs_require__(8); var pdfjsCoreWorker = __w_pdfjs_require__(8);
{ {
__w_pdfjs_require__(19); __w_pdfjs_require__(19);

4
lib/display/api.js

@ -1366,8 +1366,8 @@ var _UnsupportedManager = function UnsupportedManagerClosure() {
}(); }();
var version, build; var version, build;
{ {
exports.version = version = '1.8.284'; exports.version = version = '1.8.286';
exports.build = build = '06c93d8f'; exports.build = build = '00d67371';
} }
exports.getDocument = getDocument; exports.getDocument = getDocument;
exports.PDFDataRangeTransport = PDFDataRangeTransport; exports.PDFDataRangeTransport = PDFDataRangeTransport;

4
lib/display/global.js

@ -39,8 +39,8 @@ if (!_util.globalScope.PDFJS) {
} }
var PDFJS = _util.globalScope.PDFJS; var PDFJS = _util.globalScope.PDFJS;
{ {
PDFJS.version = '1.8.284'; PDFJS.version = '1.8.286';
PDFJS.build = '06c93d8f'; PDFJS.build = '00d67371';
} }
PDFJS.pdfBug = false; PDFJS.pdfBug = false;
if (PDFJS.verbosity !== undefined) { if (PDFJS.verbosity !== undefined) {

4
lib/pdf.js

@ -14,8 +14,8 @@
*/ */
'use strict'; 'use strict';
var pdfjsVersion = '1.8.284'; var pdfjsVersion = '1.8.286';
var pdfjsBuild = '06c93d8f'; var pdfjsBuild = '00d67371';
var pdfjsSharedUtil = require('./shared/util.js'); var pdfjsSharedUtil = require('./shared/util.js');
var pdfjsDisplayGlobal = require('./display/global.js'); var pdfjsDisplayGlobal = require('./display/global.js');
var pdfjsDisplayAPI = require('./display/api.js'); var pdfjsDisplayAPI = require('./display/api.js');

4
lib/pdf.worker.js vendored

@ -14,8 +14,8 @@
*/ */
'use strict'; 'use strict';
var pdfjsVersion = '1.8.284'; var pdfjsVersion = '1.8.286';
var pdfjsBuild = '06c93d8f'; var pdfjsBuild = '00d67371';
var pdfjsCoreWorker = require('./core/worker.js'); var pdfjsCoreWorker = require('./core/worker.js');
{ {
require('./core/network.js'); require('./core/network.js');

549
lib/test/unit/annotation_spec.js

File diff suppressed because it is too large Load Diff

166
lib/test/unit/api_spec.js

@ -16,28 +16,20 @@
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; }; 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; };
var sharedUtil = require('../../shared/util.js'); var _util = require('../../shared/util');
var displayDOMUtils = require('../../display/dom_utils.js');
var displayGlobal = require('../../display/global.js'); var _dom_utils = require('../../display/dom_utils');
var displayApi = require('../../display/api.js');
var PDFJS = displayGlobal.PDFJS; var _api = require('../../display/api');
var createPromiseCapability = sharedUtil.createPromiseCapability;
var DOMCanvasFactory = displayDOMUtils.DOMCanvasFactory; var _global = require('../../display/global');
var RenderingCancelledException = displayDOMUtils.RenderingCancelledException;
var PDFDocumentProxy = displayApi.PDFDocumentProxy;
var InvalidPDFException = sharedUtil.InvalidPDFException;
var MissingPDFException = sharedUtil.MissingPDFException;
var PasswordResponses = sharedUtil.PasswordResponses;
var PasswordException = sharedUtil.PasswordException;
var PDFPageProxy = displayApi.PDFPageProxy;
var StreamType = sharedUtil.StreamType;
var FontType = sharedUtil.FontType;
describe('api', function () { describe('api', function () {
var basicApiUrl = new URL('../pdfs/basicapi.pdf', window.location).href; var basicApiUrl = new URL('../pdfs/basicapi.pdf', window.location).href;
var basicApiFileLength = 105779; var basicApiFileLength = 105779;
var CanvasFactory; var CanvasFactory;
beforeAll(function (done) { beforeAll(function (done) {
CanvasFactory = new DOMCanvasFactory(); CanvasFactory = new _dom_utils.DOMCanvasFactory();
done(); done();
}); });
afterAll(function () { afterAll(function () {
@ -52,9 +44,9 @@ describe('api', function () {
describe('PDFJS', function () { describe('PDFJS', function () {
describe('getDocument', function () { describe('getDocument', function () {
it('creates pdf doc from URL', function (done) { it('creates pdf doc from URL', function (done) {
var loadingTask = PDFJS.getDocument(basicApiUrl); var loadingTask = _global.PDFJS.getDocument(basicApiUrl);
var isProgressReportedResolved = false; var isProgressReportedResolved = false;
var progressReportedCapability = createPromiseCapability(); var progressReportedCapability = (0, _util.createPromiseCapability)();
loadingTask.onProgress = function (progressData) { loadingTask.onProgress = function (progressData) {
if (!isProgressReportedResolved) { if (!isProgressReportedResolved) {
isProgressReportedResolved = true; isProgressReportedResolved = true;
@ -64,7 +56,7 @@ describe('api', function () {
var promises = [progressReportedCapability.promise, loadingTask.promise]; var promises = [progressReportedCapability.promise, loadingTask.promise];
Promise.all(promises).then(function (data) { Promise.all(promises).then(function (data) {
expect(data[0].loaded / data[0].total > 0).toEqual(true); expect(data[0].loaded / data[0].total > 0).toEqual(true);
expect(data[1] instanceof PDFDocumentProxy).toEqual(true); expect(data[1] instanceof _api.PDFDocumentProxy).toEqual(true);
expect(loadingTask).toEqual(data[1].loadingTask); expect(loadingTask).toEqual(data[1].loadingTask);
loadingTask.destroy(); loadingTask.destroy();
done(); done();
@ -73,7 +65,7 @@ describe('api', function () {
}); });
}); });
it('creates pdf doc from URL and aborts before worker initialized', function (done) { it('creates pdf doc from URL and aborts before worker initialized', function (done) {
var loadingTask = PDFJS.getDocument(basicApiUrl); var loadingTask = _global.PDFJS.getDocument(basicApiUrl);
loadingTask.destroy(); loadingTask.destroy();
loadingTask.promise.then(function (reason) { loadingTask.promise.then(function (reason) {
done.fail('shall fail loading'); done.fail('shall fail loading');
@ -83,7 +75,7 @@ describe('api', function () {
}); });
}); });
it('creates pdf doc from URL and aborts loading after worker initialized', function (done) { it('creates pdf doc from URL and aborts loading after worker initialized', function (done) {
var loadingTask = PDFJS.getDocument(basicApiUrl); var loadingTask = _global.PDFJS.getDocument(basicApiUrl);
var destroyed = loadingTask._worker.promise.then(function () { var destroyed = loadingTask._worker.promise.then(function () {
return loadingTask.destroy(); return loadingTask.destroy();
}); });
@ -95,7 +87,7 @@ describe('api', function () {
}); });
}); });
it('creates pdf doc from typed array', function (done) { it('creates pdf doc from typed array', function (done) {
var nonBinaryRequest = PDFJS.disableWorker; var nonBinaryRequest = _global.PDFJS.disableWorker;
var request = new XMLHttpRequest(); var request = new XMLHttpRequest();
request.open('GET', basicApiUrl, false); request.open('GET', basicApiUrl, false);
if (!nonBinaryRequest) { if (!nonBinaryRequest) {
@ -120,9 +112,9 @@ describe('api', function () {
typedArrayPdf = new Uint8Array(request.response); typedArrayPdf = new Uint8Array(request.response);
} }
expect(typedArrayPdf.length).toEqual(basicApiFileLength); expect(typedArrayPdf.length).toEqual(basicApiFileLength);
var loadingTask = PDFJS.getDocument(typedArrayPdf); var loadingTask = _global.PDFJS.getDocument(typedArrayPdf);
loadingTask.promise.then(function (data) { loadingTask.promise.then(function (data) {
expect(data instanceof PDFDocumentProxy).toEqual(true); expect(data instanceof _api.PDFDocumentProxy).toEqual(true);
loadingTask.destroy(); loadingTask.destroy();
done(); done();
}).catch(function (reason) { }).catch(function (reason) {
@ -131,41 +123,41 @@ describe('api', function () {
}); });
it('creates pdf doc from invalid PDF file', function (done) { it('creates pdf doc from invalid PDF file', function (done) {
var url = new URL('../pdfs/bug1020226.pdf', window.location).href; var url = new URL('../pdfs/bug1020226.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(url); var loadingTask = _global.PDFJS.getDocument(url);
loadingTask.promise.then(function () { loadingTask.promise.then(function () {
done.fail('shall fail loading'); done.fail('shall fail loading');
}).catch(function (error) { }).catch(function (error) {
expect(error instanceof InvalidPDFException).toEqual(true); expect(error instanceof _util.InvalidPDFException).toEqual(true);
loadingTask.destroy(); loadingTask.destroy();
done(); done();
}); });
}); });
it('creates pdf doc from non-existent URL', function (done) { it('creates pdf doc from non-existent URL', function (done) {
var nonExistentUrl = new URL('../pdfs/non-existent.pdf', window.location).href; var nonExistentUrl = new URL('../pdfs/non-existent.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(nonExistentUrl); var loadingTask = _global.PDFJS.getDocument(nonExistentUrl);
loadingTask.promise.then(function (error) { loadingTask.promise.then(function (error) {
done.fail('shall fail loading'); done.fail('shall fail loading');
}).catch(function (error) { }).catch(function (error) {
expect(error instanceof MissingPDFException).toEqual(true); expect(error instanceof _util.MissingPDFException).toEqual(true);
loadingTask.destroy(); loadingTask.destroy();
done(); done();
}); });
}); });
it('creates pdf doc from PDF file protected with user and owner password', function (done) { it('creates pdf doc from PDF file protected with user and owner password', function (done) {
var url = new URL('../pdfs/pr6531_1.pdf', window.location).href; var url = new URL('../pdfs/pr6531_1.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(url); var loadingTask = _global.PDFJS.getDocument(url);
var isPasswordNeededResolved = false; var isPasswordNeededResolved = false;
var passwordNeededCapability = createPromiseCapability(); var passwordNeededCapability = (0, _util.createPromiseCapability)();
var isPasswordIncorrectResolved = false; var isPasswordIncorrectResolved = false;
var passwordIncorrectCapability = createPromiseCapability(); var passwordIncorrectCapability = (0, _util.createPromiseCapability)();
loadingTask.onPassword = function (updatePassword, reason) { loadingTask.onPassword = function (updatePassword, reason) {
if (reason === PasswordResponses.NEED_PASSWORD && !isPasswordNeededResolved) { if (reason === _util.PasswordResponses.NEED_PASSWORD && !isPasswordNeededResolved) {
isPasswordNeededResolved = true; isPasswordNeededResolved = true;
passwordNeededCapability.resolve(); passwordNeededCapability.resolve();
updatePassword('qwerty'); updatePassword('qwerty');
return; return;
} }
if (reason === PasswordResponses.INCORRECT_PASSWORD && !isPasswordIncorrectResolved) { if (reason === _util.PasswordResponses.INCORRECT_PASSWORD && !isPasswordIncorrectResolved) {
isPasswordIncorrectResolved = true; isPasswordIncorrectResolved = true;
passwordIncorrectCapability.resolve(); passwordIncorrectCapability.resolve();
updatePassword('asdfasdf'); updatePassword('asdfasdf');
@ -175,7 +167,7 @@ describe('api', function () {
}; };
var promises = [passwordNeededCapability.promise, passwordIncorrectCapability.promise, loadingTask.promise]; var promises = [passwordNeededCapability.promise, passwordIncorrectCapability.promise, loadingTask.promise];
Promise.all(promises).then(function (data) { Promise.all(promises).then(function (data) {
expect(data[2] instanceof PDFDocumentProxy).toEqual(true); expect(data[2] instanceof _api.PDFDocumentProxy).toEqual(true);
loadingTask.destroy(); loadingTask.destroy();
done(); done();
}).catch(function (reason) { }).catch(function (reason) {
@ -184,7 +176,7 @@ describe('api', function () {
}); });
it('creates pdf doc from PDF file protected with only a user password', function (done) { it('creates pdf doc from PDF file protected with only a user password', function (done) {
var url = new URL('../pdfs/pr6531_2.pdf', window.location).href; var url = new URL('../pdfs/pr6531_2.pdf', window.location).href;
var passwordNeededLoadingTask = PDFJS.getDocument({ var passwordNeededLoadingTask = _global.PDFJS.getDocument({
url: url, url: url,
password: '' password: ''
}); });
@ -192,11 +184,11 @@ describe('api', function () {
done.fail('shall fail with no password'); done.fail('shall fail with no password');
return Promise.reject(new Error('loadingTask should be rejected')); return Promise.reject(new Error('loadingTask should be rejected'));
}, function (data) { }, function (data) {
expect(data instanceof PasswordException).toEqual(true); expect(data instanceof _util.PasswordException).toEqual(true);
expect(data.code).toEqual(PasswordResponses.NEED_PASSWORD); expect(data.code).toEqual(_util.PasswordResponses.NEED_PASSWORD);
return passwordNeededLoadingTask.destroy(); return passwordNeededLoadingTask.destroy();
}); });
var passwordIncorrectLoadingTask = PDFJS.getDocument({ var passwordIncorrectLoadingTask = _global.PDFJS.getDocument({
url: url, url: url,
password: 'qwerty' password: 'qwerty'
}); });
@ -204,16 +196,16 @@ describe('api', function () {
done.fail('shall fail with wrong password'); done.fail('shall fail with wrong password');
return Promise.reject(new Error('loadingTask should be rejected')); return Promise.reject(new Error('loadingTask should be rejected'));
}, function (data) { }, function (data) {
expect(data instanceof PasswordException).toEqual(true); expect(data instanceof _util.PasswordException).toEqual(true);
expect(data.code).toEqual(PasswordResponses.INCORRECT_PASSWORD); expect(data.code).toEqual(_util.PasswordResponses.INCORRECT_PASSWORD);
return passwordIncorrectLoadingTask.destroy(); return passwordIncorrectLoadingTask.destroy();
}); });
var passwordAcceptedLoadingTask = PDFJS.getDocument({ var passwordAcceptedLoadingTask = _global.PDFJS.getDocument({
url: url, url: url,
password: 'asdfasdf' password: 'asdfasdf'
}); });
var result3 = passwordAcceptedLoadingTask.promise.then(function (data) { var result3 = passwordAcceptedLoadingTask.promise.then(function (data) {
expect(data instanceof PDFDocumentProxy).toEqual(true); expect(data instanceof _api.PDFDocumentProxy).toEqual(true);
return passwordAcceptedLoadingTask.destroy(); return passwordAcceptedLoadingTask.destroy();
}); });
Promise.all([result1, result2, result3]).then(function () { Promise.all([result1, result2, result3]).then(function () {
@ -224,13 +216,13 @@ describe('api', function () {
}); });
it('creates pdf doc from password protected PDF file and aborts/throws ' + 'in the onPassword callback (issue 7806)', function (done) { it('creates pdf doc from password protected PDF file and aborts/throws ' + 'in the onPassword callback (issue 7806)', function (done) {
var url = new URL('../pdfs/issue3371.pdf', window.location).href; var url = new URL('../pdfs/issue3371.pdf', window.location).href;
var passwordNeededLoadingTask = PDFJS.getDocument(url); var passwordNeededLoadingTask = _global.PDFJS.getDocument(url);
var passwordIncorrectLoadingTask = PDFJS.getDocument({ var passwordIncorrectLoadingTask = _global.PDFJS.getDocument({
url: url, url: url,
password: 'qwerty' password: 'qwerty'
}); });
passwordNeededLoadingTask.onPassword = function (callback, reason) { passwordNeededLoadingTask.onPassword = function (callback, reason) {
if (reason === PasswordResponses.NEED_PASSWORD) { if (reason === _util.PasswordResponses.NEED_PASSWORD) {
passwordNeededLoadingTask.destroy(); passwordNeededLoadingTask.destroy();
return; return;
} }
@ -240,11 +232,11 @@ describe('api', function () {
done.fail('shall fail since the loadingTask should be destroyed'); done.fail('shall fail since the loadingTask should be destroyed');
return Promise.reject(new Error('loadingTask should be rejected')); return Promise.reject(new Error('loadingTask should be rejected'));
}, function (reason) { }, function (reason) {
expect(reason instanceof PasswordException).toEqual(true); expect(reason instanceof _util.PasswordException).toEqual(true);
expect(reason.code).toEqual(PasswordResponses.NEED_PASSWORD); expect(reason.code).toEqual(_util.PasswordResponses.NEED_PASSWORD);
}); });
passwordIncorrectLoadingTask.onPassword = function (callback, reason) { passwordIncorrectLoadingTask.onPassword = function (callback, reason) {
if (reason === PasswordResponses.INCORRECT_PASSWORD) { if (reason === _util.PasswordResponses.INCORRECT_PASSWORD) {
throw new Error('Incorrect password'); throw new Error('Incorrect password');
} }
expect(false).toEqual(true); expect(false).toEqual(true);
@ -253,8 +245,8 @@ describe('api', function () {
done.fail('shall fail since the onPassword callback should throw'); done.fail('shall fail since the onPassword callback should throw');
return Promise.reject(new Error('loadingTask should be rejected')); return Promise.reject(new Error('loadingTask should be rejected'));
}, function (reason) { }, function (reason) {
expect(reason instanceof PasswordException).toEqual(true); expect(reason instanceof _util.PasswordException).toEqual(true);
expect(reason.code).toEqual(PasswordResponses.INCORRECT_PASSWORD); expect(reason.code).toEqual(_util.PasswordResponses.INCORRECT_PASSWORD);
return passwordIncorrectLoadingTask.destroy(); return passwordIncorrectLoadingTask.destroy();
}); });
Promise.all([result1, result2]).then(function () { Promise.all([result1, result2]).then(function () {
@ -267,7 +259,7 @@ describe('api', function () {
}); });
describe('PDFWorker', function () { describe('PDFWorker', function () {
it('worker created or destroyed', function (done) { it('worker created or destroyed', function (done) {
var worker = new PDFJS.PDFWorker('test1'); var worker = new _global.PDFJS.PDFWorker('test1');
worker.promise.then(function () { worker.promise.then(function () {
expect(worker.name).toEqual('test1'); expect(worker.name).toEqual('test1');
expect(!!worker.port).toEqual(true); expect(!!worker.port).toEqual(true);
@ -283,7 +275,7 @@ describe('api', function () {
}); });
}); });
it('worker created or destroyed by getDocument', function (done) { it('worker created or destroyed by getDocument', function (done) {
var loadingTask = PDFJS.getDocument(basicApiUrl); var loadingTask = _global.PDFJS.getDocument(basicApiUrl);
var worker; var worker;
loadingTask.promise.then(function () { loadingTask.promise.then(function () {
worker = loadingTask._worker; worker = loadingTask._worker;
@ -302,8 +294,8 @@ describe('api', function () {
}); });
}); });
it('worker created and can be used in getDocument', function (done) { it('worker created and can be used in getDocument', function (done) {
var worker = new PDFJS.PDFWorker('test1'); var worker = new _global.PDFJS.PDFWorker('test1');
var loadingTask = PDFJS.getDocument({ var loadingTask = _global.PDFJS.getDocument({
url: basicApiUrl, url: basicApiUrl,
worker: worker worker: worker
}); });
@ -325,9 +317,9 @@ describe('api', function () {
}); });
}); });
it('creates more than one worker', function (done) { it('creates more than one worker', function (done) {
var worker1 = new PDFJS.PDFWorker('test1'); var worker1 = new _global.PDFJS.PDFWorker('test1');
var worker2 = new PDFJS.PDFWorker('test2'); var worker2 = new _global.PDFJS.PDFWorker('test2');
var worker3 = new PDFJS.PDFWorker('test3'); var worker3 = new _global.PDFJS.PDFWorker('test3');
var ready = Promise.all([worker1.promise, worker2.promise, worker3.promise]); var ready = Promise.all([worker1.promise, worker2.promise, worker3.promise]);
ready.then(function () { ready.then(function () {
expect(worker1.port !== worker2.port && worker1.port !== worker3.port && worker2.port !== worker3.port).toEqual(true); expect(worker1.port !== worker2.port && worker1.port !== worker3.port && worker2.port !== worker3.port).toEqual(true);
@ -344,7 +336,7 @@ describe('api', function () {
var loadingTask; var loadingTask;
var doc; var doc;
beforeAll(function (done) { beforeAll(function (done) {
loadingTask = PDFJS.getDocument(basicApiUrl); loadingTask = _global.PDFJS.getDocument(basicApiUrl);
loadingTask.promise.then(function (data) { loadingTask.promise.then(function (data) {
doc = data; doc = data;
done(); done();
@ -364,7 +356,7 @@ describe('api', function () {
it('gets page', function (done) { it('gets page', function (done) {
var promise = doc.getPage(1); var promise = doc.getPage(1);
promise.then(function (data) { promise.then(function (data) {
expect(data instanceof PDFPageProxy).toEqual(true); expect(data instanceof _api.PDFPageProxy).toEqual(true);
expect(data.pageIndex).toEqual(0); expect(data.pageIndex).toEqual(0);
done(); done();
}).catch(function (reason) { }).catch(function (reason) {
@ -459,7 +451,7 @@ describe('api', function () {
}); });
it('gets destinations, from /Names (NameTree) dictionary', function (done) { it('gets destinations, from /Names (NameTree) dictionary', function (done) {
var url = new URL('../pdfs/issue6204.pdf', window.location).href; var url = new URL('../pdfs/issue6204.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(url); var loadingTask = _global.PDFJS.getDocument(url);
var promise = loadingTask.promise.then(function (pdfDocument) { var promise = loadingTask.promise.then(function (pdfDocument) {
return pdfDocument.getDestinations(); return pdfDocument.getDestinations();
}); });
@ -482,7 +474,7 @@ describe('api', function () {
}); });
it('gets a destination, from /Names (NameTree) dictionary', function (done) { it('gets a destination, from /Names (NameTree) dictionary', function (done) {
var url = new URL('../pdfs/issue6204.pdf', window.location).href; var url = new URL('../pdfs/issue6204.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(url); var loadingTask = _global.PDFJS.getDocument(url);
var promise = loadingTask.promise.then(function (pdfDocument) { var promise = loadingTask.promise.then(function (pdfDocument) {
return pdfDocument.getDestination('Page.1'); return pdfDocument.getDestination('Page.1');
}); });
@ -499,7 +491,7 @@ describe('api', function () {
}); });
it('gets a non-existent destination, from /Names (NameTree) dictionary', function (done) { it('gets a non-existent destination, from /Names (NameTree) dictionary', function (done) {
var url = new URL('../pdfs/issue6204.pdf', window.location).href; var url = new URL('../pdfs/issue6204.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(url); var loadingTask = _global.PDFJS.getDocument(url);
var promise = loadingTask.promise.then(function (pdfDocument) { var promise = loadingTask.promise.then(function (pdfDocument) {
return pdfDocument.getDestination('non-existent-named-destination'); return pdfDocument.getDestination('non-existent-named-destination');
}); });
@ -522,22 +514,22 @@ describe('api', function () {
}); });
it('gets page labels', function (done) { it('gets page labels', function (done) {
var url0 = new URL('../pdfs/bug793632.pdf', window.location).href; var url0 = new URL('../pdfs/bug793632.pdf', window.location).href;
var loadingTask0 = PDFJS.getDocument(url0); var loadingTask0 = _global.PDFJS.getDocument(url0);
var promise0 = loadingTask0.promise.then(function (pdfDoc) { var promise0 = loadingTask0.promise.then(function (pdfDoc) {
return pdfDoc.getPageLabels(); return pdfDoc.getPageLabels();
}); });
var url1 = new URL('../pdfs/issue1453.pdf', window.location).href; var url1 = new URL('../pdfs/issue1453.pdf', window.location).href;
var loadingTask1 = PDFJS.getDocument(url1); var loadingTask1 = _global.PDFJS.getDocument(url1);
var promise1 = loadingTask1.promise.then(function (pdfDoc) { var promise1 = loadingTask1.promise.then(function (pdfDoc) {
return pdfDoc.getPageLabels(); return pdfDoc.getPageLabels();
}); });
var url2 = new URL('../pdfs/rotation.pdf', window.location).href; var url2 = new URL('../pdfs/rotation.pdf', window.location).href;
var loadingTask2 = PDFJS.getDocument(url2); var loadingTask2 = _global.PDFJS.getDocument(url2);
var promise2 = loadingTask2.promise.then(function (pdfDoc) { var promise2 = loadingTask2.promise.then(function (pdfDoc) {
return pdfDoc.getPageLabels(); return pdfDoc.getPageLabels();
}); });
var url3 = new URL('../pdfs/bad-PageLabels.pdf', window.location).href; var url3 = new URL('../pdfs/bad-PageLabels.pdf', window.location).href;
var loadingTask3 = PDFJS.getDocument(url3); var loadingTask3 = _global.PDFJS.getDocument(url3);
var promise3 = loadingTask3.promise.then(function (pdfDoc) { var promise3 = loadingTask3.promise.then(function (pdfDoc) {
return pdfDoc.getPageLabels(); return pdfDoc.getPageLabels();
}); });
@ -566,7 +558,7 @@ describe('api', function () {
}); });
it('gets attachments', function (done) { it('gets attachments', function (done) {
var url = new URL('../pdfs/bug766138.pdf', window.location).href; var url = new URL('../pdfs/bug766138.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(url); var loadingTask = _global.PDFJS.getDocument(url);
var promise = loadingTask.promise.then(function (pdfDoc) { var promise = loadingTask.promise.then(function (pdfDoc) {
return pdfDoc.getAttachments(); return pdfDoc.getAttachments();
}); });
@ -593,7 +585,7 @@ describe('api', function () {
var viewerPrintRegExp = /\bprint\s*\(/; var viewerPrintRegExp = /\bprint\s*\(/;
it('gets javascript with printing instructions (Print action)', function (done) { it('gets javascript with printing instructions (Print action)', function (done) {
var pdfUrl = new URL('../pdfs/bug1001080.pdf', window.location).href; var pdfUrl = new URL('../pdfs/bug1001080.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(pdfUrl); var loadingTask = _global.PDFJS.getDocument(pdfUrl);
var promise = loadingTask.promise.then(function (doc) { var promise = loadingTask.promise.then(function (doc) {
return doc.getJavaScript(); return doc.getJavaScript();
}); });
@ -608,7 +600,7 @@ describe('api', function () {
}); });
it('gets javascript with printing instructions (JS action)', function (done) { it('gets javascript with printing instructions (JS action)', function (done) {
var pdfUrl = new URL('../pdfs/issue6106.pdf', window.location).href; var pdfUrl = new URL('../pdfs/issue6106.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(pdfUrl); var loadingTask = _global.PDFJS.getDocument(pdfUrl);
var promise = loadingTask.promise.then(function (doc) { var promise = loadingTask.promise.then(function (doc) {
return doc.getJavaScript(); return doc.getJavaScript();
}); });
@ -623,7 +615,7 @@ describe('api', function () {
}); });
it('gets non-existent outline', function (done) { it('gets non-existent outline', function (done) {
var url = new URL('../pdfs/tracemonkey.pdf', window.location).href; var url = new URL('../pdfs/tracemonkey.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(url); var loadingTask = _global.PDFJS.getDocument(url);
var promise = loadingTask.promise.then(function (pdfDocument) { var promise = loadingTask.promise.then(function (pdfDocument) {
return pdfDocument.getOutline(); return pdfDocument.getOutline();
}); });
@ -658,7 +650,7 @@ describe('api', function () {
}); });
it('gets outline containing a url', function (done) { it('gets outline containing a url', function (done) {
var pdfUrl = new URL('../pdfs/issue3214.pdf', window.location).href; var pdfUrl = new URL('../pdfs/issue3214.pdf', window.location).href;
var loadingTask = PDFJS.getDocument(pdfUrl); var loadingTask = _global.PDFJS.getDocument(pdfUrl);
loadingTask.promise.then(function (pdfDocument) { loadingTask.promise.then(function (pdfDocument) {
pdfDocument.getOutline().then(function (outline) { pdfDocument.getOutline().then(function (outline) {
expect(outline instanceof Array).toEqual(true); expect(outline instanceof Array).toEqual(true);
@ -724,9 +716,9 @@ describe('api', function () {
}); });
it('checks that fingerprints are unique', function (done) { it('checks that fingerprints are unique', function (done) {
var url1 = new URL('../pdfs/issue4436r.pdf', window.location).href; var url1 = new URL('../pdfs/issue4436r.pdf', window.location).href;
var loadingTask1 = PDFJS.getDocument(url1); var loadingTask1 = _global.PDFJS.getDocument(url1);
var url2 = new URL('../pdfs/issue4575.pdf', window.location).href; var url2 = new URL('../pdfs/issue4575.pdf', window.location).href;
var loadingTask2 = PDFJS.getDocument(url2); var loadingTask2 = _global.PDFJS.getDocument(url2);
var promises = [loadingTask1.promise, loadingTask2.promise]; var promises = [loadingTask1.promise, loadingTask2.promise];
Promise.all(promises).then(function (data) { Promise.all(promises).then(function (data) {
var fingerprint1 = data[0].fingerprint; var fingerprint1 = data[0].fingerprint;
@ -748,7 +740,7 @@ describe('api', function () {
var loadingTask; var loadingTask;
var pdfDocument, page; var pdfDocument, page;
beforeAll(function (done) { beforeAll(function (done) {
loadingTask = PDFJS.getDocument(basicApiUrl); loadingTask = _global.PDFJS.getDocument(basicApiUrl);
loadingTask.promise.then(function (doc) { loadingTask.promise.then(function (doc) {
pdfDocument = doc; pdfDocument = doc;
pdfDocument.getPage(1).then(function (data) { pdfDocument.getPage(1).then(function (data) {
@ -807,13 +799,13 @@ describe('api', function () {
}); });
it('gets annotations containing relative URLs (bug 766086)', function (done) { it('gets annotations containing relative URLs (bug 766086)', function (done) {
var url = new URL('../pdfs/bug766086.pdf', window.location).href; var url = new URL('../pdfs/bug766086.pdf', window.location).href;
var defaultLoadingTask = PDFJS.getDocument(url); var defaultLoadingTask = _global.PDFJS.getDocument(url);
var defaultPromise = defaultLoadingTask.promise.then(function (pdfDoc) { var defaultPromise = defaultLoadingTask.promise.then(function (pdfDoc) {
return pdfDoc.getPage(1).then(function (pdfPage) { return pdfDoc.getPage(1).then(function (pdfPage) {
return pdfPage.getAnnotations(); return pdfPage.getAnnotations();
}); });
}); });
var docBaseUrlLoadingTask = PDFJS.getDocument({ var docBaseUrlLoadingTask = _global.PDFJS.getDocument({
url: url, url: url,
docBaseUrl: 'http://www.example.com/test/pdfs/qwerty.pdf' docBaseUrl: 'http://www.example.com/test/pdfs/qwerty.pdf'
}); });
@ -822,7 +814,7 @@ describe('api', function () {
return pdfPage.getAnnotations(); return pdfPage.getAnnotations();
}); });
}); });
var invalidDocBaseUrlLoadingTask = PDFJS.getDocument({ var invalidDocBaseUrlLoadingTask = _global.PDFJS.getDocument({
url: url, url: url,
docBaseUrl: 'qwerty.pdf' docBaseUrl: 'qwerty.pdf'
}); });
@ -882,10 +874,10 @@ describe('api', function () {
return pdfDocument.getStats(); return pdfDocument.getStats();
}); });
var expectedStreamTypes = []; var expectedStreamTypes = [];
expectedStreamTypes[StreamType.FLATE] = true; expectedStreamTypes[_util.StreamType.FLATE] = true;
var expectedFontTypes = []; var expectedFontTypes = [];
expectedFontTypes[FontType.TYPE1] = true; expectedFontTypes[_util.FontType.TYPE1] = true;
expectedFontTypes[FontType.CIDFONTTYPE2] = true; expectedFontTypes[_util.FontType.CIDFONTTYPE2] = true;
promise.then(function (stats) { promise.then(function (stats) {
expect(stats).toEqual({ expect(stats).toEqual({
streamTypes: expectedStreamTypes, streamTypes: expectedStreamTypes,
@ -907,7 +899,7 @@ describe('api', function () {
renderTask.promise.then(function () { renderTask.promise.then(function () {
done.fail('shall cancel rendering'); done.fail('shall cancel rendering');
}).catch(function (error) { }).catch(function (error) {
expect(error instanceof RenderingCancelledException).toEqual(true); expect(error instanceof _dom_utils.RenderingCancelledException).toEqual(true);
expect(error.type).toEqual('canvas'); expect(error.type).toEqual('canvas');
CanvasFactory.destroy(canvasAndCtx); CanvasFactory.destroy(canvasAndCtx);
done(); done();
@ -921,7 +913,7 @@ describe('api', function () {
var loadingTasks = []; var loadingTasks = [];
var pdfDocuments = []; var pdfDocuments = [];
function renderPDF(filename) { function renderPDF(filename) {
var loadingTask = PDFJS.getDocument(filename); var loadingTask = _global.PDFJS.getDocument(filename);
loadingTasks.push(loadingTask); loadingTasks.push(loadingTask);
return loadingTask.promise.then(function (pdf) { return loadingTask.promise.then(function (pdf) {
pdfDocuments.push(pdf); pdfDocuments.push(pdf);
@ -1001,7 +993,7 @@ describe('api', function () {
var fetches = 0; var fetches = 0;
var getDocumentPromise = getDocumentData().then(function (data) { var getDocumentPromise = getDocumentData().then(function (data) {
var initialData = data.subarray(0, initialDataLength); var initialData = data.subarray(0, initialDataLength);
transport = new PDFJS.PDFDataRangeTransport(data.length, initialData); transport = new _global.PDFJS.PDFDataRangeTransport(data.length, initialData);
transport.requestDataRange = function (begin, end) { transport.requestDataRange = function (begin, end) {
fetches++; fetches++;
waitSome(function () { waitSome(function () {
@ -1009,7 +1001,7 @@ describe('api', function () {
transport.onDataRange(begin, data.subarray(begin, end)); transport.onDataRange(begin, data.subarray(begin, end));
}); });
}; };
var loadingTask = PDFJS.getDocument(transport); var loadingTask = _global.PDFJS.getDocument(transport);
return loadingTask.promise; return loadingTask.promise;
}); });
var pdfDocument; var pdfDocument;
@ -1033,7 +1025,7 @@ describe('api', function () {
var fetches = 0; var fetches = 0;
var getDocumentPromise = getDocumentData().then(function (data) { var getDocumentPromise = getDocumentData().then(function (data) {
var initialData = data.subarray(0, initialDataLength); var initialData = data.subarray(0, initialDataLength);
transport = new PDFJS.PDFDataRangeTransport(data.length, initialData); transport = new _global.PDFJS.PDFDataRangeTransport(data.length, initialData);
transport.requestDataRange = function (begin, end) { transport.requestDataRange = function (begin, end) {
fetches++; fetches++;
if (fetches === 1) { if (fetches === 1) {
@ -1043,7 +1035,7 @@ describe('api', function () {
transport.onDataRange(begin, data.subarray(begin, end)); transport.onDataRange(begin, data.subarray(begin, end));
}); });
}; };
var loadingTask = PDFJS.getDocument(transport); var loadingTask = _global.PDFJS.getDocument(transport);
return loadingTask.promise; return loadingTask.promise;
}); });
var pdfDocument; var pdfDocument;

8
lib/test/unit/bidi_spec.js

@ -14,20 +14,20 @@
*/ */
'use strict'; 'use strict';
var coreBidi = require('../../core/bidi.js'); var _bidi = require('../../core/bidi');
var bidi = coreBidi.bidi;
describe('bidi', function () { describe('bidi', function () {
it('should mark text as RTL if more than 30% of text is RTL', function () { it('should mark text as RTL if more than 30% of text is RTL', function () {
var test = '\u0645\u0635\u0631 Egypt'; var test = '\u0645\u0635\u0631 Egypt';
var result = 'Egypt \u0631\u0635\u0645'; var result = 'Egypt \u0631\u0635\u0645';
var bidiText = bidi(test, -1, false); var bidiText = (0, _bidi.bidi)(test, -1, false);
expect(bidiText.str).toEqual(result); expect(bidiText.str).toEqual(result);
expect(bidiText.dir).toEqual('rtl'); expect(bidiText.dir).toEqual('rtl');
}); });
it('should mark text as LTR if less than 30% of text is RTL', function () { it('should mark text as LTR if less than 30% of text is RTL', function () {
var test = 'Egypt is known as \u0645\u0635\u0631 in Arabic.'; var test = 'Egypt is known as \u0645\u0635\u0631 in Arabic.';
var result = 'Egypt is known as \u0631\u0635\u0645 in Arabic.'; var result = 'Egypt is known as \u0631\u0635\u0645 in Arabic.';
var bidiText = bidi(test, -1, false); var bidiText = (0, _bidi.bidi)(test, -1, false);
expect(bidiText.str).toEqual(result); expect(bidiText.str).toEqual(result);
expect(bidiText.dir).toEqual('ltr'); expect(bidiText.dir).toEqual('ltr');
}); });

47
lib/test/unit/cff_parser_spec.js

@ -14,15 +14,12 @@
*/ */
'use strict'; 'use strict';
var coreCFFParser = require('../../core/cff_parser.js'); var _cff_parser = require('../../core/cff_parser');
var coreFonts = require('../../core/fonts.js');
var coreStream = require('../../core/stream.js'); var _fonts = require('../../core/fonts');
var CFFParser = coreCFFParser.CFFParser;
var CFFIndex = coreCFFParser.CFFIndex; var _stream = require('../../core/stream');
var CFFStrings = coreCFFParser.CFFStrings;
var CFFCompiler = coreCFFParser.CFFCompiler;
var SEAC_ANALYSIS_ENABLED = coreFonts.SEAC_ANALYSIS_ENABLED;
var Stream = coreStream.Stream;
describe('CFFParser', function () { describe('CFFParser', function () {
function createWithNullProto(obj) { function createWithNullProto(obj) {
var result = Object.create(null); var result = Object.create(null);
@ -39,14 +36,14 @@ describe('CFFParser', function () {
var hex = exampleFont.substr(i, 2); var hex = exampleFont.substr(i, 2);
fontArr.push(parseInt(hex, 16)); fontArr.push(parseInt(hex, 16));
} }
fontData = new Stream(fontArr); fontData = new _stream.Stream(fontArr);
done(); done();
}); });
afterAll(function () { afterAll(function () {
fontData = null; fontData = null;
}); });
beforeEach(function (done) { beforeEach(function (done) {
parser = new CFFParser(fontData, {}, SEAC_ANALYSIS_ENABLED); parser = new _cff_parser.CFFParser(fontData, {}, _fonts.SEAC_ANALYSIS_ENABLED);
cff = parser.parse(); cff = parser.parse();
done(); done();
}); });
@ -67,11 +64,11 @@ describe('CFFParser', function () {
expect(names[0]).toEqual('ABCDEF+Times-Roman'); expect(names[0]).toEqual('ABCDEF+Times-Roman');
}); });
it('sanitizes name index', function () { it('sanitizes name index', function () {
var index = new CFFIndex(); var index = new _cff_parser.CFFIndex();
index.add(['['.charCodeAt(0), 'a'.charCodeAt(0)]); index.add(['['.charCodeAt(0), 'a'.charCodeAt(0)]);
var names = parser.parseNameIndex(index); var names = parser.parseNameIndex(index);
expect(names).toEqual(['_a']); expect(names).toEqual(['_a']);
index = new CFFIndex(); index = new _cff_parser.CFFIndex();
var longName = []; var longName = [];
for (var i = 0; i < 129; i++) { for (var i = 0; i < 129; i++) {
longName.push(0); longName.push(0);
@ -124,7 +121,7 @@ describe('CFFParser', function () {
expect(charStrings.get(0).length).toEqual(38); expect(charStrings.get(0).length).toEqual(38);
}); });
it('parses a CharString endchar with 4 args w/seac enabled', function () { it('parses a CharString endchar with 4 args w/seac enabled', function () {
var parser = new CFFParser(fontData, {}, true); var parser = new _cff_parser.CFFParser(fontData, {}, true);
parser.parse(); parser.parse();
var bytes = new Uint8Array([0, 1, 1, 0, 237, 247, 22, 247, 72, 204, 247, 86, 14]); var bytes = new Uint8Array([0, 1, 1, 0, 237, 247, 22, 247, 72, 204, 247, 86, 14]);
parser.bytes = bytes; parser.bytes = bytes;
@ -140,7 +137,7 @@ describe('CFFParser', function () {
expect(result.seacs[0][3]).toEqual(194); expect(result.seacs[0][3]).toEqual(194);
}); });
it('parses a CharString endchar with 4 args w/seac disabled', function () { it('parses a CharString endchar with 4 args w/seac disabled', function () {
var parser = new CFFParser(fontData, {}, false); var parser = new _cff_parser.CFFParser(fontData, {}, false);
parser.parse(); parser.parse();
var bytes = new Uint8Array([0, 1, 1, 0, 237, 247, 22, 247, 72, 204, 247, 86, 14]); var bytes = new Uint8Array([0, 1, 1, 0, 237, 247, 22, 247, 72, 204, 247, 86, 14]);
parser.bytes = bytes; parser.bytes = bytes;
@ -166,37 +163,37 @@ describe('CFFParser', function () {
it('parses charset format 0', function () { it('parses charset format 0', function () {
var bytes = new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x02]); var bytes = new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x02]);
parser.bytes = bytes; parser.bytes = bytes;
var charset = parser.parseCharsets(3, 2, new CFFStrings(), false); var charset = parser.parseCharsets(3, 2, new _cff_parser.CFFStrings(), false);
expect(charset.charset[1]).toEqual('exclam'); expect(charset.charset[1]).toEqual('exclam');
charset = parser.parseCharsets(3, 2, new CFFStrings(), true); charset = parser.parseCharsets(3, 2, new _cff_parser.CFFStrings(), true);
expect(charset.charset[1]).toEqual(2); expect(charset.charset[1]).toEqual(2);
}); });
it('parses charset format 1', function () { it('parses charset format 1', function () {
var bytes = new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0x01]); var bytes = new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0x01]);
parser.bytes = bytes; parser.bytes = bytes;
var charset = parser.parseCharsets(3, 2, new CFFStrings(), false); var charset = parser.parseCharsets(3, 2, new _cff_parser.CFFStrings(), false);
expect(charset.charset).toEqual(['.notdef', 'quoteright', 'parenleft']); expect(charset.charset).toEqual(['.notdef', 'quoteright', 'parenleft']);
charset = parser.parseCharsets(3, 2, new CFFStrings(), true); charset = parser.parseCharsets(3, 2, new _cff_parser.CFFStrings(), true);
expect(charset.charset).toEqual(['.notdef', 8, 9]); expect(charset.charset).toEqual(['.notdef', 8, 9]);
}); });
it('parses charset format 2', function () { it('parses charset format 2', function () {
var bytes = new Uint8Array([0x00, 0x00, 0x00, 0x02, 0x00, 0x08, 0x00, 0x01]); var bytes = new Uint8Array([0x00, 0x00, 0x00, 0x02, 0x00, 0x08, 0x00, 0x01]);
parser.bytes = bytes; parser.bytes = bytes;
var charset = parser.parseCharsets(3, 2, new CFFStrings(), false); var charset = parser.parseCharsets(3, 2, new _cff_parser.CFFStrings(), false);
expect(charset.charset).toEqual(['.notdef', 'quoteright', 'parenleft']); expect(charset.charset).toEqual(['.notdef', 'quoteright', 'parenleft']);
charset = parser.parseCharsets(3, 2, new CFFStrings(), true); charset = parser.parseCharsets(3, 2, new _cff_parser.CFFStrings(), true);
expect(charset.charset).toEqual(['.notdef', 8, 9]); expect(charset.charset).toEqual(['.notdef', 8, 9]);
}); });
it('parses encoding format 0', function () { it('parses encoding format 0', function () {
var bytes = new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x08]); var bytes = new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x08]);
parser.bytes = bytes; parser.bytes = bytes;
var encoding = parser.parseEncoding(2, {}, new CFFStrings(), null); var encoding = parser.parseEncoding(2, {}, new _cff_parser.CFFStrings(), null);
expect(encoding.encoding).toEqual(createWithNullProto({ 0x8: 1 })); expect(encoding.encoding).toEqual(createWithNullProto({ 0x8: 1 }));
}); });
it('parses encoding format 1', function () { it('parses encoding format 1', function () {
var bytes = new Uint8Array([0x00, 0x00, 0x01, 0x01, 0x07, 0x01]); var bytes = new Uint8Array([0x00, 0x00, 0x01, 0x01, 0x07, 0x01]);
parser.bytes = bytes; parser.bytes = bytes;
var encoding = parser.parseEncoding(2, {}, new CFFStrings(), null); var encoding = parser.parseEncoding(2, {}, new _cff_parser.CFFStrings(), null);
expect(encoding.encoding).toEqual(createWithNullProto({ expect(encoding.encoding).toEqual(createWithNullProto({
0x7: 0x01, 0x7: 0x01,
0x08: 0x02 0x08: 0x02
@ -227,7 +224,7 @@ describe('CFFParser', function () {
}); });
describe('CFFCompiler', function () { describe('CFFCompiler', function () {
it('encodes integers', function () { it('encodes integers', function () {
var c = new CFFCompiler(); var c = new _cff_parser.CFFCompiler();
expect(c.encodeInteger(0)).toEqual([0x8b]); expect(c.encodeInteger(0)).toEqual([0x8b]);
expect(c.encodeInteger(100)).toEqual([0xef]); expect(c.encodeInteger(100)).toEqual([0xef]);
expect(c.encodeInteger(-100)).toEqual([0x27]); expect(c.encodeInteger(-100)).toEqual([0x27]);
@ -239,7 +236,7 @@ describe('CFFCompiler', function () {
expect(c.encodeInteger(-100000)).toEqual([0x1d, 0xff, 0xfe, 0x79, 0x60]); expect(c.encodeInteger(-100000)).toEqual([0x1d, 0xff, 0xfe, 0x79, 0x60]);
}); });
it('encodes floats', function () { it('encodes floats', function () {
var c = new CFFCompiler(); var c = new _cff_parser.CFFCompiler();
expect(c.encodeFloat(-2.25)).toEqual([0x1e, 0xe2, 0xa2, 0x5f]); expect(c.encodeFloat(-2.25)).toEqual([0x1e, 0xe2, 0xa2, 0x5f]);
expect(c.encodeFloat(5e-11)).toEqual([0x1e, 0x5c, 0x11, 0xff]); expect(c.encodeFloat(5e-11)).toEqual([0x1e, 0x5c, 0x11, 0xff]);
}); });

96
lib/test/unit/cmap_spec.js

@ -14,20 +14,18 @@
*/ */
'use strict'; 'use strict';
var coreCMap = require('../../core/cmap.js'); var _cmap = require('../../core/cmap');
var corePrimitives = require('../../core/primitives.js');
var coreStream = require('../../core/stream.js'); var _dom_utils = require('../../display/dom_utils');
var displayDOMUtils = require('../../display/dom_utils.js');
var sharedUtil = require('../../shared/util.js'); var _util = require('../../shared/util');
var testUnitTestUtils = require('./test_utils.js');
var CMapFactory = coreCMap.CMapFactory; var _primitives = require('../../core/primitives');
var CMap = coreCMap.CMap;
var IdentityCMap = coreCMap.IdentityCMap; var _test_utils = require('./test_utils');
var Name = corePrimitives.Name;
var StringStream = coreStream.StringStream; var _stream = require('../../core/stream');
var DOMCMapReaderFactory = displayDOMUtils.DOMCMapReaderFactory;
var isNodeJS = sharedUtil.isNodeJS;
var NodeCMapReaderFactory = testUnitTestUtils.NodeCMapReaderFactory;
var cMapUrl = { var cMapUrl = {
dom: '../../external/bcmaps/', dom: '../../external/bcmaps/',
node: './external/bcmaps/' node: './external/bcmaps/'
@ -37,13 +35,13 @@ describe('cmap', function () {
var fetchBuiltInCMap; var fetchBuiltInCMap;
beforeAll(function (done) { beforeAll(function (done) {
var CMapReaderFactory; var CMapReaderFactory;
if (isNodeJS()) { if ((0, _util.isNodeJS)()) {
CMapReaderFactory = new NodeCMapReaderFactory({ CMapReaderFactory = new _test_utils.NodeCMapReaderFactory({
baseUrl: cMapUrl.node, baseUrl: cMapUrl.node,
isCompressed: cMapPacked isCompressed: cMapPacked
}); });
} else { } else {
CMapReaderFactory = new DOMCMapReaderFactory({ CMapReaderFactory = new _dom_utils.DOMCMapReaderFactory({
baseUrl: cMapUrl.dom, baseUrl: cMapUrl.dom,
isCompressed: cMapPacked isCompressed: cMapPacked
}); });
@ -58,8 +56,8 @@ describe('cmap', function () {
}); });
it('parses beginbfchar', function (done) { it('parses beginbfchar', function (done) {
var str = '2 beginbfchar\n' + '<03> <00>\n' + '<04> <01>\n' + 'endbfchar\n'; var str = '2 beginbfchar\n' + '<03> <00>\n' + '<04> <01>\n' + 'endbfchar\n';
var stream = new StringStream(str); var stream = new _stream.StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = _cmap.CMapFactory.create({ encoding: stream });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
expect(cmap.lookup(0x03)).toEqual(String.fromCharCode(0x00)); expect(cmap.lookup(0x03)).toEqual(String.fromCharCode(0x00));
expect(cmap.lookup(0x04)).toEqual(String.fromCharCode(0x01)); expect(cmap.lookup(0x04)).toEqual(String.fromCharCode(0x01));
@ -71,8 +69,8 @@ describe('cmap', function () {
}); });
it('parses beginbfrange with range', function (done) { it('parses beginbfrange with range', function (done) {
var str = '1 beginbfrange\n' + '<06> <0B> 0\n' + 'endbfrange\n'; var str = '1 beginbfrange\n' + '<06> <0B> 0\n' + 'endbfrange\n';
var stream = new StringStream(str); var stream = new _stream.StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = _cmap.CMapFactory.create({ encoding: stream });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
expect(cmap.lookup(0x05)).toBeUndefined(); expect(cmap.lookup(0x05)).toBeUndefined();
expect(cmap.lookup(0x06)).toEqual(String.fromCharCode(0x00)); expect(cmap.lookup(0x06)).toEqual(String.fromCharCode(0x00));
@ -85,8 +83,8 @@ describe('cmap', function () {
}); });
it('parses beginbfrange with array', function (done) { it('parses beginbfrange with array', function (done) {
var str = '1 beginbfrange\n' + '<0D> <12> [ 0 1 2 3 4 5 ]\n' + 'endbfrange\n'; var str = '1 beginbfrange\n' + '<0D> <12> [ 0 1 2 3 4 5 ]\n' + 'endbfrange\n';
var stream = new StringStream(str); var stream = new _stream.StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = _cmap.CMapFactory.create({ encoding: stream });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
expect(cmap.lookup(0x0C)).toBeUndefined(); expect(cmap.lookup(0x0C)).toBeUndefined();
expect(cmap.lookup(0x0D)).toEqual(0x00); expect(cmap.lookup(0x0D)).toEqual(0x00);
@ -99,8 +97,8 @@ describe('cmap', function () {
}); });
it('parses begincidchar', function (done) { it('parses begincidchar', function (done) {
var str = '1 begincidchar\n' + '<14> 0\n' + 'endcidchar\n'; var str = '1 begincidchar\n' + '<14> 0\n' + 'endcidchar\n';
var stream = new StringStream(str); var stream = new _stream.StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = _cmap.CMapFactory.create({ encoding: stream });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
expect(cmap.lookup(0x14)).toEqual(0x00); expect(cmap.lookup(0x14)).toEqual(0x00);
expect(cmap.lookup(0x15)).toBeUndefined(); expect(cmap.lookup(0x15)).toBeUndefined();
@ -111,8 +109,8 @@ describe('cmap', function () {
}); });
it('parses begincidrange', function (done) { it('parses begincidrange', function (done) {
var str = '1 begincidrange\n' + '<0016> <001B> 0\n' + 'endcidrange\n'; var str = '1 begincidrange\n' + '<0016> <001B> 0\n' + 'endcidrange\n';
var stream = new StringStream(str); var stream = new _stream.StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = _cmap.CMapFactory.create({ encoding: stream });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
expect(cmap.lookup(0x15)).toBeUndefined(); expect(cmap.lookup(0x15)).toBeUndefined();
expect(cmap.lookup(0x16)).toEqual(0x00); expect(cmap.lookup(0x16)).toEqual(0x00);
@ -125,8 +123,8 @@ describe('cmap', function () {
}); });
it('decodes codespace ranges', function (done) { it('decodes codespace ranges', function (done) {
var str = '1 begincodespacerange\n' + '<01> <02>\n' + '<00000003> <00000004>\n' + 'endcodespacerange\n'; var str = '1 begincodespacerange\n' + '<01> <02>\n' + '<00000003> <00000004>\n' + 'endcodespacerange\n';
var stream = new StringStream(str); var stream = new _stream.StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = _cmap.CMapFactory.create({ encoding: stream });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
var c = {}; var c = {};
cmap.readCharCode(String.fromCharCode(1), 0, c); cmap.readCharCode(String.fromCharCode(1), 0, c);
@ -142,8 +140,8 @@ describe('cmap', function () {
}); });
it('decodes 4 byte codespace ranges', function (done) { it('decodes 4 byte codespace ranges', function (done) {
var str = '1 begincodespacerange\n' + '<8EA1A1A1> <8EA1FEFE>\n' + 'endcodespacerange\n'; var str = '1 begincodespacerange\n' + '<8EA1A1A1> <8EA1FEFE>\n' + 'endcodespacerange\n';
var stream = new StringStream(str); var stream = new _stream.StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = _cmap.CMapFactory.create({ encoding: stream });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
var c = {}; var c = {};
cmap.readCharCode(String.fromCharCode(0x8E, 0xA1, 0xA1, 0xA1), 0, c); cmap.readCharCode(String.fromCharCode(0x8E, 0xA1, 0xA1, 0xA1), 0, c);
@ -156,14 +154,14 @@ describe('cmap', function () {
}); });
it('read usecmap', function (done) { it('read usecmap', function (done) {
var str = '/Adobe-Japan1-1 usecmap\n'; var str = '/Adobe-Japan1-1 usecmap\n';
var stream = new StringStream(str); var stream = new _stream.StringStream(str);
var cmapPromise = CMapFactory.create({ var cmapPromise = _cmap.CMapFactory.create({
encoding: stream, encoding: stream,
fetchBuiltInCMap: fetchBuiltInCMap, fetchBuiltInCMap: fetchBuiltInCMap,
useCMap: null useCMap: null
}); });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
expect(cmap instanceof CMap).toEqual(true); expect(cmap instanceof _cmap.CMap).toEqual(true);
expect(cmap.useCMap).not.toBeNull(); expect(cmap.useCMap).not.toBeNull();
expect(cmap.builtInCMap).toBeFalsy(); expect(cmap.builtInCMap).toBeFalsy();
expect(cmap.length).toEqual(0x20A7); expect(cmap.length).toEqual(0x20A7);
@ -175,8 +173,8 @@ describe('cmap', function () {
}); });
it('parses cmapname', function (done) { it('parses cmapname', function (done) {
var str = '/CMapName /Identity-H def\n'; var str = '/CMapName /Identity-H def\n';
var stream = new StringStream(str); var stream = new _stream.StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = _cmap.CMapFactory.create({ encoding: stream });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
expect(cmap.name).toEqual('Identity-H'); expect(cmap.name).toEqual('Identity-H');
done(); done();
@ -186,8 +184,8 @@ describe('cmap', function () {
}); });
it('parses wmode', function (done) { it('parses wmode', function (done) {
var str = '/WMode 1 def\n'; var str = '/WMode 1 def\n';
var stream = new StringStream(str); var stream = new _stream.StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = _cmap.CMapFactory.create({ encoding: stream });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
expect(cmap.vertical).toEqual(true); expect(cmap.vertical).toEqual(true);
done(); done();
@ -196,13 +194,13 @@ describe('cmap', function () {
}); });
}); });
it('loads built in cmap', function (done) { it('loads built in cmap', function (done) {
var cmapPromise = CMapFactory.create({ var cmapPromise = _cmap.CMapFactory.create({
encoding: Name.get('Adobe-Japan1-1'), encoding: _primitives.Name.get('Adobe-Japan1-1'),
fetchBuiltInCMap: fetchBuiltInCMap, fetchBuiltInCMap: fetchBuiltInCMap,
useCMap: null useCMap: null
}); });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
expect(cmap instanceof CMap).toEqual(true); expect(cmap instanceof _cmap.CMap).toEqual(true);
expect(cmap.useCMap).toBeNull(); expect(cmap.useCMap).toBeNull();
expect(cmap.builtInCMap).toBeTruthy(); expect(cmap.builtInCMap).toBeTruthy();
expect(cmap.length).toEqual(0x20A7); expect(cmap.length).toEqual(0x20A7);
@ -213,13 +211,13 @@ describe('cmap', function () {
}); });
}); });
it('loads built in identity cmap', function (done) { it('loads built in identity cmap', function (done) {
var cmapPromise = CMapFactory.create({ var cmapPromise = _cmap.CMapFactory.create({
encoding: Name.get('Identity-H'), encoding: _primitives.Name.get('Identity-H'),
fetchBuiltInCMap: fetchBuiltInCMap, fetchBuiltInCMap: fetchBuiltInCMap,
useCMap: null useCMap: null
}); });
cmapPromise.then(function (cmap) { cmapPromise.then(function (cmap) {
expect(cmap instanceof IdentityCMap).toEqual(true); expect(cmap instanceof _cmap.IdentityCMap).toEqual(true);
expect(cmap.vertical).toEqual(false); expect(cmap.vertical).toEqual(false);
expect(cmap.length).toEqual(0x10000); expect(cmap.length).toEqual(0x10000);
expect(function () { expect(function () {
@ -231,8 +229,8 @@ describe('cmap', function () {
}); });
}); });
it('attempts to load a non-existent built-in CMap', function (done) { it('attempts to load a non-existent built-in CMap', function (done) {
var cmapPromise = CMapFactory.create({ var cmapPromise = _cmap.CMapFactory.create({
encoding: Name.get('null'), encoding: _primitives.Name.get('null'),
fetchBuiltInCMap: fetchBuiltInCMap, fetchBuiltInCMap: fetchBuiltInCMap,
useCMap: null useCMap: null
}); });
@ -246,11 +244,11 @@ describe('cmap', function () {
}); });
it('attempts to load a built-in CMap without the necessary API parameters', function (done) { it('attempts to load a built-in CMap without the necessary API parameters', function (done) {
function tmpFetchBuiltInCMap(name) { function tmpFetchBuiltInCMap(name) {
var CMapReaderFactory = isNodeJS() ? new NodeCMapReaderFactory({}) : new DOMCMapReaderFactory({}); var CMapReaderFactory = (0, _util.isNodeJS)() ? new _test_utils.NodeCMapReaderFactory({}) : new _dom_utils.DOMCMapReaderFactory({});
return CMapReaderFactory.fetch({ name: name }); return CMapReaderFactory.fetch({ name: name });
} }
var cmapPromise = CMapFactory.create({ var cmapPromise = _cmap.CMapFactory.create({
encoding: Name.get('Adobe-Japan1-1'), encoding: _primitives.Name.get('Adobe-Japan1-1'),
fetchBuiltInCMap: tmpFetchBuiltInCMap, fetchBuiltInCMap: tmpFetchBuiltInCMap,
useCMap: null useCMap: null
}); });

144
lib/test/unit/crypto_spec.js

@ -14,24 +14,12 @@
*/ */
'use strict'; 'use strict';
var coreCrypto = require('../../core/crypto.js'); var _crypto = require('../../core/crypto');
var corePrimitives = require('../../core/primitives.js');
var sharedUtil = require('../../shared/util.js'); var _primitives = require('../../core/primitives');
var calculateMD5 = coreCrypto.calculateMD5;
var ARCFourCipher = coreCrypto.ARCFourCipher; var _util = require('../../shared/util');
var calculateSHA256 = coreCrypto.calculateSHA256;
var calculateSHA384 = coreCrypto.calculateSHA384;
var calculateSHA512 = coreCrypto.calculateSHA512;
var AES128Cipher = coreCrypto.AES128Cipher;
var AES256Cipher = coreCrypto.AES256Cipher;
var PDF17 = coreCrypto.PDF17;
var PDF20 = coreCrypto.PDF20;
var CipherTransformFactory = coreCrypto.CipherTransformFactory;
var Name = corePrimitives.Name;
var Dict = corePrimitives.Dict;
var stringToBytes = sharedUtil.stringToBytes;
var PasswordException = sharedUtil.PasswordException;
var PasswordResponses = sharedUtil.PasswordResponses;
describe('crypto', function () { describe('crypto', function () {
function hex2binary(s) { function hex2binary(s) {
var digits = '0123456789ABCDEF'; var digits = '0123456789ABCDEF';
@ -51,50 +39,50 @@ describe('crypto', function () {
describe('calculateMD5', function () { describe('calculateMD5', function () {
it('should pass RFC 1321 test #1', function () { it('should pass RFC 1321 test #1', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes(''); input = (0, _util.stringToBytes)('');
result = calculateMD5(input, 0, input.length); result = (0, _crypto.calculateMD5)(input, 0, input.length);
expected = hex2binary('d41d8cd98f00b204e9800998ecf8427e'); expected = hex2binary('d41d8cd98f00b204e9800998ecf8427e');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it('should pass RFC 1321 test #2', function () { it('should pass RFC 1321 test #2', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('a'); input = (0, _util.stringToBytes)('a');
result = calculateMD5(input, 0, input.length); result = (0, _crypto.calculateMD5)(input, 0, input.length);
expected = hex2binary('0cc175b9c0f1b6a831c399e269772661'); expected = hex2binary('0cc175b9c0f1b6a831c399e269772661');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it('should pass RFC 1321 test #3', function () { it('should pass RFC 1321 test #3', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('abc'); input = (0, _util.stringToBytes)('abc');
result = calculateMD5(input, 0, input.length); result = (0, _crypto.calculateMD5)(input, 0, input.length);
expected = hex2binary('900150983cd24fb0d6963f7d28e17f72'); expected = hex2binary('900150983cd24fb0d6963f7d28e17f72');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it('should pass RFC 1321 test #4', function () { it('should pass RFC 1321 test #4', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('message digest'); input = (0, _util.stringToBytes)('message digest');
result = calculateMD5(input, 0, input.length); result = (0, _crypto.calculateMD5)(input, 0, input.length);
expected = hex2binary('f96b697d7cb7938d525a2f31aaf161d0'); expected = hex2binary('f96b697d7cb7938d525a2f31aaf161d0');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it('should pass RFC 1321 test #5', function () { it('should pass RFC 1321 test #5', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('abcdefghijklmnopqrstuvwxyz'); input = (0, _util.stringToBytes)('abcdefghijklmnopqrstuvwxyz');
result = calculateMD5(input, 0, input.length); result = (0, _crypto.calculateMD5)(input, 0, input.length);
expected = hex2binary('c3fcd3d76192e4007dfb496cca67e13b'); expected = hex2binary('c3fcd3d76192e4007dfb496cca67e13b');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it('should pass RFC 1321 test #6', function () { it('should pass RFC 1321 test #6', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv' + 'wxyz0123456789'); input = (0, _util.stringToBytes)('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv' + 'wxyz0123456789');
result = calculateMD5(input, 0, input.length); result = (0, _crypto.calculateMD5)(input, 0, input.length);
expected = hex2binary('d174ab98d277d9f5a5611c2c9f419d9f'); expected = hex2binary('d174ab98d277d9f5a5611c2c9f419d9f');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it('should pass RFC 1321 test #7', function () { it('should pass RFC 1321 test #7', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('123456789012345678901234567890123456789012345678' + '90123456789012345678901234567890'); input = (0, _util.stringToBytes)('123456789012345678901234567890123456789012345678' + '90123456789012345678901234567890');
result = calculateMD5(input, 0, input.length); result = (0, _crypto.calculateMD5)(input, 0, input.length);
expected = hex2binary('57edf4a22be3c955ac49da2e2107b67a'); expected = hex2binary('57edf4a22be3c955ac49da2e2107b67a');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
@ -104,7 +92,7 @@ describe('crypto', function () {
var key, input, result, expected, cipher; var key, input, result, expected, cipher;
key = hex2binary('0123456789abcdef'); key = hex2binary('0123456789abcdef');
input = hex2binary('0123456789abcdef'); input = hex2binary('0123456789abcdef');
cipher = new ARCFourCipher(key); cipher = new _crypto.ARCFourCipher(key);
result = cipher.encryptBlock(input); result = cipher.encryptBlock(input);
expected = hex2binary('75b7878099e0c596'); expected = hex2binary('75b7878099e0c596');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -113,7 +101,7 @@ describe('crypto', function () {
var key, input, result, expected, cipher; var key, input, result, expected, cipher;
key = hex2binary('0123456789abcdef'); key = hex2binary('0123456789abcdef');
input = hex2binary('0000000000000000'); input = hex2binary('0000000000000000');
cipher = new ARCFourCipher(key); cipher = new _crypto.ARCFourCipher(key);
result = cipher.encryptBlock(input); result = cipher.encryptBlock(input);
expected = hex2binary('7494c2e7104b0879'); expected = hex2binary('7494c2e7104b0879');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -122,7 +110,7 @@ describe('crypto', function () {
var key, input, result, expected, cipher; var key, input, result, expected, cipher;
key = hex2binary('0000000000000000'); key = hex2binary('0000000000000000');
input = hex2binary('0000000000000000'); input = hex2binary('0000000000000000');
cipher = new ARCFourCipher(key); cipher = new _crypto.ARCFourCipher(key);
result = cipher.encryptBlock(input); result = cipher.encryptBlock(input);
expected = hex2binary('de188941a3375d3a'); expected = hex2binary('de188941a3375d3a');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -131,7 +119,7 @@ describe('crypto', function () {
var key, input, result, expected, cipher; var key, input, result, expected, cipher;
key = hex2binary('ef012345'); key = hex2binary('ef012345');
input = hex2binary('00000000000000000000'); input = hex2binary('00000000000000000000');
cipher = new ARCFourCipher(key); cipher = new _crypto.ARCFourCipher(key);
result = cipher.encryptBlock(input); result = cipher.encryptBlock(input);
expected = hex2binary('d6a141a7ec3c38dfbd61'); expected = hex2binary('d6a141a7ec3c38dfbd61');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -140,7 +128,7 @@ describe('crypto', function () {
var key, input, result, expected, cipher; var key, input, result, expected, cipher;
key = hex2binary('0123456789abcdef'); key = hex2binary('0123456789abcdef');
input = hex2binary('010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '101010101010101010101'); input = hex2binary('010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '10101010101010101010101010101010101010101010101010101010101010101010' + '101010101010101010101');
cipher = new ARCFourCipher(key); cipher = new _crypto.ARCFourCipher(key);
result = cipher.encryptBlock(input); result = cipher.encryptBlock(input);
expected = hex2binary('7595c3e6114a09780c4ad452338e1ffd9a1be9498f813d76' + '533449b6778dcad8c78a8d2ba9ac66085d0e53d59c26c2d1c490c1ebbe0ce66d1b6b' + '1b13b6b919b847c25a91447a95e75e4ef16779cde8bf0a95850e32af9689444fd377' + '108f98fdcbd4e726567500990bcc7e0ca3c4aaa304a387d20f3b8fbbcd42a1bd311d' + '7a4303dda5ab078896ae80c18b0af66dff319616eb784e495ad2ce90d7f772a81747' + 'b65f62093b1e0db9e5ba532fafec47508323e671327df9444432cb7367cec82f5d44' + 'c0d00b67d650a075cd4b70dedd77eb9b10231b6b5b741347396d62897421d43df9b4' + '2e446e358e9c11a9b2184ecbef0cd8e7a877ef968f1390ec9b3d35a5585cb009290e' + '2fcde7b5ec66d9084be44055a619d9dd7fc3166f9487f7cb272912426445998514c1' + '5d53a18c864ce3a2b7555793988126520eacf2e3066e230c91bee4dd5304f5fd0405' + 'b35bd99c73135d3d9bc335ee049ef69b3867bf2d7bd1eaa595d8bfc0066ff8d31509' + 'eb0c6caa006c807a623ef84c3d33c195d23ee320c40de0558157c822d4b8c569d849' + 'aed59d4e0fd7f379586b4b7ff684ed6a189f7486d49b9c4bad9ba24b96abf924372c' + '8a8fffb10d55354900a77a3db5f205e1b99fcd8660863a159ad4abe40fa48934163d' + 'dde542a6585540fd683cbfd8c00f12129a284deacc4cdefe58be7137541c047126c8' + 'd49e2755ab181ab7e940b0c0'); expected = hex2binary('7595c3e6114a09780c4ad452338e1ffd9a1be9498f813d76' + '533449b6778dcad8c78a8d2ba9ac66085d0e53d59c26c2d1c490c1ebbe0ce66d1b6b' + '1b13b6b919b847c25a91447a95e75e4ef16779cde8bf0a95850e32af9689444fd377' + '108f98fdcbd4e726567500990bcc7e0ca3c4aaa304a387d20f3b8fbbcd42a1bd311d' + '7a4303dda5ab078896ae80c18b0af66dff319616eb784e495ad2ce90d7f772a81747' + 'b65f62093b1e0db9e5ba532fafec47508323e671327df9444432cb7367cec82f5d44' + 'c0d00b67d650a075cd4b70dedd77eb9b10231b6b5b741347396d62897421d43df9b4' + '2e446e358e9c11a9b2184ecbef0cd8e7a877ef968f1390ec9b3d35a5585cb009290e' + '2fcde7b5ec66d9084be44055a619d9dd7fc3166f9487f7cb272912426445998514c1' + '5d53a18c864ce3a2b7555793988126520eacf2e3066e230c91bee4dd5304f5fd0405' + 'b35bd99c73135d3d9bc335ee049ef69b3867bf2d7bd1eaa595d8bfc0066ff8d31509' + 'eb0c6caa006c807a623ef84c3d33c195d23ee320c40de0558157c822d4b8c569d849' + 'aed59d4e0fd7f379586b4b7ff684ed6a189f7486d49b9c4bad9ba24b96abf924372c' + '8a8fffb10d55354900a77a3db5f205e1b99fcd8660863a159ad4abe40fa48934163d' + 'dde542a6585540fd683cbfd8c00f12129a284deacc4cdefe58be7137541c047126c8' + 'd49e2755ab181ab7e940b0c0');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -149,7 +137,7 @@ describe('crypto', function () {
var key, input, result, expected, cipher; var key, input, result, expected, cipher;
key = hex2binary('fb029e3031323334'); key = hex2binary('fb029e3031323334');
input = hex2binary('aaaa0300000008004500004e661a00008011be640a0001220af' + 'fffff00890089003a000080a601100001000000000000204543454a4548454346434' + '550464545494546464343414341434143414341414100002000011bd0b604'); input = hex2binary('aaaa0300000008004500004e661a00008011be640a0001220af' + 'fffff00890089003a000080a601100001000000000000204543454a4548454346434' + '550464545494546464343414341434143414341414100002000011bd0b604');
cipher = new ARCFourCipher(key); cipher = new _crypto.ARCFourCipher(key);
result = cipher.encryptBlock(input); result = cipher.encryptBlock(input);
expected = hex2binary('f69c5806bd6ce84626bcbefb9474650aad1f7909b0f64d5f' + '58a503a258b7ed22eb0ea64930d3a056a55742fcce141d485f8aa836dea18df42c53' + '80805ad0c61a5d6f58f41040b24b7d1a693856ed0d4398e7aee3bf0e2a2ca8f7'); expected = hex2binary('f69c5806bd6ce84626bcbefb9474650aad1f7909b0f64d5f' + '58a503a258b7ed22eb0ea64930d3a056a55742fcce141d485f8aa836dea18df42c53' + '80805ad0c61a5d6f58f41040b24b7d1a693856ed0d4398e7aee3bf0e2a2ca8f7');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -158,7 +146,7 @@ describe('crypto', function () {
var key, input, result, expected, cipher; var key, input, result, expected, cipher;
key = hex2binary('0123456789abcdef'); key = hex2binary('0123456789abcdef');
input = hex2binary('123456789abcdef0123456789abcdef0123456789abcdef0123' + '45678'); input = hex2binary('123456789abcdef0123456789abcdef0123456789abcdef0123' + '45678');
cipher = new ARCFourCipher(key); cipher = new _crypto.ARCFourCipher(key);
result = cipher.encryptBlock(input); result = cipher.encryptBlock(input);
expected = hex2binary('66a0949f8af7d6891f7f832ba833c00c892ebe30143ce287' + '40011ecf'); expected = hex2binary('66a0949f8af7d6891f7f832ba833c00c892ebe30143ce287' + '40011ecf');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -167,15 +155,15 @@ describe('crypto', function () {
describe('calculateSHA256', function () { describe('calculateSHA256', function () {
it('should properly hash abc', function () { it('should properly hash abc', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('abc'); input = (0, _util.stringToBytes)('abc');
result = calculateSHA256(input, 0, input.length); result = (0, _crypto.calculateSHA256)(input, 0, input.length);
expected = hex2binary('BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9C' + 'B410FF61F20015AD'); expected = hex2binary('BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9C' + 'B410FF61F20015AD');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it('should properly hash a multiblock input', function () { it('should properly hash a multiblock input', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmno' + 'mnopnopq'); input = (0, _util.stringToBytes)('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmno' + 'mnopnopq');
result = calculateSHA256(input, 0, input.length); result = (0, _crypto.calculateSHA256)(input, 0, input.length);
expected = hex2binary('248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167' + 'F6ECEDD419DB06C1'); expected = hex2binary('248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167' + 'F6ECEDD419DB06C1');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
@ -183,15 +171,15 @@ describe('crypto', function () {
describe('calculateSHA384', function () { describe('calculateSHA384', function () {
it('should properly hash abc', function () { it('should properly hash abc', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('abc'); input = (0, _util.stringToBytes)('abc');
result = calculateSHA384(input, 0, input.length); result = (0, _crypto.calculateSHA384)(input, 0, input.length);
expected = hex2binary('CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED163' + '1A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7'); expected = hex2binary('CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED163' + '1A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it('should properly hash a multiblock input', function () { it('should properly hash a multiblock input', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('abcdefghbcdefghicdefghijdefghijkefghijklfghijklm' + 'ghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrs' + 'mnopqrstnopqrstu'); input = (0, _util.stringToBytes)('abcdefghbcdefghicdefghijdefghijkefghijklfghijklm' + 'ghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrs' + 'mnopqrstnopqrstu');
result = calculateSHA384(input, 0, input.length); result = (0, _crypto.calculateSHA384)(input, 0, input.length);
expected = hex2binary('09330C33F71147E83D192FC782CD1B4753111B173B3B05D2' + '2FA08086E3B0F712FCC7C71A557E2DB966C3E9FA91746039'); expected = hex2binary('09330C33F71147E83D192FC782CD1B4753111B173B3B05D2' + '2FA08086E3B0F712FCC7C71A557E2DB966C3E9FA91746039');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
@ -199,15 +187,15 @@ describe('crypto', function () {
describe('calculateSHA512', function () { describe('calculateSHA512', function () {
it('should properly hash abc', function () { it('should properly hash abc', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('abc'); input = (0, _util.stringToBytes)('abc');
result = calculateSHA512(input, 0, input.length); result = (0, _crypto.calculateSHA512)(input, 0, input.length);
expected = hex2binary('DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA2' + '0A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD' + '454D4423643CE80E2A9AC94FA54CA49F'); expected = hex2binary('DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA2' + '0A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD' + '454D4423643CE80E2A9AC94FA54CA49F');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it('should properly hash a multiblock input', function () { it('should properly hash a multiblock input', function () {
var input, result, expected; var input, result, expected;
input = stringToBytes('abcdefghbcdefghicdefghijdefghijkefghijklfghijklm' + 'ghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrs' + 'mnopqrstnopqrstu'); input = (0, _util.stringToBytes)('abcdefghbcdefghicdefghijdefghijkefghijklfghijklm' + 'ghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrs' + 'mnopqrstnopqrstu');
result = calculateSHA512(input, 0, input.length); result = (0, _crypto.calculateSHA512)(input, 0, input.length);
expected = hex2binary('8E959B75DAE313DA8CF4F72814FC143F8F7779C6EB9F7FA1' + '7299AEADB6889018501D289E4900F7E4331B99DEC4B5433A' + 'C7D329EEB6DD26545E96E55B874BE909'); expected = hex2binary('8E959B75DAE313DA8CF4F72814FC143F8F7779C6EB9F7FA1' + '7299AEADB6889018501D289E4900F7E4331B99DEC4B5433A' + 'C7D329EEB6DD26545E96E55B874BE909');
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
@ -219,7 +207,7 @@ describe('crypto', function () {
input = hex2binary('00112233445566778899aabbccddeeff'); input = hex2binary('00112233445566778899aabbccddeeff');
key = hex2binary('000102030405060708090a0b0c0d0e0f'); key = hex2binary('000102030405060708090a0b0c0d0e0f');
iv = hex2binary('00000000000000000000000000000000'); iv = hex2binary('00000000000000000000000000000000');
cipher = new AES128Cipher(key); cipher = new _crypto.AES128Cipher(key);
result = cipher.encrypt(input, iv); result = cipher.encrypt(input, iv);
expected = hex2binary('69c4e0d86a7b0430d8cdb78070b4c55a'); expected = hex2binary('69c4e0d86a7b0430d8cdb78070b4c55a');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -230,7 +218,7 @@ describe('crypto', function () {
var input, key, result, expected, cipher; var input, key, result, expected, cipher;
input = hex2binary('0000000000000000000000000000000069c4e0d86a7b0430d' + '8cdb78070b4c55a'); input = hex2binary('0000000000000000000000000000000069c4e0d86a7b0430d' + '8cdb78070b4c55a');
key = hex2binary('000102030405060708090a0b0c0d0e0f'); key = hex2binary('000102030405060708090a0b0c0d0e0f');
cipher = new AES128Cipher(key); cipher = new _crypto.AES128Cipher(key);
result = cipher.decryptBlock(input); result = cipher.decryptBlock(input);
expected = hex2binary('00112233445566778899aabbccddeeff'); expected = hex2binary('00112233445566778899aabbccddeeff');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -244,7 +232,7 @@ describe('crypto', function () {
input = hex2binary('00112233445566778899aabbccddeeff'); input = hex2binary('00112233445566778899aabbccddeeff');
key = hex2binary('000102030405060708090a0b0c0d0e0f101112131415161718' + '191a1b1c1d1e1f'); key = hex2binary('000102030405060708090a0b0c0d0e0f101112131415161718' + '191a1b1c1d1e1f');
iv = hex2binary('00000000000000000000000000000000'); iv = hex2binary('00000000000000000000000000000000');
cipher = new AES256Cipher(key); cipher = new _crypto.AES256Cipher(key);
result = cipher.encrypt(input, iv); result = cipher.encrypt(input, iv);
expected = hex2binary('8ea2b7ca516745bfeafc49904b496089'); expected = hex2binary('8ea2b7ca516745bfeafc49904b496089');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -256,7 +244,7 @@ describe('crypto', function () {
input = hex2binary('8ea2b7ca516745bfeafc49904b496089'); input = hex2binary('8ea2b7ca516745bfeafc49904b496089');
key = hex2binary('000102030405060708090a0b0c0d0e0f101112131415161718' + '191a1b1c1d1e1f'); key = hex2binary('000102030405060708090a0b0c0d0e0f101112131415161718' + '191a1b1c1d1e1f');
iv = hex2binary('00000000000000000000000000000000'); iv = hex2binary('00000000000000000000000000000000');
cipher = new AES256Cipher(key); cipher = new _crypto.AES256Cipher(key);
result = cipher.decryptBlock(input, false, iv); result = cipher.decryptBlock(input, false, iv);
expected = hex2binary('00112233445566778899aabbccddeeff'); expected = hex2binary('00112233445566778899aabbccddeeff');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -265,7 +253,7 @@ describe('crypto', function () {
var input, key, result, expected, cipher; var input, key, result, expected, cipher;
input = hex2binary('000000000000000000000000000000008ea2b7ca516745bf' + 'eafc49904b496089'); input = hex2binary('000000000000000000000000000000008ea2b7ca516745bf' + 'eafc49904b496089');
key = hex2binary('000102030405060708090a0b0c0d0e0f101112131415161718' + '191a1b1c1d1e1f'); key = hex2binary('000102030405060708090a0b0c0d0e0f101112131415161718' + '191a1b1c1d1e1f');
cipher = new AES256Cipher(key); cipher = new _crypto.AES256Cipher(key);
result = cipher.decryptBlock(input, false); result = cipher.decryptBlock(input, false);
expected = hex2binary('00112233445566778899aabbccddeeff'); expected = hex2binary('00112233445566778899aabbccddeeff');
expect(result).toEqual(expected); expect(result).toEqual(expected);
@ -275,7 +263,7 @@ describe('crypto', function () {
describe('PDF17Algorithm', function () { describe('PDF17Algorithm', function () {
it('should correctly check a user key', function () { it('should correctly check a user key', function () {
var password, userValidation, userPassword, alg, result; var password, userValidation, userPassword, alg, result;
alg = new PDF17(); alg = new _crypto.PDF17();
password = new Uint8Array([117, 115, 101, 114]); password = new Uint8Array([117, 115, 101, 114]);
userValidation = new Uint8Array([117, 169, 4, 32, 159, 101, 22, 220]); userValidation = new Uint8Array([117, 169, 4, 32, 159, 101, 22, 220]);
userPassword = new Uint8Array([131, 242, 143, 160, 87, 2, 138, 134, 79, 253, 189, 173, 224, 73, 144, 241, 190, 81, 197, 15, 249, 105, 145, 151, 15, 194, 65, 3, 1, 126, 187, 221]); userPassword = new Uint8Array([131, 242, 143, 160, 87, 2, 138, 134, 79, 253, 189, 173, 224, 73, 144, 241, 190, 81, 197, 15, 249, 105, 145, 151, 15, 194, 65, 3, 1, 126, 187, 221]);
@ -284,7 +272,7 @@ describe('crypto', function () {
}); });
it('should correctly check an owner key', function () { it('should correctly check an owner key', function () {
var password, ownerValidation, ownerPassword, alg, result, uBytes; var password, ownerValidation, ownerPassword, alg, result, uBytes;
alg = new PDF17(); alg = new _crypto.PDF17();
password = new Uint8Array([111, 119, 110, 101, 114]); password = new Uint8Array([111, 119, 110, 101, 114]);
ownerValidation = new Uint8Array([243, 118, 71, 153, 128, 17, 101, 62]); ownerValidation = new Uint8Array([243, 118, 71, 153, 128, 17, 101, 62]);
ownerPassword = new Uint8Array([60, 98, 137, 35, 51, 101, 200, 152, 210, 178, 226, 228, 134, 205, 163, 24, 204, 126, 177, 36, 106, 50, 36, 125, 210, 172, 171, 120, 222, 108, 139, 115]); ownerPassword = new Uint8Array([60, 98, 137, 35, 51, 101, 200, 152, 210, 178, 226, 228, 134, 205, 163, 24, 204, 126, 177, 36, 106, 50, 36, 125, 210, 172, 171, 120, 222, 108, 139, 115]);
@ -294,7 +282,7 @@ describe('crypto', function () {
}); });
it('should generate a file encryption key from the user key', function () { it('should generate a file encryption key from the user key', function () {
var password, userKeySalt, expected, alg, result, userEncryption; var password, userKeySalt, expected, alg, result, userEncryption;
alg = new PDF17(); alg = new _crypto.PDF17();
password = new Uint8Array([117, 115, 101, 114]); password = new Uint8Array([117, 115, 101, 114]);
userKeySalt = new Uint8Array([168, 94, 215, 192, 100, 38, 188, 40]); userKeySalt = new Uint8Array([168, 94, 215, 192, 100, 38, 188, 40]);
userEncryption = new Uint8Array([35, 150, 195, 169, 245, 51, 51, 255, 158, 158, 33, 242, 231, 75, 125, 190, 25, 126, 172, 114, 195, 244, 137, 245, 234, 165, 42, 74, 60, 38, 17, 17]); userEncryption = new Uint8Array([35, 150, 195, 169, 245, 51, 51, 255, 158, 158, 33, 242, 231, 75, 125, 190, 25, 126, 172, 114, 195, 244, 137, 245, 234, 165, 42, 74, 60, 38, 17, 17]);
@ -305,7 +293,7 @@ describe('crypto', function () {
it('should generate a file encryption key from the owner key', function () { it('should generate a file encryption key from the owner key', function () {
var password, ownerKeySalt, expected, alg, result, ownerEncryption; var password, ownerKeySalt, expected, alg, result, ownerEncryption;
var uBytes; var uBytes;
alg = new PDF17(); alg = new _crypto.PDF17();
password = new Uint8Array([111, 119, 110, 101, 114]); password = new Uint8Array([111, 119, 110, 101, 114]);
ownerKeySalt = new Uint8Array([200, 245, 242, 12, 218, 123, 24, 120]); ownerKeySalt = new Uint8Array([200, 245, 242, 12, 218, 123, 24, 120]);
ownerEncryption = new Uint8Array([213, 202, 14, 189, 110, 76, 70, 191, 6, 195, 10, 190, 157, 100, 144, 85, 8, 62, 123, 178, 156, 229, 50, 40, 229, 216, 54, 222, 34, 38, 106, 223]); ownerEncryption = new Uint8Array([213, 202, 14, 189, 110, 76, 70, 191, 6, 195, 10, 190, 157, 100, 144, 85, 8, 62, 123, 178, 156, 229, 50, 40, 229, 216, 54, 222, 34, 38, 106, 223]);
@ -318,7 +306,7 @@ describe('crypto', function () {
describe('PDF20Algorithm', function () { describe('PDF20Algorithm', function () {
it('should correctly check a user key', function () { it('should correctly check a user key', function () {
var password, userValidation, userPassword, alg, result; var password, userValidation, userPassword, alg, result;
alg = new PDF20(); alg = new _crypto.PDF20();
password = new Uint8Array([117, 115, 101, 114]); password = new Uint8Array([117, 115, 101, 114]);
userValidation = new Uint8Array([83, 245, 146, 101, 198, 247, 34, 198]); userValidation = new Uint8Array([83, 245, 146, 101, 198, 247, 34, 198]);
userPassword = new Uint8Array([94, 230, 205, 75, 166, 99, 250, 76, 219, 128, 17, 85, 57, 17, 33, 164, 150, 46, 103, 176, 160, 156, 187, 233, 166, 223, 163, 253, 147, 235, 95, 184]); userPassword = new Uint8Array([94, 230, 205, 75, 166, 99, 250, 76, 219, 128, 17, 85, 57, 17, 33, 164, 150, 46, 103, 176, 160, 156, 187, 233, 166, 223, 163, 253, 147, 235, 95, 184]);
@ -327,7 +315,7 @@ describe('crypto', function () {
}); });
it('should correctly check an owner key', function () { it('should correctly check an owner key', function () {
var password, ownerValidation, ownerPassword, alg, result, uBytes; var password, ownerValidation, ownerPassword, alg, result, uBytes;
alg = new PDF20(); alg = new _crypto.PDF20();
password = new Uint8Array([111, 119, 110, 101, 114]); password = new Uint8Array([111, 119, 110, 101, 114]);
ownerValidation = new Uint8Array([142, 232, 169, 208, 202, 214, 5, 185]); ownerValidation = new Uint8Array([142, 232, 169, 208, 202, 214, 5, 185]);
ownerPassword = new Uint8Array([88, 232, 62, 54, 245, 26, 245, 209, 137, 123, 221, 72, 199, 49, 37, 217, 31, 74, 115, 167, 127, 158, 176, 77, 45, 163, 87, 47, 39, 90, 217, 141]); ownerPassword = new Uint8Array([88, 232, 62, 54, 245, 26, 245, 209, 137, 123, 221, 72, 199, 49, 37, 217, 31, 74, 115, 167, 127, 158, 176, 77, 45, 163, 87, 47, 39, 90, 217, 141]);
@ -337,7 +325,7 @@ describe('crypto', function () {
}); });
it('should generate a file encryption key from the user key', function () { it('should generate a file encryption key from the user key', function () {
var password, userKeySalt, expected, alg, result, userEncryption; var password, userKeySalt, expected, alg, result, userEncryption;
alg = new PDF20(); alg = new _crypto.PDF20();
password = new Uint8Array([117, 115, 101, 114]); password = new Uint8Array([117, 115, 101, 114]);
userKeySalt = new Uint8Array([191, 11, 16, 94, 237, 216, 20, 175]); userKeySalt = new Uint8Array([191, 11, 16, 94, 237, 216, 20, 175]);
userEncryption = new Uint8Array([121, 208, 2, 181, 230, 89, 156, 60, 253, 143, 212, 28, 84, 180, 196, 177, 173, 128, 221, 107, 46, 20, 94, 186, 135, 51, 95, 24, 20, 223, 254, 36]); userEncryption = new Uint8Array([121, 208, 2, 181, 230, 89, 156, 60, 253, 143, 212, 28, 84, 180, 196, 177, 173, 128, 221, 107, 46, 20, 94, 186, 135, 51, 95, 24, 20, 223, 254, 36]);
@ -348,7 +336,7 @@ describe('crypto', function () {
it('should generate a file encryption key from the owner key', function () { it('should generate a file encryption key from the owner key', function () {
var password, ownerKeySalt, expected, alg, result, ownerEncryption; var password, ownerKeySalt, expected, alg, result, ownerEncryption;
var uBytes; var uBytes;
alg = new PDF20(); alg = new _crypto.PDF20();
password = new Uint8Array([111, 119, 110, 101, 114]); password = new Uint8Array([111, 119, 110, 101, 114]);
ownerKeySalt = new Uint8Array([29, 208, 185, 46, 11, 76, 135, 149]); ownerKeySalt = new Uint8Array([29, 208, 185, 46, 11, 76, 135, 149]);
ownerEncryption = new Uint8Array([209, 73, 224, 77, 103, 155, 201, 181, 190, 68, 223, 20, 62, 90, 56, 210, 5, 240, 178, 128, 238, 124, 68, 254, 253, 244, 62, 108, 208, 135, 10, 251]); ownerEncryption = new Uint8Array([209, 73, 224, 77, 103, 155, 201, 181, 190, 68, 223, 20, 62, 90, 56, 210, 5, 240, 178, 128, 238, 124, 68, 254, 253, 244, 62, 108, 208, 135, 10, 251]);
@ -361,7 +349,7 @@ describe('crypto', function () {
}); });
describe('CipherTransformFactory', function () { describe('CipherTransformFactory', function () {
function buildDict(map) { function buildDict(map) {
var dict = new Dict(); var dict = new _primitives.Dict();
for (var key in map) { for (var key in map) {
dict.set(key, map[key]); dict.set(key, map[key]);
} }
@ -369,7 +357,7 @@ describe('CipherTransformFactory', function () {
} }
function ensurePasswordCorrect(done, dict, fileId, password) { function ensurePasswordCorrect(done, dict, fileId, password) {
try { try {
var factory = new CipherTransformFactory(dict, fileId, password); var factory = new _crypto.CipherTransformFactory(dict, fileId, password);
expect('createCipherTransform' in factory).toEqual(true); expect('createCipherTransform' in factory).toEqual(true);
} catch (ex) { } catch (ex) {
done.fail('Password should be accepted: ' + ex); done.fail('Password should be accepted: ' + ex);
@ -379,10 +367,10 @@ describe('CipherTransformFactory', function () {
} }
function ensurePasswordNeeded(done, dict, fileId, password) { function ensurePasswordNeeded(done, dict, fileId, password) {
try { try {
new CipherTransformFactory(dict, fileId, password); new _crypto.CipherTransformFactory(dict, fileId, password);
} catch (ex) { } catch (ex) {
expect(ex instanceof PasswordException).toEqual(true); expect(ex instanceof _util.PasswordException).toEqual(true);
expect(ex.code).toEqual(PasswordResponses.NEED_PASSWORD); expect(ex.code).toEqual(_util.PasswordResponses.NEED_PASSWORD);
done(); done();
return; return;
} }
@ -390,10 +378,10 @@ describe('CipherTransformFactory', function () {
} }
function ensurePasswordIncorrect(done, dict, fileId, password) { function ensurePasswordIncorrect(done, dict, fileId, password) {
try { try {
new CipherTransformFactory(dict, fileId, password); new _crypto.CipherTransformFactory(dict, fileId, password);
} catch (ex) { } catch (ex) {
expect(ex instanceof PasswordException).toEqual(true); expect(ex instanceof _util.PasswordException).toEqual(true);
expect(ex.code).toEqual(PasswordResponses.INCORRECT_PASSWORD); expect(ex.code).toEqual(_util.PasswordResponses.INCORRECT_PASSWORD);
done(); done();
return; return;
} }
@ -405,7 +393,7 @@ describe('CipherTransformFactory', function () {
fileId1 = unescape('%F6%C6%AF%17%F3rR%8DRM%9A%80%D1%EF%DF%18'); fileId1 = unescape('%F6%C6%AF%17%F3rR%8DRM%9A%80%D1%EF%DF%18');
fileId2 = unescape('%3CL_%3AD%96%AF@%9A%9D%B3%3Cx%1Cv%AC'); fileId2 = unescape('%3CL_%3AD%96%AF@%9A%9D%B3%3Cx%1Cv%AC');
dict1 = buildDict({ dict1 = buildDict({
Filter: Name.get('Standard'), Filter: _primitives.Name.get('Standard'),
V: 2, V: 2,
Length: 128, Length: 128,
O: unescape('%80%C3%04%96%91o%20sl%3A%E6%1B%13T%91%F2%0DV%12%E3%FF%5E%B' + 'B%E9VO%D8k%9A%CA%7C%5D'), O: unescape('%80%C3%04%96%91o%20sl%3A%E6%1B%13T%91%F2%0DV%12%E3%FF%5E%B' + 'B%E9VO%D8k%9A%CA%7C%5D'),
@ -414,7 +402,7 @@ describe('CipherTransformFactory', function () {
R: 3 R: 3
}); });
dict2 = buildDict({ dict2 = buildDict({
Filter: Name.get('Standard'), Filter: _primitives.Name.get('Standard'),
V: 4, V: 4,
Length: 128, Length: 128,
O: unescape('sF%14v.y5%27%DB%97%0A5%22%B3%E1%D4%AD%BD%9B%3C%B4%A5%89u%1' + '5%B2Y%F1h%D9%E9%F4'), O: unescape('sF%14v.y5%27%DB%97%0A5%22%B3%E1%D4%AD%BD%9B%3C%B4%A5%89u%1' + '5%B2Y%F1h%D9%E9%F4'),
@ -423,7 +411,7 @@ describe('CipherTransformFactory', function () {
R: 4 R: 4
}); });
aes256Dict = buildDict({ aes256Dict = buildDict({
Filter: Name.get('Standard'), Filter: _primitives.Name.get('Standard'),
V: 5, V: 5,
Length: 256, Length: 256,
O: unescape('%3Cb%89%233e%C8%98%D2%B2%E2%E4%86%CD%A3%18%CC%7E%B1%24j2%2' + '4%7D%D2%AC%ABx%DEl%8Bs%F3vG%99%80%11e%3E%C8%F5%F2%0C%DA%7B' + '%18x'), O: unescape('%3Cb%89%233e%C8%98%D2%B2%E2%E4%86%CD%A3%18%CC%7E%B1%24j2%2' + '4%7D%D2%AC%ABx%DEl%8Bs%F3vG%99%80%11e%3E%C8%F5%F2%0C%DA%7B' + '%18x'),
@ -435,7 +423,7 @@ describe('CipherTransformFactory', function () {
R: 5 R: 5
}); });
aes256IsoDict = buildDict({ aes256IsoDict = buildDict({
Filter: Name.get('Standard'), Filter: _primitives.Name.get('Standard'),
V: 5, V: 5,
Length: 256, Length: 256,
O: unescape('X%E8%3E6%F5%1A%F5%D1%89%7B%DDH%C71%25%D9%1FJs%A7%7F%9E%B0M' + '-%A3W/%27Z%D9%8D%8E%E8%A9%D0%CA%D6%05%B9%1D%D0%B9.%0BL%87%' + '95'), O: unescape('X%E8%3E6%F5%1A%F5%D1%89%7B%DDH%C71%25%D9%1FJs%A7%7F%9E%B0M' + '-%A3W/%27Z%D9%8D%8E%E8%A9%D0%CA%D6%05%B9%1D%D0%B9.%0BL%87%' + '95'),
@ -447,7 +435,7 @@ describe('CipherTransformFactory', function () {
R: 6 R: 6
}); });
aes256BlankDict = buildDict({ aes256BlankDict = buildDict({
Filter: Name.get('Standard'), Filter: _primitives.Name.get('Standard'),
V: 5, V: 5,
Length: 256, Length: 256,
O: unescape('%B8p%04%C3g%26%FCW%CCN%D4%16%A1%E8%950YZ%C9%9E%B1-%97%F3%F' + 'E%03%13%19ffZn%8F%F5%EB%EC%CC5sV%10e%CEl%B5%E9G%C1'), O: unescape('%B8p%04%C3g%26%FCW%CCN%D4%16%A1%E8%950YZ%C9%9E%B1-%97%F3%F' + 'E%03%13%19ffZn%8F%F5%EB%EC%CC5sV%10e%CEl%B5%E9G%C1'),
@ -459,7 +447,7 @@ describe('CipherTransformFactory', function () {
R: 5 R: 5
}); });
aes256IsoBlankDict = buildDict({ aes256IsoBlankDict = buildDict({
Filter: Name.get('Standard'), Filter: _primitives.Name.get('Standard'),
V: 5, V: 5,
Length: 256, Length: 256,
O: unescape('%F7%DB%99U%A6M%ACk%AF%CF%D7AFw%E9%C1%91%CBDgI%23R%CF%0C%15' + 'r%D74%0D%CE%E9%91@%E4%98QF%BF%88%7Ej%DE%AD%8F%F4@%C1'), O: unescape('%F7%DB%99U%A6M%ACk%AF%CF%D7AFw%E9%C1%91%CBDgI%23R%CF%0C%15' + 'r%D74%0D%CE%E9%91@%E4%98QF%BF%88%7Ej%DE%AD%8F%F4@%C1'),

8
lib/test/unit/document_spec.js

@ -14,13 +14,13 @@
*/ */
'use strict'; 'use strict';
var coreDocument = require('../../core/document.js'); var _document = require('../../core/document');
var Page = coreDocument.Page;
describe('document', function () { describe('document', function () {
describe('Page', function () { describe('Page', function () {
it('should create correct objId using the idFactory', function () { it('should create correct objId using the idFactory', function () {
var page1 = new Page({}, null, 0, null, null, null, null); var page1 = new _document.Page({}, null, 0, null, null, null, null);
var page2 = new Page({}, null, 1, null, null, null, null); var page2 = new _document.Page({}, null, 1, null, null, null, null);
var idFactory1 = page1.idFactory, var idFactory1 = page1.idFactory,
idFactory2 = page2.idFactory; idFactory2 = page2.idFactory;
expect(idFactory1.createObjId()).toEqual('p0_1'); expect(idFactory1.createObjId()).toEqual('p0_1');

30
lib/test/unit/dom_utils_spec.js

@ -14,23 +14,21 @@
*/ */
'use strict'; 'use strict';
var displayDOMUtils = require('../../display/dom_utils.js'); var _dom_utils = require('../../display/dom_utils');
var displayGlobal = require('../../display/global.js');
var PDFJS = displayGlobal.PDFJS; var _global = require('../../display/global');
var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
var LinkTarget = displayDOMUtils.LinkTarget;
var isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
describe('dom_utils', function () { describe('dom_utils', function () {
describe('getFilenameFromUrl', function () { describe('getFilenameFromUrl', function () {
it('should get the filename from an absolute URL', function () { it('should get the filename from an absolute URL', function () {
var url = 'http://server.org/filename.pdf'; var url = 'http://server.org/filename.pdf';
var result = getFilenameFromUrl(url); var result = (0, _dom_utils.getFilenameFromUrl)(url);
var expected = 'filename.pdf'; var expected = 'filename.pdf';
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it('should get the filename from a relative URL', function () { it('should get the filename from a relative URL', function () {
var url = '../../filename.pdf'; var url = '../../filename.pdf';
var result = getFilenameFromUrl(url); var result = (0, _dom_utils.getFilenameFromUrl)(url);
var expected = 'filename.pdf'; var expected = 'filename.pdf';
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
@ -38,25 +36,25 @@ describe('dom_utils', function () {
describe('isExternalLinkTargetSet', function () { describe('isExternalLinkTargetSet', function () {
var savedExternalLinkTarget; var savedExternalLinkTarget;
beforeAll(function (done) { beforeAll(function (done) {
savedExternalLinkTarget = PDFJS.externalLinkTarget; savedExternalLinkTarget = _global.PDFJS.externalLinkTarget;
done(); done();
}); });
afterAll(function () { afterAll(function () {
PDFJS.externalLinkTarget = savedExternalLinkTarget; _global.PDFJS.externalLinkTarget = savedExternalLinkTarget;
}); });
it('handles the predefined LinkTargets', function () { it('handles the predefined LinkTargets', function () {
for (var key in LinkTarget) { for (var key in _dom_utils.LinkTarget) {
var linkTarget = LinkTarget[key]; var linkTarget = _dom_utils.LinkTarget[key];
PDFJS.externalLinkTarget = linkTarget; _global.PDFJS.externalLinkTarget = linkTarget;
expect(isExternalLinkTargetSet()).toEqual(!!linkTarget); expect((0, _dom_utils.isExternalLinkTargetSet)()).toEqual(!!linkTarget);
} }
}); });
it('handles incorrect LinkTargets', function () { it('handles incorrect LinkTargets', function () {
var targets = [true, '', false, -1, '_blank', null]; var targets = [true, '', false, -1, '_blank', null];
for (var i = 0, ii = targets.length; i < ii; i++) { for (var i = 0, ii = targets.length; i < ii; i++) {
var linkTarget = targets[i]; var linkTarget = targets[i];
PDFJS.externalLinkTarget = linkTarget; _global.PDFJS.externalLinkTarget = linkTarget;
expect(isExternalLinkTargetSet()).toEqual(false); expect((0, _dom_utils.isExternalLinkTargetSet)()).toEqual(false);
} }
}); });
}); });

161
lib/test/unit/evaluator_spec.js

@ -14,19 +14,16 @@
*/ */
'use strict'; 'use strict';
var coreEvaluator = require('../../core/evaluator.js'); var _primitives = require('../../core/primitives');
var corePrimitives = require('../../core/primitives.js');
var coreStream = require('../../core/stream.js'); var _evaluator = require('../../core/evaluator');
var coreWorker = require('../../core/worker.js');
var sharedUtil = require('../../shared/util.js'); var _stream = require('../../core/stream');
var OperatorList = coreEvaluator.OperatorList;
var PartialEvaluator = coreEvaluator.PartialEvaluator; var _util = require('../../shared/util');
var Dict = corePrimitives.Dict;
var Name = corePrimitives.Name; var _worker = require('../../core/worker');
var Stream = coreStream.Stream;
var StringStream = coreStream.StringStream;
var WorkerTask = coreWorker.WorkerTask;
var OPS = sharedUtil.OPS;
describe('evaluator', function () { describe('evaluator', function () {
function XrefMock(queue) { function XrefMock(queue) {
this.queue = queue || []; this.queue = queue || [];
@ -55,81 +52,81 @@ describe('evaluator', function () {
}; };
function PdfManagerMock() {} function PdfManagerMock() {}
function runOperatorListCheck(evaluator, stream, resources, callback) { function runOperatorListCheck(evaluator, stream, resources, callback) {
var result = new OperatorList(); var result = new _evaluator.OperatorList();
var task = new WorkerTask('OperatorListCheck'); var task = new _worker.WorkerTask('OperatorListCheck');
evaluator.getOperatorList(stream, task, resources, result).then(function () { evaluator.getOperatorList(stream, task, resources, result).then(function () {
callback(result); callback(result);
}); });
} }
describe('splitCombinedOperations', function () { describe('splitCombinedOperations', function () {
it('should reject unknown operations', function (done) { it('should reject unknown operations', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('fTT'); var stream = new _stream.StringStream('fTT');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(!!result.fnArray && !!result.argsArray).toEqual(true);
expect(result.fnArray.length).toEqual(1); expect(result.fnArray.length).toEqual(1);
expect(result.fnArray[0]).toEqual(OPS.fill); expect(result.fnArray[0]).toEqual(_util.OPS.fill);
expect(result.argsArray[0]).toEqual(null); expect(result.argsArray[0]).toEqual(null);
done(); done();
}); });
}); });
it('should handle one operations', function (done) { it('should handle one operations', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('Q'); var stream = new _stream.StringStream('Q');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(!!result.fnArray && !!result.argsArray).toEqual(true);
expect(result.fnArray.length).toEqual(1); expect(result.fnArray.length).toEqual(1);
expect(result.fnArray[0]).toEqual(OPS.restore); expect(result.fnArray[0]).toEqual(_util.OPS.restore);
done(); done();
}); });
}); });
it('should handle two glued operations', function (done) { it('should handle two glued operations', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var resources = new ResourcesMock(); var resources = new ResourcesMock();
resources.Res1 = {}; resources.Res1 = {};
var stream = new StringStream('/Res1 DoQ'); var stream = new _stream.StringStream('/Res1 DoQ');
runOperatorListCheck(evaluator, stream, resources, function (result) { runOperatorListCheck(evaluator, stream, resources, function (result) {
expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(!!result.fnArray && !!result.argsArray).toEqual(true);
expect(result.fnArray.length).toEqual(2); expect(result.fnArray.length).toEqual(2);
expect(result.fnArray[0]).toEqual(OPS.paintXObject); expect(result.fnArray[0]).toEqual(_util.OPS.paintXObject);
expect(result.fnArray[1]).toEqual(OPS.restore); expect(result.fnArray[1]).toEqual(_util.OPS.restore);
done(); done();
}); });
}); });
it('should handle tree glued operations', function (done) { it('should handle tree glued operations', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('fff'); var stream = new _stream.StringStream('fff');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(!!result.fnArray && !!result.argsArray).toEqual(true);
expect(result.fnArray.length).toEqual(3); expect(result.fnArray.length).toEqual(3);
expect(result.fnArray[0]).toEqual(OPS.fill); expect(result.fnArray[0]).toEqual(_util.OPS.fill);
expect(result.fnArray[1]).toEqual(OPS.fill); expect(result.fnArray[1]).toEqual(_util.OPS.fill);
expect(result.fnArray[2]).toEqual(OPS.fill); expect(result.fnArray[2]).toEqual(_util.OPS.fill);
done(); done();
}); });
}); });
it('should handle three glued operations #2', function (done) { it('should handle three glued operations #2', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var resources = new ResourcesMock(); var resources = new ResourcesMock();
resources.Res1 = {}; resources.Res1 = {};
var stream = new StringStream('B*Bf*'); var stream = new _stream.StringStream('B*Bf*');
runOperatorListCheck(evaluator, stream, resources, function (result) { runOperatorListCheck(evaluator, stream, resources, function (result) {
expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(!!result.fnArray && !!result.argsArray).toEqual(true);
expect(result.fnArray.length).toEqual(3); expect(result.fnArray.length).toEqual(3);
expect(result.fnArray[0]).toEqual(OPS.eoFillStroke); expect(result.fnArray[0]).toEqual(_util.OPS.eoFillStroke);
expect(result.fnArray[1]).toEqual(OPS.fillStroke); expect(result.fnArray[1]).toEqual(_util.OPS.fillStroke);
expect(result.fnArray[2]).toEqual(OPS.eoFill); expect(result.fnArray[2]).toEqual(_util.OPS.eoFill);
done(); done();
}); });
}); });
it('should handle glued operations and operands', function (done) { it('should handle glued operations and operands', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('f5 Ts'); var stream = new _stream.StringStream('f5 Ts');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(!!result.fnArray && !!result.argsArray).toEqual(true);
expect(result.fnArray.length).toEqual(2); expect(result.fnArray.length).toEqual(2);
expect(result.fnArray[0]).toEqual(OPS.fill); expect(result.fnArray[0]).toEqual(_util.OPS.fill);
expect(result.fnArray[1]).toEqual(OPS.setTextRise); expect(result.fnArray[1]).toEqual(_util.OPS.setTextRise);
expect(result.argsArray.length).toEqual(2); expect(result.argsArray.length).toEqual(2);
expect(result.argsArray[1].length).toEqual(1); expect(result.argsArray[1].length).toEqual(1);
expect(result.argsArray[1][0]).toEqual(5); expect(result.argsArray[1][0]).toEqual(5);
@ -137,14 +134,14 @@ describe('evaluator', function () {
}); });
}); });
it('should handle glued operations and literals', function (done) { it('should handle glued operations and literals', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('trueifalserinulln'); var stream = new _stream.StringStream('trueifalserinulln');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(!!result.fnArray && !!result.argsArray).toEqual(true);
expect(result.fnArray.length).toEqual(3); expect(result.fnArray.length).toEqual(3);
expect(result.fnArray[0]).toEqual(OPS.setFlatness); expect(result.fnArray[0]).toEqual(_util.OPS.setFlatness);
expect(result.fnArray[1]).toEqual(OPS.setRenderingIntent); expect(result.fnArray[1]).toEqual(_util.OPS.setRenderingIntent);
expect(result.fnArray[2]).toEqual(OPS.endPath); expect(result.fnArray[2]).toEqual(_util.OPS.endPath);
expect(result.argsArray.length).toEqual(3); expect(result.argsArray.length).toEqual(3);
expect(result.argsArray[0].length).toEqual(1); expect(result.argsArray[0].length).toEqual(1);
expect(result.argsArray[0][0]).toEqual(true); expect(result.argsArray[0][0]).toEqual(true);
@ -157,33 +154,33 @@ describe('evaluator', function () {
}); });
describe('validateNumberOfArgs', function () { describe('validateNumberOfArgs', function () {
it('should execute if correct number of arguments', function (done) { it('should execute if correct number of arguments', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('5 1 d0'); var stream = new _stream.StringStream('5 1 d0');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(result.argsArray[0][0]).toEqual(5); expect(result.argsArray[0][0]).toEqual(5);
expect(result.argsArray[0][1]).toEqual(1); expect(result.argsArray[0][1]).toEqual(1);
expect(result.fnArray[0]).toEqual(OPS.setCharWidth); expect(result.fnArray[0]).toEqual(_util.OPS.setCharWidth);
done(); done();
}); });
}); });
it('should execute if too many arguments', function (done) { it('should execute if too many arguments', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('5 1 4 d0'); var stream = new _stream.StringStream('5 1 4 d0');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(result.argsArray[0][0]).toEqual(1); expect(result.argsArray[0][0]).toEqual(1);
expect(result.argsArray[0][1]).toEqual(4); expect(result.argsArray[0][1]).toEqual(4);
expect(result.fnArray[0]).toEqual(OPS.setCharWidth); expect(result.fnArray[0]).toEqual(_util.OPS.setCharWidth);
done(); done();
}); });
}); });
it('should execute if nested commands', function (done) { it('should execute if nested commands', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('/F2 /GS2 gs 5.711 Tf'); var stream = new _stream.StringStream('/F2 /GS2 gs 5.711 Tf');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(result.fnArray.length).toEqual(3); expect(result.fnArray.length).toEqual(3);
expect(result.fnArray[0]).toEqual(OPS.setGState); expect(result.fnArray[0]).toEqual(_util.OPS.setGState);
expect(result.fnArray[1]).toEqual(OPS.dependency); expect(result.fnArray[1]).toEqual(_util.OPS.dependency);
expect(result.fnArray[2]).toEqual(OPS.setFont); expect(result.fnArray[2]).toEqual(_util.OPS.setFont);
expect(result.argsArray.length).toEqual(3); expect(result.argsArray.length).toEqual(3);
expect(result.argsArray[0].length).toEqual(1); expect(result.argsArray[0].length).toEqual(1);
expect(result.argsArray[1].length).toEqual(1); expect(result.argsArray[1].length).toEqual(1);
@ -192,8 +189,8 @@ describe('evaluator', function () {
}); });
}); });
it('should skip if too few arguments', function (done) { it('should skip if too few arguments', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('5 d0'); var stream = new _stream.StringStream('5 d0');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(result.argsArray).toEqual([]); expect(result.argsArray).toEqual([]);
expect(result.fnArray).toEqual([]); expect(result.fnArray).toEqual([]);
@ -201,21 +198,21 @@ describe('evaluator', function () {
}); });
}); });
it('should close opened saves', function (done) { it('should close opened saves', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('qq'); var stream = new _stream.StringStream('qq');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(!!result.fnArray && !!result.argsArray).toEqual(true);
expect(result.fnArray.length).toEqual(4); expect(result.fnArray.length).toEqual(4);
expect(result.fnArray[0]).toEqual(OPS.save); expect(result.fnArray[0]).toEqual(_util.OPS.save);
expect(result.fnArray[1]).toEqual(OPS.save); expect(result.fnArray[1]).toEqual(_util.OPS.save);
expect(result.fnArray[2]).toEqual(OPS.restore); expect(result.fnArray[2]).toEqual(_util.OPS.restore);
expect(result.fnArray[3]).toEqual(OPS.restore); expect(result.fnArray[3]).toEqual(_util.OPS.restore);
done(); done();
}); });
}); });
it('should skip paintXObject if name is missing', function (done) { it('should skip paintXObject if name is missing', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('/ Do'); var stream = new _stream.StringStream('/ Do');
runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) { runOperatorListCheck(evaluator, stream, new ResourcesMock(), function (result) {
expect(result.argsArray).toEqual([]); expect(result.argsArray).toEqual([]);
expect(result.fnArray).toEqual([]); expect(result.fnArray).toEqual([]);
@ -223,15 +220,15 @@ describe('evaluator', function () {
}); });
}); });
it('should skip paintXObject if subtype is PS', function (done) { it('should skip paintXObject if subtype is PS', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var xobjStreamDict = new Dict(); var xobjStreamDict = new _primitives.Dict();
xobjStreamDict.set('Subtype', Name.get('PS')); xobjStreamDict.set('Subtype', _primitives.Name.get('PS'));
var xobjStream = new Stream([], 0, 0, xobjStreamDict); var xobjStream = new _stream.Stream([], 0, 0, xobjStreamDict);
var xobjs = new Dict(); var xobjs = new _primitives.Dict();
xobjs.set('Res1', xobjStream); xobjs.set('Res1', xobjStream);
var resources = new Dict(); var resources = new _primitives.Dict();
resources.set('XObject', xobjs); resources.set('XObject', xobjs);
var stream = new StringStream('/Res1 Do'); var stream = new _stream.StringStream('/Res1 Do');
runOperatorListCheck(evaluator, stream, resources, function (result) { runOperatorListCheck(evaluator, stream, resources, function (result) {
expect(result.argsArray).toEqual([]); expect(result.argsArray).toEqual([]);
expect(result.fnArray).toEqual([]); expect(result.fnArray).toEqual([]);
@ -241,11 +238,11 @@ describe('evaluator', function () {
}); });
describe('thread control', function () { describe('thread control', function () {
it('should abort operator list parsing', function (done) { it('should abort operator list parsing', function (done) {
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('qqQQ'); var stream = new _stream.StringStream('qqQQ');
var resources = new ResourcesMock(); var resources = new ResourcesMock();
var result = new OperatorList(); var result = new _evaluator.OperatorList();
var task = new WorkerTask('OperatorListAbort'); var task = new _worker.WorkerTask('OperatorListAbort');
task.terminate(); task.terminate();
evaluator.getOperatorList(stream, task, resources, result).catch(function () { evaluator.getOperatorList(stream, task, resources, result).catch(function () {
expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(!!result.fnArray && !!result.argsArray).toEqual(true);
@ -255,9 +252,9 @@ describe('evaluator', function () {
}); });
it('should abort text parsing parsing', function (done) { it('should abort text parsing parsing', function (done) {
var resources = new ResourcesMock(); var resources = new ResourcesMock();
var evaluator = new PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix'); var evaluator = new _evaluator.PartialEvaluator(new PdfManagerMock(), new XrefMock(), new HandlerMock(), 'prefix');
var stream = new StringStream('qqQQ'); var stream = new _stream.StringStream('qqQQ');
var task = new WorkerTask('TextContentAbort'); var task = new _worker.WorkerTask('TextContentAbort');
task.terminate(); task.terminate();
evaluator.getTextContent(stream, task, resources).catch(function () { evaluator.getTextContent(stream, task, resources).catch(function () {
expect(true).toEqual(true); expect(true).toEqual(true);
@ -271,9 +268,9 @@ describe('evaluator', function () {
send: function send() {} send: function send() {}
}; };
it('should get correct total length after flushing', function () { it('should get correct total length after flushing', function () {
var operatorList = new OperatorList(null, new MessageHandlerMock()); var operatorList = new _evaluator.OperatorList(null, new MessageHandlerMock());
operatorList.addOp(OPS.save, null); operatorList.addOp(_util.OPS.save, null);
operatorList.addOp(OPS.restore, null); operatorList.addOp(_util.OPS.restore, null);
expect(operatorList.totalLength).toEqual(2); expect(operatorList.totalLength).toEqual(2);
expect(operatorList.length).toEqual(2); expect(operatorList.length).toEqual(2);
operatorList.flush(); operatorList.flush();

20
lib/test/unit/fonts_spec.js

@ -14,17 +14,15 @@
*/ */
'use strict'; 'use strict';
var coreFonts = require('../../core/fonts.js'); var _fonts = require('../../core/fonts');
var sharedUtil = require('../../shared/util.js');
var ProblematicCharRanges = coreFonts.ProblematicCharRanges; var _util = require('../../shared/util');
var PRIVATE_USE_OFFSET_START = coreFonts.PRIVATE_USE_OFFSET_START;
var PRIVATE_USE_OFFSET_END = coreFonts.PRIVATE_USE_OFFSET_END;
var isInt = sharedUtil.isInt;
var checkProblematicCharRanges = function checkProblematicCharRanges() { var checkProblematicCharRanges = function checkProblematicCharRanges() {
function printRange(limits) { function printRange(limits) {
return '[' + limits.lower.toString('16').toUpperCase() + ', ' + limits.upper.toString('16').toUpperCase() + ')'; return '[' + limits.lower.toString('16').toUpperCase() + ', ' + limits.upper.toString('16').toUpperCase() + ')';
} }
var numRanges = ProblematicCharRanges.length; var numRanges = _fonts.ProblematicCharRanges.length;
if (numRanges % 2 !== 0) { if (numRanges % 2 !== 0) {
throw new Error('Char ranges must contain an even number of elements.'); throw new Error('Char ranges must contain an even number of elements.');
} }
@ -32,10 +30,10 @@ var checkProblematicCharRanges = function checkProblematicCharRanges() {
numChars = 0; numChars = 0;
for (var i = 0; i < numRanges; i += 2) { for (var i = 0; i < numRanges; i += 2) {
var limits = { var limits = {
lower: ProblematicCharRanges[i], lower: _fonts.ProblematicCharRanges[i],
upper: ProblematicCharRanges[i + 1] upper: _fonts.ProblematicCharRanges[i + 1]
}; };
if (!isInt(limits.lower) || !isInt(limits.upper)) { if (!(0, _util.isInt)(limits.lower) || !(0, _util.isInt)(limits.upper)) {
throw new Error('Range endpoints must be integers: ' + printRange(limits)); throw new Error('Range endpoints must be integers: ' + printRange(limits));
} }
if (limits.lower < 0 || limits.upper < 0) { if (limits.lower < 0 || limits.upper < 0) {
@ -59,7 +57,7 @@ var checkProblematicCharRanges = function checkProblematicCharRanges() {
}; };
numChars += range; numChars += range;
} }
var puaLength = PRIVATE_USE_OFFSET_END + 1 - PRIVATE_USE_OFFSET_START; var puaLength = _fonts.PRIVATE_USE_OFFSET_END + 1 - _fonts.PRIVATE_USE_OFFSET_START;
if (numChars > puaLength) { if (numChars > puaLength) {
throw new Error('Total number of chars must not exceed the PUA length.'); throw new Error('Total number of chars must not exceed the PUA length.');
} }

34
lib/test/unit/function_spec.js

@ -14,16 +14,14 @@
*/ */
'use strict'; 'use strict';
var coreFunction = require('../../core/function.js'); var _function = require('../../core/function');
var corePsParser = require('../../core/ps_parser.js');
var coreStream = require('../../core/stream.js'); var _ps_parser = require('../../core/ps_parser');
var sharedUtil = require('../../shared/util.js');
var PostScriptEvaluator = coreFunction.PostScriptEvaluator; var _util = require('../../shared/util');
var PostScriptCompiler = coreFunction.PostScriptCompiler;
var PostScriptParser = corePsParser.PostScriptParser; var _stream = require('../../core/stream');
var PostScriptLexer = corePsParser.PostScriptLexer;
var StringStream = coreStream.StringStream;
var isArray = sharedUtil.isArray;
describe('function', function () { describe('function', function () {
beforeEach(function () { beforeEach(function () {
jasmine.addMatchers({ jasmine.addMatchers({
@ -40,7 +38,7 @@ describe('function', function () {
for (var i = 0; i < expected.length; i++) { for (var i = 0; i < expected.length; i++) {
var a = actual[i], var a = actual[i],
b = expected[i]; b = expected[i];
if (isArray(b)) { if ((0, _util.isArray)(b)) {
if (a.length !== b.length) { if (a.length !== b.length) {
result.pass = false; result.pass = false;
break; break;
@ -68,8 +66,8 @@ describe('function', function () {
}); });
describe('PostScriptParser', function () { describe('PostScriptParser', function () {
function parse(program) { function parse(program) {
var stream = new StringStream(program); var stream = new _stream.StringStream(program);
var parser = new PostScriptParser(new PostScriptLexer(stream)); var parser = new _ps_parser.PostScriptParser(new _ps_parser.PostScriptLexer(stream));
return parser.parse(); return parser.parse();
} }
it('parses empty programs', function () { it('parses empty programs', function () {
@ -123,10 +121,10 @@ describe('function', function () {
}); });
describe('PostScriptEvaluator', function () { describe('PostScriptEvaluator', function () {
function evaluate(program) { function evaluate(program) {
var stream = new StringStream(program); var stream = new _stream.StringStream(program);
var parser = new PostScriptParser(new PostScriptLexer(stream)); var parser = new _ps_parser.PostScriptParser(new _ps_parser.PostScriptLexer(stream));
var code = parser.parse(); var code = parser.parse();
var evaluator = new PostScriptEvaluator(code); var evaluator = new _function.PostScriptEvaluator(code);
var output = evaluator.execute(); var output = evaluator.execute();
return output; return output;
} }
@ -443,7 +441,7 @@ describe('function', function () {
}); });
describe('PostScriptCompiler', function () { describe('PostScriptCompiler', function () {
function check(code, domain, range, samples) { function check(code, domain, range, samples) {
var compiler = new PostScriptCompiler(); var compiler = new _function.PostScriptCompiler();
var compiledCode = compiler.compile(code, domain, range); var compiledCode = compiler.compile(code, domain, range);
if (samples === null) { if (samples === null) {
expect(compiledCode).toBeNull(); expect(compiledCode).toBeNull();
@ -619,7 +617,7 @@ describe('function', function () {
}]); }]);
}); });
it('compile optimized', function () { it('compile optimized', function () {
var compiler = new PostScriptCompiler(); var compiler = new _function.PostScriptCompiler();
var code = [0, 'add', 1, 1, 3, -1, 'roll', 'sub', 'sub', 1, 'mul']; var code = [0, 'add', 1, 1, 3, -1, 'roll', 'sub', 'sub', 1, 'mul'];
var compiledCode = compiler.compile(code, [0, 1], [0, 1]); var compiledCode = compiler.compile(code, [0, 1], [0, 1]);
expect(compiledCode).toEqual('dest[destOffset + 0] = Math.max(0, Math.min(1, src[srcOffset + 0]));'); expect(compiledCode).toEqual('dest[destOffset + 0] = Math.max(0, Math.min(1, src[srcOffset + 0]));');

6
lib/test/unit/metadata_spec.js

@ -14,13 +14,13 @@
*/ */
'use strict'; 'use strict';
var displayMetadata = require('../../display/metadata.js'); var _metadata = require('../../display/metadata');
var Metadata = displayMetadata.Metadata;
describe('metadata', function () { describe('metadata', function () {
describe('incorrect_xmp', function () { describe('incorrect_xmp', function () {
it('should fix the incorrect XMP data', function () { it('should fix the incorrect XMP data', function () {
var invalidXMP = '<x:xmpmeta xmlns:x=\'adobe:ns:meta/\'>' + '<rdf:RDF xmlns:rdf=\'http://www.w3.org/1999/02/22-rdf-syntax-ns#\'>' + '<rdf:Description xmlns:dc=\'http://purl.org/dc/elements/1.1/\'>' + '<dc:title>\\376\\377\\000P\\000D\\000F\\000&</dc:title>' + '</rdf:Description></rdf:RDF></x:xmpmeta>'; var invalidXMP = '<x:xmpmeta xmlns:x=\'adobe:ns:meta/\'>' + '<rdf:RDF xmlns:rdf=\'http://www.w3.org/1999/02/22-rdf-syntax-ns#\'>' + '<rdf:Description xmlns:dc=\'http://purl.org/dc/elements/1.1/\'>' + '<dc:title>\\376\\377\\000P\\000D\\000F\\000&</dc:title>' + '</rdf:Description></rdf:RDF></x:xmpmeta>';
var meta = new Metadata(invalidXMP); var meta = new _metadata.Metadata(invalidXMP);
expect(meta.get('dc:title')).toEqual('PDF&'); expect(meta.get('dc:title')).toEqual('PDF&');
}); });
}); });

22
lib/test/unit/murmurhash3_spec.js

@ -14,37 +14,37 @@
*/ */
'use strict'; 'use strict';
var coreMurmurHash3 = require('../../core/murmurhash3.js'); var _murmurhash = require('../../core/murmurhash3');
var MurmurHash3_64 = coreMurmurHash3.MurmurHash3_64;
describe('MurmurHash3_64', function () { describe('MurmurHash3_64', function () {
it('instantiates without seed', function () { it('instantiates without seed', function () {
var hash = new MurmurHash3_64(); var hash = new _murmurhash.MurmurHash3_64();
expect(hash).toEqual(jasmine.any(MurmurHash3_64)); expect(hash).toEqual(jasmine.any(_murmurhash.MurmurHash3_64));
}); });
it('instantiates with seed', function () { it('instantiates with seed', function () {
var hash = new MurmurHash3_64(1); var hash = new _murmurhash.MurmurHash3_64(1);
expect(hash).toEqual(jasmine.any(MurmurHash3_64)); expect(hash).toEqual(jasmine.any(_murmurhash.MurmurHash3_64));
}); });
var hexDigestExpected = 'f61cfdbfdae0f65e'; var hexDigestExpected = 'f61cfdbfdae0f65e';
var sourceText = 'test'; var sourceText = 'test';
var sourceCharCodes = [116, 101, 115, 116]; var sourceCharCodes = [116, 101, 115, 116];
it('correctly generates a hash from a string', function () { it('correctly generates a hash from a string', function () {
var hash = new MurmurHash3_64(); var hash = new _murmurhash.MurmurHash3_64();
hash.update(sourceText); hash.update(sourceText);
expect(hash.hexdigest()).toEqual(hexDigestExpected); expect(hash.hexdigest()).toEqual(hexDigestExpected);
}); });
it('correctly generates a hash from a Uint8Array', function () { it('correctly generates a hash from a Uint8Array', function () {
var hash = new MurmurHash3_64(); var hash = new _murmurhash.MurmurHash3_64();
hash.update(new Uint8Array(sourceCharCodes)); hash.update(new Uint8Array(sourceCharCodes));
expect(hash.hexdigest()).toEqual(hexDigestExpected); expect(hash.hexdigest()).toEqual(hexDigestExpected);
}); });
it('correctly generates a hash from a Uint32Array', function () { it('correctly generates a hash from a Uint32Array', function () {
var hash = new MurmurHash3_64(); var hash = new _murmurhash.MurmurHash3_64();
hash.update(new Uint32Array(new Uint8Array(sourceCharCodes).buffer)); hash.update(new Uint32Array(new Uint8Array(sourceCharCodes).buffer));
expect(hash.hexdigest()).toEqual(hexDigestExpected); expect(hash.hexdigest()).toEqual(hexDigestExpected);
}); });
it('changes the hash after update without seed', function () { it('changes the hash after update without seed', function () {
var hash = new MurmurHash3_64(); var hash = new _murmurhash.MurmurHash3_64();
var hexdigest1, hexdigest2; var hexdigest1, hexdigest2;
hash.update(sourceText); hash.update(sourceText);
hexdigest1 = hash.hexdigest(); hexdigest1 = hash.hexdigest();
@ -53,7 +53,7 @@ describe('MurmurHash3_64', function () {
expect(hexdigest1).not.toEqual(hexdigest2); expect(hexdigest1).not.toEqual(hexdigest2);
}); });
it('changes the hash after update with seed', function () { it('changes the hash after update with seed', function () {
var hash = new MurmurHash3_64(1); var hash = new _murmurhash.MurmurHash3_64(1);
var hexdigest1, hexdigest2; var hexdigest1, hexdigest2;
hash.update(sourceText); hash.update(sourceText);
hexdigest1 = hash.hexdigest(); hexdigest1 = hash.hexdigest();

10
lib/test/unit/network_spec.js

@ -14,15 +14,15 @@
*/ */
'use strict'; 'use strict';
var coreNetwork = require('../../core/network.js'); var _network = require('../../core/network');
var PDFNetworkStream = coreNetwork.PDFNetworkStream;
describe('network', function () { describe('network', function () {
var pdf1 = new URL('../pdfs/tracemonkey.pdf', window.location).href; var pdf1 = new URL('../pdfs/tracemonkey.pdf', window.location).href;
var pdf1Length = 1016315; var pdf1Length = 1016315;
var pdf2 = new URL('../pdfs/pdf.pdf', window.location).href; var pdf2 = new URL('../pdfs/pdf.pdf', window.location).href;
var pdf2Length = 32472771; var pdf2Length = 32472771;
it('read without stream and range', function (done) { it('read without stream and range', function (done) {
var stream = new PDFNetworkStream({ var stream = new _network.PDFNetworkStream({
source: { source: {
url: pdf1, url: pdf1,
rangeChunkSize: 65536, rangeChunkSize: 65536,
@ -67,7 +67,7 @@ describe('network', function () {
done(); done();
return; return;
} }
var stream = new PDFNetworkStream({ var stream = new _network.PDFNetworkStream({
source: { source: {
url: pdf2, url: pdf2,
rangeChunkSize: 65536, rangeChunkSize: 65536,
@ -106,7 +106,7 @@ describe('network', function () {
}); });
it('read custom ranges', function (done) { it('read custom ranges', function (done) {
var rangeSize = 32768; var rangeSize = 32768;
var stream = new PDFNetworkStream({ var stream = new _network.PDFNetworkStream({
source: { source: {
url: pdf1, url: pdf1,
length: pdf1Length, length: pdf1Length,

83
lib/test/unit/parser_spec.js

@ -14,18 +14,17 @@
*/ */
'use strict'; 'use strict';
var coreParser = require('../../core/parser.js'); var _parser = require('../../core/parser');
var corePrimitives = require('../../core/primitives.js');
var coreStream = require('../../core/stream.js'); var _primitives = require('../../core/primitives');
var Lexer = coreParser.Lexer;
var Linearization = coreParser.Linearization; var _stream = require('../../core/stream');
var Name = corePrimitives.Name;
var StringStream = coreStream.StringStream;
describe('parser', function () { describe('parser', function () {
describe('Lexer', function () { describe('Lexer', function () {
it('should stop parsing numbers at the end of stream', function () { it('should stop parsing numbers at the end of stream', function () {
var input = new StringStream('11.234'); var input = new _stream.StringStream('11.234');
var lexer = new Lexer(input); var lexer = new _parser.Lexer(input);
var result = lexer.getNumber(); var result = lexer.getNumber();
expect(result).toEqual(11.234); expect(result).toEqual(11.234);
}); });
@ -33,44 +32,44 @@ describe('parser', function () {
var numbers = ['-.002', '34.5', '-3.62', '123.6e10', '1E-5', '-1.', '0.0', '123', '-98', '43445', '0', '+17']; var numbers = ['-.002', '34.5', '-3.62', '123.6e10', '1E-5', '-1.', '0.0', '123', '-98', '43445', '0', '+17'];
for (var i = 0, ii = numbers.length; i < ii; i++) { for (var i = 0, ii = numbers.length; i < ii; i++) {
var num = numbers[i]; var num = numbers[i];
var input = new StringStream(num); var input = new _stream.StringStream(num);
var lexer = new Lexer(input); var lexer = new _parser.Lexer(input);
var result = lexer.getNumber(); var result = lexer.getNumber();
expect(result).toEqual(parseFloat(num)); expect(result).toEqual(parseFloat(num));
} }
}); });
it('should ignore double negative before number', function () { it('should ignore double negative before number', function () {
var input = new StringStream('--205.88'); var input = new _stream.StringStream('--205.88');
var lexer = new Lexer(input); var lexer = new _parser.Lexer(input);
var result = lexer.getNumber(); var result = lexer.getNumber();
expect(result).toEqual(-205.88); expect(result).toEqual(-205.88);
}); });
it('should handle glued numbers and operators', function () { it('should handle glued numbers and operators', function () {
var input = new StringStream('123ET'); var input = new _stream.StringStream('123ET');
var lexer = new Lexer(input); var lexer = new _parser.Lexer(input);
var value = lexer.getNumber(); var value = lexer.getNumber();
expect(value).toEqual(123); expect(value).toEqual(123);
expect(lexer.currentChar).toEqual(0x45); expect(lexer.currentChar).toEqual(0x45);
}); });
it('should stop parsing strings at the end of stream', function () { it('should stop parsing strings at the end of stream', function () {
var input = new StringStream('(1$4)'); var input = new _stream.StringStream('(1$4)');
input.getByte = function (super_getByte) { input.getByte = function (super_getByte) {
var ch = super_getByte.call(input); var ch = super_getByte.call(input);
return ch === 0x24 ? -1 : ch; return ch === 0x24 ? -1 : ch;
}.bind(input, input.getByte); }.bind(input, input.getByte);
var lexer = new Lexer(input); var lexer = new _parser.Lexer(input);
var result = lexer.getString(); var result = lexer.getString();
expect(result).toEqual('1'); expect(result).toEqual('1');
}); });
it('should not throw exception on bad input', function () { it('should not throw exception on bad input', function () {
var input = new StringStream('<7 0 2 15 5 2 2 2 4 3 2 4>'); var input = new _stream.StringStream('<7 0 2 15 5 2 2 2 4 3 2 4>');
var lexer = new Lexer(input); var lexer = new _parser.Lexer(input);
var result = lexer.getHexString(); var result = lexer.getHexString();
expect(result).toEqual('p!U"$2'); expect(result).toEqual('p!U"$2');
}); });
it('should ignore escaped CR and LF', function () { it('should ignore escaped CR and LF', function () {
var input = new StringStream('(\\101\\\r\n\\102\\\r\\103\\\n\\104)'); var input = new _stream.StringStream('(\\101\\\r\n\\102\\\r\\103\\\n\\104)');
var lexer = new Lexer(input); var lexer = new _parser.Lexer(input);
var result = lexer.getString(); var result = lexer.getString();
expect(result).toEqual('ABCD'); expect(result).toEqual('ABCD');
}); });
@ -78,22 +77,22 @@ describe('parser', function () {
var inputNames = ['/# 680 0 R', '/#AQwerty', '/#A<</B']; var inputNames = ['/# 680 0 R', '/#AQwerty', '/#A<</B'];
var expectedNames = ['#', '#AQwerty', '#A']; var expectedNames = ['#', '#AQwerty', '#A'];
for (var i = 0, ii = inputNames.length; i < ii; i++) { for (var i = 0, ii = inputNames.length; i < ii; i++) {
var input = new StringStream(inputNames[i]); var input = new _stream.StringStream(inputNames[i]);
var lexer = new Lexer(input); var lexer = new _parser.Lexer(input);
var result = lexer.getName(); var result = lexer.getName();
expect(result).toEqual(Name.get(expectedNames[i])); expect(result).toEqual(_primitives.Name.get(expectedNames[i]));
} }
}); });
}); });
describe('Linearization', function () { describe('Linearization', function () {
it('should not find a linearization dictionary', function () { it('should not find a linearization dictionary', function () {
var stream1 = new StringStream('3 0 obj\n' + '<<\n' + '/Length 4622\n' + '/Filter /FlateDecode\n' + '>>\n' + 'endobj'); var stream1 = new _stream.StringStream('3 0 obj\n' + '<<\n' + '/Length 4622\n' + '/Filter /FlateDecode\n' + '>>\n' + 'endobj');
expect(Linearization.create(stream1)).toEqual(null); expect(_parser.Linearization.create(stream1)).toEqual(null);
var stream2 = new StringStream('1 0 obj\n' + '<<\n' + '/Linearized 0\n' + '>>\n' + 'endobj'); var stream2 = new _stream.StringStream('1 0 obj\n' + '<<\n' + '/Linearized 0\n' + '>>\n' + 'endobj');
expect(Linearization.create(stream2)).toEqual(null); expect(_parser.Linearization.create(stream2)).toEqual(null);
}); });
it('should accept a valid linearization dictionary', function () { it('should accept a valid linearization dictionary', function () {
var stream = new StringStream('131 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H [ 1388 863 ]\n' + '/L 90\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj'); var stream = new _stream.StringStream('131 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H [ 1388 863 ]\n' + '/L 90\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj');
var expectedLinearizationDict = { var expectedLinearizationDict = {
length: 90, length: 90,
hints: [1388, 863], hints: [1388, 863],
@ -103,34 +102,34 @@ describe('parser', function () {
mainXRefEntriesOffset: 193883, mainXRefEntriesOffset: 193883,
pageFirst: 0 pageFirst: 0
}; };
expect(Linearization.create(stream)).toEqual(expectedLinearizationDict); expect(_parser.Linearization.create(stream)).toEqual(expectedLinearizationDict);
}); });
it('should reject a linearization dictionary with invalid ' + 'integer parameters', function () { it('should reject a linearization dictionary with invalid ' + 'integer parameters', function () {
var stream1 = new StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H [ 1388 863 ]\n' + '/L 196622\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj'); var stream1 = new _stream.StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H [ 1388 863 ]\n' + '/L 196622\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj');
expect(function () { expect(function () {
return Linearization.create(stream1); return _parser.Linearization.create(stream1);
}).toThrow(new Error('The "L" parameter in the linearization ' + 'dictionary does not equal the stream length.')); }).toThrow(new Error('The "L" parameter in the linearization ' + 'dictionary does not equal the stream length.'));
var stream2 = new StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H [ 1388 863 ]\n' + '/L 84\n' + '/E 0\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj'); var stream2 = new _stream.StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H [ 1388 863 ]\n' + '/L 84\n' + '/E 0\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj');
expect(function () { expect(function () {
return Linearization.create(stream2); return _parser.Linearization.create(stream2);
}).toThrow(new Error('The "E" parameter in the linearization ' + 'dictionary is invalid.')); }).toThrow(new Error('The "E" parameter in the linearization ' + 'dictionary is invalid.'));
var stream3 = new StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O /abc\n' + '/H [ 1388 863 ]\n' + '/L 89\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj'); var stream3 = new _stream.StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O /abc\n' + '/H [ 1388 863 ]\n' + '/L 89\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj');
expect(function () { expect(function () {
return Linearization.create(stream3); return _parser.Linearization.create(stream3);
}).toThrow(new Error('The "O" parameter in the linearization ' + 'dictionary is invalid.')); }).toThrow(new Error('The "O" parameter in the linearization ' + 'dictionary is invalid.'));
}); });
it('should reject a linearization dictionary with invalid hint parameters', function () { it('should reject a linearization dictionary with invalid hint parameters', function () {
var stream1 = new StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H 1388\n' + '/L 80\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj'); var stream1 = new _stream.StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H 1388\n' + '/L 80\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj');
expect(function () { expect(function () {
return Linearization.create(stream1); return _parser.Linearization.create(stream1);
}).toThrow(new Error('Hint array in the linearization dictionary ' + 'is invalid.')); }).toThrow(new Error('Hint array in the linearization dictionary ' + 'is invalid.'));
var stream2 = new StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H [ 1388 ]\n' + '/L 84\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj'); var stream2 = new _stream.StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H [ 1388 ]\n' + '/L 84\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj');
expect(function () { expect(function () {
return Linearization.create(stream2); return _parser.Linearization.create(stream2);
}).toThrow(new Error('Hint array in the linearization dictionary ' + 'is invalid.')); }).toThrow(new Error('Hint array in the linearization dictionary ' + 'is invalid.'));
var stream3 = new StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H [ 1388 863 0 234]\n' + '/L 93\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj'); var stream3 = new _stream.StringStream('1 0 obj\n' + '<<\n' + '/Linearized 1\n' + '/O 133\n' + '/H [ 1388 863 0 234]\n' + '/L 93\n' + '/E 43573\n' + '/N 18\n' + '/T 193883\n' + '>>\n' + 'endobj');
expect(function () { expect(function () {
return Linearization.create(stream3); return _parser.Linearization.create(stream3);
}).toThrow(new Error('Hint (2) in the linearization dictionary ' + 'is invalid.')); }).toThrow(new Error('Hint (2) in the linearization dictionary ' + 'is invalid.'));
}); });
}); });

131
lib/test/unit/primitives_spec.js

@ -14,17 +14,8 @@
*/ */
'use strict'; 'use strict';
var corePrimitives = require('../../core/primitives.js'); var _primitives = require('../../core/primitives');
var Name = corePrimitives.Name;
var Dict = corePrimitives.Dict;
var Ref = corePrimitives.Ref;
var RefSet = corePrimitives.RefSet;
var Cmd = corePrimitives.Cmd;
var isName = corePrimitives.isName;
var isCmd = corePrimitives.isCmd;
var isDict = corePrimitives.isDict;
var isRef = corePrimitives.isRef;
var isRefsEqual = corePrimitives.isRefsEqual;
describe('primitives', function () { describe('primitives', function () {
function XRefMock(array) { function XRefMock(array) {
this.map = Object.create(null); this.map = Object.create(null);
@ -40,7 +31,7 @@ describe('primitives', function () {
return this.map[ref.toString()]; return this.map[ref.toString()];
}, },
fetchIfRef: function fetchIfRef(obj) { fetchIfRef: function fetchIfRef(obj) {
if (!isRef(obj)) { if (!(0, _primitives.isRef)(obj)) {
return obj; return obj;
} }
return this.fetch(obj); return this.fetch(obj);
@ -55,14 +46,14 @@ describe('primitives', function () {
describe('Name', function () { describe('Name', function () {
it('should retain the given name', function () { it('should retain the given name', function () {
var givenName = 'Font'; var givenName = 'Font';
var name = Name.get(givenName); var name = _primitives.Name.get(givenName);
expect(name.name).toEqual(givenName); expect(name.name).toEqual(givenName);
}); });
it('should create only one object for a name and cache it', function () { it('should create only one object for a name and cache it', function () {
var firstFont = Name.get('Font'); var firstFont = _primitives.Name.get('Font');
var secondFont = Name.get('Font'); var secondFont = _primitives.Name.get('Font');
var firstSubtype = Name.get('Subtype'); var firstSubtype = _primitives.Name.get('Subtype');
var secondSubtype = Name.get('Subtype'); var secondSubtype = _primitives.Name.get('Subtype');
expect(firstFont).toBe(secondFont); expect(firstFont).toBe(secondFont);
expect(firstSubtype).toBe(secondSubtype); expect(firstSubtype).toBe(secondSubtype);
expect(firstFont).not.toBe(firstSubtype); expect(firstFont).not.toBe(firstSubtype);
@ -71,14 +62,14 @@ describe('primitives', function () {
describe('Cmd', function () { describe('Cmd', function () {
it('should retain the given cmd name', function () { it('should retain the given cmd name', function () {
var givenCmd = 'BT'; var givenCmd = 'BT';
var cmd = Cmd.get(givenCmd); var cmd = _primitives.Cmd.get(givenCmd);
expect(cmd.cmd).toEqual(givenCmd); expect(cmd.cmd).toEqual(givenCmd);
}); });
it('should create only one object for a command and cache it', function () { it('should create only one object for a command and cache it', function () {
var firstBT = Cmd.get('BT'); var firstBT = _primitives.Cmd.get('BT');
var secondBT = Cmd.get('BT'); var secondBT = _primitives.Cmd.get('BT');
var firstET = Cmd.get('ET'); var firstET = _primitives.Cmd.get('ET');
var secondET = Cmd.get('ET'); var secondET = _primitives.Cmd.get('ET');
expect(firstBT).toBe(secondBT); expect(firstBT).toBe(secondBT);
expect(firstET).toBe(secondET); expect(firstET).toBe(secondET);
expect(firstBT).not.toBe(firstET); expect(firstBT).not.toBe(firstET);
@ -101,10 +92,10 @@ describe('primitives', function () {
var testFontFile2 = 'file2'; var testFontFile2 = 'file2';
var testFontFile3 = 'file3'; var testFontFile3 = 'file3';
beforeAll(function (done) { beforeAll(function (done) {
emptyDict = new Dict(); emptyDict = new _primitives.Dict();
dictWithSizeKey = new Dict(); dictWithSizeKey = new _primitives.Dict();
dictWithSizeKey.set('Size', storedSize); dictWithSizeKey.set('Size', storedSize);
dictWithManyKeys = new Dict(); dictWithManyKeys = new _primitives.Dict();
dictWithManyKeys.set('FontFile', testFontFile); dictWithManyKeys.set('FontFile', testFontFile);
dictWithManyKeys.set('FontFile2', testFontFile2); dictWithManyKeys.set('FontFile2', testFontFile2);
dictWithManyKeys.set('FontFile3', testFontFile3); dictWithManyKeys.set('FontFile3', testFontFile3);
@ -128,7 +119,7 @@ describe('primitives', function () {
checkInvalidKeyValues(dictWithSizeKey); checkInvalidKeyValues(dictWithSizeKey);
}); });
it('should return correct value for stored Size key with undefined value', function () { it('should return correct value for stored Size key with undefined value', function () {
var dict = new Dict(); var dict = new _primitives.Dict();
dict.set('Size'); dict.set('Size');
expect(dict.has('Size')).toBeTruthy(); expect(dict.has('Size')).toBeTruthy();
checkInvalidKeyValues(dict); checkInvalidKeyValues(dict);
@ -173,12 +164,12 @@ describe('primitives', function () {
expect(callbackSpyCalls.count()).toEqual(3); expect(callbackSpyCalls.count()).toEqual(3);
}); });
it('should handle keys pointing to indirect objects, both sync and async', function (done) { it('should handle keys pointing to indirect objects, both sync and async', function (done) {
var fontRef = new Ref(1, 0); var fontRef = new _primitives.Ref(1, 0);
var xref = new XRefMock([{ var xref = new XRefMock([{
ref: fontRef, ref: fontRef,
data: testFontFile data: testFontFile
}]); }]);
var fontDict = new Dict(xref); var fontDict = new _primitives.Dict(xref);
fontDict.set('FontFile', fontRef); fontDict.set('FontFile', fontRef);
expect(fontDict.getRaw('FontFile')).toEqual(fontRef); expect(fontDict.getRaw('FontFile')).toEqual(fontRef);
expect(fontDict.get('FontFile', 'FontFile2', 'FontFile3')).toEqual(testFontFile); expect(fontDict.get('FontFile', 'FontFile2', 'FontFile3')).toEqual(testFontFile);
@ -190,8 +181,8 @@ describe('primitives', function () {
}); });
}); });
it('should handle arrays containing indirect objects', function () { it('should handle arrays containing indirect objects', function () {
var minCoordRef = new Ref(1, 0), var minCoordRef = new _primitives.Ref(1, 0),
maxCoordRef = new Ref(2, 0); maxCoordRef = new _primitives.Ref(2, 0);
var minCoord = 0, var minCoord = 0,
maxCoord = 1; maxCoord = 1;
var xref = new XRefMock([{ var xref = new XRefMock([{
@ -201,7 +192,7 @@ describe('primitives', function () {
ref: maxCoordRef, ref: maxCoordRef,
data: maxCoord data: maxCoord
}]); }]);
var xObjectDict = new Dict(xref); var xObjectDict = new _primitives.Dict(xref);
xObjectDict.set('BBox', [minCoord, maxCoord, minCoordRef, maxCoordRef]); xObjectDict.set('BBox', [minCoord, maxCoord, minCoordRef, maxCoordRef]);
expect(xObjectDict.get('BBox')).toEqual([minCoord, maxCoord, minCoordRef, maxCoordRef]); expect(xObjectDict.get('BBox')).toEqual([minCoord, maxCoord, minCoordRef, maxCoordRef]);
expect(xObjectDict.getArray('BBox')).toEqual([minCoord, maxCoord, minCoord, maxCoord]); expect(xObjectDict.getArray('BBox')).toEqual([minCoord, maxCoord, minCoord, maxCoord]);
@ -212,16 +203,16 @@ describe('primitives', function () {
expect(keys.sort()).toEqual(expectedKeys); expect(keys.sort()).toEqual(expectedKeys);
}); });
it('should create only one object for Dict.empty', function () { it('should create only one object for Dict.empty', function () {
var firstDictEmpty = Dict.empty; var firstDictEmpty = _primitives.Dict.empty;
var secondDictEmpty = Dict.empty; var secondDictEmpty = _primitives.Dict.empty;
expect(firstDictEmpty).toBe(secondDictEmpty); expect(firstDictEmpty).toBe(secondDictEmpty);
expect(firstDictEmpty).not.toBe(emptyDict); expect(firstDictEmpty).not.toBe(emptyDict);
}); });
it('should correctly merge dictionaries', function () { it('should correctly merge dictionaries', function () {
var expectedKeys = ['FontFile', 'FontFile2', 'FontFile3', 'Size']; var expectedKeys = ['FontFile', 'FontFile2', 'FontFile3', 'Size'];
var fontFileDict = new Dict(); var fontFileDict = new _primitives.Dict();
fontFileDict.set('FontFile', 'Type1 font file'); fontFileDict.set('FontFile', 'Type1 font file');
var mergedDict = Dict.merge(null, [dictWithManyKeys, dictWithSizeKey, fontFileDict]); var mergedDict = _primitives.Dict.merge(null, [dictWithManyKeys, dictWithSizeKey, fontFileDict]);
var mergedKeys = mergedDict.getKeys(); var mergedKeys = mergedDict.getKeys();
expect(mergedKeys.sort()).toEqual(expectedKeys); expect(mergedKeys.sort()).toEqual(expectedKeys);
expect(mergedDict.get('FontFile')).toEqual(testFontFile); expect(mergedDict.get('FontFile')).toEqual(testFontFile);
@ -231,94 +222,94 @@ describe('primitives', function () {
it('should retain the stored values', function () { it('should retain the stored values', function () {
var storedNum = 4; var storedNum = 4;
var storedGen = 2; var storedGen = 2;
var ref = new Ref(storedNum, storedGen); var ref = new _primitives.Ref(storedNum, storedGen);
expect(ref.num).toEqual(storedNum); expect(ref.num).toEqual(storedNum);
expect(ref.gen).toEqual(storedGen); expect(ref.gen).toEqual(storedGen);
}); });
}); });
describe('RefSet', function () { describe('RefSet', function () {
it('should have a stored value', function () { it('should have a stored value', function () {
var ref = new Ref(4, 2); var ref = new _primitives.Ref(4, 2);
var refset = new RefSet(); var refset = new _primitives.RefSet();
refset.put(ref); refset.put(ref);
expect(refset.has(ref)).toBeTruthy(); expect(refset.has(ref)).toBeTruthy();
}); });
it('should not have an unknown value', function () { it('should not have an unknown value', function () {
var ref = new Ref(4, 2); var ref = new _primitives.Ref(4, 2);
var refset = new RefSet(); var refset = new _primitives.RefSet();
expect(refset.has(ref)).toBeFalsy(); expect(refset.has(ref)).toBeFalsy();
refset.put(ref); refset.put(ref);
var anotherRef = new Ref(2, 4); var anotherRef = new _primitives.Ref(2, 4);
expect(refset.has(anotherRef)).toBeFalsy(); expect(refset.has(anotherRef)).toBeFalsy();
}); });
}); });
describe('isName', function () { describe('isName', function () {
it('handles non-names', function () { it('handles non-names', function () {
var nonName = {}; var nonName = {};
expect(isName(nonName)).toEqual(false); expect((0, _primitives.isName)(nonName)).toEqual(false);
}); });
it('handles names', function () { it('handles names', function () {
var name = Name.get('Font'); var name = _primitives.Name.get('Font');
expect(isName(name)).toEqual(true); expect((0, _primitives.isName)(name)).toEqual(true);
}); });
it('handles names with name check', function () { it('handles names with name check', function () {
var name = Name.get('Font'); var name = _primitives.Name.get('Font');
expect(isName(name, 'Font')).toEqual(true); expect((0, _primitives.isName)(name, 'Font')).toEqual(true);
expect(isName(name, 'Subtype')).toEqual(false); expect((0, _primitives.isName)(name, 'Subtype')).toEqual(false);
}); });
}); });
describe('isCmd', function () { describe('isCmd', function () {
it('handles non-commands', function () { it('handles non-commands', function () {
var nonCmd = {}; var nonCmd = {};
expect(isCmd(nonCmd)).toEqual(false); expect((0, _primitives.isCmd)(nonCmd)).toEqual(false);
}); });
it('handles commands', function () { it('handles commands', function () {
var cmd = Cmd.get('BT'); var cmd = _primitives.Cmd.get('BT');
expect(isCmd(cmd)).toEqual(true); expect((0, _primitives.isCmd)(cmd)).toEqual(true);
}); });
it('handles commands with cmd check', function () { it('handles commands with cmd check', function () {
var cmd = Cmd.get('BT'); var cmd = _primitives.Cmd.get('BT');
expect(isCmd(cmd, 'BT')).toEqual(true); expect((0, _primitives.isCmd)(cmd, 'BT')).toEqual(true);
expect(isCmd(cmd, 'ET')).toEqual(false); expect((0, _primitives.isCmd)(cmd, 'ET')).toEqual(false);
}); });
}); });
describe('isDict', function () { describe('isDict', function () {
it('handles non-dictionaries', function () { it('handles non-dictionaries', function () {
var nonDict = {}; var nonDict = {};
expect(isDict(nonDict)).toEqual(false); expect((0, _primitives.isDict)(nonDict)).toEqual(false);
}); });
it('handles empty dictionaries with type check', function () { it('handles empty dictionaries with type check', function () {
var dict = Dict.empty; var dict = _primitives.Dict.empty;
expect(isDict(dict)).toEqual(true); expect((0, _primitives.isDict)(dict)).toEqual(true);
expect(isDict(dict, 'Page')).toEqual(false); expect((0, _primitives.isDict)(dict, 'Page')).toEqual(false);
}); });
it('handles dictionaries with type check', function () { it('handles dictionaries with type check', function () {
var dict = new Dict(); var dict = new _primitives.Dict();
dict.set('Type', Name.get('Page')); dict.set('Type', _primitives.Name.get('Page'));
expect(isDict(dict, 'Page')).toEqual(true); expect((0, _primitives.isDict)(dict, 'Page')).toEqual(true);
expect(isDict(dict, 'Contents')).toEqual(false); expect((0, _primitives.isDict)(dict, 'Contents')).toEqual(false);
}); });
}); });
describe('isRef', function () { describe('isRef', function () {
it('handles non-refs', function () { it('handles non-refs', function () {
var nonRef = {}; var nonRef = {};
expect(isRef(nonRef)).toEqual(false); expect((0, _primitives.isRef)(nonRef)).toEqual(false);
}); });
it('handles refs', function () { it('handles refs', function () {
var ref = new Ref(1, 0); var ref = new _primitives.Ref(1, 0);
expect(isRef(ref)).toEqual(true); expect((0, _primitives.isRef)(ref)).toEqual(true);
}); });
}); });
describe('isRefsEqual', function () { describe('isRefsEqual', function () {
it('should handle different Refs pointing to the same object', function () { it('should handle different Refs pointing to the same object', function () {
var ref1 = new Ref(1, 0); var ref1 = new _primitives.Ref(1, 0);
var ref2 = new Ref(1, 0); var ref2 = new _primitives.Ref(1, 0);
expect(isRefsEqual(ref1, ref2)).toEqual(true); expect((0, _primitives.isRefsEqual)(ref1, ref2)).toEqual(true);
}); });
it('should handle Refs pointing to different objects', function () { it('should handle Refs pointing to different objects', function () {
var ref1 = new Ref(1, 0); var ref1 = new _primitives.Ref(1, 0);
var ref2 = new Ref(2, 0); var ref2 = new _primitives.Ref(2, 0);
expect(isRefsEqual(ref1, ref2)).toEqual(false); expect((0, _primitives.isRefsEqual)(ref1, ref2)).toEqual(false);
}); });
}); });
}); });

15
lib/test/unit/stream_spec.js

@ -14,11 +14,10 @@
*/ */
'use strict'; 'use strict';
var corePrimitives = require('../../core/primitives.js'); var _stream = require('../../core/stream');
var coreStream = require('../../core/stream.js');
var Dict = corePrimitives.Dict; var _primitives = require('../../core/primitives');
var Stream = coreStream.Stream;
var PredictorStream = coreStream.PredictorStream;
describe('stream', function () { describe('stream', function () {
beforeEach(function () { beforeEach(function () {
jasmine.addMatchers({ jasmine.addMatchers({
@ -48,13 +47,13 @@ describe('stream', function () {
}); });
describe('PredictorStream', function () { describe('PredictorStream', function () {
it('should decode simple predictor data', function () { it('should decode simple predictor data', function () {
var dict = new Dict(); var dict = new _primitives.Dict();
dict.set('Predictor', 12); dict.set('Predictor', 12);
dict.set('Colors', 1); dict.set('Colors', 1);
dict.set('BitsPerComponent', 8); dict.set('BitsPerComponent', 8);
dict.set('Columns', 2); dict.set('Columns', 2);
var input = new Stream(new Uint8Array([2, 100, 3, 2, 1, 255, 2, 1, 255]), 0, 9, dict); var input = new _stream.Stream(new Uint8Array([2, 100, 3, 2, 1, 255, 2, 1, 255]), 0, 9, dict);
var predictor = new PredictorStream(input, 9, dict); var predictor = new _stream.PredictorStream(input, 9, dict);
var result = predictor.getBytes(6); var result = predictor.getBytes(6);
expect(result).toMatchTypedArray(new Uint8Array([100, 3, 101, 2, 102, 1])); expect(result).toMatchTypedArray(new Uint8Array([100, 3, 101, 2, 102, 1]));
}); });

39
lib/test/unit/test_utils.js

@ -14,35 +14,52 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var CMapCompressionType = sharedUtil.CMapCompressionType; value: true
var NodeCMapReaderFactory = function NodeCMapReaderFactoryClosure() { });
exports.NodeCMapReaderFactory = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _util = require('../../shared/util');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var NodeCMapReaderFactory = function () {
function NodeCMapReaderFactory(params) { function NodeCMapReaderFactory(params) {
_classCallCheck(this, NodeCMapReaderFactory);
this.baseUrl = params.baseUrl || null; this.baseUrl = params.baseUrl || null;
this.isCompressed = params.isCompressed || false; this.isCompressed = params.isCompressed || false;
} }
NodeCMapReaderFactory.prototype = {
fetch: function fetch(params) { _createClass(NodeCMapReaderFactory, [{
key: 'fetch',
value: function fetch(params) {
var _this = this;
var name = params.name; var name = params.name;
if (!name) { if (!name) {
return Promise.reject(new Error('CMap name must be specified.')); return Promise.reject(new Error('CMap name must be specified.'));
} }
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
var url = this.baseUrl + name + (this.isCompressed ? '.bcmap' : ''); var url = _this.baseUrl + name + (_this.isCompressed ? '.bcmap' : '');
var fs = require('fs'); var fs = require('fs');
fs.readFile(url, function (error, data) { fs.readFile(url, function (error, data) {
if (error || !data) { if (error || !data) {
reject(new Error('Unable to load ' + (this.isCompressed ? 'binary ' : '') + 'CMap at: ' + url)); reject(new Error('Unable to load ' + (_this.isCompressed ? 'binary ' : '') + 'CMap at: ' + url));
return; return;
} }
resolve({ resolve({
cMapData: new Uint8Array(data), cMapData: new Uint8Array(data),
compressionType: this.isCompressed ? CMapCompressionType.BINARY : CMapCompressionType.NONE compressionType: _this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE
});
});
}); });
}.bind(this));
}.bind(this));
} }
}; }]);
return NodeCMapReaderFactory; return NodeCMapReaderFactory;
}(); }();
exports.NodeCMapReaderFactory = NodeCMapReaderFactory; exports.NodeCMapReaderFactory = NodeCMapReaderFactory;

56
lib/test/unit/type1_parser_spec.js

@ -14,16 +14,16 @@
*/ */
'use strict'; 'use strict';
var coreFonts = require('../../core/fonts.js'); var _fonts = require('../../core/fonts');
var coreStream = require('../../core/stream.js');
var coreType1Parser = require('../../core/type1_parser.js'); var _stream = require('../../core/stream');
var SEAC_ANALYSIS_ENABLED = coreFonts.SEAC_ANALYSIS_ENABLED;
var StringStream = coreStream.StringStream; var _type1_parser = require('../../core/type1_parser');
var Type1Parser = coreType1Parser.Type1Parser;
describe('Type1Parser', function () { describe('Type1Parser', function () {
it('splits tokens', function () { it('splits tokens', function () {
var stream = new StringStream('/BlueValues[-17 0]noaccess def'); var stream = new _stream.StringStream('/BlueValues[-17 0]noaccess def');
var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); var parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
expect(parser.getToken()).toEqual('/'); expect(parser.getToken()).toEqual('/');
expect(parser.getToken()).toEqual('BlueValues'); expect(parser.getToken()).toEqual('BlueValues');
expect(parser.getToken()).toEqual('['); expect(parser.getToken()).toEqual('[');
@ -35,59 +35,59 @@ describe('Type1Parser', function () {
expect(parser.getToken()).toEqual(null); expect(parser.getToken()).toEqual(null);
}); });
it('handles glued tokens', function () { it('handles glued tokens', function () {
var stream = new StringStream('dup/CharStrings'); var stream = new _stream.StringStream('dup/CharStrings');
var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); var parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
expect(parser.getToken()).toEqual('dup'); expect(parser.getToken()).toEqual('dup');
expect(parser.getToken()).toEqual('/'); expect(parser.getToken()).toEqual('/');
expect(parser.getToken()).toEqual('CharStrings'); expect(parser.getToken()).toEqual('CharStrings');
}); });
it('ignores whitespace', function () { it('ignores whitespace', function () {
var stream = new StringStream('\nab c\t'); var stream = new _stream.StringStream('\nab c\t');
var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); var parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
expect(parser.getToken()).toEqual('ab'); expect(parser.getToken()).toEqual('ab');
expect(parser.getToken()).toEqual('c'); expect(parser.getToken()).toEqual('c');
}); });
it('parses numbers', function () { it('parses numbers', function () {
var stream = new StringStream('123'); var stream = new _stream.StringStream('123');
var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); var parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
expect(parser.readNumber()).toEqual(123); expect(parser.readNumber()).toEqual(123);
}); });
it('parses booleans', function () { it('parses booleans', function () {
var stream = new StringStream('true false'); var stream = new _stream.StringStream('true false');
var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); var parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
expect(parser.readBoolean()).toEqual(1); expect(parser.readBoolean()).toEqual(1);
expect(parser.readBoolean()).toEqual(0); expect(parser.readBoolean()).toEqual(0);
}); });
it('parses number arrays', function () { it('parses number arrays', function () {
var stream = new StringStream('[1 2]'); var stream = new _stream.StringStream('[1 2]');
var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); var parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
expect(parser.readNumberArray()).toEqual([1, 2]); expect(parser.readNumberArray()).toEqual([1, 2]);
stream = new StringStream('[ 1 2 ]'); stream = new _stream.StringStream('[ 1 2 ]');
parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
expect(parser.readNumberArray()).toEqual([1, 2]); expect(parser.readNumberArray()).toEqual([1, 2]);
}); });
it('skips comments', function () { it('skips comments', function () {
var stream = new StringStream('%!PS-AdobeFont-1.0: CMSY10 003.002\n' + '%%Title: CMSY10\n' + '%Version: 003.002\n' + 'FontDirectory'); var stream = new _stream.StringStream('%!PS-AdobeFont-1.0: CMSY10 003.002\n' + '%%Title: CMSY10\n' + '%Version: 003.002\n' + 'FontDirectory');
var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); var parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
expect(parser.getToken()).toEqual('FontDirectory'); expect(parser.getToken()).toEqual('FontDirectory');
}); });
it('parses font program', function () { it('parses font program', function () {
var stream = new StringStream('/ExpansionFactor 99\n' + '/Subrs 1 array\n' + 'dup 0 1 RD x noaccess put\n' + 'end\n' + '/CharStrings 46 dict dup begin\n' + '/.notdef 1 RD x ND\n' + 'end'); var stream = new _stream.StringStream('/ExpansionFactor 99\n' + '/Subrs 1 array\n' + 'dup 0 1 RD x noaccess put\n' + 'end\n' + '/CharStrings 46 dict dup begin\n' + '/.notdef 1 RD x ND\n' + 'end');
var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); var parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
var program = parser.extractFontProgram(); var program = parser.extractFontProgram();
expect(program.charstrings.length).toEqual(1); expect(program.charstrings.length).toEqual(1);
expect(program.properties.privateData.ExpansionFactor).toEqual(99); expect(program.properties.privateData.ExpansionFactor).toEqual(99);
}); });
it('parses font header font matrix', function () { it('parses font header font matrix', function () {
var stream = new StringStream('/FontMatrix [0.001 0 0 0.001 0 0 ]readonly def\n'); var stream = new _stream.StringStream('/FontMatrix [0.001 0 0 0.001 0 0 ]readonly def\n');
var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); var parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
var props = {}; var props = {};
parser.extractFontHeader(props); parser.extractFontHeader(props);
expect(props.fontMatrix).toEqual([0.001, 0, 0, 0.001, 0, 0]); expect(props.fontMatrix).toEqual([0.001, 0, 0, 0.001, 0, 0]);
}); });
it('parses font header encoding', function () { it('parses font header encoding', function () {
var stream = new StringStream('/Encoding 256 array\n' + '0 1 255 {1 index exch /.notdef put} for\n' + 'dup 33 /arrowright put\n' + 'readonly def\n'); var stream = new _stream.StringStream('/Encoding 256 array\n' + '0 1 255 {1 index exch /.notdef put} for\n' + 'dup 33 /arrowright put\n' + 'readonly def\n');
var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); var parser = new _type1_parser.Type1Parser(stream, false, _fonts.SEAC_ANALYSIS_ENABLED);
var props = { overridableEncoding: true }; var props = { overridableEncoding: true };
parser.extractFontHeader(props); parser.extractFontHeader(props);
expect(props.builtInEncoding[33]).toEqual('arrowright'); expect(props.builtInEncoding[33]).toEqual('arrowright');

103
lib/test/unit/ui_utils_spec.js

@ -14,13 +14,10 @@
*/ */
'use strict'; 'use strict';
var webUiUtils = require('../../web/ui_utils.js'); var _ui_utils = require('../../web/ui_utils');
var sharedUtil = require('../../shared/util.js');
var binarySearchFirstItem = webUiUtils.binarySearchFirstItem; var _util = require('../../shared/util');
var getPDFFileNameFromURL = webUiUtils.getPDFFileNameFromURL;
var EventBus = webUiUtils.EventBus;
var createObjectURL = sharedUtil.createObjectURL;
var isNodeJS = sharedUtil.isNodeJS;
describe('ui_utils', function () { describe('ui_utils', function () {
describe('binary search', function () { describe('binary search', function () {
function isTrue(boolean) { function isTrue(boolean) {
@ -30,90 +27,90 @@ describe('ui_utils', function () {
return number > 3; return number > 3;
} }
it('empty array', function () { it('empty array', function () {
expect(binarySearchFirstItem([], isTrue)).toEqual(0); expect((0, _ui_utils.binarySearchFirstItem)([], isTrue)).toEqual(0);
}); });
it('single boolean entry', function () { it('single boolean entry', function () {
expect(binarySearchFirstItem([false], isTrue)).toEqual(1); expect((0, _ui_utils.binarySearchFirstItem)([false], isTrue)).toEqual(1);
expect(binarySearchFirstItem([true], isTrue)).toEqual(0); expect((0, _ui_utils.binarySearchFirstItem)([true], isTrue)).toEqual(0);
}); });
it('three boolean entries', function () { it('three boolean entries', function () {
expect(binarySearchFirstItem([true, true, true], isTrue)).toEqual(0); expect((0, _ui_utils.binarySearchFirstItem)([true, true, true], isTrue)).toEqual(0);
expect(binarySearchFirstItem([false, true, true], isTrue)).toEqual(1); expect((0, _ui_utils.binarySearchFirstItem)([false, true, true], isTrue)).toEqual(1);
expect(binarySearchFirstItem([false, false, true], isTrue)).toEqual(2); expect((0, _ui_utils.binarySearchFirstItem)([false, false, true], isTrue)).toEqual(2);
expect(binarySearchFirstItem([false, false, false], isTrue)).toEqual(3); expect((0, _ui_utils.binarySearchFirstItem)([false, false, false], isTrue)).toEqual(3);
}); });
it('three numeric entries', function () { it('three numeric entries', function () {
expect(binarySearchFirstItem([0, 1, 2], isGreater3)).toEqual(3); expect((0, _ui_utils.binarySearchFirstItem)([0, 1, 2], isGreater3)).toEqual(3);
expect(binarySearchFirstItem([2, 3, 4], isGreater3)).toEqual(2); expect((0, _ui_utils.binarySearchFirstItem)([2, 3, 4], isGreater3)).toEqual(2);
expect(binarySearchFirstItem([4, 5, 6], isGreater3)).toEqual(0); expect((0, _ui_utils.binarySearchFirstItem)([4, 5, 6], isGreater3)).toEqual(0);
}); });
}); });
describe('getPDFFileNameFromURL', function () { describe('getPDFFileNameFromURL', function () {
it('gets PDF filename', function () { it('gets PDF filename', function () {
expect(getPDFFileNameFromURL('/pdfs/file1.pdf')).toEqual('file1.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('/pdfs/file1.pdf')).toEqual('file1.pdf');
expect(getPDFFileNameFromURL('http://www.example.com/pdfs/file2.pdf')).toEqual('file2.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('http://www.example.com/pdfs/file2.pdf')).toEqual('file2.pdf');
}); });
it('gets fallback filename', function () { it('gets fallback filename', function () {
expect(getPDFFileNameFromURL('/pdfs/file1.txt')).toEqual('document.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('/pdfs/file1.txt')).toEqual('document.pdf');
expect(getPDFFileNameFromURL('http://www.example.com/pdfs/file2.txt')).toEqual('document.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('http://www.example.com/pdfs/file2.txt')).toEqual('document.pdf');
}); });
it('gets custom fallback filename', function () { it('gets custom fallback filename', function () {
expect(getPDFFileNameFromURL('/pdfs/file1.txt', 'qwerty1.pdf')).toEqual('qwerty1.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('/pdfs/file1.txt', 'qwerty1.pdf')).toEqual('qwerty1.pdf');
expect(getPDFFileNameFromURL('http://www.example.com/pdfs/file2.txt', 'qwerty2.pdf')).toEqual('qwerty2.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('http://www.example.com/pdfs/file2.txt', 'qwerty2.pdf')).toEqual('qwerty2.pdf');
expect(getPDFFileNameFromURL('/pdfs/file3.txt', '')).toEqual(''); expect((0, _ui_utils.getPDFFileNameFromURL)('/pdfs/file3.txt', '')).toEqual('');
}); });
it('gets PDF filename from URL containing leading/trailing whitespace', function () { it('gets PDF filename from URL containing leading/trailing whitespace', function () {
expect(getPDFFileNameFromURL(' /pdfs/file1.pdf ')).toEqual('file1.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)(' /pdfs/file1.pdf ')).toEqual('file1.pdf');
expect(getPDFFileNameFromURL(' http://www.example.com/pdfs/file2.pdf ')).toEqual('file2.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)(' http://www.example.com/pdfs/file2.pdf ')).toEqual('file2.pdf');
}); });
it('gets PDF filename from query string', function () { it('gets PDF filename from query string', function () {
expect(getPDFFileNameFromURL('/pdfs/pdfs.html?name=file1.pdf')).toEqual('file1.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('/pdfs/pdfs.html?name=file1.pdf')).toEqual('file1.pdf');
expect(getPDFFileNameFromURL('http://www.example.com/pdfs/pdf.html?file2.pdf')).toEqual('file2.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('http://www.example.com/pdfs/pdf.html?file2.pdf')).toEqual('file2.pdf');
}); });
it('gets PDF filename from hash string', function () { it('gets PDF filename from hash string', function () {
expect(getPDFFileNameFromURL('/pdfs/pdfs.html#name=file1.pdf')).toEqual('file1.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('/pdfs/pdfs.html#name=file1.pdf')).toEqual('file1.pdf');
expect(getPDFFileNameFromURL('http://www.example.com/pdfs/pdf.html#file2.pdf')).toEqual('file2.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('http://www.example.com/pdfs/pdf.html#file2.pdf')).toEqual('file2.pdf');
}); });
it('gets correct PDF filename when multiple ones are present', function () { it('gets correct PDF filename when multiple ones are present', function () {
expect(getPDFFileNameFromURL('/pdfs/file1.pdf?name=file.pdf')).toEqual('file1.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('/pdfs/file1.pdf?name=file.pdf')).toEqual('file1.pdf');
expect(getPDFFileNameFromURL('http://www.example.com/pdfs/file2.pdf#file.pdf')).toEqual('file2.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('http://www.example.com/pdfs/file2.pdf#file.pdf')).toEqual('file2.pdf');
}); });
it('gets PDF filename from URI-encoded data', function () { it('gets PDF filename from URI-encoded data', function () {
var encodedUrl = encodeURIComponent('http://www.example.com/pdfs/file1.pdf'); var encodedUrl = encodeURIComponent('http://www.example.com/pdfs/file1.pdf');
expect(getPDFFileNameFromURL(encodedUrl)).toEqual('file1.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)(encodedUrl)).toEqual('file1.pdf');
var encodedUrlWithQuery = encodeURIComponent('http://www.example.com/pdfs/file.txt?file2.pdf'); var encodedUrlWithQuery = encodeURIComponent('http://www.example.com/pdfs/file.txt?file2.pdf');
expect(getPDFFileNameFromURL(encodedUrlWithQuery)).toEqual('file2.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)(encodedUrlWithQuery)).toEqual('file2.pdf');
}); });
it('gets PDF filename from data mistaken for URI-encoded', function () { it('gets PDF filename from data mistaken for URI-encoded', function () {
expect(getPDFFileNameFromURL('/pdfs/%AA.pdf')).toEqual('%AA.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('/pdfs/%AA.pdf')).toEqual('%AA.pdf');
expect(getPDFFileNameFromURL('/pdfs/%2F.pdf')).toEqual('%2F.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('/pdfs/%2F.pdf')).toEqual('%2F.pdf');
}); });
it('gets PDF filename from (some) standard protocols', function () { it('gets PDF filename from (some) standard protocols', function () {
expect(getPDFFileNameFromURL('http://www.example.com/file1.pdf')).toEqual('file1.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('http://www.example.com/file1.pdf')).toEqual('file1.pdf');
expect(getPDFFileNameFromURL('https://www.example.com/file2.pdf')).toEqual('file2.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('https://www.example.com/file2.pdf')).toEqual('file2.pdf');
expect(getPDFFileNameFromURL('file:///path/to/files/file3.pdf')).toEqual('file3.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('file:///path/to/files/file3.pdf')).toEqual('file3.pdf');
expect(getPDFFileNameFromURL('ftp://www.example.com/file4.pdf')).toEqual('file4.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)('ftp://www.example.com/file4.pdf')).toEqual('file4.pdf');
}); });
it('gets PDF filename from query string appended to "blob:" URL', function () { it('gets PDF filename from query string appended to "blob:" URL', function () {
if (isNodeJS()) { if ((0, _util.isNodeJS)()) {
pending('Blob in not supported in Node.js.'); pending('Blob in not supported in Node.js.');
} }
var typedArray = new Uint8Array([1, 2, 3, 4, 5]); var typedArray = new Uint8Array([1, 2, 3, 4, 5]);
var blobUrl = createObjectURL(typedArray, 'application/pdf'); var blobUrl = (0, _util.createObjectURL)(typedArray, 'application/pdf');
expect(blobUrl.indexOf('blob:') === 0).toEqual(true); expect(blobUrl.indexOf('blob:') === 0).toEqual(true);
expect(getPDFFileNameFromURL(blobUrl + '?file.pdf')).toEqual('file.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)(blobUrl + '?file.pdf')).toEqual('file.pdf');
}); });
it('gets fallback filename from query string appended to "data:" URL', function () { it('gets fallback filename from query string appended to "data:" URL', function () {
var typedArray = new Uint8Array([1, 2, 3, 4, 5]); var typedArray = new Uint8Array([1, 2, 3, 4, 5]);
var dataUrl = createObjectURL(typedArray, 'application/pdf', true); var dataUrl = (0, _util.createObjectURL)(typedArray, 'application/pdf', true);
expect(dataUrl.indexOf('data:') === 0).toEqual(true); expect(dataUrl.indexOf('data:') === 0).toEqual(true);
expect(getPDFFileNameFromURL(dataUrl + '?file1.pdf')).toEqual('document.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)(dataUrl + '?file1.pdf')).toEqual('document.pdf');
expect(getPDFFileNameFromURL(' ' + dataUrl + '?file2.pdf')).toEqual('document.pdf'); expect((0, _ui_utils.getPDFFileNameFromURL)(' ' + dataUrl + '?file2.pdf')).toEqual('document.pdf');
}); });
}); });
describe('EventBus', function () { describe('EventBus', function () {
it('dispatch event', function () { it('dispatch event', function () {
var eventBus = new EventBus(); var eventBus = new _ui_utils.EventBus();
var count = 0; var count = 0;
eventBus.on('test', function () { eventBus.on('test', function () {
count++; count++;
@ -122,7 +119,7 @@ describe('ui_utils', function () {
expect(count).toEqual(1); expect(count).toEqual(1);
}); });
it('dispatch different event', function () { it('dispatch different event', function () {
var eventBus = new EventBus(); var eventBus = new _ui_utils.EventBus();
var count = 0; var count = 0;
eventBus.on('test', function () { eventBus.on('test', function () {
count++; count++;
@ -131,7 +128,7 @@ describe('ui_utils', function () {
expect(count).toEqual(0); expect(count).toEqual(0);
}); });
it('dispatch event multiple times', function () { it('dispatch event multiple times', function () {
var eventBus = new EventBus(); var eventBus = new _ui_utils.EventBus();
var count = 0; var count = 0;
eventBus.dispatch('test'); eventBus.dispatch('test');
eventBus.on('test', function () { eventBus.on('test', function () {
@ -142,7 +139,7 @@ describe('ui_utils', function () {
expect(count).toEqual(2); expect(count).toEqual(2);
}); });
it('dispatch event to multiple handlers', function () { it('dispatch event to multiple handlers', function () {
var eventBus = new EventBus(); var eventBus = new _ui_utils.EventBus();
var count = 0; var count = 0;
eventBus.on('test', function () { eventBus.on('test', function () {
count++; count++;
@ -154,7 +151,7 @@ describe('ui_utils', function () {
expect(count).toEqual(2); expect(count).toEqual(2);
}); });
it('dispatch to detached', function () { it('dispatch to detached', function () {
var eventBus = new EventBus(); var eventBus = new _ui_utils.EventBus();
var count = 0; var count = 0;
var listener = function listener() { var listener = function listener() {
count++; count++;
@ -166,7 +163,7 @@ describe('ui_utils', function () {
expect(count).toEqual(1); expect(count).toEqual(1);
}); });
it('dispatch to wrong detached', function () { it('dispatch to wrong detached', function () {
var eventBus = new EventBus(); var eventBus = new _ui_utils.EventBus();
var count = 0; var count = 0;
eventBus.on('test', function () { eventBus.on('test', function () {
count++; count++;
@ -179,7 +176,7 @@ describe('ui_utils', function () {
expect(count).toEqual(2); expect(count).toEqual(2);
}); });
it('dispatch to detached during handling', function () { it('dispatch to detached during handling', function () {
var eventBus = new EventBus(); var eventBus = new _ui_utils.EventBus();
var count = 0; var count = 0;
var listener1 = function listener1() { var listener1 = function listener1() {
eventBus.off('test', listener2); eventBus.off('test', listener2);

59
lib/test/unit/unicode_spec.js

@ -14,64 +14,59 @@
*/ */
'use strict'; 'use strict';
var coreGlyphList = require('../../core/glyphlist.js'); var _glyphlist = require('../../core/glyphlist');
var coreUnicode = require('../../core/unicode.js');
var getGlyphsUnicode = coreGlyphList.getGlyphsUnicode; var _unicode = require('../../core/unicode');
var getDingbatsGlyphsUnicode = coreGlyphList.getDingbatsGlyphsUnicode;
var mapSpecialUnicodeValues = coreUnicode.mapSpecialUnicodeValues;
var getUnicodeForGlyph = coreUnicode.getUnicodeForGlyph;
var getUnicodeRangeFor = coreUnicode.getUnicodeRangeFor;
var getNormalizedUnicodes = coreUnicode.getNormalizedUnicodes;
var reverseIfRtl = coreUnicode.reverseIfRtl;
describe('unicode', function () { describe('unicode', function () {
describe('mapSpecialUnicodeValues', function () { describe('mapSpecialUnicodeValues', function () {
it('should not re-map normal Unicode values', function () { it('should not re-map normal Unicode values', function () {
expect(mapSpecialUnicodeValues(0x0041)).toEqual(0x0041); expect((0, _unicode.mapSpecialUnicodeValues)(0x0041)).toEqual(0x0041);
expect(mapSpecialUnicodeValues(0xFB01)).toEqual(0xFB01); expect((0, _unicode.mapSpecialUnicodeValues)(0xFB01)).toEqual(0xFB01);
}); });
it('should re-map special Unicode values', function () { it('should re-map special Unicode values', function () {
expect(mapSpecialUnicodeValues(0xF8E9)).toEqual(0x00A9); expect((0, _unicode.mapSpecialUnicodeValues)(0xF8E9)).toEqual(0x00A9);
expect(mapSpecialUnicodeValues(0xFFFF)).toEqual(0); expect((0, _unicode.mapSpecialUnicodeValues)(0xFFFF)).toEqual(0);
}); });
}); });
describe('getUnicodeForGlyph', function () { describe('getUnicodeForGlyph', function () {
var standardMap, dingbatsMap; var standardMap, dingbatsMap;
beforeAll(function (done) { beforeAll(function (done) {
standardMap = getGlyphsUnicode(); standardMap = (0, _glyphlist.getGlyphsUnicode)();
dingbatsMap = getDingbatsGlyphsUnicode(); dingbatsMap = (0, _glyphlist.getDingbatsGlyphsUnicode)();
done(); done();
}); });
afterAll(function () { afterAll(function () {
standardMap = dingbatsMap = null; standardMap = dingbatsMap = null;
}); });
it('should get Unicode values for valid glyph names', function () { it('should get Unicode values for valid glyph names', function () {
expect(getUnicodeForGlyph('A', standardMap)).toEqual(0x0041); expect((0, _unicode.getUnicodeForGlyph)('A', standardMap)).toEqual(0x0041);
expect(getUnicodeForGlyph('a1', dingbatsMap)).toEqual(0x2701); expect((0, _unicode.getUnicodeForGlyph)('a1', dingbatsMap)).toEqual(0x2701);
}); });
it('should recover Unicode values from uniXXXX/uXXXX{XX} glyph names', function () { it('should recover Unicode values from uniXXXX/uXXXX{XX} glyph names', function () {
expect(getUnicodeForGlyph('uni0041', standardMap)).toEqual(0x0041); expect((0, _unicode.getUnicodeForGlyph)('uni0041', standardMap)).toEqual(0x0041);
expect(getUnicodeForGlyph('u0041', standardMap)).toEqual(0x0041); expect((0, _unicode.getUnicodeForGlyph)('u0041', standardMap)).toEqual(0x0041);
expect(getUnicodeForGlyph('uni2701', dingbatsMap)).toEqual(0x2701); expect((0, _unicode.getUnicodeForGlyph)('uni2701', dingbatsMap)).toEqual(0x2701);
expect(getUnicodeForGlyph('u2701', dingbatsMap)).toEqual(0x2701); expect((0, _unicode.getUnicodeForGlyph)('u2701', dingbatsMap)).toEqual(0x2701);
}); });
it('should not get Unicode values for invalid glyph names', function () { it('should not get Unicode values for invalid glyph names', function () {
expect(getUnicodeForGlyph('Qwerty', standardMap)).toEqual(-1); expect((0, _unicode.getUnicodeForGlyph)('Qwerty', standardMap)).toEqual(-1);
expect(getUnicodeForGlyph('Qwerty', dingbatsMap)).toEqual(-1); expect((0, _unicode.getUnicodeForGlyph)('Qwerty', dingbatsMap)).toEqual(-1);
}); });
}); });
describe('getUnicodeRangeFor', function () { describe('getUnicodeRangeFor', function () {
it('should get correct Unicode range', function () { it('should get correct Unicode range', function () {
expect(getUnicodeRangeFor(0x0041)).toEqual(0); expect((0, _unicode.getUnicodeRangeFor)(0x0041)).toEqual(0);
expect(getUnicodeRangeFor(0xFB01)).toEqual(62); expect((0, _unicode.getUnicodeRangeFor)(0xFB01)).toEqual(62);
}); });
it('should not get a Unicode range', function () { it('should not get a Unicode range', function () {
expect(getUnicodeRangeFor(0x05FF)).toEqual(-1); expect((0, _unicode.getUnicodeRangeFor)(0x05FF)).toEqual(-1);
}); });
}); });
describe('getNormalizedUnicodes', function () { describe('getNormalizedUnicodes', function () {
var NormalizedUnicodes; var NormalizedUnicodes;
beforeAll(function (done) { beforeAll(function (done) {
NormalizedUnicodes = getNormalizedUnicodes(); NormalizedUnicodes = (0, _unicode.getNormalizedUnicodes)();
done(); done();
}); });
afterAll(function () { afterAll(function () {
@ -94,7 +89,7 @@ describe('unicode', function () {
return char; return char;
} }
beforeAll(function (done) { beforeAll(function (done) {
NormalizedUnicodes = getNormalizedUnicodes(); NormalizedUnicodes = (0, _unicode.getNormalizedUnicodes)();
done(); done();
}); });
afterAll(function () { afterAll(function () {
@ -102,15 +97,15 @@ describe('unicode', function () {
}); });
it('should not reverse LTR characters', function () { it('should not reverse LTR characters', function () {
var A = getGlyphUnicode('A'); var A = getGlyphUnicode('A');
expect(reverseIfRtl(A)).toEqual('A'); expect((0, _unicode.reverseIfRtl)(A)).toEqual('A');
var fi = getGlyphUnicode('\uFB01'); var fi = getGlyphUnicode('\uFB01');
expect(reverseIfRtl(fi)).toEqual('fi'); expect((0, _unicode.reverseIfRtl)(fi)).toEqual('fi');
}); });
it('should reverse RTL characters', function () { it('should reverse RTL characters', function () {
var heAlef = getGlyphUnicode('\u05D0'); var heAlef = getGlyphUnicode('\u05D0');
expect(reverseIfRtl(heAlef)).toEqual('\u05D0'); expect((0, _unicode.reverseIfRtl)(heAlef)).toEqual('\u05D0');
var arAlef = getGlyphUnicode('\u0675'); var arAlef = getGlyphUnicode('\u0675');
expect(reverseIfRtl(arAlef)).toEqual('\u0674\u0627'); expect((0, _unicode.reverseIfRtl)(arAlef)).toEqual('\u0674\u0627');
}); });
}); });
}); });

17
lib/test/unit/util_spec.js

@ -14,34 +14,33 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../../shared/util.js'); var _util = require('../../shared/util');
var stringToPDFString = sharedUtil.stringToPDFString;
var removeNullCharacters = sharedUtil.removeNullCharacters;
describe('util', function () { describe('util', function () {
describe('stringToPDFString', function () { describe('stringToPDFString', function () {
it('handles ISO Latin 1 strings', function () { it('handles ISO Latin 1 strings', function () {
var str = '\x8Dstring\x8E'; var str = '\x8Dstring\x8E';
expect(stringToPDFString(str)).toEqual('\u201Cstring\u201D'); expect((0, _util.stringToPDFString)(str)).toEqual('\u201Cstring\u201D');
}); });
it('handles UTF-16BE strings', function () { it('handles UTF-16BE strings', function () {
var str = '\xFE\xFF\x00\x73\x00\x74\x00\x72\x00\x69\x00\x6E\x00\x67'; var str = '\xFE\xFF\x00\x73\x00\x74\x00\x72\x00\x69\x00\x6E\x00\x67';
expect(stringToPDFString(str)).toEqual('string'); expect((0, _util.stringToPDFString)(str)).toEqual('string');
}); });
it('handles empty strings', function () { it('handles empty strings', function () {
var str1 = ''; var str1 = '';
expect(stringToPDFString(str1)).toEqual(''); expect((0, _util.stringToPDFString)(str1)).toEqual('');
var str2 = '\xFE\xFF'; var str2 = '\xFE\xFF';
expect(stringToPDFString(str2)).toEqual(''); expect((0, _util.stringToPDFString)(str2)).toEqual('');
}); });
}); });
describe('removeNullCharacters', function () { describe('removeNullCharacters', function () {
it('should not modify string without null characters', function () { it('should not modify string without null characters', function () {
var str = 'string without null chars'; var str = 'string without null chars';
expect(removeNullCharacters(str)).toEqual('string without null chars'); expect((0, _util.removeNullCharacters)(str)).toEqual('string without null chars');
}); });
it('should modify string with null characters', function () { it('should modify string with null characters', function () {
var str = 'string\x00With\x00Null\x00Chars'; var str = 'string\x00With\x00Null\x00Chars';
expect(removeNullCharacters(str)).toEqual('stringWithNullChars'); expect((0, _util.removeNullCharacters)(str)).toEqual('stringWithNullChars');
}); });
}); });
}); });

2
package.json

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

Loading…
Cancel
Save