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
@@ -1,80 +1,171 @@
1
- import { A as streamSchemas, B as resolveResponseCache, D as soleStreamResponse, E as routeStreams, F as isSuccessStatus, G as sanitizeFieldName, H as resolveResponseEtag, I as isZodSchema, J as statusToCamelCase, K as sanitizeIdentifier, L as localTypeName, M as isHintPrefix, N as isJsonMediaType, O as streamContentType, P as isStreamResponse, Q as parsePath, R as mergeHeaderFields, S as EVENT_STREAM_MEDIA_TYPE, T as isNamedStream, U as resolveResponseHeaders, V as resolveResponseContentType, W as resolveResponseStream, X as toPascalCase, Y as toCamelCase, c as isCompiledJob, et as flattenRoutes, i as deprecationHeaders, j as streamStatuses, k as streamMode, n as cacheHeaders, q as shortTypeName, s as flattenJobs, u as jobAt, z as resolveResponseBody } from "./cache-CLN5y0Xp.mjs";
2
- import { C as readMetaId, E as unwrapOptionalWrappers, S as readMetaExamples, _ as readDiscriminatedUnion, b as readMeta, c as isBinarySchema, d as isIntegerSchema, f as isObjectSchema, g as readDeprecation, h as readDefType, i as FILE_PROBE, l as isDiscriminatedUnionSchema, m as readDef, p as isVoidSchema, s as globalRegistrySchemas, u as isFileSchema, v as readDiscriminatorLiteral, w as readObjectShape, x as readMetaDescription, y as readDiscriminatorStringLiteral } from "./error-response-C839d8By.mjs";
3
- //#region src/tool-name.ts
1
+ import { C as readMetaExamples, D as unwrapOptionalWrappers, S as readMetaDescription, T as readObjectShape, _ as readDiscriminatedUnion, b as readMeta, c as isBinarySchema, d as isIntegerSchema, f as isObjectSchema, g as readDeprecation, h as readDefType, i as FILE_PROBE, l as isDiscriminatedUnionSchema, m as readDef, p as isVoidSchema, s as globalRegistrySchemas, u as isFileSchema, v as readDiscriminatorLiteral, w as readMetaId, x as readMetaBrand, y as readDiscriminatorStringLiteral } from "./error-response-CNQaKVYd.mjs";
2
+ import { $ as resolveResponseStream, A as toToolName, B as streamStatuses, F as routeStreams, G as isZodSchema, H as isJsonMediaType, I as soleStreamResponse, J as resolveResponseBody, K as localTypeName, L as streamContentType, P as isNamedStream, Q as resolveResponseHeaders, R as streamMode, U as isStreamResponse, V as isHintPrefix, W as isSuccessStatus, X as resolveResponseContentType, Y as resolveResponseCache, Z as resolveResponseEtag, _ as jobAt, a as pluginRoutesOf, at as toPascalCase, c as cacheHeaders, dt as isRouteDefinition, et as sanitizeFieldName, h as isCompiledJob, it as toCamelCase, j as EVENT_STREAM_MEDIA_TYPE, k as deriveToolNames, lt as flattenRoutes, m as flattenJobs, n as describeIssue, nt as shortTypeName, q as mergeHeaderFields, rt as statusToCamelCase, st as parsePath, tt as sanitizeIdentifier, u as deprecationHeaders, z as streamSchemas } from "./plugin-server-BztlE1fz.mjs";
3
+ //#region src/generator.ts
4
4
  /**
5
- * Set by the MCP specification.
6
- *
7
- * @see https://modelcontextprotocol.io/specification/latest/server/tools
5
+ * Every route the api serves, the app's and the plugins' under their slugs,
6
+ * each with the plugin it came from.
8
7
  */
9
- const MAX_TOOL_NAME_LENGTH = 128;
8
+ const servedRoutes = (contract) => [...flattenRoutes(contract.routes).map((entry) => ({
9
+ ...entry,
10
+ plugin: void 0
11
+ })), ...Object.entries(pluginRoutesOf(contract)).flatMap(([slug, routes]) => flattenRoutes(routes, slug).map((entry) => ({
12
+ ...entry,
13
+ plugin: { slug }
14
+ })))];
15
+ const withoutHidden = (routes) => {
16
+ const listed = {};
17
+ for (const symbol of Object.getOwnPropertySymbols(routes)) listed[symbol] = routes[symbol];
18
+ for (const [key, value] of Object.entries(routes)) {
19
+ if (isRouteDefinition(value)) {
20
+ if (value.hidden !== true) listed[key] = value;
21
+ continue;
22
+ }
23
+ if (value && typeof value === "object") {
24
+ const group = withoutHidden(value);
25
+ if (Object.keys(group).length > 0) listed[key] = group;
26
+ }
27
+ }
28
+ return listed;
29
+ };
10
30
  /**
11
- * The specification allows a dot too, and kizuna's own route and tool keys are
12
- * dotted. Claude and GitHub Copilot validate against this narrower set and
13
- * reject the whole tool list over one name outside it, so the dot does not
14
- * survive here.
31
+ * The route tree the generated clients hold: the app's routes, less every
32
+ * `hidden` one.
15
33
  */
16
- const TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
17
- const toSnakeCase = (segment) => segment.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase();
34
+ const listedRoutes = (contract) => withoutHidden(contract.routes);
35
+ const isSchema = (value) => typeof value === "object" && value !== null && "_zod" in value && typeof value._zod?.def?.type === "string";
18
36
  /**
19
- * `users.listUsers` becomes `users_list_users`, the shape MCP servers publish
20
- * and models are trained on.
37
+ * Every `Kizuna.model` schema reachable from a value, found by walking its
38
+ * schemas and whatever plain objects and lists hold them.
21
39
  */
22
- const toToolName = (key) => key.split(".").map(toSnakeCase).join("_");
23
- const sentenceLabel = (origin) => origin === "route" ? "Route" : "Tool";
40
+ const reachModels = (value, models, found, seen) => {
41
+ if (typeof value !== "object" || value === null || seen.has(value)) return;
42
+ seen.add(value);
43
+ if (isSchema(value)) {
44
+ if (models.has(value)) found.add(value);
45
+ const def = value._zod.def;
46
+ for (const [key, child] of Object.entries(def)) {
47
+ if (key === "checks") continue;
48
+ if (key === "getter" && typeof child === "function") {
49
+ reachModels(child(), models, found, seen);
50
+ continue;
51
+ }
52
+ reachModels(child, models, found, seen);
53
+ }
54
+ return;
55
+ }
56
+ for (const child of Array.isArray(value) ? value : Object.values(value)) reachModels(child, models, found, seen);
57
+ };
24
58
  /**
25
- * Every key mapped to its published tool name, throwing on a name MCP clients
26
- * reject and on two keys that converge on one name.
59
+ * The named models the given routes use, sorted by name, each with the plugin
60
+ * that brought it when none of the app's own routes use it.
27
61
  */
28
- const deriveToolNames = (entries) => {
29
- const names = /* @__PURE__ */ new Map();
30
- const claimedBy = /* @__PURE__ */ new Map();
31
- for (const entry of entries) {
32
- const { key, origin } = entry;
33
- const name = toToolName(key);
34
- 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}.`);
35
- 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.`);
36
- const claimant = claimedBy.get(name);
37
- 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.`);
38
- claimedBy.set(name, entry);
39
- names.set(key, name);
62
+ const modelsOf = (entries) => {
63
+ const models = /* @__PURE__ */ new Map();
64
+ for (const [id, schema] of globalRegistrySchemas()) models.set(schema, id);
65
+ const owners = /* @__PURE__ */ new Map();
66
+ const appFirst = [...entries].sort((left, right) => Number(left.plugin !== void 0) - Number(right.plugin !== void 0));
67
+ for (const { route, plugin } of appFirst) {
68
+ const found = /* @__PURE__ */ new Set();
69
+ reachModels(route, models, found, /* @__PURE__ */ new Set());
70
+ for (const schema of found) if (!owners.has(schema)) owners.set(schema, plugin);
40
71
  }
41
- return names;
72
+ return [...owners].map(([schema, plugin]) => ({
73
+ name: models.get(schema),
74
+ schema,
75
+ description: readMetaDescription(schema),
76
+ plugin
77
+ })).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
42
78
  };
43
- //#endregion
44
- //#region src/generator.ts
79
+ const deprecationMessageOf = (route) => typeof route.deprecated === "string" ? route.deprecated : typeof route.deprecated === "object" ? route.deprecated.message : void 0;
45
80
  /**
46
- * Factory for building type-safe routes generators.
47
- *
48
- * Centralises routes walking and deprecation resolution so generator authors
49
- * only need to implement `processRoute` and `finalize`. Field-level deprecation
50
- * lives on the schemas themselves, read with `readDeprecation`.
81
+ * Run a walk over an api: its models, then every route it serves, the app's
82
+ * and each plugin's under its slug. Returns what `finalize` returns.
51
83
  *
52
- * ```ts
53
- * const generateRouteList = createGenerator(() => {
54
- * const routeList: string[] = [];
55
- * return {
56
- * processRoute({ route, deprecated }) {
57
- * routeList.push(`${route.method} ${route.path}${deprecated ? ' (deprecated)' : ''}`);
58
- * },
59
- * finalize() {
60
- * return routeList;
61
- * },
62
- * };
84
+ * @example
85
+ * const routeList = walkApi(api, {
86
+ * processRoute: ({ route }) => lines.push(`${route.method} ${route.path}`),
87
+ * finalize: () => lines.join('\n'),
63
88
  * });
64
- *
65
- * const list = generateRouteList(kizuna.api, {});
66
- * ```
67
89
  */
68
- const createGenerator = (factory) => (contract, options) => {
69
- const { processRoute, finalize } = factory(options, contract);
70
- for (const { routeKey, route, routeTags } of flattenRoutes(contract.routes)) processRoute({
90
+ const walkApi = (api, walk, options = {}) => {
91
+ const entries = servedRoutes(api).filter(({ route }) => options.skipHidden !== true || route.hidden !== true);
92
+ if (walk.processModel !== void 0) for (const model of modelsOf(entries)) walk.processModel(model);
93
+ for (const { routeKey, route, routeGroups, plugin } of entries) walk.processRoute?.({
71
94
  routeKey,
72
95
  route,
73
- routeTags,
96
+ routeGroups,
97
+ hidden: route.hidden === true,
98
+ plugin,
74
99
  deprecated: route.deprecated !== void 0 && route.deprecated !== false,
75
- deprecationMessage: typeof route.deprecated === "string" ? route.deprecated : typeof route.deprecated === "object" ? route.deprecated.message : void 0
100
+ deprecationMessage: deprecationMessageOf(route)
76
101
  });
77
- return finalize();
102
+ return walk.finalize();
103
+ };
104
+ const parseOptions = (schema, input, name) => {
105
+ if (schema === void 0) return input;
106
+ const parsed = schema.safeParse(input);
107
+ if (!parsed.success) throw new Error(`[kizuna] ${name} has invalid options: ${parsed.error.issues.map(describeIssue).join("; ")}`);
108
+ return parsed.data;
109
+ };
110
+ /**
111
+ * Declare a client for a language: the options an app passes it, and the walk
112
+ * that returns its file. Returns the function an app names under `clients`.
113
+ *
114
+ * @example
115
+ * export const dartClient = defineClient({
116
+ * target: 'dart',
117
+ * options: z.object({
118
+ * library: z.string().default('api'),
119
+ * }),
120
+ * generate: ({ options }) => {
121
+ * const writer = new DartWriter(options.library);
122
+ *
123
+ * return {
124
+ * processModel: (model) => writer.model(model),
125
+ * processRoute: (context) => writer.method(context),
126
+ * finalize: () => writer.render(),
127
+ * };
128
+ * },
129
+ * });
130
+ */
131
+ const defineClient = (definition) => (input) => {
132
+ const { output, ...rest } = input;
133
+ const options = parseOptions(definition.options, rest, `Client '${definition.target}'`);
134
+ return {
135
+ target: definition.target,
136
+ output,
137
+ render: (api) => walkApi(api, definition.generate({
138
+ options,
139
+ api
140
+ }), { skipHidden: true })
141
+ };
142
+ };
143
+ /**
144
+ * Declare a generator for a file that isn't a client, like a document or a
145
+ * manifest. A plugin installs it by returning it from `setup`.
146
+ *
147
+ * @example
148
+ * export const gatewayManifest = defineGenerator({
149
+ * generate: () => {
150
+ * const entries: string[] = [];
151
+ *
152
+ * return {
153
+ * processRoute: ({ route }) => entries.push(`${route.method} ${route.path}`),
154
+ * finalize: () => entries.join('\n'),
155
+ * };
156
+ * },
157
+ * });
158
+ */
159
+ const defineGenerator = (definition) => (input) => {
160
+ const { output, ...rest } = input;
161
+ const options = parseOptions(definition.options, rest, `The generator for '${output}'`);
162
+ return {
163
+ output,
164
+ render: (api) => walkApi(api, definition.generate({
165
+ options,
166
+ api
167
+ }))
168
+ };
78
169
  };
79
170
  //#endregion
80
- export { EVENT_STREAM_MEDIA_TYPE, FILE_PROBE, cacheHeaders, createGenerator, deprecationHeaders, deriveToolNames, flattenJobs, globalRegistrySchemas, isBinarySchema, isCompiledJob, isDiscriminatedUnionSchema, isFileSchema, isHintPrefix, isIntegerSchema, isJsonMediaType, isNamedStream, isObjectSchema, isStreamResponse, isSuccessStatus, isVoidSchema, isZodSchema, jobAt, localTypeName, mergeHeaderFields, parsePath, readDef, readDefType, readDeprecation, readDiscriminatedUnion, readDiscriminatorLiteral, readDiscriminatorStringLiteral, readMeta, readMetaDescription, readMetaExamples, readMetaId, readObjectShape, resolveResponseBody, resolveResponseCache, resolveResponseContentType, resolveResponseEtag, resolveResponseHeaders, resolveResponseStream, routeStreams, sanitizeFieldName, sanitizeIdentifier, shortTypeName, soleStreamResponse, statusToCamelCase, streamContentType, streamMode, streamSchemas, streamStatuses, toCamelCase, toPascalCase, toToolName, unwrapOptionalWrappers };
171
+ export { EVENT_STREAM_MEDIA_TYPE, FILE_PROBE, cacheHeaders, defineClient, defineGenerator, deprecationHeaders, deriveToolNames, flattenJobs, globalRegistrySchemas, isBinarySchema, isCompiledJob, isDiscriminatedUnionSchema, isFileSchema, isHintPrefix, isIntegerSchema, isJsonMediaType, isNamedStream, isObjectSchema, isStreamResponse, isSuccessStatus, isVoidSchema, isZodSchema, jobAt, listedRoutes, localTypeName, mergeHeaderFields, parsePath, readDef, readDefType, readDeprecation, readDiscriminatedUnion, readDiscriminatorLiteral, readDiscriminatorStringLiteral, readMeta, readMetaBrand, readMetaDescription, readMetaExamples, readMetaId, readObjectShape, resolveResponseBody, resolveResponseCache, resolveResponseContentType, resolveResponseEtag, resolveResponseHeaders, resolveResponseStream, routeStreams, sanitizeFieldName, sanitizeIdentifier, shortTypeName, soleStreamResponse, statusToCamelCase, streamContentType, streamMode, streamSchemas, streamStatuses, toCamelCase, toPascalCase, toToolName, unwrapOptionalWrappers, walkApi };