Merge pull request #12563 from Snuffleupagus/rm-SystemJS-worker

[api-minor] Remove SystemJS usage, in development mode, from the worker
This commit is contained in:
Jonas Jenwald 2023-05-03 23:57:17 +02:00 committed by GitHub
commit f31b320113
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
57 changed files with 5054 additions and 5528 deletions

View File

@ -28,7 +28,6 @@
"globals": {
"PDFJSDev": false,
"exports": false,
"SystemJS": false,
},
"rules": {

View File

@ -1,152 +0,0 @@
/* Copyright 2017 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable no-var */
var babel = require("plugin-babel");
var cacheExpiration = 60 /* min */ * 60 * 1000;
var dbVersion = 1;
var dbName = "babelcache";
var dbCacheTable = "translated";
var dbPromise;
function getDb() {
if (!dbPromise) {
dbPromise = new Promise(function (resolve, reject) {
var request = indexedDB.open(dbName, dbVersion);
request.onupgradeneeded = function () {
var db = request.result;
db.createObjectStore(dbCacheTable, { keyPath: "address" });
};
request.onsuccess = function () {
var db = request.result;
resolve(db);
};
request.onerror = function () {
console.warn("getDb: " + request.error);
reject(request.error);
};
});
}
return dbPromise;
}
function storeCache(address, hashCode, translated, format, sourceMap) {
return getDb().then(function (db) {
var tx = db.transaction(dbCacheTable, "readwrite");
var store = tx.objectStore(dbCacheTable);
store.put({
address,
hashCode,
translated,
expires: Date.now() + cacheExpiration,
format,
sourceMap,
});
return new Promise(function (resolve, reject) {
tx.oncomplete = function () {
resolve();
};
tx.onerror = function () {
resolve();
};
});
});
}
function loadCache(address, hashCode) {
return getDb().then(function (db) {
var tx = db.transaction(dbCacheTable, "readonly");
var store = tx.objectStore(dbCacheTable);
var getAddress = store.get(address);
return new Promise(function (resolve, reject) {
tx.oncomplete = function () {
var found = getAddress.result;
var isValid =
found && found.hashCode === hashCode && Date.now() < found.expires;
resolve(
isValid
? {
translated: found.translated,
format: found.format,
sourceMap: found.sourceMap,
}
: null
);
};
tx.onerror = function () {
resolve(null);
};
});
});
}
var encoder = new TextEncoder("utf-8");
function sha256(str) {
var buffer = encoder.encode(str);
return crypto.subtle.digest("SHA-256", buffer).then(function (hash) {
var data = new Int32Array(hash);
return (
data[0].toString(36) +
"-" +
data[1].toString(36) +
"-" +
data[2].toString(36) +
"-" +
data[3].toString(36)
);
});
}
exports.translate = function (load, opt) {
var savedHashCode, babelTranslateError;
return sha256(load.source)
.then(function (hashCode) {
savedHashCode = hashCode;
return loadCache(load.address, hashCode);
})
.then(
function (cache) {
if (cache) {
load.metadata.format = cache.format;
return cache.translated;
}
return babel.translate.call(this, load, opt).then(
function (translated) {
return storeCache(
load.address,
savedHashCode,
translated,
load.metadata.format,
load.metadata.sourceMap
).then(function () {
return translated;
});
},
function (reason) {
throw (babelTranslateError = reason);
}
);
}.bind(this)
)
.catch(
function (reason) {
if (babelTranslateError) {
throw babelTranslateError;
}
return babel.translate.call(this, load, opt);
}.bind(this)
);
};

26
package-lock.json generated
View File

@ -55,8 +55,6 @@
"streamqueue": "^1.1.2",
"stylelint": "^15.6.0",
"stylelint-prettier": "^3.0.0",
"systemjs": "^0.21.6",
"systemjs-plugin-babel": "^0.0.25",
"terser": "^5.17.1",
"through2": "^4.0.2",
"ttest": "^4.0.0",
@ -17482,18 +17480,6 @@
"integrity": "sha1-WPcc7jvVGbWdSyqEO2x95krAR2Q=",
"dev": true
},
"node_modules/systemjs": {
"version": "0.21.6",
"resolved": "https://registry.npmjs.org/systemjs/-/systemjs-0.21.6.tgz",
"integrity": "sha512-R+5S9eV9vcQgWOoS4D87joZ4xkFJHb19ZsyKY07D1+VBDE9bwYcU+KXE0r5XlDA8mFoJGyuWDbfrNoh90JsA8g==",
"dev": true
},
"node_modules/systemjs-plugin-babel": {
"version": "0.0.25",
"resolved": "https://registry.npmjs.org/systemjs-plugin-babel/-/systemjs-plugin-babel-0.0.25.tgz",
"integrity": "sha512-RMKSizWWlw4+IpDB385ugxn7Owd9W+HEtjYDQ6yO1FpsnER/vk6FbXRweUF+mvRi6EHgk8vDdUdtui7ReDwX3w==",
"dev": true
},
"node_modules/table": {
"version": "6.8.1",
"resolved": "https://registry.npmjs.org/table/-/table-6.8.1.tgz",
@ -32651,18 +32637,6 @@
"integrity": "sha1-WPcc7jvVGbWdSyqEO2x95krAR2Q=",
"dev": true
},
"systemjs": {
"version": "0.21.6",
"resolved": "https://registry.npmjs.org/systemjs/-/systemjs-0.21.6.tgz",
"integrity": "sha512-R+5S9eV9vcQgWOoS4D87joZ4xkFJHb19ZsyKY07D1+VBDE9bwYcU+KXE0r5XlDA8mFoJGyuWDbfrNoh90JsA8g==",
"dev": true
},
"systemjs-plugin-babel": {
"version": "0.0.25",
"resolved": "https://registry.npmjs.org/systemjs-plugin-babel/-/systemjs-plugin-babel-0.0.25.tgz",
"integrity": "sha512-RMKSizWWlw4+IpDB385ugxn7Owd9W+HEtjYDQ6yO1FpsnER/vk6FbXRweUF+mvRi6EHgk8vDdUdtui7ReDwX3w==",
"dev": true
},
"table": {
"version": "6.8.1",
"resolved": "https://registry.npmjs.org/table/-/table-6.8.1.tgz",

View File

@ -48,8 +48,6 @@
"streamqueue": "^1.1.2",
"stylelint": "^15.6.0",
"stylelint-prettier": "^3.0.0",
"systemjs": "^0.21.6",
"systemjs-plugin-babel": "^0.0.25",
"terser": "^5.17.1",
"through2": "^4.0.2",
"ttest": "^4.0.0",

View File

@ -1,13 +0,0 @@
{
"parserOptions": {
"ecmaVersion": 2017,
},
"extends": [
"../../.eslintrc"
],
"env": {
"es2017": true,
},
}

View File

@ -1556,11 +1556,10 @@ class WidgetAnnotation extends Annotation {
this.setDefaultAppearance(params);
data.hasAppearance =
(this._needAppearances &&
data.fieldValue !== undefined &&
data.fieldValue !== null) ||
data.hasAppearance;
data.hasAppearance ||=
this._needAppearances &&
data.fieldValue !== undefined &&
data.fieldValue !== null;
const fieldType = getInheritableProperty({ dict, key: "FT" });
data.fieldType = fieldType instanceof Name ? fieldType.name : null;
@ -1808,7 +1807,7 @@ class WidgetAnnotation extends Annotation {
if (!this._hasValueFromXFA && rotation === undefined) {
return null;
}
value = value || this.data.fieldValue;
value ||= this.data.fieldValue;
}
// Value can be an array (with choice list and multiple selections)
@ -3472,7 +3471,7 @@ class LinkAnnotation extends Annotation {
}
// The color entry for a link annotation is the color of the border.
this.data.borderColor = this.data.borderColor || this.data.color;
this.data.borderColor ||= this.data.color;
Catalog.parseDestDictionary({
destDict: params.dict,

View File

@ -985,12 +985,8 @@ class Catalog {
} else if (typeof js !== "string") {
return;
}
if (javaScript === null) {
javaScript = new Map();
}
js = stringToPDFString(js).replaceAll("\x00", "");
javaScript.set(name, js);
(javaScript ||= new Map()).set(name, js);
}
if (obj instanceof Dict && obj.has("JavaScript")) {

View File

@ -14,7 +14,7 @@
*/
import { arrayBuffersToBytes, MissingDataException } from "./core_utils.js";
import { assert, createPromiseCapability } from "../shared/util.js";
import { assert, PromiseCapability } from "../shared/util.js";
import { Stream } from "./stream.js";
class ChunkedStream extends Stream {
@ -275,7 +275,7 @@ class ChunkedStreamManager {
this.progressiveDataLength = 0;
this.aborted = false;
this._loadedStreamCapability = createPromiseCapability();
this._loadedStreamCapability = new PromiseCapability();
}
sendRequest(begin, end) {
@ -349,7 +349,7 @@ class ChunkedStreamManager {
return Promise.resolve();
}
const capability = createPromiseCapability();
const capability = new PromiseCapability();
this._promisesByRequest.set(requestId, capability);
const chunksToRequest = [];

View File

@ -1220,9 +1220,9 @@ const CalRGBCS = (function CalRGBCSClosure() {
"WhitePoint missing - required for color space CalRGB"
);
}
blackPoint = blackPoint || new Float32Array(3);
gamma = gamma || new Float32Array([1, 1, 1]);
matrix = matrix || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
blackPoint ||= new Float32Array(3);
gamma ||= new Float32Array([1, 1, 1]);
matrix ||= new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
// Translate arguments to spec variables.
const XW = whitePoint[0];
@ -1396,8 +1396,8 @@ const LabCS = (function LabCSClosure() {
"WhitePoint missing - required for color space Lab"
);
}
blackPoint = blackPoint || [0, 0, 0];
range = range || [-100, 100, -100, 100];
blackPoint ||= [0, 0, 0];
range ||= [-100, 100, -100, 100];
// Translate args to spec variables
this.XW = whitePoint[0];

View File

@ -38,22 +38,6 @@ function getLookupTableFactory(initializer) {
};
}
function getArrayLookupTableFactory(initializer) {
let lookup;
return function () {
if (initializer) {
let arr = initializer();
initializer = null;
lookup = Object.create(null);
for (let i = 0, ii = arr.length; i < ii; i += 2) {
lookup[arr[i]] = arr[i + 1];
}
arr = null;
}
return lookup;
};
}
class MissingDataException extends BaseException {
constructor(begin, end) {
super(`Missing data [${begin}, ${end})`, "MissingDataException");
@ -153,10 +137,7 @@ function getInheritableProperty({
if (stopWhenFound) {
return value;
}
if (!values) {
values = [];
}
values.push(value);
(values ||= []).push(value);
}
dict = dict.get("Parent");
}
@ -338,7 +319,7 @@ function _collectJS(entry, xref, list, parents) {
} else if (typeof js === "string") {
code = js;
}
code = code && stringToPDFString(code).replaceAll("\x00", "");
code &&= stringToPDFString(code).replaceAll("\x00", "");
if (code) {
list.push(code);
}
@ -616,7 +597,6 @@ export {
encodeToXmlString,
escapePDFName,
escapeString,
getArrayLookupTableFactory,
getInheritableProperty,
getLookupTableFactory,
getNewAnnotationsMap,

View File

@ -495,12 +495,8 @@ class Page {
for (const { opList, separateForm, separateCanvas } of opLists) {
pageOpList.addOpList(opList);
if (separateForm) {
form = separateForm;
}
if (separateCanvas) {
canvas = separateCanvas;
}
form ||= separateForm;
canvas ||= separateCanvas;
}
pageOpList.flush(
/* lastChunk = */ true,
@ -580,8 +576,8 @@ class Page {
return [];
}
const textContentPromises = [];
const annotationsData = [];
const annotationsData = [],
textContentPromises = [];
let partialEvaluator;
const intentAny = !!(intent & RenderingIntentFlag.ANY),
@ -597,19 +593,18 @@ class Page {
}
if (annotation.hasTextContent && isVisible) {
if (!partialEvaluator) {
partialEvaluator = new PartialEvaluator({
xref: this.xref,
handler,
pageIndex: this.pageIndex,
idFactory: this._localIdFactory,
fontCache: this.fontCache,
builtInCMapCache: this.builtInCMapCache,
standardFontDataCache: this.standardFontDataCache,
globalImageCache: this.globalImageCache,
options: this.evaluatorOptions,
});
}
partialEvaluator ||= new PartialEvaluator({
xref: this.xref,
handler,
pageIndex: this.pageIndex,
idFactory: this._localIdFactory,
fontCache: this.fontCache,
builtInCMapCache: this.builtInCMapCache,
standardFontDataCache: this.standardFontDataCache,
globalImageCache: this.globalImageCache,
options: this.evaluatorOptions,
});
textContentPromises.push(
annotation
.extractTextContent(partialEvaluator, task, this.view)
@ -665,10 +660,7 @@ class Page {
continue;
}
if (annotation instanceof PopupAnnotation) {
if (!popupAnnotations) {
popupAnnotations = [];
}
popupAnnotations.push(annotation);
(popupAnnotations ||= []).push(annotation);
continue;
}
sortedAnnotations.push(annotation);

View File

@ -18,7 +18,6 @@ import {
AbortException,
assert,
CMapCompressionType,
createPromiseCapability,
FONT_IDENTITY_MATRIX,
FormatError,
IDENTITY_MATRIX,
@ -26,6 +25,7 @@ import {
isArrayEqual,
normalizeUnicode,
OPS,
PromiseCapability,
shadow,
stringToPDFString,
TextRenderingMode,
@ -182,13 +182,9 @@ function incrementCachedImageMaskCount(data) {
// Trying to minimize Date.now() usage and check every 100 time.
class TimeSlotManager {
static get TIME_SLOT_DURATION_MS() {
return shadow(this, "TIME_SLOT_DURATION_MS", 20);
}
static TIME_SLOT_DURATION_MS = 20;
static get CHECK_TIME_EVERY() {
return shadow(this, "CHECK_TIME_EVERY", 100);
}
static CHECK_TIME_EVERY = 100;
constructor() {
this.reset();
@ -519,7 +515,7 @@ class PartialEvaluator {
}
if (smask && smask.backdrop) {
colorSpace = colorSpace || ColorSpace.singletons.rgb;
colorSpace ||= ColorSpace.singletons.rgb;
smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
}
@ -1253,7 +1249,7 @@ class PartialEvaluator {
return this.fontCache.get(font.cacheKey);
}
const fontCapability = createPromiseCapability();
const fontCapability = new PromiseCapability();
let preEvaluatedFont;
try {
@ -1272,10 +1268,7 @@ class PartialEvaluator {
}
if (hash && descriptor instanceof Dict) {
if (!descriptor.fontAliases) {
descriptor.fontAliases = Object.create(null);
}
const fontAliases = descriptor.fontAliases;
const fontAliases = (descriptor.fontAliases ||= Object.create(null));
if (fontAliases[hash]) {
const aliasFontRef = fontAliases[hash].aliasRef;
@ -1668,8 +1661,8 @@ class PartialEvaluator {
}) {
// Ensure that `resources`/`initialState` is correctly initialized,
// even if the provided parameter is e.g. `null`.
resources = resources || Dict.empty;
initialState = initialState || new EvalState();
resources ||= Dict.empty;
initialState ||= new EvalState();
if (!operatorList) {
throw new Error('getOperatorList: missing "operatorList" parameter');
@ -2276,11 +2269,11 @@ class PartialEvaluator {
}) {
// Ensure that `resources`/`stateManager` is correctly initialized,
// even if the provided parameter is e.g. `null`.
resources = resources || Dict.empty;
stateManager = stateManager || new StateManager(new TextState());
resources ||= Dict.empty;
stateManager ||= new StateManager(new TextState());
if (includeMarkedContent) {
markedContentData = markedContentData || { level: 0 };
markedContentData ||= { level: 0 };
}
const textContent = {
@ -4255,7 +4248,7 @@ class PartialEvaluator {
}
}
}
fontName = fontName || baseFont;
fontName ||= baseFont;
if (!(fontName instanceof Name)) {
throw new FormatError("invalid font name");
@ -4841,9 +4834,7 @@ class EvaluatorPreprocessor {
return shadow(this, "opMap", getOPMap());
}
static get MAX_INVALID_PATH_OPS() {
return shadow(this, "MAX_INVALID_PATH_OPS", 10);
}
static MAX_INVALID_PATH_OPS = 10;
constructor(stream, xref, stateManager = new StateManager()) {
// TODO(mduan): pass array of knownCommands rather than this.opMap

View File

@ -743,7 +743,7 @@ function validateOS2Table(os2, file) {
}
function createOS2Table(properties, charstrings, override) {
override = override || {
override ||= {
unitsPerEm: 0,
yMax: 0,
yMin: 0,
@ -3090,10 +3090,7 @@ class Font {
let charCodes = null;
for (const charCode in charCodeToGlyphId) {
if (glyphId === charCodeToGlyphId[charCode]) {
if (!charCodes) {
charCodes = [];
}
charCodes.push(charCode | 0);
(charCodes ||= []).push(charCode | 0);
}
}
return charCodes;
@ -3285,8 +3282,7 @@ class Font {
break; // the non-zero width found
}
}
width = width || this.defaultWidth;
return shadow(this, "spaceWidth", width);
return shadow(this, "spaceWidth", width || this.defaultWidth);
}
/**

View File

@ -513,9 +513,7 @@ function isPDFFunction(v) {
}
class PostScriptStack {
static get MAX_STACK_SIZE() {
return shadow(this, "MAX_STACK_SIZE", 100);
}
static MAX_STACK_SIZE = 100;
constructor(initialStack) {
this.stack = initialStack ? Array.from(initialStack) : [];

File diff suppressed because it is too large Load Diff

View File

@ -16,7 +16,6 @@
import {
assert,
MAX_IMAGE_SIZE_TO_CACHE,
shadow,
unreachable,
warn,
} from "../shared/util.js";
@ -173,17 +172,11 @@ class RegionalImageCache extends BaseLocalCache {
}
class GlobalImageCache {
static get NUM_PAGES_THRESHOLD() {
return shadow(this, "NUM_PAGES_THRESHOLD", 2);
}
static NUM_PAGES_THRESHOLD = 2;
static get MIN_IMAGES_TO_CACHE() {
return shadow(this, "MIN_IMAGES_TO_CACHE", 10);
}
static MIN_IMAGES_TO_CACHE = 10;
static get MAX_BYTE_SIZE() {
return shadow(this, "MAX_BYTE_SIZE", 5 * MAX_IMAGE_SIZE_TO_CACHE);
}
static MAX_BYTE_SIZE = 5 * MAX_IMAGE_SIZE_TO_CACHE;
constructor() {
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {

View File

@ -1738,381 +1738,380 @@ class InclusionTree {
}
// Section D. Coefficient bit modeling
const BitModel = (function BitModelClosure() {
const UNIFORM_CONTEXT = 17;
const RUNLENGTH_CONTEXT = 18;
class BitModel {
static UNIFORM_CONTEXT = 17;
static RUNLENGTH_CONTEXT = 18;
// Table D-1
// The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4),
// vv - sum of Vi (0..2), and hh - sum of Hi (0..2)
const LLAndLHContextsLabel = new Uint8Array([
static LLAndLHContextsLabel = new Uint8Array([
0, 5, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 1, 6, 8, 0, 3, 7, 8, 0, 4,
7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6,
8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8,
]);
const HLContextLabel = new Uint8Array([
static HLContextLabel = new Uint8Array([
0, 3, 4, 0, 5, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 1, 3, 4, 0, 6, 7, 7, 0, 8,
8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3,
4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8,
]);
const HHContextLabel = new Uint8Array([
static HHContextLabel = new Uint8Array([
0, 1, 2, 0, 1, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 3, 4, 5, 0, 4, 5, 5, 0, 5,
5, 5, 0, 0, 0, 0, 0, 6, 7, 7, 0, 7, 7, 7, 0, 7, 7, 7, 0, 0, 0, 0, 0, 8, 8,
8, 0, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8,
]);
// eslint-disable-next-line no-shadow
class BitModel {
constructor(width, height, subband, zeroBitPlanes, mb) {
this.width = width;
this.height = height;
constructor(width, height, subband, zeroBitPlanes, mb) {
this.width = width;
this.height = height;
let contextLabelTable;
if (subband === "HH") {
contextLabelTable = HHContextLabel;
} else if (subband === "HL") {
contextLabelTable = HLContextLabel;
} else {
contextLabelTable = LLAndLHContextsLabel;
}
this.contextLabelTable = contextLabelTable;
const coefficientCount = width * height;
// coefficients outside the encoding region treated as insignificant
// add border state cells for significanceState
this.neighborsSignificance = new Uint8Array(coefficientCount);
this.coefficentsSign = new Uint8Array(coefficientCount);
let coefficentsMagnitude;
if (mb > 14) {
coefficentsMagnitude = new Uint32Array(coefficientCount);
} else if (mb > 6) {
coefficentsMagnitude = new Uint16Array(coefficientCount);
} else {
coefficentsMagnitude = new Uint8Array(coefficientCount);
}
this.coefficentsMagnitude = coefficentsMagnitude;
this.processingFlags = new Uint8Array(coefficientCount);
const bitsDecoded = new Uint8Array(coefficientCount);
if (zeroBitPlanes !== 0) {
for (let i = 0; i < coefficientCount; i++) {
bitsDecoded[i] = zeroBitPlanes;
}
}
this.bitsDecoded = bitsDecoded;
this.reset();
let contextLabelTable;
if (subband === "HH") {
contextLabelTable = BitModel.HHContextLabel;
} else if (subband === "HL") {
contextLabelTable = BitModel.HLContextLabel;
} else {
contextLabelTable = BitModel.LLAndLHContextsLabel;
}
this.contextLabelTable = contextLabelTable;
setDecoder(decoder) {
this.decoder = decoder;
const coefficientCount = width * height;
// coefficients outside the encoding region treated as insignificant
// add border state cells for significanceState
this.neighborsSignificance = new Uint8Array(coefficientCount);
this.coefficentsSign = new Uint8Array(coefficientCount);
let coefficentsMagnitude;
if (mb > 14) {
coefficentsMagnitude = new Uint32Array(coefficientCount);
} else if (mb > 6) {
coefficentsMagnitude = new Uint16Array(coefficientCount);
} else {
coefficentsMagnitude = new Uint8Array(coefficientCount);
}
this.coefficentsMagnitude = coefficentsMagnitude;
this.processingFlags = new Uint8Array(coefficientCount);
reset() {
// We have 17 contexts that are accessed via context labels,
// plus the uniform and runlength context.
this.contexts = new Int8Array(19);
// Contexts are packed into 1 byte:
// highest 7 bits carry the index, lowest bit carries mps
this.contexts[0] = (4 << 1) | 0;
this.contexts[UNIFORM_CONTEXT] = (46 << 1) | 0;
this.contexts[RUNLENGTH_CONTEXT] = (3 << 1) | 0;
const bitsDecoded = new Uint8Array(coefficientCount);
if (zeroBitPlanes !== 0) {
for (let i = 0; i < coefficientCount; i++) {
bitsDecoded[i] = zeroBitPlanes;
}
}
this.bitsDecoded = bitsDecoded;
setNeighborsSignificance(row, column, index) {
const neighborsSignificance = this.neighborsSignificance;
const width = this.width,
height = this.height;
const left = column > 0;
const right = column + 1 < width;
let i;
this.reset();
}
if (row > 0) {
i = index - width;
if (left) {
neighborsSignificance[i - 1] += 0x10;
}
if (right) {
neighborsSignificance[i + 1] += 0x10;
}
neighborsSignificance[i] += 0x04;
}
setDecoder(decoder) {
this.decoder = decoder;
}
if (row + 1 < height) {
i = index + width;
if (left) {
neighborsSignificance[i - 1] += 0x10;
}
if (right) {
neighborsSignificance[i + 1] += 0x10;
}
neighborsSignificance[i] += 0x04;
}
reset() {
// We have 17 contexts that are accessed via context labels,
// plus the uniform and runlength context.
this.contexts = new Int8Array(19);
// Contexts are packed into 1 byte:
// highest 7 bits carry the index, lowest bit carries mps
this.contexts[0] = (4 << 1) | 0;
this.contexts[BitModel.UNIFORM_CONTEXT] = (46 << 1) | 0;
this.contexts[BitModel.RUNLENGTH_CONTEXT] = (3 << 1) | 0;
}
setNeighborsSignificance(row, column, index) {
const neighborsSignificance = this.neighborsSignificance;
const width = this.width,
height = this.height;
const left = column > 0;
const right = column + 1 < width;
let i;
if (row > 0) {
i = index - width;
if (left) {
neighborsSignificance[index - 1] += 0x01;
neighborsSignificance[i - 1] += 0x10;
}
if (right) {
neighborsSignificance[index + 1] += 0x01;
neighborsSignificance[i + 1] += 0x10;
}
neighborsSignificance[index] |= 0x80;
neighborsSignificance[i] += 0x04;
}
runSignificancePropagationPass() {
const decoder = this.decoder;
const width = this.width,
height = this.height;
const coefficentsMagnitude = this.coefficentsMagnitude;
const coefficentsSign = this.coefficentsSign;
const neighborsSignificance = this.neighborsSignificance;
const processingFlags = this.processingFlags;
const contexts = this.contexts;
const labels = this.contextLabelTable;
const bitsDecoded = this.bitsDecoded;
const processedInverseMask = ~1;
const processedMask = 1;
const firstMagnitudeBitMask = 2;
if (row + 1 < height) {
i = index + width;
if (left) {
neighborsSignificance[i - 1] += 0x10;
}
if (right) {
neighborsSignificance[i + 1] += 0x10;
}
neighborsSignificance[i] += 0x04;
}
for (let i0 = 0; i0 < height; i0 += 4) {
for (let j = 0; j < width; j++) {
let index = i0 * width + j;
for (let i1 = 0; i1 < 4; i1++, index += width) {
const i = i0 + i1;
if (i >= height) {
break;
}
// clear processed flag first
processingFlags[index] &= processedInverseMask;
if (left) {
neighborsSignificance[index - 1] += 0x01;
}
if (right) {
neighborsSignificance[index + 1] += 0x01;
}
neighborsSignificance[index] |= 0x80;
}
if (coefficentsMagnitude[index] || !neighborsSignificance[index]) {
continue;
}
runSignificancePropagationPass() {
const decoder = this.decoder;
const width = this.width,
height = this.height;
const coefficentsMagnitude = this.coefficentsMagnitude;
const coefficentsSign = this.coefficentsSign;
const neighborsSignificance = this.neighborsSignificance;
const processingFlags = this.processingFlags;
const contexts = this.contexts;
const labels = this.contextLabelTable;
const bitsDecoded = this.bitsDecoded;
const processedInverseMask = ~1;
const processedMask = 1;
const firstMagnitudeBitMask = 2;
const contextLabel = labels[neighborsSignificance[index]];
const decision = decoder.readBit(contexts, contextLabel);
if (decision) {
const sign = this.decodeSignBit(i, j, index);
coefficentsSign[index] = sign;
coefficentsMagnitude[index] = 1;
this.setNeighborsSignificance(i, j, index);
processingFlags[index] |= firstMagnitudeBitMask;
}
bitsDecoded[index]++;
processingFlags[index] |= processedMask;
for (let i0 = 0; i0 < height; i0 += 4) {
for (let j = 0; j < width; j++) {
let index = i0 * width + j;
for (let i1 = 0; i1 < 4; i1++, index += width) {
const i = i0 + i1;
if (i >= height) {
break;
}
// clear processed flag first
processingFlags[index] &= processedInverseMask;
if (coefficentsMagnitude[index] || !neighborsSignificance[index]) {
continue;
}
const contextLabel = labels[neighborsSignificance[index]];
const decision = decoder.readBit(contexts, contextLabel);
if (decision) {
const sign = this.decodeSignBit(i, j, index);
coefficentsSign[index] = sign;
coefficentsMagnitude[index] = 1;
this.setNeighborsSignificance(i, j, index);
processingFlags[index] |= firstMagnitudeBitMask;
}
bitsDecoded[index]++;
processingFlags[index] |= processedMask;
}
}
}
}
decodeSignBit(row, column, index) {
const width = this.width,
height = this.height;
const coefficentsMagnitude = this.coefficentsMagnitude;
const coefficentsSign = this.coefficentsSign;
let contribution, sign0, sign1, significance1;
let contextLabel, decoded;
decodeSignBit(row, column, index) {
const width = this.width,
height = this.height;
const coefficentsMagnitude = this.coefficentsMagnitude;
const coefficentsSign = this.coefficentsSign;
let contribution, sign0, sign1, significance1;
let contextLabel, decoded;
// calculate horizontal contribution
significance1 = column > 0 && coefficentsMagnitude[index - 1] !== 0;
if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
sign1 = coefficentsSign[index + 1];
if (significance1) {
sign0 = coefficentsSign[index - 1];
contribution = 1 - sign1 - sign0;
} else {
contribution = 1 - sign1 - sign1;
}
} else if (significance1) {
// calculate horizontal contribution
significance1 = column > 0 && coefficentsMagnitude[index - 1] !== 0;
if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
sign1 = coefficentsSign[index + 1];
if (significance1) {
sign0 = coefficentsSign[index - 1];
contribution = 1 - sign0 - sign0;
contribution = 1 - sign1 - sign0;
} else {
contribution = 0;
contribution = 1 - sign1 - sign1;
}
const horizontalContribution = 3 * contribution;
} else if (significance1) {
sign0 = coefficentsSign[index - 1];
contribution = 1 - sign0 - sign0;
} else {
contribution = 0;
}
const horizontalContribution = 3 * contribution;
// calculate vertical contribution and combine with the horizontal
significance1 = row > 0 && coefficentsMagnitude[index - width] !== 0;
if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
sign1 = coefficentsSign[index + width];
if (significance1) {
sign0 = coefficentsSign[index - width];
contribution = 1 - sign1 - sign0 + horizontalContribution;
} else {
contribution = 1 - sign1 - sign1 + horizontalContribution;
}
} else if (significance1) {
// calculate vertical contribution and combine with the horizontal
significance1 = row > 0 && coefficentsMagnitude[index - width] !== 0;
if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
sign1 = coefficentsSign[index + width];
if (significance1) {
sign0 = coefficentsSign[index - width];
contribution = 1 - sign0 - sign0 + horizontalContribution;
contribution = 1 - sign1 - sign0 + horizontalContribution;
} else {
contribution = horizontalContribution;
contribution = 1 - sign1 - sign1 + horizontalContribution;
}
if (contribution >= 0) {
contextLabel = 9 + contribution;
decoded = this.decoder.readBit(this.contexts, contextLabel);
} else {
contextLabel = 9 - contribution;
decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
}
return decoded;
} else if (significance1) {
sign0 = coefficentsSign[index - width];
contribution = 1 - sign0 - sign0 + horizontalContribution;
} else {
contribution = horizontalContribution;
}
runMagnitudeRefinementPass() {
const decoder = this.decoder;
const width = this.width,
height = this.height;
const coefficentsMagnitude = this.coefficentsMagnitude;
const neighborsSignificance = this.neighborsSignificance;
const contexts = this.contexts;
const bitsDecoded = this.bitsDecoded;
const processingFlags = this.processingFlags;
const processedMask = 1;
const firstMagnitudeBitMask = 2;
const length = width * height;
const width4 = width * 4;
if (contribution >= 0) {
contextLabel = 9 + contribution;
decoded = this.decoder.readBit(this.contexts, contextLabel);
} else {
contextLabel = 9 - contribution;
decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
}
return decoded;
}
for (let index0 = 0, indexNext; index0 < length; index0 = indexNext) {
indexNext = Math.min(length, index0 + width4);
for (let j = 0; j < width; j++) {
for (let index = index0 + j; index < indexNext; index += width) {
// significant but not those that have just become
if (
!coefficentsMagnitude[index] ||
(processingFlags[index] & processedMask) !== 0
) {
continue;
}
runMagnitudeRefinementPass() {
const decoder = this.decoder;
const width = this.width,
height = this.height;
const coefficentsMagnitude = this.coefficentsMagnitude;
const neighborsSignificance = this.neighborsSignificance;
const contexts = this.contexts;
const bitsDecoded = this.bitsDecoded;
const processingFlags = this.processingFlags;
const processedMask = 1;
const firstMagnitudeBitMask = 2;
const length = width * height;
const width4 = width * 4;
let contextLabel = 16;
if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
processingFlags[index] ^= firstMagnitudeBitMask;
// first refinement
const significance = neighborsSignificance[index] & 127;
contextLabel = significance === 0 ? 15 : 14;
}
const bit = decoder.readBit(contexts, contextLabel);
coefficentsMagnitude[index] =
(coefficentsMagnitude[index] << 1) | bit;
bitsDecoded[index]++;
processingFlags[index] |= processedMask;
for (let index0 = 0, indexNext; index0 < length; index0 = indexNext) {
indexNext = Math.min(length, index0 + width4);
for (let j = 0; j < width; j++) {
for (let index = index0 + j; index < indexNext; index += width) {
// significant but not those that have just become
if (
!coefficentsMagnitude[index] ||
(processingFlags[index] & processedMask) !== 0
) {
continue;
}
let contextLabel = 16;
if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
processingFlags[index] ^= firstMagnitudeBitMask;
// first refinement
const significance = neighborsSignificance[index] & 127;
contextLabel = significance === 0 ? 15 : 14;
}
const bit = decoder.readBit(contexts, contextLabel);
coefficentsMagnitude[index] =
(coefficentsMagnitude[index] << 1) | bit;
bitsDecoded[index]++;
processingFlags[index] |= processedMask;
}
}
}
}
runCleanupPass() {
const decoder = this.decoder;
const width = this.width,
height = this.height;
const neighborsSignificance = this.neighborsSignificance;
const coefficentsMagnitude = this.coefficentsMagnitude;
const coefficentsSign = this.coefficentsSign;
const contexts = this.contexts;
const labels = this.contextLabelTable;
const bitsDecoded = this.bitsDecoded;
const processingFlags = this.processingFlags;
const processedMask = 1;
const firstMagnitudeBitMask = 2;
const oneRowDown = width;
const twoRowsDown = width * 2;
const threeRowsDown = width * 3;
let iNext;
for (let i0 = 0; i0 < height; i0 = iNext) {
iNext = Math.min(i0 + 4, height);
const indexBase = i0 * width;
const checkAllEmpty = i0 + 3 < height;
for (let j = 0; j < width; j++) {
const index0 = indexBase + j;
// using the property: labels[neighborsSignificance[index]] === 0
// when neighborsSignificance[index] === 0
const allEmpty =
checkAllEmpty &&
processingFlags[index0] === 0 &&
processingFlags[index0 + oneRowDown] === 0 &&
processingFlags[index0 + twoRowsDown] === 0 &&
processingFlags[index0 + threeRowsDown] === 0 &&
neighborsSignificance[index0] === 0 &&
neighborsSignificance[index0 + oneRowDown] === 0 &&
neighborsSignificance[index0 + twoRowsDown] === 0 &&
neighborsSignificance[index0 + threeRowsDown] === 0;
let i1 = 0,
index = index0;
let i = i0,
sign;
if (allEmpty) {
const hasSignificantCoefficent = decoder.readBit(
contexts,
RUNLENGTH_CONTEXT
);
if (!hasSignificantCoefficent) {
bitsDecoded[index0]++;
bitsDecoded[index0 + oneRowDown]++;
bitsDecoded[index0 + twoRowsDown]++;
bitsDecoded[index0 + threeRowsDown]++;
continue; // next column
}
i1 =
(decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
decoder.readBit(contexts, UNIFORM_CONTEXT);
if (i1 !== 0) {
i = i0 + i1;
index += i1 * width;
}
runCleanupPass() {
const decoder = this.decoder;
const width = this.width,
height = this.height;
const neighborsSignificance = this.neighborsSignificance;
const coefficentsMagnitude = this.coefficentsMagnitude;
const coefficentsSign = this.coefficentsSign;
const contexts = this.contexts;
const labels = this.contextLabelTable;
const bitsDecoded = this.bitsDecoded;
const processingFlags = this.processingFlags;
const processedMask = 1;
const firstMagnitudeBitMask = 2;
const oneRowDown = width;
const twoRowsDown = width * 2;
const threeRowsDown = width * 3;
let iNext;
for (let i0 = 0; i0 < height; i0 = iNext) {
iNext = Math.min(i0 + 4, height);
const indexBase = i0 * width;
const checkAllEmpty = i0 + 3 < height;
for (let j = 0; j < width; j++) {
const index0 = indexBase + j;
// using the property: labels[neighborsSignificance[index]] === 0
// when neighborsSignificance[index] === 0
const allEmpty =
checkAllEmpty &&
processingFlags[index0] === 0 &&
processingFlags[index0 + oneRowDown] === 0 &&
processingFlags[index0 + twoRowsDown] === 0 &&
processingFlags[index0 + threeRowsDown] === 0 &&
neighborsSignificance[index0] === 0 &&
neighborsSignificance[index0 + oneRowDown] === 0 &&
neighborsSignificance[index0 + twoRowsDown] === 0 &&
neighborsSignificance[index0 + threeRowsDown] === 0;
let i1 = 0,
index = index0;
let i = i0,
sign;
if (allEmpty) {
const hasSignificantCoefficent = decoder.readBit(
contexts,
BitModel.RUNLENGTH_CONTEXT
);
if (!hasSignificantCoefficent) {
bitsDecoded[index0]++;
bitsDecoded[index0 + oneRowDown]++;
bitsDecoded[index0 + twoRowsDown]++;
bitsDecoded[index0 + threeRowsDown]++;
continue; // next column
}
i1 =
(decoder.readBit(contexts, BitModel.UNIFORM_CONTEXT) << 1) |
decoder.readBit(contexts, BitModel.UNIFORM_CONTEXT);
if (i1 !== 0) {
i = i0 + i1;
index += i1 * width;
}
sign = this.decodeSignBit(i, j, index);
coefficentsSign[index] = sign;
coefficentsMagnitude[index] = 1;
this.setNeighborsSignificance(i, j, index);
processingFlags[index] |= firstMagnitudeBitMask;
index = index0;
for (let i2 = i0; i2 <= i; i2++, index += width) {
bitsDecoded[index]++;
}
i1++;
}
for (i = i0 + i1; i < iNext; i++, index += width) {
if (
coefficentsMagnitude[index] ||
(processingFlags[index] & processedMask) !== 0
) {
continue;
}
const contextLabel = labels[neighborsSignificance[index]];
const decision = decoder.readBit(contexts, contextLabel);
if (decision === 1) {
sign = this.decodeSignBit(i, j, index);
coefficentsSign[index] = sign;
coefficentsMagnitude[index] = 1;
this.setNeighborsSignificance(i, j, index);
processingFlags[index] |= firstMagnitudeBitMask;
index = index0;
for (let i2 = i0; i2 <= i; i2++, index += width) {
bitsDecoded[index]++;
}
i1++;
}
for (i = i0 + i1; i < iNext; i++, index += width) {
if (
coefficentsMagnitude[index] ||
(processingFlags[index] & processedMask) !== 0
) {
continue;
}
const contextLabel = labels[neighborsSignificance[index]];
const decision = decoder.readBit(contexts, contextLabel);
if (decision === 1) {
sign = this.decodeSignBit(i, j, index);
coefficentsSign[index] = sign;
coefficentsMagnitude[index] = 1;
this.setNeighborsSignificance(i, j, index);
processingFlags[index] |= firstMagnitudeBitMask;
}
bitsDecoded[index]++;
}
bitsDecoded[index]++;
}
}
}
checkSegmentationSymbol() {
const decoder = this.decoder;
const contexts = this.contexts;
const symbol =
(decoder.readBit(contexts, UNIFORM_CONTEXT) << 3) |
(decoder.readBit(contexts, UNIFORM_CONTEXT) << 2) |
(decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
decoder.readBit(contexts, UNIFORM_CONTEXT);
if (symbol !== 0xa) {
throw new JpxError("Invalid segmentation symbol");
}
}
}
return BitModel;
})();
checkSegmentationSymbol() {
const decoder = this.decoder;
const contexts = this.contexts;
const symbol =
(decoder.readBit(contexts, BitModel.UNIFORM_CONTEXT) << 3) |
(decoder.readBit(contexts, BitModel.UNIFORM_CONTEXT) << 2) |
(decoder.readBit(contexts, BitModel.UNIFORM_CONTEXT) << 1) |
decoder.readBit(contexts, BitModel.UNIFORM_CONTEXT);
if (symbol !== 0xa) {
throw new JpxError("Invalid segmentation symbol");
}
}
}
// Section F, Discrete wavelet transformation
class Transform {

View File

@ -13,19 +13,13 @@
* limitations under the License.
*/
import {
ImageKind,
OPS,
RenderingIntentFlag,
shadow,
warn,
} from "../shared/util.js";
import { ImageKind, OPS, RenderingIntentFlag, warn } from "../shared/util.js";
function addState(parentState, pattern, checkFn, iterateFn, processFn) {
let state = parentState;
for (let i = 0, ii = pattern.length - 1; i < ii; i++) {
const item = pattern[i];
state = state[item] || (state[item] = []);
state = state[item] ||= [];
}
state[pattern.at(-1)] = {
checkFn,
@ -586,14 +580,10 @@ class QueueOptimizer extends NullOptimizer {
}
class OperatorList {
static get CHUNK_SIZE() {
return shadow(this, "CHUNK_SIZE", 1000);
}
static CHUNK_SIZE = 1000;
// Close to chunk size.
static get CHUNK_SIZE_ABOUT() {
return shadow(this, "CHUNK_SIZE_ABOUT", this.CHUNK_SIZE - 5);
}
static CHUNK_SIZE_ABOUT = this.CHUNK_SIZE - 5;
constructor(intent = 0, streamSink) {
this._streamSink = streamSink;

View File

@ -896,7 +896,7 @@ class Lexer {
throw new FormatError(msg);
}
sign = sign || 1;
sign ||= 1;
let baseValue = ch - 0x30; // '0'
let powerValue = 0;
let powerValueSign = 1;

View File

@ -17,7 +17,6 @@ import {
assert,
FormatError,
info,
shadow,
unreachable,
Util,
warn,
@ -89,9 +88,7 @@ class Pattern {
class BaseShading {
// A small number to offset the first/last color stops so we can insert ones
// to support extend. Number.MIN_VALUE is too small and breaks the extend.
static get SMALL_NUMBER() {
return shadow(this, "SMALL_NUMBER", 1e-6);
}
static SMALL_NUMBER = 1e-6;
constructor() {
if (this.constructor === BaseShading) {
@ -366,29 +363,20 @@ const getB = (function getBClosure() {
}
return lut;
}
const cache = [];
const cache = Object.create(null);
return function (count) {
if (!cache[count]) {
cache[count] = buildB(count);
}
return cache[count];
return (cache[count] ||= buildB(count));
};
})();
class MeshShading extends BaseShading {
static get MIN_SPLIT_PATCH_CHUNKS_AMOUNT() {
return shadow(this, "MIN_SPLIT_PATCH_CHUNKS_AMOUNT", 3);
}
static MIN_SPLIT_PATCH_CHUNKS_AMOUNT = 3;
static get MAX_SPLIT_PATCH_CHUNKS_AMOUNT() {
return shadow(this, "MAX_SPLIT_PATCH_CHUNKS_AMOUNT", 20);
}
static MAX_SPLIT_PATCH_CHUNKS_AMOUNT = 20;
// Count of triangles per entire mesh bounds.
static get TRIANGLE_DENSITY() {
return shadow(this, "TRIANGLE_DENSITY", 20);
}
static TRIANGLE_DENSITY = 20;
constructor(
stream,

View File

@ -48,8 +48,7 @@ class BasePdfManager {
// Check `OffscreenCanvas` support once, rather than repeatedly throughout
// the worker-thread code.
args.evaluatorOptions.isOffscreenCanvasSupported =
args.evaluatorOptions.isOffscreenCanvasSupported &&
args.evaluatorOptions.isOffscreenCanvasSupported &&=
FeatureTest.isOffscreenCanvasSupported;
this.evaluatorOptions = args.evaluatorOptions;
}

View File

@ -41,7 +41,7 @@ class Name {
static get(name) {
// eslint-disable-next-line no-restricted-syntax
return NameCache[name] || (NameCache[name] = new Name(name));
return (NameCache[name] ||= new Name(name));
}
}
@ -58,7 +58,7 @@ class Cmd {
static get(cmd) {
// eslint-disable-next-line no-restricted-syntax
return CmdCache[cmd] || (CmdCache[cmd] = new Cmd(cmd));
return (CmdCache[cmd] ||= new Cmd(cmd));
}
}
@ -282,7 +282,7 @@ class Ref {
static get(num, gen) {
const key = gen === 0 ? `${num}R` : `${num}R${gen}`;
// eslint-disable-next-line no-restricted-syntax
return RefCache[key] || (RefCache[key] = new Ref(num, gen));
return (RefCache[key] ||= new Ref(num, gen));
}
}

View File

@ -120,11 +120,7 @@ class PostScriptToken {
}
static getOperator(op) {
const opValue = PostScriptToken.opCache[op];
if (opValue) {
return opValue;
}
return (PostScriptToken.opCache[op] = new PostScriptToken(
return (PostScriptToken.opCache[op] ||= new PostScriptToken(
PostScriptTokenTypes.OPERATOR,
op
));

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* no-babel-preset */
import { getLookupTableFactory } from "./core_utils.js";

View File

@ -16,12 +16,12 @@
import {
AbortException,
assert,
createPromiseCapability,
getVerbosityLevel,
info,
InvalidPDFException,
MissingPDFException,
PasswordException,
PromiseCapability,
setVerbosityLevel,
stringToPDFString,
UnexpectedResponseException,
@ -46,7 +46,7 @@ class WorkerTask {
constructor(name) {
this.name = name;
this.terminated = false;
this._capability = createPromiseCapability();
this._capability = new PromiseCapability();
}
get finished() {
@ -228,7 +228,7 @@ class WorkerMessageHandler {
password,
rangeChunkSize,
};
const pdfManagerCapability = createPromiseCapability();
const pdfManagerCapability = new PromiseCapability();
let newPdfManager;
if (data) {
@ -261,8 +261,7 @@ class WorkerMessageHandler {
pdfManagerArgs.source = pdfStream;
pdfManagerArgs.length = fullRequest.contentLength;
// We don't need auto-fetch when streaming is enabled.
pdfManagerArgs.disableAutoFetch =
pdfManagerArgs.disableAutoFetch || fullRequest.isStreamingSupported;
pdfManagerArgs.disableAutoFetch ||= fullRequest.isStreamingSupported;
newPdfManager = new NetworkPdfManager(pdfManagerArgs);
// There may be a chance that `newPdfManager` is not initialized for
@ -661,7 +660,6 @@ class WorkerMessageHandler {
});
}
const lastXRefStreamPos = xref.lastXRefStreamPos;
newXrefInfo = {
rootRef: xref.trailer.getRaw("Root") || null,
encryptRef: xref.trailer.getRaw("Encrypt") || null,
@ -669,8 +667,7 @@ class WorkerMessageHandler {
infoRef: xref.trailer.getRaw("Info") || null,
info: infoObj,
fileIds: xref.trailer.get("ID") || null,
startXRef:
lastXRefStreamPos === null ? startXRef : lastXRefStreamPos,
startXRef: xref.lastXRefStreamPos ?? startXRef,
filename,
};
}

View File

@ -275,7 +275,7 @@ class SimpleExprParser {
}
parse(tok) {
tok = tok || this.lexer.next();
tok ||= this.lexer.next();
while (true) {
// Token ids (see form_lexer.js) are consecutive in order
@ -1005,7 +1005,7 @@ class Parser {
}
parseExpr(tok) {
tok = tok || this.lexer.next();
tok ||= this.lexer.next();
switch (tok.id) {
case TOKEN.identifier:
return this.parseAssigmentOrExpr(tok);

View File

@ -107,10 +107,7 @@ class XFAParser extends XMLParserBase {
nsAttrs = attributeObj[$nsAttributes] = Object.create(null);
}
const [ns, attrName] = [name.slice(0, i), name.slice(i + 1)];
let attrs = nsAttrs[ns];
if (!attrs) {
attrs = nsAttrs[ns] = Object.create(null);
}
const attrs = (nsAttrs[ns] ||= Object.create(null));
attrs[attrName] = value;
}
}

View File

@ -5573,8 +5573,7 @@ class Template extends XFAObject {
const flush = index => {
const html = root[$flushHTML]();
if (html) {
hasSomething =
hasSomething || (html.children && html.children.length !== 0);
hasSomething ||= !!html.children && html.children.length !== 0;
htmlContentAreas[index].children.push(html);
}
};
@ -5597,9 +5596,8 @@ class Template extends XFAObject {
const html = root[$toHTML](space);
if (html.success) {
if (html.html) {
hasSomething =
hasSomething ||
(html.html.children && html.html.children.length !== 0);
hasSomething ||=
!!html.html.children && html.html.children.length !== 0;
htmlContentAreas[i].children.push(html.html);
} else if (!hasSomething && mainHtml.children.length > 1) {
mainHtml.children.pop();

View File

@ -75,7 +75,7 @@ function getStringOption(data, options) {
}
function getMeasurement(str, def = "0") {
def = def || "0";
def ||= "0";
if (!str) {
return getMeasurement(def);
}

View File

@ -451,7 +451,7 @@ class AnnotationElement {
_createPopup(trigger, data) {
let container = this.container;
if (this.quadrilaterals) {
trigger = trigger || this.quadrilaterals;
trigger ||= this.quadrilaterals;
container = this.quadrilaterals[0];
}

View File

@ -21,7 +21,6 @@ import {
AbortException,
AnnotationMode,
assert,
createPromiseCapability,
getVerbosityLevel,
info,
InvalidPDFException,
@ -29,6 +28,7 @@ import {
MAX_IMAGE_SIZE_TO_CACHE,
MissingPDFException,
PasswordException,
PromiseCapability,
RenderingIntentFlag,
setVerbosityLevel,
shadow,
@ -588,7 +588,7 @@ class PDFDocumentLoadingTask {
static #docId = 0;
constructor() {
this._capability = createPromiseCapability();
this._capability = new PromiseCapability();
this._transport = null;
this._worker = null;
@ -675,7 +675,7 @@ class PDFDataRangeTransport {
this._progressListeners = [];
this._progressiveReadListeners = [];
this._progressiveDoneListeners = [];
this._readyCapability = createPromiseCapability();
this._readyCapability = new PromiseCapability();
}
/**
@ -1460,7 +1460,7 @@ class PDFPageProxy {
// If there's no displayReadyCapability yet, then the operatorList
// was never requested before. Make the request and create the promise.
if (!intentState.displayReadyCapability) {
intentState.displayReadyCapability = createPromiseCapability();
intentState.displayReadyCapability = new PromiseCapability();
intentState.operatorList = {
fnArray: [],
argsArray: [],
@ -1578,7 +1578,7 @@ class PDFPageProxy {
if (!intentState.opListReadCapability) {
opListTask = Object.create(null);
opListTask.operatorListChanged = operatorListChanged;
intentState.opListReadCapability = createPromiseCapability();
intentState.opListReadCapability = new PromiseCapability();
(intentState.renderTasks ||= new Set()).add(opListTask);
intentState.operatorList = {
fnArray: [],
@ -2054,7 +2054,7 @@ class PDFWorker {
this.destroyed = false;
this.verbosity = verbosity;
this._readyCapability = createPromiseCapability();
this._readyCapability = new PromiseCapability();
this._port = null;
this._webWorker = null;
this._messageHandler = null;
@ -2130,12 +2130,9 @@ class PDFWorker {
);
}
// Some versions of FF can't create a worker on localhost, see:
// https://bugzilla.mozilla.org/show_bug.cgi?id=683280
const worker =
typeof PDFJSDev === "undefined" &&
!workerSrc.endsWith("/build/pdf.worker.js") &&
!workerSrc.endsWith("/src/worker_loader.js")
!workerSrc.endsWith("/build/pdf.worker.js")
? new Worker(workerSrc, { type: "module" })
: new Worker(workerSrc);
const messageHandler = new MessageHandler("main", "worker", worker);
@ -2391,7 +2388,7 @@ class WorkerTransport {
this._networkStream = networkStream;
this._fullReader = null;
this._lastProgress = null;
this.downloadInfoCapability = createPromiseCapability();
this.downloadInfoCapability = new PromiseCapability();
this.setupMessageHandler();
@ -2490,7 +2487,7 @@ class WorkerTransport {
}
this.destroyed = true;
this.destroyCapability = createPromiseCapability();
this.destroyCapability = new PromiseCapability();
if (this._passwordCapability) {
this._passwordCapability.reject(
@ -2584,7 +2581,7 @@ class WorkerTransport {
});
messageHandler.on("ReaderHeadersReady", data => {
const headersCapability = createPromiseCapability();
const headersCapability = new PromiseCapability();
const fullReader = this._fullReader;
fullReader.headersReady.then(() => {
// If stream or range are disabled, it's our only way to report
@ -2699,7 +2696,7 @@ class WorkerTransport {
});
messageHandler.on("PasswordRequest", exception => {
this._passwordCapability = createPromiseCapability();
this._passwordCapability = new PromiseCapability();
if (loadingTask.onPassword) {
const updatePassword = password => {
@ -3120,7 +3117,7 @@ class PDFObjects {
return obj;
}
return (this.#objs[objId] = {
capability: createPromiseCapability(),
capability: new PromiseCapability(),
data: null,
});
}
@ -3280,7 +3277,7 @@ class InternalRenderTask {
this._useRequestAnimationFrame =
useRequestAnimationFrame === true && typeof window !== "undefined";
this.cancelled = false;
this.capability = createPromiseCapability();
this.capability = new PromiseCapability();
this.task = new RenderTask(this);
// caching this-bound methods
this._cancelBound = this.cancel.bind(this);
@ -3360,9 +3357,7 @@ class InternalRenderTask {
operatorListChanged() {
if (!this.graphicsReady) {
if (!this.graphicsReadyCallback) {
this.graphicsReadyCallback = this._continueBound;
}
this.graphicsReadyCallback ||= this._continueBound;
return;
}
this.stepper?.updateOperatorList(this.operatorList);

View File

@ -16,7 +16,7 @@
import {
AbortException,
assert,
createPromiseCapability,
PromiseCapability,
warn,
} from "../shared/util.js";
import {
@ -118,7 +118,7 @@ class PDFFetchStreamReader {
const source = stream.source;
this._withCredentials = source.withCredentials || false;
this._contentLength = source.length;
this._headersCapability = createPromiseCapability();
this._headersCapability = new PromiseCapability();
this._disableRange = source.disableRange || false;
this._rangeChunkSize = source.rangeChunkSize;
if (!this._rangeChunkSize && !this._disableRange) {
@ -224,7 +224,7 @@ class PDFFetchStreamRangeReader {
this._loaded = 0;
const source = stream.source;
this._withCredentials = source.withCredentials || false;
this._readCapability = createPromiseCapability();
this._readCapability = new PromiseCapability();
this._isStreamingSupported = !source.disableStream;
this._abortController = new AbortController();

View File

@ -13,11 +13,7 @@
* limitations under the License.
*/
import {
assert,
createPromiseCapability,
stringToBytes,
} from "../shared/util.js";
import { assert, PromiseCapability, stringToBytes } from "../shared/util.js";
import {
createResponseStatusError,
extractFilenameFromHeader,
@ -259,7 +255,7 @@ class PDFNetworkStreamFullRequestReader {
};
this._url = source.url;
this._fullRequestId = manager.requestFull(args);
this._headersReceivedCapability = createPromiseCapability();
this._headersReceivedCapability = new PromiseCapability();
this._disableRange = source.disableRange || false;
this._contentLength = source.length; // Optional
this._rangeChunkSize = source.rangeChunkSize;
@ -380,7 +376,7 @@ class PDFNetworkStreamFullRequestReader {
if (this._done) {
return { value: undefined, done: true };
}
const requestCapability = createPromiseCapability();
const requestCapability = new PromiseCapability();
this._requests.push(requestCapability);
return requestCapability.promise;
}
@ -471,7 +467,7 @@ class PDFNetworkStreamRangeRequestReader {
if (this._done) {
return { value: undefined, done: true };
}
const requestCapability = createPromiseCapability();
const requestCapability = new PromiseCapability();
this._requests.push(requestCapability);
return requestCapability.promise;
}

View File

@ -17,8 +17,8 @@
import {
AbortException,
assert,
createPromiseCapability,
MissingPDFException,
PromiseCapability,
} from "../shared/util.js";
import {
extractFilenameFromHeader,
@ -124,8 +124,8 @@ class BaseFullReader {
this._isRangeSupported = !source.disableRange;
this._readableStream = null;
this._readCapability = createPromiseCapability();
this._headersCapability = createPromiseCapability();
this._readCapability = new PromiseCapability();
this._headersCapability = new PromiseCapability();
}
get headersReady() {
@ -159,7 +159,7 @@ class BaseFullReader {
const chunk = this._readableStream.read();
if (chunk === null) {
this._readCapability = createPromiseCapability();
this._readCapability = new PromiseCapability();
return this.read();
}
this._loaded += chunk.length;
@ -226,7 +226,7 @@ class BaseRangeReader {
this.onProgress = null;
this._loaded = 0;
this._readableStream = null;
this._readCapability = createPromiseCapability();
this._readCapability = new PromiseCapability();
const source = stream.source;
this._isStreamingSupported = !source.disableStream;
}
@ -246,7 +246,7 @@ class BaseRangeReader {
const chunk = this._readableStream.read();
if (chunk === null) {
this._readCapability = createPromiseCapability();
this._readCapability = new PromiseCapability();
return this.read();
}
this._loaded += chunk.length;

View File

@ -13,13 +13,7 @@
* limitations under the License.
*/
import {
FormatError,
info,
shadow,
unreachable,
Util,
} from "../shared/util.js";
import { FormatError, info, unreachable, Util } from "../shared/util.js";
import { getCurrentTransform } from "./display_utils.js";
const PathType = {
@ -462,9 +456,7 @@ const PaintType = {
class TilingPattern {
// 10in @ 300dpi shall be enough.
static get MAX_PATTERN_SIZE() {
return shadow(this, "MAX_PATTERN_SIZE", 3000);
}
static MAX_PATTERN_SIZE = 3000;
constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
this.operatorList = IR[2];

View File

@ -18,8 +18,8 @@
import {
AbortException,
createPromiseCapability,
FeatureTest,
PromiseCapability,
Util,
} from "../shared/util.js";
import { deprecated, setLayerDimensions } from "./display_utils.js";
@ -317,7 +317,7 @@ class TextLayerRenderTask {
this._reader = null;
this._textDivProperties = textDivProperties || new WeakMap();
this._canceled = false;
this._capability = createPromiseCapability();
this._capability = new PromiseCapability();
this._layoutTextParams = {
prevFontSize: null,
prevFontFamily: null,
@ -417,7 +417,7 @@ class TextLayerRenderTask {
* @private
*/
_render() {
const capability = createPromiseCapability();
const capability = new PromiseCapability();
let styleCache = Object.create(null);
if (this._isReadableStream) {

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
import { assert, createPromiseCapability } from "../shared/util.js";
import { assert, PromiseCapability } from "../shared/util.js";
import { isPdfFile } from "./display_utils.js";
/** @implements {IPDFStream} */
@ -235,7 +235,7 @@ class PDFDataTransportStreamReader {
if (this._done) {
return { value: undefined, done: true };
}
const requestCapability = createPromiseCapability();
const requestCapability = new PromiseCapability();
this._requests.push(requestCapability);
return requestCapability.promise;
}
@ -300,7 +300,7 @@ class PDFDataTransportStreamRangeReader {
if (this._done) {
return { value: undefined, done: true };
}
const requestCapability = createPromiseCapability();
const requestCapability = new PromiseCapability();
this._requests.push(requestCapability);
return requestCapability.promise;
}

View File

@ -30,7 +30,6 @@ import {
AnnotationEditorType,
AnnotationMode,
CMapCompressionType,
createPromiseCapability,
createValidAbsoluteUrl,
FeatureTest,
InvalidPDFException,
@ -39,6 +38,7 @@ import {
OPS,
PasswordResponses,
PermissionFlag,
PromiseCapability,
shadow,
UnexpectedResponseException,
Util,
@ -88,7 +88,6 @@ export {
AnnotationMode,
build,
CMapCompressionType,
createPromiseCapability,
createValidAbsoluteUrl,
FeatureTest,
getDocument,
@ -109,6 +108,7 @@ export {
PDFWorker,
PermissionFlag,
PixelsPerInch,
PromiseCapability,
RenderingCancelledException,
renderTextLayer,
setLayerDimensions,

View File

@ -1,13 +0,0 @@
{
"parserOptions": {
"ecmaVersion": 2017,
},
"extends": [
"../../.eslintrc"
],
"env": {
"es2017": true,
},
}

View File

@ -293,7 +293,7 @@ var Type2Parser = function type2Parser(aFilePath) {
font.set(token.name, stack.pop());
break;
default:
if (token.operand && token.operand.length) {
if (token.operand?.length) {
var array = [];
for (var j = 0; j < token.operand.length; j++) {
array.push(stack.pop());

View File

@ -16,9 +16,9 @@
import {
AbortException,
assert,
createPromiseCapability,
MissingPDFException,
PasswordException,
PromiseCapability,
UnexpectedResponseException,
UnknownErrorException,
unreachable,
@ -87,7 +87,7 @@ class MessageHandler {
return;
}
if (data.stream) {
this._processStreamMessage(data);
this.#processStreamMessage(data);
return;
}
if (data.callback) {
@ -140,7 +140,7 @@ class MessageHandler {
return;
}
if (data.streamId) {
this._createStreamSink(data);
this.#createStreamSink(data);
return;
}
action(data.data);
@ -190,7 +190,7 @@ class MessageHandler {
*/
sendWithPromise(actionName, data, transfers) {
const callbackId = this.callbackId++;
const capability = createPromiseCapability();
const capability = new PromiseCapability();
this.callbackCapabilities[callbackId] = capability;
try {
this.comObj.postMessage(
@ -228,7 +228,7 @@ class MessageHandler {
return new ReadableStream(
{
start: controller => {
const startCapability = createPromiseCapability();
const startCapability = new PromiseCapability();
this.streamControllers[streamId] = {
controller,
startCall: startCapability,
@ -252,7 +252,7 @@ class MessageHandler {
},
pull: controller => {
const pullCapability = createPromiseCapability();
const pullCapability = new PromiseCapability();
this.streamControllers[streamId].pullCall = pullCapability;
comObj.postMessage({
sourceName,
@ -268,7 +268,7 @@ class MessageHandler {
cancel: reason => {
assert(reason instanceof Error, "cancel must have a valid reason");
const cancelCapability = createPromiseCapability();
const cancelCapability = new PromiseCapability();
this.streamControllers[streamId].cancelCall = cancelCapability;
this.streamControllers[streamId].isClosed = true;
comObj.postMessage({
@ -286,10 +286,7 @@ class MessageHandler {
);
}
/**
* @private
*/
_createStreamSink(data) {
#createStreamSink(data) {
const streamId = data.streamId,
sourceName = this.sourceName,
targetName = data.sourceName,
@ -308,7 +305,7 @@ class MessageHandler {
// so when it changes from positive to negative,
// set ready as unresolved promise.
if (lastDesiredSize > 0 && this.desiredSize <= 0) {
this.sinkCapability = createPromiseCapability();
this.sinkCapability = new PromiseCapability();
this.ready = this.sinkCapability.promise;
}
comObj.postMessage(
@ -352,7 +349,7 @@ class MessageHandler {
});
},
sinkCapability: createPromiseCapability(),
sinkCapability: new PromiseCapability(),
onPull: null,
onCancel: null,
isCancelled: false,
@ -388,10 +385,7 @@ class MessageHandler {
);
}
/**
* @private
*/
_processStreamMessage(data) {
#processStreamMessage(data) {
const streamId = data.streamId,
sourceName = this.sourceName,
targetName = data.sourceName,
@ -435,7 +429,7 @@ class MessageHandler {
streamSink.desiredSize = data.desiredSize;
new Promise(function (resolve) {
resolve(streamSink.onPull && streamSink.onPull());
resolve(streamSink.onPull?.());
}).then(
function () {
comObj.postMessage({
@ -471,12 +465,12 @@ class MessageHandler {
}
streamController.isClosed = true;
streamController.controller.close();
this._deleteStreamController(streamController, streamId);
this.#deleteStreamController(streamController, streamId);
break;
case StreamKind.ERROR:
assert(streamController, "error should have stream controller");
streamController.controller.error(wrapReason(data.reason));
this._deleteStreamController(streamController, streamId);
this.#deleteStreamController(streamController, streamId);
break;
case StreamKind.CANCEL_COMPLETE:
if (data.success) {
@ -484,7 +478,7 @@ class MessageHandler {
} else {
streamController.cancelCall.reject(wrapReason(data.reason));
}
this._deleteStreamController(streamController, streamId);
this.#deleteStreamController(streamController, streamId);
break;
case StreamKind.CANCEL:
if (!streamSink) {
@ -492,9 +486,7 @@ class MessageHandler {
}
new Promise(function (resolve) {
resolve(
streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason))
);
resolve(streamSink.onCancel?.(wrapReason(data.reason)));
}).then(
function () {
comObj.postMessage({
@ -524,16 +516,13 @@ class MessageHandler {
}
}
/**
* @private
*/
async _deleteStreamController(streamController, streamId) {
async #deleteStreamController(streamController, streamId) {
// Delete the `streamController` only when the start, pull, and cancel
// capabilities have settled, to prevent `TypeError`s.
await Promise.allSettled([
streamController.startCall && streamController.startCall.promise,
streamController.pullCall && streamController.pullCall.promise,
streamController.cancelCall && streamController.cancelCall.promise,
streamController.startCall?.promise,
streamController.pullCall?.promise,
streamController.cancelCall?.promise,
]);
delete this.streamControllers[streamId];
}

View File

@ -393,10 +393,7 @@ function assert(cond, msg) {
// Checks if URLs use one of the allowed protocols, e.g. to avoid XSS.
function _isValidProtocol(url) {
if (!url) {
return false;
}
switch (url.protocol) {
switch (url?.protocol) {
case "http:":
case "https:":
case "ftp:":
@ -427,7 +424,7 @@ function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
const dots = url.match(/\./g);
// Avoid accidentally matching a *relative* URL pointing to a file named
// e.g. "www.pdf" or similar.
if (dots && dots.length >= 2) {
if (dots?.length >= 2) {
url = `http://${url}`;
}
}
@ -537,11 +534,7 @@ class AbortException extends BaseException {
}
function bytesToString(bytes) {
if (
typeof bytes !== "object" ||
bytes === null ||
bytes.length === undefined
) {
if (typeof bytes !== "object" || bytes?.length === undefined) {
unreachable("Invalid argument for bytesToString");
}
const length = bytes.length;
@ -954,7 +947,7 @@ function utf8StringToString(str) {
}
function isArrayBuffer(v) {
return typeof v === "object" && v !== null && v.byteLength !== undefined;
return typeof v === "object" && v?.byteLength !== undefined;
}
function isArrayEqual(arr1, arr2) {
@ -982,42 +975,41 @@ function getModificationDate(date = new Date()) {
return buffer.join("");
}
/**
* Promise Capability object.
*
* @typedef {Object} PromiseCapability
* @property {Promise<any>} promise - A Promise object.
* @property {boolean} settled - If the Promise has been fulfilled/rejected.
* @property {function} resolve - Fulfills the Promise.
* @property {function} reject - Rejects the Promise.
*/
class PromiseCapability {
#settled = false;
/**
* Creates a promise capability object.
* @alias createPromiseCapability
*
* @returns {PromiseCapability}
*/
function createPromiseCapability() {
const capability = Object.create(null);
let isSettled = false;
constructor() {
/**
* @type {Promise<any>} The Promise object.
*/
this.promise = new Promise((resolve, reject) => {
/**
* @type {function} Fulfills the Promise.
*/
this.resolve = data => {
this.#settled = true;
resolve(data);
};
Object.defineProperty(capability, "settled", {
get() {
return isSettled;
},
});
capability.promise = new Promise(function (resolve, reject) {
capability.resolve = function (data) {
isSettled = true;
resolve(data);
};
capability.reject = function (reason) {
isSettled = true;
reject(reason);
};
});
return capability;
/**
* @type {function} Rejects the Promise.
*/
this.reject = reason => {
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
assert(reason instanceof Error, 'Expected valid "reason" argument.');
}
this.#settled = true;
reject(reason);
};
});
}
/**
* @type {boolean} If the Promise has been fulfilled/rejected.
*/
get settled() {
return this.#settled;
}
}
let NormalizeRegex = null;
@ -1059,7 +1051,6 @@ export {
BASELINE_FACTOR,
bytesToString,
CMapCompressionType,
createPromiseCapability,
createValidAbsoluteUrl,
DocumentActionEventType,
FeatureTest,
@ -1085,6 +1076,7 @@ export {
PasswordException,
PasswordResponses,
PermissionFlag,
PromiseCapability,
RenderingIntentFlag,
setVerbosityLevel,
shadow,

View File

@ -1,32 +0,0 @@
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
// Patch importScripts to work around a bug in WebKit and Chrome 48-.
// See https://crbug.com/572225 and https://webkit.org/b/153317.
self.importScripts = (function (importScripts) {
return function () {
setTimeout(function () {}, 0);
return importScripts.apply(this, arguments);
};
})(importScripts);
importScripts("../node_modules/systemjs/dist/system.js");
importScripts("../systemjs.config.js");
SystemJS.import("pdfjs/core/worker.js").then(function () {
// Worker is loaded at this point.
});

View File

@ -1,96 +0,0 @@
/* Copyright 2017 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable no-var, unicorn/no-typeof-undefined */
"use strict";
(function () {
var baseLocation;
if (typeof document !== "undefined") {
baseLocation = new URL("./", document.currentScript.src);
} else if (typeof location !== "undefined") {
// Probably worker -- walking subfolders until we will reach root.
baseLocation = location;
while (baseLocation.href.includes("/src/")) {
baseLocation = new URL("..", baseLocation);
}
} else {
throw new Error("Cannot configure SystemJS");
}
var PluginBabelPath = "node_modules/systemjs-plugin-babel/plugin-babel.js";
var SystemJSPluginBabelPath =
"node_modules/systemjs-plugin-babel/systemjs-babel-browser.js";
var PluginBabelCachePath = "external/systemjs/plugin-babel-cached.js";
var isCachingPossible =
typeof indexedDB !== "undefined" &&
typeof TextEncoder !== "undefined" &&
typeof crypto !== "undefined" &&
typeof crypto.subtle !== "undefined";
// When we create a bundle, webpack is run on the source and it will replace
// require with __webpack_require__. When we want to use the real require,
// __non_webpack_require__ has to be used.
// In this target, we don't create a bundle, so we have to replace the
// occurrences of __non_webpack_require__ ourselves.
function babelPluginReplaceNonWebPackRequire(babel) {
return {
visitor: {
Identifier(path, state) {
if (path.node.name === "__non_webpack_require__") {
path.replaceWith(babel.types.identifier("require"));
}
},
},
};
}
SystemJS.config({
packages: {
"": {
defaultExtension: "js",
},
},
paths: {
pdfjs: new URL("src", baseLocation).href,
"pdfjs-web": new URL("web", baseLocation).href,
"pdfjs-test": new URL("test", baseLocation).href,
"pdfjs-lib": new URL("src/pdf", baseLocation).href,
"core-js": new URL("node_modules/core-js", baseLocation).href,
"web-streams-polyfill": new URL(
"node_modules/web-streams-polyfill",
baseLocation
).href,
},
meta: {
"*": {
scriptLoad: false,
esModule: true,
babelOptions: {
env: false,
plugins: [babelPluginReplaceNonWebPackRequire],
},
},
},
map: {
"plugin-babel": new URL(PluginBabelPath, baseLocation).href,
"systemjs-babel-build": new URL(SystemJSPluginBabelPath, baseLocation)
.href,
"plugin-babel-cached": new URL(PluginBabelCachePath, baseLocation).href,
},
transpiler: isCachingPossible ? "plugin-babel-cached" : "plugin-babel",
});
})();

View File

@ -17,10 +17,10 @@
const {
AnnotationLayer,
AnnotationMode,
createPromiseCapability,
getDocument,
GlobalWorkerOptions,
PixelsPerInch,
PromiseCapability,
renderTextLayer,
shadow,
XfaLayer,
@ -922,7 +922,7 @@ class Driver {
}
_send(url, message) {
const capability = createPromiseCapability();
const capability = new PromiseCapability();
this.inflight.textContent = this.inFlightRequests++;
fetch(url, {

View File

@ -17,7 +17,6 @@ import {
AnnotationEditorType,
AnnotationMode,
AnnotationType,
createPromiseCapability,
ImageKind,
InvalidPDFException,
MissingPDFException,
@ -26,6 +25,7 @@ import {
PasswordException,
PasswordResponses,
PermissionFlag,
PromiseCapability,
UnknownErrorException,
} from "../../src/shared/util.js";
import {
@ -137,7 +137,7 @@ describe("api", function () {
const loadingTask = getDocument(basicApiGetDocumentParams);
expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
const progressReportedCapability = createPromiseCapability();
const progressReportedCapability = new PromiseCapability();
// Attach the callback that is used to report loading progress;
// similarly to how viewer.js works.
loadingTask.onProgress = function (progressData) {
@ -199,7 +199,7 @@ describe("api", function () {
const loadingTask = getDocument(typedArrayPdf);
expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
const progressReportedCapability = createPromiseCapability();
const progressReportedCapability = new PromiseCapability();
loadingTask.onProgress = function (data) {
progressReportedCapability.resolve(data);
};
@ -229,7 +229,7 @@ describe("api", function () {
const loadingTask = getDocument(arrayBufferPdf);
expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
const progressReportedCapability = createPromiseCapability();
const progressReportedCapability = new PromiseCapability();
loadingTask.onProgress = function (data) {
progressReportedCapability.resolve(data);
};
@ -291,8 +291,8 @@ describe("api", function () {
const loadingTask = getDocument(buildGetDocumentParams("pr6531_1.pdf"));
expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
const passwordNeededCapability = createPromiseCapability();
const passwordIncorrectCapability = createPromiseCapability();
const passwordNeededCapability = new PromiseCapability();
const passwordIncorrectCapability = new PromiseCapability();
// Attach the callback that is used to request a password;
// similarly to how the default viewer handles passwords.
loadingTask.onPassword = function (updatePassword, reason) {

View File

@ -15,7 +15,7 @@
import {
AbortException,
createPromiseCapability,
PromiseCapability,
UnknownErrorException,
} from "../../src/shared/util.js";
import { LoopbackPort } from "../../src/display/api.js";
@ -338,7 +338,7 @@ describe("message_handler", function () {
it("should ignore any pull after close is called", async function () {
let log = "";
const port = new LoopbackPort();
const capability = createPromiseCapability();
const capability = new PromiseCapability();
const messageHandler2 = new MessageHandler("worker", "main", port);
messageHandler2.on("fakeHandler", (data, sink) => {
sink.onPull = function () {

View File

@ -15,10 +15,10 @@
import {
bytesToString,
createPromiseCapability,
createValidAbsoluteUrl,
getModificationDate,
isArrayBuffer,
PromiseCapability,
string32,
stringToBytes,
stringToPDFString,
@ -212,9 +212,9 @@ describe("util", function () {
});
});
describe("createPromiseCapability", function () {
describe("PromiseCapability", function () {
it("should resolve with correct data", async function () {
const promiseCapability = createPromiseCapability();
const promiseCapability = new PromiseCapability();
expect(promiseCapability.settled).toEqual(false);
promiseCapability.resolve({ test: "abc" });
@ -225,7 +225,7 @@ describe("util", function () {
});
it("should reject with correct reason", async function () {
const promiseCapability = createPromiseCapability();
const promiseCapability = new PromiseCapability();
expect(promiseCapability.settled).toEqual(false);
promiseCapability.reject(new Error("reason"));

View File

@ -36,7 +36,6 @@ import {
import {
AnnotationEditorType,
build,
createPromiseCapability,
FeatureTest,
getDocument,
getFilenameFromUrl,
@ -49,6 +48,7 @@ import {
MissingPDFException,
OPS,
PDFWorker,
PromiseCapability,
shadow,
UnexpectedResponseException,
version,
@ -156,7 +156,7 @@ class DefaultExternalServices {
const PDFViewerApplication = {
initialBookmark: document.location.hash.substring(1),
_initializedCapability: createPromiseCapability(),
_initializedCapability: new PromiseCapability(),
appConfig: null,
pdfDocument: null,
pdfLoadingTask: null,
@ -309,12 +309,7 @@ const PDFViewerApplication = {
const { mainContainer, viewerContainer } = this.appConfig,
params = parseQueryString(hash);
if (
typeof PDFJSDev === "undefined" &&
params.get("workermodules") === "true"
) {
AppOptions.set("workerSrc", "../src/pdf.worker.js");
} else if (params.get("disableworker") === "true") {
if (params.get("disableworker") === "true") {
try {
await loadFakeWorker();
} catch (ex) {

View File

@ -292,7 +292,7 @@ const defaultOptions = {
value:
// eslint-disable-next-line no-nested-ternary
typeof PDFJSDev === "undefined"
? "../src/worker_loader.js"
? "../src/pdf.worker.js"
: PDFJSDev.test("MOZCENTRAL")
? "resource://pdf.js/build/pdf.worker.js"
: "../build/pdf.worker.js",

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
import { createPromiseCapability, PasswordResponses } from "pdfjs-lib";
import { PasswordResponses, PromiseCapability } from "pdfjs-lib";
/**
* @typedef {Object} PasswordPromptOptions
@ -69,7 +69,7 @@ class PasswordPrompt {
if (this.#activeCapability) {
await this.#activeCapability.promise;
}
this.#activeCapability = createPromiseCapability();
this.#activeCapability = new PromiseCapability();
try {
await this.overlayManager.open(this.dialog);

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
import { createPromiseCapability, getFilenameFromUrl } from "pdfjs-lib";
import { getFilenameFromUrl, PromiseCapability } from "pdfjs-lib";
import { BaseTreeViewer } from "./base_tree_viewer.js";
import { waitOnEventOrTimeout } from "./event_utils.js";
@ -50,7 +50,7 @@ class PDFAttachmentViewer extends BaseTreeViewer {
if (!keepRenderedCapability) {
// The only situation in which the `_renderedCapability` should *not* be
// replaced is when appending FileAttachment annotations.
this._renderedCapability = createPromiseCapability();
this._renderedCapability = new PromiseCapability();
}
this._pendingDispatchEvent = false;
}

View File

@ -13,8 +13,8 @@
* limitations under the License.
*/
import { createPromiseCapability, PDFDateString } from "pdfjs-lib";
import { getPageSizeInches, isPortraitOrientation } from "./ui_utils.js";
import { PDFDateString, PromiseCapability } from "pdfjs-lib";
const DEFAULT_FIELD_CONTENT = "-";
@ -201,7 +201,7 @@ class PDFDocumentProperties {
this.pdfDocument = null;
this.#fieldData = null;
this._dataAvailableCapability = createPromiseCapability();
this._dataAvailableCapability = new PromiseCapability();
this._currentPageNumber = 1;
this._pagesRotation = 0;
}

View File

@ -19,7 +19,7 @@
import { binarySearchFirstItem, scrollIntoView } from "./ui_utils.js";
import { getCharacterType, getNormalizeWithNFKC } from "./pdf_find_utils.js";
import { createPromiseCapability } from "pdfjs-lib";
import { PromiseCapability } from "pdfjs-lib";
const FindState = {
FOUND: 0,
@ -582,7 +582,7 @@ class PDFFindController {
clearTimeout(this._findTimeout);
this._findTimeout = null;
this._firstPageCapability = createPromiseCapability();
this._firstPageCapability = new PromiseCapability();
}
/**
@ -849,7 +849,7 @@ class PDFFindController {
let promise = Promise.resolve();
const textOptions = { disableNormalization: true };
for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) {
const extractTextCapability = createPromiseCapability();
const extractTextCapability = new PromiseCapability();
this._extractTextPromises[i] = extractTextCapability.promise;
promise = promise.then(() => {

View File

@ -14,7 +14,7 @@
*/
import { BaseTreeViewer } from "./base_tree_viewer.js";
import { createPromiseCapability } from "pdfjs-lib";
import { PromiseCapability } from "pdfjs-lib";
import { SidebarView } from "./ui_utils.js";
/**
@ -89,7 +89,7 @@ class PDFOutlineViewer extends BaseTreeViewer {
* @private
*/
_dispatchEvent(outlineCount) {
this._currentOutlineItemCapability = createPromiseCapability();
this._currentOutlineItemCapability = new PromiseCapability();
if (
outlineCount === 0 ||
this._pdfDocument?.loadingParams.disableAutoFetch
@ -308,7 +308,7 @@ class PDFOutlineViewer extends BaseTreeViewer {
if (this._pageNumberToDestHashCapability) {
return this._pageNumberToDestHashCapability.promise;
}
this._pageNumberToDestHashCapability = createPromiseCapability();
this._pageNumberToDestHashCapability = new PromiseCapability();
const pageNumberToDestHash = new Map(),
pageNumberNesting = new Map();

View File

@ -16,7 +16,7 @@
/** @typedef {import("./event_utils").EventBus} EventBus */
import { apiPageLayoutToViewerModes, RenderingStates } from "./ui_utils.js";
import { createPromiseCapability, shadow } from "pdfjs-lib";
import { PromiseCapability, shadow } from "pdfjs-lib";
/**
* @typedef {Object} PDFScriptingManagerOptions
@ -357,7 +357,7 @@ class PDFScriptingManager {
visitedPages = this._visitedPages;
if (initialize) {
this._closeCapability = createPromiseCapability();
this._closeCapability = new PromiseCapability();
}
if (!this._closeCapability) {
return; // Scripting isn't fully initialized yet.
@ -443,7 +443,7 @@ class PDFScriptingManager {
* @private
*/
_createScripting() {
this._destroyCapability = createPromiseCapability();
this._destroyCapability = new PromiseCapability();
if (this._scripting) {
throw new Error("_createScripting: Scripting already exists.");

View File

@ -28,9 +28,9 @@ import {
AnnotationEditorType,
AnnotationEditorUIManager,
AnnotationMode,
createPromiseCapability,
PermissionFlag,
PixelsPerInch,
PromiseCapability,
version,
} from "pdfjs-lib";
import {
@ -1025,9 +1025,9 @@ class PDFViewer {
this._location = null;
this._pagesRotation = 0;
this._optionalContentConfigPromise = null;
this._firstPageCapability = createPromiseCapability();
this._onePageRenderedCapability = createPromiseCapability();
this._pagesCapability = createPromiseCapability();
this._firstPageCapability = new PromiseCapability();
this._onePageRenderedCapability = new PromiseCapability();
this._pagesCapability = new PromiseCapability();
this._scrollMode = ScrollMode.VERTICAL;
this._previousScrollMode = ScrollMode.UNKNOWN;
this._spreadMode = SpreadMode.NONE;