@amritk/helpers 0.10.1 → 0.10.2
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/escape-regex-pattern.d.ts +15 -5
- package/dist/escape-regex-pattern.js +48 -10
- package/dist/generate-index-barrel.js +3 -2
- package/dist/generate-type-definition.js +44 -48
- package/dist/multiple-of-check.d.ts +4 -0
- package/dist/multiple-of-check.js +30 -0
- package/dist/parse-documentation.js +6 -2
- package/dist/ref-to-name.js +17 -2
- package/dist/resolve-dynamic-refs.js +24 -0
- package/dist/safe-accessor.d.ts +3 -3
- package/dist/safe-accessor.js +10 -6
- package/dist/validate-record.js +11 -1
- package/dist/walk-ref-graph.js +4 -2
- package/package.json +4 -2
- package/src/build-dynamic-ref-map.ts +42 -0
- package/src/derive-root-type-name.ts +42 -0
- package/src/escape-regex-pattern.ts +59 -0
- package/src/extract-dynamic-anchor-defs.ts +33 -0
- package/src/extract-refs.ts +73 -0
- package/src/generate-index-barrel.ts +63 -0
- package/src/generate-type-definition.ts +599 -0
- package/src/has-ref.ts +10 -0
- package/src/is-object.ts +15 -0
- package/src/mjst-extension.ts +81 -0
- package/src/multiple-of-check.ts +32 -0
- package/src/parse-documentation.ts +177 -0
- package/src/ref-to-filename.ts +116 -0
- package/src/ref-to-name.ts +54 -0
- package/src/resolve-dynamic-refs.ts +74 -0
- package/src/resolve-ref.ts +82 -0
- package/src/safe-accessor.ts +53 -0
- package/src/schema-guards.ts +195 -0
- package/src/unknown-key-check.ts +68 -0
- package/src/upgrade-draft07-schema.ts +179 -0
- package/src/validate-array.ts +15 -0
- package/src/validate-record.ts +28 -0
- package/src/walk-ref-graph.ts +186 -0
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
2
|
+
|
|
3
|
+
import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive } from './mjst-extension'
|
|
4
|
+
import { refToName } from './ref-to-name'
|
|
5
|
+
import { safeKey } from './safe-accessor'
|
|
6
|
+
import { isObjectSchema, isSchemaObject } from './schema-guards'
|
|
7
|
+
|
|
8
|
+
type ConditionalObjectResult = {
|
|
9
|
+
schema: JSONSchema.Object
|
|
10
|
+
thenRef: string | null
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Options controlling generated type output. */
|
|
14
|
+
export type TypeOptions = {
|
|
15
|
+
/** When true, every property, array, and record in the generated types is emitted as readonly. */
|
|
16
|
+
readonly readonly?: boolean
|
|
17
|
+
/**
|
|
18
|
+
* Suffix appended to every generated type name derived from a `$ref`.
|
|
19
|
+
* Defaults to `''` (no suffix). Set to e.g. `'Object'` to emit `ContactObject`.
|
|
20
|
+
*/
|
|
21
|
+
readonly typeSuffix?: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const getConditionalObjectSchema = (schema: JSONSchema): ConditionalObjectResult | null => {
|
|
25
|
+
if (!isSchemaObject(schema)) {
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (!('if' in schema) || !('then' in schema)) {
|
|
30
|
+
return null
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const ifSchema = schema.if
|
|
34
|
+
const thenSchema = schema.then
|
|
35
|
+
|
|
36
|
+
if (!isSchemaObject(ifSchema) || !isSchemaObject(thenSchema)) {
|
|
37
|
+
return null
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const ifProperties = ifSchema.properties
|
|
41
|
+
const thenProperties = thenSchema.properties
|
|
42
|
+
const hasIfProperties = ifProperties && typeof ifProperties === 'object'
|
|
43
|
+
const hasThenProperties = thenProperties && typeof thenProperties === 'object'
|
|
44
|
+
|
|
45
|
+
if (!hasIfProperties && !hasThenProperties) {
|
|
46
|
+
return null
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const properties = {
|
|
50
|
+
...(hasIfProperties ? ifProperties : {}),
|
|
51
|
+
...(hasThenProperties ? thenProperties : {}),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const required = new Set<string>()
|
|
55
|
+
|
|
56
|
+
if (Array.isArray(ifSchema.required)) {
|
|
57
|
+
for (const key of ifSchema.required) {
|
|
58
|
+
required.add(key)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (hasIfProperties) {
|
|
63
|
+
for (const key in ifProperties) {
|
|
64
|
+
required.add(key)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (Array.isArray(thenSchema.required)) {
|
|
69
|
+
for (const key of thenSchema.required) {
|
|
70
|
+
required.add(key)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (hasThenProperties) {
|
|
75
|
+
for (const key in thenProperties) {
|
|
76
|
+
required.add(key)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const thenRef = typeof thenSchema.$ref === 'string' ? thenSchema.$ref : null
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
schema: {
|
|
84
|
+
type: 'object',
|
|
85
|
+
properties,
|
|
86
|
+
...(required.size > 0 ? { required: Array.from(required) } : {}),
|
|
87
|
+
},
|
|
88
|
+
thenRef,
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const isObjectLikeSchema = (schema: JSONSchema): schema is JSONSchema.Object => {
|
|
93
|
+
if (!isSchemaObject(schema)) {
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (isObjectSchema(schema)) {
|
|
98
|
+
return true
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return 'patternProperties' in schema || 'additionalProperties' in schema || ('if' in schema && 'then' in schema)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const getBooleanSubSchemaType = (schema: boolean): string => {
|
|
105
|
+
return schema ? 'unknown' : 'never'
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Renders a possibly multi-line description as JSDoc body lines, prefixing each
|
|
110
|
+
* line with `${indent}* `. Blank lines become a bare `${indent}*` so we never
|
|
111
|
+
* emit trailing whitespace. Without this, embedded newlines would leave
|
|
112
|
+
* continuation lines unprefixed and break the comment block.
|
|
113
|
+
*/
|
|
114
|
+
const renderJsDocBody = (description: string, indent: string): string =>
|
|
115
|
+
description
|
|
116
|
+
.split('\n')
|
|
117
|
+
.map((line) => (line.length > 0 ? `${indent}* ${line}\n` : `${indent}*\n`))
|
|
118
|
+
.join('')
|
|
119
|
+
|
|
120
|
+
const buildJsDocBlock = (title: string, description: string, commentUrl?: string): string => {
|
|
121
|
+
let block = `/**\n`
|
|
122
|
+
block += `* ${title}\n`
|
|
123
|
+
block += `*\n`
|
|
124
|
+
block += renderJsDocBody(description, '')
|
|
125
|
+
if (commentUrl?.startsWith('http')) {
|
|
126
|
+
block += `* \n`
|
|
127
|
+
block += `* @see {@link ${commentUrl}}\n`
|
|
128
|
+
}
|
|
129
|
+
block += `*/\n`
|
|
130
|
+
return block
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Builds the inline JSDoc comment that precedes a generated property. A
|
|
135
|
+
* single-line description stays compact (` /** text *\/`); a multi-line
|
|
136
|
+
* description expands into an asterisk-prefixed block so every line is
|
|
137
|
+
* commented. The returned string always ends with a newline, ready for the
|
|
138
|
+
* property declaration to follow.
|
|
139
|
+
*/
|
|
140
|
+
const buildInlinePropertyComment = (description: string): string => {
|
|
141
|
+
if (!description.includes('\n')) {
|
|
142
|
+
return ` /** ${description} */\n`
|
|
143
|
+
}
|
|
144
|
+
return ` /**\n${renderJsDocBody(description, ' ')} */\n`
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Converts a JSON Schema type to its TypeScript equivalent, applying any
|
|
149
|
+
* `x-mjst` brand. Branding is type-level only, so we compute the underlying
|
|
150
|
+
* type and intersect it with a unique brand marker. This is the recursion entry
|
|
151
|
+
* point, so branded nested fields are wrapped too.
|
|
152
|
+
*/
|
|
153
|
+
const getTypeScriptType = (schema: JSONSchema, options: TypeOptions = {}): string => {
|
|
154
|
+
const base = getUnbrandedType(schema, options)
|
|
155
|
+
const brand = getMjstBrand(schema)
|
|
156
|
+
return brand ? `(${base} & { readonly __brand: '${brand}' })` : base
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Wraps a `Record<...>` in `Readonly<...>` when readonly output is requested. */
|
|
160
|
+
const recordType = (keyType: string, valueType: string, options: TypeOptions): string =>
|
|
161
|
+
options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Builds the `Record<…>` type for a schema's `patternProperties`. Every pattern's
|
|
165
|
+
* value type is unioned (deduplicated) rather than only the first being used, so
|
|
166
|
+
* `{ '^a': string-schema, '^b': number-schema }` becomes `Record<string, string |
|
|
167
|
+
* number>` instead of silently dropping the second pattern. The template-literal
|
|
168
|
+
* `` `x-${string}` `` key is kept only when the sole pattern is the `^x-` vendor
|
|
169
|
+
* convention. Returns `undefined` when there are no usable patterns.
|
|
170
|
+
*/
|
|
171
|
+
const patternPropertiesRecordType = (
|
|
172
|
+
patternProperties: Record<string, JSONSchema | boolean>,
|
|
173
|
+
options: TypeOptions,
|
|
174
|
+
): string | undefined => {
|
|
175
|
+
const entries = Object.entries(patternProperties)
|
|
176
|
+
if (entries.length === 0) return undefined
|
|
177
|
+
|
|
178
|
+
const seen = new Set<string>()
|
|
179
|
+
const valueTypes: string[] = []
|
|
180
|
+
for (const [, value] of entries) {
|
|
181
|
+
const valueType = typeof value === 'boolean' ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options)
|
|
182
|
+
if (!seen.has(valueType)) {
|
|
183
|
+
seen.add(valueType)
|
|
184
|
+
valueTypes.push(valueType)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (valueTypes.length === 0) return undefined
|
|
188
|
+
|
|
189
|
+
const valueType = valueTypes.join(' | ')
|
|
190
|
+
// The `^x-` vendor-extension convention maps to a template-literal key, but only
|
|
191
|
+
// when it is the single pattern (a union of key patterns can't be expressed).
|
|
192
|
+
const keyType = entries.length === 1 && entries[0]?.[0] === '^x-' ? '`x-${string}`' : 'string'
|
|
193
|
+
return recordType(keyType, valueType, options)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Converts a JSON Schema type to its TypeScript equivalent, ignoring any brand.
|
|
198
|
+
* Recursively handles nested objects and arrays.
|
|
199
|
+
*/
|
|
200
|
+
const getUnbrandedType = (schema: JSONSchema, options: TypeOptions = {}): string => {
|
|
201
|
+
// Boolean schema: `true` means any value is valid (unknown), `false` means no value is valid (never)
|
|
202
|
+
if (typeof schema === 'boolean') {
|
|
203
|
+
return getBooleanSubSchemaType(schema)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Check if schema is an object (not a boolean schema)
|
|
207
|
+
if (typeof schema !== 'object' || schema === null) {
|
|
208
|
+
return 'unknown'
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// An x-mjst instanceOf hint means the value is a runtime class (e.g. Date)
|
|
212
|
+
// that JSON Schema cannot describe — emit the class name as the type directly.
|
|
213
|
+
const instanceOf = getMjstInstanceOf(schema)
|
|
214
|
+
if (instanceOf) {
|
|
215
|
+
return instanceOf
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// An x-mjst primitive hint (e.g. bigint) names a non-JSON primitive — emit it
|
|
219
|
+
// directly as the TypeScript type.
|
|
220
|
+
const primitive = getMjstPrimitive(schema)
|
|
221
|
+
if (primitive) {
|
|
222
|
+
return primitive
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Handle $ref
|
|
226
|
+
if (schema.$ref) {
|
|
227
|
+
// External refs (e.g. http://json-schema.org/...) cannot be resolved locally — treat as unknown
|
|
228
|
+
if (!schema.$ref.startsWith('#')) {
|
|
229
|
+
return 'unknown'
|
|
230
|
+
}
|
|
231
|
+
return refToName(schema.$ref, options.typeSuffix)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Handle $dynamicRef (used for recursive schemas)
|
|
235
|
+
if (schema.$dynamicRef) {
|
|
236
|
+
// For #meta, this refers to the Schema type itself (JSON Schema 2020-12 $dynamicAnchor pattern)
|
|
237
|
+
if (schema.$dynamicRef === '#meta') {
|
|
238
|
+
return `Schema${options.typeSuffix ?? ''}`
|
|
239
|
+
}
|
|
240
|
+
return refToName(schema.$dynamicRef, options.typeSuffix)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Handle const - literal type
|
|
244
|
+
if (schema.const !== undefined) {
|
|
245
|
+
return JSON.stringify(schema.const)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Handle enum - union of literal types
|
|
249
|
+
if (schema.enum && schema.enum.length > 0) {
|
|
250
|
+
if (schema.enum.length === 1) {
|
|
251
|
+
return JSON.stringify(schema.enum[0])
|
|
252
|
+
}
|
|
253
|
+
let enumUnion = JSON.stringify(schema.enum[0])
|
|
254
|
+
for (let i = 1; i < schema.enum.length; i++) {
|
|
255
|
+
enumUnion += ' | ' + JSON.stringify(schema.enum[i])
|
|
256
|
+
}
|
|
257
|
+
return enumUnion
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Handle union types (oneOf, anyOf) - check this before returning unknown
|
|
261
|
+
if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
262
|
+
// schema.oneOf[0] is safe: we guard with .length > 0 above
|
|
263
|
+
let oneOfUnion = getTypeScriptType(schema.oneOf[0]!, options)
|
|
264
|
+
for (let i = 1; i < schema.oneOf.length; i++) {
|
|
265
|
+
oneOfUnion += ' | ' + getTypeScriptType(schema.oneOf[i]!, options)
|
|
266
|
+
}
|
|
267
|
+
return oneOfUnion
|
|
268
|
+
}
|
|
269
|
+
if (schema.anyOf && Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
270
|
+
// schema.anyOf[0] is safe: we guard with .length > 0 above
|
|
271
|
+
let anyOfUnion = getTypeScriptType(schema.anyOf[0]!, options)
|
|
272
|
+
for (let i = 1; i < schema.anyOf.length; i++) {
|
|
273
|
+
anyOfUnion += ' | ' + getTypeScriptType(schema.anyOf[i]!, options)
|
|
274
|
+
}
|
|
275
|
+
return anyOfUnion
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Handle allOf (intersection types)
|
|
279
|
+
if (schema.allOf && Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
280
|
+
// schema.allOf[0] is safe: we guard with .length > 0 above
|
|
281
|
+
let intersectionTypes = getTypeScriptType(schema.allOf[0]!, options)
|
|
282
|
+
for (let i = 1; i < schema.allOf.length; i++) {
|
|
283
|
+
intersectionTypes += ' & ' + getTypeScriptType(schema.allOf[i]!, options)
|
|
284
|
+
}
|
|
285
|
+
return intersectionTypes
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Handle object-like conditional schemas that use if/then without declaring type
|
|
289
|
+
const conditionalResult = getConditionalObjectSchema(schema)
|
|
290
|
+
if (conditionalResult) {
|
|
291
|
+
const baseType = getTypeScriptType(conditionalResult.schema, options)
|
|
292
|
+
if (conditionalResult.thenRef) {
|
|
293
|
+
return `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}`
|
|
294
|
+
}
|
|
295
|
+
return baseType
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// No type so we return unknown
|
|
299
|
+
if (!schema.type) {
|
|
300
|
+
if (schema.additionalProperties !== undefined) {
|
|
301
|
+
if (typeof schema.additionalProperties === 'boolean') {
|
|
302
|
+
return recordType('string', getBooleanSubSchemaType(schema.additionalProperties), options)
|
|
303
|
+
}
|
|
304
|
+
return recordType('string', getTypeScriptType(schema.additionalProperties, options), options)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (schema.patternProperties && typeof schema.patternProperties === 'object') {
|
|
308
|
+
const record = patternPropertiesRecordType(schema.patternProperties, options)
|
|
309
|
+
if (record !== undefined) return record
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
if (schema.default !== undefined) {
|
|
313
|
+
if (typeof schema.default === 'string') {
|
|
314
|
+
return 'string'
|
|
315
|
+
}
|
|
316
|
+
if (typeof schema.default === 'number') {
|
|
317
|
+
return 'number'
|
|
318
|
+
}
|
|
319
|
+
if (typeof schema.default === 'boolean') {
|
|
320
|
+
return 'boolean'
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return 'unknown'
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Handle type as an array (union of types)
|
|
328
|
+
if (Array.isArray(schema.type)) {
|
|
329
|
+
const mapType = (t: string): string => {
|
|
330
|
+
switch (t) {
|
|
331
|
+
case 'string':
|
|
332
|
+
return 'string'
|
|
333
|
+
case 'number':
|
|
334
|
+
case 'integer':
|
|
335
|
+
return 'number'
|
|
336
|
+
case 'boolean':
|
|
337
|
+
return 'boolean'
|
|
338
|
+
case 'null':
|
|
339
|
+
return 'null'
|
|
340
|
+
case 'array':
|
|
341
|
+
return 'unknown[]'
|
|
342
|
+
case 'object':
|
|
343
|
+
return 'Record<string, unknown>'
|
|
344
|
+
default:
|
|
345
|
+
return 'unknown'
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
let typeUnion = mapType(schema.type[0])
|
|
349
|
+
for (let i = 1; i < schema.type.length; i++) {
|
|
350
|
+
typeUnion += ' | ' + mapType(schema.type[i])
|
|
351
|
+
}
|
|
352
|
+
return typeUnion
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
switch (schema.type) {
|
|
356
|
+
// String
|
|
357
|
+
case 'string':
|
|
358
|
+
return 'string'
|
|
359
|
+
|
|
360
|
+
// Number
|
|
361
|
+
case 'number':
|
|
362
|
+
case 'integer':
|
|
363
|
+
return 'number'
|
|
364
|
+
|
|
365
|
+
// Boolean
|
|
366
|
+
case 'boolean':
|
|
367
|
+
return 'boolean'
|
|
368
|
+
|
|
369
|
+
// Array
|
|
370
|
+
case 'array':
|
|
371
|
+
if (schema.items) {
|
|
372
|
+
const itemType = getTypeScriptType(schema.items, options)
|
|
373
|
+
// Wrap union types in parentheses so `(A | B)[]` is not misread as `A | B[]`
|
|
374
|
+
const wrappedItemType = itemType.includes(' | ') ? `(${itemType})` : itemType
|
|
375
|
+
return options.readonly ? `readonly ${wrappedItemType}[]` : `${wrappedItemType}[]`
|
|
376
|
+
}
|
|
377
|
+
return options.readonly ? 'readonly unknown[]' : 'unknown[]'
|
|
378
|
+
|
|
379
|
+
// Object
|
|
380
|
+
case 'object':
|
|
381
|
+
if (schema.properties) {
|
|
382
|
+
const readonlyPrefix = options.readonly ? 'readonly ' : ''
|
|
383
|
+
// Build the required-key set once instead of an O(required) `includes`
|
|
384
|
+
// per property (O(properties × required) for a wide object).
|
|
385
|
+
const requiredSet = new Set<string>(Array.isArray(schema.required) ? schema.required : [])
|
|
386
|
+
const hasDescriptions = Object.values(schema.properties).some(
|
|
387
|
+
(p) => isSchemaObject(p) && (typeof p.description === 'string' || typeof p.$comment === 'string'),
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
if (hasDescriptions) {
|
|
391
|
+
let properties = ''
|
|
392
|
+
let first = true
|
|
393
|
+
for (const key in schema.properties) {
|
|
394
|
+
// schema.properties[key] is safe: key comes from iterating schema.properties
|
|
395
|
+
const propSchema = schema.properties[key]!
|
|
396
|
+
const isRequired = requiredSet.has(key)
|
|
397
|
+
const optional = isRequired ? '' : '?'
|
|
398
|
+
const propType = getTypeScriptType(propSchema, options)
|
|
399
|
+
const inlineDescription =
|
|
400
|
+
isSchemaObject(propSchema) && typeof propSchema.description === 'string'
|
|
401
|
+
? propSchema.description
|
|
402
|
+
: isSchemaObject(propSchema) && typeof propSchema.$comment === 'string'
|
|
403
|
+
? propSchema.$comment
|
|
404
|
+
: undefined
|
|
405
|
+
if (!first) properties += '\n'
|
|
406
|
+
first = false
|
|
407
|
+
if (inlineDescription) {
|
|
408
|
+
properties +=
|
|
409
|
+
buildInlinePropertyComment(inlineDescription) +
|
|
410
|
+
' ' +
|
|
411
|
+
readonlyPrefix +
|
|
412
|
+
safeKey(key) +
|
|
413
|
+
optional +
|
|
414
|
+
': ' +
|
|
415
|
+
propType +
|
|
416
|
+
';'
|
|
417
|
+
} else {
|
|
418
|
+
properties += ' ' + readonlyPrefix + safeKey(key) + optional + ': ' + propType + ';'
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return '{\n' + properties + '\n}'
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
let properties = ''
|
|
425
|
+
let first = true
|
|
426
|
+
for (const key in schema.properties) {
|
|
427
|
+
// schema.properties[key] is safe: key comes from iterating schema.properties
|
|
428
|
+
const propSchema = schema.properties[key]!
|
|
429
|
+
const isRequired = requiredSet.has(key)
|
|
430
|
+
const optional = isRequired ? '' : '?'
|
|
431
|
+
const propType = getTypeScriptType(propSchema, options)
|
|
432
|
+
if (!first) properties += '; '
|
|
433
|
+
properties += readonlyPrefix + safeKey(key) + optional + ': ' + propType
|
|
434
|
+
first = false
|
|
435
|
+
}
|
|
436
|
+
return '{ ' + properties + ' }'
|
|
437
|
+
}
|
|
438
|
+
// Handle additionalProperties with $ref or $dynamicRef
|
|
439
|
+
if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
|
|
440
|
+
const additionalPropType = getTypeScriptType(schema.additionalProperties, options)
|
|
441
|
+
return recordType('string', additionalPropType, options)
|
|
442
|
+
}
|
|
443
|
+
// Handle patternProperties as a Record type
|
|
444
|
+
if (schema.patternProperties && typeof schema.patternProperties === 'object') {
|
|
445
|
+
const record = patternPropertiesRecordType(schema.patternProperties, options)
|
|
446
|
+
if (record !== undefined) return record
|
|
447
|
+
}
|
|
448
|
+
return 'object'
|
|
449
|
+
|
|
450
|
+
// Default to unknown
|
|
451
|
+
default:
|
|
452
|
+
return 'unknown'
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Generates a TypeScript type definition from a JSON Schema.
|
|
458
|
+
* Handles required vs optional properties based on the schema's required array.
|
|
459
|
+
* Uses $comment as inline JSDoc description when present.
|
|
460
|
+
*/
|
|
461
|
+
export const generateTypeDefinition = (schema: JSONSchema, typeName: string, options: TypeOptions = {}): string => {
|
|
462
|
+
const readonlyPrefix = options.readonly ? 'readonly ' : ''
|
|
463
|
+
|
|
464
|
+
// Handle non-object schemas first
|
|
465
|
+
if (!isObjectLikeSchema(schema)) {
|
|
466
|
+
const tsType = getTypeScriptType(schema, options)
|
|
467
|
+
let result = ''
|
|
468
|
+
|
|
469
|
+
const topLevelComment =
|
|
470
|
+
(isSchemaObject(schema) && typeof schema.description === 'string' && schema.description) ||
|
|
471
|
+
(isSchemaObject(schema) && typeof schema.$comment === 'string' && schema.$comment) ||
|
|
472
|
+
undefined
|
|
473
|
+
if (topLevelComment) {
|
|
474
|
+
result += buildJsDocBlock(typeName, topLevelComment)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
result += `export type ${typeName} = ${tsType};`
|
|
478
|
+
return result
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
if (isObjectLikeSchema(schema)) {
|
|
482
|
+
const conditionalResult = getConditionalObjectSchema(schema)
|
|
483
|
+
const normalizedSchema = conditionalResult?.schema ?? schema
|
|
484
|
+
const conditionalThenRef = conditionalResult?.thenRef ?? null
|
|
485
|
+
let jsDocTitle: string | undefined
|
|
486
|
+
let jsDocDescription: string | undefined
|
|
487
|
+
|
|
488
|
+
const topLevelComment =
|
|
489
|
+
(isSchemaObject(schema) && typeof schema.description === 'string' && schema.description) ||
|
|
490
|
+
(isSchemaObject(schema) && typeof schema.$comment === 'string' && schema.$comment) ||
|
|
491
|
+
undefined
|
|
492
|
+
if (topLevelComment) {
|
|
493
|
+
jsDocTitle = typeName
|
|
494
|
+
jsDocDescription = topLevelComment
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const hasProperties = normalizedSchema.properties && Object.keys(normalizedSchema.properties).length > 0
|
|
498
|
+
const hasAdditionalProperties =
|
|
499
|
+
normalizedSchema.additionalProperties && typeof normalizedSchema.additionalProperties === 'object'
|
|
500
|
+
const hasPatternProperties =
|
|
501
|
+
normalizedSchema.patternProperties &&
|
|
502
|
+
typeof normalizedSchema.patternProperties === 'object' &&
|
|
503
|
+
Object.keys(normalizedSchema.patternProperties).length > 0
|
|
504
|
+
|
|
505
|
+
// Handle objects with only patternProperties (no fixed properties)
|
|
506
|
+
if (!hasProperties && hasPatternProperties && normalizedSchema.patternProperties) {
|
|
507
|
+
const record =
|
|
508
|
+
patternPropertiesRecordType(normalizedSchema.patternProperties, options) ?? 'Record<string, unknown>'
|
|
509
|
+
|
|
510
|
+
let result = ''
|
|
511
|
+
if (jsDocTitle && jsDocDescription) {
|
|
512
|
+
result += buildJsDocBlock(jsDocTitle, jsDocDescription)
|
|
513
|
+
}
|
|
514
|
+
result += `export type ${typeName} = ${record};`
|
|
515
|
+
|
|
516
|
+
return result
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// Handle objects with only additionalProperties (no fixed properties)
|
|
520
|
+
if (!hasProperties && hasAdditionalProperties && normalizedSchema.additionalProperties) {
|
|
521
|
+
const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties, options)
|
|
522
|
+
|
|
523
|
+
let result = ''
|
|
524
|
+
if (jsDocTitle && jsDocDescription) {
|
|
525
|
+
result += buildJsDocBlock(jsDocTitle, jsDocDescription)
|
|
526
|
+
}
|
|
527
|
+
result += `export type ${typeName} = {\n ${readonlyPrefix}[key: string]: ${additionalPropType};\n};`
|
|
528
|
+
|
|
529
|
+
return result
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const schemaProps = normalizedSchema.properties ?? {}
|
|
533
|
+
const requiredSet = new Set<string>(Array.isArray(normalizedSchema.required) ? normalizedSchema.required : [])
|
|
534
|
+
let properties = ''
|
|
535
|
+
let isFirstProp = true
|
|
536
|
+
for (const key in schemaProps) {
|
|
537
|
+
// schemaProps[key] is safe: key comes from iterating schemaProps
|
|
538
|
+
const propSchema = schemaProps[key]!
|
|
539
|
+
const isRequired = requiredSet.has(key)
|
|
540
|
+
const optional = isRequired ? '' : '?'
|
|
541
|
+
const propType = getTypeScriptType(propSchema, options)
|
|
542
|
+
const quotedKey = readonlyPrefix + safeKey(key)
|
|
543
|
+
|
|
544
|
+
if (!isFirstProp) properties += '\n'
|
|
545
|
+
isFirstProp = false
|
|
546
|
+
|
|
547
|
+
// Add JSDoc comment from $comment or description if available
|
|
548
|
+
const inlineDescription =
|
|
549
|
+
isSchemaObject(propSchema) && typeof propSchema.description === 'string'
|
|
550
|
+
? propSchema.description
|
|
551
|
+
: isSchemaObject(propSchema) && typeof propSchema.$comment === 'string'
|
|
552
|
+
? propSchema.$comment
|
|
553
|
+
: undefined
|
|
554
|
+
if (inlineDescription) {
|
|
555
|
+
properties +=
|
|
556
|
+
buildInlinePropertyComment(inlineDescription) + ' ' + quotedKey + optional + ': ' + propType + ';'
|
|
557
|
+
} else {
|
|
558
|
+
properties += ' ' + quotedKey + optional + ': ' + propType + ';'
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// Collect allOf $ref intersections
|
|
563
|
+
const allOfIntersections: string[] = []
|
|
564
|
+
if (isSchemaObject(schema) && Array.isArray(schema.allOf)) {
|
|
565
|
+
for (const entry of schema.allOf) {
|
|
566
|
+
if (isSchemaObject(entry) && entry.$ref) {
|
|
567
|
+
allOfIntersections.push(refToName(entry.$ref, options.typeSuffix))
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// JSON Schema 2019-09+ allows $ref as a sibling to other keywords.
|
|
573
|
+
// Treat it as an additional intersection type (e.g. for specification-extensions).
|
|
574
|
+
if (isSchemaObject(schema) && typeof schema.$ref === 'string' && schema.$ref.startsWith('#')) {
|
|
575
|
+
allOfIntersections.push(refToName(schema.$ref, options.typeSuffix))
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
let result = ''
|
|
579
|
+
if (jsDocTitle && jsDocDescription) {
|
|
580
|
+
result += buildJsDocBlock(jsDocTitle, jsDocDescription)
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
let typeBody = '{\n' + properties + '\n}'
|
|
584
|
+
|
|
585
|
+
if (conditionalThenRef) {
|
|
586
|
+
typeBody += ' & ' + refToName(conditionalThenRef, options.typeSuffix)
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
for (const intersectionType of allOfIntersections) {
|
|
590
|
+
typeBody += ' & ' + intersectionType
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
result += 'export type ' + typeName + ' = ' + typeBody + ';'
|
|
594
|
+
|
|
595
|
+
return result
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
return 'export type ' + typeName + ' = unknown;'
|
|
599
|
+
}
|
package/src/has-ref.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Type guard to check if a value is a non-null, non-array object with a string $ref property */
|
|
2
|
+
export const hasRef = (value: unknown): value is { $ref: string } & Record<string, unknown> => {
|
|
3
|
+
return (
|
|
4
|
+
typeof value === 'object' &&
|
|
5
|
+
value !== null &&
|
|
6
|
+
!Array.isArray(value) &&
|
|
7
|
+
'$ref' in value &&
|
|
8
|
+
typeof (value as { $ref: unknown }).$ref === 'string'
|
|
9
|
+
)
|
|
10
|
+
}
|
package/src/is-object.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns true if the provided value is a plain object.
|
|
3
|
+
* Optimized for JSON data validation: checks that value is truthy, typeof object,
|
|
4
|
+
* and not an array. This correctly handles all JSON value types.
|
|
5
|
+
*
|
|
6
|
+
* Examples:
|
|
7
|
+
* isObject({}) // true
|
|
8
|
+
* isObject({ a: 1 }) // true
|
|
9
|
+
* isObject([]) // false (Array)
|
|
10
|
+
* isObject(null) // false
|
|
11
|
+
* isObject(123) // false
|
|
12
|
+
* isObject('string') // false
|
|
13
|
+
*/
|
|
14
|
+
export const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
15
|
+
!!value && typeof value === 'object' && !Array.isArray(value)
|