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
Merge remote-tracking branch 'origin/main' into standalone
Elian Doran38385ac93617
diff --cc .github/workflows/dev.ymlindex 31121948b4,138fc39bc1..07e4cf819b--- a/.github/workflows/dev.yml+++ b/.github/workflows/dev.yml@@@ -1,9 -1,13 +1,15 @@@name: Devon:push:- branches: [ main, standalone ]+ branches:+ - main++ - standalone+ - "release/*"pull_request:- branches: [ main, standalone ]+ branches:+ - main++ - standalone+ - "release/*"concurrency:group: ${{ github.workflow }}-${{ github.ref }}diff --cc CLAUDE.mdindex 747564ec34,70d9757ae5..296e9ab627--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -158,15 -121,14 +158,16 @@@ SQLite via `better-sqlite3`. SQL abstra- **Only add new translation keys to `en/translation.json`** — translations for other languages are managed via Weblate and will be contributed by the community- Third-party components (e.g., mind-map context menu) should use i18next `t()` for their labels, with the English strings added to `en/translation.json` under a dedicated namespace (e.g., `"mind-map"`)- When a translated string contains **interpolated components** (e.g. links, note references) whose order may vary across languages, use `<Trans>` from `react-i18next` instead of `t()`. This lets translators reorder components freely (e.g. `"<Note/> in <Parent/>"` vs `"in <Parent/>, <Note/>"`)+ - When adding a new locale, follow the step-by-step guide in `docs/Developer Guide/Developer Guide/Concepts/Internationalisation Translations/Adding a new locale.md`-### Security Considerations-- Per-note encryption with granular protected sessions-- CSRF protection for API endpoints-- OpenID and TOTP authentication support-- Sanitization of user-generated content+Three inheritance mechanisms:+1. **Standard**: `note.getInheritableAttributes()` walks parent tree+2. **Child prefix**: `child:label` on parent copies to children+3. **Template relation**: `#template=noteNoteId` includes template's inheritable attributes++### Attribute Inheritance+Use `note.getOwnedAttribute()` for direct, `note.getAttribute()` for inherited.### Client-Side API Restrictions- **Do not use `crypto.randomUUID()`** or other Web Crypto APIs that require secure contexts - Trilium can run over HTTP, not just HTTPS- Use `randomString()` from `apps/client/src/services/utils.ts` for generating IDs insteaddiff --cc apps/build-docs/package.jsonindex 8b0996e20d,edfe201a6a..2b6abad8f3--- a/apps/build-docs/package.json+++ b/apps/build-docs/package.json@@@ -15,12 -15,8 +15,12 @@@"author": "Elian Doran <[email protected]>","license": "AGPL-3.0-only","packageManager": "[email protected]",+ "dependencies": {+ "@triliumnext/core": "workspace:*",+ "@triliumnext/server": "workspace:*"+ },"devDependencies": {- "@redocly/cli": "2.25.3",+ "@redocly/cli": "2.25.4","archiver": "7.0.1","fs-extra": "11.3.4","js-yaml": "4.1.1",diff --cc apps/client/src/services/doc_renderer.tsindex 279b554c1e,bb3bb996c2..86566dbf37--- a/apps/client/src/services/doc_renderer.ts+++ b/apps/client/src/services/doc_renderer.ts@@@ -48,20 -63,17 +63,27 @@@ async function processContent(url: striawait applyReferenceLinks($content[0]);}- function getUrl(docNameValue: string, language: string) {+ function getUrl(docNameValue: string | null, language: string) {+ if (!docNameValue) return;++ if (!isValidDocName(docNameValue)) {+ console.error(`Invalid docName: ${docNameValue}`);+ return null;+ }+// Cannot have spaces in the URL due to how JQuery.load works.docNameValue = docNameValue.replaceAll(" ", "%20");+ // The user guide is available only in English, so make sure we are requesting correctly since 404s in standalone client are treated differently.+ if (docNameValue.includes("User%20Guide")) language = "en";+ return `${getBasePath()}/doc_notes/${language}/${docNameValue}.html`;+}- const basePath = window.glob.isDev ? `${window.glob.assetPath }/..` : window.glob.assetPath;- return `${basePath}/doc_notes/${language}/${docNameValue}.html`;+function getBasePath() {+ if (window.glob.isStandalone) {+ return `server-assets`;+ }+ if (window.glob.isDev) {- return `${window.glob.assetPath }/..`;++ return `${window.glob.assetPath}/..`;+ }+ return window.glob.assetPath;}diff --cc apps/client/src/services/ws.tsindex ac7d605043,47ed90341b..0b3b7eb464--- a/apps/client/src/services/ws.ts+++ b/apps/client/src/services/ws.ts@@@ -57,45 -59,6 +59,43 @@@ export function unsubscribeToMessage(memessageHandlers = messageHandlers.filter(handler => handler !== messageHandler);}+/**+ * Dispatch a message to all handlers and process it.+ * This is the main entry point for incoming messages from any provider+ * (WebSocket, Worker, etc.)+ */+export async function dispatchMessage(message: WebSocketMessage) {+ // Notify all subscribers+ for (const messageHandler of messageHandlers) {+ messageHandler(message);+ }++ // Use string type for flexibility - server sends more message types than are typed+ const messageType = message.type as string;+ const msg = message as any;++ // Process the message+ if (messageType === "ping") {+ lastPingTs = Date.now();+ } else if (messageType === "reload-frontend") {+ utils.reloadFrontendApp("received request from backend to reload frontend");+ } else if (messageType === "frontend-update") {+ await executeFrontendUpdate(msg.data.entityChanges);+ } else if (messageType === "sync-hash-check-failed") {+ toastService.showError(t("ws.sync-check-failed"), 60000);+ } else if (messageType === "consistency-checks-failed") {+ toastService.showError(t("ws.consistency-checks-failed"), 50 * 60000);+ } else if (messageType === "api-log-messages") {+ appContext.triggerEvent("apiLogMessages", { noteId: msg.noteId, messages: msg.messages });+ } else if (messageType === "toast") {+ toastService.showMessage(msg.message);+ } else if (messageType === "execute-script") {- const bundleService = (await import("./bundle.js")).default;- const froca = (await import("./froca.js")).default;+ const originEntity = msg.originEntityId ? await froca.getNote(msg.originEntityId) : null;++ bundleService.getAndExecuteBundle(msg.currentNoteId, originEntity, msg.script, msg.params);+ }+}+// used to serialize frontend update operationslet consumeQueuePromise: Promise<void> | null = null;diff --cc apps/client/src/translations/en/translation.jsonindex 177658c6ac,9605212f6e..8b710a1435--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@@ -2304,59 -2307,10 +2307,61 @@@"sample_user_journey": "User Journey","sample_xy": "XY","sample_venn": "Venn",- "sample_ishikawa": "Ishikawa"+ "sample_ishikawa": "Ishikawa",+ "sample_treeview": "TreeView",+ "sample_wardley": "Wardley Map"},+ "setup": {+ "heading": "Get started with Trilium",+ "new-document": "New knowledge base",+ "new-document-description": "Start with a clean knowledge base and begin right away.",+ "sync-from-desktop": "Connect a desktop app",+ "sync-from-desktop-description": "You only have a Trilium desktop app running on another device. This device will sync its data from that desktop app.",+ "sync-from-server": "Connect to an existing server",+ "sync-from-server-description": "You have a Trilium server running elsewhere (either self-hosted or in the cloud). This device will sync its data from that server.",+ "next": "Next",+ "init-in-progress": "Document initialization in progress",+ "redirecting": "You will be shortly redirected to the application.",+ "title": "Setup",+ "sync-from-server-page-description": "Enter your server details below to connect your existing workspace.",+ "sync-in-progress-title": "Sync in progress",+ "sync-in-progress-description": "Your device is now connected and items are being synchronized.",+ "button-back": "Back",+ "button-finish-setup": "Finish setup",+ "sync-step-connecting": "Connecting to server",+ "sync-step-syncing": "Syncing data",+ "sync-step-finalizing": "Setting up options",+ "create-new-document-options-title": "How would you like to start?",+ "create-new-document-options-with-demo": "With demo content",+ "create-new-document-options-with-demo-description": "Explore Trilium with example content.",+ "create-new-document-options-empty": "Empty",+ "create-new-document-options-empty-description": "Start with a blank knowledge base. You can import demo notes later.",+ "create-new-document-title": "Preparing your knowledge base",+ "create-new-document-description": "This will only take a moment.",+ "sync-illustration-this-device": "This device",+ "sync-illustration-desktop-app": "Your desktop app",+ "sync-illustration-server": "Your server",+ "sync-from-desktop-step1": "Open your desktop instance of Trilium Notes.",+ "sync-from-desktop-step2": "From the Trilium Menu, click Options.",+ "sync-from-desktop-step3": "Click on Sync category in the note tree.",+ "sync-from-desktop-step4": "Change server instance address to point to one of the addresses on the right and click Save.",+ "sync-from-desktop-step5": "Click the \"Test sync\" button to verify connection is successful.",+ "sync-from-desktop-warning": "Make sure both devices are on the same network.",+ "sync-from-desktop-waiting": "Waiting for connection...",+ "advanced-options": "Advanced options",+ "sync-failed": "Failed to sync: {{message}}",+ "server-host": "Trilium server address",+ "server-host-placeholder": "https://<hostname>:<port>",+ "server-password": "Password",+ "proxy-server": "Proxy server (optional)",+ "proxy-server-placeholder": "https://<hostname>:<port>",+ "proxy-instruction": "If you leave proxy setting blank, system proxy will be used.",+ "dismiss-error": "Dismiss error",+ "wrong-password": "Incorrect password. Please try again.",+ "language": "Language",+ "continue": "Continue",+ "your-ip-addresses": "Addresses for this device"+ },"mind-map": {"addChild": "Add child","addParent": "Add parent",diff --cc apps/desktop/package.jsonindex 233ca25108,9e58f88057..0ef67c9106--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@@ -46,6 -38,13 +38,14 @@@"@electron-forge/maker-squirrel": "7.11.1","@electron-forge/maker-zip": "7.11.1","@electron-forge/plugin-auto-unpack-natives": "7.11.1",+ "@electron-forge/plugin-fuses": "7.11.1",+ "@electron/fuses": "2.1.1",+ "@triliumnext/commons": "workspace:*",++ "@triliumnext/core": "workspace:*",+ "@triliumnext/server": "workspace:*",+ "@types/electron-squirrel-startup": "1.0.2",+ "copy-webpack-plugin": "14.0.0",+ "electron": "41.1.1","prebuild-install": "7.1.3"}}diff --cc apps/server/package.jsonindex 94850bedde,2f233ddebd..f99ca9b9b8--- a/apps/server/package.json+++ b/apps/server/package.json@@@ -73,9 -77,9 +73,7 @@@"@types/ws": "8.18.1","@types/xml2js": "0.4.14","archiver": "7.0.1",- "async-mutex": "0.5.0","axios": "1.14.0",- "bindings": "1.5.0",- "bootstrap": "5.3.8",- "chardet": "2.1.1","cheerio": "1.2.0","chokidar": "5.0.0","cls-hooked": "4.2.2",@@@ -85,9 -89,9 +83,8 @@@"debounce": "3.0.0","debug": "4.4.3","ejs": "5.0.1",- "electron": "41.1.0",- "electron-debug": "4.1.0",+ "electron": "41.1.1","electron-window-state": "5.0.3",- "escape-html": "1.0.3","express": "5.2.1","express-http-proxy": "2.1.2","express-openid-connect": "2.20.1",@@@ -98,26 -102,30 +95,24 @@@"helmet": "8.1.0","html": "1.0.0","html2plaintext": "2.1.4",- "http-proxy-agent": "8.0.0",- "https-proxy-agent": "8.0.0",+ "http-proxy-agent": "9.0.0",+ "https-proxy-agent": "9.0.0",- "i18next": "26.0.3",- "i18next-fs-backend": "2.6.3","image-type": "6.1.0","ini": "6.0.0","is-animated": "2.0.2","is-svg": "6.1.0","jimp": "1.6.0",- "lorem-ipsum": "2.0.8","marked": "17.0.5",- "mime-types": "3.0.2","multer": "2.1.1","normalize-strings": "1.1.1","officeparser": "6.0.7","rand-token": "1.0.1","safe-compare": "1.1.4",- "sanitize-filename": "1.6.4",- "sanitize-html": "2.17.2","sax": "1.6.0","serve-favicon": "2.5.1",- "stream-throttle": "0.1.3",- "strip-bom": "5.0.0",+ "stream-throttle": "0.1.3","striptags": "3.2.0","supertest": "7.2.2",- "swagger-jsdoc": "6.2.8","tesseract.js": "7.0.0","time2fa": "1.4.2","tmp": "0.2.5",diff --cc apps/server/src/share/routes.tsindex 69489c5522,5b33103501..25a1383f3f--- a/apps/server/src/share/routes.ts+++ b/apps/server/src/share/routes.ts@@@ -1,15 -1,14 +1,14 @@@- import safeCompare from "safe-compare";-++import { utils } from "@triliumnext/core";import type { NextFunction, Request, Response, Router } from "express";+ import safeCompare from "safe-compare";- import shaca from "./shaca/shaca.js";- import shacaLoader from "./shaca/shaca_loader.js";- import searchService from "../services/search/services/search.js";import SearchContext from "../services/search/search_context.js";- import type SNote from "./shaca/entities/snote.js";- import type SAttachment from "./shaca/entities/sattachment.js";+ import searchService from "../services/search/services/search.js";-import utils, { sanitizeSvg } from "../services/utils.js";import { getDefaultTemplatePath, renderNoteContent } from "./content_renderer.js";- import utils from "../services/utils.js";+ import type SAttachment from "./shaca/entities/sattachment.js";+ import type SNote from "./shaca/entities/snote.js";+ import shaca from "./shaca/shaca.js";+ import shacaLoader from "./shaca/shaca_loader.js";import { isShareDbReady } from "./sql.js";function assertShareDbReady(_req: Request, res: Response, next: NextFunction) {@@@ -112,9 -111,10 +111,10 @@@ function renderImageAttachment(image: S}}- const svg = svgString;- const svg = sanitizeSvg(svgString);++ const svg = utils.sanitizeSvg(svgString);res.set("Content-Type", "image/svg+xml");res.set("Cache-Control", "no-cache, no-store, must-revalidate");+ res.set("Content-Security-Policy", "script-src 'none'");res.send(svg);}diff --cc packages/trilium-core/src/routes/api/image.tsindex 2b4e0130b0,746bad288f..71c96c7ed8--- a/packages/trilium-core/src/routes/api/image.ts+++ b/packages/trilium-core/src/routes/api/image.ts@@@ -4,6 -5,8 +4,8 @@@ import becca from "../../becca/becca.jsimport type BNote from "../../becca/entities/bnote.js";import type BRevision from "../../becca/entities/brevision.js";import imageService from "../../services/image.js";-import { RESOURCE_DIR } from "../../services/resource_dir.js";-import { sanitizeSvg } from "../../services/utils.js";++import { sanitizeSvg } from "../../services/utils/index.js";++import { unwrapStringOrBuffer } from "../../services/utils/binary.js";function returnImageFromNote(req: Request<{ noteId: string }>, res: Response) {const image = becca.getNote(req.params.noteId);@@@ -42,7 -49,7 +49,7 @@@ function returnImageInt(image: BNote |}export function renderSvgAttachment(image: BNote | BRevision, res: Response, attachmentName: string) {- let svg: string | Uint8Array = `<svg xmlns="http://www.w3.org/2000/svg"></svg>`;- let svgContent: string | Buffer = `<svg xmlns="http://www.w3.org/2000/svg"></svg>`;++ let svgContent: string | Uint8Array = `<svg xmlns="http://www.w3.org/2000/svg"></svg>`;const attachment = image.getAttachmentByTitle(attachmentName);if (attachment) {@@@ -129,3 -140,9 +141,9 @@@ export defaultreturnAttachedImage,updateImage};+-function sendSanitizedSvg(res: Response, content: string | Buffer) {- const svgString = typeof content === "string" ? content : content.toString("utf-8");++function sendSanitizedSvg(res: Response, content: string | Uint8Array) {++ const svgString = unwrapStringOrBuffer(content);+ res.set("Content-Security-Policy", "script-src 'none'");+ res.send(sanitizeSvg(svgString));+ }diff --cc packages/trilium-core/src/routes/api/options.tsindex 8ec1cf6a12,9e21dcb7b7..42e7d50f2a--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@@ -3,12 -3,12 +3,12 @@@import type { OptionNames } from "@triliumnext/commons";import type { Request } from "express";-import ValidationError from "../../errors/validation_error.js";import config from "../../services/config.js";- import { changeLanguage, getLocales } from "../../services/i18n.js";+ import { changeLanguage } from "../../services/i18n.js";-import log from "../../services/log.js";+import { getLog } from "../../services/log.js";import optionService from "../../services/options.js";import searchService from "../../services/search/services/search.js";+import { ValidationError } from "../../errors.js";interface UserTheme {val: string; // value of the theme, used in the URLdiff --cc packages/trilium-core/src/routes/index.tsindex aaf779cd88,0000000000..2c42f3d1cdmode 100644,000000..100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@@ -1,259 -1,0 +1,258 @@@+import optionsApiRoute from "./api/options";+import treeApiRoute from "./api/tree";+import keysApiRoute from "./api/keys";+import notesApiRoute from "./api/notes";+import attachmentsApiRoute from "./api/attachments";+import noteMapRoute from "./api/note_map";+import recentNotesRoute from "./api/recent_notes";+import otherRoute from "./api/others";+import branchesApiRoute from "./api/branches";+import appInfoRoute from "./api/app_info";+import statsRoute from "./api/stats";+import AbstractBeccaEntity from "../becca/entities/abstract_becca_entity";+import cloningApiRoute from "./api/cloning";+import sqlRoute from "./api/sql";+import attributesRoute from "./api/attributes";+import revisionsApiRoute from "./api/revisions";+import relationMapApiRoute from "./api/relation-map";+import recentChangesApiRoute from "./api/recent_changes";+import bulkActionRoute from "./api/bulk_action";+import searchRoute from "./api/search";+import specialNotesRoute from "./api/special_notes";+import syncApiRoute from "./api/sync";+import autocompleteApiRoute from "./api/autocomplete";+import similarNotesRoute from "./api/similar_notes";+import imageRoute from "./api/image";+import setupApiRoute from "./api/setup";+import filesRoute from "./api/files";+import importRoute from "./api/import";+import exportRoute from "./api/export";+import scriptRoute from "./api/script";++// TODO: Deduplicate with routes.ts+const GET = "get",+ PST = "post",+ PUT = "put",+ PATCH = "patch",+ DEL = "delete";++interface SharedApiRoutesContext {+ route: any;+ asyncRoute: any;+ apiRoute: any;+ asyncApiRoute: any;+ checkApiAuth: any;+ apiResultHandler: any;+ checkApiAuthOrElectron: any;+ checkAppNotInitialized: any;+ loginRateLimiter: any;+ checkCredentials: any;+ uploadMiddlewareWithErrorHandling: any;+ csrfMiddleware: any;+}++export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoute, checkApiAuth, apiResultHandler, checkApiAuthOrElectron, checkAppNotInitialized, checkCredentials, loginRateLimiter, uploadMiddlewareWithErrorHandling, csrfMiddleware }: SharedApiRoutesContext) {+ apiRoute(GET, '/api/tree', treeApiRoute.getTree);+ apiRoute(PST, '/api/tree/load', treeApiRoute.load);++ apiRoute(GET, "/api/options", optionsApiRoute.getOptions);+ // FIXME: possibly change to sending value in the body to avoid host of HTTP server issues with slashes+ apiRoute(PUT, "/api/options/:name/:value", optionsApiRoute.updateOption);+ apiRoute(PUT, "/api/options", optionsApiRoute.updateOptions);+ apiRoute(GET, "/api/options/user-themes", optionsApiRoute.getUserThemes);- apiRoute(GET, "/api/options/locales", optionsApiRoute.getSupportedLocales);++ apiRoute(PST, "/api/notes/:noteId/convert-to-attachment", notesApiRoute.convertNoteToAttachment);+ apiRoute(GET, "/api/notes/:noteId", notesApiRoute.getNote);+ apiRoute(GET, "/api/notes/:noteId/blob", notesApiRoute.getNoteBlob);+ apiRoute(GET, "/api/notes/:noteId/metadata", notesApiRoute.getNoteMetadata);+ apiRoute(PUT, "/api/notes/:noteId/data", notesApiRoute.updateNoteData);+ apiRoute(DEL, "/api/notes/:noteId", notesApiRoute.deleteNote);+ apiRoute(PUT, "/api/notes/:noteId/undelete", notesApiRoute.undeleteNote);+ apiRoute(PST, "/api/notes/:noteId/revision", notesApiRoute.forceSaveRevision);+ apiRoute(PST, "/api/notes/:parentNoteId/children", notesApiRoute.createNote);+ apiRoute(PUT, "/api/notes/:noteId/sort-children", notesApiRoute.sortChildNotes);+ apiRoute(PUT, "/api/notes/:noteId/protect/:isProtected", notesApiRoute.protectNote);+ apiRoute(PUT, "/api/notes/:noteId/type", notesApiRoute.setNoteTypeMime);+ apiRoute(PUT, "/api/notes/:noteId/title", notesApiRoute.changeTitle);+ apiRoute(PST, "/api/notes/:noteId/duplicate/:parentNoteId", notesApiRoute.duplicateSubtree);+ apiRoute(PST, "/api/notes/erase-deleted-notes-now", notesApiRoute.eraseDeletedNotesNow);+ apiRoute(PST, "/api/notes/erase-unused-attachments-now", notesApiRoute.eraseUnusedAttachmentsNow);+ apiRoute(PST, "/api/delete-notes-preview", notesApiRoute.getDeleteNotesPreview);++ apiRoute(GET, "/api/notes/:noteId/attachments", attachmentsApiRoute.getAttachments);+ apiRoute(PST, "/api/notes/:noteId/attachments", attachmentsApiRoute.saveAttachment);+ apiRoute(GET, "/api/attachments/:attachmentId", attachmentsApiRoute.getAttachment);+ apiRoute(GET, "/api/attachments/:attachmentId/all", attachmentsApiRoute.getAllAttachments);+ apiRoute(PST, "/api/attachments/:attachmentId/convert-to-note", attachmentsApiRoute.convertAttachmentToNote);+ apiRoute(DEL, "/api/attachments/:attachmentId", attachmentsApiRoute.deleteAttachment);+ apiRoute(PUT, "/api/attachments/:attachmentId/rename", attachmentsApiRoute.renameAttachment);+ apiRoute(GET, "/api/attachments/:attachmentId/blob", attachmentsApiRoute.getAttachmentBlob);++ apiRoute(GET, "/api/notes/:noteId/attributes", attributesRoute.getEffectiveNoteAttributes);+ apiRoute(PST, "/api/notes/:noteId/attributes", attributesRoute.addNoteAttribute);+ apiRoute(PUT, "/api/notes/:noteId/attributes", attributesRoute.updateNoteAttributes);+ apiRoute(PUT, "/api/notes/:noteId/attribute", attributesRoute.updateNoteAttribute);+ apiRoute(PUT, "/api/notes/:noteId/set-attribute", attributesRoute.setNoteAttribute);+ apiRoute(PUT, "/api/notes/:noteId/relations/:name/to/:targetNoteId", attributesRoute.createRelation);+ apiRoute(DEL, "/api/notes/:noteId/relations/:name/to/:targetNoteId", attributesRoute.deleteRelation);+ apiRoute(DEL, "/api/notes/:noteId/attributes/:attributeId", attributesRoute.deleteNoteAttribute);+ apiRoute(GET, "/api/attribute-names/", attributesRoute.getAttributeNames);+ apiRoute(GET, "/api/attribute-values/:attributeName", attributesRoute.getValuesForAttribute);++ apiRoute(GET, "/api/notes/:noteId/revisions", revisionsApiRoute.getRevisions);+ apiRoute(DEL, "/api/notes/:noteId/revisions", revisionsApiRoute.eraseAllRevisions);+ apiRoute(PST, "/api/revisions/erase-all-excess-revisions", revisionsApiRoute.eraseAllExcessRevisions);+ apiRoute(GET, "/api/revisions/:revisionId", revisionsApiRoute.getRevision);+ apiRoute(GET, "/api/revisions/:revisionId/blob", revisionsApiRoute.getRevisionBlob);+ apiRoute(DEL, "/api/revisions/:revisionId", revisionsApiRoute.eraseRevision);+ apiRoute(PST, "/api/revisions/:revisionId/restore", revisionsApiRoute.restoreRevision);+ apiRoute(GET, "/api/edited-notes/:date", revisionsApiRoute.getEditedNotesOnDate);++ apiRoute(PUT, "/api/branches/:branchId/move-to/:parentBranchId", branchesApiRoute.moveBranchToParent);+ apiRoute(PUT, "/api/branches/:branchId/move-before/:beforeBranchId", branchesApiRoute.moveBranchBeforeNote);+ apiRoute(PUT, "/api/branches/:branchId/move-after/:afterBranchId", branchesApiRoute.moveBranchAfterNote);+ apiRoute(PUT, "/api/branches/:branchId/expanded/:expanded", branchesApiRoute.setExpanded);+ apiRoute(PUT, "/api/branches/:branchId/expanded-subtree/:expanded", branchesApiRoute.setExpandedForSubtree);+ apiRoute(DEL, "/api/branches/:branchId", branchesApiRoute.deleteBranch);+ apiRoute(PUT, "/api/branches/:branchId/set-prefix", branchesApiRoute.setPrefix);+ apiRoute(PUT, "/api/branches/set-prefix-batch", branchesApiRoute.setPrefixBatch);++ // :filename is not used by trilium, but instead used for "save as" to assign a human-readable filename+ route(GET, "/api/revisions/:revisionId/image/:filename", [checkApiAuthOrElectron], imageRoute.returnImageFromRevision);+ route(GET, "/api/attachments/:attachmentId/image/:filename", [checkApiAuthOrElectron], imageRoute.returnAttachedImage);+ route(GET, "/api/images/:noteId/:filename", [checkApiAuthOrElectron], imageRoute.returnImageFromNote);++ // group of the services below are meant to be executed from the outside+ route(GET, "/api/setup/status", [], setupApiRoute.getStatus, apiResultHandler);+ asyncRoute(PST, "/api/setup/new-document", [checkAppNotInitialized], setupApiRoute.setupNewDocument, apiResultHandler);+ asyncRoute(PST, "/api/setup/sync-from-server", [checkAppNotInitialized], setupApiRoute.setupSyncFromServer, apiResultHandler);+ route(GET, "/api/setup/sync-seed", [loginRateLimiter, checkCredentials], setupApiRoute.getSyncSeed, apiResultHandler);+ asyncRoute(PST, "/api/setup/sync-seed", [checkAppNotInitialized], setupApiRoute.saveSyncSeed, apiResultHandler);++ asyncApiRoute(PST, "/api/sync/test", syncApiRoute.testSync);+ asyncApiRoute(PST, "/api/sync/now", syncApiRoute.syncNow);+ apiRoute(PST, "/api/sync/fill-entity-changes", syncApiRoute.fillEntityChanges);+ apiRoute(PST, "/api/sync/force-full-sync", syncApiRoute.forceFullSync);+ route(GET, "/api/sync/check", [checkApiAuth], syncApiRoute.checkSync, apiResultHandler);+ route(GET, "/api/sync/changed", [checkApiAuth], syncApiRoute.getChanged, apiResultHandler);+ route(PUT, "/api/sync/update", [checkApiAuth], syncApiRoute.update, apiResultHandler);+ route(PST, "/api/sync/finished", [checkApiAuth], syncApiRoute.syncFinished, apiResultHandler);+ route(PST, "/api/sync/check-entity-changes", [checkApiAuth], syncApiRoute.checkEntityChanges, apiResultHandler);+ route(PST, "/api/sync/queue-sector/:entityName/:sector", [checkApiAuth], syncApiRoute.queueSector, apiResultHandler);+ route(GET, "/api/sync/stats", [], syncApiRoute.getStats, apiResultHandler);++ //#region Import/export+ asyncRoute(PST, "/api/notes/:parentNoteId/notes-import", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importNotesToBranch, apiResultHandler);+ route(PST, "/api/notes/:parentNoteId/attachments-import", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importAttachmentsToNote, apiResultHandler);+ asyncRoute(GET, "/api/branches/:branchId/export/:type/:format/:version/:taskId", [checkApiAuthOrElectron], exportRoute.exportBranch);+ //#endregion++ apiRoute(GET, "/api/quick-search/:searchString", searchRoute.quickSearch);+ apiRoute(GET, "/api/search-note/:noteId", searchRoute.searchFromNote);+ apiRoute(PST, "/api/search-and-execute-note/:noteId", searchRoute.searchAndExecute);+ apiRoute(PST, "/api/search-related", searchRoute.getRelatedNotes);+ apiRoute(GET, "/api/search/:searchString", searchRoute.search);+ apiRoute(GET, "/api/search-templates", searchRoute.searchTemplates);++ apiRoute(GET, "/api/autocomplete", autocompleteApiRoute.getAutocomplete);+ apiRoute(GET, "/api/autocomplete/notesCount", autocompleteApiRoute.getNotesCount);++ apiRoute(PUT, "/api/notes/:noteId/clone-to-branch/:parentBranchId", cloningApiRoute.cloneNoteToBranch);+ apiRoute(PUT, "/api/notes/:noteId/toggle-in-parent/:parentNoteId/:present", cloningApiRoute.toggleNoteInParent);+ apiRoute(PUT, "/api/notes/:noteId/clone-to-note/:parentNoteId", cloningApiRoute.cloneNoteToParentNote);+ apiRoute(PUT, "/api/notes/:noteId/clone-after/:afterBranchId", cloningApiRoute.cloneNoteAfter);++ asyncApiRoute(GET, "/api/special-notes/inbox/:date", specialNotesRoute.getInboxNote);+ asyncApiRoute(GET, "/api/special-notes/days/:date", specialNotesRoute.getDayNote);+ asyncApiRoute(GET, "/api/special-notes/week-first-day/:date", specialNotesRoute.getWeekFirstDayNote);+ asyncApiRoute(GET, "/api/special-notes/weeks/:week", specialNotesRoute.getWeekNote);+ asyncApiRoute(GET, "/api/special-notes/months/:month", specialNotesRoute.getMonthNote);+ asyncApiRoute(GET, "/api/special-notes/quarters/:quarter", specialNotesRoute.getQuarterNote);+ apiRoute(GET, "/api/special-notes/years/:year", specialNotesRoute.getYearNote);+ apiRoute(GET, "/api/special-notes/notes-for-month/:month", specialNotesRoute.getDayNotesForMonth);+ apiRoute(PST, "/api/special-notes/sql-console", specialNotesRoute.createSqlConsole);+ asyncApiRoute(PST, "/api/special-notes/save-sql-console", specialNotesRoute.saveSqlConsole);+ apiRoute(PST, "/api/special-notes/search-note", specialNotesRoute.createSearchNote);+ apiRoute(PST, "/api/special-notes/save-search-note", specialNotesRoute.saveSearchNote);+ apiRoute(PST, "/api/special-notes/launchers/:noteId/reset", specialNotesRoute.resetLauncher);+ apiRoute(PST, "/api/special-notes/launchers/:parentNoteId/:launcherType", specialNotesRoute.createLauncher);+ apiRoute(PUT, "/api/special-notes/api-script-launcher", specialNotesRoute.createOrUpdateScriptLauncherFromApi);++ apiRoute(PST, "/api/note-map/:noteId/tree", noteMapRoute.getTreeMap);+ apiRoute(PST, "/api/note-map/:noteId/link", noteMapRoute.getLinkMap);+ apiRoute(GET, "/api/note-map/:noteId/backlinks", noteMapRoute.getBacklinks);+ apiRoute(GET, "/api/note-map/:noteId/backlink-count", noteMapRoute.getBacklinkCount);++ apiRoute(PST, "/api/recent-notes", recentNotesRoute.addRecentNote);++ apiRoute(GET, "/api/keyboard-actions", keysApiRoute.getKeyboardActions);+ apiRoute(GET, "/api/keyboard-shortcuts-for-notes", keysApiRoute.getShortcutsForNotes);++ apiRoute(GET, "/api/stats/note-size/:noteId", statsRoute.getNoteSize);+ apiRoute(GET, "/api/stats/subtree-size/:noteId", statsRoute.getSubtreeSize);++ apiRoute(GET, "/api/sql/schema", sqlRoute.getSchema);+ apiRoute(PST, "/api/sql/execute/:noteId", sqlRoute.execute);++ apiRoute(PST, "/api/bulk-action/execute", bulkActionRoute.execute);+ apiRoute(PST, "/api/bulk-action/affected-notes", bulkActionRoute.getAffectedNoteCount);++ apiRoute(GET, "/api/app-info", appInfoRoute.getAppInfo);++ apiRoute(GET, "/api/other/icon-usage", otherRoute.getIconUsage);+ apiRoute(PST, "/api/other/render-markdown", otherRoute.renderMarkdown);+ apiRoute(PST, "/api/other/to-markdown", otherRoute.toMarkdown);++ asyncApiRoute(GET, "/api/similar-notes/:noteId", similarNotesRoute.getSimilarNotes);+ apiRoute(PST, "/api/relation-map", relationMapApiRoute.getRelationMap);+ apiRoute(GET, "/api/recent-changes/:ancestorNoteId", recentChangesApiRoute.getRecentChanges);++ //#region Files+ route(GET, "/api/notes/:noteId/open", [checkApiAuthOrElectron], filesRoute.openFile);+ route(GET, "/api/notes/:noteId/download", [checkApiAuthOrElectron], filesRoute.downloadFile);+ // this "hacky" path is used for easier referencing of CSS resources+ route(GET, "/api/notes/download/:noteId", [checkApiAuthOrElectron], filesRoute.downloadFile);+ route(GET, "/api/attachments/:attachmentId/open", [checkApiAuthOrElectron], filesRoute.openAttachment);+ route(GET, "/api/attachments/:attachmentId/download", [checkApiAuthOrElectron], filesRoute.downloadAttachment);+ // this "hacky" path is used for easier referencing of CSS resources+ route(GET, "/api/attachments/download/:attachmentId", [checkApiAuthOrElectron], filesRoute.downloadAttachment);+ //#endregion++ //#region Export+ asyncRoute(PST, "/api/script/exec", [checkApiAuth, csrfMiddleware], scriptRoute.exec, apiResultHandler);++ apiRoute(PST, "/api/script/run/:noteId", scriptRoute.run);+ apiRoute(GET, "/api/script/startup", scriptRoute.getStartupBundles);+ apiRoute(GET, "/api/script/widgets", scriptRoute.getWidgetBundles);+ apiRoute(PST, "/api/script/bundle/:noteId", scriptRoute.getBundle);+ apiRoute(GET, "/api/script/relation/:noteId/:relationName", scriptRoute.getRelationBundles);+ //#endregion+}++/** Handling common patterns. If entity is not caught, serialization to JSON will fail */+export function convertEntitiesToPojo(result: unknown) {+ if (result instanceof AbstractBeccaEntity) {+ result = result.getPojo();+ } else if (Array.isArray(result)) {+ for (const idx in result) {+ if (result[idx] instanceof AbstractBeccaEntity) {+ result[idx] = result[idx].getPojo();+ }+ }+ } else if (result && typeof result === "object") {+ if ("note" in result && result.note instanceof AbstractBeccaEntity) {+ result.note = result.note.getPojo();+ }++ if ("branch" in result && result.branch instanceof AbstractBeccaEntity) {+ result.branch = result.branch.getPojo();+ }+ }++ if (result && typeof result === "object" && "executionResult" in result) {+ // from runOnBackend()+ result.executionResult = convertEntitiesToPojo(result.executionResult);+ }++ return result;+}diff --cc packages/trilium-core/src/services/app_info.tsindex 891649a181,0000000000..ba78f55b31mode 100644,000000..100644--- a/packages/trilium-core/src/services/app_info.ts+++ b/packages/trilium-core/src/services/app_info.ts@@@ -1,19 -1,0 +1,19 @@@+import build from "./build.js";+import packageJson from "../../package.json" with { type: "json" };+import { AppInfo } from "@triliumnext/commons";++const APP_DB_VERSION = 236;- const SYNC_VERSION = 37;++const SYNC_VERSION = 38;+const CLIPPER_PROTOCOL_VERSION = "1.0";++const appInfo: AppInfo = {+ appVersion: packageJson.version,+ dbVersion: APP_DB_VERSION,+ syncVersion: SYNC_VERSION,+ buildDate: build.buildDate,+ buildRevision: build.buildRevision,+ clipperProtocolVersion: CLIPPER_PROTOCOL_VERSION,+ utcDateTime: new Date().toISOString()+}++export default appInfo;diff --cc packages/trilium-core/src/services/i18n.tsindex e8566af171,0000000000..1cc7e8f7cdmode 100644,000000..100644--- a/packages/trilium-core/src/services/i18n.ts+++ b/packages/trilium-core/src/services/i18n.ts@@@ -1,54 -1,0 +1,50 @@@+import { dayjs, Dayjs, Locale, LOCALE_IDS, LOCALES, setDayjsLocale } from "@triliumnext/commons";+import sql_init from "./sql_init";+import options from "./options";+import i18next from "i18next";+import hidden_subtree from "./hidden_subtree";++export type TranslationProvider = (i18nextInstance: typeof i18next, locale: LOCALE_IDS) => Promise<void>;++export async function initTranslations(translationProvider: TranslationProvider) {+ const locale = getCurrentLanguage();++ await translationProvider(i18next, locale);++ // Initialize dayjs locale.+ await setDayjsLocale(locale);+}++export function ordinal(date: Dayjs) {+ return dayjs(date)+ .format("Do");+}+- export function getLocales(): Locale[] {- return LOCALES;- }-+function getCurrentLanguage(): LOCALE_IDS {+ let language: string | null = null;+ if (sql_init.isDbInitialized()) {+ language = options.getOptionOrNull("locale");+ if (!language) {+ console.info("Language option not found, falling back to en.");+ }+ }++ return (language ?? "en") as LOCALE_IDS;+}++export async function changeLanguage(locale: string) {+ await i18next.changeLanguage(locale);+ hidden_subtree.checkHiddenSubtree(true, { restoreNames: true });+}++export function getCurrentLocale() {+ if (!sql_init.isDbInitialized()) {+ // If DB is not initialized, we cannot get the locale from options, so we return English as a default.+ return LOCALES.find(l => l.id === "en")!;+ }++ const localeId = options.getOptionOrNull("locale") ?? "en";+ const currentLocale = LOCALES.find(l => l.id === localeId);+ if (!currentLocale) return LOCALES.find(l => l.id === "en")!;+ return currentLocale;+}diff --cc packages/trilium-core/src/services/utils/index.spec.tsindex 7ebbf4df0e,0000000000..da3991cb2amode 100644,000000..100644--- a/packages/trilium-core/src/services/utils/index.spec.ts+++ b/packages/trilium-core/src/services/utils/index.spec.ts@@@ -1,735 -1,0 +1,842 @@@+import { expect, describe, it } from "vitest";+import * as utils from "./index";++// fn value, expected value+const testCases: [fnValue: string, expectedValue: string][] = [+ [ "testName", "testName" ],+ [ "test_name", "test_name" ],+ [ "test with space", "test_with_space" ],+ [ "test:with:colon", "test:with:colon" ],++ // numbers+ [ "123456", "123456" ],+ [ "123:456", "123:456" ],+ [ "123456 abc", "123456_abc" ],++ // non-latin characters+ [ "ε", "ε" ],+ [ "attribute ε", "attribute_ε" ],++ // special characters+ [ "test/name", "test_name" ],+ [ "test%name", "test_name" ],+ [ "\/", "_" ],++ // empty string+ [ "", "unnamed" ]+];++describe("sanitizeAttributeName unit tests", () => {+ testCases.forEach((testCase) => {+ return it(`'${testCase[0]}' should return '${testCase[1]}'`, () => {+ const [ value, expected ] = testCase;+ const actual = utils.sanitizeAttributeName(value);+ expect(actual).toStrictEqual(expected);+ });+ });+});++type TestCase<T extends (...args: any) => any> = [desc: string, fnParams: Parameters<T>, expected: ReturnType<T>];++describe("#newEntityId", () => {+ it("should return a string with a length of 12", () => {+ const result = utils.newEntityId();+ expect(result).toBeTypeOf("string");+ expect(result).toHaveLength(12);+ });+});++describe("#randomString", () => {+ it("should return a string with a length as per argument", () => {+ const stringLength = 5;+ const result = utils.randomString(stringLength);+ expect(result).toBeTypeOf("string");+ expect(result).toHaveLength(stringLength);+ });+});++// TriliumNextTODO: should use mocks and assert that functions get called+describe("#randomSecureToken", () => {+ // base64 -> 4 * (bytes/3) length -> if padding and rounding up is ignored for simplicity+ // https://stackoverflow.com/a/13378842+ const byteToBase64Length = (bytes: number) => 4 * (bytes / 3);++ it("should return a string and use 32 bytes by default", () => {+ const result = utils.randomSecureToken();+ expect(result).toBeTypeOf("string");+ expect(result.length).toBeGreaterThanOrEqual(byteToBase64Length(32));+ });++ it("should return a string and use passed byte length", () => {+ const bytes = 16;+ const result = utils.randomSecureToken(bytes);+ expect(result).toBeTypeOf("string");+ expect(result.length).toBeGreaterThanOrEqual(byteToBase64Length(bytes));+ expect(result.length).toBeLessThan(44); // default argument uses 32 bytes -> which translates to 44 base64 legal chars+ });+});++// TriliumNextTODO: should use mocks and assert that functions get called+describe.todo("#md5", () => {});++// TriliumNextTODO: should use mocks and assert that functions get called+describe.todo("#hashedBlobId", () => {});++// TriliumNextTODO: should use mocks and assert that functions get called+describe.todo("#toBase64", () => {});++// TriliumNextTODO: should use mocks and assert that functions get called+describe.todo("#fromBase64", () => {});++// TriliumNextTODO: should use mocks and assert that functions get called+describe.todo("#hmac", () => {});++// TriliumNextTODO: should use mocks and assert that functions get called+describe.todo("#hash", () => {});++describe("#isEmptyOrWhitespace", () => {+ const testCases: TestCase<typeof utils.isEmptyOrWhitespace>[] = [+ [ "w/ 'null' it should return true", [ null ], true ],+ [ "w/ 'null' it should return true", [ null ], true ],+ [ "w/ undefined it should return true", [ undefined ], true ],+ [ "w/ empty string '' it should return true", [ "" ], true ],+ [ "w/ single whitespace string ' ' it should return true", [ " " ], true ],+ [ "w/ multiple whitespace string ' ' it should return true", [ " " ], true ],+ [ "w/ non-empty string ' t ' it should return false", [ " t " ], false ]+ ];++ testCases.forEach((testCase) => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.isEmptyOrWhitespace(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe("#sanitizeSqlIdentifier", () => {+ const testCases: TestCase<typeof utils.sanitizeSqlIdentifier>[] = [+ [ "w/ 'test' it should not strip anything", [ "test" ], "test" ],+ [ "w/ 'test123' it should not strip anything", [ "test123" ], "test123" ],+ [ "w/ 'tEst_TeSt' it should not strip anything", [ "tEst_TeSt" ], "tEst_TeSt" ],+ [ "w/ 'test_test' it should not strip '_'", [ "test_test" ], "test_test" ],+ [ "w/ 'test-' it should strip the '-'", [ "test-" ], "test" ],+ [ "w/ 'test-test' it should strip the '-'", [ "test-test" ], "testtest" ],+ [ "w/ 'test; --test' it should strip the '; --'", [ "test; --test" ], "testtest" ],+ [ "w/ 'test test' it should strip the ' '", [ "test test" ], "testtest" ]+ ];++ testCases.forEach((testCase) => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.sanitizeSqlIdentifier(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe("#escapeHtml", () => {+ it("should re-export 'escape-html' npm module as escapeHtml", () => {+ expect(utils.escapeHtml).toBeTypeOf("function");+ });+});++describe("#unescapeHtml", () => {+ it("should re-export 'unescape' npm module as unescapeHtml", () => {+ expect(utils.unescapeHtml).toBeTypeOf("function");+ });+});++describe("#toObject", () => {+ it("should return an object with keys and value being set from the supplied Function", () => {+ type TestListEntry = { testPropA: string; testPropB: string };+ type TestListFn = (testListEntry: TestListEntry) => [string, string];+ const testList: [TestListEntry, TestListEntry] = [+ { testPropA: "keyA", testPropB: "valueA" },+ { testPropA: "keyB", testPropB: "valueB" }+ ];+ const fn: TestListFn = (testListEntry: TestListEntry) => [ `${testListEntry.testPropA }_fn`, `${testListEntry.testPropB }_fn` ];++ const result = utils.toObject(testList, fn);+ expect(result).toStrictEqual({+ keyA_fn: "valueA_fn",+ keyB_fn: "valueB_fn"+ });+ });+});++describe("#stripTags", () => {+ //prettier-ignore+ const htmlWithNewlines =+`<p>abc+def</p>+<p>ghi</p>`;++ const testCases: TestCase<typeof utils.stripTags>[] = [+ [ "should strip all tags and only return the content, leaving new lines and spaces in tact", [ htmlWithNewlines ], "abc\ndef\nghi" ],+ //TriliumNextTODO: should this actually insert a space between content to prevent concatenated text?+ [ "should strip all tags and only return the content", [ "<h1>abc</h1><p>def</p>" ], "abcdef" ]+ ];++ testCases.forEach((testCase) => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.stripTags(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe.todo("#escapeRegExp", () => {});++describe.todo("#crash", () => {});++describe("#getContentDisposition", () => {++ const defaultFallBackDisposition = `file; filename="file"; filename*=UTF-8''file`;+ const testCases: TestCase<typeof utils.getContentDisposition>[] = [+ [+ "when passed filename is empty, it should fallback to default value 'file'",+ [ " " ],+ defaultFallBackDisposition+ ],+ [+ "when passed filename '..' would cause sanitized filename to be empty, it should fallback to default value 'file'",+ [ ".." ],+ defaultFallBackDisposition+ ],+ // COM1 is a Windows specific "illegal filename" that sanitize filename strips away+ [+ "when passed filename 'COM1' would cause sanitized filename to be empty, it should fallback to default value 'file'",+ [ "COM1" ],+ defaultFallBackDisposition+ ],+ [+ "sanitized passed filename should be returned URIEncoded",+ [ "test file.csv" ],+ `file; filename="test%20file.csv"; filename*=UTF-8''test%20file.csv`+ ]+ ];++ testCases.forEach(testCase => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.getContentDisposition(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe("#isStringNote", () => {++ const testCases: TestCase<typeof utils.isStringNote>[] = [+ [+ "w/ 'undefined' note type, but a string mime type, it should return true",+ [ undefined, "application/javascript" ],+ true+ ],+ [+ "w/ non-string note type, it should return false",+ [ "image", "image/jpeg" ],+ false+ ],+ [+ "w/ string note type (text), it should return true",+ [ "text", "text/html" ],+ true+ ],+ [+ "w/ string note type (code), it should return true",+ [ "code", "application/json" ],+ true+ ],+ [+ "w/ non-string note type (file), but string mime type, it should return true",+ [ "file", "application/json" ],+ true+ ],+ [+ "w/ non-string note type (file), but mime type starting with 'text/', it should return true",+ [ "file", "text/html" ],+ true+ ]+ ];++ testCases.forEach((testCase) => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.isStringNote(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe.todo("#quoteRegex", () => {});++describe.todo("#replaceAll", () => {});++describe("#removeFileExtension", () => {+ const testCases: TestCase<typeof utils.removeFileExtension>[] = [+ [ "w/ 'test.md' it should strip '.md'", [ "test.md" ], "test" ],+ [ "w/ 'test.markdown' it should strip '.markdown'", [ "test.markdown" ], "test" ],+ [ "w/ 'test.html' it should strip '.html'", [ "test.html" ], "test" ],+ [ "w/ 'test.htm' it should strip '.htm'", [ "test.htm" ], "test" ],+ [ "w/ 'test.zip' it should NOT strip '.zip'", [ "test.zip" ], "test.zip" ]+ ];++ testCases.forEach((testCase) => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.removeFileExtension(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe("#getNoteTitle", () => {+ const testCases: TestCase<typeof utils.getNoteTitle>[] = [+ [+ "when file has no spaces, and no special file extension, it should return the filename unaltered",+ [ "test.json", true, undefined ],+ "test.json"+ ],+ [+ "when replaceUnderscoresWithSpaces is false, it should keep the underscores in the title",+ [ "test_file.json", false, undefined ],+ "test_file.json"+ ],+ [+ "when replaceUnderscoresWithSpaces is true, it should replace the underscores in the title",+ [ "test_file.json", true, undefined ],+ "test file.json"+ ],+ [+ "when filePath ends with one of the extra handled endings (.md), it should strip the file extension from the title",+ [ "test_file.md", false, undefined ],+ "test_file"+ ],+ [+ "when filePath ends with one of the extra handled endings (.md) and replaceUnderscoresWithSpaces is true, it should strip the file extension from the title and replace underscores",+ [ "test_file.md", true, undefined ],+ "test file"+ ],+ [+ "when filepath contains a full path, it should only return the basename of the file",+ [ "Trilium Demo/Scripting examples/Statistics/Most cloned notes/template.zip", true, undefined ],+ "template.zip"+ ],+ [+ "when filepath contains a full path and has extra handled ending (.html), it should only return the basename of the file and strip the file extension",+ [ "Trilium Demo/Scripting examples/Statistics/Most cloned notes/template.html", true, undefined ],+ "template"+ ],+ [+ "when a noteMeta object is passed, it should use the title from the noteMeta, if present",+ [ "test_file.md", true, { title: "some other title" } ],+ "some other title"+ ],+ [+ "when a noteMeta object is passed, but the title prop is empty, it should try to handle the filename as if no noteMeta was passed",+ [ "test_file.md", true, { title: "" } ],+ "test file"+ ],+ [+ "when a noteMeta object is passed, but the title prop is empty, it should try to handle the filename as if no noteMeta was passed",+ [ "test_file.json", false, { title: " " } ],+ "test_file.json"+ ]+ ];++ testCases.forEach(testCase => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.getNoteTitle(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });++});++describe("#timeLimit", () => {+ it("when promise execution does NOT exceed timeout, it should resolve with promises' value", async () => {+ const resolvedValue = `resolved: ${new Date().toISOString()}`;+ const testPromise = new Promise((res, rej) => {+ setTimeout(() => {+ return res(resolvedValue);+ }, 200);+ //rej("rejected!");+ });+ await expect(utils.timeLimit(testPromise, 1_000)).resolves.toBe(resolvedValue);+ });++ it("when promise execution rejects within timeout, it should return the original promises' rejected value, not the custom set one", async () => {+ const rejectedValue = `rejected: ${new Date().toISOString()}`;+ const testPromise = new Promise((res, rej) => {+ setTimeout(() => {+ //return res("resolved");+ rej(rejectedValue);+ }, 100);+ });+ await expect(utils.timeLimit(testPromise, 200, "Custom Error")).rejects.toThrow(rejectedValue);+ });++ it("when promise execution exceeds the set timeout, and 'errorMessage' is NOT set, it should reject the promise and display default error message", async () => {+ const testPromise = new Promise((res, rej) => {+ setTimeout(() => {+ return res("resolved");+ }, 500);+ //rej("rejected!");+ });+ await expect(utils.timeLimit(testPromise, 200)).rejects.toThrow(`Process exceeded time limit 200`);+ });++ it("when promise execution exceeds the set timeout, and 'errorMessage' is set, it should reject the promise and display set error message", async () => {+ const customErrorMsg = "Custom Error";+ const testPromise = new Promise((res, rej) => {+ setTimeout(() => {+ return res("resolved");+ }, 500);+ //rej("rejected!");+ });+ await expect(utils.timeLimit(testPromise, 200, customErrorMsg)).rejects.toThrow(customErrorMsg);+ });++ // TriliumNextTODO: since TS avoids this from ever happening – do we need this check?+ it("when the passed promise is not a promise but 'undefined', it should return 'undefined'", async () => {+ //@ts-expect-error - passing in illegal type 'undefined'+ expect(utils.timeLimit(undefined, 200)).toBe(undefined);+ });++ // TriliumNextTODO: since TS avoids this from ever happening – do we need this check?+ it("when the passed promise is not a promise, it should return the passed value", async () => {+ //@ts-expect-error - passing in illegal type 'object'+ expect(utils.timeLimit({ test: 1 }, 200)).toStrictEqual({ test: 1 });+ });+});++describe("#removeDiacritic", () => {+ const testCases: TestCase<typeof utils.removeDiacritic>[] = [+ [ "w/ 'Äpfel' it should replace the 'Ä'", [ "Äpfel" ], "Apfel" ],+ [ "w/ 'Été' it should replace the 'É' and 'é'", [ "Été" ], "Ete" ],+ [ "w/ 'Fête' it should replace the 'ê'", [ "Fête" ], "Fete" ],+ [ "w/ 'Αλφαβήτα' it should replace the 'ή'", [ "Αλφαβήτα" ], "Αλφαβητα" ],+ [ "w/ '' (empty string) it should return empty string", [ "" ], "" ]+ ];++ testCases.forEach((testCase) => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.removeDiacritic(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe("#normalize", () => {+ const testCases: TestCase<typeof utils.normalize>[] = [+ [ "w/ 'Äpfel' it should replace the 'Ä' and return lowercased", [ "Äpfel" ], "apfel" ],+ [ "w/ 'Été' it should replace the 'É' and 'é' and return lowercased", [ "Été" ], "ete" ],+ [ "w/ 'FêTe' it should replace the 'ê' and return lowercased", [ "FêTe" ], "fete" ],+ [ "w/ 'ΑλΦαβήΤα' it should replace the 'ή' and return lowercased", [ "ΑλΦαβήΤα" ], "αλφαβητα" ],+ [ "w/ '' (empty string) it should return empty string", [ "" ], "" ]+ ];++ testCases.forEach((testCase) => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.normalize(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe("#toMap", () => {+ it("should return an instace of Map, with the correct size and keys, when supplied with a list and existing keys", () => {+ const testList = [ { title: "test", propA: "text", propB: 123 }, { title: "test2", propA: "prop2", propB: 456 } ];+ const result = utils.toMap(testList, "title");+ expect(result).toBeInstanceOf(Map);+ expect(result.size).toBe(2);+ expect(Array.from(result.keys())).toStrictEqual([ "test", "test2" ]);+ });+ it("should return an instace of Map, with an empty size, when the supplied list does not contain the supplied key", () => {+ const testList = [ { title: "test", propA: "text", propB: 123 }, { title: "test2", propA: "prop2", propB: 456 } ];+ //@ts-expect-error - key is non-existing on supplied list type+ const result = utils.toMap(testList, "nonExistingKey");+ expect(result).toBeInstanceOf(Map);+ expect(result.size).toBe(0);+ });+ it.fails("should correctly handle duplicate keys? (currently it will overwrite the entry, so returned size will be 1 instead of 2)", () => {+ const testList = [ { title: "testDupeTitle", propA: "text", propB: 123 }, { title: "testDupeTitle", propA: "prop2", propB: 456 } ];+ const result = utils.toMap(testList, "title");+ expect(result).toBeInstanceOf(Map);+ expect(result.size).toBe(2);+ });+});++describe("#envToBoolean", () => {+ const testCases: TestCase<typeof utils.envToBoolean>[] = [+ [ "w/ 'true' it should return boolean 'true'", [ "true" ], true ],+ [ "w/ 'True' it should return boolean 'true'", [ "True" ], true ],+ [ "w/ 'TRUE' it should return boolean 'true'", [ "TRUE" ], true ],+ [ "w/ 'true ' it should return boolean 'true'", [ "true " ], true ],+ [ "w/ 'false' it should return boolean 'false'", [ "false" ], false ],+ [ "w/ 'False' it should return boolean 'false'", [ "False" ], false ],+ [ "w/ 'FALSE' it should return boolean 'false'", [ "FALSE" ], false ],+ [ "w/ 'false ' it should return boolean 'false'", [ "false " ], false ],+ [ "w/ 'whatever' (non-boolean string) it should return undefined", [ "whatever" ], undefined ],+ [ "w/ '-' (non-boolean string) it should return undefined", [ "-" ], undefined ],+ [ "w/ '' (empty string) it should return undefined", [ "" ], undefined ],+ [ "w/ ' ' (white space string) it should return undefined", [ " " ], undefined ],+ [ "w/ undefined it should return undefined", [ undefined ], undefined ],+ //@ts-expect-error - pass wrong type as param+ [ "w/ number 1 it should return undefined", [ 1 ], undefined ]+ ];++ testCases.forEach((testCase) => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.envToBoolean(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe.todo("#getResourceDir", () => {});++describe("#isElectron", () => {+ it("should export a boolean", () => {+ expect(utils.isElectron()).toBeTypeOf("boolean");+ });+});++describe("#isMac", () => {+ it("should export a boolean", () => {+ expect(utils.isMac()).toBeTypeOf("boolean");+ });+});++describe("#isWindows", () => {+ it("should export a boolean", () => {+ expect(utils.isWindows()).toBeTypeOf("boolean");+ });+});++describe("#safeExtractMessageAndStackFromError", () => {+ it("should correctly extract the message and stack property if it gets passed an instance of an Error", () => {+ const testMessage = "Test Message";+ const testError = new Error(testMessage);+ const actual = utils.safeExtractMessageAndStackFromError(testError);+ expect(actual[0]).toBe(testMessage);+ expect(actual[1]).not.toBeUndefined();+ });++ it("should use the fallback 'Unknown Error' message, if it gets passed anything else than an instance of an Error", () => {+ const testNonError = "this is not an instance of an Error, but JS technically allows us to throw this anyways";+ const actual = utils.safeExtractMessageAndStackFromError(testNonError);+ expect(actual[0]).toBe("Unknown Error");+ expect(actual[1]).toBeUndefined();+ });+});++describe("#formatDownloadTitle", () => {+ //prettier-ignore+ const testCases: [fnValue: Parameters<typeof utils.formatDownloadTitle>, expectedValue: ReturnType<typeof utils.formatDownloadTitle>][] = [++ // empty fileName tests+ [+ [ "", "text", "" ],+ "untitled.html"+ ],+ [+ [ "", "canvas", "" ],+ "untitled.json"+ ],+ [+ [ "", null, "" ],+ "untitled"+ ],+++ // json extension from type tests+ [+ [ "test_file", "canvas", "" ],+ "test_file.json"+ ],+ [+ [ "test_file", "relationMap", "" ],+ "test_file.json"+ ],+ [+ [ "test_file", "search", "" ],+ "test_file.json"+ ],+++ // extension based on mime type+ [+ [ "test_file", null, "text/csv" ],+ "test_file.csv"+ ],+ [+ [ "test_file_wo_ext", "image", "image/svg+xml" ],+ "test_file_wo_ext.svg"+ ],+ [+ [ "test_file_wo_ext", "file", "application/json" ],+ "test_file_wo_ext.json"+ ],+ [+ [ "test_file_w_fake_ext.ext", "image", "image/svg+xml" ],+ "test_file_w_fake_ext.ext.svg"+ ],+ [+ [ "test_file_w_correct_ext.svg", "image", "image/svg+xml" ],+ "test_file_w_correct_ext.svg"+ ],+ [+ [ "test_file_w_correct_ext.svgz", "image", "image/svg+xml" ],+ "test_file_w_correct_ext.svgz"+ ],+ [+ [ "test_file.zip", "file", "application/zip" ],+ "test_file.zip"+ ],+ [+ [ "test_file", "file", "application/zip" ],+ "test_file.zip"+ ],+++ // application/octet-stream tests+ [+ [ "test_file", "file", "application/octet-stream" ],+ "test_file"+ ],+ [+ [ "test_file.zip", "file", "application/octet-stream" ],+ "test_file.zip"+ ],+ [+ [ "test_file.unknown", null, "application/octet-stream" ],+ "test_file.unknown"+ ],+++ // sanitized filename tests+ [+ [ "test/file", null, "application/octet-stream" ],+ "testfile"+ ],+ [+ [ "test:file.zip", "file", "application/zip" ],+ "testfile.zip"+ ],+ [+ [ ":::", "file", "application/zip" ],+ ".zip"+ ],+ [+ [ ":::a", "file", "application/zip" ],+ "a.zip"+ ]+ ];++ testCases.forEach((testCase) => {+ const [ fnParams, expected ] = testCase;+ return it(`With args '${JSON.stringify(fnParams)}', it should return '${expected}'`, () => {+ const actual = utils.formatDownloadTitle(...fnParams);+ expect(actual).toStrictEqual(expected);+ });+ });+});++describe("#normalizeUrl", () => {+ const testCases: TestCase<typeof utils.normalizeUrl>[] = [+ [ "should remove trailing slash from simple URL", [ "https://example.com/" ], "https://example.com" ],+ [ "should remove trailing slash from URL with path", [ "https://example.com/path/" ], "https://example.com/path" ],+ [ "should preserve URL without trailing slash", [ "https://example.com" ], "https://example.com" ],+ [ "should preserve URL without trailing slash with path", [ "https://example.com/path" ], "https://example.com/path" ],+ [ "should preserve protocol-only URLs", [ "https://" ], "https://" ],+ [ "should preserve protocol-only URLs", [ "http://" ], "http://" ],+ [ "should fix double slashes in path", [ "https://example.com//api//test" ], "https://example.com/api/test" ],+ [ "should handle multiple double slashes", [ "https://example.com///api///test" ], "https://example.com/api/test" ],+ [ "should handle trailing slash with double slashes", [ "https://example.com//api//" ], "https://example.com/api" ],+ [ "should preserve protocol double slash", [ "https://example.com/api" ], "https://example.com/api" ],+ [ "should handle empty string", [ "" ], "" ],+ [ "should handle whitespace-only string", [ " " ], "" ],+ [ "should trim whitespace", [ " https://example.com/ " ], "https://example.com" ],+ [ "should handle null as empty", [ null as any ], null ],+ [ "should handle undefined as empty", [ undefined as any ], undefined ]+ ];++ testCases.forEach((testCase) => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.normalizeUrl(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe("#normalizeCustomHandlerPattern", () => {+ const testCases: TestCase<typeof utils.normalizeCustomHandlerPattern>[] = [+ [ "should handle pattern without ending - add both versions", [ "foo" ], [ "foo", "foo/" ] ],+ [ "should handle pattern with trailing slash - add both versions", [ "foo/" ], [ "foo", "foo/" ] ],+ [ "should handle pattern ending with $ - add optional slash", [ "foo$" ], [ "foo/?$" ] ],+ [ "should handle pattern with trailing slash and $ - add both versions", [ "foo/$" ], [ "foo$", "foo/$" ] ],+ [ "should preserve existing optional slash pattern", [ "foo/?$" ], [ "foo/?$" ] ],+ [ "should preserve existing optional slash pattern (alternative)", [ "foo/?)" ], [ "foo/?)" ] ],+ [ "should handle regex pattern with special chars", [ "api/[a-z]+$" ], [ "api/[a-z]+/?$" ] ],+ [ "should handle complex regex pattern", [ "user/([0-9]+)/profile$" ], [ "user/([0-9]+)/profile/?$" ] ],+ [ "should handle empty string", [ "" ], [ "" ] ],+ [ "should handle whitespace-only string", [ " " ], [ "" ] ],+ [ "should handle null", [ null as any ], [ null ] ],+ [ "should handle undefined", [ undefined as any ], [ undefined ] ]+ ];++ testCases.forEach((testCase) => {+ const [ desc, fnParams, expected ] = testCase;+ it(desc, () => {+ const result = utils.normalizeCustomHandlerPattern(...fnParams);+ expect(result).toStrictEqual(expected);+ });+ });+});++describe("#slugify", () => {+ it("should return a slugified string", () => {+ const testString = "This is a Test String! With unicode & Special #Chars.";+ const expectedSlug = "this-is-a-test-string-with-unicode-special-chars";+ const result = utils.slugify(testString);+ expect(result).toBe(expectedSlug);+ });++ it("supports CJK characters without alteration", () => {+ const testString = "测试中文字符";+ const expectedSlug = "测试中文字符";+ const result = utils.slugify(testString);+ expect(result).toBe(expectedSlug);+ });++ it("supports Cyrillic characters without alteration", () => {+ const testString = "Тестирование кириллических символов";+ const expectedSlug = "тестирование-кириллических-символов";+ const result = utils.slugify(testString);+ expect(result).toBe(expectedSlug);+ });++ // preserves diacritic marks+ it("preserves diacritic marks", () => {+ const testString = "Café naïve façade jalapeño";+ const expectedSlug = "café-naïve-façade-jalapeño";+ const result = utils.slugify(testString);+ expect(result).toBe(expectedSlug);+ });+});++++describe("#sanitizeSvg", () => {++ it("should remove script elements", () => {++ const maliciousSvg = '<svg><script>alert("XSS")</script><rect width="100" height="100"/></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><rect width="100" height="100"/></svg>');++ });++++ it("should remove script elements with attributes", () => {++ const maliciousSvg = '<svg><script type="text/javascript">alert("XSS")</script></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg></svg>');++ });++++ it("should remove multiline script elements", () => {++ const maliciousSvg = `<svg><script>++ var x = 1;++ alert(x);++ </script></svg>`;++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg></svg>');++ });++++ it("should remove onclick event handlers with double quotes", () => {++ const maliciousSvg = '<svg><rect onclick="doEvil()" width="100"/></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><rect width="100"/></svg>');++ });++++ it("should remove onclick event handlers with single quotes", () => {++ const maliciousSvg = "<svg><rect onclick='doEvil()' width=\"100\"/></svg>";++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><rect width="100"/></svg>');++ });++++ it("should remove onload event handlers", () => {++ const maliciousSvg = '<svg onload="doEvil()"><rect width="100"/></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><rect width="100"/></svg>');++ });++++ it("should remove onerror event handlers", () => {++ const maliciousSvg = '<svg><image onerror="alert(1)" href="invalid.jpg"/></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><image href="invalid.jpg"/></svg>');++ });++++ it("should remove onmouseover event handlers", () => {++ const maliciousSvg = '<svg><rect onmouseover="alert(1)" width="100"/></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><rect width="100"/></svg>');++ });++++ it("should remove event handlers without quotes", () => {++ const maliciousSvg = '<svg><rect onclick=alert(1) width="100"/></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><rect width="100"/></svg>');++ });++++ it("should replace javascript: URLs in href with #", () => {++ const maliciousSvg = '<svg><a href="javascript:alert(1)"><text>Click me</text></a></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><a href="#"><text>Click me</text></a></svg>');++ });++++ it("should replace javascript: URLs in xlink:href with #", () => {++ const maliciousSvg = '<svg><a xlink:href="javascript:alert(1)"><text>Click me</text></a></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><a xlink:href="#"><text>Click me</text></a></svg>');++ });++++ it("should preserve valid SVG content", () => {++ const validSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect x="10" y="10" width="80" height="80" fill="blue"/><circle cx="50" cy="50" r="30" fill="red"/></svg>';++ const result = utils.sanitizeSvg(validSvg);++ expect(result).toBe(validSvg);++ });++++ it("should preserve valid href URLs", () => {++ const validSvg = '<svg><a href="https://example.com"><text>Link</text></a></svg>';++ const result = utils.sanitizeSvg(validSvg);++ expect(result).toBe(validSvg);++ });++++ it("should handle multiple malicious elements", () => {++ const maliciousSvg = '<svg onload="evil()"><script>evil()</script><rect onclick="bad()" width="100"/><a href="javascript:attack()">link</a></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><rect width="100"/><a href="#">link</a></svg>');++ });++++ it("should handle empty SVG", () => {++ const emptySvg = '<svg></svg>';++ const result = utils.sanitizeSvg(emptySvg);++ expect(result).toBe('<svg></svg>');++ });++++ it("should be case insensitive for script tags", () => {++ const maliciousSvg = '<svg><SCRIPT>alert(1)</SCRIPT><Script>alert(2)</Script></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg></svg>');++ });++++ it("should be case insensitive for event handlers", () => {++ const maliciousSvg = '<svg><rect ONCLICK="alert(1)" width="100"/></svg>';++ const result = utils.sanitizeSvg(maliciousSvg);++ expect(result).toBe('<svg><rect width="100"/></svg>');++ });++});diff --cc packages/trilium-core/src/services/utils/index.tsindex a1427becbf,0000000000..3672b683efmode 100644,000000..100644--- a/packages/trilium-core/src/services/utils/index.ts+++ b/packages/trilium-core/src/services/utils/index.ts@@@ -1,417 -1,0 +1,433 @@@+import { getCrypto } from "../encryption/crypto";+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 unescape from "unescape";+import { basename, extname } from "./path";+import { NoteMeta } from "../../meta";++export function isDev() { return getPlatform().getEnv("TRILIUM_ENV") === "dev"; }+export function isElectron() { return getPlatform().isElectron; }+export function isMac() { return getPlatform().isMac; }+export function isWindows() { return getPlatform().isWindows; }++// render and book are string note in the sense that they are expected to contain empty string+const STRING_NOTE_TYPES = new Set(["text", "code", "relationMap", "search", "render", "book", "mermaid", "canvas", "webView"]);+const STRING_MIME_TYPES = new Set(["application/javascript", "application/x-javascript", "application/json", "application/x-sql", "image/svg+xml"]);++export function hash(text: string) {+ return encodeBase64(getCrypto().createHash("sha1", text.normalize()));+}++export function md5(content: string | Uint8Array) {+ const bytes = getCrypto().createHash("md5", content);+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");+}++export function isStringNote(type: string | undefined, mime: string) {+ return (type && STRING_NOTE_TYPES.has(type)) || mime.startsWith("text/") || STRING_MIME_TYPES.has(mime);+}++// TODO: Refactor to use getCrypto() directly.+export function randomString(length: number) {+ return getCrypto().randomString(length);+}++export function newEntityId() {+ return randomString(12);+}++export function hashedBlobId(content: string | Uint8Array) {+ if (content === null || content === undefined) {+ content = "";+ }++ // sha512 is faster than sha256+ const base64Hash = encodeBase64(getCrypto().createHash("sha512", content));++ // we don't want such + and / in the IDs+ const kindaBase62Hash = base64Hash.replaceAll("+", "X").replaceAll("/", "Y");++ // 20 characters of base62 gives us ~120 bit of entropy which is plenty enough+ return kindaBase62Hash.substr(0, 20);+}++export function quoteRegex(url: string) {+ return url.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");+}++export function replaceAll(string: string, replaceWhat: string, replaceWith: string) {+ const quotedReplaceWhat = quoteRegex(replaceWhat);++ return string.replace(new RegExp(quotedReplaceWhat, "g"), replaceWith);+}++export function removeDiacritic(str: string) {+ if (!str) {+ return "";+ }+ str = str.toString();+ return str.normalize("NFD").replace(/\p{Diacritic}/gu, "");+}++export function normalize(str: string) {+ return removeDiacritic(str).toLowerCase();+}++/**+ * Normalizes URL by removing trailing slashes and fixing double slashes.+ * Preserves the protocol (http://, https://) but removes trailing slashes from the rest.+ *+ * @param url The URL to normalize+ * @returns The normalized URL without trailing slashes+ */+export function normalizeUrl(url: string | null | undefined): string | null | undefined {+ if (!url || typeof url !== 'string') {+ return url;+ }++ // Trim whitespace+ url = url.trim();++ if (!url) {+ return url;+ }++ // Fix double slashes (except in protocol) first+ url = url.replace(/([^:]\/)\/+/g, '$1');++ // Remove trailing slash, but preserve protocol+ if (url.endsWith('/') && !url.match(/^https?:\/\/$/)) {+ url = url.slice(0, -1);+ }++ return url;+}++export function timeLimit<T>(promise: Promise<T>, limitMs: number, errorMessage?: string): Promise<T> {+ // TriliumNextTODO: since TS avoids this from ever happening – do we need this check?+ if (!promise || !promise.then) {+ // it's not actually a promise+ return promise;+ }++ // better stack trace if created outside of promise+ const errorTimeLimit = new Error(errorMessage || `Process exceeded time limit ${limitMs}`);++ return new Promise((res, rej) => {+ let resolved = false;++ promise+ .then((result) => {+ resolved = true;++ res(result);+ })+ .catch((error) => rej(error));++ setTimeout(() => {+ if (!resolved) {+ rej(errorTimeLimit);+ }+ }, limitMs);+ });+}++export function sanitizeAttributeName(origName: string) {+ const fixedName = origName === "" ? "unnamed" : origName.replace(/[^\p{L}\p{N}_:]/gu, "_");+ // any not allowed character should be replaced with underscore++ return fixedName;+}++export function sanitizeSqlIdentifier(str: string) {+ return str.replace(/[^A-Za-z0-9_]/g, "");+}+++/**++ * Sanitize SVG to remove potentially dangerous elements and attributes.++ * This prevents XSS via script injection in SVG content.++ */++export function sanitizeSvg(svg: string): string {++ return svg++ // Remove script elements++ .replace(/<script[\s\S]*?<\/script>/gi, '')++ // Remove on* event handlers (onclick, onload, onerror, etc.)++ .replace(/\s+on\w+\s*=\s*["'][^"']*["']/gi, '')++ .replace(/\s+on\w+\s*=\s*[^\s>]+/gi, '')++ // Remove javascript: URLs++ .replace(/href\s*=\s*["']javascript:[^"']*["']/gi, 'href="#"')++ .replace(/xlink:href\s*=\s*["']javascript:[^"']*["']/gi, 'xlink:href="#"');++}+++export function getContentDisposition(filename: string) {+ const sanitizedFilename = sanitizeFileName(filename).trim() || "file";+ const uriEncodedFilename = encodeURIComponent(sanitizedFilename);+ return `file; filename="${uriEncodedFilename}"; filename*=UTF-8''${uriEncodedFilename}`;+}++export function formatDownloadTitle(fileName: string, type: string | null, mime: string) {+ const fileNameBase = !fileName ? "untitled" : sanitizeFileName(fileName);++ const getExtension = () => {+ if (type === "text") return ".html";+ if (type === "relationMap" || type === "canvas" || type === "search") return ".json";+ if (!mime) return "";++ const mimeLc = mime.toLowerCase();++ // better to just return the current name without a fake extension+ // it's possible that the title still preserves the correct extension anyways+ if (mimeLc === "application/octet-stream") return "";++ // if fileName has an extension matching the mime already - reuse it+ const ext = extname(fileName).toLowerCase().replace(".", "");+ if (ext && extToMime[ext] === mimeLc) return "";++ // as last resort try to get extension from mimeType+ const exts = mimeToExt[mime];+ return exts?.length ? `.${exts[0]}` : "";+ };++ return `${fileNameBase}${getExtension()}`;+}++export function toMap<T extends Record<string, any>>(list: T[], key: keyof T) {+ const map = new Map<string, T>();+ for (const el of list) {+ const keyForMap = el[key];+ if (!keyForMap) continue;+ // TriliumNextTODO: do we need to handle the case when the same key is used?+ // currently this will overwrite the existing entry in the map+ map.set(keyForMap, el);+ }+ return map;+}++export const escapeHtml = escape;++export const unescapeHtml = unescape;++export function randomSecureToken(bytes = 32) {+ return encodeBase64(getCrypto().randomBytes(32));+}++export function safeExtractMessageAndStackFromError(err: unknown): [errMessage: string, errStack: string | undefined] {+ if (err instanceof Error) {+ return [err.message, err.stack] as const;+ }++ if (typeof err === "string") {+ return [err, undefined] as const;+ }++ return ["Unknown Error", undefined] as const;+}++export function isEmptyOrWhitespace(str: string | null | undefined) {+ if (!str) return true;+ return str.match(/^ *$/) !== null;+}++export function escapeRegExp(str: string) {+ return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");+}++export function removeFileExtension(filePath: string, mime?: string) {+ const extension = extname(filePath).toLowerCase();++ if (mime?.startsWith("video/") || mime?.startsWith("audio/")) {+ return filePath.substring(0, filePath.length - extension.length);+ }++ switch (extension) {+ case ".md":+ case ".mdx":+ case ".markdown":+ case ".html":+ case ".htm":+ case ".excalidraw":+ case ".mermaid":+ case ".mmd":+ case ".pdf":+ return filePath.substring(0, filePath.length - extension.length);+ default:+ return filePath;+ }+}++export function getNoteTitle(filePath: string, replaceUnderscoresWithSpaces: boolean, noteMeta?: NoteMeta) {+ const trimmedNoteMeta = noteMeta?.title?.trim();+ if (trimmedNoteMeta) return trimmedNoteMeta;++ const fileBasename = basename(removeFileExtension(filePath, noteMeta?.mime));+ return replaceUnderscoresWithSpaces ? fileBasename.replace(/_/g, " ").trim() : fileBasename;+}++// try to turn 'true' and 'false' strings from process.env variables into boolean values or undefined+export function envToBoolean(val: string | undefined) {+ if (val === undefined || typeof val !== "string") return undefined;++ const valLc = val.toLowerCase().trim();++ if (valLc === "true") return true;+ if (valLc === "false") return false;++ return undefined;+}++/**+ * Parses a string value to an integer. If the resulting number is NaN or undefined, the result is also undefined.+ *+ * @param val the value to parse.+ * @returns the parsed value.+ */+export function stringToInt(val: string | undefined) {+ if (!val) {+ return undefined;+ }++ const parsed = parseInt(val, 10);+ if (Number.isNaN(parsed)) {+ return undefined;+ }++ return parsed;+}+++/**+ * Normalizes a path pattern for custom request handlers.+ * Ensures both trailing slash and non-trailing slash versions are handled.+ *+ * @param pattern The original pattern from customRequestHandler attribute+ * @returns An array of patterns to match both with and without trailing slash+ */+export function normalizeCustomHandlerPattern(pattern: string | null | undefined): (string | null | undefined)[] {+ if (!pattern || typeof pattern !== "string") {+ return [pattern];+ }++ pattern = pattern.trim();++ if (!pattern) {+ return [pattern];+ }++ // If pattern already ends with optional trailing slash, return as-is+ if (pattern.endsWith("/?$") || pattern.endsWith("/?)")) {+ return [pattern];+ }++ // If pattern ends with $, handle it specially+ if (pattern.endsWith("$")) {+ const basePattern = pattern.slice(0, -1);++ // If already ends with slash, create both versions+ if (basePattern.endsWith("/")) {+ const withoutSlash = `${basePattern.slice(0, -1)}$`;+ const withSlash = pattern;+ return [withoutSlash, withSlash];+ }+ // Add optional trailing slash+ const withSlash = `${basePattern}/?$`;+ return [withSlash];++ }++ // For patterns without $, add both versions+ if (pattern.endsWith("/")) {+ const withoutSlash = pattern.slice(0, -1);+ return [withoutSlash, pattern];+ }+ const withSlash = `${pattern}/`;+ return [pattern, withSlash];++}++export function formatUtcTime(time: string) {+ return time.replace("T", " ").substring(0, 19);+}++// TODO: Deduplicate with client utils+export function formatSize(size: number | null | undefined) {+ if (size === null || size === undefined) {+ return "";+ }++ size = Math.max(Math.round(size / 1024), 1);++ if (size < 1024) {+ return `${size} KiB`;+ }+ return `${Math.round(size / 102.4) / 10} MiB`;++}++export function slugify(text: string) {+ return text+ .normalize("NFC") // keep composed form, preserves accents+ .toLowerCase()+ .replace(/[^\p{Letter}\p{Number}]+/gu, "-") // replace non-letter/number with "-"+ .replace(/(^-|-$)+/g, ""); // trim dashes+}++export function stripTags(text: string) {+ return text.replace(/<(?:.|\n)*?>/gm, "");+}++export function toObject<T, K extends string | number | symbol, V>(array: T[], fn: (item: T) => [K, V]): Record<K, V> {+ const obj: Record<K, V> = {} as Record<K, V>; // TODO: unsafe?++ for (const item of array) {+ const ret = fn(item);++ obj[ret[0]] = ret[1];+ }++ return obj;+}++// TODO: Deduplicate with src/public/app/services/utils.ts+/**+ * Compares two semantic version strings.+ * Returns:+ * 1 if v1 is greater than v2+ * 0 if v1 is equal to v2+ * -1 if v1 is less than v2+ *+ * @param v1 First version string+ * @param v2 Second version string+ * @returns+ */+export function compareVersions(v1: string, v2: string): number {+ // Remove 'v' prefix and everything after dash if present+ v1 = v1.replace(/^v/, "").split("-")[0];+ v2 = v2.replace(/^v/, "").split("-")[0];++ const v1parts = v1.split(".").map(Number);+ const v2parts = v2.split(".").map(Number);++ // Pad shorter version with zeros+ while (v1parts.length < 3) v1parts.push(0);+ while (v2parts.length < 3) v2parts.push(0);++ // Compare major version+ if (v1parts[0] !== v2parts[0]) {+ return v1parts[0] > v2parts[0] ? 1 : -1;+ }++ // Compare minor version+ if (v1parts[1] !== v2parts[1]) {+ return v1parts[1] > v2parts[1] ? 1 : -1;+ }++ // Compare patch version+ if (v1parts[2] !== v2parts[2]) {+ return v1parts[2] > v2parts[2] ? 1 : -1;+ }++ return 0;+}diff --cc pnpm-lock.yamlindex 38e910b583,98db1a6096..480f85797a--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@@ -171,26 -172,19 +172,26 @@@ importersversion: 2.0.1vite:specifier: 8.0.3- version: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vite-plugin-dts:specifier: 4.5.4- version: 4.5.4(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.5.4(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: 4.1.2- version: 4.1.2(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected]([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.2(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected]([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))apps/build-docs:+ dependencies:+ '@triliumnext/core':+ specifier: workspace:*+ version: link:../../packages/trilium-core+ '@triliumnext/server':+ specifier: workspace:*+ version: link:../serverdevDependencies:'@redocly/cli':- specifier: 2.25.3- version: 2.25.3(@opentelemetry/[email protected])([email protected])([email protected])([email protected])([email protected])+ specifier: 2.25.4+ version: 2.25.4(@opentelemetry/[email protected])([email protected])([email protected])([email protected])([email protected])archiver:specifier: 7.0.1version: 7.0.1@@@ -434,225 -413,8 +420,225 @@@version: 0.7.2vite-plugin-static-copy:specifier: 4.0.0- version: 4.0.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.0.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ apps/client-standalone:+ dependencies:+ '@excalidraw/excalidraw':+ specifier: 0.18.0+ version: 0.18.0(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@fullcalendar/core':+ specifier: 6.1.20+ version: 6.1.20+ '@fullcalendar/daygrid':+ specifier: 6.1.20+ version: 6.1.20(@fullcalendar/[email protected])+ '@fullcalendar/interaction':+ specifier: 6.1.20+ version: 6.1.20(@fullcalendar/[email protected])+ '@fullcalendar/list':+ specifier: 6.1.20+ version: 6.1.20(@fullcalendar/[email protected])+ '@fullcalendar/multimonth':+ specifier: 6.1.20+ version: 6.1.20(@fullcalendar/[email protected])+ '@fullcalendar/timegrid':+ specifier: 6.1.20+ version: 6.1.20(@fullcalendar/[email protected])+ '@maplibre/maplibre-gl-leaflet':+ specifier: 0.1.3+ '@mermaid-js/layout-elk':+ specifier: 0.2.1- version: 0.2.1([email protected])++ version: 0.2.1([email protected])+ '@mind-elixir/node-menu':+ specifier: 5.0.1+ version: 5.0.1([email protected])+ '@popperjs/core':+ specifier: 2.11.8+ version: 2.11.8+ '@preact/signals':+ specifier: 2.9.0+ version: 2.9.0([email protected])+ '@sqlite.org/sqlite-wasm':+ specifier: 3.51.1-build2+ version: 3.51.1-build2+ '@triliumnext/ckeditor5':+ specifier: workspace:*+ version: link:../../packages/ckeditor5+ '@triliumnext/codemirror':+ specifier: workspace:*+ version: link:../../packages/codemirror+ '@triliumnext/commons':+ specifier: workspace:*+ version: link:../../packages/commons+ '@triliumnext/core':+ specifier: workspace:*+ version: link:../../packages/trilium-core+ '@triliumnext/highlightjs':+ specifier: workspace:*+ version: link:../../packages/highlightjs+ '@triliumnext/share-theme':+ specifier: workspace:*+ version: link:../../packages/share-theme+ '@triliumnext/split.js':+ specifier: workspace:*+ version: link:../../packages/splitjs+ '@zumer/snapdom':+ specifier: 2.7.0+ version: 2.7.0+ autocomplete.js:+ specifier: 0.38.1+ version: 0.38.1+ bootstrap:+ specifier: 5.3.8+ version: 5.3.8(@popperjs/[email protected])+ boxicons:+ specifier: 2.1.4+ version: 2.1.4+ clsx:+ specifier: 2.1.1+ version: 2.1.1+ color:+ specifier: 5.0.3+ version: 5.0.3+ debounce:+ specifier: 3.0.0+ version: 3.0.0+ draggabilly:+ specifier: 3.0.0+ version: 3.0.0+ fflate:+ specifier: 0.8.2+ version: 0.8.2+ force-graph:+ specifier: 1.51.2+ version: 1.51.2+ globals:+ specifier: 17.4.0+ version: 17.4.0+ i18next:+ specifier: 26.0.3+ version: 26.0.3([email protected])+ i18next-http-backend:+ specifier: 3.0.4+ version: 3.0.4([email protected])+ jquery:+ specifier: 4.0.0+ version: 4.0.0+ jquery.fancytree:+ specifier: 2.38.5+ version: 2.38.5([email protected])+ js-md5:+ specifier: 0.8.3+ version: 0.8.3+ js-sha1:+ specifier: 0.7.0+ version: 0.7.0+ js-sha256:+ specifier: 0.11.1+ version: 0.11.1+ js-sha512:+ specifier: 0.9.0+ version: 0.9.0+ jsplumb:+ specifier: 2.15.6+ version: 2.15.6+ katex:+ specifier: 0.16.44+ version: 0.16.44+ knockout:+ specifier: 3.5.1+ version: 3.5.1+ leaflet:+ specifier: 1.9.4+ version: 1.9.4+ leaflet-gpx:+ specifier: 2.2.0+ version: 2.2.0+ mark.js:+ specifier: 8.11.1+ version: 8.11.1+ marked:+ specifier: 17.0.5+ version: 17.0.5+ mermaid:- specifier: 11.13.0- version: 11.13.0++ specifier: 11.14.0++ version: 11.14.0+ mind-elixir:+ specifier: 5.10.0+ version: 5.10.0+ normalize.css:+ specifier: 8.0.1+ version: 8.0.1+ panzoom:+ specifier: 9.4.4+ version: 9.4.4+ preact:+ specifier: 10.29.0+ version: 10.29.0+ react-i18next:+ specifier: 17.0.2+ version: 17.0.2([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])+ react-window:+ specifier: 2.2.7+ reveal.js:+ specifier: 6.0.0+ version: 6.0.0+ svg-pan-zoom:+ specifier: 3.6.2+ version: 3.6.2+ tabulator-tables:+ specifier: 6.4.0+ version: 6.4.0+ vanilla-js-wheel-zoom:+ specifier: 9.0.4+ version: 9.0.4+ devDependencies:+ '@ckeditor/ckeditor5-inspector':+ specifier: 5.0.0+ version: 5.0.0+ '@preact/preset-vite':+ specifier: 2.10.2- version: 2.10.2(@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))++ version: 2.10.2(@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ '@types/bootstrap':+ specifier: 5.2.10+ version: 5.2.10+ '@types/jquery':+ specifier: 4.0.0+ version: 4.0.0+ '@types/leaflet':+ specifier: 1.9.21+ version: 1.9.21+ '@types/leaflet-gpx':+ specifier: 1.3.8+ version: 1.3.8+ '@types/mark.js':+ specifier: 8.11.12+ version: 8.11.12+ '@types/reveal.js':+ specifier: 5.2.2+ version: 5.2.2+ '@types/tabulator-tables':+ specifier: 6.3.1+ version: 6.3.1+ copy-webpack-plugin:+ specifier: 14.0.0- version: 14.0.0([email protected]([email protected]))++ version: 14.0.0([email protected]([email protected]))+ cross-env:+ specifier: 7.0.3+ version: 7.0.3+ happy-dom:+ specifier: 20.8.9+ version: 20.8.9([email protected])([email protected])+ script-loader:+ specifier: 0.7.2+ version: 0.7.2+ vite-plugin-static-copy:+ specifier: 4.0.0- version: 4.0.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))++ version: 4.0.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+apps/db-compare:dependencies:colors:@@@ -935,12 -703,12 +921,6 @@@axios:specifier: 1.14.0version: 1.14.0([email protected])- bindings:- specifier: 1.5.0- version: 1.5.0- bootstrap:- specifier: 5.3.8- version: 5.3.8(@popperjs/[email protected])- chardet:- specifier: 2.1.1- version: 2.1.1cheerio:specifier: 1.2.0version: 1.2.0@@@ -1008,11 -776,17 +985,11 @@@specifier: 2.1.4version: 2.1.4http-proxy-agent:- specifier: 8.0.0- version: 8.0.0+ specifier: 9.0.0+ version: 9.0.0https-proxy-agent:- specifier: 8.0.0- version: 8.0.0+ specifier: 9.0.0+ version: 9.0.0- i18next:- specifier: 26.0.3- version: 26.0.3([email protected])- i18next-fs-backend:- specifier: 2.6.3- version: 2.6.3image-type:specifier: 6.1.0version: 6.1.0@@@ -1079,9 -859,15 +1050,9 @@@turnish:specifier: 1.8.0version: 1.8.0- unescape:- specifier: 1.0.1- version: 1.0.1vite:specifier: 8.0.3- version: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- ws:- specifier: 8.20.0- version: 8.20.0([email protected])([email protected])xml2js:specifier: 0.6.2version: 0.6.2@@@ -1685,63 -1438,8 +1623,63 @@@version: 20.8.9([email protected])([email protected])vitest:specifier: 4.1.2- version: 4.1.2(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected]([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.2(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected]([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ packages/trilium-core:+ dependencies:+ '@braintree/sanitize-url':+ specifier: 7.1.1+ version: 7.1.1+ '@triliumnext/commons':+ specifier: workspace:*+ version: link:../commons+ '@triliumnext/turndown-plugin-gfm':+ specifier: workspace:*+ version: link:../turndown-plugin-gfm+ async-mutex:+ specifier: 0.5.0+ version: 0.5.0+ chardet:+ specifier: 2.1.1+ version: 2.1.1+ escape-html:+ specifier: 1.0.3+ version: 1.0.3+ i18next:+ specifier: 26.0.3+ version: 26.0.3([email protected])+ mime-types:+ specifier: 3.0.2+ version: 3.0.2+ node-html-parser:+ specifier: 7.1.0+ version: 7.1.0+ sanitize-filename:+ specifier: 1.6.4+ version: 1.6.4+ sanitize-html:+ specifier: 2.17.2+ version: 2.17.2+ strip-bom:+ specifier: 5.0.0+ version: 5.0.0+ sucrase:+ specifier: 3.35.1+ version: 3.35.1+ unescape:+ specifier: 1.0.1+ version: 1.0.1+ devDependencies:+ '@types/escape-html':+ specifier: 1.0.4+ version: 1.0.4+ '@types/mime-types':+ specifier: 3.0.1+ version: 3.0.1+ '@types/sanitize-html':+ specifier: 2.16.1+ version: 2.16.1+packages/turndown-plugin-gfm:devDependencies:happy-dom:@@@ -18267,23 -17821,7 +18089,23 @@@ snapshots'@popperjs/[email protected]': {}- '@preact/[email protected](@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':++ '@preact/[email protected](@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ dependencies:+ '@babel/core': 7.29.0+ '@babel/plugin-transform-react-jsx': 7.27.1(@babel/[email protected])+ '@babel/plugin-transform-react-jsx-development': 7.27.1(@babel/[email protected])- '@prefresh/vite': 2.4.12([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))++ '@prefresh/vite': 2.4.12([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ '@rollup/pluginutils': 4.2.1+ babel-plugin-transform-hook-names: 1.0.2(@babel/[email protected])+ debug: 4.4.3+ picocolors: 1.1.1- vite: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- vite-prerender-plugin: 0.5.11([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))++ vite: 8.0.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])++ vite-prerender-plugin: 0.5.11([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ transitivePeerDependencies:+ - preact+ - supports-color+- '@preact/[email protected](@babel/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@preact/[email protected](@babel/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@babel/core': 7.29.0'@babel/plugin-transform-react-jsx': 7.27.1(@babel/[email protected])