@pierre/words 0.0.0-stage → 0.1.1

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.md ADDED
@@ -0,0 +1,189 @@
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, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the
13
+ copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other
16
+ entities that control, are controlled by, or are under common control with
17
+ that entity. For the purposes of this definition, "control" means (i) the
18
+ power, direct or indirect, to cause the direction or management of such
19
+ entity, whether by contract or otherwise, or (ii) ownership of fifty percent
20
+ (50%) or more of the outstanding shares, or (iii) beneficial ownership of
21
+ such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ 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 source, and
28
+ configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical transformation
31
+ or translation of a Source form, including but not limited to compiled
32
+ object code, generated documentation, and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or Object form,
35
+ made available under the License, as indicated by a copyright notice that is
36
+ included in or attached to the work (an example is provided in the Appendix
37
+ below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object form,
40
+ that is based on (or derived from) the Work and for which the editorial
41
+ revisions, annotations, elaborations, or other modifications represent, as a
42
+ whole, an original work of authorship. For the purposes of this License,
43
+ Derivative Works shall not include works that remain separable from, or
44
+ merely link (or bind by name) to the interfaces of, the Work and Derivative
45
+ Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including the original
48
+ version of the Work and any modifications or additions to that Work or
49
+ Derivative Works thereof, that is intentionally submitted to Licensor for
50
+ inclusion in the Work by the copyright owner or by an individual or Legal
51
+ Entity authorized to submit on behalf of the copyright owner. For the
52
+ purposes of this definition, "submitted" means any form of electronic,
53
+ verbal, or written communication sent to the Licensor or its
54
+ representatives, including but not limited to communication on electronic
55
+ mailing lists, source code control systems, and issue tracking systems that
56
+ are managed by, or on behalf of, the Licensor for the purpose of discussing
57
+ and improving the Work, but excluding communication that is conspicuously
58
+ marked or otherwise designated in writing by the copyright owner as "Not a
59
+ Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity on
62
+ behalf of whom a Contribution has been received by Licensor and subsequently
63
+ incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
66
+ License, each Contributor hereby grants to You a perpetual, worldwide,
67
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
68
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
69
+ sublicense, and distribute the Work and such Derivative Works in Source or
70
+ Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of this
73
+ License, each Contributor hereby grants to You a perpetual, worldwide,
74
+ non-exclusive, no-charge, royalty-free, irrevocable (except as stated in
75
+ this section) patent license to make, have made, use, offer to sell, sell,
76
+ import, and otherwise transfer the Work, where such license applies only to
77
+ those patent claims licensable by such Contributor that are necessarily
78
+ infringed by their Contribution(s) alone or by combination of their
79
+ Contribution(s) with the Work to which such Contribution(s) was submitted.
80
+ If You institute patent litigation against any entity (including a
81
+ cross-claim or counterclaim in a lawsuit) alleging that the Work or a
82
+ Contribution incorporated within the Work constitutes direct or contributory
83
+ patent infringement, then any patent licenses granted to You under this
84
+ License for that Work shall terminate as of the date such litigation is
85
+ filed.
86
+
87
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
88
+ Derivative Works thereof in any medium, with or without modifications, and
89
+ in Source or Object form, provided that You meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative Works a
92
+ copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices stating
95
+ that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works that You
98
+ distribute, all copyright, patent, trademark, and attribution notices from
99
+ the Source form of the Work, excluding those notices that do not pertain to
100
+ any part of the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its distribution,
103
+ then any Derivative Works that You distribute must include a readable copy
104
+ of the attribution notices contained within such NOTICE file, excluding
105
+ those notices that do not pertain to any part of the Derivative Works, in at
106
+ least one of the following places: within a NOTICE text file distributed as
107
+ part of the Derivative Works; within the Source form or documentation, if
108
+ provided along with the Derivative Works; or, within a display generated by
109
+ the Derivative Works, if and wherever such third-party notices normally
110
+ appear. The contents of the NOTICE file are for informational purposes only
111
+ and do not modify the License. You may add Your own attribution notices
112
+ within Derivative Works that You distribute, alongside or as an addendum to
113
+ the NOTICE text from the Work, provided that such additional attribution
114
+ notices cannot be construed as modifying the License.
115
+
116
+ You may add Your own copyright statement to Your modifications and may
117
+ provide additional or different license terms and conditions for use,
118
+ reproduction, or distribution of Your modifications, or for any such
119
+ Derivative Works as a whole, provided Your use, reproduction, and
120
+ distribution of the Work otherwise complies with the conditions stated in
121
+ this License.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
124
+ Contribution intentionally submitted for inclusion in the Work by You to the
125
+ Licensor shall be under the terms and conditions of this License, without
126
+ any additional terms or conditions. Notwithstanding the above, nothing
127
+ herein shall supersede or modify the terms of any separate license agreement
128
+ you may have executed with Licensor regarding such Contributions.
129
+
130
+ 6. Trademarks. This License does not grant permission to use the trade names,
131
+ trademarks, service marks, or product names of the Licensor, except as
132
+ required for reasonable and customary use in describing the origin of the
133
+ Work and reproducing the content of the NOTICE file.
134
+
135
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
136
+ writing, Licensor provides the Work (and each Contributor provides its
137
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
138
+ KIND, either express or implied, including, without limitation, any
139
+ warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or
140
+ FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining
141
+ the appropriateness of using or redistributing the Work and assume any risks
142
+ associated with Your exercise of permissions under this License.
143
+
144
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
145
+ tort (including negligence), contract, or otherwise, unless required by
146
+ applicable law (such as deliberate and grossly negligent acts) or agreed to
147
+ in writing, shall any Contributor be liable to You for damages, including
148
+ any direct, indirect, special, incidental, or consequential damages of any
149
+ character arising as a result of this License or out of the use or inability
150
+ to use the Work (including but not limited to damages for loss of goodwill,
151
+ work stoppage, computer failure or malfunction, or any and all other
152
+ commercial damages or losses), even if such Contributor has been advised of
153
+ the possibility of such damages.
154
+
155
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
156
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
157
+ acceptance of support, warranty, indemnity, or other liability obligations
158
+ and/or rights consistent with this License. However, in accepting such
159
+ obligations, You may act only on Your own behalf and on Your sole
160
+ responsibility, not on behalf of any other Contributor, and only if You
161
+ agree to indemnify, defend, and hold each Contributor harmless for any
162
+ liability incurred by, or claims asserted against, such Contributor by
163
+ reason of your accepting any such warranty or additional liability.
164
+
165
+ END OF TERMS AND CONDITIONS
166
+
167
+ APPENDIX: How to apply the Apache License to your work.
168
+
169
+ To apply the Apache License to your work, attach the following
170
+ boilerplate notice, with the fields enclosed by brackets "[]"
171
+ replaced with your own identifying information. (Don't include
172
+ the brackets!) The text should be enclosed in the appropriate
173
+ comment syntax for the file format. We also recommend that a
174
+ file or class name and description of purpose be included on the
175
+ same "printed page" as the copyright notice for easier
176
+ identification within third-party archives.
177
+
178
+ Copyright 2025 Pierre Computer Company
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
181
+ this file except in compliance with the License. You may obtain a copy of the
182
+ License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software distributed
187
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
188
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
189
+ specific language governing permissions and limitations under the License.
package/NOTICE.md ADDED
@@ -0,0 +1,25 @@
1
+ # Third-party notices
2
+
3
+ `@pierre/words` is licensed under Apache 2.0. The material below keeps its
4
+ original license.
5
+
6
+ ## Data in the published package
7
+
8
+ | Data | Location | Source | License |
9
+ | ------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------ | --------------------------------------------------------- |
10
+ | HTML named character references | `src/entities.txt`, `dist/md.wasm` | [WHATWG HTML `entities.json`](https://html.spec.whatwg.org/entities.json) | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) |
11
+ | East Asian Width ranges | `scripts/build.ts`, `dist/md.wasm` | [Unicode `EastAsianWidth.txt`](https://www.unicode.org/Public/UCD/latest/ucd/) | [Unicode License v3](https://www.unicode.org/license.txt) |
12
+
13
+ ## Test and benchmark files, not published
14
+
15
+ | File | Source | License |
16
+ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
17
+ | `test/spec/commonmark-spec.json` | [CommonMark Spec 0.31.2](https://spec.commonmark.org/0.31.2/) by John MacFarlane | [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) |
18
+ | `test/spec/gfm-spec.json` | [GitHub Flavored Markdown Spec 0.29](https://github.com/github/cmark-gfm/blob/0.29.0.gfm.13/test/spec.txt), based on CommonMark | [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) |
19
+ | `benchmark/fixtures/gfm-spec.md` | The same GitHub Flavored Markdown Spec, without its front matter | [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) |
20
+ | `benchmark/fixtures/simd.md` | [WebAssembly SIMD proposal](https://github.com/WebAssembly/simd/blob/master/proposals/simd/SIMD.md) | See below |
21
+
22
+ The
23
+ [WebAssembly SIMD repository notice](https://github.com/WebAssembly/simd/blob/master/LICENSE)
24
+ lists a license for each of its top-level directories, and it does not list
25
+ `proposals/`. `simd.md` is used only as benchmark input.
package/README.md CHANGED
@@ -1,3 +1,157 @@
1
- # Temporary Holding Version
1
+ # Words, from Pierre
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@pierre/words` is a Markdown renderer written in WebAssembly Text (WAT). It
4
+ supports CommonMark 0.31.2 and GFM 0.29, and writes HTML or ANSI. The core has
5
+ no runtime dependencies. A React component for streaming text and a code
6
+ highlighting plugin are optional.
7
+
8
+ Try the [demo](https://diffs.com/words).
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ pnpm add @pierre/words
14
+ ```
15
+
16
+ The package runs in Node.js, browsers, and Cloudflare Workers.
17
+
18
+ ## Quick start
19
+
20
+ ```js
21
+ import { renderToAnsi, renderToHtml } from '@pierre/words';
22
+
23
+ const html = new TextDecoder().decode(renderToHtml('# Hello, **world**!'));
24
+ process.stdout.write(renderToAnsi('# Hello, **world**!', { width: 80 }));
25
+ ```
26
+
27
+ Both functions take a string, `Uint8Array`, or `ArrayBuffer`. They return a
28
+ `Uint8Array` that shares Wasm memory, so decode or copy it before the next
29
+ render.
30
+
31
+ `renderToHtml()` options:
32
+
33
+ | Option | Default | Purpose |
34
+ | ------------- | ------- | -------------------------------------------------------------------------------------- |
35
+ | `frontmatter` | `false` | Parse YAML frontmatter and return `[meta, output]`. `meta` is `null` if there is none. |
36
+ | `skipHtml` | `false` | Omit raw HTML. |
37
+ | `incomplete` | `false` | Complete common unfinished inline syntax. |
38
+
39
+ `renderToAnsi()` takes `width`, the wrap column. With the default, `0`, the
40
+ terminal wraps the text. Control characters print as U+FFFD, so a document
41
+ cannot send escape sequences.
42
+
43
+ **Warning:** `renderToHtml()` keeps raw HTML by default. Sanitize the output of
44
+ untrusted Markdown before you add it to a page. `skipHtml` alone is not a
45
+ sanitizer.
46
+
47
+ ## React
48
+
49
+ ```tsx
50
+ import { Markdown } from '@pierre/words/react';
51
+ import '@pierre/words/styles.css';
52
+
53
+ <Markdown isAnimating={status === 'streaming'} caret="block">
54
+ {message.text}
55
+ </Markdown>;
56
+ ```
57
+
58
+ Pass the full Markdown string on each update, and keep `isAnimating` true for as
59
+ long as text arrives. While it is true, the component completes unfinished
60
+ emphasis, code, and links, and hides unfinished images. Finished text renders as
61
+ normal Markdown.
62
+
63
+ | Prop | Purpose |
64
+ | --------------------------------------- | --------------------------------------------------------------------------------------------- |
65
+ | `children` | Full Markdown string. |
66
+ | `isAnimating` | The stream is active. Default: `false`. |
67
+ | `mode` | `streaming` (default), or `static` for content that never streams. |
68
+ | `parseIncompleteMarkdown` | Complete unfinished syntax while the stream is active. Default: `true`. |
69
+ | `animated` | Fade in new text. Use `true` or `{ animation: 'fadeIn', duration: 180 }`. Default: `false`. |
70
+ | `caret` | Show a `block` or `circle` caret while the stream is active. |
71
+ | `components` | HTML hooks for generated elements, including `inlineCode`. |
72
+ | `plugins.code` | Code highlighter. |
73
+ | `plugins.renderers` | Custom code block renderers, selected by language. |
74
+ | `controls` | Code copy/download buttons. Use a boolean or `{ code: { copy, download } }`. Default: `true`. |
75
+ | `lineNumbers` | Show code line numbers. Default: `true`. |
76
+ | `allowedElements`, `disallowedElements` | Element filters. Use only one of these props. |
77
+ | `unwrapDisallowed` | Keep the children of filtered elements. |
78
+ | `urlTransform` | Change link and image URLs before validation. |
79
+ | `idPrefix` | Prefix for generated ids. Default: a unique React id. |
80
+ | `onAnimationStart`, `onAnimationEnd` | Called when the stream starts and ends. |
81
+
82
+ Fades and the caret need `styles.css`. Fades run only during a stream. Reduced
83
+ motion and a zero duration turn them off.
84
+
85
+ Hooks take and return HTML strings, not React elements:
86
+
87
+ ```tsx
88
+ const components = {
89
+ a: (html: string) => html.replace('<a ', '<a class="message-link" '),
90
+ };
91
+
92
+ <Markdown components={components}>{text}</Markdown>;
93
+ ```
94
+
95
+ The component omits raw HTML and rejects unsafe URL schemes. It allows external
96
+ images, so use `urlTransform` or element filters to block them. Hooks and
97
+ plugins are trusted code: escape any untrusted text they add.
98
+
99
+ Math, Mermaid, CJK extensions, and remark or rehype plugins are not supported.
100
+
101
+ ### Syntax highlighting
102
+
103
+ ```tsx
104
+ import { createHighlightsPlugin } from '@pierre/words/highlights';
105
+ import pierreLight from '@pierre/highlights/themes/pierre-light';
106
+
107
+ const plugins = { code: createHighlightsPlugin({ theme: pierreLight }) };
108
+
109
+ <Markdown plugins={plugins}>{text}</Markdown>;
110
+ ```
111
+
112
+ Create the plugin once, outside the render. Unknown languages render as plain
113
+ text. React and `@pierre/highlights` are optional peer dependencies, and the
114
+ core entry point loads neither.
115
+
116
+ ## HTML sessions
117
+
118
+ A session renders a growing string to HTML, without React or a browser:
119
+
120
+ ```ts
121
+ import { createHtmlSession } from '@pierre/words';
122
+
123
+ const session = createHtmlSession();
124
+ const { html, stable, pending } = session.render('First paragraph.\n\nSecond');
125
+ session.render('First paragraph.\n\nSecond paragraph.');
126
+ ```
127
+
128
+ `stable` holds completed blocks, `pending` holds the part that can still change,
129
+ and `html` holds both. Sessions omit raw HTML.
130
+
131
+ Pass `{ incomplete: true }` as the second argument to complete unfinished
132
+ syntax. A link with no destination yet renders as
133
+ `<a data-markdown-incomplete>`. A session always renders an open code fence as
134
+ `<pre data-markdown-incomplete>`.
135
+
136
+ Appended text reuses completed blocks. An edit, a changed `incomplete` option,
137
+ or a link or footnote definition can force a full render. A long open paragraph
138
+ is parsed again on each update.
139
+
140
+ `@pierre/words/html` exports `createHtmlRenderer()` for formatted HTML and
141
+ `createDomRenderer()` for DOM updates without React. See
142
+ [`html/types.ts`](./html/types.ts) for their options.
143
+
144
+ ## Development
145
+
146
+ ```bash
147
+ moonx words:build
148
+ moonx words:test
149
+ moonx words:test-spec
150
+ moonx words:bench --ignore-ci-checks
151
+ ```
152
+
153
+ [Benchmarks](./benchmark/README.md) · [Architecture](./ARCHITECTURE.md)
154
+
155
+ ## License
156
+
157
+ [Apache-2.0](./LICENSE.md)
package/dist/core.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { AnsiOptions, Frontmatter, HtmlSessionOptions, HtmlUpdate, RenderOptions } from "./types.js";
2
+ //#region lib/core.d.ts
3
+ type Input = string | Uint8Array | ArrayBuffer;
4
+ /** `boundary` makes Wasm measure the session's safe boundary in UTF-16 units. */
5
+ type Options = AnsiOptions & RenderOptions & {
6
+ boundary?: boolean;
7
+ };
8
+ declare class Renderer {
9
+ memory: WebAssembly.Memory;
10
+ wasmRender: () => void;
11
+ buffer: Uint8Array<ArrayBuffer>;
12
+ dv: DataView<ArrayBuffer>;
13
+ pages: number;
14
+ constructor(wasmModule: WebAssembly.Module);
15
+ render(input: Input, mode: number, options?: Options): {
16
+ output: Uint8Array;
17
+ meta?: Uint8Array;
18
+ };
19
+ grow(len: number): void;
20
+ bindMemory(): void;
21
+ }
22
+ declare function init(wasmModule: WebAssembly.Module): Renderer;
23
+ declare function renderToHtml(input: Input): Uint8Array;
24
+ declare function renderToHtml<T = Frontmatter>(input: Input, options: RenderOptions & {
25
+ frontmatter: true;
26
+ }): [T | null, Uint8Array];
27
+ declare function renderToHtml(input: Input, options?: RenderOptions & {
28
+ frontmatter?: false;
29
+ }): Uint8Array;
30
+ declare function renderToHtml<T = Frontmatter>(input: Input, options: RenderOptions): Uint8Array | [T | null, Uint8Array];
31
+ declare function renderToAnsi(input: Input, options?: AnsiOptions): Uint8Array;
32
+ /**
33
+ * Render a growing string to HTML. A session keeps completed HTML and reparses
34
+ * only the unfinished end.
35
+ */
36
+ declare function createHtmlSession(): {
37
+ render(input: string, options?: HtmlSessionOptions): HtmlUpdate;
38
+ };
39
+ //#endregion
40
+ export { type AnsiOptions, type Frontmatter, type HtmlSessionOptions, type HtmlUpdate, type RenderOptions, createHtmlSession, init, renderToAnsi, renderToHtml };
41
+ //# sourceMappingURL=core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.d.ts","names":[],"sources":["../lib/core.ts"],"mappings":";;KAgBK,iBAAiB,aAAa;;KAE9B,UAAU,cAAc;EAAkB;;cAUzC;EACJ,QAAQ,YAAY;EACpB;EACA,QAAS,WAAW;EACpB,IAAK,SAAS;EACd;EAEA,YAAY,YAAY,YAAY;EAYpC,OACE,OAAO,OACP,cACA,UAAU;IACP,QAAQ;IAAY,OAAO;;EA8DhC,KAAK;EAQL;;iBAac,KAAK,YAAY,YAAY,SAAS;iBAItC,aAAa,OAAO,QAAQ;iBAC5B,aAAa,IAAI,aAC/B,OAAO,OACP,SAAS;EAAkB;KACzB,UAAU;iBACE,aACd,OAAO,OACP,UAAU;EAAkB;IAC3B;iBACa,aAAa,IAAI,aAC/B,OAAO,OACP,SAAS,gBACR,cAAc,UAAU;iBAUX,aAAa,OAAO,OAAO,UAAU,cAAc;;;;;iBAQnD;EACd,OAAO,eAAe,UAAU,qBAAqB"}
package/dist/core.js ADDED
@@ -0,0 +1,147 @@
1
+ //#region lib/core.ts
2
+ const enc = new TextEncoder();
3
+ const dec = new TextDecoder("utf-8", { ignoreBOM: true });
4
+ const pageSize = 65536;
5
+ const maxInput = 2 ** 30 - 2 * pageSize;
6
+ var Renderer = class {
7
+ memory;
8
+ wasmRender;
9
+ buffer;
10
+ dv;
11
+ pages;
12
+ constructor(wasmModule) {
13
+ const instance = new WebAssembly.Instance(wasmModule, {});
14
+ this.memory = instance.exports.memory;
15
+ this.wasmRender = instance.exports.render;
16
+ instance.exports.seed(Math.random() * 2 ** 32 >>> 0);
17
+ this.bindMemory();
18
+ }
19
+ render(input, mode, options) {
20
+ if (typeof input !== "string" && !(input instanceof Uint8Array) && !(input instanceof ArrayBuffer)) throw new TypeError("input must be a string, Uint8Array, or ArrayBuffer");
21
+ let inputLength;
22
+ if (typeof input === "string") {
23
+ this.grow(Math.min(input.length * 3, maxInput + 1) + 8192);
24
+ const { read, written } = enc.encodeInto(input, this.buffer.subarray(pageSize, pageSize + maxInput + 1));
25
+ if (read < input.length || written > maxInput) throw tooLarge();
26
+ inputLength = written;
27
+ } else {
28
+ if (input instanceof ArrayBuffer) input = new Uint8Array(input);
29
+ if (input.length > maxInput) throw tooLarge();
30
+ if (input.buffer === this.memory.buffer) input = input.slice();
31
+ this.grow(input.length + 8192);
32
+ this.buffer.set(input, pageSize);
33
+ inputLength = input.length;
34
+ }
35
+ this.dv.setUint8(0, mode);
36
+ this.dv.setUint8(1, (options?.frontmatter === true ? 1 : 0) | (options?.skipHtml === true ? 2 : 0) | (options?.boundary === true ? 8 : 0) | (mode === 1 && typeof input !== "string" ? 32 : 0) | (options?.incomplete === true ? 64 : 0));
37
+ this.dv.setUint32(2, inputLength, true);
38
+ this.dv.setUint32(22, options?.width != null && options.width > 0 ? Math.min(options.width, 4096) : 0, true);
39
+ this.buffer.fill(0, pageSize + inputLength, pageSize + inputLength + 32);
40
+ try {
41
+ this.wasmRender();
42
+ } finally {
43
+ this.bindMemory();
44
+ }
45
+ const outStart = this.dv.getUint32(6, true);
46
+ const outLength = this.dv.getUint32(10, true);
47
+ const metaStart = this.dv.getUint32(14, true);
48
+ const metaLength = this.dv.getUint32(18, true);
49
+ const ret = { output: this.buffer.subarray(outStart, outStart + outLength) };
50
+ if (metaStart !== 0) ret.meta = this.buffer.subarray(metaStart, metaStart + metaLength);
51
+ return ret;
52
+ }
53
+ grow(len) {
54
+ const needed = 1 + Math.ceil(len / pageSize);
55
+ if (needed > this.pages) {
56
+ this.memory.grow(needed - this.pages);
57
+ this.bindMemory();
58
+ }
59
+ }
60
+ bindMemory() {
61
+ if (this.buffer?.buffer === this.memory.buffer) return;
62
+ this.pages = this.memory.buffer.byteLength / pageSize;
63
+ this.buffer = new Uint8Array(this.memory.buffer);
64
+ this.dv = new DataView(this.memory.buffer);
65
+ }
66
+ };
67
+ let shared;
68
+ const tooLarge = () => /* @__PURE__ */ new RangeError(`input exceeds ${maxInput} bytes of UTF-8`);
69
+ function init(wasmModule) {
70
+ return shared = new Renderer(wasmModule);
71
+ }
72
+ function renderToHtml(input, options) {
73
+ const { output, meta } = shared.render(input, 0, options);
74
+ if (options?.frontmatter !== true) return output;
75
+ return [meta != null ? JSON.parse(dec.decode(meta)) : null, output];
76
+ }
77
+ function renderToAnsi(input, options) {
78
+ return shared.render(input, 1, { width: options?.width }).output;
79
+ }
80
+ /**
81
+ * Render a growing string to HTML. A session keeps completed HTML and reparses
82
+ * only the unfinished end.
83
+ */
84
+ function createHtmlSession() {
85
+ let previous = "";
86
+ let stable = "";
87
+ let offset = 0;
88
+ let definitions = false;
89
+ let incomplete;
90
+ let result;
91
+ let revision = 0;
92
+ return { render(input, options) {
93
+ if (typeof input !== "string") throw new TypeError("session input must be a string");
94
+ const wanted = options?.incomplete === true;
95
+ if (input === previous && incomplete === wanted && result != null) return result;
96
+ let reset = input.length < previous.length || input.slice(0, previous.length) !== previous || incomplete !== wanted || definitions;
97
+ if (offset !== 0 && input.charCodeAt(offset) === 65279) reset = true;
98
+ let nextStable = reset ? "" : stable;
99
+ let nextOffset = reset ? 0 : offset;
100
+ const renderOptions = {
101
+ skipHtml: true,
102
+ incomplete: wanted,
103
+ boundary: true
104
+ };
105
+ let tail = input.slice(nextOffset);
106
+ let rendered = shared.render(tail, 0, renderOptions);
107
+ if (nextOffset !== 0 && shared.dv.getUint8(30) !== 0) {
108
+ nextStable = "";
109
+ nextOffset = 0;
110
+ reset = true;
111
+ tail = input;
112
+ rendered = shared.render(tail, 0, renderOptions);
113
+ }
114
+ const html = dec.decode(rendered.output);
115
+ definitions = shared.dv.getUint8(30) !== 0;
116
+ const completed = definitions ? 0 : shared.dv.getUint32(36, true);
117
+ let pending = html;
118
+ let addition = "";
119
+ if (completed > 0 && completed <= tail.length) {
120
+ addition = html.slice(0, shared.dv.getUint32(40, true));
121
+ nextStable += addition;
122
+ nextOffset += completed;
123
+ pending = html.slice(addition.length);
124
+ }
125
+ stable = nextStable;
126
+ offset = nextOffset;
127
+ previous = input;
128
+ incomplete = wanted;
129
+ const completedHtml = stable;
130
+ let fullHtml;
131
+ result = {
132
+ get html() {
133
+ return fullHtml ??= completedHtml + pending;
134
+ },
135
+ stable: completedHtml,
136
+ addition,
137
+ pending,
138
+ reset,
139
+ revision: ++revision
140
+ };
141
+ return result;
142
+ } };
143
+ }
144
+ //#endregion
145
+ export { createHtmlSession, init, renderToAnsi, renderToHtml };
146
+
147
+ //# sourceMappingURL=core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.js","names":[],"sources":["../lib/core.ts"],"sourcesContent":["import type {\n AnsiOptions,\n Frontmatter,\n HtmlSessionOptions,\n HtmlUpdate,\n RenderOptions,\n} from './types';\n\nexport type {\n AnsiOptions,\n Frontmatter,\n HtmlSessionOptions,\n HtmlUpdate,\n RenderOptions,\n} from './types';\n\ntype Input = string | Uint8Array | ArrayBuffer;\n/** `boundary` makes Wasm measure the session's safe boundary in UTF-16 units. */\ntype Options = AnsiOptions & RenderOptions & { boundary?: boolean };\n\nconst enc = new TextEncoder();\n// Keep a leading U+FEFF so string lengths match the UTF-16 counts from Wasm.\nconst dec = new TextDecoder('utf-8', { ignoreBOM: true });\nconst pageSize = 65536;\n// Line records keep 30-bit end addresses and the input starts after the first\n// 64 KiB page. Another 64 KiB stays free for the closers completion appends.\nconst maxInput = 2 ** 30 - 2 * pageSize;\n\nclass Renderer {\n memory: WebAssembly.Memory;\n wasmRender: () => void;\n buffer!: Uint8Array<ArrayBuffer>;\n dv!: DataView<ArrayBuffer>;\n pages!: number;\n\n constructor(wasmModule: WebAssembly.Module) {\n const instance = new WebAssembly.Instance(wasmModule, {});\n this.memory = instance.exports.memory as WebAssembly.Memory;\n this.wasmRender = instance.exports.render as () => void;\n // A random label hash seed, so crafted reference labels cannot share a\n // slot. Math.random suffices and avoids ~2 MiB of webcrypto setup in Node.\n (instance.exports.seed as (seed: number) => void)(\n (Math.random() * 2 ** 32) >>> 0\n );\n this.bindMemory();\n }\n\n render(\n input: Input,\n mode: number,\n options?: Options\n ): { output: Uint8Array; meta?: Uint8Array } {\n if (\n typeof input !== 'string' &&\n !(input instanceof Uint8Array) &&\n !(input instanceof ArrayBuffer)\n ) {\n throw new TypeError('input must be a string, Uint8Array, or ArrayBuffer');\n }\n let inputLength;\n if (typeof input === 'string') {\n this.grow(Math.min(input.length * 3, maxInput + 1) + 8192);\n const { read, written } = enc.encodeInto(\n input,\n this.buffer.subarray(pageSize, pageSize + maxInput + 1)\n );\n if (read < input.length || written > maxInput) throw tooLarge();\n inputLength = written;\n } else {\n if (input instanceof ArrayBuffer) input = new Uint8Array(input);\n if (input.length > maxInput) throw tooLarge();\n // growing detaches the old buffer, so copy an aliasing input first\n if (input.buffer === this.memory.buffer) input = input.slice();\n this.grow(input.length + 8192);\n this.buffer.set(input, pageSize);\n inputLength = input.length;\n }\n this.dv.setUint8(0, mode);\n this.dv.setUint8(\n 1,\n (options?.frontmatter === true ? 1 : 0) |\n (options?.skipHtml === true ? 2 : 0) |\n (options?.boundary === true ? 8 : 0) |\n (mode === 1 && typeof input !== 'string' ? 32 : 0) |\n (options?.incomplete === true ? 64 : 0)\n );\n this.dv.setUint32(2, inputLength, true);\n this.dv.setUint32(\n 22,\n options?.width != null && options.width > 0\n ? Math.min(options.width, 4096)\n : 0,\n true\n );\n // the NUL sentinel and the slack the SIMD scans read into\n this.buffer.fill(0, pageSize + inputLength, pageSize + inputLength + 32);\n try {\n this.wasmRender();\n } finally {\n this.bindMemory();\n }\n const outStart = this.dv.getUint32(6, true);\n const outLength = this.dv.getUint32(10, true);\n const metaStart = this.dv.getUint32(14, true);\n const metaLength = this.dv.getUint32(18, true);\n const ret: { output: Uint8Array; meta?: Uint8Array } = {\n output: this.buffer.subarray(outStart, outStart + outLength),\n };\n if (metaStart !== 0)\n ret.meta = this.buffer.subarray(metaStart, metaStart + metaLength);\n return ret;\n }\n\n grow(len: number) {\n const needed = 1 + Math.ceil(len / pageSize);\n if (needed > this.pages) {\n this.memory.grow(needed - this.pages);\n this.bindMemory();\n }\n }\n\n bindMemory() {\n if (this.buffer?.buffer === this.memory.buffer) return;\n this.pages = this.memory.buffer.byteLength / pageSize;\n this.buffer = new Uint8Array(this.memory.buffer);\n this.dv = new DataView(this.memory.buffer);\n }\n}\n\nlet shared: Renderer;\n\nconst tooLarge = () =>\n new RangeError(`input exceeds ${maxInput} bytes of UTF-8`);\n\nexport function init(wasmModule: WebAssembly.Module): Renderer {\n return (shared = new Renderer(wasmModule));\n}\n\nexport function renderToHtml(input: Input): Uint8Array;\nexport function renderToHtml<T = Frontmatter>(\n input: Input,\n options: RenderOptions & { frontmatter: true }\n): [T | null, Uint8Array];\nexport function renderToHtml(\n input: Input,\n options?: RenderOptions & { frontmatter?: false }\n): Uint8Array;\nexport function renderToHtml<T = Frontmatter>(\n input: Input,\n options: RenderOptions\n): Uint8Array | [T | null, Uint8Array];\nexport function renderToHtml(\n input: Input,\n options?: RenderOptions\n): Uint8Array | [unknown, Uint8Array] {\n const { output, meta } = shared.render(input, 0, options);\n if (options?.frontmatter !== true) return output;\n return [meta != null ? JSON.parse(dec.decode(meta)) : null, output];\n}\n\nexport function renderToAnsi(input: Input, options?: AnsiOptions): Uint8Array {\n return shared.render(input, 1, { width: options?.width }).output;\n}\n\n/**\n * Render a growing string to HTML. A session keeps completed HTML and reparses\n * only the unfinished end.\n */\nexport function createHtmlSession(): {\n render(input: string, options?: HtmlSessionOptions): HtmlUpdate;\n} {\n let previous = '';\n let stable = '';\n let offset = 0;\n let definitions = false;\n let incomplete: boolean | undefined;\n let result: HtmlUpdate | undefined;\n let revision = 0;\n return {\n render(input, options) {\n if (typeof input !== 'string')\n throw new TypeError('session input must be a string');\n // A missing option and `false` are the same mode.\n const wanted = options?.incomplete === true;\n if (input === previous && incomplete === wanted && result != null)\n return result;\n // V8 compares slices with memcmp, but its startsWith reads each character.\n let reset =\n input.length < previous.length ||\n input.slice(0, previous.length) !== previous ||\n incomplete !== wanted ||\n definitions;\n if (offset !== 0 && input.charCodeAt(offset) === 0xfeff) reset = true;\n // A render can throw, so session state changes only after it succeeds.\n let nextStable = reset ? '' : stable;\n let nextOffset = reset ? 0 : offset;\n const renderOptions = {\n skipHtml: true,\n incomplete: wanted,\n boundary: true,\n };\n let tail = input.slice(nextOffset);\n let rendered = shared.render(tail, 0, renderOptions);\n if (nextOffset !== 0 && shared.dv.getUint8(30) !== 0) {\n nextStable = '';\n nextOffset = 0;\n reset = true;\n tail = input;\n rendered = shared.render(tail, 0, renderOptions);\n }\n const html = dec.decode(rendered.output);\n definitions = shared.dv.getUint8(30) !== 0;\n // Wasm measures the source and HTML before the boundary in UTF-16 units.\n const completed = definitions ? 0 : shared.dv.getUint32(36, true);\n let pending = html;\n let addition = '';\n if (completed > 0 && completed <= tail.length) {\n addition = html.slice(0, shared.dv.getUint32(40, true));\n nextStable += addition;\n nextOffset += completed;\n pending = html.slice(addition.length);\n }\n stable = nextStable;\n offset = nextOffset;\n previous = input;\n incomplete = wanted;\n const completedHtml = stable;\n let fullHtml: string | undefined;\n result = {\n // The DOM renderer reads only `addition` and `pending`, so build this on demand.\n get html() {\n return (fullHtml ??= completedHtml + pending);\n },\n stable: completedHtml,\n addition,\n pending,\n reset,\n revision: ++revision,\n };\n return result;\n },\n };\n}\n"],"mappings":";AAoBA,MAAM,MAAM,IAAI,YAAY;AAE5B,MAAM,MAAM,IAAI,YAAY,SAAS,EAAE,WAAW,KAAK,CAAC;AACxD,MAAM,WAAW;AAGjB,MAAM,WAAW,KAAK,KAAK,IAAI;AAE/B,IAAM,WAAN,MAAe;CACb;CACA;CACA;CACA;CACA;CAEA,YAAY,YAAgC;EAC1C,MAAM,WAAW,IAAI,YAAY,SAAS,YAAY,CAAC,CAAC;EACxD,KAAK,SAAS,SAAS,QAAQ;EAC/B,KAAK,aAAa,SAAS,QAAQ;EAGnC,SAAU,QAAQ,KACf,KAAK,OAAO,IAAI,KAAK,OAAQ,CAChC;EACA,KAAK,WAAW;CAClB;CAEA,OACE,OACA,MACA,SAC2C;EAC3C,IACE,OAAO,UAAU,YACjB,EAAE,iBAAiB,eACnB,EAAE,iBAAiB,cAEnB,MAAM,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