Skip to content

Build your personal knowledge base with Trilium Notes

fix(share): highlight included code notes, bounded by a size limit

Elian Doran309adf536cb0
diff --git a/apps/server/src/share/content_renderer.spec.ts b/apps/server/src/share/content_renderer.spec.ts
index c69af0e186..0426ab0dc3 100644
--- a/apps/server/src/share/content_renderer.spec.ts
+++ b/apps/server/src/share/content_renderer.spec.ts
@@ -2,7 +2,7 @@ import { trimIndentation } from "@triliumnext/commons";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { buildShareNote, buildShareNotes } from "../test/shaca_mocking.js";
-import { getContent, renderCode, type Result } from "./content_renderer.js";
+import { getContent, renderCode, type Result, shouldSyntaxHighlight } from "./content_renderer.js";
describe("content_renderer", () => {
beforeAll(() => {
@@ -59,6 +59,29 @@ describe("content_renderer", () => {
`);
});
+ it("renders an included large code note without hanging or re-parsing it as HTML (#9717)", () => {
+ // ~2 MiB of angle-bracket-heavy code that previously exploded node-html-parser.
+ const codeLine = `const x: Array<Map<string, List<number>>> = a < b && c > d; // <div>\n`;
+ const bigCode = codeLine.repeat(Math.ceil((2 * 1024 * 1024) / codeLine.length));
+ buildShareNote({ id: "bigcode", type: "code", mime: "application/javascript", content: bigCode });
+ const note = buildShareNote({
+ id: "host",
+ content: `<p>Before</p><section class="include-note" data-note-id="bigcode" data-box-size="medium">&nbsp;</section><p>After</p>`
+ });
+
+ const start = Date.now();
+ const result = getContent(note);
+ const elapsed = Date.now() - start;
+
+ expect(elapsed).toBeLessThan(2000);
+ if (typeof result.content !== "string") throw new Error("expected string content");
+ // The code is escaped, not re-parsed into markup, and not highlighted (over the limit).
+ expect(result.content).toContain("&lt;Map&lt;string");
+ expect(result.content).not.toContain("hljs");
+ expect(result.content).toContain("<p>Before</p>");
+ expect(result.content).toContain("<p>After</p>");
+ });
+
it("handles syntax highlight for code blocks with escaped syntax", () => {
const note = buildShareNote({
id: "note",
@@ -197,14 +220,14 @@ describe("content_renderer", () => {
expect(emptyResult.isEmpty).toBeTruthy();
});
- it("wraps code in <pre>", () => {
+ it("wraps code in <pre><code>", () => {
const result: Result = {
header: "",
content: "\tHello\nworld"
};
renderCode(result);
expect(result.isEmpty).toBeFalsy();
- expect(result.content).toBe("<pre>\tHello\nworld</pre>");
+ expect(result.content).toBe("<pre><code>\tHello\nworld</code></pre>");
});
it("escapes HTML-significant characters so the content cannot be re-parsed as markup", () => {
@@ -213,7 +236,19 @@ describe("content_renderer", () => {
content: `const x: Array<Map<string, number>> = a < b && c > d; // <div>`
};
renderCode(result);
- expect(result.content).toBe(`<pre>const x: Array&lt;Map&lt;string, number&gt;&gt; = a &lt; b &amp;&amp; c &gt; d; // &lt;div&gt;</pre>`);
+ expect(result.content).toBe(`<pre><code>const x: Array&lt;Map&lt;string, number&gt;&gt; = a &lt; b &amp;&amp; c &gt; d; // &lt;div&gt;</code></pre>`);
+ });
+ });
+
+ describe("shouldSyntaxHighlight", () => {
+ it("allows small code blocks", () => {
+ expect(shouldSyntaxHighlight("a\nb\nc")).toBe(true);
+ expect(shouldSyntaxHighlight("")).toBe(true);
+ });
+
+ it("rejects code blocks beyond the line limit", () => {
+ expect(shouldSyntaxHighlight(Array(500).fill("x").join("\n"))).toBe(true);
+ expect(shouldSyntaxHighlight(Array(501).fill("x").join("\n"))).toBe(false);
});
});
});
diff --git a/apps/server/src/share/content_renderer.ts b/apps/server/src/share/content_renderer.ts
index f684ceb4ce..fbffc150a1 100644
--- a/apps/server/src/share/content_renderer.ts
+++ b/apps/server/src/share/content_renderer.ts
@@ -22,6 +22,14 @@ import shareRoot from "./share_root.js";
const shareAdjustedAssetPath = isDev ? assetPath : `../${assetPath}`;
const templateCache: Map<string, string> = new Map();
+/**
+ * Maximum number of lines a code block may have before server-side syntax highlighting is skipped.
+ * Mirrors the editor's per-block cutoff (HIGHLIGHT_MAX_BLOCK_COUNT in the ckeditor5 syntax
+ * highlighting plugin); beyond it `highlightAuto` is too slow and would block the event loop on
+ * large shared/included code notes (#9717).
+ */
+const HIGHLIGHT_MAX_LINE_COUNT = 500;
+
/**
* Represents the output of the content renderer.
*/
@@ -419,6 +427,10 @@ function renderText(result: Result, note: SNote | BNote) {
continue;
}
+ if (!shouldSyntaxHighlight(codeEl.text)) {
+ continue;
+ }
+
const highlightResult = highlightAuto(codeEl.text);
codeEl.innerHTML = highlightResult.value;
codeEl.classList.add("hljs");
@@ -525,6 +537,10 @@ function renderMarkdown(result: Result, note: SNote | BNote) {
continue;
}
+ if (!shouldSyntaxHighlight(codeEl.text)) {
+ continue;
+ }
+
const highlightResult = highlightAuto(codeEl.text);
codeEl.innerHTML = highlightResult.value;
codeEl.classList.add("hljs");
@@ -533,6 +549,22 @@ function renderMarkdown(result: Result, note: SNote | BNote) {
result.content = document.innerHTML;
}
+/**
+ * Whether a code block is small enough to syntax-highlight server-side. Highlighting (especially
+ * `highlightAuto`, which probes every registered language) scales with content size and would block
+ * the single Node event loop on very large code, so blocks beyond {@link HIGHLIGHT_MAX_LINE_COUNT}
+ * lines are left unhighlighted.
+ */
+export function shouldSyntaxHighlight(code: string) {
+ let lineCount = 1;
+ for (let i = 0; i < code.length; i++) {
+ if (code.charCodeAt(i) === 10 /* \n */ && ++lineCount > HIGHLIGHT_MAX_LINE_COUNT) {
+ return false;
+ }
+ }
+ return true;
+}
+
/**
* Renders a code note.
*/
@@ -543,8 +575,10 @@ export function renderCode(result: Result) {
// Escape the raw code so that any `<`/`>` it contains are not later re-parsed as HTML.
// When such a code note is included into a shared text note, renderText re-parses the
// resulting HTML; with unescaped angle brackets (e.g. generics, comparisons, JSX) a large
- // code note explodes into a pathological node-html-parser tree and hangs the event loop.
- result.content = `<pre>${escapeHtml(result.content)}</pre>`;
+ // code note would explode into a pathological node-html-parser tree and hang the event
+ // loop (#9717). The <code> wrapper additionally lets renderText apply syntax highlighting,
+ // bounded by shouldSyntaxHighlight().
+ result.content = `<pre><code>${escapeHtml(result.content)}</code></pre>`;
}
}
diff --git a/apps/server/src/test/shaca_mocking.ts b/apps/server/src/test/shaca_mocking.ts
index 8b2068a0ec..d8d4b49ddd 100644
--- a/apps/server/src/test/shaca_mocking.ts
+++ b/apps/server/src/test/shaca_mocking.ts
@@ -17,6 +17,8 @@ interface AttachementDefinition {
interface NoteDefinition extends AttributeDefinitions, RelationDefinitions {
id?: string | undefined;
title?: string;
+ type?: string;
+ mime?: string;
content?: string | Buffer<ArrayBufferLike>;
children?: NoteDefinition[];
attachments?: AttachementDefinition[];
@@ -53,8 +55,8 @@ export function buildShareNote(noteDef: NoteDefinition) {
const note = new SNote([
noteDef.id ?? utils.randomString(12),
noteDef.title ?? "New note",
- "text",
- "text/html",
+ noteDef.type ?? "text",
+ noteDef.mime ?? "text/html",
blobId,
new Date().toUTCString(), // utcDateModified
!!noteDef.isProtected