@middag-io/ui-contracts-codegen 0.0.0-stage → 0.1.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/index.mjs ADDED
@@ -0,0 +1,513 @@
1
+ /* global fetch, structuredClone */
2
+ /**
3
+ * @middag-io/ui-contracts-codegen — TypeScript types and zod schemas from the
4
+ * MIDDAG wire JSON Schemas.
5
+ *
6
+ * A contracts package keeps a mirror of the producer's schemas in `schema/`,
7
+ * the provenance of that mirror in `schema/SOURCE.json`, and its settings in
8
+ * `contracts.config.json`. Generation reads only the mirror. Reading another
9
+ * directory takes an explicit `source` (local development), which rewrites the
10
+ * mirror and marks its provenance as local so a published build refuses it.
11
+ */
12
+ import { createHash } from "node:crypto";
13
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
14
+ import { join, relative, resolve } from "node:path";
15
+ import { compile } from "json-schema-to-typescript";
16
+
17
+ import { compareContracts } from "./compat.mjs";
18
+ import { collectRefs, emitZod, resolveRef } from "./zod.mjs";
19
+
20
+ export { compareContracts } from "./compat.mjs";
21
+ export { emitZod } from "./zod.mjs";
22
+
23
+ export const CONFIG_FILE = "contracts.config.json";
24
+ export const SCHEMA_DIR = "schema";
25
+ export const SOURCE_FILE = "SOURCE.json";
26
+
27
+ const PRETTIER_STYLE = { singleQuote: false, semi: true, trailingComma: "all", printWidth: 100 };
28
+
29
+ export const sha256 = (text) => createHash("sha256").update(text).digest("hex");
30
+
31
+ /** Read and validate `contracts.config.json`. */
32
+ export function loadConfig(packageDir) {
33
+ const file = join(packageDir, CONFIG_FILE);
34
+ if (!existsSync(file)) throw new Error(`contracts-codegen: ${file} not found`);
35
+ const config = JSON.parse(readFileSync(file, "utf8"));
36
+ const missing = ["schemas", "idPrefix", "out", "producer"].filter((k) => config[k] === undefined);
37
+ if (missing.length) {
38
+ throw new Error(`contracts-codegen: ${CONFIG_FILE} is missing ${missing.join(", ")}`);
39
+ }
40
+ if (!Array.isArray(config.schemas) || config.schemas.length === 0) {
41
+ throw new Error(`contracts-codegen: ${CONFIG_FILE} "schemas" must list at least one file`);
42
+ }
43
+ return {
44
+ forbiddenIds: [],
45
+ externals: {},
46
+ aliases: {},
47
+ relaxBareObjects: false,
48
+ disjointWith: [],
49
+ ...config,
50
+ commands: { generate: "npm run gen", check: "npm run gen:check", ...config.commands },
51
+ };
52
+ }
53
+
54
+ /** Read the mirrored schemas, in config order. */
55
+ export function readMirror(packageDir, config) {
56
+ const dir = join(packageDir, SCHEMA_DIR);
57
+ return config.schemas.map((name) => {
58
+ const path = join(dir, name);
59
+ if (!existsSync(path)) throw new Error(`contracts-codegen: mirror file ${path} not found`);
60
+ const raw = readFileSync(path, "utf8");
61
+ return { name, raw, json: JSON.parse(raw) };
62
+ });
63
+ }
64
+
65
+ export function readSource(packageDir) {
66
+ const path = join(packageDir, SCHEMA_DIR, SOURCE_FILE);
67
+ if (!existsSync(path)) throw new Error(`contracts-codegen: ${path} not found`);
68
+ return JSON.parse(readFileSync(path, "utf8"));
69
+ }
70
+
71
+ export function writeSource(packageDir, source) {
72
+ writeFileSync(join(packageDir, SCHEMA_DIR, SOURCE_FILE), JSON.stringify(source, null, 2) + "\n");
73
+ }
74
+
75
+ /** Hash of a schema set: one value for the whole mirror, in config order. */
76
+ export function schemaHash(files) {
77
+ const hash = createHash("sha256");
78
+ files.forEach((f, i) => {
79
+ if (i > 0) hash.update(" ");
80
+ hash.update(f.raw);
81
+ });
82
+ return hash.digest("hex").slice(0, 16);
83
+ }
84
+
85
+ /**
86
+ * Leak guard and consistency checks on the mirrored schemas.
87
+ * Throws on the first violation.
88
+ */
89
+ export function validateSchemas(files, config) {
90
+ let version;
91
+ for (const file of files) {
92
+ const id = file.json.$id;
93
+ if (typeof id !== "string" || !id.startsWith(config.idPrefix)) {
94
+ throw new Error(
95
+ `contracts-codegen: ${file.name} has $id ${JSON.stringify(id)}, outside ${config.idPrefix}`,
96
+ );
97
+ }
98
+ for (const forbidden of config.forbiddenIds) {
99
+ if (file.raw.includes(forbidden)) {
100
+ throw new Error(
101
+ `contracts-codegen: ${file.name} mentions ${forbidden}, which this package must not carry`,
102
+ );
103
+ }
104
+ }
105
+ const v = file.json["x-contract-version"];
106
+ if (v === undefined) {
107
+ throw new Error(
108
+ `contracts-codegen: ${file.name} has no x-contract-version stamp (regenerate it with the producer's emit:schemas)`,
109
+ );
110
+ }
111
+ if (version !== undefined && String(v) !== String(version)) {
112
+ throw new Error(
113
+ `contracts-codegen: x-contract-version differs between schemas (${version} vs ${v})`,
114
+ );
115
+ }
116
+ version = v;
117
+ }
118
+ return String(version);
119
+ }
120
+
121
+ /** Union of the $defs of every schema; the same name must carry the same definition. */
122
+ export function mergeDefs(files) {
123
+ const defs = {};
124
+ for (const file of files) {
125
+ for (const [name, def] of Object.entries(file.json.$defs ?? {})) {
126
+ if (name in defs && JSON.stringify(defs[name]) !== JSON.stringify(def)) {
127
+ throw new Error(`contracts-codegen: $def "${name}" differs between schemas`);
128
+ }
129
+ defs[name] = def;
130
+ }
131
+ }
132
+ return defs;
133
+ }
134
+
135
+ /**
136
+ * Names that two def sets share. A contracts package that extends another must
137
+ * reference it, not redefine its names.
138
+ */
139
+ export function sharedNames(defs, otherDefs) {
140
+ return Object.keys(defs)
141
+ .filter((name) => name in otherDefs)
142
+ .sort();
143
+ }
144
+
145
+ function relaxBareObjects(node) {
146
+ if (Array.isArray(node)) {
147
+ node.forEach(relaxBareObjects);
148
+ } else if (node && typeof node === "object") {
149
+ if (
150
+ node.type === "object" &&
151
+ node.properties === undefined &&
152
+ node.additionalProperties === undefined
153
+ ) {
154
+ node.additionalProperties = true;
155
+ }
156
+ for (const value of Object.values(node)) relaxBareObjects(value);
157
+ }
158
+ }
159
+
160
+ /** Replace external $refs with a tsType placeholder, collecting the imports. */
161
+ function externalizeForTypes(node, externals, imports) {
162
+ if (Array.isArray(node)) return node.map((n) => externalizeForTypes(n, externals, imports));
163
+ if (node && typeof node === "object") {
164
+ if (typeof node.$ref === "string") {
165
+ const resolved = resolveRef(node.$ref, externals);
166
+ if (resolved.kind === "external") {
167
+ const list = imports.get(resolved.module) ?? new Set();
168
+ list.add(resolved.name);
169
+ imports.set(resolved.module, list);
170
+ const rest = { ...node };
171
+ delete rest.$ref;
172
+ return { ...externalizeForTypes(rest, externals, imports), tsType: resolved.name };
173
+ }
174
+ }
175
+ const out = {};
176
+ for (const [key, value] of Object.entries(node))
177
+ out[key] = externalizeForTypes(value, externals, imports);
178
+ return out;
179
+ }
180
+ return node;
181
+ }
182
+
183
+ function header({ summary, config, source, version, hash }) {
184
+ const files = config.schemas.length === 1 ? config.schemas[0] : `{${config.schemas.join(",")}}`;
185
+ const where = source?.repository ? `${source.repository}@${source.ref ?? "?"}` : config.producer;
186
+ return [
187
+ "/**",
188
+ " * @generated by @middag-io/ui-contracts-codegen — DO NOT EDIT BY HAND.",
189
+ " *",
190
+ ` * ${summary}`,
191
+ " *",
192
+ ` * Source of truth: ${config.producer} value objects -> JSON Schema (draft 2020-12).`,
193
+ ` * Regenerate: ${config.commands.generate}`,
194
+ ` * Drift gate: ${config.commands.check}`,
195
+ " *",
196
+ ` * @source ${where} ${SCHEMA_DIR}/${files}`,
197
+ ` * @contract-version ${version}`,
198
+ ` * @hash ${hash}`,
199
+ " */",
200
+ "",
201
+ ].join("\n");
202
+ }
203
+
204
+ async function emitTypes(defs, config, banner) {
205
+ const prepared = structuredClone(defs);
206
+ if (config.relaxBareObjects) relaxBareObjects(prepared);
207
+ const imports = new Map();
208
+ const externalized = externalizeForTypes(prepared, config.externals, imports);
209
+ const names = Object.keys(externalized);
210
+ const root = {
211
+ type: "object",
212
+ additionalProperties: false,
213
+ properties: Object.fromEntries(names.map((k) => [k, { $ref: `#/$defs/${k}` }])),
214
+ required: names,
215
+ $defs: externalized,
216
+ };
217
+ let ts = await compile(root, "ContractsCodegenRoot", {
218
+ additionalProperties: false,
219
+ bannerComment: "",
220
+ declareExternallyReferenced: true,
221
+ enableConstEnums: false,
222
+ unknownAny: true,
223
+ format: true,
224
+ style: PRETTIER_STYLE,
225
+ });
226
+ ts = ts.replace(/export interface ContractsCodegenRoot \{[\s\S]*?\n\}\n+/, "");
227
+ const importLines = [...imports]
228
+ .sort(([a], [b]) => a.localeCompare(b))
229
+ .map(([module, list]) => `import type { ${[...list].sort().join(", ")} } from "${module}";`);
230
+ return (
231
+ banner + (importLines.length ? importLines.join("\n") + "\n\n" : "") + ts.trimStart() + "\n"
232
+ );
233
+ }
234
+
235
+ function emitMeta(config, source, version, hash, banner) {
236
+ const producer = {
237
+ package: config.producer,
238
+ repository: source?.repository ?? null,
239
+ ref: source?.ref ?? null,
240
+ sha: source?.sha ?? null,
241
+ };
242
+ return (
243
+ banner +
244
+ [
245
+ "/** Breaking version of the wire contract (`x-contract-version`). */",
246
+ `export const CONTRACT_VERSION = ${JSON.stringify(version)} as const;`,
247
+ "",
248
+ "/** Hash of the mirrored schemas this package was generated from. */",
249
+ `export const SCHEMA_HASH = ${JSON.stringify(hash)} as const;`,
250
+ "",
251
+ "/** Producer of the schemas and the release they were mirrored from. */",
252
+ `export const PRODUCER = ${JSON.stringify(producer, null, 2)} as const;`,
253
+ "",
254
+ ].join("\n")
255
+ );
256
+ }
257
+
258
+ /**
259
+ * Generate the package sources from its mirror.
260
+ * @returns {Promise<{ files: Record<string, string>, version: string, hash: string, defs: Record<string, unknown> }>}
261
+ */
262
+ export async function build(packageDir) {
263
+ const config = loadConfig(packageDir);
264
+ const files = readMirror(packageDir, config);
265
+ const version = validateSchemas(files, config);
266
+ const defs = mergeDefs(files);
267
+ for (const name of Object.keys(defs)) {
268
+ for (const ref of collectRefs(defs[name])) resolveRef(ref, config.externals);
269
+ }
270
+ const source = readSource(packageDir);
271
+ const hash = schemaHash(files);
272
+ const banner = (summary) => header({ summary, config, source, version, hash });
273
+
274
+ const zod = emitZod({
275
+ defs,
276
+ externals: config.externals,
277
+ typesModule: "./types.js",
278
+ aliases: config.aliases,
279
+ });
280
+
281
+ return {
282
+ config,
283
+ version,
284
+ hash,
285
+ defs,
286
+ source,
287
+ files: {
288
+ "types.ts": await emitTypes(defs, config, banner("TypeScript types of the wire contract.")),
289
+ "schemas.ts":
290
+ banner("Zod schemas of the wire contract, one per $def. Lenient on unknown keys.") +
291
+ zod.body,
292
+ "meta.ts": emitMeta(
293
+ config,
294
+ source,
295
+ version,
296
+ hash,
297
+ banner("Contract version and provenance."),
298
+ ),
299
+ "index.ts":
300
+ banner("Barrel of the generated contract layer.") +
301
+ [
302
+ 'export * from "./types.js";',
303
+ 'export * from "./schemas.js";',
304
+ 'export * from "./meta.js";',
305
+ "",
306
+ ].join("\n"),
307
+ },
308
+ };
309
+ }
310
+
311
+ function readOut(outDir) {
312
+ if (!existsSync(outDir)) return {};
313
+ const out = {};
314
+ for (const f of readdirSync(outDir)) {
315
+ if (f.endsWith(".ts")) out[f] = readFileSync(join(outDir, f), "utf8");
316
+ }
317
+ return out;
318
+ }
319
+
320
+ /** Problems with the mirror's provenance, offline (no network). */
321
+ export function provenanceProblems(packageDir, config, source) {
322
+ const problems = [];
323
+ if (!source.repository || !source.ref || !source.sha) {
324
+ problems.push(
325
+ `${SCHEMA_DIR}/${SOURCE_FILE} has no repository, ref or sha (mirror written from a local --source)`,
326
+ );
327
+ }
328
+ for (const name of config.schemas) {
329
+ const path = join(packageDir, SCHEMA_DIR, name);
330
+ const actual = existsSync(path) ? sha256(readFileSync(path, "utf8")) : undefined;
331
+ if (source.files?.[name] !== actual)
332
+ problems.push(`${SCHEMA_DIR}/${name} does not match its hash in ${SOURCE_FILE}`);
333
+ }
334
+ return problems;
335
+ }
336
+
337
+ /**
338
+ * Drift gate: the generated sources match the mirror, nothing is orphaned and
339
+ * the mirror matches its recorded provenance.
340
+ * @returns {Promise<{ ok: boolean, problems: string[], hash: string, version: string }>}
341
+ */
342
+ export async function check(packageDir) {
343
+ const result = await build(packageDir);
344
+ const outDir = join(packageDir, result.config.out);
345
+ const existing = readOut(outDir);
346
+ const problems = [];
347
+ for (const [name, content] of Object.entries(result.files)) {
348
+ if (existing[name] !== content) problems.push(`${result.config.out}/${name} is stale`);
349
+ }
350
+ for (const name of Object.keys(existing)) {
351
+ if (!(name in result.files)) problems.push(`${result.config.out}/${name} is orphaned`);
352
+ }
353
+ problems.push(...provenanceProblems(packageDir, result.config, result.source));
354
+ problems.push(...(await disjointProblems(packageDir, result)));
355
+ return { ok: problems.length === 0, problems, hash: result.hash, version: result.version };
356
+ }
357
+
358
+ async function disjointProblems(packageDir, result) {
359
+ const problems = [];
360
+ for (const other of result.config.disjointWith) {
361
+ const otherDir = resolve(packageDir, other);
362
+ const otherConfig = loadConfig(otherDir);
363
+ const otherDefs = mergeDefs(readMirror(otherDir, otherConfig));
364
+ const shared = sharedNames(result.defs, otherDefs);
365
+ if (shared.length) {
366
+ problems.push(
367
+ `$defs shared with ${otherConfig.packageName ?? other}: ${shared.join(", ")} (reference them, do not redefine)`,
368
+ );
369
+ }
370
+ }
371
+ return problems;
372
+ }
373
+
374
+ /** Write the generated sources, removing orphans. */
375
+ export async function generate(packageDir) {
376
+ const result = await build(packageDir);
377
+ const outDir = join(packageDir, result.config.out);
378
+ mkdirSync(outDir, { recursive: true });
379
+ for (const name of Object.keys(readOut(outDir))) {
380
+ if (!(name in result.files)) rmSync(join(outDir, name));
381
+ }
382
+ for (const [name, content] of Object.entries(result.files))
383
+ writeFileSync(join(outDir, name), content);
384
+ return result;
385
+ }
386
+
387
+ /**
388
+ * Copy schemas from a local directory into the mirror (development only). The
389
+ * provenance is rewritten as local, which the drift gate rejects.
390
+ */
391
+ export function copyLocalSource(packageDir, sourceDir) {
392
+ const config = loadConfig(packageDir);
393
+ const dir = join(packageDir, SCHEMA_DIR);
394
+ mkdirSync(dir, { recursive: true });
395
+ const hashes = {};
396
+ for (const name of config.schemas) {
397
+ const raw = readFileSync(join(sourceDir, name), "utf8");
398
+ writeFileSync(join(dir, name), raw);
399
+ hashes[name] = sha256(raw);
400
+ }
401
+ writeSource(packageDir, {
402
+ repository: null,
403
+ ref: null,
404
+ sha: null,
405
+ path: relative(packageDir, resolve(sourceDir)),
406
+ files: hashes,
407
+ });
408
+ }
409
+
410
+ /** Defs and version of a mirror directory (for the compatibility gate). */
411
+ export function contractOf(dir, config) {
412
+ const files = config.schemas.map((name) => {
413
+ const raw = readFileSync(join(dir, name), "utf8");
414
+ return { name, raw, json: JSON.parse(raw) };
415
+ });
416
+ return { version: String(files[0].json["x-contract-version"]), defs: mergeDefs(files) };
417
+ }
418
+
419
+ /** Compare a previous mirror directory with the package's current mirror. */
420
+ export function compat(packageDir, baseDir) {
421
+ const config = loadConfig(packageDir);
422
+ return compareContracts(
423
+ contractOf(baseDir, config),
424
+ contractOf(join(packageDir, SCHEMA_DIR), config),
425
+ );
426
+ }
427
+
428
+ /**
429
+ * Fetch one file of a GitHub repository at a ref. Public repositories need no
430
+ * token; a private producer takes one with contents: read.
431
+ */
432
+ export async function fetchGitHubFile({ repository, ref, path, token }) {
433
+ const url = `https://api.github.com/repos/${repository}/contents/${path}?ref=${encodeURIComponent(ref)}`;
434
+ const headers = {
435
+ Accept: "application/vnd.github.raw+json",
436
+ "User-Agent": "ui-contracts-codegen",
437
+ };
438
+ if (token) headers.Authorization = `Bearer ${token}`;
439
+ const res = await fetch(url, { headers });
440
+ if (!res.ok)
441
+ throw new Error(`contracts-codegen: GET ${repository}/${path}@${ref} -> ${res.status}`);
442
+ return res.text();
443
+ }
444
+
445
+ export async function resolveGitHubSha({ repository, ref, token }) {
446
+ const url = `https://api.github.com/repos/${repository}/commits/${encodeURIComponent(ref)}`;
447
+ const headers = { Accept: "application/vnd.github.sha", "User-Agent": "ui-contracts-codegen" };
448
+ if (token) headers.Authorization = `Bearer ${token}`;
449
+ const res = await fetch(url, { headers });
450
+ if (!res.ok) throw new Error(`contracts-codegen: resolve ${repository}@${ref} -> ${res.status}`);
451
+ return (await res.text()).trim();
452
+ }
453
+
454
+ /**
455
+ * Mirror the producer's schemas at a release tag. Leaves the mirror untouched
456
+ * and returns `changed: false` when the schemas did not change.
457
+ */
458
+ export async function mirror(packageDir, { repository, ref, path = SCHEMA_DIR, token }) {
459
+ const config = loadConfig(packageDir);
460
+ const dir = join(packageDir, SCHEMA_DIR);
461
+ const fetched = {};
462
+ for (const name of config.schemas) {
463
+ fetched[name] = await fetchGitHubFile({ repository, ref, path: `${path}/${name}`, token });
464
+ }
465
+ const unchanged = config.schemas.every((name) => {
466
+ const current = join(dir, name);
467
+ return existsSync(current) && readFileSync(current, "utf8") === fetched[name];
468
+ });
469
+ if (unchanged) return { changed: false };
470
+
471
+ const baseDir = join(dir, ".base");
472
+ rmSync(baseDir, { recursive: true, force: true });
473
+ mkdirSync(baseDir, { recursive: true });
474
+ for (const name of config.schemas) {
475
+ if (existsSync(join(dir, name)))
476
+ writeFileSync(join(baseDir, name), readFileSync(join(dir, name), "utf8"));
477
+ }
478
+ const hashes = {};
479
+ for (const name of config.schemas) {
480
+ writeFileSync(join(dir, name), fetched[name]);
481
+ hashes[name] = sha256(fetched[name]);
482
+ }
483
+ const sha = await resolveGitHubSha({ repository, ref, token });
484
+ writeSource(packageDir, { repository, ref, sha, path, files: hashes });
485
+ const hasBase = config.schemas.every((name) => existsSync(join(baseDir, name)));
486
+ const report = hasBase
487
+ ? compareContracts(contractOf(baseDir, config), contractOf(dir, config))
488
+ : null;
489
+ rmSync(baseDir, { recursive: true, force: true });
490
+ return { changed: true, report };
491
+ }
492
+
493
+ /** Check the mirror against the producer at the recorded ref (network). */
494
+ export async function verifySource(packageDir, { token } = {}) {
495
+ const config = loadConfig(packageDir);
496
+ const source = readSource(packageDir);
497
+ const problems = provenanceProblems(packageDir, config, source);
498
+ if (problems.length) return { ok: false, problems };
499
+ for (const name of config.schemas) {
500
+ const remote = await fetchGitHubFile({
501
+ repository: source.repository,
502
+ ref: source.sha,
503
+ path: `${source.path ?? SCHEMA_DIR}/${name}`,
504
+ token,
505
+ });
506
+ if (sha256(remote) !== source.files[name]) {
507
+ problems.push(
508
+ `${SCHEMA_DIR}/${name} differs from ${source.repository}@${source.ref} (${source.sha})`,
509
+ );
510
+ }
511
+ }
512
+ return { ok: problems.length === 0, problems };
513
+ }