@markup-carve/carve-wasm 0.1.3 → 0.1.5

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/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  WebAssembly build of the [Carve](https://markup-carve.github.io/carve/) markup
4
4
  renderer, compiled from
5
- [carve-rs](https://github.com/markup-carve/carve-rs). Lets the Rust
6
- implementation run client-side in the browser and backs the **Rust (WASM)**
7
- engine in the [Carve playground](https://markup-carve.github.io/carve/playground).
5
+ [carve-rs](https://github.com/markup-carve/carve-rs). It runs the Rust
6
+ implementation in browsers and powers the **Rust (WASM)** engine in the
7
+ [Carve playground](https://markup-carve.github.io/carve/playground).
8
8
 
9
9
  ## Install
10
10
 
@@ -12,316 +12,95 @@ engine in the [Carve playground](https://markup-carve.github.io/carve/playground
12
12
  npm install @markup-carve/carve-wasm
13
13
  ```
14
14
 
15
- > Publishing to npm is pending. Until the package is live you can build locally
16
- > (see [Build](#build) below) or consume the `pkg/` output directly.
15
+ > Publishing to npm is pending. Until the package is live, build it locally
16
+ > using the [build guide](docs/building.md) or consume the generated `pkg/`
17
+ > directory directly.
17
18
 
18
- ## Usage
19
+ ## Render Carve
19
20
 
20
- ### HTML migration
21
-
22
- `htmlToCarve(html, mode)` returns `{ value, report }`, using the same HTML5
23
- import policy and canonical writer as carve-rs. Modes are `safe` (default),
24
- `semantic`, and trusted-only `roundtrip`.
25
-
26
- ```js
27
- const { value, report } = htmlToCarve('<p>Hello <strong>world</strong></p>', 'safe')
28
- ```
29
-
30
- Portable migration code can use `fromHtml(html, mode)` and
31
- `fromMarkdown(markdown)`. Both return `{ value, report }`; Markdown carries an
32
- empty diagnostics list because the engine migrates the document whole.
33
-
34
- ### Core renderer
35
-
36
- Renders Carve markup to HTML with no extensions enabled.
37
-
38
- The published package is the **bundler** target (webpack, Vite, Rollup, ...):
39
- the wasm initializes automatically, so the exports are synchronous - no `init()`
40
- call.
41
-
42
- ```js
43
- import { toHtml } from '@markup-carve/carve-wasm'
44
-
45
- // The other core targets are toMarkdown, toPlainText, toAnsi, and toCarve.
46
-
47
- const html = toHtml('# Hello, Carve!')
48
- document.body.innerHTML = html
49
- ```
50
-
51
- ### Source-preserving patches
52
-
53
- Tools can prepare canonical formatting as stale-safe UTF-8 byte edits:
54
-
55
- ```js
56
- const patch = toCarvePatch(source)
57
- const formatted = applySourcePatch(source, patch)
58
- ```
59
-
60
- `createSourcePatch(source, replacement, kind, code)` prepares the same wire
61
- shape for another complete replacement. Its ranges are UTF-8 byte offsets. The
62
- fingerprint and byte length catch accidental staleness; they are not a
63
- cryptographic signature. Treat a patch as trusted edit instructions.
64
-
65
- ### Extensions
66
-
67
- `extensions()` reports every extension this build accepts. The list comes from
68
- the engine, so it cannot fall behind what the engine has:
69
-
70
- ```js
71
- import { extensions, toHtmlWithOptions } from '@markup-carve/carve-wasm'
72
-
73
- extensions()
74
- // ['autolink', 'citations', 'code-callouts', 'code-group', ...]
75
-
76
- toHtmlWithOptions(src, { extensions: ['glossary', 'table-of-contents'] })
77
- ```
78
-
79
- Names are kebab-case; snake_case (`math_block`) is accepted too. An unknown name
80
- throws, because an ignored extension renders as missing behavior that looks
81
- like a Carve bug.
82
-
83
- ### Full renderer (preview set)
84
-
85
- `toHtmlFull` enables the preview set the playground uses: tab normalisation,
86
- `<details>` fences, Mermaid diagrams, wikilinks, autolink, list-table, math
87
- blocks, heading permalinks, citations, code callouts, external-link decoration,
88
- code groups, and tabs.
89
-
90
- It is a curated subset rather than everything registered. Extensions that
91
- rewrite a document that never asked - `heading-numbers` numbers every heading,
92
- `table-of-contents` injects a TOC - are wrong for a preview. Name them
93
- explicitly through `toHtmlWithOptions` when you want them.
94
-
95
- ```js
96
- import { toHtmlFull } from '@markup-carve/carve-wasm'
97
-
98
- const html = toHtmlFull('# Hello\n\n``` mermaid\ngraph TD; A-->B\n```\n')
99
- document.body.innerHTML = html
100
- ```
101
-
102
- ### Symbols
103
-
104
- A `:name:` symbol renders its literal `:name:` source unless the name is in the
105
- **symbols map**. Pass one as a plain object (or a `Map`) to `toHtmlWithSymbols`,
106
- or as the optional second argument of `toHtmlFull`:
107
-
108
- ```js
109
- import { toHtmlWithSymbols } from '@markup-carve/carve-wasm'
110
-
111
- toHtmlWithSymbols('Ship it :rocket:', { rocket: '🚀' })
112
- // => '<p>Ship it 🚀</p>'
113
-
114
- toHtmlWithSymbols('Ship it :rocket: :shrug:', { rocket: '🚀' })
115
- // => '<p>Ship it 🚀 :shrug:</p>' (an unmapped name stays literal)
116
- ```
117
-
118
- The word-boundary guard is unaffected by an active map: `a:b:c`, `10:30:` and
119
- `me@example.com` never become symbols. Names and values must both be strings; a
120
- non-string value throws a `TypeError`.
121
-
122
- > **Security: symbol values are TRUSTED RAW output.**
123
- > A mapped value is inserted into the output **unescaped** - the same trust
124
- > class as a static `renderers` callback. `{ b: '<b>x</b>' }` emits a real
125
- > `<b>` element, not escaped text. This is deliberate (processor configuration
126
- > is trusted). **Never build a symbols map out of untrusted / user-supplied
127
- > input.**
128
-
129
- ### Section wrappers
130
-
131
- A top-level heading is wrapped, along with the content following it up to the
132
- next same-or-shallower heading, in a `<section>` carrying the heading's id (spec
133
- PART 9 §13). Only the id moves - `{#install .featured}` gives
134
- `<section id="install"><h2 class="featured">` - and a heading inside a
135
- blockquote, div or list item is not wrapped at all.
136
-
137
- `toHtmlWithOptions` is the general entry point, and `sections: false` renders
138
- headings flat with the id back on the `<h*>`:
21
+ The published package uses the bundler target for webpack, Vite, Rollup, and
22
+ similar tools. WASM initialization is automatic, so its exports are
23
+ synchronous.
139
24
 
140
25
  ```js
141
- import { toHtmlWithOptions } from '@markup-carve/carve-wasm'
142
-
143
- toHtmlWithOptions('# A\n\np\n', { sections: false })
144
- // '<h1 id="A">A</h1>\n<p>p</p>'
145
-
146
- toHtmlWithOptions(src, { sections: false, symbols: { rocket: '🚀' }, full: true })
26
+ import { toHtml, toHtmlFull, toHtmlWithOptions } from '@markup-carve/carve-wasm'
27
+
28
+ toHtml('# Hello, Carve!')
29
+ toHtmlFull('# Hello\n\n``` mermaid\ngraph TD; A-->B\n```\n')
30
+ toHtmlWithOptions(source, {
31
+ extensions: ['glossary', 'table-of-contents'],
32
+ rawHtml: false,
33
+ sections: true,
34
+ })
147
35
  ```
148
36
 
149
- Every field is optional. Omitting the object, or passing `null`, renders with
150
- defaults, so the three shorthands above remain the zero-config forms.
151
-
152
- | Field | Default | What it does |
153
- |---|---|---|
154
- | `sections` | `true` | Wrap each top-level heading and its content in a `<section>` |
155
- | `symbols` | none | `:name:` to value, TRUSTED-RAW (see above) |
156
- | `extensions` | none | Array of registry names; takes precedence over `full` |
157
- | `full` | `false` | Enable the preview extension set |
158
- | `rawHtml` | `true` | Emit an explicit passthrough as markup; `false` escapes it |
159
- | `profile` | none | `full` / `article` / `comment` / `minimal`; rejection throws |
160
- | `profileBaseHost` | none | The host the profile's link policy counts as internal |
161
- | `mode` | `interactive` | `static` renders the self-contained form: no client scripts |
162
- | `sourceLine` | `false` | Stamp top-level blocks with `data-source-line` |
163
- | `positions` | `false` | Keep source offsets on the nodes |
164
- | `labels` | none | Override engine-written strings, for a page not in English |
165
- | `smartTypography` | `glyph` | `source` keeps the author's run instead of the glyph |
166
- | `lowercaseHeadingIds` | `false` | Lowercase the generated heading ids |
167
- | `asciiHeadingIds` | `off` | `fold` transliterates, `strict` guarantees ASCII |
37
+ `toHtml` uses the core renderer. `toHtmlFull` enables the extension set used
38
+ by the playground preview. `toHtmlWithOptions` lets the caller choose
39
+ extensions and rendering policy. Unknown extension names throw instead of
40
+ silently producing incomplete output.
168
41
 
169
- An unrecognized key is ignored, because the object is configuration and a typo
170
- should not break a render. A recognized key with the wrong type throws a
171
- `TypeError` instead of being coerced: JS truthiness would read
172
- `{ sections: 'false' }` as `true`, the opposite of what was written.
42
+ Other core targets include `toMarkdown`, `toPlainText`, `toAnsi`, and
43
+ `toCarve`. Each has a `*WithOptions` form.
173
44
 
174
- This exists for a host whose CSS or JS assumes rendered blocks are direct
175
- children of the content container - the `.stack > * + *` spacing idiom,
176
- `:first-child`, `nth-child()` counting, `element.children` walks - all of which
177
- stop matching once a wrapper sits in between. It is the one output change that
178
- breaks a document whose *source* migrated cleanly.
45
+ ## Convert existing content
179
46
 
180
- Nothing else changes: ids, collision dedup, `</#id>` cross-references, implicit
181
- `[Heading][]` references and heading numbering all resolve against the slug
182
- rather than the element carrying it. The endnotes
183
- `<section role="doc-endnotes">` is a separate construct and is still emitted.
47
+ The package imports HTML, Markdown, Djot, and BBCode. `fromHtml`,
48
+ `fromMarkdown`, `migrateDjot`, and `migrateBbcode` return the converted value
49
+ with a fidelity report. The simpler `fromDjot` and `fromBbcode` helpers return
50
+ only the converted string.
184
51
 
185
- ### Rendering a document you did not write
186
-
187
- `rawHtml: false` renders an explicit passthrough - the `=html` raw block and the
188
- `` `…`{=html} `` inline raw span - as escaped text instead of markup. It is the
189
- switch carve-js spells `allowRawHtml`.
52
+ Markdown, Djot, and BBCode reports currently mark fidelity as unverified. An
53
+ empty diagnostic list does not claim that every construct was preserved.
190
54
 
191
55
  ```js
192
- toHtmlWithOptions(fromTheReader, { rawHtml: false })
193
- ```
56
+ import { fromHtml, fromMarkdown, htmlToAst, htmlToCarve } from '@markup-carve/carve-wasm'
194
57
 
195
- Reach for it whenever the document comes from somewhere other than the person
196
- running the page: a shared link, a comment field, a pasted file. A passthrough is
197
- the one construct that puts author-controlled markup on your origin, so leaving
198
- it on for a document a reader supplied is a way to run their script.
199
-
200
- The symbols map is unaffected and stays TRUSTED-RAW either way - it is
201
- configuration the host wrote, not content the document carries.
202
-
203
- ### Rendering with a profile
204
-
205
- `rawHtml: false` closes the passthrough vector. It does not cap input length,
206
- deny a construct, or constrain link schemes - that is what a profile is for, and
207
- the four presets match the ones the spec and the sibling bindings describe.
208
-
209
- ```js
210
- toHtmlWithOptions(fromTheReader, { profile: 'comment', rawHtml: false })
211
- ```
212
-
213
- **A rejected document throws.** The engine's infallible entry point turns a
214
- profile rejection - input past `max_length`, or a denied construct when the
215
- action is Error - into an EMPTY STRING, and a caller cannot tell that from a
216
- document that legitimately rendered to nothing. This binding renders through the
217
- fallible one, so a rejection arrives as an `Error` whose `name` is
218
- `ProfileViolationError` and whose `violations` array carries one message per
219
- refused construct.
220
-
221
- ```js
222
- try {
223
- html = toHtmlWithOptions(fromTheReader, { profile: 'comment' })
224
- } catch (error) {
225
- if (error.name === 'ProfileViolationError') report(error.violations)
226
- }
227
- ```
228
-
229
- ### Editing a tree, and reading one back
230
-
231
- `parseJson` serializes a document out. `astJsonToHtml` renders one back, and
232
- `astJsonToCarve` writes one back as source, so a host that reads the tree in
233
- order to change something can display and save the result without a server.
234
-
235
- ```js
236
- const tree = JSON.parse(parseJson(source))
237
- tree.children.unshift({ type: 'heading', level: 1, children: [{ type: 'text', value: 'Added' }] })
238
- const html = astJsonToHtml(JSON.stringify(tree), { full: true })
239
- const carve = astJsonToCarve(JSON.stringify(tree))
240
- ```
241
-
242
- A tree carrying something no Carve source can spell is refused by
243
- `astJsonToCarve` rather than written approximately, and an invalid tree throws
244
- from either.
245
-
246
- `lintCarve` returns the degradation diagnostics as
247
- `{ line, column, rule, message, start, end }`, with the rule ids carve-js and
248
- carve-php use for the same triggers. Offsets are BYTE offsets into the source,
249
- matching the engine.
250
-
251
- ### TypeScript
252
-
253
- The package ships `.d.ts` declarations. Types are inferred automatically when
254
- imported from `@markup-carve/carve-wasm`.
255
-
256
- ```ts
257
- import { toHtml, toHtmlFull, version } from '@markup-carve/carve-wasm'
258
-
259
- console.log(`carve-wasm v${version()}`)
260
- const html: string = toHtml('_Hello_')
261
- ```
262
-
263
- ## API
264
-
265
- | Export | Signature | Description |
266
- |--------|-----------|-------------|
267
- | `toHtml` | `(source: string) => string` | Core renderer, no extensions |
268
- | `toHtmlWithSymbols` | `(source: string, symbols?: object \| null) => string` | Core renderer + a `:name:` -> value symbols map (values are raw, see above) |
269
- | `toHtmlFull` | `(source: string, symbols?: object \| null) => string` | Core + common extensions (matches playground), optional symbols map |
270
- | `toHtmlWithOptions` | `(source: string, options?: object \| null) => string` | General form; see the options table above. Throws `ProfileViolationError` when a profile rejects the document |
271
- | `toHtmlWithReport` | `(source: string, strict?: boolean, maximum?: number) => RenderResult` | HTML plus bounded `raw-format-dropped` losses; strict mode throws `RenderLossError` |
272
- | `toMarkdownWithReport` | `(source: string, strict?: boolean, maximum?: number) => RenderResult` | Checked Markdown render |
273
- | `toPlainTextWithReport` | `(source: string, strict?: boolean, maximum?: number) => RenderResult` | Checked plain-text render |
274
- | `toAnsiWithReport` | `(source: string, strict?: boolean, maximum?: number) => RenderResult` | Checked ANSI render |
275
- | `toCarveWithReport` | `(source: string, strict?: boolean, maximum?: number) => RenderResult` | Checked canonical Carve render (lossless) |
276
- | `parseJson` | `(source: string) => string` | The parsed AST as JSON (PART 12 exchange shape) |
277
- | `astJsonToHtml` | `(json: string, options?: object \| null) => string` | Render an AST-JSON document; takes the same options object |
278
- | `astJsonToCarve` | `(json: string) => string` | Write an AST-JSON document back as canonical Carve source |
279
- | `lintCarve` | `(source: string) => LintWarning[]` | Degradation diagnostics, with the rule ids carve-js and carve-php share |
280
- | `readStamp` | `(source: string) => { version, generatedBy } \| null` | The document's provenance marker, if it carries one |
281
- | `needsReview` | `(source: string, currentVersion: string) => boolean` | Whether the stamp predates `currentVersion`; unstamped counts as yes |
282
- | `fromDjot` | `(source: string) => string` | Convert Djot source to Carve |
283
- | `fromBbcode` | `(source: string) => string` | Convert BBCode source to Carve; throws past the engine's size cap |
284
- | `createSourcePatch` | `(source, replacement, kind, code) => SourcePatch` | Build a minimal UTF-8 byte-range patch |
285
- | `toCarvePatch` | `(source: string) => SourcePatch` | Preview canonical formatting as a patch |
286
- | `applySourcePatch` | `(source: string, patch: SourcePatch) => string` | Validate and apply trusted patch instructions |
287
- | `version` | `() => string` | Returns the carve-wasm package version |
288
-
289
- ### The parsed AST
290
-
291
- `parseJson` returns the document as a JSON string - the [PART 12 exchange
292
- shape](https://markup-carve.github.io/carve/ast-json), the same tree every Carve
293
- engine publishes, so a consumer written against one implementation reads
294
- another's output.
295
-
296
- ```js
297
- import { parseJson } from '@markup-carve/carve-wasm'
58
+ const { value, report } = htmlToCarve('<p>Hello <strong>world</strong></p>', 'safe')
59
+ const { value: ast } = htmlToAst('<p>Hello <b>world</b></p>', 'safe')
298
60
 
299
- const ast = JSON.parse(parseJson('# Title\n\nBody[^a].\n\n[^a]: note\n'))
300
- ast.children.map((n) => n.type) // ['heading', 'paragraph', 'footnote']
301
- ast.children[0].pos // { startLine: 1, startColumn: 1, ... }
61
+ fromHtml(html, 'semantic')
62
+ fromMarkdown(markdown)
302
63
  ```
303
64
 
304
- The root carries exactly `type`, `children` and `srcByteLength`; frontmatter and
305
- footnote definitions are block nodes inside `children`, not root fields. Every
306
- node except the root carries `pos` when the engine could place it - 1-based
307
- lines and columns, 0-based offsets, ends exclusive, counted in Unicode
308
- **codepoints**, not bytes or UTF-16 units. A node the engine could not place,
309
- such as reassembled table-cell text, carries no `pos` at all rather than an
310
- invented one.
311
-
312
- A string rather than a JS object: the caller runs `JSON.parse`, which the
313
- browser does natively and faster than building the object graph across the wasm
314
- boundary one property at a time - and it keeps the bytes available for a caller
315
- that stores or forwards them.
65
+ HTML modes are `safe` (the default), `semantic`, and trusted-only
66
+ `roundtrip`. `htmlToAst` returns the serialized Carve AST without passing it
67
+ through the source writer, so its report can differ from `htmlToCarve` when a
68
+ construct is representable in the tree but not in Carve source.
69
+
70
+ ## Common host APIs
71
+
72
+ - `extensions()` returns the extension names supported by the bundled engine.
73
+ - `toCarvePatch()` and `applySourcePatch()` create and apply stale-safe UTF-8
74
+ byte edits.
75
+ - `toHtmlWithSymbols()` resolves configured `:name:` symbols. Symbol values
76
+ are trusted raw output and must not come from user input.
77
+ - `parseJson()`, `astJsonToHtml()`, and the other AST functions use the PART 12
78
+ AST JSON shared by Carve implementations.
79
+ - Include expansion calls a synchronous host resolver, records dependencies,
80
+ and enforces depth, byte, and call budgets. The resolver decides which paths
81
+ to refuse.
82
+ - Incremental parsing, tree patches, three-way merge, and ProseMirror helpers
83
+ support browser editors.
84
+
85
+ The [complete API and usage reference](docs/reference.md) documents these
86
+ APIs, renderer profiles, resource limits, includes, AST fields, and the
87
+ TypeScript declarations.
88
+
89
+ ## Security
90
+
91
+ Use `rawHtml: false` with a restrictive profile such as `comment` for
92
+ untrusted documents. Symbols and static renderer callbacks are trusted
93
+ configuration and may emit unescaped HTML. Treat source patches as trusted
94
+ edit instructions, not as signed data. A profile rejection throws.
95
+
96
+ Carve also enforces URL-scheme and attribute hardening in the renderer. See
97
+ the language [security documentation](https://markup-carve.github.io/carve/security)
98
+ for the complete model.
316
99
 
317
100
  ## Development
318
101
 
319
- The reference material a contributor needs lives in `docs/`, so this page can
320
- stay about USING the package:
102
+ Contributor documentation lives under `docs/`:
321
103
 
322
- - [Building](docs/building.md) - the wasm-pack targets, pointing the tests at a
323
- built package, and the rendering-only browser profile.
324
- - [The carve-rs pin](docs/engine-pin.md) - why the engine is pinned to an exact
325
- commit, and how to move it.
326
- - [Releasing](docs/releasing.md) - the gate, what it refuses, and the runbook
327
- for cutting a version.
104
+ - [Building and testing](docs/building.md)
105
+ - [The carve-rs engine pin](docs/engine-pin.md)
106
+ - [Release process](docs/releasing.md)