@createiq/htmldiff 1.0.5-beta.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/HtmlDiff.cjs CHANGED
@@ -202,942 +202,6 @@ var Operation = class {
202
202
  }
203
203
  };
204
204
  //#endregion
205
- //#region src/TableDiff.ts
206
- const PLACEHOLDER_PREFIX_BASE = "<!--HTMLDIFF_TABLE_";
207
- const PLACEHOLDER_SUFFIX = "-->";
208
- /**
209
- * Hard cap on table dimensions handled by the structural-aware path.
210
- * The row-LCS is O(rows²), the per-row cell-LCS is O(cells²), and each
211
- * comparison string-equals row content (potentially many KB). Without a
212
- * cap, a several-thousand-row table can pin a CPU for seconds. Tables
213
- * larger than this fall through to the word-level diff, which scales
214
- * linearly. Tuned to comfortably cover real-world ISDA schedules
215
- * (which routinely have 1000+ rows).
216
- */
217
- const MAX_TABLE_ROWS = 1500;
218
- const MAX_TABLE_CELLS_PER_ROW = 200;
219
- function makePlaceholderPrefix(oldHtml, newHtml) {
220
- for (let attempt = 0; attempt < 8; attempt++) {
221
- const prefix = `${PLACEHOLDER_PREFIX_BASE}${Math.floor(Math.random() * 4294967295).toString(16).padStart(8, "0")}_`;
222
- if (!oldHtml.includes(prefix) && !newHtml.includes(prefix)) return prefix;
223
- }
224
- return `${PLACEHOLDER_PREFIX_BASE}fallback_${Date.now()}_`;
225
- }
226
- /**
227
- * Diffs every paired-by-position table in the inputs and replaces each
228
- * source table with a placeholder, returning the modified inputs plus the
229
- * placeholder→diff mapping. Returns null when there are no tables to
230
- * preprocess or the table counts don't line up.
231
- */
232
- function preprocessTables(oldHtml, newHtml, diffCell) {
233
- const oldTables = findTopLevelTables(oldHtml);
234
- const newTables = findTopLevelTables(newHtml);
235
- if (oldTables.length === 0 && newTables.length === 0) return null;
236
- if (oldTables.length !== newTables.length) return null;
237
- for (let i = 0; i < oldTables.length; i++) if (exceedsSizeLimit(oldTables[i]) || exceedsSizeLimit(newTables[i])) return null;
238
- const pairs = [];
239
- for (let i = 0; i < oldTables.length; i++) pairs.push({
240
- oldTable: oldTables[i],
241
- newTable: newTables[i],
242
- diffed: diffTable(oldHtml, newHtml, oldTables[i], newTables[i], diffCell)
243
- });
244
- let modifiedOld = oldHtml;
245
- let modifiedNew = newHtml;
246
- const placeholderPrefix = makePlaceholderPrefix(oldHtml, newHtml);
247
- const placeholderToDiff = /* @__PURE__ */ new Map();
248
- for (let i = pairs.length - 1; i >= 0; i--) {
249
- const placeholder = `${placeholderPrefix}${i}${PLACEHOLDER_SUFFIX}`;
250
- placeholderToDiff.set(placeholder, pairs[i].diffed);
251
- modifiedOld = spliceString(modifiedOld, pairs[i].oldTable.tableStart, pairs[i].oldTable.tableEnd, placeholder);
252
- modifiedNew = spliceString(modifiedNew, pairs[i].newTable.tableStart, pairs[i].newTable.tableEnd, placeholder);
253
- }
254
- return {
255
- modifiedOld,
256
- modifiedNew,
257
- placeholderToDiff
258
- };
259
- }
260
- function restoreTablePlaceholders(diffOutput, placeholderToDiff) {
261
- let result = diffOutput;
262
- for (const [placeholder, html] of placeholderToDiff) result = result.split(placeholder).join(html);
263
- return result;
264
- }
265
- function spliceString(s, start, end, replacement) {
266
- return s.slice(0, start) + replacement + s.slice(end);
267
- }
268
- function exceedsSizeLimit(table) {
269
- if (table.rows.length > MAX_TABLE_ROWS) return true;
270
- for (const row of table.rows) if (row.cells.length > MAX_TABLE_CELLS_PER_ROW) return true;
271
- return false;
272
- }
273
- function diffTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
274
- if (sameDimensions(oldTable, newTable)) return diffPositionalTable(oldHtml, newHtml, oldTable, newTable, diffCell);
275
- if (oldTable.rows.length === newTable.rows.length) return diffSameRowCountTable(oldHtml, newHtml, oldTable, newTable, diffCell);
276
- return diffStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, diffCell);
277
- }
278
- function diffSameRowCountTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
279
- const out = [];
280
- let cursor = newTable.tableStart;
281
- let r = 0;
282
- while (r < newTable.rows.length) {
283
- const merge = detectVerticalMerge(oldHtml, newHtml, oldTable, newTable, r);
284
- if (merge) {
285
- out.push(newHtml.slice(cursor, newTable.rows[r].rowStart));
286
- out.push(merge.diff);
287
- cursor = newTable.rows[r + merge.span - 1].rowEnd;
288
- r += merge.span;
289
- continue;
290
- }
291
- const split = detectVerticalSplit(oldHtml, newHtml, oldTable, newTable, r);
292
- if (split) {
293
- out.push(newHtml.slice(cursor, newTable.rows[r].rowStart));
294
- out.push(split.diff);
295
- cursor = newTable.rows[r + split.span - 1].rowEnd;
296
- r += split.span;
297
- continue;
298
- }
299
- const newRow = newTable.rows[r];
300
- out.push(newHtml.slice(cursor, newRow.rowStart));
301
- out.push(diffPreservedRow(oldHtml, newHtml, oldTable.rows[r], newRow, diffCell));
302
- cursor = newRow.rowEnd;
303
- r++;
304
- }
305
- out.push(newHtml.slice(cursor, newTable.tableEnd));
306
- return out.join("");
307
- }
308
- /**
309
- * Detects a vertical merge starting at row `r`: new row R has a single
310
- * cell with rowspan=K (and any colspan ≥ 1), with rows R+1..R+K-1 empty
311
- * in new. Old rows R..R+K-1 must have a logical column width equal to
312
- * the new cell's colspan and contain no rowspan'd cells of their own.
313
- * This handles both single-column merges (old rows are 1-cell, new cell
314
- * rowspan=K) and rectangular merges (e.g. 2×2 merge into a single
315
- * colspan=2 rowspan=2 cell). Output: emit the merged cell with
316
- * `class='mod rowspan'` and the empty trailing rows unchanged.
317
- */
318
- function detectVerticalMerge(oldHtml, newHtml, oldTable, newTable, r) {
319
- const newRow = newTable.rows[r];
320
- if (newRow.cells.length !== 1) return null;
321
- const cell = newRow.cells[0];
322
- const span = getRowspan(newHtml, cell);
323
- if (span <= 1) return null;
324
- if (r + span > newTable.rows.length) return null;
325
- const colspan = getColspan(newHtml, cell);
326
- for (let k = 1; k < span; k++) if (newTable.rows[r + k].cells.length !== 0) return null;
327
- for (let k = 0; k < span; k++) {
328
- const oldRow = oldTable.rows[r + k];
329
- if (!oldRow) return null;
330
- if (sumColspans(oldHtml, oldRow.cells) !== colspan) return null;
331
- for (const c of oldRow.cells) if (getRowspan(oldHtml, c) !== 1) return null;
332
- }
333
- const out = [];
334
- out.push(rowHeaderSlice(newHtml, newRow));
335
- out.push(emitSpanChangedCell(newHtml, cell, "rowspan"));
336
- out.push("</tr>");
337
- for (let k = 1; k < span; k++) out.push(emitEmptyRow(newHtml, newTable.rows[r + k]));
338
- return {
339
- diff: out.join(""),
340
- span
341
- };
342
- }
343
- /**
344
- * Detects a vertical split starting at row `r`: old row R has a single
345
- * cell with rowspan=K, old rows R+1..R+K-1 are empty. New rows R..R+K-1
346
- * each have a single cell. Output: emit each new row with the new cell
347
- * tagged `class='mod rowspan'`.
348
- */
349
- function detectVerticalSplit(oldHtml, newHtml, oldTable, newTable, r) {
350
- const oldRow = oldTable.rows[r];
351
- if (oldRow.cells.length !== 1) return null;
352
- const oldCell = oldRow.cells[0];
353
- const span = getRowspan(oldHtml, oldCell);
354
- if (span <= 1) return null;
355
- if (r + span > oldTable.rows.length) return null;
356
- const colspan = getColspan(oldHtml, oldCell);
357
- for (let k = 1; k < span; k++) if (oldTable.rows[r + k].cells.length !== 0) return null;
358
- for (let k = 0; k < span; k++) {
359
- const newRow = newTable.rows[r + k];
360
- if (!newRow) return null;
361
- if (sumColspans(newHtml, newRow.cells) !== colspan) return null;
362
- for (const c of newRow.cells) if (getRowspan(newHtml, c) !== 1) return null;
363
- }
364
- const out = [];
365
- for (let k = 0; k < span; k++) {
366
- const newRow = newTable.rows[r + k];
367
- out.push(rowHeaderSlice(newHtml, newRow));
368
- for (const c of newRow.cells) out.push(emitSpanChangedCell(newHtml, c, "rowspan"));
369
- out.push("</tr>");
370
- }
371
- return {
372
- diff: out.join(""),
373
- span
374
- };
375
- }
376
- function emitEmptyRow(html, row) {
377
- return html.slice(row.rowStart, row.rowEnd);
378
- }
379
- function sameDimensions(a, b) {
380
- if (a.rows.length !== b.rows.length) return false;
381
- for (let i = 0; i < a.rows.length; i++) if (a.rows[i].cells.length !== b.rows[i].cells.length) return false;
382
- return true;
383
- }
384
- /**
385
- * Same-dimension path: walk the new table verbatim and substitute each
386
- * cell content range with the cell-level diff. The surrounding
387
- * `<thead>`/`<tbody>`/whitespace passes through untouched.
388
- */
389
- function diffPositionalTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
390
- const out = [];
391
- let cursor = newTable.tableStart;
392
- for (let r = 0; r < newTable.rows.length; r++) {
393
- const oldRow = oldTable.rows[r];
394
- const newRow = newTable.rows[r];
395
- for (let c = 0; c < newRow.cells.length; c++) {
396
- const oldCell = oldRow.cells[c];
397
- const newCell = newRow.cells[c];
398
- out.push(newHtml.slice(cursor, newCell.contentStart));
399
- out.push(diffCell(oldHtml.slice(oldCell.contentStart, oldCell.contentEnd), newHtml.slice(newCell.contentStart, newCell.contentEnd)));
400
- cursor = newCell.contentEnd;
401
- }
402
- }
403
- out.push(newHtml.slice(cursor, newTable.tableEnd));
404
- return out.join("");
405
- }
406
- /**
407
- * Mismatched-dimensions path: row-level LCS to identify added/deleted rows,
408
- * then per preserved row a cell-level LCS to identify added/deleted cells.
409
- * Reconstructs the table from scratch — there's no "single new structure"
410
- * to walk verbatim, since we're stitching together kept rows from both
411
- * sides.
412
- */
413
- function diffStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
414
- const alignment = pairSimilarUnmatchedRows(lcsAlign(oldTable.rows.map((row) => rowKey(oldHtml, row)), newTable.rows.map((row) => rowKey(newHtml, row))), oldTable, newTable, oldHtml, newHtml);
415
- if (newTable.rows.length === 0) return rebuildStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, alignment, diffCell);
416
- const out = [];
417
- out.push(newHtml.slice(newTable.tableStart, newTable.rows[0].rowStart));
418
- let cursor = newTable.rows[0].rowStart;
419
- for (const align of alignment) if (align.newIdx !== null) {
420
- const newRow = newTable.rows[align.newIdx];
421
- out.push(newHtml.slice(cursor, newRow.rowStart));
422
- if (align.oldIdx !== null) out.push(diffPreservedRow(oldHtml, newHtml, oldTable.rows[align.oldIdx], newRow, diffCell));
423
- else out.push(emitFullRow(newHtml, newRow, "ins", diffCell));
424
- cursor = newRow.rowEnd;
425
- } else if (align.oldIdx !== null) out.push(emitFullRow(oldHtml, oldTable.rows[align.oldIdx], "del", diffCell));
426
- out.push(newHtml.slice(cursor, newTable.tableEnd));
427
- return out.join("");
428
- }
429
- function rebuildStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, alignment, diffCell) {
430
- const out = [];
431
- out.push(headerSlice(newHtml, newTable, oldHtml, oldTable));
432
- for (const align of alignment) if (align.oldIdx !== null) out.push(emitFullRow(oldHtml, oldTable.rows[align.oldIdx], "del", diffCell));
433
- else if (align.newIdx !== null) out.push(emitFullRow(newHtml, newTable.rows[align.newIdx], "ins", diffCell));
434
- out.push("</table>");
435
- return out.join("");
436
- }
437
- function headerSlice(newHtml, newTable, oldHtml, oldTable) {
438
- const newFirstRow = newTable.rows[0]?.rowStart ?? newTable.tableEnd - 8;
439
- if (newFirstRow > newTable.tableStart) return newHtml.slice(newTable.tableStart, newFirstRow);
440
- const oldFirstRow = oldTable.rows[0]?.rowStart ?? oldTable.tableEnd - 8;
441
- return oldHtml.slice(oldTable.tableStart, oldFirstRow);
442
- }
443
- function rowKey(html, row) {
444
- return html.slice(row.rowStart, row.rowEnd).replace(/\s+/g, " ").trim();
445
- }
446
- function diffPreservedRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
447
- if (oldRow.cells.length === newRow.cells.length) return diffPositionalRow(oldHtml, newHtml, oldRow, newRow, diffCell);
448
- const colspanAligned = diffColspanChangedRow(oldHtml, newHtml, oldRow, newRow, diffCell);
449
- if (colspanAligned !== null) return colspanAligned;
450
- const delta = newRow.cells.length - oldRow.cells.length;
451
- const absDelta = Math.abs(delta);
452
- if (absDelta > 0 && absDelta <= MAX_COLUMN_DELTA && Math.max(oldRow.cells.length, newRow.cells.length) <= MAX_COLUMN_SEARCH_WIDTH) {
453
- if (delta > 0) return diffMultiColumnAddRow(oldHtml, newHtml, oldRow, newRow, delta, diffCell);
454
- return diffMultiColumnDeleteRow(oldHtml, newHtml, oldRow, newRow, -delta, diffCell);
455
- }
456
- return diffStructurallyAlignedRow(oldHtml, newHtml, oldRow, newRow, diffCell);
457
- }
458
- const MAX_COLUMN_DELTA = 6;
459
- const MAX_COLUMN_SEARCH_WIDTH = 40;
460
- /**
461
- * For a row where new has K more cells than old, find the K column
462
- * positions in new where cells were inserted by scanning all C(newCount,
463
- * K) combinations and picking the one that maximises positional content
464
- * similarity with the remaining cells. The inserted cells are emitted
465
- * with diff markers; the rest are aligned positionally with content
466
- * diff for matched pairs.
467
- */
468
- function diffMultiColumnAddRow(oldHtml, newHtml, oldRow, newRow, k, diffCell) {
469
- const insertedPositions = findBestColumnInsertPositions(oldRow, newRow, k, oldHtml, newHtml);
470
- const inserted = new Set(insertedPositions);
471
- const out = [rowHeaderSlice(newHtml, newRow)];
472
- let oldIdx = 0;
473
- for (let c = 0; c < newRow.cells.length; c++) if (inserted.has(c)) out.push(emitFullCell(newHtml, newRow.cells[c], "ins", diffCell));
474
- else {
475
- out.push(emitDiffedCell(oldHtml, newHtml, oldRow.cells[oldIdx], newRow.cells[c], diffCell));
476
- oldIdx++;
477
- }
478
- out.push("</tr>");
479
- return out.join("");
480
- }
481
- function diffMultiColumnDeleteRow(oldHtml, newHtml, oldRow, newRow, k, diffCell) {
482
- const deletedPositions = findBestColumnDeletePositions(oldRow, newRow, k, oldHtml, newHtml);
483
- const deleted = new Set(deletedPositions);
484
- const out = [rowHeaderSlice(newHtml, newRow)];
485
- let newIdx = 0;
486
- for (let oldIdx = 0; oldIdx < oldRow.cells.length; oldIdx++) {
487
- if (deleted.has(oldIdx)) {
488
- out.push(emitFullCell(oldHtml, oldRow.cells[oldIdx], "del", diffCell));
489
- continue;
490
- }
491
- out.push(emitDiffedCell(oldHtml, newHtml, oldRow.cells[oldIdx], newRow.cells[newIdx], diffCell));
492
- newIdx++;
493
- }
494
- out.push("</tr>");
495
- return out.join("");
496
- }
497
- function findBestColumnInsertPositions(oldRow, newRow, k, oldHtml, newHtml) {
498
- let bestPositions = [];
499
- let bestScore = -1;
500
- for (const combo of combinationsOfRange(newRow.cells.length, k)) {
501
- const inserted = new Set(combo);
502
- let score = 0;
503
- let oldIdx = 0;
504
- for (let newIdx = 0; newIdx < newRow.cells.length; newIdx++) {
505
- if (inserted.has(newIdx)) continue;
506
- score += cellSimilarity(oldRow.cells[oldIdx], newRow.cells[newIdx], oldHtml, newHtml);
507
- oldIdx++;
508
- }
509
- if (score > bestScore) {
510
- bestScore = score;
511
- bestPositions = combo;
512
- }
513
- }
514
- return bestPositions;
515
- }
516
- function findBestColumnDeletePositions(oldRow, newRow, k, oldHtml, newHtml) {
517
- let bestPositions = [];
518
- let bestScore = -1;
519
- for (const combo of combinationsOfRange(oldRow.cells.length, k)) {
520
- const deleted = new Set(combo);
521
- let score = 0;
522
- let newIdx = 0;
523
- for (let oldIdx = 0; oldIdx < oldRow.cells.length; oldIdx++) {
524
- if (deleted.has(oldIdx)) continue;
525
- score += cellSimilarity(oldRow.cells[oldIdx], newRow.cells[newIdx], oldHtml, newHtml);
526
- newIdx++;
527
- }
528
- if (score > bestScore) {
529
- bestScore = score;
530
- bestPositions = combo;
531
- }
532
- }
533
- return bestPositions;
534
- }
535
- /**
536
- * Yields all sorted-ascending combinations of `k` distinct integers
537
- * from [0, n). Iterative implementation avoids recursion overhead and
538
- * keeps memory at O(k).
539
- */
540
- function* combinationsOfRange(n, k) {
541
- if (k === 0 || k > n) return;
542
- const indices = Array.from({ length: k }, (_, i) => i);
543
- while (true) {
544
- yield indices.slice();
545
- let i = k - 1;
546
- while (i >= 0 && indices[i] === n - k + i) i--;
547
- if (i < 0) return;
548
- indices[i]++;
549
- for (let j = i + 1; j < k; j++) indices[j] = indices[j - 1] + 1;
550
- }
551
- }
552
- /**
553
- * Try to align cells by logical column position (sum of colspans). When
554
- * one side has a colspan'd cell that absorbs multiple cells on the other
555
- * side, emit the new structure with `class='mod colspan'` on the
556
- * merged/split cells. Returns null if the rows don't align cleanly —
557
- * caller falls back to a generic cell-LCS.
558
- */
559
- function diffColspanChangedRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
560
- if (sumColspans(oldHtml, oldRow.cells) !== sumColspans(newHtml, newRow.cells)) return null;
561
- const out = [];
562
- out.push(rowHeaderSlice(newHtml, newRow));
563
- let oi = 0;
564
- let ni = 0;
565
- while (oi < oldRow.cells.length && ni < newRow.cells.length) {
566
- const oCell = oldRow.cells[oi];
567
- const nCell = newRow.cells[ni];
568
- const oSpan = getColspan(oldHtml, oCell);
569
- const nSpan = getColspan(newHtml, nCell);
570
- if (oSpan === nSpan) {
571
- out.push(emitDiffedCell(oldHtml, newHtml, oCell, nCell, diffCell));
572
- oi++;
573
- ni++;
574
- } else if (nSpan > oSpan) {
575
- let totalOldSpan = 0;
576
- let oj = oi;
577
- while (oj < oldRow.cells.length && totalOldSpan < nSpan) {
578
- totalOldSpan += getColspan(oldHtml, oldRow.cells[oj]);
579
- oj++;
580
- }
581
- if (totalOldSpan !== nSpan) return null;
582
- out.push(emitSpanChangedCell(newHtml, nCell, "colspan"));
583
- oi = oj;
584
- ni++;
585
- } else {
586
- let totalNewSpan = 0;
587
- let nj = ni;
588
- while (nj < newRow.cells.length && totalNewSpan < oSpan) {
589
- totalNewSpan += getColspan(newHtml, newRow.cells[nj]);
590
- nj++;
591
- }
592
- if (totalNewSpan !== oSpan) return null;
593
- for (let k = ni; k < nj; k++) out.push(emitSpanChangedCell(newHtml, newRow.cells[k], "colspan"));
594
- oi++;
595
- ni = nj;
596
- }
597
- }
598
- if (oi !== oldRow.cells.length || ni !== newRow.cells.length) return null;
599
- out.push("</tr>");
600
- return out.join("");
601
- }
602
- function sumColspans(html, cells) {
603
- let total = 0;
604
- for (const cell of cells) total += getColspan(html, cell);
605
- return total;
606
- }
607
- function getColspan(html, cell) {
608
- return parseSpanAttribute(html.slice(cell.cellStart, cell.contentStart), "colspan");
609
- }
610
- function getRowspan(html, cell) {
611
- return parseSpanAttribute(html.slice(cell.cellStart, cell.contentStart), "rowspan");
612
- }
613
- function parseSpanAttribute(openingTag, name) {
614
- const m = (name === "colspan" ? /\bcolspan\s*=\s*["']?(\d+)["']?/i : /\browspan\s*=\s*["']?(\d+)["']?/i).exec(openingTag);
615
- if (!m) return 1;
616
- const value = Number.parseInt(m[1], 10);
617
- return Number.isFinite(value) && value > 0 ? value : 1;
618
- }
619
- /**
620
- * Emits a cell that's the merged/split product of a structural change,
621
- * tagged with `class='mod colspan'` or `class='mod rowspan'`. Content is
622
- * carried through unmodified — Word doesn't track these changes, and
623
- * inserting del/ins around content that didn't really change would be
624
- * misleading.
625
- */
626
- function emitSpanChangedCell(html, cell, kind) {
627
- const tdOpening = parseOpeningTagAt(html, cell.cellStart);
628
- if (!tdOpening) return html.slice(cell.cellStart, cell.cellEnd);
629
- return injectClass(html.slice(cell.cellStart, tdOpening.end), `mod ${kind}`) + html.slice(cell.contentStart, cell.cellEnd);
630
- }
631
- function diffPositionalRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
632
- const out = [];
633
- const trHeader = rowHeaderSlice(newHtml, newRow);
634
- out.push(trHeader);
635
- let cursor = newRow.cells[0]?.cellStart ?? newRow.rowEnd;
636
- for (let c = 0; c < newRow.cells.length; c++) {
637
- const oldCell = oldRow.cells[c];
638
- const newCell = newRow.cells[c];
639
- out.push(newHtml.slice(cursor, newCell.contentStart));
640
- out.push(diffCell(oldHtml.slice(oldCell.contentStart, oldCell.contentEnd), newHtml.slice(newCell.contentStart, newCell.contentEnd)));
641
- cursor = newCell.contentEnd;
642
- }
643
- out.push(newHtml.slice(cursor, newRow.rowEnd));
644
- return out.join("");
645
- }
646
- function diffStructurallyAlignedRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
647
- const alignment = pairSimilarUnmatchedCells(lcsAlign(oldRow.cells.map((cell) => cellKey(oldHtml, cell)), newRow.cells.map((cell) => cellKey(newHtml, cell))), oldRow, newRow, oldHtml, newHtml);
648
- const out = [];
649
- out.push(rowHeaderSlice(newHtml, newRow));
650
- for (const align of alignment) if (align.oldIdx !== null && align.newIdx !== null) {
651
- const oldCell = oldRow.cells[align.oldIdx];
652
- const newCell = newRow.cells[align.newIdx];
653
- out.push(emitDiffedCell(oldHtml, newHtml, oldCell, newCell, diffCell));
654
- } else if (align.newIdx !== null) out.push(emitFullCell(newHtml, newRow.cells[align.newIdx], "ins", diffCell));
655
- else if (align.oldIdx !== null) out.push(emitFullCell(oldHtml, oldRow.cells[align.oldIdx], "del", diffCell));
656
- out.push("</tr>");
657
- return out.join("");
658
- }
659
- function cellKey(html, cell) {
660
- return html.slice(cell.contentStart, cell.contentEnd).replace(/\s+/g, " ").trim();
661
- }
662
- /**
663
- * Emits a row with all cells either inserted (kind='ins') or deleted
664
- * (kind='del'). Adds `class='diffins'`/`'diffdel'` to the `<tr>` and to
665
- * each `<td>`, with an `<ins>`/`<del>` wrapper around any cell content
666
- * (empty cells get the class but no wrapper).
667
- */
668
- function emitFullRow(html, row, kind, diffCell) {
669
- const cls = kind === "ins" ? "diffins" : "diffdel";
670
- const trOpening = parseOpeningTagAt(html, row.rowStart);
671
- if (!trOpening) return html.slice(row.rowStart, row.rowEnd);
672
- const out = [injectClass(html.slice(row.rowStart, trOpening.end), cls)];
673
- let cursor = trOpening.end;
674
- for (const cell of row.cells) {
675
- out.push(html.slice(cursor, cell.cellStart));
676
- out.push(emitFullCell(html, cell, kind, diffCell));
677
- cursor = cell.cellEnd;
678
- }
679
- out.push(html.slice(cursor, row.rowEnd));
680
- return out.join("");
681
- }
682
- /**
683
- * Emits a fully-inserted or fully-deleted cell. Inner text runs are wrapped
684
- * with `<ins>`/`<del>` while formatting tags pass through unchanged, so
685
- * `<strong>B</strong>` renders as `<strong><ins>B</ins></strong>` —
686
- * matching htmldiff's general convention without the doubled-`<ins>` that
687
- * the full recursive diff would produce for newly-inserted formatting.
688
- * Empty cells get the class on the `<td>` but no inner wrapping.
689
- */
690
- function emitFullCell(html, cell, kind, _diffCell) {
691
- const cls = kind === "ins" ? "diffins" : "diffdel";
692
- const tdOpening = parseOpeningTagAt(html, cell.cellStart);
693
- if (!tdOpening) return html.slice(cell.cellStart, cell.cellEnd);
694
- const tdOpenTag = injectClass(html.slice(cell.cellStart, tdOpening.end), cls);
695
- const content = html.slice(cell.contentStart, cell.contentEnd);
696
- const wrapped = content.trim().length === 0 ? content : wrapInlineTextRuns(content, kind);
697
- const closing = html.slice(cell.contentEnd, cell.cellEnd);
698
- return tdOpenTag + wrapped + closing;
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, kind) {
708
- const tag = kind === "ins" ? "ins" : "del";
709
- const cls = kind === "ins" ? "diffins" : "diffdel";
710
- const out = [];
711
- let i = 0;
712
- while (i < content.length) {
713
- if (content[i] === "<") {
714
- const tagEnd = parseOpeningTagAt(content, i);
715
- if (!tagEnd) {
716
- out.push(content.slice(i));
717
- break;
718
- }
719
- out.push(content.slice(i, tagEnd.end));
720
- i = tagEnd.end;
721
- continue;
722
- }
723
- let j = i;
724
- while (j < content.length && content[j] !== "<") j++;
725
- const text = content.slice(i, j);
726
- if (text.trim().length > 0) out.push(`<${tag} class='${cls}'>${text}</${tag}>`);
727
- else out.push(text);
728
- i = j;
729
- }
730
- return out.join("");
731
- }
732
- function emitDiffedCell(oldHtml, newHtml, oldCell, newCell, diffCell) {
733
- const tdOpening = parseOpeningTagAt(newHtml, newCell.cellStart);
734
- if (!tdOpening) return newHtml.slice(newCell.cellStart, newCell.cellEnd);
735
- const tdOpenTag = newHtml.slice(newCell.cellStart, tdOpening.end);
736
- const content = diffCell(oldHtml.slice(oldCell.contentStart, oldCell.contentEnd), newHtml.slice(newCell.contentStart, newCell.contentEnd));
737
- const closing = newHtml.slice(newCell.contentEnd, newCell.cellEnd);
738
- return tdOpenTag + content + closing;
739
- }
740
- function rowHeaderSlice(html, row) {
741
- const opening = parseOpeningTagAt(html, row.rowStart);
742
- if (!opening) return "";
743
- if (row.cells.length === 0) return html.slice(row.rowStart, opening.end);
744
- return html.slice(row.rowStart, row.cells[0].cellStart);
745
- }
746
- /** Character-level similarity threshold above which we treat two rows as "the same row, edited". */
747
- const ROW_FUZZY_THRESHOLD = .5;
748
- /**
749
- * Threshold for "this cell is a content-edit of that cell." Tuned the same
750
- * as ROW_FUZZY_THRESHOLD; cells in legal docs that share most of their
751
- * content typically ARE the same logical cell with a body edit, so 0.5
752
- * works for both granularities in practice.
753
- */
754
- const CELL_FUZZY_THRESHOLD = .5;
755
- /**
756
- * After exact LCS, scan the alignment for runs of "old deleted, then new
757
- * inserted" (or vice versa) and pair entries whose content is similar
758
- * enough to be treated as an edit rather than a delete+insert. This keeps
759
- * row-level edits (a typo fix, a single word change) from being shown as
760
- * an entire row vanishing and a new one appearing — matching what users
761
- * expect from a typical track-changes view.
762
- */
763
- function pairSimilarUnmatchedRows(alignment, oldTable, newTable, oldHtml, newHtml) {
764
- return pairSimilarUnmatched(alignment, ROW_FUZZY_THRESHOLD, (oldIdx, newIdx) => rowSimilarity(oldTable.rows[oldIdx], newTable.rows[newIdx], oldHtml, newHtml));
765
- }
766
- function pairSimilarUnmatchedCells(alignment, oldRow, newRow, oldHtml, newHtml) {
767
- return pairSimilarUnmatched(alignment, CELL_FUZZY_THRESHOLD, (oldIdx, newIdx) => cellSimilarity(oldRow.cells[oldIdx], newRow.cells[newIdx], oldHtml, newHtml));
768
- }
769
- /**
770
- * Identify pairings inside each unmatched-only run, then build the output
771
- * alignment by walking the original and substituting paired entries at
772
- * the *ins position* (not the del position). This keeps the result
773
- * monotonic in newIdx — critical because the cursor-based emission
774
- * downstream walks new's html in order. Emitting at the del position
775
- * would be fine when del<ins in the alignment array (the typical case),
776
- * but can violate monotonicity when there are mixed unpaired entries in
777
- * between (column-add + row-add together, content-edit + column-add,
778
- * etc.).
779
- *
780
- * Generic over what's being paired — works for both rows (by full row
781
- * content similarity) and cells (by per-cell content similarity).
782
- */
783
- function pairSimilarUnmatched(alignment, threshold, similarity) {
784
- const pairs = /* @__PURE__ */ new Map();
785
- let i = 0;
786
- while (i < alignment.length) {
787
- if (alignment[i].oldIdx !== null && alignment[i].newIdx !== null) {
788
- i++;
789
- continue;
790
- }
791
- const runStart = i;
792
- while (i < alignment.length && alignment[i].oldIdx === null !== (alignment[i].newIdx === null)) i++;
793
- const runEnd = i;
794
- const delIndices = [];
795
- const insIndices = [];
796
- for (let k = runStart; k < runEnd; k++) if (alignment[k].oldIdx !== null) delIndices.push(k);
797
- else insIndices.push(k);
798
- const usedIns = /* @__PURE__ */ new Set();
799
- for (const di of delIndices) {
800
- let bestIi = -1;
801
- let bestSim = threshold;
802
- for (const ii of insIndices) {
803
- if (usedIns.has(ii)) continue;
804
- const sim = similarity(alignment[di].oldIdx, alignment[ii].newIdx);
805
- if (sim > bestSim) {
806
- bestSim = sim;
807
- bestIi = ii;
808
- }
809
- }
810
- if (bestIi >= 0) {
811
- pairs.set(di, bestIi);
812
- usedIns.add(bestIi);
813
- }
814
- }
815
- }
816
- const insToDel = /* @__PURE__ */ new Map();
817
- for (const [delAi, insAi] of pairs) insToDel.set(insAi, delAi);
818
- const pairedDels = new Set(pairs.keys());
819
- const result = [];
820
- for (let k = 0; k < alignment.length; k++) {
821
- if (pairedDels.has(k)) continue;
822
- if (insToDel.has(k)) {
823
- const delAi = insToDel.get(k);
824
- result.push({
825
- oldIdx: alignment[delAi].oldIdx,
826
- newIdx: alignment[k].newIdx
827
- });
828
- } else result.push(alignment[k]);
829
- }
830
- return result;
831
- }
832
- /**
833
- * Combined similarity metric used for both row-level and cell-level
834
- * fuzzy pairing. Returns the MAX of two complementary metrics:
835
- *
836
- * 1. **Character prefix+suffix similarity** — fraction of the longer
837
- * string covered by shared prefix + shared suffix. Catches small
838
- * edits in the middle of a string (one word changed in a row).
839
- * Misses cases where the bulk of common content is in the middle
840
- * and the ends differ.
841
- *
842
- * 2. **Token Jaccard similarity** — intersection-over-union of the
843
- * whitespace-split tokens. Catches "most of the content is the
844
- * same but bookended by different bits" — e.g. a row whose only
845
- * edit is a column added at the start and another at the end,
846
- * where the ~50 chars in the middle that DO match would be
847
- * invisible to prefix+suffix.
848
- *
849
- * Either metric exceeding the threshold means pair. Neither alone is
850
- * sufficient for the full range of legal-doc edits we see in
851
- * production tables.
852
- */
853
- function rowSimilarity(oldRow, newRow, oldHtml, newHtml) {
854
- return textSimilarity(rowText(oldHtml, oldRow), rowText(newHtml, newRow));
855
- }
856
- function cellSimilarity(oldCell, newCell, oldHtml, newHtml) {
857
- return textSimilarity(cellText(oldHtml, oldCell), cellText(newHtml, newCell));
858
- }
859
- function textSimilarity(a, b) {
860
- if (a === b) return 1;
861
- if (a.length === 0 || b.length === 0) return 0;
862
- return Math.max(charPrefixSuffixSimilarity(a, b), tokenJaccardSimilarity(a, b));
863
- }
864
- function charPrefixSuffixSimilarity(a, b) {
865
- let prefix = 0;
866
- const minLen = Math.min(a.length, b.length);
867
- while (prefix < minLen && a[prefix] === b[prefix]) prefix++;
868
- let suffix = 0;
869
- while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix++;
870
- return (prefix + suffix) / Math.max(a.length, b.length);
871
- }
872
- function tokenJaccardSimilarity(a, b) {
873
- const tokensA = new Set(a.split(/\s+/).filter(Boolean));
874
- const tokensB = new Set(b.split(/\s+/).filter(Boolean));
875
- if (tokensA.size === 0 && tokensB.size === 0) return 1;
876
- let intersection = 0;
877
- for (const t of tokensA) if (tokensB.has(t)) intersection++;
878
- const union = tokensA.size + tokensB.size - intersection;
879
- return union === 0 ? 0 : intersection / union;
880
- }
881
- function rowText(html, row) {
882
- const parts = [];
883
- for (const cell of row.cells) parts.push(html.slice(cell.contentStart, cell.contentEnd).replace(/<[^>]+>/g, " "));
884
- return parts.join(" ").replace(/\s+/g, " ").trim().toLowerCase();
885
- }
886
- function cellText(html, cell) {
887
- return html.slice(cell.contentStart, cell.contentEnd).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().toLowerCase();
888
- }
889
- /**
890
- * Standard LCS alignment: walks both sequences and emits a list of pairs
891
- * where `(oldIdx, newIdx)` are both set for matching positions, and one
892
- * side is null for an unmatched entry on the other side. Equality uses
893
- * strict ===.
894
- */
895
- function lcsAlign(oldKeys, newKeys) {
896
- const m = oldKeys.length;
897
- const n = newKeys.length;
898
- const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
899
- for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) if (oldKeys[i - 1] === newKeys[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
900
- else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
901
- const result = [];
902
- let i = m;
903
- let j = n;
904
- while (i > 0 || j > 0) if (i > 0 && j > 0 && oldKeys[i - 1] === newKeys[j - 1]) {
905
- result.unshift({
906
- oldIdx: i - 1,
907
- newIdx: j - 1
908
- });
909
- i--;
910
- j--;
911
- } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
912
- result.unshift({
913
- oldIdx: null,
914
- newIdx: j - 1
915
- });
916
- j--;
917
- } else {
918
- result.unshift({
919
- oldIdx: i - 1,
920
- newIdx: null
921
- });
922
- i--;
923
- }
924
- return result;
925
- }
926
- /**
927
- * Returns the opening tag string with the given class injected. Existing
928
- * `class` attributes are preserved and the new class appended.
929
- */
930
- /**
931
- * Returns the opening tag with the given class injected. Locates the real
932
- * `class` attribute via attribute-aware walking (NOT a flat regex — that
933
- * would mis-match inside a foreign attribute value like
934
- * `title="see class='x'"`). When the class already partially overlaps with
935
- * `cls` — e.g. existing `class="mod"` and we're injecting `mod colspan` —
936
- * only the missing tokens get appended, so we never end up with
937
- * `class="mod mod colspan"`.
938
- */
939
- function injectClass(openingTag, cls) {
940
- const clsTokens = cls.split(/\s+/).filter(Boolean);
941
- if (clsTokens.length === 0) return openingTag;
942
- const classAttr = findClassAttribute(openingTag);
943
- if (classAttr) {
944
- const existingTokens = classAttr.value.split(/\s+/).filter(Boolean);
945
- const missing = clsTokens.filter((t) => !existingTokens.includes(t));
946
- if (missing.length === 0) return openingTag;
947
- const updatedValue = existingTokens.length === 0 ? missing.join(" ") : `${existingTokens.join(" ")} ${missing.join(" ")}`;
948
- return openingTag.slice(0, classAttr.valueStart) + updatedValue + openingTag.slice(classAttr.valueEnd);
949
- }
950
- const insertAt = openingTag.endsWith("/>") ? openingTag.length - 2 : openingTag.length - 1;
951
- return `${openingTag.slice(0, insertAt).replace(/\s*$/, "")} class='${cls}'${openingTag.slice(insertAt)}`;
952
- }
953
- /**
954
- * Walks the opening tag's attributes (respecting quoted values) to find
955
- * the actual `class` attribute. Returns the value range (start/end of the
956
- * value content, *excluding* the surrounding quotes) and the value, or
957
- * null if no `class` attribute is present.
958
- */
959
- function findClassAttribute(openingTag) {
960
- let i = 1;
961
- while (i < openingTag.length && /[A-Za-z0-9_:-]/.test(openingTag[i])) i++;
962
- while (i < openingTag.length) {
963
- while (i < openingTag.length && /\s/.test(openingTag[i])) i++;
964
- if (i >= openingTag.length) break;
965
- if (openingTag[i] === ">" || openingTag[i] === "/") break;
966
- const nameStart = i;
967
- while (i < openingTag.length && !/[\s=>/]/.test(openingTag[i])) i++;
968
- const name = openingTag.slice(nameStart, i);
969
- while (i < openingTag.length && /\s/.test(openingTag[i])) i++;
970
- if (openingTag[i] !== "=") continue;
971
- i++;
972
- while (i < openingTag.length && /\s/.test(openingTag[i])) i++;
973
- let valueStart;
974
- let valueEnd;
975
- if (openingTag[i] === "\"" || openingTag[i] === "'") {
976
- const quote = openingTag[i];
977
- i++;
978
- valueStart = i;
979
- while (i < openingTag.length && openingTag[i] !== quote) i++;
980
- valueEnd = i;
981
- if (i < openingTag.length) i++;
982
- } else {
983
- valueStart = i;
984
- while (i < openingTag.length && !/[\s>/]/.test(openingTag[i])) i++;
985
- valueEnd = i;
986
- }
987
- if (name.toLowerCase() === "class") return {
988
- valueStart,
989
- valueEnd,
990
- value: openingTag.slice(valueStart, valueEnd)
991
- };
992
- }
993
- return null;
994
- }
995
- /**
996
- * Walks html and returns ranges for every top-level `<table>...</table>`
997
- * block. Nested tables aren't extracted as separate top-level entries —
998
- * they're captured inside the parent's content range and handled when the
999
- * cell-level diff recurses through them.
1000
- */
1001
- function findTopLevelTables(html) {
1002
- const tables = [];
1003
- let i = 0;
1004
- while (i < html.length) if (matchesTagAt(html, i, "table")) {
1005
- const opening = parseOpeningTagAt(html, i);
1006
- if (!opening) {
1007
- i++;
1008
- continue;
1009
- }
1010
- const tableContentStart = opening.end;
1011
- const tableEnd = findMatchingClosingTag(html, tableContentStart, "table");
1012
- if (tableEnd === -1) {
1013
- i = opening.end;
1014
- continue;
1015
- }
1016
- const rows = findTopLevelRows(html, tableContentStart, tableEnd - 8);
1017
- tables.push({
1018
- tableStart: i,
1019
- tableEnd,
1020
- rows
1021
- });
1022
- i = tableEnd;
1023
- } else i++;
1024
- return tables;
1025
- }
1026
- function findTopLevelRows(html, start, end) {
1027
- const rows = [];
1028
- let i = start;
1029
- while (i < end) if (matchesTagAt(html, i, "tr")) {
1030
- const opening = parseOpeningTagAt(html, i);
1031
- if (!opening) {
1032
- i++;
1033
- continue;
1034
- }
1035
- const rowContentStart = opening.end;
1036
- const rowEnd = findMatchingClosingTag(html, rowContentStart, "tr", end);
1037
- if (rowEnd === -1) {
1038
- i = opening.end;
1039
- continue;
1040
- }
1041
- const cells = findTopLevelCells(html, rowContentStart, rowEnd - 5);
1042
- rows.push({
1043
- rowStart: i,
1044
- rowEnd,
1045
- cells
1046
- });
1047
- i = rowEnd;
1048
- } else if (matchesClosingTagAt(html, i, "table")) break;
1049
- else i++;
1050
- return rows;
1051
- }
1052
- function findTopLevelCells(html, start, end) {
1053
- const cells = [];
1054
- let i = start;
1055
- while (i < end) if (matchesTagAt(html, i, "td") || matchesTagAt(html, i, "th")) {
1056
- const tagName = matchesTagAt(html, i, "td") ? "td" : "th";
1057
- const opening = parseOpeningTagAt(html, i);
1058
- if (!opening) {
1059
- i++;
1060
- continue;
1061
- }
1062
- const contentStart = opening.end;
1063
- const cellEnd = findMatchingClosingTag(html, contentStart, tagName, end);
1064
- if (cellEnd === -1) {
1065
- i = opening.end;
1066
- continue;
1067
- }
1068
- const contentEnd = cellEnd - `</${tagName}>`.length;
1069
- cells.push({
1070
- cellStart: i,
1071
- cellEnd,
1072
- contentStart,
1073
- contentEnd
1074
- });
1075
- i = cellEnd;
1076
- } else if (matchesClosingTagAt(html, i, "tr")) break;
1077
- else i++;
1078
- return cells;
1079
- }
1080
- function matchesTagAt(html, i, tagName) {
1081
- if (html[i] !== "<") return false;
1082
- if (html.slice(i + 1, i + 1 + tagName.length).toLowerCase() !== tagName) return false;
1083
- const after = html[i + 1 + tagName.length];
1084
- return after === ">" || after === " " || after === " " || after === "\n" || after === "\r" || after === "/";
1085
- }
1086
- function matchesClosingTagAt(html, i, tagName) {
1087
- if (html[i] !== "<" || html[i + 1] !== "/") return false;
1088
- if (html.slice(i + 2, i + 2 + tagName.length).toLowerCase() !== tagName) return false;
1089
- const after = html[i + 2 + tagName.length];
1090
- return after === ">" || after === " " || after === " " || after === "\n" || after === "\r";
1091
- }
1092
- function parseOpeningTagAt(html, i) {
1093
- if (html.startsWith("<!--", i)) {
1094
- const close = html.indexOf("-->", i + 4);
1095
- return close === -1 ? null : { end: close + 3 };
1096
- }
1097
- if (html.startsWith("<![CDATA[", i)) {
1098
- const close = html.indexOf("]]>", i + 9);
1099
- return close === -1 ? null : { end: close + 3 };
1100
- }
1101
- if (html.startsWith("<?", i)) {
1102
- const close = html.indexOf("?>", i + 2);
1103
- return close === -1 ? null : { end: close + 2 };
1104
- }
1105
- let j = i + 1;
1106
- let quote = null;
1107
- while (j < html.length) {
1108
- const ch = html[j];
1109
- if (quote) {
1110
- if (ch === quote) quote = null;
1111
- } else if (ch === "\"" || ch === "'") quote = ch;
1112
- else if (ch === ">") return { end: j + 1 };
1113
- j++;
1114
- }
1115
- return null;
1116
- }
1117
- /**
1118
- * Returns the index just past the matching `</tagName>`, accounting for
1119
- * nested tags of the same name. Returns -1 if no match before `limit`.
1120
- */
1121
- function findMatchingClosingTag(html, from, tagName, limit = html.length) {
1122
- let depth = 1;
1123
- let i = from;
1124
- while (i < limit) if (matchesTagAt(html, i, tagName)) {
1125
- const opening = parseOpeningTagAt(html, i);
1126
- if (!opening) {
1127
- i++;
1128
- continue;
1129
- }
1130
- if (!html.slice(i, opening.end).endsWith("/>")) depth++;
1131
- i = opening.end;
1132
- } else if (matchesClosingTagAt(html, i, tagName)) {
1133
- depth--;
1134
- const closingEnd = parseOpeningTagAt(html, i)?.end ?? i + `</${tagName}>`.length;
1135
- if (depth === 0) return closingEnd;
1136
- i = closingEnd;
1137
- } else i++;
1138
- return -1;
1139
- }
1140
- //#endregion
1141
205
  //#region src/WordSplitter.ts
1142
206
  var WordSplitter = class WordSplitter {
1143
207
  text;
@@ -1383,20 +447,9 @@ var HtmlDiff = class HtmlDiff {
1383
447
  "s",
1384
448
  "span"
1385
449
  ]);
1386
- /**
1387
- * Hard cap on nested `HtmlDiff.execute` calls (table preprocessing
1388
- * recurses through `diffCell` for cell content). Each level allocates
1389
- * fresh DP matrices and word arrays; without a guard a maliciously
1390
- * nested table-in-cell-in-table-in-cell input could blow stack and
1391
- * memory. Set high enough to comfortably handle real legal documents
1392
- * (tables nested 2-3 deep at most), low enough to short-circuit
1393
- * pathological input.
1394
- */
1395
- static MaxTablePreprocessDepth = 8;
1396
450
  content = [];
1397
451
  newText;
1398
452
  oldText;
1399
- tablePreprocessDepth;
1400
453
  specialTagDiffStack = [];
1401
454
  newWords = [];
1402
455
  oldWords = [];
@@ -1459,17 +512,13 @@ var HtmlDiff = class HtmlDiff {
1459
512
  * Initializes a new instance of the class.
1460
513
  * @param oldText The old text.
1461
514
  * @param newText The new text.
1462
- * @param tablePreprocessDepth Internal: nested-call depth for table
1463
- * preprocessing. Callers should leave at default (0); the recursive
1464
- * `diffCell` callback in TableDiff bumps it.
1465
515
  */
1466
- constructor(oldText, newText, tablePreprocessDepth = 0) {
516
+ constructor(oldText, newText) {
1467
517
  this.oldText = oldText;
1468
518
  this.newText = newText;
1469
- this.tablePreprocessDepth = tablePreprocessDepth;
1470
519
  }
1471
- static execute(oldText, newText, tablePreprocessDepth = 0) {
1472
- return new HtmlDiff(oldText, newText, tablePreprocessDepth).build();
520
+ static execute(oldText, newText) {
521
+ return new HtmlDiff(oldText, newText).build();
1473
522
  }
1474
523
  /**
1475
524
  * Builds the HTML diff output
@@ -1477,22 +526,6 @@ var HtmlDiff = class HtmlDiff {
1477
526
  */
1478
527
  build() {
1479
528
  if (this.oldText === this.newText) return this.newText;
1480
- const blockExpressions = this.blockExpressions;
1481
- const repeatingWordsAccuracy = this.repeatingWordsAccuracy;
1482
- const orphanMatchThreshold = this.orphanMatchThreshold;
1483
- const ignoreWhitespaceDifferences = this.ignoreWhitespaceDifferences;
1484
- const tablePreprocess = this.tablePreprocessDepth >= HtmlDiff.MaxTablePreprocessDepth ? null : preprocessTables(this.oldText, this.newText, (oldCell, newCell) => {
1485
- const inner = new HtmlDiff(oldCell, newCell, this.tablePreprocessDepth + 1);
1486
- for (const expr of blockExpressions) inner.addBlockExpression(expr);
1487
- inner.repeatingWordsAccuracy = repeatingWordsAccuracy;
1488
- inner.orphanMatchThreshold = orphanMatchThreshold;
1489
- inner.ignoreWhitespaceDifferences = ignoreWhitespaceDifferences;
1490
- return inner.build();
1491
- });
1492
- if (tablePreprocess) {
1493
- this.oldText = tablePreprocess.modifiedOld;
1494
- this.newText = tablePreprocess.modifiedNew;
1495
- }
1496
529
  this.splitInputsToWords();
1497
530
  this.buildContentProjections();
1498
531
  const wordsForDiffOld = this.oldContentWords ?? this.oldWords;
@@ -1500,8 +533,7 @@ var HtmlDiff = class HtmlDiff {
1500
533
  this.matchGranularity = Math.min(HtmlDiff.MatchGranularityMaximum, Math.min(wordsForDiffOld.length, wordsForDiffNew.length));
1501
534
  const operations = this.operations();
1502
535
  for (const op of operations) this.performOperation(op);
1503
- const result = this.content.join("");
1504
- return tablePreprocess ? restoreTablePlaceholders(result, tablePreprocess.placeholderToDiff) : result;
536
+ return this.content.join("");
1505
537
  }
1506
538
  /**
1507
539
  * Uses {@link expression} to group text together so that any change detected within the group is treated as a single block
@@ -1728,7 +760,7 @@ var HtmlDiff = class HtmlDiff {
1728
760
  if (words.slice(0, indexLastTagInFirstTagBlock + 1).some((w) => !HtmlDiff.SpecialCaseClosingTagsSet.has(w.toLowerCase()))) tagIndexToCompare = 0;
1729
761
  }
1730
762
  const openingAndClosingTagsMatch = !!openingTag && Utils_default.getTagName(openingTag) === Utils_default.getTagName(words[tagIndexToCompare]);
1731
- if (openingTag && openingAndClosingTagsMatch) {
763
+ if (!!openingTag && openingAndClosingTagsMatch) {
1732
764
  specialCaseTagInjection = "</ins>";
1733
765
  specialCaseTagInjectionIsBefore = true;
1734
766
  } else if (openingTag) this.specialTagDiffStack.push(openingTag);