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,45 +1,6 @@
1
- const require_error_response = require("./error-response-C8Ragjcd.cjs");
1
+ const require_plugin = require("./plugin-Dw-yCjTY.cjs");
2
+ const require_error_response = require("./error-response-C9ymqSU4.cjs");
2
3
  let zod = require("zod");
3
- //#region src/types.ts
4
- const METHODS = [
5
- "GET",
6
- "HEAD",
7
- "POST",
8
- "PUT",
9
- "PATCH",
10
- "DELETE",
11
- "OPTIONS"
12
- ];
13
- /**
14
- * Key under which every declaration says what it is, so `kizuna generate` can
15
- * tell a route from a job from any other export. A symbol, so nothing that
16
- * walks a declaration's own entries sees it.
17
- */
18
- const DECLARATION = Symbol.for("kizuna.declaration");
19
- /**
20
- * Where a declaration stores what answers it. Off the string keys, so a builder
21
- * can carry both the declaration and the `handler` that attaches one.
22
- */
23
- const HANDLER = Symbol.for("kizuna.handler");
24
- /**
25
- * Key under which a routes group carries its group tag key, the source
26
- * `flattenRoutes` and the generator use to apply the group's tag to every route
27
- * in it. Stamped by `k.routes`.
28
- */
29
- const ROUTES_TAG = Symbol.for("kizuna.routes.tag");
30
- /**
31
- * Type-only key under which `defineConfig` brands each route with its resolved
32
- * handler context. Never written at runtime.
33
- */
34
- const HANDLER_CONTEXT_BRAND = Symbol.for("kizuna.route.handlerContext");
35
- /**
36
- * Type-only key under which `defineConfig` brands a guarded route with the
37
- * statuses its guard answers for it. Never written at runtime.
38
- */
39
- const AUTO_RESPONSES_BRAND = Symbol.for("kizuna.route.autoResponses");
40
- const AUTO_GUARD_BRAND = Symbol.for("kizuna.route.guardBody");
41
- const AUTO_GUARD_WRITTEN_BRAND = Symbol.for("kizuna.route.guardBodyWritten");
42
- //#endregion
43
4
  //#region src/coercion.ts
44
5
  /**
45
6
  * The schema kinds a path/query/header string is coerced into. A field of any
@@ -158,18 +119,21 @@ const isRouteDefinition = (value) => {
158
119
  const candidate = value;
159
120
  return typeof candidate.method === "string" && typeof candidate.path === "string" && !!candidate.responses;
160
121
  };
161
- const flattenRoutes = (routes, prefix, inheritedTags = []) => {
162
- const ownTag = routes[ROUTES_TAG];
163
- const activeTags = ownTag ? [...inheritedTags, ownTag] : inheritedTags;
122
+ /**
123
+ * Flatten a tree of routes, each with its groups.
124
+ */
125
+ const flattenRoutes = (routes, prefix, inheritedGroup) => {
126
+ const declared = routes[require_plugin.ROUTES_GROUP];
127
+ const group = declared === void 0 || declared === "" ? inheritedGroup : declared;
164
128
  const collected = [];
165
129
  for (const [key, value] of Object.entries(routes)) {
166
130
  const fullKey = prefix ? `${prefix}.${key}` : key;
167
131
  if (isRouteDefinition(value)) collected.push({
168
132
  routeKey: fullKey,
169
133
  route: value,
170
- routeTags: activeTags
134
+ routeGroups: [...new Set([...group === void 0 ? [] : [group], ...value.groups ?? []])]
171
135
  });
172
- else if (value && typeof value === "object") collected.push(...flattenRoutes(value, fullKey, activeTags));
136
+ else if (value && typeof value === "object") collected.push(...flattenRoutes(value, fullKey, group));
173
137
  }
174
138
  return collected;
175
139
  };
@@ -544,6 +508,47 @@ const encodeStreamBody = (source, options) => {
544
508
  });
545
509
  };
546
510
  //#endregion
511
+ //#region src/tool-name.ts
512
+ /**
513
+ * Set by the MCP specification.
514
+ *
515
+ * @see https://modelcontextprotocol.io/specification/latest/server/tools
516
+ */
517
+ const MAX_TOOL_NAME_LENGTH = 128;
518
+ /**
519
+ * The specification allows a dot too, and kizuna's own route and tool keys are
520
+ * dotted. Claude and GitHub Copilot validate against this narrower set and
521
+ * reject the whole tool list over one name outside it, so the dot does not
522
+ * survive here.
523
+ */
524
+ const TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
525
+ const toSnakeCase = (segment) => segment.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase();
526
+ /**
527
+ * `users.listUsers` becomes `users_list_users`, the shape MCP servers publish
528
+ * and models are trained on.
529
+ */
530
+ const toToolName = (key) => key.split(".").map(toSnakeCase).join("_");
531
+ const sentenceLabel = (origin) => origin === "route" ? "Route" : "Tool";
532
+ /**
533
+ * Every key mapped to its published tool name, throwing on a name MCP clients
534
+ * reject and on two keys that converge on one name.
535
+ */
536
+ const deriveToolNames = (entries) => {
537
+ const names = /* @__PURE__ */ new Map();
538
+ const claimedBy = /* @__PURE__ */ new Map();
539
+ for (const entry of entries) {
540
+ const { key, origin } = entry;
541
+ const name = toToolName(key);
542
+ 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}.`);
543
+ 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.`);
544
+ const claimant = claimedBy.get(name);
545
+ 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.`);
546
+ claimedBy.set(name, entry);
547
+ names.set(key, name);
548
+ }
549
+ return names;
550
+ };
551
+ //#endregion
547
552
  //#region src/schedule.ts
548
553
  /**
549
554
  * The cron expression of a {@link JobSchedule}, whichever form it was written in.
@@ -925,7 +930,7 @@ const cron = {
925
930
  //#endregion
926
931
  //#region src/jobs.ts
927
932
  /**
928
- * The namespace the job endpoints are mounted under when `jobs.path` says
933
+ * The namespace the job endpoints are mounted under when `jobRunner.path` says
929
934
  * nothing.
930
935
  */
931
936
  const DEFAULT_JOBS_PATH = "/jobs";
@@ -1051,8 +1056,20 @@ const isCompiledJob = (value) => {
1051
1056
  * Throws when either job endpoint lands on a path an API route already serves.
1052
1057
  * Called by `defineConfig`, the one place that sees both.
1053
1058
  */
1059
+ /**
1060
+ * Throw when declared jobs do not say how they run, or when the job endpoints
1061
+ * would be served with no identity guarding them.
1062
+ */
1063
+ const assertJobRunner = (jobs, config) => {
1064
+ const flattened = jobs ? flattenJobs(jobs) : [];
1065
+ if (flattened.length === 0) return;
1066
+ if (config?.mode === void 0) throw new Error("The jobs do not say how they run. Set `jobRunner: { mode: 'http' }` to serve `/jobs/dispatch` and `/jobs/run`, or `jobRunner: { mode: 'in-process' }` when `startJobs` ticks them in this process.");
1067
+ if (config.mode === "in-process" || flattened.some(({ job }) => job.identity !== void 0)) return;
1068
+ const base = config.path ?? "/jobs";
1069
+ throw new Error(`The jobs declare no identity, so \`${base}/dispatch\` and \`${base}/run\` would let anyone trigger them. Pass an identity to \`k.jobs\`, or set \`jobRunner: { mode: 'in-process' }\` when the jobs run in this process with \`startJobs\`.`);
1070
+ };
1054
1071
  const jobClaims = (jobs, config) => {
1055
- if (!jobs || flattenJobs(jobs).length === 0) return [];
1072
+ if (!jobs || config?.mode === "in-process" || flattenJobs(jobs).length === 0) return [];
1056
1073
  const base = config?.path ?? "/jobs";
1057
1074
  return [{
1058
1075
  method: config?.method ?? "POST",
@@ -1169,30 +1186,128 @@ const assertValidCache = (routes) => {
1169
1186
  }
1170
1187
  };
1171
1188
  //#endregion
1172
- Object.defineProperty(exports, "AUTO_GUARD_BRAND", {
1173
- enumerable: true,
1174
- get: function() {
1175
- return AUTO_GUARD_BRAND;
1176
- }
1177
- });
1178
- Object.defineProperty(exports, "AUTO_GUARD_WRITTEN_BRAND", {
1179
- enumerable: true,
1180
- get: function() {
1181
- return AUTO_GUARD_WRITTEN_BRAND;
1182
- }
1183
- });
1184
- Object.defineProperty(exports, "AUTO_RESPONSES_BRAND", {
1185
- enumerable: true,
1186
- get: function() {
1187
- return AUTO_RESPONSES_BRAND;
1188
- }
1189
- });
1190
- Object.defineProperty(exports, "DECLARATION", {
1191
- enumerable: true,
1192
- get: function() {
1193
- return DECLARATION;
1189
+ //#region src/plugin-server.ts
1190
+ /**
1191
+ * The plugin routes `assembleApi` stashed on the api. Empty without plugins, so
1192
+ * an adapter can mount it unconditionally.
1193
+ */
1194
+ const pluginRoutesOf = (api) => api[require_plugin.PLUGIN_ROUTES_META_KEY] ?? {};
1195
+ /**
1196
+ * Their handlers, keyed to match {@link pluginRoutesOf}.
1197
+ */
1198
+ const pluginRouterOf = (api) => {
1199
+ const servers = api[require_plugin.PLUGIN_SERVERS_META_KEY];
1200
+ const router = {};
1201
+ for (const [pluginKey, served] of Object.entries(servers ?? {})) router[pluginKey] = served.router;
1202
+ return router;
1203
+ };
1204
+ /**
1205
+ * What each plugin exports, for the adapter to pass into the pipeline as the
1206
+ * handler args' `plugins`.
1207
+ */
1208
+ const pluginExportsOf = (api) => {
1209
+ const servers = api[require_plugin.PLUGIN_SERVERS_META_KEY];
1210
+ const exported = {};
1211
+ for (const [pluginKey, served] of Object.entries(servers ?? {})) if (served.exports !== void 0) exported[pluginKey] = served.exports;
1212
+ return exported;
1213
+ };
1214
+ /**
1215
+ * One issue as the app should read it: the field, and what's wrong with it.
1216
+ */
1217
+ const describeIssue = (issue) => {
1218
+ const field = issue.path.map(String).join(".");
1219
+ if (issue.code === "invalid_type" && issue.message.endsWith("received undefined")) return `${field} is required`;
1220
+ return field === "" ? issue.message : `${field}: ${issue.message}`;
1221
+ };
1222
+ /**
1223
+ * A route's path under its plugin's base path. A route at `/` serves the base
1224
+ * path itself, since `/webhooks` and `/webhooks/` are different paths.
1225
+ */
1226
+ const underBasePath = (basePath, path) => path === "/" ? basePath : `${basePath}${path}`;
1227
+ /**
1228
+ * The base path a plugin's routes are served under: the app's, else the
1229
+ * plugin's own. An app can only move a plugin that declares one.
1230
+ */
1231
+ const basePathOf = (declaration) => {
1232
+ const { definition, slug } = declaration;
1233
+ if (declaration.basePath !== void 0 && definition.basePath === void 0) throw new Error(`[kizuna] Plugin '${slug}' declares no \`basePath\`, so its routes can't be moved. Remove \`basePath\`.`);
1234
+ const basePath = declaration.basePath ?? definition.basePath;
1235
+ if (basePath !== void 0 && (!basePath.startsWith("/") || basePath.endsWith("/"))) throw new Error(`[kizuna] Plugin '${slug}' has the base path '${basePath}'. A base path starts with \`/\` and doesn't end with one.`);
1236
+ return basePath;
1237
+ };
1238
+ /**
1239
+ * Validate one installed plugin's options and run its `setup`.
1240
+ */
1241
+ const resolvePlugin = (declaration, api) => {
1242
+ const { definition, slug } = declaration;
1243
+ let options = void 0;
1244
+ if (definition.options !== void 0) {
1245
+ const parsed = definition.options.safeParse(declaration.input);
1246
+ if (!parsed.success) throw new Error(`[kizuna] Plugin '${slug}' has invalid options: ${parsed.error.issues.map(describeIssue).join("; ")}`);
1247
+ options = parsed.data;
1248
+ }
1249
+ const setup = definition.setup({
1250
+ options,
1251
+ api
1252
+ });
1253
+ const basePath = basePathOf(declaration);
1254
+ const routes = setup.routes ?? {};
1255
+ return {
1256
+ slug,
1257
+ definedSlug: definition.slug,
1258
+ options,
1259
+ routes: basePath === void 0 ? routes : Object.fromEntries(Object.entries(routes).map(([routeKey, route]) => [routeKey, {
1260
+ ...route,
1261
+ path: underBasePath(basePath, route.path)
1262
+ }])),
1263
+ exports: setup.exports,
1264
+ generators: setup.generators ?? [],
1265
+ validate: setup.validate
1266
+ };
1267
+ };
1268
+ /**
1269
+ * Resolve every installed plugin, keyed by slug. Two plugins on one slug throw,
1270
+ * naming both, since handlers could only reach one of them.
1271
+ */
1272
+ const resolvePlugins = (declarations, api) => {
1273
+ const resolved = {};
1274
+ for (const declaration of declarations ?? []) {
1275
+ const existing = resolved[declaration.slug];
1276
+ if (existing !== void 0) throw new Error(`[kizuna] Two plugins are installed under the slug '${declaration.slug}': '${existing.definedSlug}' and '${declaration.definition.slug}'. Pass one of them a \`slug\` of its own.`);
1277
+ resolved[declaration.slug] = resolvePlugin(declaration, api);
1194
1278
  }
1195
- });
1279
+ return resolved;
1280
+ };
1281
+ /**
1282
+ * A stand-in for the api that plugins receive in `setup`, before it exists.
1283
+ * Reading it inside a handler works once `bind` has run; reading it during
1284
+ * `setup` throws, since the api is still being assembled.
1285
+ */
1286
+ const createApiReference = () => {
1287
+ let current;
1288
+ const assembled = () => {
1289
+ if (current === void 0) throw new Error("[kizuna] A plugin read the api during `setup`. Read it inside a handler, once the config has assembled.");
1290
+ return current;
1291
+ };
1292
+ return {
1293
+ api: new Proxy({}, {
1294
+ get: (_target, key) => Reflect.get(assembled(), key),
1295
+ has: (_target, key) => Reflect.has(assembled(), key),
1296
+ ownKeys: () => Reflect.ownKeys(assembled()),
1297
+ getOwnPropertyDescriptor: (_target, key) => {
1298
+ const descriptor = Reflect.getOwnPropertyDescriptor(assembled(), key);
1299
+ return descriptor === void 0 ? void 0 : {
1300
+ ...descriptor,
1301
+ configurable: true
1302
+ };
1303
+ }
1304
+ }),
1305
+ bind: (target) => {
1306
+ current = target;
1307
+ }
1308
+ };
1309
+ };
1310
+ //#endregion
1196
1311
  Object.defineProperty(exports, "DEFAULT_JOBS_PATH", {
1197
1312
  enumerable: true,
1198
1313
  get: function() {
@@ -1205,34 +1320,16 @@ Object.defineProperty(exports, "EVENT_STREAM_MEDIA_TYPE", {
1205
1320
  return EVENT_STREAM_MEDIA_TYPE;
1206
1321
  }
1207
1322
  });
1208
- Object.defineProperty(exports, "HANDLER", {
1209
- enumerable: true,
1210
- get: function() {
1211
- return HANDLER;
1212
- }
1213
- });
1214
- Object.defineProperty(exports, "HANDLER_CONTEXT_BRAND", {
1215
- enumerable: true,
1216
- get: function() {
1217
- return HANDLER_CONTEXT_BRAND;
1218
- }
1219
- });
1220
- Object.defineProperty(exports, "METHODS", {
1221
- enumerable: true,
1222
- get: function() {
1223
- return METHODS;
1224
- }
1225
- });
1226
- Object.defineProperty(exports, "ROUTES_TAG", {
1323
+ Object.defineProperty(exports, "allowedMethodsForPath", {
1227
1324
  enumerable: true,
1228
1325
  get: function() {
1229
- return ROUTES_TAG;
1326
+ return allowedMethodsForPath;
1230
1327
  }
1231
1328
  });
1232
- Object.defineProperty(exports, "allowedMethodsForPath", {
1329
+ Object.defineProperty(exports, "assertJobRunner", {
1233
1330
  enumerable: true,
1234
1331
  get: function() {
1235
- return allowedMethodsForPath;
1332
+ return assertJobRunner;
1236
1333
  }
1237
1334
  });
1238
1335
  Object.defineProperty(exports, "assertValidCache", {
@@ -1277,6 +1374,12 @@ Object.defineProperty(exports, "cacheHeaders", {
1277
1374
  return cacheHeaders;
1278
1375
  }
1279
1376
  });
1377
+ Object.defineProperty(exports, "createApiReference", {
1378
+ enumerable: true,
1379
+ get: function() {
1380
+ return createApiReference;
1381
+ }
1382
+ });
1280
1383
  Object.defineProperty(exports, "cron", {
1281
1384
  enumerable: true,
1282
1385
  get: function() {
@@ -1289,6 +1392,18 @@ Object.defineProperty(exports, "deprecationHeaders", {
1289
1392
  return deprecationHeaders;
1290
1393
  }
1291
1394
  });
1395
+ Object.defineProperty(exports, "deriveToolNames", {
1396
+ enumerable: true,
1397
+ get: function() {
1398
+ return deriveToolNames;
1399
+ }
1400
+ });
1401
+ Object.defineProperty(exports, "describeIssue", {
1402
+ enumerable: true,
1403
+ get: function() {
1404
+ return describeIssue;
1405
+ }
1406
+ });
1292
1407
  Object.defineProperty(exports, "dueSchedules", {
1293
1408
  enumerable: true,
1294
1409
  get: function() {
@@ -1427,12 +1542,36 @@ Object.defineProperty(exports, "parsePath", {
1427
1542
  return parsePath;
1428
1543
  }
1429
1544
  });
1545
+ Object.defineProperty(exports, "pluginExportsOf", {
1546
+ enumerable: true,
1547
+ get: function() {
1548
+ return pluginExportsOf;
1549
+ }
1550
+ });
1551
+ Object.defineProperty(exports, "pluginRouterOf", {
1552
+ enumerable: true,
1553
+ get: function() {
1554
+ return pluginRouterOf;
1555
+ }
1556
+ });
1557
+ Object.defineProperty(exports, "pluginRoutesOf", {
1558
+ enumerable: true,
1559
+ get: function() {
1560
+ return pluginRoutesOf;
1561
+ }
1562
+ });
1430
1563
  Object.defineProperty(exports, "resolveCoercionPlans", {
1431
1564
  enumerable: true,
1432
1565
  get: function() {
1433
1566
  return resolveCoercionPlans;
1434
1567
  }
1435
1568
  });
1569
+ Object.defineProperty(exports, "resolvePlugins", {
1570
+ enumerable: true,
1571
+ get: function() {
1572
+ return resolvePlugins;
1573
+ }
1574
+ });
1436
1575
  Object.defineProperty(exports, "resolveResponseBody", {
1437
1576
  enumerable: true,
1438
1577
  get: function() {
@@ -1559,6 +1698,12 @@ Object.defineProperty(exports, "toPascalCase", {
1559
1698
  return toPascalCase;
1560
1699
  }
1561
1700
  });
1701
+ Object.defineProperty(exports, "toToolName", {
1702
+ enumerable: true,
1703
+ get: function() {
1704
+ return toToolName;
1705
+ }
1706
+ });
1562
1707
  Object.defineProperty(exports, "validateRequest", {
1563
1708
  enumerable: true,
1564
1709
  get: function() {
@@ -0,0 +1,138 @@
1
+ import { z } from "zod";
2
+ //#region src/types.ts
3
+ const METHODS = [
4
+ "GET",
5
+ "HEAD",
6
+ "POST",
7
+ "PUT",
8
+ "PATCH",
9
+ "DELETE",
10
+ "OPTIONS"
11
+ ];
12
+ /**
13
+ * Key under which every declaration says what it is, so `kizuna generate` can
14
+ * tell a route from a job from any other export. A symbol, so nothing that
15
+ * walks a declaration's own entries sees it.
16
+ */
17
+ const DECLARATION = Symbol.for("kizuna.declaration");
18
+ /**
19
+ * Where a declaration stores what answers it. Off the string keys, so a builder
20
+ * can carry both the declaration and the `handler` that attaches one.
21
+ */
22
+ const HANDLER = Symbol.for("kizuna.handler");
23
+ /**
24
+ * Where a tree from `k.routes` carries its group's dotted path.
25
+ */
26
+ const ROUTES_GROUP = Symbol.for("kizuna.routes.group");
27
+ /**
28
+ * Type-only key under which `defineConfig` brands each route with its resolved
29
+ * handler context. Never written at runtime.
30
+ */
31
+ const HANDLER_CONTEXT_BRAND = Symbol.for("kizuna.route.handlerContext");
32
+ /**
33
+ * Type-only key under which `defineConfig` brands a guarded route with the
34
+ * statuses its guard answers for it. Never written at runtime.
35
+ */
36
+ const AUTO_RESPONSES_BRAND = Symbol.for("kizuna.route.autoResponses");
37
+ const AUTO_GUARD_BRAND = Symbol.for("kizuna.route.guardBody");
38
+ const AUTO_GUARD_WRITTEN_BRAND = Symbol.for("kizuna.route.guardBodyWritten");
39
+ //#endregion
40
+ //#region src/route.ts
41
+ const createRoute = (definition) => ({
42
+ ...definition,
43
+ handler: (fn) => ({
44
+ ...definition,
45
+ [HANDLER]: fn,
46
+ [DECLARATION]: "route"
47
+ })
48
+ });
49
+ //#endregion
50
+ //#region src/plugin.ts
51
+ const PLUGIN_ROUTES_META_KEY = Symbol.for("kizuna.plugin-routes");
52
+ const PLUGIN_SERVERS_META_KEY = Symbol.for("kizuna.plugin-servers");
53
+ /**
54
+ * Declare a plugin: its slug, the options an app passes it, and the `setup` that
55
+ * builds what it brings. Returns the function an app installs it with.
56
+ *
57
+ * @example
58
+ * export const emailPlugin = definePlugin({
59
+ * slug: 'email',
60
+ * options: z.object({
61
+ * apiKey: z.string(),
62
+ * from: z.string(),
63
+ * }),
64
+ * setup: ({ options }) => {
65
+ * const resend = new Resend(options.apiKey);
66
+ *
67
+ * return {
68
+ * exports: {
69
+ * send: (email: Email) =>
70
+ * resend.emails.send({
71
+ * from: options.from,
72
+ * ...email,
73
+ * }),
74
+ * },
75
+ * };
76
+ * },
77
+ * });
78
+ */
79
+ const definePlugin = (definition) => ((input) => {
80
+ const { slug, basePath, ...options } = input ?? {};
81
+ return {
82
+ slug: typeof slug === "string" ? slug : definition.slug,
83
+ ...typeof basePath === "string" ? { basePath } : {},
84
+ definition,
85
+ input: options
86
+ };
87
+ });
88
+ /**
89
+ * Declare one of a plugin's routes and the handler that answers it, the way
90
+ * `k.route` does for an app's own.
91
+ *
92
+ * @example
93
+ * check: route({
94
+ * method: 'GET',
95
+ * path: '/status',
96
+ * auth: false,
97
+ * responses: {
98
+ * 200: StatusSchema,
99
+ * },
100
+ * }).handler(() => ({
101
+ * status: 200,
102
+ * body: {
103
+ * status: 'ok',
104
+ * },
105
+ * })),
106
+ */
107
+ const route = createRoute;
108
+ /**
109
+ * Accepts a route path, for a plugin that takes one of its routes' paths as an
110
+ * option.
111
+ */
112
+ const RoutePathSchema = z.custom((value) => typeof value === "string" && value.startsWith("/"), { error: "must start with /" });
113
+ /**
114
+ * Accepts exactly what a route's `auth` does, for a plugin that takes one of its
115
+ * routes' `auth` as an option. `defineConfig` checks the value against the app's
116
+ * identities.
117
+ */
118
+ const RouteAuthSchema = z.union([
119
+ z.literal(false),
120
+ z.string(),
121
+ z.array(z.string()),
122
+ z.object({
123
+ identity: z.union([z.string(), z.array(z.string())]),
124
+ roles: z.union([z.string(), z.array(z.string())]).optional(),
125
+ requires: z.record(z.string(), z.array(z.string())).optional()
126
+ })
127
+ ]);
128
+ /**
129
+ * Every plugin's routes as one tree, keyed by slug, for the adapter to walk as
130
+ * it walks the api's own.
131
+ */
132
+ const pluginRouteTree = (plugins) => {
133
+ const tree = {};
134
+ for (const [slug, plugin] of Object.entries(plugins ?? {})) tree[slug] = plugin.routes;
135
+ return tree;
136
+ };
137
+ //#endregion
138
+ export { definePlugin as a, createRoute as c, AUTO_RESPONSES_BRAND as d, DECLARATION as f, ROUTES_GROUP as g, METHODS as h, RoutePathSchema as i, AUTO_GUARD_BRAND as l, HANDLER_CONTEXT_BRAND as m, PLUGIN_SERVERS_META_KEY as n, pluginRouteTree as o, HANDLER as p, RouteAuthSchema as r, route as s, PLUGIN_ROUTES_META_KEY as t, AUTO_GUARD_WRITTEN_BRAND as u };
package/dist/plugin.cjs CHANGED
@@ -1,73 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region src/plugin.ts
3
- const PLUGIN_ROUTES_META_KEY = Symbol.for("kizuna.plugin-routes");
4
- const PLUGIN_SERVERS_META_KEY = Symbol.for("kizuna.plugin-servers");
5
- /**
6
- * Declare a plugin: the routes it serves, the props an app configures it with,
7
- * and the `serve` that answers those routes. Whatever `serve` returns under
8
- * `exports` reaches every handler as `plugins.<slug>`.
9
- *
10
- * Give the factory a `Slug` parameter and {@link WithSlug} so an app can rename
11
- * what it installs, or install two of them.
12
- *
13
- * @example
14
- * ```ts
15
- * const declare = (slug: string, props: AuditProps) =>
16
- * createPlugin({
17
- * slug,
18
- * routes: {
19
- * recent: {
20
- * method: 'GET',
21
- * path: props.path ?? '/audit/recent',
22
- * responses: {
23
- * 200: z.array(EntrySchema),
24
- * },
25
- * },
26
- * },
27
- * props,
28
- * serve: ({ store }) => ({
29
- * router: {
30
- * recent: async () => ({ status: 200, body: await store.recent() }),
31
- * },
32
- * exports: {
33
- * record: (routeKey: string) => store.write(routeKey),
34
- * },
35
- * }),
36
- * });
37
- *
38
- * export function auditPlugin<const Slug extends string = 'audit'>(
39
- * props: AuditProps<Slug>
40
- * ): WithSlug<ReturnType<typeof declare>, Slug> {
41
- * return declare(props.slug ?? 'audit', props) as never;
42
- * }
43
- * ```
44
- */
45
- const createPlugin = (definition) => ({
46
- slug: definition.slug,
47
- routes: definition.routes,
48
- props: definition.props,
49
- serve: definition.serve
50
- });
51
- /**
52
- * Every plugin's routes as one tree, keyed by install name, for the adapter to
53
- * walk as it walks the api's own.
54
- */
55
- const pluginRouteTree = (plugins) => {
56
- const tree = {};
57
- for (const [pluginKey, plugin] of Object.entries(plugins ?? {})) tree[pluginKey] = plugin.routes;
58
- return tree;
59
- };
60
- /**
61
- * Every plugin in a list, keyed by its own slug.
62
- */
63
- const pluginsBySlug = (plugins) => {
64
- const bySlug = {};
65
- for (const plugin of plugins ?? []) bySlug[plugin.slug] = plugin;
66
- return bySlug;
67
- };
68
- //#endregion
69
- exports.PLUGIN_ROUTES_META_KEY = PLUGIN_ROUTES_META_KEY;
70
- exports.PLUGIN_SERVERS_META_KEY = PLUGIN_SERVERS_META_KEY;
71
- exports.createPlugin = createPlugin;
72
- exports.pluginRouteTree = pluginRouteTree;
73
- exports.pluginsBySlug = pluginsBySlug;
2
+ const require_plugin = require("./plugin-Dw-yCjTY.cjs");
3
+ exports.PLUGIN_ROUTES_META_KEY = require_plugin.PLUGIN_ROUTES_META_KEY;
4
+ exports.PLUGIN_SERVERS_META_KEY = require_plugin.PLUGIN_SERVERS_META_KEY;
5
+ exports.RouteAuthSchema = require_plugin.RouteAuthSchema;
6
+ exports.RoutePathSchema = require_plugin.RoutePathSchema;
7
+ exports.definePlugin = require_plugin.definePlugin;
8
+ exports.pluginRouteTree = require_plugin.pluginRouteTree;
9
+ exports.route = require_plugin.route;
package/dist/plugin.d.cts CHANGED
@@ -1,3 +1,3 @@
1
- import { K as RoutePath } from "./security-scheme-BrszwGD5.cjs";
2
- import { _ as WithSlug, a as PluginArgs, b as pluginsBySlug, c as PluginExportValues, d as PluginPropsOf, f as PluginRouter, g as PluginsBySlug, h as PluginServe, i as PLUGIN_SERVERS_META_KEY, l as PluginExportsOf, m as PluginRoutesOf, n as ApiPlugins, o as PluginDeclaration, p as PluginRoutes, r as PLUGIN_ROUTES_META_KEY, s as PluginDefinition, t as AnyPlugin, u as PluginList, v as createPlugin, y as pluginRouteTree } from "./plugin-DhKvx_T0.cjs";
3
- export { AnyPlugin, ApiPlugins, PLUGIN_ROUTES_META_KEY, PLUGIN_SERVERS_META_KEY, PluginArgs, PluginDeclaration, PluginDefinition, PluginExportValues, PluginExportsOf, PluginList, PluginPropsOf, PluginRouter, PluginRoutes, PluginRoutesOf, PluginServe, PluginsBySlug, RoutePath, WithSlug, createPlugin, pluginRouteTree, pluginsBySlug };
1
+ import { Y as RoutePath } from "./error-response-YbkRMKno.cjs";
2
+ import { $t as ResolvedPlugin, Bt as PluginArgs, Ft as ApiPlugins, Gt as PluginFactory, Ht as PluginDefinition, It as InstallOptions, Jt as PluginRoutes, Kt as PluginList, Lt as PLUGIN_ROUTES_META_KEY, Pt as AnyPlugin, Qt as PluginsBySlug, Rt as PLUGIN_SERVERS_META_KEY, Ut as PluginExportValues, Vt as PluginDeclaration, Wt as PluginExportsOf, Xt as PluginSetup, Yt as PluginRoutesOf, Zt as PluginSetupContext, an as route, en as RouteAuthSchema, in as pluginRouteTree, nn as SlugOption, on as ApiContext, qt as PluginRouteBuilder, rn as definePlugin, tn as RoutePathSchema, zt as PluginApi } from "./adapter-C3WYdSfx.cjs";
3
+ export { AnyPlugin, ApiContext, ApiPlugins, InstallOptions, PLUGIN_ROUTES_META_KEY, PLUGIN_SERVERS_META_KEY, PluginApi, PluginArgs, PluginDeclaration, PluginDefinition, PluginExportValues, PluginExportsOf, PluginFactory, PluginList, PluginRouteBuilder, PluginRoutes, PluginRoutesOf, PluginSetup, PluginSetupContext, PluginsBySlug, ResolvedPlugin, RouteAuthSchema, RoutePath, RoutePathSchema, SlugOption, definePlugin, pluginRouteTree, route };
package/dist/plugin.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { K as RoutePath } from "./security-scheme-D3nb4XKj.mjs";
2
- import { _ as WithSlug, a as PluginArgs, b as pluginsBySlug, c as PluginExportValues, d as PluginPropsOf, f as PluginRouter, g as PluginsBySlug, h as PluginServe, i as PLUGIN_SERVERS_META_KEY, l as PluginExportsOf, m as PluginRoutesOf, n as ApiPlugins, o as PluginDeclaration, p as PluginRoutes, r as PLUGIN_ROUTES_META_KEY, s as PluginDefinition, t as AnyPlugin, u as PluginList, v as createPlugin, y as pluginRouteTree } from "./plugin-Cz0kn6Lk.mjs";
3
- export { AnyPlugin, ApiPlugins, PLUGIN_ROUTES_META_KEY, PLUGIN_SERVERS_META_KEY, PluginArgs, PluginDeclaration, PluginDefinition, PluginExportValues, PluginExportsOf, PluginList, PluginPropsOf, PluginRouter, PluginRoutes, PluginRoutesOf, PluginServe, PluginsBySlug, RoutePath, WithSlug, createPlugin, pluginRouteTree, pluginsBySlug };
1
+ import { Y as RoutePath } from "./error-response-NoOGdh8H.mjs";
2
+ import { $t as ResolvedPlugin, Bt as PluginArgs, Ft as ApiPlugins, Gt as PluginFactory, Ht as PluginDefinition, It as InstallOptions, Jt as PluginRoutes, Kt as PluginList, Lt as PLUGIN_ROUTES_META_KEY, Pt as AnyPlugin, Qt as PluginsBySlug, Rt as PLUGIN_SERVERS_META_KEY, Ut as PluginExportValues, Vt as PluginDeclaration, Wt as PluginExportsOf, Xt as PluginSetup, Yt as PluginRoutesOf, Zt as PluginSetupContext, an as route, en as RouteAuthSchema, in as pluginRouteTree, nn as SlugOption, on as ApiContext, qt as PluginRouteBuilder, rn as definePlugin, tn as RoutePathSchema, zt as PluginApi } from "./adapter-D4bTPElA.mjs";
3
+ export { AnyPlugin, ApiContext, ApiPlugins, InstallOptions, PLUGIN_ROUTES_META_KEY, PLUGIN_SERVERS_META_KEY, PluginApi, PluginArgs, PluginDeclaration, PluginDefinition, PluginExportValues, PluginExportsOf, PluginFactory, PluginList, PluginRouteBuilder, PluginRoutes, PluginRoutesOf, PluginSetup, PluginSetupContext, PluginsBySlug, ResolvedPlugin, RouteAuthSchema, RoutePath, RoutePathSchema, SlugOption, definePlugin, pluginRouteTree, route };