@mastra/schema-compat 0.10.2-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,587 @@
1
+ import type { Schema, LanguageModelV1 } from 'ai';
2
+ import type { JSONSchema7 } from 'json-schema';
3
+ import { z } from 'zod';
4
+ import type { Targets } from 'zod-to-json-schema';
5
+ import { convertZodSchemaToAISDKSchema } from './utils';
6
+
7
+ /**
8
+ * All supported string validation check types that can be processed or converted to descriptions.
9
+ * @constant
10
+ */
11
+ export const ALL_STRING_CHECKS = ['regex', 'emoji', 'email', 'url', 'uuid', 'cuid', 'min', 'max'] as const;
12
+
13
+ /**
14
+ * All supported number validation check types that can be processed or converted to descriptions.
15
+ * @constant
16
+ */
17
+ export const ALL_NUMBER_CHECKS = [
18
+ 'min', // gte internally
19
+ 'max', // lte internally
20
+ 'multipleOf',
21
+ ] as const;
22
+
23
+ /**
24
+ * All supported array validation check types that can be processed or converted to descriptions.
25
+ * @constant
26
+ */
27
+ export const ALL_ARRAY_CHECKS = ['min', 'max', 'length'] as const;
28
+
29
+ /**
30
+ * Zod types that are not supported by most AI model providers and should be avoided.
31
+ * @constant
32
+ */
33
+ export const UNSUPPORTED_ZOD_TYPES = ['ZodIntersection', 'ZodNever', 'ZodNull', 'ZodTuple', 'ZodUndefined'] as const;
34
+
35
+ /**
36
+ * Zod types that are generally supported by AI model providers.
37
+ * @constant
38
+ */
39
+ export const SUPPORTED_ZOD_TYPES = [
40
+ 'ZodObject',
41
+ 'ZodArray',
42
+ 'ZodUnion',
43
+ 'ZodString',
44
+ 'ZodNumber',
45
+ 'ZodDate',
46
+ 'ZodAny',
47
+ 'ZodDefault',
48
+ ] as const;
49
+
50
+ /**
51
+ * All Zod types (both supported and unsupported).
52
+ * @constant
53
+ */
54
+ export const ALL_ZOD_TYPES = [...SUPPORTED_ZOD_TYPES, ...UNSUPPORTED_ZOD_TYPES] as const;
55
+
56
+ /**
57
+ * Type representing string validation checks.
58
+ */
59
+ export type StringCheckType = (typeof ALL_STRING_CHECKS)[number];
60
+
61
+ /**
62
+ * Type representing number validation checks.
63
+ */
64
+ export type NumberCheckType = (typeof ALL_NUMBER_CHECKS)[number];
65
+
66
+ /**
67
+ * Type representing array validation checks.
68
+ */
69
+ export type ArrayCheckType = (typeof ALL_ARRAY_CHECKS)[number];
70
+
71
+ /**
72
+ * Type representing unsupported Zod schema types.
73
+ */
74
+ export type UnsupportedZodType = (typeof UNSUPPORTED_ZOD_TYPES)[number];
75
+
76
+ /**
77
+ * Type representing supported Zod schema types.
78
+ */
79
+ export type SupportedZodType = (typeof SUPPORTED_ZOD_TYPES)[number];
80
+
81
+ /**
82
+ * Type representing all Zod schema types (supported and unsupported).
83
+ */
84
+ export type AllZodType = (typeof ALL_ZOD_TYPES)[number];
85
+
86
+ /**
87
+ * Utility type to extract the shape of a Zod object schema.
88
+ */
89
+ export type ZodShape<T extends z.AnyZodObject> = T['shape'];
90
+
91
+ /**
92
+ * Utility type to extract the keys from a Zod object shape.
93
+ */
94
+ export type ShapeKey<T extends z.AnyZodObject> = keyof ZodShape<T>;
95
+
96
+ /**
97
+ * Utility type to extract the value types from a Zod object shape.
98
+ */
99
+ export type ShapeValue<T extends z.AnyZodObject> = ZodShape<T>[ShapeKey<T>];
100
+
101
+ // Add constraint types at the top
102
+
103
+ type StringConstraints = {
104
+ minLength?: number;
105
+ maxLength?: number;
106
+ email?: boolean;
107
+ url?: boolean;
108
+ uuid?: boolean;
109
+ cuid?: boolean;
110
+ emoji?: boolean;
111
+ regex?: { pattern: string; flags?: string };
112
+ };
113
+
114
+ type NumberConstraints = {
115
+ gt?: number;
116
+ gte?: number;
117
+ lt?: number;
118
+ lte?: number;
119
+ multipleOf?: number;
120
+ };
121
+
122
+ type ArrayConstraints = {
123
+ minLength?: number;
124
+ maxLength?: number;
125
+ exactLength?: number;
126
+ };
127
+
128
+ type DateConstraints = {
129
+ minDate?: string;
130
+ maxDate?: string;
131
+ dateFormat?: string;
132
+ };
133
+
134
+ /**
135
+ * Abstract base class for creating schema compatibility layers for different AI model providers.
136
+ *
137
+ * This class provides a framework for transforming Zod schemas to work with specific AI model
138
+ * provider requirements and limitations. Each provider may have different support levels for
139
+ * JSON Schema features, validation constraints, and data types.
140
+ *
141
+ * @abstract
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * import { SchemaCompatLayer } from '@mastra/schema-compat';
146
+ * import type { LanguageModelV1 } from 'ai';
147
+ *
148
+ * class CustomProviderCompat extends SchemaCompatLayer {
149
+ * constructor(model: LanguageModelV1) {
150
+ * super(model);
151
+ * }
152
+ *
153
+ * shouldApply(): boolean {
154
+ * return this.getModel().provider === 'custom-provider';
155
+ * }
156
+ *
157
+ * getSchemaTarget() {
158
+ * return 'jsonSchema7';
159
+ * }
160
+ *
161
+ * processZodType<T extends z.AnyZodObject>(value: z.ZodTypeAny): ShapeValue<T> {
162
+ * // Custom processing logic for this provider
163
+ * switch (value._def.typeName) {
164
+ * case 'ZodString':
165
+ * return this.defaultZodStringHandler(value, ['email', 'url']);
166
+ * default:
167
+ * return this.defaultUnsupportedZodTypeHandler(value);
168
+ * }
169
+ * }
170
+ * }
171
+ * ```
172
+ */
173
+ export abstract class SchemaCompatLayer {
174
+ private model: LanguageModelV1;
175
+
176
+ /**
177
+ * Creates a new schema compatibility instance.
178
+ *
179
+ * @param model - The language model this compatibility layer applies to
180
+ */
181
+ constructor(model: LanguageModelV1) {
182
+ this.model = model;
183
+ }
184
+
185
+ /**
186
+ * Gets the language model associated with this compatibility layer.
187
+ *
188
+ * @returns The language model instance
189
+ */
190
+ getModel(): LanguageModelV1 {
191
+ return this.model;
192
+ }
193
+
194
+ /**
195
+ * Determines whether this compatibility layer should be applied for the current model.
196
+ *
197
+ * @returns True if this compatibility layer should be used, false otherwise
198
+ * @abstract
199
+ */
200
+ abstract shouldApply(): boolean;
201
+
202
+ /**
203
+ * Returns the JSON Schema target format for this provider.
204
+ *
205
+ * @returns The schema target format, or undefined to use the default 'jsonSchema7'
206
+ * @abstract
207
+ */
208
+ abstract getSchemaTarget(): Targets | undefined;
209
+
210
+ /**
211
+ * Processes a specific Zod type according to the provider's requirements.
212
+ *
213
+ * @param value - The Zod type to process
214
+ * @returns The processed Zod type
215
+ * @abstract
216
+ */
217
+ abstract processZodType<T extends z.AnyZodObject>(value: z.ZodTypeAny): ShapeValue<T>;
218
+
219
+ /**
220
+ * Applies compatibility transformations to a Zod object schema.
221
+ *
222
+ * @param zodSchema - The Zod object schema to transform
223
+ * @returns Object containing the transformed schema
224
+ * @private
225
+ */
226
+ private applyZodSchemaCompatibility(zodSchema: z.AnyZodObject): {
227
+ schema: z.AnyZodObject;
228
+ } {
229
+ const newSchema = z.object(
230
+ Object.entries<z.ZodTypeAny>(zodSchema.shape || {}).reduce(
231
+ (acc, [key, value]) => ({
232
+ ...acc,
233
+ [key]: this.processZodType<any>(value),
234
+ }),
235
+ {},
236
+ ),
237
+ );
238
+
239
+ return { schema: newSchema };
240
+ }
241
+
242
+ /**
243
+ * Default handler for Zod object types. Recursively processes all properties in the object.
244
+ *
245
+ * @param value - The Zod object to process
246
+ * @returns The processed Zod object
247
+ */
248
+ public defaultZodObjectHandler<T extends z.AnyZodObject>(value: z.ZodTypeAny): ShapeValue<T> {
249
+ const zodObject = value as z.ZodObject<any, any, any>;
250
+ const processedShape = Object.entries(zodObject.shape || {}).reduce<Record<string, z.ZodTypeAny>>(
251
+ (acc, [key, propValue]) => {
252
+ const typedPropValue = propValue as z.ZodTypeAny;
253
+ const processedValue = this.processZodType<T>(typedPropValue);
254
+ acc[key] = processedValue;
255
+ return acc;
256
+ },
257
+ {},
258
+ );
259
+ let result = z.object(processedShape);
260
+ if (value.description) {
261
+ result = result.describe(value.description);
262
+ }
263
+ return result as ShapeValue<T>;
264
+ }
265
+
266
+ /**
267
+ * Merges validation constraints into a parameter description.
268
+ *
269
+ * This helper method converts validation constraints that may not be supported
270
+ * by a provider into human-readable descriptions.
271
+ *
272
+ * @param description - The existing parameter description
273
+ * @param constraints - The validation constraints to merge
274
+ * @returns The updated description with constraints, or undefined if no constraints
275
+ */
276
+ public mergeParameterDescription(
277
+ description: string | undefined,
278
+ constraints:
279
+ | NumberConstraints
280
+ | StringConstraints
281
+ | ArrayConstraints
282
+ | DateConstraints
283
+ | { defaultValue?: unknown },
284
+ ): string | undefined {
285
+ if (Object.keys(constraints).length > 0) {
286
+ return (description ? description + '\n' : '') + JSON.stringify(constraints);
287
+ } else {
288
+ return description;
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Default handler for unsupported Zod types. Throws an error for specified unsupported types.
294
+ *
295
+ * @param value - The Zod type to check
296
+ * @param throwOnTypes - Array of type names to throw errors for
297
+ * @returns The original value if not in the throw list
298
+ * @throws Error if the type is in the unsupported list
299
+ */
300
+ public defaultUnsupportedZodTypeHandler<T extends z.AnyZodObject>(
301
+ value: z.ZodTypeAny,
302
+ throwOnTypes: readonly UnsupportedZodType[] = UNSUPPORTED_ZOD_TYPES,
303
+ ): ShapeValue<T> {
304
+ if (throwOnTypes.includes(value._def.typeName as UnsupportedZodType)) {
305
+ throw new Error(`${this.model.modelId} does not support zod type: ${value._def.typeName}`);
306
+ }
307
+ return value as ShapeValue<T>;
308
+ }
309
+
310
+ /**
311
+ * Default handler for Zod array types. Processes array constraints according to provider support.
312
+ *
313
+ * @param value - The Zod array to process
314
+ * @param handleChecks - Array constraints to convert to descriptions vs keep as validation
315
+ * @returns The processed Zod array
316
+ */
317
+ public defaultZodArrayHandler<T extends z.AnyZodObject>(
318
+ value: z.ZodTypeAny,
319
+ handleChecks: readonly ArrayCheckType[] = ALL_ARRAY_CHECKS,
320
+ ): ShapeValue<T> {
321
+ const zodArray = (value as z.ZodArray<any>)._def;
322
+ const arrayType = zodArray.type;
323
+ const constraints: ArrayConstraints = {};
324
+ if (zodArray.minLength?.value !== undefined && handleChecks.includes('min')) {
325
+ constraints.minLength = zodArray.minLength.value;
326
+ }
327
+ if (zodArray.maxLength?.value !== undefined && handleChecks.includes('max')) {
328
+ constraints.maxLength = zodArray.maxLength.value;
329
+ }
330
+ if (zodArray.exactLength?.value !== undefined && handleChecks.includes('length')) {
331
+ constraints.exactLength = zodArray.exactLength.value;
332
+ }
333
+ const processedType =
334
+ arrayType._def.typeName === 'ZodObject' ? this.processZodType<T>(arrayType as z.ZodTypeAny) : arrayType;
335
+ let result = z.array(processedType);
336
+ if (zodArray.minLength?.value !== undefined && !handleChecks.includes('min')) {
337
+ result = result.min(zodArray.minLength.value);
338
+ }
339
+ if (zodArray.maxLength?.value !== undefined && !handleChecks.includes('max')) {
340
+ result = result.max(zodArray.maxLength.value);
341
+ }
342
+ if (zodArray.exactLength?.value !== undefined && !handleChecks.includes('length')) {
343
+ result = result.length(zodArray.exactLength.value);
344
+ }
345
+
346
+ const description = this.mergeParameterDescription(value.description, constraints);
347
+ if (description) {
348
+ result = result.describe(description);
349
+ }
350
+ return result as ShapeValue<T>;
351
+ }
352
+
353
+ /**
354
+ * Default handler for Zod union types. Processes all union options.
355
+ *
356
+ * @param value - The Zod union to process
357
+ * @returns The processed Zod union
358
+ * @throws Error if union has fewer than 2 options
359
+ */
360
+ public defaultZodUnionHandler<T extends z.AnyZodObject>(value: z.ZodTypeAny): ShapeValue<T> {
361
+ const zodUnion = value as z.ZodUnion<[z.ZodTypeAny, ...z.ZodTypeAny[]]>;
362
+ const processedOptions = zodUnion._def.options.map((option: z.ZodTypeAny) => this.processZodType<T>(option));
363
+ if (processedOptions.length < 2) throw new Error('Union must have at least 2 options');
364
+ let result = z.union(processedOptions as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]);
365
+ if (value.description) {
366
+ result = result.describe(value.description);
367
+ }
368
+ return result as ShapeValue<T>;
369
+ }
370
+
371
+ /**
372
+ * Default handler for Zod string types. Processes string validation constraints.
373
+ *
374
+ * @param value - The Zod string to process
375
+ * @param handleChecks - String constraints to convert to descriptions vs keep as validation
376
+ * @returns The processed Zod string
377
+ */
378
+ public defaultZodStringHandler<T extends z.AnyZodObject>(
379
+ value: z.ZodTypeAny,
380
+ handleChecks: readonly StringCheckType[] = ALL_STRING_CHECKS,
381
+ ): ShapeValue<T> {
382
+ const zodString = value as z.ZodString;
383
+ const constraints: StringConstraints = {};
384
+ const checks = zodString._def.checks || [];
385
+ type ZodStringCheck = (typeof checks)[number];
386
+ const newChecks: ZodStringCheck[] = [];
387
+ for (const check of checks) {
388
+ if ('kind' in check) {
389
+ if (handleChecks.includes(check.kind as StringCheckType)) {
390
+ switch (check.kind) {
391
+ case 'regex': {
392
+ constraints.regex = {
393
+ pattern: check.regex.source,
394
+ flags: check.regex.flags,
395
+ };
396
+ break;
397
+ }
398
+ case 'emoji': {
399
+ constraints.emoji = true;
400
+ break;
401
+ }
402
+ case 'email': {
403
+ constraints.email = true;
404
+ break;
405
+ }
406
+ case 'url': {
407
+ constraints.url = true;
408
+ break;
409
+ }
410
+ case 'uuid': {
411
+ constraints.uuid = true;
412
+ break;
413
+ }
414
+ case 'cuid': {
415
+ constraints.cuid = true;
416
+ break;
417
+ }
418
+ case 'min': {
419
+ constraints.minLength = check.value;
420
+ break;
421
+ }
422
+ case 'max': {
423
+ constraints.maxLength = check.value;
424
+ break;
425
+ }
426
+ }
427
+ } else {
428
+ newChecks.push(check);
429
+ }
430
+ }
431
+ }
432
+ let result = z.string();
433
+ for (const check of newChecks) {
434
+ result = result._addCheck(check);
435
+ }
436
+ const description = this.mergeParameterDescription(value.description, constraints);
437
+ if (description) {
438
+ result = result.describe(description);
439
+ }
440
+ return result as ShapeValue<T>;
441
+ }
442
+
443
+ /**
444
+ * Default handler for Zod number types. Processes number validation constraints.
445
+ *
446
+ * @param value - The Zod number to process
447
+ * @param handleChecks - Number constraints to convert to descriptions vs keep as validation
448
+ * @returns The processed Zod number
449
+ */
450
+ public defaultZodNumberHandler<T extends z.AnyZodObject>(
451
+ value: z.ZodTypeAny,
452
+ handleChecks: readonly NumberCheckType[] = ALL_NUMBER_CHECKS,
453
+ ): ShapeValue<T> {
454
+ const zodNumber = value as z.ZodNumber;
455
+ const constraints: NumberConstraints = {};
456
+ const checks = zodNumber._def.checks || [];
457
+ type ZodNumberCheck = (typeof checks)[number];
458
+ const newChecks: ZodNumberCheck[] = [];
459
+ for (const check of checks) {
460
+ if ('kind' in check) {
461
+ if (handleChecks.includes(check.kind as NumberCheckType)) {
462
+ switch (check.kind) {
463
+ case 'min':
464
+ if (check.inclusive) {
465
+ constraints.gte = check.value;
466
+ } else {
467
+ constraints.gt = check.value;
468
+ }
469
+ break;
470
+ case 'max':
471
+ if (check.inclusive) {
472
+ constraints.lte = check.value;
473
+ } else {
474
+ constraints.lt = check.value;
475
+ }
476
+ break;
477
+ case 'multipleOf': {
478
+ constraints.multipleOf = check.value;
479
+ break;
480
+ }
481
+ }
482
+ } else {
483
+ newChecks.push(check);
484
+ }
485
+ }
486
+ }
487
+ let result = z.number();
488
+ for (const check of newChecks) {
489
+ switch (check.kind) {
490
+ case 'int':
491
+ result = result.int();
492
+ break;
493
+ case 'finite':
494
+ result = result.finite();
495
+ break;
496
+ default:
497
+ result = result._addCheck(check);
498
+ }
499
+ }
500
+ const description = this.mergeParameterDescription(value.description, constraints);
501
+ if (description) {
502
+ result = result.describe(description);
503
+ }
504
+ return result as ShapeValue<T>;
505
+ }
506
+
507
+ /**
508
+ * Default handler for Zod date types. Converts dates to ISO strings with constraint descriptions.
509
+ *
510
+ * @param value - The Zod date to process
511
+ * @returns A Zod string schema representing the date in ISO format
512
+ */
513
+ public defaultZodDateHandler<T extends z.AnyZodObject>(value: z.ZodTypeAny): ShapeValue<T> {
514
+ const zodDate = value as z.ZodDate;
515
+ const constraints: DateConstraints = {};
516
+ const checks = zodDate._def.checks || [];
517
+ type ZodDateCheck = (typeof checks)[number];
518
+ const newChecks: ZodDateCheck[] = [];
519
+ for (const check of checks) {
520
+ if ('kind' in check) {
521
+ switch (check.kind) {
522
+ case 'min':
523
+ const minDate = new Date(check.value);
524
+ if (!isNaN(minDate.getTime())) {
525
+ constraints.minDate = minDate.toISOString();
526
+ }
527
+ break;
528
+ case 'max':
529
+ const maxDate = new Date(check.value);
530
+ if (!isNaN(maxDate.getTime())) {
531
+ constraints.maxDate = maxDate.toISOString();
532
+ }
533
+ break;
534
+ default:
535
+ newChecks.push(check);
536
+ }
537
+ }
538
+ }
539
+ constraints.dateFormat = 'date-time';
540
+ let result = z.string().describe('date-time');
541
+ const description = this.mergeParameterDescription(value.description, constraints);
542
+ if (description) {
543
+ result = result.describe(description);
544
+ }
545
+ return result as ShapeValue<T>;
546
+ }
547
+
548
+ /**
549
+ * Default handler for Zod optional types. Processes the inner type and maintains optionality.
550
+ *
551
+ * @param value - The Zod optional to process
552
+ * @param handleTypes - Types that should be processed vs passed through
553
+ * @returns The processed Zod optional
554
+ */
555
+ public defaultZodOptionalHandler<T extends z.AnyZodObject>(
556
+ value: z.ZodTypeAny,
557
+ handleTypes: readonly AllZodType[] = SUPPORTED_ZOD_TYPES,
558
+ ): ShapeValue<T> {
559
+ if (handleTypes.includes(value._def.innerType._def.typeName as AllZodType)) {
560
+ return this.processZodType(value._def.innerType).optional();
561
+ } else {
562
+ return value as ShapeValue<T>;
563
+ }
564
+ }
565
+
566
+ /**
567
+ * Processes a Zod object schema and converts it to an AI SDK Schema.
568
+ *
569
+ * @param zodSchema - The Zod object schema to process
570
+ * @returns An AI SDK Schema with provider-specific compatibility applied
571
+ */
572
+ public processToAISDKSchema(zodSchema: z.AnyZodObject): Schema {
573
+ const { schema } = this.applyZodSchemaCompatibility(zodSchema);
574
+
575
+ return convertZodSchemaToAISDKSchema(schema, this.getSchemaTarget());
576
+ }
577
+
578
+ /**
579
+ * Processes a Zod object schema and converts it to a JSON Schema.
580
+ *
581
+ * @param zodSchema - The Zod object schema to process
582
+ * @returns A JSONSchema7 object with provider-specific compatibility applied
583
+ */
584
+ public processToJSONSchema(zodSchema: z.AnyZodObject): JSONSchema7 {
585
+ return this.processToAISDKSchema(zodSchema).jsonSchema;
586
+ }
587
+ }