@jsb188/ai-chat 0.0.0-stage → 1.1.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.
Files changed (51) hide show
  1. package/README.md +109 -2
  2. package/VERIFICATION.md +118 -0
  3. package/benchmarks/browser.mjs +204 -0
  4. package/benchmarks/streaming.mjs +89 -0
  5. package/package.json +36 -5
  6. package/src/main.ts +5 -0
  7. package/src/modules/AIChatContent.tsx +84 -0
  8. package/src/modules/AgentNoteActionsMenu.tsx +121 -0
  9. package/src/modules/AgentNoteBootstrapProgress.tsx +41 -0
  10. package/src/modules/AgentNoteItem.helpers.ts +115 -0
  11. package/src/modules/AgentNoteItem.tsx +232 -0
  12. package/src/modules/AgentNotes.constants.ts +10 -0
  13. package/src/modules/AgentNotes.helpers.ts +274 -0
  14. package/src/modules/AgentNotes.hooks.ts +449 -0
  15. package/src/modules/AgentNotes.tsx +74 -0
  16. package/src/modules/AgentNotes.types.ts +50 -0
  17. package/src/modules/AgentNotesCollection.hooks.ts +69 -0
  18. package/src/modules/AgentNotesSection.tsx +145 -0
  19. package/src/parser.ts +4 -0
  20. package/src/types/content.ts +103 -0
  21. package/src/ui/AIChatUI.css +557 -0
  22. package/src/ui/AIChatUI.tsx +816 -0
  23. package/src/ui/AgentNotesUI.tsx +375 -0
  24. package/src/ui/AgentNotesUI.types.ts +19 -0
  25. package/src/ui/ChatBlocks.tsx +92 -0
  26. package/src/ui/ChatCodeBlock.tsx +16 -0
  27. package/src/ui/ChatInline.helpers.ts +20 -0
  28. package/src/ui/ChatInline.tsx +89 -0
  29. package/src/ui/ChatTable.helpers.ts +37 -0
  30. package/src/ui/ChatTable.tsx +126 -0
  31. package/src/utils/contentIdentity.ts +108 -0
  32. package/src/utils/parseBlocks.helpers.ts +50 -0
  33. package/src/utils/parseBlocks.ts +266 -0
  34. package/src/utils/parseContent.helpers.ts +102 -0
  35. package/src/utils/parseContent.ts +33 -0
  36. package/src/utils/parseContentIncrementally.ts +46 -0
  37. package/src/utils/parseCsv.ts +99 -0
  38. package/src/utils/parseInline.helpers.ts +48 -0
  39. package/src/utils/parseInline.ts +396 -0
  40. package/src/utils/parseTable.ts +202 -0
  41. package/tests/AgentNotes.test.tsx +1672 -0
  42. package/tests/fixtures/content.ts +13 -0
  43. package/tests/parseContent.test.ts +227 -0
  44. package/tests/parseCsv.test.ts +82 -0
  45. package/tests/parseInline.test.ts +222 -0
  46. package/tests/renderContent.ssr.test.tsx +19 -0
  47. package/tests/renderContent.test.tsx +282 -0
  48. package/tests/streaming.test.ts +51 -0
  49. package/tests/streamingEquivalence.test.ts +265 -0
  50. package/tsconfig.json +16 -0
  51. package/vitest.config.ts +18 -0
@@ -0,0 +1,46 @@
1
+ import type { ChatContentStatus, ContentDocument, ParserLimits } from '../types/content.ts';
2
+ import { parseBlocks } from './parseBlocks.ts';
3
+ import { resolveLimits } from './parseBlocks.helpers.ts';
4
+ import { parseContent } from './parseContent.ts';
5
+ import { exceedsNodeBudget, getContentParseLimits, sameParserLimits, withContentParseLimits } from './parseContent.helpers.ts';
6
+
7
+ /*
8
+ * Retain stable source prefixes and Markdown cells without changing full-parser output or mutating earlier renders.
9
+ */
10
+ export function parseContentIncrementally(
11
+ previous: ContentDocument | null,
12
+ source: string,
13
+ status: ChatContentStatus = 'complete',
14
+ limits?: Partial<ParserLimits>,
15
+ ): ContentDocument {
16
+ const budget = resolveLimits(limits);
17
+ const firstBlock = previous?.blocks[0];
18
+ let document: ContentDocument;
19
+ if (
20
+ !previous ||
21
+ !firstBlock ||
22
+ !sameParserLimits(getContentParseLimits(previous), budget) ||
23
+ !source.startsWith(previous.source) ||
24
+ source.length > budget.inputLength ||
25
+ (firstBlock.kind === 'literal' && firstBlock.start === 0 && previous.blocks.length === 1)
26
+ ) {
27
+ document = parseContent(source, status, budget);
28
+ } else if (source === previous.source && status === previous.status) {
29
+ return previous;
30
+ } else {
31
+ // The final block can lose its boundary while streaming and merge with its predecessor.
32
+ const retained = previous.blocks.slice(0, Math.max(0, previous.blocks.length - 2));
33
+ const start = previous.blocks[retained.length]?.start ?? 0;
34
+ const parsed = parseBlocks(source, status, budget, { start, previous });
35
+ const blocks = [...retained, ...parsed.blocks];
36
+ document = exceedsNodeBudget(blocks, budget.nodes)
37
+ ? parseContent(source, status, budget)
38
+ : {
39
+ source,
40
+ status,
41
+ blocks,
42
+ diagnostics: [...previous.diagnostics.filter((diagnostic) => diagnostic.end <= start), ...parsed.diagnostics],
43
+ };
44
+ }
45
+ return withContentParseLimits(document, budget);
46
+ }
@@ -0,0 +1,99 @@
1
+ import type { ContentDiagnostic, ParserLimits, TableCell, TableRow } from '../types/content.ts';
2
+ import { resolveLimits } from './parseBlocks.helpers.ts';
3
+
4
+ export interface CsvParseResult {
5
+ valid: boolean;
6
+ rows: TableRow[];
7
+ diagnostics: ContentDiagnostic[];
8
+ }
9
+
10
+ /*
11
+ * Parse literal CSV records with explicit quote states and source-preserving ranges.
12
+ * Rows include the first-record header; completely blank outside-quote lines are ignored.
13
+ */
14
+ export function parseCsv(source: string, offset = 0, limits?: Partial<ParserLimits>): CsvParseResult {
15
+ const budget = resolveLimits(limits);
16
+ const rows: TableRow[] = [];
17
+ let cells: TableCell[] = [];
18
+ let state: 'FIELD_START' | 'UNQUOTED_FIELD' | 'QUOTED_FIELD' | 'AFTER_QUOTE' = 'FIELD_START';
19
+ let index = source[0] === '\uFEFF' ? 1 : 0;
20
+ let recordStart = index;
21
+ let fieldStart = index;
22
+ let value = '';
23
+ let width: number | undefined;
24
+
25
+ /*
26
+ * Return structured failure without exposing any partially promoted table.
27
+ */
28
+ function failure(code: ContentDiagnostic['code'], reason: string, start = index): CsvParseResult {
29
+ return { valid: false, rows: [], diagnostics: [{ code, reason, start: offset + start, end: offset + source.length }] };
30
+ }
31
+
32
+ /*
33
+ * Finish a literal field and reset only the field-specific scanner state.
34
+ */
35
+ function finishField(end: number) {
36
+ cells.push({ kind: 'literal', value, start: offset + fieldStart, end: offset + end });
37
+ value = '';
38
+ state = 'FIELD_START';
39
+ }
40
+
41
+ /*
42
+ * Validate and retain one record, including empty values and duplicate headers.
43
+ */
44
+ function finishRecord(end: number): CsvParseResult | undefined {
45
+ if (cells.length > budget.tableColumns) return failure('limit-exceeded', 'Table column limit exceeded.', recordStart);
46
+ if (width !== undefined && cells.length !== width)
47
+ return failure('malformed', 'CSV record width differs from its header.', recordStart);
48
+ if (rows.length > budget.tableRows) return failure('limit-exceeded', 'Table row limit exceeded.', recordStart);
49
+ width = cells.length;
50
+ rows.push({ cells, start: offset + recordStart, end: offset + end });
51
+ cells = [];
52
+ return undefined;
53
+ }
54
+
55
+ if (source.length > budget.inputLength) return failure('limit-exceeded', 'Input length limit exceeded.', 0);
56
+ while (index < source.length) {
57
+ const char = source[index];
58
+ if (state === 'QUOTED_FIELD') {
59
+ if (char === '"') {
60
+ if (source[index + 1] === '"') {
61
+ value += '"';
62
+ index++;
63
+ } else state = 'AFTER_QUOTE';
64
+ } else value += char;
65
+ } else if (char === ',' || char === '\r' || char === '\n') {
66
+ const blankLine = char !== ',' && index === recordStart && cells.length === 0 && state === 'FIELD_START';
67
+ if (!blankLine) finishField(index);
68
+ if (char !== ',') {
69
+ if (char === '\r' && source[index + 1] === '\n') index++;
70
+ if (!blankLine) {
71
+ const error = finishRecord(index + 1);
72
+ if (error) return error;
73
+ }
74
+ recordStart = index + 1;
75
+ } else if (cells.length >= budget.tableColumns) {
76
+ return failure('limit-exceeded', 'Table column limit exceeded.', recordStart);
77
+ }
78
+ fieldStart = index + 1;
79
+ } else if (state === 'AFTER_QUOTE') {
80
+ return failure('malformed', 'Unexpected content after a quoted CSV field.');
81
+ } else if (char === '"') {
82
+ if (state !== 'FIELD_START') return failure('malformed', 'Unexpected quote inside an unquoted CSV field.');
83
+ state = 'QUOTED_FIELD';
84
+ } else {
85
+ state = 'UNQUOTED_FIELD';
86
+ value += char;
87
+ }
88
+ if (value.length > budget.cellLength) return failure('limit-exceeded', 'Table cell length limit exceeded.', fieldStart);
89
+ index++;
90
+ }
91
+ if (state === 'QUOTED_FIELD') return failure('incomplete', 'Unclosed quoted CSV field.', fieldStart);
92
+ if (recordStart < source.length || cells.length > 0) {
93
+ finishField(source.length);
94
+ const error = finishRecord(source.length);
95
+ if (error) return error;
96
+ }
97
+ if (!rows.length) return failure('malformed', 'CSV has no header record.', 0);
98
+ return { valid: true, rows, diagnostics: [] };
99
+ }
@@ -0,0 +1,48 @@
1
+ import { DEFAULT_PARSER_LIMITS, type ParserLimits } from '../types/content.ts';
2
+
3
+ /*
4
+ * Accept explicit web/contact links and relative destinations without permitting browser scheme normalization bypasses.
5
+ */
6
+ export function getSafeLinkDestination(destination: string): string | null {
7
+ if (!destination || /[\s\u0000-\u001f\u007f-\u009f\\]/u.test(destination) || /&(?:#(?:x[\da-f]+|\d+)|[a-z]+);/i.test(destination)) {
8
+ return null;
9
+ }
10
+
11
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(destination)?.[1]?.toLowerCase();
12
+ if (scheme) {
13
+ if (!['http', 'https', 'mailto', 'tel'].includes(scheme)) {
14
+ return null;
15
+ }
16
+ if (scheme === 'http' || scheme === 'https') {
17
+ try {
18
+ const url = new URL(destination);
19
+ return url.hostname ? destination : null;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+ return destination.length > scheme.length + 1 ? destination : null;
25
+ }
26
+
27
+ // A colon before a path/query/fragment boundary is never a relative path.
28
+ return /^[^/?#]*:/.test(destination) ? null : destination;
29
+ }
30
+
31
+ /*
32
+ * Decode only escaped punctuation from link destinations, leaving URL encoding and literal values untouched.
33
+ */
34
+ export function unescapeLinkDestination(destination: string): string {
35
+ return destination.replace(/\\([!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~])/g, '$1');
36
+ }
37
+ /*
38
+ * Normalize public inline parser budgets and cap recursive containers even when callers request a higher depth.
39
+ */
40
+ export function getInlineLimits(limits: Partial<ParserLimits>): ParserLimits {
41
+ const resolved = { ...DEFAULT_PARSER_LIMITS };
42
+ for (const key of Object.keys(resolved) as (keyof ParserLimits)[]) {
43
+ const value = limits[key];
44
+ if (value !== undefined && Number.isFinite(value)) resolved[key] = Math.max(0, Math.floor(value));
45
+ }
46
+ resolved.nestingDepth = Math.min(resolved.nestingDepth, 64);
47
+ return resolved;
48
+ }
@@ -0,0 +1,396 @@
1
+ import type { ContentDiagnostic, InlineNode, InlineStyle, ParserLimits } from '../types/content.ts';
2
+ import { getInlineLimits, getSafeLinkDestination, unescapeLinkDestination } from './parseInline.helpers.ts';
3
+
4
+ interface InlineIndex {
5
+ code: Map<number, { close: number; end: number }>;
6
+ brackets: Map<number, number>;
7
+ parentheses: Map<number, number>;
8
+ highlights: Map<number, number>;
9
+ classTokens: Set<number>;
10
+ }
11
+
12
+ interface InlineContext {
13
+ source: string;
14
+ offset: number;
15
+ index: InlineIndex;
16
+ limits: ParserLimits;
17
+ nodes: number;
18
+ exceeded: boolean;
19
+ diagnostics?: ContentDiagnostic[];
20
+ reportedReasons: Set<string>;
21
+ }
22
+
23
+ interface StyleFrame {
24
+ marker: string;
25
+ start: number;
26
+ children: InlineNode[];
27
+ }
28
+
29
+ /*
30
+ * Recognize punctuation that supports a backslash escape in chat markup.
31
+ */
32
+ function isEscapable(character: string | undefined): boolean {
33
+ return Boolean(character && /[!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~]/.test(character));
34
+ }
35
+
36
+ /*
37
+ * Record the first affected range for each inline issue without allocating one diagnostic per adversarial marker.
38
+ */
39
+ function reportDiagnostic(context: InlineContext, code: ContentDiagnostic['code'], reason: string, start: number, end: number): void {
40
+ if (!context.diagnostics || context.reportedReasons.has(reason)) return;
41
+ context.reportedReasons.add(reason);
42
+ context.diagnostics.push({ code, reason, start: context.offset + start, end: context.offset + end });
43
+ }
44
+
45
+ /*
46
+ * Index delimiter pairs in linear passes so unmatched backticks or brackets never rescan an entire suffix.
47
+ */
48
+ function indexInlineDelimiters(source: string): InlineIndex {
49
+ const index: InlineIndex = {
50
+ code: new Map(),
51
+ brackets: new Map(),
52
+ parentheses: new Map(),
53
+ highlights: new Map(),
54
+ classTokens: new Set(),
55
+ };
56
+ const codeRuns: { start: number; end: number }[] = [];
57
+ for (let position = 0; position < source.length; ) {
58
+ if (source[position] === '`') {
59
+ const start = position;
60
+ while (source[position] === '`') position += 1;
61
+ codeRuns.push({ start, end: position });
62
+ } else {
63
+ position += 1;
64
+ }
65
+ }
66
+ const nextCodeRun = new Map<number, { start: number; end: number }>();
67
+ for (let runIndex = codeRuns.length - 1; runIndex >= 0; runIndex -= 1) {
68
+ const run = codeRuns[runIndex];
69
+ const length = run.end - run.start;
70
+ const next = nextCodeRun.get(length);
71
+ if (next) index.code.set(run.start, { close: next.start, end: next.end });
72
+ nextCodeRun.set(length, run);
73
+ }
74
+
75
+ const brackets: { position: number; hashes: number }[] = [];
76
+ const parentheses: number[] = [];
77
+ const highlights: number[] = [];
78
+ let hashes = 0;
79
+ for (let position = 0; position < source.length; ) {
80
+ const character = source[position];
81
+ const code = index.code.get(position);
82
+ if (character === '\\' && isEscapable(source[position + 1])) {
83
+ position += 2;
84
+ continue;
85
+ }
86
+ if (code) {
87
+ position = code.end;
88
+ continue;
89
+ }
90
+ if (source.slice(position, position + 4).toLowerCase() === '[hl]') {
91
+ highlights.push(position);
92
+ position += 4;
93
+ continue;
94
+ }
95
+ if (source.slice(position, position + 5).toLowerCase() === '[/hl]') {
96
+ const opening = highlights.pop();
97
+ if (opening !== undefined) index.highlights.set(opening, position);
98
+ position += 5;
99
+ continue;
100
+ }
101
+ if (character === '#' && source[position + 1] === '#') hashes += 1;
102
+ if (character === '[') brackets.push({ position, hashes });
103
+ if (character === ']') {
104
+ const opening = brackets.pop();
105
+ if (opening !== undefined) {
106
+ index.brackets.set(opening.position, position);
107
+ if (hashes > opening.hashes) index.classTokens.add(opening.position);
108
+ }
109
+ }
110
+ if (character === '(') parentheses.push(position);
111
+ if (character === ')') {
112
+ const opening = parentheses.pop();
113
+ if (opening !== undefined) index.parentheses.set(opening, position);
114
+ }
115
+ position += 1;
116
+ }
117
+ return index;
118
+ }
119
+
120
+ /*
121
+ * Append an inline node while merging adjacent text and enforcing a shared node budget across nested labels.
122
+ */
123
+ function appendNode(context: InlineContext, nodes: InlineNode[], node: InlineNode): void {
124
+ const previous = nodes.at(-1);
125
+ if (node.kind === 'text' && previous?.kind === 'text' && previous.end === node.start) {
126
+ previous.value += node.value;
127
+ previous.end = node.end;
128
+ return;
129
+ }
130
+ context.nodes += 1;
131
+ if (context.nodes > context.limits.nodes) {
132
+ context.exceeded = true;
133
+ reportDiagnostic(context, 'limit-exceeded', 'Inline node limit exceeded.', 0, context.source.length);
134
+ }
135
+ nodes.push(node);
136
+ }
137
+
138
+ /*
139
+ * Append readable text with its original source range, including any escaped source character.
140
+ */
141
+ function appendText(
142
+ context: InlineContext,
143
+ nodes: InlineNode[],
144
+ start: number,
145
+ end: number,
146
+ value = context.source.slice(start, end),
147
+ ): void {
148
+ if (end > start) appendNode(context, nodes, { kind: 'text', value, start: context.offset + start, end: context.offset + end });
149
+ }
150
+
151
+ /*
152
+ * Restore an unmatched opening delimiter without hiding any already parsed content that followed it.
153
+ */
154
+ function unwrapFrame(context: InlineContext, frames: StyleFrame[]): void {
155
+ const frame = frames.pop()!;
156
+ const parent = frames.at(-1)!.children;
157
+ if (!context.exceeded) {
158
+ reportDiagnostic(
159
+ context,
160
+ 'incomplete',
161
+ 'Unclosed inline style delimiter.',
162
+ frame.start,
163
+ (frame.children.at(-1)?.end ?? context.offset + frame.start + frame.marker.length) - context.offset,
164
+ );
165
+ }
166
+ appendText(context, parent, frame.start, frame.start + frame.marker.length);
167
+ for (const child of frame.children) appendNode(context, parent, child);
168
+ }
169
+
170
+ /*
171
+ * Map the documented chat delimiters to their historical presentation meanings.
172
+ */
173
+ function markerStyles(marker: string): InlineStyle[] {
174
+ if (marker[0] === '*') return [marker.length === 1 ? 'medium' : 'semibold'];
175
+ if (marker === '_') return ['italic'];
176
+ if (marker === '__') return ['underline'];
177
+ if (marker === '___') return ['underline', 'italic'];
178
+ return ['strike'];
179
+ }
180
+
181
+ /*
182
+ * Emit a completed style, folding directly nested combinations into one typed style node.
183
+ */
184
+ function closeStyle(context: InlineContext, frames: StyleFrame[], end: number): void {
185
+ const frame = frames.pop()!;
186
+ const styles = markerStyles(frame.marker);
187
+ let children = frame.children;
188
+ if (children.length === 1 && children[0].kind === 'style') {
189
+ for (const style of children[0].styles) if (!styles.includes(style)) styles.push(style);
190
+ children = children[0].children;
191
+ }
192
+ appendNode(context, frames.at(-1)!.children, {
193
+ kind: 'style',
194
+ styles,
195
+ children,
196
+ start: context.offset + frame.start,
197
+ end: context.offset + end,
198
+ });
199
+ }
200
+
201
+ /*
202
+ * Resolve a bounded style stack with word-aware underscore boundaries and literal unmatched markers.
203
+ */
204
+ function handleStyle(context: InlineContext, frames: StyleFrame[], start: number, end: number, depth: number): void {
205
+ const { source } = context;
206
+ const marker = source.slice(start, end);
207
+ const previous = source[start - 1] || '';
208
+ const next = source[end] || '';
209
+ const canClose = Boolean(previous && !/\s/.test(previous)) && (marker[0] !== '_' || !/[\p{L}\p{N}_]/u.test(next));
210
+ const canOpen = Boolean(next && !/\s/.test(next)) && (marker[0] !== '_' || !/[\p{L}\p{N}_]/u.test(previous));
211
+ if (canClose) {
212
+ for (let frameIndex = frames.length - 1; frameIndex > 0; frameIndex -= 1) {
213
+ if (frames[frameIndex].marker === marker) {
214
+ while (frames.length - 1 > frameIndex) unwrapFrame(context, frames);
215
+ closeStyle(context, frames, end);
216
+ return;
217
+ }
218
+ }
219
+ }
220
+ if (canOpen) {
221
+ if (frames.length + depth > context.limits.nestingDepth) {
222
+ context.exceeded = true;
223
+ reportDiagnostic(context, 'limit-exceeded', 'Inline nesting depth limit exceeded.', 0, source.length);
224
+ return;
225
+ }
226
+ frames.push({ marker, start, children: [] });
227
+ } else {
228
+ appendText(context, frames.at(-1)!.children, start, end);
229
+ }
230
+ }
231
+
232
+ /*
233
+ * Scan one inline range; recursion is limited to explicit link labels and highlight contents.
234
+ */
235
+ function parseInlineRange(context: InlineContext, start: number, end: number, depth: number, allowLinks: boolean): InlineNode[] {
236
+ const { source, index, offset } = context;
237
+ const frames: StyleFrame[] = [{ marker: '', start, children: [] }];
238
+ if (depth > context.limits.nestingDepth) {
239
+ context.exceeded = true;
240
+ reportDiagnostic(context, 'limit-exceeded', 'Inline nesting depth limit exceeded.', 0, source.length);
241
+ return [];
242
+ }
243
+ for (let position = start; position < end && !context.exceeded; ) {
244
+ const children = frames.at(-1)!.children;
245
+ const character = source[position];
246
+ if (character === '\\' && isEscapable(source[position + 1]) && position + 1 < end) {
247
+ appendText(context, children, position, position + 2, source[position + 1]);
248
+ position += 2;
249
+ continue;
250
+ }
251
+ const code = index.code.get(position);
252
+ if (code && code.end <= end) {
253
+ const width = code.end - code.close;
254
+ appendNode(context, children, {
255
+ kind: 'code',
256
+ value: source.slice(position + width, code.close),
257
+ start: offset + position,
258
+ end: offset + code.end,
259
+ });
260
+ position = code.end;
261
+ continue;
262
+ }
263
+ const highlightEnd = index.highlights.get(position);
264
+ if (highlightEnd !== undefined && highlightEnd + 5 <= end) {
265
+ appendNode(context, children, {
266
+ kind: 'style',
267
+ styles: ['highlight'],
268
+ start: offset + position,
269
+ end: offset + highlightEnd + 5,
270
+ children: parseInlineRange(context, position + 4, highlightEnd, depth + frames.length, allowLinks),
271
+ });
272
+ position = highlightEnd + 5;
273
+ continue;
274
+ }
275
+ if (source.slice(position, position + 4).toLowerCase() === '[hl]') {
276
+ reportDiagnostic(context, 'incomplete', 'Unclosed inline highlight.', position, end);
277
+ }
278
+ const imagePrefix = character === '!' && source[position + 1] === '[';
279
+ const labelStart = imagePrefix ? position + 1 : position;
280
+ const labelEnd = index.brackets.get(labelStart);
281
+ if (labelEnd !== undefined && labelEnd < end) {
282
+ const destinationStart = labelEnd + 1;
283
+ const destinationEnd = source[destinationStart] === '(' ? index.parentheses.get(destinationStart) : undefined;
284
+ if (destinationEnd !== undefined && destinationEnd < end) {
285
+ const destination = getSafeLinkDestination(unescapeLinkDestination(source.slice(destinationStart + 1, destinationEnd)));
286
+ if (destination && allowLinks && !imagePrefix) {
287
+ appendNode(context, children, {
288
+ kind: 'link',
289
+ destination,
290
+ start: offset + position,
291
+ end: offset + destinationEnd + 1,
292
+ children: parseInlineRange(context, labelStart + 1, labelEnd, depth + frames.length, false),
293
+ });
294
+ } else {
295
+ if (!destination)
296
+ reportDiagnostic(context, 'unsupported', 'Unsafe or unsupported link destination.', position, destinationEnd + 1);
297
+ appendText(context, children, position, destinationEnd + 1);
298
+ }
299
+ position = destinationEnd + 1;
300
+ continue;
301
+ }
302
+ // Unsupported class tokens are always literal, including any formatting inside them.
303
+ if (index.classTokens.has(labelStart)) {
304
+ appendText(context, children, position, labelEnd + 1);
305
+ position = labelEnd + 1;
306
+ continue;
307
+ }
308
+ if (source[destinationStart] === '(') {
309
+ reportDiagnostic(context, 'incomplete', 'Unclosed explicit link destination.', position, end);
310
+ appendText(context, children, position, end);
311
+ position = end;
312
+ continue;
313
+ }
314
+ }
315
+ if (character === '\r' || character === '\n') {
316
+ while (frames.length > 1) unwrapFrame(context, frames);
317
+ const breakEnd = character === '\r' && source[position + 1] === '\n' ? position + 2 : position + 1;
318
+ appendNode(context, frames[0].children, { kind: 'break', start: offset + position, end: offset + breakEnd });
319
+ position = breakEnd;
320
+ continue;
321
+ }
322
+ if (character === '*' || character === '_' || character === '~' || character === '`') {
323
+ let runEnd = position + 1;
324
+ while (runEnd < end && source[runEnd] === character) runEnd += 1;
325
+ const width = runEnd - position;
326
+ if (((character === '*' || character === '_') && width <= 3) || (character === '~' && width === 2)) {
327
+ handleStyle(context, frames, position, runEnd, depth);
328
+ } else {
329
+ if (character === '`') reportDiagnostic(context, 'incomplete', 'Unclosed inline code delimiter.', position, end);
330
+ appendText(context, children, position, runEnd);
331
+ }
332
+ position = runEnd;
333
+ continue;
334
+ }
335
+ if (character === ':') {
336
+ let tokenEnd = position + 1;
337
+ while (tokenEnd < end && /[a-z0-9_+-]/i.test(source[tokenEnd])) tokenEnd += 1;
338
+ if (tokenEnd > position + 1 && source[tokenEnd] === ':') {
339
+ appendNode(context, children, {
340
+ kind: 'emoji',
341
+ name: source.slice(position + 1, tokenEnd).toLowerCase(),
342
+ source: source.slice(position, tokenEnd + 1),
343
+ start: offset + position,
344
+ end: offset + tokenEnd + 1,
345
+ });
346
+ position = tokenEnd + 1;
347
+ continue;
348
+ }
349
+ appendText(context, children, position, tokenEnd);
350
+ position = tokenEnd;
351
+ continue;
352
+ }
353
+ let textEnd = position + 1;
354
+ while (textEnd < end && !/[\\`[!*_~:\r\n]/.test(source[textEnd])) textEnd += 1;
355
+ appendText(context, children, position, textEnd);
356
+ position = textEnd;
357
+ }
358
+ while (frames.length > 1) unwrapFrame(context, frames);
359
+ return frames[0].children;
360
+ }
361
+
362
+ /*
363
+ * Parse deterministic chat inline markup with original UTF-16 source ranges and a complete literal fallback on limits.
364
+ */
365
+ export function parseInline(
366
+ source: string,
367
+ offset = 0,
368
+ limits: Partial<ParserLimits> = {},
369
+ diagnostics?: ContentDiagnostic[],
370
+ ): InlineNode[] {
371
+ if (!source) return [];
372
+ const resolvedLimits = getInlineLimits(limits);
373
+ const literal: InlineNode[] = [{ kind: 'text', value: source, start: offset, end: offset + source.length }];
374
+ if (source.length > resolvedLimits.inputLength || resolvedLimits.nodes < 1 || resolvedLimits.nestingDepth < 1) {
375
+ diagnostics?.push({
376
+ code: 'limit-exceeded',
377
+ reason: 'Inline parsing resource limit exceeded.',
378
+ start: offset,
379
+ end: offset + source.length,
380
+ });
381
+ return literal;
382
+ }
383
+ if (!/[\\`[!*_~:\r\n]/.test(source)) return literal;
384
+ const context: InlineContext = {
385
+ source,
386
+ offset,
387
+ index: indexInlineDelimiters(source),
388
+ limits: resolvedLimits,
389
+ nodes: 0,
390
+ exceeded: false,
391
+ diagnostics,
392
+ reportedReasons: new Set(),
393
+ };
394
+ const children = parseInlineRange(context, 0, source.length, 0, true);
395
+ return context.exceeded ? literal : children;
396
+ }