@createiq/htmldiff 1.0.5-beta.0 → 1.0.5-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1269 @@
1
+ /**
2
+ * Table-aware preprocessing for HtmlDiff.
3
+ *
4
+ * The word-level diff alone matches longest-common-subsequences across cell
5
+ * boundaries and produces structurally wrong output for table edits — it
6
+ * shuffles content between cells, introduces phantom `<td>`s, and provides
7
+ * no signal that an entire row or column was added/deleted. We pre-process
8
+ * the inputs to give Word-style results:
9
+ *
10
+ * • When dimensions match (same row count, same cell count per row), we
11
+ * diff cell content positionally so cross-cell shifts produce one
12
+ * independent del/ins per cell.
13
+ * • When dimensions don't match (added/deleted row, added/deleted column),
14
+ * we run a row-level LCS to identify structurally added/deleted rows,
15
+ * then within preserved rows a cell-level LCS to identify added/deleted
16
+ * columns. Structurally added rows/cells get `class='diffins'` on the
17
+ * `<tr>`/`<td>`; deleted ones get `class='diffdel'`. Preserved cells
18
+ * fall back to a content diff via the recursive HtmlDiff callback.
19
+ *
20
+ * Tables are spliced out into placeholders before the main diff runs and
21
+ * spliced back in after, so the surrounding (non-table) content is diffed
22
+ * by the normal word-level pipeline.
23
+ */
24
+
25
+ interface CellRange {
26
+ /** Start index of the cell's opening tag in the original html. */
27
+ cellStart: number
28
+ /** Index just past the cell's closing tag. */
29
+ cellEnd: number
30
+ /** Cell content range — the slice we feed into the cell-level diff. */
31
+ contentStart: number
32
+ contentEnd: number
33
+ }
34
+
35
+ interface RowRange {
36
+ rowStart: number
37
+ rowEnd: number
38
+ cells: CellRange[]
39
+ }
40
+
41
+ interface TableRange {
42
+ tableStart: number
43
+ tableEnd: number
44
+ rows: RowRange[]
45
+ }
46
+
47
+ export interface PreprocessResult {
48
+ modifiedOld: string
49
+ modifiedNew: string
50
+ /** Maps placeholder marker → already-diffed table HTML to splice back in. */
51
+ placeholderToDiff: Map<string, string>
52
+ }
53
+
54
+ // HTML comments survive WordSplitter as a single atomic token and are
55
+ // treated as equal on both sides, so they pass through the diff
56
+ // untouched and are easy to substitute back later. The nonce is generated
57
+ // per call so a previously-diffed document being re-diffed (or any input
58
+ // that legitimately contains an `<!--HTMLDIFF_TABLE_*-->` comment) can't
59
+ // collide with the placeholder we substitute. We additionally regenerate
60
+ // the nonce if it appears in either input.
61
+ const PLACEHOLDER_PREFIX_BASE = '<!--HTMLDIFF_TABLE_'
62
+ const PLACEHOLDER_SUFFIX = '-->'
63
+
64
+ /**
65
+ * Hard cap on table dimensions handled by the structural-aware path.
66
+ * The row-LCS is O(rows²), the per-row cell-LCS is O(cells²), and each
67
+ * comparison string-equals row content (potentially many KB). Without a
68
+ * cap, a several-thousand-row table can pin a CPU for seconds. Tables
69
+ * larger than this fall through to the word-level diff, which scales
70
+ * linearly. Tuned to comfortably cover real-world ISDA schedules
71
+ * (which routinely have 1000+ rows).
72
+ */
73
+ const MAX_TABLE_ROWS = 1500
74
+ const MAX_TABLE_CELLS_PER_ROW = 200
75
+
76
+ function makePlaceholderPrefix(oldHtml: string, newHtml: string): string {
77
+ // 4 random bytes → 8 hex chars → 16^8 ≈ 4.3 billion combinations. We
78
+ // also retry if the generated nonce happens to occur in either input.
79
+ // Using `Math.random` here is fine: we're not defending against a
80
+ // malicious adversary, just avoiding accidental collisions.
81
+ for (let attempt = 0; attempt < 8; attempt++) {
82
+ const nonce = Math.floor(Math.random() * 0xffffffff)
83
+ .toString(16)
84
+ .padStart(8, '0')
85
+ const prefix = `${PLACEHOLDER_PREFIX_BASE}${nonce}_`
86
+ if (!oldHtml.includes(prefix) && !newHtml.includes(prefix)) {
87
+ return prefix
88
+ }
89
+ }
90
+ // Astronomically unlikely. Falling back to a counter ensures progress
91
+ // rather than an infinite loop, and any remaining collision will simply
92
+ // surface as a malformed diff that the caller can detect.
93
+ return `${PLACEHOLDER_PREFIX_BASE}fallback_${Date.now()}_`
94
+ }
95
+
96
+ type DiffCellFn = (oldCellContent: string, newCellContent: string) => string
97
+
98
+ /**
99
+ * Diffs every paired-by-position table in the inputs and replaces each
100
+ * source table with a placeholder, returning the modified inputs plus the
101
+ * placeholder→diff mapping. Returns null when there are no tables to
102
+ * preprocess or the table counts don't line up.
103
+ */
104
+ export function preprocessTables(oldHtml: string, newHtml: string, diffCell: DiffCellFn): PreprocessResult | null {
105
+ const oldTables = findTopLevelTables(oldHtml)
106
+ const newTables = findTopLevelTables(newHtml)
107
+
108
+ if (oldTables.length === 0 && newTables.length === 0) return null
109
+ if (oldTables.length !== newTables.length) return null
110
+
111
+ // Bail out on pathologically large tables — see MAX_TABLE_ROWS comment.
112
+ for (let i = 0; i < oldTables.length; i++) {
113
+ if (exceedsSizeLimit(oldTables[i]) || exceedsSizeLimit(newTables[i])) return null
114
+ }
115
+
116
+ const pairs: Array<{ oldTable: TableRange; newTable: TableRange; diffed: string }> = []
117
+ for (let i = 0; i < oldTables.length; i++) {
118
+ pairs.push({
119
+ oldTable: oldTables[i],
120
+ newTable: newTables[i],
121
+ diffed: diffTable(oldHtml, newHtml, oldTables[i], newTables[i], diffCell),
122
+ })
123
+ }
124
+
125
+ // Splice from end → start so earlier offsets stay valid.
126
+ let modifiedOld = oldHtml
127
+ let modifiedNew = newHtml
128
+ const placeholderPrefix = makePlaceholderPrefix(oldHtml, newHtml)
129
+ const placeholderToDiff = new Map<string, string>()
130
+ for (let i = pairs.length - 1; i >= 0; i--) {
131
+ const placeholder = `${placeholderPrefix}${i}${PLACEHOLDER_SUFFIX}`
132
+ placeholderToDiff.set(placeholder, pairs[i].diffed)
133
+ modifiedOld = spliceString(modifiedOld, pairs[i].oldTable.tableStart, pairs[i].oldTable.tableEnd, placeholder)
134
+ modifiedNew = spliceString(modifiedNew, pairs[i].newTable.tableStart, pairs[i].newTable.tableEnd, placeholder)
135
+ }
136
+
137
+ return { modifiedOld, modifiedNew, placeholderToDiff }
138
+ }
139
+
140
+ export function restoreTablePlaceholders(diffOutput: string, placeholderToDiff: Map<string, string>): string {
141
+ let result = diffOutput
142
+ for (const [placeholder, html] of placeholderToDiff) {
143
+ result = result.split(placeholder).join(html)
144
+ }
145
+ return result
146
+ }
147
+
148
+ function spliceString(s: string, start: number, end: number, replacement: string): string {
149
+ return s.slice(0, start) + replacement + s.slice(end)
150
+ }
151
+
152
+ function exceedsSizeLimit(table: TableRange): boolean {
153
+ if (table.rows.length > MAX_TABLE_ROWS) return true
154
+ for (const row of table.rows) {
155
+ if (row.cells.length > MAX_TABLE_CELLS_PER_ROW) return true
156
+ }
157
+ return false
158
+ }
159
+
160
+ function diffTable(
161
+ oldHtml: string,
162
+ newHtml: string,
163
+ oldTable: TableRange,
164
+ newTable: TableRange,
165
+ diffCell: DiffCellFn
166
+ ): string {
167
+ if (sameDimensions(oldTable, newTable)) {
168
+ return diffPositionalTable(oldHtml, newHtml, oldTable, newTable, diffCell)
169
+ }
170
+ if (oldTable.rows.length === newTable.rows.length) {
171
+ // Same row count, different cell counts: column add/delete only.
172
+ // Aligning rows positionally avoids the LCS row-key mismatch that
173
+ // happens when rows have different cell counts.
174
+ return diffSameRowCountTable(oldHtml, newHtml, oldTable, newTable, diffCell)
175
+ }
176
+ return diffStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, diffCell)
177
+ }
178
+
179
+ function diffSameRowCountTable(
180
+ oldHtml: string,
181
+ newHtml: string,
182
+ oldTable: TableRange,
183
+ newTable: TableRange,
184
+ diffCell: DiffCellFn
185
+ ): string {
186
+ // Walk the new table verbatim (preserving `<thead>`/`<tbody>` wrappers,
187
+ // whitespace, etc.) and substitute each row's content with the diffed
188
+ // form. The cursor-based emission keeps everything between rows intact.
189
+ const out: string[] = []
190
+ let cursor = newTable.tableStart
191
+ let r = 0
192
+ while (r < newTable.rows.length) {
193
+ const merge = detectVerticalMerge(oldHtml, newHtml, oldTable, newTable, r)
194
+ if (merge) {
195
+ out.push(newHtml.slice(cursor, newTable.rows[r].rowStart))
196
+ out.push(merge.diff)
197
+ cursor = newTable.rows[r + merge.span - 1].rowEnd
198
+ r += merge.span
199
+ continue
200
+ }
201
+ const split = detectVerticalSplit(oldHtml, newHtml, oldTable, newTable, r)
202
+ if (split) {
203
+ out.push(newHtml.slice(cursor, newTable.rows[r].rowStart))
204
+ out.push(split.diff)
205
+ cursor = newTable.rows[r + split.span - 1].rowEnd
206
+ r += split.span
207
+ continue
208
+ }
209
+ const newRow = newTable.rows[r]
210
+ out.push(newHtml.slice(cursor, newRow.rowStart))
211
+ out.push(diffPreservedRow(oldHtml, newHtml, oldTable.rows[r], newRow, diffCell))
212
+ cursor = newRow.rowEnd
213
+ r++
214
+ }
215
+ out.push(newHtml.slice(cursor, newTable.tableEnd))
216
+ return out.join('')
217
+ }
218
+
219
+ /**
220
+ * Detects a vertical merge starting at row `r`: new row R has a single
221
+ * cell with rowspan=K (and any colspan ≥ 1), with rows R+1..R+K-1 empty
222
+ * in new. Old rows R..R+K-1 must have a logical column width equal to
223
+ * the new cell's colspan and contain no rowspan'd cells of their own.
224
+ * This handles both single-column merges (old rows are 1-cell, new cell
225
+ * rowspan=K) and rectangular merges (e.g. 2×2 merge into a single
226
+ * colspan=2 rowspan=2 cell). Output: emit the merged cell with
227
+ * `class='mod rowspan'` and the empty trailing rows unchanged.
228
+ */
229
+ function detectVerticalMerge(
230
+ oldHtml: string,
231
+ newHtml: string,
232
+ oldTable: TableRange,
233
+ newTable: TableRange,
234
+ r: number
235
+ ): { diff: string; span: number } | null {
236
+ const newRow = newTable.rows[r]
237
+ if (newRow.cells.length !== 1) return null
238
+ const cell = newRow.cells[0]
239
+ const span = getRowspan(newHtml, cell)
240
+ if (span <= 1) return null
241
+ if (r + span > newTable.rows.length) return null
242
+
243
+ const colspan = getColspan(newHtml, cell)
244
+
245
+ for (let k = 1; k < span; k++) {
246
+ if (newTable.rows[r + k].cells.length !== 0) return null
247
+ }
248
+ for (let k = 0; k < span; k++) {
249
+ const oldRow = oldTable.rows[r + k]
250
+ if (!oldRow) return null
251
+ // The absorbed region's logical width must match the merged cell's
252
+ // colspan; otherwise this isn't a clean rectangular merge and we let
253
+ // the caller fall through.
254
+ if (sumColspans(oldHtml, oldRow.cells) !== colspan) return null
255
+ for (const c of oldRow.cells) {
256
+ if (getRowspan(oldHtml, c) !== 1) return null
257
+ }
258
+ }
259
+
260
+ const out: string[] = []
261
+ out.push(rowHeaderSlice(newHtml, newRow))
262
+ out.push(emitSpanChangedCell(newHtml, cell, 'rowspan'))
263
+ out.push('</tr>')
264
+ for (let k = 1; k < span; k++) {
265
+ out.push(emitEmptyRow(newHtml, newTable.rows[r + k]))
266
+ }
267
+ return { diff: out.join(''), span }
268
+ }
269
+
270
+ /**
271
+ * Detects a vertical split starting at row `r`: old row R has a single
272
+ * cell with rowspan=K, old rows R+1..R+K-1 are empty. New rows R..R+K-1
273
+ * each have a single cell. Output: emit each new row with the new cell
274
+ * tagged `class='mod rowspan'`.
275
+ */
276
+ function detectVerticalSplit(
277
+ oldHtml: string,
278
+ newHtml: string,
279
+ oldTable: TableRange,
280
+ newTable: TableRange,
281
+ r: number
282
+ ): { diff: string; span: number } | null {
283
+ const oldRow = oldTable.rows[r]
284
+ if (oldRow.cells.length !== 1) return null
285
+ const oldCell = oldRow.cells[0]
286
+ const span = getRowspan(oldHtml, oldCell)
287
+ if (span <= 1) return null
288
+ if (r + span > oldTable.rows.length) return null
289
+
290
+ const colspan = getColspan(oldHtml, oldCell)
291
+
292
+ for (let k = 1; k < span; k++) {
293
+ if (oldTable.rows[r + k].cells.length !== 0) return null
294
+ }
295
+ for (let k = 0; k < span; k++) {
296
+ const newRow = newTable.rows[r + k]
297
+ if (!newRow) return null
298
+ // New rows must collectively cover the same logical width as the old
299
+ // merged cell's colspan, with no rowspan'd cells of their own.
300
+ if (sumColspans(newHtml, newRow.cells) !== colspan) return null
301
+ for (const c of newRow.cells) {
302
+ if (getRowspan(newHtml, c) !== 1) return null
303
+ }
304
+ }
305
+
306
+ const out: string[] = []
307
+ for (let k = 0; k < span; k++) {
308
+ const newRow = newTable.rows[r + k]
309
+ out.push(rowHeaderSlice(newHtml, newRow))
310
+ for (const c of newRow.cells) {
311
+ out.push(emitSpanChangedCell(newHtml, c, 'rowspan'))
312
+ }
313
+ out.push('</tr>')
314
+ }
315
+ return { diff: out.join(''), span }
316
+ }
317
+
318
+ function emitEmptyRow(html: string, row: RowRange): string {
319
+ // Re-emit the source row's `<tr ...></tr>` verbatim.
320
+ return html.slice(row.rowStart, row.rowEnd)
321
+ }
322
+
323
+ function sameDimensions(a: TableRange, b: TableRange): boolean {
324
+ if (a.rows.length !== b.rows.length) return false
325
+ for (let i = 0; i < a.rows.length; i++) {
326
+ if (a.rows[i].cells.length !== b.rows[i].cells.length) return false
327
+ }
328
+ return true
329
+ }
330
+
331
+ /**
332
+ * Same-dimension path: walk the new table verbatim and substitute each
333
+ * cell content range with the cell-level diff. The surrounding
334
+ * `<thead>`/`<tbody>`/whitespace passes through untouched.
335
+ */
336
+ function diffPositionalTable(
337
+ oldHtml: string,
338
+ newHtml: string,
339
+ oldTable: TableRange,
340
+ newTable: TableRange,
341
+ diffCell: DiffCellFn
342
+ ): string {
343
+ const out: string[] = []
344
+ let cursor = newTable.tableStart
345
+ for (let r = 0; r < newTable.rows.length; r++) {
346
+ const oldRow = oldTable.rows[r]
347
+ const newRow = newTable.rows[r]
348
+ for (let c = 0; c < newRow.cells.length; c++) {
349
+ const oldCell = oldRow.cells[c]
350
+ const newCell = newRow.cells[c]
351
+ out.push(newHtml.slice(cursor, newCell.contentStart))
352
+ out.push(
353
+ diffCell(
354
+ oldHtml.slice(oldCell.contentStart, oldCell.contentEnd),
355
+ newHtml.slice(newCell.contentStart, newCell.contentEnd)
356
+ )
357
+ )
358
+ cursor = newCell.contentEnd
359
+ }
360
+ }
361
+ out.push(newHtml.slice(cursor, newTable.tableEnd))
362
+ return out.join('')
363
+ }
364
+
365
+ /**
366
+ * Mismatched-dimensions path: row-level LCS to identify added/deleted rows,
367
+ * then per preserved row a cell-level LCS to identify added/deleted cells.
368
+ * Reconstructs the table from scratch — there's no "single new structure"
369
+ * to walk verbatim, since we're stitching together kept rows from both
370
+ * sides.
371
+ */
372
+ function diffStructurallyAlignedTable(
373
+ oldHtml: string,
374
+ newHtml: string,
375
+ oldTable: TableRange,
376
+ newTable: TableRange,
377
+ diffCell: DiffCellFn
378
+ ): string {
379
+ const oldKeys = oldTable.rows.map(row => rowKey(oldHtml, row))
380
+ const newKeys = newTable.rows.map(row => rowKey(newHtml, row))
381
+ const exactAlignment = lcsAlign(oldKeys, newKeys)
382
+ const alignment = pairSimilarUnmatchedRows(exactAlignment, oldTable, newTable, oldHtml, newHtml)
383
+
384
+ // Walk new's tableStart→tableEnd, substituting rows with their diffed
385
+ // form so `<thead>`/`<tbody>` wrappers and inter-row whitespace are
386
+ // preserved verbatim. Deleted rows (no position in new) are injected
387
+ // inline at their alignment position. If new has no rows at all, fall
388
+ // back to a from-scratch reconstruction so we still emit deleted rows.
389
+ if (newTable.rows.length === 0) {
390
+ return rebuildStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, alignment, diffCell)
391
+ }
392
+
393
+ // Emit the table header (`<table>` + any `<thead>`/`<tbody>` opening
394
+ // text up to the first row) up-front so a leading run of deleted-only
395
+ // alignments doesn't slip in before the table opens.
396
+ const out: string[] = []
397
+ out.push(newHtml.slice(newTable.tableStart, newTable.rows[0].rowStart))
398
+ let cursor = newTable.rows[0].rowStart
399
+ for (const align of alignment) {
400
+ if (align.newIdx !== null) {
401
+ const newRow = newTable.rows[align.newIdx]
402
+ out.push(newHtml.slice(cursor, newRow.rowStart))
403
+ if (align.oldIdx !== null) {
404
+ out.push(diffPreservedRow(oldHtml, newHtml, oldTable.rows[align.oldIdx], newRow, diffCell))
405
+ } else {
406
+ out.push(emitFullRow(newHtml, newRow, 'ins', diffCell))
407
+ }
408
+ cursor = newRow.rowEnd
409
+ } else if (align.oldIdx !== null) {
410
+ // Deleted row: inject inline at the current cursor (between the
411
+ // previously emitted row and the next one in new).
412
+ out.push(emitFullRow(oldHtml, oldTable.rows[align.oldIdx], 'del', diffCell))
413
+ }
414
+ }
415
+ out.push(newHtml.slice(cursor, newTable.tableEnd))
416
+ return out.join('')
417
+ }
418
+
419
+ function rebuildStructurallyAlignedTable(
420
+ oldHtml: string,
421
+ newHtml: string,
422
+ oldTable: TableRange,
423
+ newTable: TableRange,
424
+ alignment: Alignment[],
425
+ diffCell: DiffCellFn
426
+ ): string {
427
+ // Used when new has no rows but old does — we lose the per-row
428
+ // wrappers from new (there are none), so reconstruct from old's frame.
429
+ const out: string[] = []
430
+ out.push(headerSlice(newHtml, newTable, oldHtml, oldTable))
431
+ for (const align of alignment) {
432
+ if (align.oldIdx !== null) {
433
+ out.push(emitFullRow(oldHtml, oldTable.rows[align.oldIdx], 'del', diffCell))
434
+ } else if (align.newIdx !== null) {
435
+ out.push(emitFullRow(newHtml, newTable.rows[align.newIdx], 'ins', diffCell))
436
+ }
437
+ }
438
+ out.push('</table>')
439
+ return out.join('')
440
+ }
441
+
442
+ function headerSlice(newHtml: string, newTable: TableRange, oldHtml: string, oldTable: TableRange): string {
443
+ // Slice from <table> to the start of the first <tr>. Prefer new since
444
+ // attribute changes on <table> itself should follow new.
445
+ const newFirstRow = newTable.rows[0]?.rowStart ?? newTable.tableEnd - '</table>'.length
446
+ if (newFirstRow > newTable.tableStart) {
447
+ return newHtml.slice(newTable.tableStart, newFirstRow)
448
+ }
449
+ const oldFirstRow = oldTable.rows[0]?.rowStart ?? oldTable.tableEnd - '</table>'.length
450
+ return oldHtml.slice(oldTable.tableStart, oldFirstRow)
451
+ }
452
+
453
+ function rowKey(html: string, row: RowRange): string {
454
+ // Include cell tag text in the key so column-add doesn't accidentally
455
+ // match a row to one with different cell counts. Whitespace-normalize to
456
+ // tolerate formatting differences.
457
+ return html.slice(row.rowStart, row.rowEnd).replace(/\s+/g, ' ').trim()
458
+ }
459
+
460
+ function diffPreservedRow(
461
+ oldHtml: string,
462
+ newHtml: string,
463
+ oldRow: RowRange,
464
+ newRow: RowRange,
465
+ diffCell: DiffCellFn
466
+ ): string {
467
+ if (oldRow.cells.length === newRow.cells.length) {
468
+ return diffPositionalRow(oldHtml, newHtml, oldRow, newRow, diffCell)
469
+ }
470
+ // Cell counts differ. Try to interpret it as a horizontal merge/split via
471
+ // colspan first — preserving the new structure with `class='mod colspan'`
472
+ // on each affected cell. Falls back to the cell-LCS path if the cells
473
+ // don't align cleanly on logical column positions.
474
+ const colspanAligned = diffColspanChangedRow(oldHtml, newHtml, oldRow, newRow, diffCell)
475
+ if (colspanAligned !== null) return colspanAligned
476
+ return diffStructurallyAlignedRow(oldHtml, newHtml, oldRow, newRow, diffCell)
477
+ }
478
+
479
+ /**
480
+ * Try to align cells by logical column position (sum of colspans). When
481
+ * one side has a colspan'd cell that absorbs multiple cells on the other
482
+ * side, emit the new structure with `class='mod colspan'` on the
483
+ * merged/split cells. Returns null if the rows don't align cleanly —
484
+ * caller falls back to a generic cell-LCS.
485
+ */
486
+ function diffColspanChangedRow(
487
+ oldHtml: string,
488
+ newHtml: string,
489
+ oldRow: RowRange,
490
+ newRow: RowRange,
491
+ diffCell: DiffCellFn
492
+ ): string | null {
493
+ const oldWidth = sumColspans(oldHtml, oldRow.cells)
494
+ const newWidth = sumColspans(newHtml, newRow.cells)
495
+ if (oldWidth !== newWidth) return null
496
+
497
+ const out: string[] = []
498
+ out.push(rowHeaderSlice(newHtml, newRow))
499
+
500
+ let oi = 0
501
+ let ni = 0
502
+ while (oi < oldRow.cells.length && ni < newRow.cells.length) {
503
+ const oCell = oldRow.cells[oi]
504
+ const nCell = newRow.cells[ni]
505
+ const oSpan = getColspan(oldHtml, oCell)
506
+ const nSpan = getColspan(newHtml, nCell)
507
+
508
+ if (oSpan === nSpan) {
509
+ out.push(emitDiffedCell(oldHtml, newHtml, oCell, nCell, diffCell))
510
+ oi++
511
+ ni++
512
+ } else if (nSpan > oSpan) {
513
+ // New cell absorbs multiple old cells — horizontal merge.
514
+ let totalOldSpan = 0
515
+ let oj = oi
516
+ while (oj < oldRow.cells.length && totalOldSpan < nSpan) {
517
+ totalOldSpan += getColspan(oldHtml, oldRow.cells[oj])
518
+ oj++
519
+ }
520
+ if (totalOldSpan !== nSpan) return null
521
+ out.push(emitSpanChangedCell(newHtml, nCell, 'colspan'))
522
+ oi = oj
523
+ ni++
524
+ } else {
525
+ // One old cell becomes multiple new cells — horizontal split.
526
+ let totalNewSpan = 0
527
+ let nj = ni
528
+ while (nj < newRow.cells.length && totalNewSpan < oSpan) {
529
+ totalNewSpan += getColspan(newHtml, newRow.cells[nj])
530
+ nj++
531
+ }
532
+ if (totalNewSpan !== oSpan) return null
533
+ for (let k = ni; k < nj; k++) {
534
+ out.push(emitSpanChangedCell(newHtml, newRow.cells[k], 'colspan'))
535
+ }
536
+ oi++
537
+ ni = nj
538
+ }
539
+ }
540
+
541
+ // If we couldn't consume both sides cleanly, bail out.
542
+ if (oi !== oldRow.cells.length || ni !== newRow.cells.length) return null
543
+
544
+ out.push('</tr>')
545
+ return out.join('')
546
+ }
547
+
548
+ function sumColspans(html: string, cells: CellRange[]): number {
549
+ let total = 0
550
+ for (const cell of cells) total += getColspan(html, cell)
551
+ return total
552
+ }
553
+
554
+ function getColspan(html: string, cell: CellRange): number {
555
+ return parseSpanAttribute(html.slice(cell.cellStart, cell.contentStart), 'colspan')
556
+ }
557
+
558
+ function getRowspan(html: string, cell: CellRange): number {
559
+ return parseSpanAttribute(html.slice(cell.cellStart, cell.contentStart), 'rowspan')
560
+ }
561
+
562
+ function parseSpanAttribute(openingTag: string, name: 'colspan' | 'rowspan'): number {
563
+ const re = name === 'colspan' ? /\bcolspan\s*=\s*["']?(\d+)["']?/i : /\browspan\s*=\s*["']?(\d+)["']?/i
564
+ const m = re.exec(openingTag)
565
+ if (!m) return 1
566
+ const value = Number.parseInt(m[1], 10)
567
+ return Number.isFinite(value) && value > 0 ? value : 1
568
+ }
569
+
570
+ /**
571
+ * Emits a cell that's the merged/split product of a structural change,
572
+ * tagged with `class='mod colspan'` or `class='mod rowspan'`. Content is
573
+ * carried through unmodified — Word doesn't track these changes, and
574
+ * inserting del/ins around content that didn't really change would be
575
+ * misleading.
576
+ */
577
+ function emitSpanChangedCell(html: string, cell: CellRange, kind: 'colspan' | 'rowspan'): string {
578
+ const tdOpening = parseOpeningTagAt(html, cell.cellStart)
579
+ if (!tdOpening) return html.slice(cell.cellStart, cell.cellEnd)
580
+ const tdOpenTag = injectClass(html.slice(cell.cellStart, tdOpening.end), `mod ${kind}`)
581
+ return tdOpenTag + html.slice(cell.contentStart, cell.cellEnd)
582
+ }
583
+
584
+ function diffPositionalRow(
585
+ oldHtml: string,
586
+ newHtml: string,
587
+ oldRow: RowRange,
588
+ newRow: RowRange,
589
+ diffCell: DiffCellFn
590
+ ): string {
591
+ const out: string[] = []
592
+ // Use new's <tr> opening tag (preserves attributes from new).
593
+ const trHeader = rowHeaderSlice(newHtml, newRow)
594
+ out.push(trHeader)
595
+
596
+ let cursor = newRow.cells[0]?.cellStart ?? newRow.rowEnd
597
+ for (let c = 0; c < newRow.cells.length; c++) {
598
+ const oldCell = oldRow.cells[c]
599
+ const newCell = newRow.cells[c]
600
+ out.push(newHtml.slice(cursor, newCell.contentStart))
601
+ out.push(
602
+ diffCell(
603
+ oldHtml.slice(oldCell.contentStart, oldCell.contentEnd),
604
+ newHtml.slice(newCell.contentStart, newCell.contentEnd)
605
+ )
606
+ )
607
+ cursor = newCell.contentEnd
608
+ }
609
+ out.push(newHtml.slice(cursor, newRow.rowEnd))
610
+ return out.join('')
611
+ }
612
+
613
+ function diffStructurallyAlignedRow(
614
+ oldHtml: string,
615
+ newHtml: string,
616
+ oldRow: RowRange,
617
+ newRow: RowRange,
618
+ diffCell: DiffCellFn
619
+ ): string {
620
+ const oldKeys = oldRow.cells.map(cell => cellKey(oldHtml, cell))
621
+ const newKeys = newRow.cells.map(cell => cellKey(newHtml, cell))
622
+ const exactAlignment = lcsAlign(oldKeys, newKeys)
623
+ // After exact LCS, fuzzy-pair adjacent unmatched old/new cells whose
624
+ // content is similar enough — so a content-edit cell alongside a
625
+ // column-add in the same row produces a content diff for the edited
626
+ // cell rather than a phantom delete + insert + extra cell.
627
+ const alignment = pairSimilarUnmatchedCells(exactAlignment, oldRow, newRow, oldHtml, newHtml)
628
+
629
+ const out: string[] = []
630
+ // Use new's <tr> if it exists; otherwise old's.
631
+ out.push(rowHeaderSlice(newHtml, newRow))
632
+
633
+ for (const align of alignment) {
634
+ if (align.oldIdx !== null && align.newIdx !== null) {
635
+ const oldCell = oldRow.cells[align.oldIdx]
636
+ const newCell = newRow.cells[align.newIdx]
637
+ out.push(emitDiffedCell(oldHtml, newHtml, oldCell, newCell, diffCell))
638
+ } else if (align.newIdx !== null) {
639
+ out.push(emitFullCell(newHtml, newRow.cells[align.newIdx], 'ins', diffCell))
640
+ } else if (align.oldIdx !== null) {
641
+ out.push(emitFullCell(oldHtml, oldRow.cells[align.oldIdx], 'del', diffCell))
642
+ }
643
+ }
644
+
645
+ out.push('</tr>')
646
+ return out.join('')
647
+ }
648
+
649
+ function cellKey(html: string, cell: CellRange): string {
650
+ // Use cell content (not tag attributes) for matching, since column-add
651
+ // typically changes content but not tag attributes — and matching purely
652
+ // on attributes would mis-pair cells with the same content but different
653
+ // styling.
654
+ return html.slice(cell.contentStart, cell.contentEnd).replace(/\s+/g, ' ').trim()
655
+ }
656
+
657
+ /**
658
+ * Emits a row with all cells either inserted (kind='ins') or deleted
659
+ * (kind='del'). Adds `class='diffins'`/`'diffdel'` to the `<tr>` and to
660
+ * each `<td>`, with an `<ins>`/`<del>` wrapper around any cell content
661
+ * (empty cells get the class but no wrapper).
662
+ */
663
+ function emitFullRow(html: string, row: RowRange, kind: 'ins' | 'del', diffCell: DiffCellFn): string {
664
+ const cls = kind === 'ins' ? 'diffins' : 'diffdel'
665
+ const trOpening = parseOpeningTagAt(html, row.rowStart)
666
+ if (!trOpening) return html.slice(row.rowStart, row.rowEnd)
667
+ const trOpenTag = injectClass(html.slice(row.rowStart, trOpening.end), cls)
668
+
669
+ const out: string[] = [trOpenTag]
670
+ let cursor = trOpening.end
671
+ for (const cell of row.cells) {
672
+ out.push(html.slice(cursor, cell.cellStart))
673
+ out.push(emitFullCell(html, cell, kind, diffCell))
674
+ cursor = cell.cellEnd
675
+ }
676
+ out.push(html.slice(cursor, row.rowEnd))
677
+ return out.join('')
678
+ }
679
+
680
+ /**
681
+ * Emits a fully-inserted or fully-deleted cell. Inner text runs are wrapped
682
+ * with `<ins>`/`<del>` while formatting tags pass through unchanged, so
683
+ * `<strong>B</strong>` renders as `<strong><ins>B</ins></strong>` —
684
+ * matching htmldiff's general convention without the doubled-`<ins>` that
685
+ * the full recursive diff would produce for newly-inserted formatting.
686
+ * Empty cells get the class on the `<td>` but no inner wrapping.
687
+ */
688
+ function emitFullCell(html: string, cell: CellRange, kind: 'ins' | 'del', _diffCell: DiffCellFn): string {
689
+ const cls = kind === 'ins' ? 'diffins' : 'diffdel'
690
+ const tdOpening = parseOpeningTagAt(html, cell.cellStart)
691
+ if (!tdOpening) return html.slice(cell.cellStart, cell.cellEnd)
692
+ const tdOpenTag = injectClass(html.slice(cell.cellStart, tdOpening.end), cls)
693
+
694
+ const content = html.slice(cell.contentStart, cell.contentEnd)
695
+ const wrapped = content.trim().length === 0 ? content : wrapInlineTextRuns(content, kind)
696
+ const closing = html.slice(cell.contentEnd, cell.cellEnd)
697
+ return tdOpenTag + wrapped + closing
698
+ }
699
+
700
+ /**
701
+ * Wraps every non-whitespace text run in the given content with an
702
+ * `<ins>`/`<del>` tag, leaving HTML tags untouched. This produces output
703
+ * like `<strong><ins>X</ins></strong>` for fully-inserted formatted
704
+ * content — the same shape the rest of htmldiff emits for content
705
+ * insertions inside existing formatting.
706
+ */
707
+ function wrapInlineTextRuns(content: string, kind: 'ins' | 'del'): string {
708
+ const tag = kind === 'ins' ? 'ins' : 'del'
709
+ const cls = kind === 'ins' ? 'diffins' : 'diffdel'
710
+
711
+ const out: string[] = []
712
+ let i = 0
713
+ while (i < content.length) {
714
+ if (content[i] === '<') {
715
+ const tagEnd = parseOpeningTagAt(content, i)
716
+ if (!tagEnd) {
717
+ // Malformed — pass the rest through verbatim.
718
+ out.push(content.slice(i))
719
+ break
720
+ }
721
+ out.push(content.slice(i, tagEnd.end))
722
+ i = tagEnd.end
723
+ continue
724
+ }
725
+ let j = i
726
+ while (j < content.length && content[j] !== '<') j++
727
+ const text = content.slice(i, j)
728
+ if (text.trim().length > 0) {
729
+ out.push(`<${tag} class='${cls}'>${text}</${tag}>`)
730
+ } else {
731
+ out.push(text)
732
+ }
733
+ i = j
734
+ }
735
+ return out.join('')
736
+ }
737
+
738
+ function emitDiffedCell(
739
+ oldHtml: string,
740
+ newHtml: string,
741
+ oldCell: CellRange,
742
+ newCell: CellRange,
743
+ diffCell: DiffCellFn
744
+ ): string {
745
+ const tdOpening = parseOpeningTagAt(newHtml, newCell.cellStart)
746
+ if (!tdOpening) return newHtml.slice(newCell.cellStart, newCell.cellEnd)
747
+ const tdOpenTag = newHtml.slice(newCell.cellStart, tdOpening.end)
748
+ const content = diffCell(
749
+ oldHtml.slice(oldCell.contentStart, oldCell.contentEnd),
750
+ newHtml.slice(newCell.contentStart, newCell.contentEnd)
751
+ )
752
+ const closing = newHtml.slice(newCell.contentEnd, newCell.cellEnd)
753
+ return tdOpenTag + content + closing
754
+ }
755
+
756
+ function rowHeaderSlice(html: string, row: RowRange): string {
757
+ // Slice from <tr> to just before the first <td> opening tag. Preserves
758
+ // the <tr ...> attributes plus any inter-tag whitespace. For a row with
759
+ // no cells, we only want the `<tr ...>` opening — the caller appends the
760
+ // closing `</tr>` explicitly, so taking the whole `<tr></tr>` here would
761
+ // double the close.
762
+ const opening = parseOpeningTagAt(html, row.rowStart)
763
+ if (!opening) return ''
764
+ if (row.cells.length === 0) return html.slice(row.rowStart, opening.end)
765
+ return html.slice(row.rowStart, row.cells[0].cellStart)
766
+ }
767
+
768
+ interface Alignment {
769
+ oldIdx: number | null
770
+ newIdx: number | null
771
+ }
772
+
773
+ /** Character-level similarity threshold above which we treat two rows as "the same row, edited". */
774
+ const ROW_FUZZY_THRESHOLD = 0.5
775
+
776
+ /**
777
+ * Threshold for "this cell is a content-edit of that cell." Tuned the same
778
+ * as ROW_FUZZY_THRESHOLD; cells in legal docs that share most of their
779
+ * content typically ARE the same logical cell with a body edit, so 0.5
780
+ * works for both granularities in practice.
781
+ */
782
+ const CELL_FUZZY_THRESHOLD = 0.5
783
+
784
+ /**
785
+ * After exact LCS, scan the alignment for runs of "old deleted, then new
786
+ * inserted" (or vice versa) and pair entries whose content is similar
787
+ * enough to be treated as an edit rather than a delete+insert. This keeps
788
+ * row-level edits (a typo fix, a single word change) from being shown as
789
+ * an entire row vanishing and a new one appearing — matching what users
790
+ * expect from a typical track-changes view.
791
+ */
792
+ function pairSimilarUnmatchedRows(
793
+ alignment: Alignment[],
794
+ oldTable: TableRange,
795
+ newTable: TableRange,
796
+ oldHtml: string,
797
+ newHtml: string
798
+ ): Alignment[] {
799
+ return pairSimilarUnmatched(alignment, ROW_FUZZY_THRESHOLD, (oldIdx, newIdx) =>
800
+ rowSimilarity(oldTable.rows[oldIdx], newTable.rows[newIdx], oldHtml, newHtml)
801
+ )
802
+ }
803
+
804
+ function pairSimilarUnmatchedCells(
805
+ alignment: Alignment[],
806
+ oldRow: RowRange,
807
+ newRow: RowRange,
808
+ oldHtml: string,
809
+ newHtml: string
810
+ ): Alignment[] {
811
+ return pairSimilarUnmatched(alignment, CELL_FUZZY_THRESHOLD, (oldIdx, newIdx) =>
812
+ cellSimilarity(oldRow.cells[oldIdx], newRow.cells[newIdx], oldHtml, newHtml)
813
+ )
814
+ }
815
+
816
+ /**
817
+ * Identify pairings inside each unmatched-only run, then build the output
818
+ * alignment by walking the original and substituting paired entries at
819
+ * the *ins position* (not the del position). This keeps the result
820
+ * monotonic in newIdx — critical because the cursor-based emission
821
+ * downstream walks new's html in order. Emitting at the del position
822
+ * would be fine when del<ins in the alignment array (the typical case),
823
+ * but can violate monotonicity when there are mixed unpaired entries in
824
+ * between (column-add + row-add together, content-edit + column-add,
825
+ * etc.).
826
+ *
827
+ * Generic over what's being paired — works for both rows (by full row
828
+ * content similarity) and cells (by per-cell content similarity).
829
+ */
830
+ function pairSimilarUnmatched(
831
+ alignment: Alignment[],
832
+ threshold: number,
833
+ similarity: (oldIdx: number, newIdx: number) => number
834
+ ): Alignment[] {
835
+ const pairs = new Map<number, number>() // del-alignment-idx → ins-alignment-idx
836
+ let i = 0
837
+ while (i < alignment.length) {
838
+ if (alignment[i].oldIdx !== null && alignment[i].newIdx !== null) {
839
+ i++
840
+ continue
841
+ }
842
+ const runStart = i
843
+ while (i < alignment.length && (alignment[i].oldIdx === null) !== (alignment[i].newIdx === null)) i++
844
+ const runEnd = i
845
+
846
+ const delIndices: number[] = []
847
+ const insIndices: number[] = []
848
+ for (let k = runStart; k < runEnd; k++) {
849
+ if (alignment[k].oldIdx !== null) delIndices.push(k)
850
+ else insIndices.push(k)
851
+ }
852
+
853
+ const usedIns = new Set<number>()
854
+ for (const di of delIndices) {
855
+ let bestIi = -1
856
+ let bestSim = threshold
857
+ for (const ii of insIndices) {
858
+ if (usedIns.has(ii)) continue
859
+ const sim = similarity(alignment[di].oldIdx as number, alignment[ii].newIdx as number)
860
+ if (sim > bestSim) {
861
+ bestSim = sim
862
+ bestIi = ii
863
+ }
864
+ }
865
+ if (bestIi >= 0) {
866
+ pairs.set(di, bestIi)
867
+ usedIns.add(bestIi)
868
+ }
869
+ }
870
+ }
871
+
872
+ const insToDel = new Map<number, number>() // ins-alignment-idx → del-alignment-idx
873
+ for (const [delAi, insAi] of pairs) insToDel.set(insAi, delAi)
874
+ const pairedDels = new Set<number>(pairs.keys())
875
+
876
+ const result: Alignment[] = []
877
+ for (let k = 0; k < alignment.length; k++) {
878
+ if (pairedDels.has(k)) continue // paired del — emitted when we reach its ins
879
+ if (insToDel.has(k)) {
880
+ const delAi = insToDel.get(k) as number
881
+ result.push({ oldIdx: alignment[delAi].oldIdx, newIdx: alignment[k].newIdx })
882
+ } else {
883
+ result.push(alignment[k])
884
+ }
885
+ }
886
+ return result
887
+ }
888
+
889
+ /**
890
+ * Character-level similarity using shared prefix + suffix as a fraction
891
+ * of the longer string. Catches "single edit somewhere in a long row"
892
+ * (which token-Jaccard misses on short rows) while still correctly
893
+ * rejecting rows with no positional overlap. HTML tags are stripped to
894
+ * keep the comparison content-focused.
895
+ */
896
+ function rowSimilarity(oldRow: RowRange, newRow: RowRange, oldHtml: string, newHtml: string): number {
897
+ const a = rowText(oldHtml, oldRow)
898
+ const b = rowText(newHtml, newRow)
899
+ if (a === b) return 1
900
+ if (a.length === 0 || b.length === 0) return 0
901
+
902
+ let prefix = 0
903
+ const minLen = Math.min(a.length, b.length)
904
+ while (prefix < minLen && a[prefix] === b[prefix]) prefix++
905
+
906
+ let suffix = 0
907
+ while (
908
+ suffix < a.length - prefix &&
909
+ suffix < b.length - prefix &&
910
+ a[a.length - 1 - suffix] === b[b.length - 1 - suffix]
911
+ ) {
912
+ suffix++
913
+ }
914
+
915
+ return (prefix + suffix) / Math.max(a.length, b.length)
916
+ }
917
+
918
+ function rowText(html: string, row: RowRange): string {
919
+ const parts: string[] = []
920
+ for (const cell of row.cells) {
921
+ parts.push(html.slice(cell.contentStart, cell.contentEnd).replace(/<[^>]+>/g, ' '))
922
+ }
923
+ return parts.join(' ').replace(/\s+/g, ' ').trim().toLowerCase()
924
+ }
925
+
926
+ /**
927
+ * Character-level prefix+suffix similarity for a single cell's text
928
+ * content. Same metric as rowSimilarity, scoped to one cell so we can
929
+ * fuzzy-pair unmatched cells (e.g. a cell with a content edit alongside
930
+ * a column add in the same row).
931
+ */
932
+ function cellSimilarity(oldCell: CellRange, newCell: CellRange, oldHtml: string, newHtml: string): number {
933
+ const a = cellText(oldHtml, oldCell)
934
+ const b = cellText(newHtml, newCell)
935
+ if (a === b) return 1
936
+ if (a.length === 0 || b.length === 0) return 0
937
+
938
+ let prefix = 0
939
+ const minLen = Math.min(a.length, b.length)
940
+ while (prefix < minLen && a[prefix] === b[prefix]) prefix++
941
+
942
+ let suffix = 0
943
+ while (
944
+ suffix < a.length - prefix &&
945
+ suffix < b.length - prefix &&
946
+ a[a.length - 1 - suffix] === b[b.length - 1 - suffix]
947
+ ) {
948
+ suffix++
949
+ }
950
+
951
+ return (prefix + suffix) / Math.max(a.length, b.length)
952
+ }
953
+
954
+ function cellText(html: string, cell: CellRange): string {
955
+ return html
956
+ .slice(cell.contentStart, cell.contentEnd)
957
+ .replace(/<[^>]+>/g, ' ')
958
+ .replace(/\s+/g, ' ')
959
+ .trim()
960
+ .toLowerCase()
961
+ }
962
+
963
+ /**
964
+ * Standard LCS alignment: walks both sequences and emits a list of pairs
965
+ * where `(oldIdx, newIdx)` are both set for matching positions, and one
966
+ * side is null for an unmatched entry on the other side. Equality uses
967
+ * strict ===.
968
+ */
969
+ function lcsAlign(oldKeys: string[], newKeys: string[]): Alignment[] {
970
+ const m = oldKeys.length
971
+ const n = newKeys.length
972
+ const dp: number[][] = Array.from({ length: m + 1 }, () => new Array<number>(n + 1).fill(0))
973
+ for (let i = 1; i <= m; i++) {
974
+ for (let j = 1; j <= n; j++) {
975
+ if (oldKeys[i - 1] === newKeys[j - 1]) {
976
+ dp[i][j] = dp[i - 1][j - 1] + 1
977
+ } else {
978
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])
979
+ }
980
+ }
981
+ }
982
+
983
+ const result: Alignment[] = []
984
+ let i = m
985
+ let j = n
986
+ while (i > 0 || j > 0) {
987
+ if (i > 0 && j > 0 && oldKeys[i - 1] === newKeys[j - 1]) {
988
+ result.unshift({ oldIdx: i - 1, newIdx: j - 1 })
989
+ i--
990
+ j--
991
+ } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
992
+ result.unshift({ oldIdx: null, newIdx: j - 1 })
993
+ j--
994
+ } else {
995
+ result.unshift({ oldIdx: i - 1, newIdx: null })
996
+ i--
997
+ }
998
+ }
999
+ return result
1000
+ }
1001
+
1002
+ /**
1003
+ * Returns the opening tag string with the given class injected. Existing
1004
+ * `class` attributes are preserved and the new class appended.
1005
+ */
1006
+ /**
1007
+ * Returns the opening tag with the given class injected. Locates the real
1008
+ * `class` attribute via attribute-aware walking (NOT a flat regex — that
1009
+ * would mis-match inside a foreign attribute value like
1010
+ * `title="see class='x'"`). When the class already partially overlaps with
1011
+ * `cls` — e.g. existing `class="mod"` and we're injecting `mod colspan` —
1012
+ * only the missing tokens get appended, so we never end up with
1013
+ * `class="mod mod colspan"`.
1014
+ */
1015
+ function injectClass(openingTag: string, cls: string): string {
1016
+ const clsTokens = cls.split(/\s+/).filter(Boolean)
1017
+ if (clsTokens.length === 0) return openingTag
1018
+
1019
+ const classAttr = findClassAttribute(openingTag)
1020
+ if (classAttr) {
1021
+ const existingTokens = classAttr.value.split(/\s+/).filter(Boolean)
1022
+ const missing = clsTokens.filter(t => !existingTokens.includes(t))
1023
+ if (missing.length === 0) return openingTag
1024
+ const updatedValue =
1025
+ existingTokens.length === 0 ? missing.join(' ') : `${existingTokens.join(' ')} ${missing.join(' ')}`
1026
+ return openingTag.slice(0, classAttr.valueStart) + updatedValue + openingTag.slice(classAttr.valueEnd)
1027
+ }
1028
+
1029
+ const isSelfClosing = openingTag.endsWith('/>')
1030
+ const insertAt = isSelfClosing ? openingTag.length - 2 : openingTag.length - 1
1031
+ return `${openingTag.slice(0, insertAt).replace(/\s*$/, '')} class='${cls}'${openingTag.slice(insertAt)}`
1032
+ }
1033
+
1034
+ /**
1035
+ * Walks the opening tag's attributes (respecting quoted values) to find
1036
+ * the actual `class` attribute. Returns the value range (start/end of the
1037
+ * value content, *excluding* the surrounding quotes) and the value, or
1038
+ * null if no `class` attribute is present.
1039
+ */
1040
+ function findClassAttribute(openingTag: string): { valueStart: number; valueEnd: number; value: string } | null {
1041
+ // Skip past the tag name. Tag starts with `<`; first run of [A-Za-z0-9-]
1042
+ // is the tag name. Anything after is attribute territory.
1043
+ let i = 1
1044
+ while (i < openingTag.length && /[A-Za-z0-9_:-]/.test(openingTag[i])) i++
1045
+
1046
+ while (i < openingTag.length) {
1047
+ // Skip whitespace
1048
+ while (i < openingTag.length && /\s/.test(openingTag[i])) i++
1049
+ if (i >= openingTag.length) break
1050
+ if (openingTag[i] === '>' || openingTag[i] === '/') break
1051
+
1052
+ // Read attribute name
1053
+ const nameStart = i
1054
+ while (i < openingTag.length && !/[\s=>/]/.test(openingTag[i])) i++
1055
+ const name = openingTag.slice(nameStart, i)
1056
+
1057
+ // Optional whitespace + '=' + optional whitespace + value
1058
+ while (i < openingTag.length && /\s/.test(openingTag[i])) i++
1059
+ if (openingTag[i] !== '=') {
1060
+ // Bare attribute (no value) — not class
1061
+ continue
1062
+ }
1063
+ i++ // past '='
1064
+ while (i < openingTag.length && /\s/.test(openingTag[i])) i++
1065
+
1066
+ // Value: quoted or unquoted
1067
+ let valueStart: number
1068
+ let valueEnd: number
1069
+ if (openingTag[i] === '"' || openingTag[i] === "'") {
1070
+ const quote = openingTag[i]
1071
+ i++
1072
+ valueStart = i
1073
+ while (i < openingTag.length && openingTag[i] !== quote) i++
1074
+ valueEnd = i
1075
+ if (i < openingTag.length) i++ // past closing quote
1076
+ } else {
1077
+ valueStart = i
1078
+ while (i < openingTag.length && !/[\s>/]/.test(openingTag[i])) i++
1079
+ valueEnd = i
1080
+ }
1081
+
1082
+ if (name.toLowerCase() === 'class') {
1083
+ return { valueStart, valueEnd, value: openingTag.slice(valueStart, valueEnd) }
1084
+ }
1085
+ }
1086
+
1087
+ return null
1088
+ }
1089
+
1090
+ /**
1091
+ * Walks html and returns ranges for every top-level `<table>...</table>`
1092
+ * block. Nested tables aren't extracted as separate top-level entries —
1093
+ * they're captured inside the parent's content range and handled when the
1094
+ * cell-level diff recurses through them.
1095
+ */
1096
+ function findTopLevelTables(html: string): TableRange[] {
1097
+ const tables: TableRange[] = []
1098
+ let i = 0
1099
+ while (i < html.length) {
1100
+ if (matchesTagAt(html, i, 'table')) {
1101
+ const opening = parseOpeningTagAt(html, i)
1102
+ if (!opening) {
1103
+ i++
1104
+ continue
1105
+ }
1106
+ const tableContentStart = opening.end
1107
+ const tableEnd = findMatchingClosingTag(html, tableContentStart, 'table')
1108
+ if (tableEnd === -1) {
1109
+ i = opening.end
1110
+ continue
1111
+ }
1112
+ const closingTagStart = tableEnd - '</table>'.length
1113
+ const rows = findTopLevelRows(html, tableContentStart, closingTagStart)
1114
+ tables.push({ tableStart: i, tableEnd, rows })
1115
+ i = tableEnd
1116
+ } else {
1117
+ i++
1118
+ }
1119
+ }
1120
+ return tables
1121
+ }
1122
+
1123
+ function findTopLevelRows(html: string, start: number, end: number): RowRange[] {
1124
+ const rows: RowRange[] = []
1125
+ let i = start
1126
+ while (i < end) {
1127
+ if (matchesTagAt(html, i, 'tr')) {
1128
+ const opening = parseOpeningTagAt(html, i)
1129
+ if (!opening) {
1130
+ i++
1131
+ continue
1132
+ }
1133
+ const rowContentStart = opening.end
1134
+ const rowEnd = findMatchingClosingTag(html, rowContentStart, 'tr', end)
1135
+ if (rowEnd === -1) {
1136
+ i = opening.end
1137
+ continue
1138
+ }
1139
+ const closingTagStart = rowEnd - '</tr>'.length
1140
+ const cells = findTopLevelCells(html, rowContentStart, closingTagStart)
1141
+ rows.push({ rowStart: i, rowEnd, cells })
1142
+ i = rowEnd
1143
+ } else if (matchesClosingTagAt(html, i, 'table')) {
1144
+ // Defensive: bail out if we encounter a closing </table> while
1145
+ // scanning rows (we should have stopped at `end` already).
1146
+ break
1147
+ } else {
1148
+ i++
1149
+ }
1150
+ }
1151
+ return rows
1152
+ }
1153
+
1154
+ function findTopLevelCells(html: string, start: number, end: number): CellRange[] {
1155
+ const cells: CellRange[] = []
1156
+ let i = start
1157
+ while (i < end) {
1158
+ if (matchesTagAt(html, i, 'td') || matchesTagAt(html, i, 'th')) {
1159
+ const tagName = matchesTagAt(html, i, 'td') ? 'td' : 'th'
1160
+ const opening = parseOpeningTagAt(html, i)
1161
+ if (!opening) {
1162
+ i++
1163
+ continue
1164
+ }
1165
+ const contentStart = opening.end
1166
+ const cellEnd = findMatchingClosingTag(html, contentStart, tagName, end)
1167
+ if (cellEnd === -1) {
1168
+ i = opening.end
1169
+ continue
1170
+ }
1171
+ const contentEnd = cellEnd - `</${tagName}>`.length
1172
+ cells.push({ cellStart: i, cellEnd, contentStart, contentEnd })
1173
+ i = cellEnd
1174
+ } else if (matchesClosingTagAt(html, i, 'tr')) {
1175
+ break
1176
+ } else {
1177
+ i++
1178
+ }
1179
+ }
1180
+ return cells
1181
+ }
1182
+
1183
+ function matchesTagAt(html: string, i: number, tagName: string): boolean {
1184
+ if (html[i] !== '<') return false
1185
+ const candidate = html.slice(i + 1, i + 1 + tagName.length).toLowerCase()
1186
+ if (candidate !== tagName) return false
1187
+ const after = html[i + 1 + tagName.length]
1188
+ return after === '>' || after === ' ' || after === '\t' || after === '\n' || after === '\r' || after === '/'
1189
+ }
1190
+
1191
+ function matchesClosingTagAt(html: string, i: number, tagName: string): boolean {
1192
+ if (html[i] !== '<' || html[i + 1] !== '/') return false
1193
+ const candidate = html.slice(i + 2, i + 2 + tagName.length).toLowerCase()
1194
+ if (candidate !== tagName) return false
1195
+ const after = html[i + 2 + tagName.length]
1196
+ return after === '>' || after === ' ' || after === '\t' || after === '\n' || after === '\r'
1197
+ }
1198
+
1199
+ interface OpeningTag {
1200
+ /** Index just past the closing `>` of the opening tag. */
1201
+ end: number
1202
+ }
1203
+
1204
+ function parseOpeningTagAt(html: string, i: number): OpeningTag | null {
1205
+ // HTML comments, CDATA, processing instructions, and DOCTYPE need their
1206
+ // own terminators — a plain `>`-walker would cut a comment like
1207
+ // `<!-- a > b -->` at the first inner `>`, treating the rest as text
1208
+ // and corrupting downstream offsets. Word-exported HTML routinely
1209
+ // emits comments inside tables (conditional comments, OLE markers) so
1210
+ // these have to be handled, not just be theoretical.
1211
+ if (html.startsWith('<!--', i)) {
1212
+ const close = html.indexOf('-->', i + 4)
1213
+ return close === -1 ? null : { end: close + 3 }
1214
+ }
1215
+ if (html.startsWith('<![CDATA[', i)) {
1216
+ const close = html.indexOf(']]>', i + 9)
1217
+ return close === -1 ? null : { end: close + 3 }
1218
+ }
1219
+ if (html.startsWith('<?', i)) {
1220
+ const close = html.indexOf('?>', i + 2)
1221
+ return close === -1 ? null : { end: close + 2 }
1222
+ }
1223
+ // Walk to the next unquoted '>'. Handles attributes whose values contain
1224
+ // a literal '>' inside quotes, which a plain indexOf would mishandle.
1225
+ let j = i + 1
1226
+ let quote: string | null = null
1227
+ while (j < html.length) {
1228
+ const ch = html[j]
1229
+ if (quote) {
1230
+ if (ch === quote) quote = null
1231
+ } else if (ch === '"' || ch === "'") {
1232
+ quote = ch
1233
+ } else if (ch === '>') {
1234
+ return { end: j + 1 }
1235
+ }
1236
+ j++
1237
+ }
1238
+ return null
1239
+ }
1240
+
1241
+ /**
1242
+ * Returns the index just past the matching `</tagName>`, accounting for
1243
+ * nested tags of the same name. Returns -1 if no match before `limit`.
1244
+ */
1245
+ function findMatchingClosingTag(html: string, from: number, tagName: string, limit: number = html.length): number {
1246
+ let depth = 1
1247
+ let i = from
1248
+ while (i < limit) {
1249
+ if (matchesTagAt(html, i, tagName)) {
1250
+ const opening = parseOpeningTagAt(html, i)
1251
+ if (!opening) {
1252
+ i++
1253
+ continue
1254
+ }
1255
+ const tagText = html.slice(i, opening.end)
1256
+ if (!tagText.endsWith('/>')) depth++
1257
+ i = opening.end
1258
+ } else if (matchesClosingTagAt(html, i, tagName)) {
1259
+ depth--
1260
+ const closing = parseOpeningTagAt(html, i)
1261
+ const closingEnd = closing?.end ?? i + `</${tagName}>`.length
1262
+ if (depth === 0) return closingEnd
1263
+ i = closingEnd
1264
+ } else {
1265
+ i++
1266
+ }
1267
+ }
1268
+ return -1
1269
+ }