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(standalone): export a subtree as static HTML for web
Elian Doran458199fbc761
diff --git a/apps/client/src/widgets/dialogs/export.tsx b/apps/client/src/widgets/dialogs/export.tsxindex ae33f28e2f..169a3a6142 100644--- a/apps/client/src/widgets/dialogs/export.tsx+++ b/apps/client/src/widgets/dialogs/export.tsx@@ -6,7 +6,7 @@ import froca from "../../services/froca";import { t } from "../../services/i18n";import open from "../../services/open";import tree from "../../services/tree";-import utils, { isStandalone } from "../../services/utils";+import utils from "../../services/utils";import { ExtendedAdmonition } from "../react/Admonition";import { Badge } from "../react/Badge";import Button, { ButtonGroup } from "../react/Button";@@ -119,8 +119,7 @@ const MARKDOWN_FORMAT: ExportFormat = { value: "markdown", name: t("export.formaconst SHARE_FORMAT: ExportFormat = { value: "share", name: t("export.format_share_name"), description: t("export.format_share_description"), icon: "bx bx-globe" };const OPML_FORMAT: ExportFormat = { value: "opml", name: t("export.format_opml_name"), description: t("export.format_opml_description"), icon: "bx bx-list-ul" };-// `share` publishes a static site and only makes sense on a full server, not the standalone build.-const subtreeFormats: ExportFormat[] = [HTML_FORMAT, MARKDOWN_FORMAT, ...(isStandalone ? [] : [SHARE_FORMAT]), OPML_FORMAT];+const subtreeFormats: ExportFormat[] = [HTML_FORMAT, MARKDOWN_FORMAT, SHARE_FORMAT, OPML_FORMAT];const singleFormats: ExportFormat[] = [HTML_FORMAT, MARKDOWN_FORMAT];// One-line summary of what the chosen export actually produces, shown in the dialog's result admonition.diff --git a/apps/server/package.json b/apps/server/package.jsonindex 66537f67d0..d378ee9216 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -40,7 +40,6 @@"@modelcontextprotocol/sdk": "^1.12.1","ai": "7.0.102","better-sqlite3": "13.0.3",- "html-to-text": "10.0.1","i18next": "26.4.2","ipaddr.js": "^2.4.0","js-yaml": "5.4.2",diff --git a/apps/server/src/services/export/zip/factory.spec.ts b/apps/server/src/services/export/zip/factory.spec.tsindex 796a336925..a0ac124f73 100644--- a/apps/server/src/services/export/zip/factory.spec.ts+++ b/apps/server/src/services/export/zip/factory.spec.ts@@ -15,7 +15,7 @@ class FakeShare {vi.mock("@triliumnext/core/src/services/export/zip/html.js", () => ({ default: FakeHtml }));vi.mock("@triliumnext/core/src/services/export/zip/markdown.js", () => ({ default: FakeMarkdown }));-vi.mock("./share_theme.js", () => ({ default: FakeShare }));+vi.mock("./share_theme.js", () => ({ createShareThemeExportProvider: (data: any) => new FakeShare(data) }));const data = { branch: {} } as any;@@ -28,7 +28,7 @@ async function importFactory(dev: boolean) {vi.resetModules();vi.doMock("@triliumnext/core/src/services/export/zip/html.js", () => ({ default: FakeHtml }));vi.doMock("@triliumnext/core/src/services/export/zip/markdown.js", () => ({ default: FakeMarkdown }));- vi.doMock("./share_theme.js", () => ({ default: FakeShare }));+ vi.doMock("./share_theme.js", () => ({ createShareThemeExportProvider: (data: any) => new FakeShare(data) }));if (dev) {vi.stubEnv("TRILIUM_ENV", "dev");} else {diff --git a/apps/server/src/services/export/zip/factory.ts b/apps/server/src/services/export/zip/factory.tsindex 975cd78650..e5a56ae456 100644--- a/apps/server/src/services/export/zip/factory.ts+++ b/apps/server/src/services/export/zip/factory.ts@@ -22,8 +22,8 @@ export async function serverZipExportProviderFactory(format: ExportFormat, data:return new MarkdownExportProvider(data);}case "share": {- const { default: ShareThemeExportProvider } = await import("./share_theme.js");- return new ShareThemeExportProvider(data);+ const { createShareThemeExportProvider } = await import("./share_theme.js");+ return createShareThemeExportProvider(data);}default:throw new Error(`Unsupported export format: '${format}'`);diff --git a/apps/server/src/services/export/zip/share_theme.spec.ts b/apps/server/src/services/export/zip/share_theme.spec.tsindex a5f6796e85..2a673bb3c2 100644--- a/apps/server/src/services/export/zip/share_theme.spec.ts+++ b/apps/server/src/services/export/zip/share_theme.spec.ts@@ -1,370 +1,35 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";-// --- Mocks (hoisted above the module-under-test import) -----const mockFs = { readFileSync: vi.fn(), readdirSync: vi.fn() };-vi.mock("fs", () => ({- default: mockFs,- readFileSync: (...a: any[]) => mockFs.readFileSync(...a),- readdirSync: (...a: any[]) => mockFs.readdirSync(...a)+const mockFs = vi.hoisted(() => ({+ readdirSync: vi.fn(() => [ "styles.css", "scripts.js" ]),+ readFileSync: vi.fn((path: string) => new TextEncoder().encode(`content of ${path.split("\\").join("/")}`))}));+vi.mock("fs", () => ({ default: mockFs, ...mockFs }));-vi.mock("ejs", () => ({ default: { render: vi.fn(() => "<html>404</html>") } }));-vi.mock("html-to-text", () => ({ convert: vi.fn((s: string) => `TEXT:${s}`) }));--const mockAssets = {- getClientDir: vi.fn(() => "/client"),- getShareThemeAssetDir: vi.fn(() => "/share-assets")-};-vi.mock("../../../routes/assets", () => mockAssets);--const mockContentRenderer = {- readShareTemplate: vi.fn(() => "TEMPLATE"),- renderNoteForExport: vi.fn(() => "<p>rendered</p>")-};-vi.mock("@triliumnext/core/src/share/index.js", () => mockContentRenderer);-vi.mock("../../../share/share_provider.js", () => ({ registerShareProvider: vi.fn() }));--vi.mock("../../resource_dir", () => ({ RESOURCE_DIR: "/resource" }));--const utils = { getResourceDir: vi.fn(() => "/res"), isDev: false };-vi.mock("../../utils", () => ({- getResourceDir: () => utils.getResourceDir(),- get isDev() {- return utils.isDev;- }+vi.mock("../../../routes/assets", () => ({+ getClientDir: () => "/client",+ getShareThemeAssetDir: () => "/share-assets"}));+vi.mock("../../resource_dir", () => ({ RESOURCE_DIR: "/resource" }));-const mockIconPacks: any[] = [];-const mockBecca = {- getNote: vi.fn(),- getAttachment: vi.fn()-};-const mockLog = { error: vi.fn(), info: vi.fn() };--vi.mock("@triliumnext/core", async (importOriginal) => {- const actual = await importOriginal<typeof import("@triliumnext/core")>();- return {- ...actual,- becca: mockBecca,- getLog: () => mockLog,- icon_packs: {- ...actual.icon_packs,- getIconPacks: vi.fn(() => mockIconPacks),- MIME_TO_EXTENSION_MAPPINGS: { "font/woff2": "woff2", "font/ttf": "ttf" }- }- };-});--const { default: ShareThemeExportProvider } = await import("./share_theme.js");--// --- Test scaffolding ---------------------------------------------------------interface AppendCall {- data: any;- options: { name: string };-}-let appendCalls: AppendCall[];--function makeData(branchNote?: any) {- const branch = {- getNote: () => branchNote ?? {- getContent: () => "<p>root</p>",- noteId: "rootNote",- getBestNotePath: () => ["root", "rootNote12345"]- }- };- return {- branch,- getNoteTargetUrl: vi.fn((id: string) => `url/${id}`),- archive: { append: vi.fn((data: any, options: any) => appendCalls.push({ data, options })) },- zipExportOptions: undefined,- rewriteFn: vi.fn((content: string) => content)- } as any;-}--function makeProvider(branchNote?: any) {- return new ShareThemeExportProvider(makeData(branchNote));-}--beforeEach(() => {- vi.clearAllMocks();- appendCalls = [];- mockIconPacks.length = 0;- utils.isDev = false;- mockFs.readFileSync.mockReturnValue(Buffer.from("file-data"));- mockFs.readdirSync.mockReturnValue(["a.css", "b.js"]);- mockContentRenderer.renderNoteForExport.mockReturnValue("<p>rendered</p>");-});--afterEach(() => vi.restoreAllMocks());--describe("ShareThemeExportProvider", () => {- describe("prepareMeta", () => {- it("registers icon-color.svg, asset-dir files, and an index entry", () => {- const provider = makeProvider();- const metaFile: any = { files: [{ noteId: "rootNote", title: "Root" }] };-- provider.prepareMeta(metaFile);-- const dataFileNames = metaFile.files.map((f: any) => f.dataFileName).filter(Boolean);- expect(dataFileNames).toContain("icon-color.svg");- expect(dataFileNames).toContain("assets/a.css");- expect(dataFileNames).toContain("assets/b.js");- expect(dataFileNames).toContain("index.html");- // rootMeta is taken from the first existing file entry- expect((provider as any).rootMeta).toBe(metaFile.files[0]);- });- });-- describe("mapExtension", () => {- it("returns null for images, js for javascript, null for .zip, html otherwise", () => {- const p = makeProvider();- expect(p.mapExtension("image", "image/png", "", "share")).toBeNull();- expect(p.mapExtension("code", "application/javascript", "", "share")).toBe("js");- expect(p.mapExtension("file", "application/zip", ".zip", "share")).toBeNull();- expect(p.mapExtension("text", "text/html", "", "share")).toBe("html");- });- });-- describe("prepareContent", () => {- it("throws when the note path is missing", () => {- const p = makeProvider();- expect(() => p.prepareContent("t", "x", { notePath: [] } as any, undefined as any, {} as any))- .toThrow(/note path/i);- });-- it("returns content unchanged when there is no note (no search index entry)", () => {- const p = makeProvider();- const result = p.prepareContent("t", "raw", { notePath: ["root", "a"] } as any, undefined as any, {} as any);- expect(result).toBe("raw");- expect((p as any).searchIndex.size).toBe(0);- });-- it("rewrites attachment links, note links, and builds a search-index entry for a note", () => {- const note = {- noteId: "noteABC",- getBestNotePath: () => ["root", "parent12chars", "noteABC12char"]- };- mockBecca.getNote.mockImplementation((id: string) =>- id === "parent12chars" ? { title: "Parent" } : null);-- // Render output exercises both the attachment and note link rewrites.- mockContentRenderer.renderNoteForExport.mockReturnValue(- `<a href="api/attachments/att123456/download">f</a>` +- `<a href="x./otherNote123">n</a>` +- `<a href="x./assets/keepme12345">keep</a>`- );-- const p = makeProvider();- (p as any).rootMeta = { noteId: "rootNote" };- const noteMeta: any = {- notePath: ["root", "parent12chars", "noteABC12char"],- attachments: [{ attachmentId: "att123456", dataFileName: "files/att.png" }]- };-- const out = p.prepareContent("Title", "<p>html</p>", noteMeta, note as any, {} as any) as string;-- // Attachment download link rewritten to its data file name.- expect(out).toContain('href="files/att.png"');- // Plain note link rewritten to a hash anchor.- expect(out).toContain('href="#root/otherNote123"');- // /assets/ links are preserved untouched.- expect(out).toContain("/assets/keepme12345");-- const entry = (p as any).searchIndex.get("noteABC");- expect(entry.title).toBe("Title");- expect(entry.content).toContain("TEXT:");- // Path built from titles, excluding root and falsy titles.- expect(entry.path).toBe("Parent");- });-- it("keeps the original attachment link when the attachment has no data file (or no attachments at all)", () => {- const note = { noteId: "noAtt", getBestNotePath: () => ["root", "noAtt1234567"] };- mockBecca.getNote.mockReturnValue(null);- mockContentRenderer.renderNoteForExport.mockReturnValue(- `<a href="api/attachments/att999999/download">f</a>`- );-- const p = makeProvider();- // attachment present but without a dataFileName → keep original match (line 79 false).- const withAtt: any = {- notePath: ["root", "noAtt1234567"],- attachments: [{ attachmentId: "att999999" }]- };- const out1 = p.prepareContent("t", "<p>c</p>", withAtt, note as any, {} as any) as string;- expect(out1).toContain('href="api/attachments/att999999/download"');-- // no attachments array at all → (noteMeta.attachments || []) fallback (line 78).- const noAttArr: any = { notePath: ["root", "noAtt1234567"] };- const out2 = p.prepareContent("t", "<p>c</p>", noAttArr, note as any, {} as any) as string;- expect(out2).toContain('href="api/attachments/att999999/download"');- });-- it("rewrites a note link pointing at the root to the base path", () => {- const note = { noteId: "rootChild", getBestNotePath: () => ["root", "rootNote12345"] };- mockBecca.getNote.mockReturnValue(null);- mockContentRenderer.renderNoteForExport.mockReturnValue(`<a href="x./rootNote1234">root</a>`);-- const p = makeProvider();- (p as any).rootMeta = { noteId: "rootNote1234" };- const noteMeta: any = { notePath: ["root", "rootNote1234"], attachments: [] };-- const out = p.prepareContent("t", "<p>c</p>", noteMeta, note as any, {} as any) as string;- // basePath for a 2-element path is "" (root link points to the base).- expect(out).toContain('href=""');- });-- it("leaves binary (non-string) content untouched but still indexes the note", () => {- const note = { noteId: "binNote", getBestNotePath: () => ["root", "binNote12345"] };- mockBecca.getNote.mockReturnValue(null);- mockContentRenderer.renderNoteForExport.mockReturnValue(new Uint8Array([1, 2, 3]) as any);-- const p = makeProvider();- const noteMeta: any = { notePath: ["root", "binNote12345"], attachments: [] };-- const out = p.prepareContent("Bin", new Uint8Array([9]), noteMeta, note as any, {} as any);- expect(out).toBeInstanceOf(Uint8Array);- // Binary input means empty search content.- expect((p as any).searchIndex.get("binNote").content).toBe("");- });- });-- describe("afterDone", () => {- it("writes index, 404, assets, fonts, and the search index json", () => {- const p = makeProvider();- (p as any).indexMeta = { dataFileName: "index.html" };- (p as any).assetsMeta = [{ dataFileName: "icon-color.svg" }, { dataFileName: undefined }];- (p as any).rootMeta = { noteId: "rootNote" };-- // A builtin icon pack (read from client dir) and a custom one (from becca).- mockIconPacks.push(- { prefix: "BX", fontMime: "font/woff2", fontAttachmentId: "boxicons", builtin: true },- { prefix: "Custom", fontMime: "font/ttf", fontAttachmentId: "customAtt", builtin: false }- );- (p as any).iconPacks = mockIconPacks;- mockBecca.getAttachment.mockReturnValue({ getContent: () => Buffer.from("font") });-- // search index with one valid + one null-id entry- (p as any).searchIndex.set("n1", { id: "n1", title: "T", content: "c", path: "p" });- (p as any).searchIndex.set("n2", { id: null, title: "T2", content: "c2", path: "p2" });- (p as any).getNoteTargetUrl.mockReturnValue("resolved/n1");-- // #saveIndex re-runs prepareContent against rootMeta, so it needs a notePath.- const rootMeta: any = { noteId: "rootNote", title: "Root", notePath: ["root", "rootNote12345"], attachments: [] };- p.afterDone(rootMeta);-- const names = appendCalls.map((c) => c.options.name);- expect(names).toContain("index.html");- expect(names).toContain("404.html");- expect(names).toContain("icon-color.svg");- expect(names).toContain("assets/icon-pack-bx.woff2");- expect(names).toContain("assets/icon-pack-custom.ttf");- expect(names).toContain("search-index.json");-- const searchAppend = appendCalls.find((c) => c.options.name === "search-index.json")!;- const parsed = JSON.parse(searchAppend.data);- // Only the entry with a non-null id is URL-resolved; both are serialized.- expect(parsed.find((e: any) => e.id === "resolved/n1")).toBeTruthy();- });-- it("buffers binary index content and appends string font data as-is", () => {- const p = makeProvider();- (p as any).indexMeta = { dataFileName: "index.html" };- (p as any).assetsMeta = [];- (p as any).rootMeta = { noteId: "rootNote" };-- // renderNoteForExport returns binary → prepareContent returns binary →- // #saveIndex takes the Buffer.from(content) branch (line 149 else).- mockContentRenderer.renderNoteForExport.mockReturnValue(new Uint8Array([1, 2, 3]) as any);-- // A custom icon pack whose font content is a string exercises line 177's string branch.- mockIconPacks.push({ prefix: "Str", fontMime: "font/ttf", fontAttachmentId: "strAtt", builtin: false });- (p as any).iconPacks = mockIconPacks;- mockBecca.getAttachment.mockReturnValue({ getContent: () => "string-font-data" });-- const rootMeta: any = { noteId: "rootNote", title: "Root", notePath: ["root", "rootNote12345"], attachments: [] };- p.afterDone(rootMeta);-- const index = appendCalls.find((c) => c.options.name === "index.html")!;- expect(Buffer.isBuffer(index.data)).toBe(true);- const font = appendCalls.find((c) => c.options.name === "assets/icon-pack-str.ttf")!;- expect(font.data).toBe("string-font-data");- });-- it("defaults the index title to an empty string when rootMeta has no title", () => {- const p = makeProvider();- (p as any).indexMeta = { dataFileName: "index.html" };- (p as any).assetsMeta = [];- (p as any).rootMeta = { noteId: "rootNote" };- mockContentRenderer.renderNoteForExport.mockReturnValue("<p>x</p>");-- // No `title` → exercises the `?? ""` fallback on line 148.- const rootMeta: any = { noteId: "rootNote", notePath: ["root", "rootNote12345"], attachments: [] };- p.afterDone(rootMeta);-- expect(mockContentRenderer.renderNoteForExport).toHaveBeenCalled();- expect(appendCalls.map((c) => c.options.name)).toContain("index.html");- });-- it("skips the index when there is no index data file name", () => {- const p = makeProvider();- (p as any).indexMeta = null;- (p as any).assetsMeta = [];- p.afterDone({ noteId: "rootNote", title: "Root" } as any);-- expect(appendCalls.map((c) => c.options.name)).not.toContain("index.html");- // 404 + search-index are still written.- expect(appendCalls.map((c) => c.options.name)).toContain("404.html");- });-- it("logs an error and skips a font when its data cannot be found", () => {- const p = makeProvider();- (p as any).indexMeta = null;- (p as any).assetsMeta = [];- mockIconPacks.push({ prefix: "Missing", fontMime: "font/ttf", fontAttachmentId: "gone", builtin: false });- (p as any).iconPacks = mockIconPacks;- mockBecca.getAttachment.mockReturnValue(undefined);-- p.afterDone({ noteId: "rootNote", title: "Root" } as any);-- expect(mockLog.error).toHaveBeenCalled();- expect(appendCalls.map((c) => c.options.name)).not.toContain("assets/icon-pack-missing.ttf");- });- });-});--describe("getShareThemeAssets (asset resolution branches)", () => {- // getShareThemeAssets is private to the module; it is exercised through- // afterDone's #saveAssets, which calls it for each asset data file name.- function runSaveAssets(assetNames: string[], dev: boolean) {- utils.isDev = dev;- const p = makeProvider();- (p as any).indexMeta = null;- (p as any).assetsMeta = assetNames.map((n) => ({ dataFileName: n }));- (p as any).iconPacks = [];- p.afterDone({ noteId: "rootNote", title: "Root" } as any);- // Normalize path separators so assertions are OS-independent.- return mockFs.readFileSync.mock.calls.map((c) => String(c[0]).split("\\").join("/"));- }-- it("resolves icon-color.svg from the resource images dir", () => {- const reads = runSaveAssets(["icon-color.svg"], false);- expect(reads.some((p) => p.includes("/resource") && p.includes("icon-color.svg"))).toBe(true);- });-- it("resolves assets/* relative to the share theme asset dir", () => {- const reads = runSaveAssets(["assets/style.css"], false);- expect(reads.some((p) => p.includes("/share-assets") && p.includes("style.css"))).toBe(true);- });-- it("resolves other files from the client dist in dev mode", () => {- const reads = runSaveAssets(["main.js"], true);- expect(reads.some((p) => p.includes("client") && p.includes("dist"))).toBe(true);- });-- it("resolves other files from the public dir in production", () => {- const reads = runSaveAssets(["main.js"], false);- expect(reads.some((p) => p.includes("public") && p.includes("main.js"))).toBe(true);+const registerShareProvider = vi.hoisted(() => vi.fn());+vi.mock("../../../share/share_provider.js", () => ({ registerShareProvider }));++const { createShareThemeExportProvider } = await import("./share_theme.js");++describe("createShareThemeExportProvider", () => {+ it("reads the share theme's files and the built-in fonts from disk", () => {+ const provider = createShareThemeExportProvider({ branch: {} } as never);+ const { files, readBuiltinFont } = (provider as unknown as { assets: {+ files: Map<string, Uint8Array>;+ readBuiltinFont(fileName: string): Uint8Array | undefined;+ } }).assets;+ const decode = (data: Uint8Array | undefined) => new TextDecoder().decode(data);++ expect(registerShareProvider).toHaveBeenCalled();+ expect([ ...files.keys() ]).toEqual([ "icon-color.svg", "assets/styles.css", "assets/scripts.js" ]);+ expect(decode(files.get("icon-color.svg"))).toBe("content of /resource/images/icon-color.svg");+ expect(decode(files.get("assets/scripts.js"))).toBe("content of /share-assets/scripts.js");+ expect(decode(readBuiltinFont("boxicons.woff2"))).toBe("content of /client/fonts/boxicons.woff2");});});diff --git a/apps/server/src/services/export/zip/share_theme.ts b/apps/server/src/services/export/zip/share_theme.tsindex d2d28fe9b6..fb24b3ffcf 100644--- a/apps/server/src/services/export/zip/share_theme.ts+++ b/apps/server/src/services/export/zip/share_theme.ts@@ -1,206 +1,31 @@-import { type BBranch, type BNote, ExportFormat, icon_packs as iconPackService, type NoteMeta, type NoteMetaFile, ZipExportProvider } from "@triliumnext/core";-import ejs from "ejs";-import fs, { readdirSync, readFileSync } from "fs";-import { convert as convertToText } from "html-to-text";-import { t } from "i18next";+import type { ZipExportProviderData } from "@triliumnext/core";+import ShareThemeExportProvider, { type ShareThemeExportAssets } from "@triliumnext/core/src/services/export/zip/share_theme.js";+import { readdirSync, readFileSync } from "fs";import { join } from "path";-import { becca } from "@triliumnext/core";-import { readShareTemplate, renderNoteForExport } from "@triliumnext/core/src/share/index.js";import { getClientDir, getShareThemeAssetDir } from "../../../routes/assets";import { registerShareProvider } from "../../../share/share_provider.js";-import { getLog } from "@triliumnext/core";import { RESOURCE_DIR } from "../../resource_dir";-import { getResourceDir, isDev } from "../../utils";-registerShareProvider();+/** Builds a share-theme export over the theme's built files and the client's fonts on disk. */+export function createShareThemeExportProvider(data: ZipExportProviderData) {+ registerShareProvider();-const shareThemeAssetDir = getShareThemeAssetDir();--interface SearchIndexEntry {- id: string | null;- title: string;- content: string;- path: string;+ return new ShareThemeExportProvider(data, readShareThemeExportAssets());}-export default class ShareThemeExportProvider extends ZipExportProvider {-- private assetsMeta: NoteMeta[] = [];- private indexMeta: NoteMeta | null = null;- private searchIndex: Map<string, SearchIndexEntry> = new Map();- private rootMeta: NoteMeta | null = null;- private iconPacks: iconPackService.ProcessedIconPack[] = [];-- prepareMeta(metaFile: NoteMetaFile): void {- const assets = [- "icon-color.svg"- ];-- for (const file of readdirSync(shareThemeAssetDir)) {- assets.push(`assets/${file}`);- }-- for (const asset of assets) {- const assetMeta = {- noImport: true,- dataFileName: asset- };- this.assetsMeta.push(assetMeta);- metaFile.files.push(assetMeta);- }-- this.indexMeta = {- noImport: true,- dataFileName: "index.html"- };- this.rootMeta = metaFile.files[0];- this.iconPacks = iconPackService.getIconPacks();-- metaFile.files.push(this.indexMeta);- }-- prepareContent(title: string, content: string | Uint8Array, noteMeta: NoteMeta, note: BNote | undefined, branch: BBranch): string | Uint8Array {- if (!noteMeta?.notePath?.length) {- throw new Error("Missing note path.");- }- const basePath = "../".repeat(Math.max(0, noteMeta.notePath.length - 2));- let searchContent = "";-- if (note) {- // Prepare search index.- searchContent = typeof content === "string" ? convertToText(content, {- whitespaceCharacters: "\t\r\n\f\u200b\u00a0\u2002"- }) : "";-- // TODO: This will probably never match, but should it be exclude from running on code/jsFrontend notes?- content = renderNoteForExport(note, branch, basePath, noteMeta.notePath.slice(0, -1), this.iconPacks);- if (typeof content === "string") {- // Rewrite attachment download links- content = content.replace(/href="api\/attachments\/([a-zA-Z0-9_]+)\/download"/g, (match, attachmentId) => {- const attachmentMeta = (noteMeta.attachments || []).find((attMeta) => attMeta.attachmentId === attachmentId);- if (attachmentMeta?.dataFileName) {- return `href="${attachmentMeta.dataFileName}"`;- }- return match;- });-- // Rewrite note links- content = content.replace(/href="[^"]*\.\/([a-zA-Z0-9_\/]{12})[^"]*"/g, (match, id) => {- if (match.includes("/assets/")) return match;- if (id === this.rootMeta?.noteId) {- return `href="${basePath}"`;- }- return `href="#root/${id}"`;- });- content = this.rewriteFn(content, noteMeta);- }-- // Prepare search index.- this.searchIndex.set(note.noteId, {- id: note.noteId,- title,- content: searchContent,- path: note.getBestNotePath()- .map(noteId => noteId !== "root" && becca.getNote(noteId)?.title)- .filter(noteId => noteId)- .join(" / ")- });- }-- return content;- }-- afterDone(rootMeta: NoteMeta): void {- this.#saveAssets(rootMeta, this.assetsMeta);- this.#saveIndex(rootMeta);- this.#save404();-- // Search index- for (const item of this.searchIndex.values()) {- if (!item.id) continue;- item.id = this.getNoteTargetUrl(item.id, rootMeta);- }-- this.archive.append(JSON.stringify(Array.from(this.searchIndex.values()), null, 4), { name: "search-index.json" });- }-- mapExtension(type: string | null, mime: string, existingExtension: string, format: ExportFormat): string | null {- if (mime.startsWith("image/")) {- return null;- }-- if (mime.startsWith("application/javascript")) {- return "js";- }-- // Don't add .html if the file already has .zip extension (for attachments).- if (existingExtension === ".zip") {- return null;- }-- return "html";- }-- #saveIndex(rootMeta: NoteMeta) {- if (!this.indexMeta?.dataFileName) {- return;- }-- const note = this.branch.getNote();- const content = this.prepareContent(rootMeta.title ?? "", note.getContent(), rootMeta, note, this.branch);- this.archive.append(typeof content === "string" ? content : Buffer.from(content), { name: this.indexMeta.dataFileName });- }-- #saveAssets(rootMeta: NoteMeta, assetsMeta: NoteMeta[]) {- for (const assetMeta of assetsMeta) {- if (!assetMeta.dataFileName) {- continue;- }-- const cssContent = getShareThemeAssets(assetMeta.dataFileName);- this.archive.append(cssContent, { name: assetMeta.dataFileName });- }-- // Inject the custom fonts.- for (const iconPack of this.iconPacks) {- const extension = iconPackService.MIME_TO_EXTENSION_MAPPINGS[iconPack.fontMime];- let fontData: Uint8Array | undefined;- if (iconPack.builtin) {- fontData = readFileSync(join(getClientDir(), "fonts", `${iconPack.fontAttachmentId}.${extension}`));- } else {- fontData = becca.getAttachment(iconPack.fontAttachmentId)?.getContent();- }-- if (!fontData) {- getLog().error(`Failed to find font data for icon pack ${iconPack.prefix} with attachment ID ${iconPack.fontAttachmentId}`);- continue;- };- const fontFileName = `assets/icon-pack-${iconPack.prefix.toLowerCase()}.${extension}`;- this.archive.append(typeof fontData === "string" ? fontData : Buffer.from(fontData), {- name: fontFileName- });- }- }-- #save404() {- const content = ejs.render(readShareTemplate("404"), { t });- this.archive.append(content, { name: "404.html" });- }--}+function readShareThemeExportAssets(): ShareThemeExportAssets {+ const shareThemeAssetDir = getShareThemeAssetDir();+ const files = new Map<string, Uint8Array>([+ [ "icon-color.svg", readFileSync(join(RESOURCE_DIR, "images", "icon-color.svg")) ]+ ]);-function getShareThemeAssets(nameWithExtension: string) {- let path: string | undefined;- if (nameWithExtension === "icon-color.svg") {- path = join(RESOURCE_DIR, "images", nameWithExtension);- } else if (nameWithExtension.startsWith("assets")) {- path = join(shareThemeAssetDir, nameWithExtension.replace(/^assets\//, ""));- } else if (isDev) {- path = join(getResourceDir(), "..", "..", "client", "dist", "src", nameWithExtension);- } else {- path = join(getResourceDir(), "public", "src", nameWithExtension);+ for (const file of readdirSync(shareThemeAssetDir)) {+ files.set(`assets/${file}`, readFileSync(join(shareThemeAssetDir, file)));}- return fs.readFileSync(path);+ return {+ files,+ readBuiltinFont: (fileName) => readFileSync(join(getClientDir(), "fonts", fileName))+ };}diff --git a/apps/standalone/src/lightweight/zip_export_provider_factory.spec.ts b/apps/standalone/src/lightweight/zip_export_provider_factory.spec.tsindex a6d7527dcd..4c2574ba60 100644--- a/apps/standalone/src/lightweight/zip_export_provider_factory.spec.ts+++ b/apps/standalone/src/lightweight/zip_export_provider_factory.spec.ts@@ -1,9 +1,11 @@import type { ZipExportProviderData } from "@triliumnext/core";-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import BrowserZipProvider from "./zip_provider.js";import { standaloneZipExportProviderFactory } from "./zip_export_provider_factory.js";+vi.mock("virtual:share-theme-assets", () => ({ default: [ "styles.css", "scripts.js" ] }));+function makeData(): ZipExportProviderData {return {branch: { branchId: "test" },@@ -14,6 +16,10 @@ function makeData(): ZipExportProviderData {} as unknown as ZipExportProviderData;}+afterEach(() => {+ vi.unstubAllGlobals();+});+describe("standaloneZipExportProviderFactory", () => {it("creates an HTML export provider", async () => {const data = makeData();@@ -27,6 +33,32 @@ describe("standaloneZipExportProviderFactory", () => {expect(provider.constructor.name).toBe("MarkdownExportProvider");});+ it("creates a share-theme export provider over the theme files the build serves", async () => {+ const fetchMock = vi.fn(async (url: string) => new Response(`content of ${url}`));+ vi.stubGlobal("fetch", fetchMock);++ const provider = await standaloneZipExportProviderFactory("share", makeData());+ expect(provider.constructor.name).toBe("ShareThemeExportProvider");++ const { files, readBuiltinFont } = (provider as unknown as { assets: {+ files: Map<string, string | Uint8Array>;+ readBuiltinFont(fileName: string): Uint8Array | undefined;+ } }).assets;+ expect([ ...files.keys() ]).toEqual([ "icon-color.svg", "assets/styles.css", "assets/scripts.js" ]);+ expect(files.get("icon-color.svg")).toContain("<svg");+ expect(new TextDecoder().decode(files.get("assets/styles.css") as Uint8Array))+ .toBe("content of /share/assets/styles.css");+ expect(new TextDecoder().decode(readBuiltinFont("boxicons.woff2")))+ .toBe("content of /share/assets/fonts/boxicons.woff2");+ });++ it("fails the share-theme export when a theme file cannot be fetched", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 404 })));++ await expect(standaloneZipExportProviderFactory("share", makeData()))+ .rejects.toThrow("/share/assets/styles.css");+ });+it("throws for an unsupported format", async () => {await expect(standaloneZipExportProviderFactory("pdf" as never, makeData())diff --git a/apps/standalone/src/lightweight/zip_export_provider_factory.ts b/apps/standalone/src/lightweight/zip_export_provider_factory.tsindex 12e1f75e2b..56614b3f2a 100644--- a/apps/standalone/src/lightweight/zip_export_provider_factory.ts+++ b/apps/standalone/src/lightweight/zip_export_provider_factory.ts@@ -1,4 +1,5 @@-import { type ExportFormat, type ZipExportProviderData, ZipExportProvider } from "@triliumnext/core";+import { type ExportFormat, icon_packs, type ZipExportProviderData, ZipExportProvider } from "@triliumnext/core";+import type { ShareThemeExportAssets } from "@triliumnext/core/src/services/export/zip/share_theme.js";import contentCss from "@triliumnext/ckeditor5/src/theme/ck-content.css?raw";@@ -12,7 +13,56 @@ export async function standaloneZipExportProviderFactory(format: ExportFormat, dconst { default: MarkdownExportProvider } = await import("@triliumnext/core/src/services/export/zip/markdown.js");return new MarkdownExportProvider(data);}+ case "share": {+ const [ { default: ShareThemeExportProvider }, { registerShareProvider }, assets ] = await Promise.all([+ import("@triliumnext/core/src/services/export/zip/share_theme.js"),+ import("./share_provider.js"),+ loadShareThemeExportAssets()+ ]);+ registerShareProvider();+ return new ShareThemeExportProvider(data, assets);+ }default:throw new Error(`Unsupported export format: '${format}'`);}}++/**+ * Fetches the share theme's files and the built-in icon fonts from `share/assets`, where the build+ * copies them for the share pages. The export reads them synchronously, so they are all loaded+ * before it starts.+ */+async function loadShareThemeExportAssets(): Promise<ShareThemeExportAssets> {+ const [ { default: themeFiles }, { default: iconColorSvg } ] = await Promise.all([+ import("virtual:share-theme-assets"),+ import("../../../server/src/assets/images/icon-color.svg?raw")+ ]);+ const fontFiles = icon_packs.getIconPacks()+ .filter((iconPack) => iconPack.builtin)+ .map((iconPack) => `${iconPack.fontAttachmentId}.${icon_packs.MIME_TO_EXTENSION_MAPPINGS[iconPack.fontMime]}`);++ const [ themeContents, fontContents ] = await Promise.all([+ Promise.all(themeFiles.map((file) => fetchAsset(`/share/assets/${file}`))),+ Promise.all(fontFiles.map((file) => fetchAsset(`/share/assets/fonts/${file}`)))+ ]);++ const files = new Map<string, string | Uint8Array>([ [ "icon-color.svg", iconColorSvg ] ]);+ for (const [ index, file ] of themeFiles.entries()) {+ files.set(`assets/${file}`, themeContents[index]);+ }+ const fonts = new Map(fontFiles.map((file, index) => [ file, fontContents[index] ]));++ return {+ files,+ readBuiltinFont: (fileName) => fonts.get(fileName)+ };+}++async function fetchAsset(url: string) {+ const response = await fetch(url);+ if (!response.ok) {+ throw new Error(`Failed to fetch ${url} for the share-theme export: HTTP ${response.status}.`);+ }++ return new Uint8Array(await response.arrayBuffer());+}diff --git a/apps/standalone/src/share-theme-assets.d.ts b/apps/standalone/src/share-theme-assets.d.tsnew file mode 100644index 0000000000..73ecc304eb--- /dev/null+++ b/apps/standalone/src/share-theme-assets.d.ts@@ -0,0 +1,5 @@+/** The file names in `packages/share-theme/dist`, listed by `shareThemeAssetListPlugin` in `vite.config.mts`. */+declare module "virtual:share-theme-assets" {+ const files: string[];+ export default files;+}diff --git a/apps/standalone/vite.config.mts b/apps/standalone/vite.config.mtsindex 4037b53678..c4ce4b23e7 100644--- a/apps/standalone/vite.config.mts+++ b/apps/standalone/vite.config.mts@@ -19,6 +19,27 @@ const coreVersion = JSON.parse(fs.readFileSync(join(__dirname, "../../packages/trilium-core/package.json"), "utf-8")).version;+// Lists the share theme's built files as `virtual:share-theme-assets`, so the share-theme export+// can fetch each one from `share/assets`, where the static copy below places them.+const shareThemeAssetListPlugin = (): Plugin => {+ const moduleId = "virtual:share-theme-assets";+ const resolvedId = `\0${moduleId}`;++ return {+ name: "share-theme-asset-list",+ resolveId: (id) => (id === moduleId ? resolvedId : undefined),+ load(id) {+ if (id !== resolvedId) {+ return;+ }++ const distDir = join(__dirname, "../../packages/share-theme/dist");+ const files = fs.existsSync(distDir) ? fs.readdirSync(distDir) : [];+ return `export default ${JSON.stringify(files)};`;+ }+ };+};+// Watch client files and trigger reload in developmentconst clientWatchPlugin = () => ({name: "client-watch",@@ -123,6 +144,7 @@ let plugins: any = [stripUniverHyphenation(),sqliteWasmDedupePlugin(),sqliteWasmPlugin,+ shareThemeAssetListPlugin(),viteStaticCopy({targets: clientAssets.map((asset) => ({src: `../../client/src/${asset}/**/*`,@@ -361,7 +383,8 @@ export default defineConfig(() => ({include: ['officeparser']},worker: {- format: "es" as const+ format: "es" as const,+ plugins: () => [ shareThemeAssetListPlugin() ]},commonjsOptions: {transformMixedEsModules: true,diff --git a/docs/Developer Guide/Developer Guide/Concepts/Share.md b/docs/Developer Guide/Developer Guide/Concepts/Share.mdindex d635331e0b..5880fc6566 100644--- a/docs/Developer Guide/Developer Guide/Concepts/Share.md+++ b/docs/Developer Guide/Developer Guide/Concepts/Share.md@@ -53,6 +53,9 @@ The server renders the templates using EJS templating from the share theme and h## Exporting to static HTML files-This functionality is also handled by the server, but in `src/services/export/zip/share_theme` instead. It works quite similar to the normal sharing functionality, but it uses `BNote` instead of `SNote` (and so on for other entity types), in order to work regardless of whether a note is shared or not.+The static export lives in `packages/trilium-core/src/services/export/zip/share_theme.ts`, so both the server and the standalone build offer it. It works quite similar to the normal sharing functionality, but it uses `BNote` instead of `SNote` (and so on for other entity types), in order to work regardless of whether a note is shared or not.-The same templates are used and rendered by the server, except that they are stored in a file instead of served to web clients.\ No newline at end of file+The same templates are used, except that the rendered pages are stored in the archive instead of served to web clients. The theme's built files and the built-in icon fonts reach the provider through `ShareThemeExportAssets`, which each platform fills in its zip export factory:++* The server reads them from disk (`apps/server/src/services/export/zip/share_theme.ts`).+* The standalone build fetches them from `share/assets`, where it already copies them for the share pages. The file names come from the `virtual:share-theme-assets` module, which `vite.config.mts` generates from `packages/share-theme/dist` for both the page and the worker bundle.\ No newline at end of filediff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.jsonindex 0b15c1c0fc..3608147334 100644--- a/packages/trilium-core/package.json+++ b/packages/trilium-core/package.json@@ -21,6 +21,7 @@"color": "5.0.3","ejs": "6.0.1","escape-html": "1.0.3",+ "html-to-text": "10.0.1","i18next": "26.4.2","js-yaml": "5.4.2","lz-string": "1.5.0",@@ -39,6 +40,7 @@"devDependencies": {"@types/ejs": "3.1.5","@types/escape-html": "1.0.4",+ "@types/html-to-text": "9.0.4","@types/mime-types": "3.0.1","@types/sanitize-html": "2.16.1","@types/xml2js": "0.4.14"diff --git a/packages/trilium-core/src/services/export/zip/share_theme.spec.ts b/packages/trilium-core/src/services/export/zip/share_theme.spec.tsnew file mode 100644index 0000000000..f7a96cb9aa--- /dev/null+++ b/packages/trilium-core/src/services/export/zip/share_theme.spec.ts@@ -0,0 +1,312 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// --- Mocks (hoisted above the module-under-test import) ---++vi.mock("ejs", () => ({ default: { render: vi.fn(() => "<html>404</html>") } }));+vi.mock("html-to-text", () => ({ convert: vi.fn((s: string) => `TEXT:${s}`) }));++const mockContentRenderer = {+ readShareTemplate: vi.fn(() => "TEMPLATE"),+ renderNoteForExport: vi.fn(() => "<p>rendered</p>")+};+vi.mock("../../../share/index.js", () => mockContentRenderer);++const mockIconPacks: any[] = [];+vi.mock("../../icon_packs.js", () => ({+ getIconPacks: vi.fn(() => mockIconPacks),+ MIME_TO_EXTENSION_MAPPINGS: { "font/woff2": "woff2", "font/ttf": "ttf" }+}));++const mockBecca = {+ getNote: vi.fn(),+ getAttachment: vi.fn()+};+vi.mock("../../../becca/becca.js", () => ({ default: mockBecca }));++const mockLog = { error: vi.fn(), info: vi.fn() };+vi.mock("../../log.js", () => ({ getLog: () => mockLog }));++const { default: ShareThemeExportProvider } = await import("./share_theme.js");++// --- Test scaffolding -------------------------------------------------------++interface AppendCall {+ data: any;+ options: { name: string };+}+let appendCalls: AppendCall[];++const iconColor = new Uint8Array([ 1 ]);+const styles = "body {}";+const readBuiltinFont = vi.fn((_fileName: string): Uint8Array | undefined => new Uint8Array([ 2 ]));++function makeData(branchNote?: any) {+ const branch = {+ getNote: () => branchNote ?? {+ getContent: () => "<p>root</p>",+ noteId: "rootNote",+ getBestNotePath: () => ["root", "rootNote12345"]+ }+ };+ return {+ branch,+ getNoteTargetUrl: vi.fn((id: string) => `url/${id}`),+ archive: { append: vi.fn((data: any, options: any) => appendCalls.push({ data, options })) },+ zipExportOptions: undefined,+ rewriteFn: vi.fn((content: string) => content)+ } as any;+}++function makeProvider(branchNote?: any) {+ return new ShareThemeExportProvider(makeData(branchNote), {+ files: new Map<string, string | Uint8Array>([+ [ "icon-color.svg", iconColor ],+ [ "assets/styles.css", styles ]+ ]),+ readBuiltinFont+ });+}++function findAppend(name: string) {+ const call = appendCalls.find((c) => c.options.name === name);+ if (!call) {+ throw new Error(`Nothing appended as ${name}`);+ }+ return call;+}++beforeEach(() => {+ vi.clearAllMocks();+ appendCalls = [];+ mockIconPacks.length = 0;+ mockContentRenderer.renderNoteForExport.mockReturnValue("<p>rendered</p>");+});++afterEach(() => vi.restoreAllMocks());++describe("ShareThemeExportProvider", () => {+ describe("prepareMeta", () => {+ it("registers each asset file and an index entry", () => {+ const provider = makeProvider();+ const metaFile: any = { files: [{ noteId: "rootNote", title: "Root" }] };++ provider.prepareMeta(metaFile);++ const dataFileNames = metaFile.files.map((f: any) => f.dataFileName).filter(Boolean);+ expect(dataFileNames).toEqual([ "icon-color.svg", "assets/styles.css", "index.html" ]);+ // rootMeta is taken from the first existing file entry+ expect((provider as any).rootMeta).toBe(metaFile.files[0]);+ });+ });++ describe("mapExtension", () => {+ it("returns null for images, js for javascript, null for .zip, html otherwise", () => {+ const p = makeProvider();+ expect(p.mapExtension("image", "image/png", "", "share")).toBeNull();+ expect(p.mapExtension("code", "application/javascript", "", "share")).toBe("js");+ expect(p.mapExtension("file", "application/zip", ".zip", "share")).toBeNull();+ expect(p.mapExtension("text", "text/html", "", "share")).toBe("html");+ });+ });++ describe("prepareContent", () => {+ it("throws when the note path is missing", () => {+ const p = makeProvider();+ expect(() => p.prepareContent("t", "x", { notePath: [] } as any, undefined as any, {} as any))+ .toThrow(/note path/i);+ });++ it("returns content unchanged when there is no note (no search index entry)", () => {+ const p = makeProvider();+ const result = p.prepareContent("t", "raw", { notePath: ["root", "a"] } as any, undefined as any, {} as any);+ expect(result).toBe("raw");+ expect((p as any).searchIndex.size).toBe(0);+ });++ it("rewrites attachment links, note links, and builds a search-index entry for a note", () => {+ const note = {+ noteId: "noteABC",+ getBestNotePath: () => ["root", "parent12chars", "noteABC12char"]+ };+ mockBecca.getNote.mockImplementation((id: string) =>+ id === "parent12chars" ? { title: "Parent" } : null);++ // Render output exercises both the attachment and note link rewrites.+ mockContentRenderer.renderNoteForExport.mockReturnValue(+ `<a href="api/attachments/att123456/download">f</a>` ++ `<a href="x./otherNote123">n</a>` ++ `<a href="x./assets/keepme12345">keep</a>`+ );++ const p = makeProvider();+ (p as any).rootMeta = { noteId: "rootNote" };+ const noteMeta: any = {+ notePath: ["root", "parent12chars", "noteABC12char"],+ attachments: [{ attachmentId: "att123456", dataFileName: "files/att.png" }]+ };++ const out = p.prepareContent("Title", "<p>html</p>", noteMeta, note as any, {} as any) as string;++ // Attachment download link rewritten to its data file name.+ expect(out).toContain('href="files/att.png"');+ // Plain note link rewritten to a hash anchor.+ expect(out).toContain('href="#root/otherNote123"');+ // /assets/ links are preserved untouched.+ expect(out).toContain("/assets/keepme12345");++ const entry = (p as any).searchIndex.get("noteABC");+ expect(entry.title).toBe("Title");+ expect(entry.content).toContain("TEXT:");+ // Path built from titles, excluding root and falsy titles.+ expect(entry.path).toBe("Parent");+ });++ it("keeps the original attachment link when the attachment has no data file (or no attachments at all)", () => {+ const note = { noteId: "noAtt", getBestNotePath: () => ["root", "noAtt1234567"] };+ mockBecca.getNote.mockReturnValue(null);+ mockContentRenderer.renderNoteForExport.mockReturnValue(+ `<a href="api/attachments/att999999/download">f</a>`+ );++ const p = makeProvider();+ // Attachment present but without a dataFileName.+ const withAtt: any = {+ notePath: ["root", "noAtt1234567"],+ attachments: [{ attachmentId: "att999999" }]+ };+ const out1 = p.prepareContent("t", "<p>c</p>", withAtt, note as any, {} as any) as string;+ expect(out1).toContain('href="api/attachments/att999999/download"');++ // No attachments array at all.+ const noAttArr: any = { notePath: ["root", "noAtt1234567"] };+ const out2 = p.prepareContent("t", "<p>c</p>", noAttArr, note as any, {} as any) as string;+ expect(out2).toContain('href="api/attachments/att999999/download"');+ });++ it("rewrites a note link pointing at the root to the base path", () => {+ const note = { noteId: "rootChild", getBestNotePath: () => ["root", "rootNote12345"] };+ mockBecca.getNote.mockReturnValue(null);+ mockContentRenderer.renderNoteForExport.mockReturnValue(`<a href="x./rootNote1234">root</a>`);++ const p = makeProvider();+ (p as any).rootMeta = { noteId: "rootNote1234" };+ const noteMeta: any = { notePath: ["root", "rootNote1234"], attachments: [] };++ const out = p.prepareContent("t", "<p>c</p>", noteMeta, note as any, {} as any) as string;+ // basePath for a 2-element path is "" (root link points to the base).+ expect(out).toContain('href=""');+ });++ it("leaves binary (non-string) content untouched but still indexes the note", () => {+ const note = { noteId: "binNote", getBestNotePath: () => ["root", "binNote12345"] };+ mockBecca.getNote.mockReturnValue(null);+ mockContentRenderer.renderNoteForExport.mockReturnValue(new Uint8Array([1, 2, 3]) as any);++ const p = makeProvider();+ const noteMeta: any = { notePath: ["root", "binNote12345"], attachments: [] };++ const out = p.prepareContent("Bin", new Uint8Array([9]), noteMeta, note as any, {} as any);+ expect(out).toBeInstanceOf(Uint8Array);+ // Binary input means empty search content.+ expect((p as any).searchIndex.get("binNote").content).toBe("");+ });+ });++ describe("afterDone", () => {+ it("writes index, 404, assets, fonts, and the search index json", () => {+ const p = makeProvider();+ (p as any).indexMeta = { dataFileName: "index.html" };+ (p as any).rootMeta = { noteId: "rootNote" };++ // A builtin icon pack (read through the platform's assets) and a custom one (from becca).+ mockIconPacks.push(+ { prefix: "BX", fontMime: "font/woff2", fontAttachmentId: "boxicons", builtin: true },+ { prefix: "Custom", fontMime: "font/ttf", fontAttachmentId: "customAtt", builtin: false }+ );+ (p as any).iconPacks = mockIconPacks;+ mockBecca.getAttachment.mockReturnValue({ getContent: () => new Uint8Array([ 3 ]) });++ // search index with one valid + one null-id entry+ (p as any).searchIndex.set("n1", { id: "n1", title: "T", content: "c", path: "p" });+ (p as any).searchIndex.set("n2", { id: null, title: "T2", content: "c2", path: "p2" });+ (p as any).getNoteTargetUrl.mockReturnValue("resolved/n1");++ // #saveIndex re-runs prepareContent against rootMeta, so it needs a notePath.+ const rootMeta: any = { noteId: "rootNote", title: "Root", notePath: ["root", "rootNote12345"], attachments: [] };+ p.afterDone(rootMeta);++ expect(appendCalls.map((c) => c.options.name)).toEqual(expect.arrayContaining([+ "index.html", "404.html", "search-index.json", "assets/icon-pack-custom.ttf"+ ]));+ expect(findAppend("icon-color.svg").data).toBe(iconColor);+ expect(findAppend("assets/styles.css").data).toBe(styles);+ expect(readBuiltinFont).toHaveBeenCalledWith("boxicons.woff2");+ expect(findAppend("assets/icon-pack-bx.woff2").data).toEqual(new Uint8Array([ 2 ]));++ const parsed = JSON.parse(findAppend("search-index.json").data);+ // Only the entry with a non-null id is URL-resolved; both are serialized.+ expect(parsed.find((e: any) => e.id === "resolved/n1")).toBeTruthy();+ });++ it("appends binary index content and string font data as-is", () => {+ const p = makeProvider();+ (p as any).indexMeta = { dataFileName: "index.html" };+ (p as any).rootMeta = { noteId: "rootNote" };++ const binaryIndex = new Uint8Array([1, 2, 3]);+ mockContentRenderer.renderNoteForExport.mockReturnValue(binaryIndex as any);++ mockIconPacks.push({ prefix: "Str", fontMime: "font/ttf", fontAttachmentId: "strAtt", builtin: false });+ (p as any).iconPacks = mockIconPacks;+ mockBecca.getAttachment.mockReturnValue({ getContent: () => "string-font-data" });++ const rootMeta: any = { noteId: "rootNote", title: "Root", notePath: ["root", "rootNote12345"], attachments: [] };+ p.afterDone(rootMeta);++ expect(findAppend("index.html").data).toBe(binaryIndex);+ expect(findAppend("assets/icon-pack-str.ttf").data).toBe("string-font-data");+ });++ it("defaults the index title to an empty string when rootMeta has no title", () => {+ const p = makeProvider();+ (p as any).indexMeta = { dataFileName: "index.html" };+ (p as any).rootMeta = { noteId: "rootNote" };+ mockContentRenderer.renderNoteForExport.mockReturnValue("<p>x</p>");++ const rootMeta: any = { noteId: "rootNote", notePath: ["root", "rootNote12345"], attachments: [] };+ p.afterDone(rootMeta);++ expect(mockContentRenderer.renderNoteForExport).toHaveBeenCalled();+ expect(appendCalls.map((c) => c.options.name)).toContain("index.html");+ });++ it("skips the index when there is no index data file name", () => {+ const p = makeProvider();+ (p as any).indexMeta = null;+ p.afterDone({ noteId: "rootNote", title: "Root" } as any);++ expect(appendCalls.map((c) => c.options.name)).not.toContain("index.html");+ // 404 + search-index are still written.+ expect(appendCalls.map((c) => c.options.name)).toContain("404.html");+ });++ it("logs an error and skips a font when its data cannot be found", () => {+ const p = makeProvider();+ (p as any).indexMeta = null;+ mockIconPacks.push(+ { prefix: "Missing", fontMime: "font/ttf", fontAttachmentId: "gone", builtin: false },+ { prefix: "Absent", fontMime: "font/woff2", fontAttachmentId: "absent", builtin: true }+ );+ (p as any).iconPacks = mockIconPacks;+ mockBecca.getAttachment.mockReturnValue(undefined);+ readBuiltinFont.mockReturnValueOnce(undefined);++ p.afterDone({ noteId: "rootNote", title: "Root" } as any);++ expect(mockLog.error).toHaveBeenCalledTimes(2);+ const names = appendCalls.map((c) => c.options.name);+ expect(names).not.toContain("assets/icon-pack-missing.ttf");+ expect(names).not.toContain("assets/icon-pack-absent.woff2");+ });+ });+});diff --git a/packages/trilium-core/src/services/export/zip/share_theme.ts b/packages/trilium-core/src/services/export/zip/share_theme.tsnew file mode 100644index 0000000000..ebbff75ba5--- /dev/null+++ b/packages/trilium-core/src/services/export/zip/share_theme.ts@@ -0,0 +1,179 @@+import { convert as convertToText } from "html-to-text";+import { t } from "i18next";+import ejs from "ejs";++import becca from "../../../becca/becca.js";+import type BBranch from "../../../becca/entities/bbranch.js";+import type BNote from "../../../becca/entities/bnote.js";+import type { ExportFormat, NoteMeta, NoteMetaFile } from "../../../meta.js";+import { readShareTemplate, renderNoteForExport } from "../../../share/index.js";+import * as iconPackService from "../../icon_packs.js";+import { getLog } from "../../log.js";+import { ZipExportProvider, type ZipExportProviderData } from "./abstract_provider.js";++/** The static files a share-theme export copies into the archive, read by each platform its own way. */+export interface ShareThemeExportAssets {+ /** The share theme's files, keyed by their path in the archive: `icon-color.svg` and `assets/<file>`. */+ files: Map<string, string | Uint8Array>;+ /** Returns the font of a built-in icon pack, such as `boxicons.woff2`. */+ readBuiltinFont(fileName: string): Uint8Array | undefined;+}++interface SearchIndexEntry {+ id: string | null;+ title: string;+ content: string;+ path: string;+}++export default class ShareThemeExportProvider extends ZipExportProvider {++ private indexMeta: NoteMeta | null = null;+ private searchIndex: Map<string, SearchIndexEntry> = new Map();+ private rootMeta: NoteMeta | null = null;+ private iconPacks: iconPackService.ProcessedIconPack[] = [];+ private assets: ShareThemeExportAssets;++ constructor(data: ZipExportProviderData, assets: ShareThemeExportAssets) {+ super(data);+ this.assets = assets;+ }++ prepareMeta(metaFile: NoteMetaFile): void {+ for (const asset of this.assets.files.keys()) {+ metaFile.files.push({+ noImport: true,+ dataFileName: asset+ });+ }++ this.indexMeta = {+ noImport: true,+ dataFileName: "index.html"+ };+ this.rootMeta = metaFile.files[0];+ this.iconPacks = iconPackService.getIconPacks();++ metaFile.files.push(this.indexMeta);+ }++ prepareContent(title: string, content: string | Uint8Array, noteMeta: NoteMeta, note: BNote | undefined, branch: BBranch): string | Uint8Array {+ if (!noteMeta?.notePath?.length) {+ throw new Error("Missing note path.");+ }+ const basePath = "../".repeat(Math.max(0, noteMeta.notePath.length - 2));+ let searchContent = "";++ if (note) {+ // Prepare search index.+ searchContent = typeof content === "string" ? convertToText(content, {+ whitespaceCharacters: "\t\r\n\f "+ }) : "";++ // TODO: This will probably never match, but should it be exclude from running on code/jsFrontend notes?+ content = renderNoteForExport(note, branch, basePath, noteMeta.notePath.slice(0, -1), this.iconPacks);+ if (typeof content === "string") {+ // Rewrite attachment download links+ content = content.replace(/href="api\/attachments\/([a-zA-Z0-9_]+)\/download"/g, (match, attachmentId) => {+ const attachmentMeta = (noteMeta.attachments || []).find((attMeta) => attMeta.attachmentId === attachmentId);+ if (attachmentMeta?.dataFileName) {+ return `href="${attachmentMeta.dataFileName}"`;+ }+ return match;+ });++ // Rewrite note links+ content = content.replace(/href="[^"]*\.\/([a-zA-Z0-9_\/]{12})[^"]*"/g, (match, id) => {+ if (match.includes("/assets/")) return match;+ if (id === this.rootMeta?.noteId) {+ return `href="${basePath}"`;+ }+ return `href="#root/${id}"`;+ });+ content = this.rewriteFn(content, noteMeta);+ }++ // Prepare search index.+ this.searchIndex.set(note.noteId, {+ id: note.noteId,+ title,+ content: searchContent,+ path: note.getBestNotePath()+ .map(noteId => noteId !== "root" && becca.getNote(noteId)?.title)+ .filter(noteId => noteId)+ .join(" / ")+ });+ }++ return content;+ }++ afterDone(rootMeta: NoteMeta): void {+ this.#saveAssets();+ this.#saveIndex(rootMeta);+ this.#save404();++ // Search index+ for (const item of this.searchIndex.values()) {+ if (!item.id) continue;+ item.id = this.getNoteTargetUrl(item.id, rootMeta);+ }++ this.archive.append(JSON.stringify(Array.from(this.searchIndex.values()), null, 4), { name: "search-index.json" });+ }++ mapExtension(type: string | null, mime: string, existingExtension: string, format: ExportFormat): string | null {+ if (mime.startsWith("image/")) {+ return null;+ }++ if (mime.startsWith("application/javascript")) {+ return "js";+ }++ // Don't add .html if the file already has .zip extension (for attachments).+ if (existingExtension === ".zip") {+ return null;+ }++ return "html";+ }++ #saveIndex(rootMeta: NoteMeta) {+ if (!this.indexMeta?.dataFileName) {+ return;+ }++ const note = this.branch.getNote();+ const content = this.prepareContent(rootMeta.title ?? "", note.getContent(), rootMeta, note, this.branch);+ this.archive.append(content, { name: this.indexMeta.dataFileName });+ }++ #saveAssets() {+ for (const [ name, content ] of this.assets.files) {+ this.archive.append(content, { name });+ }++ // Inject the custom fonts.+ for (const iconPack of this.iconPacks) {+ const extension = iconPackService.MIME_TO_EXTENSION_MAPPINGS[iconPack.fontMime];+ const fontData = iconPack.builtin+ ? this.assets.readBuiltinFont(`${iconPack.fontAttachmentId}.${extension}`)+ : becca.getAttachment(iconPack.fontAttachmentId)?.getContent();++ if (!fontData) {+ getLog().error(`Failed to find font data for icon pack ${iconPack.prefix} with attachment ID ${iconPack.fontAttachmentId}`);+ continue;+ }+ this.archive.append(fontData, {+ name: `assets/icon-pack-${iconPack.prefix.toLowerCase()}.${extension}`+ });+ }+ }++ #save404() {+ const content = ejs.render(readShareTemplate("404"), { t });+ this.archive.append(content, { name: "404.html" });+ }++}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 11417d8252..b11c875376 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -633,9 +633,6 @@ importers:better-sqlite3:specifier: 13.0.3version: 13.0.3- html-to-text:- specifier: 10.0.1- version: 10.0.1i18next:specifier: 26.4.2version: 26.4.2([email protected])@@ -1425,6 +1422,9 @@ importers:escape-html:specifier: 1.0.3version: 1.0.3+ html-to-text:+ specifier: 10.0.1+ version: 10.0.1i18next:specifier: 26.4.2version: 26.4.2([email protected])@@ -1474,6 +1474,9 @@ importers:'@types/escape-html':specifier: 1.0.4version: 1.0.4+ '@types/html-to-text':+ specifier: 9.0.4+ version: 9.0.4'@types/mime-types':specifier: 3.0.1version: 3.0.1@@ -4687,6 +4690,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==}+ '@types/[email protected]':+ resolution: {integrity: sha512-pUY3cKH/Nm2yYrEmDlPR1mR7yszjGx4DrwPjQ702C4/D5CwHuZTgZdIdwPkRbcuhs7BAh2L5rg3CL5cbRiGTCQ==}+'@types/[email protected]':resolution: {integrity: sha512-Wb1ymSAftCLxhc3D6vS0Ike/0xg7W6c+DQxAkerU6pD7C8CMzTYwvrwnlcrTfsVO/nMelB9KOKIT7+N5lOeQUg==}@@ -15728,6 +15734,8 @@ snapshots:dependencies:'@types/unist': 3.0.3+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}