62 lines
2.2 KiB
Plaintext
62 lines
2.2 KiB
Plaintext
import { ZodFirstPartyTypeKind, } from "zod/v3";
|
|
import { parseDef } from "../parseDef.js";
|
|
import { parseStringDef } from "./string.js";
|
|
import { parseBrandedDef } from "./branded.js";
|
|
import { parseAnyDef } from "./any.js";
|
|
export function parseRecordDef(def, refs) {
|
|
if (refs.target === "openAi") {
|
|
console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
|
|
}
|
|
if (refs.target === "openApi3" &&
|
|
def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
|
|
return {
|
|
type: "object",
|
|
required: def.keyType._def.values,
|
|
properties: def.keyType._def.values.reduce((acc, key) => ({
|
|
...acc,
|
|
[key]: parseDef(def.valueType._def, {
|
|
...refs,
|
|
currentPath: [...refs.currentPath, "properties", key],
|
|
}) ?? parseAnyDef(refs),
|
|
}), {}),
|
|
additionalProperties: refs.rejectedAdditionalProperties,
|
|
};
|
|
}
|
|
const schema = {
|
|
type: "object",
|
|
additionalProperties: parseDef(def.valueType._def, {
|
|
...refs,
|
|
currentPath: [...refs.currentPath, "additionalProperties"],
|
|
}) ?? refs.allowedAdditionalProperties,
|
|
};
|
|
if (refs.target === "openApi3") {
|
|
return schema;
|
|
}
|
|
if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&
|
|
def.keyType._def.checks?.length) {
|
|
const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
|
|
return {
|
|
...schema,
|
|
propertyNames: keyType,
|
|
};
|
|
}
|
|
else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
|
|
return {
|
|
...schema,
|
|
propertyNames: {
|
|
enum: def.keyType._def.values,
|
|
},
|
|
};
|
|
}
|
|
else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&
|
|
def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&
|
|
def.keyType._def.type._def.checks?.length) {
|
|
const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
|
|
return {
|
|
...schema,
|
|
propertyNames: keyType,
|
|
};
|
|
}
|
|
return schema;
|
|
}
|