Add typescript definitions

This PR adds typescript definitions from the JSDoc already present.
It adds a new gulp-target 'types' that calls 'tsc', the typescript
compiler, to create the definitions.

To use the definitions, users can simply do the following:

```
import {getDocument, GlobalWorkerOptions} from "pdfjs-dist";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";
GlobalWorkerOptions.workerSrc = pdfjsWorker;

const pdf = await getDocument("file:///some.pdf").promise;
```

Co-authored-by: @oBusk
Co-authored-by: @tamuratak
This commit is contained in:
Linus Gasser 2020-07-22 22:38:04 +02:00 committed by Linus Gasser
parent 6537e64cb8
commit f1bbfdc16d
12 changed files with 344 additions and 139 deletions

View File

@ -63,6 +63,7 @@ var GH_PAGES_DIR = BUILD_DIR + "gh-pages/";
var SRC_DIR = "src/"; var SRC_DIR = "src/";
var LIB_DIR = BUILD_DIR + "lib/"; var LIB_DIR = BUILD_DIR + "lib/";
var DIST_DIR = BUILD_DIR + "dist/"; var DIST_DIR = BUILD_DIR + "dist/";
var TYPES_BUILD_DIR = BUILD_DIR + "types/";
var COMMON_WEB_FILES = ["web/images/*.{png,svg,gif,cur}", "web/debugger.js"]; var COMMON_WEB_FILES = ["web/images/*.{png,svg,gif,cur}", "web/debugger.js"];
var MOZCENTRAL_DIFF_FILE = "mozcentral.diff"; var MOZCENTRAL_DIFF_FILE = "mozcentral.diff";
@ -1141,6 +1142,21 @@ gulp.task("jsdoc", function (done) {
}); });
}); });
gulp.task("types", function (done) {
console.log("### Generating typescript definitions using tsc");
var args = [
"target ES2020",
"allowJS",
"declaration",
`outDir ${TYPES_BUILD_DIR}`,
"strict",
"esModuleInterop",
"forceConsistentCasingInFileNames",
"emitDeclarationOnly",
].join(" --");
exec(`node_modules/.bin/tsc --${args} src/pdf.js`, done);
});
function buildLib(defines, dir) { function buildLib(defines, dir) {
// When we create a bundle, webpack is run on the source and it will replace // When we create a bundle, webpack is run on the source and it will replace
// require with __webpack_require__. When we want to use the real require, // require with __webpack_require__. When we want to use the real require,
@ -1336,6 +1352,42 @@ gulp.task(
}) })
); );
gulp.task(
"typestest",
gulp.series(
"testing-pre",
"generic",
"types",
function () {
var packageJsonSrc = packageBowerJson()[0];
var TYPESTEST_DIR = BUILD_DIR + "typestest/";
return merge([
packageJsonSrc.pipe(gulp.dest(TYPESTEST_DIR)),
gulp
.src([
GENERIC_DIR + "build/pdf.js",
GENERIC_DIR + "build/pdf.worker.js",
SRC_DIR + "pdf.worker.entry.js",
])
.pipe(gulp.dest(TYPESTEST_DIR + "build/")),
gulp
.src(TYPES_BUILD_DIR + "**/**")
.pipe(gulp.dest(TYPESTEST_DIR + "build/")),
]);
},
function (done) {
exec(`node_modules/.bin/tsc -p test/types`, function (err, stdout) {
if (err !== null) {
console.log("couldn't compile typescript test: " + stdout);
}
done(err);
});
}
)
);
gulp.task("baseline", function (done) { gulp.task("baseline", function (done) {
console.log(); console.log();
console.log("### Creating baseline environment"); console.log("### Creating baseline environment");
@ -1576,31 +1628,8 @@ gulp.task(
) )
); );
gulp.task( function packageBowerJson() {
"dist-pre",
gulp.series(
"generic",
"generic-es5",
"components",
"components-es5",
"image_decoders",
"lib",
"minified",
function () {
var VERSION = getVersionJSON().version; var VERSION = getVersionJSON().version;
console.log();
console.log("### Cloning baseline distribution");
rimraf.sync(DIST_DIR);
mkdirp.sync(DIST_DIR);
safeSpawnSync("git", ["clone", "--depth", "1", DIST_REPO_URL, DIST_DIR]);
console.log();
console.log("### Overwriting all files");
rimraf.sync(path.join(DIST_DIR, "*"));
// Rebuilding manifests
var DIST_NAME = "pdfjs-dist"; var DIST_NAME = "pdfjs-dist";
var DIST_DESCRIPTION = "Generic build of Mozilla's PDF.js library."; var DIST_DESCRIPTION = "Generic build of Mozilla's PDF.js library.";
var DIST_KEYWORDS = ["Mozilla", "pdf", "pdf.js"]; var DIST_KEYWORDS = ["Mozilla", "pdf", "pdf.js"];
@ -1611,6 +1640,7 @@ gulp.task(
name: DIST_NAME, name: DIST_NAME,
version: VERSION, version: VERSION,
main: "build/pdf.js", main: "build/pdf.js",
types: "build/pdf.d.ts",
description: DIST_DESCRIPTION, description: DIST_DESCRIPTION,
keywords: DIST_KEYWORDS, keywords: DIST_KEYWORDS,
homepage: DIST_HOMEPAGE, homepage: DIST_HOMEPAGE,
@ -1630,10 +1660,6 @@ gulp.task(
url: DIST_REPO_URL, url: DIST_REPO_URL,
}, },
}; };
var packageJsonSrc = createStringSource(
"package.json",
JSON.stringify(npmManifest, null, 2)
);
var bowerManifest = { var bowerManifest = {
name: DIST_NAME, name: DIST_NAME,
version: VERSION, version: VERSION,
@ -1641,10 +1667,38 @@ gulp.task(
ignore: [], ignore: [],
keywords: DIST_KEYWORDS, keywords: DIST_KEYWORDS,
}; };
var bowerJsonSrc = createStringSource(
"bower.json", return [
JSON.stringify(bowerManifest, null, 2) createStringSource("package.json", JSON.stringify(npmManifest, null, 2)),
); createStringSource("bower.json", JSON.stringify(bowerManifest, null, 2)),
];
}
gulp.task(
"dist-pre",
gulp.series(
"generic",
"generic-es5",
"components",
"components-es5",
"image_decoders",
"lib",
"minified",
"types",
function () {
console.log();
console.log("### Cloning baseline distribution");
rimraf.sync(DIST_DIR);
mkdirp.sync(DIST_DIR);
safeSpawnSync("git", ["clone", "--depth", "1", DIST_REPO_URL, DIST_DIR]);
console.log();
console.log("### Overwriting all files");
rimraf.sync(path.join(DIST_DIR, "*"));
// Rebuilding manifests
var [packageJsonSrc, bowerJsonSrc] = packageBowerJson();
return merge([ return merge([
packageJsonSrc.pipe(gulp.dest(DIST_DIR)), packageJsonSrc.pipe(gulp.dest(DIST_DIR)),
@ -1698,6 +1752,9 @@ gulp.task(
gulp gulp
.src(LIB_DIR + "**/*", { base: LIB_DIR }) .src(LIB_DIR + "**/*", { base: LIB_DIR })
.pipe(gulp.dest(DIST_DIR + "lib/")), .pipe(gulp.dest(DIST_DIR + "lib/")),
gulp
.src(TYPES_BUILD_DIR + "**/**")
.pipe(gulp.dest(DIST_DIR + "build/")),
]); ]);
} }
) )
@ -1847,7 +1904,7 @@ gulp.task("externaltest", function (done) {
gulp.task( gulp.task(
"npm-test", "npm-test",
gulp.series( gulp.series(
gulp.parallel("lint", "externaltest", "unittestcli"), gulp.parallel("lint", "externaltest", "unittestcli", "typestest"),
"lint-chromium" "lint-chromium"
) )
); );

6
package-lock.json generated
View File

@ -15224,6 +15224,12 @@
"integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=",
"dev": true "dev": true
}, },
"typescript": {
"version": "3.9.7",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.7.tgz",
"integrity": "sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw==",
"dev": true
},
"typogr": { "typogr": {
"version": "0.6.8", "version": "0.6.8",
"resolved": "https://registry.npmjs.org/typogr/-/typogr-0.6.8.tgz", "resolved": "https://registry.npmjs.org/typogr/-/typogr-0.6.8.tgz",

View File

@ -49,6 +49,7 @@
"terser": "^4.8.0", "terser": "^4.8.0",
"through2": "^3.0.2", "through2": "^3.0.2",
"ttest": "^2.1.1", "ttest": "^2.1.1",
"typescript": "^3.9.7",
"typogr": "^0.6.8", "typogr": "^0.6.8",
"vinyl": "^2.2.0", "vinyl": "^2.2.0",
"vinyl-fs": "^3.0.3", "vinyl-fs": "^3.0.3",

View File

@ -13,6 +13,9 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* Key/value storage for annotation data in forms.
*/
class AnnotationStorage { class AnnotationStorage {
constructor() { constructor() {
this._storage = {}; this._storage = {};

View File

@ -97,13 +97,19 @@ function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
createPDFNetworkStream = pdfNetworkStreamFactory; createPDFNetworkStream = pdfNetworkStreamFactory;
} }
/* eslint-disable max-len */
/**
* @typedef {Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array} TypedArray
*/
/* eslint-enable max-len */
/** /**
* Document initialization / loading parameters object. * Document initialization / loading parameters object.
* *
* @typedef {Object} DocumentInitParameters * @typedef {Object} DocumentInitParameters
* @property {string} [url] - The URL of the PDF. * @property {string} [url] - The URL of the PDF.
* @property {TypedArray|Array|string} [data] - Binary PDF data. Use typed * @property {TypedArray|Array<number>|string} [data] - Binary PDF data. Use
* arrays (Uint8Array) to improve the memory usage. If PDF data is * typed arrays (Uint8Array) to improve the memory usage. If PDF data is
* BASE64-encoded, use atob() to convert it to a binary string first. * BASE64-encoded, use atob() to convert it to a binary string first.
* @property {Object} [httpHeaders] - Basic authentication headers. * @property {Object} [httpHeaders] - Basic authentication headers.
* @property {boolean} [withCredentials] - Indicates whether or not * @property {boolean} [withCredentials] - Indicates whether or not
@ -171,10 +177,12 @@ function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
/** /**
* @typedef {Object} PDFDocumentStats * @typedef {Object} PDFDocumentStats
* @property {Object} streamTypes - Used stream types in the document (an item * @property {Object<string, boolean>} streamTypes - Used stream types in the
* is set to true if specific stream ID was used in the document). * document (an item is set to true if specific stream ID was used in the
* @property {Object} fontTypes - Used font types in the document (an item * document).
* is set to true if specific font ID was used in the document). * @property {Object<string, boolean>} fontTypes - Used font types in the
* document (an item is set to true if specific font ID was used in the
* document).
*/ */
/** /**
@ -414,6 +422,51 @@ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
}); });
} }
/**
* The loading task controls the operations required to load a PDF document
* (such as network requests) and provides a way to listen for completion,
* after which individual pages can be rendered.
*
* @typedef {Object} PDFDocumentLoadingTask
* @property {string} docId
* Unique document loading task id -- used in MessageHandlers.
* @property {boolean} destroyed
* Shows if loading task is destroyed.
* @property {cbOnPassword} [onPassword]
* Callback to request a password if wrong or no password was provided.
* The callback receives two parameters: function that needs to be called
* with new password and reason (see {PasswordResponses}).
* @property {cbOnProgress} onProgress
* Callback to be able to monitor the loading progress of the PDF file
* (necessary to implement e.g. a loading bar). The callback receives
* an {Object} with the properties: {number} loaded and {number} total.
* @property {cbOnUnsupportedFeature} onUnsupportedFeature
* Callback for when an unsupported feature is used in the PDF document.
* The callback receives an {UNSUPPORTED_FEATURES} argument.
* @property {Promise<PDFDocumentProxy>} promise
* Promise for document loading task completion.
* @property {cbDestroy} destroy
* Aborts all network requests and destroys worker.
* Returns a promise that is resolved after destruction activity is completed.
*
* @callback cbOnPassword
* @param {string} password
* @param {number} reason
*
* @callback cbOnProgress
* @param {number} loaded
* @param {number} total
*
* @callback cbOnUnsupportedFeature
* @param {string} featureId
*
* @callback cbDestroy
*/
/**
* @type {any}
* @ignore
*/
const PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() { const PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
let nextDocumentId = 0; let nextDocumentId = 0;
@ -464,7 +517,7 @@ const PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
/** /**
* Promise for document loading task completion. * Promise for document loading task completion.
* @type {Promise} * @type {Promise<PDFDocumentProxy>}
*/ */
get promise() { get promise() {
return this._capability.promise; return this._capability.promise;
@ -472,8 +525,8 @@ const PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
/** /**
* Aborts all network requests and destroys worker. * Aborts all network requests and destroys worker.
* @returns {Promise} A promise that is resolved after destruction activity * @returns {Promise<void>} A promise that is resolved after destruction
* is completed. * activity is completed.
*/ */
destroy() { destroy() {
this.destroyed = true; this.destroyed = true;
@ -495,11 +548,13 @@ const PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
/** /**
* Abstract class to support range requests file loading. * Abstract class to support range requests file loading.
*/
class PDFDataRangeTransport {
/**
* @param {number} length * @param {number} length
* @param {Uint8Array} initialData * @param {Uint8Array} initialData
* @param {boolean} progressiveDone * @param {boolean} progressiveDone
*/ */
class PDFDataRangeTransport {
constructor(length, initialData, progressiveDone = false) { constructor(length, initialData, progressiveDone = false) {
this.length = length; this.length = length;
this.initialData = initialData; this.initialData = initialData;
@ -603,8 +658,8 @@ class PDFDocumentProxy {
/** /**
* @param {number} pageNumber - The page number to get. The first page is 1. * @param {number} pageNumber - The page number to get. The first page is 1.
* @returns {Promise} A promise that is resolved with a {@link PDFPageProxy} * @returns {Promise<PDFPageProxy>} A promise that is resolved with
* object. * a {@link PDFPageProxy} object.
*/ */
getPage(pageNumber) { getPage(pageNumber) {
return this._transport.getPage(pageNumber); return this._transport.getPage(pageNumber);
@ -613,16 +668,17 @@ class PDFDocumentProxy {
/** /**
* @param {{num: number, gen: number}} ref - The page reference. Must have * @param {{num: number, gen: number}} ref - The page reference. Must have
* the `num` and `gen` properties. * the `num` and `gen` properties.
* @returns {Promise} A promise that is resolved with the page index (starting * @returns {Promise<{num: number, gen: number}>} A promise that is resolved
* from zero) that is associated with the reference. * with the page index (starting from zero) that is associated with the
* reference.
*/ */
getPageIndex(ref) { getPageIndex(ref) {
return this._transport.getPageIndex(ref); return this._transport.getPageIndex(ref);
} }
/** /**
* @returns {Promise} A promise that is resolved with a lookup table for * @returns {Promise<Object<string,any>>} A promise that is resolved with
* mapping named destinations to reference numbers. * a lookup table for mapping named destinations to reference numbers.
* *
* This can be slow for large documents. Use `getDestination` instead. * This can be slow for large documents. Use `getDestination` instead.
*/ */
@ -632,74 +688,88 @@ class PDFDocumentProxy {
/** /**
* @param {string} id - The named destination to get. * @param {string} id - The named destination to get.
* @returns {Promise} A promise that is resolved with all information * @returns {Promise<Array<any>>} A promise that is resolved with all
* of the given named destination. * information of the given named destination.
*/ */
getDestination(id) { getDestination(id) {
return this._transport.getDestination(id); return this._transport.getDestination(id);
} }
/** /**
* @returns {Promise} A promise that is resolved with an {Array} containing * @returns {Promise<Array<string> | null>} A promise that is
* the page labels that correspond to the page indexes, or `null` when * resolved with an {Array} containing the page labels that correspond to
* no page labels are present in the PDF file. * the page indexes, or `null` when no page labels are present in the PDF
* file.
*/ */
getPageLabels() { getPageLabels() {
return this._transport.getPageLabels(); return this._transport.getPageLabels();
} }
/** /**
* @returns {Promise} A promise that is resolved with a {string} containing * @returns {Promise<string>} A promise that is resolved with a {string}
* the page layout name. * containing the page layout name.
*/ */
getPageLayout() { getPageLayout() {
return this._transport.getPageLayout(); return this._transport.getPageLayout();
} }
/** /**
* @returns {Promise} A promise that is resolved with a {string} containing * @returns {Promise<string>} A promise that is resolved with a {string}
* the page mode name. * containing the page mode name.
*/ */
getPageMode() { getPageMode() {
return this._transport.getPageMode(); return this._transport.getPageMode();
} }
/** /**
* @returns {Promise} A promise that is resolved with an {Object} containing * @returns {Promise<Object>} A promise that is resolved with an {Object}
* the viewer preferences, or `null` when no viewer preferences are present * containing the viewer preferences.
* in the PDF file.
*/ */
getViewerPreferences() { getViewerPreferences() {
return this._transport.getViewerPreferences(); return this._transport.getViewerPreferences();
} }
/** /**
* @returns {Promise} A promise that is resolved with an {Object} containing * @returns {Promise<any | null>} A promise that is resolved with an {Array}
* the currently supported actions, or `null` when no OpenAction exists. * containing the destination, or `null` when no open action is present
* in the PDF.
*/ */
getOpenAction() { getOpenAction() {
return this._transport.getOpenAction(); return this._transport.getOpenAction();
} }
/** /**
* @returns {Promise} A promise that is resolved with a lookup table for * @returns {Promise<any>} A promise that is resolved with a lookup table
* mapping named attachments to their content. * for mapping named attachments to their content.
*/ */
getAttachments() { getAttachments() {
return this._transport.getAttachments(); return this._transport.getAttachments();
} }
/** /**
* @returns {Promise} A promise that is resolved with an {Array} of all the * @returns {Promise<Array<string> | null>} A promise that is
* JavaScript strings in the name tree, or `null` if no JavaScript exists. * resolved with an {Array} of all the JavaScript strings in the name tree,
* or `null` if no JavaScript exists.
*/ */
getJavaScript() { getJavaScript() {
return this._transport.getJavaScript(); return this._transport.getJavaScript();
} }
/** /**
* @returns {Promise} A promise that is resolved with an {Array} that is a * @typedef {Object} OutlineNode
* tree outline (if it has one) of the PDF. The tree is in the format of: * @property {string} title
* @property {boolean} bold
* @property {boolean} italic
* @property {Uint8ClampedArray} color
* @property {any} dest
* @property {string} url
* @property {Array<OutlineNode>} items
*/
/**
* @returns {Promise<Array<OutlineNode>>} A promise that is resolved with
* an {Array} that is a tree outline (if it has one) of the PDF. The tree is
* in the format of:
* [ * [
* { * {
* title: string, * title: string,
@ -719,45 +789,46 @@ class PDFDocumentProxy {
} }
/** /**
* @returns {Promise} A promise that is resolved with an {Array} that contains * @returns {Promise<Array<string | null>>} A promise that is resolved with
* the permission flags for the PDF document, or `null` when * an {Array} that contains the permission flags for the PDF document, or
* no permissions are present in the PDF file. * `null` when no permissions are present in the PDF file.
*/ */
getPermissions() { getPermissions() {
return this._transport.getPermissions(); return this._transport.getPermissions();
} }
/** /**
* @returns {Promise} A promise that is resolved with an {Object} that has * @returns {Promise<{ info: Object, metadata: Metadata }>} A promise that is
* `info` and `metadata` properties. `info` is an {Object} filled with * resolved with an {Object} that has `info` and `metadata` properties.
* anything available in the information dictionary and similarly * `info` is an {Object} filled with anything available in the information
* `metadata` is a {Metadata} object with information from the metadata * dictionary and similarly `metadata` is a {Metadata} object with
* section of the PDF. * information from the metadata section of the PDF.
*/ */
getMetadata() { getMetadata() {
return this._transport.getMetadata(); return this._transport.getMetadata();
} }
/** /**
* @returns {Promise} A promise that is resolved with a {TypedArray} that has * @returns {Promise<TypedArray>} A promise that is resolved with a
* the raw data from the PDF. * {TypedArray} that has the raw data from the PDF.
*/ */
getData() { getData() {
return this._transport.getData(); return this._transport.getData();
} }
/** /**
* @returns {Promise} A promise that is resolved when the document's data * @returns {Promise<{ length: number }>} A promise that is resolved when the
* is loaded. It is resolved with an {Object} that contains the `length` * document's data is loaded. It is resolved with an {Object} that contains
* property that indicates size of the PDF data in bytes. * the `length` property that indicates size of the PDF data in bytes.
*/ */
getDownloadInfo() { getDownloadInfo() {
return this._transport.downloadInfoCapability.promise; return this._transport.downloadInfoCapability.promise;
} }
/** /**
* @returns {Promise} A promise this is resolved with current statistics about * @returns {Promise<PDFDocumentStats>} A promise this is resolved with
* document structures (see {@link PDFDocumentStats}). * current statistics about document structures
* (see {@link PDFDocumentStats}).
*/ */
getStats() { getStats() {
return this._transport.getStats(); return this._transport.getStats();
@ -784,9 +855,9 @@ class PDFDocumentProxy {
} }
/** /**
* @type {Object} A subset of the current {DocumentInitParameters}, which are * @type {DocumentInitParameters} A subset of the current
* either needed in the viewer and/or whose default values may be affected * {DocumentInitParameters}, which are either needed in the viewer and/or
* by the `apiCompatibilityParams`. * whose default values may be affected by the `apiCompatibilityParams`.
*/ */
get loadingParams() { get loadingParams() {
return this._transport.loadingParams; return this._transport.loadingParams;
@ -829,8 +900,9 @@ class PDFDocumentProxy {
* Page text content. * Page text content.
* *
* @typedef {Object} TextContent * @typedef {Object} TextContent
* @property {array} items - array of {@link TextItem} * @property {Array<TextItem>} items - array of {@link TextItem}
* @property {Object} styles - {@link TextStyle} objects, indexed by font name. * @property {Object<string, TextStyle>} styles - {@link TextStyle} objects,
* indexed by font name.
*/ */
/** /**
@ -839,7 +911,7 @@ class PDFDocumentProxy {
* @typedef {Object} TextItem * @typedef {Object} TextItem
* @property {string} str - text content. * @property {string} str - text content.
* @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
* @property {array} transform - transformation matrix. * @property {Array<any>} transform - transformation matrix.
* @property {number} width - width in device space. * @property {number} width - width in device space.
* @property {number} height - height in device space. * @property {number} height - height in device space.
* @property {string} fontName - font name used by pdf.js for converted font. * @property {string} fontName - font name used by pdf.js for converted font.
@ -879,7 +951,7 @@ class PDFDocumentProxy {
* @property {boolean} [renderInteractiveForms] - Whether or not * @property {boolean} [renderInteractiveForms] - Whether or not
* interactive form elements are rendered in the display * interactive form elements are rendered in the display
* layer. If so, we do not render them on canvas as well. * layer. If so, we do not render them on canvas as well.
* @property {Array} [transform] - Additional transform, applied * @property {Array<any>} [transform] - Additional transform, applied
* just before viewport transform. * just before viewport transform.
* @property {Object} [imageLayer] - An object that has beginLayout, * @property {Object} [imageLayer] - An object that has beginLayout,
* endLayout and appendImage functions. * endLayout and appendImage functions.
@ -891,20 +963,22 @@ class PDFDocumentProxy {
* CSS <color> value, a CanvasGradient object (a linear or * CSS <color> value, a CanvasGradient object (a linear or
* radial gradient) or a CanvasPattern object (a repetitive * radial gradient) or a CanvasPattern object (a repetitive
* image). The default value is 'rgb(255,255,255)'. * image). The default value is 'rgb(255,255,255)'.
* @property {Object} [annotationStorage] - Storage for annotation data in
* forms.
*/ */
/** /**
* PDF page operator list. * PDF page operator list.
* *
* @typedef {Object} PDFOperatorList * @typedef {Object} PDFOperatorList
* @property {Array} fnArray - Array containing the operator functions. * @property {Array<number>} fnArray - Array containing the operator
* @property {Array} argsArray - Array containing the arguments of the * functions.
* @property {Array<any>} argsArray - Array containing the arguments of the
* functions. * functions.
*/ */
/** /**
* Proxy to a PDFPage in the worker thread. * Proxy to a PDFPage in the worker thread.
* @alias PDFPageProxy
*/ */
class PDFPageProxy { class PDFPageProxy {
constructor(pageIndex, pageInfo, transport, pdfBug = false) { constructor(pageIndex, pageInfo, transport, pdfBug = false) {
@ -952,8 +1026,8 @@ class PDFPageProxy {
} }
/** /**
* @type {Array} An array of the visible portion of the PDF page in user * @type {Array<number>} An array of the visible portion of the PDF page in
* space units [x1, y1, x2, y2]. * user space units [x1, y1, x2, y2].
*/ */
get view() { get view() {
return this._pageInfo.view; return this._pageInfo.view;
@ -983,8 +1057,8 @@ class PDFPageProxy {
/** /**
* @param {GetAnnotationsParameters} params - Annotation parameters. * @param {GetAnnotationsParameters} params - Annotation parameters.
* @returns {Promise} A promise that is resolved with an {Array} of the * @returns {Promise<Array<any>>} A promise that is resolved with an
* annotation objects. * {Array} of the annotation objects.
*/ */
getAnnotations({ intent = null } = {}) { getAnnotations({ intent = null } = {}) {
if (!this.annotationsPromise || this.annotationsIntent !== intent) { if (!this.annotationsPromise || this.annotationsIntent !== intent) {
@ -1135,8 +1209,8 @@ class PDFPageProxy {
} }
/** /**
* @returns {Promise} A promise resolved with an {@link PDFOperatorList} * @returns {Promise<PDFOperatorList>} A promise resolved with an
* object that represents page's operator list. * {@link PDFOperatorList} object that represents page's operator list.
*/ */
getOperatorList() { getOperatorList() {
function operatorListChanged() { function operatorListChanged() {
@ -1209,7 +1283,7 @@ class PDFPageProxy {
/** /**
* @param {getTextContentParameters} params - getTextContent parameters. * @param {getTextContentParameters} params - getTextContent parameters.
* @returns {Promise} That is resolved a {@link TextContent} * @returns {Promise<TextContent>} That is resolved a {@link TextContent}
* object that represent the page text content. * object that represent the page text content.
*/ */
getTextContent(params = {}) { getTextContent(params = {}) {
@ -1558,6 +1632,7 @@ class LoopbackPort {
* constants from {VerbosityLevel} should be used. * constants from {VerbosityLevel} should be used.
*/ */
/** @type {any} */
const PDFWorker = (function PDFWorkerClosure() { const PDFWorker = (function PDFWorkerClosure() {
const pdfWorkerPorts = new WeakMap(); const pdfWorkerPorts = new WeakMap();
let isWorkerDisabled = false; let isWorkerDisabled = false;
@ -2592,14 +2667,15 @@ class RenderTask {
* Callback for incremental rendering -- a function that will be called * Callback for incremental rendering -- a function that will be called
* each time the rendering is paused. To continue rendering call the * each time the rendering is paused. To continue rendering call the
* function that is the first argument to the callback. * function that is the first argument to the callback.
* @type {function} * @callback
* @param {function}
*/ */
this.onContinue = null; this.onContinue = null;
} }
/** /**
* Promise for rendering task completion. * Promise for rendering task completion.
* @type {Promise} * @type {Promise<void>}
*/ */
get promise() { get promise() {
return this._internalRenderTask.capability.promise; return this._internalRenderTask.capability.promise;
@ -2805,8 +2881,10 @@ const InternalRenderTask = (function InternalRenderTaskClosure() {
return InternalRenderTask; return InternalRenderTask;
})(); })();
/** @type {string} */
const version = const version =
typeof PDFJSDev !== "undefined" ? PDFJSDev.eval("BUNDLE_VERSION") : null; typeof PDFJSDev !== "undefined" ? PDFJSDev.eval("BUNDLE_VERSION") : null;
/** @type {string} */
const build = const build =
typeof PDFJSDev !== "undefined" ? PDFJSDev.eval("BUNDLE_BUILD") : null; typeof PDFJSDev !== "undefined" ? PDFJSDev.eval("BUNDLE_BUILD") : null;

View File

@ -430,6 +430,9 @@ var CanvasExtraState = (function CanvasExtraStateClosure() {
return CanvasExtraState; return CanvasExtraState;
})(); })();
/**
* @type {any}
*/
var CanvasGraphics = (function CanvasGraphicsClosure() { var CanvasGraphics = (function CanvasGraphicsClosure() {
// Defines the time the executeOperatorList is going to be executing // Defines the time the executeOperatorList is going to be executing
// before it stops and shedules a continue of execution. // before it stops and shedules a continue of execution.

View File

@ -406,6 +406,9 @@ function getShadingPatternFromIR(raw) {
return shadingIR.fromIR(raw); return shadingIR.fromIR(raw);
} }
/**
* @type {any}
*/
var TilingPattern = (function TilingPatternClosure() { var TilingPattern = (function TilingPatternClosure() {
var PaintType = { var PaintType = {
COLORED: 1, COLORED: 1,

View File

@ -23,24 +23,35 @@ import {
* Text layer render parameters. * Text layer render parameters.
* *
* @typedef {Object} TextLayerRenderParameters * @typedef {Object} TextLayerRenderParameters
* @property {TextContent} [textContent] - Text content to render (the object * @property {import("./api").TextContent} [textContent] - Text content to
* is returned by the page's `getTextContent` method). * render (the object is returned by the page's `getTextContent` method).
* @property {ReadableStream} [textContentStream] - Text content stream to * @property {ReadableStream} [textContentStream] - Text content stream to
* render (the stream is returned by the page's `streamTextContent` method). * render (the stream is returned by the page's `streamTextContent` method).
* @property {HTMLElement} container - HTML element that will contain text runs. * @property {HTMLElement} container - HTML element that will contain text runs.
* @property {PageViewport} viewport - The target viewport to properly * @property {import("./display_utils").PageViewport} viewport - The target
* layout the text runs. * viewport to properly layout the text runs.
* @property {Array} [textDivs] - HTML elements that are correspond to the * @property {Array<HTMLElement>} [textDivs] - HTML elements that are correspond
* text items of the textContent input. This is output and shall be * to the text items of the textContent input. This is output and shall be
* initially be set to empty array. * initially be set to empty array.
* @property {Array} [textContentItemsStr] - Strings that correspond to the * @property {Array<string>} [textContentItemsStr] - Strings that correspond to
* `str` property of the text items of textContent input. This is output * the `str` property of the text items of textContent input. This is output
* and shall be initially be set to empty array. * and shall be initially be set to empty array.
* @property {number} [timeout] - Delay in milliseconds before rendering of the * @property {number} [timeout] - Delay in milliseconds before rendering of the
* text runs occurs. * text runs occurs.
* @property {boolean} [enhanceTextSelection] - Whether to turn on the text * @property {boolean} [enhanceTextSelection] - Whether to turn on the text
* selection enhancement. * selection enhancement.
*/ */
/**
* @typedef {Object} TextLayerRenderTask
* @property {Promise<void>} promise
* @property {() => void} cancel
* @property {(expandDivs: boolean) => void} expandTextDivs
*/
/**
* @type {(renderParameters: TextLayerRenderParameters) => TextLayerRenderTask}
*/
var renderTextLayer = (function renderTextLayerClosure() { var renderTextLayer = (function renderTextLayerClosure() {
var MAX_TEXT_DIVS_TO_RENDER = 100000; var MAX_TEXT_DIVS_TO_RENDER = 100000;
@ -728,12 +739,6 @@ var renderTextLayer = (function renderTextLayerClosure() {
}, },
}; };
/**
* Starts rendering of the text layer.
*
* @param {TextLayerRenderParameters} renderParameters
* @returns {TextLayerRenderTask}
*/
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
function renderTextLayer(renderParameters) { function renderTextLayer(renderParameters) {
var task = new TextLayerRenderTask({ var task = new TextLayerRenderTask({

View File

@ -397,7 +397,6 @@ var Type2Parser = function type2Parser(aFilePath) {
* var file = new Uint8Array(cffFileArray, 0, cffFileSize); * var file = new Uint8Array(cffFileArray, 0, cffFileSize);
* var parser = new Type2Parser(); * var parser = new Type2Parser();
* parser.parse(new Stream(file)); * parser.parse(new Stream(file));
*
*/ */
/* /*

View File

@ -412,6 +412,9 @@ function shadow(obj, prop, value) {
return value; return value;
} }
/**
* @type {any}
*/
const BaseException = (function BaseExceptionClosure() { const BaseException = (function BaseExceptionClosure() {
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
function BaseException(message) { function BaseException(message) {
@ -503,7 +506,7 @@ function stringToBytes(str) {
/** /**
* Gets length of the array (Array, Uint8Array, or string) in bytes. * Gets length of the array (Array, Uint8Array, or string) in bytes.
* @param {Array|Uint8Array|string} arr * @param {Array<any>|Uint8Array|string} arr
* @returns {number} * @returns {number}
*/ */
function arrayByteLength(arr) { function arrayByteLength(arr) {
@ -516,7 +519,8 @@ function arrayByteLength(arr) {
/** /**
* Combines array items (arrays) into single Uint8Array object. * Combines array items (arrays) into single Uint8Array object.
* @param {Array} arr - the array of the arrays (Array, Uint8Array, or string). * @param {Array<Array<any>|Uint8Array|string>} arr - the array of the arrays
* (Array, Uint8Array, or string).
* @returns {Uint8Array} * @returns {Uint8Array}
*/ */
function arraysToBytes(arr) { function arraysToBytes(arr) {
@ -822,7 +826,7 @@ function isArrayEqual(arr1, arr2) {
* Promise Capability object. * Promise Capability object.
* *
* @typedef {Object} PromiseCapability * @typedef {Object} PromiseCapability
* @property {Promise} promise - A Promise object. * @property {Promise<any>} promise - A Promise object.
* @property {boolean} settled - If the Promise has been fulfilled/rejected. * @property {boolean} settled - If the Promise has been fulfilled/rejected.
* @property {function} resolve - Fulfills the Promise. * @property {function} resolve - Fulfills the Promise.
* @property {function} reject - Rejects the Promise. * @property {function} reject - Rejects the Promise.

20
test/types/main.ts Normal file
View File

@ -0,0 +1,20 @@
import { getDocument } from "pdfjs-dist";
class MainTest {
task: ReturnType<typeof getDocument> | undefined;
constructor(public file: string) {
}
loadPdf() {
this.task = getDocument("file://" + this.file);
return this.task.promise;
}
}
// This is actually never called, as the test only consists in compiling the file.
// The compilation will crawl through all files and make sure that the types are consistent.
const mt = new MainTest("../pdfs/basicapi.pdf");
mt.loadPdf().then(() => {
console.log("loaded");
});

26
test/types/tsconfig.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"outDir": "../../build/tmp",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"module": "es2015",
"baseUrl": "./",
"strict": true,
"types": [],
"lib": [
"es2017",
"dom"
],
"paths": {
"pdfjs-dist": ["../../build/typestest"],
"pdfjs-dist/*": ["../../build/typestest/build/*"]
}
},
"files": [
"main.ts"
],
}