Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 305 lines 11 KB
Raw
1 import * as z from 'zod/v4';
2
3 import type { Decorations, IssueSink, StringFormat, WholeSchemaGuard, ZodBackend } from './types';
4 import { applyObjectPolicy, buildTuple, composeGuards, run, withPath } from './shared';
5
6 type S = z.ZodType;
7
8 type Payload = { value: unknown; issues: unknown[] };
9 type RunContext = { readonly direction?: 'forward' | 'backward' };
10 type RunFn = (payload: Payload, ctx: RunContext) => Payload | Promise<Payload>;
11 type SchemaDef = Record<string, unknown>;
12 type InstrumentedDef = SchemaDef & { wholeSchemaGuard?: WholeSchemaGuard };
13 type SchemaConstructor = { new (def: SchemaDef): S };
14 type Internals = {
15 def: InstrumentedDef;
16 constr: SchemaConstructor;
17 run: RunFn;
18 };
19
20 const internals = (schema: S): Internals => (schema as unknown as { _zod: Internals })._zod;
21
22 const isUnmergeable = (error: unknown): error is Error =>
23 error instanceof Error && error.message.startsWith('Unmergable intersection');
24
25 const instrumentedClasses = new WeakMap<SchemaConstructor, SchemaConstructor>();
26 const baseClasses = new WeakMap<SchemaConstructor, SchemaConstructor>();
27
28 /**
29 * A constructor that builds the schema with its own class and then wraps its
30 * `_zod.run`. Zod's `clone()` calls `new inst._zod.constr(def)`, so pointing
31 * `constr` at this wrapper keeps the behavior through `.describe()`,
32 * `.meta()`, `.check()`, and the clones frameworks make. The schema keeps
33 * its class: a guarded object is still a `ZodObject` with a `shape`.
34 *
35 * The wrapper reads its configuration from the definition on every run:
36 * `wholeSchemaGuard` checks the source value before the base parse, and an
37 * intersection turns the exception zod throws for values its branches
38 * cannot merge into an issue, as v3 reports it.
39 */
40 const instrumentedClass = (Base: SchemaConstructor): SchemaConstructor => {
41 const cached = instrumentedClasses.get(Base);
42 if (cached) {
43 return cached;
44 }
45
46 function Instrumented(def: SchemaDef): S {
47 const inst = new Base(def);
48 const zod = internals(inst);
49 zod.constr = Instrumented as unknown as SchemaConstructor;
50 const runAsBase = zod.run;
51 zod.run = (payload, ctx) => {
52 const fail = (message: string): Payload => {
53 payload.issues.push({ code: 'custom', message, input: payload.value, inst, path: [] });
54 return payload;
55 };
56 const guard = zod.def.wholeSchemaGuard;
57 if (guard !== undefined && ctx.direction !== 'backward') {
58 const failure = guard(payload.value);
59 if (failure !== undefined) {
60 return fail(failure);
61 }
62 }
63 if (zod.def.type !== 'intersection') {
64 return runAsBase(payload, ctx);
65 }
66 try {
67 return runAsBase(payload, ctx);
68 } catch (error) {
69 if (!isUnmergeable(error)) {
70 throw error;
71 }
72 return fail(error.message);
73 }
74 };
75 return inst;
76 }
77
78 const constructor = Instrumented as unknown as SchemaConstructor;
79 instrumentedClasses.set(Base, constructor);
80 instrumentedClasses.set(constructor, constructor);
81 baseClasses.set(constructor, Base);
82 return constructor;
83 };
84
85 /** `schema` rebuilt through the instrumented constructor with `def`, keeping its registry metadata. */
86 const rebuild = (schema: S, def: InstrumentedDef): S => {
87 const zod = internals(schema);
88 const Base = baseClasses.get(zod.constr) ?? zod.constr;
89 const rebuilt = new (instrumentedClass(Base))(def);
90 const meta = z.globalRegistry.get(schema);
91 if (meta) {
92 z.globalRegistry.add(rebuilt, meta);
93 }
94 return rebuilt;
95 };
96
97 const attachGuard = (schema: S, guard: WholeSchemaGuard): S => {
98 const zod = internals(schema);
99 const wholeSchemaGuard = composeGuards(guard, zod.def.wholeSchemaGuard);
100 return rebuild(schema, z.core.util.mergeDefs(zod.def, { wholeSchemaGuard }) as InstrumentedDef);
101 };
102
103 const intersection = (left: S, right: S): S => {
104 const schema = z.intersection(left, right);
105 return rebuild(schema, internals(schema).def);
106 };
107
108 /** Wrappers carry the inner description, as every v3 wrapper does through its `_def`. */
109 const carryDescription = (inner: S, wrapper: S): S => {
110 const description = z.globalRegistry.get(inner)?.description;
111 if (description !== undefined) {
112 z.globalRegistry.add(wrapper, { description });
113 }
114 return wrapper;
115 };
116
117 type Wrapper = 'optional' | 'nullable' | 'readonly' | 'prefault';
118
119 const rewrap: Record<Wrapper, (inner: S, def: SchemaDef) => S> = {
120 optional: inner => z.optional(inner),
121 nullable: inner => z.nullable(inner),
122 readonly: inner => z.readonly(inner),
123 prefault: (inner, def) => z.prefault(inner, def.defaultValue),
124 };
125
126 const isWrapper = (type: unknown): type is Wrapper =>
127 typeof type === 'string' && Object.hasOwn(rewrap, type);
128
129 /**
130 * Registers `annotations` on the innermost non-wrapper node, rebuilding the
131 * wrappers above it since `.meta()` clones. Validation-shaped keys such as
132 * `type: "integer"` must not sit on a wrapper: a nullable renders as
133 * `anyOf: [inner, null]`, and a `type` beside that `anyOf` would reject null.
134 */
135 const annotateInnermost = (schema: S, annotations: Decorations['annotations'] & object): S => {
136 const def = internals(schema).def;
137 if (!isWrapper(def.type)) {
138 return schema.meta(annotations);
139 }
140 const inner = annotateInnermost(def.innerType as S, annotations);
141 const wrapper = rewrap[def.type](inner, def);
142 const ownMeta = z.globalRegistry.get(schema);
143 if (ownMeta) {
144 z.globalRegistry.add(wrapper, ownMeta);
145 }
146 return wrapper;
147 };
148
149 const decorate = (schema: S, decorations: Decorations): S => {
150 const { description, annotations } = decorations;
151 if (annotations === undefined) {
152 return description === undefined ? schema : schema.describe(description);
153 }
154 if (!isWrapper(internals(schema).def.type)) {
155 return schema.meta(description === undefined ? annotations : { description, ...annotations });
156 }
157 const annotated = annotateInnermost(schema, annotations);
158 if (description !== undefined) {
159 z.globalRegistry.add(annotated, { ...z.globalRegistry.get(annotated), description });
160 }
161 return annotated;
162 };
163
164 type RawIssue = Record<string, unknown>;
165
166 /** Issues pushed onto a check payload; the enclosing schemas prefix the path. */
167 const sinkFor = (push: (issue: RawIssue) => void): IssueSink => ({
168 custom(message, options) {
169 push({
170 code: 'custom',
171 message,
172 ...withPath(options?.path),
173 ...(options?.params === undefined ? {} : { params: options.params }),
174 });
175 },
176 unrecognizedKeys(keys, message, options) {
177 push({ code: 'unrecognized_keys', keys: [...keys], message, ...withPath(options?.path) });
178 },
179 invalidUnion(message, failures, options) {
180 push({
181 code: 'invalid_union',
182 errors: failures.map(failure => [...failure.issues]),
183 message,
184 ...withPath(options?.path),
185 });
186 },
187 forward(failure) {
188 for (const issue of failure.issues) {
189 push({ ...(issue as RawIssue) });
190 }
191 },
192 });
193
194 let ipProbes: readonly S[] | undefined;
195 let urlProbe: S | undefined;
196
197 const isIp = (value: string): boolean => {
198 ipProbes ??= [z.ipv4(), z.ipv6()];
199 return ipProbes.some(probe => probe.safeParse(value).success);
200 };
201
202 const isUrl = (value: string): boolean => {
203 urlProbe ??= z.url();
204 return urlProbe.safeParse(value).success;
205 };
206
207 const stringFormat = (schema: S, format: StringFormat, message?: string): S => {
208 const string = schema as z.ZodString;
209 switch (format) {
210 case 'email':
211 return string.email(message);
212 case 'ip':
213 // v4 has no combined check, and a refinement keeps the value untouched.
214 return string.refine(isIp, message);
215 case 'ipv4':
216 return string.ipv4(message);
217 case 'ipv6':
218 return string.ipv6(message);
219 case 'uri':
220 // `.url()` rewrites the value it accepts; a refinement over the same
221 // check keeps the input as given, as v3 does.
222 return string.refine(isUrl, message);
223 case 'uuid':
224 // v3's uuid pattern is v4's guid: the RFC variant bits are not enforced.
225 return string.guid(message);
226 case 'date-time':
227 return string.datetime({ offset: true, error: message });
228 case 'time':
229 return string.time(message);
230 case 'date':
231 return string.date(message);
232 case 'duration':
233 return string.duration(message);
234 }
235 };
236
237 /** Zod v4 output: metadata in the global registry, refinements as checks, the guard as a run wrapper. */
238 export const zodV4Backend: ZodBackend<S> = {
239 isSchema: (value): value is S => value instanceof z.ZodType,
240 isNever: schema => schema instanceof z.ZodNever,
241
242 any: () => z.any(),
243 never: () => z.never(),
244 boolean: () => z.boolean(),
245 null: () => z.null(),
246 string: () => z.string(),
247 number: () => z.number(),
248 literal: value => z.literal(value),
249 enum: values => z.enum(values as [string, ...string[]]),
250 // `z.custom()` cannot be rendered as JSON Schema; a refined `any` can.
251 predicate: test => z.any().refine(test),
252
253 stringFormat,
254 base64: (schema, message) => (schema as z.ZodString).base64(message),
255 regex: (schema, pattern, message) => (schema as z.ZodString).regex(pattern, message),
256
257 // Native `.int()` is a safe-integer check that also emits ±2^53-1 bounds;
258 // JSON Schema integers, v3, and Ajv accept any integral number.
259 integer: (schema, message) => schema.refine(value => Number.isInteger(value), message),
260 bound: (schema, kind, value, message) => (schema as z.ZodNumber)[kind](value, message),
261
262 array: item => z.array(item),
263 minItems: (schema, count, message) => (schema as z.ZodArray<S>).min(count, message),
264 maxItems: (schema, count, message) => (schema as z.ZodArray<S>).max(count, message),
265 tuple: (items, rest) => buildTuple<S>(z.tuple(items as unknown as [S]), rest),
266
267 object: (shape, policy) => applyObjectPolicy<S>(z.object(shape), policy),
268 record: value => z.record(z.string(), value),
269
270 union: options => z.union(options as unknown as [S, S]),
271 intersection,
272
273 optional: schema => carryDescription(schema, schema.optional()),
274 nullable: schema => carryDescription(schema, schema.nullable()),
275 // `.default()` short-circuits past the inner schema; `.prefault()` parses the default through it, as v3 does.
276 withDefault: (schema, value) => carryDescription(schema, schema.prefault(value)),
277 readonly: schema => carryDescription(schema, schema.readonly()),
278 decorate,
279
280 refine: <T>(schema: S, test: (value: T) => boolean, message?: string) =>
281 schema.refine(value => test(value as T), message),
282 superRefine: <T>(schema: S, check: (value: T, issues: IssueSink) => void) =>
283 schema.superRefine((value, ctx) =>
284 check(
285 value as T,
286 sinkFor(issue => ctx.addIssue(issue as unknown as z.core.$ZodRawIssue))
287 )
288 ),
289 // A check that replaces the payload value keeps the schema's kind, where
290 // `.transform()` would produce a pipe that cannot be rendered as JSON Schema.
291 rewrite: <T>(schema: S, fn: (value: T, issues: IssueSink) => unknown) =>
292 schema.check(payload => {
293 const sink = sinkFor(issue =>
294 payload.issues.push({
295 input: payload.value,
296 continue: true,
297 ...issue,
298 } as unknown as z.core.$ZodRawIssue)
299 );
300 payload.value = fn(payload.value as T, sink);
301 }),
302
303 run,
304 attachGuard,
305 };