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
test(export): raise core export coverage to 97% lines and 99% functions
Elian Doran62651d7574ba
diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.tsindex 2f5bf96745..8cef49dd52 100644--- a/packages/trilium-core/src/services/export/markdown.spec.ts+++ b/packages/trilium-core/src/services/export/markdown.spec.ts@@ -1,7 +1,7 @@import { trimIndentation } from "@triliumnext/commons";import { describe, expect,it } from "vitest";-import markdownExportService from "./markdown.js";+import markdownExportService, { DEFAULT_ADMONITION_TYPE } from "./markdown.js";describe("Markdown export", () => {@@ -141,6 +141,25 @@ describe("Markdown export", () => {expect(exported).not.toContain('href="javascript:');});+ it("preserves a link preview that has no data-url, and still drops ordinary blank nodes", () => {+ // Without a data-url there is nothing to build a fallback anchor from, so the element stays+ // blank and only the blank-node handling can keep it from being dropped along with its metadata.+ expect(markdownExportService.toMarkdown(+ '<section class="link-embed" data-embed-type="opengraph" data-title="Example"></section>'+ )).toBe('<section class="link-embed" data-embed-type="opengraph" data-title="Example"></section>');++ // The trailing space is collapsed away here, because turndown assumes an empty inline element+ // renders as nothing; a mention with a URL keeps it thanks to the injected fallback anchor.+ expect(markdownExportService.toMarkdown(+ '<p>See <span class="link-mention" data-title="Example"></span> for details.</p>'+ )).toBe('See <span class="link-mention" data-title="Example"></span>for details.');++ // Every other blank node keeps upstream's behaviour: a paragraph break for a block element,+ // nothing at all for an inline one.+ expect(markdownExportService.toMarkdown("<p>a</p><p></p><p>b</p>")).toBe("a\n\nb");+ expect(markdownExportService.toMarkdown("<p>a<span></span>b</p>")).toBe("ab");+ });+it("exports strikethrough text correctly", () => {const html = "<s>hello</s>Hello <s>world</s>";const expected = "~~hello~~Hello ~~world~~";@@ -280,6 +299,13 @@ describe("Markdown export", () => {expect(markdownExportService.toMarkdown(html)).toBe(expected);});+ it("falls back to the default admonition type for an unrecognized class", () => {+ // Markdown alerts only define a fixed set of types, so anything Trilium can't map (a stale or+ // hand-written class) degrades to the default rather than emitting an invalid alert.+ const html = /*html*/`<aside class="admonition something-else"><p>Body</p></aside>`;+ expect(markdownExportService.toMarkdown(html)).toBe(`> [!${DEFAULT_ADMONITION_TYPE}]\n> Body`);+ });+it("exports code in tables properly", () => {const html = trimIndentation`\<table>@@ -339,6 +365,11 @@ describe("Markdown export", () => {expect(markdownExportService.toMarkdown(html)).toBe(expected);});+ it("keeps the link title, escaping quotes inside it", () => {+ const html = /*html*/`<p><a href="https://www.google.com" title='a "quoted" title'>Google</a></p>`;+ expect(markdownExportService.toMarkdown(html)).toBe(String.raw`[Google](https://www.google.com "a \"quoted\" title")`);+ });+it("exports reference links verbatim", () => {const html = /*html*/`<p><a class="reference-link" href="../../Canvas.html">Canvas</a></p>`;const expected = `<a class="reference-link" href="../../Canvas.html">Canvas</a>`;@@ -364,6 +395,22 @@ describe("Markdown export", () => {}});+ it("escapes markdown syntax in the image alt text and quotes in its title", () => {+ // Unescaped, these would be re-parsed as emphasis/link syntax on reimport.+ expect(markdownExportService.toMarkdown(/*html*/`<img src="a.png" alt="a*b_c[d]">`))+ .toBe(String.raw`![a\*b\_c\[d\]](a.png)`);+ // The trailing-pattern branch: a leading number followed by a dot would start a list.+ expect(markdownExportService.toMarkdown(/*html*/`<img src="a.png" alt="1. first">`))+ .toBe(String.raw``);+ // A quote in the title would otherwise close the title string early.+ expect(markdownExportService.toMarkdown(/*html*/`<img src="a.png" title='He said "hi"'>`))+ .toBe(String.raw``);+ });++ it("drops an image with no source", () => {+ expect(markdownExportService.toMarkdown(/*html*/`<p>before<img alt="x">after</p>`)).toBe("beforeafter");+ });+it("preserves figures", () => {const html = /*html*/trimIndentation`\<figure class="image" style="width:53.44%;">@@ -425,6 +472,14 @@ describe("Markdown export", () => {expect(markdownExportService.toMarkdown(html)).toBe(expected);});+ it("numbers an ordered list from its start attribute", () => {+ const html = /*html*/`<ol start="3"><li>Third</li><li>Fourth</li></ol>`;+ const expected = trimIndentation`\+ 3. Third+ 4. Fourth`;+ expect(markdownExportService.toMarkdown(html)).toBe(expected);+ });+it("converts inline math expressions into proper Markdown syntax", () => {const html = /*html*/String.raw`<span class="math-tex">\(H(X, Y) = \sum_{i=1}^{M} \sum_{j=1}^{L} p(x_i, y_j) \log_2 \frac{1}{p(x_i, y_j)} = - \sum_{i=1}^{M} \sum_{j=1}^{L} p(x_i, y_j) \log_2 p(x_i, y_j) \frac{\text{bits}}{\text{symbol}}\)</span></span>`;const expected = String.raw`$H(X, Y) = \sum_{i=1}^{M} \sum_{j=1}^{L} p(x_i, y_j) \log_2 \frac{1}{p(x_i, y_j)} = - \sum_{i=1}^{M} \sum_{j=1}^{L} p(x_i, y_j) \log_2 p(x_i, y_j) \frac{\text{bits}}{\text{symbol}}$`;@@ -437,6 +492,13 @@ describe("Markdown export", () => {expect(markdownExportService.toMarkdown(html)).toBe(expected);});+ it("keeps a math expression without delimiters verbatim", () => {+ // Neither \( \) nor \[ \] — nothing can be inferred, so the raw text is passed through+ // rather than guessed into the wrong math mode.+ const html = /*html*/`<span class="math-tex">E = mc^2</span>`;+ expect(markdownExportService.toMarkdown(html)).toBe("E = mc^2");+ });+it("does not generate additional spacing when exporting lists with paragraph", () => {const html = trimIndentation`\<ul>diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.tsindex 0b28427794..e89febe8d7 100644--- a/packages/trilium-core/src/services/export/markdown.ts+++ b/packages/trilium-core/src/services/export/markdown.ts@@ -22,6 +22,8 @@ const fencedCodeBlockFilter: Rule = {},replacement (content, node, options) {+ /* v8 ignore next 3 -- unreachable: the filter above only matches when firstChild is a <code>+ element, so getAttribute is always there; the guard is here to narrow the `Node` type. */if (!node.firstChild || !("getAttribute" in node.firstChild) || typeof node.firstChild.getAttribute !== "function") {return content;}@@ -142,11 +144,14 @@ function buildImageFilter() {function buildAdmonitionFilter() {function parseAdmonitionType(_node: Node) {+ /* v8 ignore next 3 -- unreachable: the filter below only matches an <aside> element, so+ getAttribute is always there; the guard is here to narrow the `Node` type. */if (!("getAttribute" in _node)) {return DEFAULT_ADMONITION_TYPE;}const node = _node as Element;+ /* v8 ignore next -- the filter requires class="… admonition …", so the attribute is always set. */const classList = node.getAttribute("class")?.split(" ") ?? [];for (const className of classList) {@@ -209,6 +214,7 @@ function buildInlineLinkFilter(): Rule {// Otherwise treat as normal.// TODO: Call super() somehow instead of duplicating the implementation.let href = node.getAttribute('href');+ /* v8 ignore next -- the filter requires a non-empty href, so this never falls through. */if (href) href = href.replace(/([()])/g, '\\$1');let title = cleanAttribute(node.getAttribute('title'));if (title) title = ` "${title.replace(/"/g, '\\"')}"`;diff --git a/packages/trilium-core/src/services/export/opml.spec.ts b/packages/trilium-core/src/services/export/opml.spec.tsindex 192f964fd5..e9c57e7fdb 100644--- a/packages/trilium-core/src/services/export/opml.spec.ts+++ b/packages/trilium-core/src/services/export/opml.spec.ts@@ -1,6 +1,7 @@import type { Response } from "express";import { beforeAll, describe, expect, it } from "vitest";+import becca from "../../becca/becca.js";import type BBranch from "../../becca/entities/bbranch.js";import type BNote from "../../becca/entities/bnote.js";import { getContext } from "../context.js";@@ -63,6 +64,14 @@ function getTaskContext() {return TaskContext.getInstance("opml-export-spec", "export", null);}+/**+ * A branch-like stand-in used to drive the export from a branch that becca does not (or does not+ * yet) know about — a state the real tree can be in while a sync/import is in flight.+ */+function detachedBranch(note: BNote, branchId: string | undefined): BBranch {+ return { branchId, prefix: null, getNote: () => note } as unknown as BBranch;+}+function runExport(branch: BBranch): FakeResponse {const res = new FakeResponse();opml.exportToOpml(getTaskContext(), branch, res as unknown as Response);@@ -176,4 +185,40 @@ describe("exportToOpml (real DB)", () => {expect(body).toContain(`<outline text="Binary note" _note="">`);});++ it("throws when the exported branch is not in becca", () => {+ const { note } = createNote("root", { title: "Detached", content: "" });++ expect(() => runExport(detachedBranch(note, "missingBranchId"))).toThrow("Unable to find branch.");+ });++ it("writes only the envelope when the branch has no id yet", () => {+ const { note } = createNote("root", { title: "Unsaved", content: "" });++ const res = runExport(detachedBranch(note, undefined));++ expect(res.body).not.toContain("<outline");+ expect(res.body).toContain(`<opml version="2.0">`);+ expect(res.ended).toBe(true);+ });++ it("skips a child whose branch is missing from becca's child-parent index", () => {+ const { note: parent, branch } = createNote("root", { title: "Index parent", content: "" });+ const { note: child } = createNote(parent.noteId, { title: "Indexed child", content: "" });++ // getChildBranches() maps note.children through that index and casts the result, so an index+ // entry lagging behind the children (as it can during sync/import) yields a hole in the list.+ const key = `${child.noteId}-${parent.noteId}`;+ const indexedBranch = becca.childParentToBranch[key];+ delete becca.childParentToBranch[key];++ try {+ const body = runExport(branch).body;++ expect(body).toContain(`text="Index parent"`);+ expect(body).not.toContain(`text="Indexed child"`);+ } finally {+ becca.childParentToBranch[key] = indexedBranch;+ }+ });}, 60_000);diff --git a/packages/trilium-core/src/services/export/opml.ts b/packages/trilium-core/src/services/export/opml.tsindex 4786d294e1..fbe0951606 100644--- a/packages/trilium-core/src/services/export/opml.ts+++ b/packages/trilium-core/src/services/export/opml.ts@@ -15,6 +15,8 @@ function exportToOpml(taskContext: TaskContext<"export">, branch: BBranch, res:}const note = branch.getNote();+ /* v8 ignore next 3 -- unreachable: BBranch.getNote() resolves through becca's childNote+ getter, which materialises a skeleton note rather than ever returning a falsy value. */if (!note) {throw new Error("Unable to find note.");}diff --git a/packages/trilium-core/src/services/export/rewrite_links.spec.ts b/packages/trilium-core/src/services/export/rewrite_links.spec.tsindex 42cc92f108..e2f0732b72 100644--- a/packages/trilium-core/src/services/export/rewrite_links.spec.ts+++ b/packages/trilium-core/src/services/export/rewrite_links.spec.ts@@ -69,6 +69,17 @@ describe("rewriteMarkdownContentLinks", () => {.toBe("");});+ it("preserves attachment links when the note meta carries no attachments key at all", () => {+ // `attachments` is optional on NoteMeta, so a note that never had any is exported without it.+ const noteMeta: NoteMeta = { noteId: "testNote1", notePath: ["root", "testNote1"] };+ const content = [+ "",+ "[doc.pdf](#root/note1?attachmentId=att2)"+ ].join("\n");++ expect(rewriteMarkdownContentLinks(content, noteMeta, nullNoteUrl)).toBe(content);+ });+it("handles attachment URL with leading slash", () => {const content = "";const noteMeta = buildNoteMeta([{ attachmentId: "abc123", dataFileName: "Note_photo.png" }]);diff --git a/packages/trilium-core/src/services/export/single.spec.ts b/packages/trilium-core/src/services/export/single.spec.tsindex d7cf5377b2..48e513f0d6 100644--- a/packages/trilium-core/src/services/export/single.spec.ts+++ b/packages/trilium-core/src/services/export/single.spec.ts@@ -1,9 +1,14 @@+import type { Response } from "express";import { describe, expect, it, vi } from "vitest";import becca from "../../becca/becca.js";import type BAttachment from "../../becca/entities/battachment.js";+import type BBranch from "../../becca/entities/bbranch.js";+import type BNote from "../../becca/entities/bnote.js";+import type { ExportFormat } from "../../meta.js";+import TaskContext from "../task_context.js";import { buildNote } from "../../test/becca_easy_mocking.js";-import { mapByNoteType } from "./single.js";+import singleExportService, { mapByNoteType } from "./single.js";describe("Note type mappings", () => {it("supports mermaid note", () => {@@ -98,4 +103,149 @@ describe("Note type mappings", () => {});}});++ it("dumps canvas, relation map and search notes verbatim as JSON", () => {+ const cases = [+ { type: "canvas" as const, extension: "excalidraw" },+ { type: "relationMap" as const, extension: "json" },+ { type: "search" as const, extension: "json" }+ ];++ for (const { type, extension } of cases) {+ const note = buildNote({ type, title: "Raw" });+ expect(mapByNoteType(note, "{}", "html")).toMatchObject({ payload: "{}", extension, mime: "application/json" });+ }+ });++ it("refuses binary content, which has no single-file text representation", () => {+ const note = buildNote({ type: "text", title: "Binary" });++ expect(() => mapByNoteType(note, new Uint8Array([1, 2, 3]), "html")).toThrow("Unsupported content type for export.");+ });+});++describe("inlineAttachments", () => {+ /** Runs a text note's HTML through the export, which is what applies the inlining. */+ function exportHtml(content: string) {+ return String(mapByNoteType(buildNote({ type: "text", title: "Inliner" }), content, "html").payload);+ }++ it("inlines an embedded image note as a base64 data URI", () => {+ const imageNote = buildNote({ type: "image", mime: "image/png", title: "pic.png" });+ vi.spyOn(imageNote, "getContent").mockReturnValue(new Uint8Array([1, 2, 3]));+ const getNote = vi.spyOn(becca, "getNote").mockReturnValue(imageNote);++ try {+ const payload = exportHtml(`<p><img src="api/images/img1/pic.png"></p>`);++ expect(getNote).toHaveBeenCalledWith("img1");+ expect(payload).toContain(`src="data:image/png;base64,AQID"`);+ expect(payload).not.toContain("api/images");+ } finally {+ getNote.mockRestore();+ }+ });++ it("leaves an embedded image alone when the note is missing, not an image, or holds text", () => {+ const textNote = buildNote({ type: "text", mime: "text/html", title: "Not an image" });+ const stringImage = buildNote({ type: "image", mime: "image/png", title: "odd.png" });+ vi.spyOn(stringImage, "getContent").mockReturnValue("not binary");+ const getNote = vi.spyOn(becca, "getNote");++ try {+ for (const stub of [null, textNote, stringImage]) {+ getNote.mockReturnValue(stub as never);+ expect(exportHtml(`<p><img src="api/images/img1/pic.png"></p>`)).toContain(`src="api/images/img1/pic.png"`);+ }+ } finally {+ getNote.mockRestore();+ }+ });++ it("inlines an attachment link as a downloadable data URI", () => {+ const fakeAttachment = {+ mime: "application/pdf",+ title: "report <v2>.pdf",+ getContent: () => new Uint8Array([1, 2, 3])+ } as unknown as BAttachment;+ const getAttachment = vi.spyOn(becca, "getAttachment").mockReturnValue(fakeAttachment);++ try {+ const payload = exportHtml(`<p><a href="#root/abc?viewMode=attachments&attachmentId=att1">Report</a></p>`);++ expect(payload).toContain(`href="data:application/pdf;base64,AQID"`);+ // The download filename is escaped, so a title with markup can't break out of the attribute.+ expect(payload).toContain(`download="report <v2>.pdf"`);+ } finally {+ getAttachment.mockRestore();+ }+ });++ it("leaves an attachment reference alone when it is missing, not an image, or holds text", () => {+ const getAttachment = vi.spyOn(becca, "getAttachment");+ const textAttachment = { mime: "text/plain", title: "notes.txt", getContent: () => "plain text" } as unknown as BAttachment;++ try {+ // `data-image` only inlines images, so a non-image attachment is left as-is ...+ getAttachment.mockReturnValue(textAttachment);+ expect(exportHtml(`<section data-image="api/attachments/att1/image/x.png"></section>`))+ .toContain(`data-image="api/attachments/att1/image/x.png"`);++ // ... as is an image attachment whose content came back as text ...+ getAttachment.mockReturnValue({ mime: "image/png", title: "x.png", getContent: () => "text" } as unknown as BAttachment);+ expect(exportHtml(`<section data-image="api/attachments/att1/image/x.png"></section>`))+ .toContain(`data-image="api/attachments/att1/image/x.png"`);++ // ... and an href to an attachment that no longer exists, or whose content is text.+ getAttachment.mockReturnValue(null as never);+ expect(exportHtml(`<p><a href="#root/abc?viewMode=attachments&attachmentId=att1">x</a></p>`))+ .toContain("attachmentId=att1");++ getAttachment.mockReturnValue(textAttachment);+ expect(exportHtml(`<p><a href="#root/abc?viewMode=attachments&attachmentId=att1">x</a></p>`))+ .toContain("attachmentId=att1");+ } finally {+ getAttachment.mockRestore();+ }+ });+});++describe("exportSingleNote", () => {+ /**+ * `format` is deliberately widened past {@link ExportFormat} so the "unrecognized format" guard —+ * which only a caller bypassing the route's own validation can reach — stays testable.+ */+ function exportNote(note: BNote, format: ExportFormat | "pdf") {+ const branch = { getNote: () => note } as unknown as BBranch;+ const res = { setHeader: vi.fn(), send: vi.fn() } as unknown as Response;+ const taskContext = TaskContext.getInstance(`export-single-${note.type}-${format}`, "export", null);++ return { result: singleExportService.exportSingleNote(taskContext, branch, format as ExportFormat, res), res };+ }++ it("writes the mapped payload and download headers for a supported note", () => {+ const note = buildNote({ type: "code", mime: "text/x-markdown", title: "script" });+ vi.spyOn(note, "getContent").mockReturnValue("# hi");++ const { res } = exportNote(note, "html");++ expect(res.setHeader).toHaveBeenCalledWith("Content-Disposition", expect.stringContaining("script.md"));+ expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "text/x-markdown; charset=UTF-8");+ expect(res.send).toHaveBeenCalledWith("# hi");+ });++ it("returns a 400 tuple for note types and formats it cannot export", () => {+ // NOTE: routes/api/export.ts discards this return value and never sends a response of its+ // own, so these rejections currently leave the HTTP request unanswered.+ for (const type of ["image", "file"] as const) {+ const { result, res } = exportNote(buildNote({ type, title: "Binary" }), "html");++ expect(result).toEqual([400, `Note type '${type}' cannot be exported as single file.`]);+ expect(res.send).not.toHaveBeenCalled();+ }++ const { result, res } = exportNote(buildNote({ type: "text", title: "Texty" }), "pdf");+ expect(result).toEqual([400, "Unrecognized format 'pdf'"]);+ expect(res.send).not.toHaveBeenCalled();+ });});diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.tsindex b5eea27dcf..374c210c31 100644--- a/packages/trilium-core/src/services/export/zip.spec.ts+++ b/packages/trilium-core/src/services/export/zip.spec.ts@@ -493,6 +493,129 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {const clonePath = `${clones[0].dirPath}${clones[0].dataFileName}`;expect(entries[clonePath].toString("utf-8")).toContain("clone of a note");});++ it("falls back to a generic data file name when the title sanitizes away entirely", async () => {+ // sanitize() strips "/" wholesale, leaving nothing to name the file after.+ const { note } = createNote("root", { title: "///", content: "<p>nameless</p>" });++ const { entries } = await exportSubtree(note.getParentBranches()[0], "html");++ expect(entries["note.html"]?.toString("utf-8")).toContain("nameless");+ });++ it("caps an overlong title when deriving the data file name", async () => {+ const { note } = createNote("root", { title: "T".repeat(250), content: "<p>long</p>" });++ const { entries } = await exportSubtree(note.getParentBranches()[0], "html");+ const dataFileName = parseMeta(entries).files[0].dataFileName ?? "";++ // Truncated to 200 characters before the ".html" extension is appended.+ expect(dataFileName).toBe(`${"T".repeat(200)}.html`);+ expect(entries[dataFileName]).toBeDefined();+ });++ it("names a share export's data file after #shareAlias instead of the title", async () => {+ const { note } = createNote("root", { title: "Internal Title", content: "<p>shared</p>" });+ getContext().init(() => note.addLabel("shareAlias", "public-alias"));++ const { entries } = await exportSubtree(note.getParentBranches()[0], "share");++ expect(parseMeta(entries).files[0].dataFileName).toBe("public-alias.html");+ });++ it("rewrites links to notes inside the export and leaves outside ones alone", async () => {+ const { note: outside } = createNote("root", { title: "Outside", content: "<p>out</p>" });+ const { note: parent } = createNote("root", { title: "LinkParent", content: "" });+ const { note: target } = createNote(parent.noteId, { title: "LinkTarget", content: "<p>target</p>" });+ const { note: source } = createNote(parent.noteId, {+ title: "LinkSource",+ content: `<p><a href="#root/${target.noteId}">inside</a><a href="#root/${outside.noteId}">outside</a></p>`+ });++ const { entries } = await exportSubtree(parent.getParentBranches()[0], "html");+ const rootMeta = parseMeta(entries).files[0];+ const sourceMeta = (rootMeta.children ?? []).find((c) => c.noteId === source.noteId);+ const dataFile = entries[`${rootMeta.dirFileName}/${sourceMeta?.dataFileName}`].toString("utf-8");++ // The in-export target becomes a relative path to its exported file ...+ expect(dataFile).toContain(`href="LinkTarget.html"`);+ // ... while a note outside the subtree has no exported file, so its link is left as-is.+ expect(dataFile).toContain(`href="#root/${outside.noteId}"`);+ });++ it("rewrites attachment links to the exported file and leaves unknown ids alone", async () => {+ const { note } = createNote("root", { title: "AttLinker", content: "" });+ const attachment = getContext().init(() =>+ note.saveAttachment({ title: "doc.txt", role: "file", mime: "text/plain", content: "attached body" })+ );+ getContext().init(() =>+ note.setContent(+ `<p><a href="#root/${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}">real</a>`+ + `<a href="#root/${note.noteId}?viewMode=attachments&attachmentId=missingAtt01">dangling</a></p>`+ )+ );++ const { entries } = await exportSubtree(note.getParentBranches()[0], "html");+ const rootMeta = parseMeta(entries).files[0];+ const dataFile = entries[rootMeta.dataFileName ?? ""].toString("utf-8");++ expect(dataFile).toContain(`href="AttLinker_doc.txt"`);+ // An attachment that isn't part of the export can't be resolved, so the attachment rewriter+ // leaves it alone and the generic note-link rewriter that runs next degrades it to the+ // owning note's own exported file.+ expect(dataFile).not.toContain("missingAtt01");+ expect(dataFile).toContain(`href="AttLinker.html"`);+ });++ it("rewrites api/notes download sources only in a share export", async () => {+ const { note: parent } = createNote("root", { title: "DownloadParent", content: "" });+ const { note: file } = createNote(parent.noteId, { title: "Payload", content: "<p>payload</p>" });+ const { note: source } = createNote(parent.noteId, {+ title: "DownloadSource",+ content: `<p><img src="api/notes/${file.noteId}/download"></p>`+ });++ const readSource = async (format: ExportFormat) => {+ const { entries } = await exportSubtree(parent.getParentBranches()[0], format);+ const rootMeta = parseMeta(entries).files[0];+ const sourceMeta = (rootMeta.children ?? []).find((c) => c.noteId === source.noteId);+ // A share export hoists the root's children to the archive root; other formats nest+ // them under the root note's directory.+ const entryName = Object.keys(entries).find((name) => name.endsWith(sourceMeta?.dataFileName ?? "\0"));+ return entries[entryName ?? ""].toString("utf-8");+ };++ // Only the share export resolves the download URL onto the exported file ...+ expect(await readSource("share")).toContain(`src="Payload.html"`);+ // ... an ordinary HTML export leaves it pointing at the API.+ expect(await readSource("html")).toContain(`src="api/notes/${file.noteId}/download"`);+ });++ it("rewrites Markdown-syntax links in a markdown code note", async () => {+ const { note: parent } = createNote("root", { title: "MdCodeParent", content: "" });+ const { note: target } = createNote(parent.noteId, { title: "MdTarget", content: "<p>target</p>" });+ const { note: source } = createNote(parent.noteId, {+ title: "MdSource",+ type: "code",+ mime: "text/x-markdown",+ content: `See [the target](#root/${target.noteId}).`+ });++ const { entries } = await exportSubtree(parent.getParentBranches()[0], "html");+ const rootMeta = parseMeta(entries).files[0];+ const sourceMeta = (rootMeta.children ?? []).find((c) => c.noteId === source.noteId);+ const dataFile = entries[`${rootMeta.dirFileName}/${sourceMeta?.dataFileName}`].toString("utf-8");++ // A markdown code note stores Markdown, not HTML, so the HTML link rewriter can't reach it.+ expect(dataFile).toContain("[the target](MdTarget.html)");+ });++ it("refuses to export a subtree whose own root is marked #excludeFromExport", async () => {+ const { note } = createNote("root", { title: "ExcludedRoot", content: "<p>x</p>" });+ getContext().init(() => note.addLabel("excludeFromExport"));++ await expect(exportSubtree(note.getParentBranches()[0], "html")).rejects.toThrow("Unable to create root meta.");+ });});describe("exportToZipFile", () => {@@ -562,6 +685,21 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {)).rejects.toThrow(/not found/);});++ it("reports the error to the task context and rethrows when the export itself fails", async () => {+ const { note, branch } = createNote("root", { title: "BranchExportFails", content: "<p>x</p>" });+ getContext().init(() => note.addLabel("excludeFromExport"));+ const { branchId } = branch;+ if (!branchId) {+ throw new Error("branch was not saved");+ }++ await expect(+ getContext().init(() =>+ zip.exportBranchToZipFile(branchId, "html", join(tempDir, "failed.zip"), "no-progress-reporting")+ )+ ).rejects.toThrow("Unable to create root meta.");+ });});});diff --git a/packages/trilium-core/src/services/export/zip/html.spec.ts b/packages/trilium-core/src/services/export/zip/html.spec.tsindex f20500d5bd..7922af7086 100644--- a/packages/trilium-core/src/services/export/zip/html.spec.ts+++ b/packages/trilium-core/src/services/export/zip/html.spec.ts@@ -238,6 +238,46 @@ describe("HtmlExportProvider", () => {expect(appendCalls.map((c) => c.name).sort()).toEqual(["index.html", "navigation.html"]);});+ it("skips every extra file whose meta carries no data file name", () => {+ const { provider, appendCalls } = buildProvider({ options: { contentCss: "body {}" } });+ const metaFile = buildMetaFile();+ provider.prepareMeta(metaFile);+ // prepareMeta publishes the very meta objects the provider writes out later, so clearing+ // the (optional) file names leaves it with nothing to name the archive entries after.+ for (const file of metaFile.files) {+ file.dataFileName = undefined;+ }++ provider.afterDone(buildRootMeta());++ expect(appendCalls).toHaveLength(0);+ });++ it("does not pretty-print a very large navigation tree", () => {+ const { provider, appendCalls } = buildProvider();+ provider.prepareMeta(buildMetaFile());+ const rootMeta: NoteMeta = {+ noteId: "root",+ title: "Root",+ dataFileName: "Root.html",+ children: Array.from({ length: 2000 }, (_, i) => ({+ noteId: `note${i}`,+ title: `Note number ${i}`,+ dataFileName: `note${i}.html`,+ children: []+ }))+ };++ provider.afterDone(rootMeta);++ const navigation = appendCalls.find((c) => c.name === "navigation.html")?.content;+ expect(typeof navigation).toBe("string");+ expect(String(navigation).length).toBeGreaterThan(100_000);+ // Emitted verbatim past the threshold, so the list still sits on the template's own line+ // instead of being broken up one tag per line by the pretty printer.+ expect(String(navigation)).toContain("<ul><li>");+ });+it("throws when meta was never prepared", () => {const { provider } = buildProvider();