@depup/vitest__utils 4.1.0-depup.0

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/diff.js ADDED
@@ -0,0 +1,2201 @@
1
+ import { plugins, format } from '@vitest/pretty-format';
2
+ import c from 'tinyrainbow';
3
+ import { stringify } from './display.js';
4
+ import { deepClone, getOwnProperties, getType as getType$1 } from './helpers.js';
5
+ import './constants.js';
6
+
7
+ /**
8
+ * Diff Match and Patch
9
+ * Copyright 2018 The diff-match-patch Authors.
10
+ * https://github.com/google/diff-match-patch
11
+ *
12
+ * Licensed under the Apache License, Version 2.0 (the "License");
13
+ * you may not use this file except in compliance with the License.
14
+ * You may obtain a copy of the License at
15
+ *
16
+ * http://www.apache.org/licenses/LICENSE-2.0
17
+ *
18
+ * Unless required by applicable law or agreed to in writing, software
19
+ * distributed under the License is distributed on an "AS IS" BASIS,
20
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ * See the License for the specific language governing permissions and
22
+ * limitations under the License.
23
+ */
24
+ /**
25
+ * @fileoverview Computes the difference between two texts to create a patch.
26
+ * Applies the patch onto another text, allowing for errors.
27
+ * @author fraser@google.com (Neil Fraser)
28
+ */
29
+ /**
30
+ * CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file:
31
+ *
32
+ * 1. Delete anything not needed to use diff_cleanupSemantic method
33
+ * 2. Convert from prototype properties to var declarations
34
+ * 3. Convert Diff to class from constructor and prototype
35
+ * 4. Add type annotations for arguments and return values
36
+ * 5. Add exports
37
+ */
38
+ /**
39
+ * The data structure representing a diff is an array of tuples:
40
+ * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
41
+ * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
42
+ */
43
+ const DIFF_DELETE = -1;
44
+ const DIFF_INSERT = 1;
45
+ const DIFF_EQUAL = 0;
46
+ /**
47
+ * Class representing one diff tuple.
48
+ * Attempts to look like a two-element array (which is what this used to be).
49
+ * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL.
50
+ * @param {string} text Text to be deleted, inserted, or retained.
51
+ * @constructor
52
+ */
53
+ class Diff {
54
+ 0;
55
+ 1;
56
+ constructor(op, text) {
57
+ this[0] = op;
58
+ this[1] = text;
59
+ }
60
+ }
61
+ /**
62
+ * Determine the common prefix of two strings.
63
+ * @param {string} text1 First string.
64
+ * @param {string} text2 Second string.
65
+ * @return {number} The number of characters common to the start of each
66
+ * string.
67
+ */
68
+ function diff_commonPrefix(text1, text2) {
69
+ // Quick check for common null cases.
70
+ if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
71
+ return 0;
72
+ }
73
+ // Binary search.
74
+ // Performance analysis: https://neil.fraser.name/news/2007/10/09/
75
+ let pointermin = 0;
76
+ let pointermax = Math.min(text1.length, text2.length);
77
+ let pointermid = pointermax;
78
+ let pointerstart = 0;
79
+ while (pointermin < pointermid) {
80
+ if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) {
81
+ pointermin = pointermid;
82
+ pointerstart = pointermin;
83
+ } else {
84
+ pointermax = pointermid;
85
+ }
86
+ pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
87
+ }
88
+ return pointermid;
89
+ }
90
+ /**
91
+ * Determine the common suffix of two strings.
92
+ * @param {string} text1 First string.
93
+ * @param {string} text2 Second string.
94
+ * @return {number} The number of characters common to the end of each string.
95
+ */
96
+ function diff_commonSuffix(text1, text2) {
97
+ // Quick check for common null cases.
98
+ if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
99
+ return 0;
100
+ }
101
+ // Binary search.
102
+ // Performance analysis: https://neil.fraser.name/news/2007/10/09/
103
+ let pointermin = 0;
104
+ let pointermax = Math.min(text1.length, text2.length);
105
+ let pointermid = pointermax;
106
+ let pointerend = 0;
107
+ while (pointermin < pointermid) {
108
+ if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) {
109
+ pointermin = pointermid;
110
+ pointerend = pointermin;
111
+ } else {
112
+ pointermax = pointermid;
113
+ }
114
+ pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
115
+ }
116
+ return pointermid;
117
+ }
118
+ /**
119
+ * Determine if the suffix of one string is the prefix of another.
120
+ * @param {string} text1 First string.
121
+ * @param {string} text2 Second string.
122
+ * @return {number} The number of characters common to the end of the first
123
+ * string and the start of the second string.
124
+ * @private
125
+ */
126
+ function diff_commonOverlap_(text1, text2) {
127
+ // Cache the text lengths to prevent multiple calls.
128
+ const text1_length = text1.length;
129
+ const text2_length = text2.length;
130
+ // Eliminate the null case.
131
+ if (text1_length === 0 || text2_length === 0) {
132
+ return 0;
133
+ }
134
+ // Truncate the longer string.
135
+ if (text1_length > text2_length) {
136
+ text1 = text1.substring(text1_length - text2_length);
137
+ } else if (text1_length < text2_length) {
138
+ text2 = text2.substring(0, text1_length);
139
+ }
140
+ const text_length = Math.min(text1_length, text2_length);
141
+ // Quick check for the worst case.
142
+ if (text1 === text2) {
143
+ return text_length;
144
+ }
145
+ // Start by looking for a single character match
146
+ // and increase length until no match is found.
147
+ // Performance analysis: https://neil.fraser.name/news/2010/11/04/
148
+ let best = 0;
149
+ let length = 1;
150
+ while (true) {
151
+ const pattern = text1.substring(text_length - length);
152
+ const found = text2.indexOf(pattern);
153
+ if (found === -1) {
154
+ return best;
155
+ }
156
+ length += found;
157
+ if (found === 0 || text1.substring(text_length - length) === text2.substring(0, length)) {
158
+ best = length;
159
+ length++;
160
+ }
161
+ }
162
+ }
163
+ /**
164
+ * Reduce the number of edits by eliminating semantically trivial equalities.
165
+ * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
166
+ */
167
+ function diff_cleanupSemantic(diffs) {
168
+ let changes = false;
169
+ const equalities = [];
170
+ let equalitiesLength = 0;
171
+ /** @type {?string} */
172
+ let lastEquality = null;
173
+ // Always equal to diffs[equalities[equalitiesLength - 1]][1]
174
+ let pointer = 0;
175
+ // Number of characters that changed prior to the equality.
176
+ let length_insertions1 = 0;
177
+ let length_deletions1 = 0;
178
+ // Number of characters that changed after the equality.
179
+ let length_insertions2 = 0;
180
+ let length_deletions2 = 0;
181
+ while (pointer < diffs.length) {
182
+ if (diffs[pointer][0] === DIFF_EQUAL) {
183
+ // Equality found.
184
+ equalities[equalitiesLength++] = pointer;
185
+ length_insertions1 = length_insertions2;
186
+ length_deletions1 = length_deletions2;
187
+ length_insertions2 = 0;
188
+ length_deletions2 = 0;
189
+ lastEquality = diffs[pointer][1];
190
+ } else {
191
+ // An insertion or deletion.
192
+ if (diffs[pointer][0] === DIFF_INSERT) {
193
+ length_insertions2 += diffs[pointer][1].length;
194
+ } else {
195
+ length_deletions2 += diffs[pointer][1].length;
196
+ }
197
+ // Eliminate an equality that is smaller or equal to the edits on both
198
+ // sides of it.
199
+ if (lastEquality && lastEquality.length <= Math.max(length_insertions1, length_deletions1) && lastEquality.length <= Math.max(length_insertions2, length_deletions2)) {
200
+ // Duplicate record.
201
+ diffs.splice(equalities[equalitiesLength - 1], 0, new Diff(DIFF_DELETE, lastEquality));
202
+ // Change second copy to insert.
203
+ diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
204
+ // Throw away the equality we just deleted.
205
+ equalitiesLength--;
206
+ // Throw away the previous equality (it needs to be reevaluated).
207
+ equalitiesLength--;
208
+ pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
209
+ length_insertions1 = 0;
210
+ length_deletions1 = 0;
211
+ length_insertions2 = 0;
212
+ length_deletions2 = 0;
213
+ lastEquality = null;
214
+ changes = true;
215
+ }
216
+ }
217
+ pointer++;
218
+ }
219
+ // Normalize the diff.
220
+ if (changes) {
221
+ diff_cleanupMerge(diffs);
222
+ }
223
+ diff_cleanupSemanticLossless(diffs);
224
+ // Find any overlaps between deletions and insertions.
225
+ // e.g: <del>abcxxx</del><ins>xxxdef</ins>
226
+ // -> <del>abc</del>xxx<ins>def</ins>
227
+ // e.g: <del>xxxabc</del><ins>defxxx</ins>
228
+ // -> <ins>def</ins>xxx<del>abc</del>
229
+ // Only extract an overlap if it is as big as the edit ahead or behind it.
230
+ pointer = 1;
231
+ while (pointer < diffs.length) {
232
+ if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
233
+ const deletion = diffs[pointer - 1][1];
234
+ const insertion = diffs[pointer][1];
235
+ const overlap_length1 = diff_commonOverlap_(deletion, insertion);
236
+ const overlap_length2 = diff_commonOverlap_(insertion, deletion);
237
+ if (overlap_length1 >= overlap_length2) {
238
+ if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) {
239
+ // Overlap found. Insert an equality and trim the surrounding edits.
240
+ diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1)));
241
+ diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1);
242
+ diffs[pointer + 1][1] = insertion.substring(overlap_length1);
243
+ pointer++;
244
+ }
245
+ } else {
246
+ if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) {
247
+ // Reverse overlap found.
248
+ // Insert an equality and swap and trim the surrounding edits.
249
+ diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2)));
250
+ diffs[pointer - 1][0] = DIFF_INSERT;
251
+ diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2);
252
+ diffs[pointer + 1][0] = DIFF_DELETE;
253
+ diffs[pointer + 1][1] = deletion.substring(overlap_length2);
254
+ pointer++;
255
+ }
256
+ }
257
+ pointer++;
258
+ }
259
+ pointer++;
260
+ }
261
+ }
262
+ // Define some regex patterns for matching boundaries.
263
+ const nonAlphaNumericRegex_ = /[^a-z0-9]/i;
264
+ const whitespaceRegex_ = /\s/;
265
+ const linebreakRegex_ = /[\r\n]/;
266
+ const blanklineEndRegex_ = /\n\r?\n$/;
267
+ const blanklineStartRegex_ = /^\r?\n\r?\n/;
268
+ /**
269
+ * Look for single edits surrounded on both sides by equalities
270
+ * which can be shifted sideways to align the edit to a word boundary.
271
+ * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
272
+ * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
273
+ */
274
+ function diff_cleanupSemanticLossless(diffs) {
275
+ let pointer = 1;
276
+ // Intentionally ignore the first and last element (don't need checking).
277
+ while (pointer < diffs.length - 1) {
278
+ if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
279
+ // This is a single edit surrounded by equalities.
280
+ let equality1 = diffs[pointer - 1][1];
281
+ let edit = diffs[pointer][1];
282
+ let equality2 = diffs[pointer + 1][1];
283
+ // First, shift the edit as far left as possible.
284
+ const commonOffset = diff_commonSuffix(equality1, edit);
285
+ if (commonOffset) {
286
+ const commonString = edit.substring(edit.length - commonOffset);
287
+ equality1 = equality1.substring(0, equality1.length - commonOffset);
288
+ edit = commonString + edit.substring(0, edit.length - commonOffset);
289
+ equality2 = commonString + equality2;
290
+ }
291
+ // Second, step character by character right, looking for the best fit.
292
+ let bestEquality1 = equality1;
293
+ let bestEdit = edit;
294
+ let bestEquality2 = equality2;
295
+ let bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2);
296
+ while (edit.charAt(0) === equality2.charAt(0)) {
297
+ equality1 += edit.charAt(0);
298
+ edit = edit.substring(1) + equality2.charAt(0);
299
+ equality2 = equality2.substring(1);
300
+ const score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2);
301
+ // The >= encourages trailing rather than leading whitespace on edits.
302
+ if (score >= bestScore) {
303
+ bestScore = score;
304
+ bestEquality1 = equality1;
305
+ bestEdit = edit;
306
+ bestEquality2 = equality2;
307
+ }
308
+ }
309
+ if (diffs[pointer - 1][1] !== bestEquality1) {
310
+ // We have an improvement, save it back to the diff.
311
+ if (bestEquality1) {
312
+ diffs[pointer - 1][1] = bestEquality1;
313
+ } else {
314
+ diffs.splice(pointer - 1, 1);
315
+ pointer--;
316
+ }
317
+ diffs[pointer][1] = bestEdit;
318
+ if (bestEquality2) {
319
+ diffs[pointer + 1][1] = bestEquality2;
320
+ } else {
321
+ diffs.splice(pointer + 1, 1);
322
+ pointer--;
323
+ }
324
+ }
325
+ }
326
+ pointer++;
327
+ }
328
+ }
329
+ /**
330
+ * Reorder and merge like edit sections. Merge equalities.
331
+ * Any edit section can move as long as it doesn't cross an equality.
332
+ * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
333
+ */
334
+ function diff_cleanupMerge(diffs) {
335
+ // Add a dummy entry at the end.
336
+ diffs.push(new Diff(DIFF_EQUAL, ""));
337
+ let pointer = 0;
338
+ let count_delete = 0;
339
+ let count_insert = 0;
340
+ let text_delete = "";
341
+ let text_insert = "";
342
+ let commonlength;
343
+ while (pointer < diffs.length) {
344
+ switch (diffs[pointer][0]) {
345
+ case DIFF_INSERT:
346
+ count_insert++;
347
+ text_insert += diffs[pointer][1];
348
+ pointer++;
349
+ break;
350
+ case DIFF_DELETE:
351
+ count_delete++;
352
+ text_delete += diffs[pointer][1];
353
+ pointer++;
354
+ break;
355
+ case DIFF_EQUAL:
356
+ // Upon reaching an equality, check for prior redundancies.
357
+ if (count_delete + count_insert > 1) {
358
+ if (count_delete !== 0 && count_insert !== 0) {
359
+ // Factor out any common prefixes.
360
+ commonlength = diff_commonPrefix(text_insert, text_delete);
361
+ if (commonlength !== 0) {
362
+ if (pointer - count_delete - count_insert > 0 && diffs[pointer - count_delete - count_insert - 1][0] === DIFF_EQUAL) {
363
+ diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength);
364
+ } else {
365
+ diffs.splice(0, 0, new Diff(DIFF_EQUAL, text_insert.substring(0, commonlength)));
366
+ pointer++;
367
+ }
368
+ text_insert = text_insert.substring(commonlength);
369
+ text_delete = text_delete.substring(commonlength);
370
+ }
371
+ // Factor out any common suffixes.
372
+ commonlength = diff_commonSuffix(text_insert, text_delete);
373
+ if (commonlength !== 0) {
374
+ diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1];
375
+ text_insert = text_insert.substring(0, text_insert.length - commonlength);
376
+ text_delete = text_delete.substring(0, text_delete.length - commonlength);
377
+ }
378
+ }
379
+ // Delete the offending records and add the merged ones.
380
+ pointer -= count_delete + count_insert;
381
+ diffs.splice(pointer, count_delete + count_insert);
382
+ if (text_delete.length) {
383
+ diffs.splice(pointer, 0, new Diff(DIFF_DELETE, text_delete));
384
+ pointer++;
385
+ }
386
+ if (text_insert.length) {
387
+ diffs.splice(pointer, 0, new Diff(DIFF_INSERT, text_insert));
388
+ pointer++;
389
+ }
390
+ pointer++;
391
+ } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
392
+ // Merge this equality with the previous one.
393
+ diffs[pointer - 1][1] += diffs[pointer][1];
394
+ diffs.splice(pointer, 1);
395
+ } else {
396
+ pointer++;
397
+ }
398
+ count_insert = 0;
399
+ count_delete = 0;
400
+ text_delete = "";
401
+ text_insert = "";
402
+ break;
403
+ }
404
+ }
405
+ if (diffs.at(-1)?.[1] === "") {
406
+ diffs.pop();
407
+ }
408
+ // Second pass: look for single edits surrounded on both sides by equalities
409
+ // which can be shifted sideways to eliminate an equality.
410
+ // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
411
+ let changes = false;
412
+ pointer = 1;
413
+ // Intentionally ignore the first and last element (don't need checking).
414
+ while (pointer < diffs.length - 1) {
415
+ if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
416
+ // This is a single edit surrounded by equalities.
417
+ if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) {
418
+ // Shift the edit over the previous equality.
419
+ diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);
420
+ diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
421
+ diffs.splice(pointer - 1, 1);
422
+ changes = true;
423
+ } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {
424
+ // Shift the edit over the next equality.
425
+ diffs[pointer - 1][1] += diffs[pointer + 1][1];
426
+ diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];
427
+ diffs.splice(pointer + 1, 1);
428
+ changes = true;
429
+ }
430
+ }
431
+ pointer++;
432
+ }
433
+ // If shifts were made, the diff needs reordering and another shift sweep.
434
+ if (changes) {
435
+ diff_cleanupMerge(diffs);
436
+ }
437
+ }
438
+ /**
439
+ * Given two strings, compute a score representing whether the internal
440
+ * boundary falls on logical boundaries.
441
+ * Scores range from 6 (best) to 0 (worst).
442
+ * Closure, but does not reference any external variables.
443
+ * @param {string} one First string.
444
+ * @param {string} two Second string.
445
+ * @return {number} The score.
446
+ * @private
447
+ */
448
+ function diff_cleanupSemanticScore_(one, two) {
449
+ if (!one || !two) {
450
+ // Edges are the best.
451
+ return 6;
452
+ }
453
+ // Each port of this function behaves slightly differently due to
454
+ // subtle differences in each language's definition of things like
455
+ // 'whitespace'. Since this function's purpose is largely cosmetic,
456
+ // the choice has been made to use each language's native features
457
+ // rather than force total conformity.
458
+ const char1 = one.charAt(one.length - 1);
459
+ const char2 = two.charAt(0);
460
+ const nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_);
461
+ const nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_);
462
+ const whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_);
463
+ const whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_);
464
+ const lineBreak1 = whitespace1 && char1.match(linebreakRegex_);
465
+ const lineBreak2 = whitespace2 && char2.match(linebreakRegex_);
466
+ const blankLine1 = lineBreak1 && one.match(blanklineEndRegex_);
467
+ const blankLine2 = lineBreak2 && two.match(blanklineStartRegex_);
468
+ if (blankLine1 || blankLine2) {
469
+ // Five points for blank lines.
470
+ return 5;
471
+ } else if (lineBreak1 || lineBreak2) {
472
+ // Four points for line breaks.
473
+ return 4;
474
+ } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {
475
+ // Three points for end of sentences.
476
+ return 3;
477
+ } else if (whitespace1 || whitespace2) {
478
+ // Two points for whitespace.
479
+ return 2;
480
+ } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {
481
+ // One point for non-alphanumeric.
482
+ return 1;
483
+ }
484
+ return 0;
485
+ }
486
+
487
+ /**
488
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
489
+ *
490
+ * This source code is licensed under the MIT license found in the
491
+ * LICENSE file in the root directory of this source tree.
492
+ */
493
+ const NO_DIFF_MESSAGE = "Compared values have no visual difference.";
494
+ const SIMILAR_MESSAGE = "Compared values serialize to the same structure.\n" + "Printing internal object structure without calling `toJSON` instead.";
495
+
496
+ function getDefaultExportFromCjs(x) {
497
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
498
+ }
499
+
500
+ var build = {};
501
+
502
+ var hasRequiredBuild;
503
+
504
+ function requireBuild () {
505
+ if (hasRequiredBuild) return build;
506
+ hasRequiredBuild = 1;
507
+
508
+ Object.defineProperty(build, '__esModule', {
509
+ value: true
510
+ });
511
+ build.default = diffSequence;
512
+ /**
513
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
514
+ *
515
+ * This source code is licensed under the MIT license found in the
516
+ * LICENSE file in the root directory of this source tree.
517
+ *
518
+ */
519
+
520
+ // This diff-sequences package implements the linear space variation in
521
+ // An O(ND) Difference Algorithm and Its Variations by Eugene W. Myers
522
+
523
+ // Relationship in notation between Myers paper and this package:
524
+ // A is a
525
+ // N is aLength, aEnd - aStart, and so on
526
+ // x is aIndex, aFirst, aLast, and so on
527
+ // B is b
528
+ // M is bLength, bEnd - bStart, and so on
529
+ // y is bIndex, bFirst, bLast, and so on
530
+ // Δ = N - M is negative of baDeltaLength = bLength - aLength
531
+ // D is d
532
+ // k is kF
533
+ // k + Δ is kF = kR - baDeltaLength
534
+ // V is aIndexesF or aIndexesR (see comment below about Indexes type)
535
+ // index intervals [1, N] and [1, M] are [0, aLength) and [0, bLength)
536
+ // starting point in forward direction (0, 0) is (-1, -1)
537
+ // starting point in reverse direction (N + 1, M + 1) is (aLength, bLength)
538
+
539
+ // The “edit graph” for sequences a and b corresponds to items:
540
+ // in a on the horizontal axis
541
+ // in b on the vertical axis
542
+ //
543
+ // Given a-coordinate of a point in a diagonal, you can compute b-coordinate.
544
+ //
545
+ // Forward diagonals kF:
546
+ // zero diagonal intersects top left corner
547
+ // positive diagonals intersect top edge
548
+ // negative diagonals insersect left edge
549
+ //
550
+ // Reverse diagonals kR:
551
+ // zero diagonal intersects bottom right corner
552
+ // positive diagonals intersect right edge
553
+ // negative diagonals intersect bottom edge
554
+
555
+ // The graph contains a directed acyclic graph of edges:
556
+ // horizontal: delete an item from a
557
+ // vertical: insert an item from b
558
+ // diagonal: common item in a and b
559
+ //
560
+ // The algorithm solves dual problems in the graph analogy:
561
+ // Find longest common subsequence: path with maximum number of diagonal edges
562
+ // Find shortest edit script: path with minimum number of non-diagonal edges
563
+
564
+ // Input callback function compares items at indexes in the sequences.
565
+
566
+ // Output callback function receives the number of adjacent items
567
+ // and starting indexes of each common subsequence.
568
+ // Either original functions or wrapped to swap indexes if graph is transposed.
569
+ // Indexes in sequence a of last point of forward or reverse paths in graph.
570
+ // Myers algorithm indexes by diagonal k which for negative is bad deopt in V8.
571
+ // This package indexes by iF and iR which are greater than or equal to zero.
572
+ // and also updates the index arrays in place to cut memory in half.
573
+ // kF = 2 * iF - d
574
+ // kR = d - 2 * iR
575
+ // Division of index intervals in sequences a and b at the middle change.
576
+ // Invariant: intervals do not have common items at the start or end.
577
+ const pkg = 'diff-sequences'; // for error messages
578
+ const NOT_YET_SET = 0; // small int instead of undefined to avoid deopt in V8
579
+
580
+ // Return the number of common items that follow in forward direction.
581
+ // The length of what Myers paper calls a “snake” in a forward path.
582
+ const countCommonItemsF = (aIndex, aEnd, bIndex, bEnd, isCommon) => {
583
+ let nCommon = 0;
584
+ while (aIndex < aEnd && bIndex < bEnd && isCommon(aIndex, bIndex)) {
585
+ aIndex += 1;
586
+ bIndex += 1;
587
+ nCommon += 1;
588
+ }
589
+ return nCommon;
590
+ };
591
+
592
+ // Return the number of common items that precede in reverse direction.
593
+ // The length of what Myers paper calls a “snake” in a reverse path.
594
+ const countCommonItemsR = (aStart, aIndex, bStart, bIndex, isCommon) => {
595
+ let nCommon = 0;
596
+ while (aStart <= aIndex && bStart <= bIndex && isCommon(aIndex, bIndex)) {
597
+ aIndex -= 1;
598
+ bIndex -= 1;
599
+ nCommon += 1;
600
+ }
601
+ return nCommon;
602
+ };
603
+
604
+ // A simple function to extend forward paths from (d - 1) to d changes
605
+ // when forward and reverse paths cannot yet overlap.
606
+ const extendPathsF = (
607
+ d,
608
+ aEnd,
609
+ bEnd,
610
+ bF,
611
+ isCommon,
612
+ aIndexesF,
613
+ iMaxF // return the value because optimization might decrease it
614
+ ) => {
615
+ // Unroll the first iteration.
616
+ let iF = 0;
617
+ let kF = -d; // kF = 2 * iF - d
618
+ let aFirst = aIndexesF[iF]; // in first iteration always insert
619
+ let aIndexPrev1 = aFirst; // prev value of [iF - 1] in next iteration
620
+ aIndexesF[iF] += countCommonItemsF(
621
+ aFirst + 1,
622
+ aEnd,
623
+ bF + aFirst - kF + 1,
624
+ bEnd,
625
+ isCommon
626
+ );
627
+
628
+ // Optimization: skip diagonals in which paths cannot ever overlap.
629
+ const nF = d < iMaxF ? d : iMaxF;
630
+
631
+ // The diagonals kF are odd when d is odd and even when d is even.
632
+ for (iF += 1, kF += 2; iF <= nF; iF += 1, kF += 2) {
633
+ // To get first point of path segment, move one change in forward direction
634
+ // from last point of previous path segment in an adjacent diagonal.
635
+ // In last possible iteration when iF === d and kF === d always delete.
636
+ if (iF !== d && aIndexPrev1 < aIndexesF[iF]) {
637
+ aFirst = aIndexesF[iF]; // vertical to insert from b
638
+ } else {
639
+ aFirst = aIndexPrev1 + 1; // horizontal to delete from a
640
+
641
+ if (aEnd <= aFirst) {
642
+ // Optimization: delete moved past right of graph.
643
+ return iF - 1;
644
+ }
645
+ }
646
+
647
+ // To get last point of path segment, move along diagonal of common items.
648
+ aIndexPrev1 = aIndexesF[iF];
649
+ aIndexesF[iF] =
650
+ aFirst +
651
+ countCommonItemsF(aFirst + 1, aEnd, bF + aFirst - kF + 1, bEnd, isCommon);
652
+ }
653
+ return iMaxF;
654
+ };
655
+
656
+ // A simple function to extend reverse paths from (d - 1) to d changes
657
+ // when reverse and forward paths cannot yet overlap.
658
+ const extendPathsR = (
659
+ d,
660
+ aStart,
661
+ bStart,
662
+ bR,
663
+ isCommon,
664
+ aIndexesR,
665
+ iMaxR // return the value because optimization might decrease it
666
+ ) => {
667
+ // Unroll the first iteration.
668
+ let iR = 0;
669
+ let kR = d; // kR = d - 2 * iR
670
+ let aFirst = aIndexesR[iR]; // in first iteration always insert
671
+ let aIndexPrev1 = aFirst; // prev value of [iR - 1] in next iteration
672
+ aIndexesR[iR] -= countCommonItemsR(
673
+ aStart,
674
+ aFirst - 1,
675
+ bStart,
676
+ bR + aFirst - kR - 1,
677
+ isCommon
678
+ );
679
+
680
+ // Optimization: skip diagonals in which paths cannot ever overlap.
681
+ const nR = d < iMaxR ? d : iMaxR;
682
+
683
+ // The diagonals kR are odd when d is odd and even when d is even.
684
+ for (iR += 1, kR -= 2; iR <= nR; iR += 1, kR -= 2) {
685
+ // To get first point of path segment, move one change in reverse direction
686
+ // from last point of previous path segment in an adjacent diagonal.
687
+ // In last possible iteration when iR === d and kR === -d always delete.
688
+ if (iR !== d && aIndexesR[iR] < aIndexPrev1) {
689
+ aFirst = aIndexesR[iR]; // vertical to insert from b
690
+ } else {
691
+ aFirst = aIndexPrev1 - 1; // horizontal to delete from a
692
+
693
+ if (aFirst < aStart) {
694
+ // Optimization: delete moved past left of graph.
695
+ return iR - 1;
696
+ }
697
+ }
698
+
699
+ // To get last point of path segment, move along diagonal of common items.
700
+ aIndexPrev1 = aIndexesR[iR];
701
+ aIndexesR[iR] =
702
+ aFirst -
703
+ countCommonItemsR(
704
+ aStart,
705
+ aFirst - 1,
706
+ bStart,
707
+ bR + aFirst - kR - 1,
708
+ isCommon
709
+ );
710
+ }
711
+ return iMaxR;
712
+ };
713
+
714
+ // A complete function to extend forward paths from (d - 1) to d changes.
715
+ // Return true if a path overlaps reverse path of (d - 1) changes in its diagonal.
716
+ const extendOverlappablePathsF = (
717
+ d,
718
+ aStart,
719
+ aEnd,
720
+ bStart,
721
+ bEnd,
722
+ isCommon,
723
+ aIndexesF,
724
+ iMaxF,
725
+ aIndexesR,
726
+ iMaxR,
727
+ division // update prop values if return true
728
+ ) => {
729
+ const bF = bStart - aStart; // bIndex = bF + aIndex - kF
730
+ const aLength = aEnd - aStart;
731
+ const bLength = bEnd - bStart;
732
+ const baDeltaLength = bLength - aLength; // kF = kR - baDeltaLength
733
+
734
+ // Range of diagonals in which forward and reverse paths might overlap.
735
+ const kMinOverlapF = -baDeltaLength - (d - 1); // -(d - 1) <= kR
736
+ const kMaxOverlapF = -baDeltaLength + (d - 1); // kR <= (d - 1)
737
+
738
+ let aIndexPrev1 = NOT_YET_SET; // prev value of [iF - 1] in next iteration
739
+
740
+ // Optimization: skip diagonals in which paths cannot ever overlap.
741
+ const nF = d < iMaxF ? d : iMaxF;
742
+
743
+ // The diagonals kF = 2 * iF - d are odd when d is odd and even when d is even.
744
+ for (let iF = 0, kF = -d; iF <= nF; iF += 1, kF += 2) {
745
+ // To get first point of path segment, move one change in forward direction
746
+ // from last point of previous path segment in an adjacent diagonal.
747
+ // In first iteration when iF === 0 and kF === -d always insert.
748
+ // In last possible iteration when iF === d and kF === d always delete.
749
+ const insert = iF === 0 || (iF !== d && aIndexPrev1 < aIndexesF[iF]);
750
+ const aLastPrev = insert ? aIndexesF[iF] : aIndexPrev1;
751
+ const aFirst = insert
752
+ ? aLastPrev // vertical to insert from b
753
+ : aLastPrev + 1; // horizontal to delete from a
754
+
755
+ // To get last point of path segment, move along diagonal of common items.
756
+ const bFirst = bF + aFirst - kF;
757
+ const nCommonF = countCommonItemsF(
758
+ aFirst + 1,
759
+ aEnd,
760
+ bFirst + 1,
761
+ bEnd,
762
+ isCommon
763
+ );
764
+ const aLast = aFirst + nCommonF;
765
+ aIndexPrev1 = aIndexesF[iF];
766
+ aIndexesF[iF] = aLast;
767
+ if (kMinOverlapF <= kF && kF <= kMaxOverlapF) {
768
+ // Solve for iR of reverse path with (d - 1) changes in diagonal kF:
769
+ // kR = kF + baDeltaLength
770
+ // kR = (d - 1) - 2 * iR
771
+ const iR = (d - 1 - (kF + baDeltaLength)) / 2;
772
+
773
+ // If this forward path overlaps the reverse path in this diagonal,
774
+ // then this is the middle change of the index intervals.
775
+ if (iR <= iMaxR && aIndexesR[iR] - 1 <= aLast) {
776
+ // Unlike the Myers algorithm which finds only the middle “snake”
777
+ // this package can find two common subsequences per division.
778
+ // Last point of previous path segment is on an adjacent diagonal.
779
+ const bLastPrev = bF + aLastPrev - (insert ? kF + 1 : kF - 1);
780
+
781
+ // Because of invariant that intervals preceding the middle change
782
+ // cannot have common items at the end,
783
+ // move in reverse direction along a diagonal of common items.
784
+ const nCommonR = countCommonItemsR(
785
+ aStart,
786
+ aLastPrev,
787
+ bStart,
788
+ bLastPrev,
789
+ isCommon
790
+ );
791
+ const aIndexPrevFirst = aLastPrev - nCommonR;
792
+ const bIndexPrevFirst = bLastPrev - nCommonR;
793
+ const aEndPreceding = aIndexPrevFirst + 1;
794
+ const bEndPreceding = bIndexPrevFirst + 1;
795
+ division.nChangePreceding = d - 1;
796
+ if (d - 1 === aEndPreceding + bEndPreceding - aStart - bStart) {
797
+ // Optimization: number of preceding changes in forward direction
798
+ // is equal to number of items in preceding interval,
799
+ // therefore it cannot contain any common items.
800
+ division.aEndPreceding = aStart;
801
+ division.bEndPreceding = bStart;
802
+ } else {
803
+ division.aEndPreceding = aEndPreceding;
804
+ division.bEndPreceding = bEndPreceding;
805
+ }
806
+ division.nCommonPreceding = nCommonR;
807
+ if (nCommonR !== 0) {
808
+ division.aCommonPreceding = aEndPreceding;
809
+ division.bCommonPreceding = bEndPreceding;
810
+ }
811
+ division.nCommonFollowing = nCommonF;
812
+ if (nCommonF !== 0) {
813
+ division.aCommonFollowing = aFirst + 1;
814
+ division.bCommonFollowing = bFirst + 1;
815
+ }
816
+ const aStartFollowing = aLast + 1;
817
+ const bStartFollowing = bFirst + nCommonF + 1;
818
+ division.nChangeFollowing = d - 1;
819
+ if (d - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing) {
820
+ // Optimization: number of changes in reverse direction
821
+ // is equal to number of items in following interval,
822
+ // therefore it cannot contain any common items.
823
+ division.aStartFollowing = aEnd;
824
+ division.bStartFollowing = bEnd;
825
+ } else {
826
+ division.aStartFollowing = aStartFollowing;
827
+ division.bStartFollowing = bStartFollowing;
828
+ }
829
+ return true;
830
+ }
831
+ }
832
+ }
833
+ return false;
834
+ };
835
+
836
+ // A complete function to extend reverse paths from (d - 1) to d changes.
837
+ // Return true if a path overlaps forward path of d changes in its diagonal.
838
+ const extendOverlappablePathsR = (
839
+ d,
840
+ aStart,
841
+ aEnd,
842
+ bStart,
843
+ bEnd,
844
+ isCommon,
845
+ aIndexesF,
846
+ iMaxF,
847
+ aIndexesR,
848
+ iMaxR,
849
+ division // update prop values if return true
850
+ ) => {
851
+ const bR = bEnd - aEnd; // bIndex = bR + aIndex - kR
852
+ const aLength = aEnd - aStart;
853
+ const bLength = bEnd - bStart;
854
+ const baDeltaLength = bLength - aLength; // kR = kF + baDeltaLength
855
+
856
+ // Range of diagonals in which forward and reverse paths might overlap.
857
+ const kMinOverlapR = baDeltaLength - d; // -d <= kF
858
+ const kMaxOverlapR = baDeltaLength + d; // kF <= d
859
+
860
+ let aIndexPrev1 = NOT_YET_SET; // prev value of [iR - 1] in next iteration
861
+
862
+ // Optimization: skip diagonals in which paths cannot ever overlap.
863
+ const nR = d < iMaxR ? d : iMaxR;
864
+
865
+ // The diagonals kR = d - 2 * iR are odd when d is odd and even when d is even.
866
+ for (let iR = 0, kR = d; iR <= nR; iR += 1, kR -= 2) {
867
+ // To get first point of path segment, move one change in reverse direction
868
+ // from last point of previous path segment in an adjacent diagonal.
869
+ // In first iteration when iR === 0 and kR === d always insert.
870
+ // In last possible iteration when iR === d and kR === -d always delete.
871
+ const insert = iR === 0 || (iR !== d && aIndexesR[iR] < aIndexPrev1);
872
+ const aLastPrev = insert ? aIndexesR[iR] : aIndexPrev1;
873
+ const aFirst = insert
874
+ ? aLastPrev // vertical to insert from b
875
+ : aLastPrev - 1; // horizontal to delete from a
876
+
877
+ // To get last point of path segment, move along diagonal of common items.
878
+ const bFirst = bR + aFirst - kR;
879
+ const nCommonR = countCommonItemsR(
880
+ aStart,
881
+ aFirst - 1,
882
+ bStart,
883
+ bFirst - 1,
884
+ isCommon
885
+ );
886
+ const aLast = aFirst - nCommonR;
887
+ aIndexPrev1 = aIndexesR[iR];
888
+ aIndexesR[iR] = aLast;
889
+ if (kMinOverlapR <= kR && kR <= kMaxOverlapR) {
890
+ // Solve for iF of forward path with d changes in diagonal kR:
891
+ // kF = kR - baDeltaLength
892
+ // kF = 2 * iF - d
893
+ const iF = (d + (kR - baDeltaLength)) / 2;
894
+
895
+ // If this reverse path overlaps the forward path in this diagonal,
896
+ // then this is a middle change of the index intervals.
897
+ if (iF <= iMaxF && aLast - 1 <= aIndexesF[iF]) {
898
+ const bLast = bFirst - nCommonR;
899
+ division.nChangePreceding = d;
900
+ if (d === aLast + bLast - aStart - bStart) {
901
+ // Optimization: number of changes in reverse direction
902
+ // is equal to number of items in preceding interval,
903
+ // therefore it cannot contain any common items.
904
+ division.aEndPreceding = aStart;
905
+ division.bEndPreceding = bStart;
906
+ } else {
907
+ division.aEndPreceding = aLast;
908
+ division.bEndPreceding = bLast;
909
+ }
910
+ division.nCommonPreceding = nCommonR;
911
+ if (nCommonR !== 0) {
912
+ // The last point of reverse path segment is start of common subsequence.
913
+ division.aCommonPreceding = aLast;
914
+ division.bCommonPreceding = bLast;
915
+ }
916
+ division.nChangeFollowing = d - 1;
917
+ if (d === 1) {
918
+ // There is no previous path segment.
919
+ division.nCommonFollowing = 0;
920
+ division.aStartFollowing = aEnd;
921
+ division.bStartFollowing = bEnd;
922
+ } else {
923
+ // Unlike the Myers algorithm which finds only the middle “snake”
924
+ // this package can find two common subsequences per division.
925
+ // Last point of previous path segment is on an adjacent diagonal.
926
+ const bLastPrev = bR + aLastPrev - (insert ? kR - 1 : kR + 1);
927
+
928
+ // Because of invariant that intervals following the middle change
929
+ // cannot have common items at the start,
930
+ // move in forward direction along a diagonal of common items.
931
+ const nCommonF = countCommonItemsF(
932
+ aLastPrev,
933
+ aEnd,
934
+ bLastPrev,
935
+ bEnd,
936
+ isCommon
937
+ );
938
+ division.nCommonFollowing = nCommonF;
939
+ if (nCommonF !== 0) {
940
+ // The last point of reverse path segment is start of common subsequence.
941
+ division.aCommonFollowing = aLastPrev;
942
+ division.bCommonFollowing = bLastPrev;
943
+ }
944
+ const aStartFollowing = aLastPrev + nCommonF; // aFirstPrev
945
+ const bStartFollowing = bLastPrev + nCommonF; // bFirstPrev
946
+
947
+ if (d - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing) {
948
+ // Optimization: number of changes in forward direction
949
+ // is equal to number of items in following interval,
950
+ // therefore it cannot contain any common items.
951
+ division.aStartFollowing = aEnd;
952
+ division.bStartFollowing = bEnd;
953
+ } else {
954
+ division.aStartFollowing = aStartFollowing;
955
+ division.bStartFollowing = bStartFollowing;
956
+ }
957
+ }
958
+ return true;
959
+ }
960
+ }
961
+ }
962
+ return false;
963
+ };
964
+
965
+ // Given index intervals and input function to compare items at indexes,
966
+ // divide at the middle change.
967
+ //
968
+ // DO NOT CALL if start === end, because interval cannot contain common items
969
+ // and because this function will throw the “no overlap” error.
970
+ const divide = (
971
+ nChange,
972
+ aStart,
973
+ aEnd,
974
+ bStart,
975
+ bEnd,
976
+ isCommon,
977
+ aIndexesF,
978
+ aIndexesR,
979
+ division // output
980
+ ) => {
981
+ const bF = bStart - aStart; // bIndex = bF + aIndex - kF
982
+ const bR = bEnd - aEnd; // bIndex = bR + aIndex - kR
983
+ const aLength = aEnd - aStart;
984
+ const bLength = bEnd - bStart;
985
+
986
+ // Because graph has square or portrait orientation,
987
+ // length difference is minimum number of items to insert from b.
988
+ // Corresponding forward and reverse diagonals in graph
989
+ // depend on length difference of the sequences:
990
+ // kF = kR - baDeltaLength
991
+ // kR = kF + baDeltaLength
992
+ const baDeltaLength = bLength - aLength;
993
+
994
+ // Optimization: max diagonal in graph intersects corner of shorter side.
995
+ let iMaxF = aLength;
996
+ let iMaxR = aLength;
997
+
998
+ // Initialize no changes yet in forward or reverse direction:
999
+ aIndexesF[0] = aStart - 1; // at open start of interval, outside closed start
1000
+ aIndexesR[0] = aEnd; // at open end of interval
1001
+
1002
+ if (baDeltaLength % 2 === 0) {
1003
+ // The number of changes in paths is 2 * d if length difference is even.
1004
+ const dMin = (nChange || baDeltaLength) / 2;
1005
+ const dMax = (aLength + bLength) / 2;
1006
+ for (let d = 1; d <= dMax; d += 1) {
1007
+ iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF);
1008
+ if (d < dMin) {
1009
+ iMaxR = extendPathsR(d, aStart, bStart, bR, isCommon, aIndexesR, iMaxR);
1010
+ } else if (
1011
+ // If a reverse path overlaps a forward path in the same diagonal,
1012
+ // return a division of the index intervals at the middle change.
1013
+ extendOverlappablePathsR(
1014
+ d,
1015
+ aStart,
1016
+ aEnd,
1017
+ bStart,
1018
+ bEnd,
1019
+ isCommon,
1020
+ aIndexesF,
1021
+ iMaxF,
1022
+ aIndexesR,
1023
+ iMaxR,
1024
+ division
1025
+ )
1026
+ ) {
1027
+ return;
1028
+ }
1029
+ }
1030
+ } else {
1031
+ // The number of changes in paths is 2 * d - 1 if length difference is odd.
1032
+ const dMin = ((nChange || baDeltaLength) + 1) / 2;
1033
+ const dMax = (aLength + bLength + 1) / 2;
1034
+
1035
+ // Unroll first half iteration so loop extends the relevant pairs of paths.
1036
+ // Because of invariant that intervals have no common items at start or end,
1037
+ // and limitation not to call divide with empty intervals,
1038
+ // therefore it cannot be called if a forward path with one change
1039
+ // would overlap a reverse path with no changes, even if dMin === 1.
1040
+ let d = 1;
1041
+ iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF);
1042
+ for (d += 1; d <= dMax; d += 1) {
1043
+ iMaxR = extendPathsR(
1044
+ d - 1,
1045
+ aStart,
1046
+ bStart,
1047
+ bR,
1048
+ isCommon,
1049
+ aIndexesR,
1050
+ iMaxR
1051
+ );
1052
+ if (d < dMin) {
1053
+ iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF);
1054
+ } else if (
1055
+ // If a forward path overlaps a reverse path in the same diagonal,
1056
+ // return a division of the index intervals at the middle change.
1057
+ extendOverlappablePathsF(
1058
+ d,
1059
+ aStart,
1060
+ aEnd,
1061
+ bStart,
1062
+ bEnd,
1063
+ isCommon,
1064
+ aIndexesF,
1065
+ iMaxF,
1066
+ aIndexesR,
1067
+ iMaxR,
1068
+ division
1069
+ )
1070
+ ) {
1071
+ return;
1072
+ }
1073
+ }
1074
+ }
1075
+
1076
+ /* istanbul ignore next */
1077
+ throw new Error(
1078
+ `${pkg}: no overlap aStart=${aStart} aEnd=${aEnd} bStart=${bStart} bEnd=${bEnd}`
1079
+ );
1080
+ };
1081
+
1082
+ // Given index intervals and input function to compare items at indexes,
1083
+ // return by output function the number of adjacent items and starting indexes
1084
+ // of each common subsequence. Divide and conquer with only linear space.
1085
+ //
1086
+ // The index intervals are half open [start, end) like array slice method.
1087
+ // DO NOT CALL if start === end, because interval cannot contain common items
1088
+ // and because divide function will throw the “no overlap” error.
1089
+ const findSubsequences = (
1090
+ nChange,
1091
+ aStart,
1092
+ aEnd,
1093
+ bStart,
1094
+ bEnd,
1095
+ transposed,
1096
+ callbacks,
1097
+ aIndexesF,
1098
+ aIndexesR,
1099
+ division // temporary memory, not input nor output
1100
+ ) => {
1101
+ if (bEnd - bStart < aEnd - aStart) {
1102
+ // Transpose graph so it has portrait instead of landscape orientation.
1103
+ // Always compare shorter to longer sequence for consistency and optimization.
1104
+ transposed = !transposed;
1105
+ if (transposed && callbacks.length === 1) {
1106
+ // Lazily wrap callback functions to swap args if graph is transposed.
1107
+ const {foundSubsequence, isCommon} = callbacks[0];
1108
+ callbacks[1] = {
1109
+ foundSubsequence: (nCommon, bCommon, aCommon) => {
1110
+ foundSubsequence(nCommon, aCommon, bCommon);
1111
+ },
1112
+ isCommon: (bIndex, aIndex) => isCommon(aIndex, bIndex)
1113
+ };
1114
+ }
1115
+ const tStart = aStart;
1116
+ const tEnd = aEnd;
1117
+ aStart = bStart;
1118
+ aEnd = bEnd;
1119
+ bStart = tStart;
1120
+ bEnd = tEnd;
1121
+ }
1122
+ const {foundSubsequence, isCommon} = callbacks[transposed ? 1 : 0];
1123
+
1124
+ // Divide the index intervals at the middle change.
1125
+ divide(
1126
+ nChange,
1127
+ aStart,
1128
+ aEnd,
1129
+ bStart,
1130
+ bEnd,
1131
+ isCommon,
1132
+ aIndexesF,
1133
+ aIndexesR,
1134
+ division
1135
+ );
1136
+ const {
1137
+ nChangePreceding,
1138
+ aEndPreceding,
1139
+ bEndPreceding,
1140
+ nCommonPreceding,
1141
+ aCommonPreceding,
1142
+ bCommonPreceding,
1143
+ nCommonFollowing,
1144
+ aCommonFollowing,
1145
+ bCommonFollowing,
1146
+ nChangeFollowing,
1147
+ aStartFollowing,
1148
+ bStartFollowing
1149
+ } = division;
1150
+
1151
+ // Unless either index interval is empty, they might contain common items.
1152
+ if (aStart < aEndPreceding && bStart < bEndPreceding) {
1153
+ // Recursely find and return common subsequences preceding the division.
1154
+ findSubsequences(
1155
+ nChangePreceding,
1156
+ aStart,
1157
+ aEndPreceding,
1158
+ bStart,
1159
+ bEndPreceding,
1160
+ transposed,
1161
+ callbacks,
1162
+ aIndexesF,
1163
+ aIndexesR,
1164
+ division
1165
+ );
1166
+ }
1167
+
1168
+ // Return common subsequences that are adjacent to the middle change.
1169
+ if (nCommonPreceding !== 0) {
1170
+ foundSubsequence(nCommonPreceding, aCommonPreceding, bCommonPreceding);
1171
+ }
1172
+ if (nCommonFollowing !== 0) {
1173
+ foundSubsequence(nCommonFollowing, aCommonFollowing, bCommonFollowing);
1174
+ }
1175
+
1176
+ // Unless either index interval is empty, they might contain common items.
1177
+ if (aStartFollowing < aEnd && bStartFollowing < bEnd) {
1178
+ // Recursely find and return common subsequences following the division.
1179
+ findSubsequences(
1180
+ nChangeFollowing,
1181
+ aStartFollowing,
1182
+ aEnd,
1183
+ bStartFollowing,
1184
+ bEnd,
1185
+ transposed,
1186
+ callbacks,
1187
+ aIndexesF,
1188
+ aIndexesR,
1189
+ division
1190
+ );
1191
+ }
1192
+ };
1193
+ const validateLength = (name, arg) => {
1194
+ if (typeof arg !== 'number') {
1195
+ throw new TypeError(`${pkg}: ${name} typeof ${typeof arg} is not a number`);
1196
+ }
1197
+ if (!Number.isSafeInteger(arg)) {
1198
+ throw new RangeError(`${pkg}: ${name} value ${arg} is not a safe integer`);
1199
+ }
1200
+ if (arg < 0) {
1201
+ throw new RangeError(`${pkg}: ${name} value ${arg} is a negative integer`);
1202
+ }
1203
+ };
1204
+ const validateCallback = (name, arg) => {
1205
+ const type = typeof arg;
1206
+ if (type !== 'function') {
1207
+ throw new TypeError(`${pkg}: ${name} typeof ${type} is not a function`);
1208
+ }
1209
+ };
1210
+
1211
+ // Compare items in two sequences to find a longest common subsequence.
1212
+ // Given lengths of sequences and input function to compare items at indexes,
1213
+ // return by output function the number of adjacent items and starting indexes
1214
+ // of each common subsequence.
1215
+ function diffSequence(aLength, bLength, isCommon, foundSubsequence) {
1216
+ validateLength('aLength', aLength);
1217
+ validateLength('bLength', bLength);
1218
+ validateCallback('isCommon', isCommon);
1219
+ validateCallback('foundSubsequence', foundSubsequence);
1220
+
1221
+ // Count common items from the start in the forward direction.
1222
+ const nCommonF = countCommonItemsF(0, aLength, 0, bLength, isCommon);
1223
+ if (nCommonF !== 0) {
1224
+ foundSubsequence(nCommonF, 0, 0);
1225
+ }
1226
+
1227
+ // Unless both sequences consist of common items only,
1228
+ // find common items in the half-trimmed index intervals.
1229
+ if (aLength !== nCommonF || bLength !== nCommonF) {
1230
+ // Invariant: intervals do not have common items at the start.
1231
+ // The start of an index interval is closed like array slice method.
1232
+ const aStart = nCommonF;
1233
+ const bStart = nCommonF;
1234
+
1235
+ // Count common items from the end in the reverse direction.
1236
+ const nCommonR = countCommonItemsR(
1237
+ aStart,
1238
+ aLength - 1,
1239
+ bStart,
1240
+ bLength - 1,
1241
+ isCommon
1242
+ );
1243
+
1244
+ // Invariant: intervals do not have common items at the end.
1245
+ // The end of an index interval is open like array slice method.
1246
+ const aEnd = aLength - nCommonR;
1247
+ const bEnd = bLength - nCommonR;
1248
+
1249
+ // Unless one sequence consists of common items only,
1250
+ // therefore the other trimmed index interval consists of changes only,
1251
+ // find common items in the trimmed index intervals.
1252
+ const nCommonFR = nCommonF + nCommonR;
1253
+ if (aLength !== nCommonFR && bLength !== nCommonFR) {
1254
+ const nChange = 0; // number of change items is not yet known
1255
+ const transposed = false; // call the original unwrapped functions
1256
+ const callbacks = [
1257
+ {
1258
+ foundSubsequence,
1259
+ isCommon
1260
+ }
1261
+ ];
1262
+
1263
+ // Indexes in sequence a of last points in furthest reaching paths
1264
+ // from outside the start at top left in the forward direction:
1265
+ const aIndexesF = [NOT_YET_SET];
1266
+ // from the end at bottom right in the reverse direction:
1267
+ const aIndexesR = [NOT_YET_SET];
1268
+
1269
+ // Initialize one object as output of all calls to divide function.
1270
+ const division = {
1271
+ aCommonFollowing: NOT_YET_SET,
1272
+ aCommonPreceding: NOT_YET_SET,
1273
+ aEndPreceding: NOT_YET_SET,
1274
+ aStartFollowing: NOT_YET_SET,
1275
+ bCommonFollowing: NOT_YET_SET,
1276
+ bCommonPreceding: NOT_YET_SET,
1277
+ bEndPreceding: NOT_YET_SET,
1278
+ bStartFollowing: NOT_YET_SET,
1279
+ nChangeFollowing: NOT_YET_SET,
1280
+ nChangePreceding: NOT_YET_SET,
1281
+ nCommonFollowing: NOT_YET_SET,
1282
+ nCommonPreceding: NOT_YET_SET
1283
+ };
1284
+
1285
+ // Find and return common subsequences in the trimmed index intervals.
1286
+ findSubsequences(
1287
+ nChange,
1288
+ aStart,
1289
+ aEnd,
1290
+ bStart,
1291
+ bEnd,
1292
+ transposed,
1293
+ callbacks,
1294
+ aIndexesF,
1295
+ aIndexesR,
1296
+ division
1297
+ );
1298
+ }
1299
+ if (nCommonR !== 0) {
1300
+ foundSubsequence(nCommonR, aEnd, bEnd);
1301
+ }
1302
+ }
1303
+ }
1304
+ return build;
1305
+ }
1306
+
1307
+ var buildExports = /*@__PURE__*/ requireBuild();
1308
+ var diffSequences = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
1309
+
1310
+ function formatTrailingSpaces(line, trailingSpaceFormatter) {
1311
+ return line.replace(/\s+$/, (match) => trailingSpaceFormatter(match));
1312
+ }
1313
+ function printDiffLine(line, isFirstOrLast, color, indicator, trailingSpaceFormatter, emptyFirstOrLastLinePlaceholder) {
1314
+ return line.length !== 0 ? color(`${indicator} ${formatTrailingSpaces(line, trailingSpaceFormatter)}`) : indicator !== " " ? color(indicator) : isFirstOrLast && emptyFirstOrLastLinePlaceholder.length !== 0 ? color(`${indicator} ${emptyFirstOrLastLinePlaceholder}`) : "";
1315
+ }
1316
+ function printDeleteLine(line, isFirstOrLast, { aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) {
1317
+ return printDiffLine(line, isFirstOrLast, aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder);
1318
+ }
1319
+ function printInsertLine(line, isFirstOrLast, { bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) {
1320
+ return printDiffLine(line, isFirstOrLast, bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder);
1321
+ }
1322
+ function printCommonLine(line, isFirstOrLast, { commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) {
1323
+ return printDiffLine(line, isFirstOrLast, commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder);
1324
+ }
1325
+ // In GNU diff format, indexes are one-based instead of zero-based.
1326
+ function createPatchMark(aStart, aEnd, bStart, bEnd, { patchColor }) {
1327
+ return patchColor(`@@ -${aStart + 1},${aEnd - aStart} +${bStart + 1},${bEnd - bStart} @@`);
1328
+ }
1329
+ // jest --no-expand
1330
+ //
1331
+ // Given array of aligned strings with inverse highlight formatting,
1332
+ // return joined lines with diff formatting (and patch marks, if needed).
1333
+ function joinAlignedDiffsNoExpand(diffs, options) {
1334
+ const iLength = diffs.length;
1335
+ const nContextLines = options.contextLines;
1336
+ const nContextLines2 = nContextLines + nContextLines;
1337
+ // First pass: count output lines and see if it has patches.
1338
+ let jLength = iLength;
1339
+ let hasExcessAtStartOrEnd = false;
1340
+ let nExcessesBetweenChanges = 0;
1341
+ let i = 0;
1342
+ while (i !== iLength) {
1343
+ const iStart = i;
1344
+ while (i !== iLength && diffs[i][0] === DIFF_EQUAL) {
1345
+ i += 1;
1346
+ }
1347
+ if (iStart !== i) {
1348
+ if (iStart === 0) {
1349
+ // at start
1350
+ if (i > nContextLines) {
1351
+ jLength -= i - nContextLines;
1352
+ hasExcessAtStartOrEnd = true;
1353
+ }
1354
+ } else if (i === iLength) {
1355
+ // at end
1356
+ const n = i - iStart;
1357
+ if (n > nContextLines) {
1358
+ jLength -= n - nContextLines;
1359
+ hasExcessAtStartOrEnd = true;
1360
+ }
1361
+ } else {
1362
+ // between changes
1363
+ const n = i - iStart;
1364
+ if (n > nContextLines2) {
1365
+ jLength -= n - nContextLines2;
1366
+ nExcessesBetweenChanges += 1;
1367
+ }
1368
+ }
1369
+ }
1370
+ while (i !== iLength && diffs[i][0] !== DIFF_EQUAL) {
1371
+ i += 1;
1372
+ }
1373
+ }
1374
+ const hasPatch = nExcessesBetweenChanges !== 0 || hasExcessAtStartOrEnd;
1375
+ if (nExcessesBetweenChanges !== 0) {
1376
+ jLength += nExcessesBetweenChanges + 1;
1377
+ } else if (hasExcessAtStartOrEnd) {
1378
+ jLength += 1;
1379
+ }
1380
+ const jLast = jLength - 1;
1381
+ const lines = [];
1382
+ let jPatchMark = 0;
1383
+ if (hasPatch) {
1384
+ lines.push("");
1385
+ }
1386
+ // Indexes of expected or received lines in current patch:
1387
+ let aStart = 0;
1388
+ let bStart = 0;
1389
+ let aEnd = 0;
1390
+ let bEnd = 0;
1391
+ const pushCommonLine = (line) => {
1392
+ const j = lines.length;
1393
+ lines.push(printCommonLine(line, j === 0 || j === jLast, options));
1394
+ aEnd += 1;
1395
+ bEnd += 1;
1396
+ };
1397
+ const pushDeleteLine = (line) => {
1398
+ const j = lines.length;
1399
+ lines.push(printDeleteLine(line, j === 0 || j === jLast, options));
1400
+ aEnd += 1;
1401
+ };
1402
+ const pushInsertLine = (line) => {
1403
+ const j = lines.length;
1404
+ lines.push(printInsertLine(line, j === 0 || j === jLast, options));
1405
+ bEnd += 1;
1406
+ };
1407
+ // Second pass: push lines with diff formatting (and patch marks, if needed).
1408
+ i = 0;
1409
+ while (i !== iLength) {
1410
+ let iStart = i;
1411
+ while (i !== iLength && diffs[i][0] === DIFF_EQUAL) {
1412
+ i += 1;
1413
+ }
1414
+ if (iStart !== i) {
1415
+ if (iStart === 0) {
1416
+ // at beginning
1417
+ if (i > nContextLines) {
1418
+ iStart = i - nContextLines;
1419
+ aStart = iStart;
1420
+ bStart = iStart;
1421
+ aEnd = aStart;
1422
+ bEnd = bStart;
1423
+ }
1424
+ for (let iCommon = iStart; iCommon !== i; iCommon += 1) {
1425
+ pushCommonLine(diffs[iCommon][1]);
1426
+ }
1427
+ } else if (i === iLength) {
1428
+ // at end
1429
+ const iEnd = i - iStart > nContextLines ? iStart + nContextLines : i;
1430
+ for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) {
1431
+ pushCommonLine(diffs[iCommon][1]);
1432
+ }
1433
+ } else {
1434
+ // between changes
1435
+ const nCommon = i - iStart;
1436
+ if (nCommon > nContextLines2) {
1437
+ const iEnd = iStart + nContextLines;
1438
+ for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) {
1439
+ pushCommonLine(diffs[iCommon][1]);
1440
+ }
1441
+ lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options);
1442
+ jPatchMark = lines.length;
1443
+ lines.push("");
1444
+ const nOmit = nCommon - nContextLines2;
1445
+ aStart = aEnd + nOmit;
1446
+ bStart = bEnd + nOmit;
1447
+ aEnd = aStart;
1448
+ bEnd = bStart;
1449
+ for (let iCommon = i - nContextLines; iCommon !== i; iCommon += 1) {
1450
+ pushCommonLine(diffs[iCommon][1]);
1451
+ }
1452
+ } else {
1453
+ for (let iCommon = iStart; iCommon !== i; iCommon += 1) {
1454
+ pushCommonLine(diffs[iCommon][1]);
1455
+ }
1456
+ }
1457
+ }
1458
+ }
1459
+ while (i !== iLength && diffs[i][0] === DIFF_DELETE) {
1460
+ pushDeleteLine(diffs[i][1]);
1461
+ i += 1;
1462
+ }
1463
+ while (i !== iLength && diffs[i][0] === DIFF_INSERT) {
1464
+ pushInsertLine(diffs[i][1]);
1465
+ i += 1;
1466
+ }
1467
+ }
1468
+ if (hasPatch) {
1469
+ lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options);
1470
+ }
1471
+ return lines.join("\n");
1472
+ }
1473
+ // jest --expand
1474
+ //
1475
+ // Given array of aligned strings with inverse highlight formatting,
1476
+ // return joined lines with diff formatting.
1477
+ function joinAlignedDiffsExpand(diffs, options) {
1478
+ return diffs.map((diff, i, diffs) => {
1479
+ const line = diff[1];
1480
+ const isFirstOrLast = i === 0 || i === diffs.length - 1;
1481
+ switch (diff[0]) {
1482
+ case DIFF_DELETE: return printDeleteLine(line, isFirstOrLast, options);
1483
+ case DIFF_INSERT: return printInsertLine(line, isFirstOrLast, options);
1484
+ default: return printCommonLine(line, isFirstOrLast, options);
1485
+ }
1486
+ }).join("\n");
1487
+ }
1488
+
1489
+ const noColor = (string) => string;
1490
+ const DIFF_CONTEXT_DEFAULT = 5;
1491
+ const DIFF_TRUNCATE_THRESHOLD_DEFAULT = 0;
1492
+ function getDefaultOptions() {
1493
+ return {
1494
+ aAnnotation: "Expected",
1495
+ aColor: c.green,
1496
+ aIndicator: "-",
1497
+ bAnnotation: "Received",
1498
+ bColor: c.red,
1499
+ bIndicator: "+",
1500
+ changeColor: c.inverse,
1501
+ changeLineTrailingSpaceColor: noColor,
1502
+ commonColor: c.dim,
1503
+ commonIndicator: " ",
1504
+ commonLineTrailingSpaceColor: noColor,
1505
+ compareKeys: undefined,
1506
+ contextLines: DIFF_CONTEXT_DEFAULT,
1507
+ emptyFirstOrLastLinePlaceholder: "",
1508
+ expand: false,
1509
+ includeChangeCounts: false,
1510
+ omitAnnotationLines: false,
1511
+ patchColor: c.yellow,
1512
+ printBasicPrototype: false,
1513
+ truncateThreshold: DIFF_TRUNCATE_THRESHOLD_DEFAULT,
1514
+ truncateAnnotation: "... Diff result is truncated",
1515
+ truncateAnnotationColor: noColor
1516
+ };
1517
+ }
1518
+ function getCompareKeys(compareKeys) {
1519
+ return compareKeys && typeof compareKeys === "function" ? compareKeys : undefined;
1520
+ }
1521
+ function getContextLines(contextLines) {
1522
+ return typeof contextLines === "number" && Number.isSafeInteger(contextLines) && contextLines >= 0 ? contextLines : DIFF_CONTEXT_DEFAULT;
1523
+ }
1524
+ // Pure function returns options with all properties.
1525
+ function normalizeDiffOptions(options = {}) {
1526
+ return {
1527
+ ...getDefaultOptions(),
1528
+ ...options,
1529
+ compareKeys: getCompareKeys(options.compareKeys),
1530
+ contextLines: getContextLines(options.contextLines)
1531
+ };
1532
+ }
1533
+
1534
+ function isEmptyString(lines) {
1535
+ return lines.length === 1 && lines[0].length === 0;
1536
+ }
1537
+ function countChanges(diffs) {
1538
+ let a = 0;
1539
+ let b = 0;
1540
+ diffs.forEach((diff) => {
1541
+ switch (diff[0]) {
1542
+ case DIFF_DELETE:
1543
+ a += 1;
1544
+ break;
1545
+ case DIFF_INSERT:
1546
+ b += 1;
1547
+ break;
1548
+ }
1549
+ });
1550
+ return {
1551
+ a,
1552
+ b
1553
+ };
1554
+ }
1555
+ function printAnnotation({ aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator, includeChangeCounts, omitAnnotationLines }, changeCounts) {
1556
+ if (omitAnnotationLines) {
1557
+ return "";
1558
+ }
1559
+ let aRest = "";
1560
+ let bRest = "";
1561
+ if (includeChangeCounts) {
1562
+ const aCount = String(changeCounts.a);
1563
+ const bCount = String(changeCounts.b);
1564
+ // Padding right aligns the ends of the annotations.
1565
+ const baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length;
1566
+ const aAnnotationPadding = " ".repeat(Math.max(0, baAnnotationLengthDiff));
1567
+ const bAnnotationPadding = " ".repeat(Math.max(0, -baAnnotationLengthDiff));
1568
+ // Padding left aligns the ends of the counts.
1569
+ const baCountLengthDiff = bCount.length - aCount.length;
1570
+ const aCountPadding = " ".repeat(Math.max(0, baCountLengthDiff));
1571
+ const bCountPadding = " ".repeat(Math.max(0, -baCountLengthDiff));
1572
+ aRest = `${aAnnotationPadding} ${aIndicator} ${aCountPadding}${aCount}`;
1573
+ bRest = `${bAnnotationPadding} ${bIndicator} ${bCountPadding}${bCount}`;
1574
+ }
1575
+ const a = `${aIndicator} ${aAnnotation}${aRest}`;
1576
+ const b = `${bIndicator} ${bAnnotation}${bRest}`;
1577
+ return `${aColor(a)}\n${bColor(b)}\n\n`;
1578
+ }
1579
+ function printDiffLines(diffs, truncated, options) {
1580
+ return printAnnotation(options, countChanges(diffs)) + (options.expand ? joinAlignedDiffsExpand(diffs, options) : joinAlignedDiffsNoExpand(diffs, options)) + (truncated ? options.truncateAnnotationColor(`\n${options.truncateAnnotation}`) : "");
1581
+ }
1582
+ // Compare two arrays of strings line-by-line. Format as comparison lines.
1583
+ function diffLinesUnified(aLines, bLines, options) {
1584
+ const normalizedOptions = normalizeDiffOptions(options);
1585
+ const [diffs, truncated] = diffLinesRaw(isEmptyString(aLines) ? [] : aLines, isEmptyString(bLines) ? [] : bLines, normalizedOptions);
1586
+ return printDiffLines(diffs, truncated, normalizedOptions);
1587
+ }
1588
+ // Given two pairs of arrays of strings:
1589
+ // Compare the pair of comparison arrays line-by-line.
1590
+ // Format the corresponding lines in the pair of displayable arrays.
1591
+ function diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options) {
1592
+ if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare)) {
1593
+ aLinesDisplay = [];
1594
+ aLinesCompare = [];
1595
+ }
1596
+ if (isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare)) {
1597
+ bLinesDisplay = [];
1598
+ bLinesCompare = [];
1599
+ }
1600
+ if (aLinesDisplay.length !== aLinesCompare.length || bLinesDisplay.length !== bLinesCompare.length) {
1601
+ // Fall back to diff of display lines.
1602
+ return diffLinesUnified(aLinesDisplay, bLinesDisplay, options);
1603
+ }
1604
+ const [diffs, truncated] = diffLinesRaw(aLinesCompare, bLinesCompare, options);
1605
+ // Replace comparison lines with displayable lines.
1606
+ let aIndex = 0;
1607
+ let bIndex = 0;
1608
+ diffs.forEach((diff) => {
1609
+ switch (diff[0]) {
1610
+ case DIFF_DELETE:
1611
+ diff[1] = aLinesDisplay[aIndex];
1612
+ aIndex += 1;
1613
+ break;
1614
+ case DIFF_INSERT:
1615
+ diff[1] = bLinesDisplay[bIndex];
1616
+ bIndex += 1;
1617
+ break;
1618
+ default:
1619
+ diff[1] = bLinesDisplay[bIndex];
1620
+ aIndex += 1;
1621
+ bIndex += 1;
1622
+ }
1623
+ });
1624
+ return printDiffLines(diffs, truncated, normalizeDiffOptions(options));
1625
+ }
1626
+ // Compare two arrays of strings line-by-line.
1627
+ function diffLinesRaw(aLines, bLines, options) {
1628
+ const truncate = options?.truncateThreshold ?? false;
1629
+ const truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0);
1630
+ const aLength = truncate ? Math.min(aLines.length, truncateThreshold) : aLines.length;
1631
+ const bLength = truncate ? Math.min(bLines.length, truncateThreshold) : bLines.length;
1632
+ const truncated = aLength !== aLines.length || bLength !== bLines.length;
1633
+ const isCommon = (aIndex, bIndex) => aLines[aIndex] === bLines[bIndex];
1634
+ const diffs = [];
1635
+ let aIndex = 0;
1636
+ let bIndex = 0;
1637
+ const foundSubsequence = (nCommon, aCommon, bCommon) => {
1638
+ for (; aIndex !== aCommon; aIndex += 1) {
1639
+ diffs.push(new Diff(DIFF_DELETE, aLines[aIndex]));
1640
+ }
1641
+ for (; bIndex !== bCommon; bIndex += 1) {
1642
+ diffs.push(new Diff(DIFF_INSERT, bLines[bIndex]));
1643
+ }
1644
+ for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) {
1645
+ diffs.push(new Diff(DIFF_EQUAL, bLines[bIndex]));
1646
+ }
1647
+ };
1648
+ diffSequences(aLength, bLength, isCommon, foundSubsequence);
1649
+ // After the last common subsequence, push remaining change items.
1650
+ for (; aIndex !== aLength; aIndex += 1) {
1651
+ diffs.push(new Diff(DIFF_DELETE, aLines[aIndex]));
1652
+ }
1653
+ for (; bIndex !== bLength; bIndex += 1) {
1654
+ diffs.push(new Diff(DIFF_INSERT, bLines[bIndex]));
1655
+ }
1656
+ return [diffs, truncated];
1657
+ }
1658
+
1659
+ // get the type of a value with handling the edge cases like `typeof []`
1660
+ // and `typeof null`
1661
+ function getType(value) {
1662
+ if (value === undefined) {
1663
+ return "undefined";
1664
+ } else if (value === null) {
1665
+ return "null";
1666
+ } else if (Array.isArray(value)) {
1667
+ return "array";
1668
+ } else if (typeof value === "boolean") {
1669
+ return "boolean";
1670
+ } else if (typeof value === "function") {
1671
+ return "function";
1672
+ } else if (typeof value === "number") {
1673
+ return "number";
1674
+ } else if (typeof value === "string") {
1675
+ return "string";
1676
+ } else if (typeof value === "bigint") {
1677
+ return "bigint";
1678
+ } else if (typeof value === "object") {
1679
+ if (value != null) {
1680
+ if (value.constructor === RegExp) {
1681
+ return "regexp";
1682
+ } else if (value.constructor === Map) {
1683
+ return "map";
1684
+ } else if (value.constructor === Set) {
1685
+ return "set";
1686
+ } else if (value.constructor === Date) {
1687
+ return "date";
1688
+ }
1689
+ }
1690
+ return "object";
1691
+ } else if (typeof value === "symbol") {
1692
+ return "symbol";
1693
+ }
1694
+ throw new Error(`value of unknown type: ${value}`);
1695
+ }
1696
+
1697
+ // platforms compatible
1698
+ function getNewLineSymbol(string) {
1699
+ return string.includes("\r\n") ? "\r\n" : "\n";
1700
+ }
1701
+ function diffStrings(a, b, options) {
1702
+ const truncate = options?.truncateThreshold ?? false;
1703
+ const truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0);
1704
+ let aLength = a.length;
1705
+ let bLength = b.length;
1706
+ if (truncate) {
1707
+ const aMultipleLines = a.includes("\n");
1708
+ const bMultipleLines = b.includes("\n");
1709
+ const aNewLineSymbol = getNewLineSymbol(a);
1710
+ const bNewLineSymbol = getNewLineSymbol(b);
1711
+ // multiple-lines string expects a newline to be appended at the end
1712
+ const _a = aMultipleLines ? `${a.split(aNewLineSymbol, truncateThreshold).join(aNewLineSymbol)}\n` : a;
1713
+ const _b = bMultipleLines ? `${b.split(bNewLineSymbol, truncateThreshold).join(bNewLineSymbol)}\n` : b;
1714
+ aLength = _a.length;
1715
+ bLength = _b.length;
1716
+ }
1717
+ const truncated = aLength !== a.length || bLength !== b.length;
1718
+ const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex];
1719
+ let aIndex = 0;
1720
+ let bIndex = 0;
1721
+ const diffs = [];
1722
+ const foundSubsequence = (nCommon, aCommon, bCommon) => {
1723
+ if (aIndex !== aCommon) {
1724
+ diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex, aCommon)));
1725
+ }
1726
+ if (bIndex !== bCommon) {
1727
+ diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex, bCommon)));
1728
+ }
1729
+ aIndex = aCommon + nCommon;
1730
+ bIndex = bCommon + nCommon;
1731
+ diffs.push(new Diff(DIFF_EQUAL, b.slice(bCommon, bIndex)));
1732
+ };
1733
+ diffSequences(aLength, bLength, isCommon, foundSubsequence);
1734
+ // After the last common subsequence, push remaining change items.
1735
+ if (aIndex !== aLength) {
1736
+ diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex)));
1737
+ }
1738
+ if (bIndex !== bLength) {
1739
+ diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex)));
1740
+ }
1741
+ return [diffs, truncated];
1742
+ }
1743
+
1744
+ // Given change op and array of diffs, return concatenated string:
1745
+ // * include common strings
1746
+ // * include change strings which have argument op with changeColor
1747
+ // * exclude change strings which have opposite op
1748
+ function concatenateRelevantDiffs(op, diffs, changeColor) {
1749
+ return diffs.reduce((reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op && diff[1].length !== 0 ? changeColor(diff[1]) : ""), "");
1750
+ }
1751
+ // Encapsulate change lines until either a common newline or the end.
1752
+ class ChangeBuffer {
1753
+ op;
1754
+ line;
1755
+ lines;
1756
+ changeColor;
1757
+ constructor(op, changeColor) {
1758
+ this.op = op;
1759
+ this.line = [];
1760
+ this.lines = [];
1761
+ this.changeColor = changeColor;
1762
+ }
1763
+ pushSubstring(substring) {
1764
+ this.pushDiff(new Diff(this.op, substring));
1765
+ }
1766
+ pushLine() {
1767
+ // Assume call only if line has at least one diff,
1768
+ // therefore an empty line must have a diff which has an empty string.
1769
+ // If line has multiple diffs, then assume it has a common diff,
1770
+ // therefore change diffs have change color;
1771
+ // otherwise then it has line color only.
1772
+ this.lines.push(this.line.length !== 1 ? new Diff(this.op, concatenateRelevantDiffs(this.op, this.line, this.changeColor)) : this.line[0][0] === this.op ? this.line[0] : new Diff(this.op, this.line[0][1]));
1773
+ this.line.length = 0;
1774
+ }
1775
+ isLineEmpty() {
1776
+ return this.line.length === 0;
1777
+ }
1778
+ // Minor input to buffer.
1779
+ pushDiff(diff) {
1780
+ this.line.push(diff);
1781
+ }
1782
+ // Main input to buffer.
1783
+ align(diff) {
1784
+ const string = diff[1];
1785
+ if (string.includes("\n")) {
1786
+ const substrings = string.split("\n");
1787
+ const iLast = substrings.length - 1;
1788
+ substrings.forEach((substring, i) => {
1789
+ if (i < iLast) {
1790
+ // The first substring completes the current change line.
1791
+ // A middle substring is a change line.
1792
+ this.pushSubstring(substring);
1793
+ this.pushLine();
1794
+ } else if (substring.length !== 0) {
1795
+ // The last substring starts a change line, if it is not empty.
1796
+ // Important: This non-empty condition also automatically omits
1797
+ // the newline appended to the end of expected and received strings.
1798
+ this.pushSubstring(substring);
1799
+ }
1800
+ });
1801
+ } else {
1802
+ // Append non-multiline string to current change line.
1803
+ this.pushDiff(diff);
1804
+ }
1805
+ }
1806
+ // Output from buffer.
1807
+ moveLinesTo(lines) {
1808
+ if (!this.isLineEmpty()) {
1809
+ this.pushLine();
1810
+ }
1811
+ lines.push(...this.lines);
1812
+ this.lines.length = 0;
1813
+ }
1814
+ }
1815
+ // Encapsulate common and change lines.
1816
+ class CommonBuffer {
1817
+ deleteBuffer;
1818
+ insertBuffer;
1819
+ lines;
1820
+ constructor(deleteBuffer, insertBuffer) {
1821
+ this.deleteBuffer = deleteBuffer;
1822
+ this.insertBuffer = insertBuffer;
1823
+ this.lines = [];
1824
+ }
1825
+ pushDiffCommonLine(diff) {
1826
+ this.lines.push(diff);
1827
+ }
1828
+ pushDiffChangeLines(diff) {
1829
+ const isDiffEmpty = diff[1].length === 0;
1830
+ // An empty diff string is redundant, unless a change line is empty.
1831
+ if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) {
1832
+ this.deleteBuffer.pushDiff(diff);
1833
+ }
1834
+ if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) {
1835
+ this.insertBuffer.pushDiff(diff);
1836
+ }
1837
+ }
1838
+ flushChangeLines() {
1839
+ this.deleteBuffer.moveLinesTo(this.lines);
1840
+ this.insertBuffer.moveLinesTo(this.lines);
1841
+ }
1842
+ // Input to buffer.
1843
+ align(diff) {
1844
+ const op = diff[0];
1845
+ const string = diff[1];
1846
+ if (string.includes("\n")) {
1847
+ const substrings = string.split("\n");
1848
+ const iLast = substrings.length - 1;
1849
+ substrings.forEach((substring, i) => {
1850
+ if (i === 0) {
1851
+ const subdiff = new Diff(op, substring);
1852
+ if (this.deleteBuffer.isLineEmpty() && this.insertBuffer.isLineEmpty()) {
1853
+ // If both current change lines are empty,
1854
+ // then the first substring is a common line.
1855
+ this.flushChangeLines();
1856
+ this.pushDiffCommonLine(subdiff);
1857
+ } else {
1858
+ // If either current change line is non-empty,
1859
+ // then the first substring completes the change lines.
1860
+ this.pushDiffChangeLines(subdiff);
1861
+ this.flushChangeLines();
1862
+ }
1863
+ } else if (i < iLast) {
1864
+ // A middle substring is a common line.
1865
+ this.pushDiffCommonLine(new Diff(op, substring));
1866
+ } else if (substring.length !== 0) {
1867
+ // The last substring starts a change line, if it is not empty.
1868
+ // Important: This non-empty condition also automatically omits
1869
+ // the newline appended to the end of expected and received strings.
1870
+ this.pushDiffChangeLines(new Diff(op, substring));
1871
+ }
1872
+ });
1873
+ } else {
1874
+ // Append non-multiline string to current change lines.
1875
+ // Important: It cannot be at the end following empty change lines,
1876
+ // because newline appended to the end of expected and received strings.
1877
+ this.pushDiffChangeLines(diff);
1878
+ }
1879
+ }
1880
+ // Output from buffer.
1881
+ getLines() {
1882
+ this.flushChangeLines();
1883
+ return this.lines;
1884
+ }
1885
+ }
1886
+ // Given diffs from expected and received strings,
1887
+ // return new array of diffs split or joined into lines.
1888
+ //
1889
+ // To correctly align a change line at the end, the algorithm:
1890
+ // * assumes that a newline was appended to the strings
1891
+ // * omits the last newline from the output array
1892
+ //
1893
+ // Assume the function is not called:
1894
+ // * if either expected or received is empty string
1895
+ // * if neither expected nor received is multiline string
1896
+ function getAlignedDiffs(diffs, changeColor) {
1897
+ const deleteBuffer = new ChangeBuffer(DIFF_DELETE, changeColor);
1898
+ const insertBuffer = new ChangeBuffer(DIFF_INSERT, changeColor);
1899
+ const commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer);
1900
+ diffs.forEach((diff) => {
1901
+ switch (diff[0]) {
1902
+ case DIFF_DELETE:
1903
+ deleteBuffer.align(diff);
1904
+ break;
1905
+ case DIFF_INSERT:
1906
+ insertBuffer.align(diff);
1907
+ break;
1908
+ default: commonBuffer.align(diff);
1909
+ }
1910
+ });
1911
+ return commonBuffer.getLines();
1912
+ }
1913
+
1914
+ function hasCommonDiff(diffs, isMultiline) {
1915
+ if (isMultiline) {
1916
+ // Important: Ignore common newline that was appended to multiline strings!
1917
+ const iLast = diffs.length - 1;
1918
+ return diffs.some((diff, i) => diff[0] === DIFF_EQUAL && (i !== iLast || diff[1] !== "\n"));
1919
+ }
1920
+ return diffs.some((diff) => diff[0] === DIFF_EQUAL);
1921
+ }
1922
+ // Compare two strings character-by-character.
1923
+ // Format as comparison lines in which changed substrings have inverse colors.
1924
+ function diffStringsUnified(a, b, options) {
1925
+ if (a !== b && a.length !== 0 && b.length !== 0) {
1926
+ const isMultiline = a.includes("\n") || b.includes("\n");
1927
+ // getAlignedDiffs assumes that a newline was appended to the strings.
1928
+ const [diffs, truncated] = diffStringsRaw(isMultiline ? `${a}\n` : a, isMultiline ? `${b}\n` : b, true, options);
1929
+ if (hasCommonDiff(diffs, isMultiline)) {
1930
+ const optionsNormalized = normalizeDiffOptions(options);
1931
+ const lines = getAlignedDiffs(diffs, optionsNormalized.changeColor);
1932
+ return printDiffLines(lines, truncated, optionsNormalized);
1933
+ }
1934
+ }
1935
+ // Fall back to line-by-line diff.
1936
+ return diffLinesUnified(a.split("\n"), b.split("\n"), options);
1937
+ }
1938
+ // Compare two strings character-by-character.
1939
+ // Optionally clean up small common substrings, also known as chaff.
1940
+ function diffStringsRaw(a, b, cleanup, options) {
1941
+ const [diffs, truncated] = diffStrings(a, b, options);
1942
+ if (cleanup) {
1943
+ diff_cleanupSemantic(diffs);
1944
+ }
1945
+ return [diffs, truncated];
1946
+ }
1947
+
1948
+ function getCommonMessage(message, options) {
1949
+ const { commonColor } = normalizeDiffOptions(options);
1950
+ return commonColor(message);
1951
+ }
1952
+ const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins;
1953
+ const PLUGINS = [
1954
+ ReactTestComponent,
1955
+ ReactElement,
1956
+ DOMElement,
1957
+ DOMCollection,
1958
+ Immutable,
1959
+ AsymmetricMatcher,
1960
+ plugins.Error
1961
+ ];
1962
+ const FORMAT_OPTIONS = {
1963
+ maxDepth: 20,
1964
+ plugins: PLUGINS
1965
+ };
1966
+ const FALLBACK_FORMAT_OPTIONS = {
1967
+ callToJSON: false,
1968
+ maxDepth: 8,
1969
+ plugins: PLUGINS
1970
+ };
1971
+ // Generate a string that will highlight the difference between two values
1972
+ // with green and red. (similar to how github does code diffing)
1973
+ /**
1974
+ * @param a Expected value
1975
+ * @param b Received value
1976
+ * @param options Diff options
1977
+ * @returns {string | null} a string diff
1978
+ */
1979
+ function diff(a, b, options) {
1980
+ if (Object.is(a, b)) {
1981
+ return "";
1982
+ }
1983
+ const aType = getType(a);
1984
+ let expectedType = aType;
1985
+ let omitDifference = false;
1986
+ if (aType === "object" && typeof a.asymmetricMatch === "function") {
1987
+ if (a.$$typeof !== Symbol.for("jest.asymmetricMatcher")) {
1988
+ // Do not know expected type of user-defined asymmetric matcher.
1989
+ return undefined;
1990
+ }
1991
+ if (typeof a.getExpectedType !== "function") {
1992
+ // For example, expect.anything() matches either null or undefined
1993
+ return undefined;
1994
+ }
1995
+ expectedType = a.getExpectedType();
1996
+ // Primitive types boolean and number omit difference below.
1997
+ // For example, omit difference for expect.stringMatching(regexp)
1998
+ omitDifference = expectedType === "string";
1999
+ }
2000
+ if (expectedType !== getType(b)) {
2001
+ const { aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator } = normalizeDiffOptions(options);
2002
+ const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options);
2003
+ let aDisplay = format(a, formatOptions);
2004
+ let bDisplay = format(b, formatOptions);
2005
+ // even if prettyFormat prints successfully big objects,
2006
+ // large string can choke later on (concatenation? RPC?),
2007
+ // so truncate it to a reasonable length here.
2008
+ // (For example, playwright's ElementHandle can become about 200_000_000 length string)
2009
+ const MAX_LENGTH = 1e5;
2010
+ function truncate(s) {
2011
+ return s.length <= MAX_LENGTH ? s : `${s.slice(0, MAX_LENGTH)}...`;
2012
+ }
2013
+ aDisplay = truncate(aDisplay);
2014
+ bDisplay = truncate(bDisplay);
2015
+ const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)}\n${aDisplay}`;
2016
+ const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)}\n${bDisplay}`;
2017
+ return `${aDiff}\n\n${bDiff}`;
2018
+ }
2019
+ if (omitDifference) {
2020
+ return undefined;
2021
+ }
2022
+ switch (aType) {
2023
+ case "string": return diffLinesUnified(a.split("\n"), b.split("\n"), options);
2024
+ case "boolean":
2025
+ case "number": return comparePrimitive(a, b, options);
2026
+ case "map": return compareObjects(sortMap(a), sortMap(b), options);
2027
+ case "set": return compareObjects(sortSet(a), sortSet(b), options);
2028
+ default: return compareObjects(a, b, options);
2029
+ }
2030
+ }
2031
+ function comparePrimitive(a, b, options) {
2032
+ const aFormat = format(a, FORMAT_OPTIONS);
2033
+ const bFormat = format(b, FORMAT_OPTIONS);
2034
+ return aFormat === bFormat ? "" : diffLinesUnified(aFormat.split("\n"), bFormat.split("\n"), options);
2035
+ }
2036
+ function sortMap(map) {
2037
+ return new Map(Array.from(map.entries()).sort());
2038
+ }
2039
+ function sortSet(set) {
2040
+ return new Set(Array.from(set.values()).sort());
2041
+ }
2042
+ function compareObjects(a, b, options) {
2043
+ let difference;
2044
+ let hasThrown = false;
2045
+ try {
2046
+ const formatOptions = getFormatOptions(FORMAT_OPTIONS, options);
2047
+ difference = getObjectsDifference(a, b, formatOptions, options);
2048
+ } catch {
2049
+ hasThrown = true;
2050
+ }
2051
+ const noDiffMessage = getCommonMessage(NO_DIFF_MESSAGE, options);
2052
+ // If the comparison yields no results, compare again but this time
2053
+ // without calling `toJSON`. It's also possible that toJSON might throw.
2054
+ if (difference === undefined || difference === noDiffMessage) {
2055
+ const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options);
2056
+ difference = getObjectsDifference(a, b, formatOptions, options);
2057
+ if (difference !== noDiffMessage && !hasThrown) {
2058
+ difference = `${getCommonMessage(SIMILAR_MESSAGE, options)}\n\n${difference}`;
2059
+ }
2060
+ }
2061
+ return difference;
2062
+ }
2063
+ function getFormatOptions(formatOptions, options) {
2064
+ const { compareKeys, printBasicPrototype, maxDepth } = normalizeDiffOptions(options);
2065
+ return {
2066
+ ...formatOptions,
2067
+ compareKeys,
2068
+ printBasicPrototype,
2069
+ maxDepth: maxDepth ?? formatOptions.maxDepth
2070
+ };
2071
+ }
2072
+ function getObjectsDifference(a, b, formatOptions, options) {
2073
+ const formatOptionsZeroIndent = {
2074
+ ...formatOptions,
2075
+ indent: 0
2076
+ };
2077
+ const aCompare = format(a, formatOptionsZeroIndent);
2078
+ const bCompare = format(b, formatOptionsZeroIndent);
2079
+ if (aCompare === bCompare) {
2080
+ return getCommonMessage(NO_DIFF_MESSAGE, options);
2081
+ } else {
2082
+ const aDisplay = format(a, formatOptions);
2083
+ const bDisplay = format(b, formatOptions);
2084
+ return diffLinesUnified2(aDisplay.split("\n"), bDisplay.split("\n"), aCompare.split("\n"), bCompare.split("\n"), options);
2085
+ }
2086
+ }
2087
+ const MAX_DIFF_STRING_LENGTH = 2e4;
2088
+ function isAsymmetricMatcher(data) {
2089
+ const type = getType$1(data);
2090
+ return type === "Object" && typeof data.asymmetricMatch === "function";
2091
+ }
2092
+ function isReplaceable(obj1, obj2) {
2093
+ const obj1Type = getType$1(obj1);
2094
+ const obj2Type = getType$1(obj2);
2095
+ return obj1Type === obj2Type && (obj1Type === "Object" || obj1Type === "Array");
2096
+ }
2097
+ function printDiffOrStringify(received, expected, options) {
2098
+ const { aAnnotation, bAnnotation } = normalizeDiffOptions(options);
2099
+ if (typeof expected === "string" && typeof received === "string" && expected.length > 0 && received.length > 0 && expected.length <= MAX_DIFF_STRING_LENGTH && received.length <= MAX_DIFF_STRING_LENGTH && expected !== received) {
2100
+ if (expected.includes("\n") || received.includes("\n")) {
2101
+ return diffStringsUnified(expected, received, options);
2102
+ }
2103
+ const [diffs] = diffStringsRaw(expected, received, true);
2104
+ const hasCommonDiff = diffs.some((diff) => diff[0] === DIFF_EQUAL);
2105
+ const printLabel = getLabelPrinter(aAnnotation, bAnnotation);
2106
+ const expectedLine = printLabel(aAnnotation) + printExpected(getCommonAndChangedSubstrings(diffs, DIFF_DELETE, hasCommonDiff));
2107
+ const receivedLine = printLabel(bAnnotation) + printReceived(getCommonAndChangedSubstrings(diffs, DIFF_INSERT, hasCommonDiff));
2108
+ return `${expectedLine}\n${receivedLine}`;
2109
+ }
2110
+ // if (isLineDiffable(expected, received)) {
2111
+ const clonedExpected = deepClone(expected, { forceWritable: true });
2112
+ const clonedReceived = deepClone(received, { forceWritable: true });
2113
+ const { replacedExpected, replacedActual } = replaceAsymmetricMatcher(clonedReceived, clonedExpected);
2114
+ const difference = diff(replacedExpected, replacedActual, options);
2115
+ return difference;
2116
+ // }
2117
+ // const printLabel = getLabelPrinter(aAnnotation, bAnnotation)
2118
+ // const expectedLine = printLabel(aAnnotation) + printExpected(expected)
2119
+ // const receivedLine
2120
+ // = printLabel(bAnnotation)
2121
+ // + (stringify(expected) === stringify(received)
2122
+ // ? 'serializes to the same string'
2123
+ // : printReceived(received))
2124
+ // return `${expectedLine}\n${receivedLine}`
2125
+ }
2126
+ function replaceAsymmetricMatcher(actual, expected, actualReplaced = new WeakSet(), expectedReplaced = new WeakSet()) {
2127
+ // handle asymmetric Error.cause diff
2128
+ if (actual instanceof Error && expected instanceof Error && typeof actual.cause !== "undefined" && typeof expected.cause === "undefined") {
2129
+ delete actual.cause;
2130
+ return {
2131
+ replacedActual: actual,
2132
+ replacedExpected: expected
2133
+ };
2134
+ }
2135
+ if (!isReplaceable(actual, expected)) {
2136
+ return {
2137
+ replacedActual: actual,
2138
+ replacedExpected: expected
2139
+ };
2140
+ }
2141
+ if (actualReplaced.has(actual) || expectedReplaced.has(expected)) {
2142
+ return {
2143
+ replacedActual: actual,
2144
+ replacedExpected: expected
2145
+ };
2146
+ }
2147
+ actualReplaced.add(actual);
2148
+ expectedReplaced.add(expected);
2149
+ getOwnProperties(expected).forEach((key) => {
2150
+ const expectedValue = expected[key];
2151
+ const actualValue = actual[key];
2152
+ if (isAsymmetricMatcher(expectedValue)) {
2153
+ if (expectedValue.asymmetricMatch(actualValue)) {
2154
+ // When matcher matches, replace expected with actual value
2155
+ // so they appear the same in the diff
2156
+ expected[key] = actualValue;
2157
+ } else if ("sample" in expectedValue && expectedValue.sample !== undefined && isReplaceable(actualValue, expectedValue.sample)) {
2158
+ // For container matchers (ArrayContaining, ObjectContaining), unwrap and recursively process
2159
+ // Matcher doesn't match: unwrap but keep structure to show mismatch
2160
+ const replaced = replaceAsymmetricMatcher(actualValue, expectedValue.sample, actualReplaced, expectedReplaced);
2161
+ actual[key] = replaced.replacedActual;
2162
+ expected[key] = replaced.replacedExpected;
2163
+ }
2164
+ } else if (isAsymmetricMatcher(actualValue)) {
2165
+ if (actualValue.asymmetricMatch(expectedValue)) {
2166
+ actual[key] = expectedValue;
2167
+ } else if ("sample" in actualValue && actualValue.sample !== undefined && isReplaceable(actualValue.sample, expectedValue)) {
2168
+ const replaced = replaceAsymmetricMatcher(actualValue.sample, expectedValue, actualReplaced, expectedReplaced);
2169
+ actual[key] = replaced.replacedActual;
2170
+ expected[key] = replaced.replacedExpected;
2171
+ }
2172
+ } else if (isReplaceable(actualValue, expectedValue)) {
2173
+ const replaced = replaceAsymmetricMatcher(actualValue, expectedValue, actualReplaced, expectedReplaced);
2174
+ actual[key] = replaced.replacedActual;
2175
+ expected[key] = replaced.replacedExpected;
2176
+ }
2177
+ });
2178
+ return {
2179
+ replacedActual: actual,
2180
+ replacedExpected: expected
2181
+ };
2182
+ }
2183
+ function getLabelPrinter(...strings) {
2184
+ const maxLength = strings.reduce((max, string) => string.length > max ? string.length : max, 0);
2185
+ return (string) => `${string}: ${" ".repeat(maxLength - string.length)}`;
2186
+ }
2187
+ const SPACE_SYMBOL = "·";
2188
+ function replaceTrailingSpaces(text) {
2189
+ return text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length));
2190
+ }
2191
+ function printReceived(object) {
2192
+ return c.red(replaceTrailingSpaces(stringify(object)));
2193
+ }
2194
+ function printExpected(value) {
2195
+ return c.green(replaceTrailingSpaces(stringify(value)));
2196
+ }
2197
+ function getCommonAndChangedSubstrings(diffs, op, hasCommonDiff) {
2198
+ return diffs.reduce((reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op ? hasCommonDiff ? c.inverse(diff[1]) : diff[1] : ""), "");
2199
+ }
2200
+
2201
+ export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher };