@one-agent/html 0.0.1-beta.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # @one-agent/html
2
+
3
+ Streaming HTML → ANSI terminal renderer for ONE agent output.
4
+
5
+ Parses an HTML stream chunk-by-chunk and emits styled, word-wrapped ANSI text suitable for direct terminal output. Used internally by the `one repl` HTML REPL and available as a standalone library.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @one-agent/html
11
+ # or
12
+ pnpm add @one-agent/html
13
+ ```
14
+
15
+ ## Quick start
16
+
17
+ ```typescript
18
+ import { StreamingHtmlRenderer, initSyntaxHighlighting } from "@one-agent/html";
19
+
20
+ // Optional: pre-warm the syntax highlighter (avoids first-call latency)
21
+ await initSyntaxHighlighting();
22
+
23
+ const renderer = new StreamingHtmlRenderer({
24
+ columns: process.stdout.columns ?? 80,
25
+ onFlush: (text) => {
26
+ process.stdout.write(text + "\n");
27
+ },
28
+ });
29
+
30
+ // Feed chunks as they arrive from the LLM stream
31
+ for await (const chunk of htmlStream) {
32
+ renderer.write(chunk);
33
+ }
34
+ renderer.end();
35
+ ```
36
+
37
+ ## API
38
+
39
+ ### `new StreamingHtmlRenderer(options)`
40
+
41
+ Creates a new renderer instance.
42
+
43
+ ```typescript
44
+ interface HtmlRendererOptions {
45
+ /** Terminal column width for word-wrapping. Default: 80. */
46
+ columns?: number;
47
+
48
+ /**
49
+ * Called when a complete block (paragraph, heading, code block, …) is ready.
50
+ * If omitted, collect output with flush() instead.
51
+ */
52
+ onFlush?: (text: string) => void;
53
+
54
+ /**
55
+ * Called after each chunk with the current in-progress partial line.
56
+ * Use to rewrite the last line: process.stdout.write('\r\x1b[K' + partial)
57
+ */
58
+ onPartial?: (partial: string) => void;
59
+ }
60
+ ```
61
+
62
+ #### `renderer.write(chunk: string)`
63
+
64
+ Feed a new chunk of HTML. Safe to call with partial tags across chunk boundaries.
65
+
66
+ #### `renderer.end()`
67
+
68
+ Signal end-of-stream. Flushes any buffered content.
69
+
70
+ #### `renderer.flush(): string`
71
+
72
+ Returns all buffered output as a single string (when no `onFlush` callback is set).
73
+
74
+ ### `initSyntaxHighlighting(): Promise<void>`
75
+
76
+ Pre-warms the [Shiki](https://shiki.style/) syntax highlighter. Call once at startup to avoid latency on the first code block. Safe to call multiple times (no-op after first load).
77
+
78
+ ### `highlightCode(code: string, lang: string): string`
79
+
80
+ Highlight a code string synchronously and return ANSI-colored text. Returns the original string if the highlighter is not yet initialised or the language is unsupported.
81
+
82
+ ## Supported HTML elements
83
+
84
+ | Element | Rendering |
85
+ |---------|-----------|
86
+ | `<p>` | Word-wrapped paragraph |
87
+ | `<h1>`–`<h6>` | Bold + colored headings with `#` prefix |
88
+ | `<pre><code>` | Syntax-highlighted code block with line numbers |
89
+ | `<code>` (inline) | Dimmed monospace |
90
+ | `<strong>`, `<b>` | Bold |
91
+ | `<em>`, `<i>` | Italic |
92
+ | `<s>`, `<del>` | Strikethrough |
93
+ | `<blockquote>` | Indented with `▌` gutter |
94
+ | `<ul>`, `<ol>` | Nested lists with `•` / numbered bullets |
95
+ | `<li>` | List item |
96
+ | `<hr>` | Horizontal rule |
97
+ | `<br>` | Line break |
98
+ | `<a>` | Underlined text (href shown if different from text) |
99
+
100
+ ## License
101
+
102
+ Apache-2.0 — see `LICENSE` and `NOTICE` at the repository root.
@@ -0,0 +1,81 @@
1
+ //#region src/renderer.d.ts
2
+ interface HtmlRendererOptions {
3
+ /**
4
+ * Terminal column width for word-wrapping. Default: 80.
5
+ */
6
+ columns?: number;
7
+ /**
8
+ * Callback fired when a complete, stable line (or block) is ready.
9
+ * In streaming mode the host calls this to write to stdout.
10
+ * If omitted, output is collected and returned by `flush()`.
11
+ */
12
+ onFlush?: (text: string) => void;
13
+ /**
14
+ * Callback fired after each chunk with the current "in-progress" partial line
15
+ * that hasn't been finalised yet. Host can use this to rewrite the last line
16
+ * with `process.stdout.write('\r\x1b[K' + partial)`.
17
+ */
18
+ onPartial?: (partial: string) => void;
19
+ }
20
+ declare class StreamingHtmlRenderer {
21
+ private readonly opts;
22
+ private parser;
23
+ /** Output collected when no onFlush provided. */
24
+ private collected;
25
+ /** Stack of open block contexts. Innermost block = last element. */
26
+ private blockStack;
27
+ /** Stack of list contexts for bullet/number generation. */
28
+ private listStack;
29
+ /** Current inline chalk chain (accumulated from open inline tags). */
30
+ private inlineChain;
31
+ /** Stack of chalk chains — restored on close tag. */
32
+ private inlineStack;
33
+ /** Inside <pre>: true — disables word-wrap, preserves whitespace. */
34
+ private inPre;
35
+ /** Table cell buffer: row → cells. */
36
+ private tableRows;
37
+ private currentRow;
38
+ private currentCell;
39
+ private inTableCell;
40
+ /** Whether we're inside a <blockquote> (may be nested). */
41
+ private blockquoteDepth;
42
+ /**
43
+ * Buffer for top-level text nodes (text that arrives outside any block tag).
44
+ * Instead of flushing each streaming chunk immediately (which creates one
45
+ * line per word/character), we accumulate here and flush at the next block
46
+ * boundary or on end().
47
+ */
48
+ private topLevelBuffer;
49
+ constructor(opts?: HtmlRendererOptions);
50
+ /** Feed a chunk of HTML (may be partial/incomplete). */
51
+ write(chunk: string): void;
52
+ /** Finalise: flush any remaining partial content and reset state. */
53
+ end(): void;
54
+ /** Return all collected output (only useful when no onFlush provided). */
55
+ flush(): string;
56
+ private handleOpen;
57
+ private _pendingHref;
58
+ private handleText;
59
+ private handleClose;
60
+ private appendToCurrentBlock;
61
+ /** Flush accumulated top-level text as a single wrapped line. */
62
+ private flushTopLevelBuffer;
63
+ private flushLine;
64
+ /** Emit current partial block content (the "live" incomplete block). */
65
+ private emitPartial;
66
+ }
67
+ //#endregion
68
+ //#region src/syntax.d.ts
69
+ /**
70
+ * Call this once at REPL startup to warm up the highlighter asynchronously.
71
+ * `highlightCode` will block briefly on first call if this hasn't resolved yet.
72
+ */
73
+ declare function initSyntaxHighlighting(): Promise<void>;
74
+ /**
75
+ * Highlight `code` for the given `lang` and return an ANSI-colored string.
76
+ * Lines are NOT wrapped or indented — the caller handles that.
77
+ * Falls back to plain text if shiki is unavailable or lang is unknown.
78
+ */
79
+ declare function highlightCode(code: string, lang?: string): string;
80
+ //#endregion
81
+ export { type HtmlRendererOptions, StreamingHtmlRenderer, highlightCode, initSyntaxHighlighting };
package/dist/index.mjs ADDED
@@ -0,0 +1,475 @@
1
+ import { Parser } from "htmlparser2";
2
+ import { Chalk } from "chalk";
3
+ import wrapAnsi from "wrap-ansi";
4
+ import stringWidth from "string-width";
5
+
6
+ //#region src/syntax.ts
7
+ const chalk$2 = new Chalk({ level: 3 });
8
+ const FS_ITALIC = 1;
9
+ const FS_BOLD = 2;
10
+ const FS_UNDERLINE = 4;
11
+ /**
12
+ * Common languages pre-loaded at init — small set for fast startup.
13
+ * Unknown languages fall back to plain rendering at highlight time.
14
+ */
15
+ const PRELOAD_LANGS = [
16
+ "typescript",
17
+ "javascript",
18
+ "tsx",
19
+ "jsx",
20
+ "python",
21
+ "bash",
22
+ "sh",
23
+ "json",
24
+ "yaml",
25
+ "html",
26
+ "css",
27
+ "markdown",
28
+ "rust",
29
+ "go",
30
+ "sql",
31
+ "toml",
32
+ "diff",
33
+ "text"
34
+ ];
35
+ const THEME = "github-light";
36
+ let highlighter = null;
37
+ let initPromise = null;
38
+ /**
39
+ * Call this once at REPL startup to warm up the highlighter asynchronously.
40
+ * `highlightCode` will block briefly on first call if this hasn't resolved yet.
41
+ */
42
+ async function initSyntaxHighlighting() {
43
+ if (initPromise) return initPromise;
44
+ initPromise = (async () => {
45
+ try {
46
+ const { createHighlighter, bundledLanguages } = await import("shiki");
47
+ const langs = PRELOAD_LANGS.filter((l) => bundledLanguages[l] != null);
48
+ highlighter = await createHighlighter({
49
+ themes: [THEME],
50
+ langs
51
+ });
52
+ } catch {
53
+ highlighter = null;
54
+ }
55
+ })();
56
+ return initPromise;
57
+ }
58
+ /** Map a hex color string (#rrggbb) to a chalk hex color function. */
59
+ function applyColor(c, hex) {
60
+ if (!hex) return c;
61
+ return c.hex(hex);
62
+ }
63
+ /**
64
+ * Highlight `code` for the given `lang` and return an ANSI-colored string.
65
+ * Lines are NOT wrapped or indented — the caller handles that.
66
+ * Falls back to plain text if shiki is unavailable or lang is unknown.
67
+ */
68
+ function highlightCode(code, lang) {
69
+ if (!highlighter || !lang) return code;
70
+ const loaded = highlighter.getLoadedLanguages();
71
+ const effectiveLang = loaded.includes(lang) ? lang : loaded.includes("text") ? "text" : null;
72
+ if (!effectiveLang) return code;
73
+ try {
74
+ return highlighter.codeToTokens(code, {
75
+ lang: effectiveLang,
76
+ theme: THEME
77
+ }).tokens.map((row) => row.map((token) => {
78
+ let c = applyColor(chalk$2, token.color);
79
+ const fs = token.fontStyle ?? 0;
80
+ if (fs & FS_ITALIC) c = c.italic;
81
+ if (fs & FS_BOLD) c = c.bold;
82
+ if (fs & FS_UNDERLINE) c = c.underline;
83
+ return c(token.content);
84
+ }).join("")).join("\n");
85
+ } catch {
86
+ return code;
87
+ }
88
+ }
89
+
90
+ //#endregion
91
+ //#region src/ansi.ts
92
+ /**
93
+ * ANSI style helpers — maps HTML tags to chalk modifiers.
94
+ * Kept separate so renderer.ts stays focused on parsing logic.
95
+ */
96
+ const chalk$1 = new Chalk({ level: 3 });
97
+ /** Block-level tags that flush output as their own paragraph. */
98
+ const BLOCK_TAGS = new Set([
99
+ "p",
100
+ "div",
101
+ "section",
102
+ "article",
103
+ "main",
104
+ "header",
105
+ "footer",
106
+ "aside",
107
+ "nav",
108
+ "h1",
109
+ "h2",
110
+ "h3",
111
+ "h4",
112
+ "h5",
113
+ "h6",
114
+ "ul",
115
+ "ol",
116
+ "li",
117
+ "blockquote",
118
+ "pre",
119
+ "table",
120
+ "thead",
121
+ "tbody",
122
+ "tr",
123
+ "hr",
124
+ "br"
125
+ ]);
126
+ /** Inline tags that only modify chalk styling. */
127
+ const INLINE_STYLE_TAGS = new Set([
128
+ "b",
129
+ "strong",
130
+ "i",
131
+ "em",
132
+ "u",
133
+ "s",
134
+ "del",
135
+ "strike",
136
+ "code",
137
+ "mark",
138
+ "small",
139
+ "sup",
140
+ "sub",
141
+ "span",
142
+ "a",
143
+ "abbr"
144
+ ]);
145
+ /** Apply chalk styling for an opening inline tag. Returns new chalk chain. */
146
+ function applyInlineOpen(tag, c) {
147
+ switch (tag) {
148
+ case "b":
149
+ case "strong": return c.bold;
150
+ case "i":
151
+ case "em": return c.italic;
152
+ case "u": return c.underline;
153
+ case "s":
154
+ case "del":
155
+ case "strike": return c.strikethrough;
156
+ case "code": return c.cyan;
157
+ case "mark": return c.bgYellow.black;
158
+ case "a": return c.blue.underline;
159
+ default: return c;
160
+ }
161
+ }
162
+ /** Style a full heading line. */
163
+ function styleHeading(level, text) {
164
+ return {
165
+ 1: (s) => chalk$1.bold.red(s),
166
+ 2: (s) => chalk$1.bold.cyan(s),
167
+ 3: (s) => chalk$1.bold.yellow(s),
168
+ 4: (s) => chalk$1.bold.yellow(s),
169
+ 5: (s) => chalk$1.bold.cyan(s),
170
+ 6: (s) => chalk$1.bold.gray(s)
171
+ }[level](text);
172
+ }
173
+ /** Style a blockquote line. */
174
+ function styleBlockquote(text) {
175
+ return chalk$1.gray("│ ") + chalk$1.italic.gray(text);
176
+ }
177
+ /** Style an <hr>. */
178
+ function styleHr(cols = 60) {
179
+ return chalk$1.gray("─".repeat(cols));
180
+ }
181
+ /** Style a <pre><code> block. */
182
+ function styleCodeBlock(text, lang) {
183
+ const header = lang ? chalk$1.gray(` ${lang}`) : "";
184
+ const body = highlightCode(text, lang).split("\n").map((line) => chalk$1.gray("│ ") + line).join("\n");
185
+ return header ? header + "\n" + body : body;
186
+ }
187
+
188
+ //#endregion
189
+ //#region src/renderer.ts
190
+ const chalk = new Chalk({ level: 3 });
191
+ var StreamingHtmlRenderer = class {
192
+ opts;
193
+ parser;
194
+ /** Output collected when no onFlush provided. */
195
+ collected = [];
196
+ /** Stack of open block contexts. Innermost block = last element. */
197
+ blockStack = [];
198
+ /** Stack of list contexts for bullet/number generation. */
199
+ listStack = [];
200
+ /** Current inline chalk chain (accumulated from open inline tags). */
201
+ inlineChain = chalk;
202
+ /** Stack of chalk chains — restored on close tag. */
203
+ inlineStack = [];
204
+ /** Inside <pre>: true — disables word-wrap, preserves whitespace. */
205
+ inPre = false;
206
+ /** Table cell buffer: row → cells. */
207
+ tableRows = [];
208
+ currentRow = [];
209
+ currentCell = "";
210
+ inTableCell = false;
211
+ /** Whether we're inside a <blockquote> (may be nested). */
212
+ blockquoteDepth = 0;
213
+ /**
214
+ * Buffer for top-level text nodes (text that arrives outside any block tag).
215
+ * Instead of flushing each streaming chunk immediately (which creates one
216
+ * line per word/character), we accumulate here and flush at the next block
217
+ * boundary or on end().
218
+ */
219
+ topLevelBuffer = "";
220
+ constructor(opts = {}) {
221
+ this.opts = {
222
+ columns: opts.columns ?? 80,
223
+ onFlush: opts.onFlush,
224
+ onPartial: opts.onPartial
225
+ };
226
+ this.parser = new Parser({
227
+ onopentag: (name, attrs) => this.handleOpen(name, attrs),
228
+ ontext: (text) => this.handleText(text),
229
+ onclosetag: (name) => this.handleClose(name)
230
+ }, { decodeEntities: true });
231
+ }
232
+ /** Feed a chunk of HTML (may be partial/incomplete). */
233
+ write(chunk) {
234
+ this.parser.write(chunk);
235
+ this.emitPartial();
236
+ }
237
+ /** Finalise: flush any remaining partial content and reset state. */
238
+ end() {
239
+ this.parser.end();
240
+ this.flushTopLevelBuffer();
241
+ this.emitPartial();
242
+ }
243
+ /** Return all collected output (only useful when no onFlush provided). */
244
+ flush() {
245
+ return this.collected.join("\n");
246
+ }
247
+ handleOpen(tag, attrs) {
248
+ if (INLINE_STYLE_TAGS.has(tag)) {
249
+ if (tag === "code" && this.inPre) {
250
+ const m = (attrs["class"] ?? "").match(/language-(\w+)/);
251
+ if (m) {
252
+ const preFrame = [...this.blockStack].reverse().find((f) => f.tag === "pre");
253
+ if (preFrame) preFrame.codeLang = m[1];
254
+ }
255
+ this.inlineStack.push(this.inlineChain);
256
+ return;
257
+ }
258
+ this.inlineStack.push(this.inlineChain);
259
+ this.inlineChain = applyInlineOpen(tag, this.inlineChain);
260
+ if (tag === "a" && attrs["href"]) this._pendingHref = attrs["href"] ?? void 0;
261
+ return;
262
+ }
263
+ if (tag === "td" || tag === "th") {
264
+ this.inTableCell = true;
265
+ this.currentCell = "";
266
+ if (tag === "th") {
267
+ this.inlineStack.push(this.inlineChain);
268
+ this.inlineChain = chalk.bold;
269
+ }
270
+ return;
271
+ }
272
+ if (BLOCK_TAGS.has(tag)) {
273
+ this.flushTopLevelBuffer();
274
+ if (tag === "pre") this.inPre = true;
275
+ if (tag === "table") this.tableRows = [];
276
+ if (tag === "tr") this.currentRow = [];
277
+ if (tag === "ul" || tag === "ol") {
278
+ const indent = this.listStack.length * 2;
279
+ this.listStack.push({
280
+ tag,
281
+ counter: 0,
282
+ indent
283
+ });
284
+ }
285
+ if (tag === "blockquote") this.blockquoteDepth++;
286
+ let headingLevel;
287
+ let listBullet;
288
+ if (/^h[1-6]$/.test(tag)) headingLevel = parseInt(tag[1]);
289
+ if (tag === "li") {
290
+ const list = this.listStack[this.listStack.length - 1];
291
+ if (list) if (list.tag === "ol") {
292
+ list.counter++;
293
+ listBullet = " ".repeat(list.indent) + chalk.bold(`${list.counter}.`) + " ";
294
+ } else listBullet = " ".repeat(list.indent) + chalk.bold("•") + " ";
295
+ }
296
+ this.blockStack.push({
297
+ tag,
298
+ text: "",
299
+ headingLevel,
300
+ listBullet
301
+ });
302
+ return;
303
+ }
304
+ if (tag === "br") this.appendToCurrentBlock("\n");
305
+ }
306
+ _pendingHref;
307
+ handleText(text) {
308
+ if (!this.inPre) text = text.replace(/\s+/g, " ");
309
+ if (!text) return;
310
+ const styled = this.inlineChain(text);
311
+ if (this.inTableCell) {
312
+ this.currentCell += styled;
313
+ return;
314
+ }
315
+ this.appendToCurrentBlock(styled);
316
+ }
317
+ handleClose(tag) {
318
+ if (INLINE_STYLE_TAGS.has(tag)) {
319
+ if (tag === "a" && this._pendingHref) {
320
+ const frame$1 = this.blockStack[this.blockStack.length - 1];
321
+ if (frame$1 && this._pendingHref) {
322
+ const hrefStyled = chalk.dim(` <${this._pendingHref}>`);
323
+ frame$1.text += hrefStyled;
324
+ }
325
+ this._pendingHref = void 0;
326
+ }
327
+ const prev = this.inlineStack.pop();
328
+ if (prev !== void 0) this.inlineChain = prev;
329
+ return;
330
+ }
331
+ if (tag === "td" || tag === "th") {
332
+ this.currentRow.push(this.currentCell.trim());
333
+ this.currentCell = "";
334
+ this.inTableCell = false;
335
+ if (tag === "th") {
336
+ const prev = this.inlineStack.pop();
337
+ if (prev !== void 0) this.inlineChain = prev;
338
+ }
339
+ return;
340
+ }
341
+ if (tag === "tr") {
342
+ this.tableRows.push([...this.currentRow]);
343
+ this.currentRow = [];
344
+ return;
345
+ }
346
+ if (tag === "table") {
347
+ const tableText = renderTable(this.tableRows);
348
+ this.tableRows = [];
349
+ this.flushLine(tableText);
350
+ if (this.blockStack[this.blockStack.length - 1]?.tag === "table") this.blockStack.pop();
351
+ return;
352
+ }
353
+ if (tag === "ul" || tag === "ol") this.listStack.pop();
354
+ if (tag === "blockquote") this.blockquoteDepth = Math.max(0, this.blockquoteDepth - 1);
355
+ if (!BLOCK_TAGS.has(tag)) return;
356
+ const frame = this.blockStack.pop();
357
+ if (!frame) return;
358
+ if (frame.tag === "pre") {
359
+ this.inPre = false;
360
+ const code = frame.text.trimEnd();
361
+ this.flushLine(styleCodeBlock(code, frame.codeLang));
362
+ return;
363
+ }
364
+ if (frame.tag === "hr") {
365
+ this.flushLine(styleHr(this.opts.columns));
366
+ return;
367
+ }
368
+ const text = frame.text.trim();
369
+ if (!text && frame.tag !== "br") return;
370
+ if (frame.headingLevel) {
371
+ const wrapped = wrapAnsi(text, this.opts.columns - frame.headingLevel - 1, {
372
+ hard: false,
373
+ trim: false
374
+ });
375
+ this.flushLine(styleHeading(frame.headingLevel, wrapped));
376
+ return;
377
+ }
378
+ if (frame.tag === "li" && frame.listBullet) {
379
+ const indent = " ".repeat((frame.listBullet.match(/^ +/)?.[0].length ?? 0) + 2);
380
+ const wrapped = wrapAnsi(text, this.opts.columns - indent.length, {
381
+ hard: false,
382
+ trim: false
383
+ }).split("\n").map((line, i) => i === 0 ? frame.listBullet + line : indent + line).join("\n");
384
+ if (this.blockquoteDepth > 0) this.flushLine(styleBlockquote(wrapped));
385
+ else this.flushLine(wrapped);
386
+ return;
387
+ }
388
+ if (frame.tag === "blockquote") {
389
+ const wrapped = wrapAnsi(text, this.opts.columns - 2, {
390
+ hard: false,
391
+ trim: false
392
+ });
393
+ this.flushLine(styleBlockquote(wrapped));
394
+ return;
395
+ }
396
+ if ([
397
+ "p",
398
+ "div",
399
+ "section",
400
+ "article"
401
+ ].includes(frame.tag)) {
402
+ const wrapped = wrapAnsi(text, this.opts.columns, {
403
+ hard: false,
404
+ trim: false
405
+ });
406
+ if (this.blockquoteDepth > 0) this.flushLine(styleBlockquote(wrapped));
407
+ else this.flushLine(wrapped);
408
+ return;
409
+ }
410
+ if (text) {
411
+ const wrapped = wrapAnsi(text, this.opts.columns, {
412
+ hard: false,
413
+ trim: false
414
+ });
415
+ this.flushLine(wrapped);
416
+ }
417
+ }
418
+ appendToCurrentBlock(text) {
419
+ if (this.blockStack.length > 0) this.blockStack[this.blockStack.length - 1].text += text;
420
+ else this.topLevelBuffer += text;
421
+ }
422
+ /** Flush accumulated top-level text as a single wrapped line. */
423
+ flushTopLevelBuffer() {
424
+ const raw = this.topLevelBuffer.trim();
425
+ this.topLevelBuffer = "";
426
+ if (!raw) return;
427
+ const wrapped = wrapAnsi(raw, this.opts.columns, {
428
+ hard: false,
429
+ trim: false
430
+ });
431
+ if (wrapped) this.flushLine(wrapped);
432
+ }
433
+ flushLine(text) {
434
+ if (!text) return;
435
+ if (this.opts.onFlush) this.opts.onFlush(text);
436
+ else this.collected.push(text);
437
+ }
438
+ /** Emit current partial block content (the "live" incomplete block). */
439
+ emitPartial() {
440
+ if (!this.opts.onPartial) return;
441
+ const top = this.blockStack[this.blockStack.length - 1];
442
+ if (!top) return;
443
+ const text = top.text.trim();
444
+ if (!text) return;
445
+ this.opts.onPartial(text);
446
+ }
447
+ };
448
+ function renderTable(rows) {
449
+ if (rows.length === 0) return "";
450
+ const colCount = Math.max(...rows.map((r) => r.length));
451
+ const colWidths = Array(colCount).fill(0);
452
+ for (const row of rows) for (let c = 0; c < colCount; c++) colWidths[c] = Math.max(colWidths[c], stringWidth(row[c] ?? ""));
453
+ const lines = [];
454
+ const sep = chalk.gray("┼" + colWidths.map((w) => "─".repeat(w + 2)).join("┼") + "┼");
455
+ for (let r = 0; r < rows.length; r++) {
456
+ const row = rows[r];
457
+ const cells = colWidths.map((w, c) => {
458
+ const cell = row[c] ?? "";
459
+ const pad = w - stringWidth(cell);
460
+ return " " + cell + " ".repeat(Math.max(0, pad)) + " ";
461
+ });
462
+ lines.push(chalk.gray("│") + cells.join(chalk.gray("│")) + chalk.gray("│"));
463
+ if (r === 0) lines.push(sep);
464
+ }
465
+ const top = chalk.gray("┌") + colWidths.map((w) => chalk.gray("─".repeat(w + 2))).join(chalk.gray("┬")) + chalk.gray("┐");
466
+ const bottom = chalk.gray("└") + colWidths.map((w) => chalk.gray("─".repeat(w + 2))).join(chalk.gray("┴")) + chalk.gray("┘");
467
+ return [
468
+ top,
469
+ ...lines,
470
+ bottom
471
+ ].join("\n");
472
+ }
473
+
474
+ //#endregion
475
+ export { StreamingHtmlRenderer, highlightCode, initSyntaxHighlighting };
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@one-agent/html",
3
+ "version": "0.0.1-beta.2",
4
+ "description": "Streaming HTML → ANSI terminal renderer for ONE agent output.",
5
+ "keywords": [
6
+ "html",
7
+ "ansi",
8
+ "terminal",
9
+ "streaming",
10
+ "renderer",
11
+ "ai-agent",
12
+ "cli"
13
+ ],
14
+ "homepage": "https://github.com/RIA-Spec/one-agent#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/RIA-Spec/one-agent/issues"
17
+ },
18
+ "license": "Apache-2.0",
19
+ "type": "module",
20
+ "main": "./dist/index.mjs",
21
+ "module": "./dist/index.mjs",
22
+ "types": "./dist/index.d.mts",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/RIA-Spec/one-agent.git"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "NOTICE",
33
+ "README.md"
34
+ ],
35
+ "exports": {
36
+ ".": "./dist/index.mjs",
37
+ "./package.json": "./package.json"
38
+ },
39
+ "dependencies": {
40
+ "chalk": "^5.6.2",
41
+ "htmlparser2": "^9.1.0",
42
+ "shiki": "^3.23.0",
43
+ "string-width": "^7.2.0",
44
+ "wrap-ansi": "^9.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^25.0.3",
48
+ "oxfmt": "^0.28.0",
49
+ "tsdown": "^0.18.1",
50
+ "typescript": "^5.9.3",
51
+ "vitest": "^4.0.16"
52
+ },
53
+ "scripts": {
54
+ "build": "tsdown",
55
+ "dev": "tsdown --watch",
56
+ "typecheck": "tsc --noEmit",
57
+ "test": "vitest run"
58
+ }
59
+ }