@amritk/adapters 0.2.10 → 0.2.11
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.
|
@@ -6,6 +6,7 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
|
6
6
|
* the *encoded* (wire) representation. For example `Schema.Date` decodes from a
|
|
7
7
|
* string, so it converts to a string schema rather than a runtime `Date`. We
|
|
8
8
|
* pass that representation straight through — it accurately reflects what Effect
|
|
9
|
-
* expects on the wire — only stripping the dialect marker.
|
|
9
|
+
* expects on the wire — only stripping the dialect marker. A top-level
|
|
10
|
+
* `BigIntFromSelf` / `DateFromSelf` is rescued into an `x-mjst` hint.
|
|
10
11
|
*/
|
|
11
12
|
export declare const effectToJsonSchema: (source: unknown) => Promise<JSONSchema>;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension';
|
|
1
2
|
/**
|
|
2
3
|
* Resolves `effect`'s `JSONSchema.make` from a runtime import, throwing a clear
|
|
3
4
|
* error when it is missing.
|
|
@@ -17,6 +18,30 @@ const loadMake = async () => {
|
|
|
17
18
|
}
|
|
18
19
|
return make;
|
|
19
20
|
};
|
|
21
|
+
// The annotation key Effect stamps an identifier under (e.g. `"DateFromSelf"`).
|
|
22
|
+
const IDENTIFIER_ANNOTATION = Symbol.for('effect/annotation/Identifier');
|
|
23
|
+
/** Reads `node.ast`, the AST that backs every Effect `Schema`. */
|
|
24
|
+
const astOf = (source) => {
|
|
25
|
+
const ast = source?.ast;
|
|
26
|
+
return ast && typeof ast === 'object' ? ast : undefined;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Effect models `bigint` and a runtime `Date` as types with no JSON Schema
|
|
30
|
+
* representation, so `JSONSchema.make` throws on `Schema.BigIntFromSelf` /
|
|
31
|
+
* `Schema.DateFromSelf`. To stay consistent with the Zod, Valibot, and TypeBox
|
|
32
|
+
* adapters — which map those to the shared `x-mjst` hint — we rescue them here:
|
|
33
|
+
* `bigint` (`BigIntKeyword`) → `primitive: 'bigint'`, and the `DateFromSelf`
|
|
34
|
+
* declaration → `instanceOf: 'Date'`. (`Schema.Date` / `Schema.BigInt` decode
|
|
35
|
+
* from a string and already convert to a `string` schema, so they are untouched.)
|
|
36
|
+
*/
|
|
37
|
+
const rescueXMjst = (ast) => {
|
|
38
|
+
if (ast._tag === 'BigIntKeyword')
|
|
39
|
+
return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } };
|
|
40
|
+
if (ast._tag === 'Declaration' && ast.annotations?.[IDENTIFIER_ANNOTATION] === 'DateFromSelf') {
|
|
41
|
+
return { [MJST_EXTENSION_KEY]: { instanceOf: 'Date' } };
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
};
|
|
20
45
|
/**
|
|
21
46
|
* Converts an Effect `Schema` into a JSON Schema via `JSONSchema.make`.
|
|
22
47
|
*
|
|
@@ -24,7 +49,8 @@ const loadMake = async () => {
|
|
|
24
49
|
* the *encoded* (wire) representation. For example `Schema.Date` decodes from a
|
|
25
50
|
* string, so it converts to a string schema rather than a runtime `Date`. We
|
|
26
51
|
* pass that representation straight through — it accurately reflects what Effect
|
|
27
|
-
* expects on the wire — only stripping the dialect marker.
|
|
52
|
+
* expects on the wire — only stripping the dialect marker. A top-level
|
|
53
|
+
* `BigIntFromSelf` / `DateFromSelf` is rescued into an `x-mjst` hint.
|
|
28
54
|
*/
|
|
29
55
|
export const effectToJsonSchema = async (source) => {
|
|
30
56
|
// Effect `Schema` values are callable, so they report as `function`, not `object`.
|
|
@@ -32,13 +58,24 @@ export const effectToJsonSchema = async (source) => {
|
|
|
32
58
|
const received = source === null ? 'null' : typeof source;
|
|
33
59
|
throw new Error(`Effect adapter expected an Effect Schema but received ${received}.`);
|
|
34
60
|
}
|
|
61
|
+
const ast = astOf(source);
|
|
62
|
+
if (ast) {
|
|
63
|
+
const rescued = rescueXMjst(ast);
|
|
64
|
+
if (rescued)
|
|
65
|
+
return rescued;
|
|
66
|
+
}
|
|
35
67
|
const make = await loadMake();
|
|
36
68
|
let json;
|
|
37
69
|
try {
|
|
38
70
|
json = make(source);
|
|
39
71
|
}
|
|
40
72
|
catch (error) {
|
|
41
|
-
|
|
73
|
+
// `make` throws on an unrepresentable type with no `jsonSchema` annotation —
|
|
74
|
+
// most often a nested `BigIntFromSelf` / `DateFromSelf`. Point the user at the
|
|
75
|
+
// fix rather than surfacing Effect's opaque "Missing annotation" message.
|
|
76
|
+
throw new Error(`Effect adapter failed to convert the schema. A nested bigint or runtime Date (BigIntFromSelf / DateFromSelf) ` +
|
|
77
|
+
`has no JSON Schema representation — use the string-encoded Schema.BigInt / Schema.Date, or add a ` +
|
|
78
|
+
`\`jsonSchema\` annotation to that field.\n${String(error)}`);
|
|
42
79
|
}
|
|
43
80
|
delete json['$schema'];
|
|
44
81
|
return json;
|
|
@@ -1,12 +1,2 @@
|
|
|
1
1
|
import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
2
|
-
/**
|
|
3
|
-
* Converts a Zod schema into a Draft 2020-12 JSON Schema using Zod 4's native
|
|
4
|
-
* `toJSONSchema`.
|
|
5
|
-
*
|
|
6
|
-
* Zod's `z.date()` has no JSON Schema representation and would otherwise throw.
|
|
7
|
-
* We pass `unrepresentable: 'any'` so conversion never fails on it, then use the
|
|
8
|
-
* `override` hook to rewrite date schemas into an `x-mjst` instanceOf hint — the
|
|
9
|
-
* same extension TypeBox dates use — so generated types and runtime checks treat
|
|
10
|
-
* them as `Date`.
|
|
11
|
-
*/
|
|
12
2
|
export declare const zodToJsonSchema: (source: unknown) => Promise<JSONSchema>;
|
|
@@ -32,6 +32,97 @@ const loadToJsonSchema = async () => {
|
|
|
32
32
|
* same extension TypeBox dates use — so generated types and runtime checks treat
|
|
33
33
|
* them as `Date`.
|
|
34
34
|
*/
|
|
35
|
+
/**
|
|
36
|
+
* Zod 4's `toJSONSchema` emits a fixed tuple as a bare `prefixItems` array with
|
|
37
|
+
* no length bound, so the result accepts a too-short array (positions past the
|
|
38
|
+
* end are simply unconstrained) and a too-long one (nothing forbids extra
|
|
39
|
+
* items). A Zod tuple requires exactly its fixed elements, so we restore that:
|
|
40
|
+
* `minItems` forces the fixed elements to be present, and — when the tuple has
|
|
41
|
+
* no `.rest(...)` (no `items`) — `items: false` forbids extras. Applied to every
|
|
42
|
+
* `prefixItems` node in the tree. Existing tighter bounds are never loosened.
|
|
43
|
+
*/
|
|
44
|
+
const enforceTupleLength = (node) => {
|
|
45
|
+
if (node === null || typeof node !== 'object')
|
|
46
|
+
return;
|
|
47
|
+
if (Array.isArray(node)) {
|
|
48
|
+
for (const item of node)
|
|
49
|
+
enforceTupleLength(item);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const obj = node;
|
|
53
|
+
if (Array.isArray(obj['prefixItems'])) {
|
|
54
|
+
const fixed = obj['prefixItems'].length;
|
|
55
|
+
const min = typeof obj['minItems'] === 'number' ? obj['minItems'] : 0;
|
|
56
|
+
if (min < fixed)
|
|
57
|
+
obj['minItems'] = fixed;
|
|
58
|
+
// No `items` keyword means no rest element: the array may not exceed the
|
|
59
|
+
// fixed tuple, so forbid additional items.
|
|
60
|
+
if (!('items' in obj))
|
|
61
|
+
obj['items'] = false;
|
|
62
|
+
}
|
|
63
|
+
for (const value of Object.values(obj))
|
|
64
|
+
enforceTupleLength(value);
|
|
65
|
+
};
|
|
66
|
+
// Keys a branch may carry and still be treated as a plain "closed object" that
|
|
67
|
+
// is safe to merge. Anything else (patternProperties, a nested allOf, $ref, a
|
|
68
|
+
// conditional, …) makes the merge unsafe, so we leave such an allOf alone.
|
|
69
|
+
const CLOSED_OBJECT_KEYS = new Set(['type', 'properties', 'required', 'additionalProperties']);
|
|
70
|
+
const isClosedObject = (node) => {
|
|
71
|
+
if (node === null || typeof node !== 'object' || Array.isArray(node))
|
|
72
|
+
return false;
|
|
73
|
+
const obj = node;
|
|
74
|
+
if (obj['type'] !== 'object' || obj['additionalProperties'] !== false)
|
|
75
|
+
return false;
|
|
76
|
+
return Object.keys(obj).every((key) => CLOSED_OBJECT_KEYS.has(key));
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Zod emits an intersection of objects as an `allOf` where every branch carries
|
|
80
|
+
* `additionalProperties: false`. That is unsatisfiable — each branch rejects the
|
|
81
|
+
* keys the others contribute — even though the Zod intersection accepts the
|
|
82
|
+
* combined object. When every `allOf` branch is a closed object we merge them
|
|
83
|
+
* into one: properties are unioned (a key in several branches becomes an `allOf`
|
|
84
|
+
* of its schemas), `required` is unioned, and `additionalProperties: false` is
|
|
85
|
+
* kept over the combined key set. `allOf`s with a non-object branch (e.g. two
|
|
86
|
+
* refined strings) are left untouched — those already combine correctly.
|
|
87
|
+
*/
|
|
88
|
+
const mergeClosedObjectAllOf = (node) => {
|
|
89
|
+
if (node === null || typeof node !== 'object')
|
|
90
|
+
return node;
|
|
91
|
+
if (Array.isArray(node))
|
|
92
|
+
return node.map(mergeClosedObjectAllOf);
|
|
93
|
+
const obj = node;
|
|
94
|
+
const out = {};
|
|
95
|
+
for (const [key, value] of Object.entries(obj))
|
|
96
|
+
out[key] = mergeClosedObjectAllOf(value);
|
|
97
|
+
const allOf = out['allOf'];
|
|
98
|
+
if (Array.isArray(allOf) && allOf.length > 1 && allOf.every(isClosedObject)) {
|
|
99
|
+
const properties = {};
|
|
100
|
+
const required = new Set();
|
|
101
|
+
for (const branch of allOf) {
|
|
102
|
+
const props = (branch['properties'] ?? {});
|
|
103
|
+
for (const [prop, schema] of Object.entries(props)) {
|
|
104
|
+
const bucket = properties[prop];
|
|
105
|
+
if (bucket)
|
|
106
|
+
bucket.push(schema);
|
|
107
|
+
else
|
|
108
|
+
properties[prop] = [schema];
|
|
109
|
+
}
|
|
110
|
+
for (const r of (branch['required'] ?? []))
|
|
111
|
+
required.add(r);
|
|
112
|
+
}
|
|
113
|
+
const mergedProps = {};
|
|
114
|
+
for (const [prop, schemas] of Object.entries(properties)) {
|
|
115
|
+
mergedProps[prop] = schemas.length === 1 ? schemas[0] : { allOf: schemas };
|
|
116
|
+
}
|
|
117
|
+
delete out['allOf'];
|
|
118
|
+
out['type'] = 'object';
|
|
119
|
+
out['properties'] = mergedProps;
|
|
120
|
+
if (required.size > 0)
|
|
121
|
+
out['required'] = [...required];
|
|
122
|
+
out['additionalProperties'] = false;
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
};
|
|
35
126
|
export const zodToJsonSchema = async (source) => {
|
|
36
127
|
if (typeof source !== 'object' || source === null) {
|
|
37
128
|
const received = source === null ? 'null' : typeof source;
|
|
@@ -73,5 +164,8 @@ export const zodToJsonSchema = async (source) => {
|
|
|
73
164
|
}
|
|
74
165
|
// The dialect marker is noise for the generators, which already target 2020-12.
|
|
75
166
|
delete json['$schema'];
|
|
76
|
-
|
|
167
|
+
// Zod under-constrains fixed tuples (bare `prefixItems`); restore their length.
|
|
168
|
+
enforceTupleLength(json);
|
|
169
|
+
// Collapse an unsatisfiable `allOf` of closed objects (object intersections).
|
|
170
|
+
return mergeClosedObjectAllOf(json);
|
|
77
171
|
};
|