(schema: JSONSchema7)
| 309 | * emit nullable/optional types without per-language heuristics. |
| 310 | */ |
| 311 | export function normalizeNullableRequiredRefs(schema: JSONSchema7): JSONSchema7 { |
| 312 | if (typeof schema !== "object" || schema === null) return schema; |
| 313 | |
| 314 | const processed = { ...schema }; |
| 315 | |
| 316 | if (processed.properties && processed.required) { |
| 317 | const requiredSet = new Set(processed.required); |
| 318 | const newProps: Record<string, JSONSchema7Definition> = {}; |
| 319 | const newRequired = [...processed.required]; |
| 320 | |
| 321 | for (const [key, value] of Object.entries(processed.properties)) { |
| 322 | if (typeof value !== "object" || value === null) { |
| 323 | newProps[key] = value; |
| 324 | continue; |
| 325 | } |
| 326 | const prop = value as JSONSchema7; |
| 327 | if ( |
| 328 | requiredSet.has(key) && |
| 329 | prop.$ref && |
| 330 | typeof prop.description === "string" && |
| 331 | /\bnull\b/i.test(prop.description) |
| 332 | ) { |
| 333 | // Convert to anyOf: [$ref, null] and remove from required |
| 334 | const { $ref, ...rest } = prop; |
| 335 | newProps[key] = { |
| 336 | ...rest, |
| 337 | anyOf: [{ $ref }, { type: "null" as const }], |
| 338 | }; |
| 339 | const idx = newRequired.indexOf(key); |
| 340 | if (idx !== -1) newRequired.splice(idx, 1); |
| 341 | } else { |
| 342 | newProps[key] = normalizeNullableRequiredRefs(prop); |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | processed.properties = newProps; |
| 347 | processed.required = newRequired; |
| 348 | } |
| 349 | |
| 350 | // Recurse into nested schemas |
| 351 | if (processed.items) { |
| 352 | if (typeof processed.items === "object" && !Array.isArray(processed.items)) { |
| 353 | processed.items = normalizeNullableRequiredRefs(processed.items as JSONSchema7); |
| 354 | } |
| 355 | } |
| 356 | for (const combiner of ["anyOf", "allOf", "oneOf"] as const) { |
| 357 | if (processed[combiner]) { |
| 358 | processed[combiner] = processed[combiner]!.map((item) => |
| 359 | typeof item === "object" ? normalizeNullableRequiredRefs(item as JSONSchema7) : item |
| 360 | ) as JSONSchema7Definition[]; |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | return processed; |
| 365 | } |
| 366 | |
| 367 | // ── File output ───────────────────────────────────────────────────────────── |
| 368 |
no outgoing calls
no test coverage detected
searching dependent graphs…