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