[api-major] Output JavaScript modules in the builds (issue 10317)

At this point in time all browsers, and also Node.js, support standard `import`/`export` statements and we can now finally consider outputting modern JavaScript modules in the builds.[1]

In order for this to work we can *only* use proper `import`/`export` statements throughout the main code-base, and (as expected) our Node.js support made this much more complicated since both the official builds and the GitHub Actions-based tests must keep working.[2]
One remaining issue is that the `pdf.scripting.js` file cannot be built as a JavaScript module, since doing so breaks PDF scripting.

Note that my initial goal was to try and split these changes into a couple of commits, however that unfortunately didn't really work since it turned out to be difficult for smaller patches to work correctly and pass (all) tests that way.[3]
This is a classic case of every change requiring a couple of other changes, with each of those changes requiring further changes in turn and the size/scope quickly increasing as a result.

One possible "issue" with these changes is that we'll now only output JavaScript modules in the builds, which could perhaps be a problem with older tools. However it unfortunately seems far too complicated/time-consuming for us to attempt to support both the old and modern module formats, hence the alternative would be to do "nothing" here and just keep our "old" builds.[4]

---
[1] The final blocker was module support in workers in Firefox, which was implemented in Firefox 114; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#browser_compatibility

[2] It's probably possible to further improve/simplify especially the Node.js-specific code, but it does appear to work as-is.

[3] Having partially "broken" patches, that fail tests, as part of the commit history is *really not* a good idea in general.

[4] Outputting JavaScript modules was first requested almost five years ago, see issue 10317, and nowadays there *should* be much better support for JavaScript modules in various tools.
This commit is contained in:
Jonas Jenwald 2023-09-28 13:00:10 +02:00
parent 0a970ee443
commit 927e50f5d4
23 changed files with 227 additions and 241 deletions

View File

@ -15,11 +15,12 @@
"use strict";
const pdfjs = require("./build/pdf.js");
const pdfjs = require("./build/pdf.mjs");
if (typeof window !== "undefined" && "Worker" in window) {
pdfjs.GlobalWorkerOptions.workerPort = new Worker(
new URL("./build/pdf.worker.js", import.meta.url)
new URL("./build/pdf.worker.mjs", import.meta.url),
{ type: "module" }
);
}

View File

@ -201,6 +201,7 @@ function createWebpackConfig(
!bundleDefines.LIB &&
!bundleDefines.TESTING &&
!disableSourceMaps;
const isModule = output.library?.type === "module";
const skipBabel = bundleDefines.SKIP_BABEL;
// `core-js`, see https://github.com/zloirock/core-js/issues/514,
@ -216,7 +217,9 @@ function createWebpackConfig(
{ corejs: "3.32.2", shippedProposals: true, useBuiltIns: "usage" },
],
];
const babelPlugins = ["@babel/plugin-transform-modules-commonjs"];
const babelPlugins = isModule
? []
: ["@babel/plugin-transform-modules-commonjs"];
const plugins = [];
if (!disableLicenseHeader) {
@ -225,8 +228,7 @@ function createWebpackConfig(
);
}
const experiments =
output.library?.type === "module" ? { outputModule: true } : undefined;
const experiments = isModule ? { outputModule: true } : undefined;
// Required to expose e.g., the `window` object.
output.globalObject = "globalThis";
@ -296,7 +298,11 @@ function createWebpackConfig(
}
return {
mode: "none",
mode: "production",
optimization: {
mangleExports: false,
minimize: false,
},
experiments,
output,
performance: {
@ -388,14 +394,28 @@ function checkChromePreferencesFile(chromePrefsPath, webPrefs) {
return ret;
}
function replaceWebpackRequire() {
// Produced bundles can be rebundled again, avoid collisions (e.g. in api.js)
// by renaming __webpack_require__ to something else.
return replace("__webpack_require__", "__w_pdfjs_require__");
}
function tweakWebpackOutput(jsName) {
const replacer = ["__non_webpack_import__\\("];
function replaceNonWebpackImport() {
return replace("__non_webpack_import__", "import");
if (jsName) {
replacer.push(
" __webpack_exports__ = {};",
" __webpack_exports__ = await __webpack_exports__;"
);
}
const regex = new RegExp(`(${replacer.join("|")})`, "gm");
return replace(regex, match => {
switch (match) {
case "__non_webpack_import__(":
return "import(/* webpackIgnore: true */ ";
case " __webpack_exports__ = {};":
return ` __webpack_exports__ = globalThis.${jsName} = {};`;
case " __webpack_exports__ = await __webpack_exports__;":
return ` __webpack_exports__ = globalThis.${jsName} = await __webpack_exports__;`;
}
return match;
});
}
function addGlobalExports(amdName, jsName) {
@ -423,21 +443,16 @@ function addGlobalExports(amdName, jsName) {
}
function createMainBundle(defines) {
const mainAMDName = "pdfjs-dist/build/pdf";
const mainOutputName = "pdf.js";
const mainFileConfig = createWebpackConfig(defines, {
filename: mainOutputName,
library: mainAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
filename: "pdf.mjs",
library: {
type: "module",
},
});
return gulp
.src("./src/pdf.js")
.pipe(webpack2Stream(mainFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(addGlobalExports(mainAMDName, "pdfjsLib"));
.pipe(tweakWebpackOutput("pdfjsLib"));
}
function createScriptingBundle(defines, extraOptions = undefined) {
@ -457,8 +472,6 @@ function createScriptingBundle(defines, extraOptions = undefined) {
return gulp
.src("./src/pdf.scripting.js")
.pipe(webpack2Stream(scriptingFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(addGlobalExports(scriptingAMDName, "pdfjsScripting"));
}
@ -489,9 +502,6 @@ function createTemporaryScriptingBundle(defines, extraOptions = undefined) {
}
function createSandboxBundle(defines, extraOptions = undefined) {
const sandboxAMDName = "pdfjs-dist/build/pdf.sandbox";
const sandboxOutputName = "pdf.sandbox.js";
const scriptingPath = TMP_DIR + "pdf.scripting.js";
// Insert the source as a string to be `eval`-ed in the sandbox.
const sandboxDefines = builder.merge(defines, {
@ -502,10 +512,10 @@ function createSandboxBundle(defines, extraOptions = undefined) {
const sandboxFileConfig = createWebpackConfig(
sandboxDefines,
{
filename: sandboxOutputName,
library: sandboxAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
filename: "pdf.sandbox.mjs",
library: {
type: "module",
},
},
extraOptions
);
@ -513,36 +523,30 @@ function createSandboxBundle(defines, extraOptions = undefined) {
return gulp
.src("./src/pdf.sandbox.js")
.pipe(webpack2Stream(sandboxFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(addGlobalExports(sandboxAMDName, "pdfjsSandbox"));
.pipe(tweakWebpackOutput("pdfjsSandbox"));
}
function createWorkerBundle(defines) {
const workerAMDName = "pdfjs-dist/build/pdf.worker";
const workerOutputName = "pdf.worker.js";
const workerFileConfig = createWebpackConfig(defines, {
filename: workerOutputName,
library: workerAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
filename: "pdf.worker.mjs",
library: {
type: "module",
},
});
return gulp
.src("./src/pdf.worker.js")
.pipe(webpack2Stream(workerFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(addGlobalExports(workerAMDName, "pdfjsWorker"));
.pipe(tweakWebpackOutput("pdfjsWorker"));
}
function createWebBundle(defines, options) {
const viewerOutputName = "viewer.js";
const viewerFileConfig = createWebpackConfig(
defines,
{
filename: viewerOutputName,
filename: "viewer.mjs",
library: {
type: "module",
},
},
{
defaultPreferencesDir: options.defaultPreferencesDir,
@ -551,17 +555,19 @@ function createWebBundle(defines, options) {
return gulp
.src("./web/viewer.js")
.pipe(webpack2Stream(viewerFileConfig))
.pipe(replaceNonWebpackImport());
.pipe(tweakWebpackOutput());
}
function createGVWebBundle(defines, options) {
const viewerOutputName = "viewer-geckoview.js";
defines = builder.merge(defines, { GECKOVIEW: true });
const viewerFileConfig = createWebpackConfig(
defines,
{
filename: viewerOutputName,
filename: "viewer-geckoview.mjs",
library: {
type: "module",
},
},
{
defaultPreferencesDir: options.defaultPreferencesDir,
@ -570,43 +576,33 @@ function createGVWebBundle(defines, options) {
return gulp
.src("./web/viewer-geckoview.js")
.pipe(webpack2Stream(viewerFileConfig))
.pipe(replaceNonWebpackImport());
.pipe(tweakWebpackOutput());
}
function createComponentsBundle(defines) {
const componentsAMDName = "pdfjs-dist/web/pdf_viewer";
const componentsOutputName = "pdf_viewer.js";
const componentsFileConfig = createWebpackConfig(defines, {
filename: componentsOutputName,
library: componentsAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
filename: "pdf_viewer.mjs",
library: {
type: "module",
},
});
return gulp
.src("./web/pdf_viewer.component.js")
.pipe(webpack2Stream(componentsFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(addGlobalExports(componentsAMDName, "pdfjsViewer"));
.pipe(tweakWebpackOutput("pdfjsViewer"));
}
function createImageDecodersBundle(defines) {
const imageDecodersAMDName = "pdfjs-dist/image_decoders/pdf.image_decoders";
const imageDecodersOutputName = "pdf.image_decoders.js";
const componentsFileConfig = createWebpackConfig(defines, {
filename: imageDecodersOutputName,
library: imageDecodersAMDName,
libraryTarget: "umd",
umdNamedDefine: true,
filename: "pdf.image_decoders.mjs",
library: {
type: "module",
},
});
return gulp
.src("./src/pdf.image_decoders.js")
.pipe(webpack2Stream(componentsFileConfig))
.pipe(replaceWebpackRequire())
.pipe(replaceNonWebpackImport())
.pipe(addGlobalExports(imageDecodersAMDName, "pdfjsImageDecoders"));
.pipe(tweakWebpackOutput("pdfjsImageDecoders"));
}
function createCMapBundle() {
@ -1161,15 +1157,15 @@ function buildMinified(defines, dir) {
}
async function parseMinified(dir) {
const pdfFile = fs.readFileSync(dir + "/build/pdf.js").toString();
const pdfFile = fs.readFileSync(dir + "build/pdf.mjs").toString();
const pdfWorkerFile = fs
.readFileSync(dir + "/build/pdf.worker.js")
.readFileSync(dir + "build/pdf.worker.mjs")
.toString();
const pdfSandboxFile = fs
.readFileSync(dir + "/build/pdf.sandbox.js")
.readFileSync(dir + "build/pdf.sandbox.mjs")
.toString();
const pdfImageDecodersFile = fs
.readFileSync(dir + "/image_decoders/pdf.image_decoders.js")
.readFileSync(dir + "image_decoders/pdf.image_decoders.mjs")
.toString();
console.log();
@ -1183,41 +1179,42 @@ async function parseMinified(dir) {
},
keep_classnames: true,
keep_fnames: true,
module: true,
};
fs.writeFileSync(
dir + "/build/pdf.min.js",
dir + "build/pdf.min.mjs",
(await minify(pdfFile, options)).code
);
fs.writeFileSync(
dir + "/build/pdf.worker.min.js",
dir + "build/pdf.worker.min.mjs",
(await minify(pdfWorkerFile, options)).code
);
fs.writeFileSync(
dir + "/build/pdf.sandbox.min.js",
dir + "build/pdf.sandbox.min.mjs",
(await minify(pdfSandboxFile, options)).code
);
fs.writeFileSync(
dir + "image_decoders/pdf.image_decoders.min.js",
dir + "image_decoders/pdf.image_decoders.min.mjs",
(await minify(pdfImageDecodersFile, options)).code
);
console.log();
console.log("### Cleaning js files");
fs.unlinkSync(dir + "/build/pdf.js");
fs.unlinkSync(dir + "/build/pdf.worker.js");
fs.unlinkSync(dir + "/build/pdf.sandbox.js");
fs.unlinkSync(dir + "build/pdf.mjs");
fs.unlinkSync(dir + "build/pdf.worker.mjs");
fs.unlinkSync(dir + "build/pdf.sandbox.mjs");
fs.renameSync(dir + "/build/pdf.min.js", dir + "/build/pdf.js");
fs.renameSync(dir + "/build/pdf.worker.min.js", dir + "/build/pdf.worker.js");
fs.renameSync(dir + "build/pdf.min.mjs", dir + "build/pdf.mjs");
fs.renameSync(dir + "build/pdf.worker.min.mjs", dir + "build/pdf.worker.mjs");
fs.renameSync(
dir + "/build/pdf.sandbox.min.js",
dir + "/build/pdf.sandbox.js"
dir + "build/pdf.sandbox.min.mjs",
dir + "build/pdf.sandbox.mjs"
);
fs.renameSync(
dir + "/image_decoders/pdf.image_decoders.min.js",
dir + "/image_decoders/pdf.image_decoders.js"
dir + "image_decoders/pdf.image_decoders.min.mjs",
dir + "image_decoders/pdf.image_decoders.mjs"
);
}
@ -1859,8 +1856,8 @@ gulp.task(
packageJson().pipe(gulp.dest(TYPESTEST_DIR)),
gulp
.src([
GENERIC_DIR + "build/pdf.js",
GENERIC_DIR + "build/pdf.worker.js",
GENERIC_DIR + "build/pdf.mjs",
GENERIC_DIR + "build/pdf.worker.mjs",
SRC_DIR + "pdf.worker.entry.js",
])
.pipe(gulp.dest(TYPESTEST_DIR + "build/")),
@ -2153,7 +2150,7 @@ function packageJson() {
const npmManifest = {
name: DIST_NAME,
version: VERSION,
main: "build/pdf.js",
main: "build/pdf.mjs",
types: "types/src/pdf.d.ts",
description: DIST_DESCRIPTION,
keywords: DIST_KEYWORDS,
@ -2171,7 +2168,6 @@ function packageJson() {
https: false,
url: false,
},
format: "amd", // to not allow system.js to choose 'cjs'
repository: {
type: "git",
url: DIST_REPO_URL,
@ -2230,49 +2226,49 @@ gulp.task(
.pipe(gulp.dest(DIST_DIR)),
gulp
.src([
GENERIC_DIR + "build/{pdf,pdf.worker,pdf.sandbox}.js",
GENERIC_DIR + "build/{pdf,pdf.worker,pdf.sandbox}.js.map",
GENERIC_DIR + "build/{pdf,pdf.worker,pdf.sandbox}.mjs",
GENERIC_DIR + "build/{pdf,pdf.worker,pdf.sandbox}.mjs.map",
SRC_DIR + "pdf.worker.entry.js",
])
.pipe(gulp.dest(DIST_DIR + "build/")),
gulp
.src([
GENERIC_LEGACY_DIR + "build/{pdf,pdf.worker,pdf.sandbox}.js",
GENERIC_LEGACY_DIR + "build/{pdf,pdf.worker,pdf.sandbox}.js.map",
GENERIC_LEGACY_DIR + "build/{pdf,pdf.worker,pdf.sandbox}.mjs",
GENERIC_LEGACY_DIR + "build/{pdf,pdf.worker,pdf.sandbox}.mjs.map",
SRC_DIR + "pdf.worker.entry.js",
])
.pipe(gulp.dest(DIST_DIR + "legacy/build/")),
gulp
.src(MINIFIED_DIR + "build/pdf.js")
.pipe(rename("pdf.min.js"))
.src(MINIFIED_DIR + "build/pdf.mjs")
.pipe(rename("pdf.min.mjs"))
.pipe(gulp.dest(DIST_DIR + "build/")),
gulp
.src(MINIFIED_DIR + "build/pdf.worker.js")
.pipe(rename("pdf.worker.min.js"))
.src(MINIFIED_DIR + "build/pdf.worker.mjs")
.pipe(rename("pdf.worker.min.mjs"))
.pipe(gulp.dest(DIST_DIR + "build/")),
gulp
.src(MINIFIED_DIR + "build/pdf.sandbox.js")
.pipe(rename("pdf.sandbox.min.js"))
.src(MINIFIED_DIR + "build/pdf.sandbox.mjs")
.pipe(rename("pdf.sandbox.min.mjs"))
.pipe(gulp.dest(DIST_DIR + "build/")),
gulp
.src(MINIFIED_DIR + "image_decoders/pdf.image_decoders.js")
.pipe(rename("pdf.image_decoders.min.js"))
.src(MINIFIED_DIR + "image_decoders/pdf.image_decoders.mjs")
.pipe(rename("pdf.image_decoders.min.mjs"))
.pipe(gulp.dest(DIST_DIR + "image_decoders/")),
gulp
.src(MINIFIED_LEGACY_DIR + "build/pdf.js")
.pipe(rename("pdf.min.js"))
.src(MINIFIED_LEGACY_DIR + "build/pdf.mjs")
.pipe(rename("pdf.min.mjs"))
.pipe(gulp.dest(DIST_DIR + "legacy/build/")),
gulp
.src(MINIFIED_LEGACY_DIR + "build/pdf.worker.js")
.pipe(rename("pdf.worker.min.js"))
.src(MINIFIED_LEGACY_DIR + "build/pdf.worker.mjs")
.pipe(rename("pdf.worker.min.mjs"))
.pipe(gulp.dest(DIST_DIR + "legacy/build/")),
gulp
.src(MINIFIED_LEGACY_DIR + "build/pdf.sandbox.js")
.pipe(rename("pdf.sandbox.min.js"))
.src(MINIFIED_LEGACY_DIR + "build/pdf.sandbox.mjs")
.pipe(rename("pdf.sandbox.min.mjs"))
.pipe(gulp.dest(DIST_DIR + "legacy/build/")),
gulp
.src(MINIFIED_LEGACY_DIR + "image_decoders/pdf.image_decoders.js")
.pipe(rename("pdf.image_decoders.min.js"))
.src(MINIFIED_LEGACY_DIR + "image_decoders/pdf.image_decoders.mjs")
.pipe(rename("pdf.image_decoders.min.mjs"))
.pipe(gulp.dest(DIST_DIR + "legacy/image_decoders/")),
gulp
.src(COMPONENTS_DIR + "**/*", { base: COMPONENTS_DIR })

View File

@ -51,7 +51,6 @@ import {
DOMStandardFontDataFactory,
isDataScheme,
isValidFetchUrl,
loadScript,
PageViewport,
RenderingCancelledException,
StatTimer,
@ -1986,14 +1985,13 @@ const PDFWorkerUtil = {
fakeWorkerId: 0,
};
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
// eslint-disable-next-line no-undef
if (isNodeJS && typeof __non_webpack_require__ === "function") {
if (isNodeJS) {
// Workers aren't supported in Node.js, force-disabling them there.
PDFWorkerUtil.isWorkerDisabled = true;
GlobalWorkerOptions.workerSrc ||= PDFJSDev.test("LIB")
? "../pdf.worker.js"
: "./pdf.worker.js";
: "./pdf.worker.mjs";
}
// Check if URLs have the same origin. For non-HTTP based URLs, returns false.
@ -2126,11 +2124,7 @@ class PDFWorker {
);
}
const worker =
typeof PDFJSDev === "undefined" &&
!workerSrc.endsWith("/build/pdf.worker.js")
? new Worker(workerSrc, { type: "module" })
: new Worker(workerSrc);
const worker = new Worker(workerSrc, { type: "module" });
const messageHandler = new MessageHandler("main", "worker", worker);
const terminateEarly = () => {
worker.removeEventListener("error", onWorkerError);
@ -2312,40 +2306,15 @@ class PDFWorker {
// Loads worker code into the main-thread.
static get _setupFakeWorkerGlobal() {
const loader = async () => {
const mainWorkerMessageHandler = this.#mainThreadWorkerMessageHandler;
if (mainWorkerMessageHandler) {
if (this.#mainThreadWorkerMessageHandler) {
// The worker was already loaded using e.g. a `<script>` tag.
return mainWorkerMessageHandler;
return this.#mainThreadWorkerMessageHandler;
}
if (typeof PDFJSDev === "undefined") {
const worker = await import("pdfjs/pdf.worker.js");
const worker =
typeof PDFJSDev === "undefined"
? await import("pdfjs/pdf.worker.js")
: await __non_webpack_import__(this.workerSrc); // eslint-disable-line no-undef
return worker.WorkerMessageHandler;
}
if (
PDFJSDev.test("GENERIC") &&
isNodeJS &&
// eslint-disable-next-line no-undef
typeof __non_webpack_require__ === "function"
) {
// Since bundlers, such as Webpack, cannot be told to leave `require`
// statements alone we are thus forced to jump through hoops in order
// to prevent `Critical dependency: ...` warnings in third-party
// deployments of the built `pdf.js`/`pdf.worker.js` files; see
// https://github.com/webpack/webpack/issues/8826
//
// The following hack is based on the assumption that code running in
// Node.js won't ever be affected by e.g. Content Security Policies that
// prevent the use of `eval`. If that ever occurs, we should revert this
// to a normal `__non_webpack_require__` statement and simply document
// the Webpack warnings instead (telling users to ignore them).
//
// eslint-disable-next-line no-eval
const worker = eval("require")(this.workerSrc);
return worker.WorkerMessageHandler;
}
await loadScript(this.workerSrc);
return window.pdfjsWorker.WorkerMessageHandler;
};
return shadow(this, "_setupFakeWorkerGlobal", loader());

View File

@ -796,29 +796,6 @@ function noContextMenu(e) {
e.preventDefault();
}
/**
* @param {string} src
* @param {boolean} [removeScriptElement]
* @returns {Promise<void>}
*/
function loadScript(src, removeScriptElement = false) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = src;
script.onload = function (evt) {
if (removeScriptElement) {
script.remove();
}
resolve(evt);
};
script.onerror = function () {
reject(new Error(`Cannot load script at: ${script.src}`));
};
(document.head || document.documentElement).append(script);
});
}
// Deprecated API function -- display regardless of the `verbosity` setting.
function deprecated(details) {
console.log("Deprecated API usage: " + details);
@ -1026,7 +1003,6 @@ export {
isDataScheme,
isPdfFile,
isValidFetchUrl,
loadScript,
noContextMenu,
PageViewport,
PDFDateString,

View File

@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* globals __non_webpack_require__ */
import {
AbortException,
@ -34,7 +33,7 @@ if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
function parseUrl(sourceUrl) {
const url = __non_webpack_require__("url");
const { url } = globalThis.__pdfjsPackages__;
const parsedUrl = url.parse(sourceUrl);
if (parsedUrl.protocol === "file:" || parsedUrl.host) {
return parsedUrl;
@ -340,13 +339,13 @@ class PDFNodeStreamFullReader extends BaseFullReader {
this._request = null;
if (this._url.protocol === "http:") {
const http = __non_webpack_require__("http");
const { http } = globalThis.__pdfjsPackages__;
this._request = http.request(
createRequestOptions(this._url, stream.httpHeaders),
handleResponse
);
} else {
const https = __non_webpack_require__("https");
const { https } = globalThis.__pdfjsPackages__;
this._request = https.request(
createRequestOptions(this._url, stream.httpHeaders),
handleResponse
@ -389,13 +388,13 @@ class PDFNodeStreamRangeReader extends BaseRangeReader {
this._request = null;
if (this._url.protocol === "http:") {
const http = __non_webpack_require__("http");
const { http } = globalThis.__pdfjsPackages__;
this._request = http.request(
createRequestOptions(this._url, this._httpHeaders),
handleResponse
);
} else {
const https = __non_webpack_require__("https");
const { https } = globalThis.__pdfjsPackages__;
this._request = https.request(
createRequestOptions(this._url, this._httpHeaders),
handleResponse
@ -420,7 +419,7 @@ class PDFNodeStreamFsFullReader extends BaseFullReader {
path = path.replace(/^\//, "");
}
const fs = __non_webpack_require__("fs");
const { fs } = globalThis.__pdfjsPackages__;
fs.lstat(path, (error, stat) => {
if (error) {
if (error.code === "ENOENT") {
@ -450,7 +449,7 @@ class PDFNodeStreamFsRangeReader extends BaseRangeReader {
path = path.replace(/^\//, "");
}
const fs = __non_webpack_require__("fs");
const { fs } = globalThis.__pdfjsPackages__;
this._setReadableStream(fs.createReadStream(path, { start, end: end - 1 }));
}
}

View File

@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* globals __non_webpack_require__ */
/* globals __non_webpack_import__, __non_webpack_require__ */
import {
BaseCanvasFactory,
@ -28,15 +28,59 @@ if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
);
}
if (isNodeJS && !globalThis.__pdfjsPackages__) {
let fs, http, https, url, canvas, path2d_polyfill;
if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("LIB")) {
// Native packages.
fs = __non_webpack_require__("fs");
http = __non_webpack_require__("http");
https = __non_webpack_require__("https");
url = __non_webpack_require__("url");
// Optional, third-party, packages.
try {
canvas = __non_webpack_require__("canvas");
} catch {}
try {
path2d_polyfill = __non_webpack_require__("path2d-polyfill");
} catch {}
} else {
// Native packages.
fs = await __non_webpack_import__("fs");
http = await __non_webpack_import__("http");
https = await __non_webpack_import__("https");
url = await __non_webpack_import__("url");
// Optional, third-party, packages.
try {
canvas = await __non_webpack_import__("canvas");
} catch {}
try {
path2d_polyfill = await __non_webpack_import__("path2d-polyfill");
} catch {}
}
globalThis.__pdfjsPackages__ = {
CanvasRenderingContext2D: canvas?.CanvasRenderingContext2D,
createCanvas: canvas?.createCanvas,
DOMMatrix: canvas?.DOMMatrix,
fs,
http,
https,
polyfillPath2D: path2d_polyfill?.polyfillPath2D,
url,
};
}
if (typeof PDFJSDev !== "undefined" && !PDFJSDev.test("SKIP_BABEL")) {
(function checkDOMMatrix() {
if (globalThis.DOMMatrix || !isNodeJS) {
return;
}
try {
globalThis.DOMMatrix = __non_webpack_require__("canvas").DOMMatrix;
} catch (ex) {
warn(`Cannot polyfill \`DOMMatrix\`, rendering may be broken: "${ex}".`);
const { DOMMatrix } = globalThis.__pdfjsPackages__;
if (DOMMatrix) {
globalThis.DOMMatrix = DOMMatrix;
} else {
warn("Cannot polyfill `DOMMatrix`, rendering may be broken.");
}
})();
@ -44,21 +88,21 @@ if (typeof PDFJSDev !== "undefined" && !PDFJSDev.test("SKIP_BABEL")) {
if (globalThis.Path2D || !isNodeJS) {
return;
}
try {
const { CanvasRenderingContext2D } = __non_webpack_require__("canvas");
const { polyfillPath2D } = __non_webpack_require__("path2d-polyfill");
const { CanvasRenderingContext2D, polyfillPath2D } =
globalThis.__pdfjsPackages__;
if (CanvasRenderingContext2D && polyfillPath2D) {
globalThis.CanvasRenderingContext2D = CanvasRenderingContext2D;
polyfillPath2D(globalThis);
} catch (ex) {
warn(`Cannot polyfill \`Path2D\`, rendering may be broken: "${ex}".`);
} else {
warn("Cannot polyfill `Path2D`, rendering may be broken.");
}
})();
}
const fetchData = function (url) {
return new Promise((resolve, reject) => {
const fs = __non_webpack_require__("fs");
const { fs } = globalThis.__pdfjsPackages__;
fs.readFile(url, (error, data) => {
if (error || !data) {
reject(new Error(error));
@ -76,8 +120,8 @@ class NodeCanvasFactory extends BaseCanvasFactory {
* @ignore
*/
_createCanvas(width, height) {
const Canvas = __non_webpack_require__("canvas");
return Canvas.createCanvas(width, height);
const { createCanvas } = globalThis.__pdfjsPackages__;
return createCanvas(width, height);
}
}

View File

@ -59,7 +59,6 @@ import {
getXfaPageViewport,
isDataScheme,
isPdfFile,
loadScript,
noContextMenu,
PDFDateString,
PixelsPerInch,
@ -102,7 +101,6 @@ export {
InvalidPDFException,
isDataScheme,
isPdfFile,
loadScript,
MissingPDFException,
noContextMenu,
normalizeUnicode,

View File

@ -16,4 +16,4 @@
(typeof window !== "undefined"
? window
: {}
).pdfjsWorker = require("./pdf.worker.js");
).pdfjsWorker = require("./pdf.worker.mjs");

View File

@ -34,7 +34,7 @@ const STANDARD_FONT_DATA_URL = "/build/generic/web/standard_fonts/";
const IMAGE_RESOURCES_PATH = "/web/images/";
const VIEWER_CSS = "../build/components/pdf_viewer.css";
const VIEWER_LOCALE = "en-US";
const WORKER_SRC = "../build/generic/build/pdf.worker.js";
const WORKER_SRC = "../build/generic/build/pdf.worker.mjs";
const RENDER_TASK_ON_CONTINUE_DELAY = 5; // ms
const SVG_NS = "http://www.w3.org/2000/svg";

View File

@ -18,8 +18,8 @@ limitations under the License.
<head>
<title>PDF.js test slave</title>
<meta charset="utf-8">
<script src="../build/generic/build/pdf.js"></script>
<script src="../build/components/pdf_viewer.js"></script>
<script src="../build/generic/build/pdf.mjs" type="module"></script>
<script src="../build/components/pdf_viewer.mjs" type="module"></script>
<link rel="resource" type="application/l10n" href="../build/generic/web/locale/locale.properties">
</head>

View File

@ -56,6 +56,8 @@ import { GlobalImageCache } from "../../src/core/image_utils.js";
import { GlobalWorkerOptions } from "../../src/display/worker_options.js";
import { Metadata } from "../../src/display/metadata.js";
const WORKER_SRC = "../../build/generic/build/pdf.worker.mjs";
describe("api", function () {
const basicApiFileName = "basicapi.pdf";
const basicApiFileLength = 105779; // bytes
@ -914,7 +916,8 @@ describe("api", function () {
}
GlobalWorkerOptions.workerPort = new Worker(
new URL("../../build/generic/build/pdf.worker.js", window.location)
new URL(WORKER_SRC, window.location),
{ type: "module" }
);
const loadingTask1 = getDocument(basicApiGetDocumentParams);
@ -934,7 +937,8 @@ describe("api", function () {
}
GlobalWorkerOptions.workerPort = new Worker(
new URL("../../build/generic/build/pdf.worker.js", window.location)
new URL(WORKER_SRC, window.location),
{ type: "module" }
);
const loadingTask1 = getDocument(basicApiGetDocumentParams);
@ -963,7 +967,8 @@ describe("api", function () {
}
GlobalWorkerOptions.workerPort = new Worker(
new URL("../../build/generic/build/pdf.worker.js", window.location)
new URL(WORKER_SRC, window.location),
{ type: "module" }
);
const loadingTask = getDocument(basicApiGetDocumentParams);

View File

@ -108,7 +108,7 @@ async function initializePDFJS(callback) {
);
}
// Configure the worker.
GlobalWorkerOptions.workerSrc = "../../build/generic/build/pdf.worker.js";
GlobalWorkerOptions.workerSrc = "../../build/generic/build/pdf.worker.mjs";
callback();
}

View File

@ -49,7 +49,6 @@ import {
getXfaPageViewport,
isDataScheme,
isPdfFile,
loadScript,
noContextMenu,
PDFDateString,
PixelsPerInch,
@ -88,7 +87,6 @@ const expectedAPI = Object.freeze({
InvalidPDFException,
isDataScheme,
isPdfFile,
loadScript,
MissingPDFException,
noContextMenu,
normalizeUnicode,
@ -132,10 +130,9 @@ describe("web_pdfjsLib", function () {
if (isNodeJS) {
pending("loadScript is not supported in Node.js.");
}
await loadScript(
"../../build/generic/build/pdf.js",
/* removeScriptElement = */ true
);
const apiPath = "../../build/generic/build/pdf.mjs";
await import(apiPath);
const webPdfjsLib = await import("../../web/pdfjs.js");
expect(Object.keys(webPdfjsLib).sort()).toEqual(

View File

@ -13,9 +13,7 @@
* limitations under the License.
*/
import { loadScript } from "../../src/display/display_utils.js";
const sandboxBundleSrc = "../../build/generic/build/pdf.sandbox.js";
const sandboxBundleSrc = "../../build/generic/build/pdf.sandbox.mjs";
describe("Scripting", function () {
let sandbox, send_queue, test_id, ref, windowAlert;
@ -53,8 +51,9 @@ describe("Scripting", function () {
const command = "alert";
send_queue.set(command, { command, value });
};
const promise = loadScript(sandboxBundleSrc).then(() => {
return window.pdfjsSandbox.QuickJSSandbox();
// eslint-disable-next-line no-unsanitized/method
const promise = import(sandboxBundleSrc).then(pdfjsSandbox => {
return pdfjsSandbox.QuickJSSandbox();
});
sandbox = {
createSandbox(data) {

View File

@ -44,7 +44,6 @@ import {
InvalidPDFException,
isDataScheme,
isPdfFile,
loadScript,
MissingPDFException,
PDFWorker,
PromiseCapability,
@ -2264,10 +2263,10 @@ async function loadFakeWorker() {
GlobalWorkerOptions.workerSrc ||= AppOptions.get("workerSrc");
if (typeof PDFJSDev === "undefined") {
window.pdfjsWorker = await import("pdfjs/pdf.worker.js");
globalThis.pdfjsWorker = await import("pdfjs/pdf.worker.js");
return;
}
await loadScript(PDFWorker.workerSrc);
await __non_webpack_import__(PDFWorker.workerSrc); // eslint-disable-line no-undef
}
async function loadPDFBug(self) {

View File

@ -300,8 +300,8 @@ const defaultOptions = {
typeof PDFJSDev === "undefined"
? "../src/pdf.worker.js"
: PDFJSDev.test("MOZCENTRAL")
? "resource://pdf.js/build/pdf.worker.js"
: "../build/pdf.worker.js",
? "resource://pdf.js/build/pdf.worker.mjs"
: "../build/pdf.worker.mjs",
kind: OptionKind.WORKER,
},
};
@ -325,8 +325,8 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
/** @type {string} */
value:
typeof PDFJSDev === "undefined"
? "../build/dev-sandbox/pdf.sandbox.js"
: "../build/pdf.sandbox.js",
? "../build/dev-sandbox/pdf.sandbox.mjs"
: "../build/pdf.sandbox.mjs",
kind: OptionKind.VIEWER,
};
} else if (PDFJSDev.test("CHROME")) {

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
import { getPdfFilenameFromUrl, loadScript } from "pdfjs-lib";
import { getPdfFilenameFromUrl } from "pdfjs-lib";
async function docProperties(pdfDocument) {
const url = "",
@ -41,11 +41,16 @@ async function docProperties(pdfDocument) {
class GenericScripting {
constructor(sandboxBundleSrc) {
this._ready = loadScript(
sandboxBundleSrc,
/* removeScriptElement = */ true
).then(() => {
return window.pdfjsSandbox.QuickJSSandbox();
this._ready = new Promise((resolve, reject) => {
const sandbox =
typeof PDFJSDev === "undefined"
? import(sandboxBundleSrc) // eslint-disable-line no-unsanitized/method
: __non_webpack_import__(sandboxBundleSrc); // eslint-disable-line no-undef
sandbox
.then(pdfjsSandbox => {
resolve(pdfjsSandbox.QuickJSSandbox());
})
.catch(reject);
});
}

View File

@ -35,7 +35,6 @@ const {
InvalidPDFException,
isDataScheme,
isPdfFile,
loadScript,
MissingPDFException,
noContextMenu,
normalizeUnicode,
@ -81,7 +80,6 @@ export {
InvalidPDFException,
isDataScheme,
isPdfFile,
loadScript,
MissingPDFException,
noContextMenu,
normalizeUnicode,

View File

@ -76,7 +76,7 @@ See https://github.com/adobe-type-tools/cmap-resources
<script src="viewer-geckoview.js" type="module-shim"></script>
<!--#else-->
<!--<script src="resource://pdf.js/web/viewer.js"></script>-->
<!--<script src="resource://pdf.js/web/viewer.mjs" type="module"></script>-->
<!--#endif-->
</head>

View File

@ -1,4 +1,4 @@
<!-- This snippet is used in the Chromium extension (included from viewer.html) -->
<base href="/content/web/">
<link rel="resource" type="application/l10n" href="locale/locale.properties">
<script src="../build/pdf.js"></script>
<script src="../build/pdf.mjs" type="module"></script>

View File

@ -1,2 +1,2 @@
<!-- This snippet is used in the Firefox extension (included from viewer.html) -->
<script src="resource://pdf.js/build/pdf.js"></script>
<script src="resource://pdf.js/build/pdf.mjs" type="module"></script>

View File

@ -1,3 +1,3 @@
<!-- This snippet is used in production (included from viewer.html) -->
<link rel="resource" type="application/l10n" href="locale/locale.properties">
<script src="../build/pdf.js"></script>
<script src="../build/pdf.mjs" type="module"></script>

View File

@ -44,9 +44,9 @@ See https://github.com/adobe-type-tools/cmap-resources
<!--#endif-->
<!--#if MOZCENTRAL-->
<!--<script src="resource://pdf.js/web/viewer.js"></script>-->
<!--<script src="resource://pdf.js/web/viewer.mjs" type="module"></script>-->
<!--#elif !MOZCENTRAL-->
<!--<script src="viewer.js"></script>-->
<!--<script src="viewer.mjs" type="module"></script>-->
<!--#elif /* Development mode. */-->
<link rel="resource" type="application/l10n" href="locale/locale.properties">