@composio/json-schema-to-zod 0.1.19 → 0.2.0

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.
package/dist/index.cjs DELETED
@@ -1,830 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- jsonSchemaToZod: () => jsonSchemaToZod
34
- });
35
- module.exports = __toCommonJS(index_exports);
36
-
37
- // src/parsers/parse-schema.ts
38
- var z16 = __toESM(require("zod/v3"), 1);
39
-
40
- // src/parsers/parse-all-of.ts
41
- var import_v3 = require("zod/v3");
42
-
43
- // src/utils/half.ts
44
- var half = (arr) => {
45
- return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
46
- };
47
-
48
- // src/parsers/parse-all-of.ts
49
- var originalIndex = Symbol("Original index");
50
- var ensureOriginalIndex = (arr) => {
51
- const newArr = [];
52
- for (let i = 0; i < arr.length; i++) {
53
- const item = arr[i];
54
- if (typeof item === "boolean") {
55
- newArr.push(item ? { [originalIndex]: i } : { [originalIndex]: i, not: {} });
56
- } else if (originalIndex in item) {
57
- return arr;
58
- } else {
59
- newArr.push({ ...item, [originalIndex]: i });
60
- }
61
- }
62
- return newArr;
63
- };
64
- function parseAllOf(jsonSchema, refs) {
65
- if (jsonSchema.allOf.length === 0) {
66
- return import_v3.z.never();
67
- }
68
- if (jsonSchema.allOf.length === 1) {
69
- const item = jsonSchema.allOf[0];
70
- return parseSchema(item, {
71
- ...refs,
72
- path: [...refs.path, "allOf", item[originalIndex]]
73
- });
74
- }
75
- const [left, right] = half(ensureOriginalIndex(jsonSchema.allOf));
76
- return import_v3.z.intersection(parseAllOf({ allOf: left }, refs), parseAllOf({ allOf: right }, refs));
77
- }
78
-
79
- // src/parsers/parse-any-of.ts
80
- var import_v32 = require("zod/v3");
81
- var parseAnyOf = (jsonSchema, refs) => {
82
- return jsonSchema.anyOf.length ? jsonSchema.anyOf.length === 1 ? parseSchema(jsonSchema.anyOf[0], {
83
- ...refs,
84
- path: [...refs.path, "anyOf", 0]
85
- }) : import_v32.z.union(
86
- jsonSchema.anyOf.map(
87
- (schema, i) => parseSchema(schema, { ...refs, path: [...refs.path, "anyOf", i] })
88
- )
89
- ) : import_v32.z.any();
90
- };
91
-
92
- // src/parsers/parse-array.ts
93
- var import_v33 = require("zod/v3");
94
-
95
- // src/utils/extend-schema.ts
96
- function extendSchemaWithMessage(zodSchema, jsonSchema, key, extend) {
97
- const value = jsonSchema[key];
98
- if (value !== void 0) {
99
- const errorMessage = jsonSchema.errorMessage?.[key];
100
- return extend(zodSchema, value, errorMessage);
101
- }
102
- return zodSchema;
103
- }
104
-
105
- // src/utils/its.ts
106
- var its = {
107
- an: {
108
- object: (x) => x.type === "object" || !x.type && (x.properties !== void 0 || x.additionalProperties !== void 0 || x.patternProperties !== void 0),
109
- array: (x) => x.type === "array",
110
- anyOf: (x) => x.anyOf !== void 0,
111
- allOf: (x) => x.allOf !== void 0,
112
- enum: (x) => x.enum !== void 0
113
- },
114
- a: {
115
- nullable: (x) => x.nullable === true,
116
- multipleType: (x) => Array.isArray(x.type),
117
- not: (x) => x.not !== void 0,
118
- const: (x) => x.const !== void 0,
119
- primitive: (x, p) => x.type === p,
120
- conditional: (x) => Boolean("if" in x && x.if && "then" in x && "else" in x && x.then && x.else),
121
- oneOf: (x) => x.oneOf !== void 0
122
- }
123
- };
124
-
125
- // src/parsers/parse-array.ts
126
- var parseArray = (jsonSchema, refs) => {
127
- if (its.an.anyOf(jsonSchema)) {
128
- const types = /* @__PURE__ */ new Set();
129
- const itemsSchemas = [];
130
- jsonSchema.anyOf.forEach((option) => {
131
- if (typeof option === "object" && option.type) {
132
- types.add(typeof option.type === "string" ? option.type : option.type[0]);
133
- }
134
- if (typeof option === "object" && option.items) {
135
- const optionItems = option.items;
136
- if (!Array.isArray(optionItems) && typeof optionItems === "object") {
137
- itemsSchemas.push(optionItems);
138
- }
139
- }
140
- });
141
- let finalItems;
142
- if (itemsSchemas.length === 1) {
143
- finalItems = itemsSchemas[0];
144
- } else if (itemsSchemas.length > 1) {
145
- finalItems = { anyOf: itemsSchemas };
146
- }
147
- const newSchema = {
148
- ...types.size > 0 ? { type: Array.from(types) } : { type: "array" },
149
- ...finalItems && { items: finalItems }
150
- };
151
- const metadataFields = ["default", "description", "examples", "title"];
152
- metadataFields.forEach((field) => {
153
- const value = jsonSchema[field];
154
- if (value !== void 0) {
155
- newSchema[field] = value;
156
- }
157
- });
158
- return parseSchema(newSchema, refs);
159
- }
160
- if (Array.isArray(jsonSchema.items)) {
161
- return import_v33.z.tuple(
162
- jsonSchema.items.map(
163
- (v, i) => parseSchema(v, { ...refs, path: [...refs.path, "items", i] })
164
- )
165
- );
166
- }
167
- let zodSchema = !jsonSchema.items ? import_v33.z.array(import_v33.z.any()) : import_v33.z.array(parseSchema(jsonSchema.items, { ...refs, path: [...refs.path, "items"] }));
168
- zodSchema = extendSchemaWithMessage(
169
- zodSchema,
170
- jsonSchema,
171
- "minItems",
172
- (zs, minItems, errorMessage) => zs.min(minItems, errorMessage)
173
- );
174
- zodSchema = extendSchemaWithMessage(
175
- zodSchema,
176
- jsonSchema,
177
- "maxItems",
178
- (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage)
179
- );
180
- if (typeof jsonSchema.min === "number" && typeof jsonSchema.minItems !== "number") {
181
- zodSchema = extendSchemaWithMessage(
182
- zodSchema,
183
- { ...jsonSchema, minItems: jsonSchema.min },
184
- "minItems",
185
- (zs, minItems, errorMessage) => zs.min(minItems, errorMessage)
186
- );
187
- }
188
- if (typeof jsonSchema.max === "number" && typeof jsonSchema.maxItems !== "number") {
189
- zodSchema = extendSchemaWithMessage(
190
- zodSchema,
191
- { ...jsonSchema, maxItems: jsonSchema.max },
192
- "maxItems",
193
- (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage)
194
- );
195
- }
196
- return zodSchema;
197
- };
198
-
199
- // src/parsers/parse-boolean.ts
200
- var import_v34 = require("zod/v3");
201
- var parseBoolean = (_jsonSchema) => {
202
- return import_v34.z.boolean();
203
- };
204
-
205
- // src/parsers/parse-const.ts
206
- var import_v35 = require("zod/v3");
207
- var parseConst = (jsonSchema) => {
208
- return import_v35.z.literal(jsonSchema.const);
209
- };
210
-
211
- // src/parsers/parse-default.ts
212
- var import_v36 = require("zod/v3");
213
- var parseDefault = (_jsonSchema) => {
214
- return import_v36.z.any();
215
- };
216
-
217
- // src/parsers/parse-enum.ts
218
- var import_v37 = require("zod/v3");
219
- var parseEnum = (jsonSchema) => {
220
- if (jsonSchema.enum.length === 0) {
221
- return import_v37.z.never();
222
- }
223
- if (jsonSchema.enum.length === 1) {
224
- return import_v37.z.literal(jsonSchema.enum[0]);
225
- }
226
- if (jsonSchema.enum.every((x) => typeof x === "string")) {
227
- return import_v37.z.enum(jsonSchema.enum);
228
- }
229
- return import_v37.z.union(
230
- jsonSchema.enum.map((x) => import_v37.z.literal(x))
231
- );
232
- };
233
-
234
- // src/parsers/parse-if-then-else.ts
235
- var import_v38 = require("zod/v3");
236
- var parseIfThenElse = (jsonSchema, refs) => {
237
- const $if = parseSchema(jsonSchema.if, { ...refs, path: [...refs.path, "if"] });
238
- const $then = parseSchema(jsonSchema.then, {
239
- ...refs,
240
- path: [...refs.path, "then"]
241
- });
242
- const $else = parseSchema(jsonSchema.else, {
243
- ...refs,
244
- path: [...refs.path, "else"]
245
- });
246
- return import_v38.z.union([$then, $else]).superRefine((value, ctx) => {
247
- const result = $if.safeParse(value).success ? $then.safeParse(value) : $else.safeParse(value);
248
- if (!result.success) {
249
- result.error.errors.forEach((error) => ctx.addIssue(error));
250
- }
251
- });
252
- };
253
-
254
- // src/parsers/parse-multiple-type.ts
255
- var import_v39 = require("zod/v3");
256
- var parseMultipleType = (jsonSchema, refs) => {
257
- return import_v39.z.union(
258
- jsonSchema.type.map((type) => parseSchema({ ...jsonSchema, type }, refs))
259
- );
260
- };
261
-
262
- // src/parsers/parse-not.ts
263
- var import_v310 = require("zod/v3");
264
- var parseNot = (jsonSchema, refs) => {
265
- return import_v310.z.any().refine(
266
- (value) => !parseSchema(jsonSchema.not, {
267
- ...refs,
268
- path: [...refs.path, "not"]
269
- }).safeParse(value).success,
270
- "Invalid input: Should NOT be valid against schema"
271
- );
272
- };
273
-
274
- // src/parsers/parse-null.ts
275
- var import_v311 = require("zod/v3");
276
- var parseNull = (_jsonSchema) => {
277
- return import_v311.z.null();
278
- };
279
-
280
- // src/utils/omit.ts
281
- var omit = (obj, ...keys) => Object.keys(obj).reduce((acc, key) => {
282
- if (!keys.includes(key)) {
283
- acc[key] = obj[key];
284
- }
285
- return acc;
286
- }, {});
287
-
288
- // src/parsers/parse-nullable.ts
289
- var parseNullable = (jsonSchema, refs) => {
290
- const hasNullDefault = jsonSchema.default === null;
291
- const baseSchema = hasNullDefault ? omit(omit(jsonSchema, "nullable"), "default") : omit(jsonSchema, "nullable");
292
- const zodSchema = parseSchema(baseSchema, refs, true).nullable();
293
- return hasNullDefault ? zodSchema.default(null) : zodSchema;
294
- };
295
-
296
- // src/parsers/parse-number.ts
297
- var import_v312 = require("zod/v3");
298
- var parseNumber = (jsonSchema) => {
299
- let zodSchema = import_v312.z.number();
300
- let isInteger = false;
301
- if (jsonSchema.type === "integer") {
302
- isInteger = true;
303
- zodSchema = extendSchemaWithMessage(
304
- zodSchema,
305
- jsonSchema,
306
- "type",
307
- (zs, _, errorMsg) => zs.int(errorMsg)
308
- );
309
- } else if (jsonSchema.format === "int64") {
310
- isInteger = true;
311
- zodSchema = extendSchemaWithMessage(
312
- zodSchema,
313
- jsonSchema,
314
- "format",
315
- (zs, _, errorMsg) => zs.int(errorMsg)
316
- );
317
- }
318
- zodSchema = extendSchemaWithMessage(
319
- zodSchema,
320
- jsonSchema,
321
- "multipleOf",
322
- (zs, multipleOf, errorMsg) => {
323
- if (multipleOf === 1) {
324
- if (isInteger) return zs;
325
- return zs.int(errorMsg);
326
- }
327
- return zs.multipleOf(multipleOf, errorMsg);
328
- }
329
- );
330
- if (typeof jsonSchema.minimum === "number") {
331
- if (jsonSchema.exclusiveMinimum === true) {
332
- zodSchema = extendSchemaWithMessage(
333
- zodSchema,
334
- jsonSchema,
335
- "minimum",
336
- (zs, minimum, errorMsg) => zs.gt(minimum, errorMsg)
337
- );
338
- } else {
339
- zodSchema = extendSchemaWithMessage(
340
- zodSchema,
341
- jsonSchema,
342
- "minimum",
343
- (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg)
344
- );
345
- }
346
- } else if (typeof jsonSchema.exclusiveMinimum === "number") {
347
- zodSchema = extendSchemaWithMessage(
348
- zodSchema,
349
- jsonSchema,
350
- "exclusiveMinimum",
351
- (zs, exclusiveMinimum, errorMsg) => zs.gt(exclusiveMinimum, errorMsg)
352
- );
353
- }
354
- if (typeof jsonSchema.maximum === "number") {
355
- if (jsonSchema.exclusiveMaximum === true) {
356
- zodSchema = extendSchemaWithMessage(
357
- zodSchema,
358
- jsonSchema,
359
- "maximum",
360
- (zs, maximum, errorMsg) => zs.lt(maximum, errorMsg)
361
- );
362
- } else {
363
- zodSchema = extendSchemaWithMessage(
364
- zodSchema,
365
- jsonSchema,
366
- "maximum",
367
- (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg)
368
- );
369
- }
370
- } else if (typeof jsonSchema.exclusiveMaximum === "number") {
371
- zodSchema = extendSchemaWithMessage(
372
- zodSchema,
373
- jsonSchema,
374
- "exclusiveMaximum",
375
- (zs, exclusiveMaximum, errorMsg) => zs.lt(exclusiveMaximum, errorMsg)
376
- );
377
- }
378
- if (typeof jsonSchema.min === "number" && typeof jsonSchema.minimum !== "number") {
379
- zodSchema = extendSchemaWithMessage(
380
- zodSchema,
381
- { ...jsonSchema, minimum: jsonSchema.min },
382
- "minimum",
383
- (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg)
384
- );
385
- }
386
- if (typeof jsonSchema.max === "number" && typeof jsonSchema.maximum !== "number") {
387
- zodSchema = extendSchemaWithMessage(
388
- zodSchema,
389
- { ...jsonSchema, maximum: jsonSchema.max },
390
- "maximum",
391
- (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg)
392
- );
393
- }
394
- return zodSchema;
395
- };
396
-
397
- // src/parsers/parse-object.ts
398
- var z14 = __toESM(require("zod/v3"), 1);
399
-
400
- // src/parsers/parse-one-of.ts
401
- var import_v313 = require("zod/v3");
402
- var parseOneOf = (jsonSchema, refs) => {
403
- if (!jsonSchema.oneOf.length) {
404
- return import_v313.z.any();
405
- }
406
- if (jsonSchema.oneOf.length === 1) {
407
- return parseSchema(jsonSchema.oneOf[0], {
408
- ...refs,
409
- path: [...refs.path, "oneOf", 0]
410
- });
411
- }
412
- return import_v313.z.any().superRefine((x, ctx) => {
413
- const schemas = jsonSchema.oneOf.map(
414
- (schema, i) => parseSchema(schema, {
415
- ...refs,
416
- path: [...refs.path, "oneOf", i]
417
- })
418
- );
419
- const unionErrors = schemas.reduce(
420
- (errors, schema) => ((result) => result.error ? [...errors, result.error] : errors)(schema.safeParse(x)),
421
- []
422
- );
423
- if (schemas.length - unionErrors.length !== 1) {
424
- ctx.addIssue({
425
- path: ctx.path,
426
- code: "invalid_union",
427
- unionErrors,
428
- message: "Invalid input: Should pass single schema"
429
- });
430
- }
431
- });
432
- };
433
-
434
- // src/parsers/parse-object.ts
435
- function parseObjectProperties(objectSchema, refs) {
436
- if (!objectSchema.properties) {
437
- return z14.object({});
438
- }
439
- const propertyKeys = Object.keys(objectSchema.properties);
440
- if (propertyKeys.length === 0) {
441
- return z14.object({});
442
- }
443
- const properties = {};
444
- for (const key of propertyKeys) {
445
- const propJsonSchema = objectSchema.properties[key];
446
- const propZodSchema = parseSchema(propJsonSchema, {
447
- ...refs,
448
- path: [...refs.path, "properties", key]
449
- });
450
- const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
451
- if (!required && propJsonSchema && typeof propJsonSchema === "object" && "default" in propJsonSchema) {
452
- if (propJsonSchema.default === null) {
453
- const hasAnyOfWithNull = propJsonSchema.anyOf && Array.isArray(propJsonSchema.anyOf) && propJsonSchema.anyOf.some(
454
- (schema) => typeof schema === "object" && schema !== null && schema.type === "null"
455
- );
456
- const hasOneOfWithNull = propJsonSchema.oneOf && Array.isArray(propJsonSchema.oneOf) && propJsonSchema.oneOf.some(
457
- (schema) => typeof schema === "object" && schema !== null && schema.type === "null"
458
- );
459
- const isNullable = "nullable" in propJsonSchema && propJsonSchema.nullable === true;
460
- if (hasAnyOfWithNull || hasOneOfWithNull || isNullable) {
461
- properties[key] = propZodSchema.optional().default(null);
462
- } else {
463
- properties[key] = propZodSchema.nullable().optional().default(null);
464
- }
465
- } else {
466
- properties[key] = propZodSchema.optional().default(propJsonSchema.default);
467
- }
468
- } else {
469
- properties[key] = required ? propZodSchema : propZodSchema.optional();
470
- }
471
- }
472
- return z14.object(properties);
473
- }
474
- function parseObject(objectSchema, refs) {
475
- const hasPatternProperties = Object.keys(objectSchema.patternProperties ?? {}).length > 0;
476
- const normalizedSchema = objectSchema.type === "object" ? objectSchema : { ...objectSchema, type: "object" };
477
- const propertiesSchema = parseObjectProperties(normalizedSchema, refs);
478
- let zodSchema = propertiesSchema;
479
- const additionalProperties = normalizedSchema.additionalProperties !== void 0 ? parseSchema(normalizedSchema.additionalProperties, {
480
- ...refs,
481
- path: [...refs.path, "additionalProperties"]
482
- }) : void 0;
483
- const isAdditionalPropertiesTrue = normalizedSchema.additionalProperties === true;
484
- if (normalizedSchema.patternProperties) {
485
- const parsedPatternProperties = Object.fromEntries(
486
- Object.entries(normalizedSchema.patternProperties).map(([key, value]) => {
487
- return [
488
- key,
489
- parseSchema(value, {
490
- ...refs,
491
- path: [...refs.path, "patternProperties", key]
492
- })
493
- ];
494
- })
495
- );
496
- const patternPropertyValues = Object.values(parsedPatternProperties);
497
- if (propertiesSchema) {
498
- if (additionalProperties) {
499
- zodSchema = propertiesSchema.catchall(
500
- z14.union([...patternPropertyValues, additionalProperties])
501
- );
502
- } else if (Object.keys(parsedPatternProperties).length > 1) {
503
- zodSchema = propertiesSchema.catchall(
504
- z14.union(patternPropertyValues)
505
- );
506
- } else {
507
- zodSchema = propertiesSchema.catchall(patternPropertyValues[0]);
508
- }
509
- } else {
510
- if (additionalProperties) {
511
- zodSchema = z14.record(
512
- z14.union([...patternPropertyValues, additionalProperties])
513
- );
514
- } else if (patternPropertyValues.length > 1) {
515
- zodSchema = z14.record(z14.union(patternPropertyValues));
516
- } else {
517
- zodSchema = z14.record(patternPropertyValues[0]);
518
- }
519
- }
520
- const objectPropertyKeys = new Set(Object.keys(normalizedSchema.properties ?? {}));
521
- zodSchema = zodSchema.superRefine((value, ctx) => {
522
- for (const key in value) {
523
- let wasMatched = objectPropertyKeys.has(key);
524
- for (const patternPropertyKey in normalizedSchema.patternProperties) {
525
- const regex = new RegExp(patternPropertyKey);
526
- if (key.match(regex)) {
527
- wasMatched = true;
528
- const result = parsedPatternProperties[patternPropertyKey].safeParse(value[key]);
529
- if (!result.success) {
530
- ctx.addIssue({
531
- path: [...ctx.path, key],
532
- code: "custom",
533
- message: `Invalid input: Key matching regex /${key}/ must match schema`,
534
- params: {
535
- issues: result.error.issues
536
- }
537
- });
538
- }
539
- }
540
- }
541
- if (!wasMatched && additionalProperties) {
542
- const result = additionalProperties.safeParse(value[key]);
543
- if (!result.success) {
544
- ctx.addIssue({
545
- path: [...ctx.path, key],
546
- code: "custom",
547
- message: "Invalid input: must match catchall schema",
548
- params: {
549
- issues: result.error.issues
550
- }
551
- });
552
- }
553
- }
554
- }
555
- });
556
- }
557
- let output;
558
- if (propertiesSchema) {
559
- if (hasPatternProperties) {
560
- output = zodSchema;
561
- } else if (additionalProperties) {
562
- if (additionalProperties instanceof z14.ZodNever) {
563
- output = propertiesSchema.strict();
564
- } else if (isAdditionalPropertiesTrue) {
565
- output = propertiesSchema.passthrough();
566
- } else {
567
- output = propertiesSchema.catchall(additionalProperties);
568
- }
569
- } else {
570
- output = propertiesSchema.strict();
571
- }
572
- } else {
573
- if (hasPatternProperties) {
574
- output = zodSchema;
575
- } else if (additionalProperties) {
576
- if (additionalProperties instanceof z14.ZodNever) {
577
- output = z14.object({}).strict();
578
- } else if (isAdditionalPropertiesTrue) {
579
- output = z14.object({}).passthrough();
580
- } else {
581
- output = z14.record(additionalProperties);
582
- }
583
- } else {
584
- output = z14.object({}).passthrough();
585
- }
586
- }
587
- if (its.an.anyOf(objectSchema)) {
588
- output = output.and(
589
- parseAnyOf(
590
- {
591
- ...objectSchema,
592
- anyOf: objectSchema.anyOf.map(
593
- (x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? { ...x, type: "object" } : x
594
- )
595
- },
596
- refs
597
- )
598
- );
599
- }
600
- if (its.a.oneOf(objectSchema)) {
601
- output = output.and(
602
- parseOneOf(
603
- {
604
- ...objectSchema,
605
- oneOf: objectSchema.oneOf.map(
606
- (x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? { ...x, type: "object" } : x
607
- )
608
- },
609
- refs
610
- )
611
- );
612
- }
613
- if (its.an.allOf(objectSchema)) {
614
- output = output.and(
615
- parseAllOf(
616
- {
617
- ...objectSchema,
618
- allOf: objectSchema.allOf.map(
619
- (x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? { ...x, type: "object" } : x
620
- )
621
- },
622
- refs
623
- )
624
- );
625
- }
626
- return output;
627
- }
628
-
629
- // src/parsers/parse-string.ts
630
- var import_v314 = require("zod/v3");
631
- var parseString = (jsonSchema) => {
632
- let zodSchema = import_v314.z.string();
633
- zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, format, errorMsg) => {
634
- switch (format) {
635
- case "email":
636
- return zs.email(errorMsg);
637
- case "ip":
638
- return zs.ip(errorMsg);
639
- case "ipv4":
640
- return zs.ip({ version: "v4", message: errorMsg });
641
- case "ipv6":
642
- return zs.ip({ version: "v6", message: errorMsg });
643
- case "uri":
644
- return zs.url(errorMsg);
645
- case "uuid":
646
- return zs.uuid(errorMsg);
647
- case "date-time":
648
- return zs.datetime({ offset: true, message: errorMsg });
649
- case "time":
650
- return zs.time(errorMsg);
651
- case "date":
652
- return zs.date(errorMsg);
653
- case "binary":
654
- return zs.base64(errorMsg);
655
- case "duration":
656
- return zs.duration(errorMsg);
657
- default:
658
- return zs;
659
- }
660
- });
661
- zodSchema = extendSchemaWithMessage(
662
- zodSchema,
663
- jsonSchema,
664
- "contentEncoding",
665
- (zs, _, errorMsg) => zs.base64(errorMsg)
666
- );
667
- zodSchema = extendSchemaWithMessage(
668
- zodSchema,
669
- jsonSchema,
670
- "pattern",
671
- (zs, pattern, errorMsg) => zs.regex(new RegExp(pattern), errorMsg)
672
- );
673
- zodSchema = extendSchemaWithMessage(
674
- zodSchema,
675
- jsonSchema,
676
- "minLength",
677
- (zs, minLength, errorMsg) => zs.min(minLength, errorMsg)
678
- );
679
- zodSchema = extendSchemaWithMessage(
680
- zodSchema,
681
- jsonSchema,
682
- "maxLength",
683
- (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg)
684
- );
685
- if (typeof jsonSchema.min === "number" && typeof jsonSchema.minLength !== "number") {
686
- zodSchema = extendSchemaWithMessage(
687
- zodSchema,
688
- { ...jsonSchema, minLength: jsonSchema.min },
689
- "minLength",
690
- (zs, minLength, errorMsg) => zs.min(minLength, errorMsg)
691
- );
692
- }
693
- if (typeof jsonSchema.max === "number" && typeof jsonSchema.maxLength !== "number") {
694
- zodSchema = extendSchemaWithMessage(
695
- zodSchema,
696
- { ...jsonSchema, maxLength: jsonSchema.max },
697
- "maxLength",
698
- (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg)
699
- );
700
- }
701
- return zodSchema;
702
- };
703
-
704
- // src/parsers/parse-schema.ts
705
- var addDescribes = (jsonSchema, zodSchema) => {
706
- let description = "";
707
- if (jsonSchema.description) {
708
- description = jsonSchema.description;
709
- } else if (jsonSchema.title) {
710
- description = jsonSchema.title;
711
- }
712
- if (jsonSchema.example !== void 0) {
713
- const exampleText = `Example: ${JSON.stringify(jsonSchema.example)}`;
714
- description = description ? `${description}
715
- ${exampleText}` : exampleText;
716
- } else if (jsonSchema.examples !== void 0 && Array.isArray(jsonSchema.examples)) {
717
- const examples = jsonSchema.examples;
718
- if (examples && examples.length && examples.length > 0) {
719
- const exampleText = examples.length === 1 ? `Example: ${JSON.stringify(examples[0])}` : `Examples:
720
- ${examples.map((ex) => ` ${JSON.stringify(ex)}`).join("\n")}`;
721
- description = description ? `${description}
722
- ${exampleText}` : exampleText;
723
- }
724
- }
725
- if (description) {
726
- zodSchema = zodSchema.describe(description);
727
- }
728
- return zodSchema;
729
- };
730
- var addDefaults = (jsonSchema, zodSchema, refs) => {
731
- if (jsonSchema.default !== void 0) {
732
- if (jsonSchema.default === null) {
733
- const inAnyOfOrOneOf = refs?.path.some((segment) => segment === "anyOf" || segment === "oneOf");
734
- if (inAnyOfOrOneOf && jsonSchema.type && jsonSchema.type !== "null" && // @ts-ignore: `nullable` is not publicly available in Zod 4
735
- !jsonSchema.nullable) {
736
- return zodSchema;
737
- }
738
- }
739
- zodSchema = zodSchema.default(jsonSchema.default);
740
- }
741
- return zodSchema;
742
- };
743
- var addAnnotations = (jsonSchema, zodSchema) => {
744
- if (jsonSchema.readOnly) {
745
- zodSchema = zodSchema.readonly();
746
- }
747
- return zodSchema;
748
- };
749
- var selectParser = (schema, refs) => {
750
- if (its.a.nullable(schema)) {
751
- return parseNullable(schema, refs);
752
- } else if (its.an.object(schema)) {
753
- return parseObject(schema, refs);
754
- } else if (its.an.array(schema)) {
755
- return parseArray(schema, refs);
756
- } else if (its.an.anyOf(schema)) {
757
- return parseAnyOf(schema, refs);
758
- } else if (its.an.allOf(schema)) {
759
- return parseAllOf(schema, refs);
760
- } else if (its.a.oneOf(schema)) {
761
- return parseOneOf(schema, refs);
762
- } else if (its.a.not(schema)) {
763
- return parseNot(schema, refs);
764
- } else if (its.an.enum(schema)) {
765
- return parseEnum(schema);
766
- } else if (its.a.const(schema)) {
767
- return parseConst(schema);
768
- } else if (its.a.multipleType(schema)) {
769
- return parseMultipleType(schema, refs);
770
- } else if (its.a.primitive(schema, "string")) {
771
- return parseString(schema);
772
- } else if (its.a.primitive(schema, "number") || its.a.primitive(schema, "integer")) {
773
- return parseNumber(schema);
774
- } else if (its.a.primitive(schema, "boolean")) {
775
- return parseBoolean(schema);
776
- } else if (its.a.primitive(schema, "null")) {
777
- return parseNull(schema);
778
- } else if (its.a.conditional(schema)) {
779
- return parseIfThenElse(schema, refs);
780
- } else {
781
- return parseDefault(schema);
782
- }
783
- };
784
- var parseSchema = (jsonSchema, refs = { seen: /* @__PURE__ */ new Map(), path: [] }, blockMeta) => {
785
- if (typeof jsonSchema !== "object") return jsonSchema ? z16.any() : z16.never();
786
- if (refs.parserOverride) {
787
- const custom = refs.parserOverride(jsonSchema, refs);
788
- if (custom instanceof z16.ZodType) {
789
- return custom;
790
- }
791
- }
792
- let seen = refs.seen.get(jsonSchema);
793
- if (seen) {
794
- if (seen.r !== void 0) {
795
- return seen.r;
796
- }
797
- if (refs.depth === void 0 || seen.n >= refs.depth) {
798
- return z16.any();
799
- }
800
- seen.n += 1;
801
- } else {
802
- seen = { r: void 0, n: 0 };
803
- refs.seen.set(jsonSchema, seen);
804
- }
805
- let parsedZodSchema = selectParser(jsonSchema, refs);
806
- if (!blockMeta) {
807
- if (!refs.withoutDescribes) {
808
- parsedZodSchema = addDescribes(jsonSchema, parsedZodSchema);
809
- }
810
- if (!refs.withoutDefaults) {
811
- parsedZodSchema = addDefaults(jsonSchema, parsedZodSchema, refs);
812
- }
813
- parsedZodSchema = addAnnotations(jsonSchema, parsedZodSchema);
814
- }
815
- seen.r = parsedZodSchema;
816
- return parsedZodSchema;
817
- };
818
-
819
- // src/json-schema-to-zod.ts
820
- var jsonSchemaToZod = (schema, options = {}) => {
821
- return parseSchema(schema, {
822
- path: [],
823
- seen: /* @__PURE__ */ new Map(),
824
- ...options
825
- });
826
- };
827
- // Annotate the CommonJS export names for ESM import in node:
828
- 0 && (module.exports = {
829
- jsonSchemaToZod
830
- });