@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.
@@ -1,9 +1,10 @@
1
1
  import { createJiti } from "jiti";
2
2
  import { apiEntries } from "kizunajs";
3
- import { createGenerator, deriveToolNames, flattenJobs, readDef, readObjectShape, resolveResponseBody, toToolName, unwrapOptionalWrappers } from "kizunajs/generator";
3
+ import { deriveToolNames, flattenJobs, readDef, readObjectShape, resolveResponseBody, toToolName, unwrapOptionalWrappers, walkApi } 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 } 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
@@ -16,53 +17,31 @@ import { execFileSync } from "node:child_process";
16
17
  * a config.
17
18
  */
18
19
  const loadConfig = async (configPath) => {
19
- return apiEntries(await createJiti(import.meta.url, { interopDefault: true }).import(configPath)).map(([name, entry]) => ({
20
+ return apiEntries(await createJiti(import.meta.url, {
21
+ interopDefault: true,
22
+ jsx: true,
23
+ tsconfigPaths: true
24
+ }).import(configPath)).map(([name, entry]) => ({
20
25
  name,
21
26
  api: entry.api,
22
27
  clients: entry.clients ?? [],
23
- typesOutput: entry.typescript?.outputFile
28
+ generators: entry.generators ?? [],
29
+ typesOutput: entry.typescript?.outputFile,
30
+ diff: entry.diff ?? {}
24
31
  }));
25
32
  };
26
33
  //#endregion
27
34
  //#region src/diff-schemas.ts
28
- const shapeOf = (schema) => {
29
- const { inner } = unwrapOptionalWrappers(schema);
30
- const raw = readObjectShape(inner);
31
- if (!raw) return void 0;
32
- const fields = /* @__PURE__ */ new Map();
33
- for (const [key, field] of Object.entries(raw)) fields.set(key, {
34
- schema: field,
35
- optional: unwrapOptionalWrappers(field).optional
36
- });
37
- return { fields };
38
- };
39
- /**
40
- * What a schema accepts, flattened enough to compare: its kind, and its values
41
- * when it is closed.
42
- */
43
- const describe = (schema) => {
44
- const { inner } = unwrapOptionalWrappers(schema);
45
- const def = readDef(inner);
46
- if (def.type === "enum") return {
47
- kind: "enum",
48
- values: Object.values(def.entries ?? {}).map(String).sort()
49
- };
50
- if (def.type === "literal") return {
51
- kind: "enum",
52
- values: (def.values ?? []).map(String).sort()
53
- };
54
- if (def.type === "array" && def.element) return { kind: `array<${describe(def.element).kind}>` };
55
- return { kind: def.type ?? "unknown" };
56
- };
57
35
  const joinPath = (parent, key) => parent === "" ? key : `${parent}.${key}`;
36
+ const fieldsOf = (schema) => schema.kind === "object" ? schema.fields : void 0;
37
+ const elementOf = (schema) => schema.kind === "array" ? schema.element : void 0;
38
+ const valuesOf = (schema) => schema.kind === "enum" ? schema.values : void 0;
58
39
  /**
59
- * The element of an array, so a change inside one is reported at its own path
60
- * rather than as the whole array changing shape.
40
+ * What a reader sees when the kinds differ, so `array` reads as `array<string>`.
61
41
  */
62
- const elementOf = (schema) => {
63
- const { inner } = unwrapOptionalWrappers(schema);
64
- const def = readDef(inner);
65
- return def.type === "array" ? def.element : void 0;
42
+ const describeKind = (schema) => {
43
+ const element = elementOf(schema);
44
+ return element ? `array<${describeKind(element)}>` : schema.kind;
66
45
  };
67
46
  /**
68
47
  * What changed between two versions of one schema, and whether it breaks the
@@ -80,15 +59,30 @@ const diffSchemas = (before, after, direction, path = "") => {
80
59
  path,
81
60
  summary: `${path || "the body"} is gone`
82
61
  }];
62
+ if (before.kind !== after.kind) return [{
63
+ breaking: true,
64
+ path,
65
+ summary: `${path || "the body"} is ${describeKind(after)} instead of ${describeKind(before)}`
66
+ }];
83
67
  const changes = [];
68
+ const wasNullable = before.nullable === true;
69
+ const isNullable = after.nullable === true;
70
+ if (wasNullable !== isNullable) changes.push({
71
+ breaking: direction === (isNullable ? "response" : "request"),
72
+ path,
73
+ summary: isNullable ? `${path || "the body"} can now be null` : `${path || "the body"} can no longer be null`
74
+ });
84
75
  const beforeElement = elementOf(before);
85
76
  const afterElement = elementOf(after);
86
- if (beforeElement && afterElement) return diffSchemas(beforeElement, afterElement, direction, `${path}[]`);
87
- const beforeShape = shapeOf(before);
88
- const afterShape = shapeOf(after);
89
- if (beforeShape && afterShape) {
90
- for (const [key, field] of afterShape.fields) {
91
- const existing = beforeShape.fields.get(key);
77
+ if (beforeElement && afterElement) {
78
+ changes.push(...diffSchemas(beforeElement, afterElement, direction, `${path}[]`));
79
+ return changes;
80
+ }
81
+ const beforeFields = fieldsOf(before);
82
+ const afterFields = fieldsOf(after);
83
+ if (beforeFields && afterFields) {
84
+ for (const [key, field] of Object.entries(afterFields)) {
85
+ const existing = beforeFields[key];
92
86
  const here = joinPath(path, key);
93
87
  if (!existing) {
94
88
  if (!field.optional) changes.push({
@@ -103,10 +97,15 @@ const diffSchemas = (before, after, direction, path = "") => {
103
97
  path: here,
104
98
  summary: `${here} is no longer optional`
105
99
  });
100
+ if (!existing.optional && field.optional) changes.push({
101
+ breaking: direction === "response",
102
+ path: here,
103
+ summary: direction === "response" ? `${here} may now be left out` : `${here} is now optional`
104
+ });
106
105
  changes.push(...diffSchemas(existing.schema, field.schema, direction, here));
107
106
  }
108
- for (const [key] of beforeShape.fields) {
109
- if (afterShape.fields.has(key)) continue;
107
+ for (const key of Object.keys(beforeFields)) {
108
+ if (afterFields[key]) continue;
110
109
  const here = joinPath(path, key);
111
110
  changes.push({
112
111
  breaking: direction === "response",
@@ -116,19 +115,11 @@ const diffSchemas = (before, after, direction, path = "") => {
116
115
  }
117
116
  return changes;
118
117
  }
119
- const was = describe(before);
120
- const now = describe(after);
121
- if (was.kind !== now.kind) {
122
- changes.push({
123
- breaking: true,
124
- path,
125
- summary: `${path || "the body"} is ${now.kind} instead of ${was.kind}`
126
- });
127
- return changes;
128
- }
129
- if (was.values && now.values) {
130
- const removed = was.values.filter((value) => !now.values?.includes(value));
131
- const added = now.values.filter((value) => !was.values?.includes(value));
118
+ const was = valuesOf(before);
119
+ const now = valuesOf(after);
120
+ if (was && now) {
121
+ const removed = was.filter((value) => !now.includes(value));
122
+ const added = now.filter((value) => !was.includes(value));
132
123
  if (removed.length > 0) changes.push({
133
124
  breaking: true,
134
125
  path,
@@ -140,53 +131,157 @@ const diffSchemas = (before, after, direction, path = "") => {
140
131
  summary: direction === "response" ? `${path || "the body"} can now be ${added.join(", ")}` : `${path || "the body"} also accepts ${added.join(", ")}`
141
132
  });
142
133
  }
134
+ const wasRefined = before.refinements ?? 0;
135
+ const isRefined = after.refinements ?? 0;
136
+ if (wasRefined !== isRefined) changes.push({
137
+ breaking: direction === "request" && isRefined > wasRefined,
138
+ path,
139
+ summary: isRefined > wasRefined ? `${path || "the body"} is validated more tightly` : `${path || "the body"} is validated less tightly`
140
+ });
143
141
  return changes;
144
142
  };
145
143
  //#endregion
146
- //#region src/diff-apis.ts
147
- const routeFacts = createGenerator(() => {
148
- const facts = /* @__PURE__ */ new Map();
144
+ //#region src/snapshot.ts
145
+ /**
146
+ * How many `.refine()` or `.superRefine()` calls a schema carries. The
147
+ * predicate itself cannot be compared across two files, but its arrival or
148
+ * departure can.
149
+ */
150
+ const refinementCount = (schema) => {
151
+ const checks = readDef(schema).checks;
152
+ if (!checks) return void 0;
153
+ const custom = checks.filter((check) => check._zod?.def?.check === "custom").length;
154
+ return custom === 0 ? void 0 : custom;
155
+ };
156
+ /**
157
+ * A Zod schema reduced to the shape a comparison reads.
158
+ */
159
+ const toSchemaNode = (schema) => {
160
+ const { inner, nullable } = unwrapOptionalWrappers(schema);
161
+ const def = readDef(inner);
162
+ const options = def.type === "union" ? def.options ?? [] : [];
163
+ const nonNull = options.filter((option) => readDef(option).type !== "null");
164
+ if (nonNull.length === 1 && options.length > 1) return {
165
+ ...toSchemaNode(nonNull[0]),
166
+ nullable: true
167
+ };
168
+ const nullability = nullable ? { nullable: true } : {};
169
+ const refinements = refinementCount(inner);
170
+ const carry = refinements === void 0 ? {} : { refinements };
171
+ const shape = readObjectShape(inner);
172
+ if (shape) {
173
+ const fields = {};
174
+ for (const [key, field] of Object.entries(shape)) fields[key] = {
175
+ optional: unwrapOptionalWrappers(field).optional,
176
+ schema: toSchemaNode(field)
177
+ };
178
+ return {
179
+ kind: "object",
180
+ ...nullability,
181
+ fields,
182
+ ...carry
183
+ };
184
+ }
185
+ if (def.type === "array" && def.element) return {
186
+ kind: "array",
187
+ ...nullability,
188
+ element: toSchemaNode(def.element),
189
+ ...carry
190
+ };
191
+ if (def.type === "enum") return {
192
+ kind: "enum",
193
+ ...nullability,
194
+ values: Object.values(def.entries ?? {}).map(String).sort(),
195
+ ...carry
196
+ };
197
+ if (def.type === "literal") return {
198
+ kind: "enum",
199
+ ...nullability,
200
+ values: (def.values ?? []).map(String).sort(),
201
+ ...carry
202
+ };
149
203
  return {
150
- processRoute({ routeKey, route, deprecated }) {
151
- facts.set(routeKey, {
152
- method: route.method,
153
- path: route.path,
154
- statuses: Object.keys(route.responses).map(Number).sort(),
155
- deprecated,
156
- ...sunsetOf(route) === void 0 ? {} : { sunset: sunsetOf(route) },
157
- ...route.body ? { body: route.body } : {},
158
- ...route.query ? { query: route.query } : {},
159
- ...route.headers ? { headers: route.headers } : {},
160
- responses: new Map(Object.entries(route.responses).map(([status, response]) => [Number(status), resolveResponseBody(response)]))
161
- });
162
- },
163
- finalize: () => facts
204
+ kind: def.type ?? "unknown",
205
+ ...nullability,
206
+ ...carry
164
207
  };
165
- });
208
+ };
166
209
  const sunsetOf = (route) => {
167
210
  const declared = route.sunset;
168
211
  if (declared === void 0) return void 0;
169
212
  return typeof declared === "string" ? declared : declared.date;
170
213
  };
171
- const jobKeys = (contract) => {
172
- const jobs = contract.jobs;
173
- if (!jobs) return /* @__PURE__ */ new Set();
174
- return new Set(flattenJobs(jobs).map((job) => job.jobKey));
214
+ const routeSnapshots = (api) => {
215
+ const routes = {};
216
+ return walkApi(api, {
217
+ processRoute({ routeKey, route, deprecated, hidden }) {
218
+ const sunset = sunsetOf(route);
219
+ const responses = {};
220
+ for (const [status, response] of Object.entries(route.responses)) {
221
+ const body = resolveResponseBody(response);
222
+ responses[status] = body === void 0 ? null : toSchemaNode(body);
223
+ }
224
+ routes[routeKey] = {
225
+ method: route.method,
226
+ path: route.path,
227
+ statuses: Object.keys(route.responses).map(Number).sort((a, b) => a - b),
228
+ deprecated,
229
+ ...hidden ? { hidden: true } : {},
230
+ ...sunset === void 0 ? {} : { sunset },
231
+ ...route.body ? { body: toSchemaNode(route.body) } : {},
232
+ ...route.query ? { query: toSchemaNode(route.query) } : {},
233
+ ...route.headers ? { headers: toSchemaNode(route.headers) } : {},
234
+ responses
235
+ };
236
+ },
237
+ finalize: () => routes
238
+ });
239
+ };
240
+ /**
241
+ * Everything `kizuna diff` compares, as plain data.
242
+ *
243
+ * Writing this at each commit is what lets a comparison read the other side
244
+ * out of git rather than checking it out and running it.
245
+ */
246
+ const toSnapshot = (api) => {
247
+ const declared = api.jobs;
248
+ const jobs = declared ? flattenJobs(declared).map((job) => job.jobKey).sort() : [];
249
+ const tools = Object.fromEntries(flattenRoutes(api.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, toToolName(routeKey)]));
250
+ return {
251
+ routes: routeSnapshots(api),
252
+ jobs,
253
+ tools
254
+ };
175
255
  };
176
256
  /**
177
- * The MCP name of every route that publishes as a tool, keyed by route key.
257
+ * YAML rather than JSON, so the file a reviewer opens in a pull request reads
258
+ * as the API rather than as punctuation.
178
259
  */
179
- const toolNames = (contract) => new Map(flattenRoutes(contract.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, toToolName(routeKey)]));
260
+ const renderSnapshot = (api) => stringify(toSnapshot(api), { lineWidth: 0 });
180
261
  /**
181
- * What changed between two apis, worst first.
182
- *
183
- * Compares the declarations rather than an OpenAPI document, so it sees route
184
- * keys, MCP tool names and job keys, none of which a document carries.
262
+ * Where a config's snapshot lives. `.kizuna/` sits beside the config, so CI
263
+ * always knows where to look without being told, and a repository holding
264
+ * several configs keeps one snapshot per config.
265
+ */
266
+ const snapshotPathFor = (configPath) => {
267
+ const declared = basename(configPath).replace(/\.config\.[cm]?[jt]s$/, "").replace(/^kizuna\./, "");
268
+ const name = declared === "" || declared === "kizuna" ? "snapshot" : `${declared}.snapshot`;
269
+ return join(dirname(configPath), ".kizuna", `${name}.yaml`);
270
+ };
271
+ /**
272
+ * The snapshot as a client target, so `kizuna generate` writes it and
273
+ * `kizuna generate --check` refuses to let it go stale.
185
274
  */
186
- const diffApis = (before, after) => {
275
+ const snapshotTarget = (configPath) => ({
276
+ output: snapshotPathFor(configPath),
277
+ render: renderSnapshot
278
+ });
279
+ //#endregion
280
+ //#region src/diff-apis.ts
281
+ const diffSnapshots = (before, after, options = {}) => {
187
282
  const changes = [];
188
- const beforeRoutes = routeFacts(before, {});
189
- const afterRoutes = routeFacts(after, {});
283
+ const beforeRoutes = new Map(Object.entries(before.routes));
284
+ const afterRoutes = new Map(Object.entries(after.routes));
190
285
  const removed = [...beforeRoutes.keys()].filter((key) => !afterRoutes.has(key));
191
286
  const added = [...afterRoutes.keys()].filter((key) => !beforeRoutes.has(key));
192
287
  const renames = /* @__PURE__ */ new Map();
@@ -203,10 +298,10 @@ const diffApis = (before, after) => {
203
298
  if (match) renames.set(match, goneKey);
204
299
  }
205
300
  for (const [toKey, fromKey] of renames) changes.push({
206
- level: "breaking",
301
+ level: options.dottedKeys ? "breaking" : "changed",
207
302
  key: fromKey,
208
303
  summary: `${fromKey} renamed to ${toKey}`,
209
- detail: "client method and generated client names change, HTTP surface unaffected"
304
+ detail: "the generated client method changes name, the HTTP surface does not"
210
305
  });
211
306
  for (const key of removed) {
212
307
  if ([...renames.values()].includes(key)) continue;
@@ -279,15 +374,26 @@ const diffApis = (before, after) => {
279
374
  key,
280
375
  summary: `${httpLabel(arrived, key)} ${change.summary}`
281
376
  });
282
- for (const [status, was] of gone.responses) {
283
- const now = arrived.responses.get(status);
284
- if (!arrived.responses.has(status)) continue;
285
- for (const change of diffSchemas(was, now, "response", `${status}`)) changes.push({
377
+ for (const [status, was] of Object.entries(gone.responses)) {
378
+ if (!(status in arrived.responses)) continue;
379
+ const now = arrived.responses[status];
380
+ for (const change of diffSchemas(was ?? void 0, now ?? void 0, "response", status)) changes.push({
286
381
  level: change.breaking ? "breaking" : "changed",
287
382
  key,
288
383
  summary: `${httpLabel(arrived, key)} ${change.summary}`
289
384
  });
290
385
  }
386
+ if (gone.hidden !== true && arrived.hidden === true) changes.push({
387
+ level: "breaking",
388
+ key,
389
+ summary: `${httpLabel(arrived, key)} is now hidden`,
390
+ detail: "the server still serves it, but it is no longer in the generated clients or the OpenAPI document"
391
+ });
392
+ if (gone.hidden === true && arrived.hidden !== true) changes.push({
393
+ level: "added",
394
+ key,
395
+ summary: `${httpLabel(arrived, key)} is no longer hidden`
396
+ });
291
397
  if (!gone.deprecated && arrived.deprecated) changes.push({
292
398
  level: "changed",
293
399
  key,
@@ -299,8 +405,8 @@ const diffApis = (before, after) => {
299
405
  summary: `${httpLabel(arrived, key)} sunsets on ${arrived.sunset}`
300
406
  });
301
407
  }
302
- for (const key of jobKeys(before)) {
303
- if (jobKeys(after).has(key)) continue;
408
+ for (const key of options.jobs ? before.jobs : []) {
409
+ if (after.jobs.includes(key)) continue;
304
410
  changes.push({
305
411
  level: "breaking",
306
412
  key,
@@ -308,10 +414,8 @@ const diffApis = (before, after) => {
308
414
  detail: "whatever calls POST /jobs/run with that key stops working"
309
415
  });
310
416
  }
311
- const beforeTools = toolNames(before);
312
- const afterTools = toolNames(after);
313
- for (const [key, name] of beforeTools) {
314
- const arrived = afterTools.get(key);
417
+ for (const [key, name] of options.tools ? Object.entries(before.tools) : []) {
418
+ const arrived = after.tools[key];
315
419
  if (arrived === void 0) {
316
420
  changes.push({
317
421
  level: "breaking",
@@ -336,6 +440,13 @@ const diffApis = (before, after) => {
336
440
  return changes.sort((left, right) => order[left.level] - order[right.level] || left.key.localeCompare(right.key));
337
441
  };
338
442
  /**
443
+ * What changed between two apis, for a caller holding both in memory.
444
+ *
445
+ * `kizuna diff` reads snapshots instead, so it never has to load the other
446
+ * side's code.
447
+ */
448
+ const diffApis = (before, after, options = {}) => diffSnapshots(toSnapshot(before), toSnapshot(after), options);
449
+ /**
339
450
  * One block per change, ready to print: the level, the summary, and the
340
451
  * detail indented beneath it.
341
452
  */
@@ -358,38 +469,37 @@ const currentContents = (output) => {
358
469
  }
359
470
  };
360
471
  /**
361
- * Writes every client an api declares, leaving a file alone when it already
362
- * matches so watchers and build tools see no change.
472
+ * Writes every generated file, the clients and what plugins generate, leaving
473
+ * a file alone when it already matches so watchers and build tools see no
474
+ * change.
363
475
  */
364
- const writeClients = (contract, clients) => clients.map((client) => {
365
- const rendered = client.generate(contract);
366
- const changed = currentContents(client.output) !== rendered;
476
+ const writeFiles = (contract, files) => files.map((file) => {
477
+ const rendered = file.render(contract);
478
+ const changed = currentContents(file.output) !== rendered;
367
479
  if (changed) {
368
- mkdirSync(dirname(client.output), { recursive: true });
369
- writeFileSync(client.output, rendered);
480
+ mkdirSync(dirname(file.output), { recursive: true });
481
+ writeFileSync(file.output, rendered);
370
482
  }
371
483
  return {
372
- kind: client.kind,
373
- output: client.output,
484
+ output: file.output,
374
485
  changed
375
486
  };
376
487
  });
377
488
  /**
378
- * Every client that no longer matches its api, without writing anything.
489
+ * Every generated file that no longer matches its api, without writing
490
+ * anything.
379
491
  *
380
492
  * This is what a pipeline runs: a generated client that has fallen behind is a
381
493
  * compile error waiting to happen in whatever imports it.
382
494
  */
383
- const checkClients = (contract, clients) => clients.flatMap((client) => {
384
- const current = currentContents(client.output);
495
+ const checkFiles = (contract, files) => files.flatMap((file) => {
496
+ const current = currentContents(file.output);
385
497
  if (current === void 0) return [{
386
- kind: client.kind,
387
- output: client.output,
498
+ output: file.output,
388
499
  reason: "missing"
389
500
  }];
390
- if (current !== client.generate(contract)) return [{
391
- kind: client.kind,
392
- output: client.output,
501
+ if (current !== file.render(contract)) return [{
502
+ output: file.output,
393
503
  reason: "outdated"
394
504
  }];
395
505
  return [];
@@ -399,12 +509,12 @@ const checkClients = (contract, clients) => clients.flatMap((client) => {
399
509
  * rather than printing a diff nobody reads.
400
510
  */
401
511
  const formatStale = (stale, command = "kizuna generate") => {
402
- const lines = stale.map((client) => {
403
- const where = relative(process.cwd(), client.output);
404
- return client.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the config`;
512
+ const lines = stale.map((file) => {
513
+ const where = relative(process.cwd(), file.output);
514
+ return file.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the config`;
405
515
  });
406
516
  return [
407
- stale.length === 1 ? "A generated client is out of date:" : `${stale.length} generated clients are out of date:`,
517
+ stale.length === 1 ? "A generated file is out of date:" : `${stale.length} generated files are out of date:`,
408
518
  ...lines,
409
519
  "",
410
520
  `Run \`${command}\` and commit the result.`
@@ -419,7 +529,7 @@ const formatStale = (stale, command = "kizuna generate") => {
419
529
  */
420
530
  const CONFIG_KEYS = [
421
531
  "adapter",
422
- "tags",
532
+ "groups",
423
533
  "auth",
424
534
  "requestContext",
425
535
  "validation",
@@ -528,12 +638,22 @@ const typeOfStringUnion = (expression, key) => {
528
638
  return codes.length > 0 ? codes.join(" | ") : "never";
529
639
  };
530
640
  /**
641
+ * The repo's Prettier `printWidth`. A line the generator writes longer than this
642
+ * is one `pnpm format` would rewrite, and `--check` would then report the file
643
+ * as behind.
644
+ */
645
+ const PRINT_WIDTH = 140;
646
+ /**
531
647
  * Each plugin in order, as a tuple, so a handler reaches each one under its own
532
- * slug.
648
+ * slug. It wraps one plugin per line when the line would run past
649
+ * {@link PRINT_WIDTH}, the way Prettier does.
533
650
  */
534
- const typeOfPluginList = (expression, used) => {
651
+ const typeOfPluginList = (expression, used, prefix) => {
535
652
  if (!ts.isArrayLiteralExpression(expression)) throw new ConfigSyntaxError("`plugins` has to be an array, so each plugin keeps its place.");
536
- return `[${expression.elements.map((element) => typeOfValue(element, used, "plugins")).join(", ")}]`;
653
+ const entries = expression.elements.map((element) => typeOfValue(element, used, "plugins"));
654
+ const inline = `[${entries.join(", ")}]`;
655
+ if (`${prefix}${inline};`.length <= PRINT_WIDTH) return inline;
656
+ return `[\n${entries.map((entry) => ` ${entry},`).join("\n")}\n ]`;
537
657
  };
538
658
  /**
539
659
  * The `issueCodes` inside `validation`, or nothing when it declares none.
@@ -565,22 +685,32 @@ const HEADER = `/**
565
685
  * and re-run \`kizuna generate\` to regenerate this file.
566
686
  */`;
567
687
  /**
688
+ * Points a relative specifier at the same file from somewhere else, so a
689
+ * `Config` written outside the config's own directory still resolves.
690
+ */
691
+ const rebaseSpecifier = (specifier, configDir, outputDir) => {
692
+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) return specifier;
693
+ const rebased = relative(outputDir, resolve(configDir, specifier)).split(sep).join("/");
694
+ return rebased.startsWith(".") ? rebased : `./${rebased}`;
695
+ };
696
+ /**
568
697
  * The `import type` lines the interface needs, grouped by module and written in
569
698
  * the order the config imported them.
570
699
  */
571
- const renderImports = (imports, used) => {
700
+ const renderImports = (imports, used, rebase) => {
572
701
  const byModule = /* @__PURE__ */ new Map();
573
702
  const defaults = [];
574
703
  for (const [local, imported] of imports) {
575
704
  if (!used.has(local)) continue;
705
+ const module = rebase(imported.module);
576
706
  if (imported.isDefault) {
577
- defaults.push(`import type ${local} from '${imported.module}';`);
707
+ defaults.push(`import type ${local} from '${module}';`);
578
708
  continue;
579
709
  }
580
710
  const specifier = imported.exported === local ? local : `${imported.exported} as ${local}`;
581
- const existing = byModule.get(imported.module);
711
+ const existing = byModule.get(module);
582
712
  if (existing) existing.push(specifier);
583
- else byModule.set(imported.module, [specifier]);
713
+ else byModule.set(module, [specifier]);
584
714
  }
585
715
  const named = [...byModule].map(([module, names]) => `import type { ${names.join(", ")} } from '${module}';`);
586
716
  return [...defaults, ...named].join("\n");
@@ -592,8 +722,11 @@ const renderImports = (imports, used) => {
592
722
  * Read from the config's syntax rather than by running it: the generated file
593
723
  * imports the same names the config did, and a config that loads is not a
594
724
  * prerequisite for typing the routes it serves.
725
+ *
726
+ * `outputPath` is what the imports are written relative to. Left out, they stay
727
+ * relative to the config.
595
728
  */
596
- const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
729
+ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts", outputPath) => {
597
730
  const source = ts.createSourceFile(fileName, configSource, ts.ScriptTarget.Latest, true);
598
731
  const imports = collectImports(source);
599
732
  const configObject = findConfigObject(source);
@@ -617,10 +750,12 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
617
750
  else if (key === "validation") {
618
751
  const codes = issueCodesOf(value);
619
752
  if (codes !== void 0) lines.push(` validation: {\n issueCodes: ${codes};\n };`);
620
- } else if (key === "plugins") lines.push(` ${key}: ${typeOfPluginList(value, used)};`);
753
+ } else if (key === "plugins") lines.push(` ${key}: ${typeOfPluginList(value, used, ` ${key}: `)};`);
621
754
  else lines.push(` ${key}: ${typeOfValue(value, used, key)};`);
622
755
  }
623
- const importBlock = renderImports(imports, used);
756
+ const configDir = dirname(resolve(fileName));
757
+ const outputDir = outputPath === void 0 ? configDir : dirname(resolve(outputPath));
758
+ const importBlock = renderImports(imports, used, (specifier) => outputDir === configDir ? specifier : rebaseSpecifier(specifier, configDir, outputDir));
624
759
  const body = `export interface Config {\n${lines.join("\n")}\n}`;
625
760
  return `${importBlock === "" ? HEADER : `${HEADER}\n${importBlock}`}\n\n${body}\n`;
626
761
  };
@@ -628,44 +763,59 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
628
763
  //#region src/diff-against.ts
629
764
  const git = (cwd, ...args) => execFileSync("git", args, {
630
765
  cwd,
631
- encoding: "utf8"
766
+ encoding: "utf8",
767
+ stdio: [
768
+ "ignore",
769
+ "pipe",
770
+ "ignore"
771
+ ]
632
772
  }).trim();
633
773
  /**
634
- * Compares the config on disk against the same config at a git ref.
635
- *
636
- * The ref is checked out into a worktree inside the repository, which costs a
637
- * few files rather than a clone. Nothing is installed there: module resolution
638
- * walks up to the repository's own `node_modules`, so the base tree needs only
639
- * its source.
640
- *
641
- * @example
642
- * const changes = await diffAgainst('main', './src/contract.ts');
774
+ * The repository holding the snapshot, falling back to the one the caller ran in.
643
775
  */
644
- const diffAgainst = async (ref, configPath, options = {}) => {
645
- const { cwd = process.cwd() } = options;
646
- const root = git(cwd, "rev-parse", "--show-toplevel");
647
- const absolute = isAbsolute(configPath) ? configPath : resolve(cwd, configPath);
648
- const fromRoot = relative(root, absolute);
649
- if (fromRoot.startsWith("..")) throw new Error(`${configPath} is outside the repository at ${root}`);
650
- const worktree = mkdtempSync(join(root, ".kizuna-diff-"));
776
+ const repositoryFor = (directory, cwd) => {
651
777
  try {
652
- git(root, "worktree", "add", "--detach", "--force", worktree, ref);
653
- const [before] = await loadConfig(join(worktree, fromRoot));
654
- if (before === void 0) throw new Error(`No config found in ${fromRoot} at ${ref}`);
655
- const [after] = await loadConfig(absolute);
656
- if (after === void 0) throw new Error(`No config found in ${configPath}`);
657
- return diffApis(before.api, after.api);
658
- } finally {
659
- try {
660
- git(root, "worktree", "remove", "--force", worktree);
661
- } catch {
662
- rmSync(worktree, {
663
- recursive: true,
664
- force: true
665
- });
666
- }
778
+ return git(directory, "rev-parse", "--show-toplevel");
779
+ } catch {
780
+ return git(cwd, "rev-parse", "--show-toplevel");
781
+ }
782
+ };
783
+ const parseSnapshot = (contents, source) => {
784
+ try {
785
+ return parse(contents);
786
+ } catch {
787
+ throw new Error(`${source} is not a Kizuna snapshot. Run \`kizuna generate\` to write one.`);
788
+ }
789
+ };
790
+ /**
791
+ * Reads a path out of a ref without checking anything out.
792
+ */
793
+ const showAtRef = (root, ref, path) => {
794
+ try {
795
+ return git(root, "show", `${ref}:${path}`);
796
+ } catch {
797
+ throw new Error(`${path} does not exist at ${ref}. It was added or renamed since, so there is nothing to compare against.`);
667
798
  }
668
799
  };
800
+ const readSnapshot = (path) => {
801
+ if (!existsSync(path)) throw new Error(`No snapshot at ${path}. Run \`kizuna generate\` to write one.`);
802
+ return parseSnapshot(readFileSync(path, "utf8"), path);
803
+ };
804
+ /**
805
+ * Compares a snapshot against the same file at a git ref.
806
+ *
807
+ * The ref is read with `git show`, so nothing is checked out, installed or
808
+ * executed for the other side. A snapshot written a year ago compares fine
809
+ * against one written today.
810
+ */
811
+ const diffAgainst = (ref, snapshotPath, options = {}) => {
812
+ const { cwd = process.cwd(), ...diff } = options;
813
+ const absolute = isAbsolute(snapshotPath) ? snapshotPath : resolve(cwd, snapshotPath);
814
+ const root = repositoryFor(dirname(absolute), cwd);
815
+ const fromRoot = relative(root, absolute);
816
+ if (fromRoot.startsWith("..")) throw new Error(`${snapshotPath} is outside the repository at ${root}`);
817
+ return diffSnapshots(parseSnapshot(showAtRef(root, ref, fromRoot.split("\\").join("/")), `${fromRoot} at ${ref}`), readSnapshot(absolute), diff);
818
+ };
669
819
  //#endregion
670
820
  //#region src/route-map.ts
671
821
  const permissionList = (requires) => {
@@ -696,11 +846,11 @@ const describeSunset = (sunset) => {
696
846
  /**
697
847
  * Every route an api serves, in the order it declares them.
698
848
  */
699
- const routeMap = createGenerator((_options, _api) => {
849
+ const routeMap = (api, _options = {}) => {
700
850
  const entries = [];
701
851
  const toolKeys = [];
702
- return {
703
- processRoute({ routeKey, route, routeTags, deprecated, deprecationMessage }) {
852
+ return walkApi(api, {
853
+ processRoute({ routeKey, route, routeGroups, deprecated, deprecationMessage, hidden }) {
704
854
  if (route.tool) toolKeys.push({
705
855
  key: routeKey,
706
856
  origin: "route"
@@ -710,9 +860,10 @@ const routeMap = createGenerator((_options, _api) => {
710
860
  method: route.method,
711
861
  path: route.path,
712
862
  auth: describeAuth(route.auth),
713
- tags: routeTags,
863
+ groups: routeGroups,
714
864
  deprecated: deprecated ? deprecationMessage ?? "" : void 0,
715
- sunset: describeSunset(route.sunset)
865
+ sunset: describeSunset(route.sunset),
866
+ ...hidden ? { hidden: true } : {}
716
867
  });
717
868
  },
718
869
  finalize() {
@@ -722,8 +873,8 @@ const routeMap = createGenerator((_options, _api) => {
722
873
  tool: names.get(entry.key) ?? (toolKeys.some((tool) => tool.key === entry.key) ? toToolName(entry.key) : void 0)
723
874
  }));
724
875
  }
725
- };
726
- });
876
+ });
877
+ };
727
878
  const pad = (text, width) => text + " ".repeat(Math.max(0, width - text.length));
728
879
  /**
729
880
  * The route map as aligned columns, one route per line.
@@ -736,12 +887,14 @@ const formatRoutes = (entries) => {
736
887
  return entries.map((entry) => {
737
888
  const notes = [
738
889
  `auth: ${entry.auth}`,
890
+ entry.groups.length > 0 && `group: ${entry.groups.join(", ")}`,
739
891
  entry.tool && `tool: ${entry.tool}`,
740
892
  entry.deprecated !== void 0 && `deprecated${entry.deprecated ? `, ${entry.deprecated}` : ""}`,
741
- entry.sunset && `sunset ${entry.sunset}`
893
+ entry.sunset && `sunset ${entry.sunset}`,
894
+ entry.hidden && "hidden"
742
895
  ].filter(Boolean);
743
896
  return `${pad(entry.method, methodWidth)} ${pad(entry.path, pathWidth)} ${pad(entry.key, keyWidth)} ${notes.join(" ")}`.trimEnd();
744
897
  }).join("\n");
745
898
  };
746
899
  //#endregion
747
- 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 };
900
+ export { loadConfig as _, ConfigSyntaxError as a, formatStale as c, diffSnapshots as d, formatChange as f, diffSchemas as g, snapshotTarget as h, readSnapshot as i, writeFiles as l, snapshotPathFor as m, routeMap as n, generateConfigTypes as o, hasBreakingChange as p, diffAgainst as r, checkFiles as s, formatRoutes as t, diffApis as u };