@amritk/helpers 0.13.5 → 0.14.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.
@@ -2,9 +2,16 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
2
 
3
3
  import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive } from './mjst-extension'
4
4
  import { refToName } from './ref-to-name'
5
+ import { resolveRef } from './resolve-ref'
5
6
  import { safeKey } from './safe-accessor'
6
7
  import { isObjectSchema, isSchemaObject } from './schema-guards'
7
8
 
9
+ /**
10
+ * Any schema that is not a boolean shorthand. Broader than `JSONSchema.Object`,
11
+ * which narrows `type` to `'object'` and so hides array keywords like `items`.
12
+ */
13
+ type SchemaNode = Exclude<JSONSchema, boolean>
14
+
8
15
  type ConditionalObjectResult = {
9
16
  schema: JSONSchema.Object
10
17
  thenRef: string | null
@@ -19,6 +26,30 @@ export type TypeOptions = {
19
26
  * Defaults to `''` (no suffix). Set to e.g. `'Object'` to emit `ContactObject`.
20
27
  */
21
28
  readonly typeSuffix?: string
29
+ /**
30
+ * The root document, used to decide whether a URI `$ref` names a type the
31
+ * generator also emits a file for. Without it such refs stay `unknown` — the
32
+ * conservative reading, since an unresolvable ref has no generated file to
33
+ * name. Pass it whenever the caller also emits imports for those refs, so the
34
+ * type and the import agree.
35
+ */
36
+ readonly rootSchema?: Record<string, unknown>
37
+ }
38
+
39
+ /**
40
+ * The type name for a `$ref`, or `unknown` when no file is generated for it.
41
+ *
42
+ * Internal refs always name a generated type. A URI ref does too — but only
43
+ * when it resolves inside the root document, which is precisely the rule
44
+ * `collectImports` uses to decide whether to import it. Keeping the two in step
45
+ * is what stops a file from importing `Channel` while typing the property that
46
+ * uses it as `unknown`.
47
+ */
48
+ const refTypeName = (ref: string, options: TypeOptions): string => {
49
+ if (ref.startsWith('#')) return refToName(ref, options.typeSuffix)
50
+ if (ref.includes('#/properties/')) return 'unknown'
51
+ if (options.rootSchema && resolveRef(ref, options.rootSchema)) return refToName(ref, options.typeSuffix)
52
+ return 'unknown'
22
53
  }
23
54
 
24
55
  const getConditionalObjectSchema = (schema: JSONSchema): ConditionalObjectResult | null => {
@@ -37,8 +68,10 @@ const getConditionalObjectSchema = (schema: JSONSchema): ConditionalObjectResult
37
68
  return null
38
69
  }
39
70
 
71
+ const ownProperties = schema.properties
40
72
  const ifProperties = ifSchema.properties
41
73
  const thenProperties = thenSchema.properties
74
+ const hasOwnProperties = ownProperties && typeof ownProperties === 'object'
42
75
  const hasIfProperties = ifProperties && typeof ifProperties === 'object'
43
76
  const hasThenProperties = thenProperties && typeof thenProperties === 'object'
44
77
 
@@ -46,13 +79,24 @@ const getConditionalObjectSchema = (schema: JSONSchema): ConditionalObjectResult
46
79
  return null
47
80
  }
48
81
 
82
+ // The conditional fragments are merged *onto* the schema's own properties —
83
+ // a schema is allowed to declare `properties` alongside `if`/`then`, and
84
+ // reading only the conditional halves silently dropped everything it declared
85
+ // unconditionally.
49
86
  const properties = {
87
+ ...(hasOwnProperties ? ownProperties : {}),
50
88
  ...(hasIfProperties ? ifProperties : {}),
51
89
  ...(hasThenProperties ? thenProperties : {}),
52
90
  }
53
91
 
54
92
  const required = new Set<string>()
55
93
 
94
+ if (Array.isArray(schema.required)) {
95
+ for (const key of schema.required) {
96
+ required.add(key)
97
+ }
98
+ }
99
+
56
100
  if (Array.isArray(ifSchema.required)) {
57
101
  for (const key of ifSchema.required) {
58
102
  required.add(key)
@@ -105,6 +149,15 @@ const getBooleanSubSchemaType = (schema: boolean): string => {
105
149
  return schema ? 'unknown' : 'never'
106
150
  }
107
151
 
152
+ /**
153
+ * Neutralizes comment terminators inside schema-authored prose. A description
154
+ * holding a star-slash pair — a glob like `**\/*.ts`, a C-style code sample —
155
+ * would close the JSDoc block early and leave the rest of the generated file
156
+ * unparseable. Escaping the slash is the conventional fix: editors and TypeDoc
157
+ * still render the original text, but the comment can no longer end there.
158
+ */
159
+ const escapeCommentText = (text: string): string => text.replace(/\*\//g, '*\\/')
160
+
108
161
  /**
109
162
  * Renders a possibly multi-line description as JSDoc body lines, prefixing each
110
163
  * line with `${indent}* `. Blank lines become a bare `${indent}*` so we never
@@ -112,7 +165,7 @@ const getBooleanSubSchemaType = (schema: boolean): string => {
112
165
  * continuation lines unprefixed and break the comment block.
113
166
  */
114
167
  const renderJsDocBody = (description: string, indent: string): string =>
115
- description
168
+ escapeCommentText(description)
116
169
  .split('\n')
117
170
  .map((line) => (line.length > 0 ? `${indent}* ${line}\n` : `${indent}*\n`))
118
171
  .join('')
@@ -139,7 +192,7 @@ const buildJsDocBlock = (title: string, description: string, commentUrl?: string
139
192
  */
140
193
  const buildInlinePropertyComment = (description: string): string => {
141
194
  if (!description.includes('\n')) {
142
- return ` /** ${description} */\n`
195
+ return ` /** ${escapeCommentText(description)} */\n`
143
196
  }
144
197
  return ` /**\n${renderJsDocBody(description, ' ')} */\n`
145
198
  }
@@ -153,7 +206,42 @@ const buildInlinePropertyComment = (description: string): string => {
153
206
  const getTypeScriptType = (schema: JSONSchema, options: TypeOptions = {}): string => {
154
207
  const base = getUnbrandedType(schema, options)
155
208
  const brand = getMjstBrand(schema)
156
- return brand ? `(${base} & { readonly __brand: '${brand}' })` : base
209
+ const branded = brand ? `(${base} & { readonly __brand: '${brand}' })` : base
210
+ // OpenAPI 3.0 spells nullability as a sibling flag instead of a `null` member
211
+ // of `type`. Without this widening the emitted type claims the value can never
212
+ // be null while the document says it can — and `generate-validators` builds an
213
+ // `input is T` predicate on top of a validator that *does* accept null, so the
214
+ // narrowing would be unsound.
215
+ return isNullableSchema(schema) ? withNull(branded) : branded
216
+ }
217
+
218
+ /** True for the OpenAPI 3.0 `nullable: true` widening (JSON Schema has no such keyword). */
219
+ const isNullableSchema = (schema: JSONSchema): boolean =>
220
+ isSchemaObject(schema) && (schema as Record<string, unknown>)['nullable'] === true
221
+
222
+ /** Parenthesizes a union so it composes safely inside `[]`, `&`, or an optional marker. */
223
+ const wrapUnion = (type: string): string => (type.includes(' | ') ? `(${type})` : type)
224
+
225
+ /** Appends `| null` unless the rendered type already admits null. */
226
+ const withNull = (type: string): string => (type.split(' | ').includes('null') ? type : `${type} | null`)
227
+
228
+ /** Joins members with ` | `, dropping duplicates while preserving order. */
229
+ const unionOf = (members: readonly string[]): string => [...new Set(members)].join(' | ')
230
+
231
+ /**
232
+ * Joins members with ` & `, dropping duplicates and any `unknown` member —
233
+ * `X & unknown` is just `X`, and composition keywords routinely contribute one
234
+ * (a `oneOf` branch that only lists `required`, say). Returns `unknown` when
235
+ * every member was dropped.
236
+ */
237
+ const intersectionOf = (members: readonly string[]): string => {
238
+ const kept = [...new Set(members)].filter((member) => member !== 'unknown')
239
+ if (kept.length === 0) return 'unknown'
240
+ // `X & object` is `X` for any object type, and a schema that declares
241
+ // `type: 'object'` next to a `oneOf` contributes exactly that bare member.
242
+ const meaningful = kept.length > 1 ? kept.filter((member) => member !== 'object') : kept
243
+ if (meaningful.length === 0) return 'object'
244
+ return meaningful.join(' & ')
157
245
  }
158
246
 
159
247
  /** Wraps a `Record<...>` in `Readonly<...>` when readonly output is requested. */
@@ -193,6 +281,253 @@ const patternPropertiesRecordType = (
193
281
  return recordType(keyType, valueType, options)
194
282
  }
195
283
 
284
+ /**
285
+ * The tuple positions a schema declares: 2020-12 `prefixItems`, or the draft-07
286
+ * array form of `items`. Returns undefined for a plain (homogeneous) array.
287
+ */
288
+ const getTuplePositions = (schema: SchemaNode): readonly JSONSchema[] | undefined => {
289
+ const record = schema as Record<string, unknown>
290
+ const prefixItems = record['prefixItems']
291
+ if (Array.isArray(prefixItems) && prefixItems.length > 0) return prefixItems as JSONSchema[]
292
+ if (Array.isArray(schema.items) && schema.items.length > 0) return schema.items as JSONSchema[]
293
+ return undefined
294
+ }
295
+
296
+ /**
297
+ * Renders a tuple type for a schema carrying `prefixItems` (or the draft-07
298
+ * array `items`). A position is only required when `minItems` reaches it — JSON
299
+ * Schema lets a tuple stop short unless told otherwise — so the rest are
300
+ * emitted optional. Extra elements past the declared positions are typed from
301
+ * the sibling `items` (`additionalItems` in the draft-07 spelling) and dropped
302
+ * entirely when that sibling is `false`.
303
+ */
304
+ const tupleTypeToTs = (schema: SchemaNode, positions: readonly JSONSchema[], options: TypeOptions): string => {
305
+ const record = schema as Record<string, unknown>
306
+ // With the draft-07 spelling `items` *is* the tuple, so the rest schema is
307
+ // `additionalItems`; with `prefixItems` it is the sibling `items`.
308
+ const rest = Array.isArray(schema.items) ? record['additionalItems'] : record['items']
309
+ const minItems = typeof schema.minItems === 'number' ? schema.minItems : 0
310
+
311
+ const parts: string[] = []
312
+ for (let i = 0; i < positions.length; i++) {
313
+ const positionType = wrapUnion(getTypeScriptType(positions[i] as JSONSchema, options))
314
+ parts.push(i < minItems ? positionType : `${positionType}?`)
315
+ }
316
+
317
+ if (rest !== false) {
318
+ const restType =
319
+ rest === undefined || rest === true ? 'unknown' : wrapUnion(getTypeScriptType(rest as JSONSchema, options))
320
+ parts.push(`...${restType}[]`)
321
+ }
322
+
323
+ const tuple = `[${parts.join(', ')}]`
324
+ return options.readonly ? `readonly ${tuple}` : tuple
325
+ }
326
+
327
+ /** Renders the TypeScript type for an `array` schema — tuple, typed list, or bare list. */
328
+ const arrayTypeToTs = (schema: SchemaNode, options: TypeOptions): string => {
329
+ const positions = getTuplePositions(schema)
330
+ if (positions) return tupleTypeToTs(schema, positions, options)
331
+
332
+ if (schema.items !== undefined && !Array.isArray(schema.items)) {
333
+ const itemType = getTypeScriptType(schema.items, options)
334
+ // Wrap union types in parentheses so `(A | B)[]` is not misread as `A | B[]`
335
+ const wrappedItemType = wrapUnion(itemType)
336
+ return options.readonly ? `readonly ${wrappedItemType}[]` : `${wrappedItemType}[]`
337
+ }
338
+ return options.readonly ? 'readonly unknown[]' : 'unknown[]'
339
+ }
340
+
341
+ /**
342
+ * The open-ended key signature a schema declares, or undefined when it declares
343
+ * none. Only a *schema-valued* `additionalProperties` counts: `true` is the JSON
344
+ * Schema default, so emitting `[key: string]: unknown` for it would widen nearly
345
+ * every generated type into uselessness, and `false` is a closed object.
346
+ */
347
+ const getIndexSignature = (schema: SchemaNode, options: TypeOptions): { key: string; value: string } | undefined => {
348
+ const additionalProperties = schema.additionalProperties
349
+ if (additionalProperties !== undefined && typeof additionalProperties !== 'boolean') {
350
+ return { key: 'string', value: getTypeScriptType(additionalProperties, options) }
351
+ }
352
+
353
+ const patternProperties = schema.patternProperties
354
+ if (patternProperties && typeof patternProperties === 'object') {
355
+ const entries = Object.entries(patternProperties)
356
+ if (entries.length === 0) return undefined
357
+ const valueTypes = entries.map(([, value]) =>
358
+ typeof value === 'boolean' ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options),
359
+ )
360
+ // The `^x-` vendor-extension convention maps to a template-literal key, but
361
+ // only when it is the single pattern (a union of key patterns can't be expressed).
362
+ const key = entries.length === 1 && entries[0]?.[0] === '^x-' ? '`x-${string}`' : 'string'
363
+ return { key, value: unionOf(valueTypes) }
364
+ }
365
+
366
+ return undefined
367
+ }
368
+
369
+ /**
370
+ * Renders the index-signature line to sit alongside declared properties.
371
+ *
372
+ * A `string` index must accept every declared property's type or TypeScript
373
+ * rejects the whole type (TS2411), so the signature is widened with them — and
374
+ * with `undefined` when any declared property is optional. A template-literal
375
+ * key (`` `x-${string}` ``) constrains a disjoint set of keys, so it needs no
376
+ * widening.
377
+ */
378
+ const buildIndexSignatureLine = (
379
+ index: { key: string; value: string },
380
+ declaredTypes: readonly string[],
381
+ hasOptionalProperty: boolean,
382
+ options: TypeOptions,
383
+ ): string => {
384
+ const readonlyPrefix = options.readonly ? 'readonly ' : ''
385
+ if (index.key !== 'string') return `${readonlyPrefix}[key: ${index.key}]: ${index.value}`
386
+ const widened = unionOf([
387
+ ...index.value.split(' | '),
388
+ ...declaredTypes,
389
+ ...(hasOptionalProperty ? ['undefined'] : []),
390
+ ])
391
+ return `${readonlyPrefix}[key: string]: ${widened}`
392
+ }
393
+
394
+ /** The description (or `$comment` fallback) to emit as JSDoc above a property. */
395
+ const propertyDescription = (propSchema: JSONSchema): string | undefined => {
396
+ if (!isSchemaObject(propSchema)) return undefined
397
+ if (typeof propSchema.description === 'string') return propSchema.description
398
+ if (typeof propSchema.$comment === 'string') return propSchema.$comment
399
+ return undefined
400
+ }
401
+
402
+ /**
403
+ * Renders an `object` schema: a property literal when it declares properties, a
404
+ * `Record`/index type when it only declares open-ended keys, else the bare
405
+ * `object`. Open-ended keys declared *alongside* properties become an index
406
+ * signature inside the literal rather than being dropped.
407
+ */
408
+ const objectTypeToTs = (schema: SchemaNode, options: TypeOptions): string => {
409
+ const index = getIndexSignature(schema, options)
410
+
411
+ if (schema.properties && Object.keys(schema.properties).length > 0) {
412
+ const readonlyPrefix = options.readonly ? 'readonly ' : ''
413
+ // Build the required-key set once instead of an O(required) `includes`
414
+ // per property (O(properties × required) for a wide object).
415
+ const requiredSet = new Set<string>(Array.isArray(schema.required) ? schema.required : [])
416
+ const hasDescriptions = Object.values(schema.properties).some((p) => propertyDescription(p) !== undefined)
417
+
418
+ const declaredTypes: string[] = []
419
+ let hasOptionalProperty = false
420
+ // Entries are emitted ready to place: multi-line layout wants each
421
+ // declaration indented and `;`-terminated (with its JSDoc block already
422
+ // carrying its own indent), the compact one wants bare declarations.
423
+ const entries: string[] = []
424
+ for (const key in schema.properties) {
425
+ // schema.properties[key] is safe: key comes from iterating schema.properties
426
+ const propSchema = schema.properties[key] as JSONSchema
427
+ const isRequired = requiredSet.has(key)
428
+ const optional = isRequired ? '' : '?'
429
+ if (!isRequired) hasOptionalProperty = true
430
+ const propType = getTypeScriptType(propSchema, options)
431
+ declaredTypes.push(propType)
432
+ const declaration = readonlyPrefix + safeKey(key) + optional + ': ' + propType
433
+ if (!hasDescriptions) {
434
+ entries.push(declaration)
435
+ continue
436
+ }
437
+ const inlineDescription = propertyDescription(propSchema)
438
+ entries.push((inlineDescription ? buildInlinePropertyComment(inlineDescription) : '') + ' ' + declaration + ';')
439
+ }
440
+
441
+ if (index) {
442
+ const line = buildIndexSignatureLine(index, declaredTypes, hasOptionalProperty, options)
443
+ entries.push(hasDescriptions ? ' ' + line + ';' : line)
444
+ }
445
+
446
+ // Descriptions force the multi-line layout — an inline `/** … */` per
447
+ // property would otherwise run the whole literal together on one line.
448
+ if (hasDescriptions) return '{\n' + entries.join('\n') + '\n}'
449
+ return '{ ' + entries.join('; ') + ' }'
450
+ }
451
+
452
+ if (index) {
453
+ return index.key === 'string' && !options.readonly
454
+ ? recordType('string', index.value, options)
455
+ : recordType(index.key, index.value, options)
456
+ }
457
+
458
+ return 'object'
459
+ }
460
+
461
+ /**
462
+ * Renders the shape a schema declares *itself* — its `type`, or the record
463
+ * keywords it carries without one. Returns undefined when the schema declares
464
+ * no shape of its own (so composition keywords alone decide the type).
465
+ */
466
+ const getLocalShapeType = (schema: SchemaNode, options: TypeOptions): string | undefined => {
467
+ // Object-like conditional schemas (`if`/`then`) describe one merged shape.
468
+ const conditionalResult = getConditionalObjectSchema(schema)
469
+ if (conditionalResult) {
470
+ const baseType = objectTypeToTs(conditionalResult.schema, options)
471
+ return conditionalResult.thenRef
472
+ ? `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}`
473
+ : baseType
474
+ }
475
+
476
+ if (!schema.type) {
477
+ const index = getIndexSignature(schema, options)
478
+ if (index) return objectTypeToTs(schema, options)
479
+
480
+ if (schema.additionalProperties !== undefined && typeof schema.additionalProperties === 'boolean') {
481
+ return recordType('string', getBooleanSubSchemaType(schema.additionalProperties), options)
482
+ }
483
+
484
+ if (schema.properties && Object.keys(schema.properties).length > 0) return objectTypeToTs(schema, options)
485
+
486
+ if (schema.default !== undefined) {
487
+ if (typeof schema.default === 'string') return 'string'
488
+ if (typeof schema.default === 'number') return 'number'
489
+ if (typeof schema.default === 'boolean') return 'boolean'
490
+ }
491
+
492
+ return undefined
493
+ }
494
+
495
+ // Array-form `type` (the multi-type / nullable idiom, e.g. `["object","null"]`)
496
+ // is a union of the per-type renderings. Each member is rendered from the SAME
497
+ // schema, so a nullable object keeps its properties and a nullable array keeps
498
+ // its item type instead of collapsing to `Record<string, unknown>` / `unknown[]`.
499
+ if (Array.isArray(schema.type)) {
500
+ return unionOf(schema.type.map((type) => singleTypeToTs(schema, type, options)))
501
+ }
502
+
503
+ return singleTypeToTs(schema, schema.type, options)
504
+ }
505
+
506
+ /** Renders one JSON Schema `type` value against the schema that declared it. */
507
+ const singleTypeToTs = (schema: SchemaNode, type: JSONSchema.TypeValue, options: TypeOptions): string => {
508
+ switch (type) {
509
+ case 'string':
510
+ return 'string'
511
+ case 'number':
512
+ case 'integer':
513
+ return 'number'
514
+ case 'boolean':
515
+ return 'boolean'
516
+ case 'null':
517
+ return 'null'
518
+ case 'array':
519
+ return arrayTypeToTs(schema, options)
520
+ case 'object': {
521
+ const rendered = objectTypeToTs(schema, options)
522
+ // A shapeless object inside a union reads better as an indexable record
523
+ // than as the bare `object`, which cannot be indexed at all.
524
+ return rendered === 'object' && Array.isArray(schema.type) ? recordType('string', 'unknown', options) : rendered
525
+ }
526
+ default:
527
+ return 'unknown'
528
+ }
529
+ }
530
+
196
531
  /**
197
532
  * Converts a JSON Schema type to its TypeScript equivalent, ignoring any brand.
198
533
  * Recursively handles nested objects and arrays.
@@ -224,11 +559,7 @@ const getUnbrandedType = (schema: JSONSchema, options: TypeOptions = {}): string
224
559
 
225
560
  // Handle $ref
226
561
  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)
562
+ return refTypeName(schema.$ref, options)
232
563
  }
233
564
 
234
565
  // Handle $dynamicRef (used for recursive schemas)
@@ -247,210 +578,68 @@ const getUnbrandedType = (schema: JSONSchema, options: TypeOptions = {}): string
247
578
 
248
579
  // Handle enum - union of literal types
249
580
  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
581
+ return unionOf(schema.enum.map((value) => JSON.stringify(value)))
258
582
  }
259
583
 
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
- }
584
+ // A schema may declare a shape of its own *and* compose others. Returning
585
+ // either alone silently drops half of what the document says, so the local
586
+ // shape, the `oneOf`/`anyOf` union, and every `allOf` member are combined into
587
+ // one intersection.
588
+ const members: string[] = []
589
+ const localType = getLocalShapeType(schema, options)
590
+ if (localType !== undefined) members.push(localType)
277
591
 
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
592
+ if (Array.isArray(schema.allOf)) {
593
+ for (const entry of schema.allOf) members.push(wrapUnion(getTypeScriptType(entry, options)))
286
594
  }
287
595
 
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
596
+ const branches = Array.isArray(schema.oneOf) && schema.oneOf.length > 0 ? schema.oneOf : undefined
597
+ const anyBranches = Array.isArray(schema.anyOf) && schema.anyOf.length > 0 ? schema.anyOf : undefined
598
+ const unionBranches = branches ?? anyBranches
599
+ if (unionBranches) {
600
+ const union = unionOf(unionBranches.map((branch) => getTypeScriptType(branch, options)))
601
+ // A lone union is the whole type; alongside other members it is one factor
602
+ // of an intersection and needs its own parentheses.
603
+ if (members.length === 0 && !Array.isArray(schema.allOf)) return union
604
+ members.push(wrapUnion(union))
296
605
  }
297
606
 
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
- }
607
+ if (members.length === 0) return 'unknown'
608
+ return intersectionOf(members)
609
+ }
311
610
 
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
- }
611
+ /**
612
+ * The types a schema composes alongside its own property block: every `allOf`
613
+ * member, a sibling `$ref` (2019-09+ allows one next to other keywords), and a
614
+ * sibling `oneOf`/`anyOf` union. Each is intersected onto the body — an `allOf`
615
+ * member written inline rather than as a `$ref` used to be dropped outright,
616
+ * taking its properties and its `required` list with it.
617
+ */
618
+ const getCompositionMembers = (schema: JSONSchema, options: TypeOptions): string[] => {
619
+ if (!isSchemaObject(schema)) return []
620
+ const members: string[] = []
323
621
 
324
- return 'unknown'
622
+ if (Array.isArray(schema.allOf)) {
623
+ for (const entry of schema.allOf) members.push(wrapUnion(getTypeScriptType(entry, options)))
325
624
  }
326
625
 
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
626
+ if (typeof schema.$ref === 'string') {
627
+ members.push(refTypeName(schema.$ref, options))
353
628
  }
354
629
 
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'
630
+ const unionBranches =
631
+ Array.isArray(schema.oneOf) && schema.oneOf.length > 0
632
+ ? schema.oneOf
633
+ : Array.isArray(schema.anyOf) && schema.anyOf.length > 0
634
+ ? schema.anyOf
635
+ : undefined
636
+ if (unionBranches) {
637
+ members.push(wrapUnion(unionOf(unionBranches.map((branch) => getTypeScriptType(branch, options)))))
453
638
  }
639
+
640
+ // `X & unknown` is `X`: a branch that only lists `required`, or a ref with no
641
+ // generated file, contributes nothing and would just add noise.
642
+ return [...new Set(members)].filter((member) => member !== 'unknown')
454
643
  }
455
644
 
456
645
  /**
@@ -461,8 +650,10 @@ const getUnbrandedType = (schema: JSONSchema, options: TypeOptions = {}): string
461
650
  export const generateTypeDefinition = (schema: JSONSchema, typeName: string, options: TypeOptions = {}): string => {
462
651
  const readonlyPrefix = options.readonly ? 'readonly ' : ''
463
652
 
464
- // Handle non-object schemas first
465
- if (!isObjectLikeSchema(schema)) {
653
+ // Handle non-object schemas first. An array-form `type` goes here too: it is a
654
+ // union (`{ … } | null`), not a single object body, so it cannot be emitted as
655
+ // a property block even when one of its members is an object.
656
+ if (!isObjectLikeSchema(schema) || (isSchemaObject(schema) && Array.isArray(schema.type))) {
466
657
  const tsType = getTypeScriptType(schema, options)
467
658
  let result = ''
468
659
 
@@ -531,48 +722,40 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string, opt
531
722
 
532
723
  const schemaProps = normalizedSchema.properties ?? {}
533
724
  const requiredSet = new Set<string>(Array.isArray(normalizedSchema.required) ? normalizedSchema.required : [])
725
+ const declaredTypes: string[] = []
726
+ let hasOptionalProperty = false
534
727
  let properties = ''
535
728
  let isFirstProp = true
729
+ const appendLine = (line: string): void => {
730
+ if (!isFirstProp) properties += '\n'
731
+ isFirstProp = false
732
+ properties += line
733
+ }
536
734
  for (const key in schemaProps) {
537
735
  // schemaProps[key] is safe: key comes from iterating schemaProps
538
736
  const propSchema = schemaProps[key]!
539
737
  const isRequired = requiredSet.has(key)
540
738
  const optional = isRequired ? '' : '?'
739
+ if (!isRequired) hasOptionalProperty = true
541
740
  const propType = getTypeScriptType(propSchema, options)
741
+ declaredTypes.push(propType)
542
742
  const quotedKey = readonlyPrefix + safeKey(key)
543
743
 
544
- if (!isFirstProp) properties += '\n'
545
- isFirstProp = false
546
-
547
744
  // 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
- }
745
+ const inlineDescription = propertyDescription(propSchema)
746
+ appendLine(
747
+ inlineDescription
748
+ ? buildInlinePropertyComment(inlineDescription) + ' ' + quotedKey + optional + ': ' + propType + ';'
749
+ : ' ' + quotedKey + optional + ': ' + propType + ';',
750
+ )
560
751
  }
561
752
 
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))
753
+ // Open-ended keys declared alongside fixed properties become an index
754
+ // signature inside the same body — dropping them used to erase everything a
755
+ // schema said about the keys it does not name.
756
+ const index = getIndexSignature(normalizedSchema, options)
757
+ if (index) {
758
+ appendLine(' ' + buildIndexSignatureLine(index, declaredTypes, hasOptionalProperty, options) + ';')
576
759
  }
577
760
 
578
761
  let result = ''
@@ -580,16 +763,18 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string, opt
580
763
  result += buildJsDocBlock(jsDocTitle, jsDocDescription)
581
764
  }
582
765
 
583
- let typeBody = '{\n' + properties + '\n}'
766
+ let typeBody = properties === '' ? '{}' : '{\n' + properties + '\n}'
584
767
 
585
768
  if (conditionalThenRef) {
586
769
  typeBody += ' & ' + refToName(conditionalThenRef, options.typeSuffix)
587
770
  }
588
771
 
589
- for (const intersectionType of allOfIntersections) {
772
+ for (const intersectionType of getCompositionMembers(schema, options)) {
590
773
  typeBody += ' & ' + intersectionType
591
774
  }
592
775
 
776
+ if (isNullableSchema(schema)) typeBody = withNull(typeBody)
777
+
593
778
  result += 'export type ' + typeName + ' = ' + typeBody + ';'
594
779
 
595
780
  return result