Skip to content

Build your personal knowledge base with Trilium Notes

test(commons): improve coverage

Elian Doran960c8532dec1
diff --git a/packages/commons/src/lib/dayjs.spec.ts b/packages/commons/src/lib/dayjs.spec.ts
index 37d9ff9435..867f29dd26 100644
--- a/packages/commons/src/lib/dayjs.spec.ts
+++ b/packages/commons/src/lib/dayjs.spec.ts
@@ -8,7 +8,7 @@
/// <reference types="../../../../node_modules/dayjs/plugin/utc.d.ts" />
import { LOCALES } from "./i18n.js";
-import { DAYJS_LOADER, dayjs } from "./dayjs.js";
+import { DAYJS_LOADER, dayjs, setDayjsLocale } from "./dayjs.js";
import { describe, expect, it } from "vitest";
describe("dayjs", () => {
@@ -59,4 +59,20 @@ describe("dayjs", () => {
expect(utcDate.utcOffset()).toBe(0);
});
});
+
+ describe("setDayjsLocale", () => {
+ it("sets the locale when present in the loader", async () => {
+ await setDayjsLocale("en");
+ expect(dayjs.locale()).toBe("en");
+ });
+
+ it("leaves the locale unchanged when not present in the loader", async () => {
+ await setDayjsLocale("en");
+ expect(dayjs.locale()).toBe("en");
+
+ // "xx-not-a-locale" is not a key in DAYJS_LOADER, so the locale must stay as "en".
+ await setDayjsLocale("xx-not-a-locale" as never);
+ expect(dayjs.locale()).toBe("en");
+ });
+ });
});
diff --git a/packages/commons/src/lib/i18n.spec.ts b/packages/commons/src/lib/i18n.spec.ts
new file mode 100644
index 0000000000..8c2c55ac96
--- /dev/null
+++ b/packages/commons/src/lib/i18n.spec.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+
+import { getTesseractCode, LOCALES } from "./i18n.js";
+
+describe("getTesseractCode", () => {
+ it("returns the Tesseract code for a mapped locale", () => {
+ expect(getTesseractCode("en")).toBe("eng");
+ expect(getTesseractCode("de")).toBe("deu");
+ });
+
+ it("returns null for a found locale without a tesseractCode", () => {
+ expect(getTesseractCode("en_rtl")).toBe(null);
+ });
+
+ it("returns null for an unknown locale", () => {
+ expect(getTesseractCode("nonexistent-locale")).toBe(null);
+ });
+});
+
+describe("LOCALES", () => {
+ it("is a non-empty array sorted by name", () => {
+ expect(Array.isArray(LOCALES)).toBe(true);
+ expect(LOCALES.length).toBeGreaterThan(0);
+
+ const names = LOCALES.map((l) => l.name);
+ const sorted = [...names].sort((a, b) => a.localeCompare(b));
+ expect(names).toEqual(sorted);
+ });
+
+ it("contains an entry with id \"en\"", () => {
+ const en = LOCALES.find((l) => l.id === "en");
+ expect(en).toBeDefined();
+ expect(en?.name).toBe("English (United States)");
+ });
+});
diff --git a/packages/commons/src/lib/link_embed.spec.ts b/packages/commons/src/lib/link_embed.spec.ts
new file mode 100644
index 0000000000..8f21c400d3
--- /dev/null
+++ b/packages/commons/src/lib/link_embed.spec.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from "vitest";
+
+import { extractYouTubeVideoId, YOUTUBE_REGEX } from "./link_embed.js";
+
+describe("extractYouTubeVideoId", () => {
+ it("extracts the id from a standard watch URL", () => {
+ expect(extractYouTubeVideoId("https://www.youtube.com/watch?v=dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
+ });
+
+ it("extracts the id from a youtu.be short link", () => {
+ expect(extractYouTubeVideoId("https://youtu.be/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
+ });
+
+ it("extracts the id from an embed URL", () => {
+ expect(extractYouTubeVideoId("https://www.youtube.com/embed/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
+ });
+
+ it("extracts the id from a shorts URL", () => {
+ expect(extractYouTubeVideoId("https://www.youtube.com/shorts/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
+ });
+
+ it("extracts the id from a watch URL with extra query params around v=", () => {
+ expect(
+ extractYouTubeVideoId("https://www.youtube.com/watch?feature=share&v=dQw4w9WgXcQ&t=10s")
+ ).toBe("dQw4w9WgXcQ");
+ });
+
+ it("returns null for a non-YouTube URL", () => {
+ expect(extractYouTubeVideoId("https://example.com/foo")).toBeNull();
+ });
+});
+
+describe("YOUTUBE_REGEX", () => {
+ it("is a RegExp that matches a known YouTube URL", () => {
+ expect(YOUTUBE_REGEX).toBeInstanceOf(RegExp);
+
+ const match = "https://www.youtube.com/watch?v=dQw4w9WgXcQ".match(YOUTUBE_REGEX);
+ expect(match).not.toBeNull();
+ expect(match?.[1]).toBe("dQw4w9WgXcQ");
+ });
+});
diff --git a/packages/commons/src/lib/markdown_renderer.spec.ts b/packages/commons/src/lib/markdown_renderer.spec.ts
index c96f632b2c..1ee96ecfa4 100644
--- a/packages/commons/src/lib/markdown_renderer.spec.ts
+++ b/packages/commons/src/lib/markdown_renderer.spec.ts
@@ -1,5 +1,14 @@
import { describe, expect, it } from "vitest";
-import { extractCodeBlocks } from "./markdown_renderer.js";
+
+import { CustomMarkdownRenderer, extractCodeBlocks, renderToHtml } from "./markdown_renderer.js";
+import { DEFAULT_TASK_STATES, DONE_TASK_STATE, NONE_TASK_STATE } from "./task_states.js";
+
+/** Identity sanitizer so we can assert the raw rendered HTML. */
+const identity = (html: string) => html;
+
+function render(content: string, title = "", options: Partial<Parameters<typeof renderToHtml>[2]> = {}): string {
+ return renderToHtml(content, title, { sanitize: identity, ...options });
+}
describe("extractCodeBlocks", () => {
it("should extract a fenced code block", () => {
@@ -83,3 +92,330 @@ describe("extractCodeBlocks", () => {
expect(hasFencedBlock).toBe(true);
});
});
+
+describe("renderToHtml", () => {
+ describe("headings / handleH1", () => {
+ it("removes the first <h1> when its text equals the title", () => {
+ const html = render("# My Title\n\nbody", "My Title");
+ expect(html).not.toContain("<h1");
+ expect(html).not.toContain("<h2");
+ expect(html).toBe("<p>body</p>");
+ });
+
+ it("demotes a first <h1> whose text differs from the title to <h2>", () => {
+ const html = render("# Other\n\nbody", "My Title");
+ expect(html).toBe("<h2>Other</h2><p>body</p>");
+ });
+
+ it("demotes a second <h1> to <h2> as well", () => {
+ const html = render("# A\n\n# B", "A");
+ // First h1 ("A") equals title -> removed; second h1 ("B") -> demoted.
+ expect(html).toBe("<h2>B</h2>");
+ });
+
+ it("keeps the first <h1> as-is when demoteH1 is false", () => {
+ const html = render("# A\n\nbody", "X", { demoteH1: false });
+ expect(html).toBe("<h1>A</h1><p>body</p>");
+ });
+
+ it("decodes named/decimal/hex entities and preserves unknown ones in demoted headings", () => {
+ const html = render("# A &amp; B &#65; &#x41; &unknownent;", "X");
+ expect(html).toBe("<h2>A & B A A &unknownent;</h2>");
+ });
+
+ it("renders a non-h1 heading via the renderer (depth >= 2)", () => {
+ // CustomMarkdownRenderer.heading delegates depth>=2 to the base renderer.
+ const html = render("## sub heading", "irrelevant");
+ expect(html).toBe("<h2>sub heading</h2>");
+ });
+ });
+
+ describe("paragraphs", () => {
+ it("renders a paragraph trimmed of trailing whitespace", () => {
+ expect(render("hello world")).toBe("<p>hello world</p>");
+ });
+ });
+
+ describe("code fences (CustomMarkdownRenderer.code)", () => {
+ it("maps a known fence language to its CKEditor MIME class", () => {
+ const html = render("```javascript\nconst x = 1;\n```");
+ expect(html).toBe(
+ '<pre><code class="language-application-javascript-env-backend">const x = 1;</code></pre>'
+ );
+ });
+
+ it("falls back to the auto MIME for an unlabeled fence", () => {
+ const html = render("```\nplain\n```");
+ expect(html).toBe('<pre><code class="language-text-x-trilium-auto">plain</code></pre>');
+ });
+
+ it("falls back to the auto MIME for an unknown fence language", () => {
+ const html = render("```nonsenselang\nfoo\n```");
+ expect(html).toBe('<pre><code class="language-text-x-trilium-auto">foo</code></pre>');
+ });
+
+ it("preserves the mermaid fence language verbatim", () => {
+ const html = render("```mermaid\ngraph TD\n```");
+ expect(html).toBe('<pre><code class="language-mermaid">graph TD</code></pre>');
+ });
+
+ it("renders nothing (no <pre>) for an empty code block", () => {
+ const html = render("```js\n```");
+ expect(html).toBe("");
+ expect(html).not.toContain("<pre>");
+ });
+
+ it("restores double quotes after escaping inside a code block", () => {
+ const html = render("```javascript\nconst s = \"x\";\n```");
+ expect(html).toContain('const s = "x";');
+ expect(html).not.toContain("&quot;");
+ });
+ });
+
+ describe("inline code (codespan)", () => {
+ it("renders inline code with spellcheck disabled and escaped content", () => {
+ const html = render("use `foo > bar` here");
+ expect(html).toBe('<p>use <code spellcheck="false">foo &gt; bar</code> here</p>');
+ });
+ });
+
+ describe("lists", () => {
+ it("renders a task list with checkbox inputs and labels", () => {
+ const html = render("- [ ] a\n- [x] b");
+ expect(html).toContain('<ul class="todo-list">');
+ expect(html).toContain('<input type="checkbox"disabled="disabled">');
+ expect(html).toContain('<input type="checkbox"checked="checked" disabled="disabled">');
+ expect(html).toContain('<label class="todo-list__label">');
+ expect(html).toContain('<span class="todo-list__label__description">a</span>');
+ expect(html).toContain('<span class="todo-list__label__description">b</span>');
+ });
+
+ it("renders a non-task unordered list as a plain <ul>", () => {
+ const html = render("- one\n- two");
+ expect(html).toBe("<ul><li>one</li><li>two</li></ul>");
+ expect(html).not.toContain("todo-list");
+ });
+
+ it("renders an ordered list as a plain <ol>", () => {
+ const html = render("1. one\n2. two");
+ expect(html).toBe("<ol><li>one</li><li>two</li></ol>");
+ });
+
+ it("prepends the checkbox into the paragraph of a loose task item (text first token)", () => {
+ const html = render("- [ ] first\n\n- [x] second");
+ // Loose items wrap content in <p>; the checkbox is injected before the text.
+ expect(html).toContain(
+ '<span class="todo-list__label__description"><p><input type="checkbox"disabled="disabled">first</p></span>'
+ );
+ expect(html).toContain(
+ '<span class="todo-list__label__description"><p><input type="checkbox"checked="checked" disabled="disabled">second</p></span>'
+ );
+ });
+
+ it("prepends the checkbox to a loose task whose paragraph first inner token is not text", () => {
+ const html = render("- [ ] ![](http://x/y.png)\n\n- [x] b");
+ // The paragraph's first inner token is an image (not text), so only the
+ // paragraph-level text receives the checkbox prefix.
+ expect(html).toContain(
+ '<span class="todo-list__label__description"><p><input type="checkbox"disabled="disabled"><img src="http://x/y.png"></p></span>'
+ );
+ });
+
+ it("unshifts the checkbox as a text token for a loose task whose first token is a checkbox", () => {
+ // marked emits a `checkbox` token (not a paragraph) as the first token of a
+ // loose native task item — the checkbox HTML is unshifted before the body.
+ const html = render("- [ ] text\n\n more");
+ expect(html).toBe(
+ '<ul class="todo-list"><li><label class="todo-list__label">' +
+ '<span class="todo-list__label__description">' +
+ '<input type="checkbox"disabled="disabled"><p>text</p><p>more</p>' +
+ "</span></label></li></ul>"
+ );
+ });
+
+ it("unshifts a checked checkbox for a loose, checked native task item", () => {
+ const html = render("- [x] done\n\n more body");
+ expect(html).toContain(
+ '<span class="todo-list__label__description">' +
+ '<input type="checkbox"checked="checked" disabled="disabled"><p>done</p><p>more body</p></span>'
+ );
+ });
+
+ it("prepends the checkbox directly to a tight task item body", () => {
+ const html = render("- [ ] one");
+ expect(html).toBe(
+ '<ul class="todo-list"><li><label class="todo-list__label">' +
+ '<input type="checkbox"disabled="disabled">' +
+ '<span class="todo-list__label__description">one</span></label></li></ul>'
+ );
+ });
+ });
+
+ describe("custom task states", () => {
+ it("recognizes a custom [/] marker as a 'doing' task", () => {
+ const html = render("- [/] x", "", { taskStates: DEFAULT_TASK_STATES });
+ expect(html).toContain('data-trilium-task-state="doing"');
+ expect(html).toContain('<input type="checkbox"disabled="disabled">');
+ expect(html).toContain('<span class="todo-list__label__description">x</span>');
+ // The `[/]` marker must be stripped from the visible text.
+ expect(html).not.toContain("[/]");
+ });
+
+ it("recognizes a custom [?] (maybe) marker", () => {
+ const html = render("- [?] m", "", { taskStates: DEFAULT_TASK_STATES });
+ expect(html).toContain('data-trilium-task-state="maybe"');
+ expect(html).toContain('<span class="todo-list__label__description">m</span>');
+ });
+
+ it("recognizes a custom [-] (cancelled) marker", () => {
+ const html = render("- [-] c", "", { taskStates: DEFAULT_TASK_STATES });
+ expect(html).toContain('data-trilium-task-state="cancelled"');
+ expect(html).toContain('<span class="todo-list__label__description">c</span>');
+ });
+
+ it("strips the custom marker across nested tokens for a loose item", () => {
+ const html = render("- [/] x\n\n more text\n\n- [x] b", "", { taskStates: DEFAULT_TASK_STATES });
+ expect(html).toContain('data-trilium-task-state="doing"');
+ expect(html).toContain(
+ '<p><input type="checkbox"disabled="disabled">x</p><p>more text</p>'
+ );
+ expect(html).not.toContain("[/]");
+ });
+
+ it("uses the no-op detector when only anchor states are supplied (no custom symbols)", () => {
+ // Anchors use symbols " " and "x" which are filtered out, leaving an empty
+ // symbol map -> detector returns a no-op, so `- [/]` stays literal text.
+ const html = render("- [/] x", "", { taskStates: [NONE_TASK_STATE, DONE_TASK_STATE] });
+ expect(html).toBe("<ul><li>[/] x</li></ul>");
+ expect(html).not.toContain("todo-list");
+ expect(html).not.toContain("data-trilium-task-state");
+ });
+ });
+
+ describe("images (CustomMarkdownRenderer.image)", () => {
+ it("removes an empty alt attribute", () => {
+ const html = render("![](http://x/y.png)");
+ expect(html).toBe('<p><img src="http://x/y.png"></p>');
+ expect(html).not.toContain("alt");
+ });
+
+ it("keeps a non-empty alt attribute", () => {
+ const html = render("![cat](http://x/y.png)");
+ expect(html).toBe('<p><img src="http://x/y.png" alt="cat"></p>');
+ });
+ });
+
+ describe("blockquotes / admonitions (CustomMarkdownRenderer.blockquote)", () => {
+ it("renders a [!NOTE] admonition", () => {
+ expect(render("> [!NOTE]\n> body")).toBe('<aside class="admonition note"><p>body</p></aside>');
+ });
+
+ it("renders all of TIP/IMPORTANT/CAUTION/WARNING admonitions", () => {
+ expect(render("> [!TIP]\n> x")).toBe('<aside class="admonition tip"><p>x</p></aside>');
+ expect(render("> [!IMPORTANT]\n> x")).toBe('<aside class="admonition important"><p>x</p></aside>');
+ expect(render("> [!CAUTION]\n> x")).toBe('<aside class="admonition caution"><p>x</p></aside>');
+ expect(render("> [!WARNING]\n> x")).toBe('<aside class="admonition warning"><p>x</p></aside>');
+ });
+
+ it("renders an empty admonition with a non-breaking space inside", () => {
+ const html = render("> [!NOTE]");
+ expect(html).toBe('<aside class="admonition note">&nbsp;</aside>');
+ });
+
+ it("keeps an unknown admonition type as a normal blockquote", () => {
+ const html = render("> [!FOO]\n> body");
+ expect(html).toContain("<blockquote>");
+ expect(html).not.toContain("admonition");
+ expect(html).toContain("[!FOO]");
+ });
+
+ it("renders a plain blockquote", () => {
+ expect(render("> just quote")).toBe("<blockquote><p>just quote</p></blockquote>");
+ });
+ });
+
+ describe("formulas", () => {
+ it("renders an inline formula", () => {
+ expect(render("$x^2$")).toBe('<span class="math-tex">\\(x^2\\)</span>');
+ });
+
+ it("renders a block formula", () => {
+ expect(render("$$x$$")).toBe('<span class="math-tex">\\[x\\]</span>');
+ });
+
+ it("does not convert an escaped dollar to a formula", () => {
+ const html = render("price is \\$5 today");
+ expect(html).toContain("$5");
+ expect(html).not.toContain("math-tex");
+ });
+
+ it("does not convert a formula-like sequence inside inline code (codeMap path)", () => {
+ const html = render("use `$x$` and real $y$");
+ // The `$x$` inside the codespan stays literal; only the bare $y$ becomes a formula.
+ expect(html).toContain('<code spellcheck="false">$x$</code>');
+ expect(html).toContain('<span class="math-tex">\\(y\\)</span>');
+ });
+ });
+
+ describe("wiki links and transclusions", () => {
+ it("renders a wiki link with the default href format", () => {
+ const html = render("[[abc123]]");
+ expect(html).toBe('<p><a class="reference-link" href="/abc123">abc123</a></p>');
+ });
+
+ it("renders a wiki link with a custom href format", () => {
+ const html = render("[[abc123]]", "", { wikiLink: { formatHref: (id) => `#root/${id}` } });
+ expect(html).toBe('<p><a class="reference-link" href="#root/abc123">abc123</a></p>');
+ });
+
+ it("renders a transclusion with the default src format", () => {
+ const html = render("![[abc123]]");
+ expect(html).toBe('<p><img src="/abc123"></p>');
+ });
+
+ it("renders a transclusion with a custom src format", () => {
+ const html = render("![[abc123]]", "", { transclusion: { formatSrc: (id) => `/api/images/${id}` } });
+ expect(html).toBe('<p><img src="/api/images/abc123"></p>');
+ });
+ });
+
+ describe("footnotes", () => {
+ it("renders footnotes without throwing", () => {
+ const html = render("text[^1]\n\n[^1]: note");
+ expect(html).toContain("data-footnote-ref");
+ expect(html).toContain('id="footnote-1"');
+ expect(html).toContain("note");
+ });
+ });
+
+ describe("trailing transforms", () => {
+ it("adds a trailing semicolon to a style attribute on an <img>", () => {
+ const injectStyle = (html: string) => html.replace("<img ", '<img style="width:10px" ');
+ const html = renderToHtml("![cat](http://x/y.png)", "", { sanitize: injectStyle });
+ expect(html).toContain('style="width:10px;"');
+ });
+
+ it("removes the slash from a self-closing tag", () => {
+ const injectSelfClose = (html: string) => `${html}<hr custom="1" />`;
+ const html = renderToHtml("text", "", { sanitize: injectSelfClose });
+ expect(html).toContain('<hr custom="1">');
+ expect(html).not.toContain("/>");
+ });
+
+ it("normalizes a non-breaking space in the output to the &nbsp; entity", () => {
+ const nbsp = String.fromCharCode(0x00a0);
+ const injectNbsp = (html: string) => `${html}${nbsp}END`;
+ const out = renderToHtml("text", "", { sanitize: injectNbsp });
+ expect(out).toBe("<p>text</p>&nbsp;END");
+ expect(out).not.toContain(nbsp);
+ });
+ });
+
+ describe("custom renderer option", () => {
+ it("uses a caller-provided CustomMarkdownRenderer instance", () => {
+ const renderer = new CustomMarkdownRenderer({ async: false });
+ const html = render("# heading\n\nbody", "X", { renderer });
+ expect(html).toBe("<h2>heading</h2><p>body</p>");
+ });
+ });
+});
diff --git a/packages/commons/src/lib/markdown_renderer.ts b/packages/commons/src/lib/markdown_renderer.ts
index 2c7f5bcaae..f8f7b90b25 100644
--- a/packages/commons/src/lib/markdown_renderer.ts
+++ b/packages/commons/src/lib/markdown_renderer.ts
@@ -10,16 +10,20 @@ function escapeForCharClass(char: string): string {
}
function stripTaskMarkerFromTokens(tokens: Token[] | undefined, stripPattern: RegExp): void {
+ /* v8 ignore start -- defensive: renderToHtml always passes a non-empty token array */
if (!tokens || tokens.length === 0) {
return;
}
+ /* v8 ignore stop */
const first = tokens[0] as Token & { text?: string; raw?: string; tokens?: Token[] };
+ /* v8 ignore start -- defensive: the marker-bearing first token always has string text/raw */
if (typeof first.text === "string") {
first.text = first.text.replace(stripPattern, "");
}
if (typeof first.raw === "string") {
first.raw = first.raw.replace(stripPattern, "");
}
+ /* v8 ignore stop */
if (Array.isArray(first.tokens)) {
stripTaskMarkerFromTokens(first.tokens, stripPattern);
}
@@ -62,9 +66,11 @@ function createTaskStateDetector(states: TaskStateDef[]): (token: Token) => void
return;
}
const name = symbolToName.get(match[1]);
+ /* v8 ignore start -- defensive: match[1] is always a symbolToName key */
if (!name) {
return;
}
+ /* v8 ignore stop */
item.task = true;
item.checked = false;
item._taskState = name;
@@ -241,6 +247,7 @@ function restoreFromMap(text: string, map: Map<string, string>): string {
const pattern = [ ...map.keys() ]
.map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
.join("|");
+ /* v8 ignore next -- defensive: every regex match is a map key, so the ?? fallback is unreachable */
return text.replace(new RegExp(pattern, "g"), (match) => map.get(match) ?? match);
}
diff --git a/packages/commons/src/lib/marked_extensions.spec.ts b/packages/commons/src/lib/marked_extensions.spec.ts
index 963c0a4a71..64daba352a 100644
--- a/packages/commons/src/lib/marked_extensions.spec.ts
+++ b/packages/commons/src/lib/marked_extensions.spec.ts
@@ -1,6 +1,21 @@
import { describe, expect, it } from "vitest";
import { Marked } from "marked";
-import { createWikiLinkExtension, createTransclusionExtension } from "./marked_extensions.js";
+import {
+ createWikiLinkExtension,
+ createTransclusionExtension,
+ wikiLinkExtension,
+ transclusionExtension
+} from "./marked_extensions.js";
+
+interface ExtensionInternals {
+ start(src: string): number | undefined;
+ tokenizer(src: string): unknown;
+ renderer(token: { href: string; text?: string }): string;
+}
+
+function asInternal(extension: unknown): ExtensionInternals {
+ return extension as ExtensionInternals;
+}
describe("marked_extensions", () => {
describe("createWikiLinkExtension", () => {
@@ -93,4 +108,73 @@ describe("marked_extensions", () => {
expect(result).toContain('src="/api/images/x&quot;'); // Escaped version
});
});
+
+ describe("wikiLink start()", () => {
+ it("should return the index of the first '[[' marker", () => {
+ const src = "hello [[note]] world";
+ expect(asInternal(wikiLinkExtension).start(src)).toBe(src.indexOf("[["));
+ expect(asInternal(wikiLinkExtension).start(src)).toBe(6);
+ });
+
+ it("should return -1 when there is no '[[' marker", () => {
+ expect(asInternal(wikiLinkExtension).start("hello world")).toBe(-1);
+ });
+ });
+
+ describe("wikiLink tokenizer()", () => {
+ it("should produce a wikiLink token for a matching source", () => {
+ const token = asInternal(wikiLinkExtension).tokenizer("[[ note ]] rest");
+ expect(token).toEqual({
+ type: "wikiLink",
+ raw: "[[ note ]]",
+ text: "note",
+ href: "note"
+ });
+ });
+
+ it("should return undefined when the source does not match", () => {
+ expect(asInternal(wikiLinkExtension).tokenizer("not a wiki link")).toBeUndefined();
+ });
+ });
+
+ describe("transclusion start()", () => {
+ it("should return the index of the first '![[' marker", () => {
+ const src = "x ![[id]]";
+ expect(asInternal(transclusionExtension).start(src)).toBe(src.indexOf("![["));
+ expect(asInternal(transclusionExtension).start(src)).toBe(2);
+ });
+
+ it("should return undefined when there is no '![[' marker", () => {
+ expect(asInternal(transclusionExtension).start("no transclusion here")).toBeUndefined();
+ });
+ });
+
+ describe("transclusion tokenizer()", () => {
+ it("should produce a transclusion token for a matching source", () => {
+ const token = asInternal(transclusionExtension).tokenizer("![[ img ]] rest");
+ expect(token).toEqual({
+ type: "transclusion",
+ raw: "![[ img ]]",
+ href: "img"
+ });
+ });
+
+ it("should return undefined when the source does not match", () => {
+ expect(asInternal(transclusionExtension).tokenizer("plain text")).toBeUndefined();
+ });
+ });
+
+ describe("default formatHref / formatSrc", () => {
+ it("should default the wiki-link href to /${noteId}", () => {
+ const extension = createWikiLinkExtension();
+ const result = asInternal(extension).renderer({ href: "abc", text: "abc" });
+ expect(result).toBe('<a class="reference-link" href="/abc">abc</a>');
+ });
+
+ it("should default the transclusion src to /${noteId}", () => {
+ const extension = createTransclusionExtension();
+ const result = asInternal(extension).renderer({ href: "abc" });
+ expect(result).toBe('<img src="/abc">');
+ });
+ });
});
diff --git a/packages/commons/src/lib/mime_type.spec.ts b/packages/commons/src/lib/mime_type.spec.ts
new file mode 100644
index 0000000000..b748b04b42
--- /dev/null
+++ b/packages/commons/src/lib/mime_type.spec.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vitest";
+
+import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, MIME_TYPES_DICT, normalizeMimeTypeForCKEditor } from "./mime_type.js";
+
+describe("normalizeMimeTypeForCKEditor", () => {
+ it("collapses non-word characters and underscores into single dashes", () => {
+ expect(normalizeMimeTypeForCKEditor("text/x-c++src")).toBe("text-x-c-src");
+ expect(normalizeMimeTypeForCKEditor("application/javascript;env=backend")).toBe("application-javascript-env-backend");
+ expect(normalizeMimeTypeForCKEditor("a__b")).toBe("a-b");
+ });
+
+ it("lowercases the MIME type", () => {
+ expect(normalizeMimeTypeForCKEditor("TEXT/HTML")).toBe("text-html");
+ expect(normalizeMimeTypeForCKEditor("Text/X-CSrc")).toBe("text-x-csrc");
+ });
+});
+
+describe("getMimeTypeFromMarkdownName", () => {
+ it("returns the definition for a language tag with a single entry", () => {
+ const result = getMimeTypeFromMarkdownName("css");
+ expect(result).toBeDefined();
+ expect(result?.mime).toBe("text/css");
+ expect(result?.mdLanguageCode).toBe("css");
+ });
+
+ it("returns the first matching entry in dict order when multiple entries share a language tag", () => {
+ const result = getMimeTypeFromMarkdownName("javascript");
+ expect(result).toBeDefined();
+ expect(result?.mdLanguageCode).toBe("javascript");
+ // "JS backend" comes before "JS frontend" in the dictionary, so it wins.
+ expect(result?.title).toBe("JS backend");
+ expect(result?.mime).toBe("application/javascript;env=backend");
+ });
+
+ it("returns undefined for an unknown language tag", () => {
+ expect(getMimeTypeFromMarkdownName("definitely-not-a-language")).toBeUndefined();
+ });
+
+ it("returns the same cached reference across calls", () => {
+ const first = getMimeTypeFromMarkdownName("css");
+ const second = getMimeTypeFromMarkdownName("css");
+ expect(second).toBe(first);
+ });
+});
+
+describe("exports", () => {
+ it("exposes the auto MIME type pseudo-value", () => {
+ expect(MIME_TYPE_AUTO).toBe("text-x-trilium-auto");
+ });
+
+ it("exposes a non-empty frozen MIME types dictionary", () => {
+ expect(Array.isArray(MIME_TYPES_DICT)).toBe(true);
+ expect(MIME_TYPES_DICT.length).toBeGreaterThan(0);
+ expect(Object.isFrozen(MIME_TYPES_DICT)).toBe(true);
+ });
+});
diff --git a/packages/commons/src/lib/notes.spec.ts b/packages/commons/src/lib/notes.spec.ts
new file mode 100644
index 0000000000..a178b9e1ab
--- /dev/null
+++ b/packages/commons/src/lib/notes.spec.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from "vitest";
+
+import { getNoteIcon, NOTE_TYPE_ICONS } from "./notes.js";
+import { NoteType } from "./rows.js";
+
+function buildArgs(overrides: {
+ noteId?: string;
+ type?: NoteType;
+ mime?: string;
+ iconClass?: string | undefined;
+ workspaceIconClass?: string | undefined;
+ isFolder?: () => boolean;
+}) {
+ return {
+ noteId: "abc123",
+ type: "text" as NoteType,
+ mime: "",
+ iconClass: undefined,
+ workspaceIconClass: undefined,
+ isFolder: () => false,
+ ...overrides
+ };
+}
+
+describe("NOTE_TYPE_ICONS", () => {
+ it("maps note types to their boxicon classes", () => {
+ expect(NOTE_TYPE_ICONS.file).toBe("bx bx-file");
+ expect(NOTE_TYPE_ICONS.image).toBe("bx bx-image");
+ expect(NOTE_TYPE_ICONS.code).toBe("bx bx-code");
+ expect(NOTE_TYPE_ICONS.book).toBe("bx bx-book");
+ expect(NOTE_TYPE_ICONS.mermaid).toBe("bx bx-selection");
+ expect(NOTE_TYPE_ICONS.mindMap).toBe("bx bx-sitemap");
+ expect(NOTE_TYPE_ICONS.llmChat).toBe("bx bx-message-square-dots");
+ });
+});
+
+describe("getNoteIcon", () => {
+ it("returns the explicit iconClass when provided", () => {
+ const icon = getNoteIcon(buildArgs({ iconClass: "bx bx-custom", workspaceIconClass: "bx bx-ws" }));
+ expect(icon).toBe("bx bx-custom");
+ });
+
+ it("returns the workspaceIconClass when no iconClass is provided", () => {
+ const icon = getNoteIcon(buildArgs({ workspaceIconClass: "bx bx-workspace" }));
+ expect(icon).toBe("bx bx-workspace");
+ });
+
+ it("returns the home icon for the root note", () => {
+ const icon = getNoteIcon(buildArgs({ noteId: "root" }));
+ expect(icon).toBe("bx bx-home-alt-2");
+ });
+
+ it("returns the share icon for the _share note", () => {
+ const icon = getNoteIcon(buildArgs({ noteId: "_share", type: "doc" }));
+ expect(icon).toBe("bx bx-share-alt");
+ });
+
+ it("returns the folder icon for a text note that is a folder", () => {
+ const icon = getNoteIcon(buildArgs({ type: "text", isFolder: () => true }));
+ expect(icon).toBe("bx bx-folder");
+ });
+
+ it("returns the note icon for a text note that is not a folder", () => {
+ const icon = getNoteIcon(buildArgs({ type: "text", isFolder: () => false }));
+ expect(icon).toBe("bx bx-note");
+ });
+
+ it("returns the mime-specific icon for a code note whose mime has an icon", () => {
+ const icon = getNoteIcon(buildArgs({ type: "code", mime: "text/css" }));
+ expect(icon).toBe("bx bxs-file-css");
+ });
+
+ it("falls back to the code icon for a code note whose mime is not in the dictionary", () => {
+ const icon = getNoteIcon(buildArgs({ type: "code", mime: "text/x-unknownxyz" }));
+ expect(icon).toBe("bx bx-code");
+ });
+
+ it("falls back to the code icon for a code note whose mime has no icon", () => {
+ const icon = getNoteIcon(buildArgs({ type: "code", mime: "text/apl" }));
+ expect(icon).toBe("bx bx-code");
+ });
+
+ it("returns the video icon for a file note with a video mime", () => {
+ const icon = getNoteIcon(buildArgs({ type: "file", mime: "video/mp4" }));
+ expect(icon).toBe("bx bx-video");
+ });
+
+ it("returns the music icon for a file note with an audio mime", () => {
+ const icon = getNoteIcon(buildArgs({ type: "file", mime: "audio/mpeg" }));
+ expect(icon).toBe("bx bx-music");
+ });
+
+ it("returns the mapped file icon for a file note with a known mime", () => {
+ const icon = getNoteIcon(buildArgs({ type: "file", mime: "application/pdf" }));
+ expect(icon).toBe("bx bxs-file-pdf");
+ });
+
+ it("falls back to the file icon for a file note with an unmapped mime", () => {
+ const icon = getNoteIcon(buildArgs({ type: "file", mime: "text/plain" }));
+ expect(icon).toBe("bx bx-file");
+ });
+
+ it("returns the mapped image icon for an image note with a known mime", () => {
+ const icon = getNoteIcon(buildArgs({ type: "image", mime: "image/gif" }));
+ expect(icon).toBe("bx bxs-file-gif");
+ });
+
+ it("falls back to the image icon for an image note with an unmapped mime", () => {
+ const icon = getNoteIcon(buildArgs({ type: "image", mime: "image/png" }));
+ expect(icon).toBe("bx bx-image");
+ });
+
+ it("returns the note-type icon for any other type", () => {
+ const icon = getNoteIcon(buildArgs({ type: "book" }));
+ expect(icon).toBe("bx bx-book");
+ });
+});
diff --git a/packages/commons/src/lib/options_interface.spec.ts b/packages/commons/src/lib/options_interface.spec.ts
new file mode 100644
index 0000000000..41b849bb71
--- /dev/null
+++ b/packages/commons/src/lib/options_interface.spec.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+
+import { SYSTEM_MONOSPACE_FONT_STACK, SYSTEM_SANS_SERIF_FONT_STACK } from "./options_interface.js";
+
+describe("SYSTEM_SANS_SERIF_FONT_STACK", () => {
+ it("is a comma-joined font stack starting with system-ui and ending in sans-serif", () => {
+ expect(typeof SYSTEM_SANS_SERIF_FONT_STACK).toBe("string");
+
+ const fonts = SYSTEM_SANS_SERIF_FONT_STACK.split(",");
+ expect(fonts[0]).toBe("system-ui");
+ expect(fonts).toContain("sans-serif");
+ expect(fonts).toEqual([
+ "system-ui",
+ "-apple-system",
+ "BlinkMacSystemFont",
+ "Segoe UI",
+ "Cantarell",
+ "Ubuntu",
+ "Noto Sans",
+ "Helvetica",
+ "Arial",
+ "sans-serif",
+ "Apple Color Emoji",
+ "Segoe UI Emoji"
+ ]);
+ });
+});
+
+describe("SYSTEM_MONOSPACE_FONT_STACK", () => {
+ it("is a comma-joined font stack starting with ui-monospace and ending in monospace", () => {
+ expect(typeof SYSTEM_MONOSPACE_FONT_STACK).toBe("string");
+
+ const fonts = SYSTEM_MONOSPACE_FONT_STACK.split(",");
+ expect(fonts[0]).toBe("ui-monospace");
+ expect(fonts).toContain("monospace");
+ expect(fonts).toEqual([
+ "ui-monospace",
+ "SFMono-Regular",
+ "SF Mono",
+ "Consolas",
+ "Source Code Pro",
+ "Ubuntu Mono",
+ "Menlo",
+ "Liberation Mono",
+ "monospace"
+ ]);
+ });
+});
diff --git a/packages/commons/src/lib/rows.spec.ts b/packages/commons/src/lib/rows.spec.ts
new file mode 100644
index 0000000000..d3766a52d0
--- /dev/null
+++ b/packages/commons/src/lib/rows.spec.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+
+import { ALLOWED_NOTE_TYPES, REVISION_SOURCES } from "./rows.js";
+
+describe("REVISION_SOURCES", () => {
+ it("contains the expected revision source values in order", () => {
+ expect(REVISION_SOURCES).toEqual(["auto", "manual", "etapi", "llm", "restore"]);
+ });
+
+ it("has exactly five entries", () => {
+ expect(REVISION_SOURCES).toHaveLength(5);
+ });
+});
+
+describe("ALLOWED_NOTE_TYPES", () => {
+ it("is a non-empty array", () => {
+ expect(Array.isArray(ALLOWED_NOTE_TYPES)).toBe(true);
+ expect(ALLOWED_NOTE_TYPES.length).toBeGreaterThan(0);
+ });
+
+ it("includes the expected note types", () => {
+ for (const type of ["text", "code", "spreadsheet", "llmChat"]) {
+ expect(ALLOWED_NOTE_TYPES).toContain(type);
+ }
+ });
+
+ it("matches the full set of allowed note types", () => {
+ expect(ALLOWED_NOTE_TYPES).toEqual([
+ "file",
+ "image",
+ "search",
+ "noteMap",
+ "launcher",
+ "doc",
+ "contentWidget",
+ "text",
+ "relationMap",
+ "render",
+ "canvas",
+ "mermaid",
+ "book",
+ "webView",
+ "code",
+ "mindMap",
+ "spreadsheet",
+ "llmChat"
+ ]);
+ });
+});
diff --git a/packages/commons/src/lib/shared_constants.spec.ts b/packages/commons/src/lib/shared_constants.spec.ts
new file mode 100644
index 0000000000..d0081ca993
--- /dev/null
+++ b/packages/commons/src/lib/shared_constants.spec.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ ALLOWED_PROTOCOLS,
+ SANITIZER_DEFAULT_ALLOWED_TAGS,
+ SHELL_OPEN_EXTERNAL_PROTOCOLS
+} from "./shared_constants.js";
+
+describe("SANITIZER_DEFAULT_ALLOWED_TAGS", () => {
+ it("is a non-empty array containing common formatting tags", () => {
+ expect(Array.isArray(SANITIZER_DEFAULT_ALLOWED_TAGS)).toBe(true);
+ expect(SANITIZER_DEFAULT_ALLOWED_TAGS.length).toBeGreaterThan(0);
+ expect(SANITIZER_DEFAULT_ALLOWED_TAGS).toContain("p");
+ expect(SANITIZER_DEFAULT_ALLOWED_TAGS).toContain("img");
+ expect(SANITIZER_DEFAULT_ALLOWED_TAGS).toContain("table");
+ });
+});
+
+describe("ALLOWED_PROTOCOLS", () => {
+ it("is a non-empty array including https, mailto and file", () => {
+ expect(Array.isArray(ALLOWED_PROTOCOLS)).toBe(true);
+ expect(ALLOWED_PROTOCOLS.length).toBeGreaterThan(0);
+ expect(ALLOWED_PROTOCOLS).toContain("https");
+ expect(ALLOWED_PROTOCOLS).toContain("mailto");
+ expect(ALLOWED_PROTOCOLS).toContain("file");
+ });
+});
+
+describe("SHELL_OPEN_EXTERNAL_PROTOCOLS", () => {
+ it("excludes every blocklisted scheme", () => {
+ const blocklisted = ["file", "data", "smb", "ldap", "ldaps", "jar", "view-source"];
+
+ for (const scheme of blocklisted) {
+ expect(SHELL_OPEN_EXTERNAL_PROTOCOLS).not.toContain(scheme);
+ }
+ });
+
+ it("includes safe schemes that are not blocklisted", () => {
+ expect(SHELL_OPEN_EXTERNAL_PROTOCOLS).toContain("https");
+ expect(SHELL_OPEN_EXTERNAL_PROTOCOLS).toContain("tel");
+ expect(SHELL_OPEN_EXTERNAL_PROTOCOLS).toContain("ftp");
+ });
+
+ it("is derived from ALLOWED_PROTOCOLS (a strict subset)", () => {
+ expect(SHELL_OPEN_EXTERNAL_PROTOCOLS.length).toBeGreaterThan(0);
+ for (const scheme of SHELL_OPEN_EXTERNAL_PROTOCOLS) {
+ expect(ALLOWED_PROTOCOLS).toContain(scheme);
+ }
+ // It must be a proper subset: the blocklist removes some entries.
+ expect(SHELL_OPEN_EXTERNAL_PROTOCOLS.length).toBeLessThan(ALLOWED_PROTOCOLS.length);
+ });
+});
diff --git a/packages/commons/src/lib/spreadsheet/extract_text.spec.ts b/packages/commons/src/lib/spreadsheet/extract_text.spec.ts
index 714dca28f3..93e1a42ba4 100644
--- a/packages/commons/src/lib/spreadsheet/extract_text.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/extract_text.spec.ts
@@ -297,6 +297,164 @@ describe("extractSpreadsheetText", () => {
expect(extractSpreadsheetText(input)).toBe("hello");
});
+ it("returns empty string when all referenced sheets are hidden", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Hidden",
+ hidden: 1,
+ cellData: { "0": { "0": { v: "secret" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+
+ expect(extractSpreadsheetText(input)).toBe("");
+ });
+
+ it("returns empty string when sheetOrder points to missing ids", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["does-not-exist"],
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ cellData: { "0": { "0": { v: "data" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+
+ expect(extractSpreadsheetText(input)).toBe("");
+ });
+
+ it("extracts cells from fully lowercased keys via prop fallback", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetorder: ["s1"],
+ sheets: {
+ s1: {
+ id: "s1",
+ hidden: 0,
+ celldata: {
+ "0": {
+ "0": { v: "lower" },
+ "1": { v: "case" }
+ },
+ "1": { "0": { v: "skipped" } }
+ },
+ rowdata: { "1": { hd: 1 } },
+ columndata: { "1": { hd: 1 } }
+ }
+ }
+ }
+ });
+
+ const text = extractSpreadsheetText(input);
+ expect(text).toBe("lower");
+ });
+
+ it("uses Object.keys(sheets) when sheetOrder is absent", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheets: {
+ s1: {
+ id: "s1",
+ hidden: 0,
+ cellData: { "0": { "0": { v: "noOrder" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+
+ expect(extractSpreadsheetText(input)).toBe("noOrder");
+ });
+
+ it("skips whitespace-only string cell values", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ sheets: {
+ s1: {
+ id: "s1",
+ hidden: 0,
+ cellData: {
+ "0": {
+ "0": { v: " " },
+ "1": { v: "kept" }
+ }
+ },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+
+ expect(extractSpreadsheetText(input)).toBe("kept");
+ });
+
+ it("defaults rowData and columnData to empty objects when absent", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ sheets: {
+ s1: {
+ id: "s1",
+ hidden: 0,
+ cellData: {
+ "0": { "0": { v: "noMeta" } }
+ }
+ }
+ }
+ }
+ });
+
+ expect(extractSpreadsheetText(input)).toBe("noMeta");
+ });
+
+ it("handles a null cell entry without throwing", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ sheets: {
+ s1: {
+ id: "s1",
+ hidden: 0,
+ cellData: {
+ "0": {
+ "0": null,
+ "1": { v: "present" }
+ }
+ },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+
+ expect(extractSpreadsheetText(input)).toBe("present");
+ });
+
it("extracts text from the sample spreadsheet", () => {
const input = JSON.stringify({
version: 1,
diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
index dd3f10e26a..853e18b5cb 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
@@ -418,4 +418,549 @@ describe("renderSpreadsheetToHtml", () => {
expect(html).not.toContain("evil.com");
expect(html).toContain("transparent");
});
+
+ // Helper to wrap a single styled cell into a complete workbook payload.
+ function singleCellWorkbook(cell: unknown, sheetExtra: Record<string, unknown> = {}): string {
+ return JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [],
+ cellData: {
+ "0": {
+ "0": cell
+ }
+ },
+ rowData: {},
+ columnData: {},
+ ...sheetExtra
+ }
+ }
+ }
+ });
+ }
+
+ it("returns empty spreadsheet message when workbook.sheets is missing", () => {
+ const input = JSON.stringify({ version: 1, workbook: { sheetOrder: [] } });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toBe("<p>Empty spreadsheet.</p>");
+ });
+
+ it("returns empty spreadsheet message when there are no top-level keys", () => {
+ const html = renderSpreadsheetToHtml(JSON.stringify(null));
+ expect(html).toBe("<p>Empty spreadsheet.</p>");
+ });
+
+ it("returns empty spreadsheet message when sheetOrder is empty", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: [],
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [],
+ cellData: { "0": { "0": { v: "x" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toBe("<p>Empty spreadsheet.</p>");
+ });
+
+ it("returns empty spreadsheet message when all sheets are hidden", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Hidden",
+ hidden: 1,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [],
+ cellData: { "0": { "0": { v: "x" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toBe("<p>Empty spreadsheet.</p>");
+ });
+
+ it("falls back to Object.keys(sheets) when sheetOrder is absent", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [],
+ cellData: { "0": { "0": { v: "fromKeys" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toContain("fromKeys");
+ });
+
+ it("uses default workbook styles object when workbook.styles is absent", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [],
+ cellData: { "0": { "0": { s: "missingStyle", v: "noStyle" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toContain("noStyle");
+ // Missing style id resolves to null -> no inline style attribute.
+ expect(html).toContain("<td>noStyle</td>");
+ });
+
+ it("renders bold, italic and underline inline styles", () => {
+ const html = renderSpreadsheetToHtml(
+ singleCellWorkbook({ v: "fancy", s: { bl: 1, it: 1, ul: { s: 1 } } })
+ );
+ expect(html).toContain("font-weight:bold");
+ expect(html).toContain("font-style:italic");
+ expect(html).toContain("text-decoration:underline");
+ expect(html).not.toContain("line-through");
+ });
+
+ it("renders strikethrough alone", () => {
+ const html = renderSpreadsheetToHtml(
+ singleCellWorkbook({ v: "strike", s: { st: { s: 1 } } })
+ );
+ expect(html).toContain("text-decoration:line-through");
+ expect(html).not.toContain("text-decoration:underline line-through");
+ });
+
+ it("combines underline and strikethrough into one text-decoration", () => {
+ const html = renderSpreadsheetToHtml(
+ singleCellWorkbook({ v: "both", s: { ul: { s: 1 }, st: { s: 1 } } })
+ );
+ expect(html).toContain("text-decoration:underline line-through");
+ });
+
+ it("renders font-size and font-family", () => {
+ const html = renderSpreadsheetToHtml(
+ singleCellWorkbook({ v: "sized", s: { fs: 14, ff: "Times New Roman" } })
+ );
+ expect(html).toContain("font-size:14pt");
+ expect(html).toContain("font-family:Times New Roman");
+ });
+
+ it("ignores non-finite font-size", () => {
+ // fs stored as a string from a stringified payload should not produce font-size.
+ const html = renderSpreadsheetToHtml(
+ singleCellWorkbook({ v: "badsize", s: { fs: "20" } })
+ );
+ expect(html).not.toContain("font-size");
+ expect(html).toContain("badsize");
+ });
+
+ it("strips dangerous characters from font-family", () => {
+ const html = renderSpreadsheetToHtml(
+ singleCellWorkbook({ v: "ff", s: { ff: "Arial;}<x>" } })
+ );
+ expect(html).toContain("font-family:Arialx");
+ expect(html).not.toContain(";}");
+ expect(html).not.toContain("<x>");
+ });
+
+ it("renders all horizontal alignment values", () => {
+ const left = renderSpreadsheetToHtml(singleCellWorkbook({ v: "l", s: { ht: 1 } }));
+ const center = renderSpreadsheetToHtml(singleCellWorkbook({ v: "c", s: { ht: 2 } }));
+ const right = renderSpreadsheetToHtml(singleCellWorkbook({ v: "r", s: { ht: 3 } }));
+ expect(left).toContain("text-align:left");
+ expect(center).toContain("text-align:center");
+ expect(right).toContain("text-align:right");
+ });
+
+ it("omits text-align for an unknown horizontal alignment", () => {
+ const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x", s: { ht: 9 } }));
+ expect(html).not.toContain("text-align");
+ expect(html).toContain("<td>x</td>");
+ });
+
+ it("renders all vertical alignment values", () => {
+ const top = renderSpreadsheetToHtml(singleCellWorkbook({ v: "t", s: { vt: 1 } }));
+ const middle = renderSpreadsheetToHtml(singleCellWorkbook({ v: "m", s: { vt: 2 } }));
+ const bottom = renderSpreadsheetToHtml(singleCellWorkbook({ v: "b", s: { vt: 3 } }));
+ expect(top).toContain("vertical-align:top");
+ expect(middle).toContain("vertical-align:middle");
+ expect(bottom).toContain("vertical-align:bottom");
+ });
+
+ it("omits vertical-align for an unknown vertical alignment", () => {
+ const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x", s: { vt: 9 } }));
+ expect(html).not.toContain("vertical-align");
+ expect(html).toContain("<td>x</td>");
+ });
+
+ it("renders borders on all four sides with widths and styles", () => {
+ const html = renderSpreadsheetToHtml(
+ singleCellWorkbook({
+ v: "bordered",
+ s: {
+ bd: {
+ t: { s: 1, cl: { rgb: "#111111" } }, // THIN -> 1px solid
+ r: { s: 6, cl: { rgb: "#222222" } }, // MEDIUM -> 2px solid
+ b: { s: 9, cl: { rgb: "#333333" } }, // THICK -> 3px solid
+ l: { s: 3, cl: { rgb: "#444444" } } // DASHED -> 1px dashed
+ }
+ }
+ })
+ );
+ expect(html).toContain("border-top:1px solid #111111");
+ expect(html).toContain("border-right:2px solid #222222");
+ expect(html).toContain("border-bottom:3px solid #333333");
+ expect(html).toContain("border-left:1px dashed #444444");
+ });
+
+ it("renders dotted border style and defaults missing border color to #000", () => {
+ const html = renderSpreadsheetToHtml(
+ singleCellWorkbook({
+ v: "dotted",
+ s: {
+ bd: {
+ t: { s: 4 } // DOTTED, no color -> default #000
+ }
+ }
+ })
+ );
+ expect(html).toContain("border-top:1px dotted #000");
+ });
+
+ it("skips border sides that are null or undefined", () => {
+ const html = renderSpreadsheetToHtml(
+ singleCellWorkbook({
+ v: "partial",
+ s: {
+ bd: {
+ t: { s: 1, cl: { rgb: "#000000" } },
+ r: null,
+ b: undefined,
+ l: null
+ }
+ }
+ })
+ );
+ expect(html).toContain("border-top:1px solid #000000");
+ expect(html).not.toContain("border-right");
+ expect(html).not.toContain("border-bottom");
+ expect(html).not.toContain("border-left");
+ });
+
+ it("accepts named, rgb and hsl color notations", () => {
+ const named = renderSpreadsheetToHtml(singleCellWorkbook({ v: "n", s: { bg: { rgb: "red" } } }));
+ const hex = renderSpreadsheetToHtml(singleCellWorkbook({ v: "h", s: { bg: { rgb: "#abcdef" } } }));
+ const rgb = renderSpreadsheetToHtml(singleCellWorkbook({ v: "rg", s: { cl: { rgb: "rgb(1,2,3)" } } }));
+ const hsl = renderSpreadsheetToHtml(singleCellWorkbook({ v: "hs", s: { cl: { rgb: "hsl(0,0%,0%)" } } }));
+ expect(named).toContain("background-color:red");
+ expect(hex).toContain("background-color:#abcdef");
+ expect(rgb).toContain("color:rgb(1,2,3)");
+ expect(hsl).toContain("color:hsl(0,0%,0%)");
+ });
+
+ it("falls back to transparent for an invalid functional color", () => {
+ const html = renderSpreadsheetToHtml(
+ singleCellWorkbook({ v: "bad", s: { bg: { rgb: "url(x)" } } })
+ );
+ expect(html).toContain("background-color:transparent");
+ });
+
+ it("resolves a style referenced by id and an empty cell style object", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {
+ redBold: { bl: 1, cl: { rgb: "#ff0000" } },
+ nullStyle: null
+ },
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [],
+ cellData: {
+ "0": {
+ "0": { s: "redBold", v: "byId" },
+ "1": { s: "nullStyle", v: "nulled" },
+ "2": { s: {}, v: "emptyStyle" }
+ }
+ },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toContain("font-weight:bold");
+ expect(html).toContain("color:#ff0000");
+ expect(html).toContain("byId");
+ // null style id and empty style object -> plain <td>.
+ expect(html).toContain("<td>nulled</td>");
+ expect(html).toContain("<td>emptyStyle</td>");
+ });
+
+ it("skips hidden rows and hidden columns", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [],
+ cellData: {
+ "0": { "0": { v: "keepA" }, "1": { v: "hideCol" } },
+ "1": { "0": { v: "hideRow" } },
+ "2": { "0": { v: "keepB" } }
+ },
+ rowData: { "1": { hd: 1 } },
+ columnData: { "1": { hd: 1 } }
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toContain("keepA");
+ expect(html).toContain("keepB");
+ expect(html).not.toContain("hideCol");
+ expect(html).not.toContain("hideRow");
+ });
+
+ it("uses explicit column width and row height when provided", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ defaultColumnWidth: 88,
+ defaultRowHeight: 24,
+ mergeData: [],
+ cellData: { "0": { "0": { v: "sized" } } },
+ rowData: { "0": { h: 50 } },
+ columnData: { "0": { w: 200 } }
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toContain('<col style="width:200px">');
+ expect(html).toContain('<tr style="height:50px">');
+ });
+
+ it("falls back to default column width and row height when absent", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [],
+ cellData: { "0": { "0": { v: "defaults" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toContain('<col style="width:88px">');
+ expect(html).toContain('<tr style="height:24px">');
+ });
+
+ it("renders an empty string for a cell with null value", () => {
+ const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: null }));
+ expect(html).toContain("<td></td>");
+ });
+
+ it("renders an empty string for a cell with no value field", () => {
+ const html = renderSpreadsheetToHtml(singleCellWorkbook({ t: 1 }));
+ expect(html).toContain("<td></td>");
+ });
+
+ it("renders an empty string for missing cell within bounds", () => {
+ // Bounds extended by a merge so an absent cell is visited.
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [],
+ cellData: {
+ "0": { "0": { v: "A" }, "2": { v: "C" } }
+ },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ // Column 1 between A and C has no cell -> empty <td>.
+ expect(html).toContain("<td>A</td>");
+ expect(html).toContain("<td></td>");
+ expect(html).toContain("<td>C</td>");
+ });
+
+ it("renders numeric cell values", () => {
+ const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: 42, t: 2 }));
+ expect(html).toContain("<td>42</td>");
+ });
+
+ it("emits colspan only for a purely horizontal merge", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 }],
+ cellData: { "0": { "0": { v: "wide" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toContain('colspan="3"');
+ expect(html).not.toContain("rowspan");
+ });
+
+ it("emits rowspan only for a purely vertical merge", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ mergeData: [{ startRow: 0, endRow: 2, startColumn: 0, endColumn: 0 }],
+ cellData: { "0": { "0": { v: "tall" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ expect(html).toContain('rowspan="3"');
+ expect(html).not.toContain("colspan");
+ });
+
+ it("extends bounds to cover a merge range that exceeds the cell data", () => {
+ const input = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {},
+ sheets: {
+ s1: {
+ id: "s1",
+ name: "Sheet1",
+ hidden: 0,
+ rowCount: 10,
+ columnCount: 5,
+ // Data only at the origin (2,2); merge starts before and ends after it,
+ // so computeBounds must extend min/max in every direction.
+ mergeData: [{ startRow: 1, endRow: 4, startColumn: 1, endColumn: 4 }],
+ cellData: { "2": { "2": { v: "center" } } },
+ rowData: {},
+ columnData: {}
+ }
+ }
+ }
+ });
+ const html = renderSpreadsheetToHtml(input);
+ // The merge origin (1,1) spans a 4x4 area extending beyond the single data cell at (2,2).
+ expect(html).toContain('rowspan="4"');
+ expect(html).toContain('colspan="4"');
+ });
});
diff --git a/packages/commons/src/lib/task_states.spec.ts b/packages/commons/src/lib/task_states.spec.ts
index a45b033600..f68ece216f 100644
--- a/packages/commons/src/lib/task_states.spec.ts
+++ b/packages/commons/src/lib/task_states.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { DONE_TASK_STATE, NONE_TASK_STATE, type TaskStateDef, type TaskStateValidationReason, validateTaskStates } from "./task_states.js";
+import { DEFAULT_TASK_STATES, DONE_STATE_NAME, DONE_TASK_STATE, isAnchorState, NONE_STATE_NAME, NONE_TASK_STATE, type TaskStateDef, type TaskStateValidationReason, validateTaskStates } from "./task_states.js";
function customState(overrides: Partial<TaskStateDef>): TaskStateDef {
return {
@@ -68,4 +68,43 @@ describe("validateTaskStates", () => {
expect(errors).toHaveLength(0);
expect(valid).toHaveLength(1);
});
+
+ it("falls back to empty id/title when the dropped state lacks them", () => {
+ const { errors } = validateTaskStates([customState({ id: undefined, title: "", name: "" })]);
+ expect(errors[0]).toEqual({ id: "", title: "", reason: "undefined-name" });
+ });
+
+ it("uses the name as the dropped state's title when the title is missing", () => {
+ const { errors } = validateTaskStates([customState({ title: "", name: "in progress" })]);
+ expect(errors[0]).toEqual({ id: "_id", title: "in progress", reason: "invalid-name" });
+ });
+});
+
+describe("isAnchorState", () => {
+ it("treats the built-in unchecked anchor as an anchor", () => {
+ expect(isAnchorState("none")).toBe(true);
+ expect(isAnchorState(NONE_STATE_NAME)).toBe(true);
+ });
+
+ it("treats the built-in checked anchor as an anchor", () => {
+ expect(isAnchorState("done")).toBe(true);
+ expect(isAnchorState(DONE_STATE_NAME)).toBe(true);
+ });
+
+ it("rejects customizable and empty state names", () => {
+ expect(isAnchorState("doing")).toBe(false);
+ expect(isAnchorState("")).toBe(false);
+ });
+});
+
+describe("DEFAULT_TASK_STATES", () => {
+ it("orders the states None, Doing, Done, Maybe, Cancelled", () => {
+ expect(DEFAULT_TASK_STATES.map((state) => state.name)).toEqual([
+ "none",
+ "doing",
+ "done",
+ "maybe",
+ "cancelled"
+ ]);
+ });
});
diff --git a/packages/commons/src/lib/test-utils.spec.ts b/packages/commons/src/lib/test-utils.spec.ts
index 90388f5814..4636f52fe4 100644
--- a/packages/commons/src/lib/test-utils.spec.ts
+++ b/packages/commons/src/lib/test-utils.spec.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { findDuplicateJsonKeys, trimIndentation } from "./test-utils.js";
+import { findDuplicateJsonKeys, sleepFor, trimIndentation } from "./test-utils.js";
describe("Utils", () => {
it("trims indentation", () => {
@@ -12,6 +12,26 @@ Hello
123`);
});
+ it("trims indentation with an interpolated value", () => {
+ const value = "hi";
+ expect(trimIndentation`\
+ <p>${value}</p>`).toBe("<p>hi</p>");
+ });
+
+ it("treats an undefined interpolated value as empty string", () => {
+ const value = undefined;
+ expect(trimIndentation`\
+ before${value}after`).toBe("beforeafter");
+ });
+
+ describe("sleepFor", () => {
+ it("returns a Promise that resolves after the given duration", async () => {
+ const result = sleepFor(1);
+ expect(result).toBeInstanceOf(Promise);
+ await expect(result).resolves.toBeUndefined();
+ });
+ });
+
describe("findDuplicateJsonKeys", () => {
it("returns empty for valid JSON without duplicates", () => {
expect(findDuplicateJsonKeys(`{"a": 1, "b": {"c": 2}}`)).toEqual([]);
@@ -33,5 +53,28 @@ Hello
it("does not treat strings inside arrays as keys", () => {
expect(findDuplicateJsonKeys(`{"items": ["a", "a", "b"]}`)).toEqual([]);
});
+
+ it("detects duplicates when a string value contains an escaped quote", () => {
+ const text = `{ "a": "x\\"y", "a": 2 }`;
+ expect(findDuplicateJsonKeys(text)).toEqual([{ key: "a", line: 1 }]);
+ });
+
+ it("detects duplicates when a string value contains an escaped backslash", () => {
+ const text = `{ "a": "x\\\\y", "a": 2 }`;
+ expect(findDuplicateJsonKeys(text)).toEqual([{ key: "a", line: 1 }]);
+ });
+
+ it("does not mistake an escaped quote inside a value for a key delimiter", () => {
+ expect(findDuplicateJsonKeys(`{ "a": "b\\": c", "d": 1 }`)).toEqual([]);
+ });
+
+ it("counts newlines that occur inside a string value", () => {
+ const text = `{\n "a": "line1\nline2",\n "a": 2\n}`;
+ expect(findDuplicateJsonKeys(text)).toEqual([{ key: "a", line: 4 }]);
+ });
+
+ it("recognises a key even when whitespace separates it from the colon", () => {
+ expect(findDuplicateJsonKeys(`{ "a" : 1, "a" : 2 }`)).toEqual([{ key: "a", line: 1 }]);
+ });
});
});
diff --git a/packages/commons/src/lib/utils.spec.ts b/packages/commons/src/lib/utils.spec.ts
index df2b4c7fe3..c61372ddc6 100644
--- a/packages/commons/src/lib/utils.spec.ts
+++ b/packages/commons/src/lib/utils.spec.ts
@@ -49,4 +49,37 @@ describe("#formatLogMessage", () => {
it("handles zero arguments", () => {
expect(formatLogMessage()).toBe("");
});
+
+ it("limits nesting depth to MAX_LOG_DEPTH, replacing deeper levels with [Object]", () => {
+ const result = formatLogMessage({ a: { b: { c: { d: 1 } } } });
+ expect(result).toContain("[Object]");
+ // The deepest level (d) is beyond the depth limit and is omitted from output.
+ expect(result).not.toContain('"d"');
+ });
+
+ it("serializes sibling nested objects independently (ancestor pop)", () => {
+ const result = formatLogMessage({ first: { x: 1 }, second: { y: 2 } });
+ expect(result).toContain('"x": 1');
+ expect(result).toContain('"y": 2');
+ expect(result).not.toContain("[Circular]");
+ });
+
+ it("falls back to String(arg) when JSON.stringify throws (BigInt value)", () => {
+ const result = formatLogMessage({ big: 10n });
+ expect(result).toBe("[object Object]");
+ });
+});
+
+describe("#deferred resolution", () => {
+ it("can be resolved", async () => {
+ const d = deferred<number>();
+ d.resolve(5);
+ expect(await d).toBe(5);
+ });
+
+ it("can be rejected", async () => {
+ const d2 = deferred<number>();
+ d2.reject(new Error("x"));
+ await expect(d2).rejects.toThrow("x");
+ });
});
diff --git a/packages/commons/src/lib/week_utils.spec.ts b/packages/commons/src/lib/week_utils.spec.ts
index 5141761d48..e793ee9c2d 100644
--- a/packages/commons/src/lib/week_utils.spec.ts
+++ b/packages/commons/src/lib/week_utils.spec.ts
@@ -1,6 +1,14 @@
import { describe, expect, it } from "vitest";
import { dayjs } from "./dayjs.js";
-import { getWeekInfo, getFirstDayOfWeek1, getWeekString, WeekSettings, DEFAULT_WEEK_SETTINGS } from "./week_utils.js";
+import {
+ DEFAULT_WEEK_SETTINGS,
+ getFirstDayOfWeek1,
+ getWeekInfo,
+ getWeekStartDate,
+ getWeekString,
+ parseWeekString,
+ WeekSettings
+} from "./week_utils.js";
describe("week_utils", () => {
describe("getWeekInfo", () => {
@@ -207,4 +215,127 @@ describe("week_utils", () => {
expect(getWeekString(dayjs("2026-01-05"), settings)).toBe("2026-W02");
});
});
+
+ describe("getFirstDayOfWeek1 (additional branches)", () => {
+ it("with firstWeekOfYear=1 (ISO 8601) for 2026, week 1 starts 2025-12-29", () => {
+ const settings: WeekSettings = {
+ firstDayOfWeek: 1,
+ firstWeekOfYear: 1,
+ minDaysInFirstWeek: 4
+ };
+ // 2026-01-04 is Sunday (isoWeekday 7); week containing it starts 2025-12-29 (Mon)
+ const result = getFirstDayOfWeek1(2026, settings);
+ expect(result.format("YYYY-MM-DD")).toBe("2025-12-29");
+ });
+
+ describe("with firstWeekOfYear=2 (minimum days in first week)", () => {
+ // 2026-01-01 is Thursday (isoWeekday 4), firstDayOfWeek=1
+ // daysToSubtract = (4-1+7)%7 = 3, so daysInFirstWeek = 7-3 = 4
+ it("returns the week containing Jan 1 when daysInFirstWeek >= minDaysInFirstWeek", () => {
+ const settings: WeekSettings = {
+ firstDayOfWeek: 1,
+ firstWeekOfYear: 2,
+ minDaysInFirstWeek: 4
+ };
+ // 4 days >= 4 minimum -> week containing Jan 1 starts 2025-12-29
+ const result = getFirstDayOfWeek1(2026, settings);
+ expect(result.format("YYYY-MM-DD")).toBe("2025-12-29");
+ });
+
+ it("returns the next week when daysInFirstWeek < minDaysInFirstWeek", () => {
+ const settings: WeekSettings = {
+ firstDayOfWeek: 1,
+ firstWeekOfYear: 2,
+ minDaysInFirstWeek: 5
+ };
+ // 4 days < 5 minimum -> add one week -> starts 2026-01-05
+ const result = getFirstDayOfWeek1(2026, settings);
+ expect(result.format("YYYY-MM-DD")).toBe("2026-01-05");
+ });
+ });
+ });
+
+ describe("getWeekInfo (year-boundary branches)", () => {
+ const settings: WeekSettings = {
+ firstDayOfWeek: 1,
+ firstWeekOfYear: 1, // ISO 8601
+ minDaysInFirstWeek: 4
+ };
+
+ it("early-January date belonging to previous year's last week (weekStart isBefore week1 -> year--)", () => {
+ // 2023-01-01 is Sunday; its week starts 2022-12-26, which is before
+ // ISO week 1 of 2023 (2023-01-02). It belongs to 2022-W52.
+ const result = getWeekInfo(dayjs("2023-01-01"), settings);
+ expect(result.weekYear).toBe(2022);
+ expect(result.weekNumber).toBe(52);
+ });
+
+ it("late-December date belonging to next year's week 1 (!isBefore nextYearFirstDayOfWeek1 -> year++)", () => {
+ // ISO week 1 of 2026 starts 2025-12-29 (Mon). 2025-12-31 is in that week,
+ // so it belongs to 2026-W01 even though its calendar year is 2025.
+ const result = getWeekInfo(dayjs("2025-12-31"), settings);
+ expect(result.weekYear).toBe(2026);
+ expect(result.weekNumber).toBe(1);
+ });
+ });
+
+ describe("getWeekStartDate", () => {
+ it("returns the Monday of the week for firstDayOfWeek=1", () => {
+ // 2026-01-15 is Thursday (isoWeekday 4); the Monday of that week is 2026-01-12
+ const result = getWeekStartDate(dayjs("2026-01-15"), 1);
+ expect(result.format("YYYY-MM-DD")).toBe("2026-01-12");
+ });
+
+ it("returns the Sunday of the week for firstDayOfWeek=7", () => {
+ // With Sunday as first day, the week containing 2026-01-15 (Thu) starts 2026-01-11
+ const result = getWeekStartDate(dayjs("2026-01-15"), 7);
+ expect(result.format("YYYY-MM-DD")).toBe("2026-01-11");
+ });
+
+ it("defaults firstDayOfWeek to 1 (Monday) when omitted", () => {
+ const result = getWeekStartDate(dayjs("2026-01-15"));
+ expect(result.format("YYYY-MM-DD")).toBe("2026-01-12");
+ });
+
+ it("truncates the time to the start of the day", () => {
+ const result = getWeekStartDate(dayjs("2026-01-15T13:45:30"), 1);
+ expect(result.format("YYYY-MM-DD HH:mm:ss")).toBe("2026-01-12 00:00:00");
+ });
+ });
+
+ describe("parseWeekString", () => {
+ it("parses '2026-W01' to the start of week 1 under default settings", () => {
+ // Under DEFAULT_WEEK_SETTINGS, week 1 of 2026 starts 2025-12-29
+ const result = parseWeekString("2026-W01", DEFAULT_WEEK_SETTINGS);
+ expect(result.format("YYYY-MM-DD")).toBe("2025-12-29");
+ });
+
+ it("uses default settings when none are provided", () => {
+ const result = parseWeekString("2026-W01");
+ expect(result.format("YYYY-MM-DD")).toBe("2025-12-29");
+ });
+
+ it("parses later week numbers relative to week 1", () => {
+ // Week 2 is one week after week 1 (2025-12-29) -> 2026-01-05
+ const result = parseWeekString("2026-W02", DEFAULT_WEEK_SETTINGS);
+ expect(result.format("YYYY-MM-DD")).toBe("2026-01-05");
+ });
+
+ it("trims surrounding whitespace before parsing", () => {
+ const result = parseWeekString(" 2026-W01 ", DEFAULT_WEEK_SETTINGS);
+ expect(result.format("YYYY-MM-DD")).toBe("2025-12-29");
+ });
+
+ it("round-trips with getWeekString and aligns with getWeekStartDate", () => {
+ const date = dayjs("2026-03-18");
+ const weekStr = getWeekString(date, DEFAULT_WEEK_SETTINGS);
+ expect(weekStr).toBe("2026-W12");
+
+ const parsed = parseWeekString(weekStr, DEFAULT_WEEK_SETTINGS);
+ const weekStart = getWeekStartDate(date, DEFAULT_WEEK_SETTINGS.firstDayOfWeek);
+
+ expect(parsed.format("YYYY-MM-DD")).toBe("2026-03-16");
+ expect(parsed.format("YYYY-MM-DD")).toBe(weekStart.format("YYYY-MM-DD"));
+ });
+ });
});
diff --git a/packages/commons/vite.config.ts b/packages/commons/vite.config.ts
index da8a87d7f6..8c21831450 100644
--- a/packages/commons/vite.config.ts
+++ b/packages/commons/vite.config.ts
@@ -18,6 +18,9 @@ export default defineConfig(() => ({
'reportsDirectory': './test-output/vitest/coverage',
'provider': 'v8' as const,
'reporter': ['text', 'html', 'lcov'],
+ 'all': true,
+ 'include': ['src/**/*.ts'],
+ 'exclude': ['src/**/*.spec.ts'],
}
},
}));