@kizunajs/cli 2.0.0-beta.2 → 2.0.0-beta.20

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.
@@ -23,9 +23,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  let jiti = require("jiti");
24
24
  let kizunajs = require("kizunajs");
25
25
  let kizunajs_generator = require("kizunajs/generator");
26
+ let node_path = require("node:path");
27
+ let yaml = require("yaml");
26
28
  let kizunajs_adapter = require("kizunajs/adapter");
27
29
  let node_fs = require("node:fs");
28
- let node_path = require("node:path");
29
30
  let typescript = require("typescript");
30
31
  typescript = __toESM(typescript, 1);
31
32
  let node_child_process = require("node:child_process");
@@ -39,53 +40,31 @@ let node_child_process = require("node:child_process");
39
40
  * a config.
40
41
  */
41
42
  const loadConfig = async (configPath) => {
42
- return (0, kizunajs.apiEntries)(await (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, { interopDefault: true }).import(configPath)).map(([name, entry]) => ({
43
+ return (0, kizunajs.apiEntries)(await (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, {
44
+ interopDefault: true,
45
+ jsx: true,
46
+ tsconfigPaths: true
47
+ }).import(configPath)).map(([name, entry]) => ({
43
48
  name,
44
49
  api: entry.api,
45
50
  clients: entry.clients ?? [],
46
- typesOutput: entry.typescript?.outputFile
51
+ generators: entry.generators ?? [],
52
+ typesOutput: entry.typescript?.outputFile,
53
+ diff: entry.diff ?? {}
47
54
  }));
48
55
  };
49
56
  //#endregion
50
57
  //#region src/diff-schemas.ts
51
- const shapeOf = (schema) => {
52
- const { inner } = (0, kizunajs_generator.unwrapOptionalWrappers)(schema);
53
- const raw = (0, kizunajs_generator.readObjectShape)(inner);
54
- if (!raw) return void 0;
55
- const fields = /* @__PURE__ */ new Map();
56
- for (const [key, field] of Object.entries(raw)) fields.set(key, {
57
- schema: field,
58
- optional: (0, kizunajs_generator.unwrapOptionalWrappers)(field).optional
59
- });
60
- return { fields };
61
- };
62
- /**
63
- * What a schema accepts, flattened enough to compare: its kind, and its values
64
- * when it is closed.
65
- */
66
- const describe = (schema) => {
67
- const { inner } = (0, kizunajs_generator.unwrapOptionalWrappers)(schema);
68
- const def = (0, kizunajs_generator.readDef)(inner);
69
- if (def.type === "enum") return {
70
- kind: "enum",
71
- values: Object.values(def.entries ?? {}).map(String).sort()
72
- };
73
- if (def.type === "literal") return {
74
- kind: "enum",
75
- values: (def.values ?? []).map(String).sort()
76
- };
77
- if (def.type === "array" && def.element) return { kind: `array<${describe(def.element).kind}>` };
78
- return { kind: def.type ?? "unknown" };
79
- };
80
58
  const joinPath = (parent, key) => parent === "" ? key : `${parent}.${key}`;
59
+ const fieldsOf = (schema) => schema.kind === "object" ? schema.fields : void 0;
60
+ const elementOf = (schema) => schema.kind === "array" ? schema.element : void 0;
61
+ const valuesOf = (schema) => schema.kind === "enum" ? schema.values : void 0;
81
62
  /**
82
- * The element of an array, so a change inside one is reported at its own path
83
- * rather than as the whole array changing shape.
63
+ * What a reader sees when the kinds differ, so `array` reads as `array<string>`.
84
64
  */
85
- const elementOf = (schema) => {
86
- const { inner } = (0, kizunajs_generator.unwrapOptionalWrappers)(schema);
87
- const def = (0, kizunajs_generator.readDef)(inner);
88
- return def.type === "array" ? def.element : void 0;
65
+ const describeKind = (schema) => {
66
+ const element = elementOf(schema);
67
+ return element ? `array<${describeKind(element)}>` : schema.kind;
89
68
  };
90
69
  /**
91
70
  * What changed between two versions of one schema, and whether it breaks the
@@ -103,15 +82,30 @@ const diffSchemas = (before, after, direction, path = "") => {
103
82
  path,
104
83
  summary: `${path || "the body"} is gone`
105
84
  }];
85
+ if (before.kind !== after.kind) return [{
86
+ breaking: true,
87
+ path,
88
+ summary: `${path || "the body"} is ${describeKind(after)} instead of ${describeKind(before)}`
89
+ }];
106
90
  const changes = [];
91
+ const wasNullable = before.nullable === true;
92
+ const isNullable = after.nullable === true;
93
+ if (wasNullable !== isNullable) changes.push({
94
+ breaking: direction === (isNullable ? "response" : "request"),
95
+ path,
96
+ summary: isNullable ? `${path || "the body"} can now be null` : `${path || "the body"} can no longer be null`
97
+ });
107
98
  const beforeElement = elementOf(before);
108
99
  const afterElement = elementOf(after);
109
- if (beforeElement && afterElement) return diffSchemas(beforeElement, afterElement, direction, `${path}[]`);
110
- const beforeShape = shapeOf(before);
111
- const afterShape = shapeOf(after);
112
- if (beforeShape && afterShape) {
113
- for (const [key, field] of afterShape.fields) {
114
- const existing = beforeShape.fields.get(key);
100
+ if (beforeElement && afterElement) {
101
+ changes.push(...diffSchemas(beforeElement, afterElement, direction, `${path}[]`));
102
+ return changes;
103
+ }
104
+ const beforeFields = fieldsOf(before);
105
+ const afterFields = fieldsOf(after);
106
+ if (beforeFields && afterFields) {
107
+ for (const [key, field] of Object.entries(afterFields)) {
108
+ const existing = beforeFields[key];
115
109
  const here = joinPath(path, key);
116
110
  if (!existing) {
117
111
  if (!field.optional) changes.push({
@@ -126,10 +120,15 @@ const diffSchemas = (before, after, direction, path = "") => {
126
120
  path: here,
127
121
  summary: `${here} is no longer optional`
128
122
  });
123
+ if (!existing.optional && field.optional) changes.push({
124
+ breaking: direction === "response",
125
+ path: here,
126
+ summary: direction === "response" ? `${here} may now be left out` : `${here} is now optional`
127
+ });
129
128
  changes.push(...diffSchemas(existing.schema, field.schema, direction, here));
130
129
  }
131
- for (const [key] of beforeShape.fields) {
132
- if (afterShape.fields.has(key)) continue;
130
+ for (const key of Object.keys(beforeFields)) {
131
+ if (afterFields[key]) continue;
133
132
  const here = joinPath(path, key);
134
133
  changes.push({
135
134
  breaking: direction === "response",
@@ -139,19 +138,11 @@ const diffSchemas = (before, after, direction, path = "") => {
139
138
  }
140
139
  return changes;
141
140
  }
142
- const was = describe(before);
143
- const now = describe(after);
144
- if (was.kind !== now.kind) {
145
- changes.push({
146
- breaking: true,
147
- path,
148
- summary: `${path || "the body"} is ${now.kind} instead of ${was.kind}`
149
- });
150
- return changes;
151
- }
152
- if (was.values && now.values) {
153
- const removed = was.values.filter((value) => !now.values?.includes(value));
154
- const added = now.values.filter((value) => !was.values?.includes(value));
141
+ const was = valuesOf(before);
142
+ const now = valuesOf(after);
143
+ if (was && now) {
144
+ const removed = was.filter((value) => !now.includes(value));
145
+ const added = now.filter((value) => !was.includes(value));
155
146
  if (removed.length > 0) changes.push({
156
147
  breaking: true,
157
148
  path,
@@ -163,53 +154,157 @@ const diffSchemas = (before, after, direction, path = "") => {
163
154
  summary: direction === "response" ? `${path || "the body"} can now be ${added.join(", ")}` : `${path || "the body"} also accepts ${added.join(", ")}`
164
155
  });
165
156
  }
157
+ const wasRefined = before.refinements ?? 0;
158
+ const isRefined = after.refinements ?? 0;
159
+ if (wasRefined !== isRefined) changes.push({
160
+ breaking: direction === "request" && isRefined > wasRefined,
161
+ path,
162
+ summary: isRefined > wasRefined ? `${path || "the body"} is validated more tightly` : `${path || "the body"} is validated less tightly`
163
+ });
166
164
  return changes;
167
165
  };
168
166
  //#endregion
169
- //#region src/diff-apis.ts
170
- const routeFacts = (0, kizunajs_generator.createGenerator)(() => {
171
- const facts = /* @__PURE__ */ new Map();
167
+ //#region src/snapshot.ts
168
+ /**
169
+ * How many `.refine()` or `.superRefine()` calls a schema carries. The
170
+ * predicate itself cannot be compared across two files, but its arrival or
171
+ * departure can.
172
+ */
173
+ const refinementCount = (schema) => {
174
+ const checks = (0, kizunajs_generator.readDef)(schema).checks;
175
+ if (!checks) return void 0;
176
+ const custom = checks.filter((check) => check._zod?.def?.check === "custom").length;
177
+ return custom === 0 ? void 0 : custom;
178
+ };
179
+ /**
180
+ * A Zod schema reduced to the shape a comparison reads.
181
+ */
182
+ const toSchemaNode = (schema) => {
183
+ const { inner, nullable } = (0, kizunajs_generator.unwrapOptionalWrappers)(schema);
184
+ const def = (0, kizunajs_generator.readDef)(inner);
185
+ const options = def.type === "union" ? def.options ?? [] : [];
186
+ const nonNull = options.filter((option) => (0, kizunajs_generator.readDef)(option).type !== "null");
187
+ if (nonNull.length === 1 && options.length > 1) return {
188
+ ...toSchemaNode(nonNull[0]),
189
+ nullable: true
190
+ };
191
+ const nullability = nullable ? { nullable: true } : {};
192
+ const refinements = refinementCount(inner);
193
+ const carry = refinements === void 0 ? {} : { refinements };
194
+ const shape = (0, kizunajs_generator.readObjectShape)(inner);
195
+ if (shape) {
196
+ const fields = {};
197
+ for (const [key, field] of Object.entries(shape)) fields[key] = {
198
+ optional: (0, kizunajs_generator.unwrapOptionalWrappers)(field).optional,
199
+ schema: toSchemaNode(field)
200
+ };
201
+ return {
202
+ kind: "object",
203
+ ...nullability,
204
+ fields,
205
+ ...carry
206
+ };
207
+ }
208
+ if (def.type === "array" && def.element) return {
209
+ kind: "array",
210
+ ...nullability,
211
+ element: toSchemaNode(def.element),
212
+ ...carry
213
+ };
214
+ if (def.type === "enum") return {
215
+ kind: "enum",
216
+ ...nullability,
217
+ values: Object.values(def.entries ?? {}).map(String).sort(),
218
+ ...carry
219
+ };
220
+ if (def.type === "literal") return {
221
+ kind: "enum",
222
+ ...nullability,
223
+ values: (def.values ?? []).map(String).sort(),
224
+ ...carry
225
+ };
172
226
  return {
173
- processRoute({ routeKey, route, deprecated }) {
174
- facts.set(routeKey, {
175
- method: route.method,
176
- path: route.path,
177
- statuses: Object.keys(route.responses).map(Number).sort(),
178
- deprecated,
179
- ...sunsetOf(route) === void 0 ? {} : { sunset: sunsetOf(route) },
180
- ...route.body ? { body: route.body } : {},
181
- ...route.query ? { query: route.query } : {},
182
- ...route.headers ? { headers: route.headers } : {},
183
- responses: new Map(Object.entries(route.responses).map(([status, response]) => [Number(status), (0, kizunajs_generator.resolveResponseBody)(response)]))
184
- });
185
- },
186
- finalize: () => facts
227
+ kind: def.type ?? "unknown",
228
+ ...nullability,
229
+ ...carry
187
230
  };
188
- });
231
+ };
189
232
  const sunsetOf = (route) => {
190
233
  const declared = route.sunset;
191
234
  if (declared === void 0) return void 0;
192
235
  return typeof declared === "string" ? declared : declared.date;
193
236
  };
194
- const jobKeys = (contract) => {
195
- const jobs = contract.jobs;
196
- if (!jobs) return /* @__PURE__ */ new Set();
197
- return new Set((0, kizunajs_generator.flattenJobs)(jobs).map((job) => job.jobKey));
237
+ const routeSnapshots = (api) => {
238
+ const routes = {};
239
+ return (0, kizunajs_generator.walkApi)(api, {
240
+ processRoute({ routeKey, route, deprecated, hidden }) {
241
+ const sunset = sunsetOf(route);
242
+ const responses = {};
243
+ for (const [status, response] of Object.entries(route.responses)) {
244
+ const body = (0, kizunajs_generator.resolveResponseBody)(response);
245
+ responses[status] = body === void 0 ? null : toSchemaNode(body);
246
+ }
247
+ routes[routeKey] = {
248
+ method: route.method,
249
+ path: route.path,
250
+ statuses: Object.keys(route.responses).map(Number).sort((a, b) => a - b),
251
+ deprecated,
252
+ ...hidden ? { hidden: true } : {},
253
+ ...sunset === void 0 ? {} : { sunset },
254
+ ...route.body ? { body: toSchemaNode(route.body) } : {},
255
+ ...route.query ? { query: toSchemaNode(route.query) } : {},
256
+ ...route.headers ? { headers: toSchemaNode(route.headers) } : {},
257
+ responses
258
+ };
259
+ },
260
+ finalize: () => routes
261
+ });
198
262
  };
199
263
  /**
200
- * The MCP name of every route that publishes as a tool, keyed by route key.
264
+ * Everything `kizuna diff` compares, as plain data.
265
+ *
266
+ * Writing this at each commit is what lets a comparison read the other side
267
+ * out of git rather than checking it out and running it.
201
268
  */
202
- const toolNames = (contract) => new Map((0, kizunajs_adapter.flattenRoutes)(contract.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, (0, kizunajs_generator.toToolName)(routeKey)]));
269
+ const toSnapshot = (api) => {
270
+ const declared = api.jobs;
271
+ const jobs = declared ? (0, kizunajs_generator.flattenJobs)(declared).map((job) => job.jobKey).sort() : [];
272
+ const tools = Object.fromEntries((0, kizunajs_adapter.flattenRoutes)(api.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, (0, kizunajs_generator.toToolName)(routeKey)]));
273
+ return {
274
+ routes: routeSnapshots(api),
275
+ jobs,
276
+ tools
277
+ };
278
+ };
203
279
  /**
204
- * What changed between two apis, worst first.
205
- *
206
- * Compares the declarations rather than an OpenAPI document, so it sees route
207
- * keys, MCP tool names and job keys, none of which a document carries.
280
+ * YAML rather than JSON, so the file a reviewer opens in a pull request reads
281
+ * as the API rather than as punctuation.
208
282
  */
209
- const diffApis = (before, after) => {
283
+ const renderSnapshot = (api) => (0, yaml.stringify)(toSnapshot(api), { lineWidth: 0 });
284
+ /**
285
+ * Where a config's snapshot lives. `.kizuna/` sits beside the config, so CI
286
+ * always knows where to look without being told, and a repository holding
287
+ * several configs keeps one snapshot per config.
288
+ */
289
+ const snapshotPathFor = (configPath) => {
290
+ const declared = (0, node_path.basename)(configPath).replace(/\.config\.[cm]?[jt]s$/, "").replace(/^kizuna\./, "");
291
+ const name = declared === "" || declared === "kizuna" ? "snapshot" : `${declared}.snapshot`;
292
+ return (0, node_path.join)((0, node_path.dirname)(configPath), ".kizuna", `${name}.yaml`);
293
+ };
294
+ /**
295
+ * The snapshot as a client target, so `kizuna generate` writes it and
296
+ * `kizuna generate --check` refuses to let it go stale.
297
+ */
298
+ const snapshotTarget = (configPath) => ({
299
+ output: snapshotPathFor(configPath),
300
+ render: renderSnapshot
301
+ });
302
+ //#endregion
303
+ //#region src/diff-apis.ts
304
+ const diffSnapshots = (before, after, options = {}) => {
210
305
  const changes = [];
211
- const beforeRoutes = routeFacts(before, {});
212
- const afterRoutes = routeFacts(after, {});
306
+ const beforeRoutes = new Map(Object.entries(before.routes));
307
+ const afterRoutes = new Map(Object.entries(after.routes));
213
308
  const removed = [...beforeRoutes.keys()].filter((key) => !afterRoutes.has(key));
214
309
  const added = [...afterRoutes.keys()].filter((key) => !beforeRoutes.has(key));
215
310
  const renames = /* @__PURE__ */ new Map();
@@ -226,10 +321,10 @@ const diffApis = (before, after) => {
226
321
  if (match) renames.set(match, goneKey);
227
322
  }
228
323
  for (const [toKey, fromKey] of renames) changes.push({
229
- level: "breaking",
324
+ level: options.dottedKeys ? "breaking" : "changed",
230
325
  key: fromKey,
231
326
  summary: `${fromKey} renamed to ${toKey}`,
232
- detail: "client method and generated client names change, HTTP surface unaffected"
327
+ detail: "the generated client method changes name, the HTTP surface does not"
233
328
  });
234
329
  for (const key of removed) {
235
330
  if ([...renames.values()].includes(key)) continue;
@@ -302,15 +397,26 @@ const diffApis = (before, after) => {
302
397
  key,
303
398
  summary: `${httpLabel(arrived, key)} ${change.summary}`
304
399
  });
305
- for (const [status, was] of gone.responses) {
306
- const now = arrived.responses.get(status);
307
- if (!arrived.responses.has(status)) continue;
308
- for (const change of diffSchemas(was, now, "response", `${status}`)) changes.push({
400
+ for (const [status, was] of Object.entries(gone.responses)) {
401
+ if (!(status in arrived.responses)) continue;
402
+ const now = arrived.responses[status];
403
+ for (const change of diffSchemas(was ?? void 0, now ?? void 0, "response", status)) changes.push({
309
404
  level: change.breaking ? "breaking" : "changed",
310
405
  key,
311
406
  summary: `${httpLabel(arrived, key)} ${change.summary}`
312
407
  });
313
408
  }
409
+ if (gone.hidden !== true && arrived.hidden === true) changes.push({
410
+ level: "breaking",
411
+ key,
412
+ summary: `${httpLabel(arrived, key)} is now hidden`,
413
+ detail: "the server still serves it, but it is no longer in the generated clients or the OpenAPI document"
414
+ });
415
+ if (gone.hidden === true && arrived.hidden !== true) changes.push({
416
+ level: "added",
417
+ key,
418
+ summary: `${httpLabel(arrived, key)} is no longer hidden`
419
+ });
314
420
  if (!gone.deprecated && arrived.deprecated) changes.push({
315
421
  level: "changed",
316
422
  key,
@@ -322,8 +428,8 @@ const diffApis = (before, after) => {
322
428
  summary: `${httpLabel(arrived, key)} sunsets on ${arrived.sunset}`
323
429
  });
324
430
  }
325
- for (const key of jobKeys(before)) {
326
- if (jobKeys(after).has(key)) continue;
431
+ for (const key of options.jobs ? before.jobs : []) {
432
+ if (after.jobs.includes(key)) continue;
327
433
  changes.push({
328
434
  level: "breaking",
329
435
  key,
@@ -331,10 +437,8 @@ const diffApis = (before, after) => {
331
437
  detail: "whatever calls POST /jobs/run with that key stops working"
332
438
  });
333
439
  }
334
- const beforeTools = toolNames(before);
335
- const afterTools = toolNames(after);
336
- for (const [key, name] of beforeTools) {
337
- const arrived = afterTools.get(key);
440
+ for (const [key, name] of options.tools ? Object.entries(before.tools) : []) {
441
+ const arrived = after.tools[key];
338
442
  if (arrived === void 0) {
339
443
  changes.push({
340
444
  level: "breaking",
@@ -359,6 +463,13 @@ const diffApis = (before, after) => {
359
463
  return changes.sort((left, right) => order[left.level] - order[right.level] || left.key.localeCompare(right.key));
360
464
  };
361
465
  /**
466
+ * What changed between two apis, for a caller holding both in memory.
467
+ *
468
+ * `kizuna diff` reads snapshots instead, so it never has to load the other
469
+ * side's code.
470
+ */
471
+ const diffApis = (before, after, options = {}) => diffSnapshots(toSnapshot(before), toSnapshot(after), options);
472
+ /**
362
473
  * One block per change, ready to print: the level, the summary, and the
363
474
  * detail indented beneath it.
364
475
  */
@@ -381,38 +492,37 @@ const currentContents = (output) => {
381
492
  }
382
493
  };
383
494
  /**
384
- * Writes every client an api declares, leaving a file alone when it already
385
- * matches so watchers and build tools see no change.
495
+ * Writes every generated file, the clients and what plugins generate, leaving
496
+ * a file alone when it already matches so watchers and build tools see no
497
+ * change.
386
498
  */
387
- const writeClients = (contract, clients) => clients.map((client) => {
388
- const rendered = client.generate(contract);
389
- const changed = currentContents(client.output) !== rendered;
499
+ const writeFiles = (contract, files) => files.map((file) => {
500
+ const rendered = file.render(contract);
501
+ const changed = currentContents(file.output) !== rendered;
390
502
  if (changed) {
391
- (0, node_fs.mkdirSync)((0, node_path.dirname)(client.output), { recursive: true });
392
- (0, node_fs.writeFileSync)(client.output, rendered);
503
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(file.output), { recursive: true });
504
+ (0, node_fs.writeFileSync)(file.output, rendered);
393
505
  }
394
506
  return {
395
- kind: client.kind,
396
- output: client.output,
507
+ output: file.output,
397
508
  changed
398
509
  };
399
510
  });
400
511
  /**
401
- * Every client that no longer matches its api, without writing anything.
512
+ * Every generated file that no longer matches its api, without writing
513
+ * anything.
402
514
  *
403
515
  * This is what a pipeline runs: a generated client that has fallen behind is a
404
516
  * compile error waiting to happen in whatever imports it.
405
517
  */
406
- const checkClients = (contract, clients) => clients.flatMap((client) => {
407
- const current = currentContents(client.output);
518
+ const checkFiles = (contract, files) => files.flatMap((file) => {
519
+ const current = currentContents(file.output);
408
520
  if (current === void 0) return [{
409
- kind: client.kind,
410
- output: client.output,
521
+ output: file.output,
411
522
  reason: "missing"
412
523
  }];
413
- if (current !== client.generate(contract)) return [{
414
- kind: client.kind,
415
- output: client.output,
524
+ if (current !== file.render(contract)) return [{
525
+ output: file.output,
416
526
  reason: "outdated"
417
527
  }];
418
528
  return [];
@@ -422,12 +532,12 @@ const checkClients = (contract, clients) => clients.flatMap((client) => {
422
532
  * rather than printing a diff nobody reads.
423
533
  */
424
534
  const formatStale = (stale, command = "kizuna generate") => {
425
- const lines = stale.map((client) => {
426
- const where = (0, node_path.relative)(process.cwd(), client.output);
427
- return client.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the config`;
535
+ const lines = stale.map((file) => {
536
+ const where = (0, node_path.relative)(process.cwd(), file.output);
537
+ return file.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the config`;
428
538
  });
429
539
  return [
430
- stale.length === 1 ? "A generated client is out of date:" : `${stale.length} generated clients are out of date:`,
540
+ stale.length === 1 ? "A generated file is out of date:" : `${stale.length} generated files are out of date:`,
431
541
  ...lines,
432
542
  "",
433
543
  `Run \`${command}\` and commit the result.`
@@ -442,7 +552,7 @@ const formatStale = (stale, command = "kizuna generate") => {
442
552
  */
443
553
  const CONFIG_KEYS = [
444
554
  "adapter",
445
- "tags",
555
+ "groups",
446
556
  "auth",
447
557
  "requestContext",
448
558
  "validation",
@@ -551,12 +661,22 @@ const typeOfStringUnion = (expression, key) => {
551
661
  return codes.length > 0 ? codes.join(" | ") : "never";
552
662
  };
553
663
  /**
664
+ * The repo's Prettier `printWidth`. A line the generator writes longer than this
665
+ * is one `pnpm format` would rewrite, and `--check` would then report the file
666
+ * as behind.
667
+ */
668
+ const PRINT_WIDTH = 140;
669
+ /**
554
670
  * Each plugin in order, as a tuple, so a handler reaches each one under its own
555
- * slug.
671
+ * slug. It wraps one plugin per line when the line would run past
672
+ * {@link PRINT_WIDTH}, the way Prettier does.
556
673
  */
557
- const typeOfPluginList = (expression, used) => {
674
+ const typeOfPluginList = (expression, used, prefix) => {
558
675
  if (!typescript.default.isArrayLiteralExpression(expression)) throw new ConfigSyntaxError("`plugins` has to be an array, so each plugin keeps its place.");
559
- return `[${expression.elements.map((element) => typeOfValue(element, used, "plugins")).join(", ")}]`;
676
+ const entries = expression.elements.map((element) => typeOfValue(element, used, "plugins"));
677
+ const inline = `[${entries.join(", ")}]`;
678
+ if (`${prefix}${inline};`.length <= PRINT_WIDTH) return inline;
679
+ return `[\n${entries.map((entry) => ` ${entry},`).join("\n")}\n ]`;
560
680
  };
561
681
  /**
562
682
  * The `issueCodes` inside `validation`, or nothing when it declares none.
@@ -588,22 +708,32 @@ const HEADER = `/**
588
708
  * and re-run \`kizuna generate\` to regenerate this file.
589
709
  */`;
590
710
  /**
711
+ * Points a relative specifier at the same file from somewhere else, so a
712
+ * `Config` written outside the config's own directory still resolves.
713
+ */
714
+ const rebaseSpecifier = (specifier, configDir, outputDir) => {
715
+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) return specifier;
716
+ const rebased = (0, node_path.relative)(outputDir, (0, node_path.resolve)(configDir, specifier)).split(node_path.sep).join("/");
717
+ return rebased.startsWith(".") ? rebased : `./${rebased}`;
718
+ };
719
+ /**
591
720
  * The `import type` lines the interface needs, grouped by module and written in
592
721
  * the order the config imported them.
593
722
  */
594
- const renderImports = (imports, used) => {
723
+ const renderImports = (imports, used, rebase) => {
595
724
  const byModule = /* @__PURE__ */ new Map();
596
725
  const defaults = [];
597
726
  for (const [local, imported] of imports) {
598
727
  if (!used.has(local)) continue;
728
+ const module = rebase(imported.module);
599
729
  if (imported.isDefault) {
600
- defaults.push(`import type ${local} from '${imported.module}';`);
730
+ defaults.push(`import type ${local} from '${module}';`);
601
731
  continue;
602
732
  }
603
733
  const specifier = imported.exported === local ? local : `${imported.exported} as ${local}`;
604
- const existing = byModule.get(imported.module);
734
+ const existing = byModule.get(module);
605
735
  if (existing) existing.push(specifier);
606
- else byModule.set(imported.module, [specifier]);
736
+ else byModule.set(module, [specifier]);
607
737
  }
608
738
  const named = [...byModule].map(([module, names]) => `import type { ${names.join(", ")} } from '${module}';`);
609
739
  return [...defaults, ...named].join("\n");
@@ -615,8 +745,11 @@ const renderImports = (imports, used) => {
615
745
  * Read from the config's syntax rather than by running it: the generated file
616
746
  * imports the same names the config did, and a config that loads is not a
617
747
  * prerequisite for typing the routes it serves.
748
+ *
749
+ * `outputPath` is what the imports are written relative to. Left out, they stay
750
+ * relative to the config.
618
751
  */
619
- const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
752
+ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts", outputPath) => {
620
753
  const source = typescript.default.createSourceFile(fileName, configSource, typescript.default.ScriptTarget.Latest, true);
621
754
  const imports = collectImports(source);
622
755
  const configObject = findConfigObject(source);
@@ -640,10 +773,12 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
640
773
  else if (key === "validation") {
641
774
  const codes = issueCodesOf(value);
642
775
  if (codes !== void 0) lines.push(` validation: {\n issueCodes: ${codes};\n };`);
643
- } else if (key === "plugins") lines.push(` ${key}: ${typeOfPluginList(value, used)};`);
776
+ } else if (key === "plugins") lines.push(` ${key}: ${typeOfPluginList(value, used, ` ${key}: `)};`);
644
777
  else lines.push(` ${key}: ${typeOfValue(value, used, key)};`);
645
778
  }
646
- const importBlock = renderImports(imports, used);
779
+ const configDir = (0, node_path.dirname)((0, node_path.resolve)(fileName));
780
+ const outputDir = outputPath === void 0 ? configDir : (0, node_path.dirname)((0, node_path.resolve)(outputPath));
781
+ const importBlock = renderImports(imports, used, (specifier) => outputDir === configDir ? specifier : rebaseSpecifier(specifier, configDir, outputDir));
647
782
  const body = `export interface Config {\n${lines.join("\n")}\n}`;
648
783
  return `${importBlock === "" ? HEADER : `${HEADER}\n${importBlock}`}\n\n${body}\n`;
649
784
  };
@@ -651,44 +786,59 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
651
786
  //#region src/diff-against.ts
652
787
  const git = (cwd, ...args) => (0, node_child_process.execFileSync)("git", args, {
653
788
  cwd,
654
- encoding: "utf8"
789
+ encoding: "utf8",
790
+ stdio: [
791
+ "ignore",
792
+ "pipe",
793
+ "ignore"
794
+ ]
655
795
  }).trim();
656
796
  /**
657
- * Compares the config on disk against the same config at a git ref.
658
- *
659
- * The ref is checked out into a worktree inside the repository, which costs a
660
- * few files rather than a clone. Nothing is installed there: module resolution
661
- * walks up to the repository's own `node_modules`, so the base tree needs only
662
- * its source.
663
- *
664
- * @example
665
- * const changes = await diffAgainst('main', './src/contract.ts');
797
+ * The repository holding the snapshot, falling back to the one the caller ran in.
666
798
  */
667
- const diffAgainst = async (ref, configPath, options = {}) => {
668
- const { cwd = process.cwd() } = options;
669
- const root = git(cwd, "rev-parse", "--show-toplevel");
670
- const absolute = (0, node_path.isAbsolute)(configPath) ? configPath : (0, node_path.resolve)(cwd, configPath);
671
- const fromRoot = (0, node_path.relative)(root, absolute);
672
- if (fromRoot.startsWith("..")) throw new Error(`${configPath} is outside the repository at ${root}`);
673
- const worktree = (0, node_fs.mkdtempSync)((0, node_path.join)(root, ".kizuna-diff-"));
799
+ const repositoryFor = (directory, cwd) => {
674
800
  try {
675
- git(root, "worktree", "add", "--detach", "--force", worktree, ref);
676
- const [before] = await loadConfig((0, node_path.join)(worktree, fromRoot));
677
- if (before === void 0) throw new Error(`No config found in ${fromRoot} at ${ref}`);
678
- const [after] = await loadConfig(absolute);
679
- if (after === void 0) throw new Error(`No config found in ${configPath}`);
680
- return diffApis(before.api, after.api);
681
- } finally {
682
- try {
683
- git(root, "worktree", "remove", "--force", worktree);
684
- } catch {
685
- (0, node_fs.rmSync)(worktree, {
686
- recursive: true,
687
- force: true
688
- });
689
- }
801
+ return git(directory, "rev-parse", "--show-toplevel");
802
+ } catch {
803
+ return git(cwd, "rev-parse", "--show-toplevel");
804
+ }
805
+ };
806
+ const parseSnapshot = (contents, source) => {
807
+ try {
808
+ return (0, yaml.parse)(contents);
809
+ } catch {
810
+ throw new Error(`${source} is not a Kizuna snapshot. Run \`kizuna generate\` to write one.`);
690
811
  }
691
812
  };
813
+ /**
814
+ * Reads a path out of a ref without checking anything out.
815
+ */
816
+ const showAtRef = (root, ref, path) => {
817
+ try {
818
+ return git(root, "show", `${ref}:${path}`);
819
+ } catch {
820
+ throw new Error(`${path} does not exist at ${ref}. It was added or renamed since, so there is nothing to compare against.`);
821
+ }
822
+ };
823
+ const readSnapshot = (path) => {
824
+ if (!(0, node_fs.existsSync)(path)) throw new Error(`No snapshot at ${path}. Run \`kizuna generate\` to write one.`);
825
+ return parseSnapshot((0, node_fs.readFileSync)(path, "utf8"), path);
826
+ };
827
+ /**
828
+ * Compares a snapshot against the same file at a git ref.
829
+ *
830
+ * The ref is read with `git show`, so nothing is checked out, installed or
831
+ * executed for the other side. A snapshot written a year ago compares fine
832
+ * against one written today.
833
+ */
834
+ const diffAgainst = (ref, snapshotPath, options = {}) => {
835
+ const { cwd = process.cwd(), ...diff } = options;
836
+ const absolute = (0, node_path.isAbsolute)(snapshotPath) ? snapshotPath : (0, node_path.resolve)(cwd, snapshotPath);
837
+ const root = repositoryFor((0, node_path.dirname)(absolute), cwd);
838
+ const fromRoot = (0, node_path.relative)(root, absolute);
839
+ if (fromRoot.startsWith("..")) throw new Error(`${snapshotPath} is outside the repository at ${root}`);
840
+ return diffSnapshots(parseSnapshot(showAtRef(root, ref, fromRoot.split("\\").join("/")), `${fromRoot} at ${ref}`), readSnapshot(absolute), diff);
841
+ };
692
842
  //#endregion
693
843
  //#region src/route-map.ts
694
844
  const permissionList = (requires) => {
@@ -719,11 +869,11 @@ const describeSunset = (sunset) => {
719
869
  /**
720
870
  * Every route an api serves, in the order it declares them.
721
871
  */
722
- const routeMap = (0, kizunajs_generator.createGenerator)((_options, _api) => {
872
+ const routeMap = (api, _options = {}) => {
723
873
  const entries = [];
724
874
  const toolKeys = [];
725
- return {
726
- processRoute({ routeKey, route, routeTags, deprecated, deprecationMessage }) {
875
+ return (0, kizunajs_generator.walkApi)(api, {
876
+ processRoute({ routeKey, route, routeGroups, deprecated, deprecationMessage, hidden }) {
727
877
  if (route.tool) toolKeys.push({
728
878
  key: routeKey,
729
879
  origin: "route"
@@ -733,9 +883,10 @@ const routeMap = (0, kizunajs_generator.createGenerator)((_options, _api) => {
733
883
  method: route.method,
734
884
  path: route.path,
735
885
  auth: describeAuth(route.auth),
736
- tags: routeTags,
886
+ groups: routeGroups,
737
887
  deprecated: deprecated ? deprecationMessage ?? "" : void 0,
738
- sunset: describeSunset(route.sunset)
888
+ sunset: describeSunset(route.sunset),
889
+ ...hidden ? { hidden: true } : {}
739
890
  });
740
891
  },
741
892
  finalize() {
@@ -745,8 +896,8 @@ const routeMap = (0, kizunajs_generator.createGenerator)((_options, _api) => {
745
896
  tool: names.get(entry.key) ?? (toolKeys.some((tool) => tool.key === entry.key) ? (0, kizunajs_generator.toToolName)(entry.key) : void 0)
746
897
  }));
747
898
  }
748
- };
749
- });
899
+ });
900
+ };
750
901
  const pad = (text, width) => text + " ".repeat(Math.max(0, width - text.length));
751
902
  /**
752
903
  * The route map as aligned columns, one route per line.
@@ -759,9 +910,11 @@ const formatRoutes = (entries) => {
759
910
  return entries.map((entry) => {
760
911
  const notes = [
761
912
  `auth: ${entry.auth}`,
913
+ entry.groups.length > 0 && `group: ${entry.groups.join(", ")}`,
762
914
  entry.tool && `tool: ${entry.tool}`,
763
915
  entry.deprecated !== void 0 && `deprecated${entry.deprecated ? `, ${entry.deprecated}` : ""}`,
764
- entry.sunset && `sunset ${entry.sunset}`
916
+ entry.sunset && `sunset ${entry.sunset}`,
917
+ entry.hidden && "hidden"
765
918
  ].filter(Boolean);
766
919
  return `${pad(entry.method, methodWidth)} ${pad(entry.path, pathWidth)} ${pad(entry.key, keyWidth)} ${notes.join(" ")}`.trimEnd();
767
920
  }).join("\n");
@@ -779,10 +932,10 @@ Object.defineProperty(exports, "__toESM", {
779
932
  return __toESM;
780
933
  }
781
934
  });
782
- Object.defineProperty(exports, "checkClients", {
935
+ Object.defineProperty(exports, "checkFiles", {
783
936
  enumerable: true,
784
937
  get: function() {
785
- return checkClients;
938
+ return checkFiles;
786
939
  }
787
940
  });
788
941
  Object.defineProperty(exports, "diffAgainst", {
@@ -803,6 +956,12 @@ Object.defineProperty(exports, "diffSchemas", {
803
956
  return diffSchemas;
804
957
  }
805
958
  });
959
+ Object.defineProperty(exports, "diffSnapshots", {
960
+ enumerable: true,
961
+ get: function() {
962
+ return diffSnapshots;
963
+ }
964
+ });
806
965
  Object.defineProperty(exports, "formatChange", {
807
966
  enumerable: true,
808
967
  get: function() {
@@ -839,15 +998,33 @@ Object.defineProperty(exports, "loadConfig", {
839
998
  return loadConfig;
840
999
  }
841
1000
  });
1001
+ Object.defineProperty(exports, "readSnapshot", {
1002
+ enumerable: true,
1003
+ get: function() {
1004
+ return readSnapshot;
1005
+ }
1006
+ });
842
1007
  Object.defineProperty(exports, "routeMap", {
843
1008
  enumerable: true,
844
1009
  get: function() {
845
1010
  return routeMap;
846
1011
  }
847
1012
  });
848
- Object.defineProperty(exports, "writeClients", {
1013
+ Object.defineProperty(exports, "snapshotPathFor", {
1014
+ enumerable: true,
1015
+ get: function() {
1016
+ return snapshotPathFor;
1017
+ }
1018
+ });
1019
+ Object.defineProperty(exports, "snapshotTarget", {
1020
+ enumerable: true,
1021
+ get: function() {
1022
+ return snapshotTarget;
1023
+ }
1024
+ });
1025
+ Object.defineProperty(exports, "writeFiles", {
849
1026
  enumerable: true,
850
1027
  get: function() {
851
- return writeClients;
1028
+ return writeFiles;
852
1029
  }
853
1030
  });