@adminforth/agent 3.1.8 → 3.1.9

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,268 @@
1
+ import DOMPurify from 'dompurify';
2
+ import { Idiomorph } from 'idiomorph';
3
+ import { Marked, type Tokens, type TokenizerAndRendererExtension } from 'marked';
4
+ import remend from 'remend';
5
+ import type { VisualizationSpec } from 'vega-embed';
6
+ import { vegaLiteConfig } from './vegaTheme';
7
+ import './markdown.css';
8
+
9
+ // Framework-free markdown of the chat: the whole message is parsed again on every change (marked takes well under a
10
+ // millisecond on a chat message), remend closes the syntax a stream left open, and idiomorph moves only the difference
11
+ // into the DOM, so finished blocks, a rendered chart and the text selection survive the next chunk.
12
+ // A binding of a UI framework creates the view on mount, passes every new text to update() and calls destroy().
13
+
14
+ export interface MarkdownLabels {
15
+ copy: string;
16
+ copied: string;
17
+ }
18
+
19
+ export interface MarkdownView {
20
+ update(text: string, final: boolean): void;
21
+ destroy(): void;
22
+ }
23
+
24
+ type KatexModule = typeof import('katex').default;
25
+ type HighlightModule = typeof import('./highlightCode');
26
+ type VegaResult = { finalize: () => void };
27
+
28
+ const COPIED_MS = 1500;
29
+ // a link or an image still streaming shows as its text until its URL is complete
30
+ const REMEND_OPTIONS = { linkMode: 'text-only', images: false } as const;
31
+ const HTML_ESCAPE_RE = /[&<>"']/g;
32
+ const HTML_ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
33
+ // $$…$$ or \[…\] on lines of their own
34
+ const BLOCK_MATH_RE = /^(?:\$\$([\s\S]+?)\$\$|\\\[([\s\S]+?)\\\])[ \t]*(?:\n|$)/;
35
+ const BLOCK_MATH_START_RE = /^(?:\$\$|\\\[)/m;
36
+ // $$…$$ and \[…\] in a line are display math, \(…\) and $…$ inline; $…$ follows pandoc so prices like $5 and $10 stay text
37
+ const INLINE_MATH_RE = /^(?:\$\$([\s\S]+?)\$\$|\\\[([\s\S]+?)\\\]|\\\(([\s\S]+?)\\\)|\$(?!\s)((?:\\.|[^\\$\n])+?)(?<!\s)\$(?!\d))/;
38
+ const INLINE_MATH_START_RE = /\$|\\[([]/;
39
+
40
+ let katex: KatexModule | null = null;
41
+ let katexLoad: Promise<void> | null = null;
42
+ let highlighter: HighlightModule | null = null;
43
+ let highlighterLoad: Promise<void> | null = null;
44
+
45
+ function escapeHtml(text: string): string {
46
+ return text.replace(HTML_ESCAPE_RE, (char) => HTML_ESCAPES[char]);
47
+ }
48
+
49
+ function stringHash(text: string): string {
50
+ let hash = 5381;
51
+ for (let i = 0; i < text.length; i++) {
52
+ hash = (hash * 33) ^ text.charCodeAt(i);
53
+ }
54
+ return (hash >>> 0).toString(36);
55
+ }
56
+
57
+ // KaTeX and its stylesheet load on the first formula, until then the formula shows as its source
58
+ function loadKatex(): Promise<void> {
59
+ katexLoad ??= Promise.all([import('katex'), import('katex/dist/katex.min.css')]).then(([module]) => {
60
+ katex = module.default;
61
+ });
62
+ return katexLoad;
63
+ }
64
+
65
+ // shiki loads with the first code block, a message without code does not pay for it
66
+ function loadHighlighter(): Promise<void> {
67
+ highlighterLoad ??= import('./highlightCode').then((module) => {
68
+ highlighter = module;
69
+ });
70
+ return highlighterLoad;
71
+ }
72
+
73
+ function mathExtensions(renderTex: (tex: string, displayMode: boolean) => string): TokenizerAndRendererExtension[] {
74
+ return [
75
+ {
76
+ name: 'mathBlock',
77
+ level: 'block',
78
+ start: (src) => src.match(BLOCK_MATH_START_RE)?.index,
79
+ tokenizer(src) {
80
+ const match = BLOCK_MATH_RE.exec(src);
81
+ if (match) {
82
+ return { type: 'mathBlock', raw: match[0], text: (match[1] ?? match[2]).trim() };
83
+ }
84
+ },
85
+ renderer: (token) => `<div class="af-md-math-block">${renderTex(token.text, true)}</div>`,
86
+ },
87
+ {
88
+ name: 'mathInline',
89
+ level: 'inline',
90
+ start: (src) => src.match(INLINE_MATH_START_RE)?.index,
91
+ tokenizer(src) {
92
+ const match = INLINE_MATH_RE.exec(src);
93
+ if (match) {
94
+ const display = match[1] !== undefined || match[2] !== undefined;
95
+ return { type: 'mathInline', raw: match[0], text: (match[1] ?? match[2] ?? match[3] ?? match[4]).trim(), display };
96
+ }
97
+ },
98
+ renderer: (token) => renderTex(token.text, token.display),
99
+ },
100
+ ];
101
+ }
102
+
103
+ export function createMarkdownView(el: HTMLElement, labels: MarkdownLabels): MarkdownView {
104
+ let text = '';
105
+ let final = false;
106
+ let rendered = false;
107
+ let frameId: number | null = null;
108
+ // the spec of every chart in the last render, by the hash idiomorph compares
109
+ const vegaSpecs = new Map<string, string>();
110
+ const charts = new Map<HTMLElement, { key: string; result: VegaResult | null }>();
111
+
112
+ const scheduleRender = () => {
113
+ frameId ??= requestAnimationFrame(render);
114
+ };
115
+
116
+ const renderTex = (tex: string, displayMode: boolean) => {
117
+ if (!katex) {
118
+ loadKatex().then(scheduleRender, (error) => console.error('Failed to load KaTeX', error));
119
+ return `<code class="af-md-math-source">${escapeHtml(tex)}</code>`;
120
+ }
121
+ return katex.renderToString(tex, { displayMode, throwOnError: false, output: 'htmlAndMathml' });
122
+ };
123
+
124
+ const renderCode = ({ text: code, lang }: Tokens.Code) => {
125
+ const info = (lang ?? '').trim().split(/\s/, 1)[0];
126
+ if (info.toLowerCase() === 'vega-lite') {
127
+ const key = stringHash(code);
128
+ vegaSpecs.set(key, code);
129
+ return `<div class="af-md-vega" data-af-md-vega="${key}"></div>`;
130
+ }
131
+
132
+ let highlighted: string | null = null;
133
+ if (highlighter) {
134
+ const language = highlighter.shikiLanguage(info);
135
+ highlighted = language && highlighter.highlightCode(code, language, scheduleRender);
136
+ } else {
137
+ loadHighlighter().then(scheduleRender, (error) => console.error('Failed to load the code highlighter', error));
138
+ }
139
+ return `<div class="af-md-code">`
140
+ + `<div class="af-md-code-toolbar"><span class="af-md-code-language">${escapeHtml(info || 'text')}</span>`
141
+ + `<button type="button" class="af-md-code-copy" data-af-md-copy>${escapeHtml(labels.copy)}</button></div>`
142
+ + `<div class="af-md-code-body">${highlighted || `<pre class="af-md-code-plain"><code>${escapeHtml(code)}</code></pre>`}</div>`
143
+ + `</div>`;
144
+ };
145
+
146
+ const marked = new Marked({
147
+ gfm: true,
148
+ renderer: { code: renderCode },
149
+ extensions: mathExtensions(renderTex),
150
+ });
151
+
152
+ // a rendered chart and a copy button showing "Copied" keep their DOM, the new markup has neither
153
+ const beforeNodeMorphed = (oldNode: Node, newNode: Node) => !(
154
+ oldNode instanceof HTMLElement && newNode instanceof HTMLElement && (
155
+ (oldNode.dataset.afMdVega !== undefined && oldNode.dataset.afMdVega === newNode.dataset.afMdVega)
156
+ || oldNode.dataset.copied !== undefined
157
+ )
158
+ );
159
+
160
+ function render() {
161
+ frameId = null;
162
+ rendered = true;
163
+ vegaSpecs.clear();
164
+ const html = marked.parse(final ? text : remend(text, REMEND_OPTIONS), { async: false });
165
+ Idiomorph.morph(el, DOMPurify.sanitize(html), { morphStyle: 'innerHTML', callbacks: { beforeNodeMorphed } });
166
+ syncCharts();
167
+ }
168
+
169
+ // charts render once their spec is complete JSON, a spec still streaming stays an empty box
170
+ function syncCharts() {
171
+ for (const [container, chart] of charts) {
172
+ if (!container.isConnected) {
173
+ chart.result?.finalize();
174
+ charts.delete(container);
175
+ }
176
+ }
177
+ for (const container of el.querySelectorAll<HTMLElement>('[data-af-md-vega]')) {
178
+ const key = container.dataset.afMdVega!;
179
+ const chart = charts.get(container);
180
+ if (chart?.key === key) {
181
+ continue;
182
+ }
183
+ chart?.result?.finalize();
184
+ charts.delete(container);
185
+ let spec: Record<string, unknown>;
186
+ try {
187
+ spec = JSON.parse(vegaSpecs.get(key)!);
188
+ } catch {
189
+ continue;
190
+ }
191
+ charts.set(container, { key, result: null });
192
+ void embedChart(container, key, spec);
193
+ }
194
+ }
195
+
196
+ async function embedChart(container: HTMLElement, key: string, spec: Record<string, unknown>) {
197
+ const { default: embed } = await import('vega-embed');
198
+ try {
199
+ // a spec without a width fills the message
200
+ const fullSpec = { width: 'container', autosize: { type: 'fit-x', contains: 'padding' }, ...spec } as VisualizationSpec;
201
+ const result = await embed(container, fullSpec, {
202
+ actions: false,
203
+ renderer: 'svg',
204
+ // read on every render, a theme switch renders the chart again with the tokens of the new theme
205
+ config: vegaLiteConfig(container),
206
+ tooltip: { theme: 'af' },
207
+ });
208
+ if (charts.get(container)?.key === key) {
209
+ charts.get(container)!.result = result;
210
+ } else {
211
+ result.finalize();
212
+ }
213
+ } catch (error) {
214
+ console.error('Failed to render Vega-Lite block', error);
215
+ }
216
+ }
217
+
218
+ const themeObserver = new MutationObserver(() => {
219
+ for (const [container, chart] of charts) {
220
+ chart.result?.finalize();
221
+ charts.delete(container);
222
+ container.replaceChildren();
223
+ }
224
+ syncCharts();
225
+ });
226
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
227
+
228
+ function onClick(event: MouseEvent) {
229
+ const button = (event.target as Element).closest<HTMLButtonElement>('[data-af-md-copy]');
230
+ if (!button) {
231
+ return;
232
+ }
233
+ const code = button.closest('.af-md-code')!.querySelector('pre')!.textContent!;
234
+ void navigator.clipboard.writeText(code).then(() => {
235
+ button.dataset.copied = '';
236
+ button.textContent = labels.copied;
237
+ setTimeout(() => {
238
+ delete button.dataset.copied;
239
+ button.textContent = labels.copy;
240
+ }, COPIED_MS);
241
+ });
242
+ }
243
+ el.addEventListener('click', onClick);
244
+
245
+ return {
246
+ update(nextText, nextFinal) {
247
+ text = nextText;
248
+ final = nextFinal;
249
+ // the first render is synchronous, so a message from the history has its height when it mounts
250
+ if (rendered) {
251
+ scheduleRender();
252
+ } else {
253
+ render();
254
+ }
255
+ },
256
+ destroy() {
257
+ if (frameId !== null) {
258
+ cancelAnimationFrame(frameId);
259
+ }
260
+ themeObserver.disconnect();
261
+ el.removeEventListener('click', onClick);
262
+ for (const chart of charts.values()) {
263
+ chart.result?.finalize();
264
+ }
265
+ charts.clear();
266
+ },
267
+ };
268
+ }
@@ -11,20 +11,19 @@
11
11
  "license": "ISC",
12
12
  "packageManager": "pnpm@10.33.0",
13
13
  "dependencies": {
14
- "@incremark/core": "^1.0.2",
15
- "@incremark/theme": "^1.0.2",
16
- "@incremark/vue": "^1.0.2",
17
14
  "@ricky0123/vad-web": "^0.0.30",
18
- "@shikijs/langs": "^4.0.2",
19
- "@shikijs/themes": "^4.0.2",
15
+ "@shikijs/langs": "^4.5.0",
16
+ "@shikijs/themes": "^4.5.0",
20
17
  "@vueuse/core": "^14.2.1",
21
18
  "ai": "6.0.168",
22
19
  "custom-vue-scrollbar": "^0.0.8",
23
20
  "dompurify": "^3.3.3",
21
+ "idiomorph": "^0.8.0",
24
22
  "katex": "^0.16.45",
25
23
  "marked": "^18.0.0",
26
24
  "onnxruntime-web": "1.27.0",
27
- "shiki": "^4.0.2",
25
+ "remend": "^1.4.0",
26
+ "shiki": "^4.5.0",
28
27
  "vega-embed": "^7.1.0",
29
28
  "voice-activity-detection": "^0.0.5"
30
29
  }