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
feat(search): structured highlight token info
perfectra1nea36a2430e69
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex ff98a71750..cacc821b05 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -232,6 +232,16 @@ export interface SubtreeSizeResponse {subTreeSize: number;}+/**+ * A single token to highlight in search results, tagged with how it should be+ * matched. `plain` tokens are matched literally (case-insensitively); `regex`+ * tokens (produced by the `%=` operator) are compiled to a regular expression.+ */+export interface HighlightedTokenInfo {+ token: string;+ type: "plain" | "regex";+}+export interface SimilarNote {score: number;notePath: string[];diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.tsindex a6e74d8197..ef0c68c49b 100644--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts@@ -90,6 +90,12 @@ class NoteContentFulltextExp extends Expression {if (!searchContext.highlightedTokens.includes(token)) {searchContext.highlightedTokens.push(token);}++ if (this.operator === "%=") {+ // Regex operator: tag each token so snippet highlighting matches it+ // as a RegExp rather than literal text.+ searchContext.regexTokens.add(token);+ }}const resultNoteSet = new NoteSet();diff --git a/packages/trilium-core/src/services/search/search_context.spec.ts b/packages/trilium-core/src/services/search/search_context.spec.tsindex 9e1c252df9..00bfd60b67 100644--- a/packages/trilium-core/src/services/search/search_context.spec.ts+++ b/packages/trilium-core/src/services/search/search_context.spec.ts@@ -147,6 +147,28 @@ describe("SearchContext", () => {});});+ describe("getHighlightedTokenInfos", () => {+ it("starts with an empty regexTokens set", () => {+ const ctx = new SearchContext();++ expect(ctx.regexTokens.size).toBe(0);+ expect(ctx.getHighlightedTokenInfos()).toEqual([]);+ });++ it("tags each highlighted token as regex or plain based on regexTokens membership", () => {+ const ctx = new SearchContext();++ ctx.highlightedTokens.push("hello", "wor.d", "world");+ ctx.regexTokens.add("wor.d");++ expect(ctx.getHighlightedTokenInfos()).toEqual([+ { token: "hello", type: "plain" },+ { token: "wor.d", type: "regex" },+ { token: "world", type: "plain" }+ ]);+ });+ });+describe("addError / hasError / getError", () => {it("records the first error and ignores subsequent ones", () => {const ctx = new SearchContext();diff --git a/packages/trilium-core/src/services/search/search_context.ts b/packages/trilium-core/src/services/search/search_context.tsindex 8a029c5850..f8aa027605 100644--- a/packages/trilium-core/src/services/search/search_context.ts+++ b/packages/trilium-core/src/services/search/search_context.ts@@ -1,5 +1,7 @@"use strict";+import type { HighlightedTokenInfo } from "@triliumnext/commons";+import hoistedNoteService from "../hoisted_note.js";import optionService from "../options.js";import { betterQuality, type ContentMatchQuality } from "./match_quality.js";@@ -24,6 +26,11 @@ class SearchContext {/** When true, skip the two-phase fuzzy fallback and use the single-token fast path. */autocomplete: boolean;highlightedTokens: string[];+ /**+ * Subset of {@link highlightedTokens} that came from the `%=` (regex) operator+ * and must be matched as regular expressions rather than literal text.+ */+ regexTokens: Set<string>;originalQuery: string;fulltextQuery: string;dbLoadNeeded: boolean;@@ -63,6 +70,7 @@ class SearchContext {this.enableFuzzyMatching = true; // Default to true if option not yet initialized}this.highlightedTokens = [];+ this.regexTokens = new Set();this.originalQuery = "";this.fulltextQuery = ""; // complete fulltext part// if true, becca does not have (up-to-date) information needed to process the query@@ -81,6 +89,17 @@ class SearchContext {this.contentMatches.set(noteId, existing ? betterQuality(existing, quality) : quality);}+ /**+ * Maps {@link highlightedTokens} to structured token infos, tagging each token+ * as `regex` when it was collected from a `%=` operator and `plain` otherwise.+ */+ getHighlightedTokenInfos(): HighlightedTokenInfo[] {+ return this.highlightedTokens.map((token) => ({+ token,+ type: this.regexTokens.has(token) ? "regex" : "plain"+ }));+ }+addError(error: string) {// we record only the first error, subsequent ones are usually a consequence of the firstif (!this.error) {diff --git a/packages/trilium-core/src/services/search/services/parse.ts b/packages/trilium-core/src/services/search/services/parse.tsindex b579317540..ab81133d7d 100644--- a/packages/trilium-core/src/services/search/services/parse.ts+++ b/packages/trilium-core/src/services/search/services/parse.ts@@ -286,6 +286,12 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelsearchContext.highlightedTokens.push(comparedValue);+ if (operator === "%=") {+ // Regex operator: the compared value is a pattern, tag it so snippet+ // highlighting matches it as a RegExp rather than literal text.+ searchContext.regexTokens.add(comparedValue);+ }+if (searchContext.fuzzyAttributeSearch && operator === "=") {operator = "*=*";}diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.tsindex ddc9a254a3..83c0cfe53c 100644--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@ -1,5 +1,5 @@+import type { HighlightedTokenInfo } from "@triliumnext/commons";import { extractLlmChatText } from "@triliumnext/commons/src/lib/llm/extract_chat_text.js";-import normalizeString from "normalize-strings";import striptags from "striptags";import becca from "../../../becca/becca.js";@@ -10,7 +10,7 @@ import { getLog } from "../../log.js";import protectedSessionService from "../../protected_session.js";import scriptService from "../../script.js";import { isScriptingEnabled } from "../../scripting_guard.js";-import { escapeHtml, escapeRegExp } from "../../utils/index.js";+import { escapeHtml, escapeRegExp, normalizePreservingLength } from "../../utils/index.js";import type Expression from "../expressions/expression.js";import SearchContext from "../search_context.js";import SearchResult from "../search_result.js";@@ -20,21 +20,32 @@ import parse from "./parse.js";import type { SearchParams, TokenStructure } from "./types.js";import { getSql } from "../../sql/index.js";+/** Cap on marker wraps per snippet field per token, bounding pathological regex patterns. */+const MAX_HIGHLIGHT_WRAPS = 50;+export interface SearchNoteResult {searchResultNoteIds: string[];highlightedTokens: string[];+ /**+ * Structured highlight tokens (additive). Empty for script-based searches, which+ * have no lexed tokens. {@link highlightedTokens} is left untouched — it is part+ * of the public scripting API.+ */+ highlightedTokenInfos: HighlightedTokenInfo[];error: string | null;}export const EMPTY_RESULT: SearchNoteResult = {searchResultNoteIds: [],highlightedTokens: [],+ highlightedTokenInfos: [],error: null};function searchFromNote(note: BNote): SearchNoteResult {let searchResultNoteIds;let highlightedTokens: string[];+ let highlightedTokenInfos: HighlightedTokenInfo[];const searchScript = note.getRelationValue("searchScript");const searchString = note.getLabelValue("searchString") || "";@@ -43,6 +54,7 @@ function searchFromNote(note: BNote): SearchNoteResult {if (searchScript) {searchResultNoteIds = searchFromRelation(note, "searchScript");highlightedTokens = [];+ highlightedTokenInfos = [];} else {const searchContext = new SearchContext({fastSearch: note.hasLabel("fastSearch"),@@ -59,6 +71,7 @@ function searchFromNote(note: BNote): SearchNoteResult {searchResultNoteIds = findResultsWithQuery(searchString, searchContext).map((sr) => sr.noteId);highlightedTokens = searchContext.highlightedTokens;+ highlightedTokenInfos = searchContext.getHighlightedTokenInfos();error = searchContext.getError();}@@ -67,6 +80,7 @@ function searchFromNote(note: BNote): SearchNoteResult {return {searchResultNoteIds: searchResultNoteIds.filter((resultNoteId) => !["root", note.noteId].includes(resultNoteId)),highlightedTokens,+ highlightedTokenInfos,error};}@@ -466,12 +480,14 @@ function getTextRepresentationForNote(note: BNote): string | null {return row?.textRepresentation ?? null;}-function extractContentSnippet(noteId: string, searchTokens: string[], maxLength: number = 200): string {+function extractContentSnippet(noteId: string, searchTokens: HighlightedTokenInfo[] | string[], maxLength: number = 200): string {const note = becca.notes[noteId];if (!note) {return "";}+ const tokenInfos = toTokenInfos(searchTokens);+try {let content: string | undefined;@@ -523,14 +539,14 @@ function extractContentSnippet(noteId: string, searchTokens: string[], maxLengthreturn "";}- // Try to find a snippet around the first matching token- const normalizedContent = normalizeString(content.toLowerCase());+ // Try to find a snippet around the first matching token. Positions are found+ // on a length-preserving normalization so they slice the original 1:1.+ const normalizedContent = normalizePreservingLength(content);let snippetStart = 0;let matchFound = false;- for (const token of searchTokens) {- const normalizedToken = normalizeString(token.toLowerCase());- const matchIndex = normalizedContent.indexOf(normalizedToken);+ for (const info of tokenInfos) {+ const matchIndex = tokenInfoFirstIndex(info, normalizedContent);if (matchIndex !== -1) {// Center the snippet around the match@@ -547,13 +563,12 @@ function extractContentSnippet(noteId: string, searchTokens: string[], maxLengthconst lines = snippet.split('\n');if (lines.length > 4) {// Find which lines contain the search tokens to ensure they're included- const normalizedLines = lines.map(line => normalizeString(line.toLowerCase()));- const normalizedTokens = searchTokens.map(token => normalizeString(token.toLowerCase()));+ const normalizedLines = lines.map((line) => normalizePreservingLength(line));// Find the first line that contains a search tokenlet firstMatchLine = -1;for (let i = 0; i < normalizedLines.length; i++) {- if (normalizedTokens.some(token => normalizedLines[i].includes(token))) {+ if (tokenInfos.some((info) => tokenInfoMatches(info, normalizedLines[i]))) {firstMatchLine = i;break;}@@ -601,12 +616,14 @@ function extractContentSnippet(noteId: string, searchTokens: string[], maxLength}}-function extractAttributeSnippet(noteId: string, searchTokens: string[], maxLength: number = 200): string {+function extractAttributeSnippet(noteId: string, searchTokens: HighlightedTokenInfo[] | string[], maxLength: number = 200): string {const note = becca.notes[noteId];if (!note) {return "";}+ const tokenInfos = toTokenInfos(searchTokens);+try {// Get all attributes for this noteconst attributes = note.getAttributes();@@ -623,10 +640,10 @@ function extractAttributeSnippet(noteId: string, searchTokens: string[], maxLengconst attrType = attr.type || "";// Check if any search token matches the attribute name or value- const hasMatch = searchTokens.some(token => {- const normalizedToken = normalizeString(token.toLowerCase());- return attrName.includes(normalizedToken) || attrValue.includes(normalizedToken);- });+ const normalizedName = normalizePreservingLength(attrName);+ const normalizedValue = normalizePreservingLength(attrValue);+ const hasMatch = tokenInfos.some((info) =>+ tokenInfoMatches(info, normalizedName) || tokenInfoMatches(info, normalizedValue));if (hasMatch) {matchingAttributes.push({@@ -724,19 +741,12 @@ function searchNotesForAutocomplete(query: string, fastSearch: boolean = true) {}/**+ * @param tokens the tokens to highlight, either legacy plain strings or structured+ * {@link HighlightedTokenInfo}s (regex-aware). Legacy strings are treated as plain.* @param ignoreInternalAttributes whether to ignore certain attributes from the search such as ~internalLink.*/-function highlightSearchResults(searchResults: SearchResult[], highlightedTokens: string[], ignoreInternalAttributes = false) {- highlightedTokens = Array.from(new Set(highlightedTokens));-- // we remove < signs because they can cause trouble in matching and overwriting existing highlighted chunks- // which would make the resulting HTML string invalid.- // { and } are used for marking <b> and </b> tag (to avoid matches on single 'b' character)- // < and > are used for marking <small> and </small>- highlightedTokens = highlightedTokens.map((token) => token.replace(/[<>{}]/g, "")).filter((token) => !!token?.trim());-- // sort by the longest, so we first highlight the longest matches- highlightedTokens.sort((a, b) => (a.length > b.length ? -1 : 1));+function highlightSearchResults(searchResults: SearchResult[], tokens: HighlightedTokenInfo[] | string[], ignoreInternalAttributes = false) {+ const tokenInfos = normalizeHighlightTokens(tokens);for (const result of searchResults) {result.highlightedNotePathTitle = result.notePathTitle.replace(/[<{}]/g, "");@@ -758,50 +768,11 @@ function highlightSearchResults(searchResults: SearchResult[], highlightedTokens}}- function wrapText(text: string, start: number, length: number, prefix: string, suffix: string) {- return text.substring(0, start) + prefix + text.substr(start, length) + suffix + text.substring(start + length);- }-- for (const token of highlightedTokens) {- if (!token) {- // Avoid empty tokens, which might cause an infinite loop.- continue;- }-+ for (const tokenInfo of tokenInfos) {for (const result of searchResults) {- // Reset token- const tokenRegex = new RegExp(escapeRegExp(token), "gi");- let match;-- // Highlight in note path title- if (result.highlightedNotePathTitle) {- const titleRegex = new RegExp(escapeRegExp(token), "gi");- while ((match = titleRegex.exec(normalizeString(result.highlightedNotePathTitle))) !== null) {- result.highlightedNotePathTitle = wrapText(result.highlightedNotePathTitle, match.index, token.length, "{", "}");- // 2 characters are added, so we need to adjust the index- titleRegex.lastIndex += 2;- }- }-- // Highlight in content snippet- if (result.highlightedContentSnippet) {- const contentRegex = new RegExp(escapeRegExp(token), "gi");- while ((match = contentRegex.exec(normalizeString(result.highlightedContentSnippet))) !== null) {- result.highlightedContentSnippet = wrapText(result.highlightedContentSnippet, match.index, token.length, "{", "}");- // 2 characters are added, so we need to adjust the index- contentRegex.lastIndex += 2;- }- }-- // Highlight in attribute snippet- if (result.highlightedAttributeSnippet) {- const attributeRegex = new RegExp(escapeRegExp(token), "gi");- while ((match = attributeRegex.exec(normalizeString(result.highlightedAttributeSnippet))) !== null) {- result.highlightedAttributeSnippet = wrapText(result.highlightedAttributeSnippet, match.index, token.length, "{", "}");- // 2 characters are added, so we need to adjust the index- attributeRegex.lastIndex += 2;- }- }+ result.highlightedNotePathTitle = highlightField(result.highlightedNotePathTitle, tokenInfo);+ result.highlightedContentSnippet = highlightField(result.highlightedContentSnippet, tokenInfo);+ result.highlightedAttributeSnippet = highlightField(result.highlightedAttributeSnippet, tokenInfo);}}@@ -836,3 +807,109 @@ export default {extractAttributeSnippet,highlightSearchResults};++/** Widens a legacy `string[]` (all plain) or a structured token-info list to token infos. */+function toTokenInfos(tokens: HighlightedTokenInfo[] | string[]): HighlightedTokenInfo[] {+ return tokens.map((token) => (typeof token === "string" ? { token, type: "plain" } : token));+}++/** Index of the first match of a token within already-normalized text, or -1 if none. */+function tokenInfoFirstIndex(info: HighlightedTokenInfo, normalizedText: string): number {+ if (info.type === "regex") {+ try {+ const match = new RegExp(info.token, "gi").exec(normalizedText);+ return match ? match.index : -1;+ } catch {+ return -1; // Skip invalid regex patterns.+ }+ }++ return normalizedText.indexOf(normalizePreservingLength(info.token));+}++/** Whether a token matches anywhere within already-normalized text. */+function tokenInfoMatches(info: HighlightedTokenInfo, normalizedText: string): boolean {+ return tokenInfoFirstIndex(info, normalizedText) !== -1;+}++/**+ * Normalizes the highlight token input for {@link highlightSearchResults}: widens+ * legacy strings to plain token infos, strips marker/angle characters from plain+ * tokens (regex patterns are kept verbatim), drops blanks, dedupes, and sorts+ * longest-first so longer matches win before shorter ones.+ */+function normalizeHighlightTokens(tokens: HighlightedTokenInfo[] | string[]): HighlightedTokenInfo[] {+ const seen = new Set<string>();+ const result: HighlightedTokenInfo[] = [];++ for (const info of toTokenInfos(tokens)) {+ // { } are used as <b>/</b> markers and < can break the surrounding HTML, so we+ // strip them from plain tokens; regex patterns keep them (e.g. `a{2}` quantifiers).+ const token = info.type === "regex" ? info.token : info.token.replace(/[<>{}]/g, "");++ if (!token.trim() || seen.has(token)) {+ continue;+ }++ seen.add(token);+ result.push({ token, type: info.type });+ }++ result.sort((a, b) => (a.token.length > b.token.length ? -1 : 1));++ return result;+}++/** Builds the case-insensitive matching regex for a token, or null for an invalid regex pattern. */+function buildHighlightRegex(info: HighlightedTokenInfo): RegExp | null {+ if (info.type === "regex") {+ try {+ return new RegExp(info.token, "gi");+ } catch {+ return null; // Skip invalid regex patterns.+ }+ }++ return new RegExp(escapeRegExp(info.token), "gi");+}++/**+ * Wraps every match of one token in a single field with `{`/`}` markers (later+ * turned into `<b>`/`</b>`). Match positions are found on a length-preserving+ * normalization so they align 1:1 with the original field. The wrap count is+ * capped to bound pathological regex patterns, and zero-width matches break the+ * loop rather than spin forever.+ */+function highlightField(field: string | undefined, info: HighlightedTokenInfo): string | undefined {+ if (!field) {+ return field;+ }++ const regex = buildHighlightRegex(info);+ if (!regex) {+ return field;+ }++ let match: RegExpExecArray | null;+ let wraps = 0;+ while ((match = regex.exec(normalizePreservingLength(field))) !== null) {+ const matchLength = match[0].length;+ if (matchLength === 0) {+ break; // Zero-width match can't be highlighted; avoid an infinite loop.+ }++ field = wrapText(field, match.index, matchLength, "{", "}");+ // Two marker characters were inserted, so advance past them as well.+ regex.lastIndex += 2;++ if (++wraps >= MAX_HIGHLIGHT_WRAPS) {+ break;+ }+ }++ return field;+}++function wrapText(text: string, start: number, length: number, prefix: string, suffix: string) {+ return text.substring(0, start) + prefix + text.substr(start, length) + suffix + text.substring(start + length);+}diff --git a/packages/trilium-core/src/services/search/services/search_highlight.spec.ts b/packages/trilium-core/src/services/search/services/search_highlight.spec.tsnew file mode 100644index 0000000000..9314472ebb--- /dev/null+++ b/packages/trilium-core/src/services/search/services/search_highlight.spec.ts@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import BBranch from "../../../becca/entities/bbranch.js";+import BNote from "../../../becca/entities/bnote.js";+import { note, NoteBuilder } from "../../../test/becca_mocking.js";+import { normalizePreservingLength } from "../../utils/index.js";+import SearchResult from "../search_result.js";+import searchService from "./search.js";++let rootNote: NoteBuilder;++// "cafe" + combining acute accent (U+0301) — an NFD-decomposed "café".+const DECOMPOSED_CAFE = "café";++function makeResult(title: string, snippet: string): SearchResult {+ const child = note(title);+ rootNote.child(child);+ const result = new SearchResult(["root", child.note.noteId]);+ result.contentSnippet = snippet;+ return result;+}++describe("normalizePreservingLength", () => {+ it("keeps ligatures that a naive stripper would expand (length preserved)", () => {+ for (const s of ["straße", "æther", "džungla", "file"]) {+ expect(normalizePreservingLength(s)).toHaveLength(s.length);+ }+ });++ it("strips diacritics from precomposed characters 1:1", () => {+ expect(normalizePreservingLength("café")).toBe("cafe");+ expect(normalizePreservingLength("Ñandú")).toBe("nandu");+ // İ lowercases to "i̇" (2 code units) under a naive lowercase; the NFD-strip+ // removes the dot first so it stays a single "i" and length is preserved.+ expect(normalizePreservingLength("İ")).toBe("i");+ });++ it("preserves length for NFD-decomposed content (keeps bare combining marks)", () => {+ expect(normalizePreservingLength(DECOMPOSED_CAFE)).toHaveLength(DECOMPOSED_CAFE.length);+ });++ it("preserves length for astral (surrogate-pair) characters", () => {+ const withEmoji = "a\u{1F600}b";+ expect(normalizePreservingLength(withEmoji)).toHaveLength(withEmoji.length);+ });+});++describe("highlightSearchResults", () => {+ beforeEach(() => {+ becca.reset();+ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({ branchId: "none_root", noteId: "root", parentNoteId: "none", notePosition: 10 });+ });++ it("wraps a plain token in <b> markers", () => {+ const result = makeResult("Note", "hello match world");+ searchService.highlightSearchResults([result], ["match"]);+ expect(result.highlightedContentSnippet).toBe("hello <b>match</b> world");+ });++ it("aligns markers correctly past a ligature that would shift a length-changing normalizer", () => {+ const result = makeResult("Note", "straße match");+ searchService.highlightSearchResults([result], ["match"]);+ expect(result.highlightedContentSnippet).toBe("straße <b>match</b>");+ });++ it("aligns markers correctly past NFD-decomposed content (no index drift, no mid-marker split)", () => {+ const result = makeResult("Note", `${DECOMPOSED_CAFE} match`);+ searchService.highlightSearchResults([result], ["match"]);+ expect(result.highlightedContentSnippet).toBe(`${DECOMPOSED_CAFE} <b>match</b>`);+ });++ it("highlights matches of a regex token via HighlightedTokenInfo", () => {+ const result = makeResult("Note", "coool result");+ searchService.highlightSearchResults([result], [{ token: "co+l", type: "regex" }]);+ expect(result.highlightedContentSnippet).toBe("<b>coool</b> result");+ });++ it("skips invalid regex patterns instead of throwing", () => {+ const result = makeResult("Note", "plain text");+ expect(() =>+ searchService.highlightSearchResults([result], [{ token: "(unclosed", type: "regex" }])+ ).not.toThrow();+ expect(result.highlightedContentSnippet).toBe("plain text");+ });+});diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.tsindex 9ad1e0b34b..822b1030bf 100644--- a/packages/trilium-core/src/services/utils/index.ts+++ b/packages/trilium-core/src/services/utils/index.ts@@ -75,6 +75,31 @@ export function normalize(str: string) {return removeDiacritic(str).toLowerCase();}+/**+ * Diacritic-stripping + lowercasing normalizer that is GUARANTEED to preserve the+ * original code-unit length, so a position found in the normalized string maps 1:1+ * onto the original string for slicing/highlighting. This is what the search+ * snippet/highlight index math relies on: it finds match offsets on the normalized+ * text but inserts markers into (or slices) the original text at the same offsets.+ *+ * Each character (Unicode code point) is transformed individually; when the+ * transformed result is not the same code-unit length as the source character —+ * a bare combining mark that would vanish, or (hypothetically) a ligature that+ * would expand — the original character is kept instead. This trades perfect+ * folding of already-decomposed content for a hard length invariant.+ */+export function normalizePreservingLength(str: string) {+ let result = "";+ for (const char of str) {+ const transformed = removeDiacritic(char).toLowerCase();+ // Keep the transform only when it stays the same code-unit length as the+ // source character, otherwise index alignment against the original breaks.+ result += transformed.length === char.length ? transformed : char;+ }++ return result;+}+/*** Normalizes URL by removing trailing slashes and fixing double slashes.* Preserves the protocol (http://, https://) but removes trailing slashes from the rest.