openai
Version:
The official TypeScript library for the OpenAI API
65 lines (56 loc) • 2.25 kB
text/typescript
import type { ZodNullableDef } from 'zod/v3';
import type { JsonSchema7Type } from '../parseDef';
import { parseDef } from '../parseDef';
import type { Refs } from '../Refs';
import type { JsonSchema7NullType } from './null';
import { primitiveMappings } from './union';
export type JsonSchema7NullableType =
| {
anyOf: [JsonSchema7Type, JsonSchema7NullType];
}
| {
type: [string, 'null'];
};
export function parseNullableDef(
def: ZodNullableDef,
refs: Refs,
forceResolution: boolean,
): JsonSchema7NullableType | undefined {
if (
['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) &&
(!def.innerType._def.checks || !def.innerType._def.checks.length)
) {
if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') {
// SAFETY: The preceding primitive discriminator check permits the mapping lookup; the nullable-property target uses its existing extension representation.
return {
type: primitiveMappings[def.innerType._def.typeName as keyof typeof primitiveMappings],
nullable: true,
} as any;
}
// SAFETY: The preceding primitive discriminator check permits the mapping lookup; the nullable-property target uses its existing extension representation.
return {
type: [primitiveMappings[def.innerType._def.typeName as keyof typeof primitiveMappings], 'null'],
};
}
if (refs.target === 'openApi3') {
const base = parseDef(
def.innerType._def,
{
...refs,
currentPath: [...refs.currentPath],
},
forceResolution,
);
if (base && '$ref' in base) {
// SAFETY: The OpenAPI branch adds nullable to the converted base schema, an extension not represented by the shared JSON Schema union.
return { allOf: [base], nullable: true } as any;
}
// SAFETY: The OpenAPI branch adds nullable to the converted base schema, an extension not represented by the shared JSON Schema union.
return base && ({ ...base, nullable: true } as any);
}
const base = parseDef(def.innerType._def, {
...refs,
currentPath: [...refs.currentPath, 'anyOf', '0'],
});
return base && { anyOf: [base, { type: 'null' }] };
}