|
| 1 | +/** |
| 2 | + * Zod-specific helpers for the v1-compat raw-shape shorthand on |
| 3 | + * `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so |
| 4 | + * that file stays library-agnostic per the Standard Schema spec. |
| 5 | + */ |
| 6 | + |
| 7 | +import * as z from 'zod/v4'; |
| 8 | + |
| 9 | +import type { StandardSchemaV1, StandardSchemaWithJSON } from './standardSchema.js'; |
| 10 | +import { isStandardSchema } from './standardSchema.js'; |
| 11 | + |
| 12 | +function isZodSchema(v: unknown): v is z.ZodType { |
| 13 | + if (typeof v !== 'object' || v === null) return false; |
| 14 | + if ('_def' in v) return true; |
| 15 | + return isStandardSchema(v) && (v as StandardSchemaV1)['~standard'].vendor === 'zod'; |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * Detects a "raw shape" — a plain object whose values are Zod field schemas, |
| 20 | + * e.g. `{ name: z.string() }`. Powers the auto-wrap in |
| 21 | + * {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only |
| 22 | + * Zod values are supported. |
| 23 | + * |
| 24 | + * @internal |
| 25 | + */ |
| 26 | +export function isZodRawShape(obj: unknown): obj is Record<string, z.ZodType> { |
| 27 | + if (typeof obj !== 'object' || obj === null) return false; |
| 28 | + if (isStandardSchema(obj)) return false; |
| 29 | + // [].every() is true, so an empty object is a valid raw shape (matches v1). |
| 30 | + return Object.values(obj).every(v => isZodSchema(v)); |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape |
| 35 | + * `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. |
| 36 | + * Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a |
| 37 | + * uniform schema type; already-wrapped schemas pass through unchanged. |
| 38 | + * |
| 39 | + * @internal |
| 40 | + */ |
| 41 | +export function normalizeRawShapeSchema( |
| 42 | + schema: StandardSchemaWithJSON | Record<string, z.ZodType> | undefined |
| 43 | +): StandardSchemaWithJSON | undefined { |
| 44 | + if (schema === undefined) return undefined; |
| 45 | + if (isZodRawShape(schema)) { |
| 46 | + return z.object(schema) as StandardSchemaWithJSON; |
| 47 | + } |
| 48 | + if (!isStandardSchema(schema)) { |
| 49 | + throw new TypeError( |
| 50 | + 'inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).' |
| 51 | + ); |
| 52 | + } |
| 53 | + return schema; |
| 54 | +} |
0 commit comments