svelte-highlight 7.21.0 → 7.21.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.
Files changed (180) hide show
  1. package/HighlightStream.svelte +22 -0
  2. package/HighlightStream.svelte.d.ts +4 -1
  3. package/README.md +247 -5
  4. package/action.d.ts +16 -2
  5. package/action.js +92 -5
  6. package/engine.d.ts +29 -1
  7. package/engine.js +38 -3
  8. package/fence.d.ts +76 -4
  9. package/fence.js +274 -3
  10. package/languages/agda.js +1 -1
  11. package/languages/aliases.d.ts +7 -0
  12. package/languages/aliases.js +4 -0
  13. package/languages/all.js +3 -1
  14. package/languages/angular.js +1 -1
  15. package/languages/assemblyscript.js +1 -1
  16. package/languages/astro.js +1 -1
  17. package/languages/baml.js +1 -1
  18. package/languages/bend.js +1 -1
  19. package/languages/bibtex.js +1 -1
  20. package/languages/bicep.js +1 -1
  21. package/languages/bitbake.js +1 -1
  22. package/languages/blade.js +1 -1
  23. package/languages/blueprint.js +1 -1
  24. package/languages/bpftrace.js +1 -1
  25. package/languages/bqn.js +1 -1
  26. package/languages/c.js +1 -1
  27. package/languages/c3.js +1 -1
  28. package/languages/caddy.js +1 -1
  29. package/languages/cairo.js +1 -1
  30. package/languages/cedar.js +1 -1
  31. package/languages/cel.js +1 -1
  32. package/languages/cisco.js +1 -1
  33. package/languages/civet.js +1 -1
  34. package/languages/clarity.js +1 -1
  35. package/languages/codeql.js +1 -1
  36. package/languages/cql.js +1 -1
  37. package/languages/crontab.js +1 -1
  38. package/languages/csharp.js +1 -1
  39. package/languages/cue.js +1 -1
  40. package/languages/cypher.js +1 -1
  41. package/languages/d2.js +1 -1
  42. package/languages/dart.js +1 -1
  43. package/languages/datalog.js +1 -1
  44. package/languages/dax.js +1 -1
  45. package/languages/dhall.js +1 -1
  46. package/languages/djot.js +1 -1
  47. package/languages/dotenv.js +1 -1
  48. package/languages/dtrace.js +1 -1
  49. package/languages/earthfile.js +1 -1
  50. package/languages/ejs.js +1 -1
  51. package/languages/esql.js +1 -1
  52. package/languages/fennel.js +1 -1
  53. package/languages/fish.js +1 -1
  54. package/languages/flux.js +1 -1
  55. package/languages/gdscript.js +1 -1
  56. package/languages/gdshader.js +1 -1
  57. package/languages/gleam.js +1 -1
  58. package/languages/go.js +1 -1
  59. package/languages/groq.js +1 -1
  60. package/languages/haproxy.js +1 -1
  61. package/languages/hcl.js +1 -1
  62. package/languages/heex.js +3 -1
  63. package/languages/helm.js +1 -1
  64. package/languages/hlsl.js +1 -1
  65. package/languages/hocon.js +1 -1
  66. package/languages/hurl.js +1 -1
  67. package/languages/idris.js +1 -1
  68. package/languages/imba.js +1 -1
  69. package/languages/index.d.ts +4 -0
  70. package/languages/index.js +2 -0
  71. package/languages/ink.js +1 -1
  72. package/languages/java.js +1 -1
  73. package/languages/javascript.js +1 -1
  74. package/languages/jinja.js +1 -1
  75. package/languages/jmespath.js +1 -1
  76. package/languages/jq.js +1 -1
  77. package/languages/json5.js +1 -1
  78. package/languages/jsonata.js +1 -1
  79. package/languages/jsonnet.js +1 -1
  80. package/languages/just.js +1 -1
  81. package/languages/kcl.js +1 -1
  82. package/languages/kconfig.js +1 -1
  83. package/languages/kdl.js +1 -1
  84. package/languages/koka.js +1 -1
  85. package/languages/kotlin.js +1 -1
  86. package/languages/kql.js +1 -1
  87. package/languages/lean.js +1 -1
  88. package/languages/liquid.js +2 -1
  89. package/languages/logql.js +1 -1
  90. package/languages/lookml.js +1 -1
  91. package/languages/luau.js +1 -1
  92. package/languages/markdoc.js +1 -1
  93. package/languages/marko.js +1 -1
  94. package/languages/mdx.js +2 -1
  95. package/languages/mermaid.js +1 -1
  96. package/languages/modelfile.js +1 -1
  97. package/languages/mojo.js +1 -1
  98. package/languages/move.js +1 -1
  99. package/languages/nickel.js +1 -1
  100. package/languages/nushell.js +1 -1
  101. package/languages/odin.js +1 -1
  102. package/languages/org.js +1 -1
  103. package/languages/pkl.js +1 -1
  104. package/languages/plsql.js +1 -1
  105. package/languages/polar.js +1 -1
  106. package/languages/powerquery.js +1 -1
  107. package/languages/promql.js +1 -1
  108. package/languages/prql.js +1 -1
  109. package/languages/purescript.js +1 -1
  110. package/languages/python.js +1 -1
  111. package/languages/racket.js +1 -1
  112. package/languages/raku.js +1 -1
  113. package/languages/regex.js +1 -1
  114. package/languages/roc.js +1 -1
  115. package/languages/ron.js +1 -1
  116. package/languages/rust.js +1 -1
  117. package/languages/semver.d.ts +2 -0
  118. package/languages/semver.js +2 -0
  119. package/languages/shaderlab.js +1 -1
  120. package/languages/slint.js +1 -1
  121. package/languages/smithy.js +1 -1
  122. package/languages/snort.js +1 -1
  123. package/languages/solidity.js +1 -1
  124. package/languages/sparql.js +1 -1
  125. package/languages/splunk.js +1 -1
  126. package/languages/structurizr.js +1 -1
  127. package/languages/surrealql.js +1 -1
  128. package/languages/svelte.js +1 -1
  129. package/languages/swift.js +1 -1
  130. package/languages/systemd.js +1 -1
  131. package/languages/toml.js +1 -1
  132. package/languages/traceql.js +1 -1
  133. package/languages/tsq.js +1 -1
  134. package/languages/tsql.js +1 -1
  135. package/languages/typescript.js +1 -1
  136. package/languages/typespec.js +1 -1
  137. package/languages/url.d.ts +2 -0
  138. package/languages/url.js +2 -0
  139. package/languages/v.js +1 -1
  140. package/languages/vcl.js +1 -1
  141. package/languages/verse.js +1 -1
  142. package/languages/vrl.js +1 -1
  143. package/languages/vue.js +1 -1
  144. package/languages/vyper.js +1 -1
  145. package/languages/wgsl.js +1 -1
  146. package/languages/wit.js +1 -1
  147. package/languages/yara.js +1 -1
  148. package/languages/zig.js +1 -1
  149. package/package.json +30 -2
  150. package/search.css +16 -0
  151. package/search.d.ts +92 -0
  152. package/search.js +518 -0
  153. package/styles/blacklight-dark.css +1 -1
  154. package/styles/blacklight-dark.js +1 -1
  155. package/styles/cyanotype-light.css +1 -1
  156. package/styles/cyanotype-light.js +1 -1
  157. package/styles/dusk-dark.css +1 -1
  158. package/styles/dusk-dark.js +1 -1
  159. package/styles/peat-dark.css +1 -1
  160. package/styles/peat-dark.js +1 -1
  161. package/styles/thermal-dark.css +1 -1
  162. package/styles/thermal-dark.js +1 -1
  163. package/styles/wet-plate-dark.css +1 -1
  164. package/styles/wet-plate-dark.js +1 -1
  165. package/themes/blacklight-dark.css +1 -1
  166. package/themes/blacklight-dark.js +2 -2
  167. package/themes/cyanotype-light.css +1 -1
  168. package/themes/cyanotype-light.js +2 -2
  169. package/themes/dusk-dark.css +1 -1
  170. package/themes/dusk-dark.js +2 -2
  171. package/themes/peat-dark.css +1 -1
  172. package/themes/peat-dark.js +2 -2
  173. package/themes/thermal-dark.css +1 -1
  174. package/themes/thermal-dark.js +2 -2
  175. package/themes/wet-plate-dark.css +1 -1
  176. package/themes/wet-plate-dark.js +2 -2
  177. package/transformers.d.ts +44 -0
  178. package/transformers.js +154 -0
  179. package/worker.d.ts +45 -0
  180. package/worker.js +379 -0
@@ -379,6 +379,28 @@
379
379
  }
380
380
  }
381
381
 
382
+ /**
383
+ * Scroll a given line into the rendered window.
384
+ * @param {number} line
385
+ */
386
+ export function scrollToLine(line) {
387
+ if (!container) return;
388
+ if (virtualize) {
389
+ const target = Math.max(0, Math.min(line, vLineCount)) * vLineHeight;
390
+ const maxScrollTop = Math.max(
391
+ 0,
392
+ container.scrollHeight - container.clientHeight,
393
+ );
394
+ container.scrollTop = Math.max(0, Math.min(target, maxScrollTop));
395
+ vScrollTop = container.scrollTop;
396
+ computeVirtualWindow();
397
+ } else {
398
+ container
399
+ .querySelector(`[data-line="${line}"]`)
400
+ ?.scrollIntoView({ block: "nearest" });
401
+ }
402
+ }
403
+
382
404
  // Mirrors `scrollToBottom`/the shrink-clamp in `HighlightVirtual`, merged:
383
405
  // while streaming with `autoScroll`, stick to the (growing) bottom; once
384
406
  // the user scrolls away, just keep the scroll position in bounds.
@@ -132,4 +132,7 @@ export default class HighlightStream extends SvelteComponentTyped<
132
132
  HighlightStreamProps,
133
133
  HighlightStreamEvents,
134
134
  Record<string, never>
135
- > {}
135
+ > {
136
+ /** Scroll a given line into the rendered window. */
137
+ scrollToLine(line: number): void;
138
+ }
package/README.md CHANGED
@@ -115,7 +115,7 @@ This renders SSR-identical output — no `<svelte:head>`, no `<style>` tag, just
115
115
  **Dual light/dark via [`light-dark()`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/light-dark):**
116
116
 
117
117
  ```svelte
118
- <HighlightStyle light={atomOneLight} dark={atomOneDark} mode="auto">
118
+ <HighlightStyle light={cyanotypeLight} dark={cyanotypeDark} mode="auto">
119
119
  <Highlight language={typescript} {code} />
120
120
  </HighlightStyle>
121
121
  ```
@@ -292,7 +292,7 @@ bun scripts/import-textmate-theme.ts ./night-owl-color-theme.json ./night-owl.pa
292
292
 
293
293
  ## Styling
294
294
 
295
- Import styles from `svelte-highlight/styles`. See [SUPPORTED_STYLES.md](SUPPORTED_STYLES.md) for a list of supported styles. For new projects, prefer [Theming](#theming) above — this is the original, string-based theming path, kept fully supported for backward compatibility. Legacy styles are stable and will not be removed. One concrete reason to pick this path over `ThemePalette`: `base.css` assumes the default `hljs-` class prefix, so projects using a custom `classPrefix` should stay here.
295
+ Import styles from `svelte-highlight/styles`. See [SUPPORTED_STYLES.md](SUPPORTED_STYLES.md) for a list of supported styles. For new projects, prefer [Theming](#theming) above — this is the original, string-based theming path, kept fully supported for backward compatibility. Legacy styles are stable and will not be removed. One concrete reason to pick this path over `ThemePalette`: `base.css` assumes the default `hljs-` class prefix, so projects using a custom `classPrefix` should stay here. 45 of the styles (90 dark/light files) are original pairs authored by svelte-highlight rather than ported from highlight.js, marked as custom in the gallery and in `SUPPORTED_STYLES.md`.
296
296
 
297
297
  There are two ways to apply `highlight.js` styles.
298
298
 
@@ -1418,7 +1418,18 @@ const html = await highlightFence({
1418
1418
  });
1419
1419
  ```
1420
1420
 
1421
- `lang` must be the grammar's canonical file name (see "[Loading a language by name](#loading-a-language-by-name)"); it rejects with `LanguageLoadError` for an unrecognized one. `meta` is the Expressive Code/Shiki-style vocabulary standardized on by tools like Astro, Starlight, and rehype-pretty-code: a bare `{1,3-5}` or `mark={1,3-5}` marks lines, `ins={...}`/`del={...}` mark insertions/deletions, `title="..."` sets a title, and `showLineNumbers` is a bare flag. The output wraps each line in `<span class="line" data-line-state="mark|ins|del">` (only when a state applies) inside a `<pre class="hljs" data-language="...">`, so a `mark`/`ins`/`del`-aware stylesheet can target `[data-line-state]` the same way it would target Expressive Code or Shiki output.
1421
+ `lang` accepts either the grammar's canonical file name or a known alias (e.g. `"ts"`, `"sh"`) -- `highlightFence` resolves it internally via `resolveLanguageName`, and rejects with `LanguageLoadError` when neither resolves. `meta` is the Expressive Code/Shiki-style vocabulary standardized on by tools like Astro, Starlight, and rehype-pretty-code: a bare `{1,3-5}` or `mark={1,3-5}` marks lines, `ins={...}`/`del={...}` mark insertions/deletions, `title="..."` sets a title, and `showLineNumbers` is a bare flag. The output wraps each line in `<span class="line" data-line-state="mark|ins|del">` (only when a state applies) inside a `<pre class="hljs" data-language="...">`, so a `mark`/`ins`/`del`-aware stylesheet can target `[data-line-state]` the same way it would target Expressive Code or Shiki output.
1422
+
1423
+ Call `resolveLanguageName` directly when you need the canonical name ahead of `highlightFence` -- e.g. to pick a display label, or to call `loadLanguage`/`<Highlight>` yourself instead:
1424
+
1425
+ ```js
1426
+ import { resolveLanguageName } from "svelte-highlight/fence";
1427
+
1428
+ resolveLanguageName("ts"); // "typescript"
1429
+ resolveLanguageName("nope"); // undefined
1430
+ ```
1431
+
1432
+ It trims, lowercases, and reads only the first word, so passing a whole info string (`resolveLanguageName("ts title=\"app.ts\"")`) works too. The alias table it reads from is also importable directly, as `svelte-highlight/languages/aliases` (`LANGUAGE_ALIASES: Readonly<Record<string, string>>`), for consumers that want the raw alias -> canonical mapping without going through `resolveLanguageName`.
1422
1433
 
1423
1434
  **mdsvex.** Wire `highlightFence` into `highlight.highlighter`, whose signature is `(code, lang, meta) => string | Promise<string>`:
1424
1435
 
@@ -1489,6 +1500,8 @@ function rehypeHighlightFence() {
1489
1500
 
1490
1501
  Use the `highlight` action to highlight existing `<pre><code>` markup in place. This is useful for progressively enhancing server-rendered content (e.g. markdown) without swapping in a component.
1491
1502
 
1503
+ Place `use:highlight` on the `<code>` element inside a `<pre>`, matching the theme CSS's `.hljs code` selector -- elsewhere (directly on `<pre>`, or a non-`<pre><code>` element) it still highlights but may not be visually targeted by the active theme.
1504
+
1492
1505
  The action accepts the same `language` prop as the components. When `code` is omitted, the element's existing `textContent` is highlighted. Updating `code` re-highlights the element.
1493
1506
 
1494
1507
  ```svelte
@@ -1515,6 +1528,26 @@ Omit `code` to highlight the element's existing contents:
1515
1528
  ></pre>
1516
1529
  ```
1517
1530
 
1531
+ `language` is also optional: when omitted, the action reads a `language-xxx` class off its own node (the Prism/highlight.js Markdown convention) and resolves it via `loadLanguage`, so server-rendered Markdown output needs no per-block `language` prop. With no matching class, it warns in dev and dispatches `error`.
1532
+
1533
+ ```svelte
1534
+ <pre><code class="language-typescript" use:highlight>const add = (a, b) => a + b;</code></pre>
1535
+ ```
1536
+
1537
+ ### Dispatched Events
1538
+
1539
+ The action dispatches `highlighted` (`detail: { html, language }`) on success and `error` (`detail: { error }`) on failure, on the node it's placed on.
1540
+
1541
+ ```svelte
1542
+ <pre><code
1543
+ use:highlight={{ language: typescript, code }}
1544
+ on:highlighted={(e) => console.log(e.detail.html, e.detail.language)}
1545
+ on:error={(e) => console.error(e.detail.error)}
1546
+ ></code></pre>
1547
+ ```
1548
+
1549
+ `highlighted` is also a composition hook for a sibling `LineNumbers`: `on:highlighted={(e) => (highlighted = e.detail.html)}` feeding `<LineNumbers {highlighted} languageName={typescript.name} />`.
1550
+
1518
1551
  ## Code Window
1519
1552
 
1520
1553
  Wrap a code block in `CodeWindow` to frame it with window chrome. It's purely cosmetic; the default slot renders your content unchanged.
@@ -1771,7 +1804,49 @@ Per-chunk work is O(tail), not O(stream length so far): finished output is seale
1771
1804
  <HighlightStream language={typescript} {code} {done} virtualize style="height: 20em;" />
1772
1805
  ```
1773
1806
 
1774
- `virtualize` renders only the lines within the scrolled viewport (plus `overscan`), the same windowing `HighlightVirtual` does for static documents -- a stream that runs to tens of thousands of lines still costs a couple dozen DOM nodes. It swaps the sealed-chunk session for `TokenizedDocument` (see [Large documents](#large-documents) below), so output always reflects the streaming (non-canonicalized) parse, even once `done` -- unlike the default mode, which upgrades to a canonical final render. `on:highlight` isn't dispatched in this mode, since materializing the full HTML on every repaint would defeat the point of windowing; `on:done`, the caret, and `autoScroll` all keep working. `on:windowchange` fires with `{ start, end, lineCount }` whenever the rendered window moves, so you can show something like "lines *N*-*M* of *T*" without counting DOM nodes yourself. Row math assumes one line per fixed-height row, so `virtualize` can't wrap lines -- it always renders with `white-space: pre`, overriding any `white-space` you pass through `$$restProps`.
1807
+ `virtualize` renders only the lines within the scrolled viewport (plus `overscan`), the same windowing `HighlightVirtual` does for static documents -- a stream that runs to tens of thousands of lines still costs a couple dozen DOM nodes. It swaps the sealed-chunk session for `TokenizedDocument` (see [Large documents](#large-documents) below), so output always reflects the streaming (non-canonicalized) parse, even once `done` -- unlike the default mode, which upgrades to a canonical final render. `on:highlight` isn't dispatched in this mode, since materializing the full HTML on every repaint would defeat the point of windowing; `on:done`, the caret, and `autoScroll` all keep working. `on:windowchange` fires with `{ start, end, lineCount }` whenever the rendered window moves, so you can show something like "lines *N*-*M* of *T*" without counting DOM nodes yourself. Row math assumes one line per fixed-height row, so `virtualize` can't wrap lines -- it always renders with `white-space: pre`, overriding any `white-space` you pass through `$$restProps`. `bind:this`, then call `scrollToLine(line)` to scroll a given line into view -- works in both `virtualize` and default modes.
1808
+
1809
+ ### Streaming Markdown with multiple fences
1810
+
1811
+ `HighlightStream` highlights a single growing code buffer, but LLM chat output is Markdown: prose interleaved with several fenced code blocks, each in its own language. `svelte-highlight/fence`'s `createFenceSplitter` (see "[Rendering Markdown/MDX fences](#rendering-markdownmdx-fences)" above) turns that growing Markdown string into prose and fence segments, so you can drive one `HighlightStream` per fence as it streams in:
1812
+
1813
+ ```svelte
1814
+ <script>
1815
+ import { HighlightStream, loadLanguage } from "svelte-highlight";
1816
+ import { createFenceSplitter } from "svelte-highlight/fence";
1817
+ import github from "svelte-highlight/styles/github";
1818
+
1819
+ const splitter = createFenceSplitter();
1820
+ let segments = splitter.segments();
1821
+ let done = false;
1822
+
1823
+ // Wire this up to your streaming source (fetch, WebSocket, SSE, ...).
1824
+ async function stream() {
1825
+ for (const chunk of chunks) {
1826
+ splitter.append(chunk);
1827
+ segments = splitter.segments();
1828
+ await new Promise((r) => setTimeout(r, 30));
1829
+ }
1830
+ done = true;
1831
+ }
1832
+ </script>
1833
+
1834
+ <svelte:head>
1835
+ {@html github}
1836
+ </svelte:head>
1837
+
1838
+ {#each segments as segment (segment.id)}
1839
+ {#if segment.kind === "text"}
1840
+ <p style="white-space: pre-wrap">{segment.text}</p>
1841
+ {:else}
1842
+ {#await loadLanguage(segment.lang ?? "plaintext") then grammar}
1843
+ <HighlightStream language={grammar} code={segment.code} done={!segment.open} />
1844
+ {/await}
1845
+ {/if}
1846
+ {/each}
1847
+ ```
1848
+
1849
+ Every segment's `id` is stable across both `append` (growing the buffer) and a full `set` (a regenerated buffer, keyed by common prefix) for everything before the first change, so the keyed `{#each}` never re-mounts a fence's `HighlightStream` just because more text arrived elsewhere in the document -- only the segment that actually changed gets a new instance. A `MarkdownStream` component that wraps this pattern is a separate deliverable; `createFenceSplitter` is the headless primitive underneath it.
1775
1850
 
1776
1851
  ## Large documents
1777
1852
 
@@ -1857,6 +1932,59 @@ For documents in the low thousands to tens of thousands of lines (roughly 2,000-
1857
1932
 
1858
1933
  Each line is its own block-level `<div>`, not a row in a `<table>`/`<tr>` (the way `LineNumbers` renders) -- `content-visibility` doesn't apply to table-internal display types, so off-screen table rows never get the skip. Off-screen `<div>` lines do: the browser skips layout/paint/style for them, using `contain-intrinsic-size` as a placeholder size until they scroll near the viewport. Unlike `HighlightVirtual`, this is a progressive enhancement, not a hard requirement -- browsers without `content-visibility` support just render every line normally, and you get native text selection, find-in-page, and line wrapping for free (drop the `white-space: pre` on each line's `<div>` to allow it).
1859
1934
 
1935
+ ## Find in document
1936
+
1937
+ Browser Cmd+F can't see rows a virtualized view (`HighlightVirtual`, `HighlightStream`'s `virtualize` mode) hasn't mounted, and neither of them ships a search box -- `svelte-highlight/search` is a headless find-in-document engine plus a DOM-painting helper, so any consumer can build one. No `<input>` component is exported; that's application UI, not a library primitive.
1938
+
1939
+ `createSearch(source)` accepts a plain `string` (split on `"\n"`), a `string[]` of lines, or a `TokenizedDocument` (duck-typed -- only `lineCount`/`lineRange` are used, never checked via `instanceof`), such as the one backing a `HighlightStream` in `virtualize` mode. Against a `TokenizedDocument`, repeated `query()` calls with unchanged text/options only rescan lines appended since the last call, instead of rescanning the whole document every time:
1940
+
1941
+ ```svelte
1942
+ <script>
1943
+ import { HighlightVirtual } from "svelte-highlight";
1944
+ import typescript from "svelte-highlight/languages/typescript";
1945
+ import { createSearch, highlightMatches } from "svelte-highlight/search";
1946
+ import "svelte-highlight/search.css";
1947
+
1948
+ export let code;
1949
+ const search = createSearch(code);
1950
+
1951
+ /** @type {HighlightVirtual} */
1952
+ let ref;
1953
+ /** @type {HTMLElement} */
1954
+ let root;
1955
+ let dispose = () => {};
1956
+
1957
+ function repaint() {
1958
+ dispose();
1959
+ dispose = highlightMatches(root, search.matches(), {
1960
+ current: search.current()?.index,
1961
+ }).dispose;
1962
+ }
1963
+
1964
+ const unsubscribe = search.onChange(repaint);
1965
+
1966
+ function onInput(event) {
1967
+ search.query(event.currentTarget.value, { wholeWord: true });
1968
+ }
1969
+
1970
+ function next() {
1971
+ const match = search.next();
1972
+ if (match) ref.scrollToLine(match.line);
1973
+ }
1974
+ </script>
1975
+
1976
+ <input on:input={onInput} />
1977
+ <button on:click={next}>Next ({search.count()})</button>
1978
+
1979
+ <div bind:this={root}>
1980
+ <HighlightVirtual bind:this={ref} language={typescript} {code} on:windowchange={repaint} />
1981
+ </div>
1982
+ ```
1983
+
1984
+ `query(text, options)` runs a search; `options.caseSensitive` and `options.wholeWord` (wraps the pattern in `\b...\b`) both default to `false`. `options.regex` treats `text` as a regular expression source instead of literal text -- capped at 256 characters and compiled in a `try`/`catch`, so an over-long or invalid pattern yields zero matches and sets `error()` rather than throwing. Empty `text` clears matches without an error. `matches()` returns every `{ line, start, end }` match in document order (never spanning a line); `count()` is its length. `current()`/`next()`/`prev()` return the selected match plus its `index` into `matches()`, wrapping around the ends; all return `undefined` before any query or with zero matches. `setSource(source)` swaps the document and re-runs an already-active query as a full rescan. `onChange(callback)` fires after every mutating call and returns an unsubscribe function.
1985
+
1986
+ `highlightMatches(root, matches, { current, name })` paints `matches` into `root`, restricted to whatever rows are currently rendered there -- resolved per match's line via `[data-line]` (the row shape `HighlightVirtual`/`HighlightStream` render), then the `line`-th `.line` element (the shape `highlightFence`/fenced code renders), then the whole `<code>` split on `"\n"`; matches whose line resolves to nothing are skipped. It uses the CSS Custom Highlight API when available (two `Highlight`s: `name`, defaulting to `"shl-search"`, and `${name}-current` for the match at index `current`), or falls back to wrapping text in `<mark data-shl-search>` (plus `data-shl-search-current`) when it isn't. It paints once per call and returns `{ dispose() }` -- there's no diffing against a previous call, so a consumer disposes and re-runs it after the rendered window changes (`on:windowchange`) or the query changes (`onChange`), as in the example above. It's a no-op on the server. `import "svelte-highlight/search.css"` is optional and styles both highlight names via the `--search-match-background`/`--search-current-background` CSS variables; passing a custom `name` bypasses it, since the stylesheet only targets the default names.
1987
+
1860
1988
  ## Terminal Output
1861
1989
 
1862
1990
  Use `AnsiOutput` to render terminal output that still contains ANSI [SGR](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters) escape codes. Colors, bold, dim, italic, and underline become styled HTML, along with OSC 8 hyperlinks, carriage-return overwrites, and reverse/strikethrough. The parser is separate from highlight.js, so reach for it with build logs, CLI output, and test runners.
@@ -2063,10 +2191,26 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2063
2191
 
2064
2192
  `$$restProps` are forwarded to the top-level `button` element.
2065
2193
 
2194
+ #### CSS Variables
2195
+
2196
+ | Variable | Description | Default value |
2197
+ | :-------------------- | :----------------------------------- | :------------ |
2198
+ | --copy-top | Top offset of the button | `0.5em` |
2199
+ | --copy-right | Right offset of the button | `0.5em` |
2200
+ | --copy-size | Width and height of the button | `2em` |
2201
+ | --copy-padding | Inner padding of the button | `0.5em` |
2202
+ | --copy-background | Background color of the button | `inherit` |
2203
+ | --copy-color | Foreground color of the button | `inherit` |
2204
+ | --copy-border-radius | Border radius of the button | `4px` |
2205
+ | --copy-border | Border of the button | `none` |
2206
+ | --copy-z-index | Stacking order of the button | `2` |
2207
+
2066
2208
  #### Dispatched Events
2067
2209
 
2068
2210
  - **on:copy**: fired after a successful copy, with `{ code }` -- the `transform`-applied string, not the original `code` prop
2069
2211
  - **on:error**: fired if the copy behavior throws, with `{ error }`
2212
+ - **on:mouseenter**: forwarded `MouseEvent`, useful for prefetching an async copy on hover
2213
+ - **on:mouseleave**: forwarded `MouseEvent`
2070
2214
 
2071
2215
  ```svelte
2072
2216
  <CopyButton
@@ -2087,6 +2231,29 @@ The default slot exposes `{ scopeClass }`. `$$restProps` are forwarded to the to
2087
2231
 
2088
2232
  `$$restProps` are forwarded to the top-level `div` element.
2089
2233
 
2234
+ #### CSS Variables
2235
+
2236
+ | Variable | Description | Default value |
2237
+ | :-------------------- | :---------------------------------------- | :---------------------------------- |
2238
+ | --window-background | Background color of the window body | `#1e1e1e` |
2239
+ | --window-border | Border of the window | `1px solid rgba(255, 255, 255, 0.1)`|
2240
+ | --window-radius | Corner radius of the window | `0` |
2241
+ | --titlebar-gap | Gap between items in the title bar | `0.5em` |
2242
+ | --titlebar-padding | Padding of the title bar | `0.65em 1em` |
2243
+ | --titlebar-background | Background color of the title bar | `#2d2d2d` |
2244
+ | --titlebar-border | Bottom border of the title bar | `1px solid rgba(255, 255, 255, 0.1)`|
2245
+ | --titlebar-color | Text color of the title bar | `rgba(255, 255, 255, 0.6)` |
2246
+ | --titlebar-font-family| Font family of the title bar | `system-ui, -apple-system, sans-serif`|
2247
+ | --titlebar-font-size | Font size of the title bar | `0.8125em` |
2248
+ | --dot-gap | Gap between the macOS traffic-light dots | `0.5em` |
2249
+ | --dot-size | Diameter of the macOS traffic-light dots | `0.75em` |
2250
+ | --dot-close | Color of the "close" traffic-light dot | `#ff5f56` |
2251
+ | --dot-minimize | Color of the "minimize" traffic-light dot| `#ffbd2e` |
2252
+ | --dot-maximize | Color of the "maximize" traffic-light dot| `#27c93f` |
2253
+ | --prompt-font-family | Font family of the terminal prompt | `ui-monospace, monospace` |
2254
+ | --prompt-font-weight | Font weight of the terminal prompt | `700` |
2255
+ | --prompt-color | Color of the terminal prompt | `inherit` |
2256
+
2090
2257
  ### `AnsiOutput`
2091
2258
 
2092
2259
  #### Props
@@ -2236,6 +2403,10 @@ Use `bind:this`, then call `undo()`, `redo()`, `focus()`, `selectAll()`, `insert
2236
2403
 
2237
2404
  `$$restProps` are forwarded to the top-level `pre` element. `overscan` and `checkpointInterval` only apply when `virtualize` is set. `doneText` is announced by a visually-hidden live region once `done` becomes `true`; set it to `""` to disable the announcement.
2238
2405
 
2406
+ #### Methods
2407
+
2408
+ Use `bind:this`, then call `scrollToLine(line)` -- works in both `virtualize` and default modes.
2409
+
2239
2410
  #### Dispatched Events
2240
2411
 
2241
2412
  - **on:highlight**: fired after each highlight pass, with `{ highlighted }` -- not dispatched when `virtualize` is set
@@ -2331,10 +2502,30 @@ See [Large documents](#large-documents) above.
2331
2502
 
2332
2503
  The highlighting engine's output is a flat scope-event stream (`ScopeEvent[]`): a sequence of `TEXT`/`OPEN`/`CLOSE` events that `renderHtml`, `toRanges`, and `tokenLines` each render differently. Every `<Highlight>`-family component exposes this stream (as `events`, in the default slot and the `highlight` event detail — see [Component API](#component-api) above), and `svelte-highlight/engine` + `svelte-highlight/registry` expose it directly, so highlighting can be consumed headlessly: server routes, build pipelines, tests, or any non-component context. `svelte-highlight/engine` has zero Svelte dependency and works in any JS runtime.
2333
2504
 
2505
+ ### Zero-bundler usage from a CDN
2506
+
2507
+ `svelte-highlight/engine` has no `import` statements of its own, so it — and any generated language grammar — can be loaded straight from a CDN like [esm.sh](https://esm.sh), with no bundler, build step, or Svelte in the loop:
2508
+
2509
+ ```html
2510
+ <script type="module">
2511
+ import { createRegistry, registerAll, renderHtml } from "https://esm.sh/svelte-highlight/engine";
2512
+ import typescript from "https://esm.sh/svelte-highlight/languages/typescript";
2513
+
2514
+ const registry = createRegistry();
2515
+ registerAll(registry, typescript);
2516
+
2517
+ const { events } = registry.tokenize("const greeting: string = 'hi';", "typescript");
2518
+ document.querySelector("pre").innerHTML = renderHtml(events);
2519
+ </script>
2520
+ ```
2521
+
2522
+ See it as a complete page in [examples/cdn](examples/cdn).
2523
+
2334
2524
  ### Stability tiers
2335
2525
 
2336
- - **Stable, semver-governed:** `ScopeEvent`, `TEXT`/`OPEN`/`CLOSE`, `TokenRange`, `HighlightResult`, `LineToken`, `Renderer`, `renderHtml`, `toRanges`, `extendLines`, `tokenLines`, `escapeHtml`, `createHtmlRenderer`, `createRangeRenderer`, `createLineRenderer`, `Registry` and its methods, `createRegistry`, `registerAll`, `StreamSession`, `TokenizedDocument`, `createTokenizedDocument`. `Snapshot` is a serializable format that round-trips within one library version, but is **not** guaranteed stable across versions — a snapshot from an older release may be rejected on resume. The same caveat applies to `TokenizedDocument`: its method surface (`setCode`/`append`/`lineCount`/`lineRange`/`tokenizedThrough`/`checkpointCount`) is stable and semver-governed, but internally it resumes from `Snapshot`s the same way `StreamSession` does, so anything that tried to serialize and later resume a `TokenizedDocument`'s internal state directly would hit the same cross-version instability -- the public API doesn't expose that today.
2526
+ - **Stable, semver-governed:** `ScopeEvent`, `TEXT`/`OPEN`/`CLOSE`, `TokenRange`, `HighlightResult`, `LineToken`, `Renderer`, `renderHtml`, `toRanges`, `extendLines`, `tokenLines`, `escapeHtml`, `createHtmlRenderer`, `createRangeRenderer`, `createLineRenderer`, `Registry` and its methods, `createRegistry`, `registerAll`, `StreamSession`, `TokenizedDocument`, `createTokenizedDocument`, `TextSegment`, `FenceSegment`, `MarkdownSegment`, `FenceSplitter`, `createFenceSplitter`, `SearchMatch`, `SearchOptions`, `Search`, `createSearch`, `highlightMatches`, `UnknownLanguageError`, `TokenizerLoopError`. `Snapshot` is a serializable format that round-trips within one library version, but is **not** guaranteed stable across versions — a snapshot from an older release may be rejected on resume. The same caveat applies to `TokenizedDocument`: its method surface (`setCode`/`append`/`lineCount`/`lineRange`/`tokenizedThrough`/`checkpointCount`) is stable and semver-governed, but internally it resumes from `Snapshot`s the same way `StreamSession` does, so anything that tried to serialize and later resume a `TokenizedDocument`'s internal state directly would hit the same cross-version instability -- the public API doesn't expose that today.
2337
2527
  - **Generated data, versioned with the library:** `GrammarIR`/`GrammarState`. These come from the build pipeline and are consumed by `registerAll`; treat them as opaque payloads whose field-level structure may change in any minor release. Always load grammars from the same package version as the engine.
2528
+ - **Experimental, may change in a minor release:** `createWorkerHighlighter`, `serveHighlighter`, `PostMessageTarget`, `WorkerHighlighter`, `WorkerSession`, `ServeHighlighterOptions` (`svelte-highlight/worker`). The wire protocol between the two halves is not part of the public contract — only the documented function behavior is.
2338
2529
 
2339
2530
  ### Headless highlighting, isolated registry
2340
2531
 
@@ -2379,6 +2570,45 @@ const snapshot = session.snapshot(); // JSON-serializable checkpoint
2379
2570
  const { value } = session.finish();
2380
2571
  ```
2381
2572
 
2573
+ ### Highlighting in a Web Worker
2574
+
2575
+ `svelte-highlight/worker` is a headless pair — a worker-side handler and a main-thread client — for running the engine off the main thread. Both halves have zero Svelte dependency.
2576
+
2577
+ ```js
2578
+ // highlight.worker.js
2579
+ import { serveHighlighter } from "svelte-highlight/worker";
2580
+ serveHighlighter();
2581
+ ```
2582
+
2583
+ ```js
2584
+ import { createWorkerHighlighter } from "svelte-highlight/worker";
2585
+
2586
+ const highlighter = createWorkerHighlighter(
2587
+ typeof Worker !== "undefined"
2588
+ ? new Worker(new URL("./highlight.worker.js", import.meta.url), { type: "module" })
2589
+ : undefined,
2590
+ );
2591
+ ```
2592
+
2593
+ An omitted (or falsy) `worker` runs the identical API in-process against `svelte-highlight/registry`'s shared singleton instead — the SSR/tests fallback, and why the construction above is a single ternary: the same code works whether or not `Worker` exists in the current environment.
2594
+
2595
+ ```js
2596
+ const { value } = await highlighter.highlight(code, "typescript");
2597
+ const lines = await highlighter.tokenLines(code, "typescript");
2598
+ ```
2599
+
2600
+ Streaming works the same way as `registry.createSession`, just async:
2601
+
2602
+ ```js
2603
+ const session = highlighter.createSession("typescript");
2604
+ await session.append(chunk); // repeat as chunks arrive
2605
+ await session.replace(from, to, text); // patch an earlier range without restarting
2606
+ const snapshot = await session.snapshot(); // JSON-serializable checkpoint
2607
+ const { value } = await session.finish();
2608
+ ```
2609
+
2610
+ Grammars load lazily inside the worker, per language, the first time each is seen. `HighlightStream` can't yet consume a remote, worker-backed session — its incremental rendering assumes a same-thread `StreamSession` — so streaming highlight results back into a component still requires posting the resolved HTML/events yourself. `terminate()` tears down the underlying `Worker` (a no-op in local mode).
2611
+
2382
2612
  ### Reaching the stream from a component — no HTML re-parsing
2383
2613
 
2384
2614
  ```svelte
@@ -2414,6 +2644,17 @@ const myRenderer = {
2414
2644
  };
2415
2645
  ```
2416
2646
 
2647
+ ### Errors
2648
+
2649
+ - **`UnknownLanguageError`** (`{ language }`): thrown by `tokenize`, `highlight`, `tokenizeRanges`, and `createSession` when `language` isn't registered.
2650
+ - **`TokenizerLoopError`** (`{ grammarName, iterations }`): thrown once a parse exceeds 500,000 tokenizer iterations, guarding against a grammar bug that never advances position.
2651
+
2652
+ Both are exported from `svelte-highlight/engine` and are distinct from `LanguageLoadError` (exported from `svelte-highlight` and `svelte-highlight/load-language`), which fires from a grammar module's *dynamic import* failure, not a registry lookup.
2653
+
2654
+ ### `illegal` is enforced only during auto-detection
2655
+
2656
+ A grammar's `illegal` pattern only aborts `tokenizeAuto`/`highlightAuto`: a candidate whose text matches its own `illegal` pattern loses relevance scoring and is dropped from consideration. An explicit `tokenize`/`highlight`/`createSession` call never checks it, unlike hljs's own `ignoreIllegals: false` default, which throws on the same condition. This is deliberate: streamed or LLM-generated code is routinely "illegal" mid-stream — an unclosed string, a dangling `#` — and an explicit-language highlighter that could throw partway through a stream would be unusable for that case. For hljs-style strict validation, run `highlightAuto(code, [language])` instead.
2657
+
2417
2658
  ## [Supported Languages](SUPPORTED_LANGUAGES.md)
2418
2659
 
2419
2660
  ## [Supported Styles](SUPPORTED_STYLES.md)
@@ -2428,6 +2669,7 @@ By default, example set-ups use Svelte 5. The exception is `examples/vite@svelte
2428
2669
  - [examples/vite](examples/vite)
2429
2670
  - [examples/vite@svelte-4](examples/vite@svelte-4)
2430
2671
  - [examples/webpack](examples/webpack)
2672
+ - [examples/worker](examples/worker)
2431
2673
 
2432
2674
  ## [Changelog](CHANGELOG.md)
2433
2675
 
package/action.d.ts CHANGED
@@ -3,9 +3,13 @@ import type { LanguageType } from "./languages";
3
3
 
4
4
  export type HighlightActionParameters = {
5
5
  /**
6
- * Language used to highlight the element's contents.
6
+ * Language used to highlight the element's contents. When omitted, the
7
+ * action reads a `language-xxx` class off the node itself (the
8
+ * Prism/highlight.js Markdown convention) and resolves it via
9
+ * `loadLanguage`. No `language` prop and no matching class dispatches
10
+ * `error` and leaves the content untouched.
7
11
  */
8
- language: LanguageType<string>;
12
+ language?: LanguageType<string>;
9
13
 
10
14
  /**
11
15
  * Code to highlight. When omitted, the element's
@@ -16,5 +20,15 @@ export type HighlightActionParameters = {
16
20
 
17
21
  /**
18
22
  * Highlight element contents in place with highlight.js.
23
+ *
24
+ * Should be placed on the `<code>` element inside a `<pre>`, matching the
25
+ * theme CSS's `.hljs code` selector -- elsewhere (directly on `<pre>`, or a
26
+ * non-`<pre><code>` element) it still highlights but may not be visually
27
+ * targeted by the active theme.
28
+ *
29
+ * Dispatches two events on the node:
30
+ * - `highlighted`: `detail: { html: string; language: string }`, after a
31
+ * successful highlight.
32
+ * - `error`: `detail: { error: unknown }`, after a failed highlight.
19
33
  */
20
34
  export declare const highlight: Action<HTMLElement, HighlightActionParameters>;
package/action.js CHANGED
@@ -1,21 +1,46 @@
1
+ import { loadLanguage } from "./load-language.js";
1
2
  import { ensureRegistered, registry } from "./registry.js";
2
3
 
4
+ const LANGUAGE_CLASS = /(?:^|\s)language-([\w#+-]+)(?:\s|$)/;
5
+
3
6
  /**
4
7
  * Highlight an element in place with highlight.js.
5
8
  * Omits `code` to highlight existing `textContent`.
6
9
  *
10
+ * Omits `language` to resolve it from a `class="language-xxx"` token on the
11
+ * node itself (the Prism/highlight.js Markdown convention), loaded via
12
+ * `loadLanguage`. No matching class dispatches `error` and leaves the
13
+ * content untouched.
14
+ *
15
+ * Dispatches `highlighted` ({ html, language }) on the node after a
16
+ * successful highlight, and `error` ({ error }) after a failed one.
17
+ *
7
18
  * @param {HTMLElement} node
8
- * @param {{ language: import("./languages").LanguageType<string>; code?: string }} parameters
9
- * @returns {ReturnType<import("svelte/action").Action<HTMLElement, { language: import("./languages").LanguageType<string>; code?: string }>>}
19
+ * @param {{ language?: import("./languages").LanguageType<string>; code?: string }} [parameters]
20
+ * @returns {ReturnType<import("svelte/action").Action<HTMLElement, { language?: import("./languages").LanguageType<string>; code?: string }>>}
10
21
  */
11
- export function highlight(node, parameters) {
22
+ export function highlight(node, parameters = {}) {
12
23
  // Snapshot the pre-action source once: updates that omit `code` fall back
13
24
  // to this instead of `node.textContent`, which after the first highlight
14
25
  // pass holds the already-highlighted (and DOM-normalized) output.
15
26
  const originalText = node.textContent ?? "";
16
27
 
17
- /** @param {{ language: import("./languages").LanguageType<string>; code?: string }} params */
18
- function apply({ language, code }) {
28
+ // Guards a `loadLanguage` continuation from applying stale results if a
29
+ // newer `apply()` call (from `update` or a fresh `destroy`) has since
30
+ // superseded it.
31
+ let generation = 0;
32
+ let destroyed = false;
33
+
34
+ /**
35
+ * @param {import("./languages").LanguageType<string>} language
36
+ * @param {string | undefined} code
37
+ * @param {number} gen
38
+ */
39
+ function highlightWith(language, code, gen) {
40
+ if (destroyed || gen !== generation) {
41
+ return;
42
+ }
43
+
19
44
  const source = code ?? originalText;
20
45
  let value;
21
46
 
@@ -29,11 +54,72 @@ export function highlight(node, parameters) {
29
54
  error,
30
55
  );
31
56
  }
57
+ // Deferred: Svelte wraps `on:` listeners on this node in an effect
58
+ // that flushes after this action's own (synchronous) mount/update
59
+ // runs, so dispatching synchronously here would fire before a
60
+ // listener declared via `on:error` is attached.
61
+ queueMicrotask(() =>
62
+ node.dispatchEvent(new CustomEvent("error", { detail: { error } })),
63
+ );
32
64
  return;
33
65
  }
34
66
 
35
67
  node.innerHTML = value;
36
68
  node.classList.add("hljs");
69
+ // See the `error` dispatch above for why this is deferred.
70
+ queueMicrotask(() =>
71
+ node.dispatchEvent(
72
+ new CustomEvent("highlighted", {
73
+ detail: { html: value, language: language.name },
74
+ }),
75
+ ),
76
+ );
77
+ }
78
+
79
+ /** @param {{ language?: import("./languages").LanguageType<string>; code?: string }} params */
80
+ function apply({ language, code } = {}) {
81
+ generation += 1;
82
+ const gen = generation;
83
+
84
+ if (language) {
85
+ highlightWith(language, code, gen);
86
+ return;
87
+ }
88
+
89
+ const match = node.getAttribute("class")?.match(LANGUAGE_CLASS);
90
+
91
+ if (!match) {
92
+ const error = new Error(
93
+ 'no "language" parameter and no "language-xxx" class found',
94
+ );
95
+ if (import.meta.env?.DEV) {
96
+ console.warn(`[svelte-highlight] ${error.message}.`);
97
+ }
98
+ queueMicrotask(() =>
99
+ node.dispatchEvent(new CustomEvent("error", { detail: { error } })),
100
+ );
101
+ return;
102
+ }
103
+
104
+ const name = /** @type {string} */ (match[1]);
105
+
106
+ loadLanguage(/** @type {import("./languages").LanguageName} */ (name)).then(
107
+ (language) => highlightWith(language, code, gen),
108
+ (error) => {
109
+ if (destroyed || gen !== generation) {
110
+ return;
111
+ }
112
+ if (import.meta.env?.DEV) {
113
+ console.warn(
114
+ `[svelte-highlight] failed to load language "${name}" from class="language-${name}"; leaving content unchanged.`,
115
+ error,
116
+ );
117
+ }
118
+ queueMicrotask(() =>
119
+ node.dispatchEvent(new CustomEvent("error", { detail: { error } })),
120
+ );
121
+ },
122
+ );
37
123
  }
38
124
 
39
125
  apply(parameters);
@@ -41,6 +127,7 @@ export function highlight(node, parameters) {
41
127
  return {
42
128
  update: apply,
43
129
  destroy() {
130
+ destroyed = true;
44
131
  node.classList.remove("hljs");
45
132
  node.textContent = originalText;
46
133
  },
package/engine.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * `createHtmlRenderer`, `createRangeRenderer`, `createLineRenderer`,
8
8
  * `Registry` and all its methods, `createRegistry`, `registerAll`,
9
9
  * `StreamSession`, `Snapshot` (see its own doc comment for a narrower
10
- * guarantee).
10
+ * guarantee), `UnknownLanguageError`, `TokenizerLoopError`.
11
11
  * - **Generated data (structure versioned with the library):** `GrammarIR`,
12
12
  * `GrammarState` (see their doc comment).
13
13
  *
@@ -40,6 +40,12 @@ export interface GrammarState {
40
40
  returnBegin?: boolean;
41
41
  returnEnd?: boolean;
42
42
  subLanguage?: string | string[];
43
+ /**
44
+ * Only enforced during auto-detection (`tokenizeAuto`/`highlightAuto`);
45
+ * inert on an explicit-language `tokenize()`/`highlight()`/`createSession()`/
46
+ * `resume()` call, so mid-stream text that would trip `illegal` under hljs's
47
+ * `ignoreIllegals: false` default is never rejected once the language is named.
48
+ */
43
49
  illegal?: string;
44
50
  keywords?: Record<string, [string, number]>;
45
51
  keywordPattern?: string;
@@ -194,6 +200,28 @@ export interface CompiledProgram {
194
200
  ir: GrammarIR;
195
201
  }
196
202
 
203
+ /**
204
+ * Thrown by `tokenize`, `highlight`, `tokenizeRanges`, and `createSession`
205
+ * when `language` isn't registered. Distinct from `LanguageLoadError`
206
+ * (`svelte-highlight`/`svelte-highlight/load-language`), which fires from a
207
+ * grammar module's dynamic `import()` failure, not a registry lookup.
208
+ * `resume()` does not throw this - see its own doc comment.
209
+ */
210
+ export class UnknownLanguageError extends Error {
211
+ constructor(language: string);
212
+ language: string;
213
+ }
214
+
215
+ /**
216
+ * Thrown by the tokenizer once a parse exceeds 500,000 iterations,
217
+ * guarding against a grammar bug that never advances position.
218
+ */
219
+ export class TokenizerLoopError extends Error {
220
+ constructor(grammarName: string, iterations: number);
221
+ grammarName: string;
222
+ iterations: number;
223
+ }
224
+
197
225
  export interface Registry {
198
226
  register(ir: GrammarIR): unknown;
199
227
  get(name: string): CompiledProgram | undefined;