Update Prettier to version 2.0

Please note that these changes were done automatically, using `gulp lint --fix`.

Given that the major version number was increased, there's a fair number of (primarily whitespace) changes; please see https://prettier.io/blog/2020/03/21/2.0.0.html
In order to reduce the size of these changes somewhat, this patch maintains the old "arrowParens" style for now (once mozilla-central updates Prettier we can simply choose the same formatting, assuming it will differ here).
This commit is contained in:
Jonas Jenwald 2020-04-14 12:28:14 +02:00
parent a4dd081d7b
commit 426945b480
145 changed files with 2005 additions and 2009 deletions

View File

@ -1,4 +1,5 @@
{ {
"arrowParens": "avoid",
"endOfLine": "lf", "endOfLine": "lf",
"printWidth": 80, "printWidth": 80,
"semi": true, "semi": true,

View File

@ -27,14 +27,14 @@ var eventBus = new pdfjsViewer.EventBus();
// Fetch the PDF document from the URL using promises. // Fetch the PDF document from the URL using promises.
var loadingTask = pdfjsLib.getDocument(DEFAULT_URL); var loadingTask = pdfjsLib.getDocument(DEFAULT_URL);
loadingTask.promise.then(function(doc) { loadingTask.promise.then(function (doc) {
// Use a promise to fetch and render the next page. // Use a promise to fetch and render the next page.
var promise = Promise.resolve(); var promise = Promise.resolve();
for (var i = 1; i <= doc.numPages; i++) { for (var i = 1; i <= doc.numPages; i++) {
promise = promise.then( promise = promise.then(
function(pageNum) { function (pageNum) {
return doc.getPage(pageNum).then(function(pdfPage) { return doc.getPage(pageNum).then(function (pdfPage) {
// Create the page view. // Create the page view.
var pdfPageView = new pdfjsViewer.PDFPageView({ var pdfPageView = new pdfjsViewer.PDFPageView({
container: container, container: container,

View File

@ -8,7 +8,7 @@ var source = require("vinyl-source-stream");
var OUTPUT_PATH = "../../build/browserify"; var OUTPUT_PATH = "../../build/browserify";
var TMP_FILE_PREFIX = "../../build/browserify_"; var TMP_FILE_PREFIX = "../../build/browserify_";
gulp.task("build-bundle", function() { gulp.task("build-bundle", function () {
return browserify("main.js", { output: TMP_FILE_PREFIX + "main.tmp" }) return browserify("main.js", { output: TMP_FILE_PREFIX + "main.tmp" })
.ignore(require.resolve("pdfjs-dist/build/pdf.worker")) // Reducing size .ignore(require.resolve("pdfjs-dist/build/pdf.worker")) // Reducing size
.bundle() .bundle()
@ -18,7 +18,7 @@ gulp.task("build-bundle", function() {
.pipe(gulp.dest(OUTPUT_PATH)); .pipe(gulp.dest(OUTPUT_PATH));
}); });
gulp.task("build-worker", function() { gulp.task("build-worker", function () {
// We can create our own viewer (see worker.js) or use already defined one. // We can create our own viewer (see worker.js) or use already defined one.
var workerSrc = require.resolve("pdfjs-dist/build/pdf.worker.entry"); var workerSrc = require.resolve("pdfjs-dist/build/pdf.worker.entry");
return browserify(workerSrc, { output: TMP_FILE_PREFIX + "worker.tmp" }) return browserify(workerSrc, { output: TMP_FILE_PREFIX + "worker.tmp" })

View File

@ -14,9 +14,9 @@ pdfjsLib.GlobalWorkerOptions.workerSrc =
// Loading a document. // Loading a document.
var loadingTask = pdfjsLib.getDocument(pdfPath); var loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise loadingTask.promise
.then(function(pdfDocument) { .then(function (pdfDocument) {
// Request a first page // Request a first page
return pdfDocument.getPage(1).then(function(pdfPage) { return pdfDocument.getPage(1).then(function (pdfPage) {
// Display page on the existing canvas with 100% scale. // Display page on the existing canvas with 100% scale.
var viewport = pdfPage.getViewport({ scale: 1.0 }); var viewport = pdfPage.getViewport({ scale: 1.0 });
var canvas = document.getElementById("theCanvas"); var canvas = document.getElementById("theCanvas");
@ -30,6 +30,6 @@ loadingTask.promise
return renderTask.promise; return renderTask.promise;
}); });
}) })
.catch(function(reason) { .catch(function (reason) {
console.error("Error: " + reason); console.error("Error: " + reason);
}); });

View File

@ -43,9 +43,9 @@ var loadingTask = pdfjsLib.getDocument({
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,
}); });
loadingTask.promise.then(function(pdfDocument) { loadingTask.promise.then(function (pdfDocument) {
// Document loaded, retrieving the page. // Document loaded, retrieving the page.
return pdfDocument.getPage(PAGE_TO_VIEW).then(function(pdfPage) { return pdfDocument.getPage(PAGE_TO_VIEW).then(function (pdfPage) {
// Creating the page view with default parameters. // Creating the page view with default parameters.
var pdfPageView = new pdfjsViewer.PDFPageView({ var pdfPageView = new pdfjsViewer.PDFPageView({
container: container, container: container,

View File

@ -55,7 +55,7 @@ var pdfViewer = new pdfjsViewer.PDFViewer({
}); });
pdfLinkService.setViewer(pdfViewer); pdfLinkService.setViewer(pdfViewer);
eventBus.on("pagesinit", function() { eventBus.on("pagesinit", function () {
// We can use pdfViewer now, e.g. let's change default scale. // We can use pdfViewer now, e.g. let's change default scale.
pdfViewer.currentScaleValue = "page-width"; pdfViewer.currentScaleValue = "page-width";
@ -71,7 +71,7 @@ var loadingTask = pdfjsLib.getDocument({
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,
}); });
loadingTask.promise.then(function(pdfDocument) { loadingTask.promise.then(function (pdfDocument) {
// Document loaded, specifying document for the viewer and // Document loaded, specifying document for the viewer and
// the (optional) linkService. // the (optional) linkService.
pdfViewer.setDocument(pdfDocument); pdfViewer.setDocument(pdfDocument);

View File

@ -55,7 +55,7 @@ var pdfSinglePageViewer = new pdfjsViewer.PDFSinglePageViewer({
}); });
pdfLinkService.setViewer(pdfSinglePageViewer); pdfLinkService.setViewer(pdfSinglePageViewer);
eventBus.on("pagesinit", function() { eventBus.on("pagesinit", function () {
// We can use pdfSinglePageViewer now, e.g. let's change default scale. // We can use pdfSinglePageViewer now, e.g. let's change default scale.
pdfSinglePageViewer.currentScaleValue = "page-width"; pdfSinglePageViewer.currentScaleValue = "page-width";
@ -71,7 +71,7 @@ var loadingTask = pdfjsLib.getDocument({
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,
}); });
loadingTask.promise.then(function(pdfDocument) { loadingTask.promise.then(function (pdfDocument) {
// Document loaded, specifying document for the viewer and // Document loaded, specifying document for the viewer and
// the (optional) linkService. // the (optional) linkService.
pdfSinglePageViewer.setDocument(pdfDocument); pdfSinglePageViewer.setDocument(pdfDocument);

View File

@ -47,11 +47,11 @@ var PDFViewerApplication = {
* @returns {Promise} - Returns the promise, which is resolved when document * @returns {Promise} - Returns the promise, which is resolved when document
* is opened. * is opened.
*/ */
open: function(params) { open: function (params) {
if (this.pdfLoadingTask) { if (this.pdfLoadingTask) {
// We need to destroy already opened document // We need to destroy already opened document
return this.close().then( return this.close().then(
function() { function () {
// ... and repeat the open() call. // ... and repeat the open() call.
return this.open(params); return this.open(params);
}.bind(this) }.bind(this)
@ -71,12 +71,12 @@ var PDFViewerApplication = {
}); });
this.pdfLoadingTask = loadingTask; this.pdfLoadingTask = loadingTask;
loadingTask.onProgress = function(progressData) { loadingTask.onProgress = function (progressData) {
self.progress(progressData.loaded / progressData.total); self.progress(progressData.loaded / progressData.total);
}; };
return loadingTask.promise.then( return loadingTask.promise.then(
function(pdfDocument) { function (pdfDocument) {
// Document loaded, specifying document for the viewer. // Document loaded, specifying document for the viewer.
self.pdfDocument = pdfDocument; self.pdfDocument = pdfDocument;
self.pdfViewer.setDocument(pdfDocument); self.pdfViewer.setDocument(pdfDocument);
@ -86,7 +86,7 @@ var PDFViewerApplication = {
self.loadingBar.hide(); self.loadingBar.hide();
self.setTitleUsingMetadata(pdfDocument); self.setTitleUsingMetadata(pdfDocument);
}, },
function(exception) { function (exception) {
var message = exception && exception.message; var message = exception && exception.message;
var l10n = self.l10n; var l10n = self.l10n;
var loadingErrorMessage; var loadingErrorMessage;
@ -119,7 +119,7 @@ var PDFViewerApplication = {
); );
} }
loadingErrorMessage.then(function(msg) { loadingErrorMessage.then(function (msg) {
self.error(msg, { message: message }); self.error(msg, { message: message });
}); });
self.loadingBar.hide(); self.loadingBar.hide();
@ -132,7 +132,7 @@ var PDFViewerApplication = {
* @returns {Promise} - Returns the promise, which is resolved when all * @returns {Promise} - Returns the promise, which is resolved when all
* destruction is completed. * destruction is completed.
*/ */
close: function() { close: function () {
var errorWrapper = document.getElementById("errorWrapper"); var errorWrapper = document.getElementById("errorWrapper");
errorWrapper.setAttribute("hidden", "true"); errorWrapper.setAttribute("hidden", "true");
@ -175,9 +175,9 @@ var PDFViewerApplication = {
this.setTitle(title); this.setTitle(title);
}, },
setTitleUsingMetadata: function(pdfDocument) { setTitleUsingMetadata: function (pdfDocument) {
var self = this; var self = this;
pdfDocument.getMetadata().then(function(data) { pdfDocument.getMetadata().then(function (data) {
var info = data.info, var info = data.info,
metadata = data.metadata; metadata = data.metadata;
self.documentInfo = info; self.documentInfo = info;
@ -275,27 +275,27 @@ var PDFViewerApplication = {
errorMessage.textContent = message; errorMessage.textContent = message;
var closeButton = document.getElementById("errorClose"); var closeButton = document.getElementById("errorClose");
closeButton.onclick = function() { closeButton.onclick = function () {
errorWrapper.setAttribute("hidden", "true"); errorWrapper.setAttribute("hidden", "true");
}; };
var errorMoreInfo = document.getElementById("errorMoreInfo"); var errorMoreInfo = document.getElementById("errorMoreInfo");
var moreInfoButton = document.getElementById("errorShowMore"); var moreInfoButton = document.getElementById("errorShowMore");
var lessInfoButton = document.getElementById("errorShowLess"); var lessInfoButton = document.getElementById("errorShowLess");
moreInfoButton.onclick = function() { moreInfoButton.onclick = function () {
errorMoreInfo.removeAttribute("hidden"); errorMoreInfo.removeAttribute("hidden");
moreInfoButton.setAttribute("hidden", "true"); moreInfoButton.setAttribute("hidden", "true");
lessInfoButton.removeAttribute("hidden"); lessInfoButton.removeAttribute("hidden");
errorMoreInfo.style.height = errorMoreInfo.scrollHeight + "px"; errorMoreInfo.style.height = errorMoreInfo.scrollHeight + "px";
}; };
lessInfoButton.onclick = function() { lessInfoButton.onclick = function () {
errorMoreInfo.setAttribute("hidden", "true"); errorMoreInfo.setAttribute("hidden", "true");
moreInfoButton.removeAttribute("hidden"); moreInfoButton.removeAttribute("hidden");
lessInfoButton.setAttribute("hidden", "true"); lessInfoButton.setAttribute("hidden", "true");
}; };
moreInfoButton.removeAttribute("hidden"); moreInfoButton.removeAttribute("hidden");
lessInfoButton.setAttribute("hidden", "true"); lessInfoButton.setAttribute("hidden", "true");
Promise.all(moreInfoText).then(function(parts) { Promise.all(moreInfoText).then(function (parts) {
errorMoreInfo.value = parts.join("\n"); errorMoreInfo.value = parts.join("\n");
}); });
}, },
@ -369,29 +369,31 @@ var PDFViewerApplication = {
}); });
linkService.setHistory(this.pdfHistory); linkService.setHistory(this.pdfHistory);
document.getElementById("previous").addEventListener("click", function() { document.getElementById("previous").addEventListener("click", function () {
PDFViewerApplication.page--; PDFViewerApplication.page--;
}); });
document.getElementById("next").addEventListener("click", function() { document.getElementById("next").addEventListener("click", function () {
PDFViewerApplication.page++; PDFViewerApplication.page++;
}); });
document.getElementById("zoomIn").addEventListener("click", function() { document.getElementById("zoomIn").addEventListener("click", function () {
PDFViewerApplication.zoomIn(); PDFViewerApplication.zoomIn();
}); });
document.getElementById("zoomOut").addEventListener("click", function() { document.getElementById("zoomOut").addEventListener("click", function () {
PDFViewerApplication.zoomOut(); PDFViewerApplication.zoomOut();
}); });
document.getElementById("pageNumber").addEventListener("click", function() {
this.select();
});
document document
.getElementById("pageNumber") .getElementById("pageNumber")
.addEventListener("change", function() { .addEventListener("click", function () {
this.select();
});
document
.getElementById("pageNumber")
.addEventListener("change", function () {
PDFViewerApplication.page = this.value | 0; PDFViewerApplication.page = this.value | 0;
// Ensure that the page number input displays the correct value, // Ensure that the page number input displays the correct value,
@ -402,14 +404,14 @@ var PDFViewerApplication = {
} }
}); });
eventBus.on("pagesinit", function() { eventBus.on("pagesinit", function () {
// We can use pdfViewer now, e.g. let's change default scale. // We can use pdfViewer now, e.g. let's change default scale.
pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE; pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
}); });
eventBus.on( eventBus.on(
"pagechanging", "pagechanging",
function(evt) { function (evt) {
var page = evt.pageNumber; var page = evt.pageNumber;
var numPages = PDFViewerApplication.pagesCount; var numPages = PDFViewerApplication.pagesCount;
@ -424,7 +426,7 @@ var PDFViewerApplication = {
document.addEventListener( document.addEventListener(
"DOMContentLoaded", "DOMContentLoaded",
function() { function () {
PDFViewerApplication.initUI(); PDFViewerApplication.initUI();
}, },
true true
@ -433,13 +435,15 @@ document.addEventListener(
(function animationStartedClosure() { (function animationStartedClosure() {
// The offsetParent is not set until the PDF.js iframe or object is visible. // The offsetParent is not set until the PDF.js iframe or object is visible.
// Waiting for first animation. // Waiting for first animation.
PDFViewerApplication.animationStartedPromise = new Promise(function(resolve) { PDFViewerApplication.animationStartedPromise = new Promise(function (
resolve
) {
window.requestAnimationFrame(resolve); window.requestAnimationFrame(resolve);
}); });
})(); })();
// We need to delay opening until all HTML is loaded. // We need to delay opening until all HTML is loaded.
PDFViewerApplication.animationStartedPromise.then(function() { PDFViewerApplication.animationStartedPromise.then(function () {
PDFViewerApplication.open({ PDFViewerApplication.open({
url: DEFAULT_URL, url: DEFAULT_URL,
}); });

View File

@ -58,7 +58,7 @@ function DOMElement(name) {
if (name === "style") { if (name === "style") {
this.sheet = { this.sheet = {
cssRules: [], cssRules: [],
insertRule: function(rule) { insertRule: function (rule) {
this.cssRules.push(rule); this.cssRules.push(rule);
}, },
}; };
@ -226,16 +226,16 @@ const document = {
return this; return this;
}, },
createElementNS: function(NS, element) { createElementNS: function (NS, element) {
var elObject = new DOMElement(element); var elObject = new DOMElement(element);
return elObject; return elObject;
}, },
createElement: function(element) { createElement: function (element) {
return this.createElementNS("", element); return this.createElementNS("", element);
}, },
getElementsByTagName: function(element) { getElementsByTagName: function (element) {
if (element === "head") { if (element === "head") {
return [this.head || (this.head = new DOMElement("head"))]; return [this.head || (this.head = new DOMElement("head"))];
} }
@ -264,14 +264,14 @@ exports.Image = Image;
var exported_symbols = Object.keys(exports); var exported_symbols = Object.keys(exports);
exports.setStubs = function(namespace) { exports.setStubs = function (namespace) {
exported_symbols.forEach(function(key) { exported_symbols.forEach(function (key) {
console.assert(!(key in namespace), "property should not be set: " + key); console.assert(!(key in namespace), "property should not be set: " + key);
namespace[key] = exports[key]; namespace[key] = exports[key];
}); });
}; };
exports.unsetStubs = function(namespace) { exports.unsetStubs = function (namespace) {
exported_symbols.forEach(function(key) { exported_symbols.forEach(function (key) {
console.assert(key in namespace, "property should be set: " + key); console.assert(key in namespace, "property should be set: " + key);
delete namespace[key]; delete namespace[key];
}); });

View File

@ -17,14 +17,14 @@ var pdfPath = process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf";
// callback. // callback.
var loadingTask = pdfjsLib.getDocument(pdfPath); var loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise loadingTask.promise
.then(function(doc) { .then(function (doc) {
var numPages = doc.numPages; var numPages = doc.numPages;
console.log("# Document Loaded"); console.log("# Document Loaded");
console.log("Number of Pages: " + numPages); console.log("Number of Pages: " + numPages);
console.log(); console.log();
var lastPromise; // will be used to chain promises var lastPromise; // will be used to chain promises
lastPromise = doc.getMetadata().then(function(data) { lastPromise = doc.getMetadata().then(function (data) {
console.log("# Metadata Is Loaded"); console.log("# Metadata Is Loaded");
console.log("## Info"); console.log("## Info");
console.log(JSON.stringify(data.info, null, 2)); console.log(JSON.stringify(data.info, null, 2));
@ -36,24 +36,24 @@ loadingTask.promise
} }
}); });
var loadPage = function(pageNum) { var loadPage = function (pageNum) {
return doc.getPage(pageNum).then(function(page) { return doc.getPage(pageNum).then(function (page) {
console.log("# Page " + pageNum); console.log("# Page " + pageNum);
var viewport = page.getViewport({ scale: 1.0 }); var viewport = page.getViewport({ scale: 1.0 });
console.log("Size: " + viewport.width + "x" + viewport.height); console.log("Size: " + viewport.width + "x" + viewport.height);
console.log(); console.log();
return page return page
.getTextContent() .getTextContent()
.then(function(content) { .then(function (content) {
// Content contains lots of information about the text layout and // Content contains lots of information about the text layout and
// styles, but we need only strings at the moment // styles, but we need only strings at the moment
var strings = content.items.map(function(item) { var strings = content.items.map(function (item) {
return item.str; return item.str;
}); });
console.log("## Text Content"); console.log("## Text Content");
console.log(strings.join(" ")); console.log(strings.join(" "));
}) })
.then(function() { .then(function () {
console.log(); console.log();
}); });
}); });
@ -66,10 +66,10 @@ loadingTask.promise
return lastPromise; return lastPromise;
}) })
.then( .then(
function() { function () {
console.log("# End of Document"); console.log("# End of Document");
}, },
function(err) { function (err) {
console.error("Error: " + err); console.error("Error: " + err);
} }
); );

View File

@ -59,11 +59,11 @@ var rawData = new Uint8Array(fs.readFileSync(pdfURL));
// Load the PDF file. // Load the PDF file.
var loadingTask = pdfjsLib.getDocument(rawData); var loadingTask = pdfjsLib.getDocument(rawData);
loadingTask.promise loadingTask.promise
.then(function(pdfDocument) { .then(function (pdfDocument) {
console.log("# PDF document loaded."); console.log("# PDF document loaded.");
// Get the first page. // Get the first page.
pdfDocument.getPage(1).then(function(page) { pdfDocument.getPage(1).then(function (page) {
// Render the page on a Node canvas with 100% scale. // Render the page on a Node canvas with 100% scale.
var viewport = page.getViewport({ scale: 1.0 }); var viewport = page.getViewport({ scale: 1.0 });
var canvasFactory = new NodeCanvasFactory(); var canvasFactory = new NodeCanvasFactory();
@ -78,10 +78,10 @@ loadingTask.promise
}; };
var renderTask = page.render(renderContext); var renderTask = page.render(renderContext);
renderTask.promise.then(function() { renderTask.promise.then(function () {
// Convert the canvas to an image buffer. // Convert the canvas to an image buffer.
var image = canvasAndContext.canvas.toBuffer(); var image = canvasAndContext.canvas.toBuffer();
fs.writeFile("output.png", image, function(error) { fs.writeFile("output.png", image, function (error) {
if (error) { if (error) {
console.error("Error: " + error); console.error("Error: " + error);
} else { } else {
@ -93,6 +93,6 @@ loadingTask.promise
}); });
}); });
}) })
.catch(function(reason) { .catch(function (reason) {
console.log(reason); console.log(reason);
}); });

View File

@ -54,7 +54,7 @@ function ReadableSVGStream(options) {
} }
util.inherits(ReadableSVGStream, stream.Readable); util.inherits(ReadableSVGStream, stream.Readable);
// Implements https://nodejs.org/api/stream.html#stream_readable_read_size_1 // Implements https://nodejs.org/api/stream.html#stream_readable_read_size_1
ReadableSVGStream.prototype._read = function() { ReadableSVGStream.prototype._read = function () {
var chunk; var chunk;
while ((chunk = this.serializer.getNext()) !== null) { while ((chunk = this.serializer.getNext()) !== null) {
if (!this.push(chunk)) { if (!this.push(chunk)) {
@ -70,12 +70,12 @@ function writeSvgToFile(svgElement, filePath) {
svgElement: svgElement, svgElement: svgElement,
}); });
var writableStream = fs.createWriteStream(filePath); var writableStream = fs.createWriteStream(filePath);
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
readableSvgStream.once("error", reject); readableSvgStream.once("error", reject);
writableStream.once("error", reject); writableStream.once("error", reject);
writableStream.once("finish", resolve); writableStream.once("finish", resolve);
readableSvgStream.pipe(writableStream); readableSvgStream.pipe(writableStream);
}).catch(function(err) { }).catch(function (err) {
readableSvgStream = null; // Explicitly null because of v8 bug 6512. readableSvgStream = null; // Explicitly null because of v8 bug 6512.
writableStream.end(); writableStream.end();
throw err; throw err;
@ -91,29 +91,29 @@ var loadingTask = pdfjsLib.getDocument({
nativeImageDecoderSupport: pdfjsLib.NativeImageDecoding.DISPLAY, nativeImageDecoderSupport: pdfjsLib.NativeImageDecoding.DISPLAY,
}); });
loadingTask.promise loadingTask.promise
.then(function(doc) { .then(function (doc) {
var numPages = doc.numPages; var numPages = doc.numPages;
console.log("# Document Loaded"); console.log("# Document Loaded");
console.log("Number of Pages: " + numPages); console.log("Number of Pages: " + numPages);
console.log(); console.log();
var lastPromise = Promise.resolve(); // will be used to chain promises var lastPromise = Promise.resolve(); // will be used to chain promises
var loadPage = function(pageNum) { var loadPage = function (pageNum) {
return doc.getPage(pageNum).then(function(page) { return doc.getPage(pageNum).then(function (page) {
console.log("# Page " + pageNum); console.log("# Page " + pageNum);
var viewport = page.getViewport({ scale: 1.0 }); var viewport = page.getViewport({ scale: 1.0 });
console.log("Size: " + viewport.width + "x" + viewport.height); console.log("Size: " + viewport.width + "x" + viewport.height);
console.log(); console.log();
return page.getOperatorList().then(function(opList) { return page.getOperatorList().then(function (opList) {
var svgGfx = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs); var svgGfx = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs);
svgGfx.embedFonts = true; svgGfx.embedFonts = true;
return svgGfx.getSVG(opList, viewport).then(function(svg) { return svgGfx.getSVG(opList, viewport).then(function (svg) {
return writeSvgToFile(svg, getFilePathForPage(pageNum)).then( return writeSvgToFile(svg, getFilePathForPage(pageNum)).then(
function() { function () {
console.log("Page: " + pageNum); console.log("Page: " + pageNum);
}, },
function(err) { function (err) {
console.log("Error: " + err); console.log("Error: " + err);
} }
); );
@ -128,10 +128,10 @@ loadingTask.promise
return lastPromise; return lastPromise;
}) })
.then( .then(
function() { function () {
console.log("# End of Document"); console.log("# End of Document");
}, },
function(err) { function (err) {
console.error("Error: " + err); console.error("Error: " + err);
} }
); );

View File

@ -49,7 +49,7 @@ var pdfViewer = new pdfjsViewer.PDFViewer({
}); });
pdfLinkService.setViewer(pdfViewer); pdfLinkService.setViewer(pdfViewer);
eventBus.on("pagesinit", function() { eventBus.on("pagesinit", function () {
// We can use pdfViewer now, e.g. let's change default scale. // We can use pdfViewer now, e.g. let's change default scale.
pdfViewer.currentScaleValue = "page-width"; pdfViewer.currentScaleValue = "page-width";
}); });
@ -60,7 +60,7 @@ var loadingTask = pdfjsLib.getDocument({
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,
}); });
loadingTask.promise.then(function(pdfDocument) { loadingTask.promise.then(function (pdfDocument) {
// Document loaded, specifying document for the viewer and // Document loaded, specifying document for the viewer and
// the (optional) linkService. // the (optional) linkService.
pdfViewer.setDocument(pdfDocument); pdfViewer.setDocument(pdfDocument);

View File

@ -30,7 +30,7 @@ function buildSVG(viewport, textContent) {
svg.setAttribute("font-size", 1); svg.setAttribute("font-size", 1);
// processing all items // processing all items
textContent.items.forEach(function(textItem) { textContent.items.forEach(function (textItem) {
// we have to take in account viewport transform, which includes scale, // we have to take in account viewport transform, which includes scale,
// rotation and Y-axis flip, and not forgetting to flip text. // rotation and Y-axis flip, and not forgetting to flip text.
var tx = pdfjsLib.Util.transform( var tx = pdfjsLib.Util.transform(
@ -51,10 +51,10 @@ function buildSVG(viewport, textContent) {
function pageLoaded() { function pageLoaded() {
// Loading document and page text content // Loading document and page text content
var loadingTask = pdfjsLib.getDocument({ url: PDF_PATH }); var loadingTask = pdfjsLib.getDocument({ url: PDF_PATH });
loadingTask.promise.then(function(pdfDocument) { loadingTask.promise.then(function (pdfDocument) {
pdfDocument.getPage(PAGE_NUMBER).then(function(page) { pdfDocument.getPage(PAGE_NUMBER).then(function (page) {
var viewport = page.getViewport({ scale: PAGE_SCALE }); var viewport = page.getViewport({ scale: PAGE_SCALE });
page.getTextContent().then(function(textContent) { page.getTextContent().then(function (textContent) {
// building SVG and adding that to the DOM // building SVG and adding that to the DOM
var svg = buildSVG(viewport, textContent); var svg = buildSVG(viewport, textContent);
document.getElementById("pageContainer").appendChild(svg); document.getElementById("pageContainer").appendChild(svg);
@ -63,7 +63,7 @@ function pageLoaded() {
}); });
} }
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function () {
if (typeof pdfjsLib === "undefined") { if (typeof pdfjsLib === "undefined") {
alert( alert(
"Built version of PDF.js was not found.\n" + "Built version of PDF.js was not found.\n" +

View File

@ -14,9 +14,9 @@ pdfjsLib.GlobalWorkerOptions.workerSrc =
// Loading a document. // Loading a document.
var loadingTask = pdfjsLib.getDocument(pdfPath); var loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise loadingTask.promise
.then(function(pdfDocument) { .then(function (pdfDocument) {
// Request a first page // Request a first page
return pdfDocument.getPage(1).then(function(pdfPage) { return pdfDocument.getPage(1).then(function (pdfPage) {
// Display page on the existing canvas with 100% scale. // Display page on the existing canvas with 100% scale.
var viewport = pdfPage.getViewport({ scale: 1.0 }); var viewport = pdfPage.getViewport({ scale: 1.0 });
var canvas = document.getElementById("theCanvas"); var canvas = document.getElementById("theCanvas");
@ -30,6 +30,6 @@ loadingTask.promise
return renderTask.promise; return renderTask.promise;
}); });
}) })
.catch(function(reason) { .catch(function (reason) {
console.error("Error: " + reason); console.error("Error: " + reason);
}); });

View File

@ -61,7 +61,7 @@ limitations under the License.
// (or rewrite the query string parser in viewer.js to get it to // (or rewrite the query string parser in viewer.js to get it to
// recognize the non-URL-encoded PDF URL.) // recognize the non-URL-encoded PDF URL.)
chrome.webRequest.onBeforeRequest.addListener( chrome.webRequest.onBeforeRequest.addListener(
function(details) { function (details) {
// This listener converts chrome-extension://.../http://...pdf to // This listener converts chrome-extension://.../http://...pdf to
// chrome-extension://.../content/web/viewer.html?file=http%3A%2F%2F...pdf // chrome-extension://.../content/web/viewer.html?file=http%3A%2F%2F...pdf
var url = parseExtensionURL(details.url); var url = parseExtensionURL(details.url);
@ -78,7 +78,7 @@ limitations under the License.
}, },
{ {
types: ["main_frame", "sub_frame"], types: ["main_frame", "sub_frame"],
urls: schemes.map(function(scheme) { urls: schemes.map(function (scheme) {
// Format: "chrome-extension://[EXTENSIONID]/<scheme>*" // Format: "chrome-extension://[EXTENSIONID]/<scheme>*"
return CRX_BASE_URL + scheme + "*"; return CRX_BASE_URL + scheme + "*";
}), }),
@ -94,7 +94,7 @@ limitations under the License.
{ {
url: CRX_BASE_URL + "*:*", url: CRX_BASE_URL + "*:*",
}, },
function(tabsFromLastSession) { function (tabsFromLastSession) {
for (var i = 0; i < tabsFromLastSession.length; ++i) { for (var i = 0; i < tabsFromLastSession.length; ++i) {
chrome.tabs.reload(tabsFromLastSession[i].id); chrome.tabs.reload(tabsFromLastSession[i].id);
} }
@ -102,7 +102,7 @@ limitations under the License.
); );
console.log("Set up extension URL router."); console.log("Set up extension URL router.");
Object.keys(localStorage).forEach(function(key) { Object.keys(localStorage).forEach(function (key) {
// The localStorage item is set upon unload by chromecom.js. // The localStorage item is set upon unload by chromecom.js.
var parsedKey = /^unload-(\d+)-(true|false)-(.+)/.exec(key); var parsedKey = /^unload-(\d+)-(true|false)-(.+)/.exec(key);
if (parsedKey) { if (parsedKey) {

View File

@ -15,7 +15,7 @@ limitations under the License.
*/ */
/* eslint strict: ["error", "function"] */ /* eslint strict: ["error", "function"] */
(function() { (function () {
"use strict"; "use strict";
var storageLocal = chrome.storage.local; var storageLocal = chrome.storage.local;
var storageSync = chrome.storage.sync; var storageSync = chrome.storage.sync;
@ -25,8 +25,8 @@ limitations under the License.
return; return;
} }
getStorageNames(function(storageKeys) { getStorageNames(function (storageKeys) {
storageLocal.get(storageKeys, function(values) { storageLocal.get(storageKeys, function (values) {
if (!values || !Object.keys(values).length) { if (!values || !Object.keys(values).length) {
// No local storage - nothing to migrate. // No local storage - nothing to migrate.
// ... except possibly for a renamed preference name. // ... except possibly for a renamed preference name.
@ -41,7 +41,7 @@ limitations under the License.
var x = new XMLHttpRequest(); var x = new XMLHttpRequest();
var schema_location = chrome.runtime.getManifest().storage.managed_schema; var schema_location = chrome.runtime.getManifest().storage.managed_schema;
x.open("get", chrome.runtime.getURL(schema_location)); x.open("get", chrome.runtime.getURL(schema_location));
x.onload = function() { x.onload = function () {
var storageKeys = Object.keys(x.response.properties); var storageKeys = Object.keys(x.response.properties);
callback(storageKeys); callback(storageKeys);
}; };
@ -52,7 +52,7 @@ limitations under the License.
// Save |values| to storage.sync and delete the values with that key from // Save |values| to storage.sync and delete the values with that key from
// storage.local. // storage.local.
function migrateToSyncStorage(values) { function migrateToSyncStorage(values) {
storageSync.set(values, function() { storageSync.set(values, function () {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
console.error( console.error(
"Failed to migrate settings due to an error: " + "Failed to migrate settings due to an error: " +
@ -61,7 +61,7 @@ limitations under the License.
return; return;
} }
// Migration successful. Delete local settings. // Migration successful. Delete local settings.
storageLocal.remove(Object.keys(values), function() { storageLocal.remove(Object.keys(values), function () {
// In theory remove() could fail (e.g. if the browser's storage // In theory remove() could fail (e.g. if the browser's storage
// backend is corrupt), but since storageSync.set succeeded, consider // backend is corrupt), but since storageSync.set succeeded, consider
// the migration successful. // the migration successful.
@ -89,7 +89,7 @@ limitations under the License.
"disablePageMode", "disablePageMode",
"viewOnLoad", "viewOnLoad",
], ],
function(items) { function (items) {
// Migration code for https://github.com/mozilla/pdf.js/pull/7635. // Migration code for https://github.com/mozilla/pdf.js/pull/7635.
if (typeof items.enableHandToolOnLoad === "boolean") { if (typeof items.enableHandToolOnLoad === "boolean") {
if (items.enableHandToolOnLoad) { if (items.enableHandToolOnLoad) {
@ -97,7 +97,7 @@ limitations under the License.
{ {
cursorToolOnLoad: 1, cursorToolOnLoad: 1,
}, },
function() { function () {
if (!chrome.runtime.lastError) { if (!chrome.runtime.lastError) {
storageSync.remove("enableHandToolOnLoad"); storageSync.remove("enableHandToolOnLoad");
} }
@ -121,7 +121,7 @@ limitations under the License.
{ {
textLayerMode: textLayerMode, textLayerMode: textLayerMode,
}, },
function() { function () {
if (!chrome.runtime.lastError) { if (!chrome.runtime.lastError) {
storageSync.remove([ storageSync.remove([
"disableTextLayer", "disableTextLayer",
@ -141,7 +141,7 @@ limitations under the License.
{ {
viewOnLoad: 1, viewOnLoad: 1,
}, },
function() { function () {
if (!chrome.runtime.lastError) { if (!chrome.runtime.lastError) {
storageSync.remove([ storageSync.remove([
"showPreviousViewOnLoad", "showPreviousViewOnLoad",

View File

@ -25,13 +25,13 @@ Promise.all([
return; return;
} }
// Get preferences as set by the system administrator. // Get preferences as set by the system administrator.
chrome.storage.managed.get(null, function(prefs) { chrome.storage.managed.get(null, function (prefs) {
// Managed storage may be disabled, e.g. in Opera. // Managed storage may be disabled, e.g. in Opera.
resolve(prefs || {}); resolve(prefs || {});
}); });
}), }),
new Promise(function getUserPrefs(resolve) { new Promise(function getUserPrefs(resolve) {
storageArea.get(null, function(prefs) { storageArea.get(null, function (prefs) {
resolve(prefs || {}); resolve(prefs || {});
}); });
}), }),
@ -40,14 +40,14 @@ Promise.all([
var x = new XMLHttpRequest(); var x = new XMLHttpRequest();
var schema_location = chrome.runtime.getManifest().storage.managed_schema; var schema_location = chrome.runtime.getManifest().storage.managed_schema;
x.open("get", chrome.runtime.getURL(schema_location)); x.open("get", chrome.runtime.getURL(schema_location));
x.onload = function() { x.onload = function () {
resolve(x.response.properties); resolve(x.response.properties);
}; };
x.responseType = "json"; x.responseType = "json";
x.send(); x.send();
}), }),
]) ])
.then(function(values) { .then(function (values) {
var managedPrefs = values[0]; var managedPrefs = values[0];
var userPrefs = values[1]; var userPrefs = values[1];
var schema = values[2]; var schema = values[2];
@ -62,7 +62,7 @@ Promise.all([
var prefNames = Object.keys(schema); var prefNames = Object.keys(schema);
var renderPreferenceFunctions = {}; var renderPreferenceFunctions = {};
// Render options // Render options
prefNames.forEach(function(prefName) { prefNames.forEach(function (prefName) {
var prefSchema = schema[prefName]; var prefSchema = schema[prefName];
if (!prefSchema.title) { if (!prefSchema.title) {
// Don't show preferences if the title is missing. // Don't show preferences if the title is missing.
@ -102,17 +102,17 @@ Promise.all([
var renderedPrefNames = Object.keys(renderPreferenceFunctions); var renderedPrefNames = Object.keys(renderPreferenceFunctions);
// Reset button to restore default settings. // Reset button to restore default settings.
document.getElementById("reset-button").onclick = function() { document.getElementById("reset-button").onclick = function () {
userPrefs = {}; userPrefs = {};
storageArea.remove(prefNames, function() { storageArea.remove(prefNames, function () {
renderedPrefNames.forEach(function(prefName) { renderedPrefNames.forEach(function (prefName) {
renderPreferenceFunctions[prefName](getPrefValue(prefName)); renderPreferenceFunctions[prefName](getPrefValue(prefName));
}); });
}); });
}; };
// Automatically update the UI when the preferences were changed elsewhere. // Automatically update the UI when the preferences were changed elsewhere.
chrome.storage.onChanged.addListener(function(changes, areaName) { chrome.storage.onChanged.addListener(function (changes, areaName) {
var prefs = null; var prefs = null;
if (areaName === storageAreaName) { if (areaName === storageAreaName) {
prefs = userPrefs; prefs = userPrefs;
@ -120,7 +120,7 @@ Promise.all([
prefs = managedPrefs; prefs = managedPrefs;
} }
if (prefs) { if (prefs) {
renderedPrefNames.forEach(function(prefName) { renderedPrefNames.forEach(function (prefName) {
var prefChanges = changes[prefName]; var prefChanges = changes[prefName];
if (prefChanges) { if (prefChanges) {
if ("newValue" in prefChanges) { if ("newValue" in prefChanges) {
@ -149,7 +149,7 @@ function renderBooleanPref(shortDescription, description, prefName) {
wrapper.title = description; wrapper.title = description;
var checkbox = wrapper.querySelector('input[type="checkbox"]'); var checkbox = wrapper.querySelector('input[type="checkbox"]');
checkbox.onchange = function() { checkbox.onchange = function () {
var pref = {}; var pref = {};
pref[prefName] = this.checked; pref[prefName] = this.checked;
storageArea.set(pref); storageArea.set(pref);
@ -166,7 +166,7 @@ function renderBooleanPref(shortDescription, description, prefName) {
function renderEnumPref(shortDescription, prefName) { function renderEnumPref(shortDescription, prefName) {
var wrapper = importTemplate(prefName + "-template"); var wrapper = importTemplate(prefName + "-template");
var select = wrapper.querySelector("select"); var select = wrapper.querySelector("select");
select.onchange = function() { select.onchange = function () {
var pref = {}; var pref = {};
pref[prefName] = parseInt(this.value); pref[prefName] = parseInt(this.value);
storageArea.set(pref); storageArea.set(pref);
@ -183,7 +183,7 @@ function renderEnumPref(shortDescription, prefName) {
function renderDefaultZoomValue(shortDescription) { function renderDefaultZoomValue(shortDescription) {
var wrapper = importTemplate("defaultZoomValue-template"); var wrapper = importTemplate("defaultZoomValue-template");
var select = wrapper.querySelector("select"); var select = wrapper.querySelector("select");
select.onchange = function() { select.onchange = function () {
storageArea.set({ storageArea.set({
defaultZoomValue: this.value, defaultZoomValue: this.value,
}); });

View File

@ -37,7 +37,7 @@ limitations under the License.
} }
} }
chrome.runtime.onMessage.addListener(function(message, sender) { chrome.runtime.onMessage.addListener(function (message, sender) {
if (message === "showPageAction" && sender.tab) { if (message === "showPageAction" && sender.tab) {
showPageAction(sender.tab.id, sender.tab.url); showPageAction(sender.tab.id, sender.tab.url);
} }

View File

@ -16,7 +16,7 @@ limitations under the License.
/* eslint strict: ["error", "function"] */ /* eslint strict: ["error", "function"] */
/* import-globals-from pdfHandler.js */ /* import-globals-from pdfHandler.js */
(function() { (function () {
"use strict"; "use strict";
if (!chrome.fileBrowserHandler) { if (!chrome.fileBrowserHandler) {
@ -41,12 +41,12 @@ limitations under the License.
// the other Chrome APIs that use "tabId" (http://crbug.com/179767) // the other Chrome APIs that use "tabId" (http://crbug.com/179767)
var tabId = details.tab_id || details.tabId; var tabId = details.tab_id || details.tabId;
if (tabId > 0) { if (tabId > 0) {
chrome.tabs.get(tabId, function(tab) { chrome.tabs.get(tabId, function (tab) {
openViewer(tab && tab.windowId, fileEntries); openViewer(tab && tab.windowId, fileEntries);
}); });
} else { } else {
// Re-use existing window, if available. // Re-use existing window, if available.
chrome.windows.getLastFocused(function(chromeWindow) { chrome.windows.getLastFocused(function (chromeWindow) {
var windowId = chromeWindow && chromeWindow.id; var windowId = chromeWindow && chromeWindow.id;
if (windowId) { if (windowId) {
chrome.windows.update(windowId, { focused: true }); chrome.windows.update(windowId, { focused: true });
@ -82,7 +82,7 @@ limitations under the License.
active: true, active: true,
url: url, url: url,
}, },
function() { function () {
openViewer(windowId, fileEntries); openViewer(windowId, fileEntries);
} }
); );
@ -93,7 +93,7 @@ limitations under the License.
focused: true, focused: true,
url: url, url: url,
}, },
function(chromeWindow) { function (chromeWindow) {
openViewer(chromeWindow.id, fileEntries); openViewer(chromeWindow.id, fileEntries);
} }
); );

View File

@ -73,10 +73,7 @@ function getHeaderFromHeaders(headers, headerName) {
function isPdfFile(details) { function isPdfFile(details) {
var header = getHeaderFromHeaders(details.responseHeaders, "content-type"); var header = getHeaderFromHeaders(details.responseHeaders, "content-type");
if (header) { if (header) {
var headerValue = header.value var headerValue = header.value.toLowerCase().split(";", 1)[0].trim();
.toLowerCase()
.split(";", 1)[0]
.trim();
if (headerValue === "application/pdf") { if (headerValue === "application/pdf") {
return true; return true;
} }
@ -120,7 +117,7 @@ function getHeadersWithContentDispositionAttachment(details) {
} }
chrome.webRequest.onHeadersReceived.addListener( chrome.webRequest.onHeadersReceived.addListener(
function(details) { function (details) {
if (details.method !== "GET") { if (details.method !== "GET") {
// Don't intercept POST requests until http://crbug.com/104058 is fixed. // Don't intercept POST requests until http://crbug.com/104058 is fixed.
return undefined; return undefined;
@ -148,7 +145,7 @@ chrome.webRequest.onHeadersReceived.addListener(
); );
chrome.webRequest.onBeforeRequest.addListener( chrome.webRequest.onBeforeRequest.addListener(
function(details) { function (details) {
if (isPdfDownloadable(details)) { if (isPdfDownloadable(details)) {
return undefined; return undefined;
} }
@ -176,7 +173,7 @@ chrome.webRequest.onBeforeRequest.addListener(
["blocking"] ["blocking"]
); );
chrome.extension.isAllowedFileSchemeAccess(function(isAllowedAccess) { chrome.extension.isAllowedFileSchemeAccess(function (isAllowedAccess) {
if (isAllowedAccess) { if (isAllowedAccess) {
return; return;
} }
@ -186,7 +183,7 @@ chrome.extension.isAllowedFileSchemeAccess(function(isAllowedAccess) {
// The viewer will detect that it has no access to file:-URLs, and prompt the // The viewer will detect that it has no access to file:-URLs, and prompt the
// user to activate file permissions. // user to activate file permissions.
chrome.webNavigation.onBeforeNavigate.addListener( chrome.webNavigation.onBeforeNavigate.addListener(
function(details) { function (details) {
if (details.frameId === 0 && !isPdfDownloadable(details)) { if (details.frameId === 0 && !isPdfDownloadable(details)) {
chrome.tabs.update(details.tabId, { chrome.tabs.update(details.tabId, {
url: getViewerURL(details.url), url: getViewerURL(details.url),
@ -208,7 +205,7 @@ chrome.extension.isAllowedFileSchemeAccess(function(isAllowedAccess) {
); );
}); });
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message && message.action === "getParentOrigin") { if (message && message.action === "getParentOrigin") {
// getParentOrigin is used to determine whether it is safe to embed a // getParentOrigin is used to determine whether it is safe to embed a
// sensitive (local) file in a frame. // sensitive (local) file in a frame.

View File

@ -43,7 +43,7 @@ var g_referrers = {};
var extraInfoSpecWithHeaders; // = ['requestHeaders', 'extraHeaders'] var extraInfoSpecWithHeaders; // = ['requestHeaders', 'extraHeaders']
(function() { (function () {
var requestFilter = { var requestFilter = {
urls: ["*://*/*"], urls: ["*://*/*"],
types: ["main_frame", "sub_frame"], types: ["main_frame", "sub_frame"],
@ -52,7 +52,7 @@ var extraInfoSpecWithHeaders; // = ['requestHeaders', 'extraHeaders']
extraInfoSpecWithHeaders = extraInfoSpec; extraInfoSpecWithHeaders = extraInfoSpec;
// May throw if the given extraInfoSpec is unsupported. // May throw if the given extraInfoSpec is unsupported.
chrome.webRequest.onSendHeaders.addListener( chrome.webRequest.onSendHeaders.addListener(
function(details) { function (details) {
g_requestHeaders[details.requestId] = details.requestHeaders; g_requestHeaders[details.requestId] = details.requestHeaders;
}, },
requestFilter, requestFilter,
@ -87,7 +87,7 @@ function saveReferer(details) {
g_referrers[details.tabId][details.frameId] = referer; g_referrers[details.tabId][details.frameId] = referer;
} }
chrome.tabs.onRemoved.addListener(function(tabId) { chrome.tabs.onRemoved.addListener(function (tabId) {
delete g_referrers[tabId]; delete g_referrers[tabId];
}); });
@ -108,7 +108,7 @@ chrome.runtime.onConnect.addListener(function onReceivePort(port) {
// If the PDF is viewed for the first time, then the referer will be set here. // If the PDF is viewed for the first time, then the referer will be set here.
var referer = (g_referrers[tabId] && g_referrers[tabId][frameId]) || ""; var referer = (g_referrers[tabId] && g_referrers[tabId][frameId]) || "";
port.onMessage.addListener(function(data) { port.onMessage.addListener(function (data) {
// If the viewer was opened directly (without opening a PDF URL first), then // If the viewer was opened directly (without opening a PDF URL first), then
// the background script does not know about g_referrers, but the viewer may // the background script does not know about g_referrers, but the viewer may
// know about the referer if stored in the history state (see chromecom.js). // know about the referer if stored in the history state (see chromecom.js).
@ -133,7 +133,7 @@ chrome.runtime.onConnect.addListener(function onReceivePort(port) {
}); });
// The port is only disconnected when the other end reloads. // The port is only disconnected when the other end reloads.
port.onDisconnect.addListener(function() { port.onDisconnect.addListener(function () {
if (g_referrers[tabId]) { if (g_referrers[tabId]) {
delete g_referrers[tabId][frameId]; delete g_referrers[tabId][frameId];
} }

View File

@ -19,7 +19,7 @@ limitations under the License.
// Do not reload the extension when an update becomes available, UNLESS the PDF // Do not reload the extension when an update becomes available, UNLESS the PDF
// viewer is not displaying any PDF files. Otherwise the tabs would close, which // viewer is not displaying any PDF files. Otherwise the tabs would close, which
// is quite disruptive (crbug.com/511670). // is quite disruptive (crbug.com/511670).
chrome.runtime.onUpdateAvailable.addListener(function() { chrome.runtime.onUpdateAvailable.addListener(function () {
if (chrome.extension.getViews({ type: "tab" }).length === 0) { if (chrome.extension.getViews({ type: "tab" }).length === 0) {
chrome.runtime.reload(); chrome.runtime.reload();
} }

View File

@ -15,7 +15,7 @@ limitations under the License.
*/ */
/* eslint strict: ["error", "function"] */ /* eslint strict: ["error", "function"] */
(function() { (function () {
"use strict"; "use strict";
// This module sends the browser and extension version to a server, to // This module sends the browser and extension version to a server, to
// determine whether it is safe to drop support for old Chrome versions in // determine whether it is safe to drop support for old Chrome versions in
@ -46,7 +46,7 @@ limitations under the License.
setInterval(maybeSendPing, 36e5); setInterval(maybeSendPing, 36e5);
function maybeSendPing() { function maybeSendPing() {
getLoggingPref(function(didOptOut) { getLoggingPref(function (didOptOut) {
if (didOptOut) { if (didOptOut) {
// Respect the user's decision to not send statistics. // Respect the user's decision to not send statistics.
return; return;
@ -154,7 +154,7 @@ limitations under the License.
return; return;
} }
chrome.storage[storageAreaName].get("disableTelemetry", function(items) { chrome.storage[storageAreaName].get("disableTelemetry", function (items) {
next(items && items.disableTelemetry); next(items && items.disableTelemetry);
}); });
} }

View File

@ -1,7 +1,7 @@
"use strict"; "use strict";
// Small subset of the webL10n API by Fabien Cazenave for PDF.js extension. // Small subset of the webL10n API by Fabien Cazenave for PDF.js extension.
(function(window) { (function (window) {
var gLanguage = ""; var gLanguage = "";
var gExternalLocalizerServices = null; var gExternalLocalizerServices = null;
var gReadyState = "loading"; var gReadyState = "loading";
@ -21,7 +21,7 @@
if (!args) { if (!args) {
return text; return text;
} }
return text.replace(/\{\{\s*(\w+)\s*\}\}/g, function(all, name) { return text.replace(/\{\{\s*(\w+)\s*\}\}/g, function (all, name) {
return name in args ? args[name] : "{{" + name + "}}"; return name in args ? args[name] : "{{" + name + "}}";
}); });
} }

View File

@ -34,10 +34,7 @@ var fs = require("fs"),
*/ */
function preprocess(inFilename, outFilename, defines) { function preprocess(inFilename, outFilename, defines) {
// TODO make this really read line by line. // TODO make this really read line by line.
var lines = fs var lines = fs.readFileSync(inFilename).toString().split("\n");
.readFileSync(inFilename)
.toString()
.split("\n");
var totalLines = lines.length; var totalLines = lines.length;
var out = ""; var out = "";
var i = 0; var i = 0;
@ -50,7 +47,7 @@ function preprocess(inFilename, outFilename, defines) {
var writeLine = var writeLine =
typeof outFilename === "function" typeof outFilename === "function"
? outFilename ? outFilename
: function(line) { : function (line) {
out += line + "\n"; out += line + "\n";
}; };
function evaluateCondition(code) { function evaluateCondition(code) {
@ -95,7 +92,7 @@ function preprocess(inFilename, outFilename, defines) {
} }
} }
function expand(line) { function expand(line) {
line = line.replace(/__[\w]+__/g, function(variable) { line = line.replace(/__[\w]+__/g, function (variable) {
variable = variable.substring(2, variable.length - 2); variable = variable.substring(2, variable.length - 2);
if (variable in defines) { if (variable in defines) {
return defines[variable]; return defines[variable];
@ -122,7 +119,7 @@ function preprocess(inFilename, outFilename, defines) {
var stack = []; var stack = [];
var control = /^(?:\/\/|<!--)\s*#(if|elif|else|endif|expand|include|error)\b(?:\s+(.*?)(?:-->)?$)?/; var control = /^(?:\/\/|<!--)\s*#(if|elif|else|endif|expand|include|error)\b(?:\s+(.*?)(?:-->)?$)?/;
var lineNumber = 0; var lineNumber = 0;
var loc = function() { var loc = function () {
return fs.realpathSync(inFilename) + ":" + lineNumber; return fs.realpathSync(inFilename) + ":" + lineNumber;
}; };
while ((line = readLine()) !== null) { while ((line = readLine()) !== null) {
@ -215,7 +212,7 @@ function preprocessCSS(mode, source, destination) {
} }
function expandImports(content, baseUrl) { function expandImports(content, baseUrl) {
return content.replace(/^\s*@import\s+url\(([^\)]+)\);\s*$/gm, function( return content.replace(/^\s*@import\s+url\(([^\)]+)\);\s*$/gm, function (
all, all,
url url
) { ) {

View File

@ -294,7 +294,7 @@ function traverseTree(ctx, node) {
node[i] = result; node[i] = result;
} }
} else if (Array.isArray(child)) { } else if (Array.isArray(child)) {
child.forEach(function(childItem, index) { child.forEach(function (childItem, index) {
if ( if (
typeof childItem === "object" && typeof childItem === "object" &&
childItem !== null && childItem !== null &&

View File

@ -9,13 +9,13 @@ var errors = 0;
var baseDir = path.join(__dirname, "fixtures"); var baseDir = path.join(__dirname, "fixtures");
var files = fs var files = fs
.readdirSync(baseDir) .readdirSync(baseDir)
.filter(function(name) { .filter(function (name) {
return /-expected\./.test(name); return /-expected\./.test(name);
}) })
.map(function(name) { .map(function (name) {
return path.join(baseDir, name); return path.join(baseDir, name);
}); });
files.forEach(function(expectationFilename) { files.forEach(function (expectationFilename) {
var inFilename = expectationFilename.replace("-expected", ""); var inFilename = expectationFilename.replace("-expected", "");
var expectation = fs var expectation = fs
.readFileSync(expectationFilename) .readFileSync(expectationFilename)
@ -24,7 +24,7 @@ files.forEach(function(expectationFilename) {
.replace(/__filename/g, fs.realpathSync(inFilename)); .replace(/__filename/g, fs.realpathSync(inFilename));
var outLines = []; var outLines = [];
var outFilename = function(line) { var outFilename = function (line) {
outLines.push(line); outLines.push(line);
}; };
var defines = { var defines = {

View File

@ -9,13 +9,13 @@ var errors = 0;
var baseDir = path.join(__dirname, "fixtures_esprima"); var baseDir = path.join(__dirname, "fixtures_esprima");
var files = fs var files = fs
.readdirSync(baseDir) .readdirSync(baseDir)
.filter(function(name) { .filter(function (name) {
return /-expected\./.test(name); return /-expected\./.test(name);
}) })
.map(function(name) { .map(function (name) {
return path.join(baseDir, name); return path.join(baseDir, name);
}); });
files.forEach(function(expectationFilename) { files.forEach(function (expectationFilename) {
var inFilename = expectationFilename.replace("-expected", ""); var inFilename = expectationFilename.replace("-expected", "");
var expectation = fs var expectation = fs
.readFileSync(expectationFilename) .readFileSync(expectationFilename)

View File

@ -36,15 +36,15 @@ function downloadLanguageCodes() {
var ALL_LOCALES = var ALL_LOCALES =
"https://hg.mozilla.org/mozilla-central/raw-file/tip/browser/locales/all-locales"; "https://hg.mozilla.org/mozilla-central/raw-file/tip/browser/locales/all-locales";
return new Promise(function(resolve) { return new Promise(function (resolve) {
https.get(ALL_LOCALES, function(response) { https.get(ALL_LOCALES, function (response) {
if (response.statusCode === 200) { if (response.statusCode === 200) {
var content = ""; var content = "";
response.setEncoding("utf8"); response.setEncoding("utf8");
response.on("data", function(chunk) { response.on("data", function (chunk) {
content += chunk; content += chunk;
}); });
response.on("end", function() { response.on("end", function () {
content = content.trim(); // Remove any leading/trailing white-space. content = content.trim(); // Remove any leading/trailing white-space.
var langCodes = normalizeText(content).split("\n"); var langCodes = normalizeText(content).split("\n");
// Remove all locales that we don't want to download below. // Remove all locales that we don't want to download below.
@ -80,22 +80,22 @@ function downloadLanguageFiles(root, langCode) {
fs.mkdirSync(outputDir); fs.mkdirSync(outputDir);
} }
return new Promise(function(resolve) { return new Promise(function (resolve) {
// Download the necessary files for this language. // Download the necessary files for this language.
files.forEach(function(fileName) { files.forEach(function (fileName) {
var outputPath = path.join(outputDir, fileName); var outputPath = path.join(outputDir, fileName);
var url = MOZ_CENTRAL_ROOT + langCode + MOZ_CENTRAL_PDFJS_DIR + fileName; var url = MOZ_CENTRAL_ROOT + langCode + MOZ_CENTRAL_PDFJS_DIR + fileName;
https.get(url, function(response) { https.get(url, function (response) {
// Not all files exist for each language. Files without translations // Not all files exist for each language. Files without translations
// have been removed (https://bugzilla.mozilla.org/show_bug.cgi?id=1443175). // have been removed (https://bugzilla.mozilla.org/show_bug.cgi?id=1443175).
if (response.statusCode === 200) { if (response.statusCode === 200) {
var content = ""; var content = "";
response.setEncoding("utf8"); response.setEncoding("utf8");
response.on("data", function(chunk) { response.on("data", function (chunk) {
content += chunk; content += chunk;
}); });
response.on("end", function() { response.on("end", function () {
fs.writeFileSync(outputPath, normalizeText(content), "utf8"); fs.writeFileSync(outputPath, normalizeText(content), "utf8");
if (--downloadsLeft === 0) { if (--downloadsLeft === 0) {
resolve(); resolve();

View File

@ -22,17 +22,17 @@ var dbPromise;
function getDb() { function getDb() {
if (!dbPromise) { if (!dbPromise) {
dbPromise = new Promise(function(resolve, reject) { dbPromise = new Promise(function (resolve, reject) {
var request = indexedDB.open(dbName, dbVersion); var request = indexedDB.open(dbName, dbVersion);
request.onupgradeneeded = function() { request.onupgradeneeded = function () {
var db = request.result; var db = request.result;
db.createObjectStore(dbCacheTable, { keyPath: "address" }); db.createObjectStore(dbCacheTable, { keyPath: "address" });
}; };
request.onsuccess = function() { request.onsuccess = function () {
var db = request.result; var db = request.result;
resolve(db); resolve(db);
}; };
request.onerror = function() { request.onerror = function () {
console.warn("getDb: " + request.error); console.warn("getDb: " + request.error);
reject(request.error); reject(request.error);
}; };
@ -42,7 +42,7 @@ function getDb() {
} }
function storeCache(address, hashCode, translated, format) { function storeCache(address, hashCode, translated, format) {
return getDb().then(function(db) { return getDb().then(function (db) {
var tx = db.transaction(dbCacheTable, "readwrite"); var tx = db.transaction(dbCacheTable, "readwrite");
var store = tx.objectStore(dbCacheTable); var store = tx.objectStore(dbCacheTable);
store.put({ store.put({
@ -52,11 +52,11 @@ function storeCache(address, hashCode, translated, format) {
expires: Date.now() + cacheExpiration, expires: Date.now() + cacheExpiration,
format: format, format: format,
}); });
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
tx.oncomplete = function() { tx.oncomplete = function () {
resolve(); resolve();
}; };
tx.onerror = function() { tx.onerror = function () {
resolve(); resolve();
}; };
}); });
@ -64,12 +64,12 @@ function storeCache(address, hashCode, translated, format) {
} }
function loadCache(address, hashCode) { function loadCache(address, hashCode) {
return getDb().then(function(db) { return getDb().then(function (db) {
var tx = db.transaction(dbCacheTable, "readonly"); var tx = db.transaction(dbCacheTable, "readonly");
var store = tx.objectStore(dbCacheTable); var store = tx.objectStore(dbCacheTable);
var getAddress = store.get(address); var getAddress = store.get(address);
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
tx.oncomplete = function() { tx.oncomplete = function () {
var found = getAddress.result; var found = getAddress.result;
var isValid = var isValid =
found && found.hashCode === hashCode && Date.now() < found.expires; found && found.hashCode === hashCode && Date.now() < found.expires;
@ -82,7 +82,7 @@ function loadCache(address, hashCode) {
: null : null
); );
}; };
tx.onerror = function() { tx.onerror = function () {
resolve(null); resolve(null);
}; };
}); });
@ -92,7 +92,7 @@ function loadCache(address, hashCode) {
var encoder = new TextEncoder("utf-8"); var encoder = new TextEncoder("utf-8");
function sha256(str) { function sha256(str) {
var buffer = encoder.encode(str); var buffer = encoder.encode(str);
return crypto.subtle.digest("SHA-256", buffer).then(function(hash) { return crypto.subtle.digest("SHA-256", buffer).then(function (hash) {
var data = new Int32Array(hash); var data = new Int32Array(hash);
return ( return (
data[0].toString(36) + data[0].toString(36) +
@ -106,38 +106,38 @@ function sha256(str) {
}); });
} }
exports.translate = function(load, opt) { exports.translate = function (load, opt) {
var savedHashCode, babelTranslateError; var savedHashCode, babelTranslateError;
return sha256(load.source) return sha256(load.source)
.then(function(hashCode) { .then(function (hashCode) {
savedHashCode = hashCode; savedHashCode = hashCode;
return loadCache(load.address, hashCode); return loadCache(load.address, hashCode);
}) })
.then( .then(
function(cache) { function (cache) {
if (cache) { if (cache) {
load.metadata.format = cache.format; load.metadata.format = cache.format;
return cache.translated; return cache.translated;
} }
return babel.translate.call(this, load, opt).then( return babel.translate.call(this, load, opt).then(
function(translated) { function (translated) {
return storeCache( return storeCache(
load.address, load.address,
savedHashCode, savedHashCode,
translated, translated,
load.metadata.format load.metadata.format
).then(function() { ).then(function () {
return translated; return translated;
}); });
}, },
function(reason) { function (reason) {
throw (babelTranslateError = reason); throw (babelTranslateError = reason);
} }
); );
}.bind(this) }.bind(this)
) )
.catch( .catch(
function(reason) { function (reason) {
if (babelTranslateError) { if (babelTranslateError) {
throw babelTranslateError; throw babelTranslateError;
} }

View File

@ -19,7 +19,7 @@
var preprocessor2 = require("../builder/preprocessor2.js"); var preprocessor2 = require("../builder/preprocessor2.js");
var path = require("path"); var path = require("path");
module.exports = function(source) { module.exports = function (source) {
// Options must be specified, ignoring request if not. // Options must be specified, ignoring request if not.
if (!this.query || typeof this.query !== "object") { if (!this.query || typeof this.query !== "object") {
return source; return source;
@ -28,10 +28,7 @@ module.exports = function(source) {
var filePath = this.resourcePath; var filePath = this.resourcePath;
var context = this.rootContext; var context = this.rootContext;
var sourcePath = path var sourcePath = path.relative(context, filePath).split(path.sep).join("/");
.relative(context, filePath)
.split(path.sep)
.join("/");
var ctx = Object.create(this.query); var ctx = Object.create(this.query);
ctx.sourceMap = true; ctx.sourceMap = true;

View File

@ -105,7 +105,7 @@ var DEFINES = {
}; };
function transform(charEncoding, transformFunction) { function transform(charEncoding, transformFunction) {
return through.obj(function(vinylFile, enc, done) { return through.obj(function (vinylFile, enc, done) {
var transformedFile = vinylFile.clone(); var transformedFile = vinylFile.clone();
transformedFile.contents = Buffer.from( transformedFile.contents = Buffer.from(
transformFunction(transformedFile.contents), transformFunction(transformedFile.contents),
@ -154,7 +154,7 @@ function startNode(args, options) {
function createStringSource(filename, content) { function createStringSource(filename, content) {
var source = stream.Readable({ objectMode: true }); var source = stream.Readable({ objectMode: true });
source._read = function() { source._read = function () {
this.push( this.push(
new Vinyl({ new Vinyl({
path: filename, path: filename,
@ -253,7 +253,7 @@ function getVersionJSON() {
function checkChromePreferencesFile(chromePrefsPath, webPrefsPath) { function checkChromePreferencesFile(chromePrefsPath, webPrefsPath) {
var chromePrefs = JSON.parse(fs.readFileSync(chromePrefsPath).toString()); var chromePrefs = JSON.parse(fs.readFileSync(chromePrefsPath).toString());
var chromePrefsKeys = Object.keys(chromePrefs.properties); var chromePrefsKeys = Object.keys(chromePrefs.properties);
chromePrefsKeys = chromePrefsKeys.filter(function(key) { chromePrefsKeys = chromePrefsKeys.filter(function (key) {
var description = chromePrefs.properties[key].description; var description = chromePrefs.properties[key].description;
// Deprecated keys are allowed in the managed preferences file. // Deprecated keys are allowed in the managed preferences file.
// The code maintained is responsible for adding migration logic to // The code maintained is responsible for adding migration logic to
@ -274,7 +274,7 @@ function checkChromePreferencesFile(chromePrefsPath, webPrefsPath) {
if (webPrefsKeys.length !== chromePrefsKeys.length) { if (webPrefsKeys.length !== chromePrefsKeys.length) {
return false; return false;
} }
return webPrefsKeys.every(function(value, index) { return webPrefsKeys.every(function (value, index) {
return ( return (
chromePrefsKeys[index] === value && chromePrefsKeys[index] === value &&
chromePrefs.properties[value].default === webPrefs[value] chromePrefs.properties[value].default === webPrefs[value]
@ -402,9 +402,7 @@ function replaceInFile(filePath, find, replacement) {
function getTempFile(prefix, suffix) { function getTempFile(prefix, suffix) {
mkdirp.sync(BUILD_DIR + "tmp/"); mkdirp.sync(BUILD_DIR + "tmp/");
var bytes = require("crypto") var bytes = require("crypto").randomBytes(6).toString("hex");
.randomBytes(6)
.toString("hex");
var filePath = BUILD_DIR + "tmp/" + prefix + bytes + suffix; var filePath = BUILD_DIR + "tmp/" + prefix + bytes + suffix;
fs.writeFileSync(filePath, ""); fs.writeFileSync(filePath, "");
return filePath; return filePath;
@ -412,7 +410,7 @@ function getTempFile(prefix, suffix) {
function createTestSource(testsName, bot) { function createTestSource(testsName, bot) {
var source = stream.Readable({ objectMode: true }); var source = stream.Readable({ objectMode: true });
source._read = function() { source._read = function () {
console.log(); console.log();
console.log("### Running " + testsName + " tests"); console.log("### Running " + testsName + " tests");
@ -456,7 +454,7 @@ function createTestSource(testsName, bot) {
} }
var testProcess = startNode(args, { cwd: TEST_DIR, stdio: "inherit" }); var testProcess = startNode(args, { cwd: TEST_DIR, stdio: "inherit" });
testProcess.on("close", function(code) { testProcess.on("close", function (code) {
source.push(null); source.push(null);
}); });
return undefined; return undefined;
@ -489,26 +487,26 @@ function makeRef(done, bot) {
} }
args.push("--browserManifestFile=" + PDF_BROWSERS); args.push("--browserManifestFile=" + PDF_BROWSERS);
var testProcess = startNode(args, { cwd: TEST_DIR, stdio: "inherit" }); var testProcess = startNode(args, { cwd: TEST_DIR, stdio: "inherit" });
testProcess.on("close", function(code) { testProcess.on("close", function (code) {
done(); done();
}); });
} }
gulp.task("default", function(done) { gulp.task("default", function (done) {
console.log("Available tasks:"); console.log("Available tasks:");
var tasks = Object.keys(gulp.registry().tasks()); var tasks = Object.keys(gulp.registry().tasks());
tasks.sort(); tasks.sort();
tasks.forEach(function(taskName) { tasks.forEach(function (taskName) {
console.log(" " + taskName); console.log(" " + taskName);
}); });
done(); done();
}); });
gulp.task("buildnumber", function(done) { gulp.task("buildnumber", function (done) {
console.log(); console.log();
console.log("### Getting extension build number"); console.log("### Getting extension build number");
exec("git log --format=oneline " + config.baseVersion + "..", function( exec("git log --format=oneline " + config.baseVersion + "..", function (
err, err,
stdout, stdout,
stderr stderr
@ -525,7 +523,7 @@ gulp.task("buildnumber", function(done) {
var version = config.versionPrefix + buildNumber; var version = config.versionPrefix + buildNumber;
exec('git log --format="%h" -n 1', function(err2, stdout2, stderr2) { exec('git log --format="%h" -n 1', function (err2, stdout2, stderr2) {
var buildCommit = ""; var buildCommit = "";
if (!err2) { if (!err2) {
buildCommit = stdout2.replace("\n", ""); buildCommit = stdout2.replace("\n", "");
@ -549,7 +547,7 @@ gulp.task("buildnumber", function(done) {
}); });
}); });
gulp.task("default_preferences-pre", function() { gulp.task("default_preferences-pre", function () {
console.log(); console.log();
console.log("### Building `default_preferences.json`"); console.log("### Building `default_preferences.json`");
@ -610,7 +608,7 @@ gulp.task("default_preferences-pre", function() {
gulp.task( gulp.task(
"default_preferences", "default_preferences",
gulp.series("default_preferences-pre", function(done) { gulp.series("default_preferences-pre", function (done) {
var AppOptionsLib = require("./" + var AppOptionsLib = require("./" +
DEFAULT_PREFERENCES_DIR + DEFAULT_PREFERENCES_DIR +
"lib/web/app_options.js"); "lib/web/app_options.js");
@ -626,7 +624,7 @@ gulp.task(
}) })
); );
gulp.task("locale", function() { gulp.task("locale", function () {
var VIEWER_LOCALE_OUTPUT = "web/locale/"; var VIEWER_LOCALE_OUTPUT = "web/locale/";
console.log(); console.log();
@ -677,7 +675,7 @@ gulp.task("locale", function() {
]); ]);
}); });
gulp.task("cmaps", function(done) { gulp.task("cmaps", function (done) {
var CMAP_INPUT = "external/cmaps"; var CMAP_INPUT = "external/cmaps";
var VIEWER_CMAP_OUTPUT = "external/bcmaps"; var VIEWER_CMAP_OUTPUT = "external/bcmaps";
@ -692,7 +690,7 @@ gulp.task("cmaps", function(done) {
} }
// Remove old bcmap files. // Remove old bcmap files.
fs.readdirSync(VIEWER_CMAP_OUTPUT).forEach(function(file) { fs.readdirSync(VIEWER_CMAP_OUTPUT).forEach(function (file) {
if (/\.bcmap$/i.test(file)) { if (/\.bcmap$/i.test(file)) {
fs.unlinkSync(VIEWER_CMAP_OUTPUT + "/" + file); fs.unlinkSync(VIEWER_CMAP_OUTPUT + "/" + file);
} }
@ -706,7 +704,7 @@ gulp.task("cmaps", function(done) {
gulp.task( gulp.task(
"bundle", "bundle",
gulp.series("buildnumber", function() { gulp.series("buildnumber", function () {
return createBundle(DEFINES).pipe(gulp.dest(BUILD_DIR)); return createBundle(DEFINES).pipe(gulp.dest(BUILD_DIR));
}) })
); );
@ -775,7 +773,7 @@ function buildGeneric(defines, dir) {
// HTML5 browsers, which implement modern ECMAScript features. // HTML5 browsers, which implement modern ECMAScript features.
gulp.task( gulp.task(
"generic", "generic",
gulp.series("buildnumber", "default_preferences", "locale", function() { gulp.series("buildnumber", "default_preferences", "locale", function () {
console.log(); console.log();
console.log("### Creating generic viewer"); console.log("### Creating generic viewer");
var defines = builder.merge(DEFINES, { GENERIC: true }); var defines = builder.merge(DEFINES, { GENERIC: true });
@ -788,7 +786,7 @@ gulp.task(
// older HTML5 browsers. // older HTML5 browsers.
gulp.task( gulp.task(
"generic-es5", "generic-es5",
gulp.series("buildnumber", "default_preferences", "locale", function() { gulp.series("buildnumber", "default_preferences", "locale", function () {
console.log(); console.log();
console.log("### Creating generic (ES5) viewer"); console.log("### Creating generic (ES5) viewer");
var defines = builder.merge(DEFINES, { GENERIC: true, SKIP_BABEL: false }); var defines = builder.merge(DEFINES, { GENERIC: true, SKIP_BABEL: false });
@ -824,7 +822,7 @@ function buildComponents(defines, dir) {
gulp.task( gulp.task(
"components", "components",
gulp.series("buildnumber", function() { gulp.series("buildnumber", function () {
console.log(); console.log();
console.log("### Creating generic components"); console.log("### Creating generic components");
var defines = builder.merge(DEFINES, { COMPONENTS: true, GENERIC: true }); var defines = builder.merge(DEFINES, { COMPONENTS: true, GENERIC: true });
@ -835,7 +833,7 @@ gulp.task(
gulp.task( gulp.task(
"components-es5", "components-es5",
gulp.series("buildnumber", function() { gulp.series("buildnumber", function () {
console.log(); console.log();
console.log("### Creating generic (ES5) components"); console.log("### Creating generic (ES5) components");
var defines = builder.merge(DEFINES, { var defines = builder.merge(DEFINES, {
@ -850,7 +848,7 @@ gulp.task(
gulp.task( gulp.task(
"image_decoders", "image_decoders",
gulp.series("buildnumber", function() { gulp.series("buildnumber", function () {
console.log(); console.log();
console.log("### Creating image decoders"); console.log("### Creating image decoders");
var defines = builder.merge(DEFINES, { var defines = builder.merge(DEFINES, {
@ -866,7 +864,7 @@ gulp.task(
gulp.task( gulp.task(
"minified-pre", "minified-pre",
gulp.series("buildnumber", "default_preferences", "locale", function() { gulp.series("buildnumber", "default_preferences", "locale", function () {
console.log(); console.log();
console.log("### Creating minified viewer"); console.log("### Creating minified viewer");
var defines = builder.merge(DEFINES, { MINIFIED: true, GENERIC: true }); var defines = builder.merge(DEFINES, { MINIFIED: true, GENERIC: true });
@ -916,7 +914,7 @@ gulp.task(
gulp.task( gulp.task(
"minified-post", "minified-post",
gulp.series("minified-pre", function(done) { gulp.series("minified-pre", function (done) {
var pdfFile = fs.readFileSync(MINIFIED_DIR + "/build/pdf.js").toString(); var pdfFile = fs.readFileSync(MINIFIED_DIR + "/build/pdf.js").toString();
var pdfWorkerFile = fs var pdfWorkerFile = fs
.readFileSync(MINIFIED_DIR + "/build/pdf.worker.js") .readFileSync(MINIFIED_DIR + "/build/pdf.worker.js")
@ -1008,7 +1006,7 @@ function preprocessDefaultPreferences(content) {
gulp.task( gulp.task(
"mozcentral-pre", "mozcentral-pre",
gulp.series("buildnumber", "default_preferences", function() { gulp.series("buildnumber", "default_preferences", function () {
console.log(); console.log();
console.log("### Building mozilla-central extension"); console.log("### Building mozilla-central extension");
var defines = builder.merge(DEFINES, { MOZCENTRAL: true }); var defines = builder.merge(DEFINES, { MOZCENTRAL: true });
@ -1075,7 +1073,7 @@ gulp.task("mozcentral", gulp.series("mozcentral-pre"));
gulp.task( gulp.task(
"chromium-pre", "chromium-pre",
gulp.series("buildnumber", "default_preferences", "locale", function() { gulp.series("buildnumber", "default_preferences", "locale", function () {
console.log(); console.log();
console.log("### Building Chromium extension"); console.log("### Building Chromium extension");
var defines = builder.merge(DEFINES, { CHROME: true, SKIP_BABEL: false }); var defines = builder.merge(DEFINES, { CHROME: true, SKIP_BABEL: false });
@ -1138,14 +1136,14 @@ gulp.task(
gulp.task("chromium", gulp.series("chromium-pre")); gulp.task("chromium", gulp.series("chromium-pre"));
gulp.task("jsdoc", function(done) { gulp.task("jsdoc", function (done) {
console.log(); console.log();
console.log("### Generating documentation (JSDoc)"); console.log("### Generating documentation (JSDoc)");
var JSDOC_FILES = ["src/doc_helper.js", "src/display/api.js"]; var JSDOC_FILES = ["src/doc_helper.js", "src/display/api.js"];
rimraf(JSDOC_BUILD_DIR, function() { rimraf(JSDOC_BUILD_DIR, function () {
mkdirp(JSDOC_BUILD_DIR).then(function() { mkdirp(JSDOC_BUILD_DIR).then(function () {
var command = var command =
'"node_modules/.bin/jsdoc" -d ' + '"node_modules/.bin/jsdoc" -d ' +
JSDOC_BUILD_DIR + JSDOC_BUILD_DIR +
@ -1238,7 +1236,7 @@ function buildLib(defines, dir) {
gulp.task( gulp.task(
"lib", "lib",
gulp.series("buildnumber", "default_preferences", function() { gulp.series("buildnumber", "default_preferences", function () {
var defines = builder.merge(DEFINES, { GENERIC: true, LIB: true }); var defines = builder.merge(DEFINES, { GENERIC: true, LIB: true });
return buildLib(defines, "build/lib/"); return buildLib(defines, "build/lib/");
@ -1247,7 +1245,7 @@ gulp.task(
gulp.task( gulp.task(
"lib-es5", "lib-es5",
gulp.series("buildnumber", "default_preferences", function() { gulp.series("buildnumber", "default_preferences", function () {
var defines = builder.merge(DEFINES, { var defines = builder.merge(DEFINES, {
GENERIC: true, GENERIC: true,
LIB: true, LIB: true,
@ -1263,14 +1261,14 @@ function compressPublish(targetName, dir) {
.src(dir + "**") .src(dir + "**")
.pipe(zip(targetName)) .pipe(zip(targetName))
.pipe(gulp.dest(BUILD_DIR)) .pipe(gulp.dest(BUILD_DIR))
.on("end", function() { .on("end", function () {
console.log("Built distribution file: " + targetName); console.log("Built distribution file: " + targetName);
}); });
} }
gulp.task( gulp.task(
"publish", "publish",
gulp.series("generic", "generic-es5", function(done) { gulp.series("generic", "generic-es5", function (done) {
var version = JSON.parse( var version = JSON.parse(
fs.readFileSync(BUILD_DIR + "version.json").toString() fs.readFileSync(BUILD_DIR + "version.json").toString()
).version; ).version;
@ -1288,14 +1286,14 @@ gulp.task(
}) })
); );
gulp.task("testing-pre", function(done) { gulp.task("testing-pre", function (done) {
process.env["TESTING"] = "true"; process.env["TESTING"] = "true";
done(); done();
}); });
gulp.task( gulp.task(
"test", "test",
gulp.series("testing-pre", "generic", "components", function() { gulp.series("testing-pre", "generic", "components", function () {
return streamqueue( return streamqueue(
{ objectMode: true }, { objectMode: true },
createTestSource("unit"), createTestSource("unit"),
@ -1306,7 +1304,7 @@ gulp.task(
gulp.task( gulp.task(
"bottest", "bottest",
gulp.series("testing-pre", "generic", "components", function() { gulp.series("testing-pre", "generic", "components", function () {
return streamqueue( return streamqueue(
{ objectMode: true }, { objectMode: true },
createTestSource("unit", true), createTestSource("unit", true),
@ -1318,40 +1316,40 @@ gulp.task(
gulp.task( gulp.task(
"browsertest", "browsertest",
gulp.series("testing-pre", "generic", "components", function() { gulp.series("testing-pre", "generic", "components", function () {
return createTestSource("browser"); return createTestSource("browser");
}) })
); );
gulp.task( gulp.task(
"unittest", "unittest",
gulp.series("testing-pre", "generic", "components", function() { gulp.series("testing-pre", "generic", "components", function () {
return createTestSource("unit"); return createTestSource("unit");
}) })
); );
gulp.task( gulp.task(
"fonttest", "fonttest",
gulp.series("testing-pre", function() { gulp.series("testing-pre", function () {
return createTestSource("font"); return createTestSource("font");
}) })
); );
gulp.task( gulp.task(
"makeref", "makeref",
gulp.series("testing-pre", "generic", "components", function(done) { gulp.series("testing-pre", "generic", "components", function (done) {
makeRef(done); makeRef(done);
}) })
); );
gulp.task( gulp.task(
"botmakeref", "botmakeref",
gulp.series("testing-pre", "generic", "components", function(done) { gulp.series("testing-pre", "generic", "components", function (done) {
makeRef(done, true); makeRef(done, true);
}) })
); );
gulp.task("baseline", function(done) { gulp.task("baseline", function (done) {
console.log(); console.log();
console.log("### Creating baseline environment"); console.log("### Creating baseline environment");
@ -1368,13 +1366,13 @@ gulp.task("baseline", function(done) {
} }
var workingDirectory = path.resolve(process.cwd(), BASELINE_DIR); var workingDirectory = path.resolve(process.cwd(), BASELINE_DIR);
exec(initializeCommand, { cwd: workingDirectory }, function(error) { exec(initializeCommand, { cwd: workingDirectory }, function (error) {
if (error) { if (error) {
done(new Error("Baseline clone/fetch failed.")); done(new Error("Baseline clone/fetch failed."));
return; return;
} }
exec("git checkout " + baselineCommit, { cwd: workingDirectory }, function( exec("git checkout " + baselineCommit, { cwd: workingDirectory }, function (
error2 error2
) { ) {
if (error2) { if (error2) {
@ -1390,13 +1388,13 @@ gulp.task("baseline", function(done) {
gulp.task( gulp.task(
"unittestcli", "unittestcli",
gulp.series("testing-pre", "lib-es5", function(done) { gulp.series("testing-pre", "lib-es5", function (done) {
var options = [ var options = [
"node_modules/jasmine/bin/jasmine", "node_modules/jasmine/bin/jasmine",
"JASMINE_CONFIG_PATH=test/unit/clitests.json", "JASMINE_CONFIG_PATH=test/unit/clitests.json",
]; ];
var jasmineProcess = startNode(options, { stdio: "inherit" }); var jasmineProcess = startNode(options, { stdio: "inherit" });
jasmineProcess.on("close", function(code) { jasmineProcess.on("close", function (code) {
if (code !== 0) { if (code !== 0) {
done(new Error("Unit tests failed.")); done(new Error("Unit tests failed."));
return; return;
@ -1406,7 +1404,7 @@ gulp.task(
}) })
); );
gulp.task("lint", function(done) { gulp.task("lint", function (done) {
console.log(); console.log();
console.log("### Linting JS files"); console.log("### Linting JS files");
@ -1422,7 +1420,7 @@ gulp.task("lint", function(done) {
options.push("--fix"); options.push("--fix");
} }
var esLintProcess = startNode(options, { stdio: "inherit" }); var esLintProcess = startNode(options, { stdio: "inherit" });
esLintProcess.on("close", function(code) { esLintProcess.on("close", function (code) {
if (code !== 0) { if (code !== 0) {
done(new Error("ESLint failed.")); done(new Error("ESLint failed."));
return; return;
@ -1434,7 +1432,7 @@ gulp.task("lint", function(done) {
gulp.task( gulp.task(
"lint-chromium", "lint-chromium",
gulp.series("default_preferences", function(done) { gulp.series("default_preferences", function (done) {
console.log(); console.log();
console.log("### Checking supplemental Chromium files"); console.log("### Checking supplemental Chromium files");
@ -1451,7 +1449,7 @@ gulp.task(
}) })
); );
gulp.task("server", function() { gulp.task("server", function () {
console.log(); console.log();
console.log("### Starting local server"); console.log("### Starting local server");
@ -1461,14 +1459,14 @@ gulp.task("server", function() {
server.start(); server.start();
}); });
gulp.task("clean", function(done) { gulp.task("clean", function (done) {
console.log(); console.log();
console.log("### Cleaning up project builds"); console.log("### Cleaning up project builds");
rimraf(BUILD_DIR, done); rimraf(BUILD_DIR, done);
}); });
gulp.task("makefile", function() { gulp.task("makefile", function () {
var makefileContent = "help:\n\tgulp\n\n"; var makefileContent = "help:\n\tgulp\n\n";
var targetsNames = []; var targetsNames = [];
for (var i in target) { for (var i in target) {
@ -1479,7 +1477,7 @@ gulp.task("makefile", function() {
return createStringSource("Makefile", makefileContent).pipe(gulp.dest(".")); return createStringSource("Makefile", makefileContent).pipe(gulp.dest("."));
}); });
gulp.task("importl10n", function(done) { gulp.task("importl10n", function (done) {
var locales = require("./external/importL10n/locales.js"); var locales = require("./external/importL10n/locales.js");
console.log(); console.log();
@ -1491,7 +1489,7 @@ gulp.task("importl10n", function(done) {
locales.downloadL10n(L10N_DIR, done); locales.downloadL10n(L10N_DIR, done);
}); });
gulp.task("gh-pages-prepare", function() { gulp.task("gh-pages-prepare", function () {
console.log(); console.log();
console.log("### Creating web site"); console.log("### Creating web site");
@ -1514,10 +1512,10 @@ gulp.task("gh-pages-prepare", function() {
]); ]);
}); });
gulp.task("wintersmith", function(done) { gulp.task("wintersmith", function (done) {
var wintersmith = require("wintersmith"); var wintersmith = require("wintersmith");
var env = wintersmith("docs/config.json"); var env = wintersmith("docs/config.json");
env.build(GH_PAGES_DIR, function(error) { env.build(GH_PAGES_DIR, function (error) {
if (error) { if (error) {
done(error); done(error);
return; return;
@ -1552,7 +1550,7 @@ gulp.task("wintersmith", function(done) {
}); });
}); });
gulp.task("gh-pages-git", function(done) { gulp.task("gh-pages-git", function (done) {
var VERSION = getVersionJSON().version; var VERSION = getVersionJSON().version;
var reason = process.env["PDFJS_UPDATE_REASON"]; var reason = process.env["PDFJS_UPDATE_REASON"];
@ -1601,7 +1599,7 @@ gulp.task(
"image_decoders", "image_decoders",
"lib", "lib",
"minified", "minified",
function() { function () {
var VERSION = getVersionJSON().version; var VERSION = getVersionJSON().version;
console.log(); console.log();
@ -1719,7 +1717,7 @@ gulp.task(
gulp.task( gulp.task(
"dist-install", "dist-install",
gulp.series("dist-pre", function(done) { gulp.series("dist-pre", function (done) {
var distPath = DIST_DIR; var distPath = DIST_DIR;
var opts = {}; var opts = {};
var installPath = process.env["PDFJS_INSTALL_PATH"]; var installPath = process.env["PDFJS_INSTALL_PATH"];
@ -1734,7 +1732,7 @@ gulp.task(
gulp.task( gulp.task(
"dist-repo-git", "dist-repo-git",
gulp.series("dist-pre", function(done) { gulp.series("dist-pre", function (done) {
var VERSION = getVersionJSON().version; var VERSION = getVersionJSON().version;
console.log(); console.log();
@ -1777,7 +1775,7 @@ gulp.task("dist", gulp.series("dist-repo-git"));
gulp.task( gulp.task(
"mozcentralbaseline", "mozcentralbaseline",
gulp.series("baseline", function(done) { gulp.series("baseline", function (done) {
console.log(); console.log();
console.log("### Creating mozcentral baseline environment"); console.log("### Creating mozcentral baseline environment");
@ -1798,7 +1796,7 @@ gulp.task(
gulp gulp
.src([BASELINE_DIR + BUILD_DIR + "mozcentral/**/*"]) .src([BASELINE_DIR + BUILD_DIR + "mozcentral/**/*"])
.pipe(gulp.dest(MOZCENTRAL_BASELINE_DIR)) .pipe(gulp.dest(MOZCENTRAL_BASELINE_DIR))
.on("end", function() { .on("end", function () {
// Commit the mozcentral baseline. // Commit the mozcentral baseline.
safeSpawnSync("git", ["init"], { cwd: MOZCENTRAL_BASELINE_DIR }); safeSpawnSync("git", ["init"], { cwd: MOZCENTRAL_BASELINE_DIR });
safeSpawnSync("git", ["add", "."], { cwd: MOZCENTRAL_BASELINE_DIR }); safeSpawnSync("git", ["add", "."], { cwd: MOZCENTRAL_BASELINE_DIR });
@ -1812,7 +1810,7 @@ gulp.task(
gulp.task( gulp.task(
"mozcentraldiff", "mozcentraldiff",
gulp.series("mozcentral", "mozcentralbaseline", function(done) { gulp.series("mozcentral", "mozcentralbaseline", function (done) {
console.log(); console.log();
console.log("### Creating mozcentral diff"); console.log("### Creating mozcentral diff");
@ -1826,7 +1824,7 @@ gulp.task(
gulp gulp
.src([BUILD_DIR + "mozcentral/**/*"]) .src([BUILD_DIR + "mozcentral/**/*"])
.pipe(gulp.dest(MOZCENTRAL_BASELINE_DIR)) .pipe(gulp.dest(MOZCENTRAL_BASELINE_DIR))
.on("end", function() { .on("end", function () {
safeSpawnSync("git", ["add", "-A"], { cwd: MOZCENTRAL_BASELINE_DIR }); safeSpawnSync("git", ["add", "-A"], { cwd: MOZCENTRAL_BASELINE_DIR });
var diff = safeSpawnSync( var diff = safeSpawnSync(
"git", "git",
@ -1836,7 +1834,7 @@ gulp.task(
createStringSource(MOZCENTRAL_DIFF_FILE, diff) createStringSource(MOZCENTRAL_DIFF_FILE, diff)
.pipe(gulp.dest(BUILD_DIR)) .pipe(gulp.dest(BUILD_DIR))
.on("end", function() { .on("end", function () {
console.log( console.log(
"Result diff can be found at " + BUILD_DIR + MOZCENTRAL_DIFF_FILE "Result diff can be found at " + BUILD_DIR + MOZCENTRAL_DIFF_FILE
); );
@ -1846,7 +1844,7 @@ gulp.task(
}) })
); );
gulp.task("externaltest", function(done) { gulp.task("externaltest", function (done) {
fancylog("Running test-fixtures.js"); fancylog("Running test-fixtures.js");
safeSpawnSync("node", ["external/builder/test-fixtures.js"], { safeSpawnSync("node", ["external/builder/test-fixtures.js"], {
stdio: "inherit", stdio: "inherit",

6
package-lock.json generated
View File

@ -11310,9 +11310,9 @@
"dev": true "dev": true
}, },
"prettier": { "prettier": {
"version": "1.19.1", "version": "2.0.4",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz", "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.4.tgz",
"integrity": "sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==", "integrity": "sha512-SVJIQ51spzFDvh4fIbCLvciiDMCrRhlN3mbZvv/+ycjvmF5E73bKdGfU8QDLNmjYJf+lsGnDBC4UUnvTe5OO0w==",
"dev": true "dev": true
}, },
"prettier-linter-helpers": { "prettier-linter-helpers": {

View File

@ -37,7 +37,7 @@
"mkdirp": "^1.0.3", "mkdirp": "^1.0.3",
"postcss-calc": "^7.0.2", "postcss-calc": "^7.0.2",
"postcss-css-variables": "^0.14.0", "postcss-css-variables": "^0.14.0",
"prettier": "^1.19.1", "prettier": "^2.0.4",
"rimraf": "^2.7.1", "rimraf": "^2.7.1",
"streamqueue": "^1.1.2", "streamqueue": "^1.1.2",
"systemjs": "^0.21.6", "systemjs": "^0.21.6",

View File

@ -503,7 +503,7 @@ class Annotation {
} }
const objectLoader = new ObjectLoader(resources, keys, resources.xref); const objectLoader = new ObjectLoader(resources, keys, resources.xref);
return objectLoader.load().then(function() { return objectLoader.load().then(function () {
return resources; return resources;
}); });
}); });
@ -941,7 +941,7 @@ class TextWidgetAnnotation extends WidgetAnnotation {
resources: this.fieldResources, resources: this.fieldResources,
operatorList, operatorList,
}) })
.then(function() { .then(function () {
return operatorList; return operatorList;
}); });
} }

View File

@ -47,7 +47,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
CCITTFaxStream.prototype = Object.create(DecodeStream.prototype); CCITTFaxStream.prototype = Object.create(DecodeStream.prototype);
CCITTFaxStream.prototype.readBlock = function() { CCITTFaxStream.prototype.readBlock = function () {
while (!this.eof) { while (!this.eof) {
const c = this.ccittFaxDecoder.readNextChar(); const c = this.ccittFaxDecoder.readNextChar();
if (c === -1) { if (c === -1) {

View File

@ -280,7 +280,7 @@ class ChunkedStream {
function ChunkedStreamSubstream() {} function ChunkedStreamSubstream() {}
ChunkedStreamSubstream.prototype = Object.create(this); ChunkedStreamSubstream.prototype = Object.create(this);
ChunkedStreamSubstream.prototype.getMissingChunks = function() { ChunkedStreamSubstream.prototype.getMissingChunks = function () {
const chunkSize = this.chunkSize; const chunkSize = this.chunkSize;
const beginChunk = Math.floor(this.start / chunkSize); const beginChunk = Math.floor(this.start / chunkSize);
const endChunk = Math.floor((this.end - 1) / chunkSize) + 1; const endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
@ -292,7 +292,7 @@ class ChunkedStream {
} }
return missingChunks; return missingChunks;
}; };
ChunkedStreamSubstream.prototype.allChunksLoaded = function() { ChunkedStreamSubstream.prototype.allChunksLoaded = function () {
if (this.numChunksLoaded === this.numChunks) { if (this.numChunksLoaded === this.numChunks) {
return true; return true;
} }
@ -454,7 +454,7 @@ class ChunkedStreamManager {
} }
} }
chunksToRequest.sort(function(a, b) { chunksToRequest.sort(function (a, b) {
return a - b; return a - b;
}); });
return this._requestChunks(chunksToRequest); return this._requestChunks(chunksToRequest);

View File

@ -530,7 +530,7 @@ var BinaryCMapReader = (function BinaryCMapReaderClosure() {
}; };
function processBinaryCMap(data, cMap, extend) { function processBinaryCMap(data, cMap, extend) {
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
var stream = new BinaryCMapStream(data); var stream = new BinaryCMapStream(data);
var header = stream.readByte(); var header = stream.readByte();
cMap.vertical = !!(header & 1); cMap.vertical = !!(header & 1);
@ -934,7 +934,9 @@ var CMapFactory = (function CMapFactoryClosure() {
} }
function extendCMap(cMap, fetchBuiltInCMap, useCMap) { function extendCMap(cMap, fetchBuiltInCMap, useCMap) {
return createBuiltInCMap(useCMap, fetchBuiltInCMap).then(function(newCMap) { return createBuiltInCMap(useCMap, fetchBuiltInCMap).then(function (
newCMap
) {
cMap.useCMap = newCMap; cMap.useCMap = newCMap;
// If there aren't any code space ranges defined clone all the parent ones // If there aren't any code space ranges defined clone all the parent ones
// into this cMap. // into this cMap.
@ -947,7 +949,7 @@ var CMapFactory = (function CMapFactoryClosure() {
} }
// Merge the map into the current one, making sure not to override // Merge the map into the current one, making sure not to override
// any previously defined entries. // any previously defined entries.
cMap.useCMap.forEach(function(key, value) { cMap.useCMap.forEach(function (key, value) {
if (!cMap.contains(key)) { if (!cMap.contains(key)) {
cMap.mapOne(key, cMap.useCMap.lookup(key)); cMap.mapOne(key, cMap.useCMap.lookup(key));
} }
@ -972,13 +974,13 @@ var CMapFactory = (function CMapFactoryClosure() {
); );
} }
return fetchBuiltInCMap(name).then(function(data) { return fetchBuiltInCMap(name).then(function (data) {
var cMapData = data.cMapData, var cMapData = data.cMapData,
compressionType = data.compressionType; compressionType = data.compressionType;
var cMap = new CMap(true); var cMap = new CMap(true);
if (compressionType === CMapCompressionType.BINARY) { if (compressionType === CMapCompressionType.BINARY) {
return new BinaryCMapReader().process(cMapData, cMap, function( return new BinaryCMapReader().process(cMapData, cMap, function (
useCMap useCMap
) { ) {
return extendCMap(cMap, fetchBuiltInCMap, useCMap); return extendCMap(cMap, fetchBuiltInCMap, useCMap);
@ -1007,7 +1009,7 @@ var CMapFactory = (function CMapFactoryClosure() {
} else if (isStream(encoding)) { } else if (isStream(encoding)) {
var cMap = new CMap(); var cMap = new CMap();
var lexer = new Lexer(encoding); var lexer = new Lexer(encoding);
return parseCMap(cMap, lexer, fetchBuiltInCMap, useCMap).then(function( return parseCMap(cMap, lexer, fetchBuiltInCMap, useCMap).then(function (
parsedCMap parsedCMap
) { ) {
if (parsedCMap.isIdentityCMap) { if (parsedCMap.isIdentityCMap) {

View File

@ -18,7 +18,7 @@ import { assert, BaseException, warn } from "../shared/util.js";
function getLookupTableFactory(initializer) { function getLookupTableFactory(initializer) {
let lookup; let lookup;
return function() { return function () {
if (initializer) { if (initializer) {
lookup = Object.create(null); lookup = Object.create(null);
initializer(lookup); initializer(lookup);

View File

@ -282,7 +282,7 @@ class Page {
resources: this.resources, resources: this.resources,
operatorList: opList, operatorList: opList,
}) })
.then(function() { .then(function () {
return opList; return opList;
}); });
}); });
@ -290,7 +290,7 @@ class Page {
// Fetch the page's annotations and add their operator lists to the // Fetch the page's annotations and add their operator lists to the
// page's operator list to render them. // page's operator list to render them.
return Promise.all([pageListPromise, this._parsedAnnotations]).then( return Promise.all([pageListPromise, this._parsedAnnotations]).then(
function([pageOpList, annotations]) { function ([pageOpList, annotations]) {
if (annotations.length === 0) { if (annotations.length === 0) {
pageOpList.flush(true); pageOpList.flush(true);
return { length: pageOpList.totalLength }; return { length: pageOpList.totalLength };
@ -311,7 +311,7 @@ class Page {
} }
} }
return Promise.all(opListPromises).then(function(opLists) { return Promise.all(opListPromises).then(function (opLists) {
pageOpList.addOp(OPS.beginAnnotations, []); pageOpList.addOp(OPS.beginAnnotations, []);
for (const opList of opLists) { for (const opList of opLists) {
pageOpList.addOpList(opList); pageOpList.addOpList(opList);
@ -366,7 +366,7 @@ class Page {
} }
getAnnotationsData(intent) { getAnnotationsData(intent) {
return this._parsedAnnotations.then(function(annotations) { return this._parsedAnnotations.then(function (annotations) {
const annotationsData = []; const annotationsData = [];
for (let i = 0, ii = annotations.length; i < ii; i++) { for (let i = 0, ii = annotations.length; i < ii; i++) {
if (!intent || isAnnotationRenderable(annotations[i], intent)) { if (!intent || isAnnotationRenderable(annotations[i], intent)) {
@ -403,12 +403,12 @@ class Page {
} }
return Promise.all(annotationPromises).then( return Promise.all(annotationPromises).then(
function(annotations) { function (annotations) {
return annotations.filter(function isDefined(annotation) { return annotations.filter(function isDefined(annotation) {
return !!annotation; return !!annotation;
}); });
}, },
function(reason) { function (reason) {
warn(`_parsedAnnotations: "${reason}".`); warn(`_parsedAnnotations: "${reason}".`);
return []; return [];
} }

View File

@ -127,9 +127,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
}); });
const reader = readableStream.getReader(); const reader = readableStream.getReader();
const data = await new Promise(function(resolve, reject) { const data = await new Promise(function (resolve, reject) {
function pump() { function pump() {
reader.read().then(function({ value, done }) { reader.read().then(function ({ value, done }) {
if (done) { if (done) {
return; return;
} }
@ -432,7 +432,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
resources: dict.get("Resources") || resources, resources: dict.get("Resources") || resources,
operatorList, operatorList,
initialState, initialState,
}).then(function() { }).then(function () {
operatorList.addOp(OPS.paintFormXObjectEnd, []); operatorList.addOp(OPS.paintFormXObjectEnd, []);
if (group) { if (group) {
@ -566,7 +566,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
image.getIR(this.options.forceDataSchema), image.getIR(this.options.forceDataSchema),
]) ])
.then( .then(
function() { function () {
// Only add the dependency once we know that the native JPEG // Only add the dependency once we know that the native JPEG
// decoding succeeded, to ensure that rendering will always // decoding succeeded, to ensure that rendering will always
// complete. // complete.
@ -738,7 +738,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
resources: patternResources, resources: patternResources,
operatorList: tilingOpList, operatorList: tilingOpList,
}) })
.then(function() { .then(function () {
return getTilingPatternIR( return getTilingPatternIR(
{ {
fnArray: tilingOpList.fnArray, fnArray: tilingOpList.fnArray,
@ -749,7 +749,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
); );
}) })
.then( .then(
function(tilingPatternIR) { function (tilingPatternIR) {
// Add the dependencies to the parent operator list so they are // Add the dependencies to the parent operator list so they are
// resolved before the sub operator list is executed synchronously. // resolved before the sub operator list is executed synchronously.
operatorList.addDependencies(tilingOpList.dependencies); operatorList.addDependencies(tilingOpList.dependencies);
@ -795,7 +795,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
} }
return translated return translated
.loadType3Data(this, resources, operatorList, task) .loadType3Data(this, resources, operatorList, task)
.then(function() { .then(function () {
return translated; return translated;
}) })
.catch(reason => { .catch(reason => {
@ -896,7 +896,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
operatorList, operatorList,
task, task,
stateManager.state stateManager.state
).then(function(loadedName) { ).then(function (loadedName) {
operatorList.addDependency(loadedName); operatorList.addDependency(loadedName);
gStateObj.push([key, [loadedName, value[1]]]); gStateObj.push([key, [loadedName, value[1]]]);
}); });
@ -950,7 +950,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
break; break;
} }
} }
return promise.then(function() { return promise.then(function () {
if (gStateObj.length > 0) { if (gStateObj.length > 0) {
operatorList.addOp(OPS.setGState, [gStateObj]); operatorList.addOp(OPS.setGState, [gStateObj]);
} }
@ -985,8 +985,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
} }
} }
if (!fontRef) { if (!fontRef) {
const partialMsg = `Font "${fontName || const partialMsg = `Font "${
(font && font.toString())}" is not available`; fontName || (font && font.toString())
}" is not available`;
if (!this.options.ignoreErrors && !this.parsingType3Font) { if (!this.options.ignoreErrors && !this.parsingType3Font) {
warn(`${partialMsg}.`); warn(`${partialMsg}.`);
@ -1275,8 +1276,8 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
} }
return new Promise(function promiseBody(resolve, reject) { return new Promise(function promiseBody(resolve, reject) {
const next = function(promise) { const next = function (promise) {
Promise.all([promise, operatorList.ready]).then(function() { Promise.all([promise, operatorList.ready]).then(function () {
try { try {
promiseBody(resolve, reject); promiseBody(resolve, reject);
} catch (ex) { } catch (ex) {
@ -1314,7 +1315,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
} }
next( next(
new Promise(function(resolveXObject, rejectXObject) { new Promise(function (resolveXObject, rejectXObject) {
if (!name) { if (!name) {
throw new FormatError( throw new FormatError(
"XObject must be referred to by name." "XObject must be referred to by name."
@ -1347,7 +1348,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
task, task,
stateManager.state.clone() stateManager.state.clone()
) )
.then(function() { .then(function () {
stateManager.restore(); stateManager.restore();
resolveXObject(); resolveXObject();
}, rejectXObject); }, rejectXObject);
@ -1373,7 +1374,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
); );
} }
resolveXObject(); resolveXObject();
}).catch(function(reason) { }).catch(function (reason) {
if (reason instanceof AbortException) { if (reason instanceof AbortException) {
return; return;
} }
@ -1403,7 +1404,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
task, task,
stateManager.state stateManager.state
) )
.then(function(loadedName) { .then(function (loadedName) {
operatorList.addDependency(loadedName); operatorList.addDependency(loadedName);
operatorList.addOp(OPS.setFont, [loadedName, fontSize]); operatorList.addOp(OPS.setFont, [loadedName, fontSize]);
}) })
@ -1497,7 +1498,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
cs: args[0], cs: args[0],
resources, resources,
}) })
.then(function(colorSpace) { .then(function (colorSpace) {
if (colorSpace) { if (colorSpace) {
stateManager.state.fillColorSpace = colorSpace; stateManager.state.fillColorSpace = colorSpace;
} }
@ -1511,7 +1512,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
cs: args[0], cs: args[0],
resources, resources,
}) })
.then(function(colorSpace) { .then(function (colorSpace) {
if (colorSpace) { if (colorSpace) {
stateManager.state.strokeColorSpace = colorSpace; stateManager.state.strokeColorSpace = colorSpace;
} }
@ -1875,7 +1876,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
function handleSetFont(fontName, fontRef) { function handleSetFont(fontName, fontRef) {
return self return self
.loadFont(fontName, fontRef, resources) .loadFont(fontName, fontRef, resources)
.then(function(translated) { .then(function (translated) {
textState.font = translated.font; textState.font = translated.font;
textState.fontMatrix = textState.fontMatrix =
translated.font.fontMatrix || FONT_IDENTITY_MATRIX; translated.font.fontMatrix || FONT_IDENTITY_MATRIX;
@ -1983,9 +1984,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
var timeSlotManager = new TimeSlotManager(); var timeSlotManager = new TimeSlotManager();
return new Promise(function promiseBody(resolve, reject) { return new Promise(function promiseBody(resolve, reject) {
const next = function(promise) { const next = function (promise) {
enqueueChunk(); enqueueChunk();
Promise.all([promise, sink.ready]).then(function() { Promise.all([promise, sink.ready]).then(function () {
try { try {
promiseBody(resolve, reject); promiseBody(resolve, reject);
} catch (ex) { } catch (ex) {
@ -2236,7 +2237,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
} }
next( next(
new Promise(function(resolveXObject, rejectXObject) { new Promise(function (resolveXObject, rejectXObject) {
if (!name) { if (!name) {
throw new FormatError( throw new FormatError(
"XObject must be referred to by name." "XObject must be referred to by name."
@ -2307,13 +2308,13 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
sink: sinkWrapper, sink: sinkWrapper,
seenStyles, seenStyles,
}) })
.then(function() { .then(function () {
if (!sinkWrapper.enqueueInvoked) { if (!sinkWrapper.enqueueInvoked) {
skipEmptyXObjs[name] = true; skipEmptyXObjs[name] = true;
} }
resolveXObject(); resolveXObject();
}, rejectXObject); }, rejectXObject);
}).catch(function(reason) { }).catch(function (reason) {
if (reason instanceof AbortException) { if (reason instanceof AbortException) {
return; return;
} }
@ -2673,10 +2674,10 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
encoding: ucs2CMapName, encoding: ucs2CMapName,
fetchBuiltInCMap: this.fetchBuiltInCMap, fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null, useCMap: null,
}).then(function(ucs2CMap) { }).then(function (ucs2CMap) {
const cMap = properties.cMap; const cMap = properties.cMap;
const toUnicode = []; const toUnicode = [];
cMap.forEach(function(charcode, cid) { cMap.forEach(function (charcode, cid) {
if (cid > 0xffff) { if (cid > 0xffff) {
throw new FormatError("Max size of CID is 65,535"); throw new FormatError("Max size of CID is 65,535");
} }
@ -2706,7 +2707,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
encoding: cmapObj, encoding: cmapObj,
fetchBuiltInCMap: this.fetchBuiltInCMap, fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null, useCMap: null,
}).then(function(cmap) { }).then(function (cmap) {
if (cmap instanceof IdentityCMap) { if (cmap instanceof IdentityCMap) {
return new IdentityToUnicodeMap(0, 0xffff); return new IdentityToUnicodeMap(0, 0xffff);
} }
@ -2718,7 +2719,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
fetchBuiltInCMap: this.fetchBuiltInCMap, fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null, useCMap: null,
}).then( }).then(
function(cmap) { function (cmap) {
if (cmap instanceof IdentityCMap) { if (cmap instanceof IdentityCMap) {
return new IdentityToUnicodeMap(0, 0xffff); return new IdentityToUnicodeMap(0, 0xffff);
} }
@ -2726,7 +2727,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
// Convert UTF-16BE // Convert UTF-16BE
// NOTE: cmap can be a sparse array, so use forEach instead of // NOTE: cmap can be a sparse array, so use forEach instead of
// `for(;;)` to iterate over all keys. // `for(;;)` to iterate over all keys.
cmap.forEach(function(charCode, token) { cmap.forEach(function (charCode, token) {
var str = []; var str = [];
for (var k = 0; k < token.length; k += 2) { for (var k = 0; k < token.length; k += 2) {
var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1); var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
@ -3212,7 +3213,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
encoding: cidEncoding, encoding: cidEncoding,
fetchBuiltInCMap: this.fetchBuiltInCMap, fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null, useCMap: null,
}).then(function(cMap) { }).then(function (cMap) {
properties.cMap = cMap; properties.cMap = cMap;
properties.vertical = properties.cMap.vertical; properties.vertical = properties.cMap.vertical;
}); });
@ -3235,7 +3236,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
}, },
}; };
PartialEvaluator.buildFontPaths = function(font, glyphs, handler) { PartialEvaluator.buildFontPaths = function (font, glyphs, handler) {
function buildPath(fontChar) { function buildPath(fontChar) {
if (font.renderer.hasBuiltPath(fontChar)) { if (font.renderer.hasBuiltPath(fontChar)) {
return; return;
@ -3261,7 +3262,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
// TODO: Change this to a `static` getter, using shadowing, once // TODO: Change this to a `static` getter, using shadowing, once
// `PartialEvaluator` is converted to a proper class. // `PartialEvaluator` is converted to a proper class.
PartialEvaluator.getFallbackFontDict = function() { PartialEvaluator.getFallbackFontDict = function () {
if (this._fallbackFontDict) { if (this._fallbackFontDict) {
return this._fallbackFontDict; return this._fallbackFontDict;
} }
@ -3346,7 +3347,7 @@ class TranslatedFont {
for (var i = 0, n = charProcKeys.length; i < n; ++i) { for (var i = 0, n = charProcKeys.length; i < n; ++i) {
const key = charProcKeys[i]; const key = charProcKeys[i];
loadCharProcsPromise = loadCharProcsPromise.then(function() { loadCharProcsPromise = loadCharProcsPromise.then(function () {
var glyphStream = charProcs.get(key); var glyphStream = charProcs.get(key);
var operatorList = new OperatorList(); var operatorList = new OperatorList();
return type3Evaluator return type3Evaluator
@ -3356,21 +3357,21 @@ class TranslatedFont {
resources: fontResources, resources: fontResources,
operatorList, operatorList,
}) })
.then(function() { .then(function () {
charProcOperatorList[key] = operatorList.getIR(); charProcOperatorList[key] = operatorList.getIR();
// Add the dependencies to the parent operator list so they are // Add the dependencies to the parent operator list so they are
// resolved before sub operator list is executed synchronously. // resolved before sub operator list is executed synchronously.
parentOperatorList.addDependencies(operatorList.dependencies); parentOperatorList.addDependencies(operatorList.dependencies);
}) })
.catch(function(reason) { .catch(function (reason) {
warn(`Type3 font resource "${key}" is not available.`); warn(`Type3 font resource "${key}" is not available.`);
const dummyOperatorList = new OperatorList(); const dummyOperatorList = new OperatorList();
charProcOperatorList[key] = dummyOperatorList.getIR(); charProcOperatorList[key] = dummyOperatorList.getIR();
}); });
}); });
} }
this.type3Loaded = loadCharProcsPromise.then(function() { this.type3Loaded = loadCharProcsPromise.then(function () {
translatedFont.charProcOperatorList = charProcOperatorList; translatedFont.charProcOperatorList = charProcOperatorList;
}); });
return this.type3Loaded; return this.type3Loaded;
@ -3530,7 +3531,7 @@ var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
// //
// If variableArgs === true: [0, `numArgs`] expected // If variableArgs === true: [0, `numArgs`] expected
// If variableArgs === false: exactly `numArgs` expected // If variableArgs === false: exactly `numArgs` expected
var getOPMap = getLookupTableFactory(function(t) { var getOPMap = getLookupTableFactory(function (t) {
// Graphic state // Graphic state
t["w"] = { id: OPS.setLineWidth, numArgs: 1, variableArgs: false }; t["w"] = { id: OPS.setLineWidth, numArgs: 1, variableArgs: false };
t["J"] = { id: OPS.setLineCap, numArgs: 1, variableArgs: false }; t["J"] = { id: OPS.setLineCap, numArgs: 1, variableArgs: false };

View File

@ -283,7 +283,7 @@ var Glyph = (function GlyphClosure() {
this.isInFont = isInFont; this.isInFont = isInFont;
} }
Glyph.prototype.matchesForCache = function( Glyph.prototype.matchesForCache = function (
fontChar, fontChar,
unicode, unicode,
accent, accent,
@ -694,7 +694,7 @@ var Font = (function FontClosure() {
this.seacMap = properties.seacMap; this.seacMap = properties.seacMap;
} }
Font.getFontID = (function() { Font.getFontID = (function () {
var ID = 1; var ID = 1;
return function Font_getFontID() { return function Font_getFontID() {
return String(ID++); return String(ID++);
@ -1367,7 +1367,7 @@ var Font = (function FontClosure() {
var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap; var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
if (!isIdentityUnicode) { if (!isIdentityUnicode) {
this.toUnicode.forEach(function(charCode, unicodeCharCode) { this.toUnicode.forEach(function (charCode, unicodeCharCode) {
map[+charCode] = unicodeCharCode; map[+charCode] = unicodeCharCode;
}); });
} }
@ -1775,7 +1775,7 @@ var Font = (function FontClosure() {
} }
// removing duplicate entries // removing duplicate entries
mappings.sort(function(a, b) { mappings.sort(function (a, b) {
return a.charCode - b.charCode; return a.charCode - b.charCode;
}); });
for (i = 1; i < mappings.length; i++) { for (i = 1; i < mappings.length; i++) {
@ -2764,7 +2764,7 @@ var Font = (function FontClosure() {
var cidToGidMap = properties.cidToGidMap || []; var cidToGidMap = properties.cidToGidMap || [];
var isCidToGidMapEmpty = cidToGidMap.length === 0; var isCidToGidMapEmpty = cidToGidMap.length === 0;
properties.cMap.forEach(function(charCode, cid) { properties.cMap.forEach(function (charCode, cid) {
if (cid > 0xffff) { if (cid > 0xffff) {
throw new FormatError("Max size of CID is 65,535"); throw new FormatError("Max size of CID is 65,535");
} }

View File

@ -159,7 +159,7 @@ var PDFFunction = (function PDFFunctionClosure() {
this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fnObj[j]) }) this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fnObj[j]) })
); );
} }
return function(src, srcOffset, dest, destOffset) { return function (src, srcOffset, dest, destOffset) {
for (var i = 0, ii = fnArray.length; i < ii; i++) { for (var i = 0, ii = fnArray.length; i < ii; i++) {
fnArray[i](src, srcOffset, dest, destOffset + i); fnArray[i](src, srcOffset, dest, destOffset + i);
} }
@ -873,7 +873,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
function AstNode(type) { function AstNode(type) {
this.type = type; this.type = type;
} }
AstNode.prototype.visit = function(visitor) { AstNode.prototype.visit = function (visitor) {
unreachable("abstract method"); unreachable("abstract method");
}; };
@ -884,7 +884,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.max = max; this.max = max;
} }
AstArgument.prototype = Object.create(AstNode.prototype); AstArgument.prototype = Object.create(AstNode.prototype);
AstArgument.prototype.visit = function(visitor) { AstArgument.prototype.visit = function (visitor) {
visitor.visitArgument(this); visitor.visitArgument(this);
}; };
@ -895,7 +895,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.max = number; this.max = number;
} }
AstLiteral.prototype = Object.create(AstNode.prototype); AstLiteral.prototype = Object.create(AstNode.prototype);
AstLiteral.prototype.visit = function(visitor) { AstLiteral.prototype.visit = function (visitor) {
visitor.visitLiteral(this); visitor.visitLiteral(this);
}; };
@ -908,7 +908,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.max = max; this.max = max;
} }
AstBinaryOperation.prototype = Object.create(AstNode.prototype); AstBinaryOperation.prototype = Object.create(AstNode.prototype);
AstBinaryOperation.prototype.visit = function(visitor) { AstBinaryOperation.prototype.visit = function (visitor) {
visitor.visitBinaryOperation(this); visitor.visitBinaryOperation(this);
}; };
@ -919,7 +919,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.max = max; this.max = max;
} }
AstMin.prototype = Object.create(AstNode.prototype); AstMin.prototype = Object.create(AstNode.prototype);
AstMin.prototype.visit = function(visitor) { AstMin.prototype.visit = function (visitor) {
visitor.visitMin(this); visitor.visitMin(this);
}; };
@ -930,7 +930,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.max = max; this.max = max;
} }
AstVariable.prototype = Object.create(AstNode.prototype); AstVariable.prototype = Object.create(AstNode.prototype);
AstVariable.prototype.visit = function(visitor) { AstVariable.prototype.visit = function (visitor) {
visitor.visitVariable(this); visitor.visitVariable(this);
}; };
@ -940,7 +940,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.arg = arg; this.arg = arg;
} }
AstVariableDefinition.prototype = Object.create(AstNode.prototype); AstVariableDefinition.prototype = Object.create(AstNode.prototype);
AstVariableDefinition.prototype.visit = function(visitor) { AstVariableDefinition.prototype.visit = function (visitor) {
visitor.visitVariableDefinition(this); visitor.visitVariableDefinition(this);
}; };
@ -1245,12 +1245,12 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
} }
var result = []; var result = [];
instructions.forEach(function(instruction) { instructions.forEach(function (instruction) {
var statementBuilder = new ExpressionBuilderVisitor(); var statementBuilder = new ExpressionBuilderVisitor();
instruction.visit(statementBuilder); instruction.visit(statementBuilder);
result.push(statementBuilder.toString()); result.push(statementBuilder.toString());
}); });
stack.forEach(function(expr, i) { stack.forEach(function (expr, i) {
var statementBuilder = new ExpressionBuilderVisitor(); var statementBuilder = new ExpressionBuilderVisitor();
expr.visit(statementBuilder); expr.visit(statementBuilder);
var min = range[i * 2], var min = range[i * 2],

View File

@ -16,7 +16,7 @@
var getLookupTableFactory = require("./core_utils.js").getLookupTableFactory; var getLookupTableFactory = require("./core_utils.js").getLookupTableFactory;
var getGlyphsUnicode = getLookupTableFactory(function(t) { var getGlyphsUnicode = getLookupTableFactory(function (t) {
t["A"] = 0x0041; t["A"] = 0x0041;
t["AE"] = 0x00c6; t["AE"] = 0x00c6;
t["AEacute"] = 0x01fc; t["AEacute"] = 0x01fc;
@ -4343,7 +4343,7 @@ var getGlyphsUnicode = getLookupTableFactory(function(t) {
t["vextendsingle"] = 0x2223; t["vextendsingle"] = 0x2223;
}); });
var getDingbatsGlyphsUnicode = getLookupTableFactory(function(t) { var getDingbatsGlyphsUnicode = getLookupTableFactory(function (t) {
t["space"] = 0x0020; t["space"] = 0x0020;
t["a1"] = 0x2701; t["a1"] = 0x2701;
t["a2"] = 0x2702; t["a2"] = 0x2702;

View File

@ -265,7 +265,7 @@ var PDFImage = (function PDFImageClosure() {
* Handles processing of image data and returns the Promise that is resolved * Handles processing of image data and returns the Promise that is resolved
* with a PDFImage when the image is ready to be used. * with a PDFImage when the image is ready to be used.
*/ */
PDFImage.buildImage = function({ PDFImage.buildImage = function ({
handler, handler,
xref, xref,
res, res,
@ -300,7 +300,7 @@ var PDFImage = (function PDFImageClosure() {
} }
} }
return Promise.all([imagePromise, smaskPromise, maskPromise]).then( return Promise.all([imagePromise, smaskPromise, maskPromise]).then(
function([imageData, smaskData, maskData]) { function ([imageData, smaskData, maskData]) {
return new PDFImage({ return new PDFImage({
xref, xref,
res, res,
@ -314,7 +314,7 @@ var PDFImage = (function PDFImageClosure() {
); );
}; };
PDFImage.createMask = function({ PDFImage.createMask = function ({
imgArray, imgArray,
width, width,
height, height,

View File

@ -62,7 +62,7 @@ class NativeImageDecoder {
image.getIR(this.forceDataSchema), image.getIR(this.forceDataSchema),
colorSpace.numComps, colorSpace.numComps,
]) ])
.then(function({ data, width, height }) { .then(function ({ data, width, height }) {
return new Stream(data, 0, data.length, dict); return new Stream(data, 0, data.length, dict);
}); });
} }

View File

@ -371,7 +371,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {
// Sorting is non-standard, and it is not required. But sorting increases // Sorting is non-standard, and it is not required. But sorting increases
// the number of template bits that can be reused from the previous // the number of template bits that can be reused from the previous
// contextLabel in the main loop. // contextLabel in the main loop.
template.sort(function(a, b) { template.sort(function (a, b) {
return a.y - b.y || a.x - b.x; return a.y - b.y || a.x - b.x;
}); });

View File

@ -43,12 +43,12 @@ const Jbig2Stream = (function Jbig2StreamClosure() {
configurable: true, configurable: true,
}); });
Jbig2Stream.prototype.ensureBuffer = function(requested) { Jbig2Stream.prototype.ensureBuffer = function (requested) {
// No-op, since `this.readBlock` will always parse the entire image and // No-op, since `this.readBlock` will always parse the entire image and
// directly insert all of its data into `this.buffer`. // directly insert all of its data into `this.buffer`.
}; };
Jbig2Stream.prototype.readBlock = function() { Jbig2Stream.prototype.readBlock = function () {
if (this.eof) { if (this.eof) {
return; return;
} }

View File

@ -56,12 +56,12 @@ const JpegStream = (function JpegStreamClosure() {
configurable: true, configurable: true,
}); });
JpegStream.prototype.ensureBuffer = function(requested) { JpegStream.prototype.ensureBuffer = function (requested) {
// No-op, since `this.readBlock` will always parse the entire image and // No-op, since `this.readBlock` will always parse the entire image and
// directly insert all of its data into `this.buffer`. // directly insert all of its data into `this.buffer`.
}; };
JpegStream.prototype.readBlock = function() { JpegStream.prototype.readBlock = function () {
if (this.eof) { if (this.eof) {
return; return;
} }
@ -250,7 +250,7 @@ const JpegStream = (function JpegStreamClosure() {
configurable: true, configurable: true,
}); });
JpegStream.prototype.getIR = function(forceDataSchema = false) { JpegStream.prototype.getIR = function (forceDataSchema = false) {
return createObjectURL(this.bytes, "image/jpeg", forceDataSchema); return createObjectURL(this.bytes, "image/jpeg", forceDataSchema);
}; };

View File

@ -42,12 +42,12 @@ const JpxStream = (function JpxStreamClosure() {
configurable: true, configurable: true,
}); });
JpxStream.prototype.ensureBuffer = function(requested) { JpxStream.prototype.ensureBuffer = function (requested) {
// No-op, since `this.readBlock` will always parse the entire image and // No-op, since `this.readBlock` will always parse the entire image and
// directly insert all of its data into `this.buffer`. // directly insert all of its data into `this.buffer`.
}; };
JpxStream.prototype.readBlock = function() { JpxStream.prototype.readBlock = function () {
if (this.eof) { if (this.eof) {
return; return;
} }

View File

@ -18,13 +18,13 @@ import { getLookupTableFactory } from "./core_utils.js";
// The Metrics object contains glyph widths (in glyph space units). // The Metrics object contains glyph widths (in glyph space units).
// As per PDF spec, for most fonts (Type 3 being an exception) a glyph // As per PDF spec, for most fonts (Type 3 being an exception) a glyph
// space unit corresponds to 1/1000th of text space unit. // space unit corresponds to 1/1000th of text space unit.
var getMetrics = getLookupTableFactory(function(t) { var getMetrics = getLookupTableFactory(function (t) {
t["Courier"] = 600; t["Courier"] = 600;
t["Courier-Bold"] = 600; t["Courier-Bold"] = 600;
t["Courier-BoldOblique"] = 600; t["Courier-BoldOblique"] = 600;
t["Courier-Oblique"] = 600; t["Courier-Oblique"] = 600;
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
t["Helvetica"] = getLookupTableFactory(function(t) { t["Helvetica"] = getLookupTableFactory(function (t) {
t["space"] = 278; t["space"] = 278;
t["exclam"] = 278; t["exclam"] = 278;
t["quotedbl"] = 355; t["quotedbl"] = 355;
@ -342,7 +342,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 556; t["Euro"] = 556;
}); });
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
t["Helvetica-Bold"] = getLookupTableFactory(function(t) { t["Helvetica-Bold"] = getLookupTableFactory(function (t) {
t["space"] = 278; t["space"] = 278;
t["exclam"] = 333; t["exclam"] = 333;
t["quotedbl"] = 474; t["quotedbl"] = 474;
@ -660,7 +660,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 556; t["Euro"] = 556;
}); });
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
t["Helvetica-BoldOblique"] = getLookupTableFactory(function(t) { t["Helvetica-BoldOblique"] = getLookupTableFactory(function (t) {
t["space"] = 278; t["space"] = 278;
t["exclam"] = 333; t["exclam"] = 333;
t["quotedbl"] = 474; t["quotedbl"] = 474;
@ -978,7 +978,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 556; t["Euro"] = 556;
}); });
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
t["Helvetica-Oblique"] = getLookupTableFactory(function(t) { t["Helvetica-Oblique"] = getLookupTableFactory(function (t) {
t["space"] = 278; t["space"] = 278;
t["exclam"] = 278; t["exclam"] = 278;
t["quotedbl"] = 355; t["quotedbl"] = 355;
@ -1296,7 +1296,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 556; t["Euro"] = 556;
}); });
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
t["Symbol"] = getLookupTableFactory(function(t) { t["Symbol"] = getLookupTableFactory(function (t) {
t["space"] = 250; t["space"] = 250;
t["exclam"] = 333; t["exclam"] = 333;
t["universal"] = 713; t["universal"] = 713;
@ -1489,7 +1489,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["apple"] = 790; t["apple"] = 790;
}); });
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
t["Times-Roman"] = getLookupTableFactory(function(t) { t["Times-Roman"] = getLookupTableFactory(function (t) {
t["space"] = 250; t["space"] = 250;
t["exclam"] = 333; t["exclam"] = 333;
t["quotedbl"] = 408; t["quotedbl"] = 408;
@ -1807,7 +1807,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 500; t["Euro"] = 500;
}); });
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
t["Times-Bold"] = getLookupTableFactory(function(t) { t["Times-Bold"] = getLookupTableFactory(function (t) {
t["space"] = 250; t["space"] = 250;
t["exclam"] = 333; t["exclam"] = 333;
t["quotedbl"] = 555; t["quotedbl"] = 555;
@ -2125,7 +2125,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 500; t["Euro"] = 500;
}); });
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
t["Times-BoldItalic"] = getLookupTableFactory(function(t) { t["Times-BoldItalic"] = getLookupTableFactory(function (t) {
t["space"] = 250; t["space"] = 250;
t["exclam"] = 389; t["exclam"] = 389;
t["quotedbl"] = 555; t["quotedbl"] = 555;
@ -2443,7 +2443,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 500; t["Euro"] = 500;
}); });
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
t["Times-Italic"] = getLookupTableFactory(function(t) { t["Times-Italic"] = getLookupTableFactory(function (t) {
t["space"] = 250; t["space"] = 250;
t["exclam"] = 333; t["exclam"] = 333;
t["quotedbl"] = 420; t["quotedbl"] = 420;
@ -2761,7 +2761,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 500; t["Euro"] = 500;
}); });
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
t["ZapfDingbats"] = getLookupTableFactory(function(t) { t["ZapfDingbats"] = getLookupTableFactory(function (t) {
t["space"] = 278; t["space"] = 278;
t["a1"] = 974; t["a1"] = 974;
t["a2"] = 961; t["a2"] = 961;

View File

@ -271,7 +271,7 @@ class Catalog {
dests[name] = fetchDestination(names[name]); dests[name] = fetchDestination(names[name]);
} }
} else if (obj instanceof Dict) { } else if (obj instanceof Dict) {
obj.forEach(function(key, value) { obj.forEach(function (key, value) {
if (value) { if (value) {
dests[key] = fetchDestination(value); dests[key] = fetchDestination(value);
} }
@ -693,7 +693,7 @@ class Catalog {
fontFallback(id, handler) { fontFallback(id, handler) {
const promises = []; const promises = [];
this.fontCache.forEach(function(promise) { this.fontCache.forEach(function (promise) {
promises.push(promise); promises.push(promise);
}); });
@ -712,7 +712,7 @@ class Catalog {
this.pageKidsCountCache.clear(); this.pageKidsCountCache.clear();
const promises = []; const promises = [];
this.fontCache.forEach(function(promise) { this.fontCache.forEach(function (promise) {
promises.push(promise); promises.push(promise);
}); });
@ -754,7 +754,7 @@ class Catalog {
} }
visitedNodes.put(currentNode); visitedNodes.put(currentNode);
xref.fetchAsync(currentNode).then(function(obj) { xref.fetchAsync(currentNode).then(function (obj) {
if (isDict(obj, "Page") || (isDict(obj) && !obj.has("Kids"))) { if (isDict(obj, "Page") || (isDict(obj) && !obj.has("Kids"))) {
if (pageIndex === currentPageIndex) { if (pageIndex === currentPageIndex) {
// Cache the Page reference, since it can *greatly* improve // Cache the Page reference, since it can *greatly* improve
@ -849,7 +849,7 @@ class Catalog {
return xref return xref
.fetchAsync(kidRef) .fetchAsync(kidRef)
.then(function(node) { .then(function (node) {
if ( if (
isRefsEqual(kidRef, pageRef) && isRefsEqual(kidRef, pageRef) &&
!isDict(node, "Page") && !isDict(node, "Page") &&
@ -868,7 +868,7 @@ class Catalog {
parentRef = node.getRaw("Parent"); parentRef = node.getRaw("Parent");
return node.getAsync("Parent"); return node.getAsync("Parent");
}) })
.then(function(parent) { .then(function (parent) {
if (!parent) { if (!parent) {
return null; return null;
} }
@ -877,7 +877,7 @@ class Catalog {
} }
return parent.getAsync("Kids"); return parent.getAsync("Kids");
}) })
.then(function(kids) { .then(function (kids) {
if (!kids) { if (!kids) {
return null; return null;
} }
@ -894,7 +894,7 @@ class Catalog {
break; break;
} }
kidPromises.push( kidPromises.push(
xref.fetchAsync(kid).then(function(obj) { xref.fetchAsync(kid).then(function (obj) {
if (!isDict(obj)) { if (!isDict(obj)) {
throw new FormatError("Kid node must be a dictionary."); throw new FormatError("Kid node must be a dictionary.");
} }
@ -910,7 +910,7 @@ class Catalog {
if (!found) { if (!found) {
throw new FormatError("Kid reference not found in parent's kids."); throw new FormatError("Kid reference not found in parent's kids.");
} }
return Promise.all(kidPromises).then(function() { return Promise.all(kidPromises).then(function () {
return [total, parentRef]; return [total, parentRef];
}); });
}); });
@ -918,7 +918,7 @@ class Catalog {
let total = 0; let total = 0;
function next(ref) { function next(ref) {
return pagesBeforeRef(ref).then(function(args) { return pagesBeforeRef(ref).then(function (args) {
if (!args) { if (!args) {
return total; return total;
} }
@ -1069,9 +1069,7 @@ class Catalog {
const URL_OPEN_METHODS = ["app.launchURL", "window.open"]; const URL_OPEN_METHODS = ["app.launchURL", "window.open"];
const regex = new RegExp( const regex = new RegExp(
"^\\s*(" + "^\\s*(" +
URL_OPEN_METHODS.join("|") URL_OPEN_METHODS.join("|").split(".").join("\\.") +
.split(".")
.join("\\.") +
")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))", ")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))",
"i" "i"
); );
@ -2186,7 +2184,7 @@ var FileSpec = (function FileSpecClosure() {
* that have references to the catalog or other pages since that will cause the * that have references to the catalog or other pages since that will cause the
* entire PDF document object graph to be traversed. * entire PDF document object graph to be traversed.
*/ */
const ObjectLoader = (function() { const ObjectLoader = (function () {
function mayHaveChildren(value) { function mayHaveChildren(value) {
return ( return (
value instanceof Ref || value instanceof Ref ||

View File

@ -304,7 +304,7 @@ var QueueOptimizer = (function QueueOptimizerClosure() {
addState( addState(
InitialState, InitialState,
[OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore], [OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore],
function(context) { function (context) {
var argsArray = context.argsArray; var argsArray = context.argsArray;
var iFirstTransform = context.iCurr - 2; var iFirstTransform = context.iCurr - 2;
return ( return (
@ -351,7 +351,7 @@ var QueueOptimizer = (function QueueOptimizerClosure() {
} }
throw new Error(`iterateImageGroup - invalid pos: ${pos}`); throw new Error(`iterateImageGroup - invalid pos: ${pos}`);
}, },
function(context, i) { function (context, i) {
var MIN_IMAGES_IN_BLOCK = 3; var MIN_IMAGES_IN_BLOCK = 3;
var MAX_IMAGES_IN_BLOCK = 1000; var MAX_IMAGES_IN_BLOCK = 1000;
@ -436,7 +436,7 @@ var QueueOptimizer = (function QueueOptimizerClosure() {
} }
throw new Error(`iterateShowTextGroup - invalid pos: ${pos}`); throw new Error(`iterateShowTextGroup - invalid pos: ${pos}`);
}, },
function(context, i) { function (context, i) {
var MIN_CHARS_IN_BLOCK = 3; var MIN_CHARS_IN_BLOCK = 3;
var MAX_CHARS_IN_BLOCK = 1000; var MAX_CHARS_IN_BLOCK = 1000;

View File

@ -51,7 +51,7 @@ var Pattern = (function PatternClosure() {
}, },
}; };
Pattern.parseShading = function( Pattern.parseShading = function (
shading, shading,
matrix, matrix,
xref, xref,

View File

@ -34,7 +34,7 @@ var Name = (function NameClosure() {
return nameValue ? nameValue : (nameCache[name] = new Name(name)); return nameValue ? nameValue : (nameCache[name] = new Name(name));
}; };
Name._clearCache = function() { Name._clearCache = function () {
nameCache = Object.create(null); nameCache = Object.create(null);
}; };
@ -57,7 +57,7 @@ var Cmd = (function CmdClosure() {
return cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd)); return cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd));
}; };
Cmd._clearCache = function() { Cmd._clearCache = function () {
cmdCache = Object.create(null); cmdCache = Object.create(null);
}; };
@ -164,7 +164,7 @@ var Dict = (function DictClosure() {
Dict.empty = new Dict(null); Dict.empty = new Dict(null);
Dict.merge = function(xref, dictArray) { Dict.merge = function (xref, dictArray) {
const mergedDict = new Dict(xref); const mergedDict = new Dict(xref);
for (let i = 0, ii = dictArray.length; i < ii; i++) { for (let i = 0, ii = dictArray.length; i < ii; i++) {
@ -205,14 +205,14 @@ var Ref = (function RefClosure() {
}, },
}; };
Ref.get = function(num, gen) { Ref.get = function (num, gen) {
const key = gen === 0 ? `${num}R` : `${num}R${gen}`; const key = gen === 0 ? `${num}R` : `${num}R${gen}`;
const refValue = refCache[key]; const refValue = refCache[key];
// eslint-disable-next-line no-restricted-syntax // eslint-disable-next-line no-restricted-syntax
return refValue ? refValue : (refCache[key] = new Ref(num, gen)); return refValue ? refValue : (refCache[key] = new Ref(num, gen));
}; };
Ref._clearCache = function() { Ref._clearCache = function () {
refCache = Object.create(null); refCache = Object.create(null);
}; };

View File

@ -20,7 +20,7 @@ import { getLookupTableFactory } from "./core_utils.js";
* Hold a map of decoded fonts and of the standard fourteen Type1 * Hold a map of decoded fonts and of the standard fourteen Type1
* fonts and their acronyms. * fonts and their acronyms.
*/ */
const getStdFontMap = getLookupTableFactory(function(t) { const getStdFontMap = getLookupTableFactory(function (t) {
t["ArialNarrow"] = "Helvetica"; t["ArialNarrow"] = "Helvetica";
t["ArialNarrow-Bold"] = "Helvetica-Bold"; t["ArialNarrow-Bold"] = "Helvetica-Bold";
t["ArialNarrow-BoldItalic"] = "Helvetica-BoldOblique"; t["ArialNarrow-BoldItalic"] = "Helvetica-BoldOblique";
@ -82,7 +82,7 @@ const getStdFontMap = getLookupTableFactory(function(t) {
* Holds the map of the non-standard fonts that might be included as * Holds the map of the non-standard fonts that might be included as
* a standard fonts without glyph data. * a standard fonts without glyph data.
*/ */
const getNonStdFontMap = getLookupTableFactory(function(t) { const getNonStdFontMap = getLookupTableFactory(function (t) {
t["Calibri"] = "Helvetica"; t["Calibri"] = "Helvetica";
t["Calibri-Bold"] = "Helvetica-Bold"; t["Calibri-Bold"] = "Helvetica-Bold";
t["Calibri-BoldItalic"] = "Helvetica-BoldOblique"; t["Calibri-BoldItalic"] = "Helvetica-BoldOblique";
@ -122,7 +122,7 @@ const getNonStdFontMap = getLookupTableFactory(function(t) {
t["Wingdings-Regular"] = "ZapfDingbats"; t["Wingdings-Regular"] = "ZapfDingbats";
}); });
const getSerifFonts = getLookupTableFactory(function(t) { const getSerifFonts = getLookupTableFactory(function (t) {
t["Adobe Jenson"] = true; t["Adobe Jenson"] = true;
t["Adobe Text"] = true; t["Adobe Text"] = true;
t["Albertus"] = true; t["Albertus"] = true;
@ -258,7 +258,7 @@ const getSerifFonts = getLookupTableFactory(function(t) {
t["XITS"] = true; t["XITS"] = true;
}); });
const getSymbolsFonts = getLookupTableFactory(function(t) { const getSymbolsFonts = getLookupTableFactory(function (t) {
t["Dingbats"] = true; t["Dingbats"] = true;
t["Symbol"] = true; t["Symbol"] = true;
t["ZapfDingbats"] = true; t["ZapfDingbats"] = true;
@ -267,7 +267,7 @@ const getSymbolsFonts = getLookupTableFactory(function(t) {
// Glyph map for well-known standard fonts. Sometimes Ghostscript uses CID // Glyph map for well-known standard fonts. Sometimes Ghostscript uses CID
// fonts, but does not embed the CID to GID mapping. The mapping is incomplete // fonts, but does not embed the CID to GID mapping. The mapping is incomplete
// for all glyphs, but common for some set of the standard fonts. // for all glyphs, but common for some set of the standard fonts.
const getGlyphMapForStandardFonts = getLookupTableFactory(function(t) { const getGlyphMapForStandardFonts = getLookupTableFactory(function (t) {
t[2] = 10; t[2] = 10;
t[3] = 32; t[3] = 32;
t[4] = 33; t[4] = 33;
@ -666,7 +666,9 @@ const getGlyphMapForStandardFonts = getLookupTableFactory(function(t) {
// The glyph map for ArialBlack differs slightly from the glyph map used for // The glyph map for ArialBlack differs slightly from the glyph map used for
// other well-known standard fonts. Hence we use this (incomplete) CID to GID // other well-known standard fonts. Hence we use this (incomplete) CID to GID
// mapping to adjust the glyph map for non-embedded ArialBlack fonts. // mapping to adjust the glyph map for non-embedded ArialBlack fonts.
const getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function(t) { const getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function (
t
) {
t[227] = 322; t[227] = 322;
t[264] = 261; t[264] = 261;
t[291] = 346; t[291] = 346;
@ -675,7 +677,7 @@ const getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function(t) {
// The glyph map for Calibri (a Windows font) differs from the glyph map used // The glyph map for Calibri (a Windows font) differs from the glyph map used
// in the standard fonts. Hence we use this (incomplete) CID to GID mapping to // in the standard fonts. Hence we use this (incomplete) CID to GID mapping to
// adjust the glyph map for non-embedded Calibri fonts. // adjust the glyph map for non-embedded Calibri fonts.
const getSupplementalGlyphMapForCalibri = getLookupTableFactory(function(t) { const getSupplementalGlyphMapForCalibri = getLookupTableFactory(function (t) {
t[1] = 32; t[1] = 32;
t[4] = 65; t[4] = 65;
t[17] = 66; t[17] = 66;

View File

@ -19,7 +19,7 @@ var getLookupTableFactory = require("./core_utils.js").getLookupTableFactory;
// Some characters, e.g. copyrightserif, are mapped to the private use area // Some characters, e.g. copyrightserif, are mapped to the private use area
// and might not be displayed using standard fonts. Mapping/hacking well-known // and might not be displayed using standard fonts. Mapping/hacking well-known
// chars to the similar equivalents in the normal characters range. // chars to the similar equivalents in the normal characters range.
var getSpecialPUASymbols = getLookupTableFactory(function(t) { var getSpecialPUASymbols = getLookupTableFactory(function (t) {
t[63721] = 0x00a9; // copyrightsans (0xF8E9) => copyright t[63721] = 0x00a9; // copyrightsans (0xF8E9) => copyright
t[63193] = 0x00a9; // copyrightserif (0xF6D9) => copyright t[63193] = 0x00a9; // copyrightserif (0xF6D9) => copyright
t[63720] = 0x00ae; // registersans (0xF8E8) => registered t[63720] = 0x00ae; // registersans (0xF8E8) => registered
@ -241,7 +241,7 @@ function isRTLRangeFor(value) {
// The normalization table is obtained by filtering the Unicode characters // The normalization table is obtained by filtering the Unicode characters
// database with <compat> entries. // database with <compat> entries.
var getNormalizedUnicodes = getLookupTableFactory(function(t) { var getNormalizedUnicodes = getLookupTableFactory(function (t) {
t["\u00A8"] = "\u0020\u0308"; t["\u00A8"] = "\u0020\u0308";
t["\u00AF"] = "\u0020\u0304"; t["\u00AF"] = "\u0020\u0304";
t["\u00B4"] = "\u0020\u0301"; t["\u00B4"] = "\u0020\u0301";

View File

@ -230,7 +230,7 @@ var WorkerMessageHandler = {
var fullRequest = pdfStream.getFullReader(); var fullRequest = pdfStream.getFullReader();
fullRequest.headersReady fullRequest.headersReady
.then(function() { .then(function () {
if (!fullRequest.isRangeSupported) { if (!fullRequest.isRangeSupported) {
return; return;
} }
@ -262,13 +262,13 @@ var WorkerMessageHandler = {
pdfManagerCapability.resolve(newPdfManager); pdfManagerCapability.resolve(newPdfManager);
cancelXHRs = null; cancelXHRs = null;
}) })
.catch(function(reason) { .catch(function (reason) {
pdfManagerCapability.reject(reason); pdfManagerCapability.reject(reason);
cancelXHRs = null; cancelXHRs = null;
}); });
var loaded = 0; var loaded = 0;
var flushChunks = function() { var flushChunks = function () {
var pdfFile = arraysToBytes(cachedChunks); var pdfFile = arraysToBytes(cachedChunks);
if (source.length && pdfFile.length !== source.length) { if (source.length && pdfFile.length !== source.length) {
warn("reported HTTP length is different from actual"); warn("reported HTTP length is different from actual");
@ -288,8 +288,8 @@ var WorkerMessageHandler = {
} }
cachedChunks = []; cachedChunks = [];
}; };
var readPromise = new Promise(function(resolve, reject) { var readPromise = new Promise(function (resolve, reject) {
var readChunk = function({ value, done }) { var readChunk = function ({ value, done }) {
try { try {
ensureNotTerminated(); ensureNotTerminated();
if (done) { if (done) {
@ -321,12 +321,12 @@ var WorkerMessageHandler = {
}; };
fullRequest.read().then(readChunk, reject); fullRequest.read().then(readChunk, reject);
}); });
readPromise.catch(function(e) { readPromise.catch(function (e) {
pdfManagerCapability.reject(e); pdfManagerCapability.reject(e);
cancelXHRs = null; cancelXHRs = null;
}); });
cancelXHRs = function(reason) { cancelXHRs = function (reason) {
pdfStream.cancelAllRequests(reason); pdfStream.cancelAllRequests(reason);
}; };
@ -348,12 +348,12 @@ var WorkerMessageHandler = {
handler handler
.sendWithPromise("PasswordRequest", ex) .sendWithPromise("PasswordRequest", ex)
.then(function({ password }) { .then(function ({ password }) {
finishWorkerTask(task); finishWorkerTask(task);
pdfManager.updatePassword(password); pdfManager.updatePassword(password);
pdfManagerReady(); pdfManagerReady();
}) })
.catch(function() { .catch(function () {
finishWorkerTask(task); finishWorkerTask(task);
handler.send("DocException", ex); handler.send("DocException", ex);
}); });
@ -386,7 +386,7 @@ var WorkerMessageHandler = {
return; return;
} }
pdfManager.requestLoadedStream(); pdfManager.requestLoadedStream();
pdfManager.onLoadedStream().then(function() { pdfManager.onLoadedStream().then(function () {
ensureNotTerminated(); ensureNotTerminated();
loadDocument(true).then(onSuccess, onFailure); loadDocument(true).then(onSuccess, onFailure);
@ -409,7 +409,7 @@ var WorkerMessageHandler = {
}; };
getPdfManager(data, evaluatorOptions) getPdfManager(data, evaluatorOptions)
.then(function(newPdfManager) { .then(function (newPdfManager) {
if (terminated) { if (terminated) {
// We were in a process of setting up the manager, but it got // We were in a process of setting up the manager, but it got
// terminated in the middle. // terminated in the middle.
@ -420,7 +420,7 @@ var WorkerMessageHandler = {
} }
pdfManager = newPdfManager; pdfManager = newPdfManager;
pdfManager.onLoadedStream().then(function(stream) { pdfManager.onLoadedStream().then(function (stream) {
handler.send("DataLoaded", { length: stream.bytes.byteLength }); handler.send("DataLoaded", { length: stream.bytes.byteLength });
}); });
}) })
@ -428,13 +428,13 @@ var WorkerMessageHandler = {
} }
handler.on("GetPage", function wphSetupGetPage(data) { handler.on("GetPage", function wphSetupGetPage(data) {
return pdfManager.getPage(data.pageIndex).then(function(page) { return pdfManager.getPage(data.pageIndex).then(function (page) {
return Promise.all([ return Promise.all([
pdfManager.ensure(page, "rotate"), pdfManager.ensure(page, "rotate"),
pdfManager.ensure(page, "ref"), pdfManager.ensure(page, "ref"),
pdfManager.ensure(page, "userUnit"), pdfManager.ensure(page, "userUnit"),
pdfManager.ensure(page, "view"), pdfManager.ensure(page, "view"),
]).then(function([rotate, ref, userUnit, view]) { ]).then(function ([rotate, ref, userUnit, view]) {
return { return {
rotate, rotate,
ref, ref,
@ -471,11 +471,11 @@ var WorkerMessageHandler = {
return pdfManager.ensureCatalog("pageMode"); return pdfManager.ensureCatalog("pageMode");
}); });
handler.on("GetViewerPreferences", function(data) { handler.on("GetViewerPreferences", function (data) {
return pdfManager.ensureCatalog("viewerPreferences"); return pdfManager.ensureCatalog("viewerPreferences");
}); });
handler.on("GetOpenAction", function(data) { handler.on("GetOpenAction", function (data) {
return pdfManager.ensureCatalog("openAction"); return pdfManager.ensureCatalog("openAction");
}); });
@ -491,7 +491,7 @@ var WorkerMessageHandler = {
return pdfManager.ensureCatalog("documentOutline"); return pdfManager.ensureCatalog("documentOutline");
}); });
handler.on("GetPermissions", function(data) { handler.on("GetPermissions", function (data) {
return pdfManager.ensureCatalog("permissions"); return pdfManager.ensureCatalog("permissions");
}); });
@ -504,7 +504,7 @@ var WorkerMessageHandler = {
handler.on("GetData", function wphSetupGetData(data) { handler.on("GetData", function wphSetupGetData(data) {
pdfManager.requestLoadedStream(); pdfManager.requestLoadedStream();
return pdfManager.onLoadedStream().then(function(stream) { return pdfManager.onLoadedStream().then(function (stream) {
return stream.bytes; return stream.bytes;
}); });
}); });
@ -513,8 +513,8 @@ var WorkerMessageHandler = {
return pdfManager.pdfDocument.xref.stats; return pdfManager.pdfDocument.xref.stats;
}); });
handler.on("GetAnnotations", function({ pageIndex, intent }) { handler.on("GetAnnotations", function ({ pageIndex, intent }) {
return pdfManager.getPage(pageIndex).then(function(page) { return pdfManager.getPage(pageIndex).then(function (page) {
return page.getAnnotationsData(intent); return page.getAnnotationsData(intent);
}); });
}); });
@ -523,7 +523,7 @@ var WorkerMessageHandler = {
"GetOperatorList", "GetOperatorList",
function wphSetupRenderPage(data, sink) { function wphSetupRenderPage(data, sink) {
var pageIndex = data.pageIndex; var pageIndex = data.pageIndex;
pdfManager.getPage(pageIndex).then(function(page) { pdfManager.getPage(pageIndex).then(function (page) {
var task = new WorkerTask(`GetOperatorList: page ${pageIndex}`); var task = new WorkerTask(`GetOperatorList: page ${pageIndex}`);
startWorkerTask(task); startWorkerTask(task);
@ -540,7 +540,7 @@ var WorkerMessageHandler = {
renderInteractiveForms: data.renderInteractiveForms, renderInteractiveForms: data.renderInteractiveForms,
}) })
.then( .then(
function(operatorListInfo) { function (operatorListInfo) {
finishWorkerTask(task); finishWorkerTask(task);
if (start) { if (start) {
@ -551,7 +551,7 @@ var WorkerMessageHandler = {
} }
sink.close(); sink.close();
}, },
function(reason) { function (reason) {
finishWorkerTask(task); finishWorkerTask(task);
if (task.terminated) { if (task.terminated) {
return; // ignoring errors from the terminated thread return; // ignoring errors from the terminated thread
@ -576,10 +576,10 @@ var WorkerMessageHandler = {
handler.on("GetTextContent", function wphExtractText(data, sink) { handler.on("GetTextContent", function wphExtractText(data, sink) {
var pageIndex = data.pageIndex; var pageIndex = data.pageIndex;
sink.onPull = function(desiredSize) {}; sink.onPull = function (desiredSize) {};
sink.onCancel = function(reason) {}; sink.onCancel = function (reason) {};
pdfManager.getPage(pageIndex).then(function(page) { pdfManager.getPage(pageIndex).then(function (page) {
var task = new WorkerTask("GetTextContent: page " + pageIndex); var task = new WorkerTask("GetTextContent: page " + pageIndex);
startWorkerTask(task); startWorkerTask(task);
@ -595,7 +595,7 @@ var WorkerMessageHandler = {
combineTextItems: data.combineTextItems, combineTextItems: data.combineTextItems,
}) })
.then( .then(
function() { function () {
finishWorkerTask(task); finishWorkerTask(task);
if (start) { if (start) {
@ -606,7 +606,7 @@ var WorkerMessageHandler = {
} }
sink.close(); sink.close();
}, },
function(reason) { function (reason) {
finishWorkerTask(task); finishWorkerTask(task);
if (task.terminated) { if (task.terminated) {
return; // ignoring errors from the terminated thread return; // ignoring errors from the terminated thread
@ -620,7 +620,7 @@ var WorkerMessageHandler = {
}); });
}); });
handler.on("FontFallback", function(data) { handler.on("FontFallback", function (data) {
return pdfManager.fontFallback(data.id, handler); return pdfManager.fontFallback(data.id, handler);
}); });
@ -646,12 +646,12 @@ var WorkerMessageHandler = {
cancelXHRs(new AbortException("Worker was terminated.")); cancelXHRs(new AbortException("Worker was terminated."));
} }
WorkerTasks.forEach(function(task) { WorkerTasks.forEach(function (task) {
waitOn.push(task.finished); waitOn.push(task.finished);
task.terminate(); task.terminate();
}); });
return Promise.all(waitOn).then(function() { return Promise.all(waitOn).then(function () {
// Notice that even if we destroying handler, resolved response promise // Notice that even if we destroying handler, resolved response promise
// must be sent back. // must be sent back.
handler.destroy(); handler.destroy();

View File

@ -42,7 +42,7 @@ class PDFWorkerStream {
this._fullRequestReader.cancel(reason); this._fullRequestReader.cancel(reason);
} }
const readers = this._rangeRequestReaders.slice(0); const readers = this._rangeRequestReaders.slice(0);
readers.forEach(function(reader) { readers.forEach(function (reader) {
reader.cancel(reason); reader.cancel(reason);
}); });
} }

View File

@ -309,12 +309,12 @@ function getDocument(src) {
} }
const docId = task.docId; const docId = task.docId;
worker.promise worker.promise
.then(function() { .then(function () {
if (task.destroyed) { if (task.destroyed) {
throw new Error("Loading aborted"); throw new Error("Loading aborted");
} }
return _fetchDocument(worker, params, rangeTransport, docId).then( return _fetchDocument(worker, params, rangeTransport, docId).then(
function(workerId) { function (workerId) {
if (task.destroyed) { if (task.destroyed) {
throw new Error("Loading aborted"); throw new Error("Loading aborted");
} }
@ -411,7 +411,7 @@ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
isEvalSupported: source.isEvalSupported, isEvalSupported: source.isEvalSupported,
fontExtraProperties: source.fontExtraProperties, fontExtraProperties: source.fontExtraProperties,
}) })
.then(function(workerId) { .then(function (workerId) {
if (worker.destroyed) { if (worker.destroyed) {
throw new Error("Worker was destroyed"); throw new Error("Worker was destroyed");
} }
@ -679,7 +679,7 @@ class PDFDocumentProxy {
getOpenActionDestination() { getOpenActionDestination() {
deprecated("getOpenActionDestination, use getOpenAction instead."); deprecated("getOpenActionDestination, use getOpenAction instead.");
return this.getOpenAction().then(function(openAction) { return this.getOpenAction().then(function (openAction) {
return openAction && openAction.dest ? openAction.dest : null; return openAction && openAction.dest ? openAction.dest : null;
}); });
} }
@ -1214,9 +1214,9 @@ class PDFPageProxy {
getTextContent(params = {}) { getTextContent(params = {}) {
const readableStream = this.streamTextContent(params); const readableStream = this.streamTextContent(params);
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
function pump() { function pump() {
reader.read().then(function({ value, done }) { reader.read().then(function ({ value, done }) {
if (done) { if (done) {
resolve(textContent); resolve(textContent);
return; return;
@ -1257,9 +1257,9 @@ class PDFPageProxy {
// Avoid errors below, since the renderTasks are just stubs. // Avoid errors below, since the renderTasks are just stubs.
return; return;
} }
intentState.renderTasks.forEach(function(renderTask) { intentState.renderTasks.forEach(function (renderTask) {
const renderCompleted = renderTask.capability.promise.catch( const renderCompleted = renderTask.capability.promise.catch(
function() {} function () {}
); // ignoring failures ); // ignoring failures
waitOn.push(renderCompleted); waitOn.push(renderCompleted);
renderTask.cancel(); renderTask.cancel();
@ -1629,7 +1629,7 @@ const PDFWorker = (function PDFWorkerClosure() {
} }
fakeWorkerCapability = createPromiseCapability(); fakeWorkerCapability = createPromiseCapability();
const loader = async function() { const loader = async function () {
const mainWorkerMessageHandler = getMainThreadWorkerMessageHandler(); const mainWorkerMessageHandler = getMainThreadWorkerMessageHandler();
if (mainWorkerMessageHandler) { if (mainWorkerMessageHandler) {
@ -1734,7 +1734,7 @@ const PDFWorker = (function PDFWorkerClosure() {
_initializeFromPort(port) { _initializeFromPort(port) {
this._port = port; this._port = port;
this._messageHandler = new MessageHandler("main", "worker", port); this._messageHandler = new MessageHandler("main", "worker", port);
this._messageHandler.on("ready", function() { this._messageHandler.on("ready", function () {
// Ignoring 'ready' event -- MessageHandler shall be already initialized // Ignoring 'ready' event -- MessageHandler shall be already initialized
// and ready to accept the messages. // and ready to accept the messages.
}); });
@ -1991,7 +1991,7 @@ class WorkerTransport {
const waitOn = []; const waitOn = [];
// We need to wait for all renderings to be completed, e.g. // We need to wait for all renderings to be completed, e.g.
// timeout/rAF can take a long time. // timeout/rAF can take a long time.
this.pageCache.forEach(function(page) { this.pageCache.forEach(function (page) {
if (page) { if (page) {
waitOn.push(page._destroy()); waitOn.push(page._destroy());
} }
@ -2033,7 +2033,7 @@ class WorkerTransport {
sink.onPull = () => { sink.onPull = () => {
this._fullReader this._fullReader
.read() .read()
.then(function({ value, done }) { .then(function ({ value, done }) {
if (done) { if (done) {
sink.close(); sink.close();
return; return;
@ -2108,7 +2108,7 @@ class WorkerTransport {
sink.onPull = () => { sink.onPull = () => {
rangeReader rangeReader
.read() .read()
.then(function({ value, done }) { .then(function ({ value, done }) {
if (done) { if (done) {
sink.close(); sink.close();
return; return;
@ -2131,7 +2131,7 @@ class WorkerTransport {
loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this)); loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
}); });
messageHandler.on("DocException", function(ex) { messageHandler.on("DocException", function (ex) {
let reason; let reason;
switch (ex.name) { switch (ex.name) {
case "PasswordException": case "PasswordException":
@ -2283,10 +2283,10 @@ class WorkerTransport {
case "JpegStream": case "JpegStream":
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const img = new Image(); const img = new Image();
img.onload = function() { img.onload = function () {
resolve(img); resolve(img);
}; };
img.onerror = function() { img.onerror = function () {
// Note that when the browser image loading/decoding fails, // Note that when the browser image loading/decoding fails,
// we'll fallback to the built-in PDF.js JPEG decoder; see // we'll fallback to the built-in PDF.js JPEG decoder; see
// `PartialEvaluator.buildPaintImageXObject` in the // `PartialEvaluator.buildPaintImageXObject` in the
@ -2354,9 +2354,9 @@ class WorkerTransport {
); );
} }
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
const img = new Image(); const img = new Image();
img.onload = function() { img.onload = function () {
const { width, height } = img; const { width, height } = img;
const size = width * height; const size = width * height;
const rgbaLength = size * 4; const rgbaLength = size * 4;
@ -2390,7 +2390,7 @@ class WorkerTransport {
tmpCanvas = null; tmpCanvas = null;
tmpCtx = null; tmpCtx = null;
}; };
img.onerror = function() { img.onerror = function () {
reject(new Error("JpegDecode failed to load image")); reject(new Error("JpegDecode failed to load image"));
// Always remember to release the image data if errors occurred. // Always remember to release the image data if errors occurred.
@ -2415,10 +2415,10 @@ class WorkerTransport {
fetched = true; fetched = true;
this.CMapReaderFactory.fetch(data) this.CMapReaderFactory.fetch(data)
.then(function(builtInCMap) { .then(function (builtInCMap) {
sink.enqueue(builtInCMap, 1, [builtInCMap.cMapData.buffer]); sink.enqueue(builtInCMap, 1, [builtInCMap.cMapData.buffer]);
}) })
.catch(function(reason) { .catch(function (reason) {
sink.error(reason); sink.error(reason);
}); });
}; };
@ -2477,7 +2477,7 @@ class WorkerTransport {
.sendWithPromise("GetPageIndex", { .sendWithPromise("GetPageIndex", {
ref, ref,
}) })
.catch(function(reason) { .catch(function (reason) {
return Promise.reject(new Error(reason)); return Promise.reject(new Error(reason));
}); });
} }
@ -2856,9 +2856,7 @@ const InternalRenderTask = (function InternalRenderTaskClosure() {
this._nextBound().catch(this.cancel.bind(this)); this._nextBound().catch(this.cancel.bind(this));
}); });
} else { } else {
Promise.resolve() Promise.resolve().then(this._nextBound).catch(this.cancel.bind(this));
.then(this._nextBound)
.catch(this.cancel.bind(this));
} }
} }

View File

@ -362,7 +362,7 @@ function compileType3Glyph(imgData) {
--i; --i;
} }
var drawOutline = function(c) { var drawOutline = function (c) {
c.save(); c.save();
// the path shall be painted in [0..1]x[0..1] space // the path shall be painted in [0..1]x[0..1] space
c.scale(1 / width, -1 / height); c.scale(1 / width, -1 / height);

View File

@ -85,7 +85,7 @@ function getFilenameFromContentDispositionHeader(contentDisposition) {
} }
try { try {
const decoder = new TextDecoder(encoding, { fatal: true }); const decoder = new TextDecoder(encoding, { fatal: true });
const bytes = Array.from(value, function(ch) { const bytes = Array.from(value, function (ch) {
return ch.charCodeAt(0) & 0xff; return ch.charCodeAt(0) & 0xff;
}); });
value = decoder.decode(new Uint8Array(bytes)); value = decoder.decode(new Uint8Array(bytes));
@ -205,11 +205,11 @@ function getFilenameFromContentDispositionHeader(contentDisposition) {
// ... but Firefox permits ? and space. // ... but Firefox permits ? and space.
return value.replace( return value.replace(
/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, /=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,
function(matches, charset, encoding, text) { function (matches, charset, encoding, text) {
if (encoding === "q" || encoding === "Q") { if (encoding === "q" || encoding === "Q") {
// RFC 2047 section 4.2. // RFC 2047 section 4.2.
text = text.replace(/_/g, " "); text = text.replace(/_/g, " ");
text = text.replace(/=([0-9a-fA-F]{2})/g, function(match, hex) { text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
return String.fromCharCode(parseInt(hex, 16)); return String.fromCharCode(parseInt(hex, 16));
}); });
return textdecode(charset, text); return textdecode(charset, text);

View File

@ -502,7 +502,7 @@ function loadScript(src) {
script.src = src; script.src = src;
script.onload = resolve; script.onload = resolve;
script.onerror = function() { script.onerror = function () {
reject(new Error(`Cannot load script at: ${script.src}`)); reject(new Error(`Cannot load script at: ${script.src}`));
}; };
(document.head || document.documentElement).appendChild(script); (document.head || document.documentElement).appendChild(script);

View File

@ -84,7 +84,7 @@ class PDFFetchStream {
this._fullRequestReader.cancel(reason); this._fullRequestReader.cancel(reason);
} }
const readers = this._rangeRequestReaders.slice(0); const readers = this._rangeRequestReaders.slice(0);
readers.forEach(function(reader) { readers.forEach(function (reader) {
reader.cancel(reason); reader.cancel(reason);
}); });
} }

View File

@ -56,7 +56,7 @@ class BaseFontLoader {
} }
clear() { clear() {
this.nativeFontFaces.forEach(function(nativeFontFace) { this.nativeFontFaces.forEach(function (nativeFontFace) {
document.fonts.delete(nativeFontFace); document.fonts.delete(nativeFontFace);
}); });
this.nativeFontFaces.length = 0; this.nativeFontFaces.length = 0;
@ -198,7 +198,7 @@ if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
} }
get _loadTestFont() { get _loadTestFont() {
const getLoadTestFont = function() { const getLoadTestFont = function () {
// This is a CFF font with 1 glyph for '.' that fills its entire width // This is a CFF font with 1 glyph for '.' that fills its entire width
// and height. // and height.
return atob( return atob(
@ -328,7 +328,7 @@ if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
} }
document.body.appendChild(div); document.body.appendChild(div);
isFontReady(loadTestFontId, function() { isFontReady(loadTestFontId, function () {
document.body.removeChild(div); document.body.removeChild(div);
request.complete(); request.complete();
}); });
@ -404,7 +404,7 @@ class FontFaceObject {
} }
warn(`getPathGenerator - ignoring character: "${ex}".`); warn(`getPathGenerator - ignoring character: "${ex}".`);
return (this.compiledGlyphs[character] = function(c, size) { return (this.compiledGlyphs[character] = function (c, size) {
// No-op function, to allow rendering to continue. // No-op function, to allow rendering to continue.
}); });
} }
@ -428,7 +428,7 @@ class FontFaceObject {
} }
// ... but fall back on using Function.prototype.apply() if we're // ... but fall back on using Function.prototype.apply() if we're
// blocked from using eval() for whatever reason (like CSP policies). // blocked from using eval() for whatever reason (like CSP policies).
return (this.compiledGlyphs[character] = function(c, size) { return (this.compiledGlyphs[character] = function (c, size) {
for (let i = 0, ii = cmds.length; i < ii; i++) { for (let i = 0, ii = cmds.length; i < ii; i++) {
current = cmds[i]; current = cmds[i];

View File

@ -38,12 +38,12 @@ class Metadata {
// Start by removing any "junk" before the first tag (see issue 10395). // Start by removing any "junk" before the first tag (see issue 10395).
return data return data
.replace(/^[^<]+/, "") .replace(/^[^<]+/, "")
.replace(/>\\376\\377([^<]+)/g, function(all, codes) { .replace(/>\\376\\377([^<]+)/g, function (all, codes) {
const bytes = codes const bytes = codes
.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { .replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
}) })
.replace(/&(amp|apos|gt|lt|quot);/g, function(str, name) { .replace(/&(amp|apos|gt|lt|quot);/g, function (str, name) {
switch (name) { switch (name) {
case "amp": case "amp":
return "&"; return "&";

View File

@ -100,7 +100,7 @@ class NetworkManager {
xhr.responseType = "arraybuffer"; xhr.responseType = "arraybuffer";
if (args.onError) { if (args.onError) {
xhr.onerror = function(evt) { xhr.onerror = function (evt) {
args.onError(xhr.status); args.onError(xhr.status);
}; };
} }
@ -271,7 +271,7 @@ class PDFNetworkStream {
this._fullRequestReader.cancel(reason); this._fullRequestReader.cancel(reason);
} }
const readers = this._rangeRequestReaders.slice(0); const readers = this._rangeRequestReaders.slice(0);
readers.forEach(function(reader) { readers.forEach(function (reader) {
reader.cancel(reason); reader.cancel(reason);
}); });
} }
@ -359,7 +359,7 @@ class PDFNetworkStreamFullRequestReader {
if (this._cachedChunks.length > 0) { if (this._cachedChunks.length > 0) {
return; return;
} }
this._requests.forEach(function(requestCapability) { this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true }); requestCapability.resolve({ value: undefined, done: true });
}); });
this._requests = []; this._requests = [];
@ -370,7 +370,7 @@ class PDFNetworkStreamFullRequestReader {
const exception = createResponseStatusError(status, url); const exception = createResponseStatusError(status, url);
this._storedError = exception; this._storedError = exception;
this._headersReceivedCapability.reject(exception); this._headersReceivedCapability.reject(exception);
this._requests.forEach(function(requestCapability) { this._requests.forEach(function (requestCapability) {
requestCapability.reject(exception); requestCapability.reject(exception);
}); });
this._requests = []; this._requests = [];
@ -425,7 +425,7 @@ class PDFNetworkStreamFullRequestReader {
cancel(reason) { cancel(reason) {
this._done = true; this._done = true;
this._headersReceivedCapability.reject(reason); this._headersReceivedCapability.reject(reason);
this._requests.forEach(function(requestCapability) { this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true }); requestCapability.resolve({ value: undefined, done: true });
}); });
this._requests = []; this._requests = [];
@ -468,7 +468,7 @@ class PDFNetworkStreamRangeRequestReader {
this._queuedChunk = chunk; this._queuedChunk = chunk;
} }
this._done = true; this._done = true;
this._requests.forEach(function(requestCapability) { this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true }); requestCapability.resolve({ value: undefined, done: true });
}); });
this._requests = []; this._requests = [];
@ -503,7 +503,7 @@ class PDFNetworkStreamRangeRequestReader {
cancel(reason) { cancel(reason) {
this._done = true; this._done = true;
this._requests.forEach(function(requestCapability) { this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true }); requestCapability.resolve({ value: undefined, done: true });
}); });
this._requests = []; this._requests = [];

View File

@ -91,7 +91,7 @@ class PDFNodeStream {
} }
const readers = this._rangeRequestReaders.slice(0); const readers = this._rangeRequestReaders.slice(0);
readers.forEach(function(reader) { readers.forEach(function (reader) {
reader.cancel(reason); reader.cancel(reason);
}); });
} }

View File

@ -29,7 +29,7 @@ import {
import { DOMSVGFactory } from "./display_utils.js"; import { DOMSVGFactory } from "./display_utils.js";
import { isNodeJS } from "../shared/is_node.js"; import { isNodeJS } from "../shared/is_node.js";
let SVGGraphics = function() { let SVGGraphics = function () {
throw new Error("Not implemented: SVGGraphics"); throw new Error("Not implemented: SVGGraphics");
}; };
@ -44,7 +44,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
const LINE_CAP_STYLES = ["butt", "round", "square"]; const LINE_CAP_STYLES = ["butt", "round", "square"];
const LINE_JOIN_STYLES = ["miter", "round", "bevel"]; const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
const convertImgDataToPng = (function() { const convertImgDataToPng = (function () {
const PNG_HEADER = new Uint8Array([ const PNG_HEADER = new Uint8Array([
0x89, 0x89,
0x50, 0x50,
@ -1327,7 +1327,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
// The previous clipping group content can go out of order -- resetting // The previous clipping group content can go out of order -- resetting
// cached clipGroups. // cached clipGroups.
current.clipGroup = null; current.clipGroup = null;
this.extraStack.forEach(function(prev) { this.extraStack.forEach(function (prev) {
prev.clipGroup = null; prev.clipGroup = null;
}); });
// Intersect with the previous clipping path. // Intersect with the previous clipping path.
@ -1439,7 +1439,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
const current = this.current; const current = this.current;
let dashArray = current.dashArray; let dashArray = current.dashArray;
if (lineWidthScale !== 1 && dashArray.length > 0) { if (lineWidthScale !== 1 && dashArray.length > 0) {
dashArray = dashArray.map(function(value) { dashArray = dashArray.map(function (value) {
return lineWidthScale * value; return lineWidthScale * value;
}); });
} }

View File

@ -234,7 +234,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
// Finding intersections with expanded box. // Finding intersections with expanded box.
var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size]; var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
var ts = new Float64Array(64); var ts = new Float64Array(64);
points.forEach(function(p, j) { points.forEach(function (p, j) {
var t = Util.applyTransform(p, m); var t = Util.applyTransform(p, m);
ts[j + 0] = c && (e.left - t[0]) / c; ts[j + 0] = c && (e.left - t[0]) / c;
ts[j + 4] = s && (e.top - t[1]) / s; ts[j + 4] = s && (e.top - t[1]) / s;
@ -268,7 +268,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
} }
function expandBounds(width, height, boxes) { function expandBounds(width, height, boxes) {
var bounds = boxes.map(function(box, i) { var bounds = boxes.map(function (box, i) {
return { return {
x1: box.left, x1: box.left,
y1: box.top, y1: box.top,
@ -281,7 +281,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
}); });
expandBoundsLTR(width, bounds); expandBoundsLTR(width, bounds);
var expanded = new Array(boxes.length); var expanded = new Array(boxes.length);
bounds.forEach(function(b) { bounds.forEach(function (b) {
var i = b.index; var i = b.index;
expanded[i] = { expanded[i] = {
left: b.x1New, left: b.x1New,
@ -293,7 +293,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
// Rotating on 90 degrees and extending extended boxes. Reusing the bounds // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
// array and objects. // array and objects.
boxes.map(function(box, i) { boxes.map(function (box, i) {
var e = expanded[i], var e = expanded[i],
b = bounds[i]; b = bounds[i];
b.x1 = box.top; b.x1 = box.top;
@ -306,7 +306,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
}); });
expandBoundsLTR(height, bounds); expandBoundsLTR(height, bounds);
bounds.forEach(function(b) { bounds.forEach(function (b) {
var i = b.index; var i = b.index;
expanded[i].top = b.x1New; expanded[i].top = b.x1New;
expanded[i].bottom = b.x2New; expanded[i].bottom = b.x2New;
@ -316,7 +316,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
function expandBoundsLTR(width, bounds) { function expandBoundsLTR(width, bounds) {
// Sorting by x1 coordinate and walk by the bounds in the same order. // Sorting by x1 coordinate and walk by the bounds in the same order.
bounds.sort(function(a, b) { bounds.sort(function (a, b) {
return a.x1 - b.x1 || a.index - b.index; return a.x1 - b.x1 || a.index - b.index;
}); });
@ -338,7 +338,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
}, },
]; ];
bounds.forEach(function(boundary) { bounds.forEach(function (boundary) {
// Searching for the affected part of horizon. // Searching for the affected part of horizon.
// TODO red-black tree or simple binary search // TODO red-black tree or simple binary search
var i = 0; var i = 0;
@ -480,7 +480,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
}); });
// Set new x2 for all unset boundaries. // Set new x2 for all unset boundaries.
horizon.forEach(function(horizonPart) { horizon.forEach(function (horizonPart) {
var affectedBoundary = horizonPart.boundary; var affectedBoundary = horizonPart.boundary;
if (affectedBoundary.x2New === undefined) { if (affectedBoundary.x2New === undefined) {
affectedBoundary.x2New = Math.max(width, affectedBoundary.x2); affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);

View File

@ -66,7 +66,7 @@ class PDFDataTransportStream {
this._queuedChunks.push(buffer); this._queuedChunks.push(buffer);
} }
} else { } else {
const found = this._rangeReaders.some(function(rangeReader) { const found = this._rangeReaders.some(function (rangeReader) {
if (rangeReader._begin !== args.begin) { if (rangeReader._begin !== args.begin) {
return false; return false;
} }
@ -136,7 +136,7 @@ class PDFDataTransportStream {
this._fullRequestReader.cancel(reason); this._fullRequestReader.cancel(reason);
} }
const readers = this._rangeReaders.slice(0); const readers = this._rangeReaders.slice(0);
readers.forEach(function(rangeReader) { readers.forEach(function (rangeReader) {
rangeReader.cancel(reason); rangeReader.cancel(reason);
}); });
this._pdfDataRangeTransport.abort(); this._pdfDataRangeTransport.abort();
@ -209,7 +209,7 @@ class PDFDataTransportStreamReader {
cancel(reason) { cancel(reason) {
this._done = true; this._done = true;
this._requests.forEach(function(requestCapability) { this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true }); requestCapability.resolve({ value: undefined, done: true });
}); });
this._requests = []; this._requests = [];
@ -245,7 +245,7 @@ class PDFDataTransportStreamRangeReader {
} else { } else {
const requestsCapability = this._requests.shift(); const requestsCapability = this._requests.shift();
requestsCapability.resolve({ value: chunk, done: false }); requestsCapability.resolve({ value: chunk, done: false });
this._requests.forEach(function(requestCapability) { this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true }); requestCapability.resolve({ value: undefined, done: true });
}); });
this._requests = []; this._requests = [];
@ -274,7 +274,7 @@ class PDFDataTransportStreamRangeReader {
cancel(reason) { cancel(reason) {
this._done = true; this._done = true;
this._requests.forEach(function(requestCapability) { this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true }); requestCapability.resolve({ value: undefined, done: true });
}); });
this._requests = []; this._requests = [];

View File

@ -317,7 +317,7 @@ class SimpleDOMNode {
return this.nodeValue || ""; return this.nodeValue || "";
} }
return this.childNodes return this.childNodes
.map(function(child) { .map(function (child) {
return child.textContent; return child.textContent;
}) })
.join(""); .join("");

View File

@ -56,7 +56,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
} else if (PDFJSDev.test("CHROME")) { } else if (PDFJSDev.test("CHROME")) {
const PDFNetworkStream = require("./display/network.js").PDFNetworkStream; const PDFNetworkStream = require("./display/network.js").PDFNetworkStream;
let PDFFetchStream; let PDFFetchStream;
const isChromeWithFetchCredentials = function() { const isChromeWithFetchCredentials = function () {
// fetch does not include credentials until Chrome 61.0.3138.0 and later. // fetch does not include credentials until Chrome 61.0.3138.0 and later.
// https://chromium.googlesource.com/chromium/src/+/2e231cf052ca5e68e22baf0008ac9e5e29121707 // https://chromium.googlesource.com/chromium/src/+/2e231cf052ca5e68e22baf0008ac9e5e29121707
try { try {

View File

@ -39,7 +39,7 @@ if (
if (globalThis.btoa || !isNodeJS) { if (globalThis.btoa || !isNodeJS) {
return; return;
} }
globalThis.btoa = function(chars) { globalThis.btoa = function (chars) {
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
return Buffer.from(chars, "binary").toString("base64"); return Buffer.from(chars, "binary").toString("base64");
}; };
@ -50,7 +50,7 @@ if (
if (globalThis.atob || !isNodeJS) { if (globalThis.atob || !isNodeJS) {
return; return;
} }
globalThis.atob = function(input) { globalThis.atob = function (input) {
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
return Buffer.from(input, "base64").toString("binary"); return Buffer.from(input, "base64").toString("binary");
}; };
@ -65,7 +65,7 @@ if (
if (typeof Element.prototype.remove !== "undefined") { if (typeof Element.prototype.remove !== "undefined") {
return; return;
} }
Element.prototype.remove = function() { Element.prototype.remove = function () {
if (this.parentNode) { if (this.parentNode) {
// eslint-disable-next-line mozilla/avoid-removeChild // eslint-disable-next-line mozilla/avoid-removeChild
this.parentNode.removeChild(this); this.parentNode.removeChild(this);
@ -92,12 +92,12 @@ if (
const OriginalDOMTokenListAdd = DOMTokenList.prototype.add; const OriginalDOMTokenListAdd = DOMTokenList.prototype.add;
const OriginalDOMTokenListRemove = DOMTokenList.prototype.remove; const OriginalDOMTokenListRemove = DOMTokenList.prototype.remove;
DOMTokenList.prototype.add = function(...tokens) { DOMTokenList.prototype.add = function (...tokens) {
for (const token of tokens) { for (const token of tokens) {
OriginalDOMTokenListAdd.call(this, token); OriginalDOMTokenListAdd.call(this, token);
} }
}; };
DOMTokenList.prototype.remove = function(...tokens) { DOMTokenList.prototype.remove = function (...tokens) {
for (const token of tokens) { for (const token of tokens) {
OriginalDOMTokenListRemove.call(this, token); OriginalDOMTokenListRemove.call(this, token);
} }
@ -116,7 +116,7 @@ if (
return; return;
} }
DOMTokenList.prototype.toggle = function(token) { DOMTokenList.prototype.toggle = function (token) {
const force = const force =
arguments.length > 1 ? !!arguments[1] : !this.contains(token); arguments.length > 1 ? !!arguments[1] : !this.contains(token);
return this[force ? "add" : "remove"](token), force; return this[force ? "add" : "remove"](token), force;
@ -133,11 +133,11 @@ if (
const OriginalPushState = window.history.pushState; const OriginalPushState = window.history.pushState;
const OriginalReplaceState = window.history.replaceState; const OriginalReplaceState = window.history.replaceState;
window.history.pushState = function(state, title, url) { window.history.pushState = function (state, title, url) {
const args = url === undefined ? [state, title] : [state, title, url]; const args = url === undefined ? [state, title] : [state, title, url];
OriginalPushState.apply(this, args); OriginalPushState.apply(this, args);
}; };
window.history.replaceState = function(state, title, url) { window.history.replaceState = function (state, title, url) {
const args = url === undefined ? [state, title] : [state, title, url]; const args = url === undefined ? [state, title] : [state, title, url];
OriginalReplaceState.apply(this, args); OriginalReplaceState.apply(this, args);
}; };

View File

@ -116,10 +116,10 @@ class MessageHandler {
if (data.callbackId) { if (data.callbackId) {
const cbSourceName = this.sourceName; const cbSourceName = this.sourceName;
const cbTargetName = data.sourceName; const cbTargetName = data.sourceName;
new Promise(function(resolve) { new Promise(function (resolve) {
resolve(action(data.data)); resolve(action(data.data));
}).then( }).then(
function(result) { function (result) {
comObj.postMessage({ comObj.postMessage({
sourceName: cbSourceName, sourceName: cbSourceName,
targetName: cbTargetName, targetName: cbTargetName,
@ -128,7 +128,7 @@ class MessageHandler {
data: result, data: result,
}); });
}, },
function(reason) { function (reason) {
comObj.postMessage({ comObj.postMessage({
sourceName: cbSourceName, sourceName: cbSourceName,
targetName: cbTargetName, targetName: cbTargetName,
@ -367,10 +367,10 @@ class MessageHandler {
streamSink.sinkCapability.resolve(); streamSink.sinkCapability.resolve();
streamSink.ready = streamSink.sinkCapability.promise; streamSink.ready = streamSink.sinkCapability.promise;
this.streamSinks[streamId] = streamSink; this.streamSinks[streamId] = streamSink;
new Promise(function(resolve) { new Promise(function (resolve) {
resolve(action(data.data, streamSink)); resolve(action(data.data, streamSink));
}).then( }).then(
function() { function () {
comObj.postMessage({ comObj.postMessage({
sourceName, sourceName,
targetName, targetName,
@ -379,7 +379,7 @@ class MessageHandler {
success: true, success: true,
}); });
}, },
function(reason) { function (reason) {
comObj.postMessage({ comObj.postMessage({
sourceName, sourceName,
targetName, targetName,
@ -443,10 +443,10 @@ class MessageHandler {
// Reset desiredSize property of sink on every pull. // Reset desiredSize property of sink on every pull.
this.streamSinks[streamId].desiredSize = data.desiredSize; this.streamSinks[streamId].desiredSize = data.desiredSize;
const { onPull } = this.streamSinks[data.streamId]; const { onPull } = this.streamSinks[data.streamId];
new Promise(function(resolve) { new Promise(function (resolve) {
resolve(onPull && onPull()); resolve(onPull && onPull());
}).then( }).then(
function() { function () {
comObj.postMessage({ comObj.postMessage({
sourceName, sourceName,
targetName, targetName,
@ -455,7 +455,7 @@ class MessageHandler {
success: true, success: true,
}); });
}, },
function(reason) { function (reason) {
comObj.postMessage({ comObj.postMessage({
sourceName, sourceName,
targetName, targetName,
@ -513,10 +513,10 @@ class MessageHandler {
break; break;
} }
const { onCancel } = this.streamSinks[data.streamId]; const { onCancel } = this.streamSinks[data.streamId];
new Promise(function(resolve) { new Promise(function (resolve) {
resolve(onCancel && onCancel(wrapReason(data.reason))); resolve(onCancel && onCancel(wrapReason(data.reason)));
}).then( }).then(
function() { function () {
comObj.postMessage({ comObj.postMessage({
sourceName, sourceName,
targetName, targetName,
@ -525,7 +525,7 @@ class MessageHandler {
success: true, success: true,
}); });
}, },
function(reason) { function (reason) {
comObj.postMessage({ comObj.postMessage({
sourceName, sourceName,
targetName, targetName,
@ -557,7 +557,7 @@ class MessageHandler {
this.streamControllers[streamId].startCall, this.streamControllers[streamId].startCall,
this.streamControllers[streamId].pullCall, this.streamControllers[streamId].pullCall,
this.streamControllers[streamId].cancelCall, this.streamControllers[streamId].cancelCall,
].map(function(capability) { ].map(function (capability) {
return capability && capability.promise; return capability && capability.promise;
}) })
); );

View File

@ -812,7 +812,7 @@ function isArrayEqual(arr1, arr2) {
if (arr1.length !== arr2.length) { if (arr1.length !== arr2.length) {
return false; return false;
} }
return arr1.every(function(element, index) { return arr1.every(function (element, index) {
return element === arr2[index]; return element === arr2[index];
}); });
} }
@ -842,12 +842,12 @@ function createPromiseCapability() {
return isSettled; return isSettled;
}, },
}); });
capability.promise = new Promise(function(resolve, reject) { capability.promise = new Promise(function (resolve, reject) {
capability.resolve = function(data) { capability.resolve = function (data) {
isSettled = true; isSettled = true;
resolve(data); resolve(data);
}; };
capability.reject = function(reason) { capability.reject = function (reason) {
isSettled = true; isSettled = true;
reject(reason); reject(reason);
}; };

View File

@ -17,9 +17,9 @@
// Patch importScripts to work around a bug in WebKit and Chrome 48-. // Patch importScripts to work around a bug in WebKit and Chrome 48-.
// See https://crbug.com/572225 and https://webkit.org/b/153317. // See https://crbug.com/572225 and https://webkit.org/b/153317.
self.importScripts = (function(importScripts) { self.importScripts = (function (importScripts) {
return function() { return function () {
setTimeout(function() {}, 0); setTimeout(function () {}, 0);
return importScripts.apply(this, arguments); return importScripts.apply(this, arguments);
}; };
})(importScripts); })(importScripts);
@ -27,6 +27,6 @@ self.importScripts = (function(importScripts) {
importScripts("../node_modules/systemjs/dist/system.js"); importScripts("../node_modules/systemjs/dist/system.js");
importScripts("../systemjs.config.js"); importScripts("../systemjs.config.js");
SystemJS.import("pdfjs/core/worker.js").then(function() { SystemJS.import("pdfjs/core/worker.js").then(function () {
// Worker is loaded at this point. // Worker is loaded at this point.
}); });

View File

@ -15,7 +15,7 @@
"use strict"; "use strict";
(function() { (function () {
var baseLocation; var baseLocation;
if (typeof document !== "undefined") { if (typeof document !== "undefined") {
baseLocation = new URL("./", document.currentScript.src); baseLocation = new URL("./", document.currentScript.src);

View File

@ -25,13 +25,13 @@ if (!fs.existsSync(file)) {
function calculateMD5(pdfFile, callback) { function calculateMD5(pdfFile, callback) {
var hash = crypto.createHash("md5"); var hash = crypto.createHash("md5");
var stream = fs.createReadStream(pdfFile); var stream = fs.createReadStream(pdfFile);
stream.on("data", function(data) { stream.on("data", function (data) {
hash.update(data); hash.update(data);
}); });
stream.on("error", function(err) { stream.on("error", function (err) {
callback(err); callback(err);
}); });
stream.on("end", function() { stream.on("end", function () {
var result = hash.digest("hex"); var result = hash.digest("hex");
callback(null, result); callback(null, result);
}); });

View File

@ -45,13 +45,13 @@ function createExtensionGlobal() {
window.chrome.extension.inIncognitoContext = false; window.chrome.extension.inIncognitoContext = false;
window.chrome.runtime = {}; window.chrome.runtime = {};
window.chrome.runtime.id = "oemmndcbldboiebfnladdacbdfmadadm"; window.chrome.runtime.id = "oemmndcbldboiebfnladdacbdfmadadm";
window.chrome.runtime.getManifest = function() { window.chrome.runtime.getManifest = function () {
return { version: "1.0.0" }; return { version: "1.0.0" };
}; };
function createStorageAPI() { function createStorageAPI() {
var storageArea = {}; var storageArea = {};
storageArea.get = function(key, callback) { storageArea.get = function (key, callback) {
assert.equal(key, "disableTelemetry"); assert.equal(key, "disableTelemetry");
// chrome.storage.*. is async, but we make it synchronous to ease testing. // chrome.storage.*. is async, but we make it synchronous to ease testing.
callback(storageArea.mock_data); callback(storageArea.mock_data);
@ -73,7 +73,7 @@ function createExtensionGlobal() {
var getRandomValues_state = 0; var getRandomValues_state = 0;
window.crypto = {}; window.crypto = {};
window.crypto.getRandomValues = function(buf) { window.crypto.getRandomValues = function (buf) {
var state = getRandomValues_state++; var state = getRandomValues_state++;
for (var i = 0; i < buf.length; ++i) { for (var i = 0; i < buf.length; ++i) {
// Totally random byte ;) // Totally random byte ;)
@ -89,38 +89,38 @@ function createExtensionGlobal() {
throw new TypeError("Illegal invocation"); throw new TypeError("Illegal invocation");
}, },
}; };
window.fetch = function(url, options) { window.fetch = function (url, options) {
assert.equal(url, LOG_URL); assert.equal(url, LOG_URL);
assert.equal(options.method, "POST"); assert.equal(options.method, "POST");
assert.equal(options.mode, "cors"); assert.equal(options.mode, "cors");
assert.ok(!options.body); assert.ok(!options.body);
test_requests.push(options.headers); test_requests.push(options.headers);
}; };
window.Headers = function(headers) { window.Headers = function (headers) {
headers = JSON.parse(JSON.stringify(headers)); // Clone. headers = JSON.parse(JSON.stringify(headers)); // Clone.
Object.keys(headers).forEach(function(k) { Object.keys(headers).forEach(function (k) {
headers[k] = String(headers[k]); headers[k] = String(headers[k]);
}); });
return headers; return headers;
}; };
window.XMLHttpRequest = function() { window.XMLHttpRequest = function () {
var invoked = { var invoked = {
open: false, open: false,
send: false, send: false,
}; };
var headers = {}; var headers = {};
return { return {
open: function(method, url) { open: function (method, url) {
assert.equal(invoked.open, false); assert.equal(invoked.open, false);
invoked.open = true; invoked.open = true;
assert.equal(method, "POST"); assert.equal(method, "POST");
assert.equal(url, LOG_URL); assert.equal(url, LOG_URL);
}, },
setRequestHeader: function(k, v) { setRequestHeader: function (k, v) {
assert.equal(invoked.open, true); assert.equal(invoked.open, true);
headers[k] = String(v); headers[k] = String(v);
}, },
send: function(body) { send: function (body) {
assert.equal(invoked.open, true); assert.equal(invoked.open, true);
assert.equal(invoked.send, false); assert.equal(invoked.send, false);
invoked.send = true; invoked.send = true;
@ -132,19 +132,19 @@ function createExtensionGlobal() {
// Time-related logic. // Time-related logic.
var timers = []; var timers = [];
window.setInterval = function(callback, ms) { window.setInterval = function (callback, ms) {
assert.equal(typeof callback, "function"); assert.equal(typeof callback, "function");
timers.push(callback); timers.push(callback);
}; };
window.Date = { window.Date = {
test_now_value: Date.now(), test_now_value: Date.now(),
now: function() { now: function () {
return window.Date.test_now_value; return window.Date.test_now_value;
}, },
}; };
window.test_fireTimers = function() { window.test_fireTimers = function () {
assert.ok(timers.length); assert.ok(timers.length);
timers.forEach(function(timer) { timers.forEach(function (timer) {
timer(); timer();
}); });
}; };
@ -156,7 +156,7 @@ function createExtensionGlobal() {
function updateBrowser(window) { function updateBrowser(window) {
window.navigator.userAgent = window.navigator.userAgent.replace( window.navigator.userAgent = window.navigator.userAgent.replace(
/Chrome\/(\d+)/, /Chrome\/(\d+)/,
function(_, v) { function (_, v) {
return "Chrome/" + (parseInt(v) + 1); return "Chrome/" + (parseInt(v) + 1);
} }
); );
@ -351,7 +351,7 @@ var tests = [
function test_extension_update() { function test_extension_update() {
var window = createExtensionGlobal(); var window = createExtensionGlobal();
telemetryScript.runInNewContext(window); telemetryScript.runInNewContext(window);
window.chrome.runtime.getManifest = function() { window.chrome.runtime.getManifest = function () {
return { version: "1.0.1" }; return { version: "1.0.1" };
}; };
window.Date.test_now_value += 12 * 36e5; window.Date.test_now_value += 12 * 36e5;
@ -373,7 +373,7 @@ var tests = [
var window = createExtensionGlobal(); var window = createExtensionGlobal();
var didWarn = false; var didWarn = false;
window.console = {}; window.console = {};
window.console.warn = function() { window.console.warn = function () {
didWarn = true; didWarn = true;
}; };
window.chrome.runtime.id = "abcdefghijklmnopabcdefghijklmnop"; window.chrome.runtime.id = "abcdefghijklmnopabcdefghijklmnop";
@ -413,7 +413,7 @@ var tests = [
function test_fetch_mode_not_supported() { function test_fetch_mode_not_supported() {
var window = createExtensionGlobal(); var window = createExtensionGlobal();
delete window.Request.prototype.mode; delete window.Request.prototype.mode;
window.fetch = function() { window.fetch = function () {
throw new Error("Unexpected call to fetch!"); throw new Error("Unexpected call to fetch!");
}; };
telemetryScript.runInNewContext(window); telemetryScript.runInNewContext(window);

View File

@ -40,7 +40,7 @@ function downloadFile(file, url, callback, redirects) {
var completed = false; var completed = false;
var protocol = /^https:\/\//.test(url) ? https : http; var protocol = /^https:\/\//.test(url) ? https : http;
protocol protocol
.get(url, function(response) { .get(url, function (response) {
var redirectTo; var redirectTo;
if ( if (
response.statusCode === 301 || response.statusCode === 301 ||
@ -71,14 +71,14 @@ function downloadFile(file, url, callback, redirects) {
return; return;
} }
var stream = fs.createWriteStream(file); var stream = fs.createWriteStream(file);
stream.on("error", function(err) { stream.on("error", function (err) {
if (!completed) { if (!completed) {
completed = true; completed = true;
callback(err); callback(err);
} }
}); });
response.pipe(stream); response.pipe(stream);
stream.on("finish", function() { stream.on("finish", function () {
stream.end(); stream.end();
if (!completed) { if (!completed) {
completed = true; completed = true;
@ -86,7 +86,7 @@ function downloadFile(file, url, callback, redirects) {
} }
}); });
}) })
.on("error", function(err) { .on("error", function (err) {
if (!completed) { if (!completed) {
if ( if (
typeof err === "object" && typeof err === "object" &&
@ -113,7 +113,7 @@ function downloadManifestFiles(manifest, callback) {
var file = links[i].file; var file = links[i].file;
var url = links[i].url; var url = links[i].url;
console.log("Downloading " + url + " to " + file + "..."); console.log("Downloading " + url + " to " + file + "...");
downloadFile(file, url, function(err) { downloadFile(file, url, function (err) {
if (err) { if (err) {
console.error("Error during downloading of " + url + ": " + err); console.error("Error during downloading of " + url + ": " + err);
fs.writeFileSync(file, ""); // making it empty file fs.writeFileSync(file, ""); // making it empty file
@ -125,10 +125,10 @@ function downloadManifestFiles(manifest, callback) {
} }
var links = manifest var links = manifest
.filter(function(item) { .filter(function (item) {
return item.link && !fs.existsSync(item.file); return item.link && !fs.existsSync(item.file);
}) })
.map(function(item) { .map(function (item) {
var file = item.file; var file = item.file;
var linkfile = file + ".link"; var linkfile = file + ".link";
var url = fs.readFileSync(linkfile).toString(); var url = fs.readFileSync(linkfile).toString();
@ -143,13 +143,13 @@ function downloadManifestFiles(manifest, callback) {
function calculateMD5(file, callback) { function calculateMD5(file, callback) {
var hash = crypto.createHash("md5"); var hash = crypto.createHash("md5");
var stream = fs.createReadStream(file); var stream = fs.createReadStream(file);
stream.on("data", function(data) { stream.on("data", function (data) {
hash.update(data); hash.update(data);
}); });
stream.on("error", function(err) { stream.on("error", function (err) {
callback(err); callback(err);
}); });
stream.on("end", function() { stream.on("end", function () {
var result = hash.digest("hex"); var result = hash.digest("hex");
callback(null, result); callback(null, result);
}); });
@ -171,7 +171,7 @@ function verifyManifestFiles(manifest, callback) {
verifyNext(); verifyNext();
return; return;
} }
calculateMD5(item.file, function(err, md5) { calculateMD5(item.file, function (err, md5) {
if (err) { if (err) {
console.log('WARNING: Unable to open file for reading "' + err + '".'); console.log('WARNING: Unable to open file for reading "' + err + '".');
error = true; error = true;

View File

@ -34,10 +34,10 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() {
if (textLayerStylePromise) { if (textLayerStylePromise) {
return textLayerStylePromise; return textLayerStylePromise;
} }
textLayerStylePromise = new Promise(function(resolve) { textLayerStylePromise = new Promise(function (resolve) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.open("GET", "./text_layer_test.css"); xhr.open("GET", "./text_layer_test.css");
xhr.onload = function() { xhr.onload = function () {
resolve(xhr.responseText); resolve(xhr.responseText);
}; };
xhr.send(null); xhr.send(null);
@ -52,7 +52,7 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() {
textContent, textContent,
enhanceTextSelection enhanceTextSelection
) { ) {
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
// Building SVG with size of the viewport. // Building SVG with size of the viewport.
var svg = document.createElementNS(SVG_NS, "svg:svg"); var svg = document.createElementNS(SVG_NS, "svg:svg");
svg.setAttribute("width", viewport.width + "px"); svg.setAttribute("width", viewport.width + "px");
@ -80,7 +80,7 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() {
viewport, viewport,
enhanceTextSelection, enhanceTextSelection,
}); });
Promise.all([stylePromise, task.promise]).then(function(results) { Promise.all([stylePromise, task.promise]).then(function (results) {
task.expandTextDivs(true); task.expandTextDivs(true);
style.textContent = results[0]; style.textContent = results[0];
svg.appendChild(foreignObject); svg.appendChild(foreignObject);
@ -91,11 +91,11 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() {
); );
var img = new Image(); var img = new Image();
img.src = "data:image/svg+xml;base64," + btoa(svg_xml); img.src = "data:image/svg+xml;base64," + btoa(svg_xml);
img.onload = function() { img.onload = function () {
ctx.drawImage(img, 0, 0); ctx.drawImage(img, 0, 0);
resolve(); resolve();
}; };
img.onerror = function(e) { img.onerror = function (e) {
reject(new Error("Error rasterizing text layer " + e)); reject(new Error("Error rasterizing text layer " + e));
}; };
}); });
@ -139,13 +139,13 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
// Load the style files and cache the results. // Load the style files and cache the results.
for (const key in styles) { for (const key in styles) {
styles[key].promise = new Promise(function(resolve, reject) { styles[key].promise = new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.open("GET", styles[key].file); xhr.open("GET", styles[key].file);
xhr.onload = function() { xhr.onload = function () {
resolve(xhr.responseText); resolve(xhr.responseText);
}; };
xhr.onerror = function(e) { xhr.onerror = function (e) {
reject(new Error("Error fetching annotation style " + e)); reject(new Error("Error fetching annotation style " + e));
}; };
xhr.send(null); xhr.send(null);
@ -158,17 +158,17 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
function inlineAnnotationImages(images) { function inlineAnnotationImages(images) {
var imagePromises = []; var imagePromises = [];
for (var i = 0, ii = images.length; i < ii; i++) { for (var i = 0, ii = images.length; i < ii; i++) {
var imagePromise = new Promise(function(resolve, reject) { var imagePromise = new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.responseType = "blob"; xhr.responseType = "blob";
xhr.onload = function() { xhr.onload = function () {
var reader = new FileReader(); var reader = new FileReader();
reader.onloadend = function() { reader.onloadend = function () {
resolve(reader.result); resolve(reader.result);
}; };
reader.readAsDataURL(xhr.response); reader.readAsDataURL(xhr.response);
}; };
xhr.onerror = function(e) { xhr.onerror = function (e) {
reject(new Error("Error fetching inline annotation image " + e)); reject(new Error("Error fetching inline annotation image " + e));
}; };
xhr.open("GET", images[i].src); xhr.open("GET", images[i].src);
@ -188,7 +188,7 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
imageResourcesPath, imageResourcesPath,
renderInteractiveForms renderInteractiveForms
) { ) {
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
// Building SVG with size of the viewport. // Building SVG with size of the viewport.
var svg = document.createElementNS(SVG_NS, "svg:svg"); var svg = document.createElementNS(SVG_NS, "svg:svg");
svg.setAttribute("width", viewport.width + "px"); svg.setAttribute("width", viewport.width + "px");
@ -207,7 +207,7 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
div.className = "annotationLayer"; div.className = "annotationLayer";
// Rendering annotation layer as HTML. // Rendering annotation layer as HTML.
stylePromise.then(function(common, overrides) { stylePromise.then(function (common, overrides) {
style.textContent = common + overrides; style.textContent = common + overrides;
var annotation_viewport = viewport.clone({ dontFlip: true }); var annotation_viewport = viewport.clone({ dontFlip: true });
@ -225,14 +225,14 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
// Inline SVG images from text annotations. // Inline SVG images from text annotations.
var images = div.getElementsByTagName("img"); var images = div.getElementsByTagName("img");
var imagePromises = inlineAnnotationImages(images); var imagePromises = inlineAnnotationImages(images);
var converted = Promise.all(imagePromises).then(function(data) { var converted = Promise.all(imagePromises).then(function (data) {
var loadedPromises = []; var loadedPromises = [];
for (var i = 0, ii = data.length; i < ii; i++) { for (var i = 0, ii = data.length; i < ii; i++) {
images[i].src = data[i]; images[i].src = data[i];
loadedPromises.push( loadedPromises.push(
new Promise(function(resolveImage, rejectImage) { new Promise(function (resolveImage, rejectImage) {
images[i].onload = resolveImage; images[i].onload = resolveImage;
images[i].onerror = function(e) { images[i].onerror = function (e) {
rejectImage(new Error("Error loading image " + e)); rejectImage(new Error("Error loading image " + e));
}; };
}) })
@ -245,17 +245,17 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
svg.appendChild(foreignObject); svg.appendChild(foreignObject);
// We need to have UTF-8 encoded XML. // We need to have UTF-8 encoded XML.
converted.then(function() { converted.then(function () {
var svg_xml = unescape( var svg_xml = unescape(
encodeURIComponent(new XMLSerializer().serializeToString(svg)) encodeURIComponent(new XMLSerializer().serializeToString(svg))
); );
var img = new Image(); var img = new Image();
img.src = "data:image/svg+xml;base64," + btoa(svg_xml); img.src = "data:image/svg+xml;base64," + btoa(svg_xml);
img.onload = function() { img.onload = function () {
ctx.drawImage(img, 0, 0); ctx.drawImage(img, 0, 0);
resolve(); resolve();
}; };
img.onerror = function(e) { img.onerror = function (e) {
reject(new Error("Error rasterizing annotation layer " + e)); reject(new Error("Error rasterizing annotation layer " + e));
}; };
}); });
@ -325,7 +325,7 @@ var Driver = (function DriverClosure() {
run: function Driver_run() { run: function Driver_run() {
var self = this; var self = this;
window.onerror = function(message, source, line, column, error) { window.onerror = function (message, source, line, column, error) {
self._info( self._info(
"Error: " + "Error: " +
message + message +
@ -351,12 +351,12 @@ var Driver = (function DriverClosure() {
var r = new XMLHttpRequest(); var r = new XMLHttpRequest();
r.open("GET", this.manifestFile, false); r.open("GET", this.manifestFile, false);
r.onreadystatechange = function() { r.onreadystatechange = function () {
if (r.readyState === 4) { if (r.readyState === 4) {
self._log("done\n"); self._log("done\n");
self.manifest = JSON.parse(r.responseText); self.manifest = JSON.parse(r.responseText);
if (self.testFilter && self.testFilter.length) { if (self.testFilter && self.testFilter.length) {
self.manifest = self.manifest.filter(function(item) { self.manifest = self.manifest.filter(function (item) {
return self.testFilter.includes(item.id); return self.testFilter.includes(item.id);
}); });
} }
@ -369,7 +369,7 @@ var Driver = (function DriverClosure() {
} }
// When gathering the stats the numbers seem to be more reliable // When gathering the stats the numbers seem to be more reliable
// if the browser is given more time to start. // if the browser is given more time to start.
setTimeout(function() { setTimeout(function () {
r.send(null); r.send(null);
}, this.delay); }, this.delay);
}, },
@ -472,7 +472,7 @@ var Driver = (function DriverClosure() {
if (!task.pdfDoc) { if (!task.pdfDoc) {
var dataUrl = this.canvas.toDataURL("image/png"); var dataUrl = this.canvas.toDataURL("image/png");
this._sendResult(dataUrl, task, failure, function() { this._sendResult(dataUrl, task, failure, function () {
self._log( self._log(
"done" + (failure ? " (failed !: " + failure + ")" : "") + "\n" "done" + (failure ? " (failed !: " + failure + ")" : "") + "\n"
); );
@ -518,7 +518,7 @@ var Driver = (function DriverClosure() {
this.canvas.mozOpaque = true; this.canvas.mozOpaque = true;
ctx = this.canvas.getContext("2d", { alpha: false }); ctx = this.canvas.getContext("2d", { alpha: false });
task.pdfDoc.getPage(task.pageNum).then( task.pdfDoc.getPage(task.pageNum).then(
function(page) { function (page) {
var viewport = page.getViewport({ scale: PDF_TO_CSS_UNITS }); var viewport = page.getViewport({ scale: PDF_TO_CSS_UNITS });
self.canvas.width = viewport.width; self.canvas.width = viewport.width;
self.canvas.height = viewport.height; self.canvas.height = viewport.height;
@ -552,7 +552,7 @@ var Driver = (function DriverClosure() {
.getTextContent({ .getTextContent({
normalizeWhitespace: true, normalizeWhitespace: true,
}) })
.then(function(textContent) { .then(function (textContent) {
return rasterizeTextLayer( return rasterizeTextLayer(
textLayerContext, textLayerContext,
viewport, viewport,
@ -590,7 +590,7 @@ var Driver = (function DriverClosure() {
// The annotation builder will draw its content on the canvas. // The annotation builder will draw its content on the canvas.
initPromise = page initPromise = page
.getAnnotations({ intent: "display" }) .getAnnotations({ intent: "display" })
.then(function(annotations) { .then(function (annotations) {
return rasterizeAnnotationLayer( return rasterizeAnnotationLayer(
annotationLayerContext, annotationLayerContext,
viewport, viewport,
@ -611,7 +611,7 @@ var Driver = (function DriverClosure() {
viewport, viewport,
renderInteractiveForms: renderForms, renderInteractiveForms: renderForms,
}; };
var completeRender = function(error) { var completeRender = function (error) {
// if text layer is present, compose it on top of the page // if text layer is present, compose it on top of the page
if (textLayerCanvas) { if (textLayerCanvas) {
ctx.save(); ctx.save();
@ -633,16 +633,16 @@ var Driver = (function DriverClosure() {
self._snapshot(task, error); self._snapshot(task, error);
}; };
initPromise initPromise
.then(function() { .then(function () {
return page.render(renderContext).promise.then(function() { return page.render(renderContext).promise.then(function () {
completeRender(false); completeRender(false);
}); });
}) })
.catch(function(error) { .catch(function (error) {
completeRender("render : " + error); completeRender("render : " + error);
}); });
}, },
function(error) { function (error) {
self._snapshot(task, "render : " + error); self._snapshot(task, "render : " + error);
} }
); );
@ -664,7 +664,7 @@ var Driver = (function DriverClosure() {
this._log("Snapshotting... "); this._log("Snapshotting... ");
var dataUrl = this.canvas.toDataURL("image/png"); var dataUrl = this.canvas.toDataURL("image/png");
this._sendResult(dataUrl, task, failure, function() { this._sendResult(dataUrl, task, failure, function () {
self._log( self._log(
"done" + (failure ? " (failed !: " + failure + ")" : "") + "\n" "done" + (failure ? " (failed !: " + failure + ")" : "") + "\n"
); );
@ -680,7 +680,7 @@ var Driver = (function DriverClosure() {
// Send the quit request // Send the quit request
var r = new XMLHttpRequest(); var r = new XMLHttpRequest();
r.open("POST", "/tellMeToQuit?path=" + escape(this.appPath), false); r.open("POST", "/tellMeToQuit?path=" + escape(this.appPath), false);
r.onreadystatechange = function(e) { r.onreadystatechange = function (e) {
if (r.readyState === 4) { if (r.readyState === 4) {
window.close(); window.close();
} }
@ -744,13 +744,13 @@ var Driver = (function DriverClosure() {
var r = new XMLHttpRequest(); var r = new XMLHttpRequest();
r.open("POST", url, true); r.open("POST", url, true);
r.setRequestHeader("Content-Type", "application/json"); r.setRequestHeader("Content-Type", "application/json");
r.onreadystatechange = function(e) { r.onreadystatechange = function (e) {
if (r.readyState === 4) { if (r.readyState === 4) {
self.inFlightRequests--; self.inFlightRequests--;
// Retry until successful // Retry until successful
if (r.status !== 200) { if (r.status !== 200) {
setTimeout(function() { setTimeout(function () {
self._send(url, message); self._send(url, message);
}); });
} }

View File

@ -46,7 +46,7 @@ function initializePDFJS(callback) {
SystemJS.import("pdfjs/core/stream.js"), SystemJS.import("pdfjs/core/stream.js"),
SystemJS.import("pdfjs/core/primitives.js"), SystemJS.import("pdfjs/core/primitives.js"),
SystemJS.import("pdfjs/core/cmap.js"), SystemJS.import("pdfjs/core/cmap.js"),
]).then(function(modules) { ]).then(function (modules) {
var fonts = modules[0], var fonts = modules[0],
stream = modules[1], stream = modules[1],
primitives = modules[2], primitives = modules[2],
@ -62,7 +62,7 @@ function initializePDFJS(callback) {
}); });
} }
(function() { (function () {
window.jasmine = jasmineRequire.core(jasmineRequire); window.jasmine = jasmineRequire.core(jasmineRequire);
jasmineRequire.html(jasmine); jasmineRequire.html(jasmine);
@ -134,7 +134,7 @@ function initializePDFJS(callback) {
}, },
}); });
config.specFilter = function(spec) { config.specFilter = function (spec) {
return specFilter.matches(spec.getFullName()); return specFilter.matches(spec.getFullName());
}; };
@ -148,12 +148,12 @@ function initializePDFJS(callback) {
// instance and then executing the loaded Jasmine environment. // instance and then executing the loaded Jasmine environment.
var currentWindowOnload = window.onload; var currentWindowOnload = window.onload;
window.onload = function() { window.onload = function () {
if (currentWindowOnload) { if (currentWindowOnload) {
currentWindowOnload(); currentWindowOnload();
} }
initializePDFJS(function() { initializePDFJS(function () {
htmlReporter.initialize(); htmlReporter.initialize();
env.execute(); env.execute();
}); });

View File

@ -25,9 +25,9 @@ var ttxResourcesHome = path.join(__dirname, "..", "ttx");
var nextTTXTaskId = Date.now(); var nextTTXTaskId = Date.now();
function runTtx(ttxResourcesHomePath, fontPath, registerOnCancel, callback) { function runTtx(ttxResourcesHomePath, fontPath, registerOnCancel, callback) {
fs.realpath(ttxResourcesHomePath, function(error, realTtxResourcesHomePath) { fs.realpath(ttxResourcesHomePath, function (error, realTtxResourcesHomePath) {
var fontToolsHome = path.join(realTtxResourcesHomePath, "fonttools-code"); var fontToolsHome = path.join(realTtxResourcesHomePath, "fonttools-code");
fs.realpath(fontPath, function(errorFontPath, realFontPath) { fs.realpath(fontPath, function (errorFontPath, realFontPath) {
var ttxPath = path.join("Tools", "ttx"); var ttxPath = path.join("Tools", "ttx");
if (!fs.existsSync(path.join(fontToolsHome, ttxPath))) { if (!fs.existsSync(path.join(fontToolsHome, ttxPath))) {
callback("TTX was not found, please checkout PDF.js submodules"); callback("TTX was not found, please checkout PDF.js submodules");
@ -44,16 +44,16 @@ function runTtx(ttxResourcesHomePath, fontPath, registerOnCancel, callback) {
env: ttxEnv, env: ttxEnv,
}); });
var ttxRunError; var ttxRunError;
registerOnCancel(function(reason) { registerOnCancel(function (reason) {
ttxRunError = reason; ttxRunError = reason;
callback(reason); callback(reason);
ttx.kill(); ttx.kill();
}); });
ttx.on("error", function(errorTtx) { ttx.on("error", function (errorTtx) {
ttxRunError = errorTtx; ttxRunError = errorTtx;
callback("Unable to execute ttx"); callback("Unable to execute ttx");
}); });
ttx.on("close", function(code) { ttx.on("close", function (code) {
if (ttxRunError) { if (ttxRunError) {
return; return;
} }
@ -74,7 +74,7 @@ exports.translateFont = function translateFont(
var resultPath = path.join(ttxResourcesHome, taskId + ".ttx"); var resultPath = path.join(ttxResourcesHome, taskId + ".ttx");
fs.writeFileSync(fontPath, buffer); fs.writeFileSync(fontPath, buffer);
runTtx(ttxResourcesHome, fontPath, registerOnCancel, function(err) { runTtx(ttxResourcesHome, fontPath, registerOnCancel, function (err) {
fs.unlinkSync(fontPath); fs.unlinkSync(fontPath);
if (err) { if (err) {
console.error(err); console.error(err);

View File

@ -57,8 +57,8 @@ function group(stats, groupBy) {
*/ */
function flatten(stats) { function flatten(stats) {
var rows = []; var rows = [];
stats.forEach(function(curStat) { stats.forEach(function (curStat) {
curStat["stats"].forEach(function(s) { curStat["stats"].forEach(function (s) {
rows.push({ rows.push({
browser: curStat["browser"], browser: curStat["browser"],
page: curStat["page"], page: curStat["page"],
@ -71,7 +71,7 @@ function flatten(stats) {
}); });
// Use only overall results if not grouped by 'stat' // Use only overall results if not grouped by 'stat'
if (!options.groupBy.includes("stat")) { if (!options.groupBy.includes("stat")) {
rows = rows.filter(function(s) { rows = rows.filter(function (s) {
return s.stat === "Overall"; return s.stat === "Overall";
}); });
} }
@ -138,7 +138,7 @@ function stat(baseline, current) {
row, row,
rows = []; rows = [];
// collect rows and measure column widths // collect rows and measure column widths
var width = labels.map(function(s) { var width = labels.map(function (s) {
return s.length; return s.length;
}); });
rows.push(labels); rows.push(labels);
@ -172,7 +172,7 @@ function stat(baseline, current) {
} }
// add horizontal line // add horizontal line
var hline = width.map(function(w) { var hline = width.map(function (w) {
return new Array(w + 1).join("-"); return new Array(w + 1).join("-");
}); });
rows.splice(1, 0, hline); rows.splice(1, 0, hline);

View File

@ -27,7 +27,7 @@ var testUtils = require("./testutils.js");
function parseOptions() { function parseOptions() {
function describeCheck(fn, text) { function describeCheck(fn, text) {
fn.toString = function() { fn.toString = function () {
return text; return text;
}; };
return fn; return fn;
@ -102,7 +102,7 @@ function parseOptions() {
) )
.default("statsDelay", 0) .default("statsDelay", 0)
.check( .check(
describeCheck(function(argv) { describeCheck(function (argv) {
return ( return (
+argv.reftest + argv.unitTest + argv.fontTest + argv.masterMode <= 1 +argv.reftest + argv.unitTest + argv.fontTest + argv.masterMode <= 1
); );
@ -110,18 +110,18 @@ function parseOptions() {
"specified at the same time.") "specified at the same time.")
) )
.check( .check(
describeCheck(function(argv) { describeCheck(function (argv) {
return !argv.noDownload || !argv.downloadOnly; return !argv.noDownload || !argv.downloadOnly;
}, "--noDownload and --downloadOnly cannot be used together.") }, "--noDownload and --downloadOnly cannot be used together.")
) )
.check( .check(
describeCheck(function(argv) { describeCheck(function (argv) {
return !argv.masterMode || argv.manifestFile === "test_manifest.json"; return !argv.masterMode || argv.manifestFile === "test_manifest.json";
}, "when --masterMode is specified --manifestFile shall be equal " + }, "when --masterMode is specified --manifestFile shall be equal " +
"test_manifest.json") "test_manifest.json")
) )
.check( .check(
describeCheck(function(argv) { describeCheck(function (argv) {
return !argv.browser || !argv.browserManifestFile; return !argv.browser || !argv.browserManifestFile;
}, "--browser and --browserManifestFile must not be specified at the " + }, "--browser and --browserManifestFile must not be specified at the " +
"same time.") "same time.")
@ -151,7 +151,7 @@ function monitorBrowserTimeout(session, onTimeout) {
session.timeoutMonitor = null; session.timeoutMonitor = null;
return; return;
} }
session.timeoutMonitor = setTimeout(function() { session.timeoutMonitor = setTimeout(function () {
onTimeout(session); onTimeout(session);
}, browserTimeout * 1000); }, browserTimeout * 1000);
} }
@ -172,7 +172,7 @@ function updateRefImages() {
} }
testUtils.confirm( testUtils.confirm(
"Would you like to update the master copy in ref/? [yn] ", "Would you like to update the master copy in ref/? [yn] ",
function(confirmed) { function (confirmed) {
if (confirmed) { if (confirmed) {
sync(true); sync(true);
} else { } else {
@ -203,7 +203,7 @@ function startRefTest(masterMode, showRefImages) {
var numFBFFailures = 0; var numFBFFailures = 0;
var numEqFailures = 0; var numEqFailures = 0;
var numEqNoSnapshot = 0; var numEqNoSnapshot = 0;
sessions.forEach(function(session) { sessions.forEach(function (session) {
numErrors += session.numErrors; numErrors += session.numErrors;
numFBFFailures += session.numFBFFailures; numFBFFailures += session.numFBFFailures;
numEqFailures += session.numEqFailures; numEqFailures += session.numEqFailures;
@ -274,12 +274,12 @@ function startRefTest(masterMode, showRefImages) {
server.hooks["POST"].push(refTestPostHandler); server.hooks["POST"].push(refTestPostHandler);
onAllSessionsClosed = finalize; onAllSessionsClosed = finalize;
startBrowsers("/test/test_slave.html", function(session) { startBrowsers("/test/test_slave.html", function (session) {
session.masterMode = masterMode; session.masterMode = masterMode;
session.taskResults = {}; session.taskResults = {};
session.tasks = {}; session.tasks = {};
session.remaining = manifest.length; session.remaining = manifest.length;
manifest.forEach(function(item) { manifest.forEach(function (item) {
var rounds = item.rounds || 1; var rounds = item.rounds || 1;
var roundsResults = []; var roundsResults = [];
roundsResults.length = rounds; roundsResults.length = rounds;
@ -304,7 +304,7 @@ function startRefTest(masterMode, showRefImages) {
console.log("tmp/ can be removed if it has nothing you need."); console.log("tmp/ can be removed if it has nothing you need.");
testUtils.confirm( testUtils.confirm(
"SHOULD THIS SCRIPT REMOVE tmp/? THINK CAREFULLY [yn] ", "SHOULD THIS SCRIPT REMOVE tmp/? THINK CAREFULLY [yn] ",
function(confirmed) { function (confirmed) {
if (confirmed) { if (confirmed) {
testUtils.removeDirSync(refsTmpDir); testUtils.removeDirSync(refsTmpDir);
} }
@ -350,7 +350,7 @@ function getTestManifest() {
var testFilter = options.testfilter.slice(0); var testFilter = options.testfilter.slice(0);
if (testFilter.length) { if (testFilter.length) {
manifest = manifest.filter(function(item) { manifest = manifest.filter(function (item) {
var i = testFilter.indexOf(item.id); var i = testFilter.indexOf(item.id);
if (i !== -1) { if (i !== -1) {
testFilter.splice(i, 1); testFilter.splice(i, 1);
@ -533,8 +533,8 @@ function checkRefTestResults(browser, id, results) {
var failed = false; var failed = false;
var session = getSession(browser); var session = getSession(browser);
var task = session.tasks[id]; var task = session.tasks[id];
results.forEach(function(roundResults, round) { results.forEach(function (roundResults, round) {
roundResults.forEach(function(pageResult, page) { roundResults.forEach(function (pageResult, page) {
if (!pageResult) { if (!pageResult) {
return; // no results return; // no results
} }
@ -589,8 +589,8 @@ function checkRefTestResults(browser, id, results) {
throw new Error("Unknown test type"); throw new Error("Unknown test type");
} }
// clear memory // clear memory
results.forEach(function(roundResults, round) { results.forEach(function (roundResults, round) {
roundResults.forEach(function(pageResult, page) { roundResults.forEach(function (pageResult, page) {
pageResult.snapshot = null; pageResult.snapshot = null;
}); });
}); });
@ -608,10 +608,10 @@ function refTestPostHandler(req, res) {
} }
var body = ""; var body = "";
req.on("data", function(data) { req.on("data", function (data) {
body += data; body += data;
}); });
req.on("end", function() { req.on("end", function () {
res.writeHead(200, { "Content-Type": "text/plain" }); res.writeHead(200, { "Content-Type": "text/plain" });
res.end(); res.end();
@ -619,7 +619,7 @@ function refTestPostHandler(req, res) {
if (pathname === "/tellMeToQuit") { if (pathname === "/tellMeToQuit") {
// finding by path // finding by path
var browserPath = parsedUrl.query.path; var browserPath = parsedUrl.query.path;
session = sessions.filter(function(curSession) { session = sessions.filter(function (curSession) {
return curSession.config.path === browserPath; return curSession.config.path === browserPath;
})[0]; })[0];
monitorBrowserTimeout(session, null); monitorBrowserTimeout(session, null);
@ -693,11 +693,11 @@ function startUnitTest(testUrl, name) {
var startTime = Date.now(); var startTime = Date.now();
startServer(); startServer();
server.hooks["POST"].push(unitTestPostHandler); server.hooks["POST"].push(unitTestPostHandler);
onAllSessionsClosed = function() { onAllSessionsClosed = function () {
stopServer(); stopServer();
var numRuns = 0, var numRuns = 0,
numErrors = 0; numErrors = 0;
sessions.forEach(function(session) { sessions.forEach(function (session) {
numRuns += session.numRuns; numRuns += session.numRuns;
numErrors += session.numErrors; numErrors += session.numErrors;
}); });
@ -712,7 +712,7 @@ function startUnitTest(testUrl, name) {
var runtime = (Date.now() - startTime) / 1000; var runtime = (Date.now() - startTime) / 1000;
console.log(name + " tests runtime was " + runtime.toFixed(1) + " seconds"); console.log(name + " tests runtime was " + runtime.toFixed(1) + " seconds");
}; };
startBrowsers(testUrl, function(session) { startBrowsers(testUrl, function (session) {
session.numRuns = 0; session.numRuns = 0;
session.numErrors = 0; session.numErrors = 0;
}); });
@ -731,25 +731,25 @@ function unitTestPostHandler(req, res) {
} }
var body = ""; var body = "";
req.on("data", function(data) { req.on("data", function (data) {
body += data; body += data;
}); });
req.on("end", function() { req.on("end", function () {
if (pathname === "/ttx") { if (pathname === "/ttx") {
var translateFont = require("./font/ttxdriver.js").translateFont; var translateFont = require("./font/ttxdriver.js").translateFont;
var onCancel = null, var onCancel = null,
ttxTimeout = 10000; ttxTimeout = 10000;
var timeoutId = setTimeout(function() { var timeoutId = setTimeout(function () {
if (onCancel) { if (onCancel) {
onCancel("TTX timeout"); onCancel("TTX timeout");
} }
}, ttxTimeout); }, ttxTimeout);
translateFont( translateFont(
body, body,
function(fn) { function (fn) {
onCancel = fn; onCancel = fn;
}, },
function(err, xml) { function (err, xml) {
clearTimeout(timeoutId); clearTimeout(timeoutId);
res.writeHead(200, { "Content-Type": "text/xml" }); res.writeHead(200, { "Content-Type": "text/xml" });
res.end(err ? "<error>" + err + "</error>" : xml); res.end(err ? "<error>" + err + "</error>" : xml);
@ -797,7 +797,7 @@ function startBrowsers(testUrl, initSessionCallback) {
process.exit(1); process.exit(1);
} }
sessions = []; sessions = [];
browsers.forEach(function(b) { browsers.forEach(function (b) {
var browser = WebBrowser.create(b); var browser = WebBrowser.create(b);
var startUrl = var startUrl =
getServerBaseAddress() + getServerBaseAddress() +
@ -846,7 +846,7 @@ function stopServer() {
} }
function getSession(browser) { function getSession(browser) {
return sessions.filter(function(session) { return sessions.filter(function (session) {
return session.name === browser; return session.name === browser;
})[0]; })[0];
} }
@ -858,9 +858,9 @@ function closeSession(browser) {
} }
if (i < sessions.length) { if (i < sessions.length) {
var session = sessions[i]; var session = sessions[i];
session.browser.stop(function() { session.browser.stop(function () {
session.closed = true; session.closed = true;
var allClosed = sessions.every(function(s) { var allClosed = sessions.every(function (s) {
return s.closed; return s.closed;
}); });
if (allClosed && onAllSessionsClosed) { if (allClosed && onAllSessionsClosed) {
@ -873,8 +873,8 @@ function closeSession(browser) {
function ensurePDFsDownloaded(callback) { function ensurePDFsDownloaded(callback) {
var downloadUtils = require("./downloadutils.js"); var downloadUtils = require("./downloadutils.js");
var manifest = getTestManifest(); var manifest = getTestManifest();
downloadUtils.downloadManifestFiles(manifest, function() { downloadUtils.downloadManifestFiles(manifest, function () {
downloadUtils.verifyManifestFiles(manifest, function(hasErrors) { downloadUtils.verifyManifestFiles(manifest, function (hasErrors) {
if (hasErrors) { if (hasErrors) {
console.log( console.log(
"Unable to verify the checksum for the files that are " + "Unable to verify the checksum for the files that are " +
@ -899,12 +899,12 @@ function main() {
} }
if (options.downloadOnly) { if (options.downloadOnly) {
ensurePDFsDownloaded(function() {}); ensurePDFsDownloaded(function () {});
} else if (!options.browser && !options.browserManifestFile) { } else if (!options.browser && !options.browserManifestFile) {
startServer(); startServer();
} else if (options.unitTest) { } else if (options.unitTest) {
// Allows linked PDF files in unit-tests as well. // Allows linked PDF files in unit-tests as well.
ensurePDFsDownloaded(function() { ensurePDFsDownloaded(function () {
startUnitTest("/test/unit/unit_test.html", "unit"); startUnitTest("/test/unit/unit_test.html", "unit");
}); });
} else if (options.fontTest) { } else if (options.fontTest) {

View File

@ -32,7 +32,7 @@ exports.copySubtreeSync = function copySubtreeSync(src, dest) {
if (!fs.existsSync(dest)) { if (!fs.existsSync(dest)) {
fs.mkdirSync(dest); fs.mkdirSync(dest);
} }
files.forEach(function(filename) { files.forEach(function (filename) {
var srcFile = path.join(src, filename); var srcFile = path.join(src, filename);
var file = path.join(dest, filename); var file = path.join(dest, filename);
var stats = fs.statSync(srcFile); var stats = fs.statSync(srcFile);
@ -99,12 +99,12 @@ function handleStdinBuffer() {
function initStdin() { function initStdin() {
process.stdin.setEncoding("utf8"); process.stdin.setEncoding("utf8");
process.stdin.on("data", function(chunk) { process.stdin.on("data", function (chunk) {
stdinBuffer += chunk; stdinBuffer += chunk;
handleStdinBuffer(); handleStdinBuffer();
}); });
process.stdin.on("end", function() { process.stdin.on("end", function () {
endOfStdin = true; endOfStdin = true;
handleStdinBuffer(); handleStdinBuffer();
}); });
@ -125,7 +125,7 @@ exports.prompt = function prompt(message, callback) {
}; };
exports.confirm = function confirm(message, callback) { exports.confirm = function confirm(message, callback) {
exports.prompt(message, function(answer) { exports.prompt(message, function (answer) {
if (answer === undefined) { if (answer === undefined) {
callback(); callback();
return; return;

View File

@ -33,14 +33,14 @@ import { Dict, Name, Ref } from "../../src/core/primitives.js";
import { Lexer, Parser } from "../../src/core/parser.js"; import { Lexer, Parser } from "../../src/core/parser.js";
import { StringStream } from "../../src/core/stream.js"; import { StringStream } from "../../src/core/stream.js";
describe("annotation", function() { describe("annotation", function () {
class PDFManagerMock { class PDFManagerMock {
constructor(params) { constructor(params) {
this.docBaseUrl = params.docBaseUrl || null; this.docBaseUrl = params.docBaseUrl || null;
} }
ensure(obj, prop, args) { ensure(obj, prop, args) {
return new Promise(function(resolve) { return new Promise(function (resolve) {
const value = obj[prop]; const value = obj[prop];
if (typeof value === "function") { if (typeof value === "function") {
resolve(value.apply(obj, args)); resolve(value.apply(obj, args));
@ -53,7 +53,7 @@ describe("annotation", function() {
let pdfManagerMock, idFactoryMock; let pdfManagerMock, idFactoryMock;
beforeAll(function(done) { beforeAll(function (done) {
pdfManagerMock = new PDFManagerMock({ pdfManagerMock = new PDFManagerMock({
docBaseUrl: null, docBaseUrl: null,
}); });
@ -61,13 +61,13 @@ describe("annotation", function() {
done(); done();
}); });
afterAll(function() { afterAll(function () {
pdfManagerMock = null; pdfManagerMock = null;
idFactoryMock = null; idFactoryMock = null;
}); });
describe("AnnotationFactory", function() { describe("AnnotationFactory", function () {
it("should get id for annotation", function(done) { it("should get id for annotation", function (done) {
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link")); annotationDict.set("Subtype", Name.get("Link"));
@ -90,7 +90,7 @@ describe("annotation", function() {
it( it(
"should handle, and get fallback IDs for, annotations that are not " + "should handle, and get fallback IDs for, annotations that are not " +
"indirect objects (issue 7569)", "indirect objects (issue 7569)",
function(done) { function (done) {
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link")); annotationDict.set("Subtype", Name.get("Link"));
@ -122,7 +122,7 @@ describe("annotation", function() {
} }
); );
it("should handle missing /Subtype", function(done) { it("should handle missing /Subtype", function (done) {
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
@ -141,35 +141,35 @@ describe("annotation", function() {
}); });
}); });
describe("getQuadPoints", function() { describe("getQuadPoints", function () {
let dict, rect; let dict, rect;
beforeEach(function(done) { beforeEach(function (done) {
dict = new Dict(); dict = new Dict();
rect = []; rect = [];
done(); done();
}); });
afterEach(function() { afterEach(function () {
dict = null; dict = null;
rect = null; rect = null;
}); });
it("should ignore missing quadpoints", function() { it("should ignore missing quadpoints", function () {
expect(getQuadPoints(dict, rect)).toEqual(null); expect(getQuadPoints(dict, rect)).toEqual(null);
}); });
it("should ignore non-array values", function() { it("should ignore non-array values", function () {
dict.set("QuadPoints", "foo"); dict.set("QuadPoints", "foo");
expect(getQuadPoints(dict, rect)).toEqual(null); expect(getQuadPoints(dict, rect)).toEqual(null);
}); });
it("should ignore arrays where the length is not a multiple of eight", function() { it("should ignore arrays where the length is not a multiple of eight", function () {
dict.set("QuadPoints", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); dict.set("QuadPoints", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
expect(getQuadPoints(dict, rect)).toEqual(null); expect(getQuadPoints(dict, rect)).toEqual(null);
}); });
it("should ignore quadpoints if one coordinate lies outside the rectangle", function() { it("should ignore quadpoints if one coordinate lies outside the rectangle", function () {
rect = [10, 10, 20, 20]; rect = [10, 10, 20, 20];
const inputs = [ const inputs = [
[11, 11, 12, 12, 9, 13, 14, 14], // Smaller than lower x coordinate. [11, 11, 12, 12, 9, 13, 14, 14], // Smaller than lower x coordinate.
@ -183,7 +183,7 @@ describe("annotation", function() {
} }
}); });
it("should process valid quadpoints arrays", function() { it("should process valid quadpoints arrays", function () {
rect = [10, 10, 20, 20]; rect = [10, 10, 20, 20];
dict.set("QuadPoints", [ dict.set("QuadPoints", [
11, 11,
@ -220,48 +220,48 @@ describe("annotation", function() {
}); });
}); });
describe("Annotation", function() { describe("Annotation", function () {
let dict, ref; let dict, ref;
beforeAll(function(done) { beforeAll(function (done) {
dict = new Dict(); dict = new Dict();
ref = Ref.get(1, 0); ref = Ref.get(1, 0);
done(); done();
}); });
afterAll(function() { afterAll(function () {
dict = ref = null; dict = ref = null;
}); });
it("should set and get valid contents", function() { it("should set and get valid contents", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setContents("Foo bar baz"); annotation.setContents("Foo bar baz");
expect(annotation.contents).toEqual("Foo bar baz"); expect(annotation.contents).toEqual("Foo bar baz");
}); });
it("should not set and get invalid contents", function() { it("should not set and get invalid contents", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setContents(undefined); annotation.setContents(undefined);
expect(annotation.contents).toEqual(""); expect(annotation.contents).toEqual("");
}); });
it("should set and get a valid modification date", function() { it("should set and get a valid modification date", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setModificationDate("D:20190422"); annotation.setModificationDate("D:20190422");
expect(annotation.modificationDate).toEqual("D:20190422"); expect(annotation.modificationDate).toEqual("D:20190422");
}); });
it("should not set and get an invalid modification date", function() { it("should not set and get an invalid modification date", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setModificationDate(undefined); annotation.setModificationDate(undefined);
expect(annotation.modificationDate).toEqual(null); expect(annotation.modificationDate).toEqual(null);
}); });
it("should set and get flags", function() { it("should set and get flags", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setFlags(13); annotation.setFlags(13);
@ -271,63 +271,63 @@ describe("annotation", function() {
expect(annotation.hasFlag(AnnotationFlag.READONLY)).toEqual(false); expect(annotation.hasFlag(AnnotationFlag.READONLY)).toEqual(false);
}); });
it("should be viewable and not printable by default", function() { it("should be viewable and not printable by default", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
expect(annotation.viewable).toEqual(true); expect(annotation.viewable).toEqual(true);
expect(annotation.printable).toEqual(false); expect(annotation.printable).toEqual(false);
}); });
it("should set and get a valid rectangle", function() { it("should set and get a valid rectangle", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setRectangle([117, 694, 164.298, 720]); annotation.setRectangle([117, 694, 164.298, 720]);
expect(annotation.rectangle).toEqual([117, 694, 164.298, 720]); expect(annotation.rectangle).toEqual([117, 694, 164.298, 720]);
}); });
it("should not set and get an invalid rectangle", function() { it("should not set and get an invalid rectangle", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setRectangle([117, 694, 164.298]); annotation.setRectangle([117, 694, 164.298]);
expect(annotation.rectangle).toEqual([0, 0, 0, 0]); expect(annotation.rectangle).toEqual([0, 0, 0, 0]);
}); });
it("should reject a color if it is not an array", function() { it("should reject a color if it is not an array", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setColor("red"); annotation.setColor("red");
expect(annotation.color).toEqual(new Uint8ClampedArray([0, 0, 0])); expect(annotation.color).toEqual(new Uint8ClampedArray([0, 0, 0]));
}); });
it("should set and get a transparent color", function() { it("should set and get a transparent color", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setColor([]); annotation.setColor([]);
expect(annotation.color).toEqual(null); expect(annotation.color).toEqual(null);
}); });
it("should set and get a grayscale color", function() { it("should set and get a grayscale color", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setColor([0.4]); annotation.setColor([0.4]);
expect(annotation.color).toEqual(new Uint8ClampedArray([102, 102, 102])); expect(annotation.color).toEqual(new Uint8ClampedArray([102, 102, 102]));
}); });
it("should set and get an RGB color", function() { it("should set and get an RGB color", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setColor([0, 0, 1]); annotation.setColor([0, 0, 1]);
expect(annotation.color).toEqual(new Uint8ClampedArray([0, 0, 255])); expect(annotation.color).toEqual(new Uint8ClampedArray([0, 0, 255]));
}); });
it("should set and get a CMYK color", function() { it("should set and get a CMYK color", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setColor([0.1, 0.92, 0.84, 0.02]); annotation.setColor([0.1, 0.92, 0.84, 0.02]);
expect(annotation.color).toEqual(new Uint8ClampedArray([234, 59, 48])); expect(annotation.color).toEqual(new Uint8ClampedArray([234, 59, 48]));
}); });
it("should not set and get an invalid color", function() { it("should not set and get an invalid color", function () {
const annotation = new Annotation({ dict, ref }); const annotation = new Annotation({ dict, ref });
annotation.setColor([0.4, 0.6]); annotation.setColor([0.4, 0.6]);
@ -335,22 +335,22 @@ describe("annotation", function() {
}); });
}); });
describe("AnnotationBorderStyle", function() { describe("AnnotationBorderStyle", function () {
it("should set and get a valid width", function() { it("should set and get a valid width", function () {
const borderStyle = new AnnotationBorderStyle(); const borderStyle = new AnnotationBorderStyle();
borderStyle.setWidth(3); borderStyle.setWidth(3);
expect(borderStyle.width).toEqual(3); expect(borderStyle.width).toEqual(3);
}); });
it("should not set and get an invalid width", function() { it("should not set and get an invalid width", function () {
const borderStyle = new AnnotationBorderStyle(); const borderStyle = new AnnotationBorderStyle();
borderStyle.setWidth("three"); borderStyle.setWidth("three");
expect(borderStyle.width).toEqual(1); expect(borderStyle.width).toEqual(1);
}); });
it("should set the width to zero, when the input is a `Name` (issue 10385)", function() { it("should set the width to zero, when the input is a `Name` (issue 10385)", function () {
const borderStyleZero = new AnnotationBorderStyle(); const borderStyleZero = new AnnotationBorderStyle();
borderStyleZero.setWidth(Name.get("0")); borderStyleZero.setWidth(Name.get("0"));
const borderStyleFive = new AnnotationBorderStyle(); const borderStyleFive = new AnnotationBorderStyle();
@ -360,56 +360,56 @@ describe("annotation", function() {
expect(borderStyleFive.width).toEqual(0); expect(borderStyleFive.width).toEqual(0);
}); });
it("should set and get a valid style", function() { it("should set and get a valid style", function () {
const borderStyle = new AnnotationBorderStyle(); const borderStyle = new AnnotationBorderStyle();
borderStyle.setStyle(Name.get("D")); borderStyle.setStyle(Name.get("D"));
expect(borderStyle.style).toEqual(AnnotationBorderStyleType.DASHED); expect(borderStyle.style).toEqual(AnnotationBorderStyleType.DASHED);
}); });
it("should not set and get an invalid style", function() { it("should not set and get an invalid style", function () {
const borderStyle = new AnnotationBorderStyle(); const borderStyle = new AnnotationBorderStyle();
borderStyle.setStyle("Dashed"); borderStyle.setStyle("Dashed");
expect(borderStyle.style).toEqual(AnnotationBorderStyleType.SOLID); expect(borderStyle.style).toEqual(AnnotationBorderStyleType.SOLID);
}); });
it("should set and get a valid dash array", function() { it("should set and get a valid dash array", function () {
const borderStyle = new AnnotationBorderStyle(); const borderStyle = new AnnotationBorderStyle();
borderStyle.setDashArray([1, 2, 3]); borderStyle.setDashArray([1, 2, 3]);
expect(borderStyle.dashArray).toEqual([1, 2, 3]); expect(borderStyle.dashArray).toEqual([1, 2, 3]);
}); });
it("should not set and get an invalid dash array", function() { it("should not set and get an invalid dash array", function () {
const borderStyle = new AnnotationBorderStyle(); const borderStyle = new AnnotationBorderStyle();
borderStyle.setDashArray([0, 0]); borderStyle.setDashArray([0, 0]);
expect(borderStyle.dashArray).toEqual([3]); expect(borderStyle.dashArray).toEqual([3]);
}); });
it("should set and get a valid horizontal corner radius", function() { it("should set and get a valid horizontal corner radius", function () {
const borderStyle = new AnnotationBorderStyle(); const borderStyle = new AnnotationBorderStyle();
borderStyle.setHorizontalCornerRadius(3); borderStyle.setHorizontalCornerRadius(3);
expect(borderStyle.horizontalCornerRadius).toEqual(3); expect(borderStyle.horizontalCornerRadius).toEqual(3);
}); });
it("should not set and get an invalid horizontal corner radius", function() { it("should not set and get an invalid horizontal corner radius", function () {
const borderStyle = new AnnotationBorderStyle(); const borderStyle = new AnnotationBorderStyle();
borderStyle.setHorizontalCornerRadius("three"); borderStyle.setHorizontalCornerRadius("three");
expect(borderStyle.horizontalCornerRadius).toEqual(0); expect(borderStyle.horizontalCornerRadius).toEqual(0);
}); });
it("should set and get a valid vertical corner radius", function() { it("should set and get a valid vertical corner radius", function () {
const borderStyle = new AnnotationBorderStyle(); const borderStyle = new AnnotationBorderStyle();
borderStyle.setVerticalCornerRadius(3); borderStyle.setVerticalCornerRadius(3);
expect(borderStyle.verticalCornerRadius).toEqual(3); expect(borderStyle.verticalCornerRadius).toEqual(3);
}); });
it("should not set and get an invalid vertical corner radius", function() { it("should not set and get an invalid vertical corner radius", function () {
const borderStyle = new AnnotationBorderStyle(); const borderStyle = new AnnotationBorderStyle();
borderStyle.setVerticalCornerRadius("three"); borderStyle.setVerticalCornerRadius("three");
@ -417,34 +417,34 @@ describe("annotation", function() {
}); });
}); });
describe("MarkupAnnotation", function() { describe("MarkupAnnotation", function () {
let dict, ref; let dict, ref;
beforeAll(function(done) { beforeAll(function (done) {
dict = new Dict(); dict = new Dict();
ref = Ref.get(1, 0); ref = Ref.get(1, 0);
done(); done();
}); });
afterAll(function() { afterAll(function () {
dict = ref = null; dict = ref = null;
}); });
it("should set and get a valid creation date", function() { it("should set and get a valid creation date", function () {
const markupAnnotation = new MarkupAnnotation({ dict, ref }); const markupAnnotation = new MarkupAnnotation({ dict, ref });
markupAnnotation.setCreationDate("D:20190422"); markupAnnotation.setCreationDate("D:20190422");
expect(markupAnnotation.creationDate).toEqual("D:20190422"); expect(markupAnnotation.creationDate).toEqual("D:20190422");
}); });
it("should not set and get an invalid creation date", function() { it("should not set and get an invalid creation date", function () {
const markupAnnotation = new MarkupAnnotation({ dict, ref }); const markupAnnotation = new MarkupAnnotation({ dict, ref });
markupAnnotation.setCreationDate(undefined); markupAnnotation.setCreationDate(undefined);
expect(markupAnnotation.creationDate).toEqual(null); expect(markupAnnotation.creationDate).toEqual(null);
}); });
it("should not parse IRT/RT when not defined", function(done) { it("should not parse IRT/RT when not defined", function (done) {
dict.set("Type", Name.get("Annot")); dict.set("Type", Name.get("Annot"));
dict.set("Subtype", Name.get("Text")); dict.set("Subtype", Name.get("Text"));
@ -460,7 +460,7 @@ describe("annotation", function() {
); );
}); });
it("should parse IRT and set default RT when not defined.", function(done) { it("should parse IRT and set default RT when not defined.", function (done) {
const annotationRef = Ref.get(819, 0); const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
@ -491,7 +491,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should parse IRT/RT for a group type", function(done) { it("should parse IRT/RT for a group type", function (done) {
const annotationRef = Ref.get(819, 0); const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
@ -548,7 +548,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should parse IRT/RT for a reply type", function(done) { it("should parse IRT/RT for a reply type", function (done) {
const annotationRef = Ref.get(819, 0); const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
@ -606,8 +606,8 @@ describe("annotation", function() {
}); });
}); });
describe("TextAnnotation", function() { describe("TextAnnotation", function () {
it("should not parse state model and state when not defined", function(done) { it("should not parse state model and state when not defined", function (done) {
const annotationRef = Ref.get(819, 0); const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
@ -641,7 +641,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should correctly parse state model and state when defined", function(done) { it("should correctly parse state model and state when defined", function (done) {
const annotationRef = Ref.get(819, 0); const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
@ -676,8 +676,8 @@ describe("annotation", function() {
}); });
}); });
describe("LinkAnnotation", function() { describe("LinkAnnotation", function () {
it("should correctly parse a URI action", function(done) { it("should correctly parse a URI action", function (done) {
const actionDict = new Dict(); const actionDict = new Dict();
actionDict.set("Type", Name.get("Action")); actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("URI")); actionDict.set("S", Name.get("URI"));
@ -710,7 +710,7 @@ describe("annotation", function() {
it( it(
"should correctly parse a URI action, where the URI entry " + "should correctly parse a URI action, where the URI entry " +
"is missing a protocol", "is missing a protocol",
function(done) { function (done) {
const actionDict = new Dict(); const actionDict = new Dict();
actionDict.set("Type", Name.get("Action")); actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("URI")); actionDict.set("S", Name.get("URI"));
@ -744,7 +744,7 @@ describe("annotation", function() {
it( it(
"should correctly parse a URI action, where the URI entry " + "should correctly parse a URI action, where the URI entry " +
"has an incorrect encoding (bug 1122280)", "has an incorrect encoding (bug 1122280)",
function(done) { function (done) {
const actionStream = new StringStream( const actionStream = new StringStream(
"<<\n" + "<<\n" +
"/Type /Action\n" + "/Type /Action\n" +
@ -793,7 +793,7 @@ describe("annotation", function() {
} }
); );
it("should correctly parse a GoTo action", function(done) { it("should correctly parse a GoTo action", function (done) {
const actionDict = new Dict(); const actionDict = new Dict();
actionDict.set("Type", Name.get("Action")); actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("GoTo")); actionDict.set("S", Name.get("GoTo"));
@ -824,7 +824,7 @@ describe("annotation", function() {
it( it(
"should correctly parse a GoToR action, where the FileSpec entry " + "should correctly parse a GoToR action, where the FileSpec entry " +
"is a string containing a relative URL", "is a string containing a relative URL",
function(done) { function (done) {
const actionDict = new Dict(); const actionDict = new Dict();
actionDict.set("Type", Name.get("Action")); actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("GoToR")); actionDict.set("S", Name.get("GoToR"));
@ -861,7 +861,7 @@ describe("annotation", function() {
it( it(
"should correctly parse a GoToR action, containing a relative URL, " + "should correctly parse a GoToR action, containing a relative URL, " +
'with the "docBaseUrl" parameter specified', 'with the "docBaseUrl" parameter specified',
function(done) { function (done) {
const actionDict = new Dict(); const actionDict = new Dict();
actionDict.set("Type", Name.get("Action")); actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("GoToR")); actionDict.set("S", Name.get("GoToR"));
@ -898,7 +898,7 @@ describe("annotation", function() {
} }
); );
it("should correctly parse a GoToR action, with named destination", function(done) { it("should correctly parse a GoToR action, with named destination", function (done) {
const actionDict = new Dict(); const actionDict = new Dict();
actionDict.set("Type", Name.get("Action")); actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("GoToR")); actionDict.set("S", Name.get("GoToR"));
@ -928,7 +928,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should correctly parse a GoToR action, with explicit destination array", function(done) { it("should correctly parse a GoToR action, with explicit destination array", function (done) {
const actionDict = new Dict(); const actionDict = new Dict();
actionDict.set("Type", Name.get("Action")); actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("GoToR")); actionDict.set("S", Name.get("GoToR"));
@ -969,7 +969,7 @@ describe("annotation", function() {
it( it(
"should correctly parse a Launch action, where the FileSpec dict " + "should correctly parse a Launch action, where the FileSpec dict " +
'contains a relative URL, with the "docBaseUrl" parameter specified', 'contains a relative URL, with the "docBaseUrl" parameter specified',
function(done) { function (done) {
const fileSpecDict = new Dict(); const fileSpecDict = new Dict();
fileSpecDict.set("Type", Name.get("FileSpec")); fileSpecDict.set("Type", Name.get("FileSpec"));
fileSpecDict.set("F", "Part II/Part II.pdf"); fileSpecDict.set("F", "Part II/Part II.pdf");
@ -1015,7 +1015,7 @@ describe("annotation", function() {
it( it(
"should recover valid URLs from JavaScript actions having certain " + "should recover valid URLs from JavaScript actions having certain " +
"white-listed formats", "white-listed formats",
function(done) { function (done) {
function checkJsAction(params) { function checkJsAction(params) {
const jsEntry = params.jsEntry; const jsEntry = params.jsEntry;
const expectedUrl = params.expectedUrl; const expectedUrl = params.expectedUrl;
@ -1084,7 +1084,7 @@ describe("annotation", function() {
} }
); );
it("should correctly parse a Named action", function(done) { it("should correctly parse a Named action", function (done) {
const actionDict = new Dict(); const actionDict = new Dict();
actionDict.set("Type", Name.get("Action")); actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("Named")); actionDict.set("S", Name.get("Named"));
@ -1112,7 +1112,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should correctly parse a simple Dest", function(done) { it("should correctly parse a simple Dest", function (done) {
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link")); annotationDict.set("Subtype", Name.get("Link"));
@ -1135,7 +1135,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should correctly parse a simple Dest, with explicit destination array", function(done) { it("should correctly parse a simple Dest, with explicit destination array", function (done) {
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link")); annotationDict.set("Subtype", Name.get("Link"));
@ -1173,7 +1173,7 @@ describe("annotation", function() {
it( it(
"should correctly parse a Dest, which violates the specification " + "should correctly parse a Dest, which violates the specification " +
"by containing a dictionary", "by containing a dictionary",
function(done) { function (done) {
const destDict = new Dict(); const destDict = new Dict();
destDict.set("Type", Name.get("Action")); destDict.set("Type", Name.get("Action"));
destDict.set("S", Name.get("GoTo")); destDict.set("S", Name.get("GoTo"));
@ -1206,7 +1206,7 @@ describe("annotation", function() {
} }
); );
it("should not set quadpoints if not defined", function(done) { it("should not set quadpoints if not defined", function (done) {
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link")); annotationDict.set("Subtype", Name.get("Link"));
@ -1226,7 +1226,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should set quadpoints if defined", function(done) { it("should set quadpoints if defined", function (done) {
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link")); annotationDict.set("Subtype", Name.get("Link"));
@ -1256,21 +1256,21 @@ describe("annotation", function() {
}); });
}); });
describe("WidgetAnnotation", function() { describe("WidgetAnnotation", function () {
let widgetDict; let widgetDict;
beforeEach(function(done) { beforeEach(function (done) {
widgetDict = new Dict(); widgetDict = new Dict();
widgetDict.set("Type", Name.get("Annot")); widgetDict.set("Type", Name.get("Annot"));
widgetDict.set("Subtype", Name.get("Widget")); widgetDict.set("Subtype", Name.get("Widget"));
done(); done();
}); });
afterEach(function() { afterEach(function () {
widgetDict = null; widgetDict = null;
}); });
it("should handle unknown field names", function(done) { it("should handle unknown field names", function (done) {
const widgetRef = Ref.get(20, 0); const widgetRef = Ref.get(20, 0);
const xref = new XRefMock([{ ref: widgetRef, data: widgetDict }]); const xref = new XRefMock([{ ref: widgetRef, data: widgetDict }]);
@ -1286,7 +1286,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should construct the field name when there are no ancestors", function(done) { it("should construct the field name when there are no ancestors", function (done) {
widgetDict.set("T", "foo"); widgetDict.set("T", "foo");
const widgetRef = Ref.get(21, 0); const widgetRef = Ref.get(21, 0);
@ -1304,7 +1304,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should construct the field name when there are ancestors", function(done) { it("should construct the field name when there are ancestors", function (done) {
const firstParent = new Dict(); const firstParent = new Dict();
firstParent.set("T", "foo"); firstParent.set("T", "foo");
@ -1333,7 +1333,7 @@ describe("annotation", function() {
it( it(
"should construct the field name if a parent is not a dictionary " + "should construct the field name if a parent is not a dictionary " +
"(issue 8143)", "(issue 8143)",
function(done) { function (done) {
const parentDict = new Dict(); const parentDict = new Dict();
parentDict.set("Parent", null); parentDict.set("Parent", null);
parentDict.set("T", "foo"); parentDict.set("T", "foo");
@ -1358,10 +1358,10 @@ describe("annotation", function() {
); );
}); });
describe("TextWidgetAnnotation", function() { describe("TextWidgetAnnotation", function () {
let textWidgetDict; let textWidgetDict;
beforeEach(function(done) { beforeEach(function (done) {
textWidgetDict = new Dict(); textWidgetDict = new Dict();
textWidgetDict.set("Type", Name.get("Annot")); textWidgetDict.set("Type", Name.get("Annot"));
textWidgetDict.set("Subtype", Name.get("Widget")); textWidgetDict.set("Subtype", Name.get("Widget"));
@ -1369,11 +1369,11 @@ describe("annotation", function() {
done(); done();
}); });
afterEach(function() { afterEach(function () {
textWidgetDict = null; textWidgetDict = null;
}); });
it("should handle unknown text alignment, maximum length and flags", function(done) { it("should handle unknown text alignment, maximum length and flags", function (done) {
const textWidgetRef = Ref.get(124, 0); const textWidgetRef = Ref.get(124, 0);
const xref = new XRefMock([{ ref: textWidgetRef, data: textWidgetDict }]); const xref = new XRefMock([{ ref: textWidgetRef, data: textWidgetDict }]);
@ -1393,7 +1393,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should not set invalid text alignment, maximum length and flags", function(done) { it("should not set invalid text alignment, maximum length and flags", function (done) {
textWidgetDict.set("Q", "center"); textWidgetDict.set("Q", "center");
textWidgetDict.set("MaxLen", "five"); textWidgetDict.set("MaxLen", "five");
textWidgetDict.set("Ff", "readonly"); textWidgetDict.set("Ff", "readonly");
@ -1417,7 +1417,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should set valid text alignment, maximum length and flags", function(done) { it("should set valid text alignment, maximum length and flags", function (done) {
textWidgetDict.set("Q", 1); textWidgetDict.set("Q", 1);
textWidgetDict.set("MaxLen", 20); textWidgetDict.set("MaxLen", 20);
textWidgetDict.set( textWidgetDict.set(
@ -1443,7 +1443,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should reject comb fields without a maximum length", function(done) { it("should reject comb fields without a maximum length", function (done) {
textWidgetDict.set("Ff", AnnotationFieldFlag.COMB); textWidgetDict.set("Ff", AnnotationFieldFlag.COMB);
const textWidgetRef = Ref.get(46, 0); const textWidgetRef = Ref.get(46, 0);
@ -1461,7 +1461,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should accept comb fields with a maximum length", function(done) { it("should accept comb fields with a maximum length", function (done) {
textWidgetDict.set("MaxLen", 20); textWidgetDict.set("MaxLen", 20);
textWidgetDict.set("Ff", AnnotationFieldFlag.COMB); textWidgetDict.set("Ff", AnnotationFieldFlag.COMB);
@ -1480,7 +1480,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should only accept comb fields when the flags are valid", function(done) { it("should only accept comb fields when the flags are valid", function (done) {
const invalidFieldFlags = [ const invalidFieldFlags = [
AnnotationFieldFlag.MULTILINE, AnnotationFieldFlag.MULTILINE,
AnnotationFieldFlag.PASSWORD, AnnotationFieldFlag.PASSWORD,
@ -1528,10 +1528,10 @@ describe("annotation", function() {
}); });
}); });
describe("ButtonWidgetAnnotation", function() { describe("ButtonWidgetAnnotation", function () {
let buttonWidgetDict; let buttonWidgetDict;
beforeEach(function(done) { beforeEach(function (done) {
buttonWidgetDict = new Dict(); buttonWidgetDict = new Dict();
buttonWidgetDict.set("Type", Name.get("Annot")); buttonWidgetDict.set("Type", Name.get("Annot"));
buttonWidgetDict.set("Subtype", Name.get("Widget")); buttonWidgetDict.set("Subtype", Name.get("Widget"));
@ -1539,11 +1539,11 @@ describe("annotation", function() {
done(); done();
}); });
afterEach(function() { afterEach(function () {
buttonWidgetDict = null; buttonWidgetDict = null;
}); });
it("should handle checkboxes with export value", function(done) { it("should handle checkboxes with export value", function (done) {
buttonWidgetDict.set("V", Name.get("1")); buttonWidgetDict.set("V", Name.get("1"));
const appearanceStatesDict = new Dict(); const appearanceStatesDict = new Dict();
@ -1574,7 +1574,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle checkboxes without export value", function(done) { it("should handle checkboxes without export value", function (done) {
buttonWidgetDict.set("V", Name.get("1")); buttonWidgetDict.set("V", Name.get("1"));
const buttonWidgetRef = Ref.get(124, 0); const buttonWidgetRef = Ref.get(124, 0);
@ -1596,7 +1596,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle radio buttons with a field value", function(done) { it("should handle radio buttons with a field value", function (done) {
const parentDict = new Dict(); const parentDict = new Dict();
parentDict.set("V", Name.get("1")); parentDict.set("V", Name.get("1"));
@ -1630,7 +1630,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle radio buttons without a field value", function(done) { it("should handle radio buttons without a field value", function (done) {
const normalAppearanceStateDict = new Dict(); const normalAppearanceStateDict = new Dict();
normalAppearanceStateDict.set("2", null); normalAppearanceStateDict.set("2", null);
@ -1661,10 +1661,10 @@ describe("annotation", function() {
}); });
}); });
describe("ChoiceWidgetAnnotation", function() { describe("ChoiceWidgetAnnotation", function () {
let choiceWidgetDict; let choiceWidgetDict;
beforeEach(function(done) { beforeEach(function (done) {
choiceWidgetDict = new Dict(); choiceWidgetDict = new Dict();
choiceWidgetDict.set("Type", Name.get("Annot")); choiceWidgetDict.set("Type", Name.get("Annot"));
choiceWidgetDict.set("Subtype", Name.get("Widget")); choiceWidgetDict.set("Subtype", Name.get("Widget"));
@ -1672,11 +1672,11 @@ describe("annotation", function() {
done(); done();
}); });
afterEach(function() { afterEach(function () {
choiceWidgetDict = null; choiceWidgetDict = null;
}); });
it("should handle missing option arrays", function(done) { it("should handle missing option arrays", function (done) {
const choiceWidgetRef = Ref.get(122, 0); const choiceWidgetRef = Ref.get(122, 0);
const xref = new XRefMock([ const xref = new XRefMock([
{ ref: choiceWidgetRef, data: choiceWidgetDict }, { ref: choiceWidgetRef, data: choiceWidgetDict },
@ -1694,7 +1694,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle option arrays with array elements", function(done) { it("should handle option arrays with array elements", function (done) {
const optionBarRef = Ref.get(20, 0); const optionBarRef = Ref.get(20, 0);
const optionBarStr = "Bar"; const optionBarStr = "Bar";
const optionOneRef = Ref.get(10, 0); const optionOneRef = Ref.get(10, 0);
@ -1727,7 +1727,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle option arrays with string elements", function(done) { it("should handle option arrays with string elements", function (done) {
const optionBarRef = Ref.get(10, 0); const optionBarRef = Ref.get(10, 0);
const optionBarStr = "Bar"; const optionBarStr = "Bar";
@ -1757,7 +1757,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle inherited option arrays (issue 8094)", function(done) { it("should handle inherited option arrays (issue 8094)", function (done) {
const options = [ const options = [
["Value1", "Description1"], ["Value1", "Description1"],
["Value2", "Description2"], ["Value2", "Description2"],
@ -1789,7 +1789,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should sanitize display values in option arrays (issue 8947)", function(done) { it("should sanitize display values in option arrays (issue 8947)", function (done) {
// The option value is a UTF-16BE string. The display value should be // The option value is a UTF-16BE string. The display value should be
// sanitized, but the export value should remain the same since that // sanitized, but the export value should remain the same since that
// may be used as a unique identifier when exporting form values. // may be used as a unique identifier when exporting form values.
@ -1817,7 +1817,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle array field values", function(done) { it("should handle array field values", function (done) {
const fieldValue = ["Foo", "Bar"]; const fieldValue = ["Foo", "Bar"];
choiceWidgetDict.set("V", fieldValue); choiceWidgetDict.set("V", fieldValue);
@ -1839,7 +1839,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle string field values", function(done) { it("should handle string field values", function (done) {
const fieldValue = "Foo"; const fieldValue = "Foo";
choiceWidgetDict.set("V", fieldValue); choiceWidgetDict.set("V", fieldValue);
@ -1861,7 +1861,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle unknown flags", function(done) { it("should handle unknown flags", function (done) {
const choiceWidgetRef = Ref.get(166, 0); const choiceWidgetRef = Ref.get(166, 0);
const xref = new XRefMock([ const xref = new XRefMock([
{ ref: choiceWidgetRef, data: choiceWidgetDict }, { ref: choiceWidgetRef, data: choiceWidgetDict },
@ -1881,7 +1881,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should not set invalid flags", function(done) { it("should not set invalid flags", function (done) {
choiceWidgetDict.set("Ff", "readonly"); choiceWidgetDict.set("Ff", "readonly");
const choiceWidgetRef = Ref.get(165, 0); const choiceWidgetRef = Ref.get(165, 0);
@ -1903,7 +1903,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should set valid flags", function(done) { it("should set valid flags", function (done) {
choiceWidgetDict.set( choiceWidgetDict.set(
"Ff", "Ff",
AnnotationFieldFlag.READONLY + AnnotationFieldFlag.READONLY +
@ -1931,8 +1931,8 @@ describe("annotation", function() {
}); });
}); });
describe("LineAnnotation", function() { describe("LineAnnotation", function () {
it("should set the line coordinates", function(done) { it("should set the line coordinates", function (done) {
const lineDict = new Dict(); const lineDict = new Dict();
lineDict.set("Type", Name.get("Annot")); lineDict.set("Type", Name.get("Annot"));
lineDict.set("Subtype", Name.get("Line")); lineDict.set("Subtype", Name.get("Line"));
@ -1954,8 +1954,8 @@ describe("annotation", function() {
}); });
}); });
describe("FileAttachmentAnnotation", function() { describe("FileAttachmentAnnotation", function () {
it("should correctly parse a file attachment", function(done) { it("should correctly parse a file attachment", function (done) {
const fileStream = new StringStream( const fileStream = new StringStream(
"<<\n" + "<<\n" +
"/Type /EmbeddedFile\n" + "/Type /EmbeddedFile\n" +
@ -2015,8 +2015,8 @@ describe("annotation", function() {
}); });
}); });
describe("PopupAnnotation", function() { describe("PopupAnnotation", function () {
it("should inherit properties from its parent", function(done) { it("should inherit properties from its parent", function (done) {
const parentDict = new Dict(); const parentDict = new Dict();
parentDict.set("Type", Name.get("Annot")); parentDict.set("Type", Name.get("Annot"));
parentDict.set("Subtype", Name.get("Text")); parentDict.set("Subtype", Name.get("Text"));
@ -2044,7 +2044,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle missing parent properties", function(done) { it("should handle missing parent properties", function (done) {
const parentDict = new Dict(); const parentDict = new Dict();
parentDict.set("Type", Name.get("Annot")); parentDict.set("Type", Name.get("Annot"));
parentDict.set("Subtype", Name.get("Text")); parentDict.set("Subtype", Name.get("Text"));
@ -2073,7 +2073,7 @@ describe("annotation", function() {
it( it(
"should inherit the parent flags when the Popup is not viewable, " + "should inherit the parent flags when the Popup is not viewable, " +
"but the parent is (PR 7352)", "but the parent is (PR 7352)",
function(done) { function (done) {
const parentDict = new Dict(); const parentDict = new Dict();
parentDict.set("Type", Name.get("Annot")); parentDict.set("Type", Name.get("Annot"));
parentDict.set("Subtype", Name.get("Text")); parentDict.set("Subtype", Name.get("Text"));
@ -2108,7 +2108,7 @@ describe("annotation", function() {
it( it(
"should correctly inherit Contents from group-master annotation " + "should correctly inherit Contents from group-master annotation " +
"if parent has ReplyType == Group", "if parent has ReplyType == Group",
function(done) { function (done) {
const annotationRef = Ref.get(819, 0); const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict(); const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Type", Name.get("Annot"));
@ -2165,8 +2165,8 @@ describe("annotation", function() {
); );
}); });
describe("InkAnnotation", function() { describe("InkAnnotation", function () {
it("should handle a single ink list", function(done) { it("should handle a single ink list", function (done) {
const inkDict = new Dict(); const inkDict = new Dict();
inkDict.set("Type", Name.get("Annot")); inkDict.set("Type", Name.get("Annot"));
inkDict.set("Subtype", Name.get("Ink")); inkDict.set("Subtype", Name.get("Ink"));
@ -2193,7 +2193,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should handle multiple ink lists", function(done) { it("should handle multiple ink lists", function (done) {
const inkDict = new Dict(); const inkDict = new Dict();
inkDict.set("Type", Name.get("Annot")); inkDict.set("Type", Name.get("Annot"));
inkDict.set("Subtype", Name.get("Ink")); inkDict.set("Subtype", Name.get("Ink"));
@ -2226,8 +2226,8 @@ describe("annotation", function() {
}); });
}); });
describe("HightlightAnnotation", function() { describe("HightlightAnnotation", function () {
it("should not set quadpoints if not defined", function(done) { it("should not set quadpoints if not defined", function (done) {
const highlightDict = new Dict(); const highlightDict = new Dict();
highlightDict.set("Type", Name.get("Annot")); highlightDict.set("Type", Name.get("Annot"));
highlightDict.set("Subtype", Name.get("Highlight")); highlightDict.set("Subtype", Name.get("Highlight"));
@ -2247,7 +2247,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should set quadpoints if defined", function(done) { it("should set quadpoints if defined", function (done) {
const highlightDict = new Dict(); const highlightDict = new Dict();
highlightDict.set("Type", Name.get("Annot")); highlightDict.set("Type", Name.get("Annot"));
highlightDict.set("Subtype", Name.get("Highlight")); highlightDict.set("Subtype", Name.get("Highlight"));
@ -2277,8 +2277,8 @@ describe("annotation", function() {
}); });
}); });
describe("UnderlineAnnotation", function() { describe("UnderlineAnnotation", function () {
it("should not set quadpoints if not defined", function(done) { it("should not set quadpoints if not defined", function (done) {
const underlineDict = new Dict(); const underlineDict = new Dict();
underlineDict.set("Type", Name.get("Annot")); underlineDict.set("Type", Name.get("Annot"));
underlineDict.set("Subtype", Name.get("Underline")); underlineDict.set("Subtype", Name.get("Underline"));
@ -2298,7 +2298,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should set quadpoints if defined", function(done) { it("should set quadpoints if defined", function (done) {
const underlineDict = new Dict(); const underlineDict = new Dict();
underlineDict.set("Type", Name.get("Annot")); underlineDict.set("Type", Name.get("Annot"));
underlineDict.set("Subtype", Name.get("Underline")); underlineDict.set("Subtype", Name.get("Underline"));
@ -2328,8 +2328,8 @@ describe("annotation", function() {
}); });
}); });
describe("SquigglyAnnotation", function() { describe("SquigglyAnnotation", function () {
it("should not set quadpoints if not defined", function(done) { it("should not set quadpoints if not defined", function (done) {
const squigglyDict = new Dict(); const squigglyDict = new Dict();
squigglyDict.set("Type", Name.get("Annot")); squigglyDict.set("Type", Name.get("Annot"));
squigglyDict.set("Subtype", Name.get("Squiggly")); squigglyDict.set("Subtype", Name.get("Squiggly"));
@ -2349,7 +2349,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should set quadpoints if defined", function(done) { it("should set quadpoints if defined", function (done) {
const squigglyDict = new Dict(); const squigglyDict = new Dict();
squigglyDict.set("Type", Name.get("Annot")); squigglyDict.set("Type", Name.get("Annot"));
squigglyDict.set("Subtype", Name.get("Squiggly")); squigglyDict.set("Subtype", Name.get("Squiggly"));
@ -2379,8 +2379,8 @@ describe("annotation", function() {
}); });
}); });
describe("StrikeOutAnnotation", function() { describe("StrikeOutAnnotation", function () {
it("should not set quadpoints if not defined", function(done) { it("should not set quadpoints if not defined", function (done) {
const strikeOutDict = new Dict(); const strikeOutDict = new Dict();
strikeOutDict.set("Type", Name.get("Annot")); strikeOutDict.set("Type", Name.get("Annot"));
strikeOutDict.set("Subtype", Name.get("StrikeOut")); strikeOutDict.set("Subtype", Name.get("StrikeOut"));
@ -2400,7 +2400,7 @@ describe("annotation", function() {
}, done.fail); }, done.fail);
}); });
it("should set quadpoints if defined", function(done) { it("should set quadpoints if defined", function (done) {
const strikeOutDict = new Dict(); const strikeOutDict = new Dict();
strikeOutDict.set("Type", Name.get("Annot")); strikeOutDict.set("Type", Name.get("Annot"));
strikeOutDict.set("Subtype", Name.get("StrikeOut")); strikeOutDict.set("Subtype", Name.get("StrikeOut"));

File diff suppressed because it is too large Load Diff

View File

@ -15,8 +15,8 @@
import { bidi } from "../../src/core/bidi.js"; import { bidi } from "../../src/core/bidi.js";
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 () {
// 33% of test text are RTL characters // 33% of test text are RTL characters
var test = "\u0645\u0635\u0631 Egypt"; var test = "\u0645\u0635\u0631 Egypt";
var result = "Egypt \u0631\u0635\u0645"; var result = "Egypt \u0631\u0635\u0645";
@ -26,7 +26,7 @@ describe("bidi", function() {
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 = bidi(test, -1, false);

View File

@ -23,7 +23,7 @@ import {
import { SEAC_ANALYSIS_ENABLED } from "../../src/core/fonts.js"; import { SEAC_ANALYSIS_ENABLED } from "../../src/core/fonts.js";
import { Stream } from "../../src/core/stream.js"; import { Stream } from "../../src/core/stream.js";
describe("CFFParser", function() { describe("CFFParser", function () {
function createWithNullProto(obj) { function createWithNullProto(obj) {
var result = Object.create(null); var result = Object.create(null);
for (var i in obj) { for (var i in obj) {
@ -41,7 +41,7 @@ describe("CFFParser", function() {
var fontData, parser, cff; var fontData, parser, cff;
beforeAll(function(done) { beforeAll(function (done) {
// This example font comes from the CFF spec: // This example font comes from the CFF spec:
// http://www.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf // http://www.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf
var exampleFont = var exampleFont =
@ -64,22 +64,22 @@ describe("CFFParser", function() {
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 CFFParser(fontData, {}, SEAC_ANALYSIS_ENABLED);
cff = parser.parse(); cff = parser.parse();
done(); done();
}); });
afterEach(function(done) { afterEach(function (done) {
parser = cff = null; parser = cff = null;
done(); done();
}); });
it("parses header", function() { it("parses header", function () {
var header = cff.header; var header = cff.header;
expect(header.major).toEqual(1); expect(header.major).toEqual(1);
expect(header.minor).toEqual(0); expect(header.minor).toEqual(0);
@ -87,20 +87,20 @@ describe("CFFParser", function() {
expect(header.offSize).toEqual(1); expect(header.offSize).toEqual(1);
}); });
it("parses name index", function() { it("parses name index", function () {
var names = cff.names; var names = cff.names;
expect(names.length).toEqual(1); expect(names.length).toEqual(1);
expect(names[0]).toEqual("ABCDEF+Times-Roman"); expect(names[0]).toEqual("ABCDEF+Times-Roman");
}); });
it("parses string index", function() { it("parses string index", function () {
var strings = cff.strings; var strings = cff.strings;
expect(strings.count).toEqual(3); expect(strings.count).toEqual(3);
expect(strings.get(0)).toEqual(".notdef"); expect(strings.get(0)).toEqual(".notdef");
expect(strings.get(391)).toEqual("001.007"); expect(strings.get(391)).toEqual("001.007");
}); });
it("parses top dict", function() { it("parses top dict", function () {
var topDict = cff.topDict; var topDict = cff.topDict;
// 391 version 392 FullName 393 FamilyName 389 Weight 28416 UniqueID // 391 version 392 FullName 393 FamilyName 389 Weight 28416 UniqueID
// -168 -218 1000 898 FontBBox 94 CharStrings 45 102 Private // -168 -218 1000 898 FontBBox 94 CharStrings 45 102 Private
@ -114,7 +114,7 @@ describe("CFFParser", function() {
expect(topDict.getByName("Private")).toEqual([45, 102]); expect(topDict.getByName("Private")).toEqual([45, 102]);
}); });
it("refuses to add topDict key with invalid value (bug 1068432)", function() { it("refuses to add topDict key with invalid value (bug 1068432)", function () {
var topDict = cff.topDict; var topDict = cff.topDict;
var defaultValue = topDict.getByName("UnderlinePosition"); var defaultValue = topDict.getByName("UnderlinePosition");
@ -125,7 +125,7 @@ describe("CFFParser", function() {
it( it(
"ignores reserved commands in parseDict, and refuses to add privateDict " + "ignores reserved commands in parseDict, and refuses to add privateDict " +
"keys with invalid values (bug 1308536)", "keys with invalid values (bug 1308536)",
function() { function () {
// prettier-ignore // prettier-ignore
var bytes = new Uint8Array([ var bytes = new Uint8Array([
64, 39, 31, 30, 252, 114, 137, 115, 79, 30, 197, 119, 2, 99, 127, 6 64, 39, 31, 30, 252, 114, 137, 115, 79, 30, 197, 119, 2, 99, 127, 6
@ -134,7 +134,7 @@ describe("CFFParser", function() {
var topDict = cff.topDict; var topDict = cff.topDict;
topDict.setByName("Private", [bytes.length, 0]); topDict.setByName("Private", [bytes.length, 0]);
var parsePrivateDict = function() { var parsePrivateDict = function () {
parser.parsePrivateDict(topDict); parser.parsePrivateDict(topDict);
}; };
expect(parsePrivateDict).not.toThrow(); expect(parsePrivateDict).not.toThrow();
@ -144,7 +144,7 @@ describe("CFFParser", function() {
} }
); );
it("parses a CharString having cntrmask", function() { it("parses a CharString having cntrmask", function () {
// prettier-ignore // prettier-ignore
var bytes = new Uint8Array([0, 1, // count var bytes = new Uint8Array([0, 1, // count
1, // offsetSize 1, // offsetSize
@ -171,7 +171,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 () {
const cffParser = new CFFParser( const cffParser = new CFFParser(
fontData, fontData,
{}, {},
@ -200,7 +200,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 () {
const cffParser = new CFFParser( const cffParser = new CFFParser(
fontData, fontData,
{}, {},
@ -224,7 +224,7 @@ describe("CFFParser", function() {
expect(result.seacs.length).toEqual(0); expect(result.seacs.length).toEqual(0);
}); });
it("parses a CharString endchar no args", function() { it("parses a CharString endchar no args", function () {
// prettier-ignore // prettier-ignore
var bytes = new Uint8Array([0, 1, // count var bytes = new Uint8Array([0, 1, // count
1, // offsetSize 1, // offsetSize
@ -241,12 +241,12 @@ describe("CFFParser", function() {
expect(result.seacs.length).toEqual(0); expect(result.seacs.length).toEqual(0);
}); });
it("parses predefined charsets", function() { it("parses predefined charsets", function () {
var charset = parser.parseCharsets(0, 0, null, true); var charset = parser.parseCharsets(0, 0, null, true);
expect(charset.predefined).toEqual(true); expect(charset.predefined).toEqual(true);
}); });
it("parses charset format 0", function() { it("parses charset format 0", function () {
// The first three bytes make the offset large enough to skip predefined. // The first three bytes make the offset large enough to skip predefined.
// prettier-ignore // prettier-ignore
var bytes = new Uint8Array([0x00, 0x00, 0x00, var bytes = new Uint8Array([0x00, 0x00, 0x00,
@ -262,7 +262,7 @@ describe("CFFParser", function() {
expect(charset.charset[1]).toEqual(2); expect(charset.charset[1]).toEqual(2);
}); });
it("parses charset format 1", function() { it("parses charset format 1", function () {
// The first three bytes make the offset large enough to skip predefined. // The first three bytes make the offset large enough to skip predefined.
// prettier-ignore // prettier-ignore
var bytes = new Uint8Array([0x00, 0x00, 0x00, var bytes = new Uint8Array([0x00, 0x00, 0x00,
@ -279,7 +279,7 @@ describe("CFFParser", function() {
expect(charset.charset).toEqual([0, 8, 9]); expect(charset.charset).toEqual([0, 8, 9]);
}); });
it("parses charset format 2", function() { it("parses charset format 2", function () {
// format 2 is the same as format 1 but the left is card16 // format 2 is the same as format 1 but the left is card16
// The first three bytes make the offset large enough to skip predefined. // The first three bytes make the offset large enough to skip predefined.
// prettier-ignore // prettier-ignore
@ -297,7 +297,7 @@ describe("CFFParser", function() {
expect(charset.charset).toEqual([0, 8, 9]); expect(charset.charset).toEqual([0, 8, 9]);
}); });
it("parses encoding format 0", function() { it("parses encoding format 0", function () {
// The first two bytes make the offset large enough to skip predefined. // The first two bytes make the offset large enough to skip predefined.
// prettier-ignore // prettier-ignore
var bytes = new Uint8Array([0x00, 0x00, var bytes = new Uint8Array([0x00, 0x00,
@ -310,7 +310,7 @@ describe("CFFParser", function() {
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 () {
// The first two bytes make the offset large enough to skip predefined. // The first two bytes make the offset large enough to skip predefined.
// prettier-ignore // prettier-ignore
var bytes = new Uint8Array([0x00, 0x00, var bytes = new Uint8Array([0x00, 0x00,
@ -326,7 +326,7 @@ describe("CFFParser", function() {
); );
}); });
it("parses fdselect format 0", function() { it("parses fdselect format 0", function () {
// prettier-ignore // prettier-ignore
var bytes = new Uint8Array([0x00, // format var bytes = new Uint8Array([0x00, // format
0x00, // gid: 0 fd: 0 0x00, // gid: 0 fd: 0
@ -339,7 +339,7 @@ describe("CFFParser", function() {
expect(fdSelect.format).toEqual(0); expect(fdSelect.format).toEqual(0);
}); });
it("parses fdselect format 3", function() { it("parses fdselect format 3", function () {
// prettier-ignore // prettier-ignore
var bytes = new Uint8Array([0x03, // format var bytes = new Uint8Array([0x03, // format
0x00, 0x02, // range count 0x00, 0x02, // range count
@ -356,7 +356,7 @@ describe("CFFParser", function() {
expect(fdSelect.format).toEqual(3); expect(fdSelect.format).toEqual(3);
}); });
it("parses invalid fdselect format 3 (bug 1146106)", function() { it("parses invalid fdselect format 3 (bug 1146106)", function () {
// prettier-ignore // prettier-ignore
var bytes = new Uint8Array([0x03, // format var bytes = new Uint8Array([0x03, // format
0x00, 0x02, // range count 0x00, 0x02, // range count
@ -376,7 +376,7 @@ describe("CFFParser", function() {
// TODO fdArray // TODO fdArray
}); });
describe("CFFCompiler", function() { describe("CFFCompiler", function () {
function testParser(bytes) { function testParser(bytes) {
bytes = new Uint8Array(bytes); bytes = new Uint8Array(bytes);
return new CFFParser( return new CFFParser(
@ -390,7 +390,7 @@ describe("CFFCompiler", function() {
); );
} }
it("encodes integers", function() { it("encodes integers", function () {
var c = new CFFCompiler(); var c = new CFFCompiler();
// all the examples from the spec // all the examples from the spec
expect(c.encodeInteger(0)).toEqual([0x8b]); expect(c.encodeInteger(0)).toEqual([0x8b]);
@ -404,13 +404,13 @@ 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 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]);
}); });
it("sanitizes name index", function() { it("sanitizes name index", function () {
var c = new CFFCompiler(); var c = new CFFCompiler();
var nameIndexCompiled = c.compileNameIndex(["[a"]); var nameIndexCompiled = c.compileNameIndex(["[a"]);
var parser = testParser(nameIndexCompiled); var parser = testParser(nameIndexCompiled);
@ -429,7 +429,7 @@ describe("CFFCompiler", function() {
expect(names[0].length).toEqual(127); expect(names[0].length).toEqual(127);
}); });
it("compiles fdselect format 0", function() { it("compiles fdselect format 0", function () {
var fdSelect = new CFFFDSelect(0, [3, 2, 1]); var fdSelect = new CFFFDSelect(0, [3, 2, 1]);
var c = new CFFCompiler(); var c = new CFFCompiler();
var out = c.compileFDSelect(fdSelect); var out = c.compileFDSelect(fdSelect);
@ -441,7 +441,7 @@ describe("CFFCompiler", function() {
]); ]);
}); });
it("compiles fdselect format 3", function() { it("compiles fdselect format 3", function () {
var fdSelect = new CFFFDSelect(3, [0, 0, 1, 1]); var fdSelect = new CFFFDSelect(3, [0, 0, 1, 1]);
var c = new CFFCompiler(); var c = new CFFCompiler();
var out = c.compileFDSelect(fdSelect); var out = c.compileFDSelect(fdSelect);
@ -460,7 +460,7 @@ describe("CFFCompiler", function() {
]); ]);
}); });
it("compiles fdselect format 3, single range", function() { it("compiles fdselect format 3, single range", function () {
var fdSelect = new CFFFDSelect(3, [0, 0]); var fdSelect = new CFFFDSelect(3, [0, 0]);
var c = new CFFCompiler(); var c = new CFFCompiler();
var out = c.compileFDSelect(fdSelect); var out = c.compileFDSelect(fdSelect);
@ -476,7 +476,7 @@ describe("CFFCompiler", function() {
]); ]);
}); });
it("compiles charset of CID font", function() { it("compiles charset of CID font", function () {
var charset = new CFFCharset(); var charset = new CFFCharset();
var c = new CFFCompiler(); var c = new CFFCompiler();
var numGlyphs = 7; var numGlyphs = 7;
@ -491,7 +491,7 @@ describe("CFFCompiler", function() {
]); ]);
}); });
it("compiles charset of non CID font", function() { it("compiles charset of non CID font", function () {
var charset = new CFFCharset(false, 0, ["space", "exclam"]); var charset = new CFFCharset(false, 0, ["space", "exclam"]);
var c = new CFFCompiler(); var c = new CFFCompiler();
var numGlyphs = 3; var numGlyphs = 3;

View File

@ -31,6 +31,6 @@ if (!isNodeJS) {
setVerbosityLevel(VerbosityLevel.ERRORS); setVerbosityLevel(VerbosityLevel.ERRORS);
// Set the network stream factory for the unit-tests. // Set the network stream factory for the unit-tests.
setPDFNetworkStreamFactory(function(params) { setPDFNetworkStreamFactory(function (params) {
return new PDFNodeStream(params); return new PDFNodeStream(params);
}); });

View File

@ -26,10 +26,10 @@ var cMapUrl = {
}; };
var cMapPacked = true; var cMapPacked = true;
describe("cmap", function() { describe("cmap", function () {
var fetchBuiltInCMap; var fetchBuiltInCMap;
beforeAll(function(done) { beforeAll(function (done) {
// Allow CMap testing in Node.js, e.g. for Travis. // Allow CMap testing in Node.js, e.g. for Travis.
var CMapReaderFactory; var CMapReaderFactory;
if (isNodeJS) { if (isNodeJS) {
@ -44,7 +44,7 @@ describe("cmap", function() {
}); });
} }
fetchBuiltInCMap = function(name) { fetchBuiltInCMap = function (name) {
return CMapReaderFactory.fetch({ return CMapReaderFactory.fetch({
name, name,
}); });
@ -52,11 +52,11 @@ describe("cmap", function() {
done(); done();
}); });
afterAll(function() { afterAll(function () {
fetchBuiltInCMap = null; fetchBuiltInCMap = null;
}); });
it("parses beginbfchar", function(done) { it("parses beginbfchar", function (done) {
// prettier-ignore // prettier-ignore
var str = "2 beginbfchar\n" + var str = "2 beginbfchar\n" +
"<03> <00>\n" + "<03> <00>\n" +
@ -65,17 +65,17 @@ describe("cmap", function() {
var stream = new StringStream(str); var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise cmapPromise
.then(function(cmap) { .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));
expect(cmap.lookup(0x05)).toBeUndefined(); expect(cmap.lookup(0x05)).toBeUndefined();
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
it("parses beginbfrange with range", function(done) { it("parses beginbfrange with range", function (done) {
// prettier-ignore // prettier-ignore
var str = "1 beginbfrange\n" + var str = "1 beginbfrange\n" +
"<06> <0B> 0\n" + "<06> <0B> 0\n" +
@ -83,18 +83,18 @@ describe("cmap", function() {
var stream = new StringStream(str); var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise cmapPromise
.then(function(cmap) { .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));
expect(cmap.lookup(0x0b)).toEqual(String.fromCharCode(0x05)); expect(cmap.lookup(0x0b)).toEqual(String.fromCharCode(0x05));
expect(cmap.lookup(0x0c)).toBeUndefined(); expect(cmap.lookup(0x0c)).toBeUndefined();
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
it("parses beginbfrange with array", function(done) { it("parses beginbfrange with array", function (done) {
// prettier-ignore // prettier-ignore
var str = "1 beginbfrange\n" + var str = "1 beginbfrange\n" +
"<0D> <12> [ 0 1 2 3 4 5 ]\n" + "<0D> <12> [ 0 1 2 3 4 5 ]\n" +
@ -102,18 +102,18 @@ describe("cmap", function() {
var stream = new StringStream(str); var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise cmapPromise
.then(function(cmap) { .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);
expect(cmap.lookup(0x12)).toEqual(0x05); expect(cmap.lookup(0x12)).toEqual(0x05);
expect(cmap.lookup(0x13)).toBeUndefined(); expect(cmap.lookup(0x13)).toBeUndefined();
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
it("parses begincidchar", function(done) { it("parses begincidchar", function (done) {
// prettier-ignore // prettier-ignore
var str = "1 begincidchar\n" + var str = "1 begincidchar\n" +
"<14> 0\n" + "<14> 0\n" +
@ -121,16 +121,16 @@ describe("cmap", function() {
var stream = new StringStream(str); var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise cmapPromise
.then(function(cmap) { .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();
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
it("parses begincidrange", function(done) { it("parses begincidrange", function (done) {
// prettier-ignore // prettier-ignore
var str = "1 begincidrange\n" + var str = "1 begincidrange\n" +
"<0016> <001B> 0\n" + "<0016> <001B> 0\n" +
@ -138,18 +138,18 @@ describe("cmap", function() {
var stream = new StringStream(str); var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise cmapPromise
.then(function(cmap) { .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);
expect(cmap.lookup(0x1b)).toEqual(0x05); expect(cmap.lookup(0x1b)).toEqual(0x05);
expect(cmap.lookup(0x1c)).toBeUndefined(); expect(cmap.lookup(0x1c)).toBeUndefined();
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
it("decodes codespace ranges", function(done) { it("decodes codespace ranges", function (done) {
// prettier-ignore // prettier-ignore
var str = "1 begincodespacerange\n" + var str = "1 begincodespacerange\n" +
"<01> <02>\n" + "<01> <02>\n" +
@ -158,7 +158,7 @@ describe("cmap", function() {
var stream = new StringStream(str); var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise cmapPromise
.then(function(cmap) { .then(function (cmap) {
var c = {}; var c = {};
cmap.readCharCode(String.fromCharCode(1), 0, c); cmap.readCharCode(String.fromCharCode(1), 0, c);
expect(c.charcode).toEqual(1); expect(c.charcode).toEqual(1);
@ -168,11 +168,11 @@ describe("cmap", function() {
expect(c.length).toEqual(4); expect(c.length).toEqual(4);
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
it("decodes 4 byte codespace ranges", function(done) { it("decodes 4 byte codespace ranges", function (done) {
// prettier-ignore // prettier-ignore
var str = "1 begincodespacerange\n" + var str = "1 begincodespacerange\n" +
"<8EA1A1A1> <8EA1FEFE>\n" + "<8EA1A1A1> <8EA1FEFE>\n" +
@ -180,18 +180,18 @@ describe("cmap", function() {
var stream = new StringStream(str); var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise cmapPromise
.then(function(cmap) { .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);
expect(c.charcode).toEqual(0x8ea1a1a1); expect(c.charcode).toEqual(0x8ea1a1a1);
expect(c.length).toEqual(4); expect(c.length).toEqual(4);
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
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 StringStream(str);
var cmapPromise = CMapFactory.create({ var cmapPromise = CMapFactory.create({
@ -200,7 +200,7 @@ describe("cmap", function() {
useCMap: null, useCMap: null,
}); });
cmapPromise cmapPromise
.then(function(cmap) { .then(function (cmap) {
expect(cmap instanceof CMap).toEqual(true); expect(cmap instanceof CMap).toEqual(true);
expect(cmap.useCMap).not.toBeNull(); expect(cmap.useCMap).not.toBeNull();
expect(cmap.builtInCMap).toBeFalsy(); expect(cmap.builtInCMap).toBeFalsy();
@ -208,44 +208,44 @@ describe("cmap", function() {
expect(cmap.isIdentityCMap).toEqual(false); expect(cmap.isIdentityCMap).toEqual(false);
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
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 StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise cmapPromise
.then(function(cmap) { .then(function (cmap) {
expect(cmap.name).toEqual("Identity-H"); expect(cmap.name).toEqual("Identity-H");
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
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 StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream }); var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise cmapPromise
.then(function(cmap) { .then(function (cmap) {
expect(cmap.vertical).toEqual(true); expect(cmap.vertical).toEqual(true);
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
it("loads built in cmap", function(done) { it("loads built in cmap", function (done) {
var cmapPromise = CMapFactory.create({ var cmapPromise = CMapFactory.create({
encoding: Name.get("Adobe-Japan1-1"), encoding: Name.get("Adobe-Japan1-1"),
fetchBuiltInCMap, fetchBuiltInCMap,
useCMap: null, useCMap: null,
}); });
cmapPromise cmapPromise
.then(function(cmap) { .then(function (cmap) {
expect(cmap instanceof CMap).toEqual(true); expect(cmap instanceof CMap).toEqual(true);
expect(cmap.useCMap).toBeNull(); expect(cmap.useCMap).toBeNull();
expect(cmap.builtInCMap).toBeTruthy(); expect(cmap.builtInCMap).toBeTruthy();
@ -253,42 +253,42 @@ describe("cmap", function() {
expect(cmap.isIdentityCMap).toEqual(false); expect(cmap.isIdentityCMap).toEqual(false);
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
it("loads built in identity cmap", function(done) { it("loads built in identity cmap", function (done) {
var cmapPromise = CMapFactory.create({ var cmapPromise = CMapFactory.create({
encoding: Name.get("Identity-H"), encoding: Name.get("Identity-H"),
fetchBuiltInCMap, fetchBuiltInCMap,
useCMap: null, useCMap: null,
}); });
cmapPromise cmapPromise
.then(function(cmap) { .then(function (cmap) {
expect(cmap instanceof IdentityCMap).toEqual(true); expect(cmap instanceof 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 () {
return cmap.isIdentityCMap; return cmap.isIdentityCMap;
}).toThrow(new Error("should not access .isIdentityCMap")); }).toThrow(new Error("should not access .isIdentityCMap"));
done(); done();
}) })
.catch(function(reason) { .catch(function (reason) {
done.fail(reason); done.fail(reason);
}); });
}); });
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 = CMapFactory.create({
encoding: Name.get("null"), encoding: Name.get("null"),
fetchBuiltInCMap, fetchBuiltInCMap,
useCMap: null, useCMap: null,
}); });
cmapPromise.then( cmapPromise.then(
function() { function () {
done.fail("No CMap should be loaded"); done.fail("No CMap should be loaded");
}, },
function(reason) { function (reason) {
expect(reason instanceof Error).toEqual(true); expect(reason instanceof Error).toEqual(true);
expect(reason.message).toEqual("Unknown CMap name: null"); expect(reason.message).toEqual("Unknown CMap name: null");
done(); done();
@ -296,7 +296,7 @@ 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 var CMapReaderFactory = isNodeJS
? new NodeCMapReaderFactory({}) ? new NodeCMapReaderFactory({})
@ -312,10 +312,10 @@ describe("cmap", function() {
useCMap: null, useCMap: null,
}); });
cmapPromise.then( cmapPromise.then(
function() { function () {
done.fail("No CMap should be loaded"); done.fail("No CMap should be loaded");
}, },
function(reason) { function (reason) {
expect(reason instanceof Error).toEqual(true); expect(reason instanceof Error).toEqual(true);
expect(reason.message).toEqual( expect(reason.message).toEqual(
'The CMap "baseUrl" parameter must be specified, ensure that ' + 'The CMap "baseUrl" parameter must be specified, ensure that ' +
@ -326,7 +326,7 @@ describe("cmap", function() {
); );
}); });
it("attempts to load a built-in CMap with inconsistent API parameters", function(done) { it("attempts to load a built-in CMap with inconsistent API parameters", function (done) {
function tmpFetchBuiltInCMap(name) { function tmpFetchBuiltInCMap(name) {
let CMapReaderFactory; let CMapReaderFactory;
if (isNodeJS) { if (isNodeJS) {
@ -351,10 +351,10 @@ describe("cmap", function() {
useCMap: null, useCMap: null,
}); });
cmapPromise.then( cmapPromise.then(
function() { function () {
done.fail("No CMap should be loaded"); done.fail("No CMap should be loaded");
}, },
function(reason) { function (reason) {
expect(reason instanceof Error).toEqual(true); expect(reason instanceof Error).toEqual(true);
const message = reason.message; const message = reason.message;
expect(message.startsWith("Unable to load CMap at: ")).toEqual(true); expect(message.startsWith("Unable to load CMap at: ")).toEqual(true);

View File

@ -19,16 +19,16 @@ import { ColorSpace } from "../../src/core/colorspace.js";
import { PDFFunctionFactory } from "../../src/core/function.js"; import { PDFFunctionFactory } from "../../src/core/function.js";
import { XRefMock } from "./test_utils.js"; import { XRefMock } from "./test_utils.js";
describe("colorspace", function() { describe("colorspace", function () {
describe("ColorSpace", function() { describe("ColorSpace", function () {
it("should be true if decode is not an array", function() { it("should be true if decode is not an array", function () {
expect(ColorSpace.isDefaultDecode("string", 0)).toBeTruthy(); expect(ColorSpace.isDefaultDecode("string", 0)).toBeTruthy();
}); });
it("should be true if length of decode array is not correct", function() { it("should be true if length of decode array is not correct", function () {
expect(ColorSpace.isDefaultDecode([0], 1)).toBeTruthy(); expect(ColorSpace.isDefaultDecode([0], 1)).toBeTruthy();
expect(ColorSpace.isDefaultDecode([0, 1, 0], 1)).toBeTruthy(); expect(ColorSpace.isDefaultDecode([0, 1, 0], 1)).toBeTruthy();
}); });
it("should be true if decode map matches the default decode map", function() { it("should be true if decode map matches the default decode map", function () {
expect(ColorSpace.isDefaultDecode([], 0)).toBeTruthy(); expect(ColorSpace.isDefaultDecode([], 0)).toBeTruthy();
expect(ColorSpace.isDefaultDecode([0, 0], 1)).toBeFalsy(); expect(ColorSpace.isDefaultDecode([0, 0], 1)).toBeFalsy();
@ -46,8 +46,8 @@ describe("colorspace", function() {
}); });
}); });
describe("DeviceGrayCS", function() { describe("DeviceGrayCS", function () {
it("should handle the case when cs is a Name object", function() { it("should handle the case when cs is a Name object", function () {
const cs = Name.get("DeviceGray"); const cs = Name.get("DeviceGray");
const xref = new XRefMock([ const xref = new XRefMock([
{ {
@ -92,7 +92,7 @@ describe("colorspace", function() {
expect(colorSpace.isPassthrough(8)).toBeFalsy(); expect(colorSpace.isPassthrough(8)).toBeFalsy();
expect(testDest).toEqual(expectedDest); expect(testDest).toEqual(expectedDest);
}); });
it("should handle the case when cs is an indirect object", function() { it("should handle the case when cs is an indirect object", function () {
const cs = Ref.get(10, 0); const cs = Ref.get(10, 0);
const xref = new XRefMock([ const xref = new XRefMock([
{ {
@ -132,8 +132,8 @@ describe("colorspace", function() {
}); });
}); });
describe("DeviceRgbCS", function() { describe("DeviceRgbCS", function () {
it("should handle the case when cs is a Name object", function() { it("should handle the case when cs is a Name object", function () {
const cs = Name.get("DeviceRGB"); const cs = Name.get("DeviceRGB");
const xref = new XRefMock([ const xref = new XRefMock([
{ {
@ -184,7 +184,7 @@ describe("colorspace", function() {
expect(colorSpace.isPassthrough(8)).toBeTruthy(); expect(colorSpace.isPassthrough(8)).toBeTruthy();
expect(testDest).toEqual(expectedDest); expect(testDest).toEqual(expectedDest);
}); });
it("should handle the case when cs is an indirect object", function() { it("should handle the case when cs is an indirect object", function () {
const cs = Ref.get(10, 0); const cs = Ref.get(10, 0);
const xref = new XRefMock([ const xref = new XRefMock([
{ {
@ -230,8 +230,8 @@ describe("colorspace", function() {
}); });
}); });
describe("DeviceCmykCS", function() { describe("DeviceCmykCS", function () {
it("should handle the case when cs is a Name object", function() { it("should handle the case when cs is a Name object", function () {
const cs = Name.get("DeviceCMYK"); const cs = Name.get("DeviceCMYK");
const xref = new XRefMock([ const xref = new XRefMock([
{ {
@ -282,7 +282,7 @@ describe("colorspace", function() {
expect(colorSpace.isPassthrough(8)).toBeFalsy(); expect(colorSpace.isPassthrough(8)).toBeFalsy();
expect(testDest).toEqual(expectedDest); expect(testDest).toEqual(expectedDest);
}); });
it("should handle the case when cs is an indirect object", function() { it("should handle the case when cs is an indirect object", function () {
const cs = Ref.get(10, 0); const cs = Ref.get(10, 0);
const xref = new XRefMock([ const xref = new XRefMock([
{ {
@ -328,8 +328,8 @@ describe("colorspace", function() {
}); });
}); });
describe("CalGrayCS", function() { describe("CalGrayCS", function () {
it("should handle the case when cs is an array", function() { it("should handle the case when cs is an array", function () {
const params = new Dict(); const params = new Dict();
params.set("WhitePoint", [1, 1, 1]); params.set("WhitePoint", [1, 1, 1]);
params.set("BlackPoint", [0, 0, 0]); params.set("BlackPoint", [0, 0, 0]);
@ -381,8 +381,8 @@ describe("colorspace", function() {
}); });
}); });
describe("CalRGBCS", function() { describe("CalRGBCS", function () {
it("should handle the case when cs is an array", function() { it("should handle the case when cs is an array", function () {
const params = new Dict(); const params = new Dict();
params.set("WhitePoint", [1, 1, 1]); params.set("WhitePoint", [1, 1, 1]);
params.set("BlackPoint", [0, 0, 0]); params.set("BlackPoint", [0, 0, 0]);
@ -434,8 +434,8 @@ describe("colorspace", function() {
}); });
}); });
describe("LabCS", function() { describe("LabCS", function () {
it("should handle the case when cs is an array", function() { it("should handle the case when cs is an array", function () {
const params = new Dict(); const params = new Dict();
params.set("WhitePoint", [1, 1, 1]); params.set("WhitePoint", [1, 1, 1]);
params.set("BlackPoint", [0, 0, 0]); params.set("BlackPoint", [0, 0, 0]);
@ -487,8 +487,8 @@ describe("colorspace", function() {
}); });
}); });
describe("IndexedCS", function() { describe("IndexedCS", function () {
it("should handle the case when cs is an array", function() { it("should handle the case when cs is an array", function () {
// prettier-ignore // prettier-ignore
const lookup = new Uint8Array([ const lookup = new Uint8Array([
23, 155, 35, 23, 155, 35,
@ -534,8 +534,8 @@ describe("colorspace", function() {
}); });
}); });
describe("AlternateCS", function() { describe("AlternateCS", function () {
it("should handle the case when cs is an array", function() { it("should handle the case when cs is an array", function () {
const fnDict = new Dict(); const fnDict = new Dict();
fnDict.set("FunctionType", 4); fnDict.set("FunctionType", 4);
fnDict.set("Domain", [0.0, 1.0]); fnDict.set("Domain", [0.0, 1.0]);

View File

@ -22,9 +22,9 @@ import {
} from "../../src/core/core_utils.js"; } from "../../src/core/core_utils.js";
import { XRefMock } from "./test_utils.js"; import { XRefMock } from "./test_utils.js";
describe("core_utils", function() { describe("core_utils", function () {
describe("getInheritableProperty", function() { describe("getInheritableProperty", function () {
it("handles non-dictionary arguments", function() { it("handles non-dictionary arguments", function () {
expect(getInheritableProperty({ dict: null, key: "foo" })).toEqual( expect(getInheritableProperty({ dict: null, key: "foo" })).toEqual(
undefined undefined
); );
@ -33,7 +33,7 @@ describe("core_utils", function() {
); );
}); });
it("handles dictionaries that do not contain the property", function() { it("handles dictionaries that do not contain the property", function () {
// Empty dictionary. // Empty dictionary.
const emptyDict = new Dict(); const emptyDict = new Dict();
expect(getInheritableProperty({ dict: emptyDict, key: "foo" })).toEqual( expect(getInheritableProperty({ dict: emptyDict, key: "foo" })).toEqual(
@ -48,7 +48,7 @@ describe("core_utils", function() {
); );
}); });
it("fetches the property if it is not inherited", function() { it("fetches the property if it is not inherited", function () {
const ref = Ref.get(10, 0); const ref = Ref.get(10, 0);
const xref = new XRefMock([{ ref, data: "quux" }]); const xref = new XRefMock([{ ref, data: "quux" }]);
const dict = new Dict(xref); const dict = new Dict(xref);
@ -64,7 +64,7 @@ describe("core_utils", function() {
).toEqual(["qux", "quux"]); ).toEqual(["qux", "quux"]);
}); });
it("fetches the property if it is inherited and present on one level", function() { it("fetches the property if it is inherited and present on one level", function () {
const ref = Ref.get(10, 0); const ref = Ref.get(10, 0);
const xref = new XRefMock([{ ref, data: "quux" }]); const xref = new XRefMock([{ ref, data: "quux" }]);
const firstDict = new Dict(xref); const firstDict = new Dict(xref);
@ -84,7 +84,7 @@ describe("core_utils", function() {
).toEqual(["qux", "quux"]); ).toEqual(["qux", "quux"]);
}); });
it("fetches the property if it is inherited and present on multiple levels", function() { it("fetches the property if it is inherited and present on multiple levels", function () {
const ref = Ref.get(10, 0); const ref = Ref.get(10, 0);
const xref = new XRefMock([{ ref, data: "quux" }]); const xref = new XRefMock([{ ref, data: "quux" }]);
const firstDict = new Dict(xref); const firstDict = new Dict(xref);
@ -122,7 +122,7 @@ describe("core_utils", function() {
]); ]);
}); });
it("stops searching when the loop limit is reached", function() { it("stops searching when the loop limit is reached", function () {
const dict = new Dict(); const dict = new Dict();
let currentDict = dict; let currentDict = dict;
let parentDict = null; let parentDict = null;
@ -147,16 +147,16 @@ describe("core_utils", function() {
}); });
}); });
describe("toRomanNumerals", function() { describe("toRomanNumerals", function () {
it("handles invalid arguments", function() { it("handles invalid arguments", function () {
for (const input of ["foo", -1, 0]) { for (const input of ["foo", -1, 0]) {
expect(function() { expect(function () {
toRomanNumerals(input); toRomanNumerals(input);
}).toThrow(new Error("The number should be a positive integer.")); }).toThrow(new Error("The number should be a positive integer."));
} }
}); });
it("converts numbers to uppercase Roman numerals", function() { it("converts numbers to uppercase Roman numerals", function () {
expect(toRomanNumerals(1)).toEqual("I"); expect(toRomanNumerals(1)).toEqual("I");
expect(toRomanNumerals(6)).toEqual("VI"); expect(toRomanNumerals(6)).toEqual("VI");
expect(toRomanNumerals(7)).toEqual("VII"); expect(toRomanNumerals(7)).toEqual("VII");
@ -169,7 +169,7 @@ describe("core_utils", function() {
expect(toRomanNumerals(2019)).toEqual("MMXIX"); expect(toRomanNumerals(2019)).toEqual("MMXIX");
}); });
it("converts numbers to lowercase Roman numerals", function() { it("converts numbers to lowercase Roman numerals", function () {
expect(toRomanNumerals(1, /* lowercase = */ true)).toEqual("i"); expect(toRomanNumerals(1, /* lowercase = */ true)).toEqual("i");
expect(toRomanNumerals(6, /* lowercase = */ true)).toEqual("vi"); expect(toRomanNumerals(6, /* lowercase = */ true)).toEqual("vi");
expect(toRomanNumerals(7, /* lowercase = */ true)).toEqual("vii"); expect(toRomanNumerals(7, /* lowercase = */ true)).toEqual("vii");
@ -183,13 +183,13 @@ describe("core_utils", function() {
}); });
}); });
describe("log2", function() { describe("log2", function () {
it("handles values smaller than/equal to zero", function() { it("handles values smaller than/equal to zero", function () {
expect(log2(0)).toEqual(0); expect(log2(0)).toEqual(0);
expect(log2(-1)).toEqual(0); expect(log2(-1)).toEqual(0);
}); });
it("handles values larger than zero", function() { it("handles values larger than zero", function () {
expect(log2(1)).toEqual(0); expect(log2(1)).toEqual(0);
expect(log2(2)).toEqual(1); expect(log2(2)).toEqual(1);
expect(log2(3)).toEqual(2); expect(log2(3)).toEqual(2);
@ -197,15 +197,15 @@ describe("core_utils", function() {
}); });
}); });
describe("isWhiteSpace", function() { describe("isWhiteSpace", function () {
it("handles space characters", function() { it("handles space characters", function () {
expect(isWhiteSpace(0x20)).toEqual(true); expect(isWhiteSpace(0x20)).toEqual(true);
expect(isWhiteSpace(0x09)).toEqual(true); expect(isWhiteSpace(0x09)).toEqual(true);
expect(isWhiteSpace(0x0d)).toEqual(true); expect(isWhiteSpace(0x0d)).toEqual(true);
expect(isWhiteSpace(0x0a)).toEqual(true); expect(isWhiteSpace(0x0a)).toEqual(true);
}); });
it("handles non-space characters", function() { it("handles non-space characters", function () {
expect(isWhiteSpace(0x0b)).toEqual(false); expect(isWhiteSpace(0x0b)).toEqual(false);
expect(isWhiteSpace(null)).toEqual(false); expect(isWhiteSpace(null)).toEqual(false);
expect(isWhiteSpace(undefined)).toEqual(false); expect(isWhiteSpace(undefined)).toEqual(false);

View File

@ -32,7 +32,7 @@ import {
stringToBytes, stringToBytes,
} from "../../src/shared/util.js"; } from "../../src/shared/util.js";
describe("crypto", function() { describe("crypto", function () {
function hex2binary(s) { function hex2binary(s) {
var digits = "0123456789ABCDEF"; var digits = "0123456789ABCDEF";
s = s.toUpperCase(); s = s.toUpperCase();
@ -50,43 +50,43 @@ describe("crypto", function() {
} }
// RFC 1321, A.5 Test suite // RFC 1321, A.5 Test suite
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 = stringToBytes("");
result = calculateMD5(input, 0, input.length); result = 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 = stringToBytes("a");
result = calculateMD5(input, 0, input.length); result = 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 = stringToBytes("abc");
result = calculateMD5(input, 0, input.length); result = 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 = stringToBytes("message digest");
result = calculateMD5(input, 0, input.length); result = 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 = stringToBytes("abcdefghijklmnopqrstuvwxyz");
result = calculateMD5(input, 0, input.length); result = 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( input = stringToBytes(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
@ -95,7 +95,7 @@ describe("crypto", function() {
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( input = stringToBytes(
"123456789012345678901234567890123456789012345678" + "123456789012345678901234567890123456789012345678" +
@ -108,8 +108,8 @@ describe("crypto", function() {
}); });
// http://www.freemedialibrary.com/index.php/RC4_test_vectors are used // http://www.freemedialibrary.com/index.php/RC4_test_vectors are used
describe("ARCFourCipher", function() { describe("ARCFourCipher", function () {
it("should pass test #1", function() { it("should pass test #1", 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");
@ -118,7 +118,7 @@ describe("crypto", function() {
expected = hex2binary("75b7878099e0c596"); expected = hex2binary("75b7878099e0c596");
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it("should pass test #2", function() { it("should pass test #2", 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");
@ -127,7 +127,7 @@ describe("crypto", function() {
expected = hex2binary("7494c2e7104b0879"); expected = hex2binary("7494c2e7104b0879");
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it("should pass test #3", function() { it("should pass test #3", 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");
@ -136,7 +136,7 @@ describe("crypto", function() {
expected = hex2binary("de188941a3375d3a"); expected = hex2binary("de188941a3375d3a");
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it("should pass test #4", function() { it("should pass test #4", 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");
@ -145,7 +145,7 @@ describe("crypto", function() {
expected = hex2binary("d6a141a7ec3c38dfbd61"); expected = hex2binary("d6a141a7ec3c38dfbd61");
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it("should pass test #5", function() { it("should pass test #5", function () {
var key, input, result, expected, cipher; var key, input, result, expected, cipher;
key = hex2binary("0123456789abcdef"); key = hex2binary("0123456789abcdef");
input = hex2binary( input = hex2binary(
@ -188,7 +188,7 @@ describe("crypto", function() {
); );
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it("should pass test #6", function() { it("should pass test #6", function () {
var key, input, result, expected, cipher; var key, input, result, expected, cipher;
key = hex2binary("fb029e3031323334"); key = hex2binary("fb029e3031323334");
input = hex2binary( input = hex2binary(
@ -205,7 +205,7 @@ describe("crypto", function() {
); );
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it("should pass test #7", function() { it("should pass test #7", function () {
var key, input, result, expected, cipher; var key, input, result, expected, cipher;
key = hex2binary("0123456789abcdef"); key = hex2binary("0123456789abcdef");
input = hex2binary( input = hex2binary(
@ -220,8 +220,8 @@ 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 = stringToBytes("abc");
result = calculateSHA256(input, 0, input.length); result = calculateSHA256(input, 0, input.length);
@ -230,7 +230,7 @@ describe("crypto", function() {
); );
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( input = stringToBytes(
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
@ -243,8 +243,8 @@ 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 = stringToBytes("abc");
result = calculateSHA384(input, 0, input.length); result = calculateSHA384(input, 0, input.length);
@ -254,7 +254,7 @@ describe("crypto", function() {
); );
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( input = stringToBytes(
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklm" + "abcdefghbcdefghicdefghijdefghijkefghijklfghijklm" +
@ -270,8 +270,8 @@ 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 = stringToBytes("abc");
result = calculateSHA512(input, 0, input.length); result = calculateSHA512(input, 0, input.length);
@ -282,7 +282,7 @@ describe("crypto", function() {
); );
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( input = stringToBytes(
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklm" + "abcdefghbcdefghicdefghijdefghijkefghijklfghijklm" +
@ -299,9 +299,9 @@ describe("crypto", function() {
}); });
}); });
describe("AES128", function() { describe("AES128", function () {
describe("Encryption", function() { describe("Encryption", function () {
it("should be able to encrypt a block", function() { it("should be able to encrypt a block", function () {
var input, key, result, expected, iv, cipher; var input, key, result, expected, iv, cipher;
input = hex2binary("00112233445566778899aabbccddeeff"); input = hex2binary("00112233445566778899aabbccddeeff");
key = hex2binary("000102030405060708090a0b0c0d0e0f"); key = hex2binary("000102030405060708090a0b0c0d0e0f");
@ -313,8 +313,8 @@ describe("crypto", function() {
}); });
}); });
describe("Decryption", function() { describe("Decryption", function () {
it("should be able to decrypt a block with IV in stream", function() { it("should be able to decrypt a block with IV in stream", function () {
var input, key, result, expected, cipher; var input, key, result, expected, cipher;
input = hex2binary( input = hex2binary(
"0000000000000000000000000000000069c4e0d86a7b0430d" + "0000000000000000000000000000000069c4e0d86a7b0430d" +
@ -329,9 +329,9 @@ describe("crypto", function() {
}); });
}); });
describe("AES256", function() { describe("AES256", function () {
describe("Encryption", function() { describe("Encryption", function () {
it("should be able to encrypt a block", function() { it("should be able to encrypt a block", function () {
var input, key, result, expected, iv, cipher; var input, key, result, expected, iv, cipher;
input = hex2binary("00112233445566778899aabbccddeeff"); input = hex2binary("00112233445566778899aabbccddeeff");
key = hex2binary( key = hex2binary(
@ -346,8 +346,8 @@ describe("crypto", function() {
}); });
}); });
describe("Decryption", function() { describe("Decryption", function () {
it("should be able to decrypt a block with specified iv", function() { it("should be able to decrypt a block with specified iv", function () {
var input, key, result, expected, cipher, iv; var input, key, result, expected, cipher, iv;
input = hex2binary("8ea2b7ca516745bfeafc49904b496089"); input = hex2binary("8ea2b7ca516745bfeafc49904b496089");
key = hex2binary( key = hex2binary(
@ -360,7 +360,7 @@ describe("crypto", function() {
expected = hex2binary("00112233445566778899aabbccddeeff"); expected = hex2binary("00112233445566778899aabbccddeeff");
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
it("should be able to decrypt a block with IV in stream", function() { it("should be able to decrypt a block with IV in stream", function () {
var input, key, result, expected, cipher; var input, key, result, expected, cipher;
input = hex2binary( input = hex2binary(
"000000000000000000000000000000008ea2b7ca516745bf" + "000000000000000000000000000000008ea2b7ca516745bf" +
@ -378,8 +378,8 @@ 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 PDF17();
password = new Uint8Array([117, 115, 101, 114]); password = new Uint8Array([117, 115, 101, 114]);
@ -393,7 +393,7 @@ describe("crypto", function() {
expect(result).toEqual(true); expect(result).toEqual(true);
}); });
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 PDF17();
password = new Uint8Array([111, 119, 110, 101, 114]); password = new Uint8Array([111, 119, 110, 101, 114]);
@ -418,7 +418,7 @@ describe("crypto", function() {
expect(result).toEqual(true); expect(result).toEqual(true);
}); });
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 PDF17();
password = new Uint8Array([117, 115, 101, 114]); password = new Uint8Array([117, 115, 101, 114]);
@ -437,7 +437,7 @@ describe("crypto", function() {
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
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 PDF17();
@ -464,8 +464,8 @@ 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 PDF20();
password = new Uint8Array([117, 115, 101, 114]); password = new Uint8Array([117, 115, 101, 114]);
@ -479,7 +479,7 @@ describe("crypto", function() {
expect(result).toEqual(true); expect(result).toEqual(true);
}); });
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 PDF20();
password = new Uint8Array([111, 119, 110, 101, 114]); password = new Uint8Array([111, 119, 110, 101, 114]);
@ -504,7 +504,7 @@ describe("crypto", function() {
expect(result).toEqual(true); expect(result).toEqual(true);
}); });
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 PDF20();
password = new Uint8Array([117, 115, 101, 114]); password = new Uint8Array([117, 115, 101, 114]);
@ -523,7 +523,7 @@ describe("crypto", function() {
expect(result).toEqual(expected); expect(result).toEqual(expected);
}); });
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 PDF20();
@ -551,7 +551,7 @@ describe("crypto", function() {
}); });
}); });
describe("CipherTransformFactory", function() { describe("CipherTransformFactory", function () {
function buildDict(map) { function buildDict(map) {
var dict = new Dict(); var dict = new Dict();
for (var key in map) { for (var key in map) {
@ -602,7 +602,7 @@ describe("CipherTransformFactory", function() {
var fileId1, fileId2, dict1, dict2; var fileId1, fileId2, dict1, dict2;
var aes256Dict, aes256IsoDict, aes256BlankDict, aes256IsoBlankDict; var aes256Dict, aes256IsoDict, aes256BlankDict, aes256IsoBlankDict;
beforeAll(function(done) { beforeAll(function (done) {
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");
@ -741,61 +741,61 @@ describe("CipherTransformFactory", function() {
done(); done();
}); });
afterAll(function() { afterAll(function () {
fileId1 = fileId2 = dict1 = dict2 = null; fileId1 = fileId2 = dict1 = dict2 = null;
aes256Dict = aes256IsoDict = aes256BlankDict = aes256IsoBlankDict = null; aes256Dict = aes256IsoDict = aes256BlankDict = aes256IsoBlankDict = null;
}); });
describe("#ctor", function() { describe("#ctor", function () {
describe("AES256 Revision 5", function() { describe("AES256 Revision 5", function () {
it("should accept user password", function(done) { it("should accept user password", function (done) {
ensurePasswordCorrect(done, aes256Dict, fileId1, "user"); ensurePasswordCorrect(done, aes256Dict, fileId1, "user");
}); });
it("should accept owner password", function(done) { it("should accept owner password", function (done) {
ensurePasswordCorrect(done, aes256Dict, fileId1, "owner"); ensurePasswordCorrect(done, aes256Dict, fileId1, "owner");
}); });
it("should not accept blank password", function(done) { it("should not accept blank password", function (done) {
ensurePasswordNeeded(done, aes256Dict, fileId1); ensurePasswordNeeded(done, aes256Dict, fileId1);
}); });
it("should not accept wrong password", function(done) { it("should not accept wrong password", function (done) {
ensurePasswordIncorrect(done, aes256Dict, fileId1, "wrong"); ensurePasswordIncorrect(done, aes256Dict, fileId1, "wrong");
}); });
it("should accept blank password", function(done) { it("should accept blank password", function (done) {
ensurePasswordCorrect(done, aes256BlankDict, fileId1); ensurePasswordCorrect(done, aes256BlankDict, fileId1);
}); });
}); });
describe("AES256 Revision 6", function() { describe("AES256 Revision 6", function () {
it("should accept user password", function(done) { it("should accept user password", function (done) {
ensurePasswordCorrect(done, aes256IsoDict, fileId1, "user"); ensurePasswordCorrect(done, aes256IsoDict, fileId1, "user");
}); });
it("should accept owner password", function(done) { it("should accept owner password", function (done) {
ensurePasswordCorrect(done, aes256IsoDict, fileId1, "owner"); ensurePasswordCorrect(done, aes256IsoDict, fileId1, "owner");
}); });
it("should not accept blank password", function(done) { it("should not accept blank password", function (done) {
ensurePasswordNeeded(done, aes256IsoDict, fileId1); ensurePasswordNeeded(done, aes256IsoDict, fileId1);
}); });
it("should not accept wrong password", function(done) { it("should not accept wrong password", function (done) {
ensurePasswordIncorrect(done, aes256IsoDict, fileId1, "wrong"); ensurePasswordIncorrect(done, aes256IsoDict, fileId1, "wrong");
}); });
it("should accept blank password", function(done) { it("should accept blank password", function (done) {
ensurePasswordCorrect(done, aes256IsoBlankDict, fileId1); ensurePasswordCorrect(done, aes256IsoBlankDict, fileId1);
}); });
}); });
it("should accept user password", function(done) { it("should accept user password", function (done) {
ensurePasswordCorrect(done, dict1, fileId1, "123456"); ensurePasswordCorrect(done, dict1, fileId1, "123456");
}); });
it("should accept owner password", function(done) { it("should accept owner password", function (done) {
ensurePasswordCorrect(done, dict1, fileId1, "654321"); ensurePasswordCorrect(done, dict1, fileId1, "654321");
}); });
it("should not accept blank password", function(done) { it("should not accept blank password", function (done) {
ensurePasswordNeeded(done, dict1, fileId1); ensurePasswordNeeded(done, dict1, fileId1);
}); });
it("should not accept wrong password", function(done) { it("should not accept wrong password", function (done) {
ensurePasswordIncorrect(done, dict1, fileId1, "wrong"); ensurePasswordIncorrect(done, dict1, fileId1, "wrong");
}); });
it("should accept blank password", function(done) { it("should accept blank password", function (done) {
ensurePasswordCorrect(done, dict2, fileId2); ensurePasswordCorrect(done, dict2, fileId2);
}); });
}); });

View File

@ -28,7 +28,7 @@ function getTopLeftPixel(canvasContext) {
}; };
} }
describe("custom canvas rendering", function() { describe("custom canvas rendering", function () {
const transparentGetDocumentParams = buildGetDocumentParams( const transparentGetDocumentParams = buildGetDocumentParams(
"transparent.pdf" "transparent.pdf"
); );
@ -37,7 +37,7 @@ describe("custom canvas rendering", function() {
let loadingTask; let loadingTask;
let page; let page;
beforeAll(function(done) { beforeAll(function (done) {
if (isNodeJS) { if (isNodeJS) {
CanvasFactory = new NodeCanvasFactory(); CanvasFactory = new NodeCanvasFactory();
} else { } else {
@ -45,23 +45,23 @@ describe("custom canvas rendering", function() {
} }
loadingTask = getDocument(transparentGetDocumentParams); loadingTask = getDocument(transparentGetDocumentParams);
loadingTask.promise loadingTask.promise
.then(function(doc) { .then(function (doc) {
return doc.getPage(1); return doc.getPage(1);
}) })
.then(function(data) { .then(function (data) {
page = data; page = data;
done(); done();
}) })
.catch(done.fail); .catch(done.fail);
}); });
afterAll(function(done) { afterAll(function (done) {
CanvasFactory = null; CanvasFactory = null;
page = null; page = null;
loadingTask.destroy().then(done); loadingTask.destroy().then(done);
}); });
it("renders to canvas with a default white background", function(done) { it("renders to canvas with a default white background", function (done) {
var viewport = page.getViewport({ scale: 1 }); var viewport = page.getViewport({ scale: 1 });
var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height); var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
@ -70,7 +70,7 @@ describe("custom canvas rendering", function() {
viewport, viewport,
}); });
renderTask.promise renderTask.promise
.then(function() { .then(function () {
expect(getTopLeftPixel(canvasAndCtx.context)).toEqual({ expect(getTopLeftPixel(canvasAndCtx.context)).toEqual({
r: 255, r: 255,
g: 255, g: 255,
@ -83,7 +83,7 @@ describe("custom canvas rendering", function() {
.catch(done.fail); .catch(done.fail);
}); });
it("renders to canvas with a custom background", function(done) { it("renders to canvas with a custom background", function (done) {
var viewport = page.getViewport({ scale: 1 }); var viewport = page.getViewport({ scale: 1 });
var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height); var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
@ -93,7 +93,7 @@ describe("custom canvas rendering", function() {
background: "rgba(255,0,0,1.0)", background: "rgba(255,0,0,1.0)",
}); });
renderTask.promise renderTask.promise
.then(function() { .then(function () {
expect(getTopLeftPixel(canvasAndCtx.context)).toEqual({ expect(getTopLeftPixel(canvasAndCtx.context)).toEqual({
r: 255, r: 255,
g: 0, g: 0,

View File

@ -58,37 +58,37 @@ function withZlib(isZlibRequired, callback) {
return promise; return promise;
} }
describe("SVGGraphics", function() { describe("SVGGraphics", function () {
var loadingTask; var loadingTask;
var page; var page;
beforeAll(function(done) { beforeAll(function (done) {
loadingTask = getDocument( loadingTask = getDocument(
buildGetDocumentParams("xobject-image.pdf", { buildGetDocumentParams("xobject-image.pdf", {
nativeImageDecoderSupport: NativeImageDecoding.DISPLAY, nativeImageDecoderSupport: NativeImageDecoding.DISPLAY,
}) })
); );
loadingTask.promise.then(function(doc) { loadingTask.promise.then(function (doc) {
doc.getPage(1).then(function(firstPage) { doc.getPage(1).then(function (firstPage) {
page = firstPage; page = firstPage;
done(); done();
}); });
}); });
}); });
afterAll(function(done) { afterAll(function (done) {
loadingTask.destroy().then(done); loadingTask.destroy().then(done);
}); });
describe("paintImageXObject", function() { describe("paintImageXObject", function () {
function getSVGImage() { function getSVGImage() {
var svgGfx; var svgGfx;
return page return page
.getOperatorList() .getOperatorList()
.then(function(opList) { .then(function (opList) {
var forceDataSchema = true; var forceDataSchema = true;
svgGfx = new SVGGraphics(page.commonObjs, page.objs, forceDataSchema); svgGfx = new SVGGraphics(page.commonObjs, page.objs, forceDataSchema);
return svgGfx.loadDependencies(opList); return svgGfx.loadDependencies(opList);
}) })
.then(function() { .then(function () {
var svgImg; var svgImg;
// A mock to steal the svg:image element from paintInlineImageXObject. // A mock to steal the svg:image element from paintInlineImageXObject.
var elementContainer = { var elementContainer = {
@ -114,7 +114,7 @@ describe("SVGGraphics", function() {
}); });
} }
it('should fail require("zlib") unless in Node.js', function() { it('should fail require("zlib") unless in Node.js', function () {
function testFunc() { function testFunc() {
__non_webpack_require__("zlib"); __non_webpack_require__("zlib");
} }
@ -129,12 +129,12 @@ describe("SVGGraphics", function() {
} }
}); });
it("should produce a reasonably small svg:image", function(done) { it("should produce a reasonably small svg:image", function (done) {
if (!isNodeJS) { if (!isNodeJS) {
pending("zlib.deflateSync is not supported in non-Node environments."); pending("zlib.deflateSync is not supported in non-Node environments.");
} }
withZlib(true, getSVGImage) withZlib(true, getSVGImage)
.then(function(svgImg) { .then(function (svgImg) {
expect(svgImg.nodeName).toBe("svg:image"); expect(svgImg.nodeName).toBe("svg:image");
expect(svgImg.getAttributeNS(null, "width")).toBe("200px"); expect(svgImg.getAttributeNS(null, "width")).toBe("200px");
expect(svgImg.getAttributeNS(null, "height")).toBe("100px"); expect(svgImg.getAttributeNS(null, "height")).toBe("100px");
@ -150,9 +150,9 @@ describe("SVGGraphics", function() {
.then(done, done.fail); .then(done, done.fail);
}); });
it("should be able to produce a svg:image without zlib", function(done) { it("should be able to produce a svg:image without zlib", function (done) {
withZlib(false, getSVGImage) withZlib(false, getSVGImage)
.then(function(svgImg) { .then(function (svgImg) {
expect(svgImg.nodeName).toBe("svg:image"); expect(svgImg.nodeName).toBe("svg:image");
expect(svgImg.getAttributeNS(null, "width")).toBe("200px"); expect(svgImg.getAttributeNS(null, "width")).toBe("200px");
expect(svgImg.getAttributeNS(null, "height")).toBe("100px"); expect(svgImg.getAttributeNS(null, "height")).toBe("100px");

View File

@ -23,32 +23,32 @@ import {
} from "../../src/display/display_utils.js"; } from "../../src/display/display_utils.js";
import { isNodeJS } from "../../src/shared/is_node.js"; import { isNodeJS } from "../../src/shared/is_node.js";
describe("display_utils", function() { describe("display_utils", function () {
describe("DOMCanvasFactory", function() { describe("DOMCanvasFactory", function () {
let canvasFactory; let canvasFactory;
beforeAll(function(done) { beforeAll(function (done) {
canvasFactory = new DOMCanvasFactory(); canvasFactory = new DOMCanvasFactory();
done(); done();
}); });
afterAll(function() { afterAll(function () {
canvasFactory = null; canvasFactory = null;
}); });
it("`create` should throw an error if the dimensions are invalid", function() { it("`create` should throw an error if the dimensions are invalid", function () {
// Invalid width. // Invalid width.
expect(function() { expect(function () {
return canvasFactory.create(-1, 1); return canvasFactory.create(-1, 1);
}).toThrow(new Error("Invalid canvas size")); }).toThrow(new Error("Invalid canvas size"));
// Invalid height. // Invalid height.
expect(function() { expect(function () {
return canvasFactory.create(1, -1); return canvasFactory.create(1, -1);
}).toThrow(new Error("Invalid canvas size")); }).toThrow(new Error("Invalid canvas size"));
}); });
it("`create` should return a canvas if the dimensions are valid", function() { it("`create` should return a canvas if the dimensions are valid", function () {
if (isNodeJS) { if (isNodeJS) {
pending("Document is not supported in Node.js."); pending("Document is not supported in Node.js.");
} }
@ -60,29 +60,29 @@ describe("display_utils", function() {
expect(canvas.height).toBe(40); expect(canvas.height).toBe(40);
}); });
it("`reset` should throw an error if no canvas is provided", function() { it("`reset` should throw an error if no canvas is provided", function () {
const canvasAndContext = { canvas: null, context: null }; const canvasAndContext = { canvas: null, context: null };
expect(function() { expect(function () {
return canvasFactory.reset(canvasAndContext, 20, 40); return canvasFactory.reset(canvasAndContext, 20, 40);
}).toThrow(new Error("Canvas is not specified")); }).toThrow(new Error("Canvas is not specified"));
}); });
it("`reset` should throw an error if the dimensions are invalid", function() { it("`reset` should throw an error if the dimensions are invalid", function () {
const canvasAndContext = { canvas: "foo", context: "bar" }; const canvasAndContext = { canvas: "foo", context: "bar" };
// Invalid width. // Invalid width.
expect(function() { expect(function () {
return canvasFactory.reset(canvasAndContext, -1, 1); return canvasFactory.reset(canvasAndContext, -1, 1);
}).toThrow(new Error("Invalid canvas size")); }).toThrow(new Error("Invalid canvas size"));
// Invalid height. // Invalid height.
expect(function() { expect(function () {
return canvasFactory.reset(canvasAndContext, 1, -1); return canvasFactory.reset(canvasAndContext, 1, -1);
}).toThrow(new Error("Invalid canvas size")); }).toThrow(new Error("Invalid canvas size"));
}); });
it("`reset` should alter the canvas/context if the dimensions are valid", function() { it("`reset` should alter the canvas/context if the dimensions are valid", function () {
if (isNodeJS) { if (isNodeJS) {
pending("Document is not supported in Node.js."); pending("Document is not supported in Node.js.");
} }
@ -97,13 +97,13 @@ describe("display_utils", function() {
expect(canvas.height).toBe(80); expect(canvas.height).toBe(80);
}); });
it("`destroy` should throw an error if no canvas is provided", function() { it("`destroy` should throw an error if no canvas is provided", function () {
expect(function() { expect(function () {
return canvasFactory.destroy({}); return canvasFactory.destroy({});
}).toThrow(new Error("Canvas is not specified")); }).toThrow(new Error("Canvas is not specified"));
}); });
it("`destroy` should clear the canvas/context", function() { it("`destroy` should clear the canvas/context", function () {
if (isNodeJS) { if (isNodeJS) {
pending("Document is not supported in Node.js."); pending("Document is not supported in Node.js.");
} }
@ -117,31 +117,31 @@ describe("display_utils", function() {
}); });
}); });
describe("DOMSVGFactory", function() { describe("DOMSVGFactory", function () {
let svgFactory; let svgFactory;
beforeAll(function(done) { beforeAll(function (done) {
svgFactory = new DOMSVGFactory(); svgFactory = new DOMSVGFactory();
done(); done();
}); });
afterAll(function() { afterAll(function () {
svgFactory = null; svgFactory = null;
}); });
it("`create` should throw an error if the dimensions are invalid", function() { it("`create` should throw an error if the dimensions are invalid", function () {
// Invalid width. // Invalid width.
expect(function() { expect(function () {
return svgFactory.create(-1, 0); return svgFactory.create(-1, 0);
}).toThrow(new Error("Invalid SVG dimensions")); }).toThrow(new Error("Invalid SVG dimensions"));
// Invalid height. // Invalid height.
expect(function() { expect(function () {
return svgFactory.create(0, -1); return svgFactory.create(0, -1);
}).toThrow(new Error("Invalid SVG dimensions")); }).toThrow(new Error("Invalid SVG dimensions"));
}); });
it("`create` should return an SVG element if the dimensions are valid", function() { it("`create` should return an SVG element if the dimensions are valid", function () {
if (isNodeJS) { if (isNodeJS) {
pending("Document is not supported in Node.js."); pending("Document is not supported in Node.js.");
} }
@ -155,13 +155,13 @@ describe("display_utils", function() {
expect(svg.getAttribute("viewBox")).toBe("0 0 20 40"); expect(svg.getAttribute("viewBox")).toBe("0 0 20 40");
}); });
it("`createElement` should throw an error if the type is not a string", function() { it("`createElement` should throw an error if the type is not a string", function () {
expect(function() { expect(function () {
return svgFactory.createElement(true); return svgFactory.createElement(true);
}).toThrow(new Error("Invalid SVG element type")); }).toThrow(new Error("Invalid SVG element type"));
}); });
it("`createElement` should return an SVG element if the type is valid", function() { it("`createElement` should return an SVG element if the type is valid", function () {
if (isNodeJS) { if (isNodeJS) {
pending("Document is not supported in Node.js."); pending("Document is not supported in Node.js.");
} }
@ -171,55 +171,55 @@ describe("display_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 () {
const url = "https://server.org/filename.pdf"; const url = "https://server.org/filename.pdf";
expect(getFilenameFromUrl(url)).toEqual("filename.pdf"); expect(getFilenameFromUrl(url)).toEqual("filename.pdf");
}); });
it("should get the filename from a relative URL", function() { it("should get the filename from a relative URL", function () {
const url = "../../filename.pdf"; const url = "../../filename.pdf";
expect(getFilenameFromUrl(url)).toEqual("filename.pdf"); expect(getFilenameFromUrl(url)).toEqual("filename.pdf");
}); });
it("should get the filename from a URL with an anchor", function() { it("should get the filename from a URL with an anchor", function () {
const url = "https://server.org/filename.pdf#foo"; const url = "https://server.org/filename.pdf#foo";
expect(getFilenameFromUrl(url)).toEqual("filename.pdf"); expect(getFilenameFromUrl(url)).toEqual("filename.pdf");
}); });
it("should get the filename from a URL with query parameters", function() { it("should get the filename from a URL with query parameters", function () {
const url = "https://server.org/filename.pdf?foo=bar"; const url = "https://server.org/filename.pdf?foo=bar";
expect(getFilenameFromUrl(url)).toEqual("filename.pdf"); expect(getFilenameFromUrl(url)).toEqual("filename.pdf");
}); });
}); });
describe("isValidFetchUrl", function() { describe("isValidFetchUrl", function () {
it("handles invalid Fetch URLs", function() { it("handles invalid Fetch URLs", function () {
expect(isValidFetchUrl(null)).toEqual(false); expect(isValidFetchUrl(null)).toEqual(false);
expect(isValidFetchUrl(100)).toEqual(false); expect(isValidFetchUrl(100)).toEqual(false);
expect(isValidFetchUrl("foo")).toEqual(false); expect(isValidFetchUrl("foo")).toEqual(false);
expect(isValidFetchUrl("/foo", 100)).toEqual(false); expect(isValidFetchUrl("/foo", 100)).toEqual(false);
}); });
it("handles relative Fetch URLs", function() { it("handles relative Fetch URLs", function () {
expect(isValidFetchUrl("/foo", "file://www.example.com")).toEqual(false); expect(isValidFetchUrl("/foo", "file://www.example.com")).toEqual(false);
expect(isValidFetchUrl("/foo", "http://www.example.com")).toEqual(true); expect(isValidFetchUrl("/foo", "http://www.example.com")).toEqual(true);
}); });
it("handles unsupported Fetch protocols", function() { it("handles unsupported Fetch protocols", function () {
expect(isValidFetchUrl("file://www.example.com")).toEqual(false); expect(isValidFetchUrl("file://www.example.com")).toEqual(false);
expect(isValidFetchUrl("ftp://www.example.com")).toEqual(false); expect(isValidFetchUrl("ftp://www.example.com")).toEqual(false);
}); });
it("handles supported Fetch protocols", function() { it("handles supported Fetch protocols", function () {
expect(isValidFetchUrl("http://www.example.com")).toEqual(true); expect(isValidFetchUrl("http://www.example.com")).toEqual(true);
expect(isValidFetchUrl("https://www.example.com")).toEqual(true); expect(isValidFetchUrl("https://www.example.com")).toEqual(true);
}); });
}); });
describe("PDFDateString", function() { describe("PDFDateString", function () {
describe("toDateObject", function() { describe("toDateObject", function () {
it("converts PDF date strings to JavaScript `Date` objects", function() { it("converts PDF date strings to JavaScript `Date` objects", function () {
const expectations = { const expectations = {
undefined: null, undefined: null,
null: null, null: null,

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