@amritk/helpers 0.13.5 → 0.15.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.
Files changed (67) hide show
  1. package/AI.md +13 -5
  2. package/README.md +4 -1
  3. package/dist/assert-id-scopes.d.ts +20 -0
  4. package/dist/assert-id-scopes.js +45 -0
  5. package/dist/build-anchor-map.d.ts +26 -0
  6. package/dist/build-anchor-map.js +35 -0
  7. package/dist/build-dynamic-ref-map.d.ts +8 -0
  8. package/dist/build-dynamic-ref-map.js +7 -5
  9. package/dist/build-resource-registry.d.ts +88 -0
  10. package/dist/build-resource-registry.js +90 -0
  11. package/dist/escape-regex-pattern.d.ts +27 -0
  12. package/dist/escape-regex-pattern.js +21 -1
  13. package/dist/extract-refs.js +6 -4
  14. package/dist/fold-nullable.d.ts +19 -0
  15. package/dist/fold-nullable.js +42 -0
  16. package/dist/generate-index-barrel.js +13 -6
  17. package/dist/generate-type-definition.d.ts +8 -0
  18. package/dist/generate-type-definition.js +249 -185
  19. package/dist/graft-external-schemas.d.ts +83 -0
  20. package/dist/graft-external-schemas.js +70 -0
  21. package/dist/max-schema-depth.d.ts +22 -0
  22. package/dist/max-schema-depth.js +10 -0
  23. package/dist/mjst-extension.d.ts +4 -2
  24. package/dist/mjst-extension.js +11 -2
  25. package/dist/multiple-of-check.d.ts +31 -0
  26. package/dist/multiple-of-check.js +6 -10
  27. package/dist/normalize-ref-scopes.d.ts +29 -0
  28. package/dist/normalize-ref-scopes.js +53 -0
  29. package/dist/prune-external-schemas.d.ts +16 -0
  30. package/dist/prune-external-schemas.js +80 -0
  31. package/dist/ref-to-filename.d.ts +1 -0
  32. package/dist/ref-to-filename.js +19 -3
  33. package/dist/ref-to-name.js +7 -4
  34. package/dist/resolve-dynamic-refs.d.ts +10 -0
  35. package/dist/resolve-dynamic-refs.js +18 -16
  36. package/dist/resolve-ref.d.ts +4 -2
  37. package/dist/resolve-ref.js +32 -6
  38. package/dist/resolve-scoped-ref.d.ts +35 -0
  39. package/dist/resolve-scoped-ref.js +35 -0
  40. package/dist/safe-accessor.d.ts +38 -1
  41. package/dist/safe-accessor.js +15 -0
  42. package/dist/string-length-check.d.ts +8 -0
  43. package/dist/string-length-check.js +23 -0
  44. package/dist/upgrade-draft07-schema.js +9 -6
  45. package/dist/walk-ref-graph.d.ts +38 -3
  46. package/dist/walk-ref-graph.js +173 -18
  47. package/package.json +16 -3
  48. package/src/build-dynamic-ref-map.ts +0 -61
  49. package/src/derive-root-type-name.ts +0 -54
  50. package/src/escape-regex-pattern.ts +0 -87
  51. package/src/extract-dynamic-anchor-defs.ts +0 -25
  52. package/src/extract-refs.ts +0 -73
  53. package/src/generate-index-barrel.ts +0 -118
  54. package/src/generate-type-definition.ts +0 -599
  55. package/src/mjst-extension.ts +0 -81
  56. package/src/multiple-of-check.ts +0 -32
  57. package/src/parse-documentation.ts +0 -177
  58. package/src/quote-js-string.ts +0 -20
  59. package/src/ref-to-filename.ts +0 -116
  60. package/src/ref-to-name.ts +0 -54
  61. package/src/resolve-dynamic-refs.ts +0 -74
  62. package/src/resolve-ref.ts +0 -82
  63. package/src/safe-accessor.ts +0 -53
  64. package/src/schema-guards.ts +0 -234
  65. package/src/unknown-key-check.ts +0 -68
  66. package/src/upgrade-draft07-schema.ts +0 -179
  67. package/src/walk-ref-graph.ts +0 -240
@@ -1,599 +0,0 @@
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
- }
@@ -1,81 +0,0 @@
1
- import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
-
3
- import { isSchemaObject } from './schema-guards'
4
-
5
- /**
6
- * Vendor extension keyword carrying mjst-specific runtime hints that plain JSON
7
- * Schema cannot express on its own. Adapters (TypeBox, Zod, ...) emit it when a
8
- * source construct has no native JSON Schema equivalent, and the generators read
9
- * it to produce the right TypeScript type and runtime checks.
10
- */
11
- export const MJST_EXTENSION_KEY = 'x-mjst'
12
-
13
- /**
14
- * The shape of the `x-mjst` extension object.
15
- *
16
- * - `instanceOf` names a JavaScript class the value must be an instance of at
17
- * runtime (e.g. `'Date'`). It round-trips constructs like TypeBox's
18
- * `Type.Date()` that JSON Schema's core vocabulary has no keyword for.
19
- * - `primitive` names a non-JSON primitive type (e.g. `'bigint'`) that has no
20
- * JSON Schema representation. Unlike `instanceOf`, the value is checked with
21
- * `typeof`, not `instanceof`.
22
- * - `brand` carries a nominal-typing brand name. It is purely type-level: the
23
- * runtime value still validates as its underlying JSON Schema type, but the
24
- * generated TypeScript type is intersected with a unique brand so values are
25
- * not interchangeable with the unbranded base type.
26
- */
27
- export type MjstExtension = {
28
- readonly instanceOf?: string
29
- readonly primitive?: string
30
- readonly brand?: string
31
- }
32
-
33
- // Only identifier-safe class names are honoured, so a malicious or malformed
34
- // schema cannot inject arbitrary code into the generated output.
35
- const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
36
-
37
- // The non-JSON primitives we know how to generate type/runtime handling for.
38
- // Anything outside this set is ignored so unknown hints degrade gracefully.
39
- const SUPPORTED_PRIMITIVES = new Set(['bigint'])
40
-
41
- // Brand names are embedded inside a single-quoted string literal in generated
42
- // output, so we only allow characters that cannot break out of the literal.
43
- const SAFE_BRAND = /^[\w$ -]+$/
44
-
45
- const readExtensionString = (schema: JSONSchema, field: keyof MjstExtension): string | undefined => {
46
- if (!isSchemaObject(schema)) return undefined
47
-
48
- const extension = (schema as Record<string, unknown>)[MJST_EXTENSION_KEY]
49
- if (typeof extension !== 'object' || extension === null) return undefined
50
-
51
- const value = (extension as Record<string, unknown>)[field]
52
- return typeof value === 'string' ? value : undefined
53
- }
54
-
55
- /**
56
- * Reads the `instanceOf` class name from a schema's `x-mjst` extension, when it
57
- * is present and a safe identifier. Returns undefined otherwise so callers fall
58
- * back to ordinary type handling.
59
- */
60
- export const getMjstInstanceOf = (schema: JSONSchema): string | undefined => {
61
- const instanceOf = readExtensionString(schema, 'instanceOf')
62
- return instanceOf !== undefined && IDENTIFIER.test(instanceOf) ? instanceOf : undefined
63
- }
64
-
65
- /**
66
- * Reads the `primitive` type name from a schema's `x-mjst` extension, when it is
67
- * one we support (e.g. `'bigint'`). Returns undefined otherwise.
68
- */
69
- export const getMjstPrimitive = (schema: JSONSchema): string | undefined => {
70
- const primitive = readExtensionString(schema, 'primitive')
71
- return primitive !== undefined && SUPPORTED_PRIMITIVES.has(primitive) ? primitive : undefined
72
- }
73
-
74
- /**
75
- * Reads the nominal `brand` name from a schema's `x-mjst` extension, when it is
76
- * present and safe to embed in generated output. Returns undefined otherwise.
77
- */
78
- export const getMjstBrand = (schema: JSONSchema): string | undefined => {
79
- const brand = readExtensionString(schema, 'brand')
80
- return brand !== undefined && SAFE_BRAND.test(brand) ? brand : undefined
81
- }