-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
Copy pathfn.js
527 lines (462 loc) · 14.3 KB
/
fn.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/**
* @prettier
*/
import { List, Map } from "immutable"
export const upperFirst = (value) => {
if (typeof value === "string") {
return `${value.charAt(0).toUpperCase()}${value.slice(1)}`
}
return value
}
/**
* Lookup can be `basic` or `extended`. By default the lookup is `extended`.
*/
export const makeGetTitle = (fnAccessor) => {
const getTitle = (schema, { lookup = "extended" } = {}) => {
const fn = fnAccessor()
if (schema?.title != null) return fn.upperFirst(String(schema.title))
if (lookup === "extended") {
if (schema?.$anchor != null) return fn.upperFirst(String(schema.$anchor))
if (schema?.$id != null) return String(schema.$id)
}
return ""
}
return getTitle
}
export const makeGetType = (fnAccessor) => {
const getType = (schema, processedSchemas = new WeakSet()) => {
const fn = fnAccessor()
if (schema == null) {
return "any"
}
if (fn.isBooleanJSONSchema(schema)) {
return schema ? "any" : "never"
}
if (typeof schema !== "object") {
return "any"
}
if (processedSchemas.has(schema)) {
return "any" // detect a cycle
}
processedSchemas.add(schema)
const { type, prefixItems, items } = schema
const getArrayType = () => {
if (Array.isArray(prefixItems)) {
const prefixItemsTypes = prefixItems.map((itemSchema) =>
getType(itemSchema, processedSchemas)
)
const itemsType = items ? getType(items, processedSchemas) : "any"
return `array<[${prefixItemsTypes.join(", ")}], ${itemsType}>`
} else if (items) {
const itemsType = getType(items, processedSchemas)
return `array<${itemsType}>`
} else {
return "array<any>"
}
}
const inferType = () => {
if (
Object.hasOwn(schema, "prefixItems") ||
Object.hasOwn(schema, "items") ||
Object.hasOwn(schema, "contains")
) {
return getArrayType()
} else if (
Object.hasOwn(schema, "properties") ||
Object.hasOwn(schema, "additionalProperties") ||
Object.hasOwn(schema, "patternProperties")
) {
return "object"
} else if (["int32", "int64"].includes(schema.format)) {
// OpenAPI 3.1.0 integer custom formats
return "integer"
} else if (["float", "double"].includes(schema.format)) {
// OpenAPI 3.1.0 number custom formats
return "number"
} else if (
Object.hasOwn(schema, "minimum") ||
Object.hasOwn(schema, "maximum") ||
Object.hasOwn(schema, "exclusiveMinimum") ||
Object.hasOwn(schema, "exclusiveMaximum") ||
Object.hasOwn(schema, "multipleOf")
) {
return "number | integer"
} else if (
Object.hasOwn(schema, "pattern") ||
Object.hasOwn(schema, "format") ||
Object.hasOwn(schema, "minLength") ||
Object.hasOwn(schema, "maxLength") ||
Object.hasOwn(schema, "contentEncoding") ||
Object.hasOwn(schema, "contentMediaType")
) {
return "string"
} else if (typeof schema.const !== "undefined") {
if (schema.const === null) {
return "null"
} else if (typeof schema.const === "boolean") {
return "boolean"
} else if (typeof schema.const === "number") {
return Number.isInteger(schema.const) ? "integer" : "number"
} else if (typeof schema.const === "string") {
return "string"
} else if (Array.isArray(schema.const)) {
return "array<any>"
} else if (typeof schema.const === "object") {
return "object"
}
}
return null
}
if (schema.not && getType(schema.not) === "any") {
return "never"
}
const typeString = Array.isArray(type)
? type.map((t) => (t === "array" ? getArrayType() : t)).join(" | ")
: type === "array"
? getArrayType()
: [
"null",
"boolean",
"object",
"array",
"number",
"integer",
"string",
].includes(type)
? type
: inferType()
const handleCombiningKeywords = (keyword, separator) => {
if (Array.isArray(schema[keyword])) {
const combinedTypes = schema[keyword].map((subSchema) =>
getType(subSchema, processedSchemas)
)
return `(${combinedTypes.join(separator)})`
}
return null
}
const oneOfString = handleCombiningKeywords("oneOf", " | ")
const anyOfString = handleCombiningKeywords("anyOf", " | ")
const allOfString = handleCombiningKeywords("allOf", " & ")
const combinedStrings = [typeString, oneOfString, anyOfString, allOfString]
.filter(Boolean)
.join(" | ")
processedSchemas.delete(schema)
return combinedStrings || "any"
}
return getType
}
export const isBooleanJSONSchema = (schema) => typeof schema === "boolean"
export const hasKeyword = (schema, keyword) =>
schema !== null &&
typeof schema === "object" &&
Object.hasOwn(schema, keyword)
export const makeIsExpandable = (fnAccessor) => {
const isExpandable = (schema) => {
const fn = fnAccessor()
return (
schema?.$schema ||
schema?.$vocabulary ||
schema?.$id ||
schema?.$anchor ||
schema?.$dynamicAnchor ||
schema?.$ref ||
schema?.$dynamicRef ||
schema?.$defs ||
schema?.$comment ||
schema?.allOf ||
schema?.anyOf ||
schema?.oneOf ||
fn.hasKeyword(schema, "not") ||
fn.hasKeyword(schema, "if") ||
fn.hasKeyword(schema, "then") ||
fn.hasKeyword(schema, "else") ||
schema?.dependentSchemas ||
schema?.prefixItems ||
fn.hasKeyword(schema, "items") ||
fn.hasKeyword(schema, "contains") ||
schema?.properties ||
schema?.patternProperties ||
fn.hasKeyword(schema, "additionalProperties") ||
fn.hasKeyword(schema, "propertyNames") ||
fn.hasKeyword(schema, "unevaluatedItems") ||
fn.hasKeyword(schema, "unevaluatedProperties") ||
schema?.description ||
schema?.enum ||
fn.hasKeyword(schema, "const") ||
fn.hasKeyword(schema, "contentSchema") ||
fn.hasKeyword(schema, "default") ||
schema?.examples ||
fn.getExtensionKeywords(schema).length > 0
)
}
return isExpandable
}
export const stringify = (value) => {
if (
value === null ||
["number", "bigint", "boolean"].includes(typeof value)
) {
return String(value)
}
if (Array.isArray(value)) {
return `[${value.map(stringify).join(", ")}]`
}
return JSON.stringify(value)
}
const stringifyConstraintMultipleOf = (schema) => {
if (typeof schema?.multipleOf !== "number") return null
if (schema.multipleOf <= 0) return null
if (schema.multipleOf === 1) return null
const { multipleOf } = schema
if (Number.isInteger(multipleOf)) {
return `multiple of ${multipleOf}`
}
const decimalPlaces = multipleOf.toString().split(".")[1].length
const factor = 10 ** decimalPlaces
const numerator = multipleOf * factor
const denominator = factor
return `multiple of ${numerator}/${denominator}`
}
const stringifyConstraintNumberRange = (schema) => {
const minimum = schema?.minimum
const maximum = schema?.maximum
const exclusiveMinimum = schema?.exclusiveMinimum
const exclusiveMaximum = schema?.exclusiveMaximum
const hasMinimum = typeof minimum === "number"
const hasMaximum = typeof maximum === "number"
const hasExclusiveMinimum = typeof exclusiveMinimum === "number"
const hasExclusiveMaximum = typeof exclusiveMaximum === "number"
const isMinExclusive = hasExclusiveMinimum && (!hasMinimum || minimum < exclusiveMinimum) // prettier-ignore
const isMaxExclusive = hasExclusiveMaximum && (!hasMaximum || maximum > exclusiveMaximum) // prettier-ignore
if (
(hasMinimum || hasExclusiveMinimum) &&
(hasMaximum || hasExclusiveMaximum)
) {
const minSymbol = isMinExclusive ? "(" : "["
const maxSymbol = isMaxExclusive ? ")" : "]"
const minValue = isMinExclusive ? exclusiveMinimum : minimum
const maxValue = isMaxExclusive ? exclusiveMaximum : maximum
return `${minSymbol}${minValue}, ${maxValue}${maxSymbol}`
}
if (hasMinimum || hasExclusiveMinimum) {
const minSymbol = isMinExclusive ? ">" : "≥"
const minValue = isMinExclusive ? exclusiveMinimum : minimum
return `${minSymbol} ${minValue}`
}
if (hasMaximum || hasExclusiveMaximum) {
const maxSymbol = isMaxExclusive ? "<" : "≤"
const maxValue = isMaxExclusive ? exclusiveMaximum : maximum
return `${maxSymbol} ${maxValue}`
}
return null
}
const stringifyConstraintRange = (label, min, max) => {
const hasMin = typeof min === "number"
const hasMax = typeof max === "number"
if (hasMin && hasMax) {
if (min === max) {
return `${min} ${label}`
} else {
return `[${min}, ${max}] ${label}`
}
}
if (hasMin) {
return `≥ ${min} ${label}`
}
if (hasMax) {
return `≤ ${max} ${label}`
}
return null
}
export const stringifyConstraints = (schema) => {
const constraints = []
// validation Keywords for Numeric Instances (number and integer)
const multipleOf = stringifyConstraintMultipleOf(schema)
if (multipleOf !== null) {
constraints.push({ scope: "number", value: multipleOf })
}
const numberRange = stringifyConstraintNumberRange(schema)
if (numberRange !== null) {
constraints.push({ scope: "number", value: numberRange })
}
// vocabularies for Semantic Content With "format"
if (schema?.format) {
constraints.push({ scope: "string", value: schema.format })
}
// validation Keywords for Strings
const stringRange = stringifyConstraintRange(
"characters",
schema?.minLength,
schema?.maxLength
)
if (stringRange !== null) {
constraints.push({ scope: "string", value: stringRange })
}
if (schema?.pattern) {
constraints.push({ scope: "string", value: `matches ${schema?.pattern}` })
}
// vocabulary for the Contents of String-Encoded Data
if (schema?.contentMediaType) {
constraints.push({
scope: "string",
value: `media type: ${schema.contentMediaType}`,
})
}
if (schema?.contentEncoding) {
constraints.push({
scope: "string",
value: `encoding: ${schema.contentEncoding}`,
})
}
// validation Keywords for Arrays
const arrayRange = stringifyConstraintRange(
schema?.uniqueItems ? "unique items" : "items",
schema?.minItems,
schema?.maxItems
)
if (arrayRange !== null) {
constraints.push({ scope: "array", value: arrayRange })
}
if (schema?.uniqueItems && !arrayRange) {
constraints.push({ scope: "array", value: "unique" })
}
const containsRange = stringifyConstraintRange(
"contained items",
schema?.minContains,
schema?.maxContains
)
if (containsRange !== null) {
constraints.push({ scope: "array", value: containsRange })
}
// validation Keywords for Objects
const objectRange = stringifyConstraintRange(
"properties",
schema?.minProperties,
schema?.maxProperties
)
if (objectRange !== null) {
constraints.push({ scope: "object", value: objectRange })
}
return constraints
}
export const getDependentRequired = (propertyName, schema) => {
if (!schema?.dependentRequired) return []
return Array.from(
Object.entries(schema.dependentRequired).reduce((acc, [prop, list]) => {
if (!Array.isArray(list)) return acc
if (!list.includes(propertyName)) return acc
acc.add(prop)
return acc
}, new Set())
)
}
export const isPlainObject = (value) =>
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
(Object.getPrototypeOf(value) === null ||
Object.getPrototypeOf(value) === Object.prototype)
export const isEmptyObject = (value) =>
isPlainObject(value) && Object.keys(value).length === 0
export const isEmptyArray = (value) =>
Array.isArray(value) && value.length === 0
export const difference = (value, comparisonValue) => {
const comparisonSet = new Set(comparisonValue)
return value.filter((item) => !comparisonSet.has(item))
}
export const getSchemaKeywords = () => {
return [
// core vocabulary
"$schema",
"$vocabulary",
"$id",
"$anchor",
"$dynamicAnchor",
"$dynamicRef",
"$ref",
"$defs",
"$comment",
// applicator vocabulary
"allOf",
"anyOf",
"oneOf",
"not",
"if",
"then",
"else",
"dependentSchemas",
"prefixItems",
"items",
"contains",
"properties",
"patternProperties",
"additionalProperties",
"propertyNames",
// unevaluated Locations vocabulary
"unevaluatedItems",
"unevaluatedProperties",
// validation vocabulary
// validation Keywords for Any Instance Type
"type",
"enum",
"const",
// validation Keywords for Numeric Instances (number and integer)
"multipleOf",
"maximum",
"exclusiveMaximum",
"minimum",
"exclusiveMinimum",
// validation Keywords for Strings
"maxLength",
"minLength",
"pattern",
// validation Keywords for Arrays
"maxItems",
"minItems",
"uniqueItems",
"maxContains",
"minContains",
// validation Keywords for Objects
"maxProperties",
"minProperties",
"required",
"dependentRequired",
// basic Meta-Data Annotations vocabulary
"title",
"description",
"default",
"deprecated",
"readOnly",
"writeOnly",
"examples",
// semantic Content With "format" vocabulary
"format",
// contents of String-Encoded Data vocabulary
"contentEncoding",
"contentMediaType",
"contentSchema",
]
}
export const makeGetExtensionKeywords = (fnAccessor) => {
const getExtensionKeywords = (schema) => {
const fn = fnAccessor()
const keywords = fn.getSchemaKeywords()
return isPlainObject(schema)
? difference(Object.keys(schema), keywords)
: []
}
return getExtensionKeywords
}
export const hasSchemaType = (schema, type) => {
const isSchemaImmutable = Map.isMap(schema)
if (!isSchemaImmutable && !isPlainObject(schema)) {
return false
}
const hasType = (schemaType) =>
type === schemaType || (Array.isArray(type) && type.includes(schemaType))
const schemaType = isSchemaImmutable ? schema.get("type") : schema.type
if (List.isList(schemaType) || Array.isArray(schemaType)) {
return schemaType.some((t) => hasType(t))
}
return hasType(schemaType)
}