Socket
Socket
Sign inDemoInstall

pdfjs-dist

Package Overview
Dependencies
82
Maintainers
3
Versions
1538
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 2.9.359 to 2.10.377

legacy/web/pdf_viewer.d.ts

2

bower.json
{
"name": "pdfjs-dist",
"version": "2.9.359",
"version": "2.10.377",
"main": [

@@ -5,0 +5,0 @@ "build/pdf.js",

@@ -36,3 +36,3 @@ /**

if (maybeLength) {
maybeLength = 0.8 * maybeLength;
maybeLength *= 0.8;
}

@@ -39,0 +39,0 @@

@@ -34,3 +34,3 @@ /**

if (maybeLength) {
maybeLength = 0.5 * maybeLength;
maybeLength *= 0.5;
}

@@ -37,0 +37,0 @@

@@ -67,2 +67,3 @@ /**

this.builtInCMapCache = new Map();
this.standardFontDataCache = new Map();
this.globalImageCache = new _image_utils.GlobalImageCache();

@@ -1005,2 +1006,22 @@ this.pageKidsCountCache = new _primitives.RefSetCache();

get xfaImages() {
const obj = this._catDict.get("Names");
let xfaImages = null;
if (obj instanceof _primitives.Dict && obj.has("XFAImages")) {
const nameTree = new _name_number_tree.NameTree(obj.getRaw("XFAImages"), this.xref);
for (const [key, value] of nameTree.getAll()) {
if (!xfaImages) {
xfaImages = new _primitives.Dict(this.xref);
}
xfaImages.set(key, value);
}
}
return (0, _util.shadow)(this, "xfaImages", xfaImages);
}
_collectJavaScript() {

@@ -1114,2 +1135,3 @@ const obj = this._catDict.get("Names");

this.builtInCMapCache.clear();
this.standardFontDataCache.clear();
});

@@ -1116,0 +1138,0 @@ }

@@ -89,3 +89,8 @@ /**

const encoding = cff.encoding ? cff.encoding.encoding : null;
let encoding = cff.encoding ? cff.encoding.encoding : null;
if (properties.isInternalFont) {
encoding = properties.defaultEncoding;
}
charCodeToGlyphId = (0, _fonts_utils.type1FontGlyphMapping)(properties, encoding, charsets);

@@ -92,0 +97,0 @@ return charCodeToGlyphId;

@@ -611,2 +611,5 @@ /**

return true;
} else if (value === 0 && j === data.length) {
data[j - 1] = 14;
validationCommand = CharstringValidationData[14];
} else {

@@ -631,2 +634,8 @@ validationCommand = CharstringValidationData[value];

(0, _util.warn)("Not enough parameters for " + validationCommand.id + "; actual: " + stackSize + ", expected: " + validationCommand.min);
if (stackSize === 0) {
data[j - 1] = 14;
return true;
}
return false;

@@ -931,3 +940,3 @@ }

format = format & 0x7f;
format &= 0x7f;
return new CFFEncoding(predefined, format, encoding, raw);

@@ -1495,3 +1504,3 @@ }

} else if (value >= 108 && value <= 1131) {
value = value - 108;
value -= 108;
code = [(value >> 8) + 247, value & 0xff];

@@ -1498,0 +1507,0 @@ } else if (value >= -1131 && value <= -108) {

@@ -388,3 +388,3 @@ /**

while (bufferSize < 8 && stack.length > 0) {
buffer = stack[--sp] << bufferSize | buffer;
buffer |= stack[--sp] << bufferSize;
bufferSize += 7;

@@ -391,0 +391,0 @@ }

@@ -41,3 +41,3 @@ /**

exports.validateCSSFont = validateCSSFont;
exports.XRefParseException = exports.XRefEntryException = exports.MissingDataException = void 0;
exports.XRefParseException = exports.XRefEntryException = exports.ParserEOFException = exports.MissingDataException = void 0;

@@ -91,2 +91,6 @@ var _util = require("../shared/util.js");

class ParserEOFException extends _util.BaseException {}
exports.ParserEOFException = ParserEOFException;
class XRefEntryException extends _util.BaseException {}

@@ -93,0 +97,0 @@

@@ -212,3 +212,3 @@ /**

this.high = this.high << places | this.low >>> 32 - places;
this.low = this.low << places;
this.low <<= places;
}

@@ -981,3 +981,3 @@ }

t4 = s[t4];
t1 = t1 ^ rcon[i];
t1 ^= rcon[i];

@@ -1034,3 +1034,3 @@ for (let n = 0; n < 4; ++n) {

t4 = s[t4];
t1 = t1 ^ r;
t1 ^= r;

@@ -1037,0 +1037,0 @@ if ((r <<= 1) >= 256) {

@@ -45,2 +45,4 @@ /**

var _xfa_fonts = require("./xfa_fonts.js");
var _parser = require("./parser.js");

@@ -75,2 +77,3 @@

builtInCMapCache,
standardFontDataCache,
globalImageCache,

@@ -87,2 +90,3 @@ nonBlendModesSet,

this.builtInCMapCache = builtInCMapCache;
this.standardFontDataCache = standardFontDataCache;
this.globalImageCache = globalImageCache;

@@ -140,7 +144,3 @@ this.nonBlendModesSet = nonBlendModesSet;

if (this.xfaData) {
const {
width,
height
} = this.xfaData.attributes.style;
return [0, 0, parseInt(width), parseInt(height)];
return this.xfaData.bbox;
}

@@ -207,3 +207,3 @@

} else if (rotate >= 360) {
rotate = rotate % 360;
rotate %= 360;
} else if (rotate < 0) {

@@ -232,3 +232,5 @@ rotate = (rotate % 360 + 360) % 360;

if (this.xfaFactory) {
return (0, _util.shadow)(this, "xfaData", this.xfaFactory.getPage(this.pageIndex));
return (0, _util.shadow)(this, "xfaData", {
bbox: this.xfaFactory.getBoundingBox(this.pageIndex)
});
}

@@ -247,2 +249,3 @@

builtInCMapCache: this.builtInCMapCache,
standardFontDataCache: this.standardFontDataCache,
globalImageCache: this.globalImageCache,

@@ -297,2 +300,3 @@ options: this.evaluatorOptions

builtInCMapCache: this.builtInCMapCache,
standardFontDataCache: this.standardFontDataCache,
globalImageCache: this.globalImageCache,

@@ -326,6 +330,7 @@ options: this.evaluatorOptions

const annotationIntent = intent.startsWith("oplist-") ? intent.split("-")[1] : intent;
const opListPromises = [];
for (const annotation of annotations) {
if (intent === "display" && annotation.mustBeViewed(annotationStorage) || intent === "print" && annotation.mustBePrinted(annotationStorage)) {
if (annotationIntent === "display" && annotation.mustBeViewed(annotationStorage) || annotationIntent === "print" && annotation.mustBePrinted(annotationStorage)) {
opListPromises.push(annotation.getOperatorList(partialEvaluator, task, renderInteractiveForms, annotationStorage).catch(function (reason) {

@@ -373,2 +378,3 @@ (0, _util.warn)("getOperatorList - ignoring annotation data during " + `"${task.name}" task: "${reason}".`);

builtInCMapCache: this.builtInCMapCache,
standardFontDataCache: this.standardFontDataCache,
globalImageCache: this.globalImageCache,

@@ -775,5 +781,38 @@ options: this.evaluatorOptions

get isPureXfa() {
return this.xfaFactory !== null;
return this.xfaFactory && this.xfaFactory.isValid();
}
get htmlForXfa() {
if (this.xfaFactory) {
return this.xfaFactory.getPages();
}
return null;
}
async loadXfaImages() {
const xfaImagesDict = await this.pdfManager.ensureCatalog("xfaImages");
if (!xfaImagesDict) {
return;
}
const keys = xfaImagesDict.getKeys();
const objectLoader = new _object_loader.ObjectLoader(xfaImagesDict, keys, this.xref);
await objectLoader.load();
const xfaImages = new Map();
for (const key of keys) {
const stream = xfaImagesDict.get(key);
if (!(0, _primitives.isStream)(stream)) {
continue;
}
xfaImages.set(key, stream.getBytes());
}
this.xfaFactory.setImages(xfaImages);
}
async loadXfaFonts(handler, task) {

@@ -800,2 +839,4 @@ const acroForm = await this.pdfManager.ensureCatalog("acroForm");

const options = Object.assign(Object.create(null), this.pdfManager.evaluatorOptions);
options.useSystemFonts = false;
const partialEvaluator = new _evaluator.PartialEvaluator({

@@ -807,8 +848,17 @@ xref: this.xref,

fontCache: this.catalog.fontCache,
builtInCMapCache: this.catalog.builtInCMapCache
builtInCMapCache: this.catalog.builtInCMapCache,
standardFontDataCache: this.catalog.standardFontDataCache,
options
});
const operatorList = new _operator_list.OperatorList();
const pdfFonts = [];
const initialState = {
font: null,
get font() {
return pdfFonts[pdfFonts.length - 1];
},
set font(font) {
pdfFonts.push(font);
},
clone() {

@@ -832,3 +882,4 @@ return this;

const fontFamily = descriptor.get("FontFamily");
let fontFamily = descriptor.get("FontFamily");
fontFamily = fontFamily.replace(/[ ]+([0-9])/g, "$1");
const fontWeight = descriptor.get("FontWeight");

@@ -853,4 +904,78 @@ const italicAngle = -descriptor.get("ItalicAngle");

await Promise.all(promises);
const missingFonts = this.xfaFactory.setFonts(pdfFonts);
if (!missingFonts) {
return;
}
options.ignoreErrors = true;
promises.length = 0;
pdfFonts.length = 0;
const reallyMissingFonts = new Set();
for (const missing of missingFonts) {
if (!(0, _xfa_fonts.getXfaFontWidths)(`${missing}-Regular`)) {
reallyMissingFonts.add(missing);
}
}
if (reallyMissingFonts.size) {
missingFonts.push("PdfJS-Fallback");
}
for (const missing of missingFonts) {
if (reallyMissingFonts.has(missing)) {
continue;
}
for (const fontInfo of [{
name: "Regular",
fontWeight: 400,
italicAngle: 0
}, {
name: "Bold",
fontWeight: 700,
italicAngle: 0
}, {
name: "Italic",
fontWeight: 400,
italicAngle: 12
}, {
name: "BoldItalic",
fontWeight: 700,
italicAngle: 12
}]) {
const name = `${missing}-${fontInfo.name}`;
const widths = (0, _xfa_fonts.getXfaFontWidths)(name);
const dict = new _primitives.Dict(null);
dict.set("BaseFont", _primitives.Name.get(name));
dict.set("Type", _primitives.Name.get("Font"));
dict.set("Subtype", _primitives.Name.get("TrueType"));
dict.set("Encoding", _primitives.Name.get("WinAnsiEncoding"));
const descriptor = new _primitives.Dict(null);
descriptor.set("Widths", widths);
dict.set("FontDescriptor", descriptor);
promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(name), 1], null, operatorList, task, initialState, dict, {
fontFamily: missing,
fontWeight: fontInfo.fontWeight,
italicAngle: fontInfo.italicAngle
}).catch(function (reason) {
(0, _util.warn)(`loadXfaFonts: "${reason}".`);
return null;
}));
}
}
await Promise.all(promises);
this.xfaFactory.appendFonts(pdfFonts, reallyMissingFonts);
}
async serializeXfaData(annotationStorage) {
if (this.xfaFactory) {
return this.xfaFactory.serializeData(annotationStorage);
}
return null;
}
get formInfo() {

@@ -966,20 +1091,32 @@ const formInfo = {

get fingerprint() {
let hash;
const idArray = this.xref.trailer.get("ID");
get fingerprints() {
function validate(data) {
return typeof data === "string" && data.length > 0 && data !== EMPTY_FINGERPRINT;
}
if (Array.isArray(idArray) && idArray[0] && (0, _util.isString)(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
hash = (0, _util.stringToBytes)(idArray[0]);
} else {
hash = (0, _crypto.calculateMD5)(this.stream.getByteRange(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
function hexString(hash) {
const buf = [];
for (let i = 0, ii = hash.length; i < ii; i++) {
const hex = hash[i].toString(16);
buf.push(hex.padStart(2, "0"));
}
return buf.join("");
}
const fingerprintBuf = [];
const idArray = this.xref.trailer.get("ID");
let hashOriginal, hashModified;
for (let i = 0, ii = hash.length; i < ii; i++) {
const hex = hash[i].toString(16);
fingerprintBuf.push(hex.padStart(2, "0"));
if (Array.isArray(idArray) && validate(idArray[0])) {
hashOriginal = (0, _util.stringToBytes)(idArray[0]);
if (idArray[1] !== idArray[0] && validate(idArray[1])) {
hashModified = (0, _util.stringToBytes)(idArray[1]);
}
} else {
hashOriginal = (0, _crypto.calculateMD5)(this.stream.getByteRange(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
}
return (0, _util.shadow)(this, "fingerprint", fingerprintBuf.join(""));
return (0, _util.shadow)(this, "fingerprints", [hexString(hashOriginal), hashModified ? hexString(hashModified) : null]);
}

@@ -1031,2 +1168,3 @@

builtInCMapCache: catalog.builtInCMapCache,
standardFontDataCache: catalog.standardFontDataCache,
globalImageCache: catalog.globalImageCache,

@@ -1049,2 +1187,3 @@ nonBlendModesSet: catalog.nonBlendModesSet,

builtInCMapCache: catalog.builtInCMapCache,
standardFontDataCache: catalog.standardFontDataCache,
globalImageCache: catalog.globalImageCache,

@@ -1051,0 +1190,0 @@ nonBlendModesSet: catalog.nonBlendModesSet,

@@ -28,2 +28,3 @@ /**

exports.getFontType = getFontType;
exports.normalizeFontName = normalizeFontName;
exports.recoverGlyphName = recoverGlyphName;

@@ -58,5 +59,9 @@ exports.type1FontGlyphMapping = type1FontGlyphMapping;

function getFontType(type, subtype) {
function getFontType(type, subtype, isStandardFont = false) {
switch (type) {
case "Type1":
if (isStandardFont) {
return _util.FontType.TYPE1STANDARD;
}
return subtype === "Type1C" ? _util.FontType.TYPE1C : _util.FontType.TYPE1;

@@ -111,3 +116,15 @@

if (properties.baseEncodingName) {
if (properties.isInternalFont) {
baseEncoding = builtInEncoding;
for (charCode = 0; charCode < baseEncoding.length; charCode++) {
glyphId = glyphNames.indexOf(baseEncoding[charCode]);
if (glyphId >= 0) {
charCodeToGlyphId[charCode] = glyphId;
} else {
charCodeToGlyphId[charCode] = 0;
}
}
} else if (properties.baseEncodingName) {
baseEncoding = (0, _encodings.getEncoding)(properties.baseEncodingName);

@@ -171,2 +188,6 @@

return charCodeToGlyphId;
}
function normalizeFontName(name) {
return name.replace(/[,_]/g, "-").replace(/\s/g, "");
}

@@ -155,503 +155,407 @@ /**

const PDFFunction = function PDFFunctionClosure() {
const CONSTRUCT_SAMPLED = 0;
const CONSTRUCT_INTERPOLATED = 2;
const CONSTRUCT_STICHED = 3;
const CONSTRUCT_POSTSCRIPT = 4;
return {
getSampleArray(size, outputSize, bps, stream) {
let i, ii;
let length = 1;
class PDFFunction {
static getSampleArray(size, outputSize, bps, stream) {
let i, ii;
let length = 1;
for (i = 0, ii = size.length; i < ii; i++) {
length *= size[i];
}
for (i = 0, ii = size.length; i < ii; i++) {
length *= size[i];
}
length *= outputSize;
const array = new Array(length);
let codeSize = 0;
let codeBuf = 0;
const sampleMul = 1.0 / (2.0 ** bps - 1);
const strBytes = stream.getBytes((length * bps + 7) / 8);
let strIdx = 0;
length *= outputSize;
const array = new Array(length);
let codeSize = 0;
let codeBuf = 0;
const sampleMul = 1.0 / (2.0 ** bps - 1);
const strBytes = stream.getBytes((length * bps + 7) / 8);
let strIdx = 0;
for (i = 0; i < length; i++) {
while (codeSize < bps) {
codeBuf <<= 8;
codeBuf |= strBytes[strIdx++];
codeSize += 8;
}
codeSize -= bps;
array[i] = (codeBuf >> codeSize) * sampleMul;
codeBuf &= (1 << codeSize) - 1;
for (i = 0; i < length; i++) {
while (codeSize < bps) {
codeBuf <<= 8;
codeBuf |= strBytes[strIdx++];
codeSize += 8;
}
return array;
},
codeSize -= bps;
array[i] = (codeBuf >> codeSize) * sampleMul;
codeBuf &= (1 << codeSize) - 1;
}
getIR({
xref,
isEvalSupported,
fn
}) {
let dict = fn.dict;
return array;
}
if (!dict) {
dict = fn;
}
static parse({
xref,
isEvalSupported,
fn
}) {
const dict = fn.dict || fn;
const typeNum = dict.get("FunctionType");
const types = [this.constructSampled, null, this.constructInterpolated, this.constructStiched, this.constructPostScript];
const typeNum = dict.get("FunctionType");
const typeFn = types[typeNum];
switch (typeNum) {
case 0:
return this.constructSampled({
xref,
isEvalSupported,
fn,
dict
});
if (!typeFn) {
throw new _util.FormatError("Unknown type of function");
}
case 1:
break;
return typeFn.call(this, {
xref,
isEvalSupported,
fn,
dict
});
},
case 2:
return this.constructInterpolated({
xref,
isEvalSupported,
dict
});
fromIR({
xref,
isEvalSupported,
IR
}) {
const type = IR[0];
case 3:
return this.constructStiched({
xref,
isEvalSupported,
dict
});
switch (type) {
case CONSTRUCT_SAMPLED:
return this.constructSampledFromIR({
xref,
isEvalSupported,
IR
});
case 4:
return this.constructPostScript({
xref,
isEvalSupported,
fn,
dict
});
}
case CONSTRUCT_INTERPOLATED:
return this.constructInterpolatedFromIR({
xref,
isEvalSupported,
IR
});
throw new _util.FormatError("Unknown type of function");
}
case CONSTRUCT_STICHED:
return this.constructStichedFromIR({
xref,
isEvalSupported,
IR
});
default:
return this.constructPostScriptFromIR({
xref,
isEvalSupported,
IR
});
}
},
parse({
xref,
isEvalSupported,
fn
}) {
const IR = this.getIR({
static parseArray({
xref,
isEvalSupported,
fnObj
}) {
if (!Array.isArray(fnObj)) {
return this.parse({
xref,
isEvalSupported,
fn
fn: fnObj
});
return this.fromIR({
}
const fnArray = [];
for (let j = 0, jj = fnObj.length; j < jj; j++) {
fnArray.push(this.parse({
xref,
isEvalSupported,
IR
});
},
fn: xref.fetchIfRef(fnObj[j])
}));
}
parseArray({
xref,
isEvalSupported,
fnObj
}) {
if (!Array.isArray(fnObj)) {
return this.parse({
xref,
isEvalSupported,
fn: fnObj
});
return function (src, srcOffset, dest, destOffset) {
for (let i = 0, ii = fnArray.length; i < ii; i++) {
fnArray[i](src, srcOffset, dest, destOffset + i);
}
};
}
const fnArray = [];
static constructSampled({
xref,
isEvalSupported,
fn,
dict
}) {
function toMultiArray(arr) {
const inputLength = arr.length;
const out = [];
let index = 0;
for (let j = 0, jj = fnObj.length; j < jj; j++) {
fnArray.push(this.parse({
xref,
isEvalSupported,
fn: xref.fetchIfRef(fnObj[j])
}));
for (let i = 0; i < inputLength; i += 2) {
out[index++] = [arr[i], arr[i + 1]];
}
return function (src, srcOffset, dest, destOffset) {
for (let i = 0, ii = fnArray.length; i < ii; i++) {
fnArray[i](src, srcOffset, dest, destOffset + i);
}
};
},
return out;
}
constructSampled({
xref,
isEvalSupported,
fn,
dict
}) {
function toMultiArray(arr) {
const inputLength = arr.length;
const out = [];
let index = 0;
function interpolate(x, xmin, xmax, ymin, ymax) {
return ymin + (x - xmin) * ((ymax - ymin) / (xmax - xmin));
}
for (let i = 0; i < inputLength; i += 2) {
out[index] = [arr[i], arr[i + 1]];
++index;
}
let domain = toNumberArray(dict.getArray("Domain"));
let range = toNumberArray(dict.getArray("Range"));
return out;
}
if (!domain || !range) {
throw new _util.FormatError("No domain or range");
}
let domain = toNumberArray(dict.getArray("Domain"));
let range = toNumberArray(dict.getArray("Range"));
const inputSize = domain.length / 2;
const outputSize = range.length / 2;
domain = toMultiArray(domain);
range = toMultiArray(range);
const size = toNumberArray(dict.getArray("Size"));
const bps = dict.get("BitsPerSample");
const order = dict.get("Order") || 1;
if (!domain || !range) {
throw new _util.FormatError("No domain or range");
}
if (order !== 1) {
(0, _util.info)("No support for cubic spline interpolation: " + order);
}
const inputSize = domain.length / 2;
const outputSize = range.length / 2;
domain = toMultiArray(domain);
range = toMultiArray(range);
const size = toNumberArray(dict.getArray("Size"));
const bps = dict.get("BitsPerSample");
const order = dict.get("Order") || 1;
let encode = toNumberArray(dict.getArray("Encode"));
if (order !== 1) {
(0, _util.info)("No support for cubic spline interpolation: " + order);
if (!encode) {
encode = [];
for (let i = 0; i < inputSize; ++i) {
encode.push([0, size[i] - 1]);
}
} else {
encode = toMultiArray(encode);
}
let encode = toNumberArray(dict.getArray("Encode"));
let decode = toNumberArray(dict.getArray("Decode"));
if (!encode) {
encode = [];
if (!decode) {
decode = range;
} else {
decode = toMultiArray(decode);
}
for (let i = 0; i < inputSize; ++i) {
encode.push([0, size[i] - 1]);
}
} else {
encode = toMultiArray(encode);
const samples = this.getSampleArray(size, outputSize, bps, fn);
return function constructSampledFn(src, srcOffset, dest, destOffset) {
const cubeVertices = 1 << inputSize;
const cubeN = new Float64Array(cubeVertices);
const cubeVertex = new Uint32Array(cubeVertices);
let i, j;
for (j = 0; j < cubeVertices; j++) {
cubeN[j] = 1;
}
let decode = toNumberArray(dict.getArray("Decode"));
let k = outputSize,
pos = 1;
if (!decode) {
decode = range;
} else {
decode = toMultiArray(decode);
}
for (i = 0; i < inputSize; ++i) {
const domain_2i = domain[i][0];
const domain_2i_1 = domain[i][1];
const xi = Math.min(Math.max(src[srcOffset + i], domain_2i), domain_2i_1);
let e = interpolate(xi, domain_2i, domain_2i_1, encode[i][0], encode[i][1]);
const size_i = size[i];
e = Math.min(Math.max(e, 0), size_i - 1);
const e0 = e < size_i - 1 ? Math.floor(e) : e - 1;
const n0 = e0 + 1 - e;
const n1 = e - e0;
const offset0 = e0 * k;
const offset1 = offset0 + k;
const samples = this.getSampleArray(size, outputSize, bps, fn);
return [CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size, outputSize, 2 ** bps - 1, range];
},
for (j = 0; j < cubeVertices; j++) {
if (j & pos) {
cubeN[j] *= n1;
cubeVertex[j] += offset1;
} else {
cubeN[j] *= n0;
cubeVertex[j] += offset0;
}
}
constructSampledFromIR({
xref,
isEvalSupported,
IR
}) {
function interpolate(x, xmin, xmax, ymin, ymax) {
return ymin + (x - xmin) * ((ymax - ymin) / (xmax - xmin));
k *= size_i;
pos <<= 1;
}
return function constructSampledFromIRResult(src, srcOffset, dest, destOffset) {
const m = IR[1];
const domain = IR[2];
const encode = IR[3];
const decode = IR[4];
const samples = IR[5];
const size = IR[6];
const n = IR[7];
const range = IR[9];
const cubeVertices = 1 << m;
const cubeN = new Float64Array(cubeVertices);
const cubeVertex = new Uint32Array(cubeVertices);
let i, j;
for (j = 0; j < outputSize; ++j) {
let rj = 0;
for (j = 0; j < cubeVertices; j++) {
cubeN[j] = 1;
for (i = 0; i < cubeVertices; i++) {
rj += samples[cubeVertex[i] + j] * cubeN[i];
}
let k = n,
pos = 1;
rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);
}
};
}
for (i = 0; i < m; ++i) {
const domain_2i = domain[i][0];
const domain_2i_1 = domain[i][1];
const xi = Math.min(Math.max(src[srcOffset + i], domain_2i), domain_2i_1);
let e = interpolate(xi, domain_2i, domain_2i_1, encode[i][0], encode[i][1]);
const size_i = size[i];
e = Math.min(Math.max(e, 0), size_i - 1);
const e0 = e < size_i - 1 ? Math.floor(e) : e - 1;
const n0 = e0 + 1 - e;
const n1 = e - e0;
const offset0 = e0 * k;
const offset1 = offset0 + k;
static constructInterpolated({
xref,
isEvalSupported,
dict
}) {
const c0 = toNumberArray(dict.getArray("C0")) || [0];
const c1 = toNumberArray(dict.getArray("C1")) || [1];
const n = dict.get("N");
const diff = [];
for (j = 0; j < cubeVertices; j++) {
if (j & pos) {
cubeN[j] *= n1;
cubeVertex[j] += offset1;
} else {
cubeN[j] *= n0;
cubeVertex[j] += offset0;
}
}
for (let i = 0, ii = c0.length; i < ii; ++i) {
diff.push(c1[i] - c0[i]);
}
k *= size_i;
pos <<= 1;
}
const length = diff.length;
return function constructInterpolatedFn(src, srcOffset, dest, destOffset) {
const x = n === 1 ? src[srcOffset] : src[srcOffset] ** n;
for (j = 0; j < n; ++j) {
let rj = 0;
for (let j = 0; j < length; ++j) {
dest[destOffset + j] = c0[j] + x * diff[j];
}
};
}
for (i = 0; i < cubeVertices; i++) {
rj += samples[cubeVertex[i] + j] * cubeN[i];
}
static constructStiched({
xref,
isEvalSupported,
dict
}) {
const domain = toNumberArray(dict.getArray("Domain"));
rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);
}
};
},
if (!domain) {
throw new _util.FormatError("No domain");
}
constructInterpolated({
xref,
isEvalSupported,
fn,
dict
}) {
const c0 = toNumberArray(dict.getArray("C0")) || [0];
const c1 = toNumberArray(dict.getArray("C1")) || [1];
const n = dict.get("N");
const length = c0.length;
const diff = [];
const inputSize = domain.length / 2;
for (let i = 0; i < length; ++i) {
diff.push(c1[i] - c0[i]);
}
if (inputSize !== 1) {
throw new _util.FormatError("Bad domain for stiched function");
}
return [CONSTRUCT_INTERPOLATED, c0, diff, n];
},
const fnRefs = dict.get("Functions");
const fns = [];
constructInterpolatedFromIR({
xref,
isEvalSupported,
IR
}) {
const c0 = IR[1];
const diff = IR[2];
const n = IR[3];
const length = diff.length;
return function constructInterpolatedFromIRResult(src, srcOffset, dest, destOffset) {
const x = n === 1 ? src[srcOffset] : src[srcOffset] ** n;
for (let i = 0, ii = fnRefs.length; i < ii; ++i) {
fns.push(this.parse({
xref,
isEvalSupported,
fn: xref.fetchIfRef(fnRefs[i])
}));
}
for (let j = 0; j < length; ++j) {
dest[destOffset + j] = c0[j] + x * diff[j];
const bounds = toNumberArray(dict.getArray("Bounds"));
const encode = toNumberArray(dict.getArray("Encode"));
const tmpBuf = new Float32Array(1);
return function constructStichedFn(src, srcOffset, dest, destOffset) {
const clip = function constructStichedFromIRClip(v, min, max) {
if (v > max) {
v = max;
} else if (v < min) {
v = min;
}
return v;
};
},
constructStiched({
xref,
isEvalSupported,
fn,
dict
}) {
const domain = toNumberArray(dict.getArray("Domain"));
const v = clip(src[srcOffset], domain[0], domain[1]);
const length = bounds.length;
let i;
if (!domain) {
throw new _util.FormatError("No domain");
for (i = 0; i < length; ++i) {
if (v < bounds[i]) {
break;
}
}
const inputSize = domain.length / 2;
let dmin = domain[0];
if (inputSize !== 1) {
throw new _util.FormatError("Bad domain for stiched function");
if (i > 0) {
dmin = bounds[i - 1];
}
const fnRefs = dict.get("Functions");
const fns = [];
let dmax = domain[1];
for (let i = 0, ii = fnRefs.length; i < ii; ++i) {
fns.push(this.parse({
xref,
isEvalSupported,
fn: xref.fetchIfRef(fnRefs[i])
}));
if (i < bounds.length) {
dmax = bounds[i];
}
const bounds = toNumberArray(dict.getArray("Bounds"));
const encode = toNumberArray(dict.getArray("Encode"));
return [CONSTRUCT_STICHED, domain, bounds, encode, fns];
},
const rmin = encode[2 * i];
const rmax = encode[2 * i + 1];
tmpBuf[0] = dmin === dmax ? rmin : rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
fns[i](tmpBuf, 0, dest, destOffset);
};
}
constructStichedFromIR({
xref,
isEvalSupported,
IR
}) {
const domain = IR[1];
const bounds = IR[2];
const encode = IR[3];
const fns = IR[4];
const tmpBuf = new Float32Array(1);
return function constructStichedFromIRResult(src, srcOffset, dest, destOffset) {
const clip = function constructStichedFromIRClip(v, min, max) {
if (v > max) {
v = max;
} else if (v < min) {
v = min;
}
static constructPostScript({
xref,
isEvalSupported,
fn,
dict
}) {
const domain = toNumberArray(dict.getArray("Domain"));
const range = toNumberArray(dict.getArray("Range"));
return v;
};
if (!domain) {
throw new _util.FormatError("No domain.");
}
const v = clip(src[srcOffset], domain[0], domain[1]);
const length = bounds.length;
let i;
if (!range) {
throw new _util.FormatError("No range.");
}
for (i = 0; i < length; ++i) {
if (v < bounds[i]) {
break;
}
}
const lexer = new _ps_parser.PostScriptLexer(fn);
const parser = new _ps_parser.PostScriptParser(lexer);
const code = parser.parse();
let dmin = domain[0];
if (isEvalSupported && _util.IsEvalSupportedCached.value) {
const compiled = new PostScriptCompiler().compile(code, domain, range);
if (i > 0) {
dmin = bounds[i - 1];
}
if (compiled) {
return new Function("src", "srcOffset", "dest", "destOffset", compiled);
}
}
let dmax = domain[1];
(0, _util.info)("Unable to compile PS function");
const numOutputs = range.length >> 1;
const numInputs = domain.length >> 1;
const evaluator = new PostScriptEvaluator(code);
const cache = Object.create(null);
const MAX_CACHE_SIZE = 2048 * 4;
let cache_available = MAX_CACHE_SIZE;
const tmpBuf = new Float32Array(numInputs);
return function constructPostScriptFn(src, srcOffset, dest, destOffset) {
let i, value;
let key = "";
const input = tmpBuf;
if (i < bounds.length) {
dmax = bounds[i];
}
const rmin = encode[2 * i];
const rmax = encode[2 * i + 1];
tmpBuf[0] = dmin === dmax ? rmin : rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
fns[i](tmpBuf, 0, dest, destOffset);
};
},
constructPostScript({
xref,
isEvalSupported,
fn,
dict
}) {
const domain = toNumberArray(dict.getArray("Domain"));
const range = toNumberArray(dict.getArray("Range"));
if (!domain) {
throw new _util.FormatError("No domain.");
for (i = 0; i < numInputs; i++) {
value = src[srcOffset + i];
input[i] = value;
key += value + "_";
}
if (!range) {
throw new _util.FormatError("No range.");
}
const cachedValue = cache[key];
const lexer = new _ps_parser.PostScriptLexer(fn);
const parser = new _ps_parser.PostScriptParser(lexer);
const code = parser.parse();
return [CONSTRUCT_POSTSCRIPT, domain, range, code];
},
constructPostScriptFromIR({
xref,
isEvalSupported,
IR
}) {
const domain = IR[1];
const range = IR[2];
const code = IR[3];
if (isEvalSupported && _util.IsEvalSupportedCached.value) {
const compiled = new PostScriptCompiler().compile(code, domain, range);
if (compiled) {
return new Function("src", "srcOffset", "dest", "destOffset", compiled);
}
if (cachedValue !== undefined) {
dest.set(cachedValue, destOffset);
return;
}
(0, _util.info)("Unable to compile PS function");
const numOutputs = range.length >> 1;
const numInputs = domain.length >> 1;
const evaluator = new PostScriptEvaluator(code);
const cache = Object.create(null);
const MAX_CACHE_SIZE = 2048 * 4;
let cache_available = MAX_CACHE_SIZE;
const tmpBuf = new Float32Array(numInputs);
return function constructPostScriptFromIRResult(src, srcOffset, dest, destOffset) {
let i, value;
let key = "";
const input = tmpBuf;
const output = new Float32Array(numOutputs);
const stack = evaluator.execute(input);
const stackIndex = stack.length - numOutputs;
for (i = 0; i < numInputs; i++) {
value = src[srcOffset + i];
input[i] = value;
key += value + "_";
}
for (i = 0; i < numOutputs; i++) {
value = stack[stackIndex + i];
let bound = range[i * 2];
const cachedValue = cache[key];
if (value < bound) {
value = bound;
} else {
bound = range[i * 2 + 1];
if (cachedValue !== undefined) {
dest.set(cachedValue, destOffset);
return;
}
const output = new Float32Array(numOutputs);
const stack = evaluator.execute(input);
const stackIndex = stack.length - numOutputs;
for (i = 0; i < numOutputs; i++) {
value = stack[stackIndex + i];
let bound = range[i * 2];
if (value < bound) {
if (value > bound) {
value = bound;
} else {
bound = range[i * 2 + 1];
if (value > bound) {
value = bound;
}
}
output[i] = value;
}
if (cache_available > 0) {
cache_available--;
cache[key] = output;
}
output[i] = value;
}
dest.set(output, destOffset);
};
}
if (cache_available > 0) {
cache_available--;
cache[key] = output;
}
};
}();
dest.set(output, destOffset);
};
}
}
function isPDFFunction(v) {

@@ -673,71 +577,69 @@ let fnDict;

const PostScriptStack = function PostScriptStackClosure() {
const MAX_STACK_SIZE = 100;
class PostScriptStack {
static get MAX_STACK_SIZE() {
return (0, _util.shadow)(this, "MAX_STACK_SIZE", 100);
}
class PostScriptStack {
constructor(initialStack) {
this.stack = !initialStack ? [] : Array.prototype.slice.call(initialStack, 0);
constructor(initialStack) {
this.stack = !initialStack ? [] : Array.prototype.slice.call(initialStack, 0);
}
push(value) {
if (this.stack.length >= PostScriptStack.MAX_STACK_SIZE) {
throw new Error("PostScript function stack overflow.");
}
push(value) {
if (this.stack.length >= MAX_STACK_SIZE) {
throw new Error("PostScript function stack overflow.");
}
this.stack.push(value);
}
this.stack.push(value);
pop() {
if (this.stack.length <= 0) {
throw new Error("PostScript function stack underflow.");
}
pop() {
if (this.stack.length <= 0) {
throw new Error("PostScript function stack underflow.");
}
return this.stack.pop();
}
return this.stack.pop();
copy(n) {
if (this.stack.length + n >= PostScriptStack.MAX_STACK_SIZE) {
throw new Error("PostScript function stack overflow.");
}
copy(n) {
if (this.stack.length + n >= MAX_STACK_SIZE) {
throw new Error("PostScript function stack overflow.");
}
const stack = this.stack;
const stack = this.stack;
for (let i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
stack.push(stack[i]);
}
for (let i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
stack.push(stack[i]);
}
}
index(n) {
this.push(this.stack[this.stack.length - n - 1]);
}
index(n) {
this.push(this.stack[this.stack.length - n - 1]);
}
roll(n, p) {
const stack = this.stack;
const l = stack.length - n;
const r = stack.length - 1;
const c = l + (p - Math.floor(p / n) * n);
roll(n, p) {
const stack = this.stack;
const l = stack.length - n;
const r = stack.length - 1;
const c = l + (p - Math.floor(p / n) * n);
for (let i = l, j = r; i < j; i++, j--) {
const t = stack[i];
stack[i] = stack[j];
stack[j] = t;
}
for (let i = l, j = r; i < j; i++, j--) {
const t = stack[i];
stack[i] = stack[j];
stack[j] = t;
}
for (let i = l, j = c - 1; i < j; i++, j--) {
const t = stack[i];
stack[i] = stack[j];
stack[j] = t;
}
for (let i = l, j = c - 1; i < j; i++, j--) {
const t = stack[i];
stack[i] = stack[j];
stack[j] = t;
}
for (let i = c, j = r; i < j; i++, j--) {
const t = stack[i];
stack[i] = stack[j];
stack[j] = t;
}
for (let i = c, j = r; i < j; i++, j--) {
const t = stack[i];
stack[i] = stack[j];
stack[j] = t;
}
}
return PostScriptStack;
}();
}

@@ -744,0 +646,0 @@ class PostScriptEvaluator {

@@ -69,3 +69,3 @@ /**

set(name, ref = null, data) {
if (!name) {
if (typeof name !== "string") {
throw new Error('LocalImageCache.set - expected "name" argument.');

@@ -99,3 +99,3 @@ }

set(name = null, ref = null, data) {
if (!name && !ref) {
if (typeof name !== "string" && !ref) {
throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');

@@ -109,3 +109,3 @@ }

if (name) {
if (name !== null) {
this._nameRefMap.set(name, ref);

@@ -159,3 +159,3 @@ }

set(name, ref = null, data) {
if (!name) {
if (typeof name !== "string") {
throw new Error('LocalGStateCache.set - expected "name" argument.');

@@ -189,3 +189,3 @@ }

set(name, ref = null, data) {
if (!name) {
if (typeof name !== "string") {
throw new Error('LocalTilingPatternCache.set - expected "name" argument.');

@@ -192,0 +192,0 @@ }

@@ -437,3 +437,3 @@ /**

output[i] = value;
buf = buf & (1 << remainingBits) - 1;
buf &= (1 << remainingBits) - 1;
bits = remainingBits;

@@ -440,0 +440,0 @@ }

@@ -951,3 +951,3 @@ /**

for (j = bitsPerValue - 1; j >= 0; j--) {
bit = grayScaleBitPlanes[j][mg][ng] ^ bit;
bit ^= grayScaleBitPlanes[j][mg][ng];
patternIndex |= bit << j;

@@ -954,0 +954,0 @@ }

@@ -540,3 +540,3 @@ /**

static get CHUNK_SIZE_ABOUT() {
return (0, _util.shadow)(this, "CHUNK_SIZE_ABOUT", OperatorList.CHUNK_SIZE - 5);
return (0, _util.shadow)(this, "CHUNK_SIZE_ABOUT", this.CHUNK_SIZE - 5);
}

@@ -549,3 +549,3 @@

if (streamSink && intent !== "oplist") {
if (streamSink && !(intent && intent.startsWith("oplist-"))) {
this.optimizer = new QueueOptimizer(this);

@@ -552,0 +552,0 @@ } else {

@@ -133,7 +133,7 @@ /**

if ((0, _primitives.isEOF)(this.buf1)) {
if (!this.recoveryMode) {
throw new _util.FormatError("End of file inside array");
if (this.recoveryMode) {
return array;
}
return array;
throw new _core_utils.ParserEOFException("End of file inside array.");
}

@@ -165,7 +165,7 @@

if ((0, _primitives.isEOF)(this.buf1)) {
if (!this.recoveryMode) {
throw new _util.FormatError("End of file inside dictionary");
if (this.recoveryMode) {
return dict;
}
return dict;
throw new _core_utils.ParserEOFException("End of file inside dictionary.");
}

@@ -1074,2 +1074,4 @@

(0, _util.warn)(`Name token is longer than allowed by the spec: ${strBuf.length}`);
} else if (strBuf.length === 0) {
(0, _util.warn)("Name token is empty.");
}

@@ -1076,0 +1078,0 @@

@@ -100,2 +100,10 @@ /**

loadXfaImages() {
return this.pdfDocument.loadXfaImages();
}
serializeXfaData(annotationStorage) {
return this.pdfDocument.serializeXfaData(annotationStorage);
}
cleanup(manuallyTriggered = false) {

@@ -102,0 +110,0 @@ return this.pdfDocument.cleanup(manuallyTriggered);

@@ -218,22 +218,5 @@ /**

}) {
const mergedDict = new Dict(xref);
const mergedDict = new Dict(xref),
properties = new Map();
if (!mergeSubDicts) {
for (const dict of dictArray) {
if (!(dict instanceof Dict)) {
continue;
}
for (const [key, value] of Object.entries(dict._map)) {
if (mergedDict._map[key] === undefined) {
mergedDict._map[key] = value;
}
}
}
return mergedDict.size > 0 ? mergedDict : Dict.empty;
}
const properties = new Map();
for (const dict of dictArray) {

@@ -250,2 +233,4 @@ if (!(dict instanceof Dict)) {

properties.set(key, property);
} else if (!mergeSubDicts) {
continue;
}

@@ -252,0 +237,0 @@

@@ -124,41 +124,39 @@ /**

const PostScriptToken = function PostScriptTokenClosure() {
const opCache = Object.create(null);
class PostScriptToken {
static get opCache() {
return (0, _util.shadow)(this, "opCache", Object.create(null));
}
class PostScriptToken {
constructor(type, value) {
this.type = type;
this.value = value;
}
constructor(type, value) {
this.type = type;
this.value = value;
}
static getOperator(op) {
const opValue = opCache[op];
static getOperator(op) {
const opValue = PostScriptToken.opCache[op];
if (opValue) {
return opValue;
}
return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);
if (opValue) {
return opValue;
}
static get LBRACE() {
return (0, _util.shadow)(this, "LBRACE", new PostScriptToken(PostScriptTokenTypes.LBRACE, "{"));
}
return PostScriptToken.opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);
}
static get RBRACE() {
return (0, _util.shadow)(this, "RBRACE", new PostScriptToken(PostScriptTokenTypes.RBRACE, "}"));
}
static get LBRACE() {
return (0, _util.shadow)(this, "LBRACE", new PostScriptToken(PostScriptTokenTypes.LBRACE, "{"));
}
static get IF() {
return (0, _util.shadow)(this, "IF", new PostScriptToken(PostScriptTokenTypes.IF, "IF"));
}
static get RBRACE() {
return (0, _util.shadow)(this, "RBRACE", new PostScriptToken(PostScriptTokenTypes.RBRACE, "}"));
}
static get IFELSE() {
return (0, _util.shadow)(this, "IFELSE", new PostScriptToken(PostScriptTokenTypes.IFELSE, "IFELSE"));
}
static get IF() {
return (0, _util.shadow)(this, "IF", new PostScriptToken(PostScriptTokenTypes.IF, "IF"));
}
static get IFELSE() {
return (0, _util.shadow)(this, "IFELSE", new PostScriptToken(PostScriptTokenTypes.IFELSE, "IFELSE"));
}
return PostScriptToken;
}();
}

@@ -165,0 +163,0 @@ class PostScriptLexer {

@@ -27,7 +27,24 @@ /**

});
exports.getSymbolsFonts = exports.getSupplementalGlyphMapForCalibri = exports.getSupplementalGlyphMapForArialBlack = exports.getStdFontMap = exports.getSerifFonts = exports.getNonStdFontMap = exports.getGlyphMapForStandardFonts = void 0;
exports.getStandardFontName = getStandardFontName;
exports.getSymbolsFonts = exports.getSupplementalGlyphMapForCalibri = exports.getSupplementalGlyphMapForArialBlack = exports.getStdFontMap = exports.getSerifFonts = exports.getNonStdFontMap = exports.getGlyphMapForStandardFonts = exports.getFontNameToFileMap = void 0;
var _core_utils = require("./core_utils.js");
var _fonts_utils = require("./fonts_utils.js");
const getStdFontMap = (0, _core_utils.getLookupTableFactory)(function (t) {
t["Times-Roman"] = "Times-Roman";
t.Helvetica = "Helvetica";
t.Courier = "Courier";
t.Symbol = "Symbol";
t["Times-Bold"] = "Times-Bold";
t["Helvetica-Bold"] = "Helvetica-Bold";
t["Courier-Bold"] = "Courier-Bold";
t.ZapfDingbats = "ZapfDingbats";
t["Times-Italic"] = "Times-Italic";
t["Helvetica-Oblique"] = "Helvetica-Oblique";
t["Courier-Oblique"] = "Courier-Oblique";
t["Times-BoldItalic"] = "Times-BoldItalic";
t["Helvetica-BoldOblique"] = "Helvetica-BoldOblique";
t["Courier-BoldOblique"] = "Courier-BoldOblique";
t.ArialNarrow = "Helvetica";

@@ -53,3 +70,2 @@ t["ArialNarrow-Bold"] = "Helvetica-Bold";

t.ArialMT = "Helvetica";
t["Courier-Bold"] = "Courier-Bold";
t["Courier-BoldItalic"] = "Courier-BoldOblique";

@@ -65,8 +81,4 @@ t["Courier-Italic"] = "Courier-Oblique";

t.CourierNewPSMT = "Courier";
t.Helvetica = "Helvetica";
t["Helvetica-Bold"] = "Helvetica-Bold";
t["Helvetica-BoldItalic"] = "Helvetica-BoldOblique";
t["Helvetica-BoldOblique"] = "Helvetica-BoldOblique";
t["Helvetica-Italic"] = "Helvetica-Oblique";
t["Helvetica-Oblique"] = "Helvetica-Oblique";
t["Symbol-Bold"] = "Symbol";

@@ -92,2 +104,23 @@ t["Symbol-BoldItalic"] = "Symbol";

exports.getStdFontMap = getStdFontMap;
const getFontNameToFileMap = (0, _core_utils.getLookupTableFactory)(function (t) {
t.Courier = "FoxitFixed.pfb";
t["Courier-Bold"] = "FoxitFixedBold.pfb";
t["Courier-BoldOblique"] = "FoxitFixedBoldItalic.pfb";
t["Courier-Oblique"] = "FoxitFixedItalic.pfb";
t.Helvetica = "FoxitSans.pfb";
t["Helvetica-Bold"] = "FoxitSansBold.pfb";
t["Helvetica-BoldOblique"] = "FoxitSansBoldItalic.pfb";
t["Helvetica-Oblique"] = "FoxitSansItalic.pfb";
t["Times-Roman"] = "FoxitSerif.pfb";
t["Times-Bold"] = "FoxitSerifBold.pfb";
t["Times-BoldItalic"] = "FoxitSerifBoldItalic.pfb";
t["Times-Italic"] = "FoxitSerifItalic.pfb";
t.Symbol = "FoxitSymbol.pfb";
t.ZapfDingbats = "FoxitDingbats.pfb";
t["LiberationSans-Regular"] = "LiberationSans-Regular.ttf";
t["LiberationSans-Bold"] = "LiberationSans-Bold.ttf";
t["LiberationSans-Italic"] = "LiberationSans-Italic.ttf";
t["LiberationSans-BoldItalic"] = "LiberationSans-BoldItalic.ttf";
});
exports.getFontNameToFileMap = getFontNameToFileMap;
const getNonStdFontMap = (0, _core_utils.getLookupTableFactory)(function (t) {

@@ -763,2 +796,8 @@ t.Calibri = "Helvetica";

});
exports.getSupplementalGlyphMapForCalibri = getSupplementalGlyphMapForCalibri;
exports.getSupplementalGlyphMapForCalibri = getSupplementalGlyphMapForCalibri;
function getStandardFontName(name) {
const fontName = (0, _fonts_utils.normalizeFontName)(name);
const stdFontMap = getStdFontMap();
return stdFontMap[fontName];
}

@@ -296,3 +296,3 @@ /**

} else if (value <= 246) {
value = value - 139;
value -= 139;
} else if (value <= 250) {

@@ -299,0 +299,0 @@ value = (value - 247) * 256 + encoded[++i] + 108;

@@ -110,3 +110,3 @@ /**

const apiVersion = docParams.apiVersion;
const workerVersion = '2.9.359';
const workerVersion = '2.10.377';

@@ -162,3 +162,3 @@ if (apiVersion !== workerVersion) {

const [numPages, fingerprint, isPureXfa] = await Promise.all([pdfManager.ensureDoc("numPages"), pdfManager.ensureDoc("fingerprint"), pdfManager.ensureDoc("isPureXfa")]);
const isPureXfa = await pdfManager.ensureDoc("isPureXfa");

@@ -168,9 +168,11 @@ if (isPureXfa) {

startWorkerTask(task);
await pdfManager.loadXfaFonts(handler, task).catch(reason => {}).then(() => finishWorkerTask(task));
await Promise.all([pdfManager.loadXfaFonts(handler, task).catch(reason => {}).then(() => finishWorkerTask(task)), pdfManager.loadXfaImages()]);
}
const [numPages, fingerprints] = await Promise.all([pdfManager.ensureDoc("numPages"), pdfManager.ensureDoc("fingerprints")]);
const htmlForXfa = isPureXfa ? await pdfManager.ensureDoc("htmlForXfa") : null;
return {
numPages,
fingerprint,
isPureXfa
fingerprints,
htmlForXfa
};

@@ -357,3 +359,6 @@ }

isEvalSupported: data.isEvalSupported,
fontExtraProperties: data.fontExtraProperties
fontExtraProperties: data.fontExtraProperties,
useSystemFonts: data.useSystemFonts,
cMapUrl: data.cMapUrl,
standardFontDataUrl: data.standardFontDataUrl
};

@@ -431,9 +436,2 @@ getPdfManager(data, evaluatorOptions, data.enableXfa).then(function (newPdfManager) {

});
handler.on("GetPageXfa", function wphSetupGetXfa({
pageIndex
}) {
return pdfManager.getPage(pageIndex).then(function (page) {
return pdfManager.ensure(page, "xfaData");
});
});
handler.on("GetOutline", function wphSetupGetOutline(data) {

@@ -481,2 +479,3 @@ return pdfManager.ensureCatalog("documentOutline");

handler.on("SaveDocument", function ({
isPureXfa,
numPages,

@@ -489,10 +488,13 @@ annotationStorage,

for (let pageIndex = 0; pageIndex < numPages; pageIndex++) {
promises.push(pdfManager.getPage(pageIndex).then(function (page) {
const task = new WorkerTask(`Save: page ${pageIndex}`);
startWorkerTask(task);
return page.save(handler, task, annotationStorage).finally(function () {
finishWorkerTask(task);
});
}));
if (isPureXfa) {
promises.push(pdfManager.serializeXfaData(annotationStorage));
} else {
for (let pageIndex = 0; pageIndex < numPages; pageIndex++) {
promises.push(pdfManager.getPage(pageIndex).then(function (page) {
const task = new WorkerTask(`Save: page ${pageIndex}`);
return page.save(handler, task, annotationStorage).finally(function () {
finishWorkerTask(task);
});
}));
}
}

@@ -502,9 +504,18 @@

let newRefs = [];
let xfaData = null;
for (const ref of refs) {
newRefs = ref.filter(x => x !== null).reduce((a, b) => a.concat(b), newRefs);
}
if (isPureXfa) {
xfaData = refs[0];
if (newRefs.length === 0) {
return stream.bytes;
if (!xfaData) {
return stream.bytes;
}
} else {
for (const ref of refs) {
newRefs = ref.filter(x => x !== null).reduce((a, b) => a.concat(b), newRefs);
}
if (newRefs.length === 0) {
return stream.bytes;
}
}

@@ -557,3 +568,4 @@

xref,
datasetsRef: xfaDatasets
datasetsRef: xfaDatasets,
xfaData
});

@@ -560,0 +572,0 @@ });

@@ -157,9 +157,3 @@ /**

function updateXFA(datasetsRef, newRefs, xref) {
if (datasetsRef === null || xref === null) {
return;
}
const datasets = xref.fetchIfRef(datasetsRef);
const str = datasets.getString();
function writeXFADataForAcroform(str, newRefs) {
const xml = new _xml_parser.SimpleXMLParser({

@@ -196,3 +190,15 @@ hasAttributes: true

xml.documentElement.dump(buffer);
let updatedXml = buffer.join("");
return buffer.join("");
}
function updateXFA(xfaData, datasetsRef, newRefs, xref) {
if (datasetsRef === null || xref === null) {
return;
}
if (xfaData === null) {
const datasets = xref.fetchIfRef(datasetsRef);
xfaData = writeXFADataForAcroform(datasets.getString(), newRefs);
}
const encrypt = xref.encrypt;

@@ -202,6 +208,6 @@

const transform = encrypt.createCipherTransform(datasetsRef.num, datasetsRef.gen);
updatedXml = transform.encryptString(updatedXml);
xfaData = transform.encryptString(xfaData);
}
const data = `${datasetsRef.num} ${datasetsRef.gen} obj\n` + `<< /Type /EmbeddedFile /Length ${updatedXml.length}>>\nstream\n` + updatedXml + "\nendstream\nendobj\n";
const data = `${datasetsRef.num} ${datasetsRef.gen} obj\n` + `<< /Type /EmbeddedFile /Length ${xfaData.length}>>\nstream\n` + xfaData + "\nendstream\nendobj\n";
newRefs.push({

@@ -218,5 +224,6 @@ ref: datasetsRef,

xref = null,
datasetsRef = null
datasetsRef = null,
xfaData = null
}) {
updateXFA(datasetsRef, newRefs, xref);
updateXFA(xfaData, datasetsRef, newRefs, xref);
const newXref = new _primitives.Dict(null);

@@ -223,0 +230,0 @@ const refForXrefTable = xrefInfo.newRef;

@@ -51,9 +51,8 @@ /**

if (root.datasets && root.datasets.data) {
this.emptyMerge = false;
this.data = root.datasets.data;
} else {
this.emptyMerge = true;
this.data = new _xfa_object.XmlObject(_namespaces.NamespaceIds.datasets.id, "data");
}
this.emptyMerge = this.data[_xfa_object.$getChildren]().length === 0;
this.root.form = this.form = root.template[_xfa_object.$clone]();

@@ -81,2 +80,4 @@ }

_bindValue(formNode, data, picture) {
formNode[_xfa_object.$data] = data;
if (formNode[_xfa_object.$hasSettableValue]()) {

@@ -87,4 +88,2 @@ if (data[_xfa_object.$isDataValue]()) {

formNode[_xfa_object.$setValue](createText(value));
formNode[_xfa_object.$data] = data;
} else if (formNode instanceof _template.Field && formNode.ui && formNode.ui.choiceList && formNode.ui.choiceList.open === "multiSelect") {

@@ -94,4 +93,2 @@ const value = data[_xfa_object.$getChildren]().map(child => child[_xfa_object.$content].trim()).join("\n");

formNode[_xfa_object.$setValue](createText(value));
formNode[_xfa_object.$data] = data;
} else if (this._isConsumeData()) {

@@ -102,4 +99,2 @@ (0, _util.warn)(`XFA - Nodes haven't the same type.`);

this._bindElement(formNode, data);
formNode[_xfa_object.$data] = data;
} else {

@@ -143,14 +138,7 @@ (0, _util.warn)(`XFA - Nodes haven't the same type.`);

generator = this.data[_xfa_object.$getRealChildrenByNameIt](name, false, false);
generator = this.data[_xfa_object.$getRealChildrenByNameIt](name, true, false);
match = generator.next().value;
while (true) {
match = generator.next().value;
if (!match) {
break;
}
if (match[_xfa_object.$global]) {
return match;
}
if (match) {
return match;
}

@@ -186,5 +174,5 @@

const [node] = (0, _som.searchNode)(this.root, dataNode, ref, false, false);
const nodes = (0, _som.searchNode)(this.root, dataNode, ref, false, false);
if (!node) {
if (!nodes) {
(0, _util.warn)(`XFA - Invalid reference: ${ref}.`);

@@ -194,2 +182,4 @@ continue;

const [node] = nodes;
if (!node[_xfa_object.$isDescendent](this.data)) {

@@ -200,5 +190,5 @@ (0, _util.warn)(`XFA - Invalid node: must be a data node.`);

const [targetNode] = (0, _som.searchNode)(this.root, formNode, target, false, false);
const targetNodes = (0, _som.searchNode)(this.root, formNode, target, false, false);
if (!targetNode) {
if (!targetNodes) {
(0, _util.warn)(`XFA - Invalid target: ${target}.`);

@@ -208,2 +198,4 @@ continue;

const [targetNode] = targetNodes;
if (!targetNode[_xfa_object.$isDescendent](formNode)) {

@@ -298,5 +290,5 @@ (0, _util.warn)(`XFA - Invalid target: must be a property or subproperty.`);

const [labelNode] = (0, _som.searchNode)(this.root, node, labelRef, true, false);
const labelNodes = (0, _som.searchNode)(this.root, node, labelRef, true, false);
if (!labelNode) {
if (!labelNodes) {
(0, _util.warn)(`XFA - Invalid label: ${labelRef}.`);

@@ -306,2 +298,4 @@ continue;

const [labelNode] = labelNodes;
if (!labelNode[_xfa_object.$isDescendent](this.datasets)) {

@@ -312,5 +306,5 @@ (0, _util.warn)(`XFA - Invalid label: must be a datasets child.`);

const [valueNode] = (0, _som.searchNode)(this.root, node, valueRef, true, false);
const valueNodes = (0, _som.searchNode)(this.root, node, valueRef, true, false);
if (!valueNode) {
if (!valueNodes) {
(0, _util.warn)(`XFA - Invalid value: ${valueRef}.`);

@@ -320,2 +314,4 @@ continue;

const [valueNode] = valueNodes;
if (!valueNode[_xfa_object.$isDescendent](this.datasets)) {

@@ -438,4 +434,22 @@ (0, _util.warn)(`XFA - Invalid value: must be a datasets child.`);

this._mergeMode = child.mergeMode === "consumeData";
const dataChildren = dataNode[_xfa_object.$getChildren]();
if (dataChildren.length > 0) {
this._bindOccurrences(child, [dataChildren[0]], null);
} else if (this.emptyMerge) {
const dataChild = child[_xfa_object.$data] = new _xfa_object.XmlObject(dataNode[_xfa_object.$namespaceId], child.name || "root");
dataNode[_xfa_object.$appendChild](dataChild);
this._bindElement(child, dataChild);
}
continue;
}
if (!child[_xfa_object.$isBindable]()) {
continue;
}
let global = false;

@@ -486,2 +500,6 @@ let picture = null;

if (!match) {
continue;
}
if (this._isConsumeData()) {

@@ -491,3 +509,5 @@ match[_xfa_object.$consumed] = true;

match = [match];
this._bindElement(child, match);
continue;
} else {

@@ -533,10 +553,26 @@ if (this._isConsumeData()) {

} else {
match = dataNode[_xfa_object.$getRealChildrenByNameIt](child.name, false, false).next().value;
match = dataNode[_xfa_object.$getRealChildrenByNameIt](child.name, false, this.emptyMerge).next().value;
if (!match) {
match = new _xfa_object.XmlObject(dataNode[_xfa_object.$namespaceId], child.name);
match = child[_xfa_object.$data] = new _xfa_object.XmlObject(dataNode[_xfa_object.$namespaceId], child.name);
if (this.emptyMerge) {
match[_xfa_object.$consumed] = true;
}
dataNode[_xfa_object.$appendChild](match);
this._setProperties(child, match);
this._bindItems(child, match);
this._bindElement(child, match);
continue;
}
if (this.emptyMerge) {
match[_xfa_object.$consumed] = true;
}
match = [match];

@@ -543,0 +579,0 @@ }

@@ -57,2 +57,4 @@ /**

if (this.element.template instanceof _template.Template) {
this[_xfa_object.$ids].set(_xfa_object.$root, this.element);
this.element.template[_xfa_object.$resolvePrototypes](this[_xfa_object.$ids]);

@@ -80,2 +82,3 @@

this._namespaceStack = [];
this._nsAgnosticLevel = 0;
this._namespacePrefixes = new Map();

@@ -139,6 +142,11 @@ this._namespaces = new Map();

if (hasNamespaceDef || prefixes) {
if (node[_xfa_object.$isNsAgnostic]()) {
this._nsAgnosticLevel++;
}
if (hasNamespaceDef || prefixes || node[_xfa_object.$isNsAgnostic]()) {
node[_xfa_object.$cleanup] = {
hasNamespace: hasNamespaceDef,
prefixes
prefixes,
nsAgnostic: node[_xfa_object.$isNsAgnostic]()
};

@@ -150,2 +158,6 @@ }

isNsAgnostic() {
return this._nsAgnosticLevel > 0;
}
_searchNamespace(nsName) {

@@ -218,3 +230,4 @@ let ns = this._namespaces.get(nsName);

hasNamespace,
prefixes
prefixes,
nsAgnostic
} = data;

@@ -233,2 +246,6 @@

}
if (nsAgnostic) {
this._nsAgnosticLevel--;
}
}

@@ -235,0 +252,0 @@

@@ -173,3 +173,3 @@ /**

[_xfa_object.$finalize]() {
this[_xfa_object.$content] = new Map(this[_xfa_object.$content].trim().split(/\s+/).filter(x => !!x && x.include(":")).map(x => x.split(":", 2)));
this[_xfa_object.$content] = new Map(this[_xfa_object.$content].trim().split(/\s+/).filter(x => x.includes(":")).map(x => x.split(":", 2)));
}

@@ -176,0 +176,0 @@

@@ -40,2 +40,6 @@ /**

[_xfa_object.$isNsAgnostic]() {
return true;
}
}

@@ -55,4 +59,2 @@

this[name] = child;
} else {
child[_xfa_object.$global] = true;
}

@@ -59,0 +61,0 @@

@@ -33,2 +33,10 @@ /**

var _data = require("./data.js");
var _fonts = require("./fonts.js");
var _utils = require("./utils.js");
var _util = require("../../shared/util.js");
var _parser = require("./parser.js");

@@ -40,17 +48,85 @@

this.root = new _parser.XFAParser().parse(XFAFactory._createDocument(data));
this.form = new _bind.Binder(this.root).bind();
const binder = new _bind.Binder(this.root);
this.form = binder.bind();
this.dataHandler = new _data.DataHandler(this.root, binder.getData());
this.form[_xfa_object.$globalData].template = this.form;
} catch (e) {
(0, _util.warn)(`XFA - an error occurred during parsing and binding: ${e}`);
}
}
isValid() {
return this.root && this.form;
}
_createPages() {
try {
this.pages = this.form[_xfa_object.$toHTML]();
this.dims = this.pages.children.map(c => {
const {
width,
height
} = c.attributes.style;
return [0, 0, parseInt(width), parseInt(height)];
});
} catch (e) {
console.log(e);
(0, _util.warn)(`XFA - an error occurred during layout: ${e}`);
}
}
getPage(pageIndex) {
return this.pages.children[pageIndex];
getBoundingBox(pageIndex) {
return this.dims[pageIndex];
}
get numberPages() {
return this.pages.children.length;
if (!this.pages) {
this._createPages();
}
return this.dims.length;
}
setImages(images) {
this.form[_xfa_object.$globalData].images = images;
}
setFonts(fonts) {
this.form[_xfa_object.$globalData].fontFinder = new _fonts.FontFinder(fonts);
const missingFonts = [];
for (let typeface of this.form[_xfa_object.$globalData].usedTypefaces) {
typeface = (0, _utils.stripQuotes)(typeface);
const font = this.form[_xfa_object.$globalData].fontFinder.find(typeface);
if (!font) {
missingFonts.push(typeface);
}
}
if (missingFonts.length > 0) {
return missingFonts;
}
return null;
}
appendFonts(fonts, reallyMissingFonts) {
this.form[_xfa_object.$globalData].fontFinder.add(fonts, reallyMissingFonts);
}
getPages() {
if (!this.pages) {
this._createPages();
}
const pages = this.pages;
this.pages = null;
return pages;
}
serializeData(storage) {
return this.dataHandler.serialize(storage);
}
static _createDocument(data) {

@@ -57,0 +133,0 @@ if (!data["/xdp:xdp"]) {

@@ -27,10 +27,14 @@ /**

});
exports.addExtraDivForBorder = addExtraDivForBorder;
exports.computeBbox = computeBbox;
exports.createWrapper = createWrapper;
exports.fixDimensions = fixDimensions;
exports.fixTextIndent = fixTextIndent;
exports.getFonts = getFonts;
exports.isPrintOnly = isPrintOnly;
exports.layoutClass = layoutClass;
exports.layoutText = layoutText;
exports.layoutNode = layoutNode;
exports.measureToString = measureToString;
exports.setAccess = setAccess;
exports.setFontFamily = setFontFamily;
exports.setMinMaxDimensions = setMinMaxDimensions;
exports.setPara = setPara;
exports.toStyle = toStyle;

@@ -42,7 +46,8 @@

var _fonts = require("./fonts.js");
var _text = require("./text.js");
var _util = require("../../shared/util.js");
const wordNonWordRegex = new RegExp("([\\p{N}\\p{L}\\p{M}]+)|([^\\p{N}\\p{L}\\p{M}]+)", "gu");
const wordFirstRegex = new RegExp("^[\\p{N}\\p{L}\\p{M}]", "u");
function measureToString(m) {

@@ -58,3 +63,3 @@ if (typeof m === "string") {

anchorType(node, style) {
const parent = node[_xfa_object.$getParent]();
const parent = node[_xfa_object.$getSubformParent]();

@@ -105,3 +110,3 @@ if (!parent || parent.layout && parent.layout !== "position") {

dimensions(node, style) {
const parent = node[_xfa_object.$getParent]();
const parent = node[_xfa_object.$getSubformParent]();

@@ -133,10 +138,2 @@ let width = node.w;

style.width = "auto";
if (node.maxW > 0) {
style.maxWidth = measureToString(node.maxW);
}
if (parent.layout === "position") {
style.minWidth = measureToString(node.minW);
}
}

@@ -148,10 +145,2 @@

style.height = "auto";
if (node.maxH > 0) {
style.maxHeight = measureToString(node.maxH);
}
if (parent.layout === "position") {
style.minHeight = measureToString(node.minH);
}
}

@@ -161,3 +150,3 @@ },

position(node, style) {
const parent = node[_xfa_object.$getParent]();
const parent = node[_xfa_object.$getSubformParent]();

@@ -213,6 +202,13 @@ if (parent && parent.layout && parent.layout !== "position") {

switch (node.hAlign) {
case "right":
case "left":
style.alignSelf = "start";
break;
case "center":
style.justifyContent = node.hAlign;
style.alignSelf = "center";
break;
case "right":
style.alignSelf = "end";
break;
}

@@ -222,117 +218,119 @@ }

borderMarginPadding(node, style) {
const borderWidths = [0, 0, 0, 0];
const borderInsets = [0, 0, 0, 0];
const marginNode = node.margin ? [node.margin.topInset, node.margin.rightInset, node.margin.bottomInset, node.margin.leftInset] : [0, 0, 0, 0];
let borderMargin;
margin(node, style) {
if (node.margin) {
style.margin = node.margin[_xfa_object.$toStyle]().margin;
}
}
if (node.border) {
Object.assign(style, node.border[_xfa_object.$toStyle](borderWidths, borderInsets));
borderMargin = style.margin;
delete style.margin;
};
function setMinMaxDimensions(node, style) {
const parent = node[_xfa_object.$getSubformParent]();
if (parent.layout === "position") {
if (node.minW > 0) {
style.minWidth = measureToString(node.minW);
}
if (borderWidths.every(x => x === 0)) {
if (marginNode.every(x => x === 0)) {
return;
}
if (node.maxW > 0) {
style.maxWidth = measureToString(node.maxW);
}
Object.assign(style, node.margin[_xfa_object.$toStyle]());
style.padding = style.margin;
delete style.margin;
delete style.outline;
delete style.outlineOffset;
return;
if (node.minH > 0) {
style.minHeight = measureToString(node.minH);
}
if (node.maxH > 0) {
style.maxHeight = measureToString(node.maxH);
}
}
}
function layoutText(text, xfaFont, margin, lineHeight, fontFinder, width) {
const measure = new _text.TextMeasure(xfaFont, margin, lineHeight, fontFinder);
if (typeof text === "string") {
measure.addString(text);
} else {
text[_xfa_object.$pushGlyphs](measure);
}
return measure.compute(width);
}
function layoutNode(node, availableSpace) {
let height = null;
let width = null;
let isBroken = false;
if ((!node.w || !node.h) && node.value) {
let marginH = 0;
let marginV = 0;
if (node.margin) {
Object.assign(style, node.margin[_xfa_object.$toStyle]());
style.padding = style.margin;
delete style.margin;
marginH = node.margin.leftInset + node.margin.rightInset;
marginV = node.margin.topInset + node.margin.bottomInset;
}
if (!style.borderWidth) {
return;
let lineHeight = null;
let margin = null;
if (node.para) {
margin = Object.create(null);
lineHeight = node.para.lineHeight === "" ? null : node.para.lineHeight;
margin.top = node.para.spaceAbove === "" ? 0 : node.para.spaceAbove;
margin.bottom = node.para.spaceBelow === "" ? 0 : node.para.spaceBelow;
margin.left = node.para.marginLeft === "" ? 0 : node.para.marginLeft;
margin.right = node.para.marginRight === "" ? 0 : node.para.marginRight;
}
style.borderData = {
borderWidth: style.borderWidth,
borderColor: style.borderColor,
borderStyle: style.borderStyle,
margin: borderMargin
};
delete style.borderWidth;
delete style.borderColor;
delete style.borderStyle;
}
let font = node.font;
};
if (!font) {
const root = node[_xfa_object.$getTemplateRoot]();
function layoutText(text, fontSize, space) {
let width = 0;
let height = 0;
let totalWidth = 0;
const lineHeight = fontSize * 1.5;
const averageCharSize = fontSize * 0.4;
const maxCharOnLine = Math.floor(space.width / averageCharSize);
const chunks = text.match(wordNonWordRegex);
let treatedChars = 0;
let i = 0;
let chunk = chunks[0];
let parent = node[_xfa_object.$getParent]();
while (chunk) {
const w = chunk.length * averageCharSize;
while (parent !== root) {
if (parent.font) {
font = parent.font;
break;
}
if (width + w <= space.width) {
width += w;
treatedChars += chunk.length;
chunk = chunks[i++];
continue;
parent = parent[_xfa_object.$getParent]();
}
}
if (!wordFirstRegex.test(chunk) || chunk.length > maxCharOnLine) {
const numOfCharOnLine = Math.floor((space.width - width) / averageCharSize);
chunk = chunk.slice(numOfCharOnLine);
treatedChars += numOfCharOnLine;
const maxWidth = !node.w ? availableSpace.width : node.w;
const fontFinder = node[_xfa_object.$globalData].fontFinder;
if (height + lineHeight > space.height) {
return {
width: 0,
height: 0,
splitPos: treatedChars
};
if (node.value.exData && node.value.exData[_xfa_object.$content] && node.value.exData.contentType === "text/html") {
const res = layoutText(node.value.exData[_xfa_object.$content], font, margin, lineHeight, fontFinder, maxWidth);
width = res.width;
height = res.height;
isBroken = res.isBroken;
} else {
const text = node.value[_xfa_object.$text]();
if (text) {
const res = layoutText(text, font, margin, lineHeight, fontFinder, maxWidth);
width = res.width;
height = res.height;
isBroken = res.isBroken;
}
}
totalWidth = Math.max(width, totalWidth);
width = 0;
height += lineHeight;
continue;
if (width !== null && !node.w) {
width += marginH;
}
if (height + lineHeight > space.height) {
return {
width: 0,
height: 0,
splitPos: treatedChars
};
if (height !== null && !node.h) {
height += marginV;
}
totalWidth = Math.max(width, totalWidth);
width = w;
height += lineHeight;
chunk = chunks[i++];
}
if (totalWidth === 0) {
totalWidth = width;
}
if (totalWidth !== 0) {
height += lineHeight;
}
return {
width: totalWidth,
height,
splitPos: -1
w: width,
h: height,
isBroken
};

@@ -355,3 +353,3 @@ }

if (node.maxW === 0) {
const parent = node[_xfa_object.$getParent]();
const parent = node[_xfa_object.$getSubformParent]();

@@ -374,3 +372,3 @@ if (parent.layout === "position" && parent.w !== "") {

if (node.maxH === 0) {
const parent = node[_xfa_object.$getParent]();
const parent = node[_xfa_object.$getSubformParent]();

@@ -396,3 +394,3 @@ if (parent.layout === "position" && parent.h !== "") {

function fixDimensions(node) {
const parent = node[_xfa_object.$getParent]();
const parent = node[_xfa_object.$getSubformParent]();

@@ -415,28 +413,9 @@ if (parent.layout && parent.layout.includes("row")) {

if (parent.w && node.w) {
node.w = Math.min(parent.w, node.w);
}
if (parent.h && node.h) {
node.h = Math.min(parent.h, node.h);
}
if (parent.layout && parent.layout !== "position") {
node.x = node.y = 0;
if (parent.layout === "tb") {
if (parent.w !== "" && (node.w === "" || node.w === 0 || node.w > parent.w)) {
node.w = parent.w;
}
}
}
if (node.layout === "position") {
node.minW = node.minH = 0;
node.maxW = node.maxH = Infinity;
} else {
if (node.layout === "table") {
if (node.w === "" && Array.isArray(node.columnWidths)) {
node.w = node.columnWidths.reduce((a, x) => a + x, 0);
}
if (node.layout === "table") {
if (node.w === "" && Array.isArray(node.columnWidths)) {
node.w = node.columnWidths.reduce((a, x) => a + x, 0);
}

@@ -484,2 +463,7 @@ }

if (converters.hasOwnProperty(name)) {
converters[name](node, style);
continue;
}
if (value instanceof _xfa_object.XFAObject) {

@@ -493,9 +477,3 @@ const newStyle = value[_xfa_object.$toStyle]();

}
continue;
}
if (converters.hasOwnProperty(name)) {
converters[name](node, style);
}
}

@@ -506,86 +484,104 @@

function addExtraDivForBorder(html) {
const style = html.attributes.style;
const data = style.borderData;
const children = [];
const attributes = {
class: "xfaWrapper",
style: Object.create(null)
function createWrapper(node, html) {
const {
attributes
} = html;
const {
style
} = attributes;
const wrapper = {
name: "div",
attributes: {
class: ["xfaWrapper"],
style: Object.create(null)
},
children: []
};
attributes.class.push("xfaWrapped");
for (const key of ["top", "left"]) {
if (style[key] !== undefined) {
attributes.style[key] = style[key];
}
}
if (node.border) {
const {
widths,
insets
} = node.border[_xfa_object.$extra];
let width, height;
let top = insets[0];
let left = insets[3];
const insetsH = insets[0] + insets[2];
const insetsW = insets[1] + insets[3];
delete style.top;
delete style.left;
switch (node.border.hand) {
case "even":
top -= widths[0] / 2;
left -= widths[3] / 2;
width = `calc(100% + ${(widths[1] + widths[3]) / 2 - insetsW}px)`;
height = `calc(100% + ${(widths[0] + widths[2]) / 2 - insetsH}px)`;
break;
if (style.position === "absolute") {
attributes.style.position = "absolute";
} else {
attributes.style.position = "relative";
}
case "left":
top -= widths[0];
left -= widths[3];
width = `calc(100% + ${widths[1] + widths[3] - insetsW}px)`;
height = `calc(100% + ${widths[0] + widths[2] - insetsH}px)`;
break;
delete style.position;
if (style.justifyContent) {
attributes.style.justifyContent = style.justifyContent;
delete style.justifyContent;
}
if (data) {
delete style.borderData;
let insets;
if (data.margin) {
insets = data.margin.split(" ");
delete data.margin;
} else {
insets = ["0px", "0px", "0px", "0px"];
case "right":
width = insetsW ? `calc(100% - ${insetsW}px)` : "100%";
height = insetsH ? `calc(100% - ${insetsH}px)` : "100%";
break;
}
let width = "100%";
let height = width;
const classNames = ["xfaBorder"];
if (insets[1] !== "0px" || insets[3] !== "0px") {
width = `calc(100% - ${parseInt(insets[1]) + parseInt(insets[3])}px`;
if (isPrintOnly(node.border)) {
classNames.push("xfaPrintOnly");
}
if (insets[0] !== "0px" || insets[2] !== "0px") {
height = `calc(100% - ${parseInt(insets[0]) + parseInt(insets[2])}px`;
}
const borderStyle = {
top: insets[0],
left: insets[3],
width,
height
const border = {
name: "div",
attributes: {
class: classNames,
style: {
top: `${top}px`,
left: `${left}px`,
width,
height
}
},
children: []
};
for (const [k, v] of Object.entries(data)) {
borderStyle[k] = v;
for (const key of ["border", "borderWidth", "borderColor", "borderRadius", "borderStyle"]) {
if (style[key] !== undefined) {
border.attributes.style[key] = style[key];
delete style[key];
}
}
if (style.transform) {
borderStyle.transform = style.transform;
wrapper.children.push(border, html);
} else {
wrapper.children.push(html);
}
for (const key of ["background", "backgroundClip", "top", "left", "width", "height", "minWidth", "minHeight", "maxWidth", "maxHeight", "transform", "transformOrigin", "visibility"]) {
if (style[key] !== undefined) {
wrapper.attributes.style[key] = style[key];
delete style[key];
}
}
const borderDiv = {
name: "div",
attributes: {
class: "xfaBorderDiv",
style: borderStyle
}
};
children.push(borderDiv);
if (style.position === "absolute") {
wrapper.attributes.style.position = "absolute";
} else {
wrapper.attributes.style.position = "relative";
}
children.push(html);
return {
name: "div",
attributes,
children
};
delete style.position;
if (style.alignSelf) {
wrapper.attributes.style.alignSelf = style.alignSelf;
delete style.alignSelf;
}
return wrapper;
}

@@ -600,31 +596,96 @@

const align = styles.textAlign || "left";
const align = styles.textAlign === "right" ? "right" : "left";
const name = "padding" + (align === "left" ? "Left" : "Right");
const padding = (0, _utils.getMeasurement)(styles[name], "0px");
styles[name] = `${padding - indent}px`;
}
if (align === "left" || align === "right") {
const name = "margin" + (align === "left" ? "Left" : "Right");
const margin = (0, _utils.getMeasurement)(styles[name], "0px");
styles[name] = `${margin - indent}pt`;
function setAccess(node, classNames) {
switch (node.access) {
case "nonInteractive":
classNames.push("xfaNonInteractive");
break;
case "readOnly":
classNames.push("xfaReadOnly");
break;
case "protected":
classNames.push("xfaDisabled");
break;
}
}
function getFonts(family) {
if (family.startsWith("'")) {
family = `"${family.slice(1, family.length - 1)}"`;
} else if (family.includes(" ") && !family.startsWith('"')) {
family = `"${family}"`;
function isPrintOnly(node) {
return node.relevant.length > 0 && !node.relevant[0].excluded && node.relevant[0].viewname === "print";
}
function setPara(node, nodeStyle, value) {
if (value.attributes.class && value.attributes.class.includes("xfaRich")) {
if (nodeStyle) {
if (node.h === "") {
nodeStyle.height = "auto";
}
if (node.w === "") {
nodeStyle.width = "auto";
}
}
if (node.para) {
const valueStyle = value.attributes.style;
valueStyle.display = "flex";
valueStyle.flexDirection = "column";
switch (node.para.vAlign) {
case "top":
valueStyle.justifyContent = "start";
break;
case "bottom":
valueStyle.justifyContent = "end";
break;
case "middle":
valueStyle.justifyContent = "center";
break;
}
const paraStyle = node.para[_xfa_object.$toStyle]();
for (const [key, val] of Object.entries(paraStyle)) {
if (!(key in valueStyle)) {
valueStyle[key] = val;
}
}
}
}
}
const fonts = [family];
function setFontFamily(xfaFont, fontFinder, style) {
const name = (0, _utils.stripQuotes)(xfaFont.typeface);
const typeface = fontFinder.find(name);
style.fontFamily = `"${name}"`;
switch (family) {
case `"Myriad Pro"`:
fonts.push(`"Roboto Condensed"`, `"Ubuntu Condensed"`, `"Microsoft Sans Serif"`, `"Apple Symbols"`, "Helvetica", `"sans serif"`);
break;
if (typeface) {
const {
fontFamily
} = typeface.regular.cssFontInfo;
case "Arial":
fonts.push("Helvetica", `"Liberation Sans"`, "Arimo", `"sans serif"`);
break;
if (fontFamily !== name) {
style.fontFamily = `"${fontFamily}"`;
}
if (style.lineHeight) {
return;
}
const pdfFont = (0, _fonts.selectFont)(xfaFont, typeface);
if (pdfFont && pdfFont.lineHeight > 0) {
style.lineHeight = Math.max(1.2, pdfFont.lineHeight);
} else {
style.lineHeight = 1.2;
}
}
return fonts.join(",");
}

@@ -28,2 +28,3 @@ /**

exports.addHTML = addHTML;
exports.checkDimensions = checkDimensions;
exports.flushHTML = flushHTML;

@@ -36,3 +37,17 @@ exports.getAvailableSpace = getAvailableSpace;

function createLine(node, children) {
return {
name: "div",
attributes: {
class: [node.layout === "lr-tb" ? "xfaLr" : "xfaRl"]
},
children
};
}
function flushHTML(node) {
if (!node[_xfa_object.$extra]) {
return null;
}
const attributes = node[_xfa_object.$extra].attributes;

@@ -49,3 +64,7 @@ const html = {

if (htmlFromFailing) {
html.children.push(htmlFromFailing);
if (node.layout.endsWith("-tb")) {
html.children.push(createLine(node, [htmlFromFailing]));
} else {
html.children.push(htmlFromFailing);
}
}

@@ -58,4 +77,2 @@ }

node[_xfa_object.$extra].children = [];
delete node[_xfa_object.$extra].line;
return html;

@@ -67,2 +84,3 @@ }

const availableSpace = extra.availableSpace;
const [x, y, w, h] = bbox;

@@ -72,3 +90,2 @@ switch (node.layout) {

{
const [x, y, w, h] = bbox;
extra.width = Math.max(extra.width, x + w);

@@ -83,21 +100,14 @@ extra.height = Math.max(extra.height, y + h);

if (!extra.line || extra.attempt === 1) {
extra.line = {
name: "div",
attributes: {
class: node.layout === "lr-tb" ? "xfaLr" : "xfaRl"
},
children: []
};
extra.line = createLine(node, []);
extra.children.push(extra.line);
extra.numberInLine = 0;
}
extra.numberInLine += 1;
extra.line.children.push(html);
if (extra.attempt === 0) {
const [,, w, h] = bbox;
extra.currentWidth += w;
extra.height = Math.max(extra.height, extra.prevHeight + h);
} else {
const [,, w, h] = bbox;
extra.width = Math.max(extra.width, extra.currentWidth);
extra.currentWidth = w;

@@ -109,2 +119,3 @@ extra.prevHeight = extra.height;

extra.width = Math.max(extra.width, extra.currentWidth);
break;

@@ -116,3 +127,2 @@

extra.children.push(html);
const [,, w, h] = bbox;
extra.width += w;

@@ -123,7 +133,3 @@ extra.height = Math.max(extra.height, h);

for (const child of extra.children) {
if (child.attributes.class === "xfaWrapper") {
child.children[child.children.length - 1].attributes.style.height = height;
} else {
child.attributes.style.height = height;
}
child.attributes.style.height = height;
}

@@ -136,3 +142,2 @@

{
const [,, w, h] = bbox;
extra.width = Math.min(availableSpace.width, Math.max(extra.width, w));

@@ -146,3 +151,2 @@ extra.height += h;

{
const [,,, h] = bbox;
extra.width = availableSpace.width;

@@ -158,2 +162,4 @@ extra.height += h;

const availableSpace = node[_xfa_object.$extra].availableSpace;
const marginV = node.margin ? node.margin.topInset + node.margin.bottomInset : 0;
const marginH = node.margin ? node.margin.leftInset + node.margin.rightInset : 0;

@@ -163,22 +169,14 @@ switch (node.layout) {

case "rl-tb":
switch (node[_xfa_object.$extra].attempt) {
case 0:
return {
width: availableSpace.width - node[_xfa_object.$extra].currentWidth,
height: availableSpace.height - node[_xfa_object.$extra].prevHeight
};
if (node[_xfa_object.$extra].attempt === 0) {
return {
width: availableSpace.width - marginH - node[_xfa_object.$extra].currentWidth,
height: availableSpace.height - marginV - node[_xfa_object.$extra].prevHeight
};
}
case 1:
return {
width: availableSpace.width,
height: availableSpace.height - node[_xfa_object.$extra].height
};
return {
width: availableSpace.width - marginH,
height: availableSpace.height - marginV - node[_xfa_object.$extra].height
};
default:
return {
width: Infinity,
height: availableSpace.height - node[_xfa_object.$extra].prevHeight
};
}
case "rl-row":

@@ -190,3 +188,3 @@ case "row":

width,
height: availableSpace.height
height: availableSpace.height - marginH
};

@@ -197,4 +195,4 @@

return {
width: availableSpace.width,
height: availableSpace.height - node[_xfa_object.$extra].height
width: availableSpace.width - marginH,
height: availableSpace.height - marginV - node[_xfa_object.$extra].height
};

@@ -206,2 +204,182 @@

}
}
function getTransformedBBox(node) {
let w = node.w === "" ? NaN : node.w;
let h = node.h === "" ? NaN : node.h;
let [centerX, centerY] = [0, 0];
switch (node.anchorType || "") {
case "bottomCenter":
[centerX, centerY] = [w / 2, h];
break;
case "bottomLeft":
[centerX, centerY] = [0, h];
break;
case "bottomRight":
[centerX, centerY] = [w, h];
break;
case "middleCenter":
[centerX, centerY] = [w / 2, h / 2];
break;
case "middleLeft":
[centerX, centerY] = [0, h / 2];
break;
case "middleRight":
[centerX, centerY] = [w, h / 2];
break;
case "topCenter":
[centerX, centerY] = [w / 2, 0];
break;
case "topRight":
[centerX, centerY] = [w, 0];
break;
}
let x, y;
switch (node.rotate || 0) {
case 0:
[x, y] = [-centerX, -centerY];
break;
case 90:
[x, y] = [-centerY, centerX];
[w, h] = [h, -w];
break;
case 180:
[x, y] = [centerX, centerY];
[w, h] = [-w, -h];
break;
case 270:
[x, y] = [centerY, -centerX];
[w, h] = [-h, w];
break;
}
return [node.x + x + Math.min(0, w), node.y + y + Math.min(0, h), Math.abs(w), Math.abs(h)];
}
function checkDimensions(node, space) {
if (node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].firstUnsplittable === null) {
return true;
}
if (node.w === 0 || node.h === 0) {
return true;
}
const ERROR = 2;
const parent = node[_xfa_object.$getSubformParent]();
const attempt = parent[_xfa_object.$extra] && parent[_xfa_object.$extra].attempt || 0;
const [, y, w, h] = getTransformedBBox(node);
switch (parent.layout) {
case "lr-tb":
case "rl-tb":
if (attempt === 0) {
if (!node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
if (node.h !== "" && Math.round(h - space.height) > ERROR) {
return false;
}
if (node.w !== "") {
if (Math.round(w - space.width) <= ERROR) {
return true;
}
if (parent[_xfa_object.$extra].numberInLine === 0) {
return space.height > 0;
}
return false;
}
return space.width > 0;
}
if (node.w !== "") {
return Math.round(w - space.width) <= ERROR;
}
return space.width > 0;
}
if (node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
return true;
}
if (node.h !== "" && Math.round(h - space.height) > ERROR) {
return false;
}
if (node.w === "" || Math.round(w - space.width) <= ERROR) {
return space.height > 0;
}
if (parent[_xfa_object.$isThereMoreWidth]()) {
return false;
}
return space.height > 0;
case "table":
case "tb":
if (node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
return true;
}
if (node.h !== "" && !node[_xfa_object.$isSplittable]()) {
return Math.round(h - space.height) <= ERROR;
}
if (node.w === "" || Math.round(w - space.width) <= ERROR) {
return space.height > 0;
}
if (parent[_xfa_object.$isThereMoreWidth]()) {
return false;
}
return space.height > 0;
case "position":
if (node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
return true;
}
if (node.h === "" || Math.round(h + y - space.height) <= ERROR) {
return true;
}
const area = node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].currentContentArea;
return h + y > area.h;
case "rl-row":
case "row":
if (node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
return true;
}
if (node.h !== "") {
return Math.round(h - space.height) <= ERROR;
}
return true;
default:
return true;
}
}

@@ -42,2 +42,5 @@ /**

this._stack = [];
this._globalData = {
usedTypefaces: new Set()
};
this._ids = new Map();

@@ -135,3 +138,3 @@ this._current = this._builder.buildRoot(this._ids);

_getNameAndPrefix(name) {
_getNameAndPrefix(name, nsAgnostic) {
const i = name.indexOf(":");

@@ -143,3 +146,3 @@

return [name.substring(i + 1), name.substring(0, i)];
return [name.substring(i + 1), nsAgnostic ? "" : name.substring(0, i)];
}

@@ -150,3 +153,3 @@

const [name, nsPrefix] = this._getNameAndPrefix(tagName);
const [name, nsPrefix] = this._getNameAndPrefix(tagName, this._builder.isNsAgnostic());

@@ -161,2 +164,4 @@ const node = this._builder.build({

node[_xfa_object.$globalData] = this._globalData;
if (isEmpty) {

@@ -182,2 +187,11 @@ node[_xfa_object.$finalize]();

if (node[_xfa_object.$isCDATAXml]() && typeof node[_xfa_object.$content] === "string") {
const parser = new XFAParser();
parser._globalData = this._globalData;
const root = parser.parse(node[_xfa_object.$content]);
node[_xfa_object.$content] = null;
node[_xfa_object.$onChild](root);
}
node[_xfa_object.$finalize]();

@@ -184,0 +198,0 @@

@@ -56,3 +56,3 @@ /**

function parseExpression(expr, dotDotAllowed) {
function parseExpression(expr, dotDotAllowed, noExpr = true) {
let match = expr.match(namePattern);

@@ -110,2 +110,7 @@

case "[":
if (noExpr) {
(0, _util.warn)("XFA - SOM expression contains a FormCalc subexpression which is not supported for now.");
return null;
}
operator = operators.dotBracket;

@@ -115,2 +120,7 @@ break;

case "(":
if (noExpr) {
(0, _util.warn)("XFA - SOM expression contains a JavaScript subexpression which is not supported for now.");
return null;
}
operator = operators.dotParen;

@@ -262,3 +272,3 @@ break;

} of path) {
for (let i = 0; i <= index; i++) {
for (let i = 0, ii = !isFinite(index) ? 0 : index; i <= ii; i++) {
node = new _xfa_object.XmlObject(root[_xfa_object.$namespaceId], name);

@@ -348,3 +358,3 @@

} else {
parsed[i].index = children.length - index;
parsed[i].index = index - children.length;
return createNodes(root, parsed.slice(i));

@@ -351,0 +361,0 @@ }

@@ -36,3 +36,7 @@ /**

exports.getStringOption = getStringOption;
exports.stripQuotes = stripQuotes;
exports.HTMLResult = void 0;
var _util = require("../../shared/util.js");
const dimConverters = {

@@ -47,2 +51,10 @@ pt: x => x,

function stripQuotes(str) {
if (str.startsWith("'") || str.startsWith('"')) {
return str.slice(1, str.length - 1);
}
return str;
}
function getInteger({

@@ -248,10 +260,27 @@ data,

class HTMLResult {
constructor(success, html, bbox) {
static get FAILURE() {
return (0, _util.shadow)(this, "FAILURE", new HTMLResult(false, null, null, null));
}
static get EMPTY() {
return (0, _util.shadow)(this, "EMPTY", new HTMLResult(true, null, null, null));
}
constructor(success, html, bbox, breakNode) {
this.success = success;
this.html = html;
this.bbox = bbox;
this.breakNode = breakNode;
}
isBreak() {
return !!this.breakNode;
}
static breakNode(node) {
return new HTMLResult(false, null, null, node);
}
static success(html, bbox = null) {
return new HTMLResult(true, html, bbox);
return new HTMLResult(true, html, bbox, null);
}

@@ -261,4 +290,2 @@

exports.HTMLResult = HTMLResult;
HTMLResult.FAILURE = new HTMLResult(false, null, null);
HTMLResult.EMPTY = new HTMLResult(true, null, null);
exports.HTMLResult = HTMLResult;

@@ -27,3 +27,3 @@ /**

});
exports.XmlObject = exports.XFAObjectArray = exports.XFAObject = exports.XFAAttribute = exports.StringObject = exports.OptionObject = exports.Option10 = exports.Option01 = exports.IntegerObject = exports.ContentObject = exports.$uid = exports.$toStyle = exports.$toHTML = exports.$text = exports.$setValue = exports.$setSetAttributes = exports.$setId = exports.$searchNode = exports.$resolvePrototypes = exports.$removeChild = exports.$onText = exports.$onChildCheck = exports.$onChild = exports.$nsAttributes = exports.$nodeName = exports.$namespaceId = exports.$isTransparent = exports.$isDescendent = exports.$isDataValue = exports.$insertAt = exports.$indexOf = exports.$ids = exports.$hasSettableValue = exports.$hasItem = exports.$global = exports.$getRealChildrenByNameIt = exports.$getParent = exports.$getNextPage = exports.$getDataValue = exports.$getChildrenByNameIt = exports.$getChildrenByName = exports.$getChildrenByClass = exports.$getChildren = exports.$getAvailableSpace = exports.$getAttributeIt = exports.$flushHTML = exports.$finalize = exports.$extra = exports.$dump = exports.$data = exports.$content = exports.$consumed = exports.$clone = exports.$cleanup = exports.$clean = exports.$childrenToHTML = exports.$break = exports.$appendChild = exports.$addHTML = exports.$acceptWhitespace = void 0;
exports.XmlObject = exports.XFAObjectArray = exports.XFAObject = exports.XFAAttribute = exports.StringObject = exports.OptionObject = exports.Option10 = exports.Option01 = exports.IntegerObject = exports.ContentObject = exports.$uid = exports.$toStyle = exports.$toString = exports.$toHTML = exports.$text = exports.$tabIndex = exports.$setValue = exports.$setSetAttributes = exports.$setId = exports.$searchNode = exports.$root = exports.$resolvePrototypes = exports.$removeChild = exports.$pushGlyphs = exports.$onText = exports.$onChildCheck = exports.$onChild = exports.$nsAttributes = exports.$nodeName = exports.$namespaceId = exports.$isUsable = exports.$isTransparent = exports.$isThereMoreWidth = exports.$isSplittable = exports.$isNsAgnostic = exports.$isDescendent = exports.$isDataValue = exports.$isCDATAXml = exports.$isBindable = exports.$insertAt = exports.$indexOf = exports.$ids = exports.$hasSettableValue = exports.$globalData = exports.$getTemplateRoot = exports.$getSubformParent = exports.$getRealChildrenByNameIt = exports.$getParent = exports.$getNextPage = exports.$getExtra = exports.$getDataValue = exports.$getContainedChildren = exports.$getChildrenByNameIt = exports.$getChildrenByName = exports.$getChildrenByClass = exports.$getChildren = exports.$getAvailableSpace = exports.$getAttributes = exports.$getAttributeIt = exports.$flushHTML = exports.$finalize = exports.$extra = exports.$dump = exports.$data = exports.$content = exports.$consumed = exports.$clone = exports.$cleanup = exports.$cleanPage = exports.$clean = exports.$childrenToHTML = exports.$appendChild = exports.$addHTML = exports.$acceptWhitespace = void 0;

@@ -34,4 +34,8 @@ var _utils = require("./utils.js");

var _core_utils = require("../core_utils.js");
var _namespaces = require("./namespaces.js");
var _som = require("./som.js");
const $acceptWhitespace = Symbol();

@@ -43,4 +47,2 @@ exports.$acceptWhitespace = $acceptWhitespace;

exports.$appendChild = $appendChild;
const $break = Symbol();
exports.$break = $break;
const $childrenToHTML = Symbol();

@@ -50,2 +52,4 @@ exports.$childrenToHTML = $childrenToHTML;

exports.$clean = $clean;
const $cleanPage = Symbol();
exports.$cleanPage = $cleanPage;
const $cleanup = Symbol();

@@ -71,2 +75,4 @@ exports.$cleanup = $cleanup;

exports.$getAttributeIt = $getAttributeIt;
const $getAttributes = Symbol();
exports.$getAttributes = $getAttributes;
const $getAvailableSpace = Symbol();

@@ -82,2 +88,4 @@ exports.$getAvailableSpace = $getAvailableSpace;

exports.$getDataValue = $getDataValue;
const $getExtra = Symbol();
exports.$getExtra = $getExtra;
const $getRealChildrenByNameIt = Symbol();

@@ -87,10 +95,14 @@ exports.$getRealChildrenByNameIt = $getRealChildrenByNameIt;

exports.$getChildren = $getChildren;
const $getContainedChildren = Symbol();
exports.$getContainedChildren = $getContainedChildren;
const $getNextPage = Symbol();
exports.$getNextPage = $getNextPage;
const $getSubformParent = Symbol();
exports.$getSubformParent = $getSubformParent;
const $getParent = Symbol();
exports.$getParent = $getParent;
const $global = Symbol();
exports.$global = $global;
const $hasItem = Symbol();
exports.$hasItem = $hasItem;
const $getTemplateRoot = Symbol();
exports.$getTemplateRoot = $getTemplateRoot;
const $globalData = Symbol();
exports.$globalData = $globalData;
const $hasSettableValue = Symbol();

@@ -104,2 +116,6 @@ exports.$hasSettableValue = $hasSettableValue;

exports.$insertAt = $insertAt;
const $isCDATAXml = Symbol();
exports.$isCDATAXml = $isCDATAXml;
const $isBindable = Symbol();
exports.$isBindable = $isBindable;
const $isDataValue = Symbol();

@@ -109,4 +125,12 @@ exports.$isDataValue = $isDataValue;

exports.$isDescendent = $isDescendent;
const $isNsAgnostic = Symbol();
exports.$isNsAgnostic = $isNsAgnostic;
const $isSplittable = Symbol();
exports.$isSplittable = $isSplittable;
const $isThereMoreWidth = Symbol();
exports.$isThereMoreWidth = $isThereMoreWidth;
const $isTransparent = Symbol();
exports.$isTransparent = $isTransparent;
const $isUsable = Symbol();
exports.$isUsable = $isUsable;
const $lastAttribute = Symbol();

@@ -125,4 +149,8 @@ const $namespaceId = Symbol("namespaceId");

exports.$onText = $onText;
const $pushGlyphs = Symbol();
exports.$pushGlyphs = $pushGlyphs;
const $removeChild = Symbol();
exports.$removeChild = $removeChild;
const $root = Symbol("root");
exports.$root = $root;
const $resolvePrototypes = Symbol();

@@ -138,2 +166,4 @@ exports.$resolvePrototypes = $resolvePrototypes;

exports.$setValue = $setValue;
const $tabIndex = Symbol();
exports.$tabIndex = $tabIndex;
const $text = Symbol();

@@ -143,2 +173,4 @@ exports.$text = $text;

exports.$toHTML = $toHTML;
const $toString = Symbol();
exports.$toString = $toString;
const $toStyle = Symbol();

@@ -177,2 +209,4 @@ exports.$toStyle = $toStyle;

const _resolvePrototypesHelper = Symbol();
const _setAttributes = Symbol();

@@ -183,2 +217,3 @@

let uid = 0;
const NS_DATASETS = _namespaces.NamespaceIds.datasets.id;

@@ -193,2 +228,3 @@ class XFAObject {

this[$uid] = `${name}${uid++}`;
this[$globalData] = null;
}

@@ -235,2 +271,6 @@

[$isNsAgnostic]() {
return false;
}
[$acceptWhitespace]() {

@@ -240,2 +280,10 @@ return false;

[$isCDATAXml]() {
return false;
}
[$isBindable]() {
return false;
}
[$setId](ids) {

@@ -247,2 +295,14 @@ if (this.id && this[$namespaceId] === _namespaces.NamespaceIds.template.id) {

[$getTemplateRoot]() {
return this[$globalData].template;
}
[$isSplittable]() {
return false;
}
[$isThereMoreWidth]() {
return false;
}
[$appendChild](child) {

@@ -279,6 +339,2 @@ child[_parent] = this;

[$hasItem]() {
return false;
}
[$indexOf](child) {

@@ -295,3 +351,3 @@ return this[_children].indexOf(child);

[$isTransparent]() {
return this.name === "";
return !this.name;
}

@@ -347,2 +403,6 @@

[$getSubformParent]() {
return this[$getParent]();
}
[$getChildren](name = null) {

@@ -392,4 +452,10 @@ if (!name) {

*[$getContainedChildren]() {
for (const node of this[$getChildren]()) {
yield node;
}
}
*[_filteredChildrenGenerator](filter, include) {
for (const node of this[$getChildren]()) {
for (const node of this[$getContainedChildren]()) {
if (!filter || include === filter.has(node[$nodeName])) {

@@ -429,3 +495,3 @@ const availableSpace = this[$getAvailableSpace]();

if (!res.success) {
return false;
return res;
}

@@ -450,3 +516,3 @@

if (!res.success) {
return false;
return res;
}

@@ -460,9 +526,7 @@

this[$extra].generator = null;
return true;
return _utils.HTMLResult.EMPTY;
}
[$setSetAttributes](attributes) {
if (attributes.use || attributes.id) {
this[_setAttributes] = new Set(Object.keys(attributes));
}
this[_setAttributes] = new Set(Object.keys(attributes));
}

@@ -478,9 +542,13 @@

for (const child of this[_children]) {
const proto = child[_getPrototype](ids, ancestors);
child[_resolvePrototypesHelper](ids, ancestors);
}
}
if (proto) {
child[_applyPrototype](proto, ids, ancestors);
} else {
child[$resolvePrototypes](ids, ancestors);
}
[_resolvePrototypesHelper](ids, ancestors) {
const proto = this[_getPrototype](ids, ancestors);
if (proto) {
this[_applyPrototype](proto, ids, ancestors);
} else {
this[$resolvePrototypes](ids, ancestors);
}

@@ -491,41 +559,71 @@ }

const {
use
use,
usehref
} = this;
if (use && use.startsWith("#")) {
const id = use.slice(1);
const proto = ids.get(id);
this.use = "";
if (!use && !usehref) {
return null;
}
if (!proto) {
(0, _util.warn)(`XFA - Invalid prototype id: ${id}.`);
return null;
}
let proto = null;
let somExpression = null;
let id = null;
let ref = use;
if (proto[$nodeName] !== this[$nodeName]) {
(0, _util.warn)(`XFA - Incompatible prototype: ${proto[$nodeName]} !== ${this[$nodeName]}.`);
return null;
}
if (usehref) {
ref = usehref;
if (ancestors.has(proto)) {
(0, _util.warn)(`XFA - Cycle detected in prototypes use.`);
return null;
if (usehref.startsWith("#som(") && usehref.endsWith(")")) {
somExpression = usehref.slice("#som(".length, usehref.length - 1);
} else if (usehref.startsWith(".#som(") && usehref.endsWith(")")) {
somExpression = usehref.slice(".#som(".length, usehref.length - 1);
} else if (usehref.startsWith("#")) {
id = usehref.slice(1);
} else if (usehref.startsWith(".#")) {
id = usehref.slice(2);
}
} else if (use.startsWith("#")) {
id = use.slice(1);
} else {
somExpression = use;
}
ancestors.add(proto);
this.use = this.usehref = "";
const protoProto = proto[_getPrototype](ids, ancestors);
if (id) {
proto = ids.get(id);
} else {
proto = (0, _som.searchNode)(ids.get($root), this, somExpression, true, false);
if (!protoProto) {
ancestors.delete(proto);
return proto;
if (proto) {
proto = proto[0];
}
}
proto[_applyPrototype](protoProto, ids, ancestors);
if (!proto) {
(0, _util.warn)(`XFA - Invalid prototype reference: ${ref}.`);
return null;
}
ancestors.delete(proto);
return proto;
if (proto[$nodeName] !== this[$nodeName]) {
(0, _util.warn)(`XFA - Incompatible prototype: ${proto[$nodeName]} !== ${this[$nodeName]}.`);
return null;
}
return null;
if (ancestors.has(proto)) {
(0, _util.warn)(`XFA - Cycle detected in prototypes use.`);
return null;
}
ancestors.add(proto);
const protoProto = proto[_getPrototype](ids, ancestors);
if (protoProto) {
proto[_applyPrototype](protoProto, ids, ancestors);
}
proto[$resolvePrototypes](ids, ancestors);
ancestors.delete(proto);
return proto;
}

@@ -564,3 +662,3 @@

for (const child of value[_children]) {
child[$resolvePrototypes](ids, ancestors);
child[_resolvePrototypesHelper](ids, ancestors);
}

@@ -576,3 +674,3 @@

child[$resolvePrototypes](ids, newAncestors);
child[_resolvePrototypesHelper](ids, ancestors);
} else {

@@ -588,2 +686,7 @@ break;

value[$resolvePrototypes](ids, ancestors);
if (protoValue) {
value[_applyPrototype](protoValue, ids, ancestors);
}
continue;

@@ -599,3 +702,3 @@ }

child[$resolvePrototypes](ids, newAncestors);
child[_resolvePrototypesHelper](ids, ancestors);
}

@@ -610,3 +713,3 @@ }

if (obj instanceof Object) {
if (typeof obj === "object" && obj !== null) {
return Object.assign({}, obj);

@@ -629,2 +732,3 @@ }

clone[$uid] = `${clone[$nodeName]}${uid++}`;
clone[_children] = [];

@@ -761,2 +865,3 @@

this[$consumed] = false;
this[$uid] = `attribute${uid++}`;
}

@@ -772,2 +877,11 @@

[$getDataValue]() {
return this[$content].trim();
}
[$setValue](value) {
value = value.value || "";
this[$content] = value.toString();
}
[$text]() {

@@ -815,2 +929,47 @@ return this[$content];

[$toString](buf) {
const tagName = this[$nodeName];
if (tagName === "#text") {
buf.push((0, _core_utils.encodeToXmlString)(this[$content]));
return;
}
const prefix = this[$namespaceId] === NS_DATASETS ? "xfa:" : "";
buf.push(`<${prefix}${tagName}`);
for (const [name, value] of this[_attributes].entries()) {
buf.push(` ${name}="${(0, _core_utils.encodeToXmlString)(value[$content])}"`);
}
if (this[_dataValue] !== null) {
if (this[_dataValue]) {
buf.push(` xfa:dataNode="dataValue"`);
} else {
buf.push(` xfa:dataNode="dataGroup"`);
}
}
if (!this[$content] && this[_children].length === 0) {
buf.push("/>");
return;
}
buf.push(">");
if (this[$content]) {
if (typeof this[$content] === "string") {
buf.push((0, _core_utils.encodeToXmlString)(this[$content]));
} else {
this[$content][$toString](buf);
}
} else {
for (const child of this[_children]) {
child[$toString](buf);
}
}
buf.push(`</${prefix}${tagName}>`);
}
[$onChild](child) {

@@ -860,2 +1019,6 @@ if (this[$content]) {

[$getAttributes]() {
return this[_attributes];
}
[$getChildrenByClass](name) {

@@ -937,2 +1100,7 @@ const value = this[_attributes].get(name);

[$setValue](value) {
value = value.value || "";
this[$content] = value.toString();
}
[$dump]() {

@@ -939,0 +1107,0 @@ const dumped = Object.create(null);

@@ -39,7 +39,10 @@ /**

const VALID_STYLES = new Set(["color", "font", "font-family", "font-size", "font-stretch", "font-style", "font-weight", "margin", "margin-bottom", "margin-left", "margin-right", "margin-top", "letter-spacing", "line-height", "orphans", "page-break-after", "page-break-before", "page-break-inside", "tab-interval", "tab-stop", "text-align", "text-decoration", "text-indent", "vertical-align", "widows", "kerning-mode", "xfa-font-horizontal-scale", "xfa-font-vertical-scale", "xfa-spacerun", "xfa-tab-stops"]);
const StyleMapping = new Map([["page-break-after", "breakAfter"], ["page-break-before", "breakBefore"], ["page-break-inside", "breakInside"], ["kerning-mode", value => value === "none" ? "none" : "normal"], ["xfa-font-horizontal-scale", value => `scaleX(${Math.max(0, Math.min(parseInt(value) / 100)).toFixed(2)})`], ["xfa-font-vertical-scale", value => `scaleY(${Math.max(0, Math.min(parseInt(value) / 100)).toFixed(2)})`], ["xfa-spacerun", ""], ["xfa-tab-stops", ""], ["font-size", value => (0, _html_utils.measureToString)(1 * (0, _utils.getMeasurement)(value))], ["letter-spacing", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["line-height", value => (0, _html_utils.measureToString)(0.99 * (0, _utils.getMeasurement)(value))], ["margin", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-bottom", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-left", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-right", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-top", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["text-indent", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["font-family", value => (0, _html_utils.getFonts)(value)]]);
const StyleMapping = new Map([["page-break-after", "breakAfter"], ["page-break-before", "breakBefore"], ["page-break-inside", "breakInside"], ["kerning-mode", value => value === "none" ? "none" : "normal"], ["xfa-font-horizontal-scale", value => `scaleX(${Math.max(0, Math.min(parseInt(value) / 100)).toFixed(2)})`], ["xfa-font-vertical-scale", value => `scaleY(${Math.max(0, Math.min(parseInt(value) / 100)).toFixed(2)})`], ["xfa-spacerun", ""], ["xfa-tab-stops", ""], ["font-size", (value, original) => {
value = original.fontSize = (0, _utils.getMeasurement)(value);
return (0, _html_utils.measureToString)(0.99 * value);
}], ["letter-spacing", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["line-height", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-bottom", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-left", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-right", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-top", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["text-indent", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["font-family", value => value]]);
const spacesRegExp = /\s+/g;
const crlfRegExp = /[\r\n]+/g;
function mapStyle(styleStr) {
function mapStyle(styleStr, fontFinder) {
const style = Object.create(null);

@@ -51,2 +54,4 @@

const original = Object.create(null);
for (const [key, value] of styleStr.split(";").map(s => s.split(":", 2))) {

@@ -65,3 +70,3 @@ const mapping = StyleMapping.get(key);

} else {
newValue = mapping(value);
newValue = mapping(value, original);
}

@@ -81,2 +86,11 @@ }

if (style.fontFamily) {
(0, _html_utils.setFontFamily)({
typeface: style.fontFamily,
weight: style.fontWeight || "normal",
posture: style.fontStyle || "normal",
size: original.fontSize || 0
}, fontFinder, style);
}
(0, _html_utils.fixTextIndent)(style);

@@ -86,8 +100,14 @@ return style;

function checkStyle(style) {
if (!style) {
function checkStyle(node) {
if (!node.style) {
return "";
}
return style.trim().split(/\s*;\s*/).filter(s => !!s).map(s => s.split(/\s*:\s*/, 2)).filter(([key]) => VALID_STYLES.has(key)).map(kv => kv.join(":")).join(";");
return node.style.trim().split(/\s*;\s*/).filter(s => !!s).map(s => s.split(/\s*:\s*/, 2)).filter(([key, value]) => {
if (key === "font-family") {
node[_xfa_object.$globalData].usedTypefaces.add(value);
}
return VALID_STYLES.has(key);
}).map(kv => kv.join(":")).join(";");
}

@@ -100,5 +120,11 @@

super(XHTML_NS_ID, name);
this.style = checkStyle(attributes.style);
this.style = attributes.style || "";
}
[_xfa_object.$clean](builder) {
super[_xfa_object.$clean](builder);
this.style = checkStyle(this);
}
[_xfa_object.$acceptWhitespace]() {

@@ -120,2 +146,105 @@ return !NoWhites.has(this[_xfa_object.$nodeName]);

[_xfa_object.$pushGlyphs](measure, mustPop = true) {
const xfaFont = Object.create(null);
const margin = {
top: NaN,
bottom: NaN,
left: NaN,
right: NaN
};
let lineHeight = null;
for (const [key, value] of this.style.split(";").map(s => s.split(":", 2))) {
switch (key) {
case "font-family":
xfaFont.typeface = (0, _utils.stripQuotes)(value);
break;
case "font-size":
xfaFont.size = (0, _utils.getMeasurement)(value);
break;
case "font-weight":
xfaFont.weight = value;
break;
case "font-style":
xfaFont.posture = value;
break;
case "letter-spacing":
xfaFont.letterSpacing = (0, _utils.getMeasurement)(value);
break;
case "margin":
const values = value.split(/ \t/).map(x => (0, _utils.getMeasurement)(x));
switch (values.length) {
case 1:
margin.top = margin.bottom = margin.left = margin.right = values[0];
break;
case 2:
margin.top = margin.bottom = values[0];
margin.left = margin.right = values[1];
break;
case 3:
margin.top = values[0];
margin.bottom = values[2];
margin.left = margin.right = values[1];
break;
case 4:
margin.top = values[0];
margin.left = values[1];
margin.bottom = values[2];
margin.right = values[3];
break;
}
break;
case "margin-top":
margin.top = (0, _utils.getMeasurement)(value);
break;
case "margin-bottom":
margin.bottom = (0, _utils.getMeasurement)(value);
break;
case "margin-left":
margin.left = (0, _utils.getMeasurement)(value);
break;
case "margin-right":
margin.right = (0, _utils.getMeasurement)(value);
break;
case "line-height":
lineHeight = (0, _utils.getMeasurement)(value);
break;
}
}
measure.pushData(xfaFont, margin, lineHeight);
if (this[_xfa_object.$content]) {
measure.addString(this[_xfa_object.$content]);
} else {
for (const child of this[_xfa_object.$getChildren]()) {
if (child[_xfa_object.$nodeName] === "#text") {
measure.addString(child[_xfa_object.$content]);
continue;
}
child[_xfa_object.$pushGlyphs](measure);
}
}
if (mustPop) {
measure.popFont();
}
}
[_xfa_object.$toHTML](availableSpace) {

@@ -137,3 +266,3 @@ const children = [];

href: this.href,
style: mapStyle(this.style)
style: mapStyle(this.style, this[_xfa_object.$globalData].fontFinder)
},

@@ -160,2 +289,12 @@ children,

[_xfa_object.$pushGlyphs](measure) {
measure.pushFont({
weight: "bold"
});
super[_xfa_object.$pushGlyphs](measure);
measure.popFont();
}
}

@@ -180,3 +319,3 @@

html.name = "div";
html.attributes.class = "xfaRich";
html.attributes.class = ["xfaRich"];
return res;

@@ -196,2 +335,6 @@ }

[_xfa_object.$pushGlyphs](measure) {
measure.addString("\n");
}
[_xfa_object.$toHTML](availableSpace) {

@@ -222,3 +365,3 @@ return _utils.HTMLResult.success({

attributes: {
class: "xfaRich",
class: ["xfaRich"],
style: {}

@@ -233,3 +376,3 @@ },

if (child.attributes && child.attributes.class === "xfaRich") {
if (child.attributes && child.attributes.class.includes("xfaRich")) {
return _utils.HTMLResult.success(child);

@@ -242,3 +385,3 @@ }

attributes: {
class: "xfaRich",
class: ["xfaRich"],
style: {}

@@ -257,2 +400,12 @@ },

[_xfa_object.$pushGlyphs](measure) {
measure.pushFont({
posture: "italic"
});
super[_xfa_object.$pushGlyphs](measure);
measure.popFont();
}
}

@@ -279,2 +432,10 @@

[_xfa_object.$pushGlyphs](measure) {
super[_xfa_object.$pushGlyphs](measure, false);
measure.addString("\n");
measure.addPara();
measure.popFont();
}
[_xfa_object.$text]() {

@@ -281,0 +442,0 @@ return super[_xfa_object.$text]() + "\n";

@@ -423,4 +423,25 @@ /**

gen = m[2] | 0;
let contentLength,
startPos = position + token.length,
updateEntries = false;
if (!this.entries[num] || this.entries[num].gen === gen) {
if (!this.entries[num]) {
updateEntries = true;
} else if (this.entries[num].gen === gen) {
try {
const parser = new _parser.Parser({
lexer: new _parser.Lexer(stream.makeSubStream(startPos))
});
parser.getObj();
updateEntries = true;
} catch (ex) {
if (ex instanceof _core_utils.ParserEOFException) {
(0, _util.warn)(`indexObjects -- checking object (${token}): "${ex}".`);
} else {
updateEntries = true;
}
}
}
if (updateEntries) {
this.entries[num] = {

@@ -433,5 +454,2 @@ offset: position - stream.start,

let contentLength,
startPos = position + token.length;
while (startPos < buffer.length) {

@@ -438,0 +456,0 @@ const endPos = startPos + skipUntil(buffer, startPos, objBytes) + 4;

@@ -170,4 +170,4 @@ /**

if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) {
width = width - 2 * data.borderStyle.width;
height = height - 2 * data.borderStyle.width;
width -= 2 * data.borderStyle.width;
height -= 2 * data.borderStyle.width;
}

@@ -174,0 +174,0 @@

@@ -29,3 +29,3 @@ /**

exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
exports.version = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultCMapReaderFactory = exports.DefaultCanvasFactory = exports.build = void 0;
exports.version = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCMapReaderFactory = exports.DefaultCanvasFactory = exports.build = void 0;

@@ -42,4 +42,2 @@ var _util = require("../shared/util.js");

var _api_compatibility = require("./api_compatibility.js");
var _canvas = require("./canvas.js");

@@ -65,2 +63,4 @@

exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
const DefaultStandardFontDataFactory = _is_node.isNodeJS ? _node_utils.NodeStandardFontDataFactory : _display_utils.DOMStandardFontDataFactory;
exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
let createPDFNetworkStream;

@@ -154,2 +154,3 @@

params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
params.ignoreErrors = params.stopAtErrors !== true;

@@ -168,2 +169,6 @@ params.fontExtraProperties = params.fontExtraProperties === true;

if (typeof params.useWorkerFetch !== "boolean") {
params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
}
if (typeof params.isEvalSupported !== "boolean") {

@@ -174,5 +179,9 @@ params.isEvalSupported = true;

if (typeof params.disableFontFace !== "boolean") {
params.disableFontFace = _api_compatibility.apiCompatibilityParams.disableFontFace || false;
params.disableFontFace = _is_node.isNodeJS;
}
if (typeof params.useSystemFonts !== "boolean") {
params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
}
if (typeof params.ownerDocument === "undefined") {

@@ -268,3 +277,3 @@ params.ownerDocument = globalThis.document;

docId,
apiVersion: '2.9.359',
apiVersion: '2.10.377',
source: {

@@ -285,3 +294,6 @@ data: source.data,

fontExtraProperties: source.fontExtraProperties,
enableXfa: source.enableXfa
enableXfa: source.enableXfa,
useSystemFonts: source.useSystemFonts,
cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
}).then(function (workerId) {

@@ -411,2 +423,9 @@ if (worker.destroyed) {

this._transport = transport;
Object.defineProperty(this, "fingerprint", {
get() {
(0, _display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, " + "please use `PDFDocumentProxy.fingerprints` instead.");
return this.fingerprints[0];
}
});
}

@@ -422,10 +441,14 @@

get fingerprint() {
return this._pdfInfo.fingerprint;
get fingerprints() {
return this._pdfInfo.fingerprints;
}
get isPureXfa() {
return this._pdfInfo.isPureXfa;
return !!this._transport._htmlForXfa;
}
get allXfaHtml() {
return this._transport._htmlForXfa;
}
getPage(pageNumber) {

@@ -528,6 +551,2 @@ return this._transport.getPage(pageNumber);

saveDocument() {
if (arguments.length > 0) {
(0, _display_utils.deprecated)("saveDocument no longer accepts any options.");
}
if (this._transport.annotationStorage.size <= 0) {

@@ -612,5 +631,7 @@ (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");

} = {}) {
if (!this._annotationsPromise || this._annotationsIntent !== intent) {
this._annotationsPromise = this._transport.getAnnotations(this._pageIndex, intent);
this._annotationsIntent = intent;
const renderingIntent = intent === "display" || intent === "print" ? intent : null;
if (!this._annotationsPromise || this._annotationsIntent !== renderingIntent) {
this._annotationsPromise = this._transport.getAnnotations(this._pageIndex, renderingIntent);
this._annotationsIntent = renderingIntent;
}

@@ -625,4 +646,4 @@

getXfa() {
return this._xfaPromise || (this._xfaPromise = this._transport.getPageXfa(this._pageIndex));
async getXfa() {
return this._transport._htmlForXfa?.children[this._pageIndex] || null;
}

@@ -644,7 +665,2 @@

if (arguments[0]?.annotationStorage !== undefined) {
(0, _display_utils.deprecated)("render no longer accepts an `annotationStorage` option, " + "please use the `includeAnnotationStorage`-boolean instead.");
includeAnnotationStorage || (includeAnnotationStorage = !!arguments[0].annotationStorage);
}
if (this._stats) {

@@ -764,3 +780,5 @@ this._stats.time("Overall");

getOperatorList() {
getOperatorList({
intent = "display"
} = {}) {
function operatorListChanged() {

@@ -773,3 +791,3 @@ if (intentState.operatorList.lastChunk) {

const renderingIntent = "oplist";
const renderingIntent = `oplist-${intent === "print" ? "print" : "display"}`;

@@ -877,3 +895,3 @@ let intentState = this._intentStates.get(renderingIntent);

if (intent === "oplist") {
if (intent.startsWith("oplist-")) {
continue;

@@ -891,3 +909,2 @@ }

this._jsActionsPromise = null;
this._xfaPromise = null;
this._structTreePromise = null;

@@ -922,3 +939,2 @@ this.pendingCleanup = false;

this._jsActionsPromise = null;
this._xfaPromise = null;
this._structTreePromise = null;

@@ -1089,2 +1105,6 @@

function cloneValue(value) {
if (typeof value === "function" || typeof value === "symbol" || value instanceof URL) {
throw new Error(`LoopbackPort.postMessage - cannot clone: ${value?.toString()}`);
}
if (typeof value !== "object" || value === null) {

@@ -1133,6 +1153,2 @@ return value;

if (value instanceof URL) {
throw new Error(`LoopbackPort.postMessage - cannot clone: ${value}`);
}
result = Array.isArray(value) ? [] : Object.create(null);

@@ -1153,7 +1169,3 @@ cloned.set(value, result);

if (typeof desc.value === "function") {
if (value.hasOwnProperty?.(i)) {
throw new Error(`LoopbackPort.postMessage - cannot clone: ${value[i]}`);
}
if (typeof desc.value === "function" && !value.hasOwnProperty?.(i)) {
continue;

@@ -1503,9 +1515,17 @@ }

onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
ownerDocument: params.ownerDocument
ownerDocument: params.ownerDocument,
styleElement: params.styleElement
});
this._params = params;
this.CMapReaderFactory = new params.CMapReaderFactory({
baseUrl: params.cMapUrl,
isCompressed: params.cMapPacked
});
if (!params.useWorkerFetch) {
this.CMapReaderFactory = new params.CMapReaderFactory({
baseUrl: params.cMapUrl,
isCompressed: params.cMapPacked
});
this.StandardFontDataFactory = new params.StandardFontDataFactory({
baseUrl: params.standardFontDataUrl
});
}
this.destroyed = false;

@@ -1689,2 +1709,4 @@ this.destroyCapability = null;

this._numPages = pdfInfo.numPages;
this._htmlForXfa = pdfInfo.htmlForXfa;
delete pdfInfo.htmlForXfa;

@@ -1850,2 +1872,6 @@ loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));

case "Pattern":
pageProxy.objs.resolve(id, imageData);
break;
default:

@@ -1870,23 +1896,23 @@ throw new Error(`Got unknown object type ${type}`);

messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
messageHandler.on("FetchBuiltInCMap", (data, sink) => {
messageHandler.on("FetchBuiltInCMap", data => {
if (this.destroyed) {
sink.error(new Error("Worker was destroyed"));
return;
return Promise.reject(new Error("Worker was destroyed."));
}
let fetched = false;
if (!this.CMapReaderFactory) {
return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
}
sink.onPull = () => {
if (fetched) {
sink.close();
return;
}
return this.CMapReaderFactory.fetch(data);
});
messageHandler.on("FetchStandardFontData", data => {
if (this.destroyed) {
return Promise.reject(new Error("Worker was destroyed."));
}
fetched = true;
this.CMapReaderFactory.fetch(data).then(function (builtInCMap) {
sink.enqueue(builtInCMap, 1, [builtInCMap.cMapData.buffer]);
}).catch(function (reason) {
sink.error(reason);
});
};
if (!this.StandardFontDataFactory) {
return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
}
return this.StandardFontDataFactory.fetch(data);
});

@@ -1954,2 +1980,3 @@ }

return this.messageHandler.sendWithPromise("SaveDocument", {
isPureXfa: !!this._htmlForXfa,
numPages: this._numPages,

@@ -2027,8 +2054,2 @@ annotationStorage: this.annotationStorage.serializable,

getPageXfa(pageIndex) {
return this.messageHandler.sendWithPromise("GetPageXfa", {
pageIndex
});
}
getStructTree(pageIndex) {

@@ -2106,4 +2127,3 @@ return this.messageHandler.sendWithPromise("GetStructTree", {

return (0, _util.shadow)(this, "loadingParams", {
disableAutoFetch: params.disableAutoFetch,
disableFontFace: params.disableFontFace
disableAutoFetch: params.disableAutoFetch
});

@@ -2354,5 +2374,5 @@ }

const version = '2.9.359';
const version = '2.10.377';
exports.version = version;
const build = 'e667c8cbc';
const build = '156762c48';
exports.build = build;

@@ -31,11 +31,13 @@ /**

exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
exports.getXfaPageViewport = getXfaPageViewport;
exports.isDataScheme = isDataScheme;
exports.isFetchSupported = isFetchSupported;
exports.isPdfFile = isPdfFile;
exports.isValidFetchUrl = isValidFetchUrl;
exports.loadScript = loadScript;
exports.StatTimer = exports.RenderingCancelledException = exports.PDFDateString = exports.PageViewport = exports.LinkTarget = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.BaseCMapReaderFactory = exports.BaseCanvasFactory = void 0;
exports.StatTimer = exports.RenderingCancelledException = exports.PDFDateString = exports.PageViewport = exports.LinkTarget = exports.DOMSVGFactory = exports.DOMStandardFontDataFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = void 0;
var _util = require("../shared/util.js");
var _base_factory = require("./base_factory.js");
const DEFAULT_LINK_REL = "noopener noreferrer nofollow";

@@ -45,42 +47,3 @@ exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;

class BaseCanvasFactory {
constructor() {
if (this.constructor === BaseCanvasFactory) {
(0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
}
}
create(width, height) {
(0, _util.unreachable)("Abstract method `create` called.");
}
reset(canvasAndContext, width, height) {
if (!canvasAndContext.canvas) {
throw new Error("Canvas is not specified");
}
if (width <= 0 || height <= 0) {
throw new Error("Invalid canvas size");
}
canvasAndContext.canvas.width = width;
canvasAndContext.canvas.height = height;
}
destroy(canvasAndContext) {
if (!canvasAndContext.canvas) {
throw new Error("Canvas is not specified");
}
canvasAndContext.canvas.width = 0;
canvasAndContext.canvas.height = 0;
canvasAndContext.canvas = null;
canvasAndContext.context = null;
}
}
exports.BaseCanvasFactory = BaseCanvasFactory;
class DOMCanvasFactory extends BaseCanvasFactory {
class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
constructor({

@@ -93,16 +56,8 @@ ownerDocument = globalThis.document

create(width, height) {
if (width <= 0 || height <= 0) {
throw new Error("Invalid canvas size");
}
_createCanvas(width, height) {
const canvas = this._document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
return {
canvas,
context
};
return canvas;
}

@@ -114,99 +69,55 @@

class BaseCMapReaderFactory {
constructor({
baseUrl = null,
isCompressed = false
}) {
if (this.constructor === BaseCMapReaderFactory) {
(0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
async function fetchData(url, asTypedArray = false) {
if (isValidFetchUrl(url, document.baseURI)) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
this.baseUrl = baseUrl;
this.isCompressed = isCompressed;
return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
}
async fetch({
name
}) {
if (!this.baseUrl) {
throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
}
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open("GET", url, true);
if (!name) {
throw new Error("CMap name must be specified.");
if (asTypedArray) {
request.responseType = "arraybuffer";
}
const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
return this._fetchData(url, compressionType).catch(reason => {
throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
});
}
request.onreadystatechange = () => {
if (request.readyState !== XMLHttpRequest.DONE) {
return;
}
_fetchData(url, compressionType) {
(0, _util.unreachable)("Abstract method `_fetchData` called.");
}
if (request.status === 200 || request.status === 0) {
let data;
}
exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
class DOMCMapReaderFactory extends BaseCMapReaderFactory {
_fetchData(url, compressionType) {
if (isFetchSupported() && isValidFetchUrl(url, document.baseURI)) {
return fetch(url).then(async response => {
if (!response.ok) {
throw new Error(response.statusText);
if (asTypedArray && request.response) {
data = new Uint8Array(request.response);
} else if (!asTypedArray && request.responseText) {
data = (0, _util.stringToBytes)(request.responseText);
}
let cMapData;
if (this.isCompressed) {
cMapData = new Uint8Array(await response.arrayBuffer());
} else {
cMapData = (0, _util.stringToBytes)(await response.text());
if (data) {
resolve(data);
return;
}
return {
cMapData,
compressionType
};
});
}
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open("GET", url, true);
if (this.isCompressed) {
request.responseType = "arraybuffer";
}
request.onreadystatechange = () => {
if (request.readyState !== XMLHttpRequest.DONE) {
return;
}
reject(new Error(request.statusText));
};
if (request.status === 200 || request.status === 0) {
let cMapData;
request.send(null);
});
}
if (this.isCompressed && request.response) {
cMapData = new Uint8Array(request.response);
} else if (!this.isCompressed && request.responseText) {
cMapData = (0, _util.stringToBytes)(request.responseText);
}
if (cMapData) {
resolve({
cMapData,
compressionType
});
return;
}
}
reject(new Error(request.statusText));
class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
_fetchData(url, compressionType) {
return fetchData(url, this.isCompressed).then(data => {
return {
cMapData: data,
compressionType
};
request.send(null);
});

@@ -219,16 +130,13 @@ }

class DOMSVGFactory {
create(width, height) {
(0, _util.assert)(width > 0 && height > 0, "Invalid SVG dimensions");
const svg = document.createElementNS(SVG_NS, "svg:svg");
svg.setAttribute("version", "1.1");
svg.setAttribute("width", width + "px");
svg.setAttribute("height", height + "px");
svg.setAttribute("preserveAspectRatio", "none");
svg.setAttribute("viewBox", "0 0 " + width + " " + height);
return svg;
class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
_fetchData(url) {
return fetchData(url, true);
}
createElement(type) {
(0, _util.assert)(typeof type === "string", "Invalid SVG element type");
}
exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
class DOMSVGFactory extends _base_factory.BaseSVGFactory {
_createSVG(type) {
return document.createElementNS(SVG_NS, type);

@@ -525,6 +433,2 @@ }

function isFetchSupported() {
return typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype && typeof ReadableStream !== "undefined";
}
function isValidFetchUrl(url, baseUrl) {

@@ -614,2 +518,18 @@ try {

exports.PDFDateString = PDFDateString;
exports.PDFDateString = PDFDateString;
function getXfaPageViewport(xfaPage, {
scale = 1,
rotation = 0
}) {
const {
width,
height
} = xfaPage.attributes.style;
const viewBox = [0, 0, parseInt(width), parseInt(height)];
return new PageViewport({
viewBox,
scale,
rotation
});
}

@@ -35,3 +35,4 @@ /**

onUnsupportedFeature,
ownerDocument = globalThis.document
ownerDocument = globalThis.document,
styleElement = null
}) {

@@ -133,3 +134,4 @@ if (this.constructor === BaseFontLoader) {

get isFontLoadingAPISupported() {
return (0, _util.shadow)(this, "isFontLoadingAPISupported", !!this._document?.fonts);
const hasFonts = !!this._document?.fonts;
return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
}

@@ -136,0 +138,0 @@

@@ -27,5 +27,5 @@ /**

});
exports.NodeCMapReaderFactory = exports.NodeCanvasFactory = void 0;
exports.NodeStandardFontDataFactory = exports.NodeCMapReaderFactory = exports.NodeCanvasFactory = void 0;
var _display_utils = require("./display_utils.js");
var _base_factory = require("./base_factory.js");

@@ -50,36 +50,41 @@ var _is_node = require("../shared/is_node.js");

exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
let NodeStandardFontDataFactory = class {
constructor() {
(0, _util.unreachable)("Not implemented: NodeStandardFontDataFactory");
}
};
exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
if (_is_node.isNodeJS) {
exports.NodeCanvasFactory = NodeCanvasFactory = class extends _display_utils.BaseCanvasFactory {
create(width, height) {
if (width <= 0 || height <= 0) {
throw new Error("Invalid canvas size");
}
const fetchData = function (url) {
return new Promise((resolve, reject) => {
const fs = require("fs");
fs.readFile(url, (error, data) => {
if (error || !data) {
reject(new Error(error));
return;
}
resolve(new Uint8Array(data));
});
});
};
exports.NodeCanvasFactory = NodeCanvasFactory = class extends _base_factory.BaseCanvasFactory {
_createCanvas(width, height) {
const Canvas = require("canvas");
const canvas = Canvas.createCanvas(width, height);
return {
canvas,
context: canvas.getContext("2d")
};
return Canvas.createCanvas(width, height);
}
};
exports.NodeCMapReaderFactory = NodeCMapReaderFactory = class extends _display_utils.BaseCMapReaderFactory {
exports.NodeCMapReaderFactory = NodeCMapReaderFactory = class extends _base_factory.BaseCMapReaderFactory {
_fetchData(url, compressionType) {
return new Promise((resolve, reject) => {
const fs = require("fs");
fs.readFile(url, (error, data) => {
if (error || !data) {
reject(new Error(error));
return;
}
resolve({
cMapData: new Uint8Array(data),
compressionType
});
});
return fetchData(url).then(data => {
return {
cMapData: data,
compressionType
};
});

@@ -89,2 +94,8 @@ }

};
exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory = class extends _base_factory.BaseStandardFontDataFactory {
_fetchData(url) {
return fetchData(url);
}
};
}

@@ -32,16 +32,2 @@ /**

let svgElement;
function createMatrix(matrix) {
if (typeof DOMMatrix !== "undefined") {
return new DOMMatrix(matrix);
}
if (!svgElement) {
svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
}
return svgElement.createSVGMatrix(matrix);
}
function applyBoundingBox(ctx, bbox) {

@@ -83,28 +69,12 @@ if (!bbox || typeof Path2D === "undefined") {

this._matrix = IR[8];
this._patternCache = null;
}
getPattern(ctx, owner, shadingFill) {
const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", ctx.canvas.width, ctx.canvas.height, true);
const tmpCtx = tmpCanvas.context;
tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
tmpCtx.beginPath();
tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
if (!shadingFill) {
tmpCtx.setTransform.apply(tmpCtx, owner.baseTransform);
if (this._matrix) {
tmpCtx.transform.apply(tmpCtx, this._matrix);
}
} else {
tmpCtx.setTransform.apply(tmpCtx, ctx.mozCurrentTransform);
}
applyBoundingBox(tmpCtx, this._bbox);
_createGradient(ctx) {
let grad;
if (this._type === "axial") {
grad = tmpCtx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
} else if (this._type === "radial") {
grad = tmpCtx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
}

@@ -116,6 +86,45 @@

tmpCtx.fillStyle = grad;
tmpCtx.fill();
const pattern = ctx.createPattern(tmpCanvas.canvas, "repeat");
pattern.setTransform(createMatrix(ctx.mozCurrentTransformInverse));
return grad;
}
getPattern(ctx, owner, inverse, shadingFill = false) {
let pattern;
if (this._patternCache) {
pattern = this._patternCache;
} else {
if (!shadingFill) {
const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", owner.ctx.canvas.width, owner.ctx.canvas.height, true);
const tmpCtx = tmpCanvas.context;
tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
tmpCtx.beginPath();
tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
tmpCtx.setTransform.apply(tmpCtx, owner.baseTransform);
if (this._matrix) {
tmpCtx.transform.apply(tmpCtx, this._matrix);
}
applyBoundingBox(tmpCtx, this._bbox);
tmpCtx.fillStyle = this._createGradient(tmpCtx);
tmpCtx.fill();
pattern = ctx.createPattern(tmpCanvas.canvas, "repeat");
} else {
applyBoundingBox(ctx, this._bbox);
pattern = this._createGradient(ctx);
}
this._patternCache = pattern;
}
if (!shadingFill) {
const domMatrix = new DOMMatrix(inverse);
try {
pattern.setTransform(domMatrix);
} catch (ex) {
(0, _util.warn)(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
}
}
return pattern;

@@ -191,4 +200,2 @@ }

k = 0;
} else if (y1 === y2) {
k = 1;
} else {

@@ -352,3 +359,3 @@ k = (y1 - y) / (y1 - y2);

getPattern(ctx, owner, shadingFill) {
getPattern(ctx, owner, inverse, shadingFill = false) {
applyBoundingBox(ctx, this._bbox);

@@ -459,4 +466,20 @@ let scale;

this.setFillAndStrokeStyleToContext(graphics, paintType, color);
let adjustedX0 = x0;
let adjustedY0 = y0;
let adjustedX1 = x1;
let adjustedY1 = y1;
if (x0 < 0) {
adjustedX0 = 0;
adjustedX1 += Math.abs(x0);
}
if (y0 < 0) {
adjustedY0 = 0;
adjustedY1 += Math.abs(y0);
}
tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
this.clipBbox(graphics, bbox, x0, y0, x1, y1);
this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();

@@ -468,3 +491,5 @@ graphics.executeOperatorList(operatorList);

scaleX: dimx.scale,
scaleY: dimy.scale
scaleY: dimy.scale,
offsetX: adjustedX0,
offsetY: adjustedY0
};

@@ -490,10 +515,8 @@ }

clipBbox(graphics, bbox, x0, y0, x1, y1) {
if (Array.isArray(bbox) && bbox.length === 4) {
const bboxWidth = x1 - x0;
const bboxHeight = y1 - y0;
graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
graphics.clip();
graphics.endPath();
}
clipBbox(graphics, x0, y0, x1, y1) {
const bboxWidth = x1 - x0;
const bboxHeight = y1 - y0;
graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
graphics.clip();
graphics.endPath();
}

@@ -528,5 +551,4 @@

getPattern(ctx, owner, shadingFill) {
ctx = this.ctx;
let matrix = ctx.mozCurrentTransformInverse;
getPattern(ctx, owner, inverse, shadingFill = false) {
let matrix = inverse;

@@ -542,6 +564,13 @@ if (!shadingFill) {

const temporaryPatternCanvas = this.createPatternCanvas(owner);
let domMatrix = createMatrix(matrix);
let domMatrix = new DOMMatrix(matrix);
domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
pattern.setTransform(domMatrix);
try {
pattern.setTransform(domMatrix);
} catch (ex) {
(0, _util.warn)(`TilingPattern.getPattern: "${ex?.message}".`);
}
return pattern;

@@ -548,0 +577,0 @@ }

@@ -1031,6 +1031,4 @@ /**

const [tx0, ty0] = _util.Util.applyTransform([x0, y0], matrix);
const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
const [tx1, ty1] = _util.Util.applyTransform([x1, y1], matrix);
const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);

@@ -1037,0 +1035,0 @@

@@ -30,4 +30,4 @@ /**

class XfaLayer {
static setupStorage(html, fieldId, element, storage) {
const storedData = storage.getValue(fieldId, {
static setupStorage(html, id, element, storage, intent) {
const storedData = storage.getValue(id, {
value: null

@@ -38,5 +38,12 @@ });

case "textarea":
html.textContent = storedData.value !== null ? storedData.value : "";
if (storedData.value !== null) {
html.textContent = storedData.value;
}
if (intent === "print") {
break;
}
html.addEventListener("input", event => {
storage.setValue(fieldId, {
storage.setValue(id, {
value: event.target.value

@@ -48,28 +55,27 @@ });

case "input":
if (storedData.value !== null) {
html.setAttribute("value", storedData.value);
}
if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
if (storedData.value === element.attributes.xfaOn) {
html.setAttribute("checked", true);
}
if (element.attributes.type === "radio") {
if (intent === "print") {
break;
}
html.addEventListener("change", event => {
const {
target
} = event;
for (const radio of document.getElementsByName(target.name)) {
if (radio !== target) {
const id = radio.id;
storage.setValue(id.split("-")[0], {
value: false
});
}
}
storage.setValue(fieldId, {
value: target.checked
storage.setValue(id, {
value: event.target.getAttribute("xfaOn")
});
});
} else {
if (storedData.value !== null) {
html.setAttribute("value", storedData.value);
}
if (intent === "print") {
break;
}
html.addEventListener("input", event => {
storage.setValue(fieldId, {
storage.setValue(id, {
value: event.target.value

@@ -93,4 +99,4 @@ });

const options = event.target.options;
const value = options.selectedIndex === -1 ? null : options[options.selectedIndex].value;
storage.setValue(fieldId, {
const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
storage.setValue(id, {
value

@@ -103,3 +109,3 @@ });

static setAttributes(html, element, storage) {
static setAttributes(html, element, storage, intent) {
const {

@@ -109,4 +115,8 @@ attributes

if (attributes.type === "radio") {
attributes.name = `${attributes.name}-${intent}`;
}
for (const [key, value] of Object.entries(attributes)) {
if (value === null || value === undefined || key === "fieldId") {
if (value === null || value === undefined || key === "dataId") {
continue;

@@ -118,2 +128,4 @@ }

html.textContent = value;
} else if (key === "class") {
html.setAttribute(key, value.join(" "));
} else {

@@ -127,4 +139,4 @@ html.setAttribute(key, value);

if (storage && attributes.fieldId !== undefined) {
this.setupStorage(html, attributes.fieldId, element, storage);
if (storage && attributes.dataId) {
this.setupStorage(html, attributes.dataId, element, storage);
}

@@ -136,2 +148,3 @@ }

const root = parameters.xfa;
const intent = parameters.intent || "display";
const rootHtml = document.createElement(root.name);

@@ -146,4 +159,4 @@

rootDiv.appendChild(rootHtml);
const coeffs = parameters.viewport.transform.join(",");
rootDiv.style.transform = `matrix(${coeffs})`;
const transform = `matrix(${parameters.viewport.transform.join(",")})`;
rootDiv.style.transform = transform;
rootDiv.setAttribute("class", "xfaLayer xfaFont");

@@ -174,7 +187,14 @@

const childHtml = document.createElement(name);
let childHtml;
if (child?.attributes?.xmlns) {
childHtml = document.createElementNS(child.attributes.xmlns, name);
} else {
childHtml = document.createElement(name);
}
html.appendChild(childHtml);
if (child.attributes) {
this.setAttributes(childHtml, child, storage);
this.setAttributes(childHtml, child, storage, intent);
}

@@ -188,2 +208,6 @@

}
for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
el.setAttribute("readOnly", true);
}
}

@@ -190,0 +214,0 @@

@@ -120,5 +120,3 @@ /**

setAttribute: function DOMElement_setAttribute(name, value) {
value = value || "";
value = xmlEncode(value);
this.attributes[name] = value;
this.attributes[name] = value || "";
},

@@ -125,0 +123,0 @@ setAttributeNS: function DOMElement_setAttributeNS(NS, name, value) {

@@ -45,2 +45,8 @@ /**

});
Object.defineProperty(exports, "getXfaPageViewport", {
enumerable: true,
get: function () {
return _display_utils.getXfaPageViewport;
}
});
Object.defineProperty(exports, "isPdfFile", {

@@ -208,8 +214,2 @@ enumerable: true,

});
Object.defineProperty(exports, "apiCompatibilityParams", {
enumerable: true,
get: function () {
return _api_compatibility.apiCompatibilityParams;
}
});
Object.defineProperty(exports, "GlobalWorkerOptions", {

@@ -248,6 +248,6 @@ enumerable: true,

var _api_compatibility = require("./display/api_compatibility.js");
var _worker_options = require("./display/worker_options.js");
var _is_node = require("./shared/is_node.js");
var _text_layer = require("./display/text_layer.js");

@@ -259,12 +259,10 @@

const pdfjsVersion = '2.9.359';
const pdfjsBuild = 'e667c8cbc';
const pdfjsVersion = '2.10.377';
const pdfjsBuild = '156762c48';
{
const {
isNodeJS
} = require("./shared/is_node.js");
if (_is_node.isNodeJS) {
const {
PDFNodeStream
} = require("./display/node_stream.js");
if (isNodeJS) {
const PDFNodeStream = require("./display/node_stream.js").PDFNodeStream;
(0, _api.setPDFNetworkStreamFactory)(params => {

@@ -274,12 +272,12 @@ return new PDFNodeStream(params);

} else {
const PDFNetworkStream = require("./display/network.js").PDFNetworkStream;
const {
PDFNetworkStream
} = require("./display/network.js");
let PDFFetchStream;
const {
PDFFetchStream
} = require("./display/fetch_stream.js");
if ((0, _display_utils.isFetchSupported)()) {
PDFFetchStream = require("./display/fetch_stream.js").PDFFetchStream;
}
(0, _api.setPDFNetworkStreamFactory)(params => {
if (PDFFetchStream && (0, _display_utils.isValidFetchUrl)(params.url)) {
if ((0, _display_utils.isValidFetchUrl)(params.url)) {
return new PDFFetchStream(params);

@@ -286,0 +284,0 @@ }

@@ -36,3 +36,3 @@ /**

const pdfjsVersion = '2.9.359';
const pdfjsBuild = 'e667c8cbc';
const pdfjsVersion = '2.10.377';
const pdfjsBuild = '156762c48';

@@ -6,3 +6,3 @@ It's *very highly* recommended to *not* use these files, but rather use the

Please note that the "lib" build target exists mostly to enable unit-testing in
Node.js/Travis, and that you'll need to handle e.g. any necessary polyfills
Node.js/GitHub, and that you'll need to handle e.g. any necessary polyfills
and/or Node.js dependencies yourself if using the files in this folder.

@@ -237,2 +237,3 @@ /**

TYPE1: "TYPE1",
TYPE1STANDARD: "TYPE1STANDARD",
TYPE1C: "TYPE1C",

@@ -239,0 +240,0 @@ CIDFONTTYPE0: "CIDFONTTYPE0",

@@ -248,3 +248,3 @@ /**

expect(reason instanceof _util.FormatError).toEqual(true);
expect(reason.message).toEqual("XObject must be referred to by name.");
expect(reason.message).toEqual("XObject should be a stream");
}

@@ -251,0 +251,0 @@ });

@@ -37,3 +37,3 @@ /**

async function initializePDFJS(callback) {
await Promise.all(["pdfjs-test/unit/annotation_spec.js", "pdfjs-test/unit/annotation_storage_spec.js", "pdfjs-test/unit/api_spec.js", "pdfjs-test/unit/bidi_spec.js", "pdfjs-test/unit/cff_parser_spec.js", "pdfjs-test/unit/cmap_spec.js", "pdfjs-test/unit/colorspace_spec.js", "pdfjs-test/unit/core_utils_spec.js", "pdfjs-test/unit/crypto_spec.js", "pdfjs-test/unit/custom_spec.js", "pdfjs-test/unit/default_appearance_spec.js", "pdfjs-test/unit/display_svg_spec.js", "pdfjs-test/unit/display_utils_spec.js", "pdfjs-test/unit/document_spec.js", "pdfjs-test/unit/encodings_spec.js", "pdfjs-test/unit/evaluator_spec.js", "pdfjs-test/unit/function_spec.js", "pdfjs-test/unit/fetch_stream_spec.js", "pdfjs-test/unit/message_handler_spec.js", "pdfjs-test/unit/metadata_spec.js", "pdfjs-test/unit/murmurhash3_spec.js", "pdfjs-test/unit/network_spec.js", "pdfjs-test/unit/network_utils_spec.js", "pdfjs-test/unit/parser_spec.js", "pdfjs-test/unit/pdf_find_controller_spec.js", "pdfjs-test/unit/pdf_find_utils_spec.js", "pdfjs-test/unit/pdf_history_spec.js", "pdfjs-test/unit/primitives_spec.js", "pdfjs-test/unit/scripting_spec.js", "pdfjs-test/unit/stream_spec.js", "pdfjs-test/unit/struct_tree_spec.js", "pdfjs-test/unit/type1_parser_spec.js", "pdfjs-test/unit/ui_utils_spec.js", "pdfjs-test/unit/unicode_spec.js", "pdfjs-test/unit/util_spec.js", "pdfjs-test/unit/writer_spec.js", "pdfjs-test/unit/xfa_formcalc_spec.js", "pdfjs-test/unit/xfa_parser_spec.js", "pdfjs-test/unit/xfa_tohtml_spec.js", "pdfjs-test/unit/xml_spec.js"].map(function (moduleName) {
await Promise.all(["pdfjs-test/unit/annotation_spec.js", "pdfjs-test/unit/annotation_storage_spec.js", "pdfjs-test/unit/api_spec.js", "pdfjs-test/unit/bidi_spec.js", "pdfjs-test/unit/cff_parser_spec.js", "pdfjs-test/unit/cmap_spec.js", "pdfjs-test/unit/colorspace_spec.js", "pdfjs-test/unit/core_utils_spec.js", "pdfjs-test/unit/crypto_spec.js", "pdfjs-test/unit/custom_spec.js", "pdfjs-test/unit/default_appearance_spec.js", "pdfjs-test/unit/display_svg_spec.js", "pdfjs-test/unit/display_utils_spec.js", "pdfjs-test/unit/document_spec.js", "pdfjs-test/unit/encodings_spec.js", "pdfjs-test/unit/evaluator_spec.js", "pdfjs-test/unit/function_spec.js", "pdfjs-test/unit/fetch_stream_spec.js", "pdfjs-test/unit/message_handler_spec.js", "pdfjs-test/unit/metadata_spec.js", "pdfjs-test/unit/murmurhash3_spec.js", "pdfjs-test/unit/network_spec.js", "pdfjs-test/unit/network_utils_spec.js", "pdfjs-test/unit/parser_spec.js", "pdfjs-test/unit/pdf_find_controller_spec.js", "pdfjs-test/unit/pdf_find_utils_spec.js", "pdfjs-test/unit/pdf_history_spec.js", "pdfjs-test/unit/primitives_spec.js", "pdfjs-test/unit/scripting_spec.js", "pdfjs-test/unit/stream_spec.js", "pdfjs-test/unit/struct_tree_spec.js", "pdfjs-test/unit/type1_parser_spec.js", "pdfjs-test/unit/ui_utils_spec.js", "pdfjs-test/unit/unicode_spec.js", "pdfjs-test/unit/util_spec.js", "pdfjs-test/unit/writer_spec.js", "pdfjs-test/unit/xfa_formcalc_spec.js", "pdfjs-test/unit/xfa_parser_spec.js", "pdfjs-test/unit/xfa_serialize_data_spec.js", "pdfjs-test/unit/xfa_tohtml_spec.js", "pdfjs-test/unit/xml_spec.js"].map(function (moduleName) {
return import(moduleName);

@@ -40,0 +40,0 @@ }));

@@ -52,2 +52,12 @@ /**

});
it("should create only one object for *empty* names and cache it", function () {
const firstEmpty = _primitives.Name.get("");
const secondEmpty = _primitives.Name.get("");
const normalName = _primitives.Name.get("string");
expect(firstEmpty).toBe(secondEmpty);
expect(firstEmpty).not.toBe(normalName);
});
});

@@ -427,2 +437,9 @@ describe("Cmd", function () {

});
it("handles *empty* names, with name check", function () {
const emptyName = _primitives.Name.get("");
expect((0, _primitives.isName)(emptyName)).toEqual(true);
expect((0, _primitives.isName)(emptyName, "")).toEqual(true);
expect((0, _primitives.isName)(emptyName, "string")).toEqual(false);
});
});

@@ -429,0 +446,0 @@ describe("isCmd", function () {

@@ -30,3 +30,3 @@ /**

exports.isEmptyObj = isEmptyObj;
exports.XRefMock = exports.TEST_PDFS_PATH = exports.DefaultFileReaderFactory = exports.CMAP_PARAMS = void 0;
exports.XRefMock = exports.TEST_PDFS_PATH = exports.STANDARD_FONT_DATA_URL = exports.DefaultFileReaderFactory = exports.CMAP_PARAMS = void 0;

@@ -50,2 +50,4 @@ var _primitives = require("../../core/primitives.js");

exports.CMAP_PARAMS = CMAP_PARAMS;
const STANDARD_FONT_DATA_URL = _is_node.isNodeJS ? "./external/standard_fonts/" : "../../external/standard_fonts/";
exports.STANDARD_FONT_DATA_URL = STANDARD_FONT_DATA_URL;

@@ -89,2 +91,3 @@ class DOMFileReaderFactory {

params.url = _is_node.isNodeJS ? TEST_PDFS_PATH + filename : new URL(TEST_PDFS_PATH + filename, window.location).href;
params.standardFontDataUrl = STANDARD_FONT_DATA_URL;

@@ -91,0 +94,0 @@ for (const option in options) {

@@ -264,2 +264,37 @@ /**

});
it("should parse a xfa document and parse CDATA when needed", function () {
const xml = `
<?xml version="1.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3">
<subform>
<field>
<extras>
<exData contentType="text/html" name="foo">
<![CDATA[<body xmlns="http://www.w3.org/1999/xhtml">
<span>hello</span></body>]]>
</exData>
</extra>
</field>
</subform>
</template>
</xdp:xdp>
`;
const root = new _parser.XFAParser().parse(xml);
const exdata = (0, _som.searchNode)(root, root, "foo")[0];
const body = exdata[_xfa_object.$dump]().$content[_xfa_object.$dump]();
const expected = {
$name: "body",
attributes: {},
children: [{
$content: "hello",
$name: "span",
attributes: {},
children: []
}]
};
expect(body).toEqual(expected);
});
it("should parse a xfa document and apply some prototypes", function () {

@@ -321,2 +356,60 @@ const xml = `

});
it("should parse a xfa document and apply some prototypes through usehref", function () {
const xml = `
<?xml version="1.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3">
<subform>
<proto>
<draw name="foo">
<font typeface="Foo" size="123pt" weight="bold" posture="italic">
<fill>
<color value="1,2,3"/>
</fill>
</font>
</draw>
</proto>
<field>
<font usehref=".#som($template.#subform.foo.#font)"/>
</field>
<field>
<font usehref=".#som($template.#subform.foo.#font)" size="456pt" weight="bold" posture="normal">
<fill>
<color value="4,5,6"/>
</fill>
<extras id="id2"/>
</font>
</field>
</subform>
</template>
</xdp:xdp>
`;
const root = new _parser.XFAParser().parse(xml)[_xfa_object.$dump]();
let font = root.template.subform.field[0].font;
expect(font.typeface).toEqual("Foo");
expect(font.overline).toEqual(0);
expect(font.size).toEqual(123);
expect(font.weight).toEqual("bold");
expect(font.posture).toEqual("italic");
expect(font.fill.color.value).toEqual({
r: 1,
g: 2,
b: 3
});
expect(font.extras).toEqual(undefined);
font = root.template.subform.field[1].font;
expect(font.typeface).toEqual("Foo");
expect(font.overline).toEqual(0);
expect(font.size).toEqual(456);
expect(font.weight).toEqual("bold");
expect(font.posture).toEqual("normal");
expect(font.fill.color.value).toEqual({
r: 4,
g: 5,
b: 6
});
expect(font.extras.id).toEqual("id2");
});
it("should parse a xfa document with xhtml", function () {

@@ -663,2 +756,51 @@ const xml = `

});
it("should make a basic binding and create a non-existing node", function () {
const xml = `
<?xml version="1.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3">
<subform name="A" mergeMode="matchTemplate">
<subform name="B">
<field name="C">
</field>
<field name="D">
<value>
<text>foobar</text>
</value>
</field>
</subform>
</subform>
</template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:data>
<A>
</A>
</xfa:data>
</xfa:datasets>
</xdp:xdp>
`;
const root = new _parser.XFAParser().parse(xml);
const binder = new _bind.Binder(root);
const form = binder.bind();
const data = binder.getData();
expect((0, _som.searchNode)(form, form, "A.B.D.value.text")[0][_xfa_object.$dump]().$content).toBe("foobar");
const expected = {
$name: "A",
attributes: {},
children: [{
$name: "B",
attributes: {},
children: [{
$name: "C",
attributes: {},
children: []
}, {
$name: "D",
attributes: {},
children: []
}]
}]
};
expect((0, _som.searchNode)(data, data, "A")[0][_xfa_object.$dump]()).toEqual(expected);
});
it("should make another basic binding", function () {

@@ -1006,3 +1148,93 @@ const xml = `

});
it("should make binding and create nodes in data with some bind tag", function () {
const xml = `
<?xml version="1.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3">
<subform name="root" mergeMode="matchTemplate">
<subform name="A">
<occur max="-1"/>
<bind ref="$.root.foo[*]" match="dataRef"/>
</subform>
<subform name="B">
<occur max="2"/>
<bind ref="$.root.bar[2]" match="dataRef"/>
</subform>
</subform>
</template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:data>
<root>
</root>
</xfa:data>
</xfa:datasets>
</xdp:xdp>
`;
const root = new _parser.XFAParser().parse(xml);
const binder = new _bind.Binder(root);
binder.bind();
const data = binder.getData();
const expected = {
$name: "root",
children: [{
$name: "root",
children: [{
$name: "foo",
children: [],
attributes: {}
}, {
$name: "bar",
children: [],
attributes: {}
}, {
$name: "bar",
children: [],
attributes: {}
}, {
$name: "bar",
children: [],
attributes: {}
}],
attributes: {}
}],
attributes: {}
};
expect((0, _som.searchNode)(data, data, "root")[0][_xfa_object.$dump]()).toEqual(expected);
});
it("should make a binding with a bindItems", function () {
const xml = `
<?xml version="1.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3">
<subform name="A" mergeMode="matchTemplate">
<subform name="B">
<field name="C">
<ui>
<choicelist/>
</ui>
<bindItems ref="xfa.datasets.foo.bar[*]" labelRef="$" valueRef="oof"/>
</field>
</subform>
</subform>
</template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<foo>
<bar oof="a">1</bar>
<bar oof="b">2</bar>
<bar oof="c">3</bar>
<bar oof="d">4</bar>
<bar oof="e">5</bar>
</foo>
<xfa:data>
<A><B></B></A>
</xfa:data>
</xfa:datasets>
</xdp:xdp>
`;
const root = new _parser.XFAParser().parse(xml);
const form = new _bind.Binder(root).bind();
expect((0, _som.searchNode)(form, form, "A.B.C.items[0].text[*]").map(x => x[_xfa_object.$dump]().$content)).toEqual(["1", "2", "3", "4", "5"]);
expect((0, _som.searchNode)(form, form, "A.B.C.items[1].text[*]").map(x => x[_xfa_object.$dump]().$content)).toEqual(["a", "b", "c", "d", "e"]);
});
});
});

@@ -27,2 +27,22 @@ /**

describe("XFAFactory", function () {
function searchHtmlNode(root, name, value) {
if (root[name] === value) {
return root;
}
if (!root.children) {
return null;
}
for (const child of root.children) {
const node = searchHtmlNode(child, name, value);
if (node) {
return node;
}
}
return null;
}
describe("toHTML", function () {

@@ -40,2 +60,3 @@ it("should convert some basic properties to CSS", function () {

<draw y="1pt" w="11pt" h="22pt" rotate="90" x="2pt">
<assist><toolTip>A tooltip !!</toolTip></assist>
<font size="7pt" typeface="FooBar" baselineShift="2pt">

@@ -53,7 +74,14 @@ <fill>

</pageSet>
<subform name="first">
</subform>
<subform name="second">
<breakBefore targetType="pageArea" startNew="1"/>
<subform>
<draw w="1pt" h="1pt"><value><text>foo</text></value></draw>
</subform>
</subform>
<subform name="third">
<breakBefore targetType="pageArea" startNew="1"/>
<subform>
<draw w="1pt" h="1pt"><value><text>bar</text></value></draw>
</subform>
</subform>
</subform>

@@ -70,4 +98,6 @@ </template>

});
factory.setFonts([]);
expect(factory.numberPages).toEqual(2);
const page1 = factory.getPage(0);
const pages = factory.getPages();
const page1 = pages.children[0];
expect(page1.attributes.style).toEqual({

@@ -78,4 +108,4 @@ height: "789px",

expect(page1.children.length).toEqual(2);
const container = page1.children[0];
expect(container.attributes.class).toEqual("xfaContentarea");
const container = page1.children[1];
expect(container.attributes.class).toEqual(["xfaContentarea"]);
expect(container.attributes.style).toEqual({

@@ -85,28 +115,165 @@ height: "789px",

left: "123px",
top: "0px",
position: "absolute"
top: "0px"
});
const wrapper = page1.children[1];
const wrapper = page1.children[0];
const draw = wrapper.children[0];
expect(wrapper.attributes.class).toEqual("xfaWrapper");
expect(wrapper.attributes.class).toEqual(["xfaWrapper"]);
expect(wrapper.attributes.style).toEqual({
alignSelf: "start",
height: "22px",
left: "2px",
position: "absolute",
top: "1px"
top: "1px",
transform: "rotate(-90deg)",
transformOrigin: "top left",
width: "11px"
});
expect(draw.attributes.class).toEqual("xfaDraw xfaFont");
expect(draw.attributes.class).toEqual(["xfaDraw", "xfaFont", "xfaWrapped"]);
expect(draw.attributes.title).toEqual("A tooltip !!");
expect(draw.attributes.style).toEqual({
color: "#0c1722",
fontFamily: "FooBar",
fontFamily: '"FooBar"',
fontKerning: "none",
letterSpacing: "0px",
fontStyle: "normal",
fontWeight: "normal",
fontSize: "6.93px",
height: "22px",
padding: "1px 4px 2px 3px",
transform: "rotate(-90deg)",
transformOrigin: "top left",
verticalAlign: "2px",
width: "11px"
verticalAlign: "2px"
});
expect(draw.attributes.style).toEqual(factory.getPage(1).children[1].children[0].attributes.style);
expect(draw.attributes.style).toEqual(pages.children[1].children[0].children[0].attributes.style);
});
it("should have a maxLength property", function () {
const xml = `
<?xml version="1.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3">
<subform name="root" mergeMode="matchTemplate">
<pageSet>
<pageArea>
<contentArea x="0pt" w="456pt" h="789pt"/>
<medium stock="default" short="456pt" long="789pt"/>
<field y="1pt" w="11pt" h="22pt" x="2pt">
<ui>
<textEdit multiLine="0"/>
</ui>
<value>
<text maxChars="123"/>
</value>
</field>
</pageArea>
</pageSet>
<subform name="first">
<draw w="1pt" h="1pt"><value><text>foo</text></value></draw>
</subform>
</subform>
</template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:data>
</xfa:data>
</xfa:datasets>
</xdp:xdp>
`;
const factory = new _factory.XFAFactory({
"xdp:xdp": xml
});
expect(factory.numberPages).toEqual(1);
const pages = factory.getPages();
const field = searchHtmlNode(pages, "name", "input");
expect(field.attributes.maxLength).toEqual(123);
});
it("should have an input or textarea", function () {
const xml = `
<?xml version="1.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3">
<subform name="root" mergeMode="matchTemplate">
<pageSet>
<pageArea>
<contentArea x="123pt" w="456pt" h="789pt"/>
<medium stock="default" short="456pt" long="789pt"/>
<field y="1pt" w="11pt" h="22pt" x="2pt">
<ui>
<textEdit/>
</ui>
</field>
<field y="1pt" w="11pt" h="22pt" x="2pt">
<ui>
<textEdit multiLine="1"/>
</ui>
</field>
</pageArea>
</pageSet>
<subform name="first">
<draw w="1pt" h="1pt"><value><text>foo</text></value></draw>
</subform>
</subform>
</template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:data>
</xfa:data>
</xfa:datasets>
</xdp:xdp>
`;
const factory = new _factory.XFAFactory({
"xdp:xdp": xml
});
expect(factory.numberPages).toEqual(1);
const pages = factory.getPages();
const field1 = searchHtmlNode(pages, "name", "input");
expect(field1).not.toEqual(null);
const field2 = searchHtmlNode(pages, "name", "textarea");
expect(field2).not.toEqual(null);
});
});
it("should have an input or textarea", function () {
const xml = `
<?xml version="1.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3">
<subform name="root" mergeMode="matchTemplate">
<pageSet>
<pageArea>
<contentArea x="123pt" w="456pt" h="789pt"/>
<medium stock="default" short="456pt" long="789pt"/>
<field y="1pt" w="11pt" h="22pt" x="2pt">
<ui>
<textEdit multiLine="1"/>
</ui>
</field>
</pageArea>
</pageSet>
<subform name="first">
<field y="1pt" w="11pt" h="22pt" x="2pt" name="hello">
<ui>
<textEdit/>
</ui>
<value>
<integer/>
</value>
</field>
</subform>
</subform>
</template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:data>
<toto>
<first>
<hello>123
</hello>
</first>
</toto>
</xfa:data>
</xfa:datasets>
</xdp:xdp>
`;
const factory = new _factory.XFAFactory({
"xdp:xdp": xml
});
expect(factory.numberPages).toEqual(1);
const pages = factory.getPages();
const field1 = searchHtmlNode(pages, "name", "input");
expect(field1).not.toEqual(null);
expect(field1.attributes.value).toEqual("123");
});
});

@@ -188,2 +188,6 @@ /**

},
standardFontDataUrl: {
value: "../web/standard_fonts/",
kind: OptionKind.API
},
verbosity: {

@@ -190,0 +194,0 @@ value: 1,

@@ -111,3 +111,3 @@ /**

const viewerVersion = '2.9.359';
const viewerVersion = '2.10.377';

@@ -114,0 +114,0 @@ if (_pdf.version !== viewerVersion) {

@@ -238,3 +238,3 @@ /**

let i;
pageIndex = pageIndex | 0;
pageIndex |= 0;

@@ -384,4 +384,5 @@ if (selectPanel) {

const glyphs = args[0];
const newArgs = [];
let str = [];
const charCodeRow = c("tr");
const fontCharRow = c("tr");
const unicodeRow = c("tr");

@@ -392,22 +393,30 @@ for (let j = 0; j < glyphs.length; j++) {

if (typeof glyph === "object" && glyph !== null) {
str.push(glyph.fontChar);
charCodeRow.appendChild(c("td", glyph.originalCharCode));
fontCharRow.appendChild(c("td", glyph.fontChar));
unicodeRow.appendChild(c("td", glyph.unicode));
} else {
if (str.length > 0) {
newArgs.push(str.join(""));
str = [];
}
newArgs.push(glyph);
const advanceEl = c("td", glyph);
advanceEl.classList.add("advance");
charCodeRow.appendChild(advanceEl);
fontCharRow.appendChild(c("td"));
unicodeRow.appendChild(c("td"));
}
}
if (str.length > 0) {
newArgs.push(str.join(""));
}
decArgs = [newArgs];
decArgs = c("td");
const table = c("table");
table.classList.add("showText");
decArgs.appendChild(table);
table.appendChild(charCodeRow);
table.appendChild(fontCharRow);
table.appendChild(unicodeRow);
}
line.appendChild(c("td", fn));
line.appendChild(c("td", JSON.stringify(simplifyArgs(decArgs))));
if (decArgs instanceof HTMLElement) {
line.appendChild(decArgs);
} else {
line.appendChild(c("td", JSON.stringify(simplifyArgs(decArgs))));
}
}

@@ -414,0 +423,0 @@

@@ -31,2 +31,4 @@ /**

var _print_utils = require("./print_utils.js");
var _app = require("./app.js");

@@ -40,2 +42,3 @@

const canvasWrapper = document.createElement("div");
canvasWrapper.className = "printedPage";
canvasWrapper.appendChild(canvas);

@@ -116,2 +119,7 @@ printContainer.appendChild(canvasWrapper);

if (pdfDocument.isPureXfa) {
(0, _print_utils.getXfaHtmlForPrinting)(printContainer, pdfDocument);
return;
}
for (let i = 0, ii = pagesOverview.length; i < ii; ++i) {

@@ -118,0 +126,0 @@ composePage(pdfDocument, i + 1, pagesOverview[i], printContainer, _printResolution, _optionalContentConfigPromise);

@@ -39,3 +39,3 @@ /**

this._ready = new Promise((resolve, reject) => {
webL10n.setLanguage(lang, () => {
webL10n.setLanguage((0, _l10n_utils.fixupLangCode)(lang), () => {
resolve(webL10n);

@@ -42,0 +42,0 @@ });

@@ -27,2 +27,3 @@ /**

});
exports.fixupLangCode = fixupLangCode;
exports.getL10nFallback = getL10nFallback;

@@ -97,2 +98,23 @@ exports.NullL10n = void 0;

const PARTIAL_LANG_CODES = {
en: "en-US",
es: "es-ES",
fy: "fy-NL",
ga: "ga-IE",
gu: "gu-IN",
hi: "hi-IN",
hy: "hy-AM",
nb: "nb-NO",
ne: "ne-NP",
nn: "nn-NO",
pa: "pa-IN",
pt: "pt-PT",
sv: "sv-SE",
zh: "zh-CN"
};
function fixupLangCode(langCode) {
return PARTIAL_LANG_CODES[langCode?.toLowerCase()] || langCode;
}
function formatL10nValue(text, args) {

@@ -99,0 +121,0 @@ if (!args) {

@@ -46,2 +46,3 @@ /**

const CHARACTERS_TO_NORMALIZE = {
"\u2010": "-",
"\u2018": "'",

@@ -215,2 +216,3 @@ "\u2019": "'",

element = null,
selectedLeft = 0,
pageIndex = -1,

@@ -230,3 +232,3 @@ matchIndex = -1

top: MATCH_SCROLL_OFFSET_TOP,
left: MATCH_SCROLL_OFFSET_LEFT
left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT
};

@@ -233,0 +235,0 @@ (0, _ui_utils.scrollIntoView)(element, spot, true);

@@ -36,3 +36,2 @@ /**

externalLinkRel = null,
externalLinkEnabled = true,
ignoreDestinationZoom = false

@@ -43,3 +42,3 @@ } = {}) {

this.externalLinkRel = externalLinkRel;
this.externalLinkEnabled = externalLinkEnabled;
this.externalLinkEnabled = true;
this._ignoreDestinationZoom = ignoreDestinationZoom;

@@ -91,3 +90,3 @@ this.baseUrl = null;

if (destRef instanceof Object) {
if (typeof destRef === "object" && destRef !== null) {
pageNumber = this._cachedPageNumber(destRef);

@@ -94,0 +93,0 @@

@@ -315,3 +315,3 @@ /**

if (destRef instanceof Object) {
if (typeof destRef === "object" && destRef !== null) {
pageNumber = this.linkService._cachedPageNumber(destRef);

@@ -318,0 +318,0 @@

@@ -161,4 +161,11 @@ /**

reset(keepZoomLayer = false, keepAnnotations = false) {
this.cancelRendering(keepAnnotations);
reset({
keepZoomLayer = false,
keepAnnotationLayer = false,
keepXfaLayer = false
} = {}) {
this.cancelRendering({
keepAnnotationLayer,
keepXfaLayer
});
this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL;

@@ -168,6 +175,6 @@ const div = this.div;

div.style.height = Math.floor(this.viewport.height) + "px";
const childNodes = div.childNodes;
const currentZoomLayerNode = keepZoomLayer && this.zoomLayer || null;
const currentAnnotationNode = keepAnnotations && this.annotationLayer?.div || null;
const currentXfaLayerNode = this.xfaLayer?.div || null;
const childNodes = div.childNodes,
zoomLayerNode = keepZoomLayer && this.zoomLayer || null,
annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null,
xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null;

@@ -177,4 +184,7 @@ for (let i = childNodes.length - 1; i >= 0; i--) {

if (currentZoomLayerNode === node || currentAnnotationNode === node || currentXfaLayerNode === node) {
continue;
switch (node) {
case zoomLayerNode:
case annotationLayerNode:
case xfaLayerNode:
continue;
}

@@ -187,10 +197,11 @@

if (currentAnnotationNode) {
if (annotationLayerNode) {
this.annotationLayer.hide();
} else if (this.annotationLayer) {
this.annotationLayer.cancel();
this.annotationLayer = null;
}
if (!currentZoomLayerNode) {
if (xfaLayerNode) {
this.xfaLayer.hide();
}
if (!zoomLayerNode) {
if (this.canvas) {

@@ -238,3 +249,7 @@ this.paintedViewportMap.delete(this.canvas);

if (this.svg) {
this.cssTransform(this.svg, true);
this.cssTransform({
target: this.svg,
redrawAnnotationLayer: true,
redrawXfaLayer: true
});
this.eventBus.dispatch("pagerendered", {

@@ -262,3 +277,7 @@ source: this,

if (this.useOnlyCssZoom || this.hasRestrictedScaling && isScalingRestricted) {
this.cssTransform(this.canvas, true);
this.cssTransform({
target: this.canvas,
redrawAnnotationLayer: true,
redrawXfaLayer: true
});
this.eventBus.dispatch("pagerendered", {

@@ -281,9 +300,18 @@ source: this,

if (this.zoomLayer) {
this.cssTransform(this.zoomLayer.firstChild);
this.cssTransform({
target: this.zoomLayer.firstChild
});
}
this.reset(true, true);
this.reset({
keepZoomLayer: true,
keepAnnotationLayer: true,
keepXfaLayer: true
});
}
cancelRendering(keepAnnotations = false) {
cancelRendering({
keepAnnotationLayer = false,
keepXfaLayer = false
} = {}) {
if (this.paintTask) {

@@ -301,3 +329,3 @@ this.paintTask.cancel();

if (!keepAnnotations && this.annotationLayer) {
if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) {
this.annotationLayer.cancel();

@@ -307,2 +335,7 @@ this.annotationLayer = null;

if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) {
this.xfaLayer.cancel();
this.xfaLayer = null;
}
if (this._onTextLayerRendered) {

@@ -315,3 +348,7 @@ this.eventBus._off("textlayerrendered", this._onTextLayerRendered);

cssTransform(target, redrawAnnotations = false) {
cssTransform({
target,
redrawAnnotationLayer = false,
redrawXfaLayer = false
}) {
const width = this.viewport.width;

@@ -376,7 +413,7 @@ const height = this.viewport.height;

if (redrawAnnotations && this.annotationLayer) {
if (redrawAnnotationLayer && this.annotationLayer) {
this._renderAnnotationLayer();
}
if (this.xfaLayer) {
if (redrawXfaLayer && this.xfaLayer) {
this._renderXfaLayer();

@@ -450,2 +487,7 @@ }

this.textLayer = textLayer;
if (this.xfaLayer?.div) {
div.appendChild(this.xfaLayer.div);
}
let renderContinueCallback = null;

@@ -452,0 +494,0 @@

@@ -31,2 +31,4 @@ /**

var _print_utils = require("./print_utils.js");
var _viewer_compatibility = require("./viewer_compatibility.js");

@@ -120,2 +122,7 @@

renderPages() {
if (this.pdfDocument.isPureXfa) {
(0, _print_utils.getXfaHtmlForPrinting)(this.printContainer, this.pdfDocument);
return Promise.resolve();
}
const pageCount = this.pagesOverview.length;

@@ -156,2 +163,3 @@

const wrapper = document.createElement("div");
wrapper.className = "printedPage";
wrapper.appendChild(img);

@@ -158,0 +166,0 @@ this.printContainer.appendChild(wrapper);

@@ -48,3 +48,2 @@ /**

this._mouseState = Object.create(null);
this._pageEventsReady = false;
this._ready = false;

@@ -83,3 +82,9 @@ this._eventBus = eventBus;

this._scripting = this._createScripting();
try {
this._scripting = this._createScripting();
} catch (error) {
console.error(`PDFScriptingManager.setDocument: "${error?.message}".`);
await this._destroyScripting();
return;
}

@@ -327,6 +332,5 @@ this._internalEvents.set("updatefromsandbox", event => {

this._closeCapability = (0, _pdf.createPromiseCapability)();
this._pageEventsReady = true;
}
if (!this._pageEventsReady) {
if (!this._closeCapability) {
return;

@@ -367,3 +371,3 @@ }

if (!this._pageEventsReady) {
if (!this._closeCapability) {
return;

@@ -458,3 +462,2 @@ }

delete this._mouseState.isDown;
this._pageEventsReady = false;
this._ready = false;

@@ -461,0 +464,0 @@ this._destroyCapability?.resolve();

@@ -156,3 +156,3 @@ /**

const pdfjsVersion = '2.9.359';
const pdfjsBuild = 'e667c8cbc';
const pdfjsVersion = '2.10.377';
const pdfjsBuild = '156762c48';

@@ -208,3 +208,3 @@ /**

textDivs[divIdx].textContent = "";
appendTextToDiv(divIdx, 0, begin.offset, className);
return appendTextToDiv(divIdx, 0, begin.offset, className);
}

@@ -219,9 +219,10 @@

const span = document.createElement("span");
span.className = className;
span.className = `${className} appended`;
span.appendChild(node);
div.appendChild(span);
return;
return className.includes("selected") ? span.offsetLeft : 0;
}
div.appendChild(node);
return 0;
}

@@ -245,11 +246,4 @@

const highlightSuffix = isSelected ? " selected" : "";
let selectedLeft = 0;
if (isSelected) {
findController.scrollMatchIntoView({
element: textDivs[begin.divIdx],
pageIndex: pageIdx,
matchIndex: selectedMatchIdx
});
}
if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {

@@ -266,5 +260,5 @@ if (prevEnd !== null) {

if (begin.divIdx === end.divIdx) {
appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix);
selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix);
} else {
appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix);
selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix);

@@ -279,2 +273,11 @@ for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {

prevEnd = end;
if (isSelected) {
findController.scrollMatchIntoView({
element: textDivs[begin.divIdx],
selectedLeft,
pageIndex: pageIdx,
matchIndex: selectedMatchIdx
});
}
}

@@ -281,0 +284,0 @@

@@ -124,3 +124,3 @@ /**

function scrollIntoView(element, spot, skipOverflowHiddenElements = false) {
function scrollIntoView(element, spot, scrollMatches = false) {
let parent = element.offsetParent;

@@ -136,8 +136,3 @@

while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || skipOverflowHiddenElements && getComputedStyle(parent).overflow === "hidden") {
if (parent.dataset._scaleY) {
offsetY /= parent.dataset._scaleY;
offsetX /= parent.dataset._scaleX;
}
while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) {
offsetY += parent.offsetTop;

@@ -144,0 +139,0 @@ offsetX += parent.offsetLeft;

@@ -35,2 +35,3 @@ /**

pdfPage,
xfaHtml,
annotationStorage

@@ -40,2 +41,3 @@ }) {

this.pdfPage = pdfPage;
this.xfaHtml = xfaHtml;
this.annotationStorage = annotationStorage;

@@ -47,2 +49,22 @@ this.div = null;

render(viewport, intent = "display") {
if (intent === "print") {
const parameters = {
viewport: viewport.clone({
dontFlip: true
}),
div: this.div,
xfa: this.xfaHtml,
page: null,
annotationStorage: this.annotationStorage,
intent
};
const div = document.createElement("div");
this.pageDiv.appendChild(div);
parameters.div = div;
_pdf.XfaLayer.render(parameters);
return Promise.resolve();
}
return this.pdfPage.getXfa().then(xfa => {

@@ -60,3 +82,4 @@ if (this._cancelled) {

page: this.pdfPage,
annotationStorage: this.annotationStorage
annotationStorage: this.annotationStorage,
intent
};

@@ -95,7 +118,8 @@

class DefaultXfaLayerFactory {
createXfaLayerBuilder(pageDiv, pdfPage, annotationStorage = null) {
createXfaLayerBuilder(pageDiv, pdfPage, annotationStorage = null, xfaHtml = null) {
return new XfaLayerBuilder({
pageDiv,
pdfPage,
annotationStorage
annotationStorage,
xfaHtml
});

@@ -102,0 +126,0 @@ }

{
"name": "pdfjs-dist",
"version": "2.9.359",
"version": "2.10.377",
"main": "build/pdf.js",
"types": "types/pdf.d.ts",
"types": "types/src/pdf.d.ts",
"description": "Generic build of Mozilla's PDF.js library.",

@@ -7,0 +7,0 @@ "keywords": [

@@ -19,3 +19,3 @@ /* Copyright 2021 Mozilla Foundation

const pdfjs = require("./build/pdf.js");
const PdfjsWorker = require("worker-loader?esModule=false&filename=[name].js!./build/pdf.worker.js");
const PdfjsWorker = require("worker-loader?esModule=false&filename=[name].[contenthash].js!./build/pdf.worker.js");

@@ -22,0 +22,0 @@ if (typeof window !== "undefined" && "Worker" in window) {

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc