@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,853 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ let jiti = require("jiti");
24
+ let kizunajs = require("kizunajs");
25
+ let kizunajs_generator = require("kizunajs/generator");
26
+ let kizunajs_adapter = require("kizunajs/adapter");
27
+ let node_fs = require("node:fs");
28
+ let node_path = require("node:path");
29
+ let typescript = require("typescript");
30
+ typescript = __toESM(typescript, 1);
31
+ let node_child_process = require("node:child_process");
32
+ //#region src/load-config.ts
33
+ /**
34
+ * Imports a config module with jiti, so a `.ts` config works without a build
35
+ * step, and returns every api it declares along with the clients and the types
36
+ * output each one asks for.
37
+ *
38
+ * Returns an empty list when the module default-exports nothing that looks like
39
+ * a config.
40
+ */
41
+ 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
+ name,
44
+ api: entry.api,
45
+ clients: entry.clients ?? [],
46
+ typesOutput: entry.typescript?.outputFile
47
+ }));
48
+ };
49
+ //#endregion
50
+ //#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
+ const joinPath = (parent, key) => parent === "" ? key : `${parent}.${key}`;
81
+ /**
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.
84
+ */
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;
89
+ };
90
+ /**
91
+ * What changed between two versions of one schema, and whether it breaks the
92
+ * people already calling the route.
93
+ */
94
+ const diffSchemas = (before, after, direction, path = "") => {
95
+ if (before === void 0 && after === void 0) return [];
96
+ if (before === void 0) return after === void 0 ? [] : [{
97
+ breaking: direction === "request",
98
+ path,
99
+ summary: direction === "request" ? `${path || "a body"} is now required` : `${path || "a body"} is now sent`
100
+ }];
101
+ if (after === void 0) return [{
102
+ breaking: direction === "response",
103
+ path,
104
+ summary: `${path || "the body"} is gone`
105
+ }];
106
+ const changes = [];
107
+ const beforeElement = elementOf(before);
108
+ 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);
115
+ const here = joinPath(path, key);
116
+ if (!existing) {
117
+ if (!field.optional) changes.push({
118
+ breaking: direction === "request",
119
+ path: here,
120
+ summary: direction === "request" ? `${here} is now required` : `${here} is now part of the response`
121
+ });
122
+ continue;
123
+ }
124
+ if (existing.optional && !field.optional) changes.push({
125
+ breaking: direction === "request",
126
+ path: here,
127
+ summary: `${here} is no longer optional`
128
+ });
129
+ changes.push(...diffSchemas(existing.schema, field.schema, direction, here));
130
+ }
131
+ for (const [key] of beforeShape.fields) {
132
+ if (afterShape.fields.has(key)) continue;
133
+ const here = joinPath(path, key);
134
+ changes.push({
135
+ breaking: direction === "response",
136
+ path: here,
137
+ summary: `${here} is gone`
138
+ });
139
+ }
140
+ return changes;
141
+ }
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));
155
+ if (removed.length > 0) changes.push({
156
+ breaking: true,
157
+ path,
158
+ summary: `${path || "the body"} no longer accepts ${removed.join(", ")}`
159
+ });
160
+ if (added.length > 0) changes.push({
161
+ breaking: direction === "response",
162
+ path,
163
+ summary: direction === "response" ? `${path || "the body"} can now be ${added.join(", ")}` : `${path || "the body"} also accepts ${added.join(", ")}`
164
+ });
165
+ }
166
+ return changes;
167
+ };
168
+ //#endregion
169
+ //#region src/diff-apis.ts
170
+ const routeFacts = (0, kizunajs_generator.createGenerator)(() => {
171
+ const facts = /* @__PURE__ */ new Map();
172
+ 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
187
+ };
188
+ });
189
+ const sunsetOf = (route) => {
190
+ const declared = route.sunset;
191
+ if (declared === void 0) return void 0;
192
+ return typeof declared === "string" ? declared : declared.date;
193
+ };
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));
198
+ };
199
+ /**
200
+ * The MCP name of every route that publishes as a tool, keyed by route key.
201
+ */
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)]));
203
+ /**
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.
208
+ */
209
+ const diffApis = (before, after) => {
210
+ const changes = [];
211
+ const beforeRoutes = routeFacts(before, {});
212
+ const afterRoutes = routeFacts(after, {});
213
+ const removed = [...beforeRoutes.keys()].filter((key) => !afterRoutes.has(key));
214
+ const added = [...afterRoutes.keys()].filter((key) => !beforeRoutes.has(key));
215
+ const renames = /* @__PURE__ */ new Map();
216
+ /**
217
+ * A route as it is called over HTTP.
218
+ */
219
+ const httpLabel = (route, fallback) => route ? `${route.method} ${route.path}` : fallback;
220
+ for (const goneKey of removed) {
221
+ const gone = beforeRoutes.get(goneKey);
222
+ const match = added.find((key) => {
223
+ const arrived = afterRoutes.get(key);
224
+ return arrived?.method === gone?.method && arrived?.path === gone?.path && !renames.has(key);
225
+ });
226
+ if (match) renames.set(match, goneKey);
227
+ }
228
+ for (const [toKey, fromKey] of renames) changes.push({
229
+ level: "breaking",
230
+ key: fromKey,
231
+ summary: `${fromKey} renamed to ${toKey}`,
232
+ detail: "client method and generated client names change, HTTP surface unaffected"
233
+ });
234
+ for (const key of removed) {
235
+ if ([...renames.values()].includes(key)) continue;
236
+ const gone = beforeRoutes.get(key);
237
+ changes.push({
238
+ level: "breaking",
239
+ key,
240
+ summary: `${httpLabel(gone, key)} is gone`,
241
+ detail: `${gone?.method} ${gone?.path} no longer exists`
242
+ });
243
+ }
244
+ for (const key of added) {
245
+ if (renames.has(key)) continue;
246
+ const arrived = afterRoutes.get(key);
247
+ changes.push({
248
+ level: "added",
249
+ key,
250
+ summary: `${httpLabel(arrived, key)} added`,
251
+ detail: `${arrived?.method} ${arrived?.path}`
252
+ });
253
+ }
254
+ for (const [key, gone] of beforeRoutes) {
255
+ const arrived = afterRoutes.get(key);
256
+ if (!arrived) continue;
257
+ if (gone.method !== arrived.method) changes.push({
258
+ level: "breaking",
259
+ key,
260
+ summary: `${gone.path} answers ${arrived.method} instead of ${gone.method}`
261
+ });
262
+ if (gone.path !== arrived.path) changes.push({
263
+ level: "breaking",
264
+ key,
265
+ summary: `${gone.method} ${gone.path} moved to ${arrived.path}`
266
+ });
267
+ const droppedStatuses = gone.statuses.filter((status) => !arrived.statuses.includes(status));
268
+ if (droppedStatuses.length > 0) changes.push({
269
+ level: "breaking",
270
+ key,
271
+ summary: `${httpLabel(gone, key)} no longer answers ${droppedStatuses.join(", ")}`,
272
+ detail: "a caller handling that status will not see it again"
273
+ });
274
+ const newStatuses = arrived.statuses.filter((status) => !gone.statuses.includes(status));
275
+ if (newStatuses.length > 0) changes.push({
276
+ level: "changed",
277
+ key,
278
+ summary: `${httpLabel(arrived, key)} can now answer ${newStatuses.join(", ")}`
279
+ });
280
+ const inputs = [
281
+ [
282
+ "request",
283
+ "body",
284
+ gone.body,
285
+ arrived.body
286
+ ],
287
+ [
288
+ "request",
289
+ "query",
290
+ gone.query,
291
+ arrived.query
292
+ ],
293
+ [
294
+ "request",
295
+ "headers",
296
+ gone.headers,
297
+ arrived.headers
298
+ ]
299
+ ];
300
+ for (const [direction, label, was, now] of inputs) for (const change of diffSchemas(was, now, direction, label)) changes.push({
301
+ level: change.breaking ? "breaking" : "changed",
302
+ key,
303
+ summary: `${httpLabel(arrived, key)} ${change.summary}`
304
+ });
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({
309
+ level: change.breaking ? "breaking" : "changed",
310
+ key,
311
+ summary: `${httpLabel(arrived, key)} ${change.summary}`
312
+ });
313
+ }
314
+ if (!gone.deprecated && arrived.deprecated) changes.push({
315
+ level: "changed",
316
+ key,
317
+ summary: `${httpLabel(arrived, key)} is now deprecated`
318
+ });
319
+ if (gone.sunset !== arrived.sunset && arrived.sunset !== void 0) changes.push({
320
+ level: "changed",
321
+ key,
322
+ summary: `${httpLabel(arrived, key)} sunsets on ${arrived.sunset}`
323
+ });
324
+ }
325
+ for (const key of jobKeys(before)) {
326
+ if (jobKeys(after).has(key)) continue;
327
+ changes.push({
328
+ level: "breaking",
329
+ key,
330
+ summary: `the job ${key} is gone`,
331
+ detail: "whatever calls POST /jobs/run with that key stops working"
332
+ });
333
+ }
334
+ const beforeTools = toolNames(before);
335
+ const afterTools = toolNames(after);
336
+ for (const [key, name] of beforeTools) {
337
+ const arrived = afterTools.get(key);
338
+ if (arrived === void 0) {
339
+ changes.push({
340
+ level: "breaking",
341
+ key,
342
+ summary: `the tool ${name} is gone`,
343
+ detail: "a prompt or workflow naming that tool stops working"
344
+ });
345
+ continue;
346
+ }
347
+ if (arrived !== name) changes.push({
348
+ level: "breaking",
349
+ key,
350
+ summary: `the tool ${name} is now ${arrived}`,
351
+ detail: "a prompt or workflow naming the old one stops working"
352
+ });
353
+ }
354
+ const order = {
355
+ breaking: 0,
356
+ changed: 1,
357
+ added: 2
358
+ };
359
+ return changes.sort((left, right) => order[left.level] - order[right.level] || left.key.localeCompare(right.key));
360
+ };
361
+ /**
362
+ * One block per change, ready to print: the level, the summary, and the
363
+ * detail indented beneath it.
364
+ */
365
+ const formatChange = (change) => {
366
+ const label = change.level.toUpperCase().padEnd(8);
367
+ const detail = change.detail === void 0 ? "" : `\n ${change.detail}`;
368
+ return `${label} ${change.summary}${detail}`;
369
+ };
370
+ /**
371
+ * Whether a diff should fail a pipeline.
372
+ */
373
+ const hasBreakingChange = (changes) => changes.some((change) => change.level === "breaking");
374
+ //#endregion
375
+ //#region src/generate-clients.ts
376
+ const currentContents = (output) => {
377
+ try {
378
+ return (0, node_fs.readFileSync)(output, "utf8");
379
+ } catch {
380
+ return;
381
+ }
382
+ };
383
+ /**
384
+ * Writes every client an api declares, leaving a file alone when it already
385
+ * matches so watchers and build tools see no change.
386
+ */
387
+ const writeClients = (contract, clients) => clients.map((client) => {
388
+ const rendered = client.generate(contract);
389
+ const changed = currentContents(client.output) !== rendered;
390
+ if (changed) {
391
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(client.output), { recursive: true });
392
+ (0, node_fs.writeFileSync)(client.output, rendered);
393
+ }
394
+ return {
395
+ kind: client.kind,
396
+ output: client.output,
397
+ changed
398
+ };
399
+ });
400
+ /**
401
+ * Every client that no longer matches its api, without writing anything.
402
+ *
403
+ * This is what a pipeline runs: a generated client that has fallen behind is a
404
+ * compile error waiting to happen in whatever imports it.
405
+ */
406
+ const checkClients = (contract, clients) => clients.flatMap((client) => {
407
+ const current = currentContents(client.output);
408
+ if (current === void 0) return [{
409
+ kind: client.kind,
410
+ output: client.output,
411
+ reason: "missing"
412
+ }];
413
+ if (current !== client.generate(contract)) return [{
414
+ kind: client.kind,
415
+ output: client.output,
416
+ reason: "outdated"
417
+ }];
418
+ return [];
419
+ });
420
+ /**
421
+ * What a pipeline prints when a check fails, naming the command that fixes it
422
+ * rather than printing a diff nobody reads.
423
+ */
424
+ 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`;
428
+ });
429
+ return [
430
+ stale.length === 1 ? "A generated client is out of date:" : `${stale.length} generated clients are out of date:`,
431
+ ...lines,
432
+ "",
433
+ `Run \`${command}\` and commit the result.`
434
+ ].join("\n");
435
+ };
436
+ //#endregion
437
+ //#region src/generate-types.ts
438
+ /**
439
+ * The keys of `KizunaConfigShape`, in the order the generated interface writes
440
+ * them. Everything else a config declares, `routes` and `clients` included, is
441
+ * read at runtime rather than typed against, so it stays out.
442
+ */
443
+ const CONFIG_KEYS = [
444
+ "adapter",
445
+ "tags",
446
+ "auth",
447
+ "requestContext",
448
+ "validation",
449
+ "jobs",
450
+ "plugins"
451
+ ];
452
+ /**
453
+ * The keys inside `auth`, which nests rather than flattening: `identities` is a
454
+ * record of declarations, `guardSchema` is one.
455
+ */
456
+ const AUTH_KEYS = ["identities", "guardSchema"];
457
+ var ConfigSyntaxError = class extends Error {};
458
+ /**
459
+ * Every `import` in the config, keyed by the local name it binds.
460
+ */
461
+ const collectImports = (source) => {
462
+ const imports = /* @__PURE__ */ new Map();
463
+ for (const statement of source.statements) {
464
+ if (!typescript.default.isImportDeclaration(statement) || !typescript.default.isStringLiteral(statement.moduleSpecifier)) continue;
465
+ const module = statement.moduleSpecifier.text;
466
+ const bindings = statement.importClause?.namedBindings;
467
+ if (statement.importClause?.name) imports.set(statement.importClause.name.text, {
468
+ module,
469
+ exported: "default",
470
+ isDefault: true
471
+ });
472
+ if (bindings && typescript.default.isNamedImports(bindings)) for (const element of bindings.elements) imports.set(element.name.text, {
473
+ module,
474
+ exported: (element.propertyName ?? element.name).text,
475
+ isDefault: false
476
+ });
477
+ }
478
+ return imports;
479
+ };
480
+ /**
481
+ * The object literal handed to `defineConfig`, following a default export
482
+ * through a `const` when the config names it before exporting it.
483
+ */
484
+ const findConfigObject = (source) => {
485
+ let exported;
486
+ for (const statement of source.statements) if (typescript.default.isExportAssignment(statement) && !statement.isExportEquals) exported = statement.expression;
487
+ if (!exported) throw new ConfigSyntaxError("No default export found. A kizuna config default-exports its `defineConfig(...)` call.");
488
+ const resolve = (expression) => {
489
+ if (!typescript.default.isIdentifier(expression)) return expression;
490
+ for (const statement of source.statements) {
491
+ if (!typescript.default.isVariableStatement(statement)) continue;
492
+ for (const declaration of statement.declarationList.declarations) if (typescript.default.isIdentifier(declaration.name) && declaration.name.text === expression.text && declaration.initializer) return declaration.initializer;
493
+ }
494
+ return expression;
495
+ };
496
+ const call = resolve(exported);
497
+ if (!typescript.default.isCallExpression(call) || !typescript.default.isIdentifier(call.expression) || call.expression.text !== "defineConfig") throw new ConfigSyntaxError("The default export is not a `defineConfig(...)` call.");
498
+ const [argument] = call.arguments;
499
+ if (!argument || !typescript.default.isObjectLiteralExpression(argument)) throw new ConfigSyntaxError("`defineConfig` was called without an object literal, so there is nothing to read.");
500
+ return argument;
501
+ };
502
+ /**
503
+ * The identifier a value is rooted at, so the generated file imports it. A call
504
+ * is rooted at what it calls, which is how `expressAdapter()` reaches
505
+ * `expressAdapter`.
506
+ */
507
+ const rootIdentifier = (expression) => {
508
+ if (typescript.default.isIdentifier(expression)) return expression;
509
+ if (typescript.default.isCallExpression(expression)) return rootIdentifier(expression.expression);
510
+ };
511
+ /**
512
+ * A value's type, as the generated interface writes it. A call becomes the
513
+ * return of what it calls, because the config stores the call's result.
514
+ */
515
+ const typeOfValue = (expression, used, key) => {
516
+ const root = rootIdentifier(expression);
517
+ 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.`);
518
+ used.add(root.text);
519
+ return typescript.default.isCallExpression(expression) ? `ReturnType<typeof ${root.text}>` : `typeof ${root.text}`;
520
+ };
521
+ /**
522
+ * A record of declarations, as `identities` and `requestContext` take them.
523
+ */
524
+ const typeOfRecord = (expression, used, key, indent) => {
525
+ if (!typescript.default.isObjectLiteralExpression(expression)) return typeOfValue(expression, used, key);
526
+ const lines = [];
527
+ for (const property of expression.properties) {
528
+ if (typescript.default.isShorthandPropertyAssignment(property)) {
529
+ used.add(property.name.text);
530
+ lines.push(`${indent} ${property.name.text}: typeof ${property.name.text};`);
531
+ continue;
532
+ }
533
+ if (typescript.default.isPropertyAssignment(property) && !typescript.default.isComputedPropertyName(property.name)) {
534
+ const name = typescript.default.isIdentifier(property.name) ? property.name.text : property.name.getText();
535
+ lines.push(`${indent} ${name}: ${typeOfValue(property.initializer, used, key)};`);
536
+ continue;
537
+ }
538
+ throw new ConfigSyntaxError(`\`${key}\` holds something this generator cannot follow. Every entry has to name a declaration.`);
539
+ }
540
+ return `{\n${lines.join("\n")}\n${indent}}`;
541
+ };
542
+ /**
543
+ * The string literals in an array, as a union. This is what `issueCodes` is.
544
+ */
545
+ const typeOfStringUnion = (expression, key) => {
546
+ if (!typescript.default.isArrayLiteralExpression(expression)) throw new ConfigSyntaxError(`\`${key}\` has to be an array of string literals.`);
547
+ const codes = expression.elements.map((element) => {
548
+ if (!typescript.default.isStringLiteral(element)) throw new ConfigSyntaxError(`\`${key}\` has to hold string literals, so every code is known at compile time.`);
549
+ return `'${element.text}'`;
550
+ });
551
+ return codes.length > 0 ? codes.join(" | ") : "never";
552
+ };
553
+ /**
554
+ * Each plugin in order, as a tuple, so a handler reaches each one under its own
555
+ * slug.
556
+ */
557
+ const typeOfPluginList = (expression, used) => {
558
+ 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(", ")}]`;
560
+ };
561
+ /**
562
+ * The `issueCodes` inside `validation`, or nothing when it declares none.
563
+ */
564
+ const issueCodesOf = (expression) => {
565
+ if (!typescript.default.isObjectLiteralExpression(expression)) throw new ConfigSyntaxError("`validation` has to be an object literal.");
566
+ for (const property of expression.properties) if (typescript.default.isPropertyAssignment(property) && typescript.default.isIdentifier(property.name) && property.name.text === "issueCodes") return typeOfStringUnion(property.initializer, "validation");
567
+ };
568
+ /**
569
+ * What `auth` carries: the identities, each as its own key, and the schema their
570
+ * guards refuse with.
571
+ */
572
+ const authLines = (expression, used) => {
573
+ if (!typescript.default.isObjectLiteralExpression(expression)) throw new ConfigSyntaxError("`auth` has to be an object literal, so its identities can be read.");
574
+ const declared = /* @__PURE__ */ new Map();
575
+ for (const property of expression.properties) if (typescript.default.isShorthandPropertyAssignment(property)) declared.set(property.name.text, property.name);
576
+ else if (typescript.default.isPropertyAssignment(property) && typescript.default.isIdentifier(property.name)) declared.set(property.name.text, property.initializer);
577
+ const lines = [];
578
+ for (const key of AUTH_KEYS) {
579
+ const value = declared.get(key);
580
+ if (!value) continue;
581
+ lines.push(key === "identities" ? ` identities: ${typeOfRecord(value, used, "auth", " ")};` : ` guardSchema: ${typeOfValue(value, used, "auth")};`);
582
+ }
583
+ return lines;
584
+ };
585
+ const HEADER = `/**
586
+ * This file was automatically generated by kizuna.
587
+ * DO NOT MODIFY IT BY HAND. Instead, modify your source kizuna config,
588
+ * and re-run \`kizuna generate\` to regenerate this file.
589
+ */`;
590
+ /**
591
+ * The `import type` lines the interface needs, grouped by module and written in
592
+ * the order the config imported them.
593
+ */
594
+ const renderImports = (imports, used) => {
595
+ const byModule = /* @__PURE__ */ new Map();
596
+ const defaults = [];
597
+ for (const [local, imported] of imports) {
598
+ if (!used.has(local)) continue;
599
+ if (imported.isDefault) {
600
+ defaults.push(`import type ${local} from '${imported.module}';`);
601
+ continue;
602
+ }
603
+ const specifier = imported.exported === local ? local : `${imported.exported} as ${local}`;
604
+ const existing = byModule.get(imported.module);
605
+ if (existing) existing.push(specifier);
606
+ else byModule.set(imported.module, [specifier]);
607
+ }
608
+ const named = [...byModule].map(([module, names]) => `import type { ${names.join(", ")} } from '${module}';`);
609
+ return [...defaults, ...named].join("\n");
610
+ };
611
+ /**
612
+ * Write the `Config` a `kizuna.config.ts` implies, which is what
613
+ * `new Kizuna<Config>()` is typed by.
614
+ *
615
+ * Read from the config's syntax rather than by running it: the generated file
616
+ * imports the same names the config did, and a config that loads is not a
617
+ * prerequisite for typing the routes it serves.
618
+ */
619
+ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
620
+ const source = typescript.default.createSourceFile(fileName, configSource, typescript.default.ScriptTarget.Latest, true);
621
+ const imports = collectImports(source);
622
+ const configObject = findConfigObject(source);
623
+ const declared = /* @__PURE__ */ new Map();
624
+ for (const property of configObject.properties) {
625
+ if (typescript.default.isShorthandPropertyAssignment(property)) {
626
+ declared.set(property.name.text, property.name);
627
+ continue;
628
+ }
629
+ if (typescript.default.isPropertyAssignment(property) && typescript.default.isIdentifier(property.name)) declared.set(property.name.text, property.initializer);
630
+ }
631
+ const used = /* @__PURE__ */ new Set();
632
+ const lines = [];
633
+ for (const key of CONFIG_KEYS) {
634
+ const value = declared.get(key);
635
+ if (!value) continue;
636
+ if (key === "auth") {
637
+ const inner = authLines(value, used);
638
+ if (inner.length > 0) lines.push(` auth: {\n${inner.join("\n")}\n };`);
639
+ } else if (key === "requestContext") lines.push(` ${key}: ${typeOfRecord(value, used, key, " ")};`);
640
+ else if (key === "validation") {
641
+ const codes = issueCodesOf(value);
642
+ if (codes !== void 0) lines.push(` validation: {\n issueCodes: ${codes};\n };`);
643
+ } else if (key === "plugins") lines.push(` ${key}: ${typeOfPluginList(value, used)};`);
644
+ else lines.push(` ${key}: ${typeOfValue(value, used, key)};`);
645
+ }
646
+ const importBlock = renderImports(imports, used);
647
+ const body = `export interface Config {\n${lines.join("\n")}\n}`;
648
+ return `${importBlock === "" ? HEADER : `${HEADER}\n${importBlock}`}\n\n${body}\n`;
649
+ };
650
+ //#endregion
651
+ //#region src/diff-against.ts
652
+ const git = (cwd, ...args) => (0, node_child_process.execFileSync)("git", args, {
653
+ cwd,
654
+ encoding: "utf8"
655
+ }).trim();
656
+ /**
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');
666
+ */
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-"));
674
+ 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
+ }
690
+ }
691
+ };
692
+ //#endregion
693
+ //#region src/route-map.ts
694
+ const permissionList = (requires) => {
695
+ if (!requires || typeof requires !== "object") return "";
696
+ return Object.entries(requires).map(([subject, actions]) => `${subject}:${actions.join("|")}`).join(" ");
697
+ };
698
+ /**
699
+ * What a route's `auth` asks of a caller, in one cell.
700
+ */
701
+ const describeAuth = (auth) => {
702
+ if (auth === void 0 || auth === false) return "public";
703
+ if (typeof auth === "string") return auth;
704
+ if (Array.isArray(auth)) return auth.join("|");
705
+ const rule = auth;
706
+ const identity = Array.isArray(rule.identity) ? rule.identity.join("|") : String(rule.identity);
707
+ const roles = rule.roles === void 0 ? "" : Array.isArray(rule.roles) ? rule.roles.join("|") : String(rule.roles);
708
+ const requires = permissionList(rule.requires);
709
+ return [
710
+ identity,
711
+ roles && `roles ${roles}`,
712
+ requires && `requires ${requires}`
713
+ ].filter(Boolean).join(", ");
714
+ };
715
+ const describeSunset = (sunset) => {
716
+ if (sunset === void 0) return void 0;
717
+ return typeof sunset === "string" ? sunset : sunset.date;
718
+ };
719
+ /**
720
+ * Every route an api serves, in the order it declares them.
721
+ */
722
+ const routeMap = (0, kizunajs_generator.createGenerator)((_options, _api) => {
723
+ const entries = [];
724
+ const toolKeys = [];
725
+ return {
726
+ processRoute({ routeKey, route, routeTags, deprecated, deprecationMessage }) {
727
+ if (route.tool) toolKeys.push({
728
+ key: routeKey,
729
+ origin: "route"
730
+ });
731
+ entries.push({
732
+ key: routeKey,
733
+ method: route.method,
734
+ path: route.path,
735
+ auth: describeAuth(route.auth),
736
+ tags: routeTags,
737
+ deprecated: deprecated ? deprecationMessage ?? "" : void 0,
738
+ sunset: describeSunset(route.sunset)
739
+ });
740
+ },
741
+ finalize() {
742
+ const names = toolKeys.length > 0 ? (0, kizunajs_generator.deriveToolNames)(toolKeys) : /* @__PURE__ */ new Map();
743
+ return entries.map((entry) => ({
744
+ ...entry,
745
+ tool: names.get(entry.key) ?? (toolKeys.some((tool) => tool.key === entry.key) ? (0, kizunajs_generator.toToolName)(entry.key) : void 0)
746
+ }));
747
+ }
748
+ };
749
+ });
750
+ const pad = (text, width) => text + " ".repeat(Math.max(0, width - text.length));
751
+ /**
752
+ * The route map as aligned columns, one route per line.
753
+ */
754
+ const formatRoutes = (entries) => {
755
+ if (entries.length === 0) return "This config declares no routes.";
756
+ const methodWidth = Math.max(...entries.map((entry) => entry.method.length));
757
+ const pathWidth = Math.max(...entries.map((entry) => entry.path.length));
758
+ const keyWidth = Math.max(...entries.map((entry) => entry.key.length));
759
+ return entries.map((entry) => {
760
+ const notes = [
761
+ `auth: ${entry.auth}`,
762
+ entry.tool && `tool: ${entry.tool}`,
763
+ entry.deprecated !== void 0 && `deprecated${entry.deprecated ? `, ${entry.deprecated}` : ""}`,
764
+ entry.sunset && `sunset ${entry.sunset}`
765
+ ].filter(Boolean);
766
+ return `${pad(entry.method, methodWidth)} ${pad(entry.path, pathWidth)} ${pad(entry.key, keyWidth)} ${notes.join(" ")}`.trimEnd();
767
+ }).join("\n");
768
+ };
769
+ //#endregion
770
+ Object.defineProperty(exports, "ConfigSyntaxError", {
771
+ enumerable: true,
772
+ get: function() {
773
+ return ConfigSyntaxError;
774
+ }
775
+ });
776
+ Object.defineProperty(exports, "__toESM", {
777
+ enumerable: true,
778
+ get: function() {
779
+ return __toESM;
780
+ }
781
+ });
782
+ Object.defineProperty(exports, "checkClients", {
783
+ enumerable: true,
784
+ get: function() {
785
+ return checkClients;
786
+ }
787
+ });
788
+ Object.defineProperty(exports, "diffAgainst", {
789
+ enumerable: true,
790
+ get: function() {
791
+ return diffAgainst;
792
+ }
793
+ });
794
+ Object.defineProperty(exports, "diffApis", {
795
+ enumerable: true,
796
+ get: function() {
797
+ return diffApis;
798
+ }
799
+ });
800
+ Object.defineProperty(exports, "diffSchemas", {
801
+ enumerable: true,
802
+ get: function() {
803
+ return diffSchemas;
804
+ }
805
+ });
806
+ Object.defineProperty(exports, "formatChange", {
807
+ enumerable: true,
808
+ get: function() {
809
+ return formatChange;
810
+ }
811
+ });
812
+ Object.defineProperty(exports, "formatRoutes", {
813
+ enumerable: true,
814
+ get: function() {
815
+ return formatRoutes;
816
+ }
817
+ });
818
+ Object.defineProperty(exports, "formatStale", {
819
+ enumerable: true,
820
+ get: function() {
821
+ return formatStale;
822
+ }
823
+ });
824
+ Object.defineProperty(exports, "generateConfigTypes", {
825
+ enumerable: true,
826
+ get: function() {
827
+ return generateConfigTypes;
828
+ }
829
+ });
830
+ Object.defineProperty(exports, "hasBreakingChange", {
831
+ enumerable: true,
832
+ get: function() {
833
+ return hasBreakingChange;
834
+ }
835
+ });
836
+ Object.defineProperty(exports, "loadConfig", {
837
+ enumerable: true,
838
+ get: function() {
839
+ return loadConfig;
840
+ }
841
+ });
842
+ Object.defineProperty(exports, "routeMap", {
843
+ enumerable: true,
844
+ get: function() {
845
+ return routeMap;
846
+ }
847
+ });
848
+ Object.defineProperty(exports, "writeClients", {
849
+ enumerable: true,
850
+ get: function() {
851
+ return writeClients;
852
+ }
853
+ });