@kizunajs/cli 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,747 @@
1
+ import { createJiti } from "jiti";
2
+ import { apiEntries } from "kizunajs";
3
+ import { createGenerator, deriveToolNames, flattenJobs, readDef, readObjectShape, resolveResponseBody, toToolName, unwrapOptionalWrappers } from "kizunajs/generator";
4
+ 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 ts from "typescript";
8
+ import { execFileSync } from "node:child_process";
9
+ //#region src/load-config.ts
10
+ /**
11
+ * Imports a config module with jiti, so a `.ts` config works without a build
12
+ * step, and returns every api it declares along with the clients and the types
13
+ * output each one asks for.
14
+ *
15
+ * Returns an empty list when the module default-exports nothing that looks like
16
+ * a config.
17
+ */
18
+ const loadConfig = async (configPath) => {
19
+ return apiEntries(await createJiti(import.meta.url, { interopDefault: true }).import(configPath)).map(([name, entry]) => ({
20
+ name,
21
+ api: entry.api,
22
+ clients: entry.clients ?? [],
23
+ typesOutput: entry.typescript?.outputFile
24
+ }));
25
+ };
26
+ //#endregion
27
+ //#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
+ const joinPath = (parent, key) => parent === "" ? key : `${parent}.${key}`;
58
+ /**
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.
61
+ */
62
+ const elementOf = (schema) => {
63
+ const { inner } = unwrapOptionalWrappers(schema);
64
+ const def = readDef(inner);
65
+ return def.type === "array" ? def.element : void 0;
66
+ };
67
+ /**
68
+ * What changed between two versions of one schema, and whether it breaks the
69
+ * people already calling the route.
70
+ */
71
+ const diffSchemas = (before, after, direction, path = "") => {
72
+ if (before === void 0 && after === void 0) return [];
73
+ if (before === void 0) return after === void 0 ? [] : [{
74
+ breaking: direction === "request",
75
+ path,
76
+ summary: direction === "request" ? `${path || "a body"} is now required` : `${path || "a body"} is now sent`
77
+ }];
78
+ if (after === void 0) return [{
79
+ breaking: direction === "response",
80
+ path,
81
+ summary: `${path || "the body"} is gone`
82
+ }];
83
+ const changes = [];
84
+ const beforeElement = elementOf(before);
85
+ 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);
92
+ const here = joinPath(path, key);
93
+ if (!existing) {
94
+ if (!field.optional) changes.push({
95
+ breaking: direction === "request",
96
+ path: here,
97
+ summary: direction === "request" ? `${here} is now required` : `${here} is now part of the response`
98
+ });
99
+ continue;
100
+ }
101
+ if (existing.optional && !field.optional) changes.push({
102
+ breaking: direction === "request",
103
+ path: here,
104
+ summary: `${here} is no longer optional`
105
+ });
106
+ changes.push(...diffSchemas(existing.schema, field.schema, direction, here));
107
+ }
108
+ for (const [key] of beforeShape.fields) {
109
+ if (afterShape.fields.has(key)) continue;
110
+ const here = joinPath(path, key);
111
+ changes.push({
112
+ breaking: direction === "response",
113
+ path: here,
114
+ summary: `${here} is gone`
115
+ });
116
+ }
117
+ return changes;
118
+ }
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));
132
+ if (removed.length > 0) changes.push({
133
+ breaking: true,
134
+ path,
135
+ summary: `${path || "the body"} no longer accepts ${removed.join(", ")}`
136
+ });
137
+ if (added.length > 0) changes.push({
138
+ breaking: direction === "response",
139
+ path,
140
+ summary: direction === "response" ? `${path || "the body"} can now be ${added.join(", ")}` : `${path || "the body"} also accepts ${added.join(", ")}`
141
+ });
142
+ }
143
+ return changes;
144
+ };
145
+ //#endregion
146
+ //#region src/diff-apis.ts
147
+ const routeFacts = createGenerator(() => {
148
+ const facts = /* @__PURE__ */ new Map();
149
+ 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
164
+ };
165
+ });
166
+ const sunsetOf = (route) => {
167
+ const declared = route.sunset;
168
+ if (declared === void 0) return void 0;
169
+ return typeof declared === "string" ? declared : declared.date;
170
+ };
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));
175
+ };
176
+ /**
177
+ * The MCP name of every route that publishes as a tool, keyed by route key.
178
+ */
179
+ const toolNames = (contract) => new Map(flattenRoutes(contract.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, toToolName(routeKey)]));
180
+ /**
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.
185
+ */
186
+ const diffApis = (before, after) => {
187
+ const changes = [];
188
+ const beforeRoutes = routeFacts(before, {});
189
+ const afterRoutes = routeFacts(after, {});
190
+ const removed = [...beforeRoutes.keys()].filter((key) => !afterRoutes.has(key));
191
+ const added = [...afterRoutes.keys()].filter((key) => !beforeRoutes.has(key));
192
+ const renames = /* @__PURE__ */ new Map();
193
+ /**
194
+ * A route as it is called over HTTP.
195
+ */
196
+ const httpLabel = (route, fallback) => route ? `${route.method} ${route.path}` : fallback;
197
+ for (const goneKey of removed) {
198
+ const gone = beforeRoutes.get(goneKey);
199
+ const match = added.find((key) => {
200
+ const arrived = afterRoutes.get(key);
201
+ return arrived?.method === gone?.method && arrived?.path === gone?.path && !renames.has(key);
202
+ });
203
+ if (match) renames.set(match, goneKey);
204
+ }
205
+ for (const [toKey, fromKey] of renames) changes.push({
206
+ level: "breaking",
207
+ key: fromKey,
208
+ summary: `${fromKey} renamed to ${toKey}`,
209
+ detail: "client method and generated client names change, HTTP surface unaffected"
210
+ });
211
+ for (const key of removed) {
212
+ if ([...renames.values()].includes(key)) continue;
213
+ const gone = beforeRoutes.get(key);
214
+ changes.push({
215
+ level: "breaking",
216
+ key,
217
+ summary: `${httpLabel(gone, key)} is gone`,
218
+ detail: `${gone?.method} ${gone?.path} no longer exists`
219
+ });
220
+ }
221
+ for (const key of added) {
222
+ if (renames.has(key)) continue;
223
+ const arrived = afterRoutes.get(key);
224
+ changes.push({
225
+ level: "added",
226
+ key,
227
+ summary: `${httpLabel(arrived, key)} added`,
228
+ detail: `${arrived?.method} ${arrived?.path}`
229
+ });
230
+ }
231
+ for (const [key, gone] of beforeRoutes) {
232
+ const arrived = afterRoutes.get(key);
233
+ if (!arrived) continue;
234
+ if (gone.method !== arrived.method) changes.push({
235
+ level: "breaking",
236
+ key,
237
+ summary: `${gone.path} answers ${arrived.method} instead of ${gone.method}`
238
+ });
239
+ if (gone.path !== arrived.path) changes.push({
240
+ level: "breaking",
241
+ key,
242
+ summary: `${gone.method} ${gone.path} moved to ${arrived.path}`
243
+ });
244
+ const droppedStatuses = gone.statuses.filter((status) => !arrived.statuses.includes(status));
245
+ if (droppedStatuses.length > 0) changes.push({
246
+ level: "breaking",
247
+ key,
248
+ summary: `${httpLabel(gone, key)} no longer answers ${droppedStatuses.join(", ")}`,
249
+ detail: "a caller handling that status will not see it again"
250
+ });
251
+ const newStatuses = arrived.statuses.filter((status) => !gone.statuses.includes(status));
252
+ if (newStatuses.length > 0) changes.push({
253
+ level: "changed",
254
+ key,
255
+ summary: `${httpLabel(arrived, key)} can now answer ${newStatuses.join(", ")}`
256
+ });
257
+ const inputs = [
258
+ [
259
+ "request",
260
+ "body",
261
+ gone.body,
262
+ arrived.body
263
+ ],
264
+ [
265
+ "request",
266
+ "query",
267
+ gone.query,
268
+ arrived.query
269
+ ],
270
+ [
271
+ "request",
272
+ "headers",
273
+ gone.headers,
274
+ arrived.headers
275
+ ]
276
+ ];
277
+ for (const [direction, label, was, now] of inputs) for (const change of diffSchemas(was, now, direction, label)) changes.push({
278
+ level: change.breaking ? "breaking" : "changed",
279
+ key,
280
+ summary: `${httpLabel(arrived, key)} ${change.summary}`
281
+ });
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({
286
+ level: change.breaking ? "breaking" : "changed",
287
+ key,
288
+ summary: `${httpLabel(arrived, key)} ${change.summary}`
289
+ });
290
+ }
291
+ if (!gone.deprecated && arrived.deprecated) changes.push({
292
+ level: "changed",
293
+ key,
294
+ summary: `${httpLabel(arrived, key)} is now deprecated`
295
+ });
296
+ if (gone.sunset !== arrived.sunset && arrived.sunset !== void 0) changes.push({
297
+ level: "changed",
298
+ key,
299
+ summary: `${httpLabel(arrived, key)} sunsets on ${arrived.sunset}`
300
+ });
301
+ }
302
+ for (const key of jobKeys(before)) {
303
+ if (jobKeys(after).has(key)) continue;
304
+ changes.push({
305
+ level: "breaking",
306
+ key,
307
+ summary: `the job ${key} is gone`,
308
+ detail: "whatever calls POST /jobs/run with that key stops working"
309
+ });
310
+ }
311
+ const beforeTools = toolNames(before);
312
+ const afterTools = toolNames(after);
313
+ for (const [key, name] of beforeTools) {
314
+ const arrived = afterTools.get(key);
315
+ if (arrived === void 0) {
316
+ changes.push({
317
+ level: "breaking",
318
+ key,
319
+ summary: `the tool ${name} is gone`,
320
+ detail: "a prompt or workflow naming that tool stops working"
321
+ });
322
+ continue;
323
+ }
324
+ if (arrived !== name) changes.push({
325
+ level: "breaking",
326
+ key,
327
+ summary: `the tool ${name} is now ${arrived}`,
328
+ detail: "a prompt or workflow naming the old one stops working"
329
+ });
330
+ }
331
+ const order = {
332
+ breaking: 0,
333
+ changed: 1,
334
+ added: 2
335
+ };
336
+ return changes.sort((left, right) => order[left.level] - order[right.level] || left.key.localeCompare(right.key));
337
+ };
338
+ /**
339
+ * One block per change, ready to print: the level, the summary, and the
340
+ * detail indented beneath it.
341
+ */
342
+ const formatChange = (change) => {
343
+ const label = change.level.toUpperCase().padEnd(8);
344
+ const detail = change.detail === void 0 ? "" : `\n ${change.detail}`;
345
+ return `${label} ${change.summary}${detail}`;
346
+ };
347
+ /**
348
+ * Whether a diff should fail a pipeline.
349
+ */
350
+ const hasBreakingChange = (changes) => changes.some((change) => change.level === "breaking");
351
+ //#endregion
352
+ //#region src/generate-clients.ts
353
+ const currentContents = (output) => {
354
+ try {
355
+ return readFileSync(output, "utf8");
356
+ } catch {
357
+ return;
358
+ }
359
+ };
360
+ /**
361
+ * Writes every client an api declares, leaving a file alone when it already
362
+ * matches so watchers and build tools see no change.
363
+ */
364
+ const writeClients = (contract, clients) => clients.map((client) => {
365
+ const rendered = client.generate(contract);
366
+ const changed = currentContents(client.output) !== rendered;
367
+ if (changed) {
368
+ mkdirSync(dirname(client.output), { recursive: true });
369
+ writeFileSync(client.output, rendered);
370
+ }
371
+ return {
372
+ kind: client.kind,
373
+ output: client.output,
374
+ changed
375
+ };
376
+ });
377
+ /**
378
+ * Every client that no longer matches its api, without writing anything.
379
+ *
380
+ * This is what a pipeline runs: a generated client that has fallen behind is a
381
+ * compile error waiting to happen in whatever imports it.
382
+ */
383
+ const checkClients = (contract, clients) => clients.flatMap((client) => {
384
+ const current = currentContents(client.output);
385
+ if (current === void 0) return [{
386
+ kind: client.kind,
387
+ output: client.output,
388
+ reason: "missing"
389
+ }];
390
+ if (current !== client.generate(contract)) return [{
391
+ kind: client.kind,
392
+ output: client.output,
393
+ reason: "outdated"
394
+ }];
395
+ return [];
396
+ });
397
+ /**
398
+ * What a pipeline prints when a check fails, naming the command that fixes it
399
+ * rather than printing a diff nobody reads.
400
+ */
401
+ 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`;
405
+ });
406
+ return [
407
+ stale.length === 1 ? "A generated client is out of date:" : `${stale.length} generated clients are out of date:`,
408
+ ...lines,
409
+ "",
410
+ `Run \`${command}\` and commit the result.`
411
+ ].join("\n");
412
+ };
413
+ //#endregion
414
+ //#region src/generate-types.ts
415
+ /**
416
+ * The keys of `KizunaConfigShape`, in the order the generated interface writes
417
+ * them. Everything else a config declares, `routes` and `clients` included, is
418
+ * read at runtime rather than typed against, so it stays out.
419
+ */
420
+ const CONFIG_KEYS = [
421
+ "adapter",
422
+ "tags",
423
+ "auth",
424
+ "requestContext",
425
+ "validation",
426
+ "jobs",
427
+ "plugins"
428
+ ];
429
+ /**
430
+ * The keys inside `auth`, which nests rather than flattening: `identities` is a
431
+ * record of declarations, `guardSchema` is one.
432
+ */
433
+ const AUTH_KEYS = ["identities", "guardSchema"];
434
+ var ConfigSyntaxError = class extends Error {};
435
+ /**
436
+ * Every `import` in the config, keyed by the local name it binds.
437
+ */
438
+ const collectImports = (source) => {
439
+ const imports = /* @__PURE__ */ new Map();
440
+ for (const statement of source.statements) {
441
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
442
+ const module = statement.moduleSpecifier.text;
443
+ const bindings = statement.importClause?.namedBindings;
444
+ if (statement.importClause?.name) imports.set(statement.importClause.name.text, {
445
+ module,
446
+ exported: "default",
447
+ isDefault: true
448
+ });
449
+ if (bindings && ts.isNamedImports(bindings)) for (const element of bindings.elements) imports.set(element.name.text, {
450
+ module,
451
+ exported: (element.propertyName ?? element.name).text,
452
+ isDefault: false
453
+ });
454
+ }
455
+ return imports;
456
+ };
457
+ /**
458
+ * The object literal handed to `defineConfig`, following a default export
459
+ * through a `const` when the config names it before exporting it.
460
+ */
461
+ const findConfigObject = (source) => {
462
+ let exported;
463
+ for (const statement of source.statements) if (ts.isExportAssignment(statement) && !statement.isExportEquals) exported = statement.expression;
464
+ if (!exported) throw new ConfigSyntaxError("No default export found. A kizuna config default-exports its `defineConfig(...)` call.");
465
+ const resolve = (expression) => {
466
+ if (!ts.isIdentifier(expression)) return expression;
467
+ for (const statement of source.statements) {
468
+ if (!ts.isVariableStatement(statement)) continue;
469
+ for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.name.text === expression.text && declaration.initializer) return declaration.initializer;
470
+ }
471
+ return expression;
472
+ };
473
+ const call = resolve(exported);
474
+ if (!ts.isCallExpression(call) || !ts.isIdentifier(call.expression) || call.expression.text !== "defineConfig") throw new ConfigSyntaxError("The default export is not a `defineConfig(...)` call.");
475
+ const [argument] = call.arguments;
476
+ if (!argument || !ts.isObjectLiteralExpression(argument)) throw new ConfigSyntaxError("`defineConfig` was called without an object literal, so there is nothing to read.");
477
+ return argument;
478
+ };
479
+ /**
480
+ * The identifier a value is rooted at, so the generated file imports it. A call
481
+ * is rooted at what it calls, which is how `expressAdapter()` reaches
482
+ * `expressAdapter`.
483
+ */
484
+ const rootIdentifier = (expression) => {
485
+ if (ts.isIdentifier(expression)) return expression;
486
+ if (ts.isCallExpression(expression)) return rootIdentifier(expression.expression);
487
+ };
488
+ /**
489
+ * A value's type, as the generated interface writes it. A call becomes the
490
+ * return of what it calls, because the config stores the call's result.
491
+ */
492
+ const typeOfValue = (expression, used, key) => {
493
+ const root = rootIdentifier(expression);
494
+ if (!root) throw new ConfigSyntaxError(`\`${key}\` is not a name this generator can follow. Move the value to its own \`const\` and name it here.`);
495
+ used.add(root.text);
496
+ return ts.isCallExpression(expression) ? `ReturnType<typeof ${root.text}>` : `typeof ${root.text}`;
497
+ };
498
+ /**
499
+ * A record of declarations, as `identities` and `requestContext` take them.
500
+ */
501
+ const typeOfRecord = (expression, used, key, indent) => {
502
+ if (!ts.isObjectLiteralExpression(expression)) return typeOfValue(expression, used, key);
503
+ const lines = [];
504
+ for (const property of expression.properties) {
505
+ if (ts.isShorthandPropertyAssignment(property)) {
506
+ used.add(property.name.text);
507
+ lines.push(`${indent} ${property.name.text}: typeof ${property.name.text};`);
508
+ continue;
509
+ }
510
+ if (ts.isPropertyAssignment(property) && !ts.isComputedPropertyName(property.name)) {
511
+ const name = ts.isIdentifier(property.name) ? property.name.text : property.name.getText();
512
+ lines.push(`${indent} ${name}: ${typeOfValue(property.initializer, used, key)};`);
513
+ continue;
514
+ }
515
+ throw new ConfigSyntaxError(`\`${key}\` holds something this generator cannot follow. Every entry has to name a declaration.`);
516
+ }
517
+ return `{\n${lines.join("\n")}\n${indent}}`;
518
+ };
519
+ /**
520
+ * The string literals in an array, as a union. This is what `issueCodes` is.
521
+ */
522
+ const typeOfStringUnion = (expression, key) => {
523
+ if (!ts.isArrayLiteralExpression(expression)) throw new ConfigSyntaxError(`\`${key}\` has to be an array of string literals.`);
524
+ const codes = expression.elements.map((element) => {
525
+ if (!ts.isStringLiteral(element)) throw new ConfigSyntaxError(`\`${key}\` has to hold string literals, so every code is known at compile time.`);
526
+ return `'${element.text}'`;
527
+ });
528
+ return codes.length > 0 ? codes.join(" | ") : "never";
529
+ };
530
+ /**
531
+ * Each plugin in order, as a tuple, so a handler reaches each one under its own
532
+ * slug.
533
+ */
534
+ const typeOfPluginList = (expression, used) => {
535
+ 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(", ")}]`;
537
+ };
538
+ /**
539
+ * The `issueCodes` inside `validation`, or nothing when it declares none.
540
+ */
541
+ const issueCodesOf = (expression) => {
542
+ if (!ts.isObjectLiteralExpression(expression)) throw new ConfigSyntaxError("`validation` has to be an object literal.");
543
+ for (const property of expression.properties) if (ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === "issueCodes") return typeOfStringUnion(property.initializer, "validation");
544
+ };
545
+ /**
546
+ * What `auth` carries: the identities, each as its own key, and the schema their
547
+ * guards refuse with.
548
+ */
549
+ const authLines = (expression, used) => {
550
+ if (!ts.isObjectLiteralExpression(expression)) throw new ConfigSyntaxError("`auth` has to be an object literal, so its identities can be read.");
551
+ const declared = /* @__PURE__ */ new Map();
552
+ for (const property of expression.properties) if (ts.isShorthandPropertyAssignment(property)) declared.set(property.name.text, property.name);
553
+ else if (ts.isPropertyAssignment(property) && ts.isIdentifier(property.name)) declared.set(property.name.text, property.initializer);
554
+ const lines = [];
555
+ for (const key of AUTH_KEYS) {
556
+ const value = declared.get(key);
557
+ if (!value) continue;
558
+ lines.push(key === "identities" ? ` identities: ${typeOfRecord(value, used, "auth", " ")};` : ` guardSchema: ${typeOfValue(value, used, "auth")};`);
559
+ }
560
+ return lines;
561
+ };
562
+ const HEADER = `/**
563
+ * This file was automatically generated by kizuna.
564
+ * DO NOT MODIFY IT BY HAND. Instead, modify your source kizuna config,
565
+ * and re-run \`kizuna generate\` to regenerate this file.
566
+ */`;
567
+ /**
568
+ * The `import type` lines the interface needs, grouped by module and written in
569
+ * the order the config imported them.
570
+ */
571
+ const renderImports = (imports, used) => {
572
+ const byModule = /* @__PURE__ */ new Map();
573
+ const defaults = [];
574
+ for (const [local, imported] of imports) {
575
+ if (!used.has(local)) continue;
576
+ if (imported.isDefault) {
577
+ defaults.push(`import type ${local} from '${imported.module}';`);
578
+ continue;
579
+ }
580
+ const specifier = imported.exported === local ? local : `${imported.exported} as ${local}`;
581
+ const existing = byModule.get(imported.module);
582
+ if (existing) existing.push(specifier);
583
+ else byModule.set(imported.module, [specifier]);
584
+ }
585
+ const named = [...byModule].map(([module, names]) => `import type { ${names.join(", ")} } from '${module}';`);
586
+ return [...defaults, ...named].join("\n");
587
+ };
588
+ /**
589
+ * Write the `Config` a `kizuna.config.ts` implies, which is what
590
+ * `new Kizuna<Config>()` is typed by.
591
+ *
592
+ * Read from the config's syntax rather than by running it: the generated file
593
+ * imports the same names the config did, and a config that loads is not a
594
+ * prerequisite for typing the routes it serves.
595
+ */
596
+ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
597
+ const source = ts.createSourceFile(fileName, configSource, ts.ScriptTarget.Latest, true);
598
+ const imports = collectImports(source);
599
+ const configObject = findConfigObject(source);
600
+ const declared = /* @__PURE__ */ new Map();
601
+ for (const property of configObject.properties) {
602
+ if (ts.isShorthandPropertyAssignment(property)) {
603
+ declared.set(property.name.text, property.name);
604
+ continue;
605
+ }
606
+ if (ts.isPropertyAssignment(property) && ts.isIdentifier(property.name)) declared.set(property.name.text, property.initializer);
607
+ }
608
+ const used = /* @__PURE__ */ new Set();
609
+ const lines = [];
610
+ for (const key of CONFIG_KEYS) {
611
+ const value = declared.get(key);
612
+ if (!value) continue;
613
+ if (key === "auth") {
614
+ const inner = authLines(value, used);
615
+ if (inner.length > 0) lines.push(` auth: {\n${inner.join("\n")}\n };`);
616
+ } else if (key === "requestContext") lines.push(` ${key}: ${typeOfRecord(value, used, key, " ")};`);
617
+ else if (key === "validation") {
618
+ const codes = issueCodesOf(value);
619
+ if (codes !== void 0) lines.push(` validation: {\n issueCodes: ${codes};\n };`);
620
+ } else if (key === "plugins") lines.push(` ${key}: ${typeOfPluginList(value, used)};`);
621
+ else lines.push(` ${key}: ${typeOfValue(value, used, key)};`);
622
+ }
623
+ const importBlock = renderImports(imports, used);
624
+ const body = `export interface Config {\n${lines.join("\n")}\n}`;
625
+ return `${importBlock === "" ? HEADER : `${HEADER}\n${importBlock}`}\n\n${body}\n`;
626
+ };
627
+ //#endregion
628
+ //#region src/diff-against.ts
629
+ const git = (cwd, ...args) => execFileSync("git", args, {
630
+ cwd,
631
+ encoding: "utf8"
632
+ }).trim();
633
+ /**
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');
643
+ */
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-"));
651
+ 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
+ }
667
+ }
668
+ };
669
+ //#endregion
670
+ //#region src/route-map.ts
671
+ const permissionList = (requires) => {
672
+ if (!requires || typeof requires !== "object") return "";
673
+ return Object.entries(requires).map(([subject, actions]) => `${subject}:${actions.join("|")}`).join(" ");
674
+ };
675
+ /**
676
+ * What a route's `auth` asks of a caller, in one cell.
677
+ */
678
+ const describeAuth = (auth) => {
679
+ if (auth === void 0 || auth === false) return "public";
680
+ if (typeof auth === "string") return auth;
681
+ if (Array.isArray(auth)) return auth.join("|");
682
+ const rule = auth;
683
+ const identity = Array.isArray(rule.identity) ? rule.identity.join("|") : String(rule.identity);
684
+ const roles = rule.roles === void 0 ? "" : Array.isArray(rule.roles) ? rule.roles.join("|") : String(rule.roles);
685
+ const requires = permissionList(rule.requires);
686
+ return [
687
+ identity,
688
+ roles && `roles ${roles}`,
689
+ requires && `requires ${requires}`
690
+ ].filter(Boolean).join(", ");
691
+ };
692
+ const describeSunset = (sunset) => {
693
+ if (sunset === void 0) return void 0;
694
+ return typeof sunset === "string" ? sunset : sunset.date;
695
+ };
696
+ /**
697
+ * Every route an api serves, in the order it declares them.
698
+ */
699
+ const routeMap = createGenerator((_options, _api) => {
700
+ const entries = [];
701
+ const toolKeys = [];
702
+ return {
703
+ processRoute({ routeKey, route, routeTags, deprecated, deprecationMessage }) {
704
+ if (route.tool) toolKeys.push({
705
+ key: routeKey,
706
+ origin: "route"
707
+ });
708
+ entries.push({
709
+ key: routeKey,
710
+ method: route.method,
711
+ path: route.path,
712
+ auth: describeAuth(route.auth),
713
+ tags: routeTags,
714
+ deprecated: deprecated ? deprecationMessage ?? "" : void 0,
715
+ sunset: describeSunset(route.sunset)
716
+ });
717
+ },
718
+ finalize() {
719
+ const names = toolKeys.length > 0 ? deriveToolNames(toolKeys) : /* @__PURE__ */ new Map();
720
+ return entries.map((entry) => ({
721
+ ...entry,
722
+ tool: names.get(entry.key) ?? (toolKeys.some((tool) => tool.key === entry.key) ? toToolName(entry.key) : void 0)
723
+ }));
724
+ }
725
+ };
726
+ });
727
+ const pad = (text, width) => text + " ".repeat(Math.max(0, width - text.length));
728
+ /**
729
+ * The route map as aligned columns, one route per line.
730
+ */
731
+ const formatRoutes = (entries) => {
732
+ if (entries.length === 0) return "This config declares no routes.";
733
+ const methodWidth = Math.max(...entries.map((entry) => entry.method.length));
734
+ const pathWidth = Math.max(...entries.map((entry) => entry.path.length));
735
+ const keyWidth = Math.max(...entries.map((entry) => entry.key.length));
736
+ return entries.map((entry) => {
737
+ const notes = [
738
+ `auth: ${entry.auth}`,
739
+ entry.tool && `tool: ${entry.tool}`,
740
+ entry.deprecated !== void 0 && `deprecated${entry.deprecated ? `, ${entry.deprecated}` : ""}`,
741
+ entry.sunset && `sunset ${entry.sunset}`
742
+ ].filter(Boolean);
743
+ return `${pad(entry.method, methodWidth)} ${pad(entry.path, pathWidth)} ${pad(entry.key, keyWidth)} ${notes.join(" ")}`.trimEnd();
744
+ }).join("\n");
745
+ };
746
+ //#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 };