@kizunajs/cli 2.0.0-beta.3 → 2.0.0-beta.5

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,9 +1,10 @@
1
1
  import { createJiti } from "jiti";
2
2
  import { apiEntries } from "kizunajs";
3
3
  import { createGenerator, deriveToolNames, flattenJobs, readDef, readObjectShape, resolveResponseBody, toToolName, unwrapOptionalWrappers } from "kizunajs/generator";
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { parse, stringify } from "yaml";
4
6
  import { flattenRoutes } from "kizunajs/adapter";
5
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
8
  import ts from "typescript";
8
9
  import { execFileSync } from "node:child_process";
9
10
  //#region src/load-config.ts
@@ -24,49 +25,22 @@ const loadConfig = async (configPath) => {
24
25
  name,
25
26
  api: entry.api,
26
27
  clients: entry.clients ?? [],
27
- typesOutput: entry.typescript?.outputFile
28
+ typesOutput: entry.typescript?.outputFile,
29
+ diff: entry.diff ?? {}
28
30
  }));
29
31
  };
30
32
  //#endregion
31
33
  //#region src/diff-schemas.ts
32
- const shapeOf = (schema) => {
33
- const { inner } = unwrapOptionalWrappers(schema);
34
- const raw = readObjectShape(inner);
35
- if (!raw) return void 0;
36
- const fields = /* @__PURE__ */ new Map();
37
- for (const [key, field] of Object.entries(raw)) fields.set(key, {
38
- schema: field,
39
- optional: unwrapOptionalWrappers(field).optional
40
- });
41
- return { fields };
42
- };
43
- /**
44
- * What a schema accepts, flattened enough to compare: its kind, and its values
45
- * when it is closed.
46
- */
47
- const describe = (schema) => {
48
- const { inner } = unwrapOptionalWrappers(schema);
49
- const def = readDef(inner);
50
- if (def.type === "enum") return {
51
- kind: "enum",
52
- values: Object.values(def.entries ?? {}).map(String).sort()
53
- };
54
- if (def.type === "literal") return {
55
- kind: "enum",
56
- values: (def.values ?? []).map(String).sort()
57
- };
58
- if (def.type === "array" && def.element) return { kind: `array<${describe(def.element).kind}>` };
59
- return { kind: def.type ?? "unknown" };
60
- };
61
34
  const joinPath = (parent, key) => parent === "" ? key : `${parent}.${key}`;
35
+ const fieldsOf = (schema) => schema.kind === "object" ? schema.fields : void 0;
36
+ const elementOf = (schema) => schema.kind === "array" ? schema.element : void 0;
37
+ const valuesOf = (schema) => schema.kind === "enum" ? schema.values : void 0;
62
38
  /**
63
- * The element of an array, so a change inside one is reported at its own path
64
- * rather than as the whole array changing shape.
39
+ * What a reader sees when the kinds differ, so `array` reads as `array<string>`.
65
40
  */
66
- const elementOf = (schema) => {
67
- const { inner } = unwrapOptionalWrappers(schema);
68
- const def = readDef(inner);
69
- return def.type === "array" ? def.element : void 0;
41
+ const describeKind = (schema) => {
42
+ const element = elementOf(schema);
43
+ return element ? `array<${describeKind(element)}>` : schema.kind;
70
44
  };
71
45
  /**
72
46
  * What changed between two versions of one schema, and whether it breaks the
@@ -88,11 +62,11 @@ const diffSchemas = (before, after, direction, path = "") => {
88
62
  const beforeElement = elementOf(before);
89
63
  const afterElement = elementOf(after);
90
64
  if (beforeElement && afterElement) return diffSchemas(beforeElement, afterElement, direction, `${path}[]`);
91
- const beforeShape = shapeOf(before);
92
- const afterShape = shapeOf(after);
93
- if (beforeShape && afterShape) {
94
- for (const [key, field] of afterShape.fields) {
95
- const existing = beforeShape.fields.get(key);
65
+ const beforeFields = fieldsOf(before);
66
+ const afterFields = fieldsOf(after);
67
+ if (beforeFields && afterFields) {
68
+ for (const [key, field] of Object.entries(afterFields)) {
69
+ const existing = beforeFields[key];
96
70
  const here = joinPath(path, key);
97
71
  if (!existing) {
98
72
  if (!field.optional) changes.push({
@@ -109,8 +83,8 @@ const diffSchemas = (before, after, direction, path = "") => {
109
83
  });
110
84
  changes.push(...diffSchemas(existing.schema, field.schema, direction, here));
111
85
  }
112
- for (const [key] of beforeShape.fields) {
113
- if (afterShape.fields.has(key)) continue;
86
+ for (const key of Object.keys(beforeFields)) {
87
+ if (afterFields[key]) continue;
114
88
  const here = joinPath(path, key);
115
89
  changes.push({
116
90
  breaking: direction === "response",
@@ -120,19 +94,16 @@ const diffSchemas = (before, after, direction, path = "") => {
120
94
  }
121
95
  return changes;
122
96
  }
123
- const was = describe(before);
124
- const now = describe(after);
125
- if (was.kind !== now.kind) {
126
- changes.push({
127
- breaking: true,
128
- path,
129
- summary: `${path || "the body"} is ${now.kind} instead of ${was.kind}`
130
- });
131
- return changes;
132
- }
133
- if (was.values && now.values) {
134
- const removed = was.values.filter((value) => !now.values?.includes(value));
135
- const added = now.values.filter((value) => !was.values?.includes(value));
97
+ if (before.kind !== after.kind) return [{
98
+ breaking: true,
99
+ path,
100
+ summary: `${path || "the body"} is ${describeKind(after)} instead of ${describeKind(before)}`
101
+ }];
102
+ const was = valuesOf(before);
103
+ const now = valuesOf(after);
104
+ if (was && now) {
105
+ const removed = was.filter((value) => !now.includes(value));
106
+ const added = now.filter((value) => !was.includes(value));
136
107
  if (removed.length > 0) changes.push({
137
108
  breaking: true,
138
109
  path,
@@ -144,53 +115,145 @@ const diffSchemas = (before, after, direction, path = "") => {
144
115
  summary: direction === "response" ? `${path || "the body"} can now be ${added.join(", ")}` : `${path || "the body"} also accepts ${added.join(", ")}`
145
116
  });
146
117
  }
118
+ const wasRefined = before.refinements ?? 0;
119
+ const isRefined = after.refinements ?? 0;
120
+ if (wasRefined !== isRefined) changes.push({
121
+ breaking: direction === "request" && isRefined > wasRefined,
122
+ path,
123
+ summary: isRefined > wasRefined ? `${path || "the body"} is validated more tightly` : `${path || "the body"} is validated less tightly`
124
+ });
147
125
  return changes;
148
126
  };
149
127
  //#endregion
150
- //#region src/diff-apis.ts
151
- const routeFacts = createGenerator(() => {
152
- const facts = /* @__PURE__ */ new Map();
128
+ //#region src/snapshot.ts
129
+ /**
130
+ * How many `.refine()` or `.superRefine()` calls a schema carries. The
131
+ * predicate itself cannot be compared across two files, but its arrival or
132
+ * departure can.
133
+ */
134
+ const refinementCount = (schema) => {
135
+ const checks = readDef(schema).checks;
136
+ if (!checks) return void 0;
137
+ const custom = checks.filter((check) => check._zod?.def?.check === "custom").length;
138
+ return custom === 0 ? void 0 : custom;
139
+ };
140
+ /**
141
+ * A Zod schema reduced to the shape a comparison reads.
142
+ */
143
+ const toSchemaNode = (schema) => {
144
+ const { inner } = unwrapOptionalWrappers(schema);
145
+ const def = readDef(inner);
146
+ const refinements = refinementCount(inner);
147
+ const carry = refinements === void 0 ? {} : { refinements };
148
+ const shape = readObjectShape(inner);
149
+ if (shape) {
150
+ const fields = {};
151
+ for (const [key, field] of Object.entries(shape)) fields[key] = {
152
+ optional: unwrapOptionalWrappers(field).optional,
153
+ schema: toSchemaNode(field)
154
+ };
155
+ return {
156
+ kind: "object",
157
+ fields,
158
+ ...carry
159
+ };
160
+ }
161
+ if (def.type === "array" && def.element) return {
162
+ kind: "array",
163
+ element: toSchemaNode(def.element),
164
+ ...carry
165
+ };
166
+ if (def.type === "enum") return {
167
+ kind: "enum",
168
+ values: Object.values(def.entries ?? {}).map(String).sort(),
169
+ ...carry
170
+ };
171
+ if (def.type === "literal") return {
172
+ kind: "enum",
173
+ values: (def.values ?? []).map(String).sort(),
174
+ ...carry
175
+ };
176
+ return {
177
+ kind: def.type ?? "unknown",
178
+ ...carry
179
+ };
180
+ };
181
+ const sunsetOf = (route) => {
182
+ const declared = route.sunset;
183
+ if (declared === void 0) return void 0;
184
+ return typeof declared === "string" ? declared : declared.date;
185
+ };
186
+ const routeSnapshots = createGenerator(() => {
187
+ const routes = {};
153
188
  return {
154
189
  processRoute({ routeKey, route, deprecated }) {
155
- facts.set(routeKey, {
190
+ const sunset = sunsetOf(route);
191
+ const responses = {};
192
+ for (const [status, response] of Object.entries(route.responses)) {
193
+ const body = resolveResponseBody(response);
194
+ responses[status] = body === void 0 ? null : toSchemaNode(body);
195
+ }
196
+ routes[routeKey] = {
156
197
  method: route.method,
157
198
  path: route.path,
158
- statuses: Object.keys(route.responses).map(Number).sort(),
199
+ statuses: Object.keys(route.responses).map(Number).sort((a, b) => a - b),
159
200
  deprecated,
160
- ...sunsetOf(route) === void 0 ? {} : { sunset: sunsetOf(route) },
161
- ...route.body ? { body: route.body } : {},
162
- ...route.query ? { query: route.query } : {},
163
- ...route.headers ? { headers: route.headers } : {},
164
- responses: new Map(Object.entries(route.responses).map(([status, response]) => [Number(status), resolveResponseBody(response)]))
165
- });
201
+ ...sunset === void 0 ? {} : { sunset },
202
+ ...route.body ? { body: toSchemaNode(route.body) } : {},
203
+ ...route.query ? { query: toSchemaNode(route.query) } : {},
204
+ ...route.headers ? { headers: toSchemaNode(route.headers) } : {},
205
+ responses
206
+ };
166
207
  },
167
- finalize: () => facts
208
+ finalize: () => routes
168
209
  };
169
210
  });
170
- const sunsetOf = (route) => {
171
- const declared = route.sunset;
172
- if (declared === void 0) return void 0;
173
- return typeof declared === "string" ? declared : declared.date;
174
- };
175
- const jobKeys = (contract) => {
176
- const jobs = contract.jobs;
177
- if (!jobs) return /* @__PURE__ */ new Set();
178
- return new Set(flattenJobs(jobs).map((job) => job.jobKey));
211
+ /**
212
+ * Everything `kizuna diff` compares, as plain data.
213
+ *
214
+ * Writing this at each commit is what lets a comparison read the other side
215
+ * out of git rather than checking it out and running it.
216
+ */
217
+ const toSnapshot = (api) => {
218
+ const declared = api.jobs;
219
+ const jobs = declared ? flattenJobs(declared).map((job) => job.jobKey).sort() : [];
220
+ const tools = Object.fromEntries(flattenRoutes(api.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, toToolName(routeKey)]));
221
+ return {
222
+ routes: routeSnapshots(api, {}),
223
+ jobs,
224
+ tools
225
+ };
179
226
  };
180
227
  /**
181
- * The MCP name of every route that publishes as a tool, keyed by route key.
228
+ * YAML rather than JSON, so the file a reviewer opens in a pull request reads
229
+ * as the API rather than as punctuation.
182
230
  */
183
- const toolNames = (contract) => new Map(flattenRoutes(contract.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, toToolName(routeKey)]));
231
+ const renderSnapshot = (api) => stringify(toSnapshot(api), { lineWidth: 0 });
184
232
  /**
185
- * What changed between two apis, worst first.
186
- *
187
- * Compares the declarations rather than an OpenAPI document, so it sees route
188
- * keys, MCP tool names and job keys, none of which a document carries.
233
+ * Where a config's snapshot lives. `.kizuna/` sits beside the config, so CI
234
+ * always knows where to look without being told, and a repository holding
235
+ * several configs keeps one snapshot per config.
236
+ */
237
+ const snapshotPathFor = (configPath) => {
238
+ const declared = basename(configPath).replace(/\.config\.[cm]?[jt]s$/, "").replace(/^kizuna\./, "");
239
+ const name = declared === "" || declared === "kizuna" ? "diff" : `${declared}.diff`;
240
+ return join(dirname(configPath), ".kizuna", `${name}.yaml`);
241
+ };
242
+ /**
243
+ * The snapshot as a client target, so `kizuna generate` writes it and
244
+ * `kizuna generate --check` refuses to let it go stale.
189
245
  */
190
- const diffApis = (before, after) => {
246
+ const snapshotTarget = (configPath) => ({
247
+ kind: "diff",
248
+ output: snapshotPathFor(configPath),
249
+ generate: renderSnapshot
250
+ });
251
+ //#endregion
252
+ //#region src/diff-apis.ts
253
+ const diffSnapshots = (before, after, options = {}) => {
191
254
  const changes = [];
192
- const beforeRoutes = routeFacts(before, {});
193
- const afterRoutes = routeFacts(after, {});
255
+ const beforeRoutes = new Map(Object.entries(before.routes));
256
+ const afterRoutes = new Map(Object.entries(after.routes));
194
257
  const removed = [...beforeRoutes.keys()].filter((key) => !afterRoutes.has(key));
195
258
  const added = [...afterRoutes.keys()].filter((key) => !beforeRoutes.has(key));
196
259
  const renames = /* @__PURE__ */ new Map();
@@ -207,10 +270,10 @@ const diffApis = (before, after) => {
207
270
  if (match) renames.set(match, goneKey);
208
271
  }
209
272
  for (const [toKey, fromKey] of renames) changes.push({
210
- level: "breaking",
273
+ level: options.dottedKeys ? "breaking" : "changed",
211
274
  key: fromKey,
212
275
  summary: `${fromKey} renamed to ${toKey}`,
213
- detail: "client method and generated client names change, HTTP surface unaffected"
276
+ detail: "the generated client method changes name, the HTTP surface does not"
214
277
  });
215
278
  for (const key of removed) {
216
279
  if ([...renames.values()].includes(key)) continue;
@@ -283,10 +346,10 @@ const diffApis = (before, after) => {
283
346
  key,
284
347
  summary: `${httpLabel(arrived, key)} ${change.summary}`
285
348
  });
286
- for (const [status, was] of gone.responses) {
287
- const now = arrived.responses.get(status);
288
- if (!arrived.responses.has(status)) continue;
289
- for (const change of diffSchemas(was, now, "response", `${status}`)) changes.push({
349
+ for (const [status, was] of Object.entries(gone.responses)) {
350
+ if (!(status in arrived.responses)) continue;
351
+ const now = arrived.responses[status];
352
+ for (const change of diffSchemas(was ?? void 0, now ?? void 0, "response", status)) changes.push({
290
353
  level: change.breaking ? "breaking" : "changed",
291
354
  key,
292
355
  summary: `${httpLabel(arrived, key)} ${change.summary}`
@@ -303,8 +366,8 @@ const diffApis = (before, after) => {
303
366
  summary: `${httpLabel(arrived, key)} sunsets on ${arrived.sunset}`
304
367
  });
305
368
  }
306
- for (const key of jobKeys(before)) {
307
- if (jobKeys(after).has(key)) continue;
369
+ for (const key of options.jobs ? before.jobs : []) {
370
+ if (after.jobs.includes(key)) continue;
308
371
  changes.push({
309
372
  level: "breaking",
310
373
  key,
@@ -312,10 +375,8 @@ const diffApis = (before, after) => {
312
375
  detail: "whatever calls POST /jobs/run with that key stops working"
313
376
  });
314
377
  }
315
- const beforeTools = toolNames(before);
316
- const afterTools = toolNames(after);
317
- for (const [key, name] of beforeTools) {
318
- const arrived = afterTools.get(key);
378
+ for (const [key, name] of options.tools ? Object.entries(before.tools) : []) {
379
+ const arrived = after.tools[key];
319
380
  if (arrived === void 0) {
320
381
  changes.push({
321
382
  level: "breaking",
@@ -340,6 +401,13 @@ const diffApis = (before, after) => {
340
401
  return changes.sort((left, right) => order[left.level] - order[right.level] || left.key.localeCompare(right.key));
341
402
  };
342
403
  /**
404
+ * What changed between two apis, for a caller holding both in memory.
405
+ *
406
+ * `kizuna diff` reads snapshots instead, so it never has to load the other
407
+ * side's code.
408
+ */
409
+ const diffApis = (before, after, options = {}) => diffSnapshots(toSnapshot(before), toSnapshot(after), options);
410
+ /**
343
411
  * One block per change, ready to print: the level, the summary, and the
344
412
  * detail indented beneath it.
345
413
  */
@@ -408,7 +476,7 @@ const formatStale = (stale, command = "kizuna generate") => {
408
476
  return client.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the config`;
409
477
  });
410
478
  return [
411
- stale.length === 1 ? "A generated client is out of date:" : `${stale.length} generated clients are out of date:`,
479
+ stale.length === 1 ? "A generated file is out of date:" : `${stale.length} generated files are out of date:`,
412
480
  ...lines,
413
481
  "",
414
482
  `Run \`${command}\` and commit the result.`
@@ -647,44 +715,59 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts", output
647
715
  //#region src/diff-against.ts
648
716
  const git = (cwd, ...args) => execFileSync("git", args, {
649
717
  cwd,
650
- encoding: "utf8"
718
+ encoding: "utf8",
719
+ stdio: [
720
+ "ignore",
721
+ "pipe",
722
+ "ignore"
723
+ ]
651
724
  }).trim();
652
725
  /**
653
- * Compares the config on disk against the same config at a git ref.
654
- *
655
- * The ref is checked out into a worktree inside the repository, which costs a
656
- * few files rather than a clone. Nothing is installed there: module resolution
657
- * walks up to the repository's own `node_modules`, so the base tree needs only
658
- * its source.
659
- *
660
- * @example
661
- * const changes = await diffAgainst('main', './src/contract.ts');
726
+ * The repository holding the snapshot, falling back to the one the caller ran in.
662
727
  */
663
- const diffAgainst = async (ref, configPath, options = {}) => {
664
- const { cwd = process.cwd() } = options;
665
- const root = git(cwd, "rev-parse", "--show-toplevel");
666
- const absolute = isAbsolute(configPath) ? configPath : resolve(cwd, configPath);
667
- const fromRoot = relative(root, absolute);
668
- if (fromRoot.startsWith("..")) throw new Error(`${configPath} is outside the repository at ${root}`);
669
- const worktree = mkdtempSync(join(root, ".kizuna-diff-"));
728
+ const repositoryFor = (directory, cwd) => {
670
729
  try {
671
- git(root, "worktree", "add", "--detach", "--force", worktree, ref);
672
- const [before] = await loadConfig(join(worktree, fromRoot));
673
- if (before === void 0) throw new Error(`No config found in ${fromRoot} at ${ref}`);
674
- const [after] = await loadConfig(absolute);
675
- if (after === void 0) throw new Error(`No config found in ${configPath}`);
676
- return diffApis(before.api, after.api);
677
- } finally {
678
- try {
679
- git(root, "worktree", "remove", "--force", worktree);
680
- } catch {
681
- rmSync(worktree, {
682
- recursive: true,
683
- force: true
684
- });
685
- }
730
+ return git(directory, "rev-parse", "--show-toplevel");
731
+ } catch {
732
+ return git(cwd, "rev-parse", "--show-toplevel");
733
+ }
734
+ };
735
+ const parseSnapshot = (contents, source) => {
736
+ try {
737
+ return parse(contents);
738
+ } catch {
739
+ throw new Error(`${source} is not a Kizuna diff file. Run \`kizuna generate\` to write one.`);
686
740
  }
687
741
  };
742
+ /**
743
+ * Reads a path out of a ref without checking anything out.
744
+ */
745
+ const showAtRef = (root, ref, path) => {
746
+ try {
747
+ return git(root, "show", `${ref}:${path}`);
748
+ } catch {
749
+ throw new Error(`${path} does not exist at ${ref}. It was added or renamed since, so there is nothing to compare against.`);
750
+ }
751
+ };
752
+ const readSnapshot = (path) => {
753
+ if (!existsSync(path)) throw new Error(`No snapshot at ${path}. Run \`kizuna generate\` to write one.`);
754
+ return parseSnapshot(readFileSync(path, "utf8"), path);
755
+ };
756
+ /**
757
+ * Compares a snapshot against the same file at a git ref.
758
+ *
759
+ * The ref is read with `git show`, so nothing is checked out, installed or
760
+ * executed for the other side. A snapshot written a year ago compares fine
761
+ * against one written today.
762
+ */
763
+ const diffAgainst = (ref, snapshotPath, options = {}) => {
764
+ const { cwd = process.cwd(), ...diff } = options;
765
+ const absolute = isAbsolute(snapshotPath) ? snapshotPath : resolve(cwd, snapshotPath);
766
+ const root = repositoryFor(dirname(absolute), cwd);
767
+ const fromRoot = relative(root, absolute);
768
+ if (fromRoot.startsWith("..")) throw new Error(`${snapshotPath} is outside the repository at ${root}`);
769
+ return diffSnapshots(parseSnapshot(showAtRef(root, ref, fromRoot.split("\\").join("/")), `${fromRoot} at ${ref}`), readSnapshot(absolute), diff);
770
+ };
688
771
  //#endregion
689
772
  //#region src/route-map.ts
690
773
  const permissionList = (requires) => {
@@ -763,4 +846,4 @@ const formatRoutes = (entries) => {
763
846
  }).join("\n");
764
847
  };
765
848
  //#endregion
766
- export { generateConfigTypes as a, writeClients as c, hasBreakingChange as d, diffSchemas as f, ConfigSyntaxError as i, diffApis as l, routeMap as n, checkClients as o, loadConfig as p, diffAgainst as r, formatStale as s, formatRoutes as t, formatChange as u };
849
+ export { loadConfig as _, ConfigSyntaxError as a, formatStale as c, diffSnapshots as d, formatChange as f, diffSchemas as g, snapshotTarget as h, readSnapshot as i, writeClients as l, snapshotPathFor as m, routeMap as n, generateConfigTypes as o, hasBreakingChange as p, diffAgainst as r, checkClients as s, formatRoutes as t, diffApis as u };