@amritk/adapters 0.3.1 → 0.3.3
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/LICENSE +21 -0
- package/dist/effect-to-json-schema.js +91 -145
- package/dist/get-adapter.js +28 -34
- package/dist/normalize-tuples.js +42 -64
- package/dist/report-lossy-constructs.js +13 -32
- package/dist/typebox-to-json-schema.js +37 -65
- package/dist/valibot-to-json-schema.js +56 -86
- package/dist/zod-to-json-schema.js +145 -218
- package/package.json +3 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 amritk
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -1,156 +1,102 @@
|
|
|
1
|
-
import { MJST_EXTENSION_KEY } from
|
|
2
|
-
import { enforceTupleLength, normalizeDraftTuples } from
|
|
3
|
-
/**
|
|
4
|
-
* Resolves `effect`'s `JSONSchema.make` from a runtime import, throwing a clear
|
|
5
|
-
* error when it is missing.
|
|
6
|
-
*/
|
|
1
|
+
import { MJST_EXTENSION_KEY } from "@amritk/helpers/mjst-extension";
|
|
2
|
+
import { enforceTupleLength, normalizeDraftTuples } from "./normalize-tuples.js";
|
|
7
3
|
const loadMake = async () => {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
return make;
|
|
4
|
+
let mod;
|
|
5
|
+
try {
|
|
6
|
+
mod = await import("effect");
|
|
7
|
+
} catch {
|
|
8
|
+
throw new Error("The Effect adapter requires 'effect' to be installed in your project.");
|
|
9
|
+
}
|
|
10
|
+
const jsonSchema = mod["JSONSchema"];
|
|
11
|
+
const make = jsonSchema?.["make"];
|
|
12
|
+
if (typeof make !== "function") {
|
|
13
|
+
throw new Error("Effect's 'JSONSchema.make' was not found. The Effect adapter requires effect v3 or later.");
|
|
14
|
+
}
|
|
15
|
+
return make;
|
|
21
16
|
};
|
|
22
|
-
|
|
23
|
-
const IDENTIFIER_ANNOTATION = Symbol.for('effect/annotation/Identifier');
|
|
24
|
-
/** Reads `node.ast`, the AST that backs every Effect `Schema`. */
|
|
17
|
+
const IDENTIFIER_ANNOTATION = /* @__PURE__ */ Symbol.for("effect/annotation/Identifier");
|
|
25
18
|
const astOf = (source) => {
|
|
26
|
-
|
|
27
|
-
|
|
19
|
+
const ast = source?.ast;
|
|
20
|
+
return ast && typeof ast === "object" ? ast : void 0;
|
|
28
21
|
};
|
|
29
|
-
|
|
30
|
-
* Effect models `bigint` and a runtime `Date` as types with no JSON Schema
|
|
31
|
-
* representation, so `JSONSchema.make` throws — for a top-level value *and* for
|
|
32
|
-
* one buried inside a struct, array, or union. To stay consistent with the Zod,
|
|
33
|
-
* Valibot, and TypeBox adapters — which map those to the shared `x-mjst` hint —
|
|
34
|
-
* we rescue them wherever they appear: `bigint` (`BigIntKeyword`) →
|
|
35
|
-
* `primitive: 'bigint'`, and the `DateFromSelf` declaration → `instanceOf: 'Date'`.
|
|
36
|
-
*
|
|
37
|
-
* `Schema.Date` / `Schema.BigInt` decode from a string and already convert to a
|
|
38
|
-
* `string` schema, so they are untouched — the walk below hands any such
|
|
39
|
-
* fully-representable subtree straight to `make` and keeps its output verbatim.
|
|
40
|
-
*/
|
|
41
|
-
const isDateFromSelf = (ast) => ast._tag === 'Declaration' && ast.annotations?.[IDENTIFIER_ANNOTATION] === 'DateFromSelf';
|
|
42
|
-
// `make` stamps every schema with a dialect marker and hoists referenced types
|
|
43
|
-
// into a sibling `$defs`. When we convert a nested subtree in isolation we strip
|
|
44
|
-
// the marker and lift its `$defs` into the shared root map so `$ref`s (which use
|
|
45
|
-
// absolute `#/$defs/...` paths) still resolve once everything is reassembled.
|
|
22
|
+
const isDateFromSelf = (ast) => ast._tag === "Declaration" && ast.annotations?.[IDENTIFIER_ANNOTATION] === "DateFromSelf";
|
|
46
23
|
const hoistInto = (schema, rootDefs) => {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
24
|
+
delete schema["$schema"];
|
|
25
|
+
const defs = schema["$defs"];
|
|
26
|
+
if (defs && typeof defs === "object") {
|
|
27
|
+
Object.assign(rootDefs, defs);
|
|
28
|
+
delete schema["$defs"];
|
|
29
|
+
}
|
|
30
|
+
return schema;
|
|
54
31
|
};
|
|
55
|
-
/**
|
|
56
|
-
* Recursively converts an Effect AST into JSON Schema, rescuing nested
|
|
57
|
-
* unrepresentable leaves into `x-mjst` hints along the way.
|
|
58
|
-
*
|
|
59
|
-
* The strategy is to lean on `make` as much as possible: any subtree it can
|
|
60
|
-
* convert is representable, so we take its output verbatim. Only when `make`
|
|
61
|
-
* throws do we descend structurally — reconstructing the container (struct,
|
|
62
|
-
* array, union, ...) and recursing into its children — until we reach the
|
|
63
|
-
* bigint / `Date` leaf that has no JSON Schema form and rescue it.
|
|
64
|
-
*/
|
|
65
32
|
const walk = (make, ast, rootDefs) => {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
33
|
+
try {
|
|
34
|
+
return hoistInto(make({ ast }), rootDefs);
|
|
35
|
+
} catch {
|
|
36
|
+
}
|
|
37
|
+
if (ast._tag === "BigIntKeyword")
|
|
38
|
+
return { [MJST_EXTENSION_KEY]: { primitive: "bigint" } };
|
|
39
|
+
if (isDateFromSelf(ast))
|
|
40
|
+
return { [MJST_EXTENSION_KEY]: { instanceOf: "Date" } };
|
|
41
|
+
switch (ast._tag) {
|
|
42
|
+
case "TypeLiteral": {
|
|
43
|
+
const properties = {};
|
|
44
|
+
const required = [];
|
|
45
|
+
for (const ps of ast.propertySignatures ?? []) {
|
|
46
|
+
properties[ps.name] = walk(make, ps.type, rootDefs);
|
|
47
|
+
if (!ps.isOptional)
|
|
48
|
+
required.push(ps.name);
|
|
49
|
+
}
|
|
50
|
+
return { type: "object", required, properties, additionalProperties: false };
|
|
69
51
|
}
|
|
70
|
-
|
|
71
|
-
|
|
52
|
+
case "TupleType": {
|
|
53
|
+
const elements = ast.elements ?? [];
|
|
54
|
+
const rest = ast.rest ?? [];
|
|
55
|
+
const [firstRest] = rest;
|
|
56
|
+
if (elements.length === 0 && rest.length === 1 && firstRest) {
|
|
57
|
+
return { type: "array", items: walk(make, firstRest.type, rootDefs) };
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
type: "array",
|
|
61
|
+
minItems: elements.filter((e) => !e.isOptional).length,
|
|
62
|
+
items: elements.map((e) => walk(make, e.type, rootDefs)),
|
|
63
|
+
additionalItems: firstRest ? walk(make, firstRest.type, rootDefs) : false
|
|
64
|
+
};
|
|
72
65
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
case 'TupleType': {
|
|
89
|
-
const elements = ast.elements ?? [];
|
|
90
|
-
const rest = ast.rest ?? [];
|
|
91
|
-
const [firstRest] = rest;
|
|
92
|
-
// `Schema.Array(x)` is a tuple with no fixed elements and a single rest.
|
|
93
|
-
if (elements.length === 0 && rest.length === 1 && firstRest) {
|
|
94
|
-
return { type: 'array', items: walk(make, firstRest.type, rootDefs) };
|
|
95
|
-
}
|
|
96
|
-
return {
|
|
97
|
-
type: 'array',
|
|
98
|
-
minItems: elements.filter((e) => !e.isOptional).length,
|
|
99
|
-
items: elements.map((e) => walk(make, e.type, rootDefs)),
|
|
100
|
-
additionalItems: firstRest ? walk(make, firstRest.type, rootDefs) : false,
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
case 'Union':
|
|
104
|
-
return { anyOf: (ast.types ?? []).map((t) => walk(make, t, rootDefs)) };
|
|
105
|
-
// `Refinement` and `Transformation` describe the encoded value via `from`;
|
|
106
|
-
// `Suspend` defers to a thunk. Follow through to reach the wrapped subtree.
|
|
107
|
-
case 'Refinement':
|
|
108
|
-
case 'Transformation':
|
|
109
|
-
if (ast.from)
|
|
110
|
-
return walk(make, ast.from, rootDefs);
|
|
111
|
-
break;
|
|
112
|
-
case 'Suspend':
|
|
113
|
-
if (ast.f)
|
|
114
|
-
return walk(make, ast.f(), rootDefs);
|
|
115
|
-
break;
|
|
116
|
-
}
|
|
117
|
-
// A genuinely unrepresentable type we do not know how to rescue (e.g. a raw
|
|
118
|
-
// `symbol`). Point the user at the fix rather than Effect's opaque message.
|
|
119
|
-
throw new Error(`Effect adapter failed to convert the schema. A ${ast._tag ?? 'nested'} type has no JSON Schema ` +
|
|
120
|
-
`representation — replace it with a JSON-representable type, or add a \`jsonSchema\` annotation to that field.`);
|
|
66
|
+
case "Union":
|
|
67
|
+
return { anyOf: (ast.types ?? []).map((t) => walk(make, t, rootDefs)) };
|
|
68
|
+
// `Refinement` and `Transformation` describe the encoded value via `from`;
|
|
69
|
+
// `Suspend` defers to a thunk. Follow through to reach the wrapped subtree.
|
|
70
|
+
case "Refinement":
|
|
71
|
+
case "Transformation":
|
|
72
|
+
if (ast.from)
|
|
73
|
+
return walk(make, ast.from, rootDefs);
|
|
74
|
+
break;
|
|
75
|
+
case "Suspend":
|
|
76
|
+
if (ast.f)
|
|
77
|
+
return walk(make, ast.f(), rootDefs);
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
throw new Error(`Effect adapter failed to convert the schema. A ${ast._tag ?? "nested"} type has no JSON Schema representation \u2014 replace it with a JSON-representable type, or add a \`jsonSchema\` annotation to that field.`);
|
|
121
81
|
};
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
}
|
|
143
|
-
const make = await loadMake();
|
|
144
|
-
const rootDefs = {};
|
|
145
|
-
const json = walk(make, ast, rootDefs);
|
|
146
|
-
// Reattach the hoisted definitions once the whole tree is assembled.
|
|
147
|
-
if (Object.keys(rootDefs).length > 0)
|
|
148
|
-
json['$defs'] = rootDefs;
|
|
149
|
-
// `JSONSchema.make` (and the structural rescue path) emit fixed tuples in
|
|
150
|
-
// draft-07 form (`items: [...]` + `additionalItems`), which the generators do
|
|
151
|
-
// not recognize as a tuple — element types and length would go unvalidated.
|
|
152
|
-
// Normalize to 2020-12 `prefixItems`, then restore the length bound.
|
|
153
|
-
normalizeDraftTuples(json);
|
|
154
|
-
enforceTupleLength(json);
|
|
155
|
-
return json;
|
|
82
|
+
const effectToJsonSchema = async (source) => {
|
|
83
|
+
if (typeof source !== "object" && typeof source !== "function" || source === null) {
|
|
84
|
+
const received = source === null ? "null" : typeof source;
|
|
85
|
+
throw new Error(`Effect adapter expected an Effect Schema but received ${received}.`);
|
|
86
|
+
}
|
|
87
|
+
const ast = astOf(source);
|
|
88
|
+
if (!ast) {
|
|
89
|
+
throw new Error("Effect adapter expected an Effect Schema but the value has no `ast` property.");
|
|
90
|
+
}
|
|
91
|
+
const make = await loadMake();
|
|
92
|
+
const rootDefs = {};
|
|
93
|
+
const json = walk(make, ast, rootDefs);
|
|
94
|
+
if (Object.keys(rootDefs).length > 0)
|
|
95
|
+
json["$defs"] = rootDefs;
|
|
96
|
+
normalizeDraftTuples(json);
|
|
97
|
+
enforceTupleLength(json);
|
|
98
|
+
return json;
|
|
99
|
+
};
|
|
100
|
+
export {
|
|
101
|
+
effectToJsonSchema
|
|
156
102
|
};
|
package/dist/get-adapter.js
CHANGED
|
@@ -1,43 +1,37 @@
|
|
|
1
|
-
import { effectToJsonSchema } from
|
|
2
|
-
import { typeboxToJsonSchema } from
|
|
3
|
-
import { valibotToJsonSchema } from
|
|
4
|
-
import { zodToJsonSchema } from
|
|
1
|
+
import { effectToJsonSchema } from "./effect-to-json-schema.js";
|
|
2
|
+
import { typeboxToJsonSchema } from "./typebox-to-json-schema.js";
|
|
3
|
+
import { valibotToJsonSchema } from "./valibot-to-json-schema.js";
|
|
4
|
+
import { zodToJsonSchema } from "./zod-to-json-schema.js";
|
|
5
5
|
const typeboxAdapter = {
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
format: "typebox",
|
|
7
|
+
toJSONSchema: typeboxToJsonSchema
|
|
8
8
|
};
|
|
9
9
|
const zodAdapter = {
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
format: "zod",
|
|
11
|
+
toJSONSchema: zodToJsonSchema
|
|
12
12
|
};
|
|
13
13
|
const valibotAdapter = {
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
format: "valibot",
|
|
15
|
+
toJSONSchema: valibotToJsonSchema
|
|
16
16
|
};
|
|
17
17
|
const effectAdapter = {
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
format: "effect",
|
|
19
|
+
toJSONSchema: effectToJsonSchema
|
|
20
20
|
};
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
case 'effect':
|
|
38
|
-
return effectAdapter;
|
|
39
|
-
default:
|
|
40
|
-
throw new Error(`No adapter is available for input format '${format}'. ` +
|
|
41
|
-
`Supported: 'typebox', 'zod', 'valibot', 'effect'. Use --input json for plain JSON Schema files.`);
|
|
42
|
-
}
|
|
21
|
+
const getAdapter = (format) => {
|
|
22
|
+
switch (format) {
|
|
23
|
+
case "typebox":
|
|
24
|
+
return typeboxAdapter;
|
|
25
|
+
case "zod":
|
|
26
|
+
return zodAdapter;
|
|
27
|
+
case "valibot":
|
|
28
|
+
return valibotAdapter;
|
|
29
|
+
case "effect":
|
|
30
|
+
return effectAdapter;
|
|
31
|
+
default:
|
|
32
|
+
throw new Error(`No adapter is available for input format '${format}'. Supported: 'typebox', 'zod', 'valibot', 'effect'. Use --input json for plain JSON Schema files.`);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
export {
|
|
36
|
+
getAdapter
|
|
43
37
|
};
|
package/dist/normalize-tuples.js
CHANGED
|
@@ -1,67 +1,45 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
if (Array.isArray(node)) {
|
|
18
|
-
for (const item of node)
|
|
19
|
-
normalizeDraftTuples(item);
|
|
20
|
-
return;
|
|
1
|
+
const normalizeDraftTuples = (node) => {
|
|
2
|
+
if (node === null || typeof node !== "object")
|
|
3
|
+
return;
|
|
4
|
+
if (Array.isArray(node)) {
|
|
5
|
+
for (const item of node)
|
|
6
|
+
normalizeDraftTuples(item);
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
const obj = node;
|
|
10
|
+
if (Array.isArray(obj["items"])) {
|
|
11
|
+
obj["prefixItems"] = obj["items"];
|
|
12
|
+
if ("additionalItems" in obj) {
|
|
13
|
+
obj["items"] = obj["additionalItems"];
|
|
14
|
+
delete obj["additionalItems"];
|
|
15
|
+
} else {
|
|
16
|
+
delete obj["items"];
|
|
21
17
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
if ('additionalItems' in obj) {
|
|
26
|
-
// A rest element — its schema (or `false`) becomes `items`.
|
|
27
|
-
obj['items'] = obj['additionalItems'];
|
|
28
|
-
delete obj['additionalItems'];
|
|
29
|
-
}
|
|
30
|
-
else {
|
|
31
|
-
// No rest element: drop `items` so `enforceTupleLength` forbids extras.
|
|
32
|
-
delete obj['items'];
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
for (const value of Object.values(obj))
|
|
36
|
-
normalizeDraftTuples(value);
|
|
18
|
+
}
|
|
19
|
+
for (const value of Object.values(obj))
|
|
20
|
+
normalizeDraftTuples(value);
|
|
37
21
|
};
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
// fixed tuple, so forbid additional items.
|
|
62
|
-
if (!('items' in obj))
|
|
63
|
-
obj['items'] = false;
|
|
64
|
-
}
|
|
65
|
-
for (const value of Object.values(obj))
|
|
66
|
-
enforceTupleLength(value);
|
|
22
|
+
const enforceTupleLength = (node) => {
|
|
23
|
+
if (node === null || typeof node !== "object")
|
|
24
|
+
return;
|
|
25
|
+
if (Array.isArray(node)) {
|
|
26
|
+
for (const item of node)
|
|
27
|
+
enforceTupleLength(item);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const obj = node;
|
|
31
|
+
if (Array.isArray(obj["prefixItems"])) {
|
|
32
|
+
const fixed = obj["prefixItems"].length;
|
|
33
|
+
const min = typeof obj["minItems"] === "number" ? obj["minItems"] : 0;
|
|
34
|
+
if (min < fixed)
|
|
35
|
+
obj["minItems"] = fixed;
|
|
36
|
+
if (!("items" in obj))
|
|
37
|
+
obj["items"] = false;
|
|
38
|
+
}
|
|
39
|
+
for (const value of Object.values(obj))
|
|
40
|
+
enforceTupleLength(value);
|
|
41
|
+
};
|
|
42
|
+
export {
|
|
43
|
+
enforceTupleLength,
|
|
44
|
+
normalizeDraftTuples
|
|
67
45
|
};
|
|
@@ -1,33 +1,14 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
* construct, so the loss is visible in one line instead of silent or scattered.
|
|
15
|
-
* - Strict: throws instead, refusing to hand back a type that is wider than the
|
|
16
|
-
* source schema.
|
|
17
|
-
*
|
|
18
|
-
* Does nothing when no constructs were widened, so callers can invoke it
|
|
19
|
-
* unconditionally after a conversion.
|
|
20
|
-
*/
|
|
21
|
-
export const reportLossyConstructs = (adapter, constructs, strict) => {
|
|
22
|
-
if (constructs.size === 0)
|
|
23
|
-
return;
|
|
24
|
-
const list = [...constructs].sort().join(', ');
|
|
25
|
-
const plural = constructs.size !== 1;
|
|
26
|
-
const detail = `${list} ${plural ? 'have' : 'has'} no full JSON Schema representation and ${plural ? 'were' : 'was'} ` +
|
|
27
|
-
`widened. The generated type will be wider than the ${adapter} schema.`;
|
|
28
|
-
if (strict) {
|
|
29
|
-
throw new Error(`[mjst] ${adapter} adapter (strict mode): ${detail} ` +
|
|
30
|
-
'Remove the unsupported construct(s) from the schema, or disable strict mode to widen and warn instead.');
|
|
31
|
-
}
|
|
32
|
-
console.warn(`[mjst] ${adapter} adapter: ${detail}`);
|
|
1
|
+
const reportLossyConstructs = (adapter, constructs, strict) => {
|
|
2
|
+
if (constructs.size === 0)
|
|
3
|
+
return;
|
|
4
|
+
const list = [...constructs].sort().join(", ");
|
|
5
|
+
const plural = constructs.size !== 1;
|
|
6
|
+
const detail = `${list} ${plural ? "have" : "has"} no full JSON Schema representation and ${plural ? "were" : "was"} widened. The generated type will be wider than the ${adapter} schema.`;
|
|
7
|
+
if (strict) {
|
|
8
|
+
throw new Error(`[mjst] ${adapter} adapter (strict mode): ${detail} Remove the unsupported construct(s) from the schema, or disable strict mode to widen and warn instead.`);
|
|
9
|
+
}
|
|
10
|
+
console.warn(`[mjst] ${adapter} adapter: ${detail}`);
|
|
11
|
+
};
|
|
12
|
+
export {
|
|
13
|
+
reportLossyConstructs
|
|
33
14
|
};
|
|
@@ -1,73 +1,45 @@
|
|
|
1
|
-
import { MJST_EXTENSION_KEY } from
|
|
2
|
-
|
|
3
|
-
// TypeBox extended type with no native JSON Schema equivalent.
|
|
4
|
-
const JSON_SCHEMA_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'object', 'array', 'null']);
|
|
5
|
-
// Maps a TypeBox extended `type` string to the runtime class an `x-mjst`
|
|
6
|
-
// instanceOf hint should reference. Add entries here as more extended types
|
|
7
|
-
// gain generator support.
|
|
1
|
+
import { MJST_EXTENSION_KEY } from "@amritk/helpers/mjst-extension";
|
|
2
|
+
const JSON_SCHEMA_TYPES = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "object", "array", "null"]);
|
|
8
3
|
const EXTENDED_TYPE_TO_INSTANCE = {
|
|
9
|
-
|
|
4
|
+
Date: "Date"
|
|
10
5
|
};
|
|
11
|
-
// Maps a TypeBox extended `type` string to a non-JSON `x-mjst` primitive hint
|
|
12
|
-
// (e.g. Type.BigInt() emits `{ type: 'bigint' }`).
|
|
13
6
|
const EXTENDED_TYPE_TO_PRIMITIVE = {
|
|
14
|
-
|
|
7
|
+
bigint: "bigint"
|
|
15
8
|
};
|
|
16
|
-
/**
|
|
17
|
-
* Recursively rewrites TypeBox extended types into an `x-mjst` instanceOf hint.
|
|
18
|
-
*
|
|
19
|
-
* TypeBox emits non-standard `type` strings for runtime classes (e.g.
|
|
20
|
-
* `Type.Date()` produces `{ type: 'Date' }`). We drop the bogus `type` and
|
|
21
|
-
* record the class under `x-mjst` so the generators can emit the right
|
|
22
|
-
* TypeScript type and `instanceof` checks. Extended types we do not yet map are
|
|
23
|
-
* left untouched with a warning, preserving a permissive best-effort fallback.
|
|
24
|
-
*/
|
|
25
9
|
const rewriteExtendedTypes = (value) => {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
10
|
+
if (Array.isArray(value))
|
|
11
|
+
return value.map(rewriteExtendedTypes);
|
|
12
|
+
if (typeof value !== "object" || value === null)
|
|
13
|
+
return value;
|
|
14
|
+
const source = value;
|
|
15
|
+
const result = {};
|
|
16
|
+
for (const [key, val] of Object.entries(source)) {
|
|
17
|
+
result[key] = rewriteExtendedTypes(val);
|
|
18
|
+
}
|
|
19
|
+
const type = result["type"];
|
|
20
|
+
if (typeof type === "string" && !JSON_SCHEMA_TYPES.has(type)) {
|
|
21
|
+
const primitive = EXTENDED_TYPE_TO_PRIMITIVE[type];
|
|
22
|
+
const instanceOf = EXTENDED_TYPE_TO_INSTANCE[type];
|
|
23
|
+
if (primitive) {
|
|
24
|
+
delete result["type"];
|
|
25
|
+
result[MJST_EXTENSION_KEY] = { primitive };
|
|
26
|
+
} else if (instanceOf) {
|
|
27
|
+
delete result["type"];
|
|
28
|
+
result[MJST_EXTENSION_KEY] = { instanceOf };
|
|
29
|
+
} else {
|
|
30
|
+
console.warn(`[mjst] TypeBox type '${type}' has no JSON Schema or x-mjst mapping; leaving it unchanged.`);
|
|
34
31
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const primitive = EXTENDED_TYPE_TO_PRIMITIVE[type];
|
|
38
|
-
const instanceOf = EXTENDED_TYPE_TO_INSTANCE[type];
|
|
39
|
-
if (primitive) {
|
|
40
|
-
delete result['type'];
|
|
41
|
-
result[MJST_EXTENSION_KEY] = { primitive };
|
|
42
|
-
}
|
|
43
|
-
else if (instanceOf) {
|
|
44
|
-
delete result['type'];
|
|
45
|
-
result[MJST_EXTENSION_KEY] = { instanceOf };
|
|
46
|
-
}
|
|
47
|
-
else {
|
|
48
|
-
console.warn(`[mjst] TypeBox type '${type}' has no JSON Schema or x-mjst mapping; leaving it unchanged.`);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
return result;
|
|
32
|
+
}
|
|
33
|
+
return result;
|
|
52
34
|
};
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
*/
|
|
64
|
-
export const typeboxToJsonSchema = (source) => {
|
|
65
|
-
if (typeof source !== 'object' || source === null) {
|
|
66
|
-
const received = source === null ? 'null' : typeof source;
|
|
67
|
-
throw new Error(`TypeBox adapter expected a schema object but received ${received}.`);
|
|
68
|
-
}
|
|
69
|
-
// Boundary cast: JSON.parse yields `unknown`, and the round-tripped, rewritten
|
|
70
|
-
// TypeBox schema is a valid JSON Schema by construction.
|
|
71
|
-
const sanitized = JSON.parse(JSON.stringify(source));
|
|
72
|
-
return rewriteExtendedTypes(sanitized);
|
|
35
|
+
const typeboxToJsonSchema = (source) => {
|
|
36
|
+
if (typeof source !== "object" || source === null) {
|
|
37
|
+
const received = source === null ? "null" : typeof source;
|
|
38
|
+
throw new Error(`TypeBox adapter expected a schema object but received ${received}.`);
|
|
39
|
+
}
|
|
40
|
+
const sanitized = JSON.parse(JSON.stringify(source));
|
|
41
|
+
return rewriteExtendedTypes(sanitized);
|
|
42
|
+
};
|
|
43
|
+
export {
|
|
44
|
+
typeboxToJsonSchema
|
|
73
45
|
};
|
|
@@ -1,89 +1,59 @@
|
|
|
1
|
-
import { MJST_EXTENSION_KEY } from
|
|
2
|
-
import { reportLossyConstructs } from
|
|
3
|
-
/**
|
|
4
|
-
* Resolves `@valibot/to-json-schema`'s `toJsonSchema` from a runtime import,
|
|
5
|
-
* throwing a clear error when the converter is missing.
|
|
6
|
-
*/
|
|
1
|
+
import { MJST_EXTENSION_KEY } from "@amritk/helpers/mjst-extension";
|
|
2
|
+
import { reportLossyConstructs } from "./report-lossy-constructs.js";
|
|
7
3
|
const loadToJsonSchema = async () => {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
return converter;
|
|
4
|
+
let mod;
|
|
5
|
+
try {
|
|
6
|
+
mod = await import("@valibot/to-json-schema");
|
|
7
|
+
} catch {
|
|
8
|
+
throw new Error("The Valibot adapter requires '@valibot/to-json-schema' (and 'valibot') to be installed in your project.");
|
|
9
|
+
}
|
|
10
|
+
const named = mod["toJsonSchema"];
|
|
11
|
+
const fromDefault = mod["default"]?.["toJsonSchema"];
|
|
12
|
+
const converter = typeof named === "function" ? named : typeof fromDefault === "function" ? fromDefault : void 0;
|
|
13
|
+
if (!converter) {
|
|
14
|
+
throw new Error("'@valibot/to-json-schema' did not export 'toJsonSchema'.");
|
|
15
|
+
}
|
|
16
|
+
return converter;
|
|
22
17
|
};
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if (ctx.valibotSchema?.type === 'bigint')
|
|
65
|
-
return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } };
|
|
66
|
-
if (ctx.errors && ctx.valibotSchema?.type)
|
|
67
|
-
droppedConstructs.add(ctx.valibotSchema.type);
|
|
68
|
-
return undefined;
|
|
69
|
-
},
|
|
70
|
-
overrideAction: (ctx) => {
|
|
71
|
-
// A dropped refinement (e.g. a regex flag JSON Schema cannot express)
|
|
72
|
-
// also widens the result, so it belongs in the same report.
|
|
73
|
-
if (ctx.errors && ctx.valibotAction?.type)
|
|
74
|
-
droppedConstructs.add(ctx.valibotAction.type);
|
|
75
|
-
return undefined;
|
|
76
|
-
},
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
catch (error) {
|
|
80
|
-
throw new Error(`Valibot adapter failed to convert the schema. Is it a valid Valibot schema?\n${String(error)}`);
|
|
81
|
-
}
|
|
82
|
-
// Surface everything that widened in one batched, branded notice (or throw in
|
|
83
|
-
// strict mode).
|
|
84
|
-
reportLossyConstructs('Valibot', droppedConstructs, options?.strict);
|
|
85
|
-
// Drop the dialect marker the converter emits; the generators infer the
|
|
86
|
-
// dialect from structure, not `$schema`.
|
|
87
|
-
delete json['$schema'];
|
|
88
|
-
return json;
|
|
18
|
+
const valibotToJsonSchema = async (source, options) => {
|
|
19
|
+
if (typeof source !== "object" || source === null) {
|
|
20
|
+
const received = source === null ? "null" : typeof source;
|
|
21
|
+
throw new Error(`Valibot adapter expected a Valibot schema but received ${received}.`);
|
|
22
|
+
}
|
|
23
|
+
const toJsonSchema = await loadToJsonSchema();
|
|
24
|
+
const droppedConstructs = /* @__PURE__ */ new Set();
|
|
25
|
+
let json;
|
|
26
|
+
try {
|
|
27
|
+
json = toJsonSchema(source, {
|
|
28
|
+
errorMode: "ignore",
|
|
29
|
+
// The converter defaults to draft-07, which emits fixed tuples as
|
|
30
|
+
// `items: [...]`; the generators key tuple validation off 2020-12
|
|
31
|
+
// `prefixItems`, so a draft-07 tuple would be silently under-validated
|
|
32
|
+
// (element types and length unchecked). Target 2020-12 explicitly.
|
|
33
|
+
target: "draft-2020-12",
|
|
34
|
+
overrideSchema: (ctx) => {
|
|
35
|
+
if (ctx.valibotSchema?.type === "date")
|
|
36
|
+
return { [MJST_EXTENSION_KEY]: { instanceOf: "Date" } };
|
|
37
|
+
if (ctx.valibotSchema?.type === "bigint")
|
|
38
|
+
return { [MJST_EXTENSION_KEY]: { primitive: "bigint" } };
|
|
39
|
+
if (ctx.errors && ctx.valibotSchema?.type)
|
|
40
|
+
droppedConstructs.add(ctx.valibotSchema.type);
|
|
41
|
+
return void 0;
|
|
42
|
+
},
|
|
43
|
+
overrideAction: (ctx) => {
|
|
44
|
+
if (ctx.errors && ctx.valibotAction?.type)
|
|
45
|
+
droppedConstructs.add(ctx.valibotAction.type);
|
|
46
|
+
return void 0;
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
} catch (error) {
|
|
50
|
+
throw new Error(`Valibot adapter failed to convert the schema. Is it a valid Valibot schema?
|
|
51
|
+
${String(error)}`);
|
|
52
|
+
}
|
|
53
|
+
reportLossyConstructs("Valibot", droppedConstructs, options?.strict);
|
|
54
|
+
delete json["$schema"];
|
|
55
|
+
return json;
|
|
56
|
+
};
|
|
57
|
+
export {
|
|
58
|
+
valibotToJsonSchema
|
|
89
59
|
};
|
|
@@ -1,236 +1,163 @@
|
|
|
1
|
-
import { MJST_EXTENSION_KEY } from
|
|
2
|
-
import { enforceTupleLength, normalizeDraftTuples } from
|
|
3
|
-
import { reportLossyConstructs } from
|
|
4
|
-
|
|
5
|
-
// (`{}`) — the same widening the Zod 4 path performs with `unrepresentable:
|
|
6
|
-
// 'any'`. Reported through a warning so the loss is never silent. The Zod 4
|
|
7
|
-
// path keys these by Zod's lowercase type name; the fallback keys them by Zod
|
|
8
|
-
// 3's `ZodFirstPartyTypeKind`, mapped here to the same friendly labels.
|
|
9
|
-
const LOSSY_TYPES = new Set(['symbol', 'nan', 'void', 'undefined', 'never', 'map', 'set', 'promise', 'function']);
|
|
1
|
+
import { MJST_EXTENSION_KEY } from "@amritk/helpers/mjst-extension";
|
|
2
|
+
import { enforceTupleLength, normalizeDraftTuples } from "./normalize-tuples.js";
|
|
3
|
+
import { reportLossyConstructs } from "./report-lossy-constructs.js";
|
|
4
|
+
const LOSSY_TYPES = /* @__PURE__ */ new Set(["symbol", "nan", "void", "undefined", "never", "map", "set", "promise", "function"]);
|
|
10
5
|
const LOSSY_TYPENAMES = {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
6
|
+
ZodSymbol: "symbol",
|
|
7
|
+
ZodNaN: "nan",
|
|
8
|
+
ZodVoid: "void",
|
|
9
|
+
ZodUndefined: "undefined",
|
|
10
|
+
ZodNever: "never",
|
|
11
|
+
ZodMap: "map",
|
|
12
|
+
ZodSet: "set",
|
|
13
|
+
ZodPromise: "promise",
|
|
14
|
+
ZodFunction: "function"
|
|
20
15
|
};
|
|
21
|
-
/**
|
|
22
|
-
* Resolves Zod's `toJSONSchema` from a runtime import, tolerating both the
|
|
23
|
-
* named export (`import { toJSONSchema }`) and the `z` namespace
|
|
24
|
-
* (`z.toJSONSchema`). Returns `null` when Zod is missing or too old (Zod 3 has
|
|
25
|
-
* no `toJSONSchema`) so the caller can fall back to `zod-to-json-schema`.
|
|
26
|
-
*/
|
|
27
16
|
const loadToJsonSchema = async () => {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
return converter ? converter : null;
|
|
17
|
+
let mod;
|
|
18
|
+
try {
|
|
19
|
+
mod = await import("zod");
|
|
20
|
+
} catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
const named = mod["toJSONSchema"];
|
|
24
|
+
const namespace = mod["z"] ?? mod["default"] ?? mod;
|
|
25
|
+
const fromNamespace = namespace?.["toJSONSchema"];
|
|
26
|
+
const converter = typeof named === "function" ? named : typeof fromNamespace === "function" ? fromNamespace : void 0;
|
|
27
|
+
return converter ? converter : null;
|
|
40
28
|
};
|
|
41
|
-
/**
|
|
42
|
-
* Resolves the `zod-to-json-schema` package — the Zod 3 fallback used when the
|
|
43
|
-
* installed Zod lacks the native `toJSONSchema`. Returns `null` when the
|
|
44
|
-
* package is absent or does not expose the expected shape.
|
|
45
|
-
*/
|
|
46
29
|
const loadFallbackConverter = async () => {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
return { convert: convert, ignoreOverride };
|
|
30
|
+
let mod;
|
|
31
|
+
try {
|
|
32
|
+
mod = await import("zod-to-json-schema");
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
const named = mod["zodToJsonSchema"];
|
|
37
|
+
const fromDefault = mod["default"];
|
|
38
|
+
const convert = typeof named === "function" ? named : typeof fromDefault === "function" ? fromDefault : void 0;
|
|
39
|
+
const ignoreOverride = mod["ignoreOverride"];
|
|
40
|
+
if (typeof convert !== "function" || typeof ignoreOverride !== "symbol")
|
|
41
|
+
return null;
|
|
42
|
+
return { convert, ignoreOverride };
|
|
61
43
|
};
|
|
62
|
-
/**
|
|
63
|
-
* Runs the Zod 4 native `toJSONSchema`, mapping `z.date()`/`z.bigint()` into the
|
|
64
|
-
* shared `x-mjst` hints and recording lossy (unrepresentable) types.
|
|
65
|
-
*
|
|
66
|
-
* Zod's `z.date()` has no JSON Schema representation and would otherwise throw.
|
|
67
|
-
* We pass `unrepresentable: 'any'` so conversion never fails on it, then use the
|
|
68
|
-
* `override` hook to rewrite date schemas into an `x-mjst` instanceOf hint — the
|
|
69
|
-
* same extension TypeBox dates use — so generated types and runtime checks treat
|
|
70
|
-
* them as `Date`.
|
|
71
|
-
*/
|
|
72
44
|
const convertWithZod4 = (source, toJSONSchema, droppedTypes) => {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?\n${String(error)}`);
|
|
96
|
-
}
|
|
45
|
+
try {
|
|
46
|
+
return toJSONSchema(source, {
|
|
47
|
+
unrepresentable: "any",
|
|
48
|
+
override: (ctx) => {
|
|
49
|
+
const type = ctx.zodSchema?._zod?.def?.type;
|
|
50
|
+
if (type === "date") {
|
|
51
|
+
for (const key of Object.keys(ctx.jsonSchema))
|
|
52
|
+
delete ctx.jsonSchema[key];
|
|
53
|
+
ctx.jsonSchema[MJST_EXTENSION_KEY] = { instanceOf: "Date" };
|
|
54
|
+
} else if (type === "bigint") {
|
|
55
|
+
for (const key of Object.keys(ctx.jsonSchema))
|
|
56
|
+
delete ctx.jsonSchema[key];
|
|
57
|
+
ctx.jsonSchema[MJST_EXTENSION_KEY] = { primitive: "bigint" };
|
|
58
|
+
} else if (type && LOSSY_TYPES.has(type)) {
|
|
59
|
+
droppedTypes.add(type);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
} catch (error) {
|
|
64
|
+
throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?
|
|
65
|
+
${String(error)}`);
|
|
66
|
+
}
|
|
97
67
|
};
|
|
98
|
-
/**
|
|
99
|
-
* Runs the `zod-to-json-schema` fallback for Zod 3, reaching the same outcome as
|
|
100
|
-
* {@link convertWithZod4}: `z.date()`/`z.bigint()` become the shared `x-mjst`
|
|
101
|
-
* hints and lossy types are recorded for the warning. Zod 3's date/bigint would
|
|
102
|
-
* otherwise degrade to a string/integer schema, so the `override` hook rewrites
|
|
103
|
-
* them, and lossy leaf types (which the fallback silently drops) are turned into
|
|
104
|
-
* an open `{}` schema so the field survives — matching the Zod 4 widening.
|
|
105
|
-
*
|
|
106
|
-
* Emits refs under `$defs` (via `definitionPath`) to match the Zod 4 path; the
|
|
107
|
-
* shared finalize step normalises the fallback's draft-07 tuple form afterwards.
|
|
108
|
-
*/
|
|
109
68
|
const convertWithFallback = (source, fallback, droppedTypes) => {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
69
|
+
try {
|
|
70
|
+
return fallback.convert(source, {
|
|
71
|
+
definitionPath: "$defs",
|
|
72
|
+
override: (def) => {
|
|
73
|
+
const typeName = def?.typeName;
|
|
74
|
+
if (typeName === "ZodDate")
|
|
75
|
+
return { [MJST_EXTENSION_KEY]: { instanceOf: "Date" } };
|
|
76
|
+
if (typeName === "ZodBigInt")
|
|
77
|
+
return { [MJST_EXTENSION_KEY]: { primitive: "bigint" } };
|
|
78
|
+
const friendly = typeName ? LOSSY_TYPENAMES[typeName] : void 0;
|
|
79
|
+
if (friendly) {
|
|
80
|
+
droppedTypes.add(friendly);
|
|
81
|
+
return {};
|
|
82
|
+
}
|
|
83
|
+
return fallback.ignoreOverride;
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
} catch (error) {
|
|
87
|
+
throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?
|
|
88
|
+
${String(error)}`);
|
|
89
|
+
}
|
|
131
90
|
};
|
|
132
|
-
|
|
133
|
-
// is safe to merge. Anything else (patternProperties, a nested allOf, $ref, a
|
|
134
|
-
// conditional, …) makes the merge unsafe, so we leave such an allOf alone.
|
|
135
|
-
const CLOSED_OBJECT_KEYS = new Set(['type', 'properties', 'required', 'additionalProperties']);
|
|
91
|
+
const CLOSED_OBJECT_KEYS = /* @__PURE__ */ new Set(["type", "properties", "required", "additionalProperties"]);
|
|
136
92
|
const isClosedObject = (node) => {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
93
|
+
if (node === null || typeof node !== "object" || Array.isArray(node))
|
|
94
|
+
return false;
|
|
95
|
+
const obj = node;
|
|
96
|
+
if (obj["type"] !== "object" || obj["additionalProperties"] !== false)
|
|
97
|
+
return false;
|
|
98
|
+
return Object.keys(obj).every((key) => CLOSED_OBJECT_KEYS.has(key));
|
|
143
99
|
};
|
|
144
|
-
/**
|
|
145
|
-
* Zod emits an intersection of objects as an `allOf` where every branch carries
|
|
146
|
-
* `additionalProperties: false`. That is unsatisfiable — each branch rejects the
|
|
147
|
-
* keys the others contribute — even though the Zod intersection accepts the
|
|
148
|
-
* combined object. When every `allOf` branch is a closed object we merge them
|
|
149
|
-
* into one: properties are unioned (a key in several branches becomes an `allOf`
|
|
150
|
-
* of its schemas), `required` is unioned, and `additionalProperties: false` is
|
|
151
|
-
* kept over the combined key set. `allOf`s with a non-object branch (e.g. two
|
|
152
|
-
* refined strings) are left untouched — those already combine correctly.
|
|
153
|
-
*/
|
|
154
100
|
const mergeClosedObjectAllOf = (node) => {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
}
|
|
183
|
-
delete out['allOf'];
|
|
184
|
-
out['type'] = 'object';
|
|
185
|
-
out['properties'] = mergedProps;
|
|
186
|
-
if (required.size > 0)
|
|
187
|
-
out['required'] = [...required];
|
|
188
|
-
out['additionalProperties'] = false;
|
|
101
|
+
if (node === null || typeof node !== "object")
|
|
102
|
+
return node;
|
|
103
|
+
if (Array.isArray(node))
|
|
104
|
+
return node.map(mergeClosedObjectAllOf);
|
|
105
|
+
const obj = node;
|
|
106
|
+
const out = {};
|
|
107
|
+
for (const [key, value] of Object.entries(obj))
|
|
108
|
+
out[key] = mergeClosedObjectAllOf(value);
|
|
109
|
+
const allOf = out["allOf"];
|
|
110
|
+
if (Array.isArray(allOf) && allOf.length > 1 && allOf.every(isClosedObject)) {
|
|
111
|
+
const properties = {};
|
|
112
|
+
const required = /* @__PURE__ */ new Set();
|
|
113
|
+
for (const branch of allOf) {
|
|
114
|
+
const props = branch["properties"] ?? {};
|
|
115
|
+
for (const [prop, schema] of Object.entries(props)) {
|
|
116
|
+
const bucket = properties[prop];
|
|
117
|
+
if (bucket)
|
|
118
|
+
bucket.push(schema);
|
|
119
|
+
else
|
|
120
|
+
properties[prop] = [schema];
|
|
121
|
+
}
|
|
122
|
+
for (const r of branch["required"] ?? [])
|
|
123
|
+
required.add(r);
|
|
124
|
+
}
|
|
125
|
+
const mergedProps = {};
|
|
126
|
+
for (const [prop, schemas] of Object.entries(properties)) {
|
|
127
|
+
mergedProps[prop] = schemas.length === 1 ? schemas[0] : { allOf: schemas };
|
|
189
128
|
}
|
|
190
|
-
|
|
129
|
+
delete out["allOf"];
|
|
130
|
+
out["type"] = "object";
|
|
131
|
+
out["properties"] = mergedProps;
|
|
132
|
+
if (required.size > 0)
|
|
133
|
+
out["required"] = [...required];
|
|
134
|
+
out["additionalProperties"] = false;
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
191
137
|
};
|
|
192
|
-
/**
|
|
193
|
-
* Shared post-processing applied to both the Zod 4 and Zod 3 conversion output:
|
|
194
|
-
* report widened lossy types (a batched warning, or a throw in strict mode),
|
|
195
|
-
* drop the dialect marker, normalise draft-07 tuples, restore tuple length
|
|
196
|
-
* bounds, and collapse unsatisfiable object intersections.
|
|
197
|
-
*/
|
|
198
138
|
const finalize = (json, droppedTypes, strict) => {
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
delete json['$schema'];
|
|
205
|
-
// The Zod 3 fallback emits draft-07 tuples; rewrite them to 2020-12 form.
|
|
206
|
-
normalizeDraftTuples(json);
|
|
207
|
-
// Zod under-constrains fixed tuples (bare `prefixItems`); restore their length.
|
|
208
|
-
enforceTupleLength(json);
|
|
209
|
-
// Collapse an unsatisfiable `allOf` of closed objects (object intersections).
|
|
210
|
-
return mergeClosedObjectAllOf(json);
|
|
139
|
+
reportLossyConstructs("Zod", droppedTypes, strict);
|
|
140
|
+
delete json["$schema"];
|
|
141
|
+
normalizeDraftTuples(json);
|
|
142
|
+
enforceTupleLength(json);
|
|
143
|
+
return mergeClosedObjectAllOf(json);
|
|
211
144
|
};
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
const fallback = await loadFallbackConverter();
|
|
231
|
-
if (fallback) {
|
|
232
|
-
return finalize(convertWithFallback(source, fallback, droppedTypes), droppedTypes, options?.strict);
|
|
233
|
-
}
|
|
234
|
-
throw new Error("The Zod adapter requires either 'zod' v4+ (for its native toJSONSchema) or the 'zod-to-json-schema' " +
|
|
235
|
-
'package (a fallback for Zod 3). Neither was found — install one in your project.');
|
|
145
|
+
const zodToJsonSchema = async (source, options) => {
|
|
146
|
+
if (typeof source !== "object" || source === null) {
|
|
147
|
+
const received = source === null ? "null" : typeof source;
|
|
148
|
+
throw new Error(`Zod adapter expected a Zod schema but received ${received}.`);
|
|
149
|
+
}
|
|
150
|
+
const droppedTypes = /* @__PURE__ */ new Set();
|
|
151
|
+
const toJSONSchema = await loadToJsonSchema();
|
|
152
|
+
if (toJSONSchema) {
|
|
153
|
+
return finalize(convertWithZod4(source, toJSONSchema, droppedTypes), droppedTypes, options?.strict);
|
|
154
|
+
}
|
|
155
|
+
const fallback = await loadFallbackConverter();
|
|
156
|
+
if (fallback) {
|
|
157
|
+
return finalize(convertWithFallback(source, fallback, droppedTypes), droppedTypes, options?.strict);
|
|
158
|
+
}
|
|
159
|
+
throw new Error("The Zod adapter requires either 'zod' v4+ (for its native toJSONSchema) or the 'zod-to-json-schema' package (a fallback for Zod 3). Neither was found \u2014 install one in your project.");
|
|
160
|
+
};
|
|
161
|
+
export {
|
|
162
|
+
zodToJsonSchema
|
|
236
163
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/adapters",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
4
4
|
"description": "Convert schemas from external libraries (TypeBox, Zod, ...) into JSON Schema for mjst.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -31,13 +31,13 @@
|
|
|
31
31
|
"access": "public"
|
|
32
32
|
},
|
|
33
33
|
"scripts": {
|
|
34
|
-
"build": "tsgo -p tsconfig.build.json && tsc-alias -p tsconfig.build.json -f",
|
|
34
|
+
"build": "tsgo -p tsconfig.build.json && tsc-alias -p tsconfig.build.json -f && node ../../scripts/strip-comments.mjs",
|
|
35
35
|
"types:check": "tsgo -p . --noEmit",
|
|
36
36
|
"test": "NODE_ENV=production vitest run --root ../.. adapters"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"json-schema-typed": "^8.0.1",
|
|
40
|
-
"@amritk/helpers": "0.13.
|
|
40
|
+
"@amritk/helpers": "0.13.3"
|
|
41
41
|
},
|
|
42
42
|
"exports": {
|
|
43
43
|
"./package.json": "./package.json",
|