Skip to content

Build your personal knowledge base with Trilium Notes

refactor: migrate yauzl usage to promise-based APIs from 3.4.0

Elian Doranc315dfd4c41e
diff --git a/apps/server/package.json b/apps/server/package.json
index b33b6a4258..4ea092db86 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -66,6 +66,7 @@
"@types/supertest": "7.2.0",
"@types/tmp": "0.2.6",
"@types/ws": "8.18.1",
+ "@types/yauzl": "3.3.0",
"archiver": "8.0.0",
"cheerio": "1.2.0",
"chokidar": "5.0.0",
diff --git a/apps/server/src/yauzl.d.ts b/apps/server/src/yauzl.d.ts
new file mode 100644
index 0000000000..96407854fe
--- /dev/null
+++ b/apps/server/src/yauzl.d.ts
@@ -0,0 +1,43 @@
+/*
+ * Promise-based APIs introduced in yauzl 3.4.0 that are not yet covered by @types/yauzl.
+ * Remove once the upstream types catch up.
+ * See https://github.com/thejoshwolfe/yauzl/pull/171
+ */
+
+import type { Readable } from "stream";
+
+declare module "yauzl" {
+ export function openPromise(path: string, options?: Options): Promise<ZipFile>;
+ export function fromFdPromise(fd: number, options?: Options): Promise<ZipFile>;
+ export function fromBufferPromise(buffer: Buffer, options?: Options): Promise<ZipFile>;
+ export function fromRandomAccessReaderPromise(
+ reader: RandomAccessReader,
+ totalSize: number,
+ options?: Options
+ ): Promise<ZipFile>;
+
+ interface ZipFile {
+ /**
+ * Async-iterator alternative to readEntry()/"entry" events. Requires lazyEntries: true
+ * (implied by the *Promise() open functions) and may only be called once per ZipFile.
+ */
+ eachEntry(): AsyncIterableIterator<Entry>;
+ openReadStreamPromise(entry: Entry, options?: ZipFileOptions): Promise<Readable>;
+ readLocalFileHeaderPromise(
+ entry: Entry,
+ options: { minimal: true }
+ ): Promise<{ fileDataStart: number }>;
+ readLocalFileHeaderPromise(
+ entry: Entry,
+ options?: { minimal?: boolean }
+ ): Promise<LocalFileHeader>;
+ openReadStreamLowLevelPromise(
+ fileDataStart: number,
+ compressedSize: number,
+ relativeStart: number,
+ relativeEnd: number,
+ decompress: boolean,
+ uncompressedSize: number | null
+ ): Promise<Readable>;
+ }
+}
diff --git a/apps/server/src/zip_provider.ts b/apps/server/src/zip_provider.ts
index 17924c3642..0cee2efa69 100644
--- a/apps/server/src/zip_provider.ts
+++ b/apps/server/src/zip_provider.ts
@@ -36,39 +36,31 @@ function streamToBuffer(stream: Stream): Promise<Buffer> {
}
export default class NodejsZipProvider implements ZipProvider {
- detectFilenameEncoding(buffer: Uint8Array): Promise<string> {
- return new Promise<string>((res, rej) => {
- yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, validateEntrySizes: false, decodeStrings: false }, (err, zipfile) => {
- if (err) return rej(err);
- if (!zipfile) return rej(new Error("Unable to read zip file."));
-
- const samples: Buffer[] = [];
- zipfile.readEntry();
- zipfile.on("entry", (entry: yauzl.Entry) => {
- const isUtf8Flagged = !!(entry.generalPurposeBitFlag & 0x800);
- if (!isUtf8Flagged && Buffer.isBuffer(entry.fileName)) {
- samples.push(entry.fileName as Buffer);
- }
- zipfile.readEntry();
- });
- zipfile.on("end", () => {
- void (async () => {
- if (samples.length === 0) {
- return res("utf-8");
- }
- const combined = Buffer.concat(samples);
- try {
- const chardet = await import("chardet");
- const detected = chardet.default.detect(combined);
- res(detected || "utf-8");
- } catch {
- res("utf-8");
- }
- })();
- });
- zipfile.on("error", rej);
- });
+ async detectFilenameEncoding(buffer: Uint8Array): Promise<string> {
+ const zipfile = await yauzl.fromBufferPromise(Buffer.from(buffer), {
+ validateEntrySizes: false,
+ decodeStrings: false
});
+
+ const samples: Buffer[] = [];
+ for await (const entry of zipfile.eachEntry()) {
+ const isUtf8Flagged = !!(entry.generalPurposeBitFlag & 0x800);
+ if (!isUtf8Flagged) {
+ samples.push(entry.fileNameRaw);
+ }
+ }
+
+ if (samples.length === 0) {
+ return "utf-8";
+ }
+
+ const combined = Buffer.concat(samples);
+ try {
+ const chardet = await import("chardet");
+ return chardet.default.detect(combined) || "utf-8";
+ } catch {
+ return "utf-8";
+ }
}
createZipArchive(): ZipArchive {
@@ -86,51 +78,31 @@ export default class NodejsZipProvider implements ZipProvider {
};
}
- readZipFile(
+ async readZipFile(
buffer: Uint8Array,
processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>,
filenameEncoding?: string
): Promise<void> {
- return new Promise<void>((res, rej) => {
- yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, validateEntrySizes: false, decodeStrings: false }, (err, zipfile) => {
- if (err) { rej(err); return; }
- if (!zipfile) { rej(new Error("Unable to read zip file.")); return; }
-
- zipfile.readEntry();
- zipfile.on("entry", (entry: yauzl.Entry) => {
- void (async () => {
- try {
- // yauzl with decodeStrings: false returns fileName as a Buffer.
- // Use the detected encoding for non-UTF-8-flagged entries,
- // falling back to UTF-8.
- let fileName: string;
- if (Buffer.isBuffer(entry.fileName)) {
- const isUtf8Flagged = !!(entry.generalPurposeBitFlag & 0x800);
- const encoding = isUtf8Flagged ? "utf-8" : (filenameEncoding || "utf-8");
- fileName = decodeBuffer(entry.fileName as Buffer, encoding);
- } else {
- fileName = entry.fileName;
- }
-
- const readContent = () => new Promise<Uint8Array>((res, rej) => {
- zipfile.openReadStream(entry, (err, readStream) => {
- if (err) { rej(err); return; }
- if (!readStream) { rej(new Error("Unable to read content.")); return; }
- streamToBuffer(readStream).then(res, rej);
- });
- });
-
- await processEntry({ fileName }, readContent);
- } catch (e) {
- rej(e);
- }
- zipfile.readEntry();
- })();
- });
- zipfile.on("end", res);
- zipfile.on("error", rej);
- });
+ const zipfile = await yauzl.fromBufferPromise(Buffer.from(buffer), {
+ validateEntrySizes: false,
+ decodeStrings: false
});
+
+ for await (const entry of zipfile.eachEntry()) {
+ // yauzl with decodeStrings: false leaves file names undecoded.
+ // Use the detected encoding for non-UTF-8-flagged entries,
+ // falling back to UTF-8.
+ const isUtf8Flagged = !!(entry.generalPurposeBitFlag & 0x800);
+ const encoding = isUtf8Flagged ? "utf-8" : (filenameEncoding || "utf-8");
+ const fileName = decodeBuffer(entry.fileNameRaw, encoding);
+
+ const readContent = async () => {
+ const readStream = await zipfile.openReadStreamPromise(entry);
+ return await streamToBuffer(readStream);
+ };
+
+ await processEntry({ fileName }, readContent);
+ }
}
}
diff --git a/packages/pdfjs-viewer/package.json b/packages/pdfjs-viewer/package.json
index 44a14e7fcc..5792a754af 100644
--- a/packages/pdfjs-viewer/package.json
+++ b/packages/pdfjs-viewer/package.json
@@ -10,6 +10,7 @@
"@triliumnext/commons": "workspace:*"
},
"devDependencies": {
- "pdfjs-dist": "5.7.284"
+ "pdfjs-dist": "5.7.284",
+ "yauzl": "3.4.0"
}
}
\ No newline at end of file
diff --git a/packages/pdfjs-viewer/scripts/update-viewer.ts b/packages/pdfjs-viewer/scripts/update-viewer.ts
index 34acc27faf..8d05ab0789 100644
--- a/packages/pdfjs-viewer/scripts/update-viewer.ts
+++ b/packages/pdfjs-viewer/scripts/update-viewer.ts
@@ -1,8 +1,10 @@
+/// <reference path="./yauzl.d.ts" />
import { join, dirname } from "path";
import packageJson from "../package.json" with { type: "json" };
import fs from "fs/promises";
import * as yauzl from "yauzl";
import { createWriteStream } from "fs";
+import { pipeline } from "stream/promises";
const version = packageJson.devDependencies["pdfjs-dist"];
const url = `https://github.com/mozilla/pdf.js/releases/download/v${version}/pdfjs-${version}-dist.zip`;
@@ -23,37 +25,24 @@ async function main() {
}
const buffer = await response.arrayBuffer();
- yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true }, (err, zip) => {
- zip.readEntry();
- zip.on("entry", (entry: yauzl.Entry) => {
- if (entry.fileName.endsWith("/") || !FILES_TO_COPY.some(prefix => entry.fileName.startsWith(prefix))) {
- // Directory entry or not in the list of files to copy, skip
- console.log("Skipping", entry.fileName);
- zip.readEntry();
- return;
- }
+ const zip = await yauzl.fromBufferPromise(Buffer.from(buffer));
+ for await (const entry of zip.eachEntry()) {
+ if (entry.fileName.endsWith("/") || !FILES_TO_COPY.some(prefix => entry.fileName.startsWith(prefix))) {
+ // Directory entry or not in the list of files to copy, skip
+ console.log("Skipping", entry.fileName);
+ continue;
+ }
- const relativePath = entry.fileName.substring("web/".length);
- zip.openReadStream(entry, async (err, readStream) => {
- if (err) {
- console.error(`Failed to read ${entry.fileName} from zip:`, err);
- return;
- }
- const outPath = join(__dirname, "../viewer", relativePath);
- await fs.mkdir(dirname(outPath), { recursive: true });
- const outStream = createWriteStream(outPath);
- readStream.pipe(outStream);
- outStream.on("finish", () => {
- console.log(`Extracted ${relativePath} to ${outPath}`);
- });
- });
- zip.readEntry();
- });
- zip.on("end", async () => {
- console.log("Finished extracting pdfjs-dist files.");
- await patchViewerHTML();
- });
- });
+ const relativePath = entry.fileName.substring("web/".length);
+ const outPath = join(__dirname, "../viewer", relativePath);
+ await fs.mkdir(dirname(outPath), { recursive: true });
+ const readStream = await zip.openReadStreamPromise(entry);
+ await pipeline(readStream, createWriteStream(outPath));
+ console.log(`Extracted ${relativePath} to ${outPath}`);
+ }
+
+ console.log("Finished extracting pdfjs-dist files.");
+ await patchViewerHTML();
};
async function patchViewerHTML() {
diff --git a/packages/pdfjs-viewer/scripts/yauzl.d.ts b/packages/pdfjs-viewer/scripts/yauzl.d.ts
new file mode 100644
index 0000000000..62f370db6c
--- /dev/null
+++ b/packages/pdfjs-viewer/scripts/yauzl.d.ts
@@ -0,0 +1,20 @@
+/*
+ * Promise-based APIs introduced in yauzl 3.4.0 that are not yet covered by @types/yauzl.
+ * Remove once the upstream types catch up.
+ * See https://github.com/thejoshwolfe/yauzl/pull/171
+ */
+
+import type { Readable } from "stream";
+
+declare module "yauzl" {
+ export function fromBufferPromise(buffer: Buffer, options?: Options): Promise<ZipFile>;
+
+ interface ZipFile {
+ /**
+ * Async-iterator alternative to readEntry()/"entry" events. Requires lazyEntries: true
+ * (implied by the *Promise() open functions) and may only be called once per ZipFile.
+ */
+ eachEntry(): AsyncIterableIterator<Entry>;
+ openReadStreamPromise(entry: Entry, options?: ZipFileOptions): Promise<Readable>;
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 83dd837d38..77d1970f71 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -74,7 +74,7 @@ overrides:
hono@>=4.0.0 <=4.12.11: '>=4.12.12'
'@hono/node-server@<1.19.13': '>=1.19.13'
basic-ftp@=5.2.0: '>=5.2.1'
- extract-zip>yauzl: 3.3.2
+ extract-zip>yauzl: 3.4.0
patchedDependencies:
'@ckeditor/ckeditor5-code-block': 1530be090e4f5235e197fb6208a8e8230e3355d5633fc7cad2b2e892659e9c04
@@ -686,6 +686,9 @@ importers:
'@types/ws':
specifier: 8.18.1
version: 8.18.1
+ '@types/yauzl':
+ specifier: 3.3.0
+ version: 3.3.0
archiver:
specifier: 8.0.0
version: 8.0.0
@@ -1590,6 +1593,9 @@ importers:
pdfjs-dist:
specifier: 5.7.284
version: 5.7.284
+ yauzl:
+ specifier: 3.4.0
+ version: 3.4.0
packages/share-theme:
dependencies:
@@ -5713,6 +5719,9 @@ packages:
resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-7YJZZveDGYqCMt0PrN0sjZj9gT07xLqnHBimKwhWYTJ4lh5MxDGmaCaN4+6x1TOPt+dk3Ge8w9cO3uJXoy/qrA==}
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-QYb/sa74/s7OKMbACMjrYnGspj9Hs5YI5aaffSL65UfeBUzVzBJfVo3oWSpbzPurvm7yaCCo2Lk7lVj610HqKw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -13796,10 +13805,6 @@ packages:
resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==}
- resolution: {integrity: sha512-Md9ankxxN23wncAN8s7+Tn3Co52zLUPMtnrLAbVCnfG5d2tKBFfmygYSgXlqFgXObtzIgqkx7aNgDBpso9+4qA==}
- engines: {node: '>=12'}
-
resolution: {integrity: sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==}
engines: {node: '>=12'}
@@ -18922,6 +18927,10 @@ snapshots:
'@types/node': 24.13.1
optional: true
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 24.13.1
+
dependencies:
'@eslint-community/regexpp': 4.12.2
@@ -23340,7 +23349,7 @@ snapshots:
dependencies:
debug: 4.4.3
get-stream: 5.2.0
- yauzl: 3.3.2
+ yauzl: 3.4.0
optionalDependencies:
'@types/yauzl': 2.10.3
transitivePeerDependencies:
@@ -29257,10 +29266,6 @@ snapshots:
buffer-crc32: 0.2.13
fd-slicer: 1.1.0
- dependencies:
- pend: 1.2.0
-
dependencies:
pend: 1.2.0
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 12aed8a5f3..95f8ad697e 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -85,8 +85,8 @@ overrides:
"@hono/node-server@<1.19.13": ">=1.19.13"
"basic-ftp@=5.2.0": ">=5.2.1"
# extract-zip's yauzl@2 hangs electron-forge packaging on Node >=24.16 (electron/forge#4277,
- # electron/electron#51619). [email protected] is the maintainer-recommended fix.
- "extract-zip>yauzl": "3.3.2"
+ # electron/electron#51619). yauzl@>=3.3.1 is the maintainer-recommended fix.
+ "extract-zip>yauzl": "3.4.0"
patchedDependencies:
"@ckeditor/ckeditor5-mention": patches/@ckeditor__ckeditor5-mention.patch