@naturalcycles/nodejs-lib 15.143.0 → 15.145.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/validation/ajv/getAjv.js +5 -0
- package/dist/validation/ajv/index.d.ts +1 -0
- package/dist/validation/ajv/index.js +1 -0
- package/dist/validation/ajv/jSchema.d.ts +49 -1
- package/dist/validation/ajv/jSchema.js +84 -30
- package/dist/validation/ajv/jsonSchemaBuilder.util.js +2 -0
- package/dist/validation/ajv/mock/generateMockFromSchema.d.ts +67 -0
- package/dist/validation/ajv/mock/generateMockFromSchema.js +524 -0
- package/package.json +1 -1
- package/src/validation/ajv/getAjv.ts +6 -0
- package/src/validation/ajv/index.ts +1 -0
- package/src/validation/ajv/jSchema.ts +127 -40
- package/src/validation/ajv/jsonSchemaBuilder.util.ts +2 -0
- package/src/validation/ajv/mock/generateMockFromSchema.ts +633 -0
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
import { _clamp, _isPlainObject } from '@naturalcycles/js-lib'
|
|
2
|
+
import { localDate, localTime } from '@naturalcycles/js-lib/datetime'
|
|
3
|
+
import { _mapValues, Set2 } from '@naturalcycles/js-lib/object'
|
|
4
|
+
import type { AnyObject, IsoDate, StringMap, UnixTimestamp } from '@naturalcycles/js-lib/types'
|
|
5
|
+
import { _stringMapEntries } from '@naturalcycles/js-lib/types'
|
|
6
|
+
import type { JSchema, JsonSchema, JsonSchemaIsoDateOptions } from '../jSchema.js'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Generates a value that passes the schema, e.g for a mock in a test.
|
|
10
|
+
* Uses the example or default of a field when it has one.
|
|
11
|
+
* A string with a pattern needs an example or a default.
|
|
12
|
+
*
|
|
13
|
+
* ```
|
|
14
|
+
* const account = generateMockFromSchema(accountSchema, { allFields: true })
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* @experimental
|
|
18
|
+
*/
|
|
19
|
+
export function generateMockFromSchema<OUT>(
|
|
20
|
+
schema: JSchema<OUT, any>,
|
|
21
|
+
opt: GenerateMockFromSchemaOptions = {},
|
|
22
|
+
): OUT {
|
|
23
|
+
const value = generateValue(schema.build(), '', { opt, choices: new Map(), reachedChoices: [] })
|
|
24
|
+
return schema.validate(value)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Generates the mock of `generateMockFromSchema` with `allFields`, plus one variant for each other
|
|
29
|
+
* branch of each `j.anyOfThese` and `j.anyOfBy` union, and for each other property of each group
|
|
30
|
+
* of exclusive properties, so every field appears in some variant.
|
|
31
|
+
* `j.anyOf` and `j.oneOf` always take their first branch, since their branches add no fields.
|
|
32
|
+
* With `maxProperties`, only the first fields up to the limit appear,
|
|
33
|
+
* e.g `b` never appears for `{ a?, b? }.maxProperties(1)`. With overlapping groups of exclusive
|
|
34
|
+
* properties, a property shared by two groups may not appear. When an earlier `j.anyOfThese` branch
|
|
35
|
+
* also matches a later branch's value, validation drops the later branch's extra fields, so put the
|
|
36
|
+
* wider branch first.
|
|
37
|
+
*
|
|
38
|
+
* ```
|
|
39
|
+
* const variants = generateMockVariantsFromSchema(accountSchema)
|
|
40
|
+
* // [{ value }, { value, choice: { path: 'address.taxId', option: 1, key: 'mx_rfc' } }]
|
|
41
|
+
* ```
|
|
42
|
+
*
|
|
43
|
+
* @experimental
|
|
44
|
+
*/
|
|
45
|
+
export function generateMockVariantsFromSchema<OUT>(schema: JSchema<OUT, any>): MockVariant<OUT>[] {
|
|
46
|
+
// Built once, so a choice is the same object in every run
|
|
47
|
+
const root = schema.build()
|
|
48
|
+
const queue: QueuedVariant[] = [{ choices: new Map() }]
|
|
49
|
+
const seenChoices = new Set<ChoicePoint>()
|
|
50
|
+
const variants: MockVariant<OUT>[] = []
|
|
51
|
+
|
|
52
|
+
for (const { choices, choice } of queue) {
|
|
53
|
+
const ctx: GenerationContext = { opt: { allFields: true }, choices, reachedChoices: [] }
|
|
54
|
+
const value = generateValue(root, '', ctx)
|
|
55
|
+
variants.push({ value: schema.validate(value), ...(choice && { choice }) })
|
|
56
|
+
|
|
57
|
+
for (const { point, path, options } of ctx.reachedChoices) {
|
|
58
|
+
if (seenChoices.has(point)) continue
|
|
59
|
+
seenChoices.add(point)
|
|
60
|
+
for (let option = 1; option < options.length; option++) {
|
|
61
|
+
const { key } = options[option]!
|
|
62
|
+
queue.push({
|
|
63
|
+
choices: new Map(choices).set(point, option),
|
|
64
|
+
choice: { path, option, ...(key !== undefined && { key }) },
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return variants
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const MOCK_UNIX_TIMESTAMP = 1_655_287_200 as UnixTimestamp // 2022-06-15T10:00:00Z
|
|
74
|
+
const MOCK_ISO_DATE = '2022-06-15'
|
|
75
|
+
|
|
76
|
+
function generateValue(node: JsonSchema, path: string, ctx: GenerationContext): any {
|
|
77
|
+
assertSupportedKeywords(node, path)
|
|
78
|
+
const value = generateValueFromKeywords(node, path, ctx)
|
|
79
|
+
if (node.optionalValues?.includes(value)) {
|
|
80
|
+
throw cannotGenerate(
|
|
81
|
+
path,
|
|
82
|
+
`the generated value ${JSON.stringify(value)} would be removed by optionalValues, give the field an example`,
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
return value
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function generateValueFromKeywords(node: JsonSchema, path: string, ctx: GenerationContext): any {
|
|
89
|
+
if (node.examples?.length) return copyPlainValue(node.examples[0])
|
|
90
|
+
if (node.default !== undefined) return copyPlainValue(node.default)
|
|
91
|
+
if (node.isUndefined) return undefined
|
|
92
|
+
if (node.enum) return node.enum[0]
|
|
93
|
+
if (node.ifDefined) return generateValue(node.ifDefined, path, ctx)
|
|
94
|
+
|
|
95
|
+
if (node.anyOfThese || node.anyOfBy) return generateFieldUnion(node, path, ctx)
|
|
96
|
+
const branches = [...(node.anyOf || []), ...(node.oneOf || [])]
|
|
97
|
+
if (branches.length) {
|
|
98
|
+
return generateValue(branches.find(isNonNullBranch) || branches[0]!, path, ctx)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (node.instanceof === 'Date') return localTime.fromUnix(MOCK_UNIX_TIMESTAMP).toDate()
|
|
102
|
+
if (node.instanceof) {
|
|
103
|
+
throw cannotGenerate(path, `cannot create an instance of ${node.instanceof}`)
|
|
104
|
+
}
|
|
105
|
+
if (node.Buffer) return Buffer.from('mock')
|
|
106
|
+
if (node.Set2) return new Set2(generateList(node, node.Set2, path, ctx))
|
|
107
|
+
|
|
108
|
+
if (node.type === 'string') return generateString(node, path)
|
|
109
|
+
if (node.type === 'number' || node.type === 'integer') return generateNumber(node, path)
|
|
110
|
+
if (node.type === 'boolean') return true
|
|
111
|
+
if (node.type === 'null') return null
|
|
112
|
+
if (node.type === 'array') return generateArray(node, path, ctx)
|
|
113
|
+
if (node.type === 'object') return generateObject(node, path, ctx)
|
|
114
|
+
// A schema without a type, e.g `j.any()`, accepts any value
|
|
115
|
+
return 'mock'
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function assertSupportedKeywords(node: JsonSchema, path: string): void {
|
|
119
|
+
for (const keyword of Object.keys(node)) {
|
|
120
|
+
if (!SUPPORTED_KEYWORDS[keyword as keyof JsonSchema]) {
|
|
121
|
+
throw cannotGenerate(path, `the keyword ${keyword} is not supported`)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Copies plain objects, arrays and sets, so a variant does not share them with the schema
|
|
128
|
+
* or with other variants.
|
|
129
|
+
*/
|
|
130
|
+
function copyPlainValue(value: any): any {
|
|
131
|
+
if (Array.isArray(value)) return value.map(copyPlainValue)
|
|
132
|
+
if (value instanceof Set2) return new Set2(Array.from(value, copyPlainValue))
|
|
133
|
+
if (!_isPlainObject(value)) return value
|
|
134
|
+
return _mapValues(value, (_, item) => copyPlainValue(item))
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Generates one branch of the union: the branch listed for it in `ctx.choices`, or else the first.
|
|
139
|
+
*/
|
|
140
|
+
function generateFieldUnion(node: JsonSchema, path: string, ctx: GenerationContext): any {
|
|
141
|
+
const branches = getUnionBranches(node).filter(branch => isNonNullBranch(branch.schema))
|
|
142
|
+
if (!branches.length) throw cannotGenerate(path, 'the union has no branch that is not null')
|
|
143
|
+
ctx.reachedChoices.push({ point: node, path, options: branches })
|
|
144
|
+
|
|
145
|
+
const { key, schema } = branches[ctx.choices.get(node) ?? 0]!
|
|
146
|
+
const value = generateValue(schema, path, ctx)
|
|
147
|
+
if (!node.anyOfBy) return value
|
|
148
|
+
|
|
149
|
+
const { propertyName } = node.anyOfBy
|
|
150
|
+
const properties: StringMap<JsonSchema> = schema.properties || {}
|
|
151
|
+
return { ...value, [propertyName]: toPropertyValue(key!, properties[propertyName]) }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function getUnionBranches(node: JsonSchema): UnionBranch[] {
|
|
155
|
+
if (node.anyOfBy) {
|
|
156
|
+
return _stringMapEntries(node.anyOfBy.schemaDictionary).map(([key, schema]) => ({
|
|
157
|
+
key,
|
|
158
|
+
schema,
|
|
159
|
+
}))
|
|
160
|
+
}
|
|
161
|
+
return (node.anyOfThese || []).map(schema => ({ schema }))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Dictionary keys are strings, while the property can be e.g a number enum.
|
|
166
|
+
* A nullable or optional property wraps its schema, e.g in `anyOf`, so those are searched too.
|
|
167
|
+
*/
|
|
168
|
+
function toPropertyValue(key: string, propertySchema: JsonSchema | undefined): unknown {
|
|
169
|
+
const schemas = [
|
|
170
|
+
propertySchema,
|
|
171
|
+
...(propertySchema?.anyOf || []),
|
|
172
|
+
...(propertySchema?.oneOf || []),
|
|
173
|
+
propertySchema?.ifDefined,
|
|
174
|
+
].filter(schema => schema !== undefined)
|
|
175
|
+
const enumValue = schemas
|
|
176
|
+
.flatMap(schema => schema.enum || [])
|
|
177
|
+
.find((value: unknown) => String(value) === key)
|
|
178
|
+
if (enumValue !== undefined) return enumValue
|
|
179
|
+
const types = new Set(schemas.map(schema => schema.type))
|
|
180
|
+
if (types.has('number') || types.has('integer')) return Number(key)
|
|
181
|
+
if (types.has('boolean')) return key === 'true'
|
|
182
|
+
return key
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function isNonNullBranch(branch: JsonSchema): boolean {
|
|
186
|
+
if (branch.type === 'null' || branch.isUndefined) return false
|
|
187
|
+
// `j.literal(null)` builds `{ enum: [null] }`
|
|
188
|
+
return !(branch.enum?.length === 1 && branch.enum[0] === null)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function generateString(node: JsonSchema, path: string): string {
|
|
192
|
+
if (node.IsoDate) return generateIsoDate(node.IsoDate)
|
|
193
|
+
if (node.IsoDateTime) return `${MOCK_ISO_DATE}T10:00:00Z`
|
|
194
|
+
if (node.IsoMonth) return MOCK_ISO_DATE.slice(0, 7)
|
|
195
|
+
if (node.UtcOffset) return '+02:00'
|
|
196
|
+
if (node.email) return 'mock@example.com'
|
|
197
|
+
if (node.pattern) {
|
|
198
|
+
throw cannotGenerate(path, 'a string with a pattern needs an example, .example(...)')
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const value = 'mock'.padEnd(node.minLength || 0, 'x')
|
|
202
|
+
return value.slice(0, node.maxLength ?? value.length)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* ISO dates sort as strings, so the bounds are compared as strings.
|
|
207
|
+
*/
|
|
208
|
+
function generateIsoDate(bounds: JsonSchemaIsoDateOptions): string {
|
|
209
|
+
const { sameOrAfter, after, sameOrBefore, before } = bounds
|
|
210
|
+
let date: string = MOCK_ISO_DATE
|
|
211
|
+
if (sameOrAfter && date < sameOrAfter) date = sameOrAfter
|
|
212
|
+
if (after && date <= after) {
|
|
213
|
+
date = localDate(after as IsoDate)
|
|
214
|
+
.plusDays(1)
|
|
215
|
+
.toISODate()
|
|
216
|
+
}
|
|
217
|
+
if (sameOrBefore && date > sameOrBefore) date = sameOrBefore
|
|
218
|
+
if (before && date >= before) {
|
|
219
|
+
date = localDate(before as IsoDate)
|
|
220
|
+
.minusDays(1)
|
|
221
|
+
.toISODate()
|
|
222
|
+
}
|
|
223
|
+
return date
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* The preferred number if it fits the schema, else the preferred number rounded to the step,
|
|
228
|
+
* else the first number that fits from the lower bound up, or from the upper bound down.
|
|
229
|
+
*/
|
|
230
|
+
function generateNumber(node: JsonSchema, path: string): number {
|
|
231
|
+
const step = getStep(node)
|
|
232
|
+
const preferred = getPreferredNumber(node)
|
|
233
|
+
const candidates = [preferred, ...roundToStep(preferred, step), ...getBoundCandidates(node, step)]
|
|
234
|
+
const value = candidates.find(candidate => fitsNumberSchema(node, candidate, step))
|
|
235
|
+
if (value === undefined) {
|
|
236
|
+
throw cannotGenerate(path, 'no number satisfies the bounds of the schema')
|
|
237
|
+
}
|
|
238
|
+
// Turns -0 into 0
|
|
239
|
+
return value + 0
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* `multipleOf`, or 1 for an integer. For an integer with a fractional `multipleOf`,
|
|
244
|
+
* the smallest whole multiple of it, e.g 2 for 0.4.
|
|
245
|
+
*/
|
|
246
|
+
function getStep(node: JsonSchema): number | undefined {
|
|
247
|
+
const { multipleOf } = node
|
|
248
|
+
if (node.type !== 'integer') return multipleOf
|
|
249
|
+
if (!multipleOf) return 1
|
|
250
|
+
// With `multipleOf` as a fraction `scaled / scale`, the whole multiple is `scaled / gcd`
|
|
251
|
+
const scale = getDecimalScale(multipleOf)
|
|
252
|
+
const scaled = Math.round(multipleOf * scale)
|
|
253
|
+
return scaled / getGreatestCommonDivisor(scaled, scale)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The power of 10 that makes the number whole, e.g 100 for 0.25.
|
|
258
|
+
* Stops at 10^15, the precision of a number, e.g for 1/3.
|
|
259
|
+
*/
|
|
260
|
+
function getDecimalScale(value: number): number {
|
|
261
|
+
let scale = 1
|
|
262
|
+
while (Math.abs(value * scale - Math.round(value * scale)) > 1e-9 && scale < 1e15) scale *= 10
|
|
263
|
+
return scale
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function getGreatestCommonDivisor(a: number, b: number): number {
|
|
267
|
+
if (!b) return a
|
|
268
|
+
return getGreatestCommonDivisor(b, a % b)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function getPreferredNumber(node: JsonSchema): number {
|
|
272
|
+
if (node.format === 'UnixTimestamp') return MOCK_UNIX_TIMESTAMP
|
|
273
|
+
if (node.format === 'UnixTimestampMillis') return MOCK_UNIX_TIMESTAMP * 1000
|
|
274
|
+
return 1
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function roundToStep(value: number, step: number | undefined): number[] {
|
|
278
|
+
if (!step) return []
|
|
279
|
+
return [Math.ceil(value / step) * step, Math.floor(value / step) * step]
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* The first numbers at or inside the lower bound, or else the upper bound: with a step, the first
|
|
284
|
+
* two multiples, without one the bound itself, the midpoint between the bounds, and the bound + 1.
|
|
285
|
+
*/
|
|
286
|
+
function getBoundCandidates(node: JsonSchema, step: number | undefined): number[] {
|
|
287
|
+
const lower = getTightestBound([node.minimum, node.exclusiveMinimum], Math.max)
|
|
288
|
+
const upper = getTightestBound([node.maximum, node.exclusiveMaximum], Math.min)
|
|
289
|
+
|
|
290
|
+
if (lower !== undefined && step) {
|
|
291
|
+
const first = Math.ceil(lower / step) * step
|
|
292
|
+
return [first, first + step]
|
|
293
|
+
}
|
|
294
|
+
if (lower !== undefined) {
|
|
295
|
+
const midpoint = upper === undefined ? lower : lower + (upper - lower) / 2
|
|
296
|
+
return [lower, midpoint, lower + 1]
|
|
297
|
+
}
|
|
298
|
+
if (upper !== undefined && step) {
|
|
299
|
+
const last = Math.floor(upper / step) * step
|
|
300
|
+
return [last, last - step]
|
|
301
|
+
}
|
|
302
|
+
if (upper !== undefined) return [upper, upper - 1]
|
|
303
|
+
return []
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function getTightestBound(
|
|
307
|
+
bounds: (number | undefined)[],
|
|
308
|
+
pick: (...values: number[]) => number,
|
|
309
|
+
): number | undefined {
|
|
310
|
+
const definedBounds = bounds.filter(bound => bound !== undefined)
|
|
311
|
+
if (!definedBounds.length) return
|
|
312
|
+
return pick(...definedBounds)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function fitsNumberSchema(node: JsonSchema, value: number, step: number | undefined): boolean {
|
|
316
|
+
if (node.minimum !== undefined && value < node.minimum) return false
|
|
317
|
+
if (node.exclusiveMinimum !== undefined && value <= node.exclusiveMinimum) return false
|
|
318
|
+
if (node.maximum !== undefined && value > node.maximum) return false
|
|
319
|
+
if (node.exclusiveMaximum !== undefined && value >= node.exclusiveMaximum) return false
|
|
320
|
+
if (node.multipleOf && !Number.isInteger(value / node.multipleOf)) return false
|
|
321
|
+
if (step && !Number.isInteger(value / step)) return false
|
|
322
|
+
if (node.type === 'integer' && !Number.isInteger(value)) return false
|
|
323
|
+
return true
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function generateArray(node: JsonSchema, path: string, ctx: GenerationContext): any[] {
|
|
327
|
+
if (node.prefixItems) {
|
|
328
|
+
return node.prefixItems.map(item => generateValue(item, path, ctx))
|
|
329
|
+
}
|
|
330
|
+
if (!node.items) return []
|
|
331
|
+
return generateList(node, node.items, path, ctx)
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* `minItems` items, at least one with `allFields`, at most `maxItems`.
|
|
336
|
+
*/
|
|
337
|
+
function generateList(
|
|
338
|
+
node: JsonSchema,
|
|
339
|
+
itemSchema: JsonSchema,
|
|
340
|
+
path: string,
|
|
341
|
+
ctx: GenerationContext,
|
|
342
|
+
): any[] {
|
|
343
|
+
const minCount = Math.max(node.minItems || 0, ctx.opt.allFields ? 1 : 0)
|
|
344
|
+
const count = _clamp(minCount, 0, node.maxItems ?? minCount)
|
|
345
|
+
|
|
346
|
+
if (count > 1 && (node.Set2 || node.uniqueItems)) {
|
|
347
|
+
throw cannotGenerate(
|
|
348
|
+
path,
|
|
349
|
+
`a list of ${count} distinct items needs an example, .example([...])`,
|
|
350
|
+
)
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// The items share the path of the list: they come from the same schema
|
|
354
|
+
return Array.from({ length: count }, () => generateValue(itemSchema, path, ctx))
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function generateObject(node: JsonSchema, path: string, ctx: GenerationContext): AnyObject {
|
|
358
|
+
const keys = selectPropertyKeys(node, path, ctx)
|
|
359
|
+
const properties: StringMap<JsonSchema> = node.properties || {}
|
|
360
|
+
const result: AnyObject = {}
|
|
361
|
+
|
|
362
|
+
for (const key of keys) {
|
|
363
|
+
const value = generateValue(properties[key]!, joinPath(path, key), ctx)
|
|
364
|
+
if (value !== undefined) result[key] = value
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const shouldFillMaps = ctx.opt.allFields || keys.length < (node.minProperties || 0)
|
|
368
|
+
const hasRoomForMaps = keys.length < (node.maxProperties ?? Infinity)
|
|
369
|
+
if (!shouldFillMaps || !hasRoomForMaps) return result
|
|
370
|
+
|
|
371
|
+
const missingCount = (node.minProperties || 0) - keys.length
|
|
372
|
+
if (missingCount > 1) {
|
|
373
|
+
throw cannotGenerate(path, `a map of ${missingCount} keys needs an example, .example({...})`)
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
for (const [pattern, valueSchema] of _stringMapEntries(node.patternProperties || {})) {
|
|
377
|
+
const key = generateKey(node, path, ctx)
|
|
378
|
+
if (key === undefined) {
|
|
379
|
+
throw cannotGenerate(
|
|
380
|
+
path,
|
|
381
|
+
`a map with keys matching ${pattern} needs an example, .example({...})`,
|
|
382
|
+
)
|
|
383
|
+
}
|
|
384
|
+
assertKeyIsFree(node, result, key, path)
|
|
385
|
+
result[key] = generateValue(valueSchema, joinPath(path, key), ctx)
|
|
386
|
+
}
|
|
387
|
+
if (typeof node.additionalProperties === 'object') {
|
|
388
|
+
const key = generateKey(node, path, ctx) ?? findFreeKey(node, result)
|
|
389
|
+
assertKeyIsFree(node, result, key, path)
|
|
390
|
+
result[key] = generateValue(node.additionalProperties, joinPath(path, key), ctx)
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
return result
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* `key`, or else `key1`, `key2` and so on, whichever the object does not have yet.
|
|
398
|
+
*/
|
|
399
|
+
function findFreeKey(node: JsonSchema, result: AnyObject): string {
|
|
400
|
+
let key = 'key'
|
|
401
|
+
for (let index = 1; isKeyTaken(node, result, key); index++) key = `key${index}`
|
|
402
|
+
return key
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function assertKeyIsFree(node: JsonSchema, result: AnyObject, key: string, path: string): void {
|
|
406
|
+
if (isKeyTaken(node, result, key)) {
|
|
407
|
+
throw cannotGenerate(
|
|
408
|
+
joinPath(path, key),
|
|
409
|
+
`the key schema gives the key ${JSON.stringify(key)}, which is also a field of the object: give the key schema another example, or the map an example, .example({...})`,
|
|
410
|
+
)
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function isKeyTaken(node: JsonSchema, result: AnyObject, key: string): boolean {
|
|
415
|
+
return Object.hasOwn(node.properties || {}, key) || Object.hasOwn(result, key)
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* The required keys, or every key with `allFields`, plus optional keys until `minProperties`
|
|
420
|
+
* is reached, and at most `maxProperties` keys. Only one key of each group of exclusive properties
|
|
421
|
+
* is kept. The keys keep the order of the schema.
|
|
422
|
+
*/
|
|
423
|
+
function selectPropertyKeys(node: JsonSchema, path: string, ctx: GenerationContext): string[] {
|
|
424
|
+
const required = node.required || []
|
|
425
|
+
const excludedKeys = new Set(
|
|
426
|
+
(node.exclusiveProperties || []).flatMap(group => {
|
|
427
|
+
const keptKey = chooseExclusiveKey(group, required, path, ctx)
|
|
428
|
+
return group.filter(key => key !== keptKey)
|
|
429
|
+
}),
|
|
430
|
+
)
|
|
431
|
+
const candidateKeys = Object.keys(node.properties || {}).filter(key => !excludedKeys.has(key))
|
|
432
|
+
const requiredKeys = candidateKeys.filter(key => required.includes(key))
|
|
433
|
+
const optionalKeys = candidateKeys.filter(key => !required.includes(key))
|
|
434
|
+
|
|
435
|
+
const minCount = ctx.opt.allFields
|
|
436
|
+
? candidateKeys.length
|
|
437
|
+
: Math.max(requiredKeys.length, node.minProperties || 0)
|
|
438
|
+
const count = _clamp(minCount, 0, node.maxProperties ?? minCount)
|
|
439
|
+
|
|
440
|
+
const keptOptionalKeys = new Set(optionalKeys.slice(0, Math.max(0, count - requiredKeys.length)))
|
|
441
|
+
return candidateKeys.filter(key => required.includes(key) || keptOptionalKeys.has(key))
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* The required key of the group, or else the key listed for the group in `ctx.choices`,
|
|
446
|
+
* or else the first.
|
|
447
|
+
*/
|
|
448
|
+
function chooseExclusiveKey(
|
|
449
|
+
group: readonly string[],
|
|
450
|
+
required: string[],
|
|
451
|
+
path: string,
|
|
452
|
+
ctx: GenerationContext,
|
|
453
|
+
): string {
|
|
454
|
+
const requiredKey = group.find(key => required.includes(key))
|
|
455
|
+
if (requiredKey) return requiredKey
|
|
456
|
+
ctx.reachedChoices.push({ point: group, path, options: group.map(key => ({ key })) })
|
|
457
|
+
return group[ctx.choices.get(group) ?? 0]!
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function generateKey(node: JsonSchema, path: string, ctx: GenerationContext): string | undefined {
|
|
461
|
+
if (!node.keySchema) return
|
|
462
|
+
return String(generateValue(node.keySchema, joinPath(path, '<key>'), ctx))
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function cannotGenerate(path: string, reason: string): Error {
|
|
466
|
+
return new Error(`Cannot generate a value at ${path || '(root)'}: ${reason}`)
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function joinPath(path: string, segment: string): string {
|
|
470
|
+
if (!path) return segment
|
|
471
|
+
return `${path}.${segment}`
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Whether the generator supports each keyword. A schema with an unsupported or unknown keyword
|
|
476
|
+
* throws, so the generator does not silently produce a wrong value.
|
|
477
|
+
*/
|
|
478
|
+
const SUPPORTED_KEYWORDS: Record<keyof JsonSchema, boolean> = {
|
|
479
|
+
// Values
|
|
480
|
+
type: true,
|
|
481
|
+
default: true,
|
|
482
|
+
examples: true,
|
|
483
|
+
enum: true,
|
|
484
|
+
// Unions
|
|
485
|
+
anyOf: true,
|
|
486
|
+
oneOf: true,
|
|
487
|
+
anyOfThese: true,
|
|
488
|
+
anyOfBy: true,
|
|
489
|
+
ifDefined: true,
|
|
490
|
+
isUndefined: true,
|
|
491
|
+
// Strings
|
|
492
|
+
pattern: true,
|
|
493
|
+
minLength: true,
|
|
494
|
+
maxLength: true,
|
|
495
|
+
format: true,
|
|
496
|
+
email: true,
|
|
497
|
+
IsoDate: true,
|
|
498
|
+
IsoDateTime: true,
|
|
499
|
+
IsoMonth: true,
|
|
500
|
+
UtcOffset: true,
|
|
501
|
+
// Numbers
|
|
502
|
+
minimum: true,
|
|
503
|
+
exclusiveMinimum: true,
|
|
504
|
+
maximum: true,
|
|
505
|
+
exclusiveMaximum: true,
|
|
506
|
+
multipleOf: true,
|
|
507
|
+
precision: true,
|
|
508
|
+
// Arrays and sets
|
|
509
|
+
items: true,
|
|
510
|
+
prefixItems: true,
|
|
511
|
+
minItems: true,
|
|
512
|
+
maxItems: true,
|
|
513
|
+
uniqueItems: true,
|
|
514
|
+
Set2: true,
|
|
515
|
+
// Objects
|
|
516
|
+
properties: true,
|
|
517
|
+
required: true,
|
|
518
|
+
patternProperties: true,
|
|
519
|
+
additionalProperties: true,
|
|
520
|
+
keySchema: true,
|
|
521
|
+
minProperties: true,
|
|
522
|
+
minProperties2: true,
|
|
523
|
+
maxProperties: true,
|
|
524
|
+
exclusiveProperties: true,
|
|
525
|
+
instanceof: true,
|
|
526
|
+
Buffer: true,
|
|
527
|
+
// Annotations, and rules that the validation at the end checks
|
|
528
|
+
$schema: true,
|
|
529
|
+
$id: true,
|
|
530
|
+
title: true,
|
|
531
|
+
description: true,
|
|
532
|
+
deprecated: true,
|
|
533
|
+
readOnly: true,
|
|
534
|
+
writeOnly: true,
|
|
535
|
+
hasIsOfTypeCheck: true,
|
|
536
|
+
errorMessages: true,
|
|
537
|
+
enumNames: true,
|
|
538
|
+
enumKeys: true,
|
|
539
|
+
transform: true,
|
|
540
|
+
optionalValues: true,
|
|
541
|
+
customValidations: true,
|
|
542
|
+
customConversions: true,
|
|
543
|
+
postValidation: true,
|
|
544
|
+
// Not built by `j`
|
|
545
|
+
if: false,
|
|
546
|
+
// oxlint-disable-next-line unicorn/no-thenable -- a JSON Schema keyword, the object is never awaited
|
|
547
|
+
then: false,
|
|
548
|
+
else: false,
|
|
549
|
+
contentMediaType: false,
|
|
550
|
+
contentEncoding: false,
|
|
551
|
+
// Type-only and parser-only fields, never in a built schema
|
|
552
|
+
out: false,
|
|
553
|
+
optionalField: false,
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* @experimental
|
|
558
|
+
*/
|
|
559
|
+
export interface GenerateMockFromSchemaOptions {
|
|
560
|
+
/**
|
|
561
|
+
* Fills every optional field, and puts one item in each list and one key in each map.
|
|
562
|
+
* Default: false, only the required fields.
|
|
563
|
+
*/
|
|
564
|
+
allFields?: boolean
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* @experimental
|
|
569
|
+
*/
|
|
570
|
+
export interface MockVariant<OUT> {
|
|
571
|
+
value: OUT
|
|
572
|
+
/**
|
|
573
|
+
* The choice this variant changes: a branch of a union, or a property of a group of exclusive
|
|
574
|
+
* properties. Absent for the first variant.
|
|
575
|
+
*/
|
|
576
|
+
choice?: {
|
|
577
|
+
/**
|
|
578
|
+
* Path of the union, or of the object with the group, e.g `address.taxId`, empty at the root.
|
|
579
|
+
* Two unions can share a path when one is directly inside a branch of the other.
|
|
580
|
+
*/
|
|
581
|
+
path: string
|
|
582
|
+
/**
|
|
583
|
+
* Index of the branch, counting only branches that are not `null`, or of the property in the group.
|
|
584
|
+
*/
|
|
585
|
+
option: number
|
|
586
|
+
/**
|
|
587
|
+
* Key of the branch in a `j.anyOfBy` union, or the property of the group.
|
|
588
|
+
*/
|
|
589
|
+
key?: string
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
interface GenerationContext {
|
|
594
|
+
opt: GenerateMockFromSchemaOptions
|
|
595
|
+
/**
|
|
596
|
+
* The option to take at a choice. Other choices take their first option.
|
|
597
|
+
*/
|
|
598
|
+
choices: Map<ChoicePoint, number>
|
|
599
|
+
/**
|
|
600
|
+
* Filled while generating: the choices, in the order they are reached.
|
|
601
|
+
*/
|
|
602
|
+
reachedChoices: ReachedChoice[]
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* A union, by its schema node, or a group of exclusive properties.
|
|
607
|
+
*/
|
|
608
|
+
type ChoicePoint = JsonSchema | readonly string[]
|
|
609
|
+
|
|
610
|
+
interface ReachedChoice {
|
|
611
|
+
point: ChoicePoint
|
|
612
|
+
path: string
|
|
613
|
+
/**
|
|
614
|
+
* For a union, the branches that are not `null`. For a group, its properties.
|
|
615
|
+
*/
|
|
616
|
+
options: ChoiceOption[]
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
interface ChoiceOption {
|
|
620
|
+
/**
|
|
621
|
+
* Key of the branch in a `j.anyOfBy` union, or the property of a group of exclusive properties.
|
|
622
|
+
*/
|
|
623
|
+
key?: string
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
interface UnionBranch extends ChoiceOption {
|
|
627
|
+
schema: JsonSchema
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
interface QueuedVariant {
|
|
631
|
+
choices: Map<ChoicePoint, number>
|
|
632
|
+
choice?: MockVariant<unknown>['choice']
|
|
633
|
+
}
|