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): stream zip-based providers and expose native browse
Elian Doran248db684a5c4
diff --git a/apps/client/src/widgets/dialogs/import/anytype.tsx b/apps/client/src/widgets/dialogs/import/anytype.tsxindex 7be4676a8d..b5ed4094b3 100644--- a/apps/client/src/widgets/dialogs/import/anytype.tsx+++ b/apps/client/src/widgets/dialogs/import/anytype.tsx@@ -1,7 +1,6 @@-import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n.js";-import importService from "../../../services/import.js";import Button from "../../react/Button.js";import { Card, CardSection } from "../../react/Card.js";import FileDropZone from "../../react/FileDropZone.js";@@ -9,31 +8,18 @@ import { useTriliumOptionBool } from "../../react/hooks.js";import OptionsRow, { OptionsRowWithToggle } from "../../type_widgets/options/components/OptionsRow.js";import iconUrl from "./icons/anytype.svg?url";import type { ImportProvider, ImportProviderPanelProps } from "./types.js";+import useProviderImport from "./useProviderImport.js";function AnytypePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanelProps) {- const [file, setFile] = useState<File | null>(null);const [compressImages] = useTriliumOptionBool("compressImages");const [shrinkImages, setShrinkImages] = useState(compressImages);+ // `format: "anytype"` routes the upload/native import to the Anytype importer, overriding the .zip+ // extension's default (the generic zip importer).+ const { hasSelection, displayNames, onChange, onBrowse, doImport } = useProviderImport({ format: "anytype", parentNoteId, shrinkImages, closeDialog });- const onChange = useCallback((files: FileList | null) => setFile(files?.[0] ?? null), []);-- const doImport = useCallback(async () => {- if (!file) {- return;- }-- // Close immediately and let the shared import toasts (registered in import.ts) report progress,- // completion and any error. `format: "anytype"` routes the upload to the Anytype importer on the- // shared file-import endpoint, overriding the .zip extension's default (the generic zip importer).- // uploadFiles surfaces any upload error via its own toast; swallow the rejection so this void-ed- // call doesn't raise an unhandled rejection.- closeDialog();- await importService.uploadFiles("notes", parentNoteId, [file], { format: "anytype", safeImport: "true", shrinkImages: shrinkImages ? "true" : "false" }).catch(() => {});- }, [file, shrinkImages, parentNoteId, closeDialog]);-- // Keep the latest import handler in a ref so the footer effect depends only on `file` being present,- // never on doImport's identity — otherwise re-pushing the footer on every change would loop with the- // parent re-rendering us back (see the Notion/Keep panels for the same reasoning).+ // Keep the latest import handler in a ref so the footer effect depends only on whether a file is+ // selected, never on doImport's identity — otherwise re-pushing the footer on every change would loop+ // with the parent re-rendering us back (see the Notion/Keep panels for the same reasoning).const doImportRef = useRef(doImport);doImportRef.current = doImport;@@ -42,17 +28,17 @@ function AnytypePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa<Buttontext={t("anytype_import.import")}kind="primary"- disabled={!file}+ disabled={!hasSelection}onClick={() => void doImportRef.current()}/>);- }, [file, setFooter]);+ }, [hasSelection, setFooter]);return (<Card heading={t("anytype_import.choose_file")}><CardSection><OptionsRow name="import-file" description={t("anytype_import.description_long")} stacked>- <FileDropZone onChange={onChange} accept=".zip" />+ <FileDropZone onChange={onChange} onBrowse={onBrowse} displayNames={displayNames} accept=".zip" /></OptionsRow><OptionsRowWithTogglename="shrink-images"diff --git a/apps/client/src/widgets/dialogs/import/keep.tsx b/apps/client/src/widgets/dialogs/import/keep.tsxindex 34a3da5bb9..7e0a6ae20d 100644--- a/apps/client/src/widgets/dialogs/import/keep.tsx+++ b/apps/client/src/widgets/dialogs/import/keep.tsx@@ -1,7 +1,6 @@-import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n.js";-import importService from "../../../services/import.js";import Button from "../../react/Button.js";import { Card, CardSection } from "../../react/Card.js";import FileDropZone from "../../react/FileDropZone.js";@@ -9,31 +8,18 @@ import { useTriliumOptionBool } from "../../react/hooks.js";import OptionsRow, { OptionsRowWithToggle } from "../../type_widgets/options/components/OptionsRow.js";import iconUrl from "./icons/keep.svg?url";import type { ImportProvider, ImportProviderPanelProps } from "./types.js";+import useProviderImport from "./useProviderImport.js";function KeepPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanelProps) {- const [file, setFile] = useState<File | null>(null);const [compressImages] = useTriliumOptionBool("compressImages");const [shrinkImages, setShrinkImages] = useState(compressImages);+ // `format: "keep"` routes the upload/native import to the Google Keep importer, overriding the .zip+ // extension's default (the generic zip importer).+ const { hasSelection, displayNames, onChange, onBrowse, doImport } = useProviderImport({ format: "keep", parentNoteId, shrinkImages, closeDialog });- const onChange = useCallback((files: FileList | null) => setFile(files?.[0] ?? null), []);-- const doImport = useCallback(async () => {- if (!file) {- return;- }-- // Close immediately and let the shared import toasts (registered in import.ts) report progress,- // completion and any error. `format: "keep"` routes the upload to the Google Keep importer on the- // shared file-import endpoint, overriding the .zip extension's default (the generic zip importer).- // uploadFiles surfaces any upload error via its own toast; swallow the rejection so this void-ed- // call doesn't raise an unhandled rejection.- closeDialog();- await importService.uploadFiles("notes", parentNoteId, [file], { format: "keep", safeImport: "true", shrinkImages: shrinkImages ? "true" : "false" }).catch(() => {});- }, [file, shrinkImages, parentNoteId, closeDialog]);-- // Keep the latest import handler in a ref so the footer effect depends only on `file` being present,- // never on doImport's identity — otherwise re-pushing the footer on every change would loop with the- // parent re-rendering us back (see the Notion/OneNote panels for the same reasoning).+ // Keep the latest import handler in a ref so the footer effect depends only on whether a file is+ // selected, never on doImport's identity — otherwise re-pushing the footer on every change would loop+ // with the parent re-rendering us back (see the Notion/OneNote panels for the same reasoning).const doImportRef = useRef(doImport);doImportRef.current = doImport;@@ -42,17 +28,17 @@ function KeepPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanel<Buttontext={t("keep_import.import")}kind="primary"- disabled={!file}+ disabled={!hasSelection}onClick={() => void doImportRef.current()}/>);- }, [file, setFooter]);+ }, [hasSelection, setFooter]);return (<Card heading={t("keep_import.choose_file")}><CardSection><OptionsRow name="import-file" description={t("keep_import.description_long")} stacked>- <FileDropZone onChange={onChange} accept=".zip" />+ <FileDropZone onChange={onChange} onBrowse={onBrowse} displayNames={displayNames} accept=".zip" /></OptionsRow><OptionsRowWithTogglename="shrink-images"diff --git a/apps/client/src/widgets/dialogs/import/notion.tsx b/apps/client/src/widgets/dialogs/import/notion.tsxindex 3df669f5d6..52fc875095 100644--- a/apps/client/src/widgets/dialogs/import/notion.tsx+++ b/apps/client/src/widgets/dialogs/import/notion.tsx@@ -1,7 +1,6 @@-import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n.js";-import importService from "../../../services/import.js";import Button from "../../react/Button.js";import { Card, CardSection } from "../../react/Card.js";import FileDropZone from "../../react/FileDropZone.js";@@ -9,31 +8,18 @@ import { useTriliumOptionBool } from "../../react/hooks.js";import OptionsRow, { OptionsRowWithToggle } from "../../type_widgets/options/components/OptionsRow.js";import iconUrl from "./icons/notion.svg?url";import type { ImportProvider, ImportProviderPanelProps } from "./types.js";+import useProviderImport from "./useProviderImport.js";function NotionPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanelProps) {- const [file, setFile] = useState<File | null>(null);const [compressImages] = useTriliumOptionBool("compressImages");const [shrinkImages, setShrinkImages] = useState(compressImages);+ // `format: "notion"` routes the upload/native import to the Notion importer, overriding the .zip+ // extension's default (the generic zip importer).+ const { hasSelection, displayNames, onChange, onBrowse, doImport } = useProviderImport({ format: "notion", parentNoteId, shrinkImages, closeDialog });- const onChange = useCallback((files: FileList | null) => setFile(files?.[0] ?? null), []);-- const doImport = useCallback(async () => {- if (!file) {- return;- }-- // Close immediately and let the shared import toasts (registered in import.ts) report progress,- // completion and any error. `format: "notion"` routes the upload to the Notion importer on the- // shared file-import endpoint, overriding the .zip extension's default (the generic zip importer).- // uploadFiles surfaces any upload error via its own toast; swallow the rejection so this void-ed- // call doesn't raise an unhandled rejection.- closeDialog();- await importService.uploadFiles("notes", parentNoteId, [file], { format: "notion", safeImport: "true", shrinkImages: shrinkImages ? "true" : "false" }).catch(() => {});- }, [file, shrinkImages, parentNoteId, closeDialog]);-- // Keep the latest import handler in a ref so the footer effect depends only on `file` being present,- // never on doImport's identity — otherwise re-pushing the footer on every change would loop with the- // parent re-rendering us back (see the OneNote panel for the same reasoning).+ // Keep the latest import handler in a ref so the footer effect depends only on whether a file is+ // selected, never on doImport's identity — otherwise re-pushing the footer on every change would loop+ // with the parent re-rendering us back (see the OneNote panel for the same reasoning).const doImportRef = useRef(doImport);doImportRef.current = doImport;@@ -42,17 +28,17 @@ function NotionPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPan<Buttontext={t("notion_import.import")}kind="primary"- disabled={!file}+ disabled={!hasSelection}onClick={() => void doImportRef.current()}/>);- }, [file, setFooter]);+ }, [hasSelection, setFooter]);return (<Card heading={t("notion_import.choose_file")}><CardSection><OptionsRow name="import-file" description={t("notion_import.description_long")} stacked>- <FileDropZone onChange={onChange} accept=".zip" />+ <FileDropZone onChange={onChange} onBrowse={onBrowse} displayNames={displayNames} accept=".zip" /></OptionsRow><OptionsRowWithTogglename="shrink-images"diff --git a/apps/client/src/widgets/dialogs/import/obsidian.tsx b/apps/client/src/widgets/dialogs/import/obsidian.tsxindex b6cf7222c4..dc6a9d5931 100644--- a/apps/client/src/widgets/dialogs/import/obsidian.tsx+++ b/apps/client/src/widgets/dialogs/import/obsidian.tsx@@ -1,7 +1,6 @@-import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n.js";-import importService from "../../../services/import.js";import Button from "../../react/Button.js";import { Card, CardSection } from "../../react/Card.js";import FileDropZone from "../../react/FileDropZone.js";@@ -9,31 +8,18 @@ import { useTriliumOptionBool } from "../../react/hooks.js";import { OptionsRowWithToggle } from "../../type_widgets/options/components/OptionsRow.js";import iconUrl from "./icons/obsidian.svg?url";import type { ImportProvider, ImportProviderPanelProps } from "./types.js";+import useProviderImport from "./useProviderImport.js";function ObsidianPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanelProps) {- const [file, setFile] = useState<File | null>(null);const [compressImages] = useTriliumOptionBool("compressImages");const [shrinkImages, setShrinkImages] = useState(compressImages);+ // `format: "obsidian"` routes the upload/native import to the Obsidian importer, overriding the .zip+ // extension's default (the generic zip importer).+ const { hasSelection, displayNames, onChange, onBrowse, doImport } = useProviderImport({ format: "obsidian", parentNoteId, shrinkImages, closeDialog });- const onChange = useCallback((files: FileList | null) => setFile(files?.[0] ?? null), []);-- const doImport = useCallback(async () => {- if (!file) {- return;- }-- // Close immediately and let the shared import toasts (registered in import.ts) report progress,- // completion and any error. `format: "obsidian"` routes the upload to the Obsidian importer on the- // shared file-import endpoint, overriding the .zip extension's default (the generic zip importer).- // uploadFiles surfaces any upload error via its own toast; swallow the rejection so this void-ed- // call doesn't raise an unhandled rejection.- closeDialog();- await importService.uploadFiles("notes", parentNoteId, [file], { format: "obsidian", safeImport: "true", shrinkImages: shrinkImages ? "true" : "false" }).catch(() => {});- }, [file, shrinkImages, parentNoteId, closeDialog]);-- // Keep the latest import handler in a ref so the footer effect depends only on `file` being present,- // never on doImport's identity — otherwise re-pushing the footer on every change would loop with the- // parent re-rendering us back (see the Anytype/Notion panels for the same reasoning).+ // Keep the latest import handler in a ref so the footer effect depends only on whether a file is+ // selected, never on doImport's identity — otherwise re-pushing the footer on every change would loop+ // with the parent re-rendering us back (see the Anytype/Notion panels for the same reasoning).const doImportRef = useRef(doImport);doImportRef.current = doImport;@@ -42,17 +28,17 @@ function ObsidianPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderP<Buttontext={t("obsidian_import.import")}kind="primary"- disabled={!file}+ disabled={!hasSelection}onClick={() => void doImportRef.current()}/>);- }, [file, setFooter]);+ }, [hasSelection, setFooter]);return (<Card heading={t("obsidian_import.choose_file")}><CardSection><p className="import-files-description">{t("obsidian_import.description_long")}</p>- <FileDropZone onChange={onChange} />+ <FileDropZone onChange={onChange} onBrowse={onBrowse} displayNames={displayNames} /><OptionsRowWithTogglename="shrink-images"label={t("import.shrinkImages")}diff --git a/apps/client/src/widgets/dialogs/import/useProviderImport.ts b/apps/client/src/widgets/dialogs/import/useProviderImport.tsnew file mode 100644index 0000000000..231059da5a--- /dev/null+++ b/apps/client/src/widgets/dialogs/import/useProviderImport.ts@@ -0,0 +1,80 @@+import type { NativeImportOptions, NativeImportPickedFile } from "@triliumnext/commons";+import { useCallback, useState } from "preact/hooks";++import importService from "../../../services/import.js";+import utils from "../../../services/utils.js";++interface ProviderImportArgs {+ /** Importer tag (e.g. "obsidian") routing both the upload and the native import. */+ format: string;+ parentNoteId: string;+ shrinkImages: boolean;+ closeDialog: () => void;+}++interface ProviderImport {+ /** Whether a file is selected (either route), used to enable the Import button. */+ hasSelection: boolean;+ /** Native-pick filename(s) to show in the drop zone; undefined when using the upload route. */+ displayNames?: string[];+ onChange: (files: FileList | null) => void;+ /** Desktop-only native browse (reads the zip in place); undefined elsewhere. */+ onBrowse?: () => void;+ doImport: () => Promise<void>;+}++/**+ * Selection + import logic shared by the zip-based provider panels (Obsidian/Anytype/Notion/Keep). They all+ * take a single tagged `.zip`: on desktop, "browse" opens the native dialog so the archive is read in place+ * (streamed, memory-bounded), while drag-and-drop keeps the upload route. The two selections are mutually+ * exclusive — choosing one clears the other.+ */+export default function useProviderImport({ format, parentNoteId, shrinkImages, closeDialog }: ProviderImportArgs): ProviderImport {+ const [file, setFile] = useState<File | null>(null);+ const [nativeFile, setNativeFile] = useState<NativeImportPickedFile | null>(null);++ const onChange = useCallback((files: FileList | null) => {+ setFile(files?.[0] ?? null);+ if (files?.length) {+ setNativeFile(null);+ }+ }, []);++ const browse = useCallback(async () => {+ const pick = await window.electronApi?.nativeImport.pickFiles();+ if (pick?.status !== "selected" || !pick.files?.length) {+ return;+ }+ setFile(null);+ setNativeFile(pick.files[0]);+ }, []);++ const doImport = useCallback(async () => {+ // Close immediately and let the shared import toasts (registered in import.ts) report progress,+ // completion and any error. Swallow rejections so these void-ed calls don't raise unhandled ones.+ if (nativeFile) {+ const options: NativeImportOptions = {+ safeImport: true, shrinkImages, textImportedAsText: true, codeImportedAsCode: true,+ spreadsheetImportedAsSpreadsheet: true, explodeArchives: true, replaceUnderscoresWithSpaces: true+ };+ closeDialog();+ await window.electronApi?.nativeImport.importFromToken({+ token: nativeFile.token, parentNoteId, taskId: utils.randomString(10), options, last: true, format+ }).catch(() => {});+ return;+ }+ if (!file) {+ return;+ }+ closeDialog();+ await importService.uploadFiles("notes", parentNoteId, [file], { format, safeImport: "true", shrinkImages: shrinkImages ? "true" : "false" }).catch(() => {});+ }, [file, nativeFile, shrinkImages, format, parentNoteId, closeDialog]);++ return {+ hasSelection: !!file || !!nativeFile,+ displayNames: nativeFile ? [nativeFile.fileName] : undefined,+ onChange,+ onBrowse: utils.isElectron() ? () => void browse() : undefined,+ doImport+ };+}diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex ed4260de3c..a8d50ed506 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -214,7 +214,7 @@ contextBridge.exposeInMainWorld("electronApi", {pickFiles() {return ipcRenderer.invoke("import-pick-files");},- importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions; last: boolean }) {+ importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions; last: boolean; format?: string }) {return ipcRenderer.invoke("import-from-token", opts);}},diff --git a/apps/desktop/src/services/import.spec.ts b/apps/desktop/src/services/import.spec.tsindex 991d0b8e98..ae7a77c400 100644--- a/apps/desktop/src/services/import.spec.ts+++ b/apps/desktop/src/services/import.spec.ts@@ -151,6 +151,20 @@ describe("desktop native import — capability token", () => {}});+ it("forwards a provider format and still streams the tagged zip from path (not read into a buffer)", async () => {+ electronMock.showOpenDialogSync.mockReturnValue(["/data/vault.zip"]);+ const { files } = await pick();++ await importFromToken({ token: files?.[0].token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: true, format: "obsidian" });++ const [, file, , , format] = coreMock.dispatch.mock.calls[0];+ expect(format).toBe("obsidian");+ // A tagged provider zip is streamed in place: empty buffer + path, never read here.+ expect(file).toMatchObject({ originalname: "vault.zip", path: "/data/vault.zip" });+ expect((file as { buffer: Buffer }).buffer.length).toBe(0);+ expect(fsMock.readFile).not.toHaveBeenCalled();+ });+it("rejects an unknown/forged token without importing (a script can't supply a path or guess a token)", async () => {const result = await importFromToken({ token: "forged-token", parentNoteId: "parent1", taskId: "t", options: OPTIONS, last: true });diff --git a/apps/desktop/src/services/import.ts b/apps/desktop/src/services/import.tsindex 6ab498efd5..bceb06527b 100644--- a/apps/desktop/src/services/import.ts+++ b/apps/desktop/src/services/import.ts@@ -12,6 +12,8 @@ interface ImportFromTokenOpts {options: NativeImportOptions;/** Set only on the final file of a batch, so the success toast fires once everything is imported. */last: boolean;+ /** Routes the file to a specific importer (e.g. "obsidian"); the provider dialogs set this. */+ format?: string;}/**@@ -96,8 +98,8 @@ async function runNativeImport(path: string, opts: ImportFromTokenOpts): Promisecls.disableEntityEvents();cls.ignoreEntityChangeIds();- const file = await buildImportFile(path, options.explodeArchives);- const result = await importDispatchService(taskContext, file, parentNote, options);+ const file = await buildImportFile(path, options.explodeArchives, opts.format);+ const result = await importDispatchService(taskContext, file, parentNote, options, opts.format);// Import ran with entity events disabled, so becca wasn't updated incrementally — force a reload.// Must run inside the CLS context: becca_loader.load() toggles slow-query logging via the namespace.@@ -120,17 +122,18 @@ async function runNativeImport(path: string, opts: ImportFromTokenOpts): Promise}/**- * Builds the {@link File} the importer expects from a path on disk. A zip that will be exploded is left- * unbuffered (an empty buffer + the `path`) so it streams per entry; every other file is small enough to- * read into memory here. The MIME is resolved by the importer from the filename, so it's left blank.+ * Builds the {@link File} the importer expects from a path on disk. A zip that's read in place — a generic+ * zip that will be exploded, or any tagged provider zip (obsidian/anytype/notion/keep) — is left unbuffered+ * (an empty buffer + the `path`) so it streams per entry; every other file is small enough to read into+ * memory here. The MIME is resolved by the importer from the filename, so it's left blank.*/-async function buildImportFile(path: string, explodeArchives: boolean): Promise<File> {+async function buildImportFile(path: string, explodeArchives: boolean, format?: string): Promise<File> {const fileName = basename(path);- const isExplodableZip = extname(fileName).toLowerCase() === ".zip" && explodeArchives;+ const streamsFromPath = !!format || (extname(fileName).toLowerCase() === ".zip" && explodeArchives);return {originalname: fileName,mimetype: "",- buffer: isExplodableZip ? Buffer.alloc(0) : await readFile(path),+ buffer: streamsFromPath ? Buffer.alloc(0) : await readFile(path),path};}diff --git a/apps/server/src/routes/route_api.spec.ts b/apps/server/src/routes/route_api.spec.tsindex c94ef02c72..f390b1bd75 100644--- a/apps/server/src/routes/route_api.spec.ts+++ b/apps/server/src/routes/route_api.spec.ts@@ -47,16 +47,18 @@ describe("importMiddlewareWithErrorHandling (disk storage)", () => {expect(res.body.tempPresent).toBe(false);});- it("buffers a .zip when a provider format tags it (e.g. notion), rather than streaming", async () => {+ it("streams a .zip tagged with a provider format (e.g. notion) from its temp path too", async () => {const res = await request(buildApp()).post("/import").field("format", "notion").attach("upload", Buffer.from("notion-zip"), "export.zip");expect(res.status).toBe(200);- // Tagged providers go through their buffer-based importer, so it's materialized + cleaned up.- expect(res.body.content).toBe("notion-zip");- expect(res.body.tempPresent).toBe(false);+ // Provider importers now read the archive in place via file.path, so it isn't buffered and the+ // temp file is kept for the duration of the import.+ expect(res.body.content).toBeUndefined();+ expect(res.body.hasPath).toBe(true);+ expect(res.body.tempPresent).toBe(true);});it("buffers a .zip when explodeArchives is disabled (imported as a single file)", async () => {diff --git a/apps/server/src/routes/route_api.ts b/apps/server/src/routes/route_api.tsindex cac34ee1be..4cfa809423 100644--- a/apps/server/src/routes/route_api.ts+++ b/apps/server/src/routes/route_api.ts@@ -228,9 +228,10 @@ export const importMiddlewareWithErrorHandling = function (req: express.Request,const file = req.file;if (file?.path && isStreamableZipUpload(req)) {- // Generic `.zip` import: hand the importer the temp file's path so the archive is read in- // place per entry (the route prefers `file.path`), never buffered. Keep the temp file alive- // through the import and delete it once the response is done (or the connection drops).+ // Zip import (generic *or* a tagged provider): hand the importer the temp file's path so the+ // archive is read in place per entry (the route prefers `file.path`), never buffered. Keep the+ // temp file alive through the import and delete it once the response is done (or the connection+ // drops).const tempPath = file.path;res.on("close", () => void rm(tempPath, { force: true }).catch(() => {}));next();@@ -242,20 +243,24 @@ export const importMiddlewareWithErrorHandling = function (req: express.Request,};/**- * Whether this upload is a plain `.zip` the generic zip importer will read — the case worth streaming from- * disk. Tagged provider uploads (notion/keep/anytype/obsidian) and non-zip files go through buffer-based- * importers, so they take the {@link materializeUploadedImport} path instead. Kept in sync with the- * generic-zip branch in the core import route (routes/api/import.ts).+ * Whether this upload is a `.zip` read by a zip-reading importer — the case worth streaming from disk. That+ * covers both the generic zip importer and the tagged providers (notion/keep/anytype/obsidian), which all+ * read the archive via the zip provider and now accept a path. Non-zip files, and a generic `.zip` the user+ * chose not to explode, go through the buffer-based {@link materializeUploadedImport} path instead. Kept in+ * sync with the zip branches in the core import route (services/import/dispatch.ts).*/function isStreamableZipUpload(req: express.Request): boolean {const body = req.body as Record<string, string> | undefined;- if (body?.format) {+ const isZip = req.file?.originalname?.toLowerCase().endsWith(".zip") ?? false;+ if (!isZip) {return false;}- if (body?.explodeArchives === "false") {- return false;+ // A tagged provider always reads its zip regardless of the explode toggle; only the generic importer+ // honours `explodeArchives=false` (storing the zip as a single attachment, which needs the buffer).+ if (body?.format) {+ return true;}- return req.file?.originalname?.toLowerCase().endsWith(".zip") ?? false;+ return body?.explodeArchives !== "false";}/**diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex 6dfcd09ab4..98a20b4210 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -580,9 +580,10 @@ export interface ElectronNativeImportApi {/*** Imports the file behind `token` into `parentNoteId`. Progress/success/error are reported over the* WebSocket via `taskId`, matching the HTTP import path. When importing several files in one batch, set- * `last` only on the final call so the success toast fires once, after everything is in.+ * `last` only on the final call so the success toast fires once, after everything is in. `format` routes+ * the file to a specific importer (e.g. "obsidian"), mirroring the HTTP route's format tag.*/- importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions; last: boolean }): Promise<NativeImportResult>;+ importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions; last: boolean; format?: string }): Promise<NativeImportResult>;}/**diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.tsindex 93102bd368..9dd36b7e74 100644--- a/packages/trilium-core/src/services/import/anytype/importer.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.ts@@ -38,14 +38,14 @@ import { decodeUtf8 } from "../../utils/binary.js";import date_utils from "../../utils/date.js";import { newEntityId } from "../../utils/index.js";import { basename } from "../../utils/path.js";-import { getZipProvider } from "../../zip_provider.js";+import { getZipProvider, type ZipSource } from "../../zip_provider.js";import { saveFileAttachment } from "../collection_utils.js";import { applyCollectionView, applyFiles, applyProperties, buildFileObjectMap, buildOptionMap, buildRelationMap, createCollectionNote, normalizePath, parseCollection, parseFiles, parseProperties, synthesizeColumns } from "./collection.js";import { extractContent } from "./content.js";import type { AnytypeDetails, AnytypeSnapshot, FileObjectInfo, LinkResolver, ParsedColumn, ParsedObject, RelationInfo, ResolvedLink } from "./model.js";-async function importAnytype(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote, fileName?: string): Promise<BNote> {- const { objects, relations, options, fileObjects, files, protobufObjectCount, markdownFileCount } = await parseZip(fileBuffer);+async function importAnytype(taskContext: TaskContext<"importNotes">, source: ZipSource, importRootNote: BNote, fileName?: string): Promise<BNote> {+ const { objects, relations, options, fileObjects, files, protobufObjectCount, markdownFileCount } = await parseZip(source);const relationMap = buildRelationMap(relations);const optionMap = buildOptionMap(options);const fileObjectMap = buildFileObjectMap(fileObjects);@@ -118,7 +118,7 @@ async function importAnytype(taskContext: TaskContext<"importNotes">, fileBuffer* `*.md` (Markdown) entries are merely counted, so the caller can fail with guidance instead of importing an* empty tree.*/-async function parseZip(fileBuffer: Uint8Array): Promise<{ objects: AnytypeSnapshot[]; relations: AnytypeSnapshot[]; options: AnytypeSnapshot[]; fileObjects: AnytypeSnapshot[]; files: Map<string, Uint8Array>; protobufObjectCount: number; markdownFileCount: number }> {+async function parseZip(source: ZipSource): Promise<{ objects: AnytypeSnapshot[]; relations: AnytypeSnapshot[]; options: AnytypeSnapshot[]; fileObjects: AnytypeSnapshot[]; files: Map<string, Uint8Array>; protobufObjectCount: number; markdownFileCount: number }> {const provider = getZipProvider();const objects: AnytypeSnapshot[] = [];const relations: AnytypeSnapshot[] = [];@@ -127,9 +127,9 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ objects: AnytypeSnapsconst files = new Map<string, Uint8Array>();let protobufObjectCount = 0;let markdownFileCount = 0;- const filenameEncoding = await provider.detectFilenameEncoding(fileBuffer);+ const filenameEncoding = await provider.detectFilenameEncoding(source);- await provider.readZipFile(fileBuffer, async (entry, readContent) => {+ await provider.readZipFile(source, async (entry, readContent) => {// Raw bytes under files/ are kept as-is (they back file-property attachments), not parsed as JSON.if (isFileEntry(entry.fileName)) {files.set(normalizePath(entry.fileName), await readContent());diff --git a/packages/trilium-core/src/services/import/dispatch.ts b/packages/trilium-core/src/services/import/dispatch.tsindex c68391d51b..1ff395a9a4 100644--- a/packages/trilium-core/src/services/import/dispatch.ts+++ b/packages/trilium-core/src/services/import/dispatch.ts@@ -1,6 +1,7 @@import type BNote from "../../becca/entities/bnote.js";import type TaskContext from "../task_context.js";import { extname } from "../utils/path.js";+import type { ZipSource } from "../zip_provider.js";import anytypeImportService from "./anytype/importer.js";import type { File } from "./common.js";import enexImportService from "./enex.js";@@ -36,28 +37,31 @@ export interface ImportOptions {export default async function importFile(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote, options: ImportOptions, format?: string): Promise<BNote | (string | number)[] | null> {const extension = extname(file.originalname).toLowerCase();- if (format === "notion" && typeof file.buffer !== "string") {+ // Every zip-reading importer (generic + the tagged providers) reads the archive straight from the temp+ // file (server disk storage / native pick) so a multi-GB zip is streamed per entry — never held in one+ // buffer, and free of fs.readFile's ~2 GiB ceiling. Falls back to the buffer when there's no path (the+ // browser/WASM upload). The `typeof file.buffer !== "string"` guards below ensure the no-path fallback+ // is real bytes, not a string body.+ const zipSource: ZipSource = file.path ? { path: file.path } : file.buffer as Uint8Array;++ if (format === "notion" && (file.path || typeof file.buffer !== "string")) {// An explicit format always wins over extension sniffing: a Notion export is just a `.zip`,// indistinguishable from a Trilium export without inspecting its contents. The Notion import// dialog tags the upload, so we route it to the Notion importer rather than the generic zip.- return await notionImportService.importNotion(taskContext, file.buffer, parentNote);- } else if (format === "keep" && typeof file.buffer !== "string") {+ return await notionImportService.importNotion(taskContext, zipSource, parentNote);+ } else if (format === "keep" && (file.path || typeof file.buffer !== "string")) {// Like Notion, a Google Keep (Takeout) export is just a `.zip` indistinguishable from a Trilium// export by extension alone, so the Keep import dialog tags the upload to route it here.- return await keepImportService.importKeep(taskContext, file.buffer, parentNote);- } else if (format === "anytype" && typeof file.buffer !== "string") {+ return await keepImportService.importKeep(taskContext, zipSource, parentNote);+ } else if (format === "anytype" && (file.path || typeof file.buffer !== "string")) {// An Anytype JSON export is likewise a plain `.zip`; the Anytype import dialog tags the upload so// it routes to the Anytype importer rather than the generic zip importer.- return await anytypeImportService.importAnytype(taskContext, file.buffer, parentNote, file.originalname);- } else if (format === "obsidian" && typeof file.buffer !== "string") {+ return await anytypeImportService.importAnytype(taskContext, zipSource, parentNote, file.originalname);+ } else if (format === "obsidian" && (file.path || typeof file.buffer !== "string")) {// An Obsidian vault is exported as a plain `.zip` of Markdown files, indistinguishable from a// Trilium export by extension alone; the Obsidian import dialog tags the upload to route it here.- return await obsidianImportService.importObsidian(taskContext, file.buffer, parentNote, file.originalname);- } else if (extension === ".zip" && options.explodeArchives && typeof file.buffer !== "string") {- // Prefer reading the archive straight from the temp file (server disk storage / native pick) so a- // multi-GB zip is streamed per entry — never held in one buffer, and free of fs.readFile's- // ~2 GiB ceiling. Falls back to the buffer when there's no path (the browser/WASM upload).- const zipSource = file.path ? { path: file.path } : file.buffer;+ return await obsidianImportService.importObsidian(taskContext, zipSource, parentNote, file.originalname);+ } else if (extension === ".zip" && options.explodeArchives && (file.path || typeof file.buffer !== "string")) {return await zipImportService.importZip(taskContext, zipSource, parentNote);} else if (extension === ".opml" && options.explodeArchives) {return await opmlImportService.importOpml(taskContext, file.buffer, parentNote);diff --git a/packages/trilium-core/src/services/import/keep/importer.ts b/packages/trilium-core/src/services/import/keep/importer.tsindex 632860b942..d2c06a4e2f 100644--- a/packages/trilium-core/src/services/import/keep/importer.ts+++ b/packages/trilium-core/src/services/import/keep/importer.ts@@ -23,7 +23,7 @@ import { sanitizeHtml } from "../../sanitizer.js";import type TaskContext from "../../task_context.js";import { decodeUtf8 } from "../../utils/binary.js";import dateUtils from "../../utils/date.js";-import { getZipProvider } from "../../zip_provider.js";+import { getZipProvider, type ZipSource } from "../../zip_provider.js";import mimeService from "../mime.js";import { convertKeepHtml, convertKeepHtmlInline } from "./converter.js";@@ -81,8 +81,8 @@ interface ParsedNote {utcDateModified?: string;}-async function importKeep(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote): Promise<BNote> {- const { notes, binaries } = await parseNotes(fileBuffer);+async function importKeep(taskContext: TaskContext<"importNotes">, source: ZipSource, importRootNote: BNote): Promise<BNote> {+ const { notes, binaries } = await parseNotes(source);taskContext.setTotalCount(notes.length);return createNotes(importRootNote, notes, binaries, taskContext);@@ -93,13 +93,13 @@ async function importKeep(taskContext: TaskContext<"importNotes">, fileBuffer: U* (keyed by its base file name) so notes can later resolve the files they reference. The redundant per-note* `.html`/`.txt` and the `Labels.txt` index are skipped.*/-async function parseNotes(fileBuffer: Uint8Array): Promise<{ notes: ParsedNote[]; binaries: Map<string, Uint8Array> }> {+async function parseNotes(source: ZipSource): Promise<{ notes: ParsedNote[]; binaries: Map<string, Uint8Array> }> {const provider = getZipProvider();- const filenameEncoding = await provider.detectFilenameEncoding(fileBuffer);+ const filenameEncoding = await provider.detectFilenameEncoding(source);const notes: ParsedNote[] = [];const binaries = new Map<string, Uint8Array>();- await provider.readZipFile(fileBuffer, async (entry, readContent) => {+ await provider.readZipFile(source, async (entry, readContent) => {const path = entry.fileName;if (isDirectory(path)) {return;diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.tsindex a4e3af0f93..29feef86f0 100644--- a/packages/trilium-core/src/services/import/notion/importer.ts+++ b/packages/trilium-core/src/services/import/notion/importer.ts@@ -24,7 +24,7 @@ import protectedSessionService from "../../protected_session.js";import { sanitizeHtml } from "../../sanitizer.js";import type TaskContext from "../../task_context.js";import dateUtils from "../../utils/date.js";-import { getZipProvider } from "../../zip_provider.js";+import { getZipProvider, type ZipSource } from "../../zip_provider.js";import mimeService from "../mime.js";import { toAttributeName } from "../collection_utils.js";import { applyDatabaseSchemas, applyOwnedProperties, applyRelationProperties, extractProperties, reconcileDateColumns, resolveDatabaseContainers } from "./collection.js";@@ -33,8 +33,8 @@ import type { LinkTarget, ParsedPage } from "./model.js";import { getNotionId, stripNotionId } from "./notion_id.js";import { baseName, firstChildNotionId, folderDepth, internalPageId, isDirectory, normalizePath, ownedFolderKey, parentFolderKey, removeExtension, resolveResourcePath } from "./paths.js";-async function importNotion(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote): Promise<BNote> {- const { pages, resources, csvPaths, csvColumnsByFolder, markdownFileCount, csvRowTitles } = await parseZip(fileBuffer);+async function importNotion(taskContext: TaskContext<"importNotes">, source: ZipSource, importRootNote: BNote): Promise<BNote> {+ const { pages, resources, csvPaths, csvColumnsByFolder, markdownFileCount, csvRowTitles } = await parseZip(source);if (pages.length === 0 && markdownFileCount > 0) {// The user exported from Notion as "Markdown & CSV", but this importer only understands the HTML// export — it reconstructs databases by correlating each `.csv` with the surrounding `.html` pages,@@ -75,7 +75,7 @@ async function importNotion(taskContext: TaskContext<"importNotes">, fileBuffer:*/const MAX_NESTED_ZIP_DEPTH = 2;-async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[]; resources: Map<string, Uint8Array>; csvPaths: string[]; csvColumnsByFolder: Map<string, string[]>; markdownFileCount: number; csvRowTitles: Set<string> }> {+async function parseZip(source: ZipSource): Promise<{ pages: ParsedPage[]; resources: Map<string, Uint8Array>; csvPaths: string[]; csvColumnsByFolder: Map<string, string[]>; markdownFileCount: number; csvRowTitles: Set<string> }> {const provider = getZipProvider();const pages: ParsedPage[] = [];const resources = new Map<string, Uint8Array>();@@ -89,9 +89,11 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];// disabled export, where row pages are flattened to the root instead of nesting under the database.const csvRowTitles = new Set<string>();- const readArchive = async (buffer: Uint8Array, depth: number): Promise<void> => {- const filenameEncoding = await provider.detectFilenameEncoding(buffer);- await provider.readZipFile(buffer, async (entry, readContent) => {+ // `nestedSource` is the top-level archive (possibly a path, streamed from disk) on the first call, and a+ // nested zip's bytes (read into memory) on deeper calls — both are valid ZipSources.+ const readArchive = async (nestedSource: ZipSource, depth: number): Promise<void> => {+ const filenameEncoding = await provider.detectFilenameEncoding(nestedSource);+ await provider.readZipFile(nestedSource, async (entry, readContent) => {const path = entry.fileName;if (isDirectory(path)) {return;@@ -135,7 +137,7 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];}, filenameEncoding);};- await readArchive(fileBuffer, 0);+ await readArchive(source, 0);return { pages, resources, csvPaths, csvColumnsByFolder, markdownFileCount, csvRowTitles };}diff --git a/packages/trilium-core/src/services/import/obsidian/importer.ts b/packages/trilium-core/src/services/import/obsidian/importer.tsindex ba9b8daba0..4541805376 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.ts@@ -42,7 +42,7 @@ import { decodeUtf8 } from "../../utils/binary.js";import date_utils from "../../utils/date.js";import { removeFileExtension } from "../../utils/index.js";import { basename } from "../../utils/path.js";-import { getZipProvider } from "../../zip_provider.js";+import { getZipProvider, type ZipSource } from "../../zip_provider.js";import { buildPromotedDefinition, toAttributeName } from "../collection_utils.js";import { type FrontmatterAttribute, parseFrontmatter } from "../frontmatter.js";import markdownService from "../markdown.js";@@ -60,8 +60,8 @@ interface VaultNote {modified?: Date;}-async function importObsidian(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote, fileName?: string): Promise<BNote> {- const { notes, attachments, types, vaultRoot } = await parseVault(fileBuffer);+async function importObsidian(taskContext: TaskContext<"importNotes">, source: ZipSource, importRootNote: BNote, fileName?: string): Promise<BNote> {+ const { notes, attachments, types, vaultRoot } = await parseVault(source);taskContext.setTotalCount(notes.length);return createNotes(importRootNote, notes, attachments, types, vaultTitle(vaultRoot, fileName), taskContext);@@ -73,15 +73,15 @@ async function importObsidian(taskContext: TaskContext<"importNotes">, fileBuffe* folder and any other dot-prefixed entry are skipped, as is every non-Markdown file (handled in later* passes). Sorted by path so the resulting tree is built (and ordered) deterministically.*/-async function parseVault(fileBuffer: Uint8Array): Promise<{ notes: VaultNote[]; attachments: Map<string, Uint8Array>; types: Map<string, string>; vaultRoot: string }> {+async function parseVault(source: ZipSource): Promise<{ notes: VaultNote[]; attachments: Map<string, Uint8Array>; types: Map<string, string>; vaultRoot: string }> {const provider = getZipProvider();const allPaths: string[] = [];const raw: { path: string; markdown: string; modified?: Date }[] = [];const rawAttachments: { path: string; bytes: Uint8Array }[] = [];let typesJson = "";- const filenameEncoding = await provider.detectFilenameEncoding(fileBuffer);+ const filenameEncoding = await provider.detectFilenameEncoding(source);- await provider.readZipFile(fileBuffer, async (entry, readContent) => {+ await provider.readZipFile(source, async (entry, readContent) => {const path = normalizePath(entry.fileName);if (isDirectory(path)) {return;