@cueloop/schema 0.1.0-alpha.6 → 0.1.0-alpha.61

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.
@@ -0,0 +1,195 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { inlineRuns, type InlineRun } from "./inline";
3
+
4
+ /** Every run concatenated back in order must equal the source (nothing dropped). */
5
+ function reconstruct(runs: InlineRun[]): string {
6
+ return runs.map((run) => run.text).join("");
7
+ }
8
+
9
+ /** Each visible run's text must sit at its claimed source offset. */
10
+ function offsetsAreExact(source: string, runs: InlineRun[]): boolean {
11
+ return runs.every(
12
+ (run) =>
13
+ run.start === null || source.slice(run.start, run.start + run.text.length) === run.text,
14
+ );
15
+ }
16
+
17
+ /** The visible (non-marker) runs, which are what an anchor can resolve against. */
18
+ function visible(runs: InlineRun[]): InlineRun[] {
19
+ return runs.filter((run) => run.start !== null);
20
+ }
21
+
22
+ describe("inlineRuns", () => {
23
+ test("plain text is a single positioned run", () => {
24
+ // Arrange
25
+ const source = "just plain words";
26
+
27
+ // Act
28
+ const runs = inlineRuns(source);
29
+
30
+ // Assert
31
+ expect(runs).toEqual([{ text: "just plain words", role: "text", start: 0 }]);
32
+ });
33
+
34
+ test("strong emphasis: markers concealed, content positioned", () => {
35
+ // Arrange
36
+ const source = "a **bold** b";
37
+
38
+ // Act
39
+ const runs = inlineRuns(source);
40
+
41
+ // Assert
42
+ expect(runs).toEqual([
43
+ { text: "a ", role: "text", start: 0 },
44
+ { text: "**", role: "marker", start: null },
45
+ { text: "bold", role: "strong", start: 4 },
46
+ { text: "**", role: "marker", start: null },
47
+ { text: " b", role: "text", start: 10 },
48
+ ]);
49
+ expect(reconstruct(runs)).toBe(source);
50
+ expect(offsetsAreExact(source, runs)).toBe(true);
51
+ });
52
+
53
+ test("em, code, and strike each conceal their markers and keep offsets", () => {
54
+ // Assert
55
+ for (const [source, role, inner] of [
56
+ ["x *em* y", "em", "em"],
57
+ ["x `code` y", "code", "code"],
58
+ ["x ~~gone~~ y", "strike", "gone"],
59
+ ] as const) {
60
+ const runs = inlineRuns(source);
61
+ const content = runs.find((run) => run.role === role)!;
62
+
63
+ expect(content.text).toBe(inner);
64
+ expect(source.slice(content.start!, content.start! + inner.length)).toBe(inner);
65
+ expect(reconstruct(runs)).toBe(source);
66
+ expect(runs.filter((run) => run.role === "marker").every((run) => run.start === null)).toBe(
67
+ true,
68
+ );
69
+ }
70
+ });
71
+
72
+ test("code spans do not parse markup inside them", () => {
73
+ // Act
74
+ const runs = inlineRuns("call `a**b**c` now");
75
+
76
+ // Assert - the backtick content is one literal code run, no strong inside
77
+ const code = runs.find((run) => run.role === "code")!;
78
+
79
+ expect(code.text).toBe("a**b**c");
80
+ expect(runs.some((run) => run.role === "strong")).toBe(false);
81
+ });
82
+
83
+ test("links: label positioned with href, brackets and url concealed", () => {
84
+ // Arrange
85
+ const source = "see [the docs](https://example.com) here";
86
+
87
+ // Act
88
+ const runs = inlineRuns(source);
89
+ const label = runs.find((run) => run.role === "link")!;
90
+
91
+ // Assert
92
+ expect(label).toEqual({
93
+ text: "the docs",
94
+ role: "link",
95
+ start: 5,
96
+ href: "https://example.com",
97
+ });
98
+ expect(reconstruct(runs)).toBe(source);
99
+ // the url text is a concealed marker, never a visible run
100
+ expect(visible(runs).some((run) => run.text.includes("https"))).toBe(false);
101
+ });
102
+
103
+ test("links: a destination with balanced parentheses stays whole", () => {
104
+ // Arrange
105
+ const source = "see [foo](https://en.wikipedia.org/wiki/Foo_(bar)) here";
106
+
107
+ // Act
108
+ const runs = inlineRuns(source);
109
+ const label = runs.find((run) => run.role === "link")!;
110
+
111
+ // Assert
112
+ expect(label.href).toBe("https://en.wikipedia.org/wiki/Foo_(bar)");
113
+ expect(reconstruct(runs)).toBe(source);
114
+ });
115
+
116
+ test("links: an unclosed destination never becomes a link", () => {
117
+ // Arrange
118
+ const source = "see [foo](https://example.com/(open here";
119
+
120
+ // Act
121
+ const runs = inlineRuns(source);
122
+
123
+ // Assert
124
+ expect(runs.some((run) => run.role === "link")).toBe(false);
125
+ expect(reconstruct(runs)).toBe(source);
126
+ });
127
+
128
+ test("nested emphasis: inner marker wins, both markers concealed", () => {
129
+ // Act
130
+ const runs = inlineRuns("**a *b* c**");
131
+
132
+ // Assert
133
+ expect(visible(runs)).toEqual([
134
+ { text: "a ", role: "strong", start: 2 },
135
+ { text: "b", role: "em", start: 5 },
136
+ { text: " c", role: "strong", start: 7 },
137
+ ]);
138
+ expect(reconstruct(runs)).toBe("**a *b* c**");
139
+ });
140
+
141
+ test("a lone em close is not stolen by an inner ** run", () => {
142
+ // Act - the em must span the whole thing, with **b** strong nested inside
143
+ const runs = inlineRuns("*a **b** c*");
144
+
145
+ // Assert
146
+ expect(runs.find((run) => run.role === "em" && run.text === "a ")).toBeDefined();
147
+ expect(runs.find((run) => run.role === "strong" && run.text === "b")).toBeDefined();
148
+ expect(reconstruct(runs)).toBe("*a **b** c*");
149
+ });
150
+
151
+ test("unbalanced markers fall back to literal text", () => {
152
+ // Assert
153
+ for (const source of ["**not closed", "a * b", "`open code", "[label](noclose"]) {
154
+ const runs = inlineRuns(source);
155
+
156
+ expect(reconstruct(runs)).toBe(source);
157
+ expect(runs.every((run) => run.role === "text" || run.role === "marker")).toBe(true);
158
+ expect(offsetsAreExact(source, runs)).toBe(true);
159
+ }
160
+ });
161
+
162
+ test("empty spans do not match", () => {
163
+ // Act
164
+ const runs = inlineRuns("a **** b `` c [](x)");
165
+
166
+ // Assert - nothing emphasized; all reconstructs
167
+ expect(reconstruct(runs)).toBe("a **** b `` c [](x)");
168
+ expect(runs.some((run) => ["strong", "em", "code", "link"].includes(run.role))).toBe(false);
169
+ });
170
+
171
+ test("backslash escapes render the punctuation literally, marker concealed", () => {
172
+ // Act
173
+ const runs = inlineRuns("not \\*emph\\* here");
174
+
175
+ // Assert - no em; the escaped stars are positioned text, backslashes concealed
176
+ expect(runs.some((run) => run.role === "em")).toBe(false);
177
+ expect(reconstruct(runs)).toBe("not \\*emph\\* here");
178
+ expect(offsetsAreExact("not \\*emph\\* here", runs)).toBe(true);
179
+ const star = runs.find((run) => run.text === "*" && run.start !== null)!;
180
+
181
+ expect("not \\*emph\\* here"[star.start!]).toBe("*");
182
+ });
183
+
184
+ test("reconstruct + exact offsets hold on a mixed line", () => {
185
+ // Arrange
186
+ const source = "The **daemon** persists `sessions` to [disk](d) ~~fast~~";
187
+
188
+ // Act
189
+ const runs = inlineRuns(source);
190
+
191
+ // Assert
192
+ expect(reconstruct(runs)).toBe(source);
193
+ expect(offsetsAreExact(source, runs)).toBe(true);
194
+ });
195
+ });
package/src/inline.ts ADDED
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Inline markdown tokenizer: turns one block's text into styled runs while
3
+ * preserving exact source offsets, so the review surface can conceal the markup
4
+ * markers yet keep quote anchors char-precise.
5
+ *
6
+ * Each run is either VISIBLE text - carrying `start`, its offset in the input -
7
+ * or a CONCEALED marker (`**`, `` ` ``, `[`, `](url)`, ...) with `start: null`.
8
+ * A null run occupies no source offset, exactly like a word-diff removal, so the
9
+ * renderer's offset-mapping (overlayMarks / renderedOffsetFor / workRangeForRendered)
10
+ * paints highlights across the visible letters and skips the markers unchanged.
11
+ *
12
+ * Pure and dependency-free: the parse tree never escapes this module - the only
13
+ * output is the flat run list. Covers the plan subset: **strong**, *em*, `code`,
14
+ * ~~strike~~, [label](url), and backslash escapes. Unbalanced markup falls back
15
+ * to literal text.
16
+ */
17
+
18
+ /** What a visible run represents; a marker run is concealed markup, no emphasis. */
19
+ export type InlineRole = "text" | "strong" | "em" | "code" | "strike" | "link" | "marker";
20
+
21
+ export interface InlineRun {
22
+ text: string;
23
+ role: InlineRole;
24
+ /** Offset of this run in the input text; null for a concealed marker. */
25
+ start: number | null;
26
+ /** Link target, present only on `link` runs. */
27
+ href?: string;
28
+ }
29
+
30
+ /** An emphasis span opened by a delimiter at some index, once its close is found. */
31
+ interface Span {
32
+ /** Length of the opening marker (e.g. 2 for `**`). */
33
+ openLength: number;
34
+ /** Length of the closing marker. */
35
+ closeLength: number;
36
+ /** Index in `text` where the closing marker starts. */
37
+ closeIndex: number;
38
+ /** Emphasis role applied to the span's (recursively parsed) content. */
39
+ role: "strong" | "em" | "strike";
40
+ }
41
+
42
+ const PUNCTUATION = new Set(["*", "_", "`", "~", "[", "]", "(", ")", "\\"]);
43
+
44
+ /** Tokenize one block's text into visible + concealed-marker runs, in order. */
45
+ export function inlineRuns(text: string): InlineRun[] {
46
+ const runs: InlineRun[] = [];
47
+
48
+ tokenize(text, 0, "text", runs);
49
+
50
+ return runs;
51
+ }
52
+
53
+ /**
54
+ * Walk `source` (whose first character sits at absolute offset `base`), emitting
55
+ * plain text as `role` runs and recursing into emphasis spans. Links and code
56
+ * spans are handled inline because their content is not further emphasized the
57
+ * same way.
58
+ */
59
+ function tokenize(source: string, base: number, role: InlineRole, out: InlineRun[]): void {
60
+ let plainStart = 0;
61
+ let cursor = 0;
62
+ const flushPlain = (end: number): void => {
63
+ if (end > plainStart) {
64
+ out.push({ text: source.slice(plainStart, end), role, start: base + plainStart });
65
+ }
66
+ };
67
+
68
+ while (cursor < source.length) {
69
+ const char = source[cursor]!;
70
+
71
+ if (char === "\\" && cursor + 1 < source.length && PUNCTUATION.has(source[cursor + 1]!)) {
72
+ flushPlain(cursor);
73
+ out.push({ text: "\\", role: "marker", start: null });
74
+ out.push({ text: source[cursor + 1]!, role, start: base + cursor + 1 });
75
+ cursor += 2;
76
+ plainStart = cursor;
77
+ continue;
78
+ }
79
+
80
+ const link = matchLink(source, cursor);
81
+
82
+ if (link) {
83
+ flushPlain(cursor);
84
+ out.push({ text: source.slice(cursor, link.labelStart), role: "marker", start: null });
85
+ out.push({
86
+ text: source.slice(link.labelStart, link.labelEnd),
87
+ role: "link",
88
+ start: base + link.labelStart,
89
+ href: source.slice(link.hrefStart, link.hrefEnd),
90
+ });
91
+ out.push({ text: source.slice(link.labelEnd, link.end), role: "marker", start: null });
92
+ cursor = link.end;
93
+ plainStart = cursor;
94
+ continue;
95
+ }
96
+
97
+ const code = matchCode(source, cursor);
98
+
99
+ if (code) {
100
+ flushPlain(cursor);
101
+ out.push({ text: source.slice(cursor, code.contentStart), role: "marker", start: null });
102
+ out.push({
103
+ text: source.slice(code.contentStart, code.contentEnd),
104
+ role: "code",
105
+ start: base + code.contentStart,
106
+ });
107
+ out.push({ text: source.slice(code.contentEnd, code.end), role: "marker", start: null });
108
+ cursor = code.end;
109
+ plainStart = cursor;
110
+ continue;
111
+ }
112
+
113
+ const span = matchEmphasis(source, cursor);
114
+
115
+ if (span) {
116
+ flushPlain(cursor);
117
+ out.push({
118
+ text: source.slice(cursor, cursor + span.openLength),
119
+ role: "marker",
120
+ start: null,
121
+ });
122
+ const contentStart = cursor + span.openLength;
123
+
124
+ tokenize(source.slice(contentStart, span.closeIndex), base + contentStart, span.role, out);
125
+ out.push({
126
+ text: source.slice(span.closeIndex, span.closeIndex + span.closeLength),
127
+ role: "marker",
128
+ start: null,
129
+ });
130
+ cursor = span.closeIndex + span.closeLength;
131
+ plainStart = cursor;
132
+ continue;
133
+ }
134
+
135
+ cursor++;
136
+ }
137
+ flushPlain(source.length);
138
+ }
139
+
140
+ /** A `[label](url)` link at `index`, or null. Empty label or url does not match. */
141
+ function matchLink(
142
+ text: string,
143
+ index: number,
144
+ ): {
145
+ labelStart: number;
146
+ labelEnd: number;
147
+ hrefStart: number;
148
+ hrefEnd: number;
149
+ end: number;
150
+ } | null {
151
+ if (text[index] !== "[") return null;
152
+ const labelStart = index + 1;
153
+ const labelEnd = text.indexOf("]", labelStart);
154
+
155
+ if (labelEnd < 0 || labelEnd === labelStart) return null;
156
+ if (text[labelEnd + 1] !== "(") return null;
157
+ const hrefStart = labelEnd + 2;
158
+ // the destination may carry balanced parentheses (wiki URLs); the span ends
159
+ // at the first unmatched closer
160
+ let depth = 0;
161
+
162
+ for (let scan = hrefStart; scan < text.length; scan++) {
163
+ const character = text[scan];
164
+
165
+ if (character === "(") depth++;
166
+ else if (character === ")") {
167
+ if (depth > 0) {
168
+ depth--;
169
+ continue;
170
+ }
171
+ if (scan === hrefStart) return null;
172
+
173
+ return { labelStart, labelEnd, hrefStart, hrefEnd: scan, end: scan + 1 };
174
+ }
175
+ }
176
+
177
+ return null;
178
+ }
179
+
180
+ /** A `` `code` `` span at `index` (n backticks .. n backticks), or null. */
181
+ function matchCode(
182
+ text: string,
183
+ index: number,
184
+ ): { contentStart: number; contentEnd: number; end: number } | null {
185
+ if (text[index] !== "`") return null;
186
+ let fence = 0;
187
+
188
+ while (text[index + fence] === "`") fence++;
189
+ const contentStart = index + fence;
190
+ const closer = "`".repeat(fence);
191
+ const contentEnd = text.indexOf(closer, contentStart);
192
+
193
+ if (contentEnd < 0 || contentEnd === contentStart) return null;
194
+
195
+ return { contentStart, contentEnd, end: contentEnd + fence };
196
+ }
197
+
198
+ /** A `**strong**`, `*em*`, or `~~strike~~` span at `index`, or null. */
199
+ function matchEmphasis(text: string, index: number): Span | null {
200
+ const two = text.slice(index, index + 2);
201
+
202
+ if (two === "**") return closingSpan(text, index, 2, "strong");
203
+ if (two === "~~") return closingSpan(text, index, 2, "strike");
204
+ if (text[index] === "*") return closingSpan(text, index, 1, "em");
205
+
206
+ return null;
207
+ }
208
+
209
+ /** Find the matching close for a marker of `length` at `index`; null if unbalanced. */
210
+ function closingSpan(
211
+ text: string,
212
+ index: number,
213
+ length: number,
214
+ role: "strong" | "em" | "strike",
215
+ ): Span | null {
216
+ const marker = text.slice(index, index + length);
217
+ const contentStart = index + length;
218
+ const closeIndex =
219
+ length === 1 ? findLoneStar(text, contentStart) : text.indexOf(marker, contentStart);
220
+
221
+ if (closeIndex < 0 || closeIndex === contentStart) return null; // unbalanced or empty
222
+
223
+ return { openLength: length, closeLength: length, closeIndex, role };
224
+ }
225
+
226
+ /** Index of the next standalone `*` (not part of a `**` run), or -1. */
227
+ function findLoneStar(text: string, from: number): number {
228
+ let index = from;
229
+
230
+ while (index < text.length) {
231
+ if (text[index] === "*") {
232
+ if (text[index + 1] !== "*") return index;
233
+ while (text[index] === "*") index++; // skip the whole `**` run
234
+ continue;
235
+ }
236
+ index++;
237
+ }
238
+
239
+ return -1;
240
+ }
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { parseBlocks, blockToMd, sectionOf } from "./markdown";
2
+ import { parseBlocks, blockToMd, sectionOf, stripLeadingBlockMarker } from "./markdown";
3
3
 
4
4
  const SAMPLE = `# Title
5
5
 
@@ -29,8 +29,11 @@ const y = 2;
29
29
 
30
30
  describe("parseBlocks", () => {
31
31
  test("parses every block kind with source line ranges", () => {
32
+ // Act
32
33
  const blocks = parseBlocks(SAMPLE);
33
- expect(blocks.map((b) => b.kind)).toEqual([
34
+
35
+ // Assert
36
+ expect(blocks.map((block) => block.kind)).toEqual([
34
37
  "h1",
35
38
  "h2",
36
39
  "p",
@@ -43,7 +46,8 @@ describe("parseBlocks", () => {
43
46
  "quote",
44
47
  "hr",
45
48
  ]);
46
- const code = blocks.find((b) => b.kind === "code")!;
49
+ const code = blocks.find((block) => block.kind === "code")!;
50
+
47
51
  expect(code.lang).toBe("ts");
48
52
  expect(code.text).toBe("const x = 1;\nconst y = 2;");
49
53
  // fence lines included in the source range
@@ -51,50 +55,101 @@ describe("parseBlocks", () => {
51
55
  });
52
56
 
53
57
  test("multi-line paragraph keeps its text and range", () => {
58
+ // Arrange
54
59
  const blocks = parseBlocks(SAMPLE);
55
- const p = blocks.find((b) => b.kind === "p")!;
56
- expect(p.text).toBe("A paragraph that\nspans two lines.");
57
- expect(p.lineEnd - p.lineStart).toBe(1);
60
+ const paragraph = blocks.find((block) => block.kind === "p")!;
61
+
62
+ // Assert
63
+ expect(paragraph.text).toBe("A paragraph that\nspans two lines.");
64
+ expect(paragraph.lineEnd - paragraph.lineStart).toBe(1);
58
65
  });
59
66
 
60
67
  test("line ranges index into the source", () => {
68
+ // Arrange
61
69
  const lines = SAMPLE.split("\n");
62
- for (const b of parseBlocks(SAMPLE)) {
63
- if (b.kind === "code") {
64
- expect(lines[b.lineStart]!.startsWith("```")).toBe(true);
65
- } else if (b.kind === "h2") {
66
- expect(lines[b.lineStart]!.startsWith("## ")).toBe(true);
70
+
71
+ // Assert
72
+ for (const block of parseBlocks(SAMPLE)) {
73
+ if (block.kind === "code") {
74
+ expect(lines[block.lineStart]!.startsWith("```")).toBe(true);
75
+ } else if (block.kind === "h2") {
76
+ expect(lines[block.lineStart]!.startsWith("## ")).toBe(true);
67
77
  }
68
78
  }
69
79
  });
70
80
 
71
81
  test("round-trips through blockToMd", () => {
82
+ // Arrange
72
83
  const blocks = parseBlocks(SAMPLE);
73
- let oli = 0;
84
+ let orderedItemCount = 0;
74
85
  const rebuilt = blocks
75
- .map((b) => {
76
- oli = b.kind === "oli" ? oli + 1 : 0;
77
- return blockToMd(b, oli || 1);
86
+ .map((block) => {
87
+ orderedItemCount = block.kind === "oli" ? orderedItemCount + 1 : 0;
88
+
89
+ return blockToMd(block, orderedItemCount || 1);
78
90
  })
79
91
  .join("\n\n");
92
+
93
+ // Act
80
94
  // re-parsing the rebuild yields the same kinds and texts
81
95
  const again = parseBlocks(rebuilt);
82
- expect(again.map((b) => [b.kind, b.text])).toEqual(blocks.map((b) => [b.kind, b.text]));
96
+
97
+ // Assert
98
+ expect(again.map((block) => [block.kind, block.text])).toEqual(
99
+ blocks.map((block) => [block.kind, block.text]),
100
+ );
83
101
  });
84
102
 
85
103
  test("unknown constructs degrade to paragraphs, no content lost", () => {
104
+ // Arrange
86
105
  const md = "| a | b |\n|---|---|\n| 1 | 2 |";
106
+
107
+ // Act
87
108
  const blocks = parseBlocks(md);
88
- expect(blocks.map((b) => b.text).join("\n")).toContain("| a | b |");
109
+
110
+ // Assert
111
+ expect(blocks.map((block) => block.text).join("\n")).toContain("| a | b |");
89
112
  });
90
113
  });
91
114
 
92
115
  describe("sectionOf", () => {
93
116
  test("returns the nearest preceding heading", () => {
117
+ // Arrange
94
118
  const blocks = parseBlocks(SAMPLE);
95
- const oliIdx = blocks.findIndex((b) => b.kind === "oli");
96
- expect(sectionOf(blocks, oliIdx)).toBe("Steps");
97
- const pIdx = blocks.findIndex((b) => b.kind === "p");
98
- expect(sectionOf(blocks, pIdx)).toBe("Context");
119
+
120
+ // Assert
121
+ const orderedItemIndex = blocks.findIndex((block) => block.kind === "oli");
122
+
123
+ expect(sectionOf(blocks, orderedItemIndex)).toBe("Steps");
124
+ const paragraphIndex = blocks.findIndex((block) => block.kind === "p");
125
+
126
+ expect(sectionOf(blocks, paragraphIndex)).toBe("Context");
127
+ });
128
+ });
129
+
130
+ describe("stripLeadingBlockMarker", () => {
131
+ test("strips the marker the parser strips for every marked block kind", () => {
132
+ // Assert
133
+ expect(stripLeadingBlockMarker("# Heading")).toBe("Heading");
134
+ expect(stripLeadingBlockMarker("### Heading")).toBe("Heading");
135
+ expect(stripLeadingBlockMarker("- bullet item")).toBe("bullet item");
136
+ expect(stripLeadingBlockMarker("3. ordered item")).toBe("ordered item");
137
+ expect(stripLeadingBlockMarker("> quoted line")).toBe("quoted line");
138
+ });
139
+
140
+ test("agrees with the text the parser produces", () => {
141
+ // Arrange
142
+ const source = "- This is a dummy plan - confirm the item";
143
+
144
+ // Act
145
+ const [listBlock] = parseBlocks(source);
146
+
147
+ // Assert
148
+ expect(stripLeadingBlockMarker(source)).toBe(listBlock!.text);
149
+ });
150
+
151
+ test("leaves an unmarked line untouched", () => {
152
+ // Assert
153
+ expect(stripLeadingBlockMarker("a plain paragraph")).toBe("a plain paragraph");
99
154
  });
100
155
  });