|
| 1 | +import { describe, expect, it } from 'vitest'; |
| 2 | +import { z } from 'zod'; |
| 3 | +import { toOpenAiJsonSchema } from './jsonSchema.js'; |
| 4 | + |
| 5 | +function findSchemaKey(value: unknown, key: string): boolean { |
| 6 | + if (Array.isArray(value)) { |
| 7 | + return value.some((item) => findSchemaKey(item, key)); |
| 8 | + } |
| 9 | + |
| 10 | + if (value == null || typeof value !== 'object') { |
| 11 | + return false; |
| 12 | + } |
| 13 | + |
| 14 | + return Object.entries(value).some( |
| 15 | + ([entryKey, entryValue]) => |
| 16 | + entryKey === key || findSchemaKey(entryValue, key), |
| 17 | + ); |
| 18 | +} |
| 19 | + |
| 20 | +describe('toOpenAiJsonSchema', () => { |
| 21 | + it('rewrites Zod discriminated-union oneOf entries to anyOf', () => { |
| 22 | + const schema = z.object({ |
| 23 | + result: z.discriminatedUnion('kind', [ |
| 24 | + z.object({ kind: z.literal('existing'), id: z.string() }), |
| 25 | + z.object({ kind: z.literal('new'), type: z.string() }), |
| 26 | + ]), |
| 27 | + }); |
| 28 | + |
| 29 | + const jsonSchema = toOpenAiJsonSchema(schema); |
| 30 | + |
| 31 | + expect(findSchemaKey(jsonSchema, 'oneOf')).toBe(false); |
| 32 | + expect(findSchemaKey(jsonSchema, 'anyOf')).toBe(true); |
| 33 | + }); |
| 34 | +}); |
0 commit comments