Update test framework: fix run_tests.py to support all test files, add auto-import-check for test files

This commit is contained in:
qiaoxinjiu
2026-05-09 15:11:30 +08:00
parent eb053a347f
commit eaba8328da
21739 changed files with 2236758 additions and 719 deletions

18
node_modules/jsondiffpatch/bin/jsondiffpatch.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
#!/usr/bin/env node
import { readFileSync } from 'node:fs';
import * as jsondiffpatch from '../lib/with-text-diffs.js';
import * as consoleFormatter from '../lib/formatters/console.js';
const fileLeft = process.argv[2];
const fileRight = process.argv[3];
if (!fileLeft || !fileRight) {
console.log('\n USAGE: jsondiffpatch left.json right.json');
} else {
const left = JSON.parse(readFileSync(fileLeft));
const right = JSON.parse(readFileSync(fileRight));
const delta = jsondiffpatch.diff(left, right);
consoleFormatter.log(delta);
}

1
node_modules/jsondiffpatch/lib/clone.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export default function clone(arg: unknown): unknown;

28
node_modules/jsondiffpatch/lib/clone.js generated vendored Normal file
View File

@@ -0,0 +1,28 @@
function cloneRegExp(re) {
const regexMatch = /^\/(.*)\/([gimyu]*)$/.exec(re.toString());
return new RegExp(regexMatch[1], regexMatch[2]);
}
export default function clone(arg) {
if (typeof arg !== 'object') {
return arg;
}
if (arg === null) {
return null;
}
if (Array.isArray(arg)) {
return arg.map(clone);
}
if (arg instanceof Date) {
return new Date(arg.getTime());
}
if (arg instanceof RegExp) {
return cloneRegExp(arg);
}
const cloned = {};
for (const name in arg) {
if (Object.prototype.hasOwnProperty.call(arg, name)) {
cloned[name] = clone(arg[name]);
}
}
return cloned;
}

17
node_modules/jsondiffpatch/lib/contexts/context.d.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import type { Options } from '../types.js';
export default abstract class Context<TResult> {
abstract pipe: string;
result?: TResult;
hasResult?: boolean;
exiting?: boolean;
parent?: this;
childName?: string | number;
root?: this;
options?: Options;
children?: this[];
nextAfterChildren?: this | null;
next?: this | null;
setResult(result: TResult): this;
exit(): this;
push(child: this, name?: string | number): this;
}

30
node_modules/jsondiffpatch/lib/contexts/context.js generated vendored Normal file
View File

@@ -0,0 +1,30 @@
export default class Context {
setResult(result) {
this.result = result;
this.hasResult = true;
return this;
}
exit() {
this.exiting = true;
return this;
}
push(child, name) {
child.parent = this;
if (typeof name !== 'undefined') {
child.childName = name;
}
child.root = this.root || this;
child.options = child.options || this.options;
if (!this.children) {
this.children = [child];
this.nextAfterChildren = this.next || null;
this.next = child;
}
else {
this.children[this.children.length - 1].next = child;
this.children.push(child);
}
child.next = this;
return this;
}
}

14
node_modules/jsondiffpatch/lib/contexts/diff.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import Context from './context.js';
import type { Delta } from '../types.js';
declare class DiffContext extends Context<Delta> {
left: unknown;
right: unknown;
pipe: 'diff';
leftType?: string;
rightType?: string;
leftIsArray?: boolean;
rightIsArray?: boolean;
constructor(left: unknown, right: unknown);
setResult(result: Delta): this;
}
export default DiffContext;

25
node_modules/jsondiffpatch/lib/contexts/diff.js generated vendored Normal file
View File

@@ -0,0 +1,25 @@
import Context from './context.js';
import defaultClone from '../clone.js';
class DiffContext extends Context {
constructor(left, right) {
super();
this.left = left;
this.right = right;
this.pipe = 'diff';
}
setResult(result) {
if (this.options.cloneDiffValues && typeof result === 'object') {
const clone = typeof this.options.cloneDiffValues === 'function'
? this.options.cloneDiffValues
: defaultClone;
if (typeof result[0] === 'object') {
result[0] = clone(result[0]);
}
if (typeof result[1] === 'object') {
result[1] = clone(result[1]);
}
}
return super.setResult(result);
}
}
export default DiffContext;

10
node_modules/jsondiffpatch/lib/contexts/patch.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import Context from './context.js';
import type { Delta } from '../types.js';
declare class PatchContext extends Context<unknown> {
left: unknown;
delta: Delta;
pipe: 'patch';
nested?: boolean;
constructor(left: unknown, delta: Delta);
}
export default PatchContext;

10
node_modules/jsondiffpatch/lib/contexts/patch.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import Context from './context.js';
class PatchContext extends Context {
constructor(left, delta) {
super();
this.left = left;
this.delta = delta;
this.pipe = 'patch';
}
}
export default PatchContext;

10
node_modules/jsondiffpatch/lib/contexts/reverse.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import Context from './context.js';
import type { Delta } from '../types.js';
declare class ReverseContext extends Context<Delta> {
delta: Delta;
pipe: 'reverse';
nested?: boolean;
newName?: `_${number}`;
constructor(delta: Delta);
}
export default ReverseContext;

9
node_modules/jsondiffpatch/lib/contexts/reverse.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import Context from './context.js';
class ReverseContext extends Context {
constructor(delta) {
super();
this.delta = delta;
this.pipe = 'reverse';
}
}
export default ReverseContext;

1
node_modules/jsondiffpatch/lib/date-reviver.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export default function dateReviver(key: string, value: unknown): unknown;

12
node_modules/jsondiffpatch/lib/date-reviver.js generated vendored Normal file
View File

@@ -0,0 +1,12 @@
// use as 2nd parameter for JSON.parse to revive Date instances
export default function dateReviver(key, value) {
let parts;
if (typeof value === 'string') {
parts =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d*))?(Z|([+-])(\d{2}):(\d{2}))$/.exec(value);
if (parts) {
return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3], +parts[4], +parts[5], +parts[6], +(parts[7] || 0)));
}
}
return value;
}

13
node_modules/jsondiffpatch/lib/diffpatcher.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import Processor from './processor.js';
import type { Delta, Options } from './types.js';
declare class DiffPatcher {
processor: Processor;
constructor(options?: Options);
options(options: Options): Options;
diff(left: unknown, right: unknown): Delta;
patch(left: unknown, delta: Delta): unknown;
reverse(delta: Delta): Delta;
unpatch(right: unknown, delta: Delta): unknown;
clone(value: unknown): unknown;
}
export default DiffPatcher;

44
node_modules/jsondiffpatch/lib/diffpatcher.js generated vendored Normal file
View File

@@ -0,0 +1,44 @@
import Processor from './processor.js';
import Pipe from './pipe.js';
import DiffContext from './contexts/diff.js';
import PatchContext from './contexts/patch.js';
import ReverseContext from './contexts/reverse.js';
import clone from './clone.js';
import * as trivial from './filters/trivial.js';
import * as nested from './filters/nested.js';
import * as arrays from './filters/arrays.js';
import * as dates from './filters/dates.js';
import * as texts from './filters/texts.js';
class DiffPatcher {
constructor(options) {
this.processor = new Processor(options);
this.processor.pipe(new Pipe('diff')
.append(nested.collectChildrenDiffFilter, trivial.diffFilter, dates.diffFilter, texts.diffFilter, nested.objectsDiffFilter, arrays.diffFilter)
.shouldHaveResult());
this.processor.pipe(new Pipe('patch')
.append(nested.collectChildrenPatchFilter, arrays.collectChildrenPatchFilter, trivial.patchFilter, texts.patchFilter, nested.patchFilter, arrays.patchFilter)
.shouldHaveResult());
this.processor.pipe(new Pipe('reverse')
.append(nested.collectChildrenReverseFilter, arrays.collectChildrenReverseFilter, trivial.reverseFilter, texts.reverseFilter, nested.reverseFilter, arrays.reverseFilter)
.shouldHaveResult());
}
options(options) {
return this.processor.options(options);
}
diff(left, right) {
return this.processor.process(new DiffContext(left, right));
}
patch(left, delta) {
return this.processor.process(new PatchContext(left, delta));
}
reverse(delta) {
return this.processor.process(new ReverseContext(delta));
}
unpatch(right, delta) {
return this.patch(right, this.reverse(delta));
}
clone(value) {
return clone(value);
}
}
export default DiffPatcher;

15
node_modules/jsondiffpatch/lib/filters/arrays.d.ts generated vendored Normal file
View File

@@ -0,0 +1,15 @@
import DiffContext from '../contexts/diff.js';
import PatchContext from '../contexts/patch.js';
import ReverseContext from '../contexts/reverse.js';
import type { Filter } from '../types.js';
export interface MatchContext {
objectHash?: ((item: object, index?: number) => string | undefined) | undefined;
matchByPosition?: boolean | undefined;
hashCache1?: (string | undefined)[];
hashCache2?: (string | undefined)[];
}
export declare const diffFilter: Filter<DiffContext>;
export declare const patchFilter: Filter<PatchContext>;
export declare const collectChildrenPatchFilter: Filter<PatchContext>;
export declare const reverseFilter: Filter<ReverseContext>;
export declare const collectChildrenReverseFilter: Filter<ReverseContext>;

404
node_modules/jsondiffpatch/lib/filters/arrays.js generated vendored Normal file
View File

@@ -0,0 +1,404 @@
import DiffContext from '../contexts/diff.js';
import PatchContext from '../contexts/patch.js';
import ReverseContext from '../contexts/reverse.js';
import lcs from './lcs.js';
const ARRAY_MOVE = 3;
function arraysHaveMatchByRef(array1, array2, len1, len2) {
for (let index1 = 0; index1 < len1; index1++) {
const val1 = array1[index1];
for (let index2 = 0; index2 < len2; index2++) {
const val2 = array2[index2];
if (index1 !== index2 && val1 === val2) {
return true;
}
}
}
}
function matchItems(array1, array2, index1, index2, context) {
const value1 = array1[index1];
const value2 = array2[index2];
if (value1 === value2) {
return true;
}
if (typeof value1 !== 'object' || typeof value2 !== 'object') {
return false;
}
const objectHash = context.objectHash;
if (!objectHash) {
// no way to match objects was provided, try match by position
return context.matchByPosition && index1 === index2;
}
context.hashCache1 = context.hashCache1 || [];
let hash1 = context.hashCache1[index1];
if (typeof hash1 === 'undefined') {
context.hashCache1[index1] = hash1 = objectHash(value1, index1);
}
if (typeof hash1 === 'undefined') {
return false;
}
context.hashCache2 = context.hashCache2 || [];
let hash2 = context.hashCache2[index2];
if (typeof hash2 === 'undefined') {
context.hashCache2[index2] = hash2 = objectHash(value2, index2);
}
if (typeof hash2 === 'undefined') {
return false;
}
return hash1 === hash2;
}
export const diffFilter = function arraysDiffFilter(context) {
if (!context.leftIsArray) {
return;
}
const matchContext = {
objectHash: context.options && context.options.objectHash,
matchByPosition: context.options && context.options.matchByPosition,
};
let commonHead = 0;
let commonTail = 0;
let index;
let index1;
let index2;
const array1 = context.left;
const array2 = context.right;
const len1 = array1.length;
const len2 = array2.length;
let child;
if (len1 > 0 &&
len2 > 0 &&
!matchContext.objectHash &&
typeof matchContext.matchByPosition !== 'boolean') {
matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);
}
// separate common head
while (commonHead < len1 &&
commonHead < len2 &&
matchItems(array1, array2, commonHead, commonHead, matchContext)) {
index = commonHead;
child = new DiffContext(array1[index], array2[index]);
context.push(child, index);
commonHead++;
}
// separate common tail
while (commonTail + commonHead < len1 &&
commonTail + commonHead < len2 &&
matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {
index1 = len1 - 1 - commonTail;
index2 = len2 - 1 - commonTail;
child = new DiffContext(array1[index1], array2[index2]);
context.push(child, index2);
commonTail++;
}
let result;
if (commonHead + commonTail === len1) {
if (len1 === len2) {
// arrays are identical
context.setResult(undefined).exit();
return;
}
// trivial case, a block (1 or more consecutive items) was added
result = result || {
_t: 'a',
};
for (index = commonHead; index < len2 - commonTail; index++) {
result[index] = [array2[index]];
}
context.setResult(result).exit();
return;
}
if (commonHead + commonTail === len2) {
// trivial case, a block (1 or more consecutive items) was removed
result = result || {
_t: 'a',
};
for (index = commonHead; index < len1 - commonTail; index++) {
result[`_${index}`] = [array1[index], 0, 0];
}
context.setResult(result).exit();
return;
}
// reset hash cache
delete matchContext.hashCache1;
delete matchContext.hashCache2;
// diff is not trivial, find the LCS (Longest Common Subsequence)
const trimmed1 = array1.slice(commonHead, len1 - commonTail);
const trimmed2 = array2.slice(commonHead, len2 - commonTail);
const seq = lcs.get(trimmed1, trimmed2, matchItems, matchContext);
const removedItems = [];
result = result || {
_t: 'a',
};
for (index = commonHead; index < len1 - commonTail; index++) {
if (seq.indices1.indexOf(index - commonHead) < 0) {
// removed
result[`_${index}`] = [array1[index], 0, 0];
removedItems.push(index);
}
}
let detectMove = true;
if (context.options &&
context.options.arrays &&
context.options.arrays.detectMove === false) {
detectMove = false;
}
let includeValueOnMove = false;
if (context.options &&
context.options.arrays &&
context.options.arrays.includeValueOnMove) {
includeValueOnMove = true;
}
const removedItemsLength = removedItems.length;
for (index = commonHead; index < len2 - commonTail; index++) {
const indexOnArray2 = seq.indices2.indexOf(index - commonHead);
if (indexOnArray2 < 0) {
// added, try to match with a removed item and register as position move
let isMove = false;
if (detectMove && removedItemsLength > 0) {
for (let removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {
index1 = removedItems[removeItemIndex1];
if (matchItems(trimmed1, trimmed2, index1 - commonHead, index - commonHead, matchContext)) {
// store position move as: [originalValue, newPosition, ARRAY_MOVE]
result[`_${index1}`].splice(1, 2, index, ARRAY_MOVE);
if (!includeValueOnMove) {
// don't include moved value on diff, to save bytes
result[`_${index1}`][0] = '';
}
index2 = index;
child = new DiffContext(array1[index1], array2[index2]);
context.push(child, index2);
removedItems.splice(removeItemIndex1, 1);
isMove = true;
break;
}
}
}
if (!isMove) {
// added
result[index] = [array2[index]];
}
}
else {
// match, do inner diff
index1 = seq.indices1[indexOnArray2] + commonHead;
index2 = seq.indices2[indexOnArray2] + commonHead;
child = new DiffContext(array1[index1], array2[index2]);
context.push(child, index2);
}
}
context.setResult(result).exit();
};
diffFilter.filterName = 'arrays';
const compare = {
numerically(a, b) {
return a - b;
},
numericallyBy(name) {
return (a, b) => a[name] - b[name];
},
};
export const patchFilter = function nestedPatchFilter(context) {
if (!context.nested) {
return;
}
const nestedDelta = context.delta;
if (nestedDelta._t !== 'a') {
return;
}
let index;
let index1;
const delta = nestedDelta;
const array = context.left;
// first, separate removals, insertions and modifications
let toRemove = [];
let toInsert = [];
const toModify = [];
for (index in delta) {
if (index !== '_t') {
if (index[0] === '_') {
const removedOrMovedIndex = index;
// removed item from original array
if (delta[removedOrMovedIndex][2] === 0 ||
delta[removedOrMovedIndex][2] === ARRAY_MOVE) {
toRemove.push(parseInt(index.slice(1), 10));
}
else {
throw new Error('only removal or move can be applied at original array indices,' +
` invalid diff type: ${delta[removedOrMovedIndex][2]}`);
}
}
else {
const numberIndex = index;
if (delta[numberIndex].length === 1) {
// added item at new array
toInsert.push({
index: parseInt(numberIndex, 10),
value: delta[numberIndex][0],
});
}
else {
// modified item at new array
toModify.push({
index: parseInt(numberIndex, 10),
delta: delta[numberIndex],
});
}
}
}
}
// remove items, in reverse order to avoid sawing our own floor
toRemove = toRemove.sort(compare.numerically);
for (index = toRemove.length - 1; index >= 0; index--) {
index1 = toRemove[index];
const indexDiff = delta[`_${index1}`];
const removedValue = array.splice(index1, 1)[0];
if (indexDiff[2] === ARRAY_MOVE) {
// reinsert later
toInsert.push({
index: indexDiff[1],
value: removedValue,
});
}
}
// insert items, in reverse order to avoid moving our own floor
toInsert = toInsert.sort(compare.numericallyBy('index'));
const toInsertLength = toInsert.length;
for (index = 0; index < toInsertLength; index++) {
const insertion = toInsert[index];
array.splice(insertion.index, 0, insertion.value);
}
// apply modifications
const toModifyLength = toModify.length;
let child;
if (toModifyLength > 0) {
for (index = 0; index < toModifyLength; index++) {
const modification = toModify[index];
child = new PatchContext(array[modification.index], modification.delta);
context.push(child, modification.index);
}
}
if (!context.children) {
context.setResult(array).exit();
return;
}
context.exit();
};
patchFilter.filterName = 'arrays';
export const collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
if (!context || !context.children) {
return;
}
const deltaWithChildren = context.delta;
if (deltaWithChildren._t !== 'a') {
return;
}
const array = context.left;
const length = context.children.length;
let child;
for (let index = 0; index < length; index++) {
child = context.children[index];
const arrayIndex = child.childName;
array[arrayIndex] = child.result;
}
context.setResult(array).exit();
};
collectChildrenPatchFilter.filterName = 'arraysCollectChildren';
export const reverseFilter = function arraysReverseFilter(context) {
if (!context.nested) {
const nonNestedDelta = context.delta;
if (nonNestedDelta[2] === ARRAY_MOVE) {
const arrayMoveDelta = nonNestedDelta;
context.newName = `_${arrayMoveDelta[1]}`;
context
.setResult([
arrayMoveDelta[0],
parseInt(context.childName.substring(1), 10),
ARRAY_MOVE,
])
.exit();
}
return;
}
const nestedDelta = context.delta;
if (nestedDelta._t !== 'a') {
return;
}
const arrayDelta = nestedDelta;
let name;
let child;
for (name in arrayDelta) {
if (name === '_t') {
continue;
}
child = new ReverseContext(arrayDelta[name]);
context.push(child, name);
}
context.exit();
};
reverseFilter.filterName = 'arrays';
const reverseArrayDeltaIndex = (delta, index, itemDelta) => {
if (typeof index === 'string' && index[0] === '_') {
return parseInt(index.substring(1), 10);
}
else if (Array.isArray(itemDelta) && itemDelta[2] === 0) {
return `_${index}`;
}
let reverseIndex = +index;
for (const deltaIndex in delta) {
const deltaItem = delta[deltaIndex];
if (Array.isArray(deltaItem)) {
if (deltaItem[2] === ARRAY_MOVE) {
const moveFromIndex = parseInt(deltaIndex.substring(1), 10);
const moveToIndex = deltaItem[1];
if (moveToIndex === +index) {
return moveFromIndex;
}
if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {
reverseIndex++;
}
else if (moveFromIndex >= reverseIndex &&
moveToIndex < reverseIndex) {
reverseIndex--;
}
}
else if (deltaItem[2] === 0) {
const deleteIndex = parseInt(deltaIndex.substring(1), 10);
if (deleteIndex <= reverseIndex) {
reverseIndex++;
}
}
else if (deltaItem.length === 1 &&
parseInt(deltaIndex, 10) <= reverseIndex) {
reverseIndex--;
}
}
}
return reverseIndex;
};
export const collectChildrenReverseFilter = (context) => {
if (!context || !context.children) {
return;
}
const deltaWithChildren = context.delta;
if (deltaWithChildren._t !== 'a') {
return;
}
const arrayDelta = deltaWithChildren;
const length = context.children.length;
let child;
const delta = {
_t: 'a',
};
for (let index = 0; index < length; index++) {
child = context.children[index];
let name = child.newName;
if (typeof name === 'undefined') {
name = reverseArrayDeltaIndex(arrayDelta, child.childName, child.result);
}
if (delta[name] !== child.result) {
// There's no way to type this well.
delta[name] = child.result;
}
}
context.setResult(delta).exit();
};
collectChildrenReverseFilter.filterName = 'arraysCollectChildren';

3
node_modules/jsondiffpatch/lib/filters/dates.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import type { Filter } from '../types.js';
import type DiffContext from '../contexts/diff.js';
export declare const diffFilter: Filter<DiffContext>;

20
node_modules/jsondiffpatch/lib/filters/dates.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
export const diffFilter = function datesDiffFilter(context) {
if (context.left instanceof Date) {
if (context.right instanceof Date) {
if (context.left.getTime() !== context.right.getTime()) {
context.setResult([context.left, context.right]);
}
else {
context.setResult(undefined);
}
}
else {
context.setResult([context.left, context.right]);
}
context.exit();
}
else if (context.right instanceof Date) {
context.setResult([context.left, context.right]).exit();
}
};
diffFilter.filterName = 'dates';

10
node_modules/jsondiffpatch/lib/filters/lcs.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import type { MatchContext } from './arrays.js';
interface Subsequence {
sequence: unknown[];
indices1: number[];
indices2: number[];
}
declare const _default: {
get: (array1: readonly unknown[], array2: readonly unknown[], match?: ((array1: readonly unknown[], array2: readonly unknown[], index1: number, index2: number, context: MatchContext) => boolean | undefined) | undefined, context?: MatchContext | undefined) => Subsequence;
};
export default _default;

74
node_modules/jsondiffpatch/lib/filters/lcs.js generated vendored Normal file
View File

@@ -0,0 +1,74 @@
/*
LCS implementation that supports arrays or strings
reference: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
*/
const defaultMatch = function (array1, array2, index1, index2) {
return array1[index1] === array2[index2];
};
const lengthMatrix = function (array1, array2, match, context) {
const len1 = array1.length;
const len2 = array2.length;
let x, y;
// initialize empty matrix of len1+1 x len2+1
const matrix = new Array(len1 + 1);
for (x = 0; x < len1 + 1; x++) {
matrix[x] = new Array(len2 + 1);
for (y = 0; y < len2 + 1; y++) {
matrix[x][y] = 0;
}
}
matrix.match = match;
// save sequence lengths for each coordinate
for (x = 1; x < len1 + 1; x++) {
for (y = 1; y < len2 + 1; y++) {
if (match(array1, array2, x - 1, y - 1, context)) {
matrix[x][y] = matrix[x - 1][y - 1] + 1;
}
else {
matrix[x][y] = Math.max(matrix[x - 1][y], matrix[x][y - 1]);
}
}
}
return matrix;
};
const backtrack = function (matrix, array1, array2, context) {
let index1 = array1.length;
let index2 = array2.length;
const subsequence = {
sequence: [],
indices1: [],
indices2: [],
};
while (index1 !== 0 && index2 !== 0) {
const sameLetter = matrix.match(array1, array2, index1 - 1, index2 - 1, context);
if (sameLetter) {
subsequence.sequence.unshift(array1[index1 - 1]);
subsequence.indices1.unshift(index1 - 1);
subsequence.indices2.unshift(index2 - 1);
--index1;
--index2;
}
else {
const valueAtMatrixAbove = matrix[index1][index2 - 1];
const valueAtMatrixLeft = matrix[index1 - 1][index2];
if (valueAtMatrixAbove > valueAtMatrixLeft) {
--index2;
}
else {
--index1;
}
}
}
return subsequence;
};
const get = function (array1, array2, match, context) {
const innerContext = context || {};
const matrix = lengthMatrix(array1, array2, match || defaultMatch, innerContext);
return backtrack(matrix, array1, array2, innerContext);
};
export default {
get,
};

10
node_modules/jsondiffpatch/lib/filters/nested.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import DiffContext from '../contexts/diff.js';
import PatchContext from '../contexts/patch.js';
import ReverseContext from '../contexts/reverse.js';
import type { Filter } from '../types.js';
export declare const collectChildrenDiffFilter: Filter<DiffContext>;
export declare const objectsDiffFilter: Filter<DiffContext>;
export declare const patchFilter: Filter<PatchContext>;
export declare const collectChildrenPatchFilter: Filter<PatchContext>;
export declare const reverseFilter: Filter<ReverseContext>;
export declare const collectChildrenReverseFilter: Filter<ReverseContext>;

144
node_modules/jsondiffpatch/lib/filters/nested.js generated vendored Normal file
View File

@@ -0,0 +1,144 @@
import DiffContext from '../contexts/diff.js';
import PatchContext from '../contexts/patch.js';
import ReverseContext from '../contexts/reverse.js';
export const collectChildrenDiffFilter = (context) => {
if (!context || !context.children) {
return;
}
const length = context.children.length;
let child;
let result = context.result;
for (let index = 0; index < length; index++) {
child = context.children[index];
if (typeof child.result === 'undefined') {
continue;
}
result = result || {};
result[child.childName] = child.result;
}
if (result && context.leftIsArray) {
result._t = 'a';
}
context.setResult(result).exit();
};
collectChildrenDiffFilter.filterName = 'collectChildren';
export const objectsDiffFilter = (context) => {
if (context.leftIsArray || context.leftType !== 'object') {
return;
}
const left = context.left;
const right = context.right;
let name;
let child;
const propertyFilter = context.options.propertyFilter;
for (name in left) {
if (!Object.prototype.hasOwnProperty.call(left, name)) {
continue;
}
if (propertyFilter && !propertyFilter(name, context)) {
continue;
}
child = new DiffContext(left[name], right[name]);
context.push(child, name);
}
for (name in right) {
if (!Object.prototype.hasOwnProperty.call(right, name)) {
continue;
}
if (propertyFilter && !propertyFilter(name, context)) {
continue;
}
if (typeof left[name] === 'undefined') {
child = new DiffContext(undefined, right[name]);
context.push(child, name);
}
}
if (!context.children || context.children.length === 0) {
context.setResult(undefined).exit();
return;
}
context.exit();
};
objectsDiffFilter.filterName = 'objects';
export const patchFilter = function nestedPatchFilter(context) {
if (!context.nested) {
return;
}
const nestedDelta = context.delta;
if (nestedDelta._t) {
return;
}
const objectDelta = nestedDelta;
let name;
let child;
for (name in objectDelta) {
child = new PatchContext(context.left[name], objectDelta[name]);
context.push(child, name);
}
context.exit();
};
patchFilter.filterName = 'objects';
export const collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
if (!context || !context.children) {
return;
}
const deltaWithChildren = context.delta;
if (deltaWithChildren._t) {
return;
}
const object = context.left;
const length = context.children.length;
let child;
for (let index = 0; index < length; index++) {
child = context.children[index];
const property = child.childName;
if (Object.prototype.hasOwnProperty.call(context.left, property) &&
child.result === undefined) {
delete object[property];
}
else if (object[property] !== child.result) {
object[property] = child.result;
}
}
context.setResult(object).exit();
};
collectChildrenPatchFilter.filterName = 'collectChildren';
export const reverseFilter = function nestedReverseFilter(context) {
if (!context.nested) {
return;
}
const nestedDelta = context.delta;
if (nestedDelta._t) {
return;
}
const objectDelta = context.delta;
let name;
let child;
for (name in objectDelta) {
child = new ReverseContext(objectDelta[name]);
context.push(child, name);
}
context.exit();
};
reverseFilter.filterName = 'objects';
export const collectChildrenReverseFilter = (context) => {
if (!context || !context.children) {
return;
}
const deltaWithChildren = context.delta;
if (deltaWithChildren._t) {
return;
}
const length = context.children.length;
let child;
const delta = {};
for (let index = 0; index < length; index++) {
child = context.children[index];
const property = child.childName;
if (delta[property] !== child.result) {
delta[property] = child.result;
}
}
context.setResult(delta).exit();
};
collectChildrenReverseFilter.filterName = 'collectChildren';

7
node_modules/jsondiffpatch/lib/filters/texts.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import type DiffContext from '../contexts/diff.js';
import type PatchContext from '../contexts/patch.js';
import type ReverseContext from '../contexts/reverse.js';
import type { Filter } from '../types.js';
export declare const diffFilter: Filter<DiffContext>;
export declare const patchFilter: Filter<PatchContext>;
export declare const reverseFilter: Filter<ReverseContext>;

134
node_modules/jsondiffpatch/lib/filters/texts.js generated vendored Normal file
View File

@@ -0,0 +1,134 @@
const TEXT_DIFF = 2;
const DEFAULT_MIN_LENGTH = 60;
let cachedDiffPatch = null;
function getDiffMatchPatch(options, required) {
var _a;
if (!cachedDiffPatch) {
let instance;
if ((_a = options === null || options === void 0 ? void 0 : options.textDiff) === null || _a === void 0 ? void 0 : _a.diffMatchPatch) {
instance = new options.textDiff.diffMatchPatch();
}
else {
if (!required) {
return null;
}
const error = new Error('The diff-match-patch library was not provided. Pass the library in through the options or use the `jsondiffpatch/with-text-diffs` entry-point.');
// eslint-disable-next-line camelcase
error.diff_match_patch_not_found = true;
throw error;
}
cachedDiffPatch = {
diff: function (txt1, txt2) {
return instance.patch_toText(instance.patch_make(txt1, txt2));
},
patch: function (txt1, patch) {
const results = instance.patch_apply(instance.patch_fromText(patch), txt1);
for (let i = 0; i < results[1].length; i++) {
if (!results[1][i]) {
const error = new Error('text patch failed');
error.textPatchFailed = true;
}
}
return results[0];
},
};
}
return cachedDiffPatch;
}
export const diffFilter = function textsDiffFilter(context) {
if (context.leftType !== 'string') {
return;
}
const left = context.left;
const right = context.right;
const minLength = (context.options &&
context.options.textDiff &&
context.options.textDiff.minLength) ||
DEFAULT_MIN_LENGTH;
if (left.length < minLength || right.length < minLength) {
context.setResult([left, right]).exit();
return;
}
// large text, try to use a text-diff algorithm
const diffMatchPatch = getDiffMatchPatch(context.options);
if (!diffMatchPatch) {
// diff-match-patch library not available,
// fallback to regular string replace
context.setResult([left, right]).exit();
return;
}
const diff = diffMatchPatch.diff;
context.setResult([diff(left, right), 0, TEXT_DIFF]).exit();
};
diffFilter.filterName = 'texts';
export const patchFilter = function textsPatchFilter(context) {
if (context.nested) {
return;
}
const nonNestedDelta = context.delta;
if (nonNestedDelta[2] !== TEXT_DIFF) {
return;
}
const textDiffDelta = nonNestedDelta;
// text-diff, use a text-patch algorithm
const patch = getDiffMatchPatch(context.options, true).patch;
context.setResult(patch(context.left, textDiffDelta[0])).exit();
};
patchFilter.filterName = 'texts';
const textDeltaReverse = function (delta) {
let i;
let l;
let line;
let lineTmp;
let header = null;
const headerRegex = /^@@ +-(\d+),(\d+) +\+(\d+),(\d+) +@@$/;
let lineHeader;
const lines = delta.split('\n');
for (i = 0, l = lines.length; i < l; i++) {
line = lines[i];
const lineStart = line.slice(0, 1);
if (lineStart === '@') {
header = headerRegex.exec(line);
lineHeader = i;
// fix header
lines[lineHeader] =
'@@ -' +
header[3] +
',' +
header[4] +
' +' +
header[1] +
',' +
header[2] +
' @@';
}
else if (lineStart === '+') {
lines[i] = '-' + lines[i].slice(1);
if (lines[i - 1].slice(0, 1) === '+') {
// swap lines to keep default order (-+)
lineTmp = lines[i];
lines[i] = lines[i - 1];
lines[i - 1] = lineTmp;
}
}
else if (lineStart === '-') {
lines[i] = '+' + lines[i].slice(1);
}
}
return lines.join('\n');
};
export const reverseFilter = function textsReverseFilter(context) {
if (context.nested) {
return;
}
const nonNestedDelta = context.delta;
if (nonNestedDelta[2] !== TEXT_DIFF) {
return;
}
const textDiffDelta = nonNestedDelta;
// text-diff, use a text-diff algorithm
context
.setResult([textDeltaReverse(textDiffDelta[0]), 0, TEXT_DIFF])
.exit();
};
reverseFilter.filterName = 'texts';

7
node_modules/jsondiffpatch/lib/filters/trivial.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import type DiffContext from '../contexts/diff.js';
import type PatchContext from '../contexts/patch.js';
import type ReverseContext from '../contexts/reverse.js';
import type { Filter } from '../types.js';
export declare const diffFilter: Filter<DiffContext>;
export declare const patchFilter: Filter<PatchContext>;
export declare const reverseFilter: Filter<ReverseContext>;

105
node_modules/jsondiffpatch/lib/filters/trivial.js generated vendored Normal file
View File

@@ -0,0 +1,105 @@
export const diffFilter = function trivialMatchesDiffFilter(context) {
if (context.left === context.right) {
context.setResult(undefined).exit();
return;
}
if (typeof context.left === 'undefined') {
if (typeof context.right === 'function') {
throw new Error('functions are not supported');
}
context.setResult([context.right]).exit();
return;
}
if (typeof context.right === 'undefined') {
context.setResult([context.left, 0, 0]).exit();
return;
}
if (typeof context.left === 'function' ||
typeof context.right === 'function') {
throw new Error('functions are not supported');
}
context.leftType = context.left === null ? 'null' : typeof context.left;
context.rightType = context.right === null ? 'null' : typeof context.right;
if (context.leftType !== context.rightType) {
context.setResult([context.left, context.right]).exit();
return;
}
if (context.leftType === 'boolean' || context.leftType === 'number') {
context.setResult([context.left, context.right]).exit();
return;
}
if (context.leftType === 'object') {
context.leftIsArray = Array.isArray(context.left);
}
if (context.rightType === 'object') {
context.rightIsArray = Array.isArray(context.right);
}
if (context.leftIsArray !== context.rightIsArray) {
context.setResult([context.left, context.right]).exit();
return;
}
if (context.left instanceof RegExp) {
if (context.right instanceof RegExp) {
context
.setResult([context.left.toString(), context.right.toString()])
.exit();
}
else {
context.setResult([context.left, context.right]).exit();
}
}
};
diffFilter.filterName = 'trivial';
export const patchFilter = function trivialMatchesPatchFilter(context) {
if (typeof context.delta === 'undefined') {
context.setResult(context.left).exit();
return;
}
context.nested = !Array.isArray(context.delta);
if (context.nested) {
return;
}
const nonNestedDelta = context.delta;
if (nonNestedDelta.length === 1) {
context.setResult(nonNestedDelta[0]).exit();
return;
}
if (nonNestedDelta.length === 2) {
if (context.left instanceof RegExp) {
const regexArgs = /^\/(.*)\/([gimyu]+)$/.exec(nonNestedDelta[1]);
if (regexArgs) {
context.setResult(new RegExp(regexArgs[1], regexArgs[2])).exit();
return;
}
}
context.setResult(nonNestedDelta[1]).exit();
return;
}
if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
context.setResult(undefined).exit();
}
};
patchFilter.filterName = 'trivial';
export const reverseFilter = function trivialReferseFilter(context) {
if (typeof context.delta === 'undefined') {
context.setResult(context.delta).exit();
return;
}
context.nested = !Array.isArray(context.delta);
if (context.nested) {
return;
}
const nonNestedDelta = context.delta;
if (nonNestedDelta.length === 1) {
context.setResult([nonNestedDelta[0], 0, 0]).exit();
return;
}
if (nonNestedDelta.length === 2) {
context.setResult([nonNestedDelta[1], nonNestedDelta[0]]).exit();
return;
}
if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
context.setResult([nonNestedDelta[0]]).exit();
}
};
reverseFilter.filterName = 'trivial';

View File

@@ -0,0 +1,29 @@
import BaseFormatter from './base.js';
import type { BaseFormatterContext, DeltaType, NodeType } from './base.js';
import type { AddedDelta, ArrayDelta, DeletedDelta, Delta, ModifiedDelta, MovedDelta, ObjectDelta, TextDiffDelta } from '../types.js';
interface AnnotatedFormatterContext extends BaseFormatterContext {
indentLevel?: number;
indentPad?: string;
indent: (levels?: number) => void;
row: (json: string, htmlNote?: string) => void;
}
declare class AnnotatedFormatter extends BaseFormatter<AnnotatedFormatterContext> {
constructor();
prepareContext(context: Partial<AnnotatedFormatterContext>): void;
typeFormattterErrorFormatter(context: AnnotatedFormatterContext, err: unknown): void;
formatTextDiffString(context: AnnotatedFormatterContext, value: string): void;
rootBegin(context: AnnotatedFormatterContext, type: DeltaType, nodeType: NodeType): void;
rootEnd(context: AnnotatedFormatterContext, type: DeltaType): void;
nodeBegin(context: AnnotatedFormatterContext, key: string, leftKey: string | number, type: DeltaType, nodeType: NodeType): void;
nodeEnd(context: AnnotatedFormatterContext, key: string, leftKey: string | number, type: DeltaType, nodeType: NodeType, isLast: boolean): void;
format_unchanged(): void;
format_movedestination(): void;
format_node(context: AnnotatedFormatterContext, delta: ObjectDelta | ArrayDelta, left: unknown): void;
format_added(context: AnnotatedFormatterContext, delta: AddedDelta, left: unknown, key: string | undefined, leftKey: string | number | undefined): void;
format_modified(context: AnnotatedFormatterContext, delta: ModifiedDelta, left: unknown, key: string | undefined, leftKey: string | number | undefined): void;
format_deleted(context: AnnotatedFormatterContext, delta: DeletedDelta, left: unknown, key: string | undefined, leftKey: string | number | undefined): void;
format_moved(context: AnnotatedFormatterContext, delta: MovedDelta, left: unknown, key: string | undefined, leftKey: string | number | undefined): void;
format_textdiff(context: AnnotatedFormatterContext, delta: TextDiffDelta, left: unknown, key: string | undefined, leftKey: string | number | undefined): void;
}
export default AnnotatedFormatter;
export declare function format(delta: Delta, left?: unknown): string | undefined;

169
node_modules/jsondiffpatch/lib/formatters/annotated.js generated vendored Normal file
View File

@@ -0,0 +1,169 @@
import BaseFormatter from './base.js';
class AnnotatedFormatter extends BaseFormatter {
constructor() {
super();
this.includeMoveDestinations = false;
}
prepareContext(context) {
super.prepareContext(context);
context.indent = function (levels) {
this.indentLevel =
(this.indentLevel || 0) + (typeof levels === 'undefined' ? 1 : levels);
this.indentPad = new Array(this.indentLevel + 1).join('&nbsp;&nbsp;');
};
context.row = (json, htmlNote) => {
context.out('<tr><td style="white-space: nowrap;">' +
'<pre class="jsondiffpatch-annotated-indent"' +
' style="display: inline-block">');
if (context.indentPad != null)
context.out(context.indentPad);
context.out('</pre><pre style="display: inline-block">');
context.out(json);
context.out('</pre></td><td class="jsondiffpatch-delta-note"><div>');
if (htmlNote != null)
context.out(htmlNote);
context.out('</div></td></tr>');
};
}
typeFormattterErrorFormatter(context, err) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
context.row('', `<pre class="jsondiffpatch-error">${err}</pre>`);
}
formatTextDiffString(context, value) {
const lines = this.parseTextDiff(value);
context.out('<ul class="jsondiffpatch-textdiff">');
for (let i = 0, l = lines.length; i < l; i++) {
const line = lines[i];
context.out('<li><div class="jsondiffpatch-textdiff-location">' +
`<span class="jsondiffpatch-textdiff-line-number">${line.location.line}</span><span class="jsondiffpatch-textdiff-char">${line.location.chr}</span></div><div class="jsondiffpatch-textdiff-line">`);
const pieces = line.pieces;
for (let pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
const piece = pieces[pieceIndex];
context.out(`<span class="jsondiffpatch-textdiff-${piece.type}">${piece.text}</span>`);
}
context.out('</div></li>');
}
context.out('</ul>');
}
rootBegin(context, type, nodeType) {
context.out('<table class="jsondiffpatch-annotated-delta">');
if (type === 'node') {
context.row('{');
context.indent();
}
if (nodeType === 'array') {
context.row('"_t": "a",', 'Array delta (member names indicate array indices)');
}
}
rootEnd(context, type) {
if (type === 'node') {
context.indent(-1);
context.row('}');
}
context.out('</table>');
}
nodeBegin(context, key, leftKey, type, nodeType) {
context.row(`&quot;${key}&quot;: {`);
if (type === 'node') {
context.indent();
}
if (nodeType === 'array') {
context.row('"_t": "a",', 'Array delta (member names indicate array indices)');
}
}
nodeEnd(context, key, leftKey, type, nodeType, isLast) {
if (type === 'node') {
context.indent(-1);
}
context.row(`}${isLast ? '' : ','}`);
}
format_unchanged() { }
format_movedestination() { }
format_node(context, delta, left) {
// recurse
this.formatDeltaChildren(context, delta, left);
}
format_added(context, delta, left, key, leftKey) {
formatAnyChange.call(this, context, delta, left, key, leftKey);
}
format_modified(context, delta, left, key, leftKey) {
formatAnyChange.call(this, context, delta, left, key, leftKey);
}
format_deleted(context, delta, left, key, leftKey) {
formatAnyChange.call(this, context, delta, left, key, leftKey);
}
format_moved(context, delta, left, key, leftKey) {
formatAnyChange.call(this, context, delta, left, key, leftKey);
}
format_textdiff(context, delta, left, key, leftKey) {
formatAnyChange.call(this, context, delta, left, key, leftKey);
}
}
const wrapPropertyName = (name) => `<pre style="display:inline-block">&quot;${name}&quot;</pre>`;
const deltaAnnotations = {
added(delta, left, key, leftKey) {
const formatLegend = ' <pre>([newValue])</pre>';
if (typeof leftKey === 'undefined') {
return `new value${formatLegend}`;
}
if (typeof leftKey === 'number') {
return `insert at index ${leftKey}${formatLegend}`;
}
return `add property ${wrapPropertyName(leftKey)}${formatLegend}`;
},
modified(delta, left, key, leftKey) {
const formatLegend = ' <pre>([previousValue, newValue])</pre>';
if (typeof leftKey === 'undefined') {
return `modify value${formatLegend}`;
}
if (typeof leftKey === 'number') {
return `modify at index ${leftKey}${formatLegend}`;
}
return `modify property ${wrapPropertyName(leftKey)}${formatLegend}`;
},
deleted(delta, left, key, leftKey) {
const formatLegend = ' <pre>([previousValue, 0, 0])</pre>';
if (typeof leftKey === 'undefined') {
return `delete value${formatLegend}`;
}
if (typeof leftKey === 'number') {
return `remove index ${leftKey}${formatLegend}`;
}
return `delete property ${wrapPropertyName(leftKey)}${formatLegend}`;
},
moved(delta, left, key, leftKey) {
return ('move from <span title="(position to remove at original state)">' +
`index ${leftKey}</span> to <span title="(position to insert at final` +
` state)">index ${delta[1]}</span>`);
},
textdiff(delta, left, key, leftKey) {
const location = typeof leftKey === 'undefined'
? ''
: typeof leftKey === 'number'
? ` at index ${leftKey}`
: ` at property ${wrapPropertyName(leftKey)}`;
return (`text diff${location}, format is <a href="https://code.google.com/` +
'p/google-diff-match-patch/wiki/Unidiff">a variation of Unidiff</a>');
},
};
const formatAnyChange = function (context, delta, left, key, leftKey) {
const deltaType = this.getDeltaType(delta);
const annotator = deltaAnnotations[deltaType];
const htmlNote = annotator && annotator(delta, left, key, leftKey);
let json = JSON.stringify(delta, null, 2);
if (deltaType === 'textdiff') {
// split text diffs lines
json = json.split('\\n').join('\\n"+\n "');
}
context.indent();
context.row(json, htmlNote);
context.indent(-1);
};
export default AnnotatedFormatter;
let defaultInstance;
export function format(delta, left) {
if (!defaultInstance) {
defaultInstance = new AnnotatedFormatter();
}
return defaultInstance.format(delta, left);
}

59
node_modules/jsondiffpatch/lib/formatters/base.d.ts generated vendored Normal file
View File

@@ -0,0 +1,59 @@
import type { AddedDelta, ArrayDelta, DeletedDelta, Delta, ModifiedDelta, MovedDelta, ObjectDelta, TextDiffDelta } from '../types.js';
export interface BaseFormatterContext {
buffer: string[];
out: (...args: string[]) => void;
}
export type DeltaType = 'movedestination' | 'unchanged' | 'added' | 'modified' | 'deleted' | 'textdiff' | 'moved' | 'node' | 'unknown';
export type NodeType = 'array' | 'object' | '';
interface DeltaTypeMap {
movedestination: undefined;
unchanged: undefined;
added: AddedDelta;
modified: ModifiedDelta;
deleted: DeletedDelta;
textdiff: TextDiffDelta;
moved: MovedDelta;
node: ObjectDelta | ArrayDelta;
}
interface MoveDestination {
key: `_${number}`;
value: unknown;
}
interface LineOutputPiece {
type: 'context' | 'added' | 'deleted';
text: string;
}
interface LineOutputLocation {
line: string;
chr: string;
}
interface LineOutput {
pieces: LineOutputPiece[];
location: LineOutputLocation;
}
declare abstract class BaseFormatter<TContext extends BaseFormatterContext, TFormatted = string | undefined> {
includeMoveDestinations?: boolean;
format(delta: Delta, left?: unknown): TFormatted;
prepareContext(context: Partial<TContext>): void;
typeFormattterNotFound(context: TContext, deltaType: 'unknown'): never;
typeFormattterErrorFormatter(context: TContext, err: unknown, delta: Delta, leftValue: unknown, key: string | undefined, leftKey: string | number | undefined, movedFrom: MoveDestination | undefined): void;
finalize({ buffer }: TContext): string | undefined;
recurse<TDeltaType extends keyof DeltaTypeMap>(context: TContext, delta: DeltaTypeMap[TDeltaType], left: unknown, key?: string, leftKey?: string | number, movedFrom?: MoveDestination | undefined, isLast?: boolean): undefined;
formatDeltaChildren(context: TContext, delta: ObjectDelta | ArrayDelta, left: unknown): void;
forEachDeltaKey(delta: ObjectDelta | ArrayDelta, left: unknown, fn: (key: string, leftKey: string | number, moveDestination: MoveDestination | undefined, isLast: boolean) => void): void;
getDeltaType(delta: Delta, movedFrom?: MoveDestination | undefined): "unknown" | "movedestination" | "unchanged" | "added" | "modified" | "deleted" | "textdiff" | "moved" | "node";
parseTextDiff(value: string): LineOutput[];
abstract rootBegin(context: TContext, type: DeltaType, nodeType: NodeType): void;
abstract rootEnd(context: TContext, type: DeltaType, nodeType: NodeType): void;
abstract nodeBegin(context: TContext, key: string, leftKey: string | number, type: DeltaType, nodeType: NodeType, isLast: boolean): void;
abstract nodeEnd(context: TContext, key: string, leftKey: string | number, type: DeltaType, nodeType: NodeType, isLast: boolean): void;
abstract format_unchanged(context: TContext, delta: undefined, leftValue: unknown, key: string | undefined, leftKey: string | number | undefined, movedFrom: MoveDestination | undefined): void;
abstract format_movedestination(context: TContext, delta: undefined, leftValue: unknown, key: string | undefined, leftKey: string | number | undefined, movedFrom: MoveDestination | undefined): void;
abstract format_node(context: TContext, delta: ObjectDelta | ArrayDelta, leftValue: unknown, key: string | undefined, leftKey: string | number | undefined, movedFrom: MoveDestination | undefined): void;
abstract format_added(context: TContext, delta: AddedDelta, leftValue: unknown, key: string | undefined, leftKey: string | number | undefined, movedFrom: MoveDestination | undefined): void;
abstract format_modified(context: TContext, delta: ModifiedDelta, leftValue: unknown, key: string | undefined, leftKey: string | number | undefined, movedFrom: MoveDestination | undefined): void;
abstract format_deleted(context: TContext, delta: DeletedDelta, leftValue: unknown, key: string | undefined, leftKey: string | number | undefined, movedFrom: MoveDestination | undefined): void;
abstract format_moved(context: TContext, delta: MovedDelta, leftValue: unknown, key: string | undefined, leftKey: string | number | undefined, movedFrom: MoveDestination | undefined): void;
abstract format_textdiff(context: TContext, delta: TextDiffDelta, leftValue: unknown, key: string | undefined, leftKey: string | number | undefined, movedFrom: MoveDestination | undefined): void;
}
export default BaseFormatter;

207
node_modules/jsondiffpatch/lib/formatters/base.js generated vendored Normal file
View File

@@ -0,0 +1,207 @@
const trimUnderscore = (str) => {
if (str.substring(0, 1) === '_') {
return str.slice(1);
}
return str;
};
const arrayKeyToSortNumber = (key) => {
if (key === '_t') {
return -1;
}
else {
if (key.substring(0, 1) === '_') {
return parseInt(key.slice(1), 10);
}
else {
return parseInt(key, 10) + 0.1;
}
}
};
const arrayKeyComparer = (key1, key2) => arrayKeyToSortNumber(key1) - arrayKeyToSortNumber(key2);
class BaseFormatter {
format(delta, left) {
const context = {};
this.prepareContext(context);
const preparedContext = context;
this.recurse(preparedContext, delta, left);
return this.finalize(preparedContext);
}
prepareContext(context) {
context.buffer = [];
context.out = function (...args) {
this.buffer.push(...args);
};
}
typeFormattterNotFound(context, deltaType) {
throw new Error(`cannot format delta type: ${deltaType}`);
}
/* eslint-disable @typescript-eslint/no-unused-vars */
typeFormattterErrorFormatter(context, err, delta, leftValue, key, leftKey, movedFrom) { }
/* eslint-enable @typescript-eslint/no-unused-vars */
finalize({ buffer }) {
if (Array.isArray(buffer)) {
return buffer.join('');
}
}
recurse(context, delta, left, key, leftKey, movedFrom, isLast) {
const useMoveOriginHere = delta && movedFrom;
const leftValue = useMoveOriginHere ? movedFrom.value : left;
if (typeof delta === 'undefined' && typeof key === 'undefined') {
return undefined;
}
const type = this.getDeltaType(delta, movedFrom);
const nodeType = type === 'node'
? delta._t === 'a'
? 'array'
: 'object'
: '';
if (typeof key !== 'undefined') {
this.nodeBegin(context, key, leftKey, type, nodeType, isLast);
}
else {
this.rootBegin(context, type, nodeType);
}
let typeFormattter;
try {
typeFormattter =
type !== 'unknown'
? this[`format_${type}`]
: this.typeFormattterNotFound(context, type);
typeFormattter.call(this, context, delta, leftValue, key, leftKey, movedFrom);
}
catch (err) {
this.typeFormattterErrorFormatter(context, err, delta, leftValue, key, leftKey, movedFrom);
if (typeof console !== 'undefined' && console.error) {
console.error(err.stack);
}
}
if (typeof key !== 'undefined') {
this.nodeEnd(context, key, leftKey, type, nodeType, isLast);
}
else {
this.rootEnd(context, type, nodeType);
}
}
formatDeltaChildren(context, delta, left) {
this.forEachDeltaKey(delta, left, (key, leftKey, movedFrom, isLast) => {
this.recurse(context, delta[key], left ? left[leftKey] : undefined, key, leftKey, movedFrom, isLast);
});
}
forEachDeltaKey(delta, left, fn) {
const keys = Object.keys(delta);
const arrayKeys = delta._t === 'a';
const moveDestinations = {};
let name;
if (typeof left !== 'undefined') {
for (name in left) {
if (Object.prototype.hasOwnProperty.call(left, name)) {
if (typeof delta[name] === 'undefined' &&
(!arrayKeys ||
typeof delta[`_${name}`] ===
'undefined')) {
keys.push(name);
}
}
}
}
// look for move destinations
for (name in delta) {
if (Object.prototype.hasOwnProperty.call(delta, name)) {
const value = delta[name];
if (Array.isArray(value) && value[2] === 3) {
const movedDelta = value;
moveDestinations[`${movedDelta[1]}`] = {
key: name,
value: left && left[parseInt(name.substring(1), 10)],
};
if (this.includeMoveDestinations !== false) {
if (typeof left === 'undefined' &&
typeof delta[movedDelta[1]] === 'undefined') {
keys.push(movedDelta[1].toString());
}
}
}
}
}
if (arrayKeys) {
keys.sort(arrayKeyComparer);
}
else {
keys.sort();
}
for (let index = 0, length = keys.length; index < length; index++) {
const key = keys[index];
if (arrayKeys && key === '_t') {
continue;
}
const leftKey = arrayKeys ? parseInt(trimUnderscore(key), 10) : key;
const isLast = index === length - 1;
fn(key, leftKey, moveDestinations[leftKey], isLast);
}
}
getDeltaType(delta, movedFrom) {
if (typeof delta === 'undefined') {
if (typeof movedFrom !== 'undefined') {
return 'movedestination';
}
return 'unchanged';
}
if (Array.isArray(delta)) {
if (delta.length === 1) {
return 'added';
}
if (delta.length === 2) {
return 'modified';
}
if (delta.length === 3 && delta[2] === 0) {
return 'deleted';
}
if (delta.length === 3 && delta[2] === 2) {
return 'textdiff';
}
if (delta.length === 3 && delta[2] === 3) {
return 'moved';
}
}
else if (typeof delta === 'object') {
return 'node';
}
return 'unknown';
}
parseTextDiff(value) {
const output = [];
const lines = value.split('\n@@ ');
for (let i = 0, l = lines.length; i < l; i++) {
const line = lines[i];
const lineOutput = {
pieces: [],
};
const location = /^(?:@@ )?[-+]?(\d+),(\d+)/.exec(line).slice(1);
lineOutput.location = {
line: location[0],
chr: location[1],
};
const pieces = line.split('\n').slice(1);
for (let pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
const piece = pieces[pieceIndex];
if (!piece.length) {
continue;
}
const pieceOutput = {
type: 'context',
};
if (piece.substring(0, 1) === '+') {
pieceOutput.type = 'added';
}
else if (piece.substring(0, 1) === '-') {
pieceOutput.type = 'deleted';
}
pieceOutput.text = piece.slice(1);
lineOutput.pieces.push(pieceOutput);
}
output.push(lineOutput);
}
return output;
}
}
export default BaseFormatter;

35
node_modules/jsondiffpatch/lib/formatters/console.d.ts generated vendored Normal file
View File

@@ -0,0 +1,35 @@
import type { ChalkInstance } from 'chalk';
import BaseFormatter from './base.js';
import type { BaseFormatterContext, DeltaType, NodeType } from './base.js';
import type { AddedDelta, ArrayDelta, DeletedDelta, Delta, ModifiedDelta, MovedDelta, ObjectDelta, TextDiffDelta } from '../types.js';
interface ConsoleFormatterContext extends BaseFormatterContext {
indentLevel?: number;
indentPad?: string;
outLine: () => void;
indent: (levels?: number) => void;
color?: (ChalkInstance | undefined)[];
pushColor: (color: ChalkInstance | undefined) => void;
popColor: () => void;
}
declare class ConsoleFormatter extends BaseFormatter<ConsoleFormatterContext> {
constructor();
prepareContext(context: Partial<ConsoleFormatterContext>): void;
typeFormattterErrorFormatter(context: ConsoleFormatterContext, err: unknown): void;
formatValue(context: ConsoleFormatterContext, value: unknown): void;
formatTextDiffString(context: ConsoleFormatterContext, value: string): void;
rootBegin(context: ConsoleFormatterContext, type: DeltaType, nodeType: NodeType): void;
rootEnd(context: ConsoleFormatterContext, type: DeltaType, nodeType: NodeType): void;
nodeBegin(context: ConsoleFormatterContext, key: string, leftKey: string | number, type: DeltaType, nodeType: NodeType): void;
nodeEnd(context: ConsoleFormatterContext, key: string, leftKey: string | number, type: DeltaType, nodeType: NodeType, isLast: boolean): void;
format_unchanged(context: ConsoleFormatterContext, delta: undefined, left: unknown): void;
format_movedestination(context: ConsoleFormatterContext, delta: undefined, left: unknown): void;
format_node(context: ConsoleFormatterContext, delta: ObjectDelta | ArrayDelta, left: unknown): void;
format_added(context: ConsoleFormatterContext, delta: AddedDelta): void;
format_modified(context: ConsoleFormatterContext, delta: ModifiedDelta): void;
format_deleted(context: ConsoleFormatterContext, delta: DeletedDelta): void;
format_moved(context: ConsoleFormatterContext, delta: MovedDelta): void;
format_textdiff(context: ConsoleFormatterContext, delta: TextDiffDelta): void;
}
export default ConsoleFormatter;
export declare const format: (delta: Delta, left?: unknown) => string | undefined;
export declare function log(delta: Delta, left?: unknown): void;

157
node_modules/jsondiffpatch/lib/formatters/console.js generated vendored Normal file
View File

@@ -0,0 +1,157 @@
import chalk from 'chalk';
import BaseFormatter from './base.js';
const colors = {
added: chalk.green,
deleted: chalk.red,
movedestination: chalk.gray,
moved: chalk.yellow,
unchanged: chalk.gray,
error: chalk.white.bgRed,
textDiffLine: chalk.gray,
};
class ConsoleFormatter extends BaseFormatter {
constructor() {
super();
this.includeMoveDestinations = false;
}
prepareContext(context) {
super.prepareContext(context);
context.indent = function (levels) {
this.indentLevel =
(this.indentLevel || 0) + (typeof levels === 'undefined' ? 1 : levels);
this.indentPad = new Array(this.indentLevel + 1).join(' ');
this.outLine();
};
context.outLine = function () {
this.buffer.push(`\n${this.indentPad || ''}`);
};
context.out = function (...args) {
for (let i = 0, l = args.length; i < l; i++) {
const lines = args[i].split('\n');
let text = lines.join(`\n${this.indentPad || ''}`);
if (this.color && this.color[0]) {
text = this.color[0](text);
}
this.buffer.push(text);
}
};
context.pushColor = function (color) {
this.color = this.color || [];
this.color.unshift(color);
};
context.popColor = function () {
this.color = this.color || [];
this.color.shift();
};
}
typeFormattterErrorFormatter(context, err) {
context.pushColor(colors.error);
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
context.out(`[ERROR]${err}`);
context.popColor();
}
formatValue(context, value) {
context.out(JSON.stringify(value, null, 2));
}
formatTextDiffString(context, value) {
const lines = this.parseTextDiff(value);
context.indent();
for (let i = 0, l = lines.length; i < l; i++) {
const line = lines[i];
context.pushColor(colors.textDiffLine);
context.out(`${line.location.line},${line.location.chr} `);
context.popColor();
const pieces = line.pieces;
for (let pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
const piece = pieces[pieceIndex];
context.pushColor(colors[piece.type]);
context.out(piece.text);
context.popColor();
}
if (i < l - 1) {
context.outLine();
}
}
context.indent(-1);
}
rootBegin(context, type, nodeType) {
context.pushColor(colors[type]);
if (type === 'node') {
context.out(nodeType === 'array' ? '[' : '{');
context.indent();
}
}
rootEnd(context, type, nodeType) {
if (type === 'node') {
context.indent(-1);
context.out(nodeType === 'array' ? ']' : '}');
}
context.popColor();
}
nodeBegin(context, key, leftKey, type, nodeType) {
context.pushColor(colors[type]);
context.out(`${leftKey}: `);
if (type === 'node') {
context.out(nodeType === 'array' ? '[' : '{');
context.indent();
}
}
nodeEnd(context, key, leftKey, type, nodeType, isLast) {
if (type === 'node') {
context.indent(-1);
context.out(nodeType === 'array' ? ']' : `}${isLast ? '' : ','}`);
}
if (!isLast) {
context.outLine();
}
context.popColor();
}
format_unchanged(context, delta, left) {
if (typeof left === 'undefined') {
return;
}
this.formatValue(context, left);
}
format_movedestination(context, delta, left) {
if (typeof left === 'undefined') {
return;
}
this.formatValue(context, left);
}
format_node(context, delta, left) {
// recurse
this.formatDeltaChildren(context, delta, left);
}
format_added(context, delta) {
this.formatValue(context, delta[0]);
}
format_modified(context, delta) {
context.pushColor(colors.deleted);
this.formatValue(context, delta[0]);
context.popColor();
context.out(' => ');
context.pushColor(colors.added);
this.formatValue(context, delta[1]);
context.popColor();
}
format_deleted(context, delta) {
this.formatValue(context, delta[0]);
}
format_moved(context, delta) {
context.out(`==> ${delta[1]}`);
}
format_textdiff(context, delta) {
this.formatTextDiffString(context, delta[0]);
}
}
export default ConsoleFormatter;
let defaultInstance;
export const format = (delta, left) => {
if (!defaultInstance) {
defaultInstance = new ConsoleFormatter();
}
return defaultInstance.format(delta, left);
};
export function log(delta, left) {
console.log(format(delta, left));
}

27
node_modules/jsondiffpatch/lib/formatters/html.d.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import BaseFormatter from './base.js';
import type { BaseFormatterContext, DeltaType, NodeType } from './base.js';
import type { AddedDelta, ArrayDelta, DeletedDelta, Delta, ModifiedDelta, MovedDelta, ObjectDelta, TextDiffDelta } from '../types.js';
interface HtmlFormatterContext extends BaseFormatterContext {
hasArrows?: boolean;
}
declare class HtmlFormatter extends BaseFormatter<HtmlFormatterContext> {
typeFormattterErrorFormatter(context: HtmlFormatterContext, err: unknown): void;
formatValue(context: HtmlFormatterContext, value: unknown): void;
formatTextDiffString(context: HtmlFormatterContext, value: string): void;
rootBegin(context: HtmlFormatterContext, type: DeltaType, nodeType: NodeType): void;
rootEnd(context: HtmlFormatterContext): void;
nodeBegin(context: HtmlFormatterContext, key: string, leftKey: string | number, type: DeltaType, nodeType: NodeType): void;
nodeEnd(context: HtmlFormatterContext): void;
format_unchanged(context: HtmlFormatterContext, delta: undefined, left: unknown): void;
format_movedestination(context: HtmlFormatterContext, delta: undefined, left: unknown): void;
format_node(context: HtmlFormatterContext, delta: ObjectDelta | ArrayDelta, left: unknown): void;
format_added(context: HtmlFormatterContext, delta: AddedDelta): void;
format_modified(context: HtmlFormatterContext, delta: ModifiedDelta): void;
format_deleted(context: HtmlFormatterContext, delta: DeletedDelta): void;
format_moved(context: HtmlFormatterContext, delta: MovedDelta): void;
format_textdiff(context: HtmlFormatterContext, delta: TextDiffDelta): void;
}
export declare const showUnchanged: (show?: boolean, node?: Element | null, delay?: number) => void;
export declare const hideUnchanged: (node?: Element, delay?: number) => void;
export default HtmlFormatter;
export declare function format(delta: Delta, left?: unknown): string | undefined;

238
node_modules/jsondiffpatch/lib/formatters/html.js generated vendored Normal file
View File

@@ -0,0 +1,238 @@
import BaseFormatter from './base.js';
class HtmlFormatter extends BaseFormatter {
typeFormattterErrorFormatter(context, err) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
context.out(`<pre class="jsondiffpatch-error">${err}</pre>`);
}
formatValue(context, value) {
context.out(`<pre>${htmlEscape(JSON.stringify(value, null, 2))}</pre>`);
}
formatTextDiffString(context, value) {
const lines = this.parseTextDiff(value);
context.out('<ul class="jsondiffpatch-textdiff">');
for (let i = 0, l = lines.length; i < l; i++) {
const line = lines[i];
context.out('<li><div class="jsondiffpatch-textdiff-location">' +
`<span class="jsondiffpatch-textdiff-line-number">${line.location.line}</span><span class="jsondiffpatch-textdiff-char">${line.location.chr}</span></div><div class="jsondiffpatch-textdiff-line">`);
const pieces = line.pieces;
for (let pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
const piece = pieces[pieceIndex];
context.out(`<span class="jsondiffpatch-textdiff-${piece.type}">${htmlEscape(decodeURI(piece.text))}</span>`);
}
context.out('</div></li>');
}
context.out('</ul>');
}
rootBegin(context, type, nodeType) {
const nodeClass = `jsondiffpatch-${type}${nodeType ? ` jsondiffpatch-child-node-type-${nodeType}` : ''}`;
context.out(`<div class="jsondiffpatch-delta ${nodeClass}">`);
}
rootEnd(context) {
context.out(`</div>${context.hasArrows
? '<script type="text/javascript">setTimeout(' +
`${adjustArrows.toString()},10);</script>`
: ''}`);
}
nodeBegin(context, key, leftKey, type, nodeType) {
const nodeClass = `jsondiffpatch-${type}${nodeType ? ` jsondiffpatch-child-node-type-${nodeType}` : ''}`;
context.out(`<li class="${nodeClass}" data-key="${leftKey}">` +
`<div class="jsondiffpatch-property-name">${leftKey}</div>`);
}
nodeEnd(context) {
context.out('</li>');
}
format_unchanged(context, delta, left) {
if (typeof left === 'undefined') {
return;
}
context.out('<div class="jsondiffpatch-value">');
this.formatValue(context, left);
context.out('</div>');
}
format_movedestination(context, delta, left) {
if (typeof left === 'undefined') {
return;
}
context.out('<div class="jsondiffpatch-value">');
this.formatValue(context, left);
context.out('</div>');
}
format_node(context, delta, left) {
// recurse
const nodeType = delta._t === 'a' ? 'array' : 'object';
context.out(`<ul class="jsondiffpatch-node jsondiffpatch-node-type-${nodeType}">`);
this.formatDeltaChildren(context, delta, left);
context.out('</ul>');
}
format_added(context, delta) {
context.out('<div class="jsondiffpatch-value">');
this.formatValue(context, delta[0]);
context.out('</div>');
}
format_modified(context, delta) {
context.out('<div class="jsondiffpatch-value jsondiffpatch-left-value">');
this.formatValue(context, delta[0]);
context.out('</div>' + '<div class="jsondiffpatch-value jsondiffpatch-right-value">');
this.formatValue(context, delta[1]);
context.out('</div>');
}
format_deleted(context, delta) {
context.out('<div class="jsondiffpatch-value">');
this.formatValue(context, delta[0]);
context.out('</div>');
}
format_moved(context, delta) {
context.out('<div class="jsondiffpatch-value">');
this.formatValue(context, delta[0]);
context.out(`</div><div class="jsondiffpatch-moved-destination">${delta[1]}</div>`);
// draw an SVG arrow from here to move destination
context.out(
/* jshint multistr: true */
'<div class="jsondiffpatch-arrow" ' +
`style="position: relative; left: -34px;">
<svg width="30" height="60" ` +
`style="position: absolute; display: none;">
<defs>
<marker id="markerArrow" markerWidth="8" markerHeight="8"
refx="2" refy="4"
orient="auto" markerUnits="userSpaceOnUse">
<path d="M1,1 L1,7 L7,4 L1,1" style="fill: #339;" />
</marker>
</defs>
<path d="M30,0 Q-10,25 26,50"
style="stroke: #88f; stroke-width: 2px; fill: none; ` +
`stroke-opacity: 0.5; marker-end: url(#markerArrow);"
></path>
</svg>
</div>`);
context.hasArrows = true;
}
format_textdiff(context, delta) {
context.out('<div class="jsondiffpatch-value">');
this.formatTextDiffString(context, delta[0]);
context.out('</div>');
}
}
function htmlEscape(text) {
let html = text;
const replacements = [
[/&/g, '&amp;'],
[/</g, '&lt;'],
[/>/g, '&gt;'],
[/'/g, '&apos;'],
[/"/g, '&quot;'],
];
for (let i = 0; i < replacements.length; i++) {
html = html.replace(replacements[i][0], replacements[i][1]);
}
return html;
}
const adjustArrows = function jsondiffpatchHtmlFormatterAdjustArrows(nodeArg) {
const node = nodeArg || document;
const getElementText = ({ textContent, innerText }) => textContent || innerText;
const eachByQuery = (el, query, fn) => {
const elems = el.querySelectorAll(query);
for (let i = 0, l = elems.length; i < l; i++) {
fn(elems[i]);
}
};
const eachChildren = ({ children }, fn) => {
for (let i = 0, l = children.length; i < l; i++) {
fn(children[i], i);
}
};
eachByQuery(node, '.jsondiffpatch-arrow', ({ parentNode, children, style }) => {
const arrowParent = parentNode;
const svg = children[0];
const path = svg.children[1];
svg.style.display = 'none';
const destination = getElementText(arrowParent.querySelector('.jsondiffpatch-moved-destination'));
const container = arrowParent.parentNode;
let destinationElem;
eachChildren(container, (child) => {
if (child.getAttribute('data-key') === destination) {
destinationElem = child;
}
});
if (!destinationElem) {
return;
}
try {
const distance = destinationElem.offsetTop - arrowParent.offsetTop;
svg.setAttribute('height', `${Math.abs(distance) + 6}`);
style.top = `${-8 + (distance > 0 ? 0 : distance)}px`;
const curve = distance > 0
? `M30,0 Q-10,${Math.round(distance / 2)} 26,${distance - 4}`
: `M30,${-distance} Q-10,${Math.round(-distance / 2)} 26,4`;
path.setAttribute('d', curve);
svg.style.display = '';
}
catch (err) {
// continue regardless of error
}
});
};
export const showUnchanged = (show, node, delay) => {
const el = node || document.body;
const prefix = 'jsondiffpatch-unchanged-';
const classes = {
showing: `${prefix}showing`,
hiding: `${prefix}hiding`,
visible: `${prefix}visible`,
hidden: `${prefix}hidden`,
};
const list = el.classList;
if (!list) {
return;
}
if (!delay) {
list.remove(classes.showing);
list.remove(classes.hiding);
list.remove(classes.visible);
list.remove(classes.hidden);
if (show === false) {
list.add(classes.hidden);
}
return;
}
if (show === false) {
list.remove(classes.showing);
list.add(classes.visible);
setTimeout(() => {
list.add(classes.hiding);
}, 10);
}
else {
list.remove(classes.hiding);
list.add(classes.showing);
list.remove(classes.hidden);
}
const intervalId = setInterval(() => {
adjustArrows(el);
}, 100);
setTimeout(() => {
list.remove(classes.showing);
list.remove(classes.hiding);
if (show === false) {
list.add(classes.hidden);
list.remove(classes.visible);
}
else {
list.add(classes.visible);
list.remove(classes.hidden);
}
setTimeout(() => {
list.remove(classes.visible);
clearInterval(intervalId);
}, delay + 400);
}, delay);
};
export const hideUnchanged = (node, delay) => showUnchanged(false, node, delay);
export default HtmlFormatter;
let defaultInstance;
export function format(delta, left) {
if (!defaultInstance) {
defaultInstance = new HtmlFormatter();
}
return defaultInstance.format(delta, left);
}

View File

@@ -0,0 +1,61 @@
import BaseFormatter from './base.js';
import type { BaseFormatterContext } from './base.js';
import type { AddedDelta, ArrayDelta, Delta, ModifiedDelta, MovedDelta, ObjectDelta } from '../types.js';
export interface AddOp {
op: 'add';
path: string;
value: unknown;
}
export interface RemoveOp {
op: 'remove';
path: string;
}
export interface ReplaceOp {
op: 'replace';
path: string;
value: unknown;
}
export interface MoveOp {
op: 'move';
from: string;
path: string;
}
export type Op = AddOp | RemoveOp | ReplaceOp | MoveOp;
interface JSONFormatterContext extends BaseFormatterContext {
result: Op[];
path: (string | number)[];
pushCurrentOp: (obj: {
op: 'add';
value: unknown;
} | {
op: 'remove';
} | {
op: 'replace';
value: unknown;
}) => void;
pushMoveOp: (to: number) => void;
currentPath: () => string;
toPath: (to: number) => string;
}
declare class JSONFormatter extends BaseFormatter<JSONFormatterContext, Op[]> {
constructor();
prepareContext(context: Partial<JSONFormatterContext>): void;
typeFormattterErrorFormatter(context: JSONFormatterContext, err: unknown): void;
rootBegin(): void;
rootEnd(): void;
nodeBegin({ path }: JSONFormatterContext, key: string, leftKey: string | number): void;
nodeEnd({ path }: JSONFormatterContext): void;
format_unchanged(): void;
format_movedestination(): void;
format_node(context: JSONFormatterContext, delta: ObjectDelta | ArrayDelta, left: unknown): void;
format_added(context: JSONFormatterContext, delta: AddedDelta): void;
format_modified(context: JSONFormatterContext, delta: ModifiedDelta): void;
format_deleted(context: JSONFormatterContext): void;
format_moved(context: JSONFormatterContext, delta: MovedDelta): void;
format_textdiff(): void;
format(delta: Delta, left?: unknown): Op[];
}
export default JSONFormatter;
export declare const partitionOps: (arr: Op[], fns: ((op: Op) => boolean)[]) => Op[][];
export declare const format: (delta: Delta, left?: unknown) => Op[];
export declare const log: (delta: Delta, left?: unknown) => void;

152
node_modules/jsondiffpatch/lib/formatters/jsonpatch.js generated vendored Normal file
View File

@@ -0,0 +1,152 @@
import BaseFormatter from './base.js';
const OPERATIONS = {
add: 'add',
remove: 'remove',
replace: 'replace',
move: 'move',
};
class JSONFormatter extends BaseFormatter {
constructor() {
super();
this.includeMoveDestinations = true;
}
prepareContext(context) {
super.prepareContext(context);
context.result = [];
context.path = [];
context.pushCurrentOp = function (obj) {
if (obj.op === 'add' || obj.op === 'replace') {
this.result.push({
op: obj.op,
path: this.currentPath(),
value: obj.value,
});
}
else if (obj.op === 'remove') {
this.result.push({ op: obj.op, path: this.currentPath() });
}
else {
obj;
}
};
context.pushMoveOp = function (to) {
const from = this.currentPath();
this.result.push({
op: OPERATIONS.move,
from,
path: this.toPath(to),
});
};
context.currentPath = function () {
return `/${this.path.join('/')}`;
};
context.toPath = function (toPath) {
const to = this.path.slice();
to[to.length - 1] = toPath;
return `/${to.join('/')}`;
};
}
typeFormattterErrorFormatter(context, err) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
context.out(`[ERROR] ${err}`);
}
rootBegin() { }
rootEnd() { }
nodeBegin({ path }, key, leftKey) {
path.push(leftKey);
}
nodeEnd({ path }) {
path.pop();
}
format_unchanged() { }
format_movedestination() { }
format_node(context, delta, left) {
this.formatDeltaChildren(context, delta, left);
}
format_added(context, delta) {
context.pushCurrentOp({ op: OPERATIONS.add, value: delta[0] });
}
format_modified(context, delta) {
context.pushCurrentOp({ op: OPERATIONS.replace, value: delta[1] });
}
format_deleted(context) {
context.pushCurrentOp({ op: OPERATIONS.remove });
}
format_moved(context, delta) {
const to = delta[1];
context.pushMoveOp(to);
}
format_textdiff() {
throw new Error('Not implemented');
}
format(delta, left) {
const context = {};
this.prepareContext(context);
const preparedContext = context;
this.recurse(preparedContext, delta, left);
return preparedContext.result;
}
}
export default JSONFormatter;
const last = (arr) => arr[arr.length - 1];
const sortBy = (arr, pred) => {
arr.sort(pred);
return arr;
};
const compareByIndexDesc = (indexA, indexB) => {
const lastA = parseInt(indexA, 10);
const lastB = parseInt(indexB, 10);
if (!(isNaN(lastA) || isNaN(lastB))) {
return lastB - lastA;
}
else {
return 0;
}
};
const opsByDescendingOrder = (removeOps) => sortBy(removeOps, (a, b) => {
const splitA = a.path.split('/');
const splitB = b.path.split('/');
if (splitA.length !== splitB.length) {
return splitA.length - splitB.length;
}
else {
return compareByIndexDesc(last(splitA), last(splitB));
}
});
export const partitionOps = (arr, fns) => {
const initArr = Array(fns.length + 1)
.fill(undefined)
.map(() => []);
return arr
.map((item) => {
let position = fns.map((fn) => fn(item)).indexOf(true);
if (position < 0) {
position = fns.length;
}
return { item, position };
})
.reduce((acc, item) => {
acc[item.position].push(item.item);
return acc;
}, initArr);
};
const isMoveOp = ({ op }) => op === 'move';
const isRemoveOp = ({ op }) => op === 'remove';
const reorderOps = (diff) => {
const [moveOps, removedOps, restOps] = partitionOps(diff, [
isMoveOp,
isRemoveOp,
]);
const removeOpsReverse = opsByDescendingOrder(removedOps);
return [...removeOpsReverse, ...moveOps, ...restOps];
};
let defaultInstance;
export const format = (delta, left) => {
if (!defaultInstance) {
defaultInstance = new JSONFormatter();
}
return reorderOps(defaultInstance.format(delta, left));
};
export const log = (delta, left) => {
console.log(format(delta, left));
};

View File

@@ -0,0 +1,48 @@
.jsondiffpatch-annotated-delta {
font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier,
monospace;
font-size: 12px;
margin: 0;
padding: 0 0 0 12px;
display: inline-block;
}
.jsondiffpatch-annotated-delta pre {
font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier,
monospace;
font-size: 12px;
margin: 0;
padding: 0;
display: inline-block;
}
.jsondiffpatch-annotated-delta td {
margin: 0;
padding: 0;
}
.jsondiffpatch-annotated-delta td pre:hover {
font-weight: bold;
}
td.jsondiffpatch-delta-note {
font-style: italic;
padding-left: 10px;
}
.jsondiffpatch-delta-note > div {
margin: 0;
padding: 0;
}
.jsondiffpatch-delta-note pre {
font-style: normal;
}
.jsondiffpatch-annotated-delta .jsondiffpatch-delta-note {
color: #777;
}
.jsondiffpatch-annotated-delta tr:hover {
background: #ffc;
}
.jsondiffpatch-annotated-delta tr:hover > td.jsondiffpatch-delta-note {
color: black;
}
.jsondiffpatch-error {
background: red;
color: white;
font-weight: bold;
}

View File

@@ -0,0 +1,163 @@
.jsondiffpatch-delta {
font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier,
monospace;
font-size: 12px;
margin: 0;
padding: 0 0 0 12px;
display: inline-block;
}
.jsondiffpatch-delta pre {
font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier,
monospace;
font-size: 12px;
margin: 0;
padding: 0;
display: inline-block;
}
ul.jsondiffpatch-delta {
list-style-type: none;
padding: 0 0 0 20px;
margin: 0;
}
.jsondiffpatch-delta ul {
list-style-type: none;
padding: 0 0 0 20px;
margin: 0;
}
.jsondiffpatch-added .jsondiffpatch-property-name,
.jsondiffpatch-added .jsondiffpatch-value pre,
.jsondiffpatch-modified .jsondiffpatch-right-value pre,
.jsondiffpatch-textdiff-added {
background: #bbffbb;
}
.jsondiffpatch-deleted .jsondiffpatch-property-name,
.jsondiffpatch-deleted pre,
.jsondiffpatch-modified .jsondiffpatch-left-value pre,
.jsondiffpatch-textdiff-deleted {
background: #ffbbbb;
text-decoration: line-through;
}
.jsondiffpatch-unchanged,
.jsondiffpatch-movedestination {
color: gray;
}
.jsondiffpatch-unchanged,
.jsondiffpatch-movedestination > .jsondiffpatch-value {
transition: all 0.5s;
-webkit-transition: all 0.5s;
overflow-y: hidden;
}
.jsondiffpatch-unchanged-showing .jsondiffpatch-unchanged,
.jsondiffpatch-unchanged-showing
.jsondiffpatch-movedestination
> .jsondiffpatch-value {
max-height: 100px;
}
.jsondiffpatch-unchanged-hidden .jsondiffpatch-unchanged,
.jsondiffpatch-unchanged-hidden
.jsondiffpatch-movedestination
> .jsondiffpatch-value {
max-height: 0;
}
.jsondiffpatch-unchanged-hiding
.jsondiffpatch-movedestination
> .jsondiffpatch-value,
.jsondiffpatch-unchanged-hidden
.jsondiffpatch-movedestination
> .jsondiffpatch-value {
display: block;
}
.jsondiffpatch-unchanged-visible .jsondiffpatch-unchanged,
.jsondiffpatch-unchanged-visible
.jsondiffpatch-movedestination
> .jsondiffpatch-value {
max-height: 100px;
}
.jsondiffpatch-unchanged-hiding .jsondiffpatch-unchanged,
.jsondiffpatch-unchanged-hiding
.jsondiffpatch-movedestination
> .jsondiffpatch-value {
max-height: 0;
}
.jsondiffpatch-unchanged-showing .jsondiffpatch-arrow,
.jsondiffpatch-unchanged-hiding .jsondiffpatch-arrow {
display: none;
}
.jsondiffpatch-value {
display: inline-block;
}
.jsondiffpatch-property-name {
display: inline-block;
padding-right: 5px;
vertical-align: top;
}
.jsondiffpatch-property-name:after {
content: ': ';
}
.jsondiffpatch-child-node-type-array > .jsondiffpatch-property-name:after {
content: ': [';
}
.jsondiffpatch-child-node-type-array:after {
content: '],';
}
div.jsondiffpatch-child-node-type-array:before {
content: '[';
}
div.jsondiffpatch-child-node-type-array:after {
content: ']';
}
.jsondiffpatch-child-node-type-object > .jsondiffpatch-property-name:after {
content: ': {';
}
.jsondiffpatch-child-node-type-object:after {
content: '},';
}
div.jsondiffpatch-child-node-type-object:before {
content: '{';
}
div.jsondiffpatch-child-node-type-object:after {
content: '}';
}
.jsondiffpatch-value pre:after {
content: ',';
}
li:last-child > .jsondiffpatch-value pre:after,
.jsondiffpatch-modified > .jsondiffpatch-left-value pre:after {
content: '';
}
.jsondiffpatch-modified .jsondiffpatch-value {
display: inline-block;
}
.jsondiffpatch-modified .jsondiffpatch-right-value {
margin-left: 5px;
}
.jsondiffpatch-moved .jsondiffpatch-value {
display: none;
}
.jsondiffpatch-moved .jsondiffpatch-moved-destination {
display: inline-block;
background: #ffffbb;
color: #888;
}
.jsondiffpatch-moved .jsondiffpatch-moved-destination:before {
content: ' => ';
}
ul.jsondiffpatch-textdiff {
padding: 0;
}
.jsondiffpatch-textdiff-location {
color: #bbb;
display: inline-block;
min-width: 60px;
}
.jsondiffpatch-textdiff-line {
display: inline-block;
}
.jsondiffpatch-textdiff-line-number:after {
content: ',';
}
.jsondiffpatch-error {
background: red;
color: white;
font-weight: bold;
}

16
node_modules/jsondiffpatch/lib/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
import DiffPatcher from './diffpatcher.js';
import dateReviver from './date-reviver.js';
import type { Delta, Options } from './types.js';
import type Context from './contexts/context.js';
import type DiffContext from './contexts/diff.js';
import type PatchContext from './contexts/patch.js';
import type ReverseContext from './contexts/reverse.js';
export { DiffPatcher, dateReviver };
export type * from './types.js';
export type { Context, DiffContext, PatchContext, ReverseContext };
export declare function create(options?: Options): DiffPatcher;
export declare function diff(left: unknown, right: unknown): Delta;
export declare function patch(left: unknown, delta: Delta): unknown;
export declare function unpatch(right: unknown, delta: Delta): unknown;
export declare function reverse(delta: Delta): Delta;
export declare function clone(value: unknown): unknown;

37
node_modules/jsondiffpatch/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,37 @@
import DiffPatcher from './diffpatcher.js';
import dateReviver from './date-reviver.js';
export { DiffPatcher, dateReviver };
export function create(options) {
return new DiffPatcher(options);
}
let defaultInstance;
export function diff(left, right) {
if (!defaultInstance) {
defaultInstance = new DiffPatcher();
}
return defaultInstance.diff(left, right);
}
export function patch(left, delta) {
if (!defaultInstance) {
defaultInstance = new DiffPatcher();
}
return defaultInstance.patch(left, delta);
}
export function unpatch(right, delta) {
if (!defaultInstance) {
defaultInstance = new DiffPatcher();
}
return defaultInstance.unpatch(right, delta);
}
export function reverse(delta) {
if (!defaultInstance) {
defaultInstance = new DiffPatcher();
}
return defaultInstance.reverse(delta);
}
export function clone(value) {
if (!defaultInstance) {
defaultInstance = new DiffPatcher();
}
return defaultInstance.clone(value);
}

24
node_modules/jsondiffpatch/lib/pipe.d.ts generated vendored Normal file
View File

@@ -0,0 +1,24 @@
import type Context from './contexts/context.js';
import type Processor from './processor.js';
import type { Filter } from './types.js';
declare class Pipe<TContext extends Context<any>> {
name: string;
filters: Filter<TContext>[];
processor?: Processor;
debug?: boolean;
resultCheck?: ((context: TContext) => void) | null;
constructor(name: string);
process(input: TContext): void;
log(msg: string): void;
append(...args: Filter<TContext>[]): this;
prepend(...args: Filter<TContext>[]): this;
indexOf(filterName: string): number;
list(): string[];
after(filterName: string, ...params: Filter<TContext>[]): this;
before(filterName: string, ...params: Filter<TContext>[]): this;
replace(filterName: string, ...params: Filter<TContext>[]): this;
remove(filterName: string): this;
clear(): this;
shouldHaveResult(should?: boolean): this | undefined;
}
export default Pipe;

98
node_modules/jsondiffpatch/lib/pipe.js generated vendored Normal file
View File

@@ -0,0 +1,98 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
class Pipe {
constructor(name) {
this.name = name;
this.filters = [];
}
process(input) {
if (!this.processor) {
throw new Error('add this pipe to a processor before using it');
}
const debug = this.debug;
const length = this.filters.length;
const context = input;
for (let index = 0; index < length; index++) {
const filter = this.filters[index];
if (debug) {
this.log(`filter: ${filter.filterName}`);
}
filter(context);
if (typeof context === 'object' && context.exiting) {
context.exiting = false;
break;
}
}
if (!context.next && this.resultCheck) {
this.resultCheck(context);
}
}
log(msg) {
console.log(`[jsondiffpatch] ${this.name} pipe, ${msg}`);
}
append(...args) {
this.filters.push(...args);
return this;
}
prepend(...args) {
this.filters.unshift(...args);
return this;
}
indexOf(filterName) {
if (!filterName) {
throw new Error('a filter name is required');
}
for (let index = 0; index < this.filters.length; index++) {
const filter = this.filters[index];
if (filter.filterName === filterName) {
return index;
}
}
throw new Error(`filter not found: ${filterName}`);
}
list() {
return this.filters.map((f) => f.filterName);
}
after(filterName, ...params) {
const index = this.indexOf(filterName);
this.filters.splice(index + 1, 0, ...params);
return this;
}
before(filterName, ...params) {
const index = this.indexOf(filterName);
this.filters.splice(index, 0, ...params);
return this;
}
replace(filterName, ...params) {
const index = this.indexOf(filterName);
this.filters.splice(index, 1, ...params);
return this;
}
remove(filterName) {
const index = this.indexOf(filterName);
this.filters.splice(index, 1);
return this;
}
clear() {
this.filters.length = 0;
return this;
}
shouldHaveResult(should) {
if (should === false) {
this.resultCheck = null;
return;
}
if (this.resultCheck) {
return;
}
this.resultCheck = (context) => {
if (!context.hasResult) {
console.log(context);
const error = new Error(`${this.name} failed`);
error.noResult = true;
throw error;
}
};
return this;
}
}
export default Pipe;

19
node_modules/jsondiffpatch/lib/processor.d.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import type Context from './contexts/context.js';
import type Pipe from './pipe.js';
import type { Options } from './types.js';
import type DiffContext from './contexts/diff.js';
import type PatchContext from './contexts/patch.js';
import type ReverseContext from './contexts/reverse.js';
declare class Processor {
selfOptions: Options;
pipes: {
diff: Pipe<DiffContext>;
patch: Pipe<PatchContext>;
reverse: Pipe<ReverseContext>;
};
constructor(options?: Options);
options(options?: Options): Options;
pipe<TContext extends Context<any>>(name: string | Pipe<TContext>, pipeArg?: Pipe<TContext>): Pipe<DiffContext> | Pipe<PatchContext> | Pipe<ReverseContext> | Pipe<TContext>;
process<TContext extends Context<any>>(input: TContext, pipe?: Pipe<TContext>): TContext['result'] | undefined;
}
export default Processor;

63
node_modules/jsondiffpatch/lib/processor.js generated vendored Normal file
View File

@@ -0,0 +1,63 @@
class Processor {
constructor(options) {
this.selfOptions = options || {};
this.pipes = {};
}
options(options) {
if (options) {
this.selfOptions = options;
}
return this.selfOptions;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
pipe(name, pipeArg) {
let pipe = pipeArg;
if (typeof name === 'string') {
if (typeof pipe === 'undefined') {
return this.pipes[name];
}
else {
this.pipes[name] = pipe;
}
}
if (name && name.name) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
pipe = name;
if (pipe.processor === this) {
return pipe;
}
this.pipes[pipe.name] = pipe;
}
pipe.processor = this;
return pipe;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
process(input, pipe) {
let context = input;
context.options = this.options();
let nextPipe = pipe || input.pipe || 'default';
let lastPipe;
while (nextPipe) {
if (typeof context.nextAfterChildren !== 'undefined') {
// children processed and coming back to parent
context.next = context.nextAfterChildren;
context.nextAfterChildren = null;
}
if (typeof nextPipe === 'string') {
nextPipe = this.pipe(nextPipe);
}
nextPipe.process(context);
lastPipe = nextPipe;
nextPipe = null;
if (context) {
if (context.next) {
context = context.next;
nextPipe = context.pipe || lastPipe;
}
}
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return context.hasResult ? context.result : undefined;
}
}
export default Processor;

35
node_modules/jsondiffpatch/lib/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,35 @@
import type dmp from 'diff-match-patch';
import type Context from './contexts/context.js';
import type DiffContext from './contexts/diff.js';
export interface Options {
objectHash?: (item: object, index?: number) => string | undefined;
matchByPosition?: boolean;
arrays?: {
detectMove?: boolean;
includeValueOnMove?: boolean;
};
textDiff?: {
diffMatchPatch: typeof dmp;
minLength?: number;
};
propertyFilter?: (name: string, context: DiffContext) => boolean;
cloneDiffValues?: boolean | ((value: unknown) => unknown);
}
export type AddedDelta = [unknown];
export type ModifiedDelta = [unknown, unknown];
export type DeletedDelta = [unknown, 0, 0];
export interface ObjectDelta {
[property: string]: Delta;
}
export interface ArrayDelta {
_t: 'a';
[index: number | `${number}`]: Delta;
[index: `_${number}`]: DeletedDelta | MovedDelta;
}
export type MovedDelta = [unknown, number, 3];
export type TextDiffDelta = [string, 0, 2];
export type Delta = AddedDelta | ModifiedDelta | DeletedDelta | ObjectDelta | ArrayDelta | MovedDelta | TextDiffDelta | undefined;
export interface Filter<TContext extends Context<any>> {
(context: TContext): void;
filterName: string;
}

1
node_modules/jsondiffpatch/lib/types.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export {};

18
node_modules/jsondiffpatch/lib/with-text-diffs.d.ts generated vendored Normal file
View File

@@ -0,0 +1,18 @@
import DiffPatcher from './diffpatcher.js';
import dateReviver from './date-reviver.js';
import type { Delta, Options } from './types.js';
import type Context from './contexts/context.js';
import type DiffContext from './contexts/diff.js';
import type PatchContext from './contexts/patch.js';
import type ReverseContext from './contexts/reverse.js';
export { DiffPatcher, dateReviver };
export type * from './types.js';
export type { Context, DiffContext, PatchContext, ReverseContext };
export declare function create(options?: Omit<Options, 'textDiff'> & {
textDiff?: Omit<Options['textDiff'], 'diffMatchPatch'>;
}): DiffPatcher;
export declare function diff(left: unknown, right: unknown): Delta;
export declare function patch(left: unknown, delta: Delta): unknown;
export declare function unpatch(right: unknown, delta: Delta): unknown;
export declare function reverse(delta: Delta): Delta;
export declare function clone(value: unknown): unknown;

48
node_modules/jsondiffpatch/lib/with-text-diffs.js generated vendored Normal file
View File

@@ -0,0 +1,48 @@
import DiffMatchPatch from 'diff-match-patch';
import DiffPatcher from './diffpatcher.js';
import dateReviver from './date-reviver.js';
export { DiffPatcher, dateReviver };
export function create(options) {
return new DiffPatcher(Object.assign(Object.assign({}, options), { textDiff: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.textDiff), { diffMatchPatch: DiffMatchPatch }) }));
}
let defaultInstance;
export function diff(left, right) {
if (!defaultInstance) {
defaultInstance = new DiffPatcher({
textDiff: { diffMatchPatch: DiffMatchPatch },
});
}
return defaultInstance.diff(left, right);
}
export function patch(left, delta) {
if (!defaultInstance) {
defaultInstance = new DiffPatcher({
textDiff: { diffMatchPatch: DiffMatchPatch },
});
}
return defaultInstance.patch(left, delta);
}
export function unpatch(right, delta) {
if (!defaultInstance) {
defaultInstance = new DiffPatcher({
textDiff: { diffMatchPatch: DiffMatchPatch },
});
}
return defaultInstance.unpatch(right, delta);
}
export function reverse(delta) {
if (!defaultInstance) {
defaultInstance = new DiffPatcher({
textDiff: { diffMatchPatch: DiffMatchPatch },
});
}
return defaultInstance.reverse(delta);
}
export function clone(value) {
if (!defaultInstance) {
defaultInstance = new DiffPatcher({
textDiff: { diffMatchPatch: DiffMatchPatch },
});
}
return defaultInstance.clone(value);
}

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,83 @@
{
"name": "chalk",
"version": "5.6.2",
"description": "Terminal string styling done right",
"license": "MIT",
"repository": "chalk/chalk",
"funding": "https://github.com/chalk/chalk?sponsor=1",
"type": "module",
"main": "./source/index.js",
"exports": "./source/index.js",
"imports": {
"#ansi-styles": "./source/vendor/ansi-styles/index.js",
"#supports-color": {
"node": "./source/vendor/supports-color/index.js",
"default": "./source/vendor/supports-color/browser.js"
}
},
"types": "./source/index.d.ts",
"sideEffects": false,
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
},
"scripts": {
"test": "xo && c8 ava && tsd",
"bench": "matcha benchmark.js"
},
"files": [
"source",
"!source/index.test-d.ts"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"ansi",
"style",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"devDependencies": {
"@types/node": "^16.11.10",
"ava": "^3.15.0",
"c8": "^7.10.0",
"color-convert": "^2.0.1",
"execa": "^6.0.0",
"log-update": "^5.0.0",
"matcha": "^0.7.0",
"tsd": "^0.19.0",
"xo": "^0.57.0",
"yoctodelay": "^2.0.0"
},
"xo": {
"rules": {
"unicorn/prefer-string-slice": "off",
"@typescript-eslint/consistent-type-imports": "off",
"@typescript-eslint/consistent-type-exports": "off",
"@typescript-eslint/consistent-type-definitions": "off",
"unicorn/expiring-todo-comments": "off"
}
},
"c8": {
"reporter": [
"text",
"lcov"
],
"exclude": [
"source/vendor"
]
}
}

297
node_modules/jsondiffpatch/node_modules/chalk/readme.md generated vendored Normal file
View File

@@ -0,0 +1,297 @@
<h1 align="center">
<br>
<br>
<img width="320" src="media/logo.svg" alt="Chalk">
<br>
<br>
<br>
</h1>
> Terminal string styling done right
[![Coverage Status](https://codecov.io/gh/chalk/chalk/branch/main/graph/badge.svg)](https://codecov.io/gh/chalk/chalk)
[![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents)
[![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk)
![](media/screenshot.png)
## Info
- [Why not switch to a smaller coloring package?](https://github.com/chalk/chalk?tab=readme-ov-file#why-not-switch-to-a-smaller-coloring-package)
- See [yoctocolors](https://github.com/sindresorhus/yoctocolors) for a smaller alternative
## Highlights
- Expressive API
- Highly performant
- No dependencies
- Ability to nest styles
- [256/Truecolor color support](#256-and-truecolor-color-support)
- Auto-detects color support
- Doesn't extend `String.prototype`
- Clean and focused
- Actively maintained
- [Used by ~115,000 packages](https://www.npmjs.com/browse/depended/chalk) as of July 4, 2024
## Install
```sh
npm install chalk
```
**IMPORTANT:** Chalk 5 is ESM. If you want to use Chalk with TypeScript or a build tool, you will probably want to use Chalk 4 for now. [Read more.](https://github.com/chalk/chalk/releases/tag/v5.0.0)
## Usage
```js
import chalk from 'chalk';
console.log(chalk.blue('Hello world!'));
```
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
```js
import chalk from 'chalk';
const log = console.log;
// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
// Nest styles of the same type even (color, underline, background)
log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
));
// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
// Use RGB colors in terminal emulators that support it.
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
```
Easily define your own themes:
```js
import chalk from 'chalk';
const error = chalk.bold.red;
const warning = chalk.hex('#FFA500'); // Orange color
console.log(error('Error!'));
console.log(warning('Warning!'));
```
Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
```js
import chalk from 'chalk';
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
Multiple arguments will be separated by space.
### chalk.level
Specifies the level of color support.
Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
If you need to change this in a reusable module, create a new instance:
```js
import {Chalk} from 'chalk';
const customChalk = new Chalk({level: 0});
```
| Level | Description |
| :---: | :--- |
| `0` | All colors disabled |
| `1` | Basic color support (16 colors) |
| `2` | 256 color support |
| `3` | Truecolor support (16 million colors) |
### supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
### chalkStderr and supportsColorStderr
`chalkStderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `supportsColor` apply to this too. `supportsColorStderr` is exposed for convenience.
### modifierNames, foregroundColorNames, backgroundColorNames, and colorNames
All supported style strings are exposed as an array of strings for convenience. `colorNames` is the combination of `foregroundColorNames` and `backgroundColorNames`.
This can be useful if you wrap Chalk and need to validate input:
```js
import {modifierNames, foregroundColorNames} from 'chalk';
console.log(modifierNames.includes('bold'));
//=> true
console.log(foregroundColorNames.includes('pink'));
//=> false
```
## Styles
### Modifiers
- `reset` - Reset the current style.
- `bold` - Make the text bold.
- `dim` - Make the text have lower opacity.
- `italic` - Make the text italic. *(Not widely supported)*
- `underline` - Put a horizontal line below the text. *(Not widely supported)*
- `overline` - Put a horizontal line above the text. *(Not widely supported)*
- `inverse`- Invert background and foreground colors.
- `hidden` - Print the text but make it invisible.
- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
- `visible`- Print the text only when Chalk has a color level above zero. Can be useful for things that are purely cosmetic.
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`
## 256 and Truecolor color support
Chalk supports 256 colors and [Truecolor](https://github.com/termstandard/colors) (16 million colors) on supported terminal apps.
Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
Examples:
- `chalk.hex('#DEADED').underline('Hello, world!')`
- `chalk.rgb(15, 100, 204).inverse('Hello!')`
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `hex` for foreground colors and `bgHex` for background colors).
- `chalk.bgHex('#DEADED').underline('Hello, world!')`
- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
The following color models can be used:
- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
## Browser support
Since Chrome 69, ANSI escape codes are natively supported in the developer console.
## Windows
If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
## FAQ
### Why not switch to a smaller coloring package?
Chalk may be larger, but there is a reason for that. It offers a more user-friendly API, well-documented types, supports millions of colors, and covers edge cases that smaller alternatives miss. Chalk is mature, reliable, and built to last.
But beyond the technical aspects, there's something more critical: trust and long-term maintenance. I have been active in open source for over a decade, and I'm committed to keeping Chalk maintained. Smaller packages might seem appealing now, but there's no guarantee they will be around for the long term, or that they won't become malicious over time.
Chalk is also likely already in your dependency tree (since 100K+ packages depend on it), so switching wont save space—in fact, it might increase it. npm deduplicates dependencies, so multiple Chalk instances turn into one, but adding another package alongside it will increase your overall size.
If the goal is to clean up the ecosystem, switching away from Chalk wont even make a dent. The real problem lies with packages that have very deep dependency trees (for example, those including a lot of polyfills). Chalk has no dependencies. It's better to focus on impactful changes rather than minor optimizations.
If absolute package size is important to you, I also maintain [yoctocolors](https://github.com/sindresorhus/yoctocolors), one of the smallest color packages out there.
*\- [Sindre](https://github.com/sindresorhus)*
### But the smaller coloring package has benchmarks showing it is faster
[Micro-benchmarks are flawed](https://sindresorhus.com/blog/micro-benchmark-fallacy) because they measure performance in unrealistic, isolated scenarios, often giving a distorted view of real-world performance. Don't believe marketing fluff. All the coloring packages are more than fast enough.
## Related
- [chalk-template](https://github.com/chalk/chalk-template) - [Tagged template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) support for this module
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
*(Not accepting additional entries)*
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)

View File

@@ -0,0 +1,325 @@
// TODO: Make it this when TS suports that.
// import {ModifierName, ForegroundColor, BackgroundColor, ColorName} from '#ansi-styles';
// import {ColorInfo, ColorSupportLevel} from '#supports-color';
import {
ModifierName,
ForegroundColorName,
BackgroundColorName,
ColorName,
} from './vendor/ansi-styles/index.js';
import {ColorInfo, ColorSupportLevel} from './vendor/supports-color/index.js';
export interface Options {
/**
Specify the color support for Chalk.
By default, color support is automatically detected based on the environment.
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
readonly level?: ColorSupportLevel;
}
/**
Return a new Chalk instance.
*/
export const Chalk: new (options?: Options) => ChalkInstance; // eslint-disable-line @typescript-eslint/naming-convention
export interface ChalkInstance {
(...text: unknown[]): string;
/**
The color support for Chalk.
By default, color support is automatically detected based on the environment.
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
level: ColorSupportLevel;
/**
Use RGB values to set text color.
@example
```
import chalk from 'chalk';
chalk.rgb(222, 173, 237);
```
*/
rgb: (red: number, green: number, blue: number) => this;
/**
Use HEX value to set text color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk from 'chalk';
chalk.hex('#DEADED');
```
*/
hex: (color: string) => this;
/**
Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
@example
```
import chalk from 'chalk';
chalk.ansi256(201);
```
*/
ansi256: (index: number) => this;
/**
Use RGB values to set background color.
@example
```
import chalk from 'chalk';
chalk.bgRgb(222, 173, 237);
```
*/
bgRgb: (red: number, green: number, blue: number) => this;
/**
Use HEX value to set background color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk from 'chalk';
chalk.bgHex('#DEADED');
```
*/
bgHex: (color: string) => this;
/**
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
@example
```
import chalk from 'chalk';
chalk.bgAnsi256(201);
```
*/
bgAnsi256: (index: number) => this;
/**
Modifier: Reset the current style.
*/
readonly reset: this;
/**
Modifier: Make the text bold.
*/
readonly bold: this;
/**
Modifier: Make the text have lower opacity.
*/
readonly dim: this;
/**
Modifier: Make the text italic. *(Not widely supported)*
*/
readonly italic: this;
/**
Modifier: Put a horizontal line below the text. *(Not widely supported)*
*/
readonly underline: this;
/**
Modifier: Put a horizontal line above the text. *(Not widely supported)*
*/
readonly overline: this;
/**
Modifier: Invert background and foreground colors.
*/
readonly inverse: this;
/**
Modifier: Print the text but make it invisible.
*/
readonly hidden: this;
/**
Modifier: Puts a horizontal line through the center of the text. *(Not widely supported)*
*/
readonly strikethrough: this;
/**
Modifier: Print the text only when Chalk has a color level above zero.
Can be useful for things that are purely cosmetic.
*/
readonly visible: this;
readonly black: this;
readonly red: this;
readonly green: this;
readonly yellow: this;
readonly blue: this;
readonly magenta: this;
readonly cyan: this;
readonly white: this;
/*
Alias for `blackBright`.
*/
readonly gray: this;
/*
Alias for `blackBright`.
*/
readonly grey: this;
readonly blackBright: this;
readonly redBright: this;
readonly greenBright: this;
readonly yellowBright: this;
readonly blueBright: this;
readonly magentaBright: this;
readonly cyanBright: this;
readonly whiteBright: this;
readonly bgBlack: this;
readonly bgRed: this;
readonly bgGreen: this;
readonly bgYellow: this;
readonly bgBlue: this;
readonly bgMagenta: this;
readonly bgCyan: this;
readonly bgWhite: this;
/*
Alias for `bgBlackBright`.
*/
readonly bgGray: this;
/*
Alias for `bgBlackBright`.
*/
readonly bgGrey: this;
readonly bgBlackBright: this;
readonly bgRedBright: this;
readonly bgGreenBright: this;
readonly bgYellowBright: this;
readonly bgBlueBright: this;
readonly bgMagentaBright: this;
readonly bgCyanBright: this;
readonly bgWhiteBright: this;
}
/**
Main Chalk object that allows to chain styles together.
Call the last one as a method with a string argument.
Order doesn't matter, and later styles take precedent in case of a conflict.
This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
*/
declare const chalk: ChalkInstance;
export const supportsColor: ColorInfo;
export const chalkStderr: typeof chalk;
export const supportsColorStderr: typeof supportsColor;
export {
ModifierName, ForegroundColorName, BackgroundColorName, ColorName,
modifierNames, foregroundColorNames, backgroundColorNames, colorNames,
// } from '#ansi-styles';
} from './vendor/ansi-styles/index.js';
export {
ColorInfo,
ColorSupport,
ColorSupportLevel,
// } from '#supports-color';
} from './vendor/supports-color/index.js';
// TODO: Remove these aliases in the next major version
/**
@deprecated Use `ModifierName` instead.
Basic modifier names.
*/
export type Modifiers = ModifierName;
/**
@deprecated Use `ForegroundColorName` instead.
Basic foreground color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type ForegroundColor = ForegroundColorName;
/**
@deprecated Use `BackgroundColorName` instead.
Basic background color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type BackgroundColor = BackgroundColorName;
/**
@deprecated Use `ColorName` instead.
Basic color names. The combination of foreground and background color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type Color = ColorName;
/**
@deprecated Use `modifierNames` instead.
Basic modifier names.
*/
export const modifiers: readonly Modifiers[];
/**
@deprecated Use `foregroundColorNames` instead.
Basic foreground color names.
*/
export const foregroundColors: readonly ForegroundColor[];
/**
@deprecated Use `backgroundColorNames` instead.
Basic background color names.
*/
export const backgroundColors: readonly BackgroundColor[];
/**
@deprecated Use `colorNames` instead.
Basic color names. The combination of foreground and background color names.
*/
export const colors: readonly Color[];
export default chalk;

View File

@@ -0,0 +1,225 @@
import ansiStyles from '#ansi-styles';
import supportsColor from '#supports-color';
import { // eslint-disable-line import/order
stringReplaceAll,
stringEncaseCRLFWithFirstIndex,
} from './utilities.js';
const {stdout: stdoutColor, stderr: stderrColor} = supportsColor;
const GENERATOR = Symbol('GENERATOR');
const STYLER = Symbol('STYLER');
const IS_EMPTY = Symbol('IS_EMPTY');
// `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = [
'ansi',
'ansi',
'ansi256',
'ansi16m',
];
const styles = Object.create(null);
const applyOptions = (object, options = {}) => {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error('The `level` option should be an integer from 0 to 3');
}
// Detect level if not set manually
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === undefined ? colorLevel : options.level;
};
export class Chalk {
constructor(options) {
// eslint-disable-next-line no-constructor-return
return chalkFactory(options);
}
}
const chalkFactory = options => {
const chalk = (...strings) => strings.join(' ');
applyOptions(chalk, options);
Object.setPrototypeOf(chalk, createChalk.prototype);
return chalk;
};
function createChalk(options) {
return chalkFactory(options);
}
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
for (const [styleName, style] of Object.entries(ansiStyles)) {
styles[styleName] = {
get() {
const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
Object.defineProperty(this, styleName, {value: builder});
return builder;
},
};
}
styles.visible = {
get() {
const builder = createBuilder(this, this[STYLER], true);
Object.defineProperty(this, 'visible', {value: builder});
return builder;
},
};
const getModelAnsi = (model, level, type, ...arguments_) => {
if (model === 'rgb') {
if (level === 'ansi16m') {
return ansiStyles[type].ansi16m(...arguments_);
}
if (level === 'ansi256') {
return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
}
return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
}
if (model === 'hex') {
return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));
}
return ansiStyles[type][model](...arguments_);
};
const usedModels = ['rgb', 'hex', 'ansi256'];
for (const model of usedModels) {
styles[model] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
},
};
const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
},
};
}
const proto = Object.defineProperties(() => {}, {
...styles,
level: {
enumerable: true,
get() {
return this[GENERATOR].level;
},
set(level) {
this[GENERATOR].level = level;
},
},
});
const createStyler = (open, close, parent) => {
let openAll;
let closeAll;
if (parent === undefined) {
openAll = open;
closeAll = close;
} else {
openAll = parent.openAll + open;
closeAll = close + parent.closeAll;
}
return {
open,
close,
openAll,
closeAll,
parent,
};
};
const createBuilder = (self, _styler, _isEmpty) => {
// Single argument is hot path, implicit coercion is faster than anything
// eslint-disable-next-line no-implicit-coercion
const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
// We alter the prototype because we must return a function, but there is
// no way to create a function with a different prototype
Object.setPrototypeOf(builder, proto);
builder[GENERATOR] = self;
builder[STYLER] = _styler;
builder[IS_EMPTY] = _isEmpty;
return builder;
};
const applyStyle = (self, string) => {
if (self.level <= 0 || !string) {
return self[IS_EMPTY] ? '' : string;
}
let styler = self[STYLER];
if (styler === undefined) {
return string;
}
const {openAll, closeAll} = styler;
if (string.includes('\u001B')) {
while (styler !== undefined) {
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
string = stringReplaceAll(string, styler.close, styler.open);
styler = styler.parent;
}
}
// We can move both next actions out of loop, because remaining actions in loop won't have
// any/visible effect on parts we add here. Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
const lfIndex = string.indexOf('\n');
if (lfIndex !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;
};
Object.defineProperties(createChalk.prototype, styles);
const chalk = createChalk();
export const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});
export {
modifierNames,
foregroundColorNames,
backgroundColorNames,
colorNames,
// TODO: Remove these aliases in the next major version
modifierNames as modifiers,
foregroundColorNames as foregroundColors,
backgroundColorNames as backgroundColors,
colorNames as colors,
} from './vendor/ansi-styles/index.js';
export {
stdoutColor as supportsColor,
stderrColor as supportsColorStderr,
};
export default chalk;

View File

@@ -0,0 +1,33 @@
// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
export function stringReplaceAll(string, substring, replacer) {
let index = string.indexOf(substring);
if (index === -1) {
return string;
}
const substringLength = substring.length;
let endIndex = 0;
let returnValue = '';
do {
returnValue += string.slice(endIndex, index) + substring + replacer;
endIndex = index + substringLength;
index = string.indexOf(substring, endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}
export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
let endIndex = 0;
let returnValue = '';
do {
const gotCR = string[index - 1] === '\r';
returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
endIndex = index + 1;
index = string.indexOf('\n', endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}

View File

@@ -0,0 +1,236 @@
export interface CSPair { // eslint-disable-line @typescript-eslint/naming-convention
/**
The ANSI terminal control sequence for starting this style.
*/
readonly open: string;
/**
The ANSI terminal control sequence for ending this style.
*/
readonly close: string;
}
export interface ColorBase {
/**
The ANSI terminal control sequence for ending this color.
*/
readonly close: string;
ansi(code: number): string;
ansi256(code: number): string;
ansi16m(red: number, green: number, blue: number): string;
}
export interface Modifier {
/**
Resets the current color chain.
*/
readonly reset: CSPair;
/**
Make text bold.
*/
readonly bold: CSPair;
/**
Emitting only a small amount of light.
*/
readonly dim: CSPair;
/**
Make text italic. (Not widely supported)
*/
readonly italic: CSPair;
/**
Make text underline. (Not widely supported)
*/
readonly underline: CSPair;
/**
Make text overline.
Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash.
*/
readonly overline: CSPair;
/**
Inverse background and foreground colors.
*/
readonly inverse: CSPair;
/**
Prints the text, but makes it invisible.
*/
readonly hidden: CSPair;
/**
Puts a horizontal line through the center of the text. (Not widely supported)
*/
readonly strikethrough: CSPair;
}
export interface ForegroundColor {
readonly black: CSPair;
readonly red: CSPair;
readonly green: CSPair;
readonly yellow: CSPair;
readonly blue: CSPair;
readonly cyan: CSPair;
readonly magenta: CSPair;
readonly white: CSPair;
/**
Alias for `blackBright`.
*/
readonly gray: CSPair;
/**
Alias for `blackBright`.
*/
readonly grey: CSPair;
readonly blackBright: CSPair;
readonly redBright: CSPair;
readonly greenBright: CSPair;
readonly yellowBright: CSPair;
readonly blueBright: CSPair;
readonly cyanBright: CSPair;
readonly magentaBright: CSPair;
readonly whiteBright: CSPair;
}
export interface BackgroundColor {
readonly bgBlack: CSPair;
readonly bgRed: CSPair;
readonly bgGreen: CSPair;
readonly bgYellow: CSPair;
readonly bgBlue: CSPair;
readonly bgCyan: CSPair;
readonly bgMagenta: CSPair;
readonly bgWhite: CSPair;
/**
Alias for `bgBlackBright`.
*/
readonly bgGray: CSPair;
/**
Alias for `bgBlackBright`.
*/
readonly bgGrey: CSPair;
readonly bgBlackBright: CSPair;
readonly bgRedBright: CSPair;
readonly bgGreenBright: CSPair;
readonly bgYellowBright: CSPair;
readonly bgBlueBright: CSPair;
readonly bgCyanBright: CSPair;
readonly bgMagentaBright: CSPair;
readonly bgWhiteBright: CSPair;
}
export interface ConvertColor {
/**
Convert from the RGB color space to the ANSI 256 color space.
@param red - (`0...255`)
@param green - (`0...255`)
@param blue - (`0...255`)
*/
rgbToAnsi256(red: number, green: number, blue: number): number;
/**
Convert from the RGB HEX color space to the RGB color space.
@param hex - A hexadecimal string containing RGB data.
*/
hexToRgb(hex: string): [red: number, green: number, blue: number];
/**
Convert from the RGB HEX color space to the ANSI 256 color space.
@param hex - A hexadecimal string containing RGB data.
*/
hexToAnsi256(hex: string): number;
/**
Convert from the ANSI 256 color space to the ANSI 16 color space.
@param code - A number representing the ANSI 256 color.
*/
ansi256ToAnsi(code: number): number;
/**
Convert from the RGB color space to the ANSI 16 color space.
@param red - (`0...255`)
@param green - (`0...255`)
@param blue - (`0...255`)
*/
rgbToAnsi(red: number, green: number, blue: number): number;
/**
Convert from the RGB HEX color space to the ANSI 16 color space.
@param hex - A hexadecimal string containing RGB data.
*/
hexToAnsi(hex: string): number;
}
/**
Basic modifier names.
*/
export type ModifierName = keyof Modifier;
/**
Basic foreground color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type ForegroundColorName = keyof ForegroundColor;
/**
Basic background color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type BackgroundColorName = keyof BackgroundColor;
/**
Basic color names. The combination of foreground and background color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type ColorName = ForegroundColorName | BackgroundColorName;
/**
Basic modifier names.
*/
export const modifierNames: readonly ModifierName[];
/**
Basic foreground color names.
*/
export const foregroundColorNames: readonly ForegroundColorName[];
/**
Basic background color names.
*/
export const backgroundColorNames: readonly BackgroundColorName[];
/*
Basic color names. The combination of foreground and background color names.
*/
export const colorNames: readonly ColorName[];
declare const ansiStyles: {
readonly modifier: Modifier;
readonly color: ColorBase & ForegroundColor;
readonly bgColor: ColorBase & BackgroundColor;
readonly codes: ReadonlyMap<number, number>;
} & ForegroundColor & BackgroundColor & Modifier & ConvertColor;
export default ansiStyles;

View File

@@ -0,0 +1,223 @@
const ANSI_BACKGROUND_OFFSET = 10;
const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`;
const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`;
const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`;
const styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
overline: [53, 55],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
gray: [90, 39], // Alias of `blackBright`
grey: [90, 39], // Alias of `blackBright`
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39],
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgGray: [100, 49], // Alias of `bgBlackBright`
bgGrey: [100, 49], // Alias of `bgBlackBright`
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49],
},
};
export const modifierNames = Object.keys(styles.modifier);
export const foregroundColorNames = Object.keys(styles.color);
export const backgroundColorNames = Object.keys(styles.bgColor);
export const colorNames = [...foregroundColorNames, ...backgroundColorNames];
function assembleStyles() {
const codes = new Map();
for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) {
styles[styleName] = {
open: `\u001B[${style[0]}m`,
close: `\u001B[${style[1]}m`,
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false,
});
}
Object.defineProperty(styles, 'codes', {
value: codes,
enumerable: false,
});
styles.color.close = '\u001B[39m';
styles.bgColor.close = '\u001B[49m';
styles.color.ansi = wrapAnsi16();
styles.color.ansi256 = wrapAnsi256();
styles.color.ansi16m = wrapAnsi16m();
styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js
Object.defineProperties(styles, {
rgbToAnsi256: {
value(red, green, blue) {
// We use the extended greyscale palette here, with the exception of
// black and white. normal palette only has 4 greyscale shades.
if (red === green && green === blue) {
if (red < 8) {
return 16;
}
if (red > 248) {
return 231;
}
return Math.round(((red - 8) / 247) * 24) + 232;
}
return 16
+ (36 * Math.round(red / 255 * 5))
+ (6 * Math.round(green / 255 * 5))
+ Math.round(blue / 255 * 5);
},
enumerable: false,
},
hexToRgb: {
value(hex) {
const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
if (!matches) {
return [0, 0, 0];
}
let [colorString] = matches;
if (colorString.length === 3) {
colorString = [...colorString].map(character => character + character).join('');
}
const integer = Number.parseInt(colorString, 16);
return [
/* eslint-disable no-bitwise */
(integer >> 16) & 0xFF,
(integer >> 8) & 0xFF,
integer & 0xFF,
/* eslint-enable no-bitwise */
];
},
enumerable: false,
},
hexToAnsi256: {
value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
enumerable: false,
},
ansi256ToAnsi: {
value(code) {
if (code < 8) {
return 30 + code;
}
if (code < 16) {
return 90 + (code - 8);
}
let red;
let green;
let blue;
if (code >= 232) {
red = (((code - 232) * 10) + 8) / 255;
green = red;
blue = red;
} else {
code -= 16;
const remainder = code % 36;
red = Math.floor(code / 36) / 5;
green = Math.floor(remainder / 6) / 5;
blue = (remainder % 6) / 5;
}
const value = Math.max(red, green, blue) * 2;
if (value === 0) {
return 30;
}
// eslint-disable-next-line no-bitwise
let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));
if (value === 2) {
result += 60;
}
return result;
},
enumerable: false,
},
rgbToAnsi: {
value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
enumerable: false,
},
hexToAnsi: {
value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
enumerable: false,
},
});
return styles;
}
const ansiStyles = assembleStyles();
export default ansiStyles;

View File

@@ -0,0 +1 @@
export {default} from './index.js';

View File

@@ -0,0 +1,34 @@
/* eslint-env browser */
const level = (() => {
if (!('navigator' in globalThis)) {
return 0;
}
if (globalThis.navigator.userAgentData) {
const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium');
if (brand && brand.version > 93) {
return 3;
}
}
if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) {
return 1;
}
return 0;
})();
const colorSupport = level !== 0 && {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3,
};
const supportsColor = {
stdout: colorSupport,
stderr: colorSupport,
};
export default supportsColor;

View File

@@ -0,0 +1,55 @@
import type {WriteStream} from 'node:tty';
export type Options = {
/**
Whether `process.argv` should be sniffed for `--color` and `--no-color` flags.
@default true
*/
readonly sniffFlags?: boolean;
};
/**
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
export type ColorSupportLevel = 0 | 1 | 2 | 3;
/**
Detect whether the terminal supports color.
*/
export type ColorSupport = {
/**
The color level.
*/
level: ColorSupportLevel;
/**
Whether basic 16 colors are supported.
*/
hasBasic: boolean;
/**
Whether ANSI 256 colors are supported.
*/
has256: boolean;
/**
Whether Truecolor 16 million colors are supported.
*/
has16m: boolean;
};
export type ColorInfo = ColorSupport | false;
export function createSupportsColor(stream?: WriteStream, options?: Options): ColorInfo;
declare const supportsColor: {
stdout: ColorInfo;
stderr: ColorInfo;
};
export default supportsColor;

View File

@@ -0,0 +1,190 @@
import process from 'node:process';
import os from 'node:os';
import tty from 'node:tty';
// From: https://github.com/sindresorhus/has-flag/blob/main/index.js
/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {
const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf('--');
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
const {env} = process;
let flagForceColor;
if (
hasFlag('no-color')
|| hasFlag('no-colors')
|| hasFlag('color=false')
|| hasFlag('color=never')
) {
flagForceColor = 0;
} else if (
hasFlag('color')
|| hasFlag('colors')
|| hasFlag('color=true')
|| hasFlag('color=always')
) {
flagForceColor = 1;
}
function envForceColor() {
if ('FORCE_COLOR' in env) {
if (env.FORCE_COLOR === 'true') {
return 1;
}
if (env.FORCE_COLOR === 'false') {
return 0;
}
return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3,
};
}
function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {
const noFlagForceColor = envForceColor();
if (noFlagForceColor !== undefined) {
flagForceColor = noFlagForceColor;
}
const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
if (forceColor === 0) {
return 0;
}
if (sniffFlags) {
if (hasFlag('color=16m')
|| hasFlag('color=full')
|| hasFlag('color=truecolor')) {
return 3;
}
if (hasFlag('color=256')) {
return 2;
}
}
// Check for Azure DevOps pipelines.
// Has to be above the `!streamIsTTY` check.
if ('TF_BUILD' in env && 'AGENT_NAME' in env) {
return 1;
}
if (haveStream && !streamIsTTY && forceColor === undefined) {
return 0;
}
const min = forceColor || 0;
if (env.TERM === 'dumb') {
return min;
}
if (process.platform === 'win32') {
// Windows 10 build 10586 is the first Windows release that supports 256 colors.
// Windows 10 build 14931 is the first release that supports 16m/TrueColor.
const osRelease = os.release().split('.');
if (
Number(osRelease[0]) >= 10
&& Number(osRelease[2]) >= 10_586
) {
return Number(osRelease[2]) >= 14_931 ? 3 : 2;
}
return 1;
}
if ('CI' in env) {
if (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) {
return 3;
}
if (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
return 1;
}
return min;
}
if ('TEAMCITY_VERSION' in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if (env.COLORTERM === 'truecolor') {
return 3;
}
if (env.TERM === 'xterm-kitty') {
return 3;
}
if (env.TERM === 'xterm-ghostty') {
return 3;
}
if (env.TERM === 'wezterm') {
return 3;
}
if ('TERM_PROGRAM' in env) {
const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
switch (env.TERM_PROGRAM) {
case 'iTerm.app': {
return version >= 3 ? 3 : 2;
}
case 'Apple_Terminal': {
return 2;
}
// No default
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ('COLORTERM' in env) {
return 1;
}
return min;
}
export function createSupportsColor(stream, options = {}) {
const level = _supportsColor(stream, {
streamIsTTY: stream && stream.isTTY,
...options,
});
return translateLevel(level);
}
const supportsColor = {
stdout: createSupportsColor({isTTY: tty.isatty(1)}),
stderr: createSupportsColor({isTTY: tty.isatty(2)}),
};
export default supportsColor;

67
node_modules/jsondiffpatch/package.json generated vendored Normal file
View File

@@ -0,0 +1,67 @@
{
"name": "jsondiffpatch",
"version": "0.6.0",
"author": "Benjamin Eidelman <beneidel@gmail.com>",
"description": "Diff & Patch for Javascript objects",
"contributors": [
"Benjamin Eidelman <beneidel@gmail.com>"
],
"type": "module",
"sideEffects": [
"*.css"
],
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"exports": {
".": "./lib/index.js",
"./with-text-diffs": "./lib/with-text-diffs.js",
"./formatters/*": "./lib/formatters/*.js",
"./formatters/styles/*.css": "./lib/formatters/styles/*.css"
},
"files": [
"bin",
"lib"
],
"bin": {
"jsondiffpatch": "./bin/jsondiffpatch.js"
},
"scripts": {
"build": "tsc && ncp ./src/formatters/styles/ ./lib/formatters/styles/",
"type-check": "tsc --noEmit",
"lint": "eslint . --ext .ts",
"test": "jest --coverage",
"prepack": "npm run build",
"prepublishOnly": "npm run test && npm run lint"
},
"repository": {
"type": "git",
"url": "https://github.com/benjamine/jsondiffpatch.git"
},
"keywords": [
"json",
"diff",
"patch"
],
"dependencies": {
"@types/diff-match-patch": "^1.0.36",
"chalk": "^5.3.0",
"diff-match-patch": "^1.0.5"
},
"devDependencies": {
"@types/jest": "^29.5.10",
"@typescript-eslint/eslint-plugin": "^6.13.1",
"@typescript-eslint/parser": "^6.13.1",
"eslint": "^8.55.0",
"eslint-config-prettier": "^9.1.0",
"jest": "^29.7.0",
"ncp": "^2.0.0",
"ts-jest": "^29.1.1",
"tslib": "^2.6.2",
"typescript": "~5.3.2"
},
"license": "MIT",
"engines": {
"node": "^18.0.0 || >=20.0.0"
},
"homepage": "https://github.com/benjamine/jsondiffpatch"
}