Skip to content

Build your personal knowledge base with Trilium Notes

refactor(core): integrate more utils into core

Elian Doran9c5bac5741f9
diff --git a/apps/server/src/routes/custom.ts b/apps/server/src/routes/custom.ts
index 5498ef6d06..46ee1b1888 100644
--- a/apps/server/src/routes/custom.ts
+++ b/apps/server/src/routes/custom.ts
@@ -1,3 +1,4 @@
+import { utils } from "@triliumnext/core";
import type { Request, Response, Router } from "express";
import becca from "../becca/becca.js";
@@ -6,7 +7,6 @@ import cls from "../services/cls.js";
import log from "../services/log.js";
import scriptService from "../services/script.js";
import sql from "../services/sql.js";
-import { normalizeCustomHandlerPattern,safeExtractMessageAndStackFromError } from "../services/utils.js";
import fileService from "./api/files.js";
function handleRequest(req: Request, res: Response) {
@@ -41,7 +41,7 @@ function handleRequest(req: Request, res: Response) {
}
// Get normalized patterns to handle both trailing slash cases
- const patterns = normalizeCustomHandlerPattern(attr.value);
+ const patterns = utils.normalizeCustomHandlerPattern(attr.value);
let match: RegExpMatchArray | null = null;
try {
@@ -54,7 +54,7 @@ function handleRequest(req: Request, res: Response) {
}
}
} catch (e: unknown) {
- const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);
+ const [errMessage, errStack] = utils.safeExtractMessageAndStackFromError(e);
log.error(`Testing path for label '${attr.attributeId}', regex '${attr.value}' failed with error: ${errMessage}, stack: ${errStack}`);
continue;
}
@@ -75,7 +75,7 @@ function handleRequest(req: Request, res: Response) {
res
});
} catch (e: unknown) {
- const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);
+ const [errMessage, errStack] = utils.safeExtractMessageAndStackFromError(e);
log.error(`Custom handler '${note.noteId}' failed with: ${errMessage}, ${errStack}`);
res.setHeader("Content-Type", "text/plain").status(500).send(errMessage);
}
diff --git a/apps/server/src/services/config.ts b/apps/server/src/services/config.ts
index 267b68e008..27643a79bf 100644
--- a/apps/server/src/services/config.ts
+++ b/apps/server/src/services/config.ts
@@ -19,12 +19,13 @@
* ╚════════════════════════════════════════════════════════════════════════════╝
*/
-import ini from "ini";
+import utils from "@triliumnext/core";
import fs from "fs";
-import dataDir from "./data_dir.js";
+import ini from "ini";
import path from "path";
+
+import dataDir from "./data_dir.js";
import resourceDir from "./resource_dir.js";
-import { envToBoolean, stringToInt } from "./utils.js";
/**
* Path to the sample configuration file that serves as a template for new installations.
@@ -253,7 +254,7 @@ function getIniSection(sectionName: string): IniConfigSection | undefined {
*/
function transformBoolean(value: unknown): boolean {
// First try the standard envToBoolean function which handles "true"/"false" strings
- const result = envToBoolean(String(value));
+ const result = utils.envToBoolean(String(value));
if (result !== undefined) return result;
// Handle numeric boolean values (both string and number types)
@@ -456,7 +457,7 @@ const configMapping = {
aliasEnvVars: ['TRILIUM_LOGGING_RETENTION_DAYS'],
iniGetter: () => getIniSection("Logging")?.retentionDays,
defaultValue: LOGGING_DEFAULT_RETENTION_DAYS,
- transformer: (value: unknown) => stringToInt(String(value)) ?? LOGGING_DEFAULT_RETENTION_DAYS
+ transformer: (value: unknown) => utils.stringToInt(String(value)) ?? LOGGING_DEFAULT_RETENTION_DAYS
}
}
};
diff --git a/apps/server/src/services/export/opml.ts b/apps/server/src/services/export/opml.ts
index 52e60a60f0..7d83a7d6f2 100644
--- a/apps/server/src/services/export/opml.ts
+++ b/apps/server/src/services/export/opml.ts
@@ -1,10 +1,9 @@
-"use strict";
+import { utils } from "@triliumnext/core";
+import type { Response } from "express";
-import { getContentDisposition, stripTags } from "../utils.js";
import becca from "../../becca/becca.js";
-import type TaskContext from "../task_context.js";
import type BBranch from "../../becca/entities/bbranch.js";
-import type { Response } from "express";
+import type TaskContext from "../task_context.js";
function exportToOpml(taskContext: TaskContext<"export">, branch: BBranch, version: string, res: Response) {
if (!["1.0", "2.0"].includes(version)) {
@@ -59,7 +58,7 @@ function exportToOpml(taskContext: TaskContext<"export">, branch: BBranch, versi
const filename = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.title}.opml`;
- res.setHeader("Content-Disposition", getContentDisposition(filename));
+ res.setHeader("Content-Disposition", utils.getContentDisposition(filename));
res.setHeader("Content-Type", "text/x-opml");
res.write(`<?xml version="1.0" encoding="UTF-8"?>
@@ -83,7 +82,7 @@ function exportToOpml(taskContext: TaskContext<"export">, branch: BBranch, versi
function prepareText(text: string) {
const newLines = text.replace(/(<p[^>]*>|<br\s*\/?>)/g, "\n").replace(/&nbsp;/g, " "); // nbsp isn't in XML standard (only HTML)
- const stripped = stripTags(newLines);
+ const stripped = utils.stripTags(newLines);
const escaped = escapeXmlAttribute(stripped);
diff --git a/apps/server/src/services/import/single.ts b/apps/server/src/services/import/single.ts
index 2a66164c9e..7fba5024a5 100644
--- a/apps/server/src/services/import/single.ts
+++ b/apps/server/src/services/import/single.ts
@@ -1,10 +1,10 @@
import type { NoteType } from "@triliumnext/commons";
-import { sanitize } from "@triliumnext/core";
+import { sanitize, utils } from "@triliumnext/core";
import type BNote from "../../becca/entities/bnote.js";
import imageService from "../../services/image.js";
import noteService from "../../services/notes.js";
-import { getNoteTitle, processStringOrBuffer } from "../../services/utils.js";
+import { processStringOrBuffer } from "../../services/utils.js";
import protectedSessionService from "../protected_session.js";
import type TaskContext from "../task_context.js";
import type { File } from "./common.js";
@@ -57,7 +57,7 @@ function importFile(taskContext: TaskContext<"importNotes">, file: File, parentN
const mime = mimeService.getMime(originalName) || file.mimetype;
const { note } = noteService.createNewNote({
parentNoteId: parentNote.noteId,
- title: getNoteTitle(originalName, mime === "application/pdf", { mime }),
+ title: utils.getNoteTitle(originalName, mime === "application/pdf", { mime }),
content: file.buffer,
isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),
type: "file",
@@ -72,7 +72,7 @@ function importFile(taskContext: TaskContext<"importNotes">, file: File, parentN
}
function importCodeNote(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
- const title = getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
+ const title = utils.getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
const content = processStringOrBuffer(file.buffer);
const detectedMime = mimeService.getMime(file.originalname) || file.mimetype;
const mime = mimeService.normalizeMimeType(detectedMime);
@@ -97,7 +97,7 @@ function importCodeNote(taskContext: TaskContext<"importNotes">, file: File, par
}
function importCustomType(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote, type: NoteType, mime: string) {
- const title = getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
+ const title = utils.getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
const content = processStringOrBuffer(file.buffer);
const { note } = noteService.createNewNote({
@@ -115,7 +115,7 @@ function importCustomType(taskContext: TaskContext<"importNotes">, file: File, p
}
function importPlainText(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
- const title = getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
+ const title = utils.getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
const plainTextContent = processStringOrBuffer(file.buffer);
const htmlContent = convertTextToHtml(plainTextContent);
@@ -150,7 +150,7 @@ function convertTextToHtml(text: string) {
}
function importMarkdown(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
- const title = getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
+ const title = utils.getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
const markdownContent = processStringOrBuffer(file.buffer);
let htmlContent = markdownService.renderToHtml(markdownContent, title);
@@ -179,7 +179,7 @@ function importHtml(taskContext: TaskContext<"importNotes">, file: File, parentN
// Try to get title from HTML first, fall back to filename
// We do this before sanitization since that turns all <h1>s into <h2>
const htmlTitle = importUtils.extractHtmlTitle(content);
- const title = htmlTitle || getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
+ const title = htmlTitle || utils.getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
content = importUtils.handleH1(content, title);
diff --git a/apps/server/src/services/import/zip.ts b/apps/server/src/services/import/zip.ts
index a20794305e..29fce3430a 100644
--- a/apps/server/src/services/import/zip.ts
+++ b/apps/server/src/services/import/zip.ts
@@ -1,7 +1,7 @@
import { ALLOWED_NOTE_TYPES, type NoteType } from "@triliumnext/commons";
-import { sanitize } from "@triliumnext/core";
+import { sanitize, utils } from "@triliumnext/core";
import path from "path";
import type { Stream } from "stream";
import yauzl from "yauzl";
@@ -14,7 +14,7 @@ import type BNote from "../../becca/entities/bnote.js";
import attributeService from "../../services/attributes.js";
import log from "../../services/log.js";
import noteService from "../../services/notes.js";
-import { getNoteTitle, newEntityId, processStringOrBuffer, removeFileExtension, unescapeHtml } from "../../services/utils.js";
+import { newEntityId, processStringOrBuffer, unescapeHtml } from "../../services/utils.js";
import type AttributeMeta from "../meta/attribute_meta.js";
import type NoteMeta from "../meta/note_meta.js";
import protectedSessionService from "../protected_session.js";
@@ -162,7 +162,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu
// in case we lack metadata, we treat e.g. "Programming.html" and "Programming" as the same note
// (one data file, the other directory for children)
- const filePathNoExt = removeFileExtension(filePath);
+ const filePathNoExt = utils.removeFileExtension(filePath);
if (filePathNoExt in createdPaths) {
return createdPaths[filePathNoExt];
@@ -234,7 +234,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu
return;
}
- const noteTitle = getNoteTitle(filePath, !!taskContext.data?.replaceUnderscoresWithSpaces, noteMeta);
+ const noteTitle = utils.getNoteTitle(filePath, !!taskContext.data?.replaceUnderscoresWithSpaces, noteMeta);
const parentNoteId = getParentNoteId(filePath, parentNoteMeta);
if (!parentNoteId) {
@@ -467,7 +467,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu
content = processStringOrBuffer(content);
}
- const noteTitle = getNoteTitle(filePath, taskContext.data?.replaceUnderscoresWithSpaces || false, noteMeta);
+ const noteTitle = utils.getNoteTitle(filePath, taskContext.data?.replaceUnderscoresWithSpaces || false, noteMeta);
content = processNoteContent(noteMeta, type, mime, content, noteTitle || "", filePath);
diff --git a/apps/server/src/services/script_context.ts b/apps/server/src/services/script_context.ts
index f6dc0f7800..25be301d19 100644
--- a/apps/server/src/services/script_context.ts
+++ b/apps/server/src/services/script_context.ts
@@ -1,6 +1,7 @@
-import { toObject } from "./utils.js";
-import BackendScriptApi from "./backend_script_api.js";
+import { utils } from "@triliumnext/core";
+
import type BNote from "../becca/entities/bnote.js";
+import BackendScriptApi from "./backend_script_api.js";
import type { ApiParams } from "./backend_script_api_interface.js";
type Module = {
@@ -16,8 +17,8 @@ class ScriptContext {
constructor(allNotes: BNote[], apiParams: ApiParams) {
this.allNotes = allNotes;
this.modules = {};
- this.notes = toObject(allNotes, (note) => [note.noteId, note]);
- this.apis = toObject(allNotes, (note) => [note.noteId, new BackendScriptApi(note, apiParams)]);
+ this.notes = utils.toObject(allNotes, (note) => [note.noteId, note]);
+ this.apis = utils.toObject(allNotes, (note) => [note.noteId, new BackendScriptApi(note, apiParams)]);
}
require(moduleNoteIds: string[]) {
diff --git a/apps/server/src/services/utils.spec.ts b/apps/server/src/services/utils.spec.ts
index 1a69d7dd17..e29c391c03 100644
--- a/apps/server/src/services/utils.spec.ts
+++ b/apps/server/src/services/utils.spec.ts
@@ -1,707 +1,9 @@
-import { describe, expect,it } from "vitest";
+import { describe, expect, it } from "vitest";
-import utils from "./utils.js";
-
-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");
- });
-});
+import utils from "./utils";
describe("#isDev", () => {
it("should export a boolean", () => {
expect(utils.isDev).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);
- });
-});
diff --git a/apps/server/src/services/utils.ts b/apps/server/src/services/utils.ts
index 70531a376f..e9f611f157 100644
--- a/apps/server/src/services/utils.ts
+++ b/apps/server/src/services/utils.ts
@@ -1,14 +1,10 @@
import { getCrypto,utils as coreUtils } from "@triliumnext/core";
import chardet from "chardet";
import crypto from "crypto";
-import { t } from "i18next";
import { release as osRelease } from "os";
import path from "path";
import stripBom from "strip-bom";
-import log from "./log.js";
-import type NoteMeta from "./meta/note_meta.js";
-
const osVersion = osRelease().split('.').map(Number);
export const isMac = process.platform === "darwin";
@@ -83,22 +79,6 @@ export function constantTimeCompare(a: string | null | undefined, b: string | nu
return crypto.timingSafeEqual(bufA, bufB);
}
-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;
-}
-
-export function stripTags(text: string) {
- return text.replace(/<(?:.|\n)*?>/gm, "");
-}
-
/** @deprecated */
export function getContentDisposition(filename: string) {
return coreUtils.getContentDisposition(filename);
@@ -124,37 +104,6 @@ export function formatDownloadTitle(fileName: string, type: string | null, mime:
return coreUtils.formatDownloadTitle(fileName, type, mime);
}
-export function removeFileExtension(filePath: string, mime?: string) {
- const extension = path.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 basename = path.basename(removeFileExtension(filePath, noteMeta?.mime));
- return replaceUnderscoresWithSpaces ? basename.replace(/_/g, " ").trim() : basename;
-}
-
/** @deprecated */
export function removeDiacritic(str: string) {
return coreUtils.removeDiacritic(str);
@@ -170,37 +119,6 @@ export function toMap<T extends Record<string, any>>(list: T[], key: keyof T) {
return coreUtils.toMap(list, key);
}
-// 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;
-}
-
/**
* Returns the directory for resources. On Electron builds this corresponds to the `resources` subdirectory inside the distributable package.
* On development builds, this simply refers to the src directory of the application.
@@ -220,48 +138,6 @@ export function getResourceDir() {
return path.join(__dirname, "..");
}
-// 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
- */
-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;
-}
-
/**
* For buffers, they are scanned for a supported encoding and decoded (UTF-8, UTF-16). In some cases, the BOM is also stripped.
*
@@ -291,82 +167,6 @@ export function processStringOrBuffer(data: string | Buffer | null) {
}
}
-/**
- * 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`;
-
-}
-
-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
-}
-
/** @deprecated */
export const escapeHtml = coreUtils.escapeHtml;
/** @deprecated */
@@ -394,13 +194,11 @@ export function waitForStreamToFinish(stream: any): Promise<void> {
export default {
compareVersions,
constantTimeCompare,
- envToBoolean,
escapeHtml,
escapeRegExp,
formatDownloadTitle,
fromBase64,
getContentDisposition,
- getNoteTitle,
getResourceDir,
hashedBlobId,
hmac,
@@ -413,19 +211,14 @@ export default {
md5,
newEntityId,
normalize,
- normalizeCustomHandlerPattern,
quoteRegex,
randomSecureToken,
randomString,
removeDiacritic,
- removeFileExtension,
replaceAll,
safeExtractMessageAndStackFromError,
- stripTags,
- slugify,
toBase64,
toMap,
- toObject,
unescapeHtml,
waitForStreamToFinish
};
diff --git a/apps/server/src/www.ts b/apps/server/src/www.ts
index ec3c31bbcf..a70281b179 100644
--- a/apps/server/src/www.ts
+++ b/apps/server/src/www.ts
@@ -1,4 +1,4 @@
-import { getMessagingProvider } from "@triliumnext/core";
+import { getMessagingProvider, utils } from "@triliumnext/core";
import type { Express } from "express";
import fs from "fs";
import http from "http";
@@ -12,7 +12,6 @@ import host from "./services/host.js";
import log from "./services/log.js";
import port from "./services/port.js";
import { getDbSize } from "./services/sql_init.js";
-import utils, { formatSize, formatUtcTime } from "./services/utils.js";
import WebSocketMessagingProvider from "./services/ws_messaging_provider.js";
const MINIMUM_NODE_VERSION = "20.0.0";
@@ -71,9 +70,9 @@ export default async function startTriliumServer() {
async function displayStartupMessage() {
log.info(`\n${LOGO.replace("[version]", appInfo.appVersion)}`);
log.info(`📦 Versions: app=${appInfo.appVersion} db=${appInfo.dbVersion} sync=${appInfo.syncVersion} clipper=${appInfo.clipperProtocolVersion}`);
- log.info(`🔧 Build: ${formatUtcTime(appInfo.buildDate)} (${appInfo.buildRevision.substring(0, 10)})`);
+ log.info(`🔧 Build: ${utils.formatUtcTime(appInfo.buildDate)} (${appInfo.buildRevision.substring(0, 10)})`);
log.info(`📂 Data dir: ${appInfo.dataDirectory}`);
- log.info(`⏰ UTC time: ${formatUtcTime(appInfo.utcDateTime)}`);
+ log.info(`⏰ UTC time: ${utils.formatUtcTime(appInfo.utcDateTime)}`);
// for perf. issues it's good to know the rough configuration
const cpuInfos = (await import("os")).cpus();
@@ -82,7 +81,7 @@ async function displayStartupMessage() {
const cpuModel = (cpuInfos[0].model || "").trimEnd();
log.info(`💻 CPU: ${cpuModel} (${cpuInfos.length}-core @ ${cpuInfos[0].speed} Mhz)`);
}
- log.info(`💾 DB size: ${formatSize(getDbSize() * 1024)}`);
+ log.info(`💾 DB size: ${utils.formatSize(getDbSize() * 1024)}`);
log.info("");
}
diff --git a/packages/trilium-core/src/services/utils/index.spec.ts b/packages/trilium-core/src/services/utils/index.spec.ts
index 368a81c035..295c172056 100644
--- a/packages/trilium-core/src/services/utils/index.spec.ts
+++ b/packages/trilium-core/src/services/utils/index.spec.ts
@@ -1,5 +1,5 @@
import { expect, describe, it } from "vitest";
-import { sanitizeAttributeName } from "./index";
+import * as utils from "./index";
// fn value, expected value
const testCases: [fnValue: string, expectedValue: string][] = [
@@ -30,8 +30,706 @@ describe("sanitizeAttributeName unit tests", () => {
testCases.forEach((testCase) => {
return it(`'${testCase[0]}' should return '${testCase[1]}'`, () => {
const [ value, expected ] = testCase;
- const actual = sanitizeAttributeName(value);
+ 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);
+ });
+});
diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.ts
index 74f47927a4..57401fa512 100644
--- a/packages/trilium-core/src/services/utils/index.ts
+++ b/packages/trilium-core/src/services/utils/index.ts
@@ -4,6 +4,7 @@ import { encodeBase64 } from "./binary";
import mimeTypes from "mime-types";
import escape from "escape-html";
import unescape from "unescape";
+import path from "path";
// TODO: Implement platform detection.
export const isElectron = false;
@@ -202,3 +203,200 @@ export function isEmptyOrWhitespace(str: string | null | undefined) {
export function escapeRegExp(str: string) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
+
+export function removeFileExtension(filePath: string, mime?: string) {
+ const extension = path.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 basename = path.basename(removeFileExtension(filePath, noteMeta?.mime));
+ return replaceUnderscoresWithSpaces ? basename.replace(/_/g, " ").trim() : basename;
+}
+
+// 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 --git a/packages/trilium-core/tsconfig.lib.json b/packages/trilium-core/tsconfig.lib.json
index ab39479e9b..84c5a86535 100644
--- a/packages/trilium-core/tsconfig.lib.json
+++ b/packages/trilium-core/tsconfig.lib.json
@@ -7,6 +7,7 @@
"outDir": "dist",
"tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo",
"emitDeclarationOnly": true,
+ "noEmitOnError": false,
"forceConsistentCasingInFileNames": true,
"types": []
},