@amritk/adapters 0.2.5 → 0.2.6

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,676 +1,57 @@
1
- var __defProp = Object.defineProperty;
2
- var __returnValue = (v) => v;
3
- function __exportSetter(name, newValue) {
4
- this[name] = __returnValue.bind(null, newValue);
5
- }
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, {
9
- get: all[name],
10
- enumerable: true,
11
- configurable: true,
12
- set: __exportSetter.bind(all, name)
13
- });
14
- };
15
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
16
-
17
- // ../../node_modules/.bun/@valibot+to-json-schema@1.7.0+731820d9428d8f81/node_modules/@valibot/to-json-schema/dist/index.mjs
18
- var exports_dist = {};
19
- __export(exports_dist, {
20
- toStandardJsonSchema: () => toStandardJsonSchema,
21
- toJsonSchemaDefs: () => toJsonSchemaDefs,
22
- toJsonSchema: () => toJsonSchema,
23
- getGlobalDefs: () => getGlobalDefs,
24
- addGlobalDefs: () => addGlobalDefs
25
- });
26
- function addError(errors, message) {
27
- if (errors) {
28
- errors.push(message);
29
- return errors;
30
- }
31
- return [message];
32
- }
33
- function escapeRegExp(string) {
34
- return string.replace(ESCAPE_REGEX, "\\$&");
35
- }
36
- function handleError(message, config) {
37
- switch (config?.errorMode) {
38
- case "ignore":
39
- break;
40
- case "warn":
41
- console.warn(message);
42
- break;
43
- default:
44
- throw new Error(message);
45
- }
46
- }
47
- function isJsonConstValue(value) {
48
- return typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || typeof value === "string";
49
- }
50
- function isJsonEnumValues(values) {
51
- return values.every(isJsonConstValue);
52
- }
53
- function convertAction(jsonSchema, valibotAction, config) {
54
- if (config?.ignoreActions?.includes(valibotAction.type))
55
- return jsonSchema;
56
- let errors;
57
- switch (valibotAction.type) {
58
- case "base64":
59
- jsonSchema.contentEncoding = "base64";
60
- break;
61
- case "bic":
62
- case "cuid2":
63
- case "decimal":
64
- case "digits":
65
- case "domain":
66
- case "emoji":
67
- case "hash":
68
- case "hexadecimal":
69
- case "hex_color":
70
- case "isrc":
71
- case "iso_time_second":
72
- case "iso_week":
73
- case "mac":
74
- case "mac48":
75
- case "mac64":
76
- case "nanoid":
77
- case "octal":
78
- case "slug":
79
- case "ulid":
80
- if (jsonSchema.pattern)
81
- errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
82
- else
83
- jsonSchema.pattern = valibotAction.requirement.source;
84
- break;
85
- case "description":
86
- jsonSchema.description = valibotAction.description;
87
- break;
88
- case "email":
89
- case "rfc_email":
90
- jsonSchema.format = "email";
91
- break;
92
- case "ends_with":
93
- if (jsonSchema.pattern)
94
- errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
95
- else
96
- jsonSchema.pattern = `${escapeRegExp(valibotAction.requirement)}$`;
97
- break;
98
- case "empty":
99
- if (jsonSchema.type === "array")
100
- jsonSchema.maxItems = 0;
101
- else {
102
- if (jsonSchema.type !== "string")
103
- errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
104
- jsonSchema.maxLength = 0;
105
- }
106
- break;
107
- case "entries":
108
- jsonSchema.minProperties = valibotAction.requirement;
109
- jsonSchema.maxProperties = valibotAction.requirement;
110
- break;
111
- case "examples":
112
- if (Array.isArray(jsonSchema.examples))
113
- jsonSchema.examples = [...jsonSchema.examples, ...valibotAction.examples];
114
- else
115
- jsonSchema.examples = valibotAction.examples;
116
- break;
117
- case "gt_value":
118
- if (jsonSchema.type !== "number" && jsonSchema.type !== "integer")
119
- errors = addError(errors, `The "gt_value" action is not supported on type "${jsonSchema.type}".`);
120
- if (config?.target === "openapi-3.0") {
121
- errors = addError(errors, 'The "gt_value" action is not supported for OpenAPI 3.0.');
122
- break;
123
- }
124
- jsonSchema.exclusiveMinimum = valibotAction.requirement;
125
- break;
126
- case "includes":
127
- if (jsonSchema.pattern)
128
- errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
129
- else
130
- jsonSchema.pattern = escapeRegExp(valibotAction.requirement);
131
- break;
132
- case "integer":
133
- jsonSchema.type = "integer";
134
- break;
135
- case "ipv4":
136
- jsonSchema.format = "ipv4";
137
- break;
138
- case "ipv6":
139
- jsonSchema.format = "ipv6";
140
- break;
141
- case "iso_date":
142
- jsonSchema.format = "date";
143
- break;
144
- case "iso_date_time":
145
- case "iso_timestamp":
146
- jsonSchema.format = "date-time";
147
- break;
148
- case "iso_time":
149
- jsonSchema.format = "time";
150
- break;
151
- case "jws_compact":
152
- if (jsonSchema.pattern)
153
- errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
154
- else
155
- jsonSchema.pattern = valibotAction.requirement.source;
156
- break;
157
- case "length":
158
- if (jsonSchema.type === "array") {
159
- jsonSchema.minItems = valibotAction.requirement;
160
- jsonSchema.maxItems = valibotAction.requirement;
161
- } else {
162
- if (jsonSchema.type !== "string")
163
- errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
164
- jsonSchema.minLength = valibotAction.requirement;
165
- jsonSchema.maxLength = valibotAction.requirement;
166
- }
167
- break;
168
- case "lt_value":
169
- if (jsonSchema.type !== "number" && jsonSchema.type !== "integer")
170
- errors = addError(errors, `The "lt_value" action is not supported on type "${jsonSchema.type}".`);
171
- if (config?.target === "openapi-3.0") {
172
- errors = addError(errors, 'The "lt_value" action is not supported for OpenAPI 3.0.');
173
- break;
174
- }
175
- jsonSchema.exclusiveMaximum = valibotAction.requirement;
176
- break;
177
- case "max_entries":
178
- jsonSchema.maxProperties = valibotAction.requirement;
179
- break;
180
- case "max_length":
181
- if (jsonSchema.type === "array")
182
- jsonSchema.maxItems = valibotAction.requirement;
183
- else {
184
- if (jsonSchema.type !== "string")
185
- errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
186
- jsonSchema.maxLength = valibotAction.requirement;
187
- }
188
- break;
189
- case "max_value":
190
- if (jsonSchema.type !== "number" && jsonSchema.type !== "integer")
191
- errors = addError(errors, `The "max_value" action is not supported on type "${jsonSchema.type}".`);
192
- jsonSchema.maximum = valibotAction.requirement;
193
- break;
194
- case "metadata":
195
- if (typeof valibotAction.metadata.title === "string")
196
- jsonSchema.title = valibotAction.metadata.title;
197
- if (typeof valibotAction.metadata.description === "string")
198
- jsonSchema.description = valibotAction.metadata.description;
199
- if (Array.isArray(valibotAction.metadata.examples))
200
- if (Array.isArray(jsonSchema.examples))
201
- jsonSchema.examples = [...jsonSchema.examples, ...valibotAction.metadata.examples];
202
- else
203
- jsonSchema.examples = valibotAction.metadata.examples;
204
- break;
205
- case "min_entries":
206
- jsonSchema.minProperties = valibotAction.requirement;
207
- break;
208
- case "min_length":
209
- if (jsonSchema.type === "array")
210
- jsonSchema.minItems = valibotAction.requirement;
211
- else {
212
- if (jsonSchema.type !== "string")
213
- errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
214
- jsonSchema.minLength = valibotAction.requirement;
215
- }
216
- break;
217
- case "min_value":
218
- if (jsonSchema.type !== "number" && jsonSchema.type !== "integer")
219
- errors = addError(errors, `The "min_value" action is not supported on type "${jsonSchema.type}".`);
220
- jsonSchema.minimum = valibotAction.requirement;
221
- break;
222
- case "multiple_of":
223
- jsonSchema.multipleOf = valibotAction.requirement;
224
- break;
225
- case "non_empty":
226
- if (jsonSchema.type === "array")
227
- jsonSchema.minItems = 1;
228
- else {
229
- if (jsonSchema.type !== "string")
230
- errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`);
231
- jsonSchema.minLength = 1;
232
- }
233
- break;
234
- case "not_value":
235
- if (!isJsonConstValue(valibotAction.requirement)) {
236
- errors = addError(errors, 'The requirement of the "not_value" action is not JSON compatible.');
237
- break;
238
- }
239
- if (config?.target === "openapi-3.0")
240
- jsonSchema.not = { enum: [valibotAction.requirement] };
241
- else
242
- jsonSchema.not = { const: valibotAction.requirement };
243
- break;
244
- case "not_values":
245
- if (!isJsonEnumValues(valibotAction.requirement)) {
246
- errors = addError(errors, 'A requirement of the "not_values" action is not JSON compatible.');
247
- break;
248
- }
249
- jsonSchema.not = { enum: valibotAction.requirement };
250
- break;
251
- case "regex":
252
- if (valibotAction.requirement.flags)
253
- errors = addError(errors, "RegExp flags are not supported by JSON Schema.");
254
- if (jsonSchema.pattern)
255
- errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
256
- else
257
- jsonSchema.pattern = valibotAction.requirement.source;
258
- break;
259
- case "safe_integer":
260
- jsonSchema.type = "integer";
261
- if (typeof jsonSchema.minimum !== "number" || jsonSchema.minimum < Number.MIN_SAFE_INTEGER)
262
- jsonSchema.minimum = Number.MIN_SAFE_INTEGER;
263
- if (typeof jsonSchema.maximum !== "number" || jsonSchema.maximum > Number.MAX_SAFE_INTEGER)
264
- jsonSchema.maximum = Number.MAX_SAFE_INTEGER;
265
- break;
266
- case "starts_with":
267
- if (jsonSchema.pattern)
268
- errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`);
269
- else
270
- jsonSchema.pattern = `^${escapeRegExp(valibotAction.requirement)}`;
271
- break;
272
- case "title":
273
- jsonSchema.title = valibotAction.title;
274
- break;
275
- case "url":
276
- jsonSchema.format = "uri";
277
- break;
278
- case "uuid":
279
- jsonSchema.format = "uuid";
280
- break;
281
- case "value":
282
- if (!isJsonConstValue(valibotAction.requirement)) {
283
- errors = addError(errors, 'The requirement of the "value" action is not JSON compatible.');
284
- break;
285
- }
286
- if (config?.target === "openapi-3.0")
287
- jsonSchema.enum = [valibotAction.requirement];
288
- else
289
- jsonSchema.const = valibotAction.requirement;
290
- break;
291
- case "values":
292
- if (!isJsonEnumValues(valibotAction.requirement)) {
293
- errors = addError(errors, 'A requirement of the "values" action is not JSON compatible.');
294
- break;
295
- }
296
- jsonSchema.enum = valibotAction.requirement;
297
- break;
298
- default:
299
- errors = addError(errors, `The "${valibotAction.type}" action cannot be converted to JSON Schema.`);
300
- }
301
- if (config?.overrideAction) {
302
- const actionOverride = config.overrideAction({
303
- valibotAction,
304
- jsonSchema,
305
- errors
306
- });
307
- if (actionOverride)
308
- return { ...actionOverride };
309
- }
310
- if (errors)
311
- for (const message of errors)
312
- handleError(message, config);
313
- return jsonSchema;
314
- }
315
- function flattenPipe(pipe) {
316
- return pipe.flatMap((item) => ("pipe" in item) ? flattenPipe(item.pipe) : item);
317
- }
318
- function convertSchema(jsonSchema, valibotSchema, config, context, skipRef = false) {
319
- if (!skipRef) {
320
- const referenceId = context.referenceMap.get(valibotSchema);
321
- if (referenceId) {
322
- jsonSchema.$ref = `#/$defs/${referenceId}`;
323
- if (config?.overrideRef) {
324
- const refOverride = config.overrideRef({
325
- ...context,
326
- referenceId,
327
- valibotSchema,
328
- jsonSchema
329
- });
330
- if (refOverride)
331
- jsonSchema.$ref = refOverride;
332
- }
333
- return jsonSchema;
1
+ import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension';
2
+ /**
3
+ * Resolves `@valibot/to-json-schema`'s `toJsonSchema` from a runtime import,
4
+ * throwing a clear error when the converter is missing.
5
+ */
6
+ const loadToJsonSchema = async () => {
7
+ let mod;
8
+ try {
9
+ mod = (await import('@valibot/to-json-schema'));
334
10
  }
335
- }
336
- if ("pipe" in valibotSchema) {
337
- const flatPipe = flattenPipe(valibotSchema.pipe);
338
- let startIndex = 0;
339
- let stopIndex = flatPipe.length - 1;
340
- if (config?.typeMode === "input") {
341
- const inputStopIndex = flatPipe.slice(1).findIndex((item) => item.kind === "schema" || item.kind === "transformation" && (item.type === "find_item" || item.type === "parse_json" || item.type === "raw_transform" || item.type === "reduce_items" || item.type === "stringify_json" || item.type === "to_bigint" || item.type === "to_boolean" || item.type === "to_date" || item.type === "to_number" || item.type === "to_string" || item.type === "transform"));
342
- if (inputStopIndex !== -1)
343
- stopIndex = inputStopIndex;
344
- } else if (config?.typeMode === "output") {
345
- const outputStartIndex = flatPipe.findLastIndex((item) => item.kind === "schema");
346
- if (outputStartIndex !== -1)
347
- startIndex = outputStartIndex;
11
+ catch {
12
+ throw new Error("The Valibot adapter requires '@valibot/to-json-schema' (and 'valibot') to be installed in your project.");
348
13
  }
349
- for (let index = startIndex;index <= stopIndex; index++) {
350
- const valibotPipeItem = flatPipe[index];
351
- if (valibotPipeItem.kind === "schema") {
352
- if (index > startIndex)
353
- handleError('Set the "typeMode" config to "input" or "output" to convert pipelines with multiple schemas.', config);
354
- jsonSchema = convertSchema(jsonSchema, valibotPipeItem, config, context, true);
355
- } else
356
- jsonSchema = convertAction(jsonSchema, valibotPipeItem, config);
14
+ const named = mod['toJsonSchema'];
15
+ const fromDefault = mod['default']?.['toJsonSchema'];
16
+ const converter = typeof named === 'function' ? named : typeof fromDefault === 'function' ? fromDefault : undefined;
17
+ if (!converter) {
18
+ throw new Error("'@valibot/to-json-schema' did not export 'toJsonSchema'.");
357
19
  }
358
- return jsonSchema;
359
- }
360
- let errors;
361
- switch (valibotSchema.type) {
362
- case "boolean":
363
- jsonSchema.type = "boolean";
364
- break;
365
- case "null":
366
- if (config?.target === "openapi-3.0")
367
- jsonSchema.enum = [null];
368
- else
369
- jsonSchema.type = "null";
370
- break;
371
- case "number":
372
- jsonSchema.type = "number";
373
- break;
374
- case "string":
375
- jsonSchema.type = "string";
376
- break;
377
- case "array":
378
- jsonSchema.type = "array";
379
- jsonSchema.items = convertSchema({}, valibotSchema.item, config, context);
380
- break;
381
- case "tuple":
382
- case "tuple_with_rest":
383
- case "loose_tuple":
384
- case "strict_tuple":
385
- jsonSchema.type = "array";
386
- if (config?.target === "openapi-3.0") {
387
- jsonSchema.items = { anyOf: [] };
388
- jsonSchema.minItems = valibotSchema.items.length;
389
- for (const item of valibotSchema.items)
390
- jsonSchema.items.anyOf.push(convertSchema({}, item, config, context));
391
- if (valibotSchema.type === "tuple_with_rest")
392
- jsonSchema.items.anyOf.push(convertSchema({}, valibotSchema.rest, config, context));
393
- else if (valibotSchema.type === "strict_tuple" || valibotSchema.type === "tuple")
394
- jsonSchema.maxItems = valibotSchema.items.length;
395
- } else if (config?.target === "draft-2020-12") {
396
- jsonSchema.prefixItems = [];
397
- jsonSchema.minItems = valibotSchema.items.length;
398
- for (const item of valibotSchema.items)
399
- jsonSchema.prefixItems.push(convertSchema({}, item, config, context));
400
- if (valibotSchema.type === "tuple_with_rest")
401
- jsonSchema.items = convertSchema({}, valibotSchema.rest, config, context);
402
- else if (valibotSchema.type === "strict_tuple")
403
- jsonSchema.items = false;
404
- } else {
405
- jsonSchema.items = [];
406
- jsonSchema.minItems = valibotSchema.items.length;
407
- for (const item of valibotSchema.items)
408
- jsonSchema.items.push(convertSchema({}, item, config, context));
409
- if (valibotSchema.type === "tuple_with_rest")
410
- jsonSchema.additionalItems = convertSchema({}, valibotSchema.rest, config, context);
411
- else if (valibotSchema.type === "strict_tuple")
412
- jsonSchema.additionalItems = false;
413
- }
414
- break;
415
- case "object":
416
- case "object_with_rest":
417
- case "loose_object":
418
- case "strict_object":
419
- jsonSchema.type = "object";
420
- jsonSchema.properties = {};
421
- jsonSchema.required = [];
422
- for (const key in valibotSchema.entries) {
423
- const entry = valibotSchema.entries[key];
424
- jsonSchema.properties[key] = convertSchema({}, entry, config, context);
425
- if (entry.type !== "exact_optional" && entry.type !== "nullish" && entry.type !== "optional")
426
- jsonSchema.required.push(key);
427
- }
428
- if (valibotSchema.type === "object_with_rest")
429
- jsonSchema.additionalProperties = convertSchema({}, valibotSchema.rest, config, context);
430
- else if (valibotSchema.type === "strict_object")
431
- jsonSchema.additionalProperties = false;
432
- break;
433
- case "record":
434
- if (config?.target === "openapi-3.0" && "pipe" in valibotSchema.key)
435
- errors = addError(errors, 'The "record" schema with a schema for the key that contains a "pipe" cannot be converted to JSON Schema.');
436
- if (valibotSchema.key.type !== "string")
437
- errors = addError(errors, `The "record" schema with the "${valibotSchema.key.type}" schema for the key cannot be converted to JSON Schema.`);
438
- jsonSchema.type = "object";
439
- if (config?.target !== "openapi-3.0")
440
- jsonSchema.propertyNames = convertSchema({}, valibotSchema.key, config, context);
441
- jsonSchema.additionalProperties = convertSchema({}, valibotSchema.value, config, context);
442
- break;
443
- case "any":
444
- case "unknown":
445
- break;
446
- case "never":
447
- jsonSchema.not = {};
448
- break;
449
- case "nullable":
450
- case "nullish":
451
- if (config?.target === "openapi-3.0") {
452
- const innerSchema = convertSchema({}, valibotSchema.wrapped, config, context);
453
- Object.assign(jsonSchema, innerSchema);
454
- jsonSchema.nullable = true;
455
- } else
456
- jsonSchema.anyOf = [convertSchema({}, valibotSchema.wrapped, config, context), { type: "null" }];
457
- if (valibotSchema.default !== undefined)
458
- jsonSchema.default = typeof valibotSchema.default === "function" ? valibotSchema.default() : valibotSchema.default;
459
- break;
460
- case "exact_optional":
461
- case "optional":
462
- case "undefinedable":
463
- jsonSchema = convertSchema(jsonSchema, valibotSchema.wrapped, config, context);
464
- if (valibotSchema.default !== undefined)
465
- jsonSchema.default = typeof valibotSchema.default === "function" ? valibotSchema.default() : valibotSchema.default;
466
- break;
467
- case "literal":
468
- if (typeof valibotSchema.literal !== "boolean" && typeof valibotSchema.literal !== "number" && typeof valibotSchema.literal !== "string")
469
- errors = addError(errors, 'The value of the "literal" schema is not JSON compatible.');
470
- if (config?.target === "openapi-3.0")
471
- jsonSchema.enum = [valibotSchema.literal];
472
- else
473
- jsonSchema.const = valibotSchema.literal;
474
- break;
475
- case "enum":
476
- jsonSchema.enum = valibotSchema.options;
477
- if (valibotSchema.options.every((option) => typeof option === "string"))
478
- jsonSchema.type = "string";
479
- else if (valibotSchema.options.every((option) => typeof option === "number"))
480
- jsonSchema.type = "number";
481
- else if (config?.target !== "openapi-3.0")
482
- jsonSchema.type = ["string", "number"];
483
- break;
484
- case "picklist": {
485
- const hasInvalidOption = valibotSchema.options.some((option) => typeof option !== "number" && typeof option !== "string");
486
- if (hasInvalidOption)
487
- errors = addError(errors, 'An option of the "picklist" schema is not JSON compatible.');
488
- jsonSchema.enum = valibotSchema.options;
489
- if (valibotSchema.options.every((option) => typeof option === "string"))
490
- jsonSchema.type = "string";
491
- else if (valibotSchema.options.every((option) => typeof option === "number"))
492
- jsonSchema.type = "number";
493
- else if (!hasInvalidOption && config?.target !== "openapi-3.0")
494
- jsonSchema.type = ["string", "number"];
495
- break;
20
+ return converter;
21
+ };
22
+ /**
23
+ * Converts a Valibot schema into a Draft 2020-12 JSON Schema via
24
+ * `@valibot/to-json-schema`.
25
+ *
26
+ * Valibot's `date` schema has no JSON Schema representation and would otherwise
27
+ * throw, so we run with `errorMode: 'ignore'` (other unsupported constructs
28
+ * degrade to an open schema rather than failing the whole conversion) and use
29
+ * the `overrideSchema` hook to rewrite dates into the shared `x-mjst` instanceOf
30
+ * extension — the same handling TypeBox and Zod dates receive.
31
+ */
32
+ export const valibotToJsonSchema = async (source) => {
33
+ if (typeof source !== 'object' || source === null) {
34
+ const received = source === null ? 'null' : typeof source;
35
+ throw new Error(`Valibot adapter expected a Valibot schema but received ${received}.`);
496
36
  }
497
- case "union":
498
- jsonSchema.anyOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
499
- break;
500
- case "variant":
501
- jsonSchema.oneOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
502
- break;
503
- case "intersect":
504
- jsonSchema.allOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context));
505
- break;
506
- case "lazy": {
507
- let wrappedValibotSchema = context.getterMap.get(valibotSchema.getter);
508
- if (!wrappedValibotSchema) {
509
- wrappedValibotSchema = valibotSchema.getter(undefined);
510
- context.getterMap.set(valibotSchema.getter, wrappedValibotSchema);
511
- }
512
- let referenceId = context.referenceMap.get(wrappedValibotSchema);
513
- if (!referenceId) {
514
- referenceId = `${refCount++}`;
515
- context.referenceMap.set(wrappedValibotSchema, referenceId);
516
- context.definitions[referenceId] = convertSchema({}, wrappedValibotSchema, config, context, true);
517
- }
518
- jsonSchema.$ref = `#/$defs/${referenceId}`;
519
- if (config?.overrideRef) {
520
- const refOverride = config.overrideRef({
521
- ...context,
522
- referenceId,
523
- valibotSchema: wrappedValibotSchema,
524
- jsonSchema
37
+ const toJsonSchema = await loadToJsonSchema();
38
+ let json;
39
+ try {
40
+ json = toJsonSchema(source, {
41
+ errorMode: 'ignore',
42
+ overrideSchema: (ctx) => {
43
+ if (ctx.valibotSchema?.type === 'date')
44
+ return { [MJST_EXTENSION_KEY]: { instanceOf: 'Date' } };
45
+ if (ctx.valibotSchema?.type === 'bigint')
46
+ return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } };
47
+ return undefined;
48
+ },
525
49
  });
526
- if (refOverride)
527
- jsonSchema.$ref = refOverride;
528
- }
529
- break;
530
50
  }
531
- default:
532
- errors = addError(errors, `The "${valibotSchema.type}" schema cannot be converted to JSON Schema.`);
533
- }
534
- if (config?.overrideSchema) {
535
- const schemaOverride = config.overrideSchema({
536
- ...context,
537
- referenceId: context.referenceMap.get(valibotSchema),
538
- valibotSchema,
539
- jsonSchema,
540
- errors
541
- });
542
- if (schemaOverride)
543
- return { ...schemaOverride };
544
- }
545
- if (errors)
546
- for (const message of errors)
547
- handleError(message, config);
548
- return jsonSchema;
549
- }
550
- function addGlobalDefs(definitions) {
551
- store = {
552
- ...store ?? {},
553
- ...definitions
554
- };
555
- }
556
- function getGlobalDefs() {
557
- return store;
558
- }
559
- function toJsonSchema(schema, config) {
560
- const context = {
561
- definitions: {},
562
- referenceMap: /* @__PURE__ */ new Map,
563
- getterMap: /* @__PURE__ */ new Map
564
- };
565
- const definitions = config?.definitions ?? getGlobalDefs();
566
- if (definitions) {
567
- for (const key in definitions)
568
- context.referenceMap.set(definitions[key], key);
569
- for (const key in definitions)
570
- context.definitions[key] = convertSchema({}, definitions[key], config, context, true);
571
- }
572
- const jsonSchema = convertSchema({}, schema, config, context);
573
- const target = config?.target ?? "draft-07";
574
- if (target === "draft-2020-12")
575
- jsonSchema.$schema = "https://json-schema.org/draft/2020-12/schema";
576
- else if (target === "draft-07")
577
- jsonSchema.$schema = "http://json-schema.org/draft-07/schema#";
578
- if (context.referenceMap.size)
579
- jsonSchema.$defs = context.definitions;
580
- return jsonSchema;
581
- }
582
- function toJsonSchemaDefs(definitions, config) {
583
- const context = {
584
- definitions: {},
585
- referenceMap: /* @__PURE__ */ new Map,
586
- getterMap: /* @__PURE__ */ new Map
587
- };
588
- for (const key in definitions)
589
- context.referenceMap.set(definitions[key], key);
590
- for (const key in definitions)
591
- context.definitions[key] = convertSchema({}, definitions[key], config, context, true);
592
- return context.definitions;
593
- }
594
- function toStandardJsonSchema(schema) {
595
- return { "~standard": {
596
- ...schema["~standard"],
597
- jsonSchema: {
598
- input(options) {
599
- if (SUPPORTED_TARGETS.includes(options.target))
600
- return toJsonSchema(schema, {
601
- typeMode: "input",
602
- target: options.target,
603
- ...options.libraryOptions
604
- });
605
- throw new Error(`Unsupported target: ${options.target}`);
606
- },
607
- output(options) {
608
- if (SUPPORTED_TARGETS.includes(options.target))
609
- return toJsonSchema(schema, {
610
- typeMode: "output",
611
- target: options.target,
612
- ...options.libraryOptions
613
- });
614
- throw new Error(`Unsupported target: ${options.target}`);
615
- }
51
+ catch (error) {
52
+ throw new Error(`Valibot adapter failed to convert the schema. Is it a valid Valibot schema?\n${String(error)}`);
616
53
  }
617
- } };
618
- }
619
- var ESCAPE_REGEX, refCount = 0, store, SUPPORTED_TARGETS;
620
- var init_dist = __esm(() => {
621
- ESCAPE_REGEX = /[.*+?^${}()|[\]\\]/g;
622
- SUPPORTED_TARGETS = [
623
- "draft-07",
624
- "draft-2020-12",
625
- "openapi-3.0"
626
- ];
627
- });
628
-
629
- // ../helpers/dist/mjst-extension.js
630
- var MJST_EXTENSION_KEY = "x-mjst";
631
- var SUPPORTED_PRIMITIVES = new Set(["bigint"]);
632
-
633
- // src/valibot-to-json-schema.ts
634
- var loadToJsonSchema = async () => {
635
- let mod;
636
- try {
637
- mod = await Promise.resolve().then(() => (init_dist(), exports_dist));
638
- } catch {
639
- throw new Error("The Valibot adapter requires '@valibot/to-json-schema' (and 'valibot') to be installed in your project.");
640
- }
641
- const named = mod["toJsonSchema"];
642
- const fromDefault = mod["default"]?.["toJsonSchema"];
643
- const converter = typeof named === "function" ? named : typeof fromDefault === "function" ? fromDefault : undefined;
644
- if (!converter) {
645
- throw new Error("'@valibot/to-json-schema' did not export 'toJsonSchema'.");
646
- }
647
- return converter;
648
- };
649
- var valibotToJsonSchema = async (source) => {
650
- if (typeof source !== "object" || source === null) {
651
- const received = source === null ? "null" : typeof source;
652
- throw new Error(`Valibot adapter expected a Valibot schema but received ${received}.`);
653
- }
654
- const toJsonSchema2 = await loadToJsonSchema();
655
- let json;
656
- try {
657
- json = toJsonSchema2(source, {
658
- errorMode: "ignore",
659
- overrideSchema: (ctx) => {
660
- if (ctx.valibotSchema?.type === "date")
661
- return { [MJST_EXTENSION_KEY]: { instanceOf: "Date" } };
662
- if (ctx.valibotSchema?.type === "bigint")
663
- return { [MJST_EXTENSION_KEY]: { primitive: "bigint" } };
664
- return;
665
- }
666
- });
667
- } catch (error) {
668
- throw new Error(`Valibot adapter failed to convert the schema. Is it a valid Valibot schema?
669
- ${String(error)}`);
670
- }
671
- delete json["$schema"];
672
- return json;
673
- };
674
- export {
675
- valibotToJsonSchema
54
+ // Valibot emits a draft-07 dialect marker; the generators target 2020-12.
55
+ delete json['$schema'];
56
+ return json;
676
57
  };