Skip to content
This repository was archived by the owner on Jun 22, 2023. It is now read-only.

Commit b78a616

Browse files
author
Boris Cherny
committed
Bugfix: make compile() non-mutating (fix bcherny#370, fix bcherny#443)
1 parent a7d14c4 commit b78a616

File tree

3 files changed

+36
-3
lines changed

3 files changed

+36
-3
lines changed

src/index.ts

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import {readFileSync} from 'fs'
22
import {JSONSchema4} from 'json-schema'
33
import {Options as $RefOptions} from 'json-schema-ref-parser'
4-
import {endsWith, merge} from 'lodash'
4+
import {cloneDeep, endsWith, merge} from 'lodash'
55
import {dirname} from 'path'
66
import {Options as PrettierOptions} from 'prettier'
77
import {format} from './formatter'
@@ -138,9 +138,12 @@ export async function compile(schema: JSONSchema4, name: string, options: Partia
138138
_options.cwd += '/'
139139
}
140140

141-
const dereferenced = await dereference(schema, _options)
141+
// Initial clone to avoid mutating the input
142+
const _schema = cloneDeep(schema)
143+
144+
const dereferenced = await dereference(_schema, _options)
142145
if (process.env.VERBOSE) {
143-
if (isDeepStrictEqual(schema, dereferenced)) {
146+
if (isDeepStrictEqual(_schema, dereferenced)) {
144147
log('green', 'dereferencer', time(), '✅ No change')
145148
} else {
146149
log('green', 'dereferencer', time(), '✅ Result:', dereferenced)

test/test.ts

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {run as runCLITests} from './testCLI'
22
import {run as runCompileFromFileTests} from './testCompileFromFile'
33
import {hasOnly, run as runE2ETests} from './testE2E'
4+
import {run as runIdempotenceTests} from './testIdempotence'
45
import {run as runLinkerTests} from './testLinker'
56
import {run as runNormalizerTests} from './testNormalizer'
67
import {run as runUtilsTests} from './testUtils'
@@ -10,6 +11,7 @@ runE2ETests()
1011
if (!hasOnly()) {
1112
runCompileFromFileTests()
1213
runCLITests()
14+
runIdempotenceTests()
1315
runLinkerTests()
1416
runNormalizerTests()
1517
runUtilsTests()

test/testIdempotence.ts

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import test from 'ava'
2+
import {JSONSchema4} from 'json-schema'
3+
import {cloneDeep} from 'lodash'
4+
import {compile} from '../src'
5+
6+
export function run() {
7+
const SCHEMA: JSONSchema4 = {
8+
type: 'object',
9+
properties: {
10+
firstName: {
11+
type: 'string'
12+
}
13+
},
14+
required: ['firstName']
15+
}
16+
17+
test('compile() should not mutate its input', async t => {
18+
const before = cloneDeep(SCHEMA)
19+
await compile(SCHEMA, 'A')
20+
t.deepEqual(before, SCHEMA)
21+
})
22+
23+
test('compile() should be idempotent', async t => {
24+
const a = await compile(SCHEMA, 'A')
25+
const b = await compile(SCHEMA, 'A')
26+
t.deepEqual(a, b)
27+
})
28+
}

0 commit comments

Comments
 (0)