Skip to content

Re-factor the PDFDocument.documentInfo method, and remove the isString helper function #14602

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 9 additions & 12 deletions src/core/annotation.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
escapeString,
getModificationDate,
isAscii,
isString,
OPS,
RenderingIntentFlag,
shadow,
Expand Down Expand Up @@ -542,9 +541,8 @@ class Annotation {
* annotation was last modified
*/
setModificationDate(modificationDate) {
this.modificationDate = isString(modificationDate)
? modificationDate
: null;
this.modificationDate =
typeof modificationDate === "string" ? modificationDate : null;
}

/**
Expand Down Expand Up @@ -1121,7 +1119,7 @@ class MarkupAnnotation extends Annotation {
* annotation was originally created
*/
setCreationDate(creationDate) {
this.creationDate = isString(creationDate) ? creationDate : null;
this.creationDate = typeof creationDate === "string" ? creationDate : null;
}

_setDefaultAppearance({
Expand Down Expand Up @@ -1258,9 +1256,8 @@ class WidgetAnnotation extends Annotation {

const defaultAppearance =
getInheritableProperty({ dict, key: "DA" }) || params.acroForm.get("DA");
this._defaultAppearance = isString(defaultAppearance)
? defaultAppearance
: "";
this._defaultAppearance =
typeof defaultAppearance === "string" ? defaultAppearance : "";
data.defaultAppearanceData = parseDefaultAppearance(
this._defaultAppearance
);
Expand Down Expand Up @@ -1305,11 +1302,11 @@ class WidgetAnnotation extends Annotation {
_decodeFormValue(formValue) {
if (Array.isArray(formValue)) {
return formValue
.filter(item => isString(item))
.filter(item => typeof item === "string")
.map(item => stringToPDFString(item));
} else if (formValue instanceof Name) {
return stringToPDFString(formValue.name);
} else if (isString(formValue)) {
} else if (typeof formValue === "string") {
return stringToPDFString(formValue);
}
return null;
Expand Down Expand Up @@ -1788,7 +1785,7 @@ class TextWidgetAnnotation extends WidgetAnnotation {
const dict = params.dict;

// The field value is always a string.
if (!isString(this.data.fieldValue)) {
if (typeof this.data.fieldValue !== "string") {
this.data.fieldValue = "";
}

Expand Down Expand Up @@ -2452,7 +2449,7 @@ class ChoiceWidgetAnnotation extends WidgetAnnotation {
// item is selected or an array of strings if multiple items are selected.
// For consistency in the API and convenience in the display layer, we
// always make the field value an array with zero, one or multiple items.
if (isString(this.data.fieldValue)) {
if (typeof this.data.fieldValue === "string") {
this.data.fieldValue = [this.data.fieldValue];
} else if (!this.data.fieldValue) {
this.data.fieldValue = [];
Expand Down
45 changes: 24 additions & 21 deletions src/core/catalog.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import {
DocumentActionEventType,
FormatError,
info,
isString,
objectSize,
PermissionFlag,
shadow,
Expand Down Expand Up @@ -424,12 +423,14 @@ class Catalog {
const group = this.xref.fetchIfRef(groupRef);
groups.push({
id: groupRef.toString(),
name: isString(group.get("Name"))
? stringToPDFString(group.get("Name"))
: null,
intent: isString(group.get("Intent"))
? stringToPDFString(group.get("Intent"))
: null,
name:
typeof group.get("Name") === "string"
? stringToPDFString(group.get("Name"))
: null,
intent:
typeof group.get("Intent") === "string"
? stringToPDFString(group.get("Intent"))
: null,
});
}
config = this._readOptionalContentConfig(defaultConfig, groupRefs);
Expand Down Expand Up @@ -521,12 +522,14 @@ class Catalog {
MAX_NESTED_LEVELS = 10;

return {
name: isString(config.get("Name"))
? stringToPDFString(config.get("Name"))
: null,
creator: isString(config.get("Creator"))
? stringToPDFString(config.get("Creator"))
: null,
name:
typeof config.get("Name") === "string"
? stringToPDFString(config.get("Name"))
: null,
creator:
typeof config.get("Creator") === "string"
? stringToPDFString(config.get("Creator"))
: null,
baseState:
config.get("BaseState") instanceof Name
? config.get("BaseState").name
Expand Down Expand Up @@ -676,7 +679,7 @@ class Catalog {

if (labelDict.has("P")) {
const p = labelDict.get("P");
if (!isString(p)) {
if (typeof p !== "string") {
throw new FormatError("Invalid prefix in PageLabel dictionary.");
}
prefix = stringToPDFString(p);
Expand Down Expand Up @@ -1467,7 +1470,7 @@ class Catalog {
for (const obj of action.get("Fields") || []) {
if (obj instanceof Ref) {
refs.push(obj.toString());
} else if (isString(obj)) {
} else if (typeof obj === "string") {
fields.push(stringToPDFString(obj));
}
}
Expand Down Expand Up @@ -1499,7 +1502,7 @@ class Catalog {
// We assume that we found a FileSpec dictionary
// and fetch the URL without checking any further.
url = urlDict.get("F") || null;
} else if (isString(urlDict)) {
} else if (typeof urlDict === "string") {
url = urlDict;
}

Expand All @@ -1509,9 +1512,9 @@ class Catalog {
if (remoteDest instanceof Name) {
remoteDest = remoteDest.name;
}
if (isString(url)) {
if (typeof url === "string") {
const baseUrl = url.split("#")[0];
if (isString(remoteDest)) {
if (typeof remoteDest === "string") {
url = baseUrl + "#" + remoteDest;
} else if (Array.isArray(remoteDest)) {
url = baseUrl + "#" + JSON.stringify(remoteDest);
Expand All @@ -1538,7 +1541,7 @@ class Catalog {

if (jsAction instanceof BaseStream) {
js = jsAction.getString();
} else if (isString(jsAction)) {
} else if (typeof jsAction === "string") {
js = jsAction;
}

Expand All @@ -1563,7 +1566,7 @@ class Catalog {
dest = destDict.get("Dest");
}

if (isString(url)) {
if (typeof url === "string") {
const absoluteUrl = createValidAbsoluteUrl(url, docBaseUrl, {
addDefaultProtocol: true,
tryConvertEncoding: true,
Expand All @@ -1577,7 +1580,7 @@ class Catalog {
if (dest instanceof Name) {
dest = dest.name;
}
if (isString(dest) || Array.isArray(dest)) {
if (typeof dest === "string" || Array.isArray(dest)) {
resultObj.dest = dest;
}
}
Expand Down
9 changes: 4 additions & 5 deletions src/core/cmap.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import {
CMapCompressionType,
FormatError,
isString,
unreachable,
warn,
} from "../shared/util.js";
Expand Down Expand Up @@ -767,7 +766,7 @@ const CMapFactory = (function CMapFactoryClosure() {
}

function expectString(obj) {
if (!isString(obj)) {
if (typeof obj !== "string") {
throw new FormatError("Malformed CMap: expected string.");
}
}
Expand Down Expand Up @@ -812,7 +811,7 @@ const CMapFactory = (function CMapFactoryClosure() {
expectString(obj);
const high = strToInt(obj);
obj = lexer.getObj();
if (Number.isInteger(obj) || isString(obj)) {
if (Number.isInteger(obj) || typeof obj === "string") {
const dstLow = Number.isInteger(obj) ? String.fromCharCode(obj) : obj;
cMap.mapBfRange(low, high, dstLow);
} else if (isCmd(obj, "[")) {
Expand Down Expand Up @@ -878,12 +877,12 @@ const CMapFactory = (function CMapFactoryClosure() {
if (isCmd(obj, "endcodespacerange")) {
return;
}
if (!isString(obj)) {
if (typeof obj !== "string") {
break;
}
const low = strToInt(obj);
obj = lexer.getObj();
if (!isString(obj)) {
if (typeof obj !== "string") {
break;
}
const high = strToInt(obj);
Expand Down
83 changes: 44 additions & 39 deletions src/core/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import {
InvalidPDFException,
isArrayBuffer,
isArrayEqual,
isString,
OPS,
PageActionEventType,
RenderingIntentFlag,
Expand Down Expand Up @@ -1129,18 +1128,6 @@ class PDFDocument {
}

get documentInfo() {
const DocumentInfoValidators = {
Title: isString,
Author: isString,
Subject: isString,
Keywords: isString,
Creator: isString,
Producer: isString,
CreationDate: isString,
ModDate: isString,
Trapped: isName,
};

let version = this._version;
if (
typeof version !== "string" ||
Expand Down Expand Up @@ -1172,46 +1159,64 @@ class PDFDocument {
}
info("The document information dictionary is invalid.");
}
if (!(infoDict instanceof Dict)) {
return shadow(this, "documentInfo", docInfo);
}

if (infoDict instanceof Dict) {
// Fill the document info with valid entries from the specification,
// as well as any existing well-formed custom entries.
for (const key of infoDict.getKeys()) {
const value = infoDict.get(key);
for (const key of infoDict.getKeys()) {
const value = infoDict.get(key);

if (DocumentInfoValidators[key]) {
// Make sure the (standard) value conforms to the specification.
if (DocumentInfoValidators[key](value)) {
docInfo[key] =
typeof value !== "string" ? value : stringToPDFString(value);
} else {
info(`Bad value in document info for "${key}".`);
switch (key) {
case "Title":
case "Author":
case "Subject":
case "Keywords":
case "Creator":
case "Producer":
case "CreationDate":
case "ModDate":
if (typeof value === "string") {
docInfo[key] = stringToPDFString(value);
continue;
}
} else {
break;
case "Trapped":
if (value instanceof Name) {
docInfo[key] = value;
continue;
}
break;
default:
// For custom values, only accept white-listed types to prevent
// errors that would occur when trying to send non-serializable
// objects to the main-thread (for example `Dict` or `Stream`).
const customType = typeof value;
let customValue;
if (customType === "string") {
customValue = stringToPDFString(value);
} else if (
value instanceof Name ||
customType === "number" ||
customType === "boolean"
) {
customValue = value;
} else {
info(`Unsupported value in document info for (custom) "${key}".`);
continue;
switch (typeof value) {
case "string":
customValue = stringToPDFString(value);
break;
case "number":
case "boolean":
customValue = value;
break;
default:
if (value instanceof Name) {
customValue = value;
}
break;
}

if (customValue === undefined) {
warn(`Bad value, for custom key "${key}", in Info: ${value}.`);
continue;
}
if (!docInfo.Custom) {
docInfo.Custom = Object.create(null);
}
docInfo.Custom[key] = customValue;
}
continue;
}
warn(`Bad value, for key "${key}", in Info: ${value}.`);
}
return shadow(this, "documentInfo", docInfo);
}
Expand Down
7 changes: 3 additions & 4 deletions src/core/evaluator.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
IDENTITY_MATRIX,
info,
isArrayEqual,
isString,
OPS,
shadow,
stringToPDFString,
Expand Down Expand Up @@ -1784,7 +1783,7 @@ class PartialEvaluator {
var state = stateManager.state;
for (i = 0; i < arrLength; ++i) {
const arrItem = arr[i];
if (isString(arrItem)) {
if (typeof arrItem === "string") {
Array.prototype.push.apply(
combinedGlyphs,
self.handleText(arrItem, state)
Expand Down Expand Up @@ -3974,10 +3973,10 @@ class PartialEvaluator {
let fontName = descriptor.get("FontName");
let baseFont = dict.get("BaseFont");
// Some bad PDFs have a string as the font name.
if (isString(fontName)) {
if (typeof fontName === "string") {
fontName = Name.get(fontName);
}
if (isString(baseFont)) {
if (typeof baseFont === "string") {
baseFont = Name.get(baseFont);
}

Expand Down
4 changes: 2 additions & 2 deletions src/core/murmurhash3.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* Hashes roughly 100 KB per millisecond on i7 3.4 GHz.
*/

import { isArrayBuffer, isString } from "../shared/util.js";
import { isArrayBuffer } from "../shared/util.js";

const SEED = 0xc3d2e1f0;
// Workaround for missing math precision in JS.
Expand All @@ -32,7 +32,7 @@ class MurmurHash3_64 {

update(input) {
let data, length;
if (isString(input)) {
if (typeof input === "string") {
data = new Uint8Array(input.length * 2);
length = 0;
for (let i = 0, ii = input.length; i < ii; i++) {
Expand Down
Loading