|
| 1 | +import { Contract, walkObject } from '@vanilla-extract/private'; |
| 2 | +import { diff } from 'deep-object-diff'; |
| 3 | +import chalk from 'chalk'; |
| 4 | + |
| 5 | +const normaliseObject = (obj: Contract) => walkObject(obj, () => ''); |
| 6 | + |
| 7 | +export function validateContract(contract: any, tokens: any) { |
| 8 | + const theDiff = diff(normaliseObject(contract), normaliseObject(tokens)); |
| 9 | + const valid = Object.keys(theDiff).length === 0; |
| 10 | + |
| 11 | + return { |
| 12 | + valid, |
| 13 | + diffString: valid ? '' : renderDiff(contract, theDiff), |
| 14 | + }; |
| 15 | +} |
| 16 | + |
| 17 | +function diffLine(value: string, nesting: number, type?: '+' | '-') { |
| 18 | + const whitespace = [...Array(nesting).keys()].map(() => ' ').join(''); |
| 19 | + const line = `${type ? type : ' '}${whitespace}${value}`; |
| 20 | + |
| 21 | + if (process.env.NODE_ENV !== 'test') { |
| 22 | + if (type === '-') { |
| 23 | + return chalk.red(line); |
| 24 | + } |
| 25 | + |
| 26 | + if (type === '+') { |
| 27 | + return chalk.green(line); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + return line; |
| 32 | +} |
| 33 | + |
| 34 | +function renderDiff(orig: any, diff: any, nesting: number = 0): string { |
| 35 | + const lines = []; |
| 36 | + |
| 37 | + if (nesting === 0) { |
| 38 | + lines.push(diffLine('{', 0)); |
| 39 | + } |
| 40 | + |
| 41 | + const innerNesting = nesting + 1; |
| 42 | + |
| 43 | + const keys = Object.keys(diff).sort(); |
| 44 | + |
| 45 | + for (const key of keys) { |
| 46 | + const value = diff[key]; |
| 47 | + |
| 48 | + if (!(key in orig)) { |
| 49 | + lines.push(diffLine(`${key}: ...,`, innerNesting, '+')); |
| 50 | + } else if (typeof value === 'object') { |
| 51 | + lines.push(diffLine(`${key}: {`, innerNesting)); |
| 52 | + |
| 53 | + lines.push(renderDiff(orig[key], diff[key], innerNesting)); |
| 54 | + |
| 55 | + lines.push(diffLine('}', innerNesting)); |
| 56 | + } else { |
| 57 | + lines.push(diffLine(`${key}: ...,`, innerNesting, '-')); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + if (nesting === 0) { |
| 62 | + lines.push(diffLine('}', 0)); |
| 63 | + } |
| 64 | + return lines.join('\n'); |
| 65 | +} |
0 commit comments