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
chore(core): replace escape-html with a local escapeHtml
Elian Dorand4e2d8075967
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.jsonindex 4e7ee055e9..562cd17e0e 100644--- a/packages/trilium-core/package.json+++ b/packages/trilium-core/package.json@@ -24,7 +24,6 @@"chardet": "2.2.0","color": "5.0.3","ejs": "7.0.2",- "escape-html": "1.0.3","html-to-text": "10.0.1","i18next": "26.5.10","js-yaml": "5.5.0",@@ -43,7 +42,6 @@},"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.2",diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.tsindex 9f949f197b..c58136f18a 100644--- a/packages/trilium-core/src/services/export/markdown.spec.ts+++ b/packages/trilium-core/src/services/export/markdown.spec.ts@@ -127,7 +127,7 @@ describe("Markdown export", () => {// The fallback anchor is generated from the data attributes, so its href and title must be// HTML-escaped or a title like `A & B <x>` would break the exported markup. This escaping is- // done deterministically with escape-html, so it holds under both test environments.+ // done deterministically with `escapeHtml()`, so it holds under both test environments.expect(exported).toContain('<a href="https://e.com/?a=1&b=2">A & B <x></a>');// The section wrapper and its data attributes survive so the preview re-imports losslessly.diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.tsindex 10fb6af251..25dc61e7ca 100644--- a/packages/trilium-core/src/services/export/markdown.ts+++ b/packages/trilium-core/src/services/export/markdown.ts@@ -5,11 +5,11 @@ import {import { ADMONITION_TYPE_MAPPINGS } from "@triliumnext/commons/src/lib/markdown_renderer.js";import { HIGHLIGHT_BACKGROUND } from "@triliumnext/commons/src/lib/marked_extensions.js";import { gfm, serializeStructuralHtml } from "@triliumnext/turndown-plugin-gfm";-import escapeHtml from "escape-html";import { parse as parseHtml } from "node-html-parser";import Turnish, { type Rule } from "turnish";import { getTaskStates } from "../task_states.js";+import { escapeHtml } from "../utils/index.js";/** One converter per headerless-table mode, built lazily and reused across invocations. */const instances = new Map<HeaderlessTableMode, Turnish>();diff --git a/packages/trilium-core/src/services/utils/index.spec.ts b/packages/trilium-core/src/services/utils/index.spec.tsindex 24f168cca5..8136150340 100644--- a/packages/trilium-core/src/services/utils/index.spec.ts+++ b/packages/trilium-core/src/services/utils/index.spec.ts@@ -151,8 +151,12 @@ describe("#sanitizeSqlIdentifier", () => {});describe("#escapeHtml", () => {- it("should re-export 'escape-html' npm module as escapeHtml", () => {- expect(utils.escapeHtml).toBeTypeOf("function");+ it("escapes the five markup characters and leaves everything else alone", () => {+ expect(utils.escapeHtml(`<a href="x?a=1&b=2" title='t'>`))+ .toBe("<a href="x?a=1&b=2" title='t'>");+ expect(utils.escapeHtml("& is escaped again")).toBe("&amp; is escaped again");+ expect(utils.escapeHtml("plain text, ünïcödé")).toBe("plain text, ünïcödé");+ expect(utils.escapeHtml("")).toBe("");});});diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.tsindex 954456f9cf..ac7a786368 100644--- a/packages/trilium-core/src/services/utils/index.ts+++ b/packages/trilium-core/src/services/utils/index.ts@@ -6,7 +6,6 @@ import { getPlatform } from "../platform";import { sanitizeFileName } from "../sanitizer";import { encodeBase64 } from "./binary";import { extensions as mimeToExt, types as extToMime } from "mime-types";-import escape from "escape-html";import { basename, extname } from "./path";import { NoteMeta } from "../../meta";@@ -285,7 +284,14 @@ export function toMap<T extends Record<string, any>>(list: T[], key: keyof T) {return map;}-export const escapeHtml = escape;+const HTML_ESCAPES: Record<string, string> = {+ "&": "&", "<": "<", ">": ">", "\"": """, "'": "'"+};++/** Escapes `&`, `<`, `>`, `"` and `'`, so the result is safe in element content and quoted attributes. */+export function escapeHtml(str: string): string {+ return str.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char]);+}/*** Escapes `value` for use inside a double-quoted CSS string, one hex escape per character.diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex ceff22af00..f0c45d4e94 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -15,7 +15,6 @@ import {type NavigationItem, type PageHeading, type ShareNote} from "@triliumnext/share-theme/model/page";import ejs from "ejs";-import escapeHtml from "escape-html";import { t } from "i18next";import { HTMLElement, type Node as ParsedNode, Options, parse, TextNode } from "node-html-parser";@@ -414,7 +413,7 @@ export function preparePageContent(const heading = { level: Number(element.tagName.slice(1)), text, html, slug, href };element.setAttribute("id", slug);element.insertAdjacentHTML("beforeend", `<a class="toc-anchor" href="${href}"`- + ` aria-label="${escapeHtml(options.headingLinkLabel)}">`+ + ` aria-label="${utils.escapeHtml(options.headingLinkLabel)}">`+ `<span class="tn-icon bx bx-link" aria-hidden="true"></span></a>`);return heading;});@@ -600,7 +599,7 @@ function renderIndex(result: Result) {for (const childNote of rootNote.getChildNotes()) {const link = getShareLink(childNote, sanitize.sanitizeUrl);const target = link.isExternal ? ` target="_blank" rel="noopener noreferrer"` : "";- result.content += `<li><a class="${childNote.type}" href="${escapeHtml(link.href)}"${target}>`+ result.content += `<li><a class="${childNote.type}" href="${utils.escapeHtml(link.href)}"${target}>`+ `${childNote.escapedTitle}</a></li>`;}@@ -614,7 +613,7 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt};const document = parse(result.content || "", parseOpts);if (options.block !== undefined && !sliceToBlockReference(document, options.block)) {- const message = escapeHtml(t("content_renderer.broken-block-reference"));+ const message = utils.escapeHtml(t("content_renderer.broken-block-reference"));result.content = `<p class="block-reference-broken">${message}</p>`;return;}@@ -677,14 +676,14 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt// carrying `shareCredentials` the caller has not presented becomes a placeholder, and its// title is withheld too, since an embedded note need not appear in the visible share tree.if (options.canAccessEmbed && !options.canAccessEmbed(embeddedNote)) {- embedEl.replaceWith(...parse(`<p class="include-note-forbidden">${escapeHtml(t("content_renderer.included-note-requires-credentials"))}</p>`, parseOpts).childNodes);+ embedEl.replaceWith(...parse(`<p class="include-note-forbidden">${utils.escapeHtml(t("content_renderer.included-note-requires-credentials"))}</p>`, parseOpts).childNodes);continue;}// The link-processing passes below resolve the reference link to the shared note.if (embed.asLink) {- const href = escapeHtml(getNoteEmbedHref(embed.noteId, embed.block));- const title = escapeHtml(embeddedNote.title);+ const href = utils.escapeHtml(getNoteEmbedHref(embed.noteId, embed.block));+ const title = utils.escapeHtml(embeddedNote.title);const link = `<a class="reference-link" href="${href}">${title}</a>`;embedEl.replaceWith(...parse(link, parseOpts).childNodes);continue;@@ -769,13 +768,13 @@ function renderAttachmentEmbed(}const src = `api/attachments/${image.attachmentId}/image/${encodeURIComponent(image.title)}`;- return `<img src="${src}" alt="${escapeHtml(attachment.title)}">`;+ return `<img src="${src}" alt="${utils.escapeHtml(attachment.title)}">`;}/** The reference link to an attachment, which `handleAttachmentLink` then resolves. */function renderAttachmentLink(attachmentId: string, attachment: BAttachment | SAttachment) {- const href = escapeHtml(getAttachmentEmbedHref(attachment.ownerId, attachmentId));- return `<a class="reference-link" href="${href}">${escapeHtml(attachment.title)}</a>`;+ const href = utils.escapeHtml(getAttachmentEmbedHref(attachment.ownerId, attachmentId));+ return `<a class="reference-link" href="${href}">${utils.escapeHtml(attachment.title)}</a>`;}function handleAttachmentLink(linkEl: HTMLElement, href: string, getNote: GetNoteFunction, getAttachment: (id: string) => BAttachment | SAttachment | null) {@@ -841,7 +840,7 @@ function cleanUpReferenceLinks(linkEl: HTMLElement, href: string, getNote: GetNo} else if (note.isProtected) {linkEl.innerHTML = "[protected]";} else {- linkEl.innerHTML = `<span><span class="${escapeHtml(note.getIcon())}"></span>${utils.escapeHtml(note.title)}</span>`;+ linkEl.innerHTML = `<span><span class="${utils.escapeHtml(note.getIcon())}"></span>${utils.escapeHtml(note.title)}</span>`;}}@@ -992,9 +991,9 @@ export function renderCode(// loop (#9717). The <code> wrapper and its `language-*` class additionally let renderText// apply syntax highlighting, bounded by shouldSyntaxHighlight().const languageClass = mime- ? ` class="language-${escapeHtml(normalizeMimeTypeForCKEditor(mime))}"`+ ? ` class="language-${utils.escapeHtml(normalizeMimeTypeForCKEditor(mime))}"`: "";- result.content = `<pre><code${languageClass}>${escapeHtml(result.content)}</code></pre>`;+ result.content = `<pre><code${languageClass}>${utils.escapeHtml(result.content)}</code></pre>`;}}@@ -1020,7 +1019,7 @@ function renderMermaid(result: Result, note: SNote | BNote) {<hr><details><summary>Chart source</summary>- <pre class="mermaid-note-source">${escapeHtml(result.content)}</pre>+ <pre class="mermaid-note-source">${utils.escapeHtml(result.content)}</pre></details></div>`;}diff --git a/packages/trilium-core/src/share/shaca/entities/snote.ts b/packages/trilium-core/src/share/shaca/entities/snote.tsindex b3dba859ac..8b420ce2fd 100644--- a/packages/trilium-core/src/share/shaca/entities/snote.ts+++ b/packages/trilium-core/src/share/shaca/entities/snote.ts@@ -1,10 +1,9 @@import { BlobRow, getNoteIcon, NoteType } from "@triliumnext/commons";import { decodeUtf8 } from "../../../services/utils/binary.js";-import escape from "escape-html";import becca from "../../../becca/becca.js";-import { isStringNote } from "../../../services/utils/index.js";+import { escapeHtml, isStringNote } from "../../../services/utils/index.js";import sql from "../../sql.js";import AbstractShacaEntity from "./abstract_shaca_entity.js";import type { SNoteRow } from "./rows.js";@@ -491,7 +490,7 @@ class SNote extends AbstractShacaEntity {}get escapedTitle() {- return escape(this.title);+ return escapeHtml(this.title);}get encodedTitle() {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dcba7ccc68..7222c6c6af 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1486,9 +1486,6 @@ importers:ejs:specifier: 7.0.2version: 7.0.2- escape-html:- specifier: 1.0.3- version: 1.0.3html-to-text:specifier: 10.0.1version: 10.0.1@@ -1538,9 +1535,6 @@ importers:'@types/ejs':specifier: 3.1.5version: 3.1.5- '@types/escape-html':- specifier: 1.0.4- version: 1.0.4'@types/html-to-text':specifier: 9.0.4version: 9.0.4@@ -4836,9 +4830,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-AzxnvBzNh8K/0SmxMmZtpJf1/IWoGXLP+pQDuUaVkPyotI8ryvAtBSqgxR/qOSvxWHYWrxkeNsJ+Ca5xOuUxJQ==}- '@types/[email protected]':- resolution: {integrity: sha512-qZ72SFTgUAZ5a7Tj6kf2SHLetiH5S6f8G5frB2SPQ3EyF02kxdyBFf4Tz4banE3xCgGnKgWLt//a6VuYHKYJTg==}-'@types/[email protected]':resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==}@@ -15841,8 +15832,6 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]': {}-'@types/[email protected]': {}'@types/[email protected]': {}