From 587abf0ef486543a8d9f02a1387415cbabafccb8 Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Thu, 11 Jun 2026 10:07:39 +0200 Subject: [PATCH] Re-use the `getPassword` helper function more in the `src/core/worker.js` file Currently the same code, for requesting the password from the main-thread, is now duplicated three times. Let's avoid that by moving the new `getPassword` helper function, added in the previous commit, and re-use that everywhere instead. --- src/core/worker.js | 57 ++++++++++++++++++++-------------------------- 1 file changed, 25 insertions(+), 32 deletions(-) diff --git a/src/core/worker.js b/src/core/worker.js index e9bcb3ffa..35c36d4ea 100644 --- a/src/core/worker.js +++ b/src/core/worker.js @@ -308,6 +308,27 @@ class WorkerMessageHandler { return promise; } + async function getPassword(ex) { + if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) { + assert( + ex instanceof PasswordException, + "getPassword - must be a `PasswordException`." + ); + } + const task = new WorkerTask(`PasswordException: response ${ex.code}`); + startWorkerTask(task); + + try { + const res = await handler.sendWithPromise("PasswordRequest", ex); + return res.password; + } finally { + // Ensure that any `catch` handler runs *before* removing the task. + Promise.resolve().then(() => { + finishWorkerTask(task); + }); + } + } + function setupDoc(data) { function onSuccess(doc) { ensureNotTerminated(); @@ -320,18 +341,12 @@ class WorkerMessageHandler { } if (ex instanceof PasswordException) { - const task = new WorkerTask(`PasswordException: response ${ex.code}`); - startWorkerTask(task); - - handler - .sendWithPromise("PasswordRequest", ex) - .then(function ({ password }) { - finishWorkerTask(task); + getPassword(ex) + .then(password => { pdfManager.updatePassword(password); pdfManagerReady(); }) - .catch(function () { - finishWorkerTask(task); + .catch(() => { handler.send("DocException", ex); }); } else { @@ -448,17 +463,6 @@ class WorkerMessageHandler { * Unique attachment identifier (required). */ async function (id) { - async function getPassword(ex) { - const task = new WorkerTask(`PasswordException: response ${ex.code}`); - startWorkerTask(task); - - try { - const res = await handler.sendWithPromise("PasswordRequest", ex); - return res.password; - } finally { - finishWorkerTask(task); - } - } let passwordEx; // Loop to prompt again after an incorrect password. @@ -646,23 +650,12 @@ class WorkerMessageHandler { warn("extractPages: XRefParseException."); } } else if (e instanceof PasswordException) { - const task = new WorkerTask( - `PasswordException: response ${e.code}` - ); - - startWorkerTask(task); - try { - const { password } = await handler.sendWithPromise( - "PasswordRequest", - e - ); + const password = await getPassword(e); manager.updatePassword(password); } catch { isValid = false; warn("extractPages: invalid password."); - } finally { - finishWorkerTask(task); } } else { isValid = false;