@middag-io/ui-contracts-codegen 0.0.0-stage → 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/lib/zod.mjs ADDED
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Zod emitter: one exported schema per JSON Schema $def.
3
+ *
4
+ * json-schema-to-zod has no $ref parser and cannot inline cycles, so the
5
+ * schemas are emitted here. Defs are declared in dependency order (topological);
6
+ * a reference to an already-declared def is a direct reference, and a back-edge
7
+ * (a recursive def such as NavigationNode) becomes z.lazy(() => XSchema).
8
+ * Recursive defs get an explicit z.ZodType<T> annotation so TypeScript does not
9
+ * infer `any` on the self-reference.
10
+ *
11
+ * Objects are lenient: `additionalProperties: false` is not turned into
12
+ * .strict(), so unknown keys (forward-compat fields, host overlays) are
13
+ * stripped instead of rejected. The strict shape lives in the TypeScript types.
14
+ */
15
+
16
+ const LOCAL_REF = /^#\/\$defs\/(.+)$/;
17
+
18
+ /**
19
+ * Resolve a $ref against the local defs and the configured externals.
20
+ * @returns {{ kind: "local", name: string } | { kind: "external", name: string, module: string }}
21
+ */
22
+ export function resolveRef(ref, externals) {
23
+ const local = ref.match(LOCAL_REF);
24
+ if (local) return { kind: "local", name: local[1] };
25
+ for (const [prefix, module] of Object.entries(externals ?? {})) {
26
+ if (!ref.startsWith(prefix)) continue;
27
+ const hash = ref.indexOf("#");
28
+ const pointer = hash >= 0 ? ref.slice(hash) : "";
29
+ const match = pointer.match(LOCAL_REF);
30
+ if (match) return { kind: "external", name: match[1], module };
31
+ }
32
+ throw new Error(`contracts-codegen: unsupported $ref "${ref}" (not local, no matching external)`);
33
+ }
34
+
35
+ /** Every $ref string found anywhere in a node. */
36
+ export function collectRefs(node, acc = new Set()) {
37
+ if (Array.isArray(node)) {
38
+ for (const n of node) collectRefs(n, acc);
39
+ } else if (node && typeof node === "object") {
40
+ if (typeof node.$ref === "string") acc.add(node.$ref);
41
+ for (const [k, v] of Object.entries(node)) {
42
+ if (k !== "$ref") collectRefs(v, acc);
43
+ }
44
+ }
45
+ return acc;
46
+ }
47
+
48
+ const pad = (depth) => " ".repeat(depth);
49
+
50
+ function primitive(type) {
51
+ switch (type) {
52
+ case "string":
53
+ return "z.string()";
54
+ case "integer":
55
+ return "z.number().int()";
56
+ case "number":
57
+ return "z.number()";
58
+ case "boolean":
59
+ return "z.boolean()";
60
+ case "null":
61
+ return "z.null()";
62
+ case "array":
63
+ return "z.array(z.unknown())";
64
+ case "object":
65
+ return "z.record(z.string(), z.unknown())";
66
+ default:
67
+ return "z.unknown()";
68
+ }
69
+ }
70
+
71
+ /** An open enum must be a top-level $def that is a non-empty string enum. */
72
+ export function isStringEnum(node) {
73
+ return (
74
+ Boolean(node) &&
75
+ Array.isArray(node.enum) &&
76
+ node.enum.length > 0 &&
77
+ node.enum.every((e) => typeof e === "string")
78
+ );
79
+ }
80
+
81
+ export function assertOpenEnums(defs, openEnums) {
82
+ for (const name of openEnums) {
83
+ if (!isStringEnum(defs[name])) {
84
+ throw new Error(
85
+ `contracts-codegen: openEnums entry "${name}" is not a top-level string enum $def`,
86
+ );
87
+ }
88
+ }
89
+ }
90
+
91
+ function union(members) {
92
+ if (members.length === 1) return members[0];
93
+ return `z.union([${members.join(", ")}])`;
94
+ }
95
+
96
+ /**
97
+ * @param {object} options
98
+ * @param {Record<string, unknown>} options.defs merged $defs
99
+ * @param {Record<string, string>} [options.externals] $ref prefix -> module
100
+ * @param {string} options.typesModule module of the generated types (for recursive annotations)
101
+ * @param {Record<string, string>} [options.aliases] extra export name -> def name
102
+ * @param {string[]} [options.openEnums] top-level string-enum $defs that also accept any other string
103
+ * @returns {{ body: string, order: string[], recursive: string[] }}
104
+ */
105
+ export function emitZod({ defs, externals = {}, typesModule, aliases = {}, openEnums = [] }) {
106
+ assertOpenEnums(defs, openEnums);
107
+ const names = Object.keys(defs);
108
+ const externalImports = new Map();
109
+
110
+ const deps = Object.fromEntries(
111
+ names.map((name) => {
112
+ const local = new Set();
113
+ for (const ref of collectRefs(defs[name])) {
114
+ const resolved = resolveRef(ref, externals);
115
+ if (resolved.kind === "local") {
116
+ if (!(resolved.name in defs)) {
117
+ throw new Error(`contracts-codegen: unknown $ref target "${resolved.name}" in ${name}`);
118
+ }
119
+ local.add(resolved.name);
120
+ }
121
+ }
122
+ return [name, local];
123
+ }),
124
+ );
125
+
126
+ const visited = new Set();
127
+ const order = [];
128
+ const visit = (name) => {
129
+ if (visited.has(name)) return;
130
+ visited.add(name);
131
+ for (const dep of deps[name]) if (dep !== name) visit(dep);
132
+ order.push(name);
133
+ };
134
+ for (const name of names) visit(name);
135
+ const rank = Object.fromEntries(order.map((n, i) => [n, i]));
136
+
137
+ const isRecursive = (name) => {
138
+ const seen = new Set();
139
+ const stack = [...deps[name]];
140
+ while (stack.length) {
141
+ const cur = stack.pop();
142
+ if (cur === name) return true;
143
+ if (seen.has(cur)) continue;
144
+ seen.add(cur);
145
+ stack.push(...deps[cur]);
146
+ }
147
+ return false;
148
+ };
149
+ const recursive = new Set(names.filter(isRecursive));
150
+
151
+ const expr = (node, owner, depth) => {
152
+ if (node === true || node === undefined) return "z.unknown()";
153
+ if (node === false) return "z.never()";
154
+ if (node === null || typeof node !== "object") return "z.unknown()";
155
+
156
+ if (typeof node.$ref === "string") {
157
+ const resolved = resolveRef(node.$ref, externals);
158
+ if (resolved.kind === "external") {
159
+ const list = externalImports.get(resolved.module) ?? new Set();
160
+ list.add(`${resolved.name}Schema`);
161
+ externalImports.set(resolved.module, list);
162
+ return `${resolved.name}Schema`;
163
+ }
164
+ const ref = `${resolved.name}Schema`;
165
+ const backEdge = resolved.name === owner || rank[resolved.name] >= rank[owner];
166
+ return backEdge ? `z.lazy(() => ${ref})` : ref;
167
+ }
168
+ if (Array.isArray(node.allOf)) {
169
+ const parts = node.allOf.map((s) => expr(s, owner, depth));
170
+ return parts.reduce((acc, part) => `z.intersection(${acc}, ${part})`);
171
+ }
172
+ if (Array.isArray(node.oneOf)) return union(node.oneOf.map((s) => expr(s, owner, depth)));
173
+ if (Array.isArray(node.anyOf)) return union(node.anyOf.map((s) => expr(s, owner, depth)));
174
+ if (node.const !== undefined) return `z.literal(${JSON.stringify(node.const)})`;
175
+ if (Array.isArray(node.enum)) {
176
+ if (node.enum.length > 0 && node.enum.every((e) => typeof e === "string")) {
177
+ return `z.enum([${node.enum.map((e) => JSON.stringify(e)).join(", ")}])`;
178
+ }
179
+ return union(node.enum.map((e) => `z.literal(${JSON.stringify(e)})`));
180
+ }
181
+ if (Array.isArray(node.type)) {
182
+ return union(node.type.map((t) => typed(node, t, owner, depth)));
183
+ }
184
+ if (typeof node.type === "string") return typed(node, node.type, owner, depth);
185
+ if (node.properties) return object(node, owner, depth);
186
+ return "z.unknown()";
187
+ };
188
+
189
+ const typed = (node, type, owner, depth) => {
190
+ switch (type) {
191
+ case "string": {
192
+ let out = "z.string()";
193
+ if (Number.isInteger(node.minLength)) out += `.min(${node.minLength})`;
194
+ if (Number.isInteger(node.maxLength)) out += `.max(${node.maxLength})`;
195
+ if (typeof node.pattern === "string")
196
+ out += `.regex(new RegExp(${JSON.stringify(node.pattern)}))`;
197
+ return out;
198
+ }
199
+ case "integer":
200
+ case "number": {
201
+ let out = primitive(type);
202
+ if (typeof node.minimum === "number") out += `.gte(${node.minimum})`;
203
+ if (typeof node.maximum === "number") out += `.lte(${node.maximum})`;
204
+ return out;
205
+ }
206
+ case "array": {
207
+ let out = `z.array(${node.items !== undefined ? expr(node.items, owner, depth) : "z.unknown()"})`;
208
+ if (Number.isInteger(node.minItems)) out += `.min(${node.minItems})`;
209
+ if (Number.isInteger(node.maxItems)) out += `.max(${node.maxItems})`;
210
+ return out;
211
+ }
212
+ case "object":
213
+ return object(node, owner, depth);
214
+ default:
215
+ return primitive(type);
216
+ }
217
+ };
218
+
219
+ const object = (node, owner, depth) => {
220
+ const props = node.properties ?? {};
221
+ const extra = node.additionalProperties;
222
+ if (Object.keys(props).length === 0) {
223
+ if (extra && typeof extra === "object") {
224
+ return `z.record(z.string(), ${expr(extra, owner, depth)})`;
225
+ }
226
+ return "z.record(z.string(), z.unknown())";
227
+ }
228
+ const required = new Set(node.required ?? []);
229
+ const lines = Object.entries(props).map(([key, sub]) => {
230
+ let out = expr(sub, owner, depth + 1);
231
+ if (!required.has(key)) out += ".optional()";
232
+ return `${pad(depth + 1)}${JSON.stringify(key)}: ${out},`;
233
+ });
234
+ let out = `z.object({\n${lines.join("\n")}\n${pad(depth)}})`;
235
+ if (extra === true) out += ".catchall(z.unknown())";
236
+ else if (extra && typeof extra === "object") out += `.catchall(${expr(extra, owner, depth)})`;
237
+ return out;
238
+ };
239
+
240
+ const decls = order.map((name) => {
241
+ const body = openEnums.includes(name)
242
+ ? `z.union([${expr(defs[name], name, 0)}, z.string()])`
243
+ : expr(defs[name], name, 0);
244
+ return recursive.has(name)
245
+ ? `export const ${name}Schema: z.ZodType<${name}> = ${body};`
246
+ : `export const ${name}Schema = ${body};`;
247
+ });
248
+
249
+ const aliasLines = Object.entries(aliases).map(([alias, def]) => {
250
+ if (!(def in defs))
251
+ throw new Error(`contracts-codegen: alias "${alias}" targets unknown def "${def}"`);
252
+ return `export const ${alias} = ${def}Schema;`;
253
+ });
254
+
255
+ const recursiveTypes = order.filter((n) => recursive.has(n));
256
+ const imports = ['import { z } from "zod";'];
257
+ if (recursiveTypes.length) {
258
+ imports.push(`import type { ${recursiveTypes.join(", ")} } from "${typesModule}";`);
259
+ }
260
+ for (const [module, list] of [...externalImports].sort(([a], [b]) => a.localeCompare(b))) {
261
+ imports.push(`import { ${[...list].sort().join(", ")} } from "${module}";`);
262
+ }
263
+
264
+ const body = [
265
+ ...imports,
266
+ "",
267
+ decls.join("\n\n"),
268
+ ...(aliasLines.length ? ["", ...aliasLines] : []),
269
+ "",
270
+ ].join("\n");
271
+
272
+ return { body, order, recursive: recursiveTypes };
273
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@middag-io/ui-contracts-codegen",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Generates the TypeScript types and zod schemas of a MIDDAG contracts package from the wire JSON Schemas emitted by the PHP value objects.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "middag-contracts-gen": "bin/middag-contracts-gen.mjs"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./lib/index.d.mts",
13
+ "default": "./lib/index.mjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "bin",
18
+ "lib",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "engines": {
23
+ "node": ">=20.19.0"
24
+ },
25
+ "dependencies": {
26
+ "json-schema-to-typescript": "^15.0.4"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/middag-io/middag-react.git",
31
+ "directory": "packages/contracts-codegen"
32
+ },
33
+ "homepage": "https://github.com/middag-io/middag-react/tree/main/packages/contracts-codegen#readme",
34
+ "bugs": "https://github.com/middag-io/middag-react/issues",
35
+ "keywords": [
36
+ "middag",
37
+ "contracts",
38
+ "json-schema",
39
+ "zod",
40
+ "codegen"
41
+ ]
42
+ }