Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(import): let the zip provider read an archive from a path in place
Elian Doran06db27a6f239
diff --git a/apps/server/src/zip_provider.spec.ts b/apps/server/src/zip_provider.spec.tsindex 6faf5e6c73..0692571a27 100644--- a/apps/server/src/zip_provider.spec.ts+++ b/apps/server/src/zip_provider.spec.ts@@ -1,6 +1,9 @@import type { ZipEntry } from "@triliumnext/core/src/services/zip_provider.js";+import { mkdtempSync, rmSync, writeFileSync } from "fs";+import { tmpdir } from "os";+import { join } from "path";import { PassThrough } from "stream";-import { describe, expect, it } from "vitest";+import { afterAll, describe, expect, it } from "vitest";import NodejsZipProvider from "./zip_provider.js";@@ -71,4 +74,54 @@ describe("NodejsZipProvider", () => {expect(Object.keys(entries).sort()).toEqual(["a.txt", "dir/b.txt"]);expect(entries["dir/b.txt"].toString("utf-8")).toBe("beta");});++ describe("reading from a path (in place, no full-buffer load)", () => {+ const dir = mkdtempSync(join(tmpdir(), "trilium-zip-provider-spec-"));+ afterAll(() => rmSync(dir, { recursive: true, force: true }));++ let zipCounter = 0;+ async function writeZip(entries: { name: string; content: string | Uint8Array }[]): Promise<string> {+ const buffer = await buildZip(entries);+ const path = join(dir, `zip-${zipCounter++}.zip`);+ writeFileSync(path, buffer);+ return path;+ }++ async function readPath(path: string): Promise<Record<string, Buffer>> {+ const out: Record<string, Buffer> = {};+ await provider.readZipFile({ path }, async (entry: ZipEntry, readContent) => {+ out[entry.fileName] = Buffer.from(await readContent());+ });+ return out;+ }++ it("reads entries straight from a file path", async () => {+ const path = await writeZip([+ { name: "a.txt", content: "alpha" },+ { name: "dir/b.txt", content: "beta" }+ ]);+ const entries = await readPath(path);+ expect(Object.keys(entries).sort()).toEqual(["a.txt", "dir/b.txt"]);+ expect(entries["dir/b.txt"].toString("utf-8")).toBe("beta");+ });++ it("yields byte-identical content whether read from a path or its bytes", async () => {+ const binary = new Uint8Array([0x89, 0x50, 0x00, 0xff, 0x80, 0x01]);+ const buffer = await buildZip([{ name: "pixel.png", content: binary }]);+ const path = join(dir, `roundtrip-${zipCounter++}.zip`);+ writeFileSync(path, buffer);++ const fromPath = await readPath(path);+ const fromBytes = await readZip(buffer);+ expect(Buffer.compare(fromPath["pixel.png"], fromBytes["pixel.png"])).toBe(0);+ });++ it("detects the same filename encoding from a path as from the bytes", async () => {+ const buffer = await buildZip([{ name: "plain.txt", content: "x" }]);+ const path = join(dir, `encoding-${zipCounter++}.zip`);+ writeFileSync(path, buffer);++ expect(await provider.detectFilenameEncoding({ path })).toBe(await provider.detectFilenameEncoding(buffer));+ });+ });});diff --git a/apps/server/src/zip_provider.ts b/apps/server/src/zip_provider.tsindex 83ed1daa8e..7e7d349e4f 100644--- a/apps/server/src/zip_provider.ts+++ b/apps/server/src/zip_provider.ts@@ -1,4 +1,4 @@-import type { FileStream, ZipArchive, ZipArchiveEntryOptions, ZipEntry, ZipProvider } from "@triliumnext/core/src/services/zip_provider.js";+import type { FileStream, ZipArchive, ZipArchiveEntryOptions, ZipEntry, ZipProvider, ZipSource } from "@triliumnext/core/src/services/zip_provider.js";import { ZipArchive as ArchiverZip } from "archiver";import fs from "fs";import type { Stream } from "stream";@@ -77,18 +77,34 @@ function streamToBuffer(stream: Stream): Promise<Buffer> {});}+async function openZip(source: ZipSource) {+ const options = { validateEntrySizes: false, decodeStrings: false };+ if (source instanceof Uint8Array) {+ // Wrap the bytes in a Buffer *view* (no copy); fall through to fromBuffer. A `path` source is+ // opened straight from disk so a multi-GB zip is never held in memory (and dodges fs.readFile's+ // ~2 GiB ceiling) — yauzl reads the central directory and each entry on demand from the fd.+ const buf = Buffer.isBuffer(source) ? source : Buffer.from(source.buffer, source.byteOffset, source.byteLength);+ return yauzl.fromBufferPromise(buf, options);+ }+ return yauzl.openPromise(source.path, options);+}+export default class NodejsZipProvider implements ZipProvider {- async detectFilenameEncoding(buffer: Uint8Array): Promise<string> {- const zipfile = await yauzl.fromBufferPromise(Buffer.from(buffer), {- validateEntrySizes: false,- decodeStrings: false- });+ async detectFilenameEncoding(source: ZipSource): Promise<string> {+ const zipfile = await openZip(source);const samples: Buffer[] = [];- for await (const entry of zipfile.eachEntry()) {- const isUtf8Flagged = !!(entry.generalPurposeBitFlag & 0x800);- if (!isUtf8Flagged) {- samples.push(entry.fileNameRaw);+ try {+ for await (const entry of zipfile.eachEntry()) {+ const isUtf8Flagged = !!(entry.generalPurposeBitFlag & 0x800);+ if (!isUtf8Flagged) {+ samples.push(entry.fileNameRaw);+ }+ }+ } finally {+ // Release the file descriptor for a path source (no-op for an already-closed buffer reader).+ if (zipfile.isOpen) {+ zipfile.close();}}@@ -121,29 +137,33 @@ export default class NodejsZipProvider implements ZipProvider {}async readZipFile(- buffer: Uint8Array,+ source: ZipSource,processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>,filenameEncoding?: string): Promise<void> {- 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);- };+ const zipfile = await openZip(source);- await processEntry({ fileName, lastModified: entry.getLastModDate() }, readContent);+ try {+ 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, lastModified: entry.getLastModDate() }, readContent);+ }+ } finally {+ // Release the file descriptor for a path source (no-op for an already-closed buffer reader).+ if (zipfile.isOpen) {+ zipfile.close();+ }}}}diff --git a/apps/standalone/src/lightweight/zip_provider.ts b/apps/standalone/src/lightweight/zip_provider.tsindex b4cf84e058..7fa963c705 100644--- a/apps/standalone/src/lightweight/zip_provider.ts+++ b/apps/standalone/src/lightweight/zip_provider.ts@@ -1,6 +1,14 @@-import type { FileStream, ZipArchive, ZipEntry, ZipProvider } from "@triliumnext/core/src/services/zip_provider.js";+import type { FileStream, ZipArchive, ZipEntry, ZipProvider, ZipSource } from "@triliumnext/core/src/services/zip_provider.js";import { strToU8, unzip, zipSync } from "fflate";+/** The browser/WASM build has no filesystem, so a `path` source is unsupported here — only raw bytes. */+function requireBuffer(source: ZipSource): Uint8Array {+ if (!(source instanceof Uint8Array)) {+ throw new Error("Path-based zip reading is not supported in the browser; uploads arrive as bytes.");+ }+ return source;+}+type ZipOutput = {send?: (body: unknown) => unknown;write?: (chunk: Uint8Array | string) => unknown;@@ -54,7 +62,8 @@ class BrowserZipArchive implements ZipArchive {}export default class BrowserZipProvider implements ZipProvider {- async detectFilenameEncoding(buffer: Uint8Array): Promise<string> {+ async detectFilenameEncoding(source: ZipSource): Promise<string> {+ const buffer = requireBuffer(source);// fflate decodes filenames as CP437/Latin-1 (preserving raw bytes).// We recover raw bytes and detect the encoding.const rawSamples = await this.#collectRawFilenameSamples(buffer);@@ -73,10 +82,11 @@ export default class BrowserZipProvider implements ZipProvider {}readZipFile(- buffer: Uint8Array,+ source: ZipSource,processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>,filenameEncoding?: string): Promise<void> {+ const buffer = requireBuffer(source);return new Promise<void>((res, rej) => {unzip(buffer, async (err, files) => {if (err) { rej(err); return; }diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.tsindex 8cc13c481d..564cfeb3a0 100644--- a/packages/trilium-core/src/services/import/zip.ts+++ b/packages/trilium-core/src/services/import/zip.ts@@ -1,6 +1,6 @@import { ALLOWED_NOTE_TYPES, type NoteType } from "@triliumnext/commons";import { basename, dirname } from "../utils/path.js";-import { getZipProvider } from "../zip_provider.js";+import { getZipProvider, type ZipSource } from "../zip_provider.js";import becca from "../../becca/becca.js";import BAttachment from "../../becca/entities/battachment.js";@@ -39,7 +39,7 @@ interface ImportZipOpts {preserveIds?: boolean;}-async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote, opts?: ImportZipOpts): Promise<BNote> {+async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSource, importRootNote: BNote, opts?: ImportZipOpts): Promise<BNote> {/** maps from original noteId (in ZIP file) to newly generated noteId */const noteIdMap: Record<string, string> = {};/** type maps from original attachmentId (in ZIP file) to newly generated attachmentId */@@ -665,7 +665,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Uiconst zipProvider = getZipProvider();// Detect filename encoding once for the whole ZIP (e.g. GBK for Chinese Windows ZIPs)- const filenameEncoding = await zipProvider.detectFilenameEncoding(fileBuffer);+ const filenameEncoding = await zipProvider.detectFilenameEncoding(source);// we're running two passes in order to obtain critical information first (meta file and root)const topLevelItems = new Set<string>();@@ -673,7 +673,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Ui// client can show a progress bar ("X of N") instead of a bare running countlet entriesToProcess = 0;- await zipProvider.readZipFile(fileBuffer, async (entry, readContent) => {+ await zipProvider.readZipFile(source, async (entry, readContent) => {const filePath = normalizeFilePath(entry.fileName);if (isMacOSMetadata(filePath)) {@@ -699,7 +699,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Ui// the processing pass increments progress once per entry; expose the total so the client shows a bartaskContext.setTotalCount(entriesToProcess);- await zipProvider.readZipFile(fileBuffer, async (entry, readContent) => {+ await zipProvider.readZipFile(source, async (entry, readContent) => {const filePath = normalizeFilePath(entry.fileName);if (isMacOSMetadata(filePath)) {diff --git a/packages/trilium-core/src/services/zip_provider.ts b/packages/trilium-core/src/services/zip_provider.tsindex 5addbc8836..b1ecb16bdc 100644--- a/packages/trilium-core/src/services/zip_provider.ts+++ b/packages/trilium-core/src/services/zip_provider.ts@@ -1,3 +1,10 @@+/**+ * A zip to read: either its raw bytes, or — server/desktop only — a filesystem path the provider opens+ * and reads *in place* (no full-buffer copy, no ~2 GiB `fs.readFile` ceiling). The browser/WASM provider+ * only supports the byte form.+ */+export type ZipSource = Uint8Array | { path: string };+export interface ZipEntry {fileName: string;/**@@ -42,19 +49,20 @@ export interface FileStream {export interface ZipProvider {/**- * Detects the filename encoding used in a ZIP file by collecting all- * non-UTF-8-flagged entry names and running charset detection on them.- * Returns the detected encoding label (usable with TextDecoder), or "utf-8" as fallback.+ * Detects the filename encoding used in a ZIP by collecting all non-UTF-8-flagged entry names and+ * running charset detection on them. Returns the detected encoding label (usable with TextDecoder),+ * or "utf-8" as fallback. Accepts raw bytes or — server/desktop only — a {@link ZipSource} path.*/- detectFilenameEncoding(buffer: Uint8Array): Promise<string>;+ detectFilenameEncoding(source: ZipSource): Promise<string>;/**- * Iterates over every entry in a ZIP buffer, calling `processEntry` for each one.- * `readContent()` inside the callback reads the raw bytes of that entry on demand.- * If `filenameEncoding` is provided, non-UTF-8-flagged filenames are decoded using it.+ * Iterates over every entry in a ZIP, calling `processEntry` for each one. `readContent()` inside the+ * callback reads the raw bytes of that entry on demand. If `filenameEncoding` is provided,+ * non-UTF-8-flagged filenames are decoded using it. Accepts raw bytes or — server/desktop only — a+ * {@link ZipSource} path, in which case the zip is read straight from disk per entry.*/readZipFile(- buffer: Uint8Array,+ source: ZipSource,processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>,filenameEncoding?: string): Promise<void>;