xonecas.io
6533
Yo

yoctomarkdown / files

yoctomarkdown / tests / index.test.ts

6.9 KB
1import { test, expect, describe } from "bun:test";
2import { highlightSync, createHighlighter } from "../src/index";
3
4describe("Programmatic Usage: highlightSync", () => {
5  test("should format basic markdown elements", () => {
6    const res = highlightSync("# Heading\n\n**bold** and *italic*", {
7      theme: "none",
8    });
9    expect(res).toContain("Heading");
10    expect(res).toContain("bold");
11    expect(res).toContain("italic");
12  });
13
14  test("should format lists", () => {
15    const res = highlightSync("- Item 1\n- Item 2\n1. Number 1", {
16      theme: "none",
17    });
18    expect(res).toContain("Item 1");
19    expect(res).toContain("Item 2");
20    expect(res).toContain("Number 1");
21  });
22
23  test("performance test on large input", () => {
24    const largeMd = "# Heading\n\nSome **bold** text here.\n".repeat(5000);
25    const start = performance.now();
26    highlightSync(largeMd, { theme: "none" });
27    const end = performance.now();
28
29    const duration = end - start;
30    console.log(`Programmatic Parse Time: ${duration.toFixed(2)}ms`);
31    expect(duration).toBeLessThan(200); // 5000 lines should be fast
32  });
33});
34
35function renderTerminalOutput(
36  output: string,
37  columns = Number.POSITIVE_INFINITY,
38) {
39  const screen: string[][] = [[]];
40  let row = 0;
41  let column = 0;
42  function ensureRow(targetRow: number) {
43    while (screen.length <= targetRow) {
44      screen.push([]);
45    }
46  }
47
48  function writeChar(char: string) {
49    if (column >= columns) {
50      row += 1;
51      column = 0;
52    }
53
54    ensureRow(row);
55    if (!screen[row]) {
56      screen[row] = [];
57    }
58    const currentLine = screen[row];
59    if (!currentLine) {
60      return;
61    }
62    currentLine[column] = char;
63    column += 1;
64  }
65
66  for (let i = 0; i < output.length; i += 1) {
67    const rest = output.slice(i);
68
69    // Parse CSI sequences: \x1b[ <params> <letter>
70    if (rest.startsWith("\x1b[")) {
71      // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape regex
72      const csiMatch = rest.match(/^\x1b\[([0-9;]*)([A-Za-z])/);
73      if (csiMatch) {
74        const param = csiMatch[1] ?? "";
75        const code = csiMatch[2] ?? "";
76        const n = param === "" ? 1 : parseInt(param, 10);
77        i += csiMatch[0].length - 1; // -1 because loop does i++
78
79        switch (code) {
80          case "A": // Cursor Up
81            row = Math.max(0, row - n);
82            break;
83          case "D": // Cursor Backward
84            column = Math.max(0, column - n);
85            break;
86          case "J": // Erase in Display (from cursor down)
87            ensureRow(row);
88            screen[row] = (screen[row] ?? []).slice(0, column);
89            for (
90              let clearRow = row + 1;
91              clearRow < screen.length;
92              clearRow += 1
93            ) {
94              screen[clearRow] = [];
95            }
96            break;
97          case "K": {
98            // Erase in Line
99            const mode = param === "" ? 0 : n;
100            ensureRow(row);
101            if (mode === 0) {
102              // erase to end of line
103              screen[row] = (screen[row] ?? []).slice(0, column);
104            } else if (mode === 2) {
105              // erase whole line
106              screen[row] = [];
107            }
108            break;
109          }
110          case "C": // Cursor Forward
111            column += n;
112            break;
113          case "G": // Cursor Horizontal Absolute (1-based)
114            column = (param === "" ? 1 : n) - 1;
115            break;
116          default:
117            break;
118        }
119        continue;
120      }
121    }
122
123    const char = output[i];
124    if (char === "\n") {
125      row += 1;
126      column = 0;
127      ensureRow(row);
128      continue;
129    }
130
131    if (char === "\r") {
132      column = 0;
133      continue;
134    }
135
136    if (char !== undefined && char !== "\x1b") {
137      writeChar(char);
138    }
139  }
140
141  return screen
142    .map((line) => line.join("").replace(/\s+$/u, ""))
143    .join("\n")
144    .replace(/\n+$/u, "");
145}
146
147function expectStreamMatch(res: string, markdown: string) {
148  const expected = highlightSync(markdown, { theme: "none" });
149  expect(renderTerminalOutput(res)).toBe(renderTerminalOutput(expected));
150}
151
152describe("Programmatic Usage: createHighlighter (Streaming)", () => {
153  test("should handle chunks without breaking output", () => {
154    const highlighter = createHighlighter({ theme: "none" });
155    let res = highlighter.write("# Hea");
156    res += highlighter.write("ding\n");
157    res += highlighter.write("\nSome **tex");
158    res += highlighter.write("t**\n");
159    res += highlighter.end();
160
161    expect(res).toContain("Heading");
162    expect(res).toContain("Some **text**");
163  });
164
165  test("should handle character by character streaming", () => {
166    const markdown =
167      "# Title\n\nThis is a **test** of *character* streaming.\n\n- item 1\n- item 2\n";
168    const highlighter = createHighlighter({ theme: "none" });
169    let res = "";
170    for (const char of markdown) {
171      res += highlighter.write(char);
172    }
173    res += highlighter.end();
174
175    expectStreamMatch(res, markdown);
176  });
177
178  test("should handle random chunk sizes", () => {
179    const markdown =
180      "```javascript\nconst x = 1;\n```\n\n# Heading 2\n\nSome text with `code`.\n> Blockquote here\n\n1. One\n2. Two\n";
181    const highlighter = createHighlighter({ theme: "none" });
182    let res = "";
183
184    // Split into random chunks
185    let i = 0;
186    while (i < markdown.length) {
187      const chunkSize = Math.floor(Math.random() * 10) + 1;
188      res += highlighter.write(markdown.slice(i, i + chunkSize));
189      i += chunkSize;
190    }
191    res += highlighter.end();
192
193    expectStreamMatch(res, markdown);
194  });
195
196  test("should preserve text before streamed output (inline use)", () => {
197    // When a highlighter is used inline (e.g. "AI: " prefix already on
198    // the terminal line), the erase/redraw must not destroy the prefix.
199    const markdown = "Hello **world**";
200    const highlighter = createHighlighter({ theme: "none" });
201    let res = "AI: "; // simulates text already on terminal line
202    for (const ch of markdown) {
203      res += highlighter.write(ch);
204    }
205    res += highlighter.end();
206
207    expect(renderTerminalOutput(res)).toBe("AI: Hello **world**");
208  });
209
210  test("should erase and redraw partial lines that wrap in terminal", () => {
211    // erasePreviousPartial uses cursor-back + \x1b[0J (erase from cursor
212    // to end of screen). This preserves any text before our output on the
213    // same terminal line and is scroll-safe (all relative).
214    const markdown =
215      "No `\\x1b[2K` or `\\r` sequences in the streamed text. The ANSI colour codes remain (intentional — those are static style codes from yoctocolors, not cursor-control sequences).\n";
216    const splitAt = 134;
217
218    const highlighter = createHighlighter({ theme: "none" });
219    let res = "";
220    res += highlighter.write(markdown.slice(0, splitAt));
221    res += highlighter.write(markdown.slice(splitAt));
222    res += highlighter.end();
223
224    expect(renderTerminalOutput(res, 120)).toBe(
225      renderTerminalOutput(markdown, 120),
226    );
227  });
228});