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
fix(core): get rid of Node dependencies from ZIP export
Elian Dorand2a0c540baf4
diff --git a/apps/client-standalone/src/lightweight/zip_provider.ts b/apps/client-standalone/src/lightweight/zip_provider.tsindex 47a1c20f0c..f956431877 100644--- a/apps/client-standalone/src/lightweight/zip_provider.ts+++ b/apps/client-standalone/src/lightweight/zip_provider.ts@@ -1,7 +1,59 @@-import type { ZipEntry, ZipProvider } from "@triliumnext/core/src/services/import/zip_provider.js";-import { unzip } from "fflate";+import type { FileStream, ZipArchive, ZipEntry, ZipProvider } from "@triliumnext/core/src/services/import/zip_provider.js";+import { strToU8, unzip, zipSync } from "fflate";++type ZipOutput = {+ send?: (body: unknown) => unknown;+ write?: (chunk: Uint8Array | string) => unknown;+ end?: (chunk?: Uint8Array | string) => unknown;+};++class BrowserZipArchive implements ZipArchive {+ readonly #entries: Record<string, Uint8Array> = {};+ #destination: ZipOutput | null = null;++ append(content: string | Uint8Array, options: { name: string }) {+ this.#entries[options.name] = typeof content === "string" ? strToU8(content) : content;+ }++ pipe(destination: unknown) {+ this.#destination = destination as ZipOutput;+ }++ async finalize(): Promise<void> {+ if (!this.#destination) {+ throw new Error("ZIP output destination not set.");+ }++ const content = zipSync(this.#entries, { level: 9 });++ if (typeof this.#destination.send === "function") {+ this.#destination.send(content);+ return;+ }++ if (typeof this.#destination.end === "function") {+ if (typeof this.#destination.write === "function") {+ this.#destination.write(content);+ this.#destination.end();+ } else {+ this.#destination.end(content);+ }+ return;+ }++ throw new Error("Unsupported ZIP output destination.");+ }+}export default class BrowserZipProvider implements ZipProvider {+ createZipArchive(): ZipArchive {+ return new BrowserZipArchive();+ }++ createFileStream(_filePath: string): FileStream {+ throw new Error("File stream creation is not supported in the browser.");+ }+readZipFile(buffer: Uint8Array,processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>diff --git a/apps/server/src/services/backend_script_api.ts b/apps/server/src/services/backend_script_api.tsindex 9064a9d7dd..98b2e76c30 100644--- a/apps/server/src/services/backend_script_api.ts+++ b/apps/server/src/services/backend_script_api.ts@@ -1,5 +1,5 @@import { type AttributeRow, dayjs, formatLogMessage } from "@triliumnext/commons";-import { type AbstractBeccaEntity, Becca, branches as branchService, NoteParams, SearchContext, sync_mutex as syncMutex,zipExportService } from "@triliumnext/core";+import { type AbstractBeccaEntity, Becca, branches as branchService, NoteParams, SearchContext, sync_mutex as syncMutex, zipExportService } from "@triliumnext/core";import axios from "axios";import * as cheerio from "cheerio";import xml2js from "xml2js";diff --git a/apps/server/src/zip_provider.ts b/apps/server/src/zip_provider.tsindex 1f858e8de4..9d8188a7f5 100644--- a/apps/server/src/zip_provider.ts+++ b/apps/server/src/zip_provider.ts@@ -1,6 +1,30 @@-import type { ZipEntry, ZipProvider } from "@triliumnext/core/src/services/import/zip_provider.js";+import type { FileStream, ZipArchive, ZipEntry, ZipProvider } from "@triliumnext/core/src/services/import/zip_provider.js";+import archiver, { type Archiver } from "archiver";+import fs from "fs";import type { Stream } from "stream";-import yauzl from "yauzl";+import * as yauzl from "yauzl";++class NodejsZipArchive implements ZipArchive {+ readonly #archive: Archiver;++ constructor() {+ this.#archive = archiver("zip", {+ zlib: { level: 9 }+ });+ }++ append(content: string | Uint8Array, options: { name: string; date?: Date }) {+ this.#archive.append(typeof content === "string" ? content : Buffer.from(content), options);+ }++ pipe(destination: unknown) {+ this.#archive.pipe(destination as NodeJS.WritableStream);+ }++ finalize(): Promise<void> {+ return this.#archive.finalize();+ }+}function streamToBuffer(stream: Stream): Promise<Buffer> {const chunks: Uint8Array[] = [];@@ -12,6 +36,21 @@ function streamToBuffer(stream: Stream): Promise<Buffer> {}export default class NodejsZipProvider implements ZipProvider {+ createZipArchive(): ZipArchive {+ return new NodejsZipArchive();+ }++ createFileStream(filePath: string): FileStream {+ const stream = fs.createWriteStream(filePath);+ return {+ destination: stream,+ waitForFinish: () => new Promise((resolve, reject) => {+ stream.on("finish", resolve);+ stream.on("error", reject);+ })+ };+ }+readZipFile(buffer: Uint8Array,processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex e75c046311..ba5093d6c3 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -101,7 +101,7 @@ export type { RequestProvider, ExecOpts, CookieJar } from "./services/request";export type * from "./meta";export * as routeHelpers from "./routes/helpers";-export { getZipProvider, type ZipProvider } from "./services/import/zip_provider";+export { getZipProvider, type ZipArchive, type ZipProvider } from "./services/import/zip_provider";export { default as zipImportService } from "./services/import/zip";export { default as zipExportService } from "./services/export/zip";export { type AdvancedExportOptions } from "./services/export/zip/abstract_provider";diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.tsindex f0a51d7270..1d2287ebd5 100644--- a/packages/trilium-core/src/services/export/zip.ts+++ b/packages/trilium-core/src/services/export/zip.ts@@ -1,7 +1,4 @@import { NoteType } from "@triliumnext/commons";-import archiver from "archiver";-import type { Response } from "express";-import fs from "fs";import path from "path";import sanitize from "sanitize-filename";@@ -13,21 +10,21 @@ import dateUtils from "../utils/date.js";import { getLog } from "../log.js";import protectedSessionService from "../protected_session.js";import TaskContext from "../task_context.js";-import { getContentDisposition, waitForStreamToFinish } from "../utils/index"+import { getZipProvider, type ZipArchive } from "../import/zip_provider.js";+import { getContentDisposition } from "../utils/index"import { AdvancedExportOptions, ZipExportProvider, ZipExportProviderData } from "./zip/abstract_provider.js";import HtmlExportProvider from "./zip/html.js";import MarkdownExportProvider from "./zip/markdown.js";import { AttachmentMeta, AttributeMeta, ExportFormat, NoteMeta, NoteMetaFile } from "../../meta";import { ValidationError } from "../../errors";-async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch, format: ExportFormat, res: Response | fs.WriteStream, setHeaders = true, zipExportOptions?: AdvancedExportOptions) {+// eslint-disable-next-line @typescript-eslint/no-explicit-any+async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch, format: ExportFormat, res: Record<string, any>, setHeaders = true, zipExportOptions?: AdvancedExportOptions) {if (!["html", "markdown", "share"].includes(format)) {throw new ValidationError(`Only 'html', 'markdown' and 'share' allowed as export format, '${format}' given`);}- const archive = archiver("zip", {- zlib: { level: 9 } // Sets the compression level.- });+ const archive = getZipProvider().createZipArchive();const rewriteFn = (zipExportOptions?.customRewriteLinks ? zipExportOptions?.customRewriteLinks(rewriteLinks, getNoteTargetUrl) : rewriteLinks);const provider = buildProvider();const log = getLog();@@ -341,7 +338,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,content = prepareContent(noteMeta.title, content, noteMeta, undefined);- archive.append(typeof content === "string" ? content : Buffer.from(content), {+ archive.append(typeof content === "string" ? content : new Uint8Array(content), {name: filePathPrefix + noteMeta.dataFileName});@@ -359,7 +356,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,if (noteMeta.dataFileName) {const content = prepareContent(noteMeta.title, note.getContent(), noteMeta, note);- archive.append(content as string | Buffer, {+ archive.append(content as string | Uint8Array, {name: filePathPrefix + noteMeta.dataFileName,date: dateUtils.parseDateTime(note.utcDateModified)});@@ -375,7 +372,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,const attachment = note.getAttachmentById(attachmentMeta.attachmentId);const content = attachment.getContent();- archive.append(typeof content === "string" ? content : Buffer.from(content), {+ archive.append(typeof content === "string" ? content : new Uint8Array(content), {name: filePathPrefix + attachmentMeta.dataFileName,date: dateUtils.parseDateTime(note.utcDateModified)});@@ -469,7 +466,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,async function exportToZipFile(noteId: string, format: ExportFormat, zipFilePath: string, zipExportOptions?: AdvancedExportOptions) {- const fileOutputStream = fs.createWriteStream(zipFilePath);+ const { destination, waitForFinish } = getZipProvider().createFileStream(zipFilePath);const taskContext = new TaskContext("no-progress-reporting", "export", null);const note = becca.getNote(noteId);@@ -478,8 +475,8 @@ async function exportToZipFile(noteId: string, format: ExportFormat, zipFilePaththrow new ValidationError(`Note ${noteId} not found.`);}- await exportToZip(taskContext, note.getParentBranches()[0], format, fileOutputStream, false, zipExportOptions);- await waitForStreamToFinish(fileOutputStream);+ await exportToZip(taskContext, note.getParentBranches()[0], format, destination as Record<string, any>, false, zipExportOptions);+ await waitForFinish();getLog().info(`Exported '${noteId}' with format '${format}' to '${zipFilePath}'`);}diff --git a/packages/trilium-core/src/services/export/zip/abstract_provider.ts b/packages/trilium-core/src/services/export/zip/abstract_provider.tsindex 963f098735..da2c814e01 100644--- a/packages/trilium-core/src/services/export/zip/abstract_provider.ts+++ b/packages/trilium-core/src/services/export/zip/abstract_provider.ts@@ -1,10 +1,10 @@import { NoteType } from "@triliumnext/commons";-import { Archiver } from "archiver";import mimeTypes from "mime-types";import type BBranch from "../../../becca/entities/bbranch.js";import type BNote from "../../../becca/entities/bnote.js";import { ExportFormat, NoteMeta, NoteMetaFile } from "../../../meta.js";+import type { ZipArchive } from "../../import/zip_provider.js";type RewriteLinksFn = (content: string, noteMeta: NoteMeta) => string;@@ -29,7 +29,7 @@ export interface AdvancedExportOptions {export interface ZipExportProviderData {branch: BBranch;getNoteTargetUrl: (targetNoteId: string, sourceMeta: NoteMeta) => string | null;- archive: Archiver;+ archive: ZipArchive;zipExportOptions: AdvancedExportOptions | undefined;rewriteFn: RewriteLinksFn;}@@ -37,7 +37,7 @@ export interface ZipExportProviderData {export abstract class ZipExportProvider {branch: BBranch;getNoteTargetUrl: (targetNoteId: string, sourceMeta: NoteMeta) => string | null;- archive: Archiver;+ archive: ZipArchive;zipExportOptions?: AdvancedExportOptions;rewriteFn: RewriteLinksFn;diff --git a/packages/trilium-core/src/services/export/zip/html.ts b/packages/trilium-core/src/services/export/zip/html.tsindex d4c6ef7a54..1c3d734177 100644--- a/packages/trilium-core/src/services/export/zip/html.ts+++ b/packages/trilium-core/src/services/export/zip/html.ts@@ -2,7 +2,7 @@ import fs from "fs";import html from "html";import path from "path";-import { escapeHtml, getResourceDir, isDev } from "../../utils/index";+import { escapeHtml, isDev } from "../../utils/index";import { ZipExportProvider } from "./abstract_provider.js";import { NoteMeta } from "../../../meta";@@ -170,11 +170,12 @@ export default class HtmlExportProvider extends ZipExportProvider {return;}- const cssFile = isDev()- ? path.join(__dirname, "../../../../../../node_modules/ckeditor5/dist/ckeditor5-content.css")- : path.join(getResourceDir(), "ckeditor5-content.css");- const cssContent = fs.readFileSync(cssFile, "utf-8");- this.archive.append(cssContent, { name: cssMeta.dataFileName });+ // TODO: Bring back CSS.+ // const cssFile = isDev()+ // ? path.join(__dirname, "../../../../../../node_modules/ckeditor5/dist/ckeditor5-content.css")+ // : path.join(getResourceDir(), "ckeditor5-content.css");+ // const cssContent = fs.readFileSync(cssFile, "utf-8");+ // this.archive.append(cssContent, { name: cssMeta.dataFileName });}}diff --git a/packages/trilium-core/src/services/import/zip_provider.ts b/packages/trilium-core/src/services/import/zip_provider.tsindex 7b6cc9d04e..cd75d93d37 100644--- a/packages/trilium-core/src/services/import/zip_provider.ts+++ b/packages/trilium-core/src/services/import/zip_provider.ts@@ -2,6 +2,24 @@ export interface ZipEntry {fileName: string;}+export interface ZipArchiveEntryOptions {+ name: string;+ date?: Date;+}++export interface ZipArchive {+ append(content: string | Uint8Array, options: ZipArchiveEntryOptions): void;+ pipe(destination: unknown): void;+ finalize(): Promise<void>;+}++export interface FileStream {+ /** An opaque writable destination that can be passed to {@link ZipArchive.pipe}. */+ destination: unknown;+ /** Resolves when the stream has finished writing (or rejects on error). */+ waitForFinish(): Promise<void>;+}+export interface ZipProvider {/*** Iterates over every entry in a ZIP buffer, calling `processEntry` for each one.@@ -11,6 +29,11 @@ export interface ZipProvider {buffer: Uint8Array,processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>): Promise<void>;++ createZipArchive(): ZipArchive;++ /** Creates a writable file stream for the given path. */+ createFileStream(filePath: string): FileStream;}let zipProvider: ZipProvider | null = null;