svelte-highlight 7.17.0 → 7.18.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/ansi-color.js ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Pure color math for AnsiOutput: SGR color to CSS, and WCAG contrast-based
3
+ * auto-foreground selection. Split out of the component (rather than left
4
+ * inline in its `<script>`) so it's directly testable and benchable without
5
+ * a DOM - .svelte files aren't type-checked by `tsgo`/covered by `bun test`.
6
+ */
7
+
8
+ /** @typedef {import("./ansi.d.ts").AnsiColor} AnsiColor */
9
+ /** @typedef {import("./ansi.d.ts").AnsiSegment} AnsiSegment */
10
+
11
+ export const FOREGROUND_FALLBACK = "#d4d4d4";
12
+ export const CONTRAST_TARGET = 4.5;
13
+ /** @type {[number, number, number]} */
14
+ const BLACK = [0, 0, 0];
15
+ /** @type {[number, number, number]} */
16
+ const WHITE = [255, 255, 255];
17
+
18
+ /**
19
+ * 16-color xterm defaults, each overridable via `--ansi-<name>`.
20
+ * @type {Record<string, string>}
21
+ */
22
+ export const ANSI_COLOR_DEFAULTS = {
23
+ black: "#000000",
24
+ red: "#cd0000",
25
+ green: "#00cd00",
26
+ yellow: "#cdcd00",
27
+ blue: "#0000ee",
28
+ magenta: "#cd00cd",
29
+ cyan: "#00cdcd",
30
+ white: "#e5e5e5",
31
+ "bright-black": "#7f7f7f",
32
+ "bright-red": "#ff0000",
33
+ "bright-green": "#00ff00",
34
+ "bright-yellow": "#ffff00",
35
+ "bright-blue": "#5c5cff",
36
+ "bright-magenta": "#ff00ff",
37
+ "bright-cyan": "#00ffff",
38
+ "bright-white": "#ffffff",
39
+ };
40
+
41
+ // 256-color cube steps (6x6x6).
42
+ const CUBE = [0, 95, 135, 175, 215, 255];
43
+
44
+ /**
45
+ * 256-color index to an RGB triple. Shared by `indexedHex` (stringifies it
46
+ * for CSS) and `colorToRgb` (used as-is) so the latter doesn't have to
47
+ * round-trip through a hex string just to parse the numbers back out.
48
+ * @param {number} index
49
+ * @returns {[number, number, number]}
50
+ */
51
+ function indexedRgb(index) {
52
+ if (index >= 232) {
53
+ const value = (index - 232) * 10 + 8;
54
+ return [value, value, value];
55
+ }
56
+ const n = index - 16;
57
+ // n is always in [0, 215] for index in [16, 231], so these three indices
58
+ // are always in CUBE's bounds ([0, 5]).
59
+ return [
60
+ /** @type {number} */ (CUBE[Math.floor(n / 36) % 6]),
61
+ /** @type {number} */ (CUBE[Math.floor(n / 6) % 6]),
62
+ /** @type {number} */ (CUBE[n % 6]),
63
+ ];
64
+ }
65
+
66
+ /**
67
+ * 256-color index to hex.
68
+ * @param {number} index
69
+ * @returns {string}
70
+ */
71
+ export function indexedHex(index) {
72
+ const [r, g, b] = indexedRgb(index);
73
+ return `#${[r, g, b].map((c) => c.toString(16).padStart(2, "0")).join("")}`;
74
+ }
75
+
76
+ /**
77
+ * Parsed color to CSS (named colors use `--ansi-*` vars).
78
+ * @param {AnsiColor} color
79
+ * @returns {string}
80
+ */
81
+ export function cssColor(color) {
82
+ if ("name" in color) {
83
+ return `var(--ansi-${color.name}, ${ANSI_COLOR_DEFAULTS[color.name]})`;
84
+ }
85
+ if ("rgb" in color) {
86
+ return `rgb(${color.rgb[0]}, ${color.rgb[1]}, ${color.rgb[2]})`;
87
+ }
88
+ return indexedHex(color.index);
89
+ }
90
+
91
+ /**
92
+ * @param {string} hex A `#rrggbb` string.
93
+ * @returns {[number, number, number]}
94
+ */
95
+ export function hexToRgb(hex) {
96
+ const value = hex.replace("#", "");
97
+ return [
98
+ Number.parseInt(value.slice(0, 2), 16),
99
+ Number.parseInt(value.slice(2, 4), 16),
100
+ Number.parseInt(value.slice(4, 6), 16),
101
+ ];
102
+ }
103
+
104
+ /**
105
+ * Named colors use the default palette (theme overrides aren't known here).
106
+ * @param {AnsiColor} color
107
+ * @returns {[number, number, number]}
108
+ */
109
+ export function colorToRgb(color) {
110
+ if ("name" in color) {
111
+ return hexToRgb(ANSI_COLOR_DEFAULTS[color.name] ?? "#000000");
112
+ }
113
+ if ("rgb" in color) return color.rgb;
114
+ return indexedRgb(color.index);
115
+ }
116
+
117
+ /**
118
+ * WCAG relative luminance.
119
+ * @param {[number, number, number]} rgb
120
+ * @returns {number}
121
+ */
122
+ export function luminance(rgb) {
123
+ const toLinear = (/** @type {number} */ c) => {
124
+ const v = c / 255;
125
+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
126
+ };
127
+ return (
128
+ 0.2126 * toLinear(rgb[0]) +
129
+ 0.7152 * toLinear(rgb[1]) +
130
+ 0.0722 * toLinear(rgb[2])
131
+ );
132
+ }
133
+
134
+ /**
135
+ * WCAG contrast ratio.
136
+ * @param {[number, number, number]} a
137
+ * @param {[number, number, number]} b
138
+ * @returns {number}
139
+ */
140
+ export function contrastRatio(a, b) {
141
+ const la = luminance(a);
142
+ const lb = luminance(b);
143
+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
144
+ }
145
+
146
+ /**
147
+ * Black or white, whichever contrasts more with `bg`.
148
+ * @param {[number, number, number]} bg
149
+ * @returns {string}
150
+ */
151
+ export function readableForeground(bg) {
152
+ return contrastRatio(BLACK, bg) >= contrastRatio(WHITE, bg)
153
+ ? "#000000"
154
+ : "#ffffff";
155
+ }
156
+
157
+ /**
158
+ * Foreground CSS, with auto-contrast override when needed.
159
+ * @param {AnsiSegment} segment
160
+ * @param {boolean} autoContrast
161
+ * @returns {string | undefined}
162
+ */
163
+ export function foregroundCss(segment, autoContrast) {
164
+ // Concealed text is rendered transparent (layout and copy text stay).
165
+ if (segment.conceal) return "transparent";
166
+ if (autoContrast && segment.bg) {
167
+ const bg = colorToRgb(segment.bg);
168
+ const fg = segment.fg
169
+ ? colorToRgb(segment.fg)
170
+ : hexToRgb(FOREGROUND_FALLBACK);
171
+ if (contrastRatio(fg, bg) < CONTRAST_TARGET) return readableForeground(bg);
172
+ }
173
+ return segment.fg ? cssColor(segment.fg) : undefined;
174
+ }
175
+
176
+ /**
177
+ * @param {AnsiSegment} segment
178
+ * @returns {string | undefined}
179
+ */
180
+ export function classNames(segment) {
181
+ const names = [];
182
+ if (segment.bold) names.push("bold");
183
+ if (segment.dim) names.push("dim");
184
+ if (segment.italic) names.push("italic");
185
+ if (segment.underline) names.push("underline");
186
+ if (segment.strikethrough) names.push("strikethrough");
187
+ return names.length ? names.join(" ") : undefined;
188
+ }
189
+
190
+ /**
191
+ * @param {AnsiSegment} segment
192
+ * @param {boolean} autoContrast
193
+ * @returns {string | undefined}
194
+ */
195
+ export function inlineStyle(segment, autoContrast) {
196
+ let style = "";
197
+ if (segment.bg) style += `background-color:${cssColor(segment.bg)};`;
198
+ const fg = foregroundCss(segment, autoContrast);
199
+ if (fg) style += `color:${fg};`;
200
+ return style || undefined;
201
+ }
@@ -133,9 +133,10 @@ export function createDomLinePainter({ registry }) {
133
133
  openScopes,
134
134
  pendingHtml,
135
135
  );
136
- if (result.completedLines.length > 0) {
137
- completedLines = completedLines.concat(result.completedLines);
138
- }
136
+ // push, not concat: concat copies the whole (ever-growing) array on
137
+ // every call, which is O(lines) per completed line - push is O(1)
138
+ // amortized (same reasoning as HighlightStream's sealed-chunk append).
139
+ for (const line of result.completedLines) completedLines.push(line);
139
140
  openScopes = result.openScopes;
140
141
  pendingHtml = result.pendingHtml;
141
142
  renderedEventCount = committed.length;
package/engine.js CHANGED
@@ -61,13 +61,13 @@
61
61
  * Memoized result of scanning a single rule/frame's pattern: `match` is the
62
62
  * earliest guard-passing match at or after the position `this.pos` had when
63
63
  * it was computed (or `null` if none exists in `this.code` as of `codeLen`
64
- * characters). See `Tokenizer#cachedMatch`.
64
+ * characters). See `Tokenizer#nextMatch`'s cache-hit checks.
65
65
  * @typedef {{ codeLen: number, match: RegExpExecArray | null }} MatchCache
66
66
  */
67
67
 
68
68
  /**
69
69
  * One entry of the tokenizer's parse stack. `endCache` memoizes this
70
- * frame's end-pattern scan (see `cachedMatch`); it's per-frame rather than
70
+ * frame's end-pattern scan (see `nextMatch`); it's per-frame rather than
71
71
  * per-state because `endSameAsBegin`'s guard depends on this frame's own
72
72
  * `beginMatch`, and two frames can share the same state (recursive nesting).
73
73
  * `beginPos` is this frame's begin match's position in `this.code` (see
@@ -124,14 +124,26 @@ export const TEXT = 0;
124
124
  export const OPEN = 1;
125
125
  export const CLOSE = 2;
126
126
 
127
- /** @param {string} value */
127
+ const HTML_ESCAPE_RE = /[&<>"']/g;
128
+ /** @type {Record<string, string>} */
129
+ const HTML_ESCAPE_MAP = {
130
+ "&": "&amp;",
131
+ "<": "&lt;",
132
+ ">": "&gt;",
133
+ '"': "&quot;",
134
+ "'": "&#x27;",
135
+ };
136
+
137
+ /**
138
+ * Five sequential `.replace()` passes (one per character) previously cost
139
+ * ~87% of renderHtml's time, since every TEXT event runs through this. A
140
+ * single regex pass, skipped entirely when there's nothing to escape, cuts
141
+ * that to a fraction (see bench/render.bench.ts).
142
+ * @param {string} value
143
+ */
128
144
  export function escapeHtml(value) {
129
- return value
130
- .replace(/&/g, "&amp;")
131
- .replace(/</g, "&lt;")
132
- .replace(/>/g, "&gt;")
133
- .replace(/"/g, "&quot;")
134
- .replace(/'/g, "&#x27;");
145
+ if (!HTML_ESCAPE_RE.test(value)) return value;
146
+ return value.replace(HTML_ESCAPE_RE, (char) => HTML_ESCAPE_MAP[char] ?? char);
135
147
  }
136
148
 
137
149
  /**
@@ -205,7 +217,7 @@ class Tokenizer {
205
217
  this.subContinuations = Object.create(null);
206
218
  /**
207
219
  * Memoized begin-pattern scans, indexed by state index (see
208
- * `cachedMatch`). A rule's "next match" is independent of which parent
220
+ * `nextMatch`). A rule's "next match" is independent of which parent
209
221
  * state referenced it, so this is shared across all of them rather than
210
222
  * being per-frame like `Frame#endCache`.
211
223
  * @type {(MatchCache | undefined)[]}
@@ -416,27 +428,17 @@ class Tokenizer {
416
428
  }
417
429
 
418
430
  /**
419
- * Memoized `execValid(re, this.pos, guardFn())`. Without this, every token
431
+ * Whether `cache` is still valid at `this.pos`: without this, every token
420
432
  * boundary re-scans every rule's pattern from scratch. A cached match stays
421
433
  * valid until `this.pos` passes it; a cached miss stays valid until the
422
- * code grows (streaming append). `guardFn` is only called on a cache miss,
423
- * so guarded rules don't allocate a fresh guard closure on every call once
424
- * their match is cached.
425
- * @param {RegExp} re
426
- * @param {() => ((m: RegExpExecArray) => boolean) | null} guardFn
434
+ * code grows (streaming append).
427
435
  * @param {MatchCache | undefined} cache
428
- * @returns {MatchCache}
436
+ * @returns {cache is MatchCache}
429
437
  */
430
- cachedMatch(re, guardFn, cache) {
431
- if (cache) {
432
- if (cache.match !== null && cache.match.index >= this.pos) return cache;
433
- if (cache.match === null && cache.codeLen === this.code.length)
434
- return cache;
435
- }
436
- return {
437
- codeLen: this.code.length,
438
- match: this.execValid(re, this.pos, guardFn()),
439
- };
438
+ isCacheValid(cache) {
439
+ if (!cache) return false;
440
+ if (cache.match !== null && cache.match.index >= this.pos) return true;
441
+ return cache.match === null && cache.codeLen === this.code.length;
440
442
  }
441
443
 
442
444
  /**
@@ -547,13 +549,23 @@ class Tokenizer {
547
549
  // rules[i] is in-bounds by the loop condition.
548
550
  const ruleIdx = /** @type {number} */ (state.rules[i]);
549
551
  const child = /** @type {CompiledState} */ (this.program.states[ruleIdx]);
550
- const cache = this.cachedMatch(
551
- // Every state referenced from a `rules` list has a `begin` pattern.
552
- /** @type {RegExp} */ (child.beginRe),
553
- () => this.beginGuard(child),
554
- this.beginCache[ruleIdx],
555
- );
556
- this.beginCache[ruleIdx] = cache;
552
+ let cache = this.beginCache[ruleIdx];
553
+ // Guard closures (this.beginGuard(child)) are only built on a cache
554
+ // miss - passing them in as a pre-built thunk, as this used to via a
555
+ // shared cachedMatch() helper, allocated one on every call regardless
556
+ // of hit/miss, since JS evaluates argument expressions eagerly.
557
+ if (!this.isCacheValid(cache)) {
558
+ cache = {
559
+ codeLen: this.code.length,
560
+ match: this.execValid(
561
+ // Every state referenced from a `rules` list has a `begin` pattern.
562
+ /** @type {RegExp} */ (child.beginRe),
563
+ this.pos,
564
+ this.beginGuard(child),
565
+ ),
566
+ };
567
+ this.beginCache[ruleIdx] = cache;
568
+ }
557
569
  consider(cache.match, i, "begin", ruleIdx);
558
570
  }
559
571
  // End candidates walk outward while `endsWithParent` chains allow.
@@ -562,15 +574,21 @@ class Tokenizer {
562
574
  // d ranges over [1, frames.length - 1], always in bounds.
563
575
  const frame = /** @type {Frame} */ (this.frames[d]);
564
576
  if (frame.state.endRe) {
565
- const cache = this.cachedMatch(
566
- frame.state.endRe,
567
- () =>
568
- frame.state.endSameAsBegin
569
- ? (/** @type {RegExpExecArray} */ m) => m[1] === frame.beginMatch
570
- : null,
571
- frame.endCache,
572
- );
573
- frame.endCache = cache;
577
+ let cache = frame.endCache;
578
+ if (!this.isCacheValid(cache)) {
579
+ cache = {
580
+ codeLen: this.code.length,
581
+ match: this.execValid(
582
+ /** @type {RegExp} */ (frame.state.endRe),
583
+ this.pos,
584
+ frame.state.endSameAsBegin
585
+ ? (/** @type {RegExpExecArray} */ m) =>
586
+ m[1] === frame.beginMatch
587
+ : null,
588
+ ),
589
+ };
590
+ frame.endCache = cache;
591
+ }
574
592
  consider(cache.match, pri++, "end", d);
575
593
  }
576
594
  if (!frame.state.endsWithParent) break;
package/index.d.ts CHANGED
@@ -25,3 +25,15 @@ export {
25
25
  } from "./scoped";
26
26
  export { default as Typewriter } from "./Typewriter.svelte";
27
27
  export type { ThemePalette } from "./theme";
28
+ export {
29
+ easeInCubic,
30
+ easeInOutCubic,
31
+ easeInOutQuad,
32
+ easeInOutSine,
33
+ easeInQuad,
34
+ easeInSine,
35
+ easeOutCubic,
36
+ easeOutQuad,
37
+ easeOutSine,
38
+ linear,
39
+ } from "./typewriter-easing";
package/index.js CHANGED
@@ -21,3 +21,15 @@ export {
21
21
  scopeStyle,
22
22
  } from "./scoped.js";
23
23
  export { default as Typewriter } from "./Typewriter.svelte";
24
+ export {
25
+ easeInCubic,
26
+ easeInOutCubic,
27
+ easeInOutQuad,
28
+ easeInOutSine,
29
+ easeInQuad,
30
+ easeInSine,
31
+ easeOutCubic,
32
+ easeOutQuad,
33
+ easeOutSine,
34
+ linear,
35
+ } from "./typewriter-easing.js";
package/package.json CHANGED
@@ -1,13 +1,10 @@
1
1
  {
2
2
  "name": "svelte-highlight",
3
- "version": "7.17.0",
3
+ "version": "7.18.1",
4
4
  "license": "MIT",
5
5
  "description": "Svelte component library for highlighting code using highlight.js",
6
6
  "author": "Eric Liu (https://github.com/metonym)",
7
7
  "type": "module",
8
- "dependencies": {
9
- "magic-string": "^0.30.17"
10
- },
11
8
  "repository": {
12
9
  "type": "git",
13
10
  "url": "git+https://github.com/metonym/svelte-highlight.git"
package/preprocessor.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import path from "node:path";
2
2
  import { pathToFileURL } from "node:url";
3
- import MagicString from "magic-string";
4
3
  import { parse } from "svelte/compiler";
5
4
  import { ensureRegistered, registry } from "./registry.js";
6
5
 
@@ -252,6 +251,151 @@ function renderStatic(language, code) {
252
251
  );
253
252
  }
254
253
 
254
+ const BASE64_VLQ_CHARS =
255
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
256
+
257
+ /** @param {number} value */
258
+ function encodeVlq(value) {
259
+ let vlq = value < 0 ? (-value << 1) + 1 : value << 1;
260
+ let result = "";
261
+ do {
262
+ let digit = vlq & 31;
263
+ vlq >>>= 5;
264
+ if (vlq > 0) digit |= 32;
265
+ result += BASE64_VLQ_CHARS[digit];
266
+ } while (vlq > 0);
267
+ return result;
268
+ }
269
+
270
+ /** @param {string} content */
271
+ function computeLineStarts(content) {
272
+ const starts = [0];
273
+ for (let i = 0; i < content.length; i += 1) {
274
+ if (content[i] === "\n") starts.push(i + 1);
275
+ }
276
+ return starts;
277
+ }
278
+
279
+ /**
280
+ * @param {number[]} lineStarts
281
+ * @param {number} index
282
+ */
283
+ function positionAt(lineStarts, index) {
284
+ let lo = 0;
285
+ let hi = lineStarts.length - 1;
286
+ while (lo < hi) {
287
+ const mid = (lo + hi + 1) >> 1;
288
+ if ((lineStarts[mid] ?? 0) <= index) lo = mid;
289
+ else hi = mid - 1;
290
+ }
291
+ return { line: lo, column: index - (lineStarts[lo] ?? 0) };
292
+ }
293
+
294
+ /**
295
+ * Splices non-overlapping replacements into `content` and produces a matching
296
+ * (source-map v3) sourcemap. Every edit here replaces a whole element with a
297
+ * self-contained HTML string, so there's nothing finer-grained to map inside
298
+ * a replacement - one segment per edit boundary is as accurate as mapping
299
+ * every character, and far cheaper to produce.
300
+ *
301
+ * @param {string} content
302
+ * @param {{ start: number; end: number; replacement: string }[]} edits sorted by `start`, non-overlapping
303
+ */
304
+ function applyEdits(content, edits) {
305
+ const lineStarts = computeLineStarts(content);
306
+ /** @type {string[]} */
307
+ const out = [];
308
+ /** @type {{ genCol: number; line: number; col: number }[][]} */
309
+ const segmentsByLine = [[]];
310
+
311
+ let genLine = 0;
312
+ let genCol = 0;
313
+
314
+ /**
315
+ * @param {number} line
316
+ * @param {number} col
317
+ */
318
+ function mark(line, col) {
319
+ segmentsByLine[genLine]?.push({ genCol, line, col });
320
+ }
321
+
322
+ /**
323
+ * Appends `text` to the output, advancing genLine/genCol across any
324
+ * newlines it contains. When `origLine` is given (unedited text only -
325
+ * a replacement's interior lines have no original counterpart), marks
326
+ * the start of each new line at column 0 against the next original line.
327
+ *
328
+ * @param {string} text
329
+ * @param {number} [origLine]
330
+ */
331
+ function advance(text, origLine) {
332
+ let from = 0;
333
+ let line = origLine ?? 0;
334
+ for (let i = 0; i < text.length; i += 1) {
335
+ if (text[i] !== "\n") continue;
336
+ out.push(text.slice(from, i + 1));
337
+ from = i + 1;
338
+ genLine += 1;
339
+ genCol = 0;
340
+ segmentsByLine.push([]);
341
+ if (origLine !== undefined) {
342
+ line += 1;
343
+ mark(line, 0);
344
+ }
345
+ }
346
+ out.push(text.slice(from));
347
+ genCol += text.length - from;
348
+ }
349
+
350
+ /**
351
+ * @param {number} start
352
+ * @param {number} end
353
+ */
354
+ function copyUnedited(start, end) {
355
+ if (start === end) return;
356
+ const pos = positionAt(lineStarts, start);
357
+ mark(pos.line, pos.column);
358
+ advance(content.slice(start, end), pos.line);
359
+ }
360
+
361
+ let cursor = 0;
362
+ for (const edit of edits) {
363
+ copyUnedited(cursor, edit.start);
364
+
365
+ const pos = positionAt(lineStarts, edit.start);
366
+ mark(pos.line, pos.column);
367
+ advance(edit.replacement);
368
+
369
+ cursor = edit.end;
370
+ }
371
+ copyUnedited(cursor, content.length);
372
+
373
+ let mappings = "";
374
+ let prevLine = 0;
375
+ let prevCol = 0;
376
+ for (const [lineIndex, segments] of segmentsByLine.entries()) {
377
+ if (lineIndex > 0) mappings += ";";
378
+ let prevGenCol = 0;
379
+ for (let i = 0; i < segments.length; i += 1) {
380
+ const segment = segments[i];
381
+ if (!segment) continue;
382
+ mappings += i === 0 ? "" : ",";
383
+ mappings += encodeVlq(segment.genCol - prevGenCol);
384
+ mappings += encodeVlq(0); // single source, index never changes
385
+ mappings += encodeVlq(segment.line - prevLine);
386
+ mappings += encodeVlq(segment.col - prevCol);
387
+ prevGenCol = segment.genCol;
388
+ prevLine = segment.line;
389
+ prevCol = segment.col;
390
+ }
391
+ }
392
+
393
+ return {
394
+ code: out.join(""),
395
+ map: { version: 3, sources: [""], names: [], mappings },
396
+ };
397
+ }
398
+
255
399
  /**
256
400
  * @typedef {{
257
401
  * onWarn?: (message: string, details: { filename?: string | undefined; line: number; cause: unknown }) => void;
@@ -348,27 +492,34 @@ export function highlightStatic(options = {}) {
348
492
  }),
349
493
  );
350
494
 
351
- const ms = new MagicString(content);
352
- let changed = false;
495
+ /** @type {{ start: number; end: number; replacement: string }[]} */
496
+ const edits = [];
353
497
 
354
498
  for (const [index, match] of matches.entries()) {
355
499
  const html = htmlByMatch[index];
356
500
  if (!html) continue;
357
501
 
358
- try {
359
- ms.overwrite(match.element.start, match.element.end, html);
360
- changed = true;
361
- } catch (cause) {
502
+ const { start, end } = match.element;
503
+ const previous = edits.at(-1);
504
+
505
+ // Matched elements can't nest (they require an empty slot) and
506
+ // collectElements visits them in source order, so this should
507
+ // never actually trigger - kept as a defensive fallback so one
508
+ // malformed range can't take down the whole preprocessor pass.
509
+ if (start >= end || (previous && start < previous.end)) {
362
510
  warn("failed to apply the static replacement", {
363
511
  filename,
364
- line: locate(content, match.element.start).line,
365
- cause,
512
+ line: locate(content, start).line,
513
+ cause: new Error("invalid or overlapping replacement range"),
366
514
  });
515
+ continue;
367
516
  }
517
+
518
+ edits.push({ start, end, replacement: html });
368
519
  }
369
520
 
370
- if (!changed) return;
371
- return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
521
+ if (edits.length === 0) return;
522
+ return applyEdits(content, edits);
372
523
  },
373
524
  };
374
525
  }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Sealed-chunk bookkeeping for HighlightStream's default (non-virtualized)
3
+ * engine: once `SEAL_CHUNK_LINES` completed lines accumulate, they're
4
+ * folded into one immutable HTML string and never touched again, so keyed
5
+ * `{#each sealedChunks}` reconciliation only ever diffs the (constant-size)
6
+ * unsealed tail, not the whole stream.
7
+ */
8
+
9
+ /**
10
+ * Joins `lines` (already-highlighted line HTML, one entry per line) into one
11
+ * `<span class="highlight-stream-line" data-line="i">` per line, separated
12
+ * by the newlines a real multi-line block needs.
13
+ * @param {string[]} lines
14
+ * @param {number} startLine Index of `lines[0]` in the overall document.
15
+ * @returns {string}
16
+ */
17
+ export function buildSealedChunkHtml(lines, startLine) {
18
+ if (lines.length === 0) return "";
19
+ // Only the very first line of the whole document (index 0) skips a
20
+ // leading separator; every other line - including this chunk's own first
21
+ // line, when it isn't the document's first - gets one. Peeling that one
22
+ // check out of the loop avoids re-evaluating it every iteration.
23
+ let html = `<span class="highlight-stream-line" data-line="${startLine}">${lines[0]}</span>`;
24
+ for (let i = 1; i < lines.length; i++) {
25
+ const lineIndex = startLine + i;
26
+ html += `\n<span class="highlight-stream-line" data-line="${lineIndex}">${lines[i]}</span>`;
27
+ }
28
+ return startLine > 0 ? `\n${html}` : html;
29
+ }
30
+
31
+ /**
32
+ * Appends `chunk` to `chunks` in place and returns the same array reference
33
+ * (Svelte's `x = x` self-assign invalidation idiom relies on referential
34
+ * equality staying stable so a keyed each-block doesn't rebuild). O(1)
35
+ * amortized, not O(c): a concat/spread-copy here would make sealing chunk
36
+ * `c` of a growing stream cost O(c), i.e. O(c^2) total across the stream.
37
+ * @param {string[]} chunks
38
+ * @param {string} chunk
39
+ * @returns {string[]}
40
+ */
41
+ export function pushSealedChunk(chunks, chunk) {
42
+ chunks.push(chunk);
43
+ return chunks;
44
+ }