@zyro-sec/latex 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/limits.ts ADDED
@@ -0,0 +1,40 @@
1
+ import { LatexParseError } from "./types"
2
+
3
+ export const DEFAULT_MAX_SOURCE_LENGTH = 100_000
4
+ export const DEFAULT_MAX_NESTING_DEPTH = 256
5
+
6
+ export function resolvePositiveInteger(value: number | undefined, fallback: number, optionName: string): number {
7
+ if (value === undefined) return fallback
8
+ if (!Number.isSafeInteger(value) || value < 1) {
9
+ throw new RangeError(`${optionName} must be a positive safe integer`)
10
+ }
11
+ return value
12
+ }
13
+
14
+ export function assertSourceLength(source: string, maximum: number, label = "LaTeX source"): void {
15
+ if (source.length > maximum) {
16
+ throw new LatexParseError(`${label} exceeds the ${maximum}-character limit`, maximum)
17
+ }
18
+ }
19
+
20
+ export function assertNestingDepth(source: string, maximum: number): void {
21
+ let depth = 0
22
+ let slashRun = 0
23
+ for (let index = 0; index < source.length; index++) {
24
+ const char = source[index]
25
+ if (char === "\\") {
26
+ slashRun++
27
+ continue
28
+ }
29
+ const escaped = slashRun % 2 === 1
30
+ slashRun = 0
31
+ if (char === "{" && !escaped) {
32
+ depth++
33
+ if (depth > maximum) {
34
+ throw new LatexParseError(`LaTeX nesting exceeds the ${maximum}-level limit`, index)
35
+ }
36
+ } else if (char === "}" && !escaped) {
37
+ depth = Math.max(0, depth - 1)
38
+ }
39
+ }
40
+ }
@@ -0,0 +1,267 @@
1
+ import { afterEach, expect, test } from "bun:test"
2
+ import {
3
+ CodeRenderable,
4
+ MarkdownRenderable,
5
+ RGBA,
6
+ ScrollBoxRenderable,
7
+ SyntaxStyle,
8
+ TextAttributes,
9
+ TextRenderable,
10
+ createMarkdownCodeBlockRenderer,
11
+ } from "@opentui/core"
12
+ import { createTestRenderer } from "@opentui/core/testing"
13
+ import { renderLatex } from "./render"
14
+ import { createLatexCodeBlockRenderer } from "./markdown"
15
+
16
+ const renderers: {
17
+ renderer: Awaited<ReturnType<typeof createTestRenderer>>["renderer"]
18
+ syntaxStyle: SyntaxStyle
19
+ }[] = []
20
+
21
+ afterEach(async () => {
22
+ await Promise.all(
23
+ renderers.splice(0).map(async (output) => {
24
+ output.renderer.destroy()
25
+ await output.renderer.closed
26
+ output.syntaxStyle.destroy()
27
+ }),
28
+ )
29
+ })
30
+
31
+ async function setup(content: string, width = 80) {
32
+ const output = await createTestRenderer({
33
+ width,
34
+ height: 24,
35
+ remote: true,
36
+ })
37
+ const syntaxStyle = SyntaxStyle.fromStyles({ default: { fg: "#ffffff" } }, output.renderer.nativeScene)
38
+ renderers.push({ renderer: output.renderer, syntaxStyle })
39
+ const palette = { text: "#abcdef", subdued: "#667788" }
40
+ const render = createLatexCodeBlockRenderer(output.renderer, () => palette)
41
+ const markdown = new MarkdownRenderable(output.renderer, {
42
+ content,
43
+ syntaxStyle,
44
+ streaming: true,
45
+ renderBlock: createMarkdownCodeBlockRenderer({ latex: render, math: render }),
46
+ })
47
+ output.renderer.root.add(markdown)
48
+ await output.renderOnce()
49
+ return { ...output, markdown, palette }
50
+ }
51
+
52
+ test.each(["latex", "math", "tex", "LATEX title=example"])("renders a %s fence", async (language) => {
53
+ const output = await setup(`\`\`\`${language}\n\\frac{1}{2}\n\`\`\``)
54
+ const formula = output.markdown.getChildren()[0]?.getChildren()[0]
55
+ expect(formula).toBeInstanceOf(TextRenderable)
56
+ if (!(formula instanceof TextRenderable)) throw new Error("Expected a formula")
57
+ expect(formula.height).toBe(3)
58
+ expect(formula.chunks.find((chunk) => chunk.text === "1")?.fg?.equals(RGBA.fromHex("#abcdef"))).toBe(true)
59
+ expect(output.captureCharFrame()).toContain("1")
60
+ expect(output.captureCharFrame()).toContain("2")
61
+ expect(output.captureCharFrame()).not.toContain("\\frac")
62
+ })
63
+
64
+ test.each([
65
+ String.raw`\frac{1}{`,
66
+ String.raw`\unsupported{x}`,
67
+ String.raw`\cfrac[x]{1}{2}`,
68
+ String.raw`\left\unknown x\right)`,
69
+ String.raw`\begin{array}{p{2cm}}x\end{array}`,
70
+ String.raw`\documentclass{article}
71
+ \begin{document}
72
+ Hello
73
+ \end{document}`,
74
+ ])("preserves invalid or unsupported math as source: %s", async (source) => {
75
+ const output = await setup(`\`\`\`latex\n${source}\n\`\`\``)
76
+ const block = output.markdown.getChildren()[0]
77
+ expect(block).toBeInstanceOf(CodeRenderable)
78
+ if (!(block instanceof CodeRenderable)) throw new Error("Expected source fallback")
79
+ expect(block.content).toBe(source)
80
+ })
81
+
82
+ test.each([
83
+ String.raw`\sqrt[\frac{1}{2}]{x}`,
84
+ String.raw`\left\|v\right\|`,
85
+ String.raw`\left(A\rightarrow B\right)`,
86
+ String.raw`\begin{aligned}a&=b+c\\&=d\end{aligned}`,
87
+ String.raw`\displaylines{x=1\\y=2}`,
88
+ String.raw`\cfrac[l]{1}{12345}`,
89
+ String.raw`\underbrace{a+b+c}_{n}`,
90
+ String.raw`\begin{array}{l|r}a&wide\\long&b\end{array}`,
91
+ ])("renders structured math through the Markdown adapter: %s", async (source) => {
92
+ const output = await setup(`\`\`\`latex\n${source}\n\`\`\``)
93
+ expect(output.markdown.getChildren()[0]).toBeInstanceOf(ScrollBoxRenderable)
94
+ expect(output.markdown.getChildren()[0]?.getChildren()[0]).toBeInstanceOf(TextRenderable)
95
+ expect(output.captureCharFrame()).not.toContain("\\")
96
+ })
97
+
98
+ test("renders the next valid formula after an incomplete streaming prefix", async () => {
99
+ const output = await setup("```latex\n\\frac{1}{")
100
+ expect(output.markdown.getChildren()[0]).toBeInstanceOf(CodeRenderable)
101
+
102
+ output.markdown.content += "2}"
103
+ await output.renderOnce()
104
+ expect(output.markdown.getChildren()[0]?.getChildren()[0]).toBeInstanceOf(TextRenderable)
105
+ expect(output.captureCharFrame()).not.toContain("\\frac")
106
+
107
+ output.markdown.content += "\n```"
108
+ output.markdown.streaming = false
109
+ await output.renderOnce()
110
+ expect(output.markdown.getChildren()[0]?.getChildren()[0]).toBeInstanceOf(TextRenderable)
111
+ })
112
+
113
+ test("renders the final formula when the last text update is applied before completion", async () => {
114
+ const output = await setup("```latex\n\\frac{1}{")
115
+ output.markdown.content += "2}\n```"
116
+ output.markdown.streaming = false
117
+ await output.renderOnce()
118
+ expect(output.markdown.getChildren().filter((child) => child instanceof ScrollBoxRenderable).length).toBe(1)
119
+ expect(output.captureCharFrame()).not.toContain("\\frac")
120
+ })
121
+
122
+ test("retains the last valid Unicode formula while the next fraction is incomplete", async () => {
123
+ const output = await setup("```latex\n\\frac{a_1+b_1}{c_1+d_1}")
124
+ const previous = output.captureCharFrame()
125
+ output.markdown.content += "+\\frac{a_"
126
+ await output.renderOnce()
127
+ expect(output.markdown.getChildren()[0]).toBeInstanceOf(ScrollBoxRenderable)
128
+ expect(output.captureCharFrame()).toBe(previous)
129
+
130
+ output.markdown.content += "2+b_2}{c_2+d_2}"
131
+ await output.renderOnce()
132
+ expect(output.captureCharFrame()).not.toBe(previous)
133
+ expect(output.captureCharFrame()).not.toContain("\\frac")
134
+ })
135
+
136
+ test.each(["close", "stop"])("discards an incomplete preview when the stream ends: %s", async (end) => {
137
+ const output = await setup("```latex\nx^2")
138
+ output.markdown.content += " + \\frac{1}{"
139
+ await output.renderOnce()
140
+ expect(output.markdown.getChildren()[0]).toBeInstanceOf(ScrollBoxRenderable)
141
+
142
+ // A closing fence counts once its line ends.
143
+ if (end === "close") output.markdown.content += "\n```\n"
144
+ if (end === "stop") output.markdown.streaming = false
145
+ await output.renderOnce()
146
+ expect(output.markdown.getChildren()[0]).toBeInstanceOf(CodeRenderable)
147
+ })
148
+
149
+ test("a closed fence that stops parsing shows its source after a rendered formula", async () => {
150
+ const output = await setup("```math\n\\frac{")
151
+ output.markdown.content += "1}{2}\n"
152
+ await output.renderOnce()
153
+ expect(output.markdown.getChildren()[0]).toBeInstanceOf(ScrollBoxRenderable)
154
+ output.markdown.content += "\\badunknown\n```\n"
155
+ output.markdown.streaming = false
156
+ await output.renderOnce()
157
+ const fallback = output.markdown.getChildren()[0]
158
+ expect(fallback).toBeInstanceOf(CodeRenderable)
159
+ expect(fallback!.isDestroyed).toBe(false)
160
+ expect(output.captureCharFrame()).toContain("\\badunknown")
161
+ })
162
+
163
+ test("does not reuse another fence's preview or keep a removed fence's preview", async () => {
164
+ const output = await setup("```latex\nx^2\n```\n\n```latex\n\\frac{1}{")
165
+ expect(output.markdown.getChildren()[1]).toBeInstanceOf(CodeRenderable)
166
+
167
+ output.markdown.content = ""
168
+ await output.renderOnce()
169
+ output.markdown.content = "```latex\nx^2 + \\frac{1}{"
170
+ await output.renderOnce()
171
+ expect(output.markdown.getChildren()[0]).toBeInstanceOf(CodeRenderable)
172
+ })
173
+
174
+ test("does not leave a stale formula when a stream ends with invalid math", async () => {
175
+ const output = await setup("```latex\nx^2")
176
+ expect(output.markdown.getChildren()[0]?.getChildren()[0]).toBeInstanceOf(TextRenderable)
177
+
178
+ output.markdown.content += " + \\unsupported{x}\n```"
179
+ output.markdown.streaming = false
180
+ await output.renderOnce()
181
+ expect(output.markdown.getChildren()[0]).toBeInstanceOf(CodeRenderable)
182
+ })
183
+
184
+ test("keeps a matrix and surrounding Markdown intact in a narrow terminal", async () => {
185
+ const output = await setup("Before\n\n```math\n\\begin{pmatrix}a & b \\\\ c & d\\end{pmatrix}\n```\n\nAfter", 32)
186
+ await output.renderOnce()
187
+ const frame = output.captureCharFrame()
188
+ expect(frame).toContain("Before")
189
+ expect(frame).toContain("a b")
190
+ expect(frame).toContain("c d")
191
+ expect(frame).toContain("After")
192
+ expect(frame).not.toContain("pmatrix")
193
+ })
194
+
195
+ test("leaves ordinary code fences alone", async () => {
196
+ const output = await setup("```typescript\nconst x = 2\n```")
197
+ expect(output.markdown.getChildren()[0]).toBeInstanceOf(CodeRenderable)
198
+ })
199
+
200
+ test("allows wide formulas to scroll horizontally without wrapping", async () => {
201
+ const output = await setup(
202
+ "```latex\n\\text{Start a very long formula with enough content to overflow Finish}\n```",
203
+ 24,
204
+ )
205
+ const viewport = output.markdown.getChildren()[0]
206
+ expect(viewport).toBeInstanceOf(ScrollBoxRenderable)
207
+ if (!(viewport instanceof ScrollBoxRenderable)) throw new Error("Expected a horizontal viewport")
208
+ expect(output.captureCharFrame()).toContain("Start")
209
+ expect(output.captureCharFrame()).not.toContain("Finish")
210
+ expect(viewport.height).toBe(1)
211
+
212
+ await output.mockMouse.scroll(2, 1, "right")
213
+ await output.renderOnce()
214
+ expect(viewport.scrollLeft).toBeGreaterThan(0)
215
+
216
+ viewport.scrollLeft = viewport.scrollWidth
217
+ await output.renderOnce()
218
+ expect(output.captureCharFrame()).toContain("Finish")
219
+ expect(output.captureCharFrame()).not.toContain("Start")
220
+ })
221
+
222
+ test("subdues structure and emphasizes relations using the theme", async () => {
223
+ const output = await setup("```latex\nx=\\sqrt{\\frac{1}{2}}\n```")
224
+ const formula = output.markdown.getChildren()[0]?.getChildren()[0]
225
+ if (!(formula instanceof TextRenderable)) throw new Error("Expected Unicode math")
226
+ for (const mark of ["\u2500", "\u2502", "\u256d", "\u256f", "\u2570"]) {
227
+ expect(formula.chunks.find((chunk) => chunk.text === mark)?.fg?.equals(RGBA.fromHex(output.palette.subdued))).toBe(
228
+ true,
229
+ )
230
+ }
231
+ expect(formula.chunks.find((chunk) => chunk.text === "x")?.fg?.equals(RGBA.fromHex(output.palette.text))).toBe(true)
232
+ expect(formula.chunks.find((chunk) => chunk.text === "=")?.attributes).toBe(TextAttributes.BOLD)
233
+
234
+ output.palette.text = "#123456"
235
+ output.palette.subdued = "#789abc"
236
+ output.markdown.refreshStyles()
237
+ await output.renderOnce()
238
+ const updated = output.markdown.getChildren()[0]?.getChildren()[0]
239
+ if (!(updated instanceof TextRenderable)) throw new Error("Expected Unicode math")
240
+ expect(updated.chunks.find((chunk) => chunk.text === "x")?.fg?.equals(RGBA.fromHex(output.palette.text))).toBe(true)
241
+ for (const mark of ["\u2500", "\u2502", "\u256d", "\u256f", "\u2570"]) {
242
+ expect(updated.chunks.find((chunk) => chunk.text === mark)?.fg?.equals(RGBA.fromHex(output.palette.subdued))).toBe(
243
+ true,
244
+ )
245
+ }
246
+ })
247
+
248
+ test.each([String.raw`\text{${"\u4e2d\u6587"}}=x`, String.raw`\frac{\text{${"\u4e2d\u6587"}}}{abcd}=x`])(
249
+ "preserves wide-character alignment: %s",
250
+ async (source) => {
251
+ const layout = renderLatex(source)
252
+ const output = await setup(`\`\`\`latex\n${source}\n\`\`\``, layout.width)
253
+ const viewport = output.markdown.getChildren()[0]
254
+ if (!(viewport instanceof ScrollBoxRenderable)) throw new Error("Expected math viewport")
255
+ const formula = viewport.getChildren()[0]
256
+ if (!(formula instanceof TextRenderable)) throw new Error("Expected Unicode math")
257
+ expect(
258
+ formula.chunks
259
+ .map((chunk) => chunk.text)
260
+ .join("")
261
+ .split("\n")
262
+ .map((line) => line.trimEnd())
263
+ .join("\n"),
264
+ ).toBe(layout.toString())
265
+ expect(viewport.scrollWidth).toBe(layout.width)
266
+ },
267
+ )
@@ -0,0 +1,116 @@
1
+ import {
2
+ CodeRenderable,
3
+ RenderableEvents,
4
+ ScrollBoxRenderable,
5
+ StyledText,
6
+ TextRenderable,
7
+ createTextAttributes,
8
+ parseColor,
9
+ type ColorInput,
10
+ type MarkdownCodeBlockRenderer,
11
+ type RenderContext,
12
+ } from "@opentui/core"
13
+ import stringWidth from "string-width"
14
+ import { renderLatex } from "./render"
15
+ import { LatexParseError, type MathLayout } from "./types"
16
+
17
+ export type LatexOptions = {
18
+ text: ColorInput
19
+ subdued: ColorInput
20
+ }
21
+
22
+ type LatexFrame = {
23
+ source: string
24
+ layout: MathLayout
25
+ }
26
+
27
+ export function createLatexCodeBlockRenderer(
28
+ context: RenderContext,
29
+ options: () => LatexOptions,
30
+ ): MarkdownCodeBlockRenderer {
31
+ const lastGood = new Map<string, LatexFrame>()
32
+ return (block, render) => {
33
+ const fallback = render.defaultRender()
34
+ const key = fallback?.id
35
+ const previous = key ? lastGood.get(key) : undefined
36
+ const retained = previous && block.text.startsWith(previous.source) ? previous : undefined
37
+ // A fence still streaming in keeps the last formula that parsed.
38
+ const streaming = fallback instanceof CodeRenderable && fallback.streaming && !block.closed
39
+ const layout = layoutLatex(block.text)
40
+ const frame: LatexFrame | undefined = layout
41
+ ? { source: block.text, layout }
42
+ : streaming && retained
43
+ ? { ...retained }
44
+ : undefined
45
+ if (!frame) return fallback ?? undefined
46
+ const palette = options()
47
+ const text = parseColor(palette.text)
48
+ const subdued = parseColor(palette.subdued)
49
+ const formula = new TextRenderable(context, {
50
+ content: new StyledText(
51
+ frame.layout.cells.flatMap((row, index) => [
52
+ ...Array.from(row).flatMap((cell, column) => {
53
+ // Wide glyphs already occupy the following cell; do not emit another space for it.
54
+ if (column > 0 && stringWidth(row[column - 1]?.char ?? "") > 1) return []
55
+ return [
56
+ {
57
+ __isChunk: true as const,
58
+ text: cell?.char ?? " ",
59
+ fg: /^[()[\]{}|\u221a\u239b-\u23ad\u2500-\u257f]$/u.test(cell?.char ?? "") ? subdued : text,
60
+ attributes: createTextAttributes({
61
+ bold: cell?.style?.bold || /^[=<>\u2260\u2261\u2264\u2265\u2248]$/u.test(cell?.char ?? ""),
62
+ italic: cell?.style?.italic,
63
+ dim: cell?.style?.dim,
64
+ }),
65
+ },
66
+ ]
67
+ }),
68
+ ...(index < frame.layout.height - 1 ? [{ __isChunk: true as const, text: "\n", fg: text }] : []),
69
+ ]),
70
+ ),
71
+ width: "100%",
72
+ minWidth: frame.layout.width,
73
+ height: frame.layout.height,
74
+ wrapMode: "none",
75
+ selectable: false,
76
+ flexShrink: 0,
77
+ })
78
+ const viewport = new ScrollBoxRenderable(context, {
79
+ width: "100%",
80
+ height: frame.layout.height,
81
+ flexShrink: 0,
82
+ marginTop: 1,
83
+ scrollX: true,
84
+ scrollY: false,
85
+ onMouseScroll(event) {
86
+ if (event.modifiers.shift || event.scroll?.direction === "left" || event.scroll?.direction === "right") {
87
+ event.stopPropagation()
88
+ }
89
+ },
90
+ })
91
+ // The setters opt out of automatic scrollbar visibility; constructor options do not.
92
+ viewport.horizontalScrollBar.visible = false
93
+ viewport.verticalScrollBar.visible = false
94
+ viewport.add(formula)
95
+ if (key) {
96
+ lastGood.set(key, frame)
97
+ viewport.once(RenderableEvents.DESTROYED, () => {
98
+ // Markdown destroys the old block before constructing its replacement in the same stack.
99
+ queueMicrotask(() => {
100
+ if (lastGood.get(key) === frame) lastGood.delete(key)
101
+ })
102
+ })
103
+ }
104
+ return viewport
105
+ }
106
+ }
107
+
108
+ function layoutLatex(source: string) {
109
+ try {
110
+ return renderLatex(source, { strict: true, displayMode: true })
111
+ } catch (error) {
112
+ // Preserve the exact source for incomplete math, unsupported commands, and oversized input.
113
+ if (error instanceof LatexParseError || error instanceof RangeError) return undefined
114
+ throw error
115
+ }
116
+ }
@@ -0,0 +1,23 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { renderLatexToString } from "./render"
3
+
4
+ describe("parser rendering regressions", () => {
5
+ test.each([
6
+ [String.raw`\|v\|`, "║v║"],
7
+ [String.raw`\left\|v\right\|`, "║v║"],
8
+ [String.raw`\left|v\right|`, "│v│"],
9
+ [String.raw`\left(A\rightarrow B\right)`, "(A → B)"],
10
+ [String.raw`\left\lbrace x\right\rbrace`, "{x}"],
11
+ [String.raw`\operatorname{arg\,max} x`, "arg max x"],
12
+ [String.raw`\textrm{if }x`, "if x"],
13
+ [String.raw`\displaylines{x=1\\y=2}`, "x = 1\n\ny = 2"],
14
+ ])("renders supported syntax without leaking or losing tokens: %s", (source, expected) => {
15
+ expect(renderLatexToString(source, { strict: true })).toBe(expected)
16
+ })
17
+
18
+ test("renders empty aligned cells like explicitly empty groups", () => {
19
+ expect(renderLatexToString(String.raw`\begin{aligned}&=x\\&=y\end{aligned}`, { strict: true })).toBe(
20
+ renderLatexToString(String.raw`\begin{aligned}{}&=x\\{}&=y\end{aligned}`, { strict: true }),
21
+ )
22
+ })
23
+ })