kizunajs 2.0.0-beta.2 → 2.0.0-beta.21

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.
Files changed (81) hide show
  1. package/README.md +3 -2
  2. package/dist/{adapter-CZW-unqX.mjs → adapter-BSqNrxhq.mjs} +522 -104
  3. package/dist/adapter-C3WYdSfx.d.cts +2754 -0
  4. package/dist/{adapter-DDR_yo9L.cjs → adapter-ClaFZoab.cjs} +638 -196
  5. package/dist/adapter-D4bTPElA.d.mts +2754 -0
  6. package/dist/adapter.cjs +37 -29
  7. package/dist/adapter.d.cts +3 -5
  8. package/dist/adapter.d.mts +3 -5
  9. package/dist/adapter.mjs +5 -5
  10. package/dist/{error-response-C8Ragjcd.cjs → error-response-C9ymqSU4.cjs} +25 -5
  11. package/dist/{error-response-C839d8By.mjs → error-response-CNQaKVYd.mjs} +20 -6
  12. package/dist/{security-scheme-BrszwGD5.d.cts → error-response-NoOGdh8H.d.mts} +151 -24
  13. package/dist/{security-scheme-D3nb4XKj.d.mts → error-response-YbkRMKno.d.cts} +151 -24
  14. package/dist/generator.cjs +190 -95
  15. package/dist/generator.d.cts +189 -28
  16. package/dist/generator.d.mts +189 -28
  17. package/dist/generator.mjs +151 -60
  18. package/dist/index.cjs +159 -84
  19. package/dist/index.d.cts +193 -253
  20. package/dist/index.d.mts +193 -253
  21. package/dist/index.mjs +112 -38
  22. package/dist/jobs-entry.cjs +12 -11
  23. package/dist/jobs-entry.d.cts +1 -1
  24. package/dist/jobs-entry.d.mts +1 -1
  25. package/dist/jobs-entry.mjs +3 -2
  26. package/dist/plugin-Dw-yCjTY.cjs +233 -0
  27. package/dist/{cache-CLN5y0Xp.mjs → plugin-server-BztlE1fz.mjs} +188 -49
  28. package/dist/{cache-BgohRj0i.cjs → plugin-server-kUsK7thV.cjs} +238 -93
  29. package/dist/plugin-xxCxibmu.mjs +138 -0
  30. package/dist/plugin.cjs +8 -72
  31. package/dist/plugin.d.cts +3 -3
  32. package/dist/plugin.d.mts +3 -3
  33. package/dist/plugin.mjs +2 -68
  34. package/dist/{protected-resource-metadata-CA0v5cjg.d.mts → protected-resource-metadata-B9hMFQ9N.d.cts} +1 -1
  35. package/dist/{protected-resource-metadata-Cprrv0mt.d.cts → protected-resource-metadata-CfBVsqIk.d.mts} +1 -1
  36. package/dist/{schemas-C56no6bv.cjs → schemas-DNPVDvkd.cjs} +28 -1
  37. package/dist/{schemas-CJQcc97N.mjs → schemas-HW2FDsvz.mjs} +23 -2
  38. package/dist/schemas.cjs +3 -2
  39. package/dist/schemas.d.cts +24 -3
  40. package/dist/schemas.d.mts +24 -3
  41. package/dist/schemas.mjs +3 -3
  42. package/package.json +1 -1
  43. package/src/adapter.ts +245 -29
  44. package/src/api-definition.ts +12 -16
  45. package/src/api.ts +7 -3
  46. package/src/brand.ts +29 -0
  47. package/src/config.ts +51 -10
  48. package/src/configured.ts +13 -6
  49. package/src/define-config.ts +118 -39
  50. package/src/generator.ts +363 -46
  51. package/src/group-routes.ts +106 -0
  52. package/src/groups.ts +140 -0
  53. package/src/handler-pipeline.ts +78 -19
  54. package/src/index.ts +15 -6
  55. package/src/job-runner.ts +5 -0
  56. package/src/job-transport.ts +3 -3
  57. package/src/job.ts +8 -6
  58. package/src/jobs-dev-runner.ts +6 -0
  59. package/src/jobs.ts +61 -8
  60. package/src/kizuna.ts +56 -33
  61. package/src/plugin-server.ts +129 -19
  62. package/src/plugin.ts +269 -127
  63. package/src/routes.ts +80 -32
  64. package/src/schemas.ts +1 -0
  65. package/src/tool-answer.ts +21 -0
  66. package/src/tool-definitions.ts +166 -0
  67. package/src/tool-events.ts +90 -18
  68. package/src/tool-records.ts +11 -3
  69. package/src/tool-runner.ts +298 -0
  70. package/src/types.ts +90 -24
  71. package/src/zod-internals.ts +22 -5
  72. package/src/zod-meta.ts +7 -2
  73. package/dist/adapter-BGfMqEkM.d.cts +0 -563
  74. package/dist/adapter-Ci3cfcoT.d.mts +0 -563
  75. package/dist/api-definition-BHnh15zD.d.mts +0 -803
  76. package/dist/api-definition-DQj-ewHy.d.cts +0 -803
  77. package/dist/error-response-BBGSdgYw.d.mts +0 -67
  78. package/dist/error-response-Do38sr-9.d.cts +0 -67
  79. package/dist/plugin-Cz0kn6Lk.d.mts +0 -830
  80. package/dist/plugin-DhKvx_T0.d.cts +0 -830
  81. package/src/tags.ts +0 -67
@@ -287,6 +287,18 @@ type RouteAuth<Names extends string = string> = false | Names | readonly Names[]
287
287
  roles?: string | readonly string[];
288
288
  requires?: RequiredPermissions;
289
289
  };
290
+ /**
291
+ * Rejects a route that is both `hidden` and a `tool`: a hidden route is left out
292
+ * of everything that publishes routes, MCP included.
293
+ */
294
+ type RouteHiddenToolCheck<Route> = Route extends {
295
+ hidden: true;
296
+ tool: true | RouteToolOptions;
297
+ } ? {
298
+ tool: {
299
+ 'kizuna: a hidden route cannot publish as a tool. Remove `tool`, or `hidden`': true;
300
+ };
301
+ } : unknown;
290
302
  /**
291
303
  * Response headers keyed by name.
292
304
  */
@@ -310,7 +322,7 @@ declare const HANDLER: unique symbol;
310
322
  type RouteHandlerFunction = (args: never) => unknown;
311
323
  /**
312
324
  * What a route publishes as, over MCP. `description`, `title` and the four
313
- * hints are MCP's own, field for field; `confirm` is kizuna's.
325
+ * hints are MCP's own, field for field; `needsApproval` is kizuna's.
314
326
  *
315
327
  * Each hint defaults from the route's method, so a `GET` is already marked read
316
328
  * only and a `DELETE` already destructive. Set one to say what the method
@@ -348,16 +360,18 @@ interface RouteToolOptions {
348
360
  */
349
361
  openWorldHint?: boolean;
350
362
  /**
351
- * What the person reads before this route runs as a tool. They agree or
352
- * decline, and declining leaves the handler uncalled.
363
+ * The person approves each call before it runs as a tool.
353
364
  *
354
- * Kizuna's own, sent over MCP's elicitation. The four hints above say what
355
- * the route does, and leave a client to decide whether that warrants
356
- * asking; this asks.
365
+ * @example
366
+ * ```ts
367
+ * tool: {
368
+ * needsApproval: true,
369
+ * },
370
+ * ```
357
371
  */
358
- confirm?: string;
372
+ needsApproval?: boolean;
359
373
  }
360
- interface RouteDefinition<TagKeys extends string = string, SchemeNames extends string = string> {
374
+ interface RouteDefinition<GroupPaths extends string = string, SchemeNames extends string = string> {
361
375
  method: Method;
362
376
  /**
363
377
  * What this route requires of its caller. See {@link RouteAuth}.
@@ -386,6 +400,59 @@ interface RouteDefinition<TagKeys extends string = string, SchemeNames extends s
386
400
  * },
387
401
  */
388
402
  tool?: boolean | RouteToolOptions;
403
+ /**
404
+ * Keep this route out of the generated clients, the OpenAPI document and
405
+ * MCP. It is still served.
406
+ *
407
+ * @example
408
+ * ```ts
409
+ * check: k
410
+ * .route({
411
+ * method: 'GET',
412
+ * path: '/health',
413
+ * hidden: true,
414
+ * responses: {
415
+ * 200: HealthSchema,
416
+ * },
417
+ * })
418
+ * .handler(() => ({
419
+ * status: 200,
420
+ * body: {
421
+ * status: 'ok',
422
+ * },
423
+ * })),
424
+ * ```
425
+ */
426
+ hidden?: boolean;
427
+ /**
428
+ * Receive the body exactly as it was sent, as `rawBody`, beside the
429
+ * validated `body`. Check a sender's signature against `rawBody`, since
430
+ * re-serialising the JSON can change a byte and break it.
431
+ *
432
+ * @example
433
+ * ```ts
434
+ * resendEvents: k
435
+ * .route({
436
+ * method: 'POST',
437
+ * path: '/webhooks/resend',
438
+ * auth: false,
439
+ * hidden: true,
440
+ * rawBody: true,
441
+ * body: ResendEventSchema,
442
+ * responses: {
443
+ * 204: z.void(),
444
+ * },
445
+ * })
446
+ * .handler(({ rawBody, headers }) => {
447
+ * verifySignature(rawBody, headers);
448
+ *
449
+ * return {
450
+ * status: 204,
451
+ * };
452
+ * }),
453
+ * ```
454
+ */
455
+ rawBody?: true;
389
456
  /**
390
457
  * Deprecates the route. Pass a message to tell callers what to use instead,
391
458
  * or the object form to announce the deprecation in response headers.
@@ -439,11 +506,9 @@ interface RouteDefinition<TagKeys extends string = string, SchemeNames extends s
439
506
  link?: string;
440
507
  };
441
508
  /**
442
- * Tag keys grouping this route in the OpenAPI spec. Keys come from the tag set
443
- * declared with `k.tags`; `k.routes` stamps the group's tag onto every
444
- * route, and the generator resolves each key to its `title` for the spec.
509
+ * More groups to list this route under, as dotted paths.
445
510
  */
446
- tags?: readonly TagKeys[];
511
+ groups?: readonly GroupPaths[];
447
512
  /**
448
513
  * The security schemes this route requires, referencing identities named
449
514
  * under `identities` on `defineConfig`. Each entry is a scheme name or a
@@ -507,11 +572,9 @@ interface RouteDefinition<TagKeys extends string = string, SchemeNames extends s
507
572
  [HANDLER]?: RouteHandlerFunction;
508
573
  }
509
574
  /**
510
- * Key under which a routes group carries its group tag key, the source
511
- * `flattenRoutes` and the generator use to apply the group's tag to every route
512
- * in it. Stamped by `k.routes`.
575
+ * Where a tree from `k.routes` carries its group's dotted path.
513
576
  */
514
- declare const ROUTES_TAG: unique symbol;
577
+ declare const ROUTES_GROUP: unique symbol;
515
578
  /**
516
579
  * Type-only key under which `defineConfig` brands each route with its resolved
517
580
  * handler context. Never written at runtime.
@@ -541,16 +604,16 @@ interface AutoResponsesBrand<Statuses extends number, Body = ProblemDetails, Wri
541
604
  * The statuses a route's `auth` puts on it once it names an identity.
542
605
  */
543
606
  type GuardStatus = Extract<KnownStatus, 401 | 403>;
544
- interface Routes<TagKeys extends string = string, SchemeNames extends string = string> {
545
- [ROUTES_TAG]?: string;
546
- [key: string]: RouteDefinition<TagKeys, SchemeNames> | Routes<TagKeys, SchemeNames>;
607
+ interface Routes<GroupPaths extends string = string, SchemeNames extends string = string> {
608
+ [ROUTES_GROUP]?: string;
609
+ [key: string]: RouteDefinition<GroupPaths, SchemeNames> | Routes<GroupPaths, SchemeNames>;
547
610
  }
548
611
  /**
549
612
  * A route as authored in `k.route` and `k.routes`: the route shape minus
550
613
  * `security`, `roles` and `requires`, which `defineConfig` resolves from its
551
614
  * `auth`. Writing any of them on a route is a type error.
552
615
  */
553
- type AuthoredRouteDefinition<TagKeys extends string = string, Names extends string = string> = Omit<RouteDefinition<TagKeys>, 'security' | 'roles' | 'requires' | 'auth'> & {
616
+ type AuthoredRouteDefinition<GroupPaths extends string = string, Names extends string = string> = Omit<RouteDefinition<GroupPaths>, 'security' | 'roles' | 'requires' | 'auth'> & {
554
617
  security?: never;
555
618
  roles?: never;
556
619
  requires?: never;
@@ -562,9 +625,9 @@ type AuthoredRouteDefinition<TagKeys extends string = string, Names extends stri
562
625
  /**
563
626
  * A tree of {@link AuthoredRouteDefinition}s, the shape `k.routes` accepts.
564
627
  */
565
- interface AuthoredRoutes<TagKeys extends string = string, Names extends string = string> {
566
- [ROUTES_TAG]?: string;
567
- [key: string]: AuthoredRouteDefinition<TagKeys, Names> | AuthoredRoutes<TagKeys, Names>;
628
+ interface AuthoredRoutes<GroupPaths extends string = string, Names extends string = string> {
629
+ [ROUTES_GROUP]?: string;
630
+ [key: string]: AuthoredRouteDefinition<GroupPaths, Names> | AuthoredRoutes<GroupPaths, Names>;
568
631
  }
569
632
  //#endregion
570
633
  //#region src/permissions.d.ts
@@ -794,4 +857,68 @@ declare const resolveSecurityRequirements: (route: RouteDefinition) => Array<{
794
857
  scopes: string[];
795
858
  }>;
796
859
  //#endregion
797
- export { GuardBody as $, DECLARATION as A, ResponseContentType as B, AUTO_GUARD_BRAND as C, AuthoredRoutes as D, AuthoredRouteDefinition as E, HandlerContextBrand as F, RouteHandlerFunction as G, ResponseHeaders as H, METHODS as I, Routes as J, RoutePath as K, Method as L, GuardStatus as M, HANDLER as N, AutoResponsesBrand as O, HANDLER_CONTEXT_BRAND as P, StreamResponseDefinition as Q, ROUTES_TAG as R, isRoles as S, AUTO_RESPONSES_BRAND as T, RouteAuth as U, ResponseDefinition as V, RouteDefinition as W, SecurityRequirement as X, SchemeNameOf as Y, StreamDefinition as Z, RoleDefinition as _, SecurityScheme as a, problemFromBody as at, createRoles as b, declaredScopes as c, CatalogOf as d, GuardOutput as et, GrantNamesOf as f, Permissions as g, PermissionSet as h, OpenApiSecuritySchemeObject as i, problemDetails as it, DeclarationKind as j, CachePolicy as k, isSecurityScheme as l, PermissionName as m, OAuthFlow as n, ProblemDetails as nt, authenticationChallenge as o, STATUS_TITLES as ot, PermissionCatalog as p, RouteToolOptions as q, OAuthFlows as r, StripProblemEnvelope as rt, authorizationServerIssuer as s, getStatusText as st, ContextOf as t, GuardSchemaCheck as tt, resolveSecurityRequirements as u, RoleNamesOf as v, AUTO_GUARD_WRITTEN_BRAND as w, isPermissions as x, Roles as y, RequiredPermissions as z };
860
+ //#region src/error-response.d.ts
861
+ /**
862
+ * RFC 9457 Problem Details, the single error schema used across kizuna.
863
+ *
864
+ * Matches the shape returned by `deny()` in guards, validation errors,
865
+ * and all built-in error responses (404, 405, 415, etc.).
866
+ *
867
+ * ```ts
868
+ * import { ProblemDetailsSchema } from 'kizunajs/schemas';
869
+ *
870
+ * const routes = k.routes({
871
+ * getUser: {
872
+ * method: 'GET',
873
+ * path: '/users/:id',
874
+ * responses: {
875
+ * 200: UserSchema,
876
+ * 404: ProblemDetailsSchema,
877
+ * },
878
+ * },
879
+ * });
880
+ * ```
881
+ *
882
+ * Add domain fields as RFC 9457 **extension members** with native `.extend`, inline:
883
+ *
884
+ * ```ts
885
+ * responses: {
886
+ * 409: ProblemDetailsSchema.extend({
887
+ * conflictingId: z.string(),
888
+ * }),
889
+ * }
890
+ * ```
891
+ *
892
+ * or as a named component (appears in the OpenAPI spec) via `Kizuna.model`:
893
+ *
894
+ * ```ts
895
+ * export const ConflictError = Kizuna.model({
896
+ * title: 'ConflictError',
897
+ * schema: ProblemDetailsSchema.extend({
898
+ * conflictingId: z.string(),
899
+ * }),
900
+ * });
901
+ * ```
902
+ *
903
+ * The handler supplies `detail` plus any extensions; `type`/`title`/`status` are
904
+ * auto-filled. Extension members are also how an API migrating onto kizuna keeps its
905
+ * existing error fields (e.g. `errorCode`, `requestId`), old clients still read them.
906
+ */
907
+ declare const ProblemDetailsSchema: z.ZodObject<{
908
+ type: z.ZodString;
909
+ title: z.ZodString;
910
+ status: z.ZodNumber;
911
+ detail: z.ZodString;
912
+ }, z.core.$strip>;
913
+ /**
914
+ * Type guard for an RFC 9457 Problem Details body, the shared shape behind every kizuna
915
+ * error response (validation failures, guards, handler errors, built-in 404/405/415, …).
916
+ */
917
+ declare function isProblemDetails(body: unknown): body is {
918
+ type: string;
919
+ title: string;
920
+ status: number;
921
+ detail: string;
922
+ };
923
+ //#endregion
924
+ export { SecurityRequirement as $, AutoResponsesBrand as A, ROUTES_GROUP as B, isPermissions as C, AUTO_RESPONSES_BRAND as D, AUTO_GUARD_WRITTEN_BRAND as E, HANDLER as F, RouteAuth as G, ResponseContentType as H, HANDLER_CONTEXT_BRAND as I, RouteHiddenToolCheck as J, RouteDefinition as K, HandlerContextBrand as L, DECLARATION as M, DeclarationKind as N, AuthoredRouteDefinition as O, GuardStatus as P, SchemeNameOf as Q, METHODS as R, createRoles as S, AUTO_GUARD_BRAND as T, ResponseDefinition as U, RequiredPermissions as V, ResponseHeaders as W, RouteToolOptions as X, RoutePath as Y, Routes as Z, PermissionSet as _, OAuthFlows as a, ProblemDetails as at, RoleNamesOf as b, authenticationChallenge as c, problemFromBody as ct, isSecurityScheme as d, StreamDefinition as et, resolveSecurityRequirements as f, PermissionName as g, PermissionCatalog as h, OAuthFlow as i, GuardSchemaCheck as it, CachePolicy as j, AuthoredRoutes as k, authorizationServerIssuer as l, STATUS_TITLES as lt, GrantNamesOf as m, isProblemDetails as n, GuardBody as nt, OpenApiSecuritySchemeObject as o, StripProblemEnvelope as ot, CatalogOf as p, RouteHandlerFunction as q, ContextOf as r, GuardOutput as rt, SecurityScheme as s, problemDetails as st, ProblemDetailsSchema as t, StreamResponseDefinition as tt, declaredScopes as u, getStatusText as ut, Permissions as v, isRoles as w, Roles as x, RoleDefinition as y, Method as z };
@@ -1,108 +1,201 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_cache = require("./cache-BgohRj0i.cjs");
3
- const require_error_response = require("./error-response-C8Ragjcd.cjs");
4
- //#region src/tool-name.ts
2
+ const require_error_response = require("./error-response-C9ymqSU4.cjs");
3
+ const require_plugin_server = require("./plugin-server-kUsK7thV.cjs");
4
+ //#region src/generator.ts
5
5
  /**
6
- * Set by the MCP specification.
7
- *
8
- * @see https://modelcontextprotocol.io/specification/latest/server/tools
6
+ * Every route the api serves, the app's and the plugins' under their slugs,
7
+ * each with the plugin it came from.
9
8
  */
10
- const MAX_TOOL_NAME_LENGTH = 128;
9
+ const servedRoutes = (contract) => [...require_plugin_server.flattenRoutes(contract.routes).map((entry) => ({
10
+ ...entry,
11
+ plugin: void 0
12
+ })), ...Object.entries(require_plugin_server.pluginRoutesOf(contract)).flatMap(([slug, routes]) => require_plugin_server.flattenRoutes(routes, slug).map((entry) => ({
13
+ ...entry,
14
+ plugin: { slug }
15
+ })))];
16
+ const withoutHidden = (routes) => {
17
+ const listed = {};
18
+ for (const symbol of Object.getOwnPropertySymbols(routes)) listed[symbol] = routes[symbol];
19
+ for (const [key, value] of Object.entries(routes)) {
20
+ if (require_plugin_server.isRouteDefinition(value)) {
21
+ if (value.hidden !== true) listed[key] = value;
22
+ continue;
23
+ }
24
+ if (value && typeof value === "object") {
25
+ const group = withoutHidden(value);
26
+ if (Object.keys(group).length > 0) listed[key] = group;
27
+ }
28
+ }
29
+ return listed;
30
+ };
11
31
  /**
12
- * The specification allows a dot too, and kizuna's own route and tool keys are
13
- * dotted. Claude and GitHub Copilot validate against this narrower set and
14
- * reject the whole tool list over one name outside it, so the dot does not
15
- * survive here.
32
+ * The route tree the generated clients hold: the app's routes, less every
33
+ * `hidden` one.
16
34
  */
17
- const TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
18
- const toSnakeCase = (segment) => segment.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase();
35
+ const listedRoutes = (contract) => withoutHidden(contract.routes);
36
+ const isSchema = (value) => typeof value === "object" && value !== null && "_zod" in value && typeof value._zod?.def?.type === "string";
19
37
  /**
20
- * `users.listUsers` becomes `users_list_users`, the shape MCP servers publish
21
- * and models are trained on.
38
+ * Every `Kizuna.model` schema reachable from a value, found by walking its
39
+ * schemas and whatever plain objects and lists hold them.
22
40
  */
23
- const toToolName = (key) => key.split(".").map(toSnakeCase).join("_");
24
- const sentenceLabel = (origin) => origin === "route" ? "Route" : "Tool";
41
+ const reachModels = (value, models, found, seen) => {
42
+ if (typeof value !== "object" || value === null || seen.has(value)) return;
43
+ seen.add(value);
44
+ if (isSchema(value)) {
45
+ if (models.has(value)) found.add(value);
46
+ const def = value._zod.def;
47
+ for (const [key, child] of Object.entries(def)) {
48
+ if (key === "checks") continue;
49
+ if (key === "getter" && typeof child === "function") {
50
+ reachModels(child(), models, found, seen);
51
+ continue;
52
+ }
53
+ reachModels(child, models, found, seen);
54
+ }
55
+ return;
56
+ }
57
+ for (const child of Array.isArray(value) ? value : Object.values(value)) reachModels(child, models, found, seen);
58
+ };
25
59
  /**
26
- * Every key mapped to its published tool name, throwing on a name MCP clients
27
- * reject and on two keys that converge on one name.
60
+ * The named models the given routes use, sorted by name, each with the plugin
61
+ * that brought it when none of the app's own routes use it.
28
62
  */
29
- const deriveToolNames = (entries) => {
30
- const names = /* @__PURE__ */ new Map();
31
- const claimedBy = /* @__PURE__ */ new Map();
32
- for (const entry of entries) {
33
- const { key, origin } = entry;
34
- const name = toToolName(key);
35
- if (!TOOL_NAME_PATTERN.test(name)) throw new Error(`${sentenceLabel(origin)} "${key}" becomes the tool name "${name}", which contains characters outside the letters, digits, underscore, and dash that MCP clients accept. Rename the ${origin}.`);
36
- if (name.length > MAX_TOOL_NAME_LENGTH) throw new Error(`${sentenceLabel(origin)} "${key}" becomes the tool name "${name}", which is ${name.length} characters, exceeding the MCP maximum of ${MAX_TOOL_NAME_LENGTH}. Use a shorter key.`);
37
- const claimant = claimedBy.get(name);
38
- if (claimant !== void 0) throw new Error(`${sentenceLabel(claimant.origin)} "${claimant.key}" and ${origin} "${key}" both become the tool name "${name}". Rename one of them.`);
39
- claimedBy.set(name, entry);
40
- names.set(key, name);
63
+ const modelsOf = (entries) => {
64
+ const models = /* @__PURE__ */ new Map();
65
+ for (const [id, schema] of require_error_response.globalRegistrySchemas()) models.set(schema, id);
66
+ const owners = /* @__PURE__ */ new Map();
67
+ const appFirst = [...entries].sort((left, right) => Number(left.plugin !== void 0) - Number(right.plugin !== void 0));
68
+ for (const { route, plugin } of appFirst) {
69
+ const found = /* @__PURE__ */ new Set();
70
+ reachModels(route, models, found, /* @__PURE__ */ new Set());
71
+ for (const schema of found) if (!owners.has(schema)) owners.set(schema, plugin);
41
72
  }
42
- return names;
73
+ return [...owners].map(([schema, plugin]) => ({
74
+ name: models.get(schema),
75
+ schema,
76
+ description: require_error_response.readMetaDescription(schema),
77
+ plugin
78
+ })).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
43
79
  };
44
- //#endregion
45
- //#region src/generator.ts
80
+ const deprecationMessageOf = (route) => typeof route.deprecated === "string" ? route.deprecated : typeof route.deprecated === "object" ? route.deprecated.message : void 0;
46
81
  /**
47
- * Factory for building type-safe routes generators.
48
- *
49
- * Centralises routes walking and deprecation resolution so generator authors
50
- * only need to implement `processRoute` and `finalize`. Field-level deprecation
51
- * lives on the schemas themselves, read with `readDeprecation`.
82
+ * Run a walk over an api: its models, then every route it serves, the app's
83
+ * and each plugin's under its slug. Returns what `finalize` returns.
52
84
  *
53
- * ```ts
54
- * const generateRouteList = createGenerator(() => {
55
- * const routeList: string[] = [];
56
- * return {
57
- * processRoute({ route, deprecated }) {
58
- * routeList.push(`${route.method} ${route.path}${deprecated ? ' (deprecated)' : ''}`);
59
- * },
60
- * finalize() {
61
- * return routeList;
62
- * },
63
- * };
85
+ * @example
86
+ * const routeList = walkApi(api, {
87
+ * processRoute: ({ route }) => lines.push(`${route.method} ${route.path}`),
88
+ * finalize: () => lines.join('\n'),
64
89
  * });
65
- *
66
- * const list = generateRouteList(kizuna.api, {});
67
- * ```
68
90
  */
69
- const createGenerator = (factory) => (contract, options) => {
70
- const { processRoute, finalize } = factory(options, contract);
71
- for (const { routeKey, route, routeTags } of require_cache.flattenRoutes(contract.routes)) processRoute({
91
+ const walkApi = (api, walk, options = {}) => {
92
+ const entries = servedRoutes(api).filter(({ route }) => options.skipHidden !== true || route.hidden !== true);
93
+ if (walk.processModel !== void 0) for (const model of modelsOf(entries)) walk.processModel(model);
94
+ for (const { routeKey, route, routeGroups, plugin } of entries) walk.processRoute?.({
72
95
  routeKey,
73
96
  route,
74
- routeTags,
97
+ routeGroups,
98
+ hidden: route.hidden === true,
99
+ plugin,
75
100
  deprecated: route.deprecated !== void 0 && route.deprecated !== false,
76
- deprecationMessage: typeof route.deprecated === "string" ? route.deprecated : typeof route.deprecated === "object" ? route.deprecated.message : void 0
101
+ deprecationMessage: deprecationMessageOf(route)
77
102
  });
78
- return finalize();
103
+ return walk.finalize();
104
+ };
105
+ const parseOptions = (schema, input, name) => {
106
+ if (schema === void 0) return input;
107
+ const parsed = schema.safeParse(input);
108
+ if (!parsed.success) throw new Error(`[kizuna] ${name} has invalid options: ${parsed.error.issues.map(require_plugin_server.describeIssue).join("; ")}`);
109
+ return parsed.data;
110
+ };
111
+ /**
112
+ * Declare a client for a language: the options an app passes it, and the walk
113
+ * that returns its file. Returns the function an app names under `clients`.
114
+ *
115
+ * @example
116
+ * export const dartClient = defineClient({
117
+ * target: 'dart',
118
+ * options: z.object({
119
+ * library: z.string().default('api'),
120
+ * }),
121
+ * generate: ({ options }) => {
122
+ * const writer = new DartWriter(options.library);
123
+ *
124
+ * return {
125
+ * processModel: (model) => writer.model(model),
126
+ * processRoute: (context) => writer.method(context),
127
+ * finalize: () => writer.render(),
128
+ * };
129
+ * },
130
+ * });
131
+ */
132
+ const defineClient = (definition) => (input) => {
133
+ const { output, ...rest } = input;
134
+ const options = parseOptions(definition.options, rest, `Client '${definition.target}'`);
135
+ return {
136
+ target: definition.target,
137
+ output,
138
+ render: (api) => walkApi(api, definition.generate({
139
+ options,
140
+ api
141
+ }), { skipHidden: true })
142
+ };
143
+ };
144
+ /**
145
+ * Declare a generator for a file that isn't a client, like a document or a
146
+ * manifest. A plugin installs it by returning it from `setup`.
147
+ *
148
+ * @example
149
+ * export const gatewayManifest = defineGenerator({
150
+ * generate: () => {
151
+ * const entries: string[] = [];
152
+ *
153
+ * return {
154
+ * processRoute: ({ route }) => entries.push(`${route.method} ${route.path}`),
155
+ * finalize: () => entries.join('\n'),
156
+ * };
157
+ * },
158
+ * });
159
+ */
160
+ const defineGenerator = (definition) => (input) => {
161
+ const { output, ...rest } = input;
162
+ const options = parseOptions(definition.options, rest, `The generator for '${output}'`);
163
+ return {
164
+ output,
165
+ render: (api) => walkApi(api, definition.generate({
166
+ options,
167
+ api
168
+ }))
169
+ };
79
170
  };
80
171
  //#endregion
81
- exports.EVENT_STREAM_MEDIA_TYPE = require_cache.EVENT_STREAM_MEDIA_TYPE;
172
+ exports.EVENT_STREAM_MEDIA_TYPE = require_plugin_server.EVENT_STREAM_MEDIA_TYPE;
82
173
  exports.FILE_PROBE = require_error_response.FILE_PROBE;
83
- exports.cacheHeaders = require_cache.cacheHeaders;
84
- exports.createGenerator = createGenerator;
85
- exports.deprecationHeaders = require_cache.deprecationHeaders;
86
- exports.deriveToolNames = deriveToolNames;
87
- exports.flattenJobs = require_cache.flattenJobs;
174
+ exports.cacheHeaders = require_plugin_server.cacheHeaders;
175
+ exports.defineClient = defineClient;
176
+ exports.defineGenerator = defineGenerator;
177
+ exports.deprecationHeaders = require_plugin_server.deprecationHeaders;
178
+ exports.deriveToolNames = require_plugin_server.deriveToolNames;
179
+ exports.flattenJobs = require_plugin_server.flattenJobs;
88
180
  exports.globalRegistrySchemas = require_error_response.globalRegistrySchemas;
89
181
  exports.isBinarySchema = require_error_response.isBinarySchema;
90
- exports.isCompiledJob = require_cache.isCompiledJob;
182
+ exports.isCompiledJob = require_plugin_server.isCompiledJob;
91
183
  exports.isDiscriminatedUnionSchema = require_error_response.isDiscriminatedUnionSchema;
92
184
  exports.isFileSchema = require_error_response.isFileSchema;
93
- exports.isHintPrefix = require_cache.isHintPrefix;
185
+ exports.isHintPrefix = require_plugin_server.isHintPrefix;
94
186
  exports.isIntegerSchema = require_error_response.isIntegerSchema;
95
- exports.isJsonMediaType = require_cache.isJsonMediaType;
96
- exports.isNamedStream = require_cache.isNamedStream;
187
+ exports.isJsonMediaType = require_plugin_server.isJsonMediaType;
188
+ exports.isNamedStream = require_plugin_server.isNamedStream;
97
189
  exports.isObjectSchema = require_error_response.isObjectSchema;
98
- exports.isStreamResponse = require_cache.isStreamResponse;
99
- exports.isSuccessStatus = require_cache.isSuccessStatus;
190
+ exports.isStreamResponse = require_plugin_server.isStreamResponse;
191
+ exports.isSuccessStatus = require_plugin_server.isSuccessStatus;
100
192
  exports.isVoidSchema = require_error_response.isVoidSchema;
101
- exports.isZodSchema = require_cache.isZodSchema;
102
- exports.jobAt = require_cache.jobAt;
103
- exports.localTypeName = require_cache.localTypeName;
104
- exports.mergeHeaderFields = require_cache.mergeHeaderFields;
105
- exports.parsePath = require_cache.parsePath;
193
+ exports.isZodSchema = require_plugin_server.isZodSchema;
194
+ exports.jobAt = require_plugin_server.jobAt;
195
+ exports.listedRoutes = listedRoutes;
196
+ exports.localTypeName = require_plugin_server.localTypeName;
197
+ exports.mergeHeaderFields = require_plugin_server.mergeHeaderFields;
198
+ exports.parsePath = require_plugin_server.parsePath;
106
199
  exports.readDef = require_error_response.readDef;
107
200
  exports.readDefType = require_error_response.readDefType;
108
201
  exports.readDeprecation = require_error_response.readDeprecation;
@@ -110,27 +203,29 @@ exports.readDiscriminatedUnion = require_error_response.readDiscriminatedUnion;
110
203
  exports.readDiscriminatorLiteral = require_error_response.readDiscriminatorLiteral;
111
204
  exports.readDiscriminatorStringLiteral = require_error_response.readDiscriminatorStringLiteral;
112
205
  exports.readMeta = require_error_response.readMeta;
206
+ exports.readMetaBrand = require_error_response.readMetaBrand;
113
207
  exports.readMetaDescription = require_error_response.readMetaDescription;
114
208
  exports.readMetaExamples = require_error_response.readMetaExamples;
115
209
  exports.readMetaId = require_error_response.readMetaId;
116
210
  exports.readObjectShape = require_error_response.readObjectShape;
117
- exports.resolveResponseBody = require_cache.resolveResponseBody;
118
- exports.resolveResponseCache = require_cache.resolveResponseCache;
119
- exports.resolveResponseContentType = require_cache.resolveResponseContentType;
120
- exports.resolveResponseEtag = require_cache.resolveResponseEtag;
121
- exports.resolveResponseHeaders = require_cache.resolveResponseHeaders;
122
- exports.resolveResponseStream = require_cache.resolveResponseStream;
123
- exports.routeStreams = require_cache.routeStreams;
124
- exports.sanitizeFieldName = require_cache.sanitizeFieldName;
125
- exports.sanitizeIdentifier = require_cache.sanitizeIdentifier;
126
- exports.shortTypeName = require_cache.shortTypeName;
127
- exports.soleStreamResponse = require_cache.soleStreamResponse;
128
- exports.statusToCamelCase = require_cache.statusToCamelCase;
129
- exports.streamContentType = require_cache.streamContentType;
130
- exports.streamMode = require_cache.streamMode;
131
- exports.streamSchemas = require_cache.streamSchemas;
132
- exports.streamStatuses = require_cache.streamStatuses;
133
- exports.toCamelCase = require_cache.toCamelCase;
134
- exports.toPascalCase = require_cache.toPascalCase;
135
- exports.toToolName = toToolName;
211
+ exports.resolveResponseBody = require_plugin_server.resolveResponseBody;
212
+ exports.resolveResponseCache = require_plugin_server.resolveResponseCache;
213
+ exports.resolveResponseContentType = require_plugin_server.resolveResponseContentType;
214
+ exports.resolveResponseEtag = require_plugin_server.resolveResponseEtag;
215
+ exports.resolveResponseHeaders = require_plugin_server.resolveResponseHeaders;
216
+ exports.resolveResponseStream = require_plugin_server.resolveResponseStream;
217
+ exports.routeStreams = require_plugin_server.routeStreams;
218
+ exports.sanitizeFieldName = require_plugin_server.sanitizeFieldName;
219
+ exports.sanitizeIdentifier = require_plugin_server.sanitizeIdentifier;
220
+ exports.shortTypeName = require_plugin_server.shortTypeName;
221
+ exports.soleStreamResponse = require_plugin_server.soleStreamResponse;
222
+ exports.statusToCamelCase = require_plugin_server.statusToCamelCase;
223
+ exports.streamContentType = require_plugin_server.streamContentType;
224
+ exports.streamMode = require_plugin_server.streamMode;
225
+ exports.streamSchemas = require_plugin_server.streamSchemas;
226
+ exports.streamStatuses = require_plugin_server.streamStatuses;
227
+ exports.toCamelCase = require_plugin_server.toCamelCase;
228
+ exports.toPascalCase = require_plugin_server.toPascalCase;
229
+ exports.toToolName = require_plugin_server.toToolName;
136
230
  exports.unwrapOptionalWrappers = require_error_response.unwrapOptionalWrappers;
231
+ exports.walkApi = walkApi;