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
@@ -0,0 +1,2754 @@
1
+ import { A as AutoResponsesBrand, D as AUTO_RESPONSES_BRAND, E as AUTO_GUARD_WRITTEN_BRAND, F as HANDLER, I as HANDLER_CONTEXT_BRAND, J as RouteHiddenToolCheck, K as RouteDefinition, L as HandlerContextBrand, O as AuthoredRouteDefinition, P as GuardStatus, U as ResponseDefinition, V as RequiredPermissions, W as ResponseHeaders, X as RouteToolOptions, Y as RoutePath, Z as Routes, a as OAuthFlows, at as ProblemDetails, b as RoleNamesOf, et as StreamDefinition, j as CachePolicy, m as GrantNamesOf, ot as StripProblemEnvelope, p as CatalogOf, q as RouteHandlerFunction, r as ContextOf, s as SecurityScheme, t as ProblemDetailsSchema, tt as StreamResponseDefinition, x as Roles, z as Method } from "./error-response-YbkRMKno.cjs";
2
+ import { z } from "zod";
3
+
4
+ //#region src/identity.d.ts
5
+ /**
6
+ * The token a `bearer`, `oauth2`, or `openIdConnect` method extracts from the
7
+ * `Authorization` header.
8
+ */
9
+ interface BearerCredential {
10
+ token: string;
11
+ }
12
+ /**
13
+ * The username and password a `basic` method decodes from the
14
+ * `Authorization: Basic <base64>` header.
15
+ */
16
+ interface BasicCredential {
17
+ username: string;
18
+ password: string;
19
+ }
20
+ /**
21
+ * The value an `apiKey` method reads from the header, query parameter, or cookie
22
+ * the identity named, with `in`/`name` echoing where it came from.
23
+ *
24
+ * @example
25
+ * // for k.identity.apiKey({ name: 'x-workspace-token', in: 'header' }):
26
+ * // { in: 'header'; name: 'x-workspace-token'; value: string }
27
+ */
28
+ interface ApiKeyCredential<In extends 'header' | 'query' | 'cookie' = 'header' | 'query' | 'cookie', Name extends string = string> {
29
+ in: In;
30
+ name: Name;
31
+ value: string;
32
+ }
33
+ /**
34
+ * The credential a guard receives, keyed by the identity's authentication method.
35
+ * A guard destructures the one key its identity declares, `{ bearer }`,
36
+ * `{ apiKey }`, `{ basic }`, `{ oauth2 }`, or `{ openIdConnect }`. The value is
37
+ * `null` when the request carried no such credential.
38
+ */
39
+ type Credential = {
40
+ bearer: BearerCredential | null;
41
+ } | {
42
+ oauth2: BearerCredential | null;
43
+ } | {
44
+ openIdConnect: BearerCredential | null;
45
+ } | {
46
+ basic: BasicCredential | null;
47
+ } | {
48
+ apiKey: ApiKeyCredential | null;
49
+ };
50
+ /**
51
+ * The empty credential a `custom` identity carries. Its guard receives no
52
+ * credential key and reads the credential itself (e.g. `params.token`).
53
+ */
54
+ type NoCredential = Record<never, never>;
55
+ declare const CREDENTIAL: unique symbol;
56
+ /**
57
+ * An authenticated caller, defined with the `k.identity` builders. Extends
58
+ * {@link SecurityScheme} with what its callers hold and the credential its
59
+ * authentication method extracts from the request.
60
+ */
61
+ interface Identity<ContextSchema extends z.ZodType | undefined = z.ZodType | undefined, RolesType extends Roles | undefined = Roles | undefined, CredentialType extends Credential | NoCredential = Credential, ParamsSchema extends z.ZodType | undefined = z.ZodType | undefined> extends SecurityScheme<ContextSchema> {
62
+ /**
63
+ * The path parameters this identity's guard reads. A route whose `auth`
64
+ * names the identity has to carry them, and the guard receives them typed.
65
+ */
66
+ readonly params: ParamsSchema;
67
+ /**
68
+ * The roles this identity's callers hold. The guard returns `role`.
69
+ */
70
+ readonly roles: RolesType;
71
+ /**
72
+ * Phantom marker carrying the {@link Credential} the method extracts. Never
73
+ * present at runtime.
74
+ */
75
+ readonly [CREDENTIAL]?: CredentialType;
76
+ }
77
+ /**
78
+ * The {@link Credential} an identity's authentication method extracts and passes
79
+ * to its guard, a single discriminated member, e.g. `{ apiKey: { in; name;
80
+ * value } | null }` for an `apiKey` identity.
81
+ */
82
+ type CredentialOf<Id> = Id extends Identity<z.ZodType | undefined, Roles | undefined, infer Extracted> ? Extracted : Credential;
83
+ /**
84
+ * The path params an identity's guard receives: what its `params` schema
85
+ * declares, or the adapter's raw record when it declares none.
86
+ */
87
+ type IdentityParamsOf<Id> = Id extends {
88
+ params: infer ParamsSchema;
89
+ } ? ParamsSchema extends z.ZodType ? z.output<ParamsSchema> : Record<string, string> : Record<string, string>;
90
+ /**
91
+ * The {@link Roles} an identity declares, or `never` when it declares none.
92
+ */
93
+ type RolesOf<Id> = Id extends Identity<z.ZodType | undefined, infer RolesType> ? (RolesType extends Roles ? RolesType : never) : never;
94
+ /**
95
+ * The role a guard returns and a handler reads: one declared name, or several.
96
+ */
97
+ type RoleOf<Id> = RoleNamesOf<RolesOf<Id>> | readonly RoleNamesOf<RolesOf<Id>>[];
98
+ /**
99
+ * What a caller holds, as permission names, when the identity's roles come from a catalog.
100
+ */
101
+ type GrantsOf<Id> = readonly GrantNamesOf<RolesOf<Id>>[];
102
+ /**
103
+ * What roles add to a guard's return: `role` when the identity declares them,
104
+ * with optional `permissions` when they come from a catalog, the subset of the
105
+ * role's this caller was given, `{}` otherwise.
106
+ */
107
+ type GuardHoldings<Id> = [RolesOf<Id>] extends [never] ? {} : [CatalogOf<RolesOf<Id>>] extends [never] ? {
108
+ role: RoleOf<Id>;
109
+ } : {
110
+ role: RoleOf<Id>;
111
+ permissions?: GrantsOf<Id>;
112
+ };
113
+ /**
114
+ * What roles add to a handler's `auth`: `role` when the identity declares them,
115
+ * and `permissions`, what the caller holds, when they come from a catalog: the
116
+ * role's, or the subset the guard returned.
117
+ */
118
+ type IdentityRole<Id> = [RolesOf<Id>] extends [never] ? {} : [CatalogOf<RolesOf<Id>>] extends [never] ? {
119
+ role: RoleOf<Id>;
120
+ } : {
121
+ role: RoleOf<Id>;
122
+ permissions: GrantsOf<Id>;
123
+ };
124
+ interface BearerConfig<ContextSchema extends z.ZodType | undefined, RolesType extends Roles | undefined> {
125
+ context?: ContextSchema;
126
+ roles?: RolesType;
127
+ bearerFormat?: string;
128
+ description?: string;
129
+ scheme?: string;
130
+ }
131
+ interface ApiKeyConfig<ContextSchema extends z.ZodType | undefined, RolesType extends Roles | undefined, Name extends string, In extends 'header' | 'query' | 'cookie'> {
132
+ name: Name;
133
+ in: In;
134
+ context?: ContextSchema;
135
+ roles?: RolesType;
136
+ description?: string;
137
+ scheme?: string;
138
+ }
139
+ interface BasicConfig<ContextSchema extends z.ZodType | undefined, RolesType extends Roles | undefined> {
140
+ context?: ContextSchema;
141
+ roles?: RolesType;
142
+ description?: string;
143
+ scheme?: string;
144
+ }
145
+ interface OAuth2Config<ContextSchema extends z.ZodType | undefined, RolesType extends Roles | undefined> {
146
+ flows: OAuthFlows;
147
+ /**
148
+ * Issuer identifier of the authorization server (RFC 8414), for consumers
149
+ * that advertise it, such as RFC 9728 metadata. The flow URLs cannot stand
150
+ * in for it: an issuer may carry a path the endpoint URLs do not reveal.
151
+ */
152
+ issuer?: string;
153
+ /**
154
+ * URL of this API's RFC 9728 metadata document, sent as `resource_metadata`
155
+ * in every `Bearer` challenge so a client can find the authorization server.
156
+ */
157
+ resourceMetadata?: string;
158
+ context?: ContextSchema;
159
+ roles?: RolesType;
160
+ description?: string;
161
+ scheme?: string;
162
+ }
163
+ interface OpenIdConnectConfig<ContextSchema extends z.ZodType | undefined, RolesType extends Roles | undefined> {
164
+ openIdConnectUrl: string;
165
+ /**
166
+ * URL of this API's RFC 9728 metadata document, sent as `resource_metadata`
167
+ * in every `Bearer` challenge so a client can find the authorization server.
168
+ */
169
+ resourceMetadata?: string;
170
+ context?: ContextSchema;
171
+ roles?: RolesType;
172
+ description?: string;
173
+ scheme?: string;
174
+ }
175
+ interface CustomConfig<ContextSchema extends z.ZodType | undefined, RolesType extends Roles | undefined, ParamsSchema extends z.ZodType | undefined = undefined> {
176
+ context?: ContextSchema;
177
+ roles?: RolesType;
178
+ description?: string;
179
+ scheme?: string;
180
+ /**
181
+ * The path parameters this identity's guard reads, for a credential that
182
+ * travels in the path. A route whose `auth` names the identity has to carry
183
+ * them.
184
+ *
185
+ * @example
186
+ * params: z.object({
187
+ * token: z.string(),
188
+ * }),
189
+ */
190
+ params?: ParamsSchema;
191
+ }
192
+ //#endregion
193
+ //#region src/access-check.d.ts
194
+ interface AccessCheckInput {
195
+ roles: readonly string[] | undefined;
196
+ requires: RequiredPermissions | undefined;
197
+ requiredSchemes: readonly string[];
198
+ schemes: Record<string, SecurityScheme> | undefined;
199
+ securityContext: Record<string, unknown>;
200
+ }
201
+ /**
202
+ * A guard's return with `permissions` settled: what the role holds, narrowed to
203
+ * the list the guard returned when it returned one. Anything the role cannot
204
+ * hold is dropped. Unchanged for an identity whose roles carry no permissions.
205
+ */
206
+ declare const withPermissions: (scheme: string, definition: SecurityScheme | undefined, result: unknown) => unknown;
207
+ /**
208
+ * The permissions a route requires that an OAuth caller's role holds but the
209
+ * token does not carry. A token with more scope would pass, so the `403` says
210
+ * `insufficient_scope`. Empty when no new token could help.
211
+ */
212
+ declare const insufficientScope: (input: AccessCheckInput) => string[];
213
+ /**
214
+ * The `403` detail when the caller holds none of the roles the route accepts
215
+ * or lacks a permission it requires, or `undefined`.
216
+ */
217
+ declare const requiresDenial: (input: AccessCheckInput) => string | undefined;
218
+ //#endregion
219
+ //#region src/tool-events.d.ts
220
+ /**
221
+ * Every route in a tree as its dotted key, e.g. `'weather.getForecast'`. A tool
222
+ * is addressed by that key everywhere, the way a job is.
223
+ */
224
+ type ToolKeys<R extends Routes, Prefix extends string = ''> = { [Name in keyof R & string]: R[Name] extends RouteDefinition ? `${Prefix}${Name}` : R[Name] extends Routes ? ToolKeys<R[Name], `${Prefix}${Name}.`> : never }[keyof R & string];
225
+ /**
226
+ * The route one dotted key names.
227
+ */
228
+ type ToolAt<R extends Routes, Key extends string> = Key extends `${infer Head}.${infer Rest}` ? R[Head] extends Routes ? ToolAt<R[Head], Rest> : never : R[Key] extends RouteDefinition ? R[Key] : never;
229
+ type SchemaSide<Schema extends z.ZodType, Io extends 'input' | 'output'> = Io extends 'input' ? z.input<Schema> : z.output<Schema>;
230
+ /**
231
+ * Collapse an intersection into one object, so a call reads as the record it
232
+ * is rather than as the pieces it was built from.
233
+ */
234
+ type Flatten<Shape> = { [Key in keyof Shape]: Shape[Key] } & {};
235
+ /**
236
+ * What a model sends to call a route: the same `{ params, query, body }` the
237
+ * MCP endpoint takes, with each part present only when the route declares it.
238
+ */
239
+ type ToolInput<Route, Io extends 'input' | 'output'> = Flatten<(Route extends {
240
+ pathParams: infer Params extends z.ZodType;
241
+ } ? {
242
+ params: SchemaSide<Params, Io>;
243
+ } : {}) & (Route extends {
244
+ query: infer Query extends z.ZodType;
245
+ } ? {
246
+ query: SchemaSide<Query, Io>;
247
+ } : {}) & (Route extends {
248
+ body: infer Body extends z.ZodType;
249
+ } ? {
250
+ body: SchemaSide<Body, Io>;
251
+ } : {})>;
252
+ type SuccessBody<Response, Io extends 'input' | 'output'> = Response extends z.ZodType ? SchemaSide<Response, Io> : Response extends {
253
+ stream: unknown;
254
+ } ? void : Response extends {
255
+ body: infer Body extends z.ZodType;
256
+ } ? SchemaSide<Body, Io> : never;
257
+ /**
258
+ * What the route answers with, from each `2xx` it declares.
259
+ */
260
+ type ToolOutput<Route, Io extends 'input' | 'output'> = Route extends {
261
+ responses: infer Responses;
262
+ } ? { [Status in keyof Responses]: `${Status & number}` extends `2${string}` ? SuccessBody<Responses[Status], Io> : never }[keyof Responses] : never;
263
+ /**
264
+ * The `input` field of a call, absent for a route that takes nothing.
265
+ */
266
+ type InputField<Route, Io extends 'input' | 'output'> = [keyof ToolInput<Route, Io>] extends [never] ? {} : {
267
+ input: ToolInput<Route, Io>;
268
+ };
269
+ type OutputField<Route, Io extends 'input' | 'output'> = [Exclude<ToolOutput<Route, Io>, void>] extends [never] ? {} : void extends ToolOutput<Route, Io> ? {
270
+ output?: Exclude<ToolOutput<Route, Io>, void>;
271
+ } : {
272
+ output: ToolOutput<Route, Io>;
273
+ };
274
+ /**
275
+ * One tool call, discriminated on `name` so `input` narrows to the route's own
276
+ * argument type.
277
+ */
278
+ type ToolCall<R extends Routes, Io extends 'input' | 'output' = 'output'> = { [Key in ToolKeys<R>]: Flatten<{
279
+ id: string;
280
+ name: Key;
281
+ /**
282
+ * The call waits for the person to approve it.
283
+ */
284
+ needsApproval?: true;
285
+ } & InputField<ToolAt<R, Key>, Io>> }[ToolKeys<R>];
286
+ /**
287
+ * One tool result, discriminated on `name` so `output` narrows to the route's
288
+ * own result type.
289
+ */
290
+ type ToolResult<R extends Routes, Io extends 'input' | 'output' = 'output'> = { [Key in ToolKeys<R>]: Flatten<{
291
+ id: string;
292
+ name: Key;
293
+ } & OutputField<ToolAt<R, Key>, Io>> }[ToolKeys<R>];
294
+ /**
295
+ * A tool that failed. The payload is the same whichever route it was, so this
296
+ * carries the name as a plain enum rather than a discriminated union.
297
+ */
298
+ interface ToolError<R extends Routes> {
299
+ id: string;
300
+ name: ToolKeys<R>;
301
+ message: string;
302
+ }
303
+ /**
304
+ * The events {@link toolEvents} adds to a stream.
305
+ */
306
+ interface ToolEvents<R extends Routes> {
307
+ tool_call: z.ZodType<ToolCall<R, 'output'>, ToolCall<R, 'input'>>;
308
+ tool_result: z.ZodType<ToolResult<R, 'output'>, ToolResult<R, 'input'>>;
309
+ tool_error: z.ZodType<ToolError<R>>;
310
+ }
311
+ /**
312
+ * Server-sent events for the routes a model may call, to spread into a route's
313
+ * `stream`. Each one is discriminated on the route's dotted key, so a client's
314
+ * `for await` narrows the payload to the route that produced it.
315
+ *
316
+ * @example
317
+ * ```ts
318
+ * stream: {
319
+ * delta: z.object({
320
+ * text: z.string(),
321
+ * }),
322
+ * },
323
+ * tools: assistantTools,
324
+ * ```
325
+ */
326
+ declare const toolEvents: <const R extends Routes>(tools: R) => ToolEvents<R>;
327
+ /**
328
+ * The events a stream carries once its `tools` have been folded in. A response
329
+ * declaring none is its `stream` untouched.
330
+ */
331
+ type StreamWithTools<Def extends StreamResponseDefinition> = Def extends {
332
+ tools: infer R extends Routes;
333
+ } ? Def['stream'] & ToolEvents<R> : Def['stream'];
334
+ /**
335
+ * Fold a response's `tools` into its `stream`, so everything downstream reads
336
+ * one record of named events and never learns a tool was involved. Called by
337
+ * `k.routes` before a route is validated.
338
+ */
339
+ declare const expandStreamTools: (route: RouteDefinition, routeKey: string) => void;
340
+ //#endregion
341
+ //#region src/stream.d.ts
342
+ interface StreamContext {
343
+ signal: AbortSignal;
344
+ }
345
+ interface EventFields {
346
+ id?: string;
347
+ retry?: number;
348
+ }
349
+ interface StreamComment {
350
+ comment: string;
351
+ }
352
+ /**
353
+ * What a handler yields per event, on the schema's input side.
354
+ */
355
+ type StreamYield<Stream extends StreamDefinition> = (Stream extends z.ZodType ? {
356
+ data: z.input<Stream>;
357
+ } & EventFields : { [Name in keyof Stream & string]: {
358
+ event: Name;
359
+ data: z.input<Stream[Name]>;
360
+ } & EventFields }[keyof Stream & string]) | StreamComment;
361
+ /**
362
+ * What a client reads per event, on the schema's output side.
363
+ */
364
+ type StreamMessage<Stream extends StreamDefinition> = Stream extends z.ZodType ? {
365
+ data: z.output<Stream>;
366
+ } & EventFields : { [Name in keyof Stream & string]: {
367
+ event: Name;
368
+ data: z.output<Stream[Name]>;
369
+ } & EventFields }[keyof Stream & string];
370
+ type IsEventStream<Def> = Def extends {
371
+ contentType: infer ContentType;
372
+ } ? (ContentType extends 'text/event-stream' ? true : false) : true;
373
+ type StreamChunk<Def extends StreamResponseDefinition> = IsEventStream<Def> extends true ? StreamYield<StreamWithTools<Def>> : Def['stream'] extends z.ZodType ? z.input<Def['stream']> : never;
374
+ type StreamMessageOf<Def extends StreamResponseDefinition> = IsEventStream<Def> extends true ? StreamMessage<StreamWithTools<Def>> : Def['stream'] extends z.ZodType ? z.output<Def['stream']> : never;
375
+ /**
376
+ * The `body` of a streamed status: an async generator function receiving `{ signal }`, or any async iterable.
377
+ */
378
+ type StreamBodyOf<Def extends StreamResponseDefinition> = ((context: StreamContext) => AsyncIterable<StreamChunk<Def>>) | AsyncIterable<StreamChunk<Def>>;
379
+ /**
380
+ * The `body` type of one streamed status, for a generator written outside its handler.
381
+ *
382
+ * @example
383
+ * ```ts
384
+ * const cannedReply: StreamBody<typeof replyRoute, 200> = async function* () {
385
+ * yield {
386
+ * event: 'delta',
387
+ * data: {
388
+ * text: 'Hello',
389
+ * },
390
+ * };
391
+ * };
392
+ * ```
393
+ */
394
+ type StreamBody<R extends Pick<RouteDefinition, 'responses'>, Status extends keyof R['responses']> = R['responses'][Status] extends StreamResponseDefinition ? StreamBodyOf<R['responses'][Status]> : never;
395
+ declare const EVENT_STREAM_MEDIA_TYPE = "text/event-stream";
396
+ type StreamMode = 'events' | 'text' | 'binary';
397
+ declare const streamContentType: (definition: StreamResponseDefinition) => string;
398
+ declare const streamMode: (definition: StreamResponseDefinition) => StreamMode;
399
+ declare const isNamedStream: (stream: StreamDefinition) => stream is Record<string, z.ZodType>;
400
+ declare const streamStatuses: (route: Pick<RouteDefinition, "responses">) => number[];
401
+ /**
402
+ * Whether any status of the route streams.
403
+ */
404
+ declare const routeStreams: (route: Pick<RouteDefinition, "responses">) => boolean;
405
+ /**
406
+ * The one streamed 2xx of a route with no other 2xx beside it, the shape the
407
+ * native clients generate. `undefined` for a route that does not stream, or one
408
+ * that mixes a stream with another success status.
409
+ */
410
+ declare const soleStreamResponse: (route: Pick<RouteDefinition, "responses">) => {
411
+ status: number;
412
+ definition: StreamResponseDefinition;
413
+ } | undefined;
414
+ declare const streamSchemas: (stream: StreamDefinition) => z.ZodType[];
415
+ interface EncodeStreamOptions {
416
+ signal: AbortSignal;
417
+ validate?: boolean;
418
+ onError?: (error: unknown) => void;
419
+ }
420
+ interface StreamSource {
421
+ routeKey: string;
422
+ route: RouteDefinition;
423
+ status: number;
424
+ body: unknown;
425
+ }
426
+ /**
427
+ * The bytes of a streamed response, pulled from the handler's body as the consumer reads.
428
+ */
429
+ declare const encodeStreamBody: (source: StreamSource, options: EncodeStreamOptions) => ReadableStream<Uint8Array>;
430
+ //#endregion
431
+ //#region src/path-params.d.ts
432
+ type LowercaseLetter = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z';
433
+ type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
434
+ /**
435
+ * The characters {@link parsePath}'s `/:([a-zA-Z_][a-zA-Z0-9_]*)/` accepts.
436
+ */
437
+ type IdentifierStart = LowercaseLetter | Uppercase<LowercaseLetter> | '_';
438
+ type IdentifierChar = IdentifierStart | Digit;
439
+ type TakeIdentifierRest<Text extends string, Name extends string> = Text extends `${infer Head}${infer Tail}` ? Head extends IdentifierChar ? TakeIdentifierRest<Tail, `${Name}${Head}`> : Name : Name;
440
+ type TakeIdentifier<Text extends string> = Text extends `${infer Head}${infer Tail}` ? Head extends IdentifierStart ? TakeIdentifierRest<Tail, Head> : '' : '';
441
+ /**
442
+ * The `:param` names in a path, as a union. The type-level {@link parsePath}.
443
+ */
444
+ type PathParamName<Path extends string> = Path extends `${string}:${infer AfterColon}` ? TakeIdentifier<AfterColon> extends infer Name extends string ? Name extends '' ? PathParamName<AfterColon> : Name | PathParamName<AfterColon> : never : never;
445
+ type ExtractPathParams<T extends string> = { [Name in PathParamName<T>]: string };
446
+ type HasPathParams<T extends string> = [PathParamName<T>] extends [never] ? false : true;
447
+ /**
448
+ * Resolves to `string` for schemas without a known key set, which switches the
449
+ * check off.
450
+ */
451
+ type DeclaredParamName<Schema> = Schema extends z.ZodType ? Extract<keyof z.output<Schema>, string> : never;
452
+ type UndeclaredParam<Path extends string, Schema> = Exclude<PathParamName<Path>, DeclaredParamName<Schema>>;
453
+ type UnmatchedParam<Path extends string, Schema> = Exclude<DeclaredParamName<Schema>, PathParamName<Path>>;
454
+ type PathParamsMismatch<Path extends string, Schema> = string extends DeclaredParamName<Schema> ? never : [UnmatchedParam<Path, Schema>] extends [never] ? [UndeclaredParam<Path, Schema>] extends [never] ? never : `kizuna: path "${Path}" has parameter ":${UndeclaredParam<Path, Schema>}", which pathParams does not declare` : `kizuna: pathParams declares "${UnmatchedParam<Path, Schema>}", which is not a parameter in path "${Path}"`;
455
+ /**
456
+ * Every mismatch in a route tree, as a union. The `string extends keyof Node`
457
+ * arm stops the walk at a generic that fell back to its constraint.
458
+ */
459
+ type TreeMismatch<Node> = Node extends {
460
+ method: Method;
461
+ path: string;
462
+ } ? Node extends {
463
+ path: infer Path extends string;
464
+ pathParams: infer Schema;
465
+ } ? PathParamsMismatch<Path, Schema> : never : Node extends object ? string extends keyof Node ? never : { [Key in keyof Node]: TreeMismatch<Node[Key]> }[keyof Node] : never;
466
+ type MismatchShape<Node> = { [Key in keyof Node]: Node[Key] extends {
467
+ method: Method;
468
+ path: infer Path extends string;
469
+ pathParams: infer Schema;
470
+ } ? [PathParamsMismatch<Path, Schema>] extends [never] ? unknown : {
471
+ pathParams: PathParamsMismatch<Path, Schema>;
472
+ } : Node[Key] extends object ? MismatchShape<Node[Key]> : unknown };
473
+ /**
474
+ * Reports routes whose `pathParams` keys disagree with their path's `:param`
475
+ * placeholders. Intersect it with the inferred route tree
476
+ * (`defs: T & PathParamsCheck<T>`): a clean tree gives `unknown`, leaving `T`
477
+ * untouched, and a mismatch resolves the offending `pathParams` to an error
478
+ * message. Routes that omit `pathParams` are left alone.
479
+ */
480
+ type PathParamsCheck<RouteTree> = [TreeMismatch<RouteTree>] extends [never] ? unknown : MismatchShape<RouteTree>;
481
+ /**
482
+ * The {@link PathParamsCheck} of one route, for `k.route`. Intersect it with the
483
+ * inferred definition: a route whose `pathParams` keys match its path gives
484
+ * `unknown`, and a mismatch resolves `pathParams` to an error message.
485
+ */
486
+ type RoutePathParamsCheck<Definition> = Definition extends {
487
+ path: infer Path extends string;
488
+ pathParams: infer Schema;
489
+ } ? [PathParamsMismatch<Path, Schema>] extends [never] ? unknown : {
490
+ pathParams: PathParamsMismatch<Path, Schema>;
491
+ } : unknown;
492
+ interface PathSegment {
493
+ kind: 'literal' | 'param';
494
+ value: string;
495
+ }
496
+ declare const parsePath: (path: string) => {
497
+ segments: PathSegment[];
498
+ paramNames: string[];
499
+ };
500
+ declare const buildPath: (path: string, params?: Record<string, string | number | bigint | Date>) => string;
501
+ //#endregion
502
+ //#region src/tool-definitions.d.ts
503
+ /**
504
+ * What a route says about publishing itself, or `undefined` when it says
505
+ * nothing.
506
+ */
507
+ declare const toolOptionsOf: (route: RouteDefinition) => RouteToolOptions | undefined;
508
+ /**
509
+ * Why a route cannot run as a tool, or `undefined` when it can.
510
+ */
511
+ declare const toolRefusal: (route: RouteDefinition) => string | undefined;
512
+ /**
513
+ * The routes a model may call: the ones that declared `tool`, less the ones
514
+ * whose shape a tool call cannot carry.
515
+ */
516
+ declare const selectToolRoutes: (routes: FlattenedRoute[]) => FlattenedRoute[];
517
+ /**
518
+ * What a model reads before it calls the route.
519
+ */
520
+ declare const describeTool: (route: RouteDefinition) => string;
521
+ interface ToolInputSchema {
522
+ shape: Record<string, z.ZodType> | undefined;
523
+ hasParams: boolean;
524
+ hasQuery: boolean;
525
+ hasBody: boolean;
526
+ }
527
+ /**
528
+ * The `{ params, query, body }` a model sends to call the route.
529
+ */
530
+ declare const buildToolInputSchema: (route: RouteDefinition) => ToolInputSchema;
531
+ /**
532
+ * One route as a model sees it.
533
+ */
534
+ interface ToolDefinition {
535
+ /**
536
+ * What the model calls it, e.g. `users_list_users`.
537
+ */
538
+ name: string;
539
+ /**
540
+ * What the stream events call it, e.g. `users.listUsers`.
541
+ */
542
+ key: string;
543
+ description: string;
544
+ /**
545
+ * The `{ params, query, body }` it takes, as JSON Schema.
546
+ */
547
+ inputSchema: Record<string, unknown>;
548
+ }
549
+ /**
550
+ * One {@link ToolDefinition} per route.
551
+ */
552
+ declare const buildToolDefinitions: (routes: Routes) => ToolDefinition[];
553
+ //#endregion
554
+ //#region src/tool-runner.d.ts
555
+ /**
556
+ * A call as the model sent it. `name` is the tool name or its dotted key.
557
+ */
558
+ interface ToolRunCall {
559
+ id: string;
560
+ name: string;
561
+ input?: unknown;
562
+ }
563
+ interface ToolRunOptions {
564
+ /**
565
+ * The person's answer to a call that needs approval. Unset, the call waits.
566
+ * `false` declines it.
567
+ */
568
+ approved?: boolean;
569
+ }
570
+ /**
571
+ * The call as the model knows it, to put back in the conversation.
572
+ */
573
+ interface ModelToolCall {
574
+ id: string;
575
+ name: string;
576
+ input: unknown;
577
+ }
578
+ /**
579
+ * How a call went. `content` is what the model reads.
580
+ */
581
+ type ToolRunResult = {
582
+ call: ModelToolCall;
583
+ } & ({
584
+ state: 'done';
585
+ status: number;
586
+ body: unknown;
587
+ content: string;
588
+ isError: false;
589
+ } | {
590
+ state: 'failed';
591
+ status: number;
592
+ body: unknown;
593
+ content: string;
594
+ isError: true;
595
+ } | {
596
+ state: 'declined';
597
+ content: string;
598
+ isError: true;
599
+ } | {
600
+ /**
601
+ * Nothing ran. The client asks the person and sends a {@link ToolAnswer} back.
602
+ */
603
+ state: 'needs-approval';
604
+ });
605
+ /**
606
+ * The person's answer to a call that needs approval.
607
+ */
608
+ interface ToolAnswer {
609
+ call: ToolRunCall;
610
+ approved: boolean;
611
+ }
612
+ /**
613
+ * The tool events `run` yields.
614
+ */
615
+ type ToolEventYield<R extends Routes> = {
616
+ event: 'tool_call';
617
+ data: ToolCall<R, 'input'>;
618
+ } | {
619
+ event: 'tool_result';
620
+ data: ToolResult<R, 'input'>;
621
+ } | {
622
+ event: 'tool_error';
623
+ data: ToolError<R>;
624
+ };
625
+ /**
626
+ * The routes a streamed response names under `tools`, bound to the caller.
627
+ */
628
+ interface StreamTools<R extends Routes = Routes> {
629
+ /**
630
+ * What to hand the model.
631
+ */
632
+ readonly definitions: ToolDefinition[];
633
+ /**
634
+ * Run one call as the caller, through the route's validation, guards and
635
+ * handler. An answered call runs with `run(answer.call, answer)`.
636
+ *
637
+ * @example
638
+ * ```ts
639
+ * const result = yield* tools.run({
640
+ * id: block.id,
641
+ * name: block.name,
642
+ * input: block.input,
643
+ * });
644
+ * ```
645
+ */
646
+ run: (call: ToolRunCall, options?: ToolRunOptions) => AsyncGenerator<ToolEventYield<R>, ToolRunResult, undefined>;
647
+ }
648
+ //#endregion
649
+ //#region src/handler-pipeline.d.ts
650
+ /**
651
+ * True when a literal status key is in the 4xx/5xx range. Widened `number` keys (no
652
+ * `const` inference) resolve to `false`, so enforcement only kicks in when the concrete
653
+ * status is known, exactly where the wire output matters.
654
+ */
655
+ type IsErrorStatus<Status> = `${Status & number}` extends `4${string}` | `5${string}` ? true : false;
656
+ /**
657
+ * Error responses (4xx/5xx) must be RFC 9457 Problem Details, a schema assignable to the
658
+ * envelope. Anything else resolves to `never`, surfacing as a compile error at the handler
659
+ * return / `throwError()` site. Success responses pass through unchanged.
660
+ */
661
+ type ApplyErrorEnvelope<Input, Status> = IsErrorStatus<Status> extends true ? (Input extends ProblemDetails ? StripProblemEnvelope<Input> : never) : Input;
662
+ type HandlerBody<S, Status> = S extends z.ZodType ? ApplyErrorEnvelope<z.input<S>, Status> : S extends StreamResponseDefinition ? IsErrorStatus<Status> extends true ? never : StreamBodyOf<S> : S extends {
663
+ body: z.ZodType;
664
+ } ? ApplyErrorEnvelope<z.input<S['body']>, Status> : never;
665
+ type ResponseReturn<R extends Pick<RouteDefinition, 'responses'>, Status extends keyof R['responses']> = {
666
+ status: Status extends number ? Status : never;
667
+ body: HandlerBody<R['responses'][Status], Status>;
668
+ headers?: ResponseHeaders;
669
+ };
670
+ /**
671
+ * Constrained to `responses` alone so a job, which has no method or path, reuses it.
672
+ */
673
+ type HandlerReturn<R extends Pick<RouteDefinition, 'responses'>> = { [Status in keyof R['responses']]: ResponseReturn<R, Status> }[keyof R['responses']];
674
+ type StreamStatuses<R extends Pick<RouteDefinition, 'responses'>> = { [Status in keyof R['responses']]: R['responses'][Status] extends StreamResponseDefinition ? Status : never }[keyof R['responses']];
675
+ /**
676
+ * The responses `throwError` takes: every declared status except the streamed
677
+ * ones. A stream is a body to produce, and bailing out is what `throwError` is for.
678
+ */
679
+ type ThrowableReturn<R extends Pick<RouteDefinition, 'responses'>> = { [Status in Exclude<keyof R['responses'], StreamStatuses<R>>]: ResponseReturn<R, Status> }[Exclude<keyof R['responses'], StreamStatuses<R>>];
680
+ type StreamToolsOf<R extends RouteDefinition> = { [Status in keyof R['responses']]: R['responses'][Status] extends {
681
+ stream: unknown;
682
+ tools: infer Tools extends Routes;
683
+ } ? Tools : never }[keyof R['responses']];
684
+ type ToolsArg<R extends RouteDefinition> = [StreamToolsOf<R>] extends [never] ? {} : {
685
+ /**
686
+ * Runs the routes this response names under `tools`, as the caller.
687
+ */
688
+ tools: StreamTools<StreamToolsOf<R>>;
689
+ };
690
+ /**
691
+ * The body as sent, for a route with `rawBody: true`, or nothing.
692
+ */
693
+ type RawBodyArg<R> = R extends {
694
+ rawBody: true;
695
+ } ? {
696
+ /**
697
+ * The body exactly as it was sent, before any parsing. Check a
698
+ * sender's signature against this, not against `body`.
699
+ */
700
+ rawBody: string;
701
+ } : unknown;
702
+ type EventStreamStatuses<R extends Pick<RouteDefinition, 'responses'>> = { [Status in keyof R['responses']]: R['responses'][Status] extends {
703
+ stream: unknown;
704
+ } ? R['responses'][Status] extends {
705
+ contentType: infer ContentType extends string;
706
+ } ? 'text/event-stream' extends ContentType ? Status : never : Status : never }[keyof R['responses']];
707
+ /**
708
+ * Where a client that lost an event stream asks it to resume, for a route that streams events.
709
+ */
710
+ type LastEventIdArg<R extends RouteDefinition> = [EventStreamStatuses<R>] extends [never] ? unknown : {
711
+ /**
712
+ * The `id` of the last event the client received before it reconnected, from its `Last-Event-ID`
713
+ * header. Send what follows it.
714
+ */
715
+ lastEventId: string | undefined;
716
+ };
717
+ type HandlerArgs<R extends RouteDefinition> = ToolsArg<R> & RawBodyArg<R> & LastEventIdArg<R> & {
718
+ params: R extends {
719
+ pathParams: z.ZodType;
720
+ } ? z.output<R['pathParams']> : ExtractPathParams<R['path']>;
721
+ query: R extends {
722
+ query: z.ZodType;
723
+ } ? z.output<R['query']> : undefined;
724
+ body: R extends {
725
+ body: z.ZodType;
726
+ } ? z.output<R['body']> : undefined;
727
+ headers: R extends {
728
+ headers: z.ZodType;
729
+ } ? z.output<R['headers']> : Record<string, string | string[] | undefined>;
730
+ /**
731
+ * Throws a typed error response. Takes the same `{ status, body }` shape as a handler return.
732
+ *
733
+ * This function throws internally and never returns.
734
+ */
735
+ throwError: (response: ThrowableReturn<R> | GuardAnswer<R>) => never;
736
+ };
737
+ type RouteHandler<R extends RouteDefinition, HandlerContext = unknown> = (args: HandlerArgs<R> & HandlerContext & BrandedHandlerContext<R>) => Promise<HandlerReturn<R> | GuardAnswer<R>> | HandlerReturn<R> | GuardAnswer<R>;
738
+ /**
739
+ * The `403` a guarded route already declares, which its handler may answer
740
+ * itself.
741
+ */
742
+ type GuardAnswer<R> = typeof AUTO_RESPONSES_BRAND extends keyof R ? 403 extends NonNullable<R[typeof AUTO_RESPONSES_BRAND]> ? {
743
+ status: 403;
744
+ body: typeof AUTO_GUARD_WRITTEN_BRAND extends keyof R ? NonNullable<R[typeof AUTO_GUARD_WRITTEN_BRAND]> : {
745
+ detail: string;
746
+ };
747
+ headers?: ResponseHeaders;
748
+ } : never : never;
749
+ type Router<T extends Routes, HandlerContext = unknown> = { [Key in keyof T as Key extends symbol ? never : Key]: T[Key] extends RouteDefinition ? RouteHandler<T[Key], HandlerContext> : T[Key] extends Routes ? Router<T[Key], HandlerContext> : never };
750
+ /**
751
+ * What a handler reads for an identity: its `context` and, when the identity
752
+ * declares roles, the caller's `role`, with `permissions` for roles built from
753
+ * a catalog, flattened into one type.
754
+ * Read in a handler under the identity's name. Flattened (rather than left as
755
+ * an intersection) so it works as a contextual type, letting a guard return a
756
+ * literal `role: 'owner'` without an annotation.
757
+ */
758
+ type GuardSuccess<S> = { [Field in keyof (ContextOf<S> & IdentityRole<S>)]: (ContextOf<S> & IdentityRole<S>)[Field] };
759
+ /**
760
+ * What a guard returns to allow a request: the identity's context and its
761
+ * `role`. `permissions` is optional beside the role, since kizuna fills it in
762
+ * from the role before the handler runs.
763
+ */
764
+ type GuardReturn<S> = { [Field in keyof (ContextOf<S> & GuardHoldings<S>)]: (ContextOf<S> & GuardHoldings<S>)[Field] };
765
+ /**
766
+ * The identity names a route's `auth` requires: a name, several, the `identity`
767
+ * of a rule, or none for `false`.
768
+ */
769
+ type AuthIdentityNames<Value> = Value extends false ? never : Value extends string ? Value : Value extends readonly (infer Name extends string)[] ? Name : Value extends {
770
+ identity: infer Identity;
771
+ } ? Identity extends string ? Identity : Identity extends readonly (infer Name extends string)[] ? Name : never : never;
772
+ /**
773
+ * What a route requires of its caller, `false` for one that declares nothing.
774
+ */
775
+ type AuthOf<R> = R extends {
776
+ auth: infer Value;
777
+ } ? Value : false;
778
+ /**
779
+ * The scheme-keyed security context a route's handler receives, derived from
780
+ * its `auth`: `false` (public) contributes nothing; each identity it names
781
+ * yields that identity's context, the caller's role, and for roles built from a
782
+ * catalog, the caller's permissions.
783
+ *
784
+ * @example
785
+ * type Context = ContextFromAuth<{ identity: 'member' }, { member: typeof member }>;
786
+ * // { member: { workspaceUserId: string; role: 'owner' | 'admin' | readonly ('owner' | 'admin')[]; permissions: readonly ('workspace:read' | 'workspace:delete')[] } }
787
+ */
788
+ type ContextFromAuth<Value, Identities> = { [Name in AuthIdentityNames<Value> & keyof Identities as [keyof GuardSuccess<Identities[Name]>] extends [never] ? never : Name]: GuardSuccess<Identities[Name]> };
789
+ /**
790
+ * The `auth` argument one route's handler receives, from the route's own rule.
791
+ */
792
+ type AuthContextOf<Route, Identities> = AuthArg<AuthOf<Route>, Identities>;
793
+ /**
794
+ * The `auth` argument a secured route's handler receives.
795
+ */
796
+ type AuthArg<Value, Identities> = ContextFromAuth<Value, Identities> extends infer Ctx ? ([keyof Ctx] extends [never] ? {} : {
797
+ auth: Ctx;
798
+ }) : never;
799
+ /**
800
+ * The `requestContext` argument a handler receives.
801
+ */
802
+ type RequestContextValues<RequestContext> = string extends keyof RequestContext ? {} : [keyof RequestContext] extends [never] ? {} : {
803
+ requestContext: { [Name in keyof RequestContext]: RequestContext[Name] extends {
804
+ context: infer Schema extends z.ZodType;
805
+ } ? z.output<Schema> : never };
806
+ };
807
+ /**
808
+ * The path param names of every route the identity `Name` secures.
809
+ */
810
+ type GuardedParamNames<R extends Routes, Name extends string> = { [Key in keyof R & string]: R[Key] extends RouteDefinition ? Name extends AuthIdentityNames<AuthOf<R[Key]>> ? keyof ExtractPathParams<R[Key]['path']> & string : never : R[Key] extends Routes ? GuardedParamNames<R[Key], Name> : never }[keyof R & string];
811
+ /**
812
+ * The `params` a guard for identity `Name` receives: the param names of the
813
+ * routes it secures, each optional since the guard runs across all of them.
814
+ * Falls back to `Record<string, string>` when no params are derivable.
815
+ */
816
+ type GuardParams<R extends Routes, Name extends string> = [GuardedParamNames<R, Name>] extends [never] ? Record<string, string> : { [Param in GuardedParamNames<R, Name>]?: string };
817
+ /**
818
+ * The handler tree for an api or route group: every route typed with its
819
+ * inputs, the adapter's handler context, and the scheme-keyed security context
820
+ * its `auth` resolves to. The identities a route requires appear in the handler
821
+ * args under `auth`, keyed by each identity's name, each carrying its context
822
+ * and the caller's role.
823
+ */
824
+ type HandlersFromRoutes<R extends Routes, HandlerContext, Identities> = { [Key in keyof R as Key extends symbol ? never : Key]: R[Key] extends RouteDefinition ? RouteHandlerFromContext<R[Key], HandlerContext, AuthArg<AuthOf<R[Key]>, Identities>> : R[Key] extends Routes ? HandlersFromRoutes<R[Key], HandlerContext, Identities> : never };
825
+ type RouteHandlerFromContext<R extends RouteDefinition, HandlerContext, SecurityContext> = (args: HandlerArgs<R> & HandlerContext & SecurityContext) => Promise<HandlerReturn<R> | GuardAnswer<R>> | HandlerReturn<R> | GuardAnswer<R>;
826
+ /**
827
+ * A route's brand, skipped when the resolved context is empty.
828
+ */
829
+ type RouteContextBrand<Context> = [keyof Context] extends [never] ? unknown : HandlerContextBrand<Context>;
830
+ type RouteGuardBrand<Value, Body, Written> = [AuthIdentityNames<Value>] extends [never] ? unknown : AutoResponsesBrand<GuardStatus, Body, Written>;
831
+ /**
832
+ * The `401` and `403` a route's own `auth` gives it, so a handler written at the
833
+ * route may answer the `403` itself.
834
+ */
835
+ type RouteGuardBrandOf<Route, Body, Written> = RouteGuardBrand<AuthOf<Route>, Body, Written>;
836
+ type HandlerContextOverlay<R extends Routes, Identities, Context, GuardBody_, GuardWritten_> = { [Key in keyof R]: R[Key] extends RouteDefinition ? RouteContextBrand<AuthArg<AuthOf<R[Key]>, Identities> & Context> & RouteGuardBrand<AuthOf<R[Key]>, GuardBody_, GuardWritten_> : R[Key] extends Routes ? HandlerContextOverlay<R[Key], Identities, Context, GuardBody_, GuardWritten_> : unknown };
837
+ /**
838
+ * An api's routes, each branded with what the api adds to a handler's
839
+ * args: `auth`, `requestContext`, plugins, and jobs. Read back by
840
+ * {@link RouteHandler}.
841
+ */
842
+ type RoutesWithHandlerContext<R extends Routes, Identities, RequestContext, ApiContext = unknown, GuardBody_ = ProblemDetails, GuardWritten_ = {
843
+ detail: string;
844
+ }> = R & HandlerContextOverlay<R, Identities, RequestContextValues<RequestContext> & ApiContext, GuardBody_, GuardWritten_>;
845
+ type BrandedHandlerContext<R> = typeof HANDLER_CONTEXT_BRAND extends keyof R ? NonNullable<R[typeof HANDLER_CONTEXT_BRAND]> : {};
846
+ declare const isRouteDefinition: (value: unknown) => value is RouteDefinition;
847
+ interface FlattenedRoute {
848
+ routeKey: string;
849
+ route: RouteDefinition;
850
+ /**
851
+ * The route's groups, as dotted paths, its own first.
852
+ */
853
+ routeGroups: string[];
854
+ }
855
+ /**
856
+ * Flatten a tree of routes, each with its groups.
857
+ */
858
+ declare const flattenRoutes: (routes: Routes, prefix?: string, inheritedGroup?: string) => FlattenedRoute[];
859
+ interface RawInputs {
860
+ params: unknown;
861
+ query: unknown;
862
+ body: unknown;
863
+ headers: unknown;
864
+ }
865
+ type ValidationStage = 'params' | 'query' | 'headers' | 'body';
866
+ interface ValidationFailure {
867
+ stage: ValidationStage;
868
+ issues: z.core.$ZodIssue[];
869
+ }
870
+ declare const formatValidationError: (failure: ValidationFailure) => {
871
+ detail: string;
872
+ issues: z.core.$ZodIssue[];
873
+ };
874
+ declare const validateRequest: (route: RouteDefinition, raw: RawInputs) => {
875
+ ok: true;
876
+ parsed: RawInputs;
877
+ } | {
878
+ ok: false;
879
+ error: ValidationFailure;
880
+ };
881
+ declare const allowedMethodsForPath: (routes: Routes, path: string) => Method[];
882
+ //#endregion
883
+ //#region src/route-matcher.d.ts
884
+ interface RouteMatch {
885
+ routeKey: string;
886
+ route: RouteDefinition;
887
+ params: Record<string, string>;
888
+ }
889
+ type MatchResult = {
890
+ kind: 'matched';
891
+ match: RouteMatch;
892
+ } | {
893
+ kind: 'method-mismatch';
894
+ allowed: Method[];
895
+ } | {
896
+ kind: 'not-found';
897
+ };
898
+ declare const sortFlattenedRoutes: <T extends {
899
+ route: RouteDefinition;
900
+ }>(routes: T[]) => T[];
901
+ declare const matchRoute: (method: string, pathname: string, routes: Routes, basePath?: string) => MatchResult;
902
+ //#endregion
903
+ //#region src/route.d.ts
904
+ /**
905
+ * A route and the handler that answers it. The handler is stored without its
906
+ * argument types, so a config that lists routes never depends on what a handler
907
+ * reads back off that config.
908
+ */
909
+ type RouteWithHandler<Definition extends AuthoredRouteDefinition> = Definition & {
910
+ readonly [HANDLER]: RouteHandlerFunction;
911
+ };
912
+ /**
913
+ * What `k.route` returns: the route itself, and the `handler` that answers it.
914
+ * A route nothing serves, one a generator or a client reads, needs no handler.
915
+ */
916
+ type RouteBuilder<Definition extends AuthoredRouteDefinition, HandlerContext = unknown> = Definition & RouteHandlerStep<Definition, HandlerContext>;
917
+ interface RouteHandlerStep<Definition extends AuthoredRouteDefinition, HandlerContext> {
918
+ /**
919
+ * The handler that answers this route. `body`, `params`, `query` and
920
+ * `headers` are typed from the route, and the return is checked against its
921
+ * `responses`.
922
+ */
923
+ handler(fn: RouteHandler<Definition, HandlerContext>): RouteWithHandler<Definition>;
924
+ }
925
+ //#endregion
926
+ //#region src/raw-response.d.ts
927
+ declare const RAW_RESPONSE: unique symbol;
928
+ interface RawResponse {
929
+ readonly [RAW_RESPONSE]: true;
930
+ readonly response?: unknown;
931
+ }
932
+ /**
933
+ * Answer with a response kizuna will neither validate nor render. For plugin
934
+ * routes whose wire format is not JSON, such as MCP's JSON-RPC over
935
+ * server-sent events. Ordinary route handlers cannot reach it.
936
+ */
937
+ declare const rawResponse: (response?: unknown) => RawResponse;
938
+ declare const isRawResponse: (value: unknown) => value is RawResponse;
939
+ //#endregion
940
+ //#region src/groups.d.ts
941
+ interface GroupOptions {
942
+ /**
943
+ * The group's name in the docs. Unique among its siblings.
944
+ */
945
+ title: string;
946
+ /**
947
+ * Shown beside the group in the OpenAPI document.
948
+ */
949
+ description?: string;
950
+ /**
951
+ * External documentation for the group.
952
+ */
953
+ externalDocs?: {
954
+ url: string;
955
+ description?: string;
956
+ };
957
+ /**
958
+ * The groups nested under this one.
959
+ */
960
+ groups?: Record<string, GroupOptions | string>;
961
+ }
962
+ /**
963
+ * A declared group, with its place in the tree.
964
+ */
965
+ interface ResolvedGroup {
966
+ /**
967
+ * Its dotted path, `'workspace.members'`.
968
+ */
969
+ readonly path: string;
970
+ readonly title: string;
971
+ readonly description?: string;
972
+ readonly externalDocs?: GroupOptions['externalDocs'];
973
+ /**
974
+ * Dotted paths from the top group down to this one.
975
+ */
976
+ readonly lineage: readonly string[];
977
+ }
978
+ /**
979
+ * The groups from `k.groups`.
980
+ */
981
+ interface GroupSet<Declared extends Record<string, GroupOptions | string> = Record<string, GroupOptions | string>> {
982
+ readonly __brand: 'GroupSet';
983
+ /**
984
+ * The tree as written, for its type.
985
+ */
986
+ readonly declared: Declared;
987
+ /**
988
+ * Every group by dotted path, parents first.
989
+ */
990
+ readonly groups: ReadonlyMap<string, ResolvedGroup>;
991
+ }
992
+ /**
993
+ * Every dotted path a `k.groups` input declares.
994
+ */
995
+ type GroupPaths<Declared> = { [Key in Extract<keyof Declared, string>]: Key | (Declared[Key] extends {
996
+ groups: infer Nested;
997
+ } ? `${Key}.${GroupPaths<Nested>}` : never) }[Extract<keyof Declared, string>];
998
+ /**
999
+ * The dotted group paths a {@link GroupSet} declares.
1000
+ */
1001
+ type GroupPathsOf<Set extends GroupSet> = Set extends GroupSet<infer Declared> ? GroupPaths<Declared> : never;
1002
+ declare const isGroupSet: (value: unknown) => value is GroupSet;
1003
+ /**
1004
+ * Declare the groups routes are filed under. A string is shorthand for
1005
+ * `{ title }`.
1006
+ *
1007
+ * @example
1008
+ * const groups = k.groups({
1009
+ * workspace: {
1010
+ * title: 'Workspace',
1011
+ * groups: {
1012
+ * members: 'Members',
1013
+ * },
1014
+ * },
1015
+ * health: 'Health',
1016
+ * });
1017
+ */
1018
+ declare const createGroups: <const Declared extends Record<string, GroupOptions | string>>(declared: Declared) => GroupSet<Declared>;
1019
+ //#endregion
1020
+ //#region src/request-context.d.ts
1021
+ /**
1022
+ * A request context declaration from `k.requestContext`: the schema of a
1023
+ * request-scoped value every handler receives, and optionally the request
1024
+ * headers it derives from. The declaration carries its own `handler`, and
1025
+ * `defineConfig` names it under `requestContext`.
1026
+ */
1027
+ interface RequestContextSchema<ContextSchema extends z.ZodType = z.ZodType, HeadersSchema extends z.ZodType | undefined = z.ZodType | undefined> {
1028
+ readonly __brand: 'RequestContext';
1029
+ /**
1030
+ * Schema for the value the resolver returns and handlers receive.
1031
+ */
1032
+ readonly context: ContextSchema;
1033
+ /**
1034
+ * Schema for the request headers the value derives from. Clients type
1035
+ * against it: the generated fetch client takes the values once under
1036
+ * `requestContext`, and the Swift and Kotlin clients take them in their
1037
+ * initializers. Routes and the OpenAPI document are untouched.
1038
+ */
1039
+ readonly headers?: HeadersSchema;
1040
+ }
1041
+ interface RequestContextConfig<ContextSchema extends z.ZodType, HeadersSchema extends z.ZodType | undefined> {
1042
+ context: ContextSchema;
1043
+ headers?: HeadersSchema;
1044
+ }
1045
+ /**
1046
+ * The header inputs a client sends for a declaration: the `z.input` of its
1047
+ * `headers` schema, or nothing when the declaration has none.
1048
+ */
1049
+ type RequestContextHeaderInputs<Declaration> = Declaration extends {
1050
+ headers?: infer HeadersSchema;
1051
+ } ? [NonNullable<HeadersSchema>] extends [never] ? {} : NonNullable<HeadersSchema> extends z.ZodType ? z.input<NonNullable<HeadersSchema>> : {} : {};
1052
+ /**
1053
+ * The header values a resolver reads for a declaration: the `z.output` of its
1054
+ * `headers` schema, or the adapter's raw header record when it has none.
1055
+ */
1056
+ type RequestContextHeaderValues<Declaration> = Declaration extends {
1057
+ headers?: infer HeadersSchema;
1058
+ } ? [NonNullable<HeadersSchema>] extends [never] ? Record<string, string | string[] | undefined> : NonNullable<HeadersSchema> extends z.ZodType ? z.output<NonNullable<HeadersSchema>> : Record<string, string | string[] | undefined> : Record<string, string | string[] | undefined>;
1059
+ //#endregion
1060
+ //#region src/schedule.d.ts
1061
+ /**
1062
+ * A job's schedule: a five-field cron expression, or that expression together
1063
+ * with the IANA time zone its fields are read in.
1064
+ */
1065
+ type JobSchedule = string | {
1066
+ cron: string;
1067
+ /**
1068
+ * IANA time zone name, e.g. `'Europe/Oslo'`. Omitted means UTC.
1069
+ */
1070
+ timezone?: string;
1071
+ };
1072
+ /**
1073
+ * The cron expression of a {@link JobSchedule}, whichever form it was written in.
1074
+ */
1075
+ declare const scheduleExpression: (schedule: JobSchedule) => string;
1076
+ /**
1077
+ * The time zone of a {@link JobSchedule}, or `undefined` for UTC.
1078
+ */
1079
+ declare const scheduleTimezone: (schedule: JobSchedule) => string | undefined;
1080
+ declare const DAY_NAMES: Readonly<Record<string, number>>;
1081
+ /**
1082
+ * A cron expression resolved to the set of values each field permits.
1083
+ */
1084
+ interface ParsedCron {
1085
+ minutes: ReadonlySet<number>;
1086
+ hours: ReadonlySet<number>;
1087
+ daysOfMonth: ReadonlySet<number>;
1088
+ months: ReadonlySet<number>;
1089
+ daysOfWeek: ReadonlySet<number>;
1090
+ /**
1091
+ * Whether the day-of-month field was narrowed from `*`. When both day fields
1092
+ * are narrowed, a run happens on a day matching *either* of them, the Vixie
1093
+ * cron rule.
1094
+ */
1095
+ dayOfMonthRestricted: boolean;
1096
+ /**
1097
+ * Whether the day-of-week field was narrowed from `*`. See
1098
+ * {@link ParsedCron.dayOfMonthRestricted}.
1099
+ */
1100
+ dayOfWeekRestricted: boolean;
1101
+ timezone: string | undefined;
1102
+ }
1103
+ /**
1104
+ * Parse a five-field cron expression into the values each field permits.
1105
+ * Throws with the offending field named.
1106
+ *
1107
+ * @example
1108
+ * parseCron('0 5 * * *').hours; // Set { 5 }
1109
+ */
1110
+ declare const parseCron: (schedule: JobSchedule) => ParsedCron;
1111
+ /**
1112
+ * Throws when a job's schedule is not a valid cron expression, naming the job.
1113
+ * Called by `k.jobs` so a bad schedule fails when the api is built rather
1114
+ * than when the scheduler first fires.
1115
+ */
1116
+ declare const assertValidSchedule: (schedule: JobSchedule, jobName: string) => void;
1117
+ /**
1118
+ * The first time at or after `from` that `schedule` fires, exclusive of `from`
1119
+ * itself. Returns `undefined` for a schedule that names a date which never
1120
+ * occurs, such as February 30th.
1121
+ *
1122
+ * @example
1123
+ * nextRun('0 5 * * *', new Date('2026-08-05T06:00:00Z'));
1124
+ * // 2026-08-06T05:00:00Z
1125
+ */
1126
+ declare const nextRun: (schedule: JobSchedule, from?: Date) => Date | undefined;
1127
+ /**
1128
+ * The next `count` times a schedule fires after `from`. Stops early when the
1129
+ * schedule names a date that never occurs.
1130
+ */
1131
+ declare const nextRuns: (schedule: JobSchedule, count: number, from?: Date) => Date[];
1132
+ /**
1133
+ * Whether a schedule fires in the half-open window `(after, at]`.
1134
+ */
1135
+ declare const firesBetween: (schedule: JobSchedule, after: Date, at: Date) => boolean;
1136
+ /**
1137
+ * The schedules due as of `at`, keyed as they were passed in.
1138
+ *
1139
+ * @example
1140
+ * const due = dueSchedules(
1141
+ * Object.fromEntries(Object.entries(kizuna.api.jobs ?? {}).map(([name, job]) => [name, job.schedule]))
1142
+ * );
1143
+ */
1144
+ declare const dueSchedules: (schedules: Record<string, JobSchedule>, options?: {
1145
+ at?: Date;
1146
+ /**
1147
+ * How far back a tick looks. Widen it when the platform's delivery is
1148
+ * less punctual than its cron expression suggests.
1149
+ *
1150
+ * @default 60000
1151
+ */
1152
+ windowMs?: number;
1153
+ }) => string[];
1154
+ /**
1155
+ * Builders for a five-field cron expression, for a `schedule` you would rather
1156
+ * read than decode. Each returns a plain cron string.
1157
+ *
1158
+ * @example
1159
+ * schedule: cron.daily('05:00');
1160
+ */
1161
+ declare const cron: {
1162
+ every: (interval: string) => string;
1163
+ hourly: (minute?: number) => string;
1164
+ daily: (time: string) => string;
1165
+ weekly: (day: keyof typeof DAY_NAMES, time: string) => string;
1166
+ monthly: (dayOfMonth: number, time: string) => string;
1167
+ };
1168
+ //#endregion
1169
+ //#region src/job-transport.d.ts
1170
+ /**
1171
+ * One job, ready to deliver. The input is already validated, so a transport
1172
+ * never looks at a schema.
1173
+ */
1174
+ interface JobMessage {
1175
+ /**
1176
+ * The job's dotted key, e.g. `billing.reconcileInvoices`. It is how the
1177
+ * message is addressed: a job has no URL of its own.
1178
+ */
1179
+ job: string;
1180
+ /**
1181
+ * The validated input, or `undefined` when the job declares none. JSON-safe.
1182
+ */
1183
+ input: unknown;
1184
+ /**
1185
+ * Hold delivery until this time.
1186
+ */
1187
+ runAt?: Date;
1188
+ /**
1189
+ * Deliver at most one message carrying this key.
1190
+ */
1191
+ dedupeKey?: string;
1192
+ /**
1193
+ * How many attempts the job declared. Backoff is the transport's own.
1194
+ */
1195
+ retry?: number;
1196
+ }
1197
+ /**
1198
+ * What a transport honours. `defineConfig` warns when a job asks for something
1199
+ * left out.
1200
+ */
1201
+ interface JobTransportSupports {
1202
+ retry?: boolean;
1203
+ dedupe?: boolean;
1204
+ runAt?: boolean;
1205
+ }
1206
+ interface JobDescriptor {
1207
+ /**
1208
+ * The job's dotted key.
1209
+ */
1210
+ job: string;
1211
+ }
1212
+ interface ScheduledJob extends JobDescriptor {
1213
+ /**
1214
+ * A five-field cron expression.
1215
+ */
1216
+ cron: string;
1217
+ /**
1218
+ * IANA time zone the expression is read in, or `undefined` for UTC.
1219
+ */
1220
+ timezone: string | undefined;
1221
+ }
1222
+ interface JobWorker {
1223
+ stop: () => Promise<void> | void;
1224
+ }
1225
+ interface JobWorkerContext {
1226
+ /**
1227
+ * Every job the api declares, to subscribe by name.
1228
+ */
1229
+ jobs: readonly JobDescriptor[];
1230
+ /**
1231
+ * Run one message through the same handler a route would reach. Let its
1232
+ * rejection propagate: that is how the transport learns to retry.
1233
+ */
1234
+ run: (message: JobMessage) => Promise<void>;
1235
+ }
1236
+ interface JobTransportDefinition {
1237
+ name: string;
1238
+ supports?: JobTransportSupports;
1239
+ /**
1240
+ * Deliver one job. Resolve once the message is handed over, not once the job
1241
+ * has run; reject when it could not be handed over at all.
1242
+ */
1243
+ dispatch: (message: JobMessage) => Promise<void> | void;
1244
+ /**
1245
+ * Drain stored work, for a transport that is pulled rather than pushed.
1246
+ */
1247
+ start?: (context: JobWorkerContext) => Promise<JobWorker>;
1248
+ /**
1249
+ * Take scheduling over, for a transport with a scheduler of its own.
1250
+ * `startJobs` then hands the schedules across instead of ticking them.
1251
+ */
1252
+ register?: (schedules: readonly ScheduledJob[]) => Promise<void> | void;
1253
+ }
1254
+ interface JobTransport extends JobTransportDefinition {
1255
+ readonly supports: JobTransportSupports;
1256
+ }
1257
+ declare class JobDispatchError extends Error {
1258
+ readonly transport: string;
1259
+ readonly job: string;
1260
+ constructor(transport: string, job: string, cause: unknown);
1261
+ }
1262
+ /**
1263
+ * Define a transport: what carries a queued job to whatever runs it.
1264
+ *
1265
+ * @example
1266
+ * export const pgBoss = (boss: PgBoss) =>
1267
+ * defineJobTransport({
1268
+ * name: 'pg-boss',
1269
+ * supports: {
1270
+ * retry: true,
1271
+ * dedupe: true,
1272
+ * runAt: true,
1273
+ * },
1274
+ * dispatch: async (message) => {
1275
+ * await boss.send(message.job, message.input ?? {}, {
1276
+ * startAfter: message.runAt,
1277
+ * singletonKey: message.dedupeKey,
1278
+ * retryLimit: message.retry,
1279
+ * });
1280
+ * },
1281
+ * start: async ({ jobs, run }) => {
1282
+ * for (const { job } of jobs) {
1283
+ * await boss.work(job, async ([queued]) => {
1284
+ * await run({
1285
+ * job,
1286
+ * input: queued.data,
1287
+ * });
1288
+ * });
1289
+ * }
1290
+ * return {
1291
+ * stop: () => boss.stop(),
1292
+ * };
1293
+ * },
1294
+ * });
1295
+ */
1296
+ declare const defineJobTransport: (definition: JobTransportDefinition) => JobTransport;
1297
+ //#endregion
1298
+ //#region src/job-runner.d.ts
1299
+ /**
1300
+ * The arguments a job takes when run in code: its input when it declares one,
1301
+ * nothing otherwise.
1302
+ */
1303
+ type JobRunArgs<Job extends CompiledJob> = Job['definition'] extends {
1304
+ input: z.ZodType;
1305
+ } ? [input: z.input<Job['definition']['input']>] : [];
1306
+ /**
1307
+ * What `queue` takes: the job's input when it declares one, alongside how the
1308
+ * message should be delivered.
1309
+ */
1310
+ type JobQueueArgs<Job extends CompiledJob> = Job['definition'] extends {
1311
+ input: z.ZodType;
1312
+ } ? [message: {
1313
+ input: z.input<Job['definition']['input']>;
1314
+ } & JobQueueOptions] : [message?: JobQueueOptions];
1315
+ interface JobQueueOptions {
1316
+ /**
1317
+ * Hold the job until this time. Honoured by transports declaring
1318
+ * `supports.runAt`.
1319
+ */
1320
+ runAt?: Date;
1321
+ /**
1322
+ * Run this at most once, however many times it is queued. Honoured by
1323
+ * transports declaring `supports.dedupe`.
1324
+ */
1325
+ dedupeKey?: string;
1326
+ }
1327
+ /**
1328
+ * One job, reachable two ways.
1329
+ */
1330
+ interface JobFn<Job extends CompiledJob> {
1331
+ /**
1332
+ * Run the job now and resolve to what its handler returned.
1333
+ */
1334
+ run: (...args: JobRunArgs<Job>) => Promise<JobHandlerReturn<Job['definition']>>;
1335
+ /**
1336
+ * Put the job in line and answer without waiting for it. With no transport
1337
+ * configured the job runs in this process and is lost on a crash.
1338
+ */
1339
+ queue: (...args: JobQueueArgs<Job>) => Promise<void>;
1340
+ }
1341
+ /**
1342
+ * An api's jobs, shaped exactly like the declaration.
1343
+ *
1344
+ * @example
1345
+ * await jobs.billing.reconcileInvoices.run({ since });
1346
+ * await jobs.indexUser.queue({
1347
+ * input: {
1348
+ * userId,
1349
+ * },
1350
+ * });
1351
+ */
1352
+ type JobRunner<Jobs_ extends Jobs> = { [Name in keyof Jobs_]: Jobs_[Name] extends CompiledJob ? JobFn<Jobs_[Name]> : Jobs_[Name] extends Jobs ? JobRunner<Jobs_[Name]> : never };
1353
+ declare class JobInputError extends Error {
1354
+ readonly job: string;
1355
+ readonly issues: z.core.$ZodIssue[];
1356
+ constructor(job: string, issues: z.core.$ZodIssue[]);
1357
+ }
1358
+ /**
1359
+ * Called when a job queued without a transport rejects. Without one, the
1360
+ * failure is logged.
1361
+ */
1362
+ type JobErrorHandler = (job: string, error: unknown) => void;
1363
+ interface JobRunnerOptions {
1364
+ /**
1365
+ * Carries a queued job to whatever runs it. Without one, `queue` runs the job
1366
+ * in this process without waiting for it.
1367
+ */
1368
+ transport?: JobTransport;
1369
+ onError?: JobErrorHandler;
1370
+ /**
1371
+ * What each plugin exports, handed to every job handler as `plugins`.
1372
+ */
1373
+ plugins?: Record<string, unknown>;
1374
+ }
1375
+ /**
1376
+ * A job's `run` and `queue` reached by dotted key. Untyped, because a caller
1377
+ * holding a key does not know it statically.
1378
+ */
1379
+ interface JobFnByKey {
1380
+ run: (input?: unknown) => Promise<unknown>;
1381
+ queue: (message?: JobQueueOptions & {
1382
+ input?: unknown;
1383
+ }) => Promise<void>;
1384
+ }
1385
+ /**
1386
+ * Walk a {@link JobRunner} tree to the pair for one dotted key.
1387
+ */
1388
+ declare const jobFnAt: (runner: unknown, jobKey: string) => JobFnByKey | undefined;
1389
+ /**
1390
+ * Pair a job tree with the handlers that run it, so the jobs can be run from
1391
+ * anywhere. `defineConfig` builds one from the handlers each job carries, and
1392
+ * every route and job handler receives it as `jobs`.
1393
+ *
1394
+ * @example
1395
+ * const jobs = createJobRunner(jobTree, handlers);
1396
+ *
1397
+ * await jobs.billing.reconcileInvoices.run({ since: '2026-08-01' });
1398
+ * await jobs.indexUser.queue({
1399
+ * input: {
1400
+ * userId: user.id,
1401
+ * },
1402
+ * });
1403
+ */
1404
+ declare const createJobRunner: <Jobs_ extends Jobs>(source: Jobs_ | {
1405
+ jobs?: Jobs_;
1406
+ }, handlers: JobHandlers<Jobs_>, options?: JobRunnerOptions) => JobRunner<Jobs_>;
1407
+ //#endregion
1408
+ //#region src/jobs.d.ts
1409
+ /**
1410
+ * Settings shared by every job, named in `defineConfig` under `jobRunner`. The jobs
1411
+ * themselves are declared with `k.jobs`.
1412
+ */
1413
+ type JobsConfig = HttpJobsConfig | InProcessJobsConfig;
1414
+ /**
1415
+ * Jobs triggered over HTTP, by platform cron ticking `/jobs/dispatch` or a
1416
+ * transport delivering to `/jobs/run`.
1417
+ */
1418
+ interface HttpJobsConfig {
1419
+ /**
1420
+ * `'http'` serves `/jobs/dispatch` and `/jobs/run`, guarded by the jobs'
1421
+ * identity. `'in-process'` is for a long-running server whose schedules
1422
+ * `startJobs` ticks, and serves neither.
1423
+ */
1424
+ mode: 'http';
1425
+ /**
1426
+ * The namespace both job endpoints are mounted under, `dispatch` and `run`
1427
+ * beneath it. Nothing is served on the namespace itself.
1428
+ *
1429
+ * @default '/jobs'
1430
+ */
1431
+ path?: `/${string}`;
1432
+ /**
1433
+ * `GET` instead of `POST`. Vercel Cron sends `GET` and nothing else.
1434
+ *
1435
+ * @default 'POST'
1436
+ */
1437
+ method?: 'POST' | 'GET';
1438
+ /**
1439
+ * How far back a tick looks for due jobs. Widen it when the scheduler
1440
+ * delivers late.
1441
+ *
1442
+ * @default 60000
1443
+ */
1444
+ windowMs?: number;
1445
+ /**
1446
+ * Dispatch only these jobs.
1447
+ */
1448
+ only?: readonly string[];
1449
+ /**
1450
+ * Never dispatch these.
1451
+ */
1452
+ exclude?: readonly string[];
1453
+ }
1454
+ /**
1455
+ * Jobs a long-running server runs itself, its schedules ticked by `startJobs`.
1456
+ * No job endpoint is served, so the jobs need no identity.
1457
+ */
1458
+ interface InProcessJobsConfig {
1459
+ mode: 'in-process';
1460
+ path?: never;
1461
+ method?: never;
1462
+ windowMs?: never;
1463
+ only?: never;
1464
+ exclude?: never;
1465
+ }
1466
+ /**
1467
+ * How a deployment runs the jobs it declares: how they are triggered, what
1468
+ * carries queued work out of the process, and where a failure that happened
1469
+ * after the response went out is reported.
1470
+ */
1471
+ type JobRunnerConfig = JobsConfig & JobDeliveryConfig;
1472
+ /**
1473
+ * Where queued work goes and where a late failure is reported, whichever way
1474
+ * the jobs are triggered.
1475
+ */
1476
+ interface JobDeliveryConfig {
1477
+ /**
1478
+ * Carries a queued job to whatever runs it. Without one, `queue` runs the
1479
+ * job in this process and it is lost on a crash.
1480
+ */
1481
+ transport?: JobTransport;
1482
+ /**
1483
+ * Reached when a job fails after its response was sent, which is the only
1484
+ * point where nothing else can report it.
1485
+ */
1486
+ onError?: JobErrorHandler;
1487
+ }
1488
+ /**
1489
+ * A scheduled job, as authored in `k.jobs`.
1490
+ */
1491
+ interface JobDefinition {
1492
+ /**
1493
+ * A five-field cron expression, or `{ cron, timezone }`. Validated when the
1494
+ * contract is built. Omit it for a job that is only ever queued from code.
1495
+ */
1496
+ schedule?: JobSchedule;
1497
+ /**
1498
+ * How many attempts a failed run deserves. Handed to the transport, which is
1499
+ * what retries.
1500
+ *
1501
+ * @default 1
1502
+ */
1503
+ retry?: number;
1504
+ summary?: string;
1505
+ description?: string;
1506
+ /**
1507
+ * Schema for the payload the job is queued with.
1508
+ */
1509
+ input?: z.ZodType;
1510
+ /**
1511
+ * Schema for what the job reports on success. Omit it and the job answers
1512
+ * `204`.
1513
+ */
1514
+ result?: z.ZodType;
1515
+ /**
1516
+ * Extra responses beyond the synthesized `200`/`204`, `422`, `500`, `503`.
1517
+ */
1518
+ responses?: {
1519
+ [status: number]: Exclude<ResponseDefinition, StreamResponseDefinition>;
1520
+ };
1521
+ /**
1522
+ * The handler that runs this job. Attach it with `k.job(...).handler(...)`,
1523
+ * which types `input` from this job and checks the return against `result`.
1524
+ */
1525
+ handler?: (args: never) => unknown;
1526
+ }
1527
+ /**
1528
+ * A job as authored in `k.job`.
1529
+ */
1530
+ type AuthoredJobDefinition = JobDefinition;
1531
+ /**
1532
+ * A job's synthesized responses. These are the retry contract: `503` asks for a
1533
+ * retry, `422` says the failure is permanent.
1534
+ */
1535
+ type JobResponses<Definition extends JobDefinition> = (Definition extends {
1536
+ result: z.ZodType;
1537
+ } ? {
1538
+ 200: Definition['result'];
1539
+ } : {
1540
+ 204: z.ZodVoid;
1541
+ }) & {
1542
+ 422: typeof ProblemDetailsSchema;
1543
+ 500: typeof ProblemDetailsSchema;
1544
+ 503: typeof ProblemDetailsSchema;
1545
+ };
1546
+ /**
1547
+ * A job after `k.jobs` compiles it.
1548
+ */
1549
+ interface CompiledJob<Definition extends JobDefinition = JobDefinition, IdentityName extends string | undefined = string | undefined> {
1550
+ definition: Definition;
1551
+ schedule: JobSchedule | undefined;
1552
+ /**
1553
+ * The identity every job in the group requires, or `undefined` when the group
1554
+ * was declared without one. It guards the dispatch endpoint.
1555
+ */
1556
+ identity: IdentityName;
1557
+ /**
1558
+ * The payload schema, or `undefined` when the job takes none.
1559
+ */
1560
+ input: z.ZodType | undefined;
1561
+ responses: JobResponses<Definition>;
1562
+ }
1563
+ /**
1564
+ * An api's jobs. Nestable, like routes, so a large codebase can group them ,
1565
+ * `jobs.billing.reconcileInvoices`.
1566
+ */
1567
+ interface Jobs {
1568
+ [key: string]: CompiledJob | Jobs;
1569
+ }
1570
+ /**
1571
+ * The compiled form of an authored job tree, preserving its shape.
1572
+ */
1573
+ type CompiledJobs<Definitions extends AuthoredJobs, IdentityName extends string | undefined> = { [Name in keyof Definitions]: Definitions[Name] extends JobDefinition ? CompiledJob<Definitions[Name], IdentityName> : Definitions[Name] extends AuthoredJobs ? CompiledJobs<Definitions[Name], IdentityName> : never };
1574
+ /**
1575
+ * The shape `k.jobs` accepts: jobs, or groups of them, to any depth.
1576
+ */
1577
+ interface AuthoredJobs {
1578
+ [key: string]: JobDefinition | AuthoredJobs;
1579
+ }
1580
+ type JobHandlerReturn<Definition extends JobDefinition> = HandlerReturn<{
1581
+ responses: JobResponses<Definition>;
1582
+ }>;
1583
+ /**
1584
+ * The input and `throwError` every job handler receives. It also receives the
1585
+ * api's `jobs` and, when the config installs any, the plugins' exports as
1586
+ * `plugins`.
1587
+ */
1588
+ type JobHandlerArgs<Definition extends JobDefinition> = {
1589
+ /**
1590
+ * The validated payload, or `undefined` when the job declares no `input`.
1591
+ */
1592
+ input: Definition extends {
1593
+ input: z.ZodType;
1594
+ } ? z.output<Definition['input']> : undefined;
1595
+ /**
1596
+ * Throws a typed response. Takes the same `{ status, body }` shape as a
1597
+ * handler return.
1598
+ *
1599
+ * This function throws internally and never returns.
1600
+ */
1601
+ throwError: (response: JobHandlerReturn<Definition>) => never;
1602
+ };
1603
+ /**
1604
+ * A job declaring no `result` has only `204` to answer, so it may return nothing
1605
+ * at all.
1606
+ */
1607
+ type JobVoidReturn<Definition extends JobDefinition> = Definition extends {
1608
+ result: z.ZodType;
1609
+ } ? never : void;
1610
+ type JobHandler<Job extends CompiledJob, Jobs_ extends Jobs = Jobs> = (args: JobHandlerArgs<Job['definition']> & JobsArg<Jobs_>) => Promise<JobHandlerReturn<Job['definition']> | JobVoidReturn<Job['definition']>> | JobHandlerReturn<Job['definition']> | JobVoidReturn<Job['definition']>;
1611
+ /**
1612
+ * The `jobs` argument every handler receives: the api's jobs bound to their
1613
+ * handlers, so one can be run in process. Absent when the api declares none.
1614
+ */
1615
+ type JobsArg<Jobs_ extends Jobs> = string extends keyof Jobs_ ? {} : {
1616
+ jobs: JobRunner<Jobs_>;
1617
+ };
1618
+ /**
1619
+ * A job tree with no jobs in it, for an api that declares none.
1620
+ */
1621
+ type NoJobs = Record<string, never>;
1622
+ /**
1623
+ * The handler each declared job carries, keyed by name.
1624
+ */
1625
+ type JobHandlers<Jobs_ extends Jobs, Root extends Jobs = Jobs_> = { [Name in keyof Jobs_]: Jobs_[Name] extends CompiledJob ? JobHandler<Jobs_[Name], Root> : Jobs_[Name] extends Jobs ? JobHandlers<Jobs_[Name], Root> : never };
1626
+ /**
1627
+ * Whether a node in an authored tree is a job rather than a group of them.
1628
+ */
1629
+ declare const isJobDefinition: (value: unknown) => value is JobDefinition;
1630
+ interface FlattenedJob {
1631
+ /**
1632
+ * Dotted path to the job, e.g. `billing.reconcileInvoices`. It is how every
1633
+ * other part of the system names a job.
1634
+ */
1635
+ jobKey: string;
1636
+ job: CompiledJob;
1637
+ }
1638
+ /**
1639
+ * Every job in a tree, with its dotted key.
1640
+ */
1641
+ declare const flattenJobs: (jobs: Jobs, prefix?: string) => FlattenedJob[];
1642
+ /**
1643
+ * The job at a dotted key, or `undefined`.
1644
+ */
1645
+ declare const jobAt: (jobs: Jobs, jobKey: string) => CompiledJob | undefined;
1646
+ declare const isCompiledJob: (value: unknown) => value is CompiledJob;
1647
+ //#endregion
1648
+ //#region src/api-definition.d.ts
1649
+ /**
1650
+ * A kizuna API definition: its routes plus groups, identities, and validation
1651
+ * settings. Produced by `defineConfig` and consumed by the server adapters,
1652
+ * fetch client, OpenAPI generator, and SDK generators.
1653
+ */
1654
+ interface ApiDefinition<Routes_ extends Routes = Routes, Groups extends Record<string, GroupOptions | string> = Record<string, GroupOptions | string>, Codes extends string = string, Schemes extends Record<string, SecurityScheme> = Record<string, SecurityScheme>, RequestContext extends Record<string, RequestContextSchema> = Record<string, RequestContextSchema>, Plugins extends ApiPlugins = ApiPlugins, Jobs_ extends Jobs = Jobs, GuardSchema extends z.ZodType | undefined = z.ZodType | undefined> {
1655
+ /**
1656
+ * The API's route groups.
1657
+ */
1658
+ routes: Routes_;
1659
+ /**
1660
+ * The body every guard's `deny()` produces, named in `defineConfig` under
1661
+ * `guardSchema`. Each guarded route's `401` and `403` carry it in place of
1662
+ * bare Problem Details.
1663
+ */
1664
+ guardSchema?: GuardSchema;
1665
+ /**
1666
+ * The plugins installed on `defineConfig`. Their routes are served by
1667
+ * `api.mount` but stay outside `routes`, so the client and the generators
1668
+ * do not see them.
1669
+ */
1670
+ plugins?: Plugins;
1671
+ /**
1672
+ * The scheduled jobs declared with `k.jobs`, keyed by name.
1673
+ */
1674
+ jobs?: Jobs_;
1675
+ /**
1676
+ * The job settings named in `defineConfig` under `jobRunner`.
1677
+ */
1678
+ jobsConfig?: JobsConfig;
1679
+ /**
1680
+ * The groups declared with `k.groups`.
1681
+ */
1682
+ groups?: GroupSet<Groups>;
1683
+ /**
1684
+ * The identities named in `defineConfig`. A route's `auth` names them,
1685
+ * `defineConfig` writes each route's `security` from it, and the
1686
+ * OpenAPI generator emits them under `components.securitySchemes`.
1687
+ */
1688
+ securitySchemes?: Schemes;
1689
+ /**
1690
+ * The request context schemas named in `defineConfig`. Each key names a
1691
+ * provider registered on `defineConfig`; every handler receives its value.
1692
+ * Never gates a request and never appears in the OpenAPI document.
1693
+ */
1694
+ requestContext?: RequestContext;
1695
+ /**
1696
+ * Validation behavior for the API.
1697
+ */
1698
+ validation?: {
1699
+ /**
1700
+ * Custom validation issue codes this API's handlers may emit.
1701
+ */
1702
+ issueCodes?: readonly Codes[];
1703
+ };
1704
+ }
1705
+ /**
1706
+ * An api's route groups.
1707
+ */
1708
+ type RoutesOf<C extends ApiDefinition> = C['routes'];
1709
+ /**
1710
+ * An api's identities, or an empty map when it declares none.
1711
+ */
1712
+ type SchemesOf<C extends ApiDefinition> = Exclude<C['securitySchemes'], undefined>;
1713
+ /**
1714
+ * An api's request context schemas, or an empty map when it declares none.
1715
+ */
1716
+ type RequestContextOf<C extends ApiDefinition> = Exclude<C['requestContext'], undefined>;
1717
+ /**
1718
+ * An api's plugins, or an empty map when it declares none.
1719
+ */
1720
+ type ApiPluginsOf<C extends ApiDefinition> = Exclude<C['plugins'], undefined>;
1721
+ /**
1722
+ * An api's jobs, or an empty map when it declares none.
1723
+ */
1724
+ type JobsOf<C extends ApiDefinition> = Exclude<C['jobs'], undefined>;
1725
+ type GuardSchemaOf<C extends ApiDefinition> = Extract<C['guardSchema'], z.ZodType>;
1726
+ //#endregion
1727
+ //#region src/config.d.ts
1728
+ /**
1729
+ * A file `kizuna generate` writes and `--check` compares, made by a client's
1730
+ * factory, a generator's, or kizuna itself.
1731
+ *
1732
+ * @example
1733
+ * swiftClient({
1734
+ * output: './Sources/APIClient/APIClient.swift',
1735
+ * });
1736
+ */
1737
+ interface GeneratedFile {
1738
+ /**
1739
+ * The language a client generates, like `swift`. A generator has none.
1740
+ */
1741
+ readonly target?: string;
1742
+ /**
1743
+ * Path the file is written to, resolved against the config's directory.
1744
+ */
1745
+ readonly output: string;
1746
+ /**
1747
+ * Renders the file's contents.
1748
+ */
1749
+ readonly render: (api: ApiDefinition) => string;
1750
+ }
1751
+ /**
1752
+ * What else `kizuna diff` treats as breaking.
1753
+ */
1754
+ interface DiffSettings {
1755
+ /**
1756
+ * Report a renamed dotted key, such as `users.getUser` becoming
1757
+ * `users.fetchUser`, as breaking. The key names the method on a generated
1758
+ * client, so a rename breaks anyone shipping one as an SDK and leaves the
1759
+ * HTTP surface untouched.
1760
+ *
1761
+ * @default false
1762
+ */
1763
+ dottedKeys?: boolean;
1764
+ /**
1765
+ * Report a job key that is gone. A job answers `POST /jobs/run` by its
1766
+ * dotted key, so this matters once something outside your own code
1767
+ * dispatches them.
1768
+ *
1769
+ * @default false
1770
+ */
1771
+ jobs?: boolean;
1772
+ /**
1773
+ * Report an MCP tool a model can no longer call.
1774
+ *
1775
+ * @default false
1776
+ */
1777
+ tools?: boolean;
1778
+ }
1779
+ /**
1780
+ * What `kizuna.config.ts` default-exports: the api its config assembles, and
1781
+ * what is generated from it.
1782
+ */
1783
+ interface ApiEntry {
1784
+ api: ApiDefinition;
1785
+ clients?: readonly GeneratedFile[];
1786
+ /**
1787
+ * The files the config's plugins generate.
1788
+ */
1789
+ generators?: readonly GeneratedFile[];
1790
+ /**
1791
+ * Where `kizuna generate` writes the `Config`.
1792
+ */
1793
+ typescript?: {
1794
+ outputFile?: string;
1795
+ };
1796
+ /**
1797
+ * What else `kizuna diff` treats as breaking.
1798
+ */
1799
+ diff?: DiffSettings;
1800
+ }
1801
+ /**
1802
+ * The config a `kizuna.config.ts` module default-exports. A repository serving
1803
+ * several APIs writes a config file for each.
1804
+ */
1805
+ declare const apiEntries: (module: Record<string, unknown>) => [string, ApiEntry][];
1806
+ //#endregion
1807
+ //#region src/configured.d.ts
1808
+ /**
1809
+ * What one API is made of, written by `kizuna generate` and handed to
1810
+ * `new Kizuna<Config>()`. Everything a handler receives beyond its own inputs,
1811
+ * and every name kizuna checks a route against, is read from it.
1812
+ *
1813
+ * @example
1814
+ * ```ts
1815
+ * // src/kizuna.types.ts, generated
1816
+ * export interface Config {
1817
+ * adapter: ReturnType<typeof expressAdapter>;
1818
+ * groups: typeof groups;
1819
+ * auth: { identities: { user: typeof user } };
1820
+ * jobs: typeof jobs;
1821
+ * }
1822
+ * ```
1823
+ */
1824
+ interface KizunaConfigShape {
1825
+ adapter?: unknown;
1826
+ groups?: unknown;
1827
+ auth?: {
1828
+ identities?: unknown;
1829
+ guardSchema?: unknown;
1830
+ };
1831
+ requestContext?: unknown;
1832
+ validation?: {
1833
+ issueCodes?: string;
1834
+ };
1835
+ jobs?: unknown;
1836
+ plugins?: unknown;
1837
+ }
1838
+ /**
1839
+ * One job, as a handler reaches it.
1840
+ */
1841
+ interface JobFnOf<Definition extends AuthoredJobDefinition> {
1842
+ /**
1843
+ * Run the job now and resolve to what its handler returned.
1844
+ */
1845
+ run: Definition extends {
1846
+ input: z.ZodType;
1847
+ } ? (input: z.input<Definition['input']>) => Promise<JobHandlerReturn<Definition>> : () => Promise<JobHandlerReturn<Definition>>;
1848
+ /**
1849
+ * Put the job in line and answer without waiting for it.
1850
+ */
1851
+ queue: Definition extends {
1852
+ input: z.ZodType;
1853
+ } ? (message: {
1854
+ input: z.input<Definition['input']>;
1855
+ } & JobQueueOptions) => Promise<void> : (message?: JobQueueOptions) => Promise<void>;
1856
+ }
1857
+ /**
1858
+ * A tree of jobs, as a handler reaches them.
1859
+ */
1860
+ type JobsOfTree<Tree> = { [Key in keyof Tree]: Tree[Key] extends {
1861
+ definition: infer Definition extends AuthoredJobDefinition;
1862
+ } ? JobFnOf<Definition> : JobsOfTree<Tree[Key]> };
1863
+ /**
1864
+ * The groups a config declares, or none.
1865
+ */
1866
+ type ConfiguredGroups<Config> = Config extends {
1867
+ groups: GroupSet<infer Groups extends Record<string, GroupOptions | string>>;
1868
+ } ? Groups : {};
1869
+ type ConfiguredCodes<Config> = Config extends {
1870
+ validation: {
1871
+ issueCodes: infer Codes extends string;
1872
+ };
1873
+ } ? Codes : never;
1874
+ type ConfiguredIdentities<Config> = Config extends {
1875
+ auth: {
1876
+ identities: infer Identities extends Record<string, SecurityScheme>;
1877
+ };
1878
+ } ? Identities : Record<string, never>;
1879
+ type ConfiguredRequestContextSchemas<Config> = Config extends {
1880
+ requestContext: infer Declarations extends Record<string, RequestContextSchema>;
1881
+ } ? Declarations : Record<string, never>;
1882
+ type ConfiguredGuardSchema<Config> = Config extends {
1883
+ auth: {
1884
+ guardSchema: infer Schema extends z.ZodType;
1885
+ };
1886
+ } ? Schema : undefined;
1887
+ type ConfiguredAdapterValue<Config> = Config extends {
1888
+ adapter: infer Adapter extends AnyAdapter;
1889
+ } ? Adapter : undefined;
1890
+ type ConfiguredJobs<Config> = Config extends {
1891
+ jobs: infer Tree;
1892
+ } ? {
1893
+ jobs: JobsOfTree<Tree>;
1894
+ } : {};
1895
+ type ConfiguredPlugins<Config> = Config extends {
1896
+ plugins: infer Plugins extends PluginList;
1897
+ } ? PluginArgs<PluginsBySlug<Plugins>> : {};
1898
+ /**
1899
+ * The api's jobs and plugins, for a plugin that runs the app's own functions.
1900
+ */
1901
+ type ApiContext<Config> = ConfiguredJobs<Config> & ConfiguredPlugins<Config>;
1902
+ type ConfiguredAdapterContext<Config> = HandlerContextOf<ConfiguredAdapterValue<Config>>;
1903
+ type ConfiguredRequestContext<Config> = RequestContextValues<ConfiguredRequestContextSchemas<Config>>;
1904
+ //#endregion
1905
+ //#region src/plugin.d.ts
1906
+ declare const PLUGIN_ROUTES_META_KEY: unique symbol;
1907
+ declare const PLUGIN_SERVERS_META_KEY: unique symbol;
1908
+ /**
1909
+ * The routes a plugin serves, keyed by name. Each carries its handler, declared
1910
+ * with {@link route}.
1911
+ */
1912
+ type PluginRoutes = Record<string, RouteDefinition>;
1913
+ /**
1914
+ * What a plugin's `setup` returns. Every key is optional, and everything in it
1915
+ * shares whatever `setup` created.
1916
+ */
1917
+ interface PluginSetup {
1918
+ /**
1919
+ * Functions every route and job handler reaches at `plugins.<slug>`.
1920
+ */
1921
+ exports?: unknown;
1922
+ /**
1923
+ * Routes an outside system calls, like a webhook or a status check.
1924
+ */
1925
+ routes?: PluginRoutes;
1926
+ /**
1927
+ * Files `kizuna generate` writes, built with `defineGenerator`.
1928
+ */
1929
+ generators?: readonly GeneratedFile[];
1930
+ /**
1931
+ * Runs once the config has assembled, with the api available. Throw to stop
1932
+ * the app starting, for a check that needs the app's routes or identities.
1933
+ */
1934
+ validate?: () => void;
1935
+ }
1936
+ /**
1937
+ * The assembled api, as a plugin's handlers read it. It exists once the config
1938
+ * has assembled, so read it inside a handler, never in `setup` itself.
1939
+ */
1940
+ type PluginApi = Record<string | symbol, unknown> & {
1941
+ readonly routes: Routes;
1942
+ };
1943
+ /**
1944
+ * What `setup` receives.
1945
+ */
1946
+ interface PluginSetupContext<Options> {
1947
+ /**
1948
+ * The options the app passed, validated against the plugin's `options`
1949
+ * schema.
1950
+ */
1951
+ options: Options;
1952
+ /**
1953
+ * The assembled api, for handlers that read the app's routes or identities.
1954
+ */
1955
+ api: PluginApi;
1956
+ }
1957
+ type OptionsOutput<Schema> = Schema extends z.ZodType ? z.output<Schema> : undefined;
1958
+ type OptionsInput<Schema> = Schema extends z.ZodType ? z.input<Schema> : {};
1959
+ /**
1960
+ * What {@link definePlugin} takes.
1961
+ */
1962
+ interface PluginDefinition<Slug extends string, Schema extends z.ZodType | undefined, Setup extends PluginSetup, BasePath extends RoutePath | undefined = undefined> {
1963
+ /**
1964
+ * Handlers reach the plugin at `plugins.<slug>`.
1965
+ */
1966
+ slug: Slug;
1967
+ /**
1968
+ * Where the plugin's routes are served. Each route's `path` is relative to
1969
+ * it, and a route at `/` serves the base path itself. The app can pass
1970
+ * another one when it clashes with its own routes.
1971
+ *
1972
+ * @example
1973
+ * basePath: '/webhooks',
1974
+ */
1975
+ basePath?: BasePath;
1976
+ /**
1977
+ * A Zod schema for what the app passes in. It's validated once, when the
1978
+ * config assembles, and a failure names the plugin and the field.
1979
+ */
1980
+ options?: Schema;
1981
+ /**
1982
+ * Builds the plugin from its validated options, once, when the config
1983
+ * assembles. It runs during `kizuna generate` too, so it creates clients and
1984
+ * leaves connections to the handlers.
1985
+ */
1986
+ setup: (context: PluginSetupContext<OptionsOutput<Schema>>) => Setup;
1987
+ }
1988
+ /**
1989
+ * One installed plugin: the slug it's installed under, the plugin it is, and the
1990
+ * options the app passed, still unvalidated.
1991
+ */
1992
+ interface PluginDeclaration<Slug extends string = string, Setup extends PluginSetup = PluginSetup> {
1993
+ readonly slug: Slug;
1994
+ /**
1995
+ * The base path the app passed, when it moved the plugin's routes.
1996
+ */
1997
+ readonly basePath?: string;
1998
+ readonly definition: PluginDefinition<string, z.ZodType | undefined, PluginSetup, RoutePath | undefined>;
1999
+ readonly input: unknown;
2000
+ /**
2001
+ * Carries what `setup` returns, for the types. Never set at runtime.
2002
+ */
2003
+ readonly setupType?: Setup;
2004
+ }
2005
+ /**
2006
+ * What {@link definePlugin} returns: the function an app calls in `plugins`.
2007
+ *
2008
+ * Two overloads. Passing `slug` installs the plugin under it; leaving it out
2009
+ * installs it under the plugin's own. The one without `slug` comes last, so
2010
+ * `ReturnType<typeof emailPlugin>`, which `kizuna generate` writes, keeps the
2011
+ * plugin's own slug rather than widening it to `string`.
2012
+ */
2013
+ type PluginFactory<DefaultSlug extends string, Schema extends z.ZodType | undefined, Setup extends PluginSetup, BasePath extends RoutePath | undefined = undefined> = {} extends OptionsInput<Schema> ? {
2014
+ <const Slug extends string>(options: OptionsInput<Schema> & InstallOptions<BasePath> & SlugOption<Slug>): PluginDeclaration<Slug, Setup>;
2015
+ (options?: OptionsInput<Schema> & InstallOptions<BasePath>): PluginDeclaration<DefaultSlug, Setup>;
2016
+ } : {
2017
+ <const Slug extends string>(options: OptionsInput<Schema> & InstallOptions<BasePath> & SlugOption<Slug>): PluginDeclaration<Slug, Setup>;
2018
+ (options: OptionsInput<Schema> & InstallOptions<BasePath>): PluginDeclaration<DefaultSlug, Setup>;
2019
+ };
2020
+ interface SlugOption<Slug extends string> {
2021
+ /**
2022
+ * Install the plugin under another slug, when two plugins want the same one.
2023
+ */
2024
+ slug: Slug;
2025
+ }
2026
+ /**
2027
+ * `basePath` at install, offered only by a plugin that declares one.
2028
+ */
2029
+ type InstallOptions<BasePath> = BasePath extends RoutePath ? {
2030
+ /**
2031
+ * Serve the plugin's routes somewhere else, when they clash with the
2032
+ * app's own.
2033
+ */
2034
+ basePath?: RoutePath;
2035
+ } : {
2036
+ basePath?: never;
2037
+ };
2038
+ /**
2039
+ * Declare a plugin: its slug, the options an app passes it, and the `setup` that
2040
+ * builds what it brings. Returns the function an app installs it with.
2041
+ *
2042
+ * @example
2043
+ * export const emailPlugin = definePlugin({
2044
+ * slug: 'email',
2045
+ * options: z.object({
2046
+ * apiKey: z.string(),
2047
+ * from: z.string(),
2048
+ * }),
2049
+ * setup: ({ options }) => {
2050
+ * const resend = new Resend(options.apiKey);
2051
+ *
2052
+ * return {
2053
+ * exports: {
2054
+ * send: (email: Email) =>
2055
+ * resend.emails.send({
2056
+ * from: options.from,
2057
+ * ...email,
2058
+ * }),
2059
+ * },
2060
+ * };
2061
+ * },
2062
+ * });
2063
+ */
2064
+ declare const definePlugin: <Slug extends string, Setup extends PluginSetup, Schema extends z.ZodType | undefined = undefined, BasePath extends RoutePath | undefined = undefined>(definition: PluginDefinition<Slug, Schema, Setup, BasePath>) => PluginFactory<Slug, Schema, Setup, BasePath>;
2065
+ /**
2066
+ * Declare one of a plugin's routes and the handler that answers it, the way
2067
+ * `k.route` does for an app's own.
2068
+ *
2069
+ * @example
2070
+ * check: route({
2071
+ * method: 'GET',
2072
+ * path: '/status',
2073
+ * auth: false,
2074
+ * responses: {
2075
+ * 200: StatusSchema,
2076
+ * },
2077
+ * }).handler(() => ({
2078
+ * status: 200,
2079
+ * body: {
2080
+ * status: 'ok',
2081
+ * },
2082
+ * })),
2083
+ */
2084
+ declare const route: <const Definition extends AuthoredRouteDefinition>(definition: Definition & RouteHiddenToolCheck<Definition>) => PluginRouteBuilder<Definition>;
2085
+ /**
2086
+ * What {@link route} returns: the route, and the `handler` that answers it. A
2087
+ * plugin's handler may also answer with `rawResponse` when its wire format is
2088
+ * not JSON.
2089
+ */
2090
+ type PluginRouteBuilder<Definition extends AuthoredRouteDefinition> = Definition & {
2091
+ handler(fn: (args: HandlerArgs<Definition>) => Promise<HandlerReturn<Definition> | RawResponse> | HandlerReturn<Definition> | RawResponse): RouteWithHandler<Definition>;
2092
+ };
2093
+ /**
2094
+ * Accepts a route path, for a plugin that takes one of its routes' paths as an
2095
+ * option.
2096
+ */
2097
+ declare const RoutePathSchema: z.ZodCustom<`/${string}`, `/${string}`>;
2098
+ /**
2099
+ * Accepts exactly what a route's `auth` does, for a plugin that takes one of its
2100
+ * routes' `auth` as an option. `defineConfig` checks the value against the app's
2101
+ * identities.
2102
+ */
2103
+ declare const RouteAuthSchema: z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodString, z.ZodArray<z.ZodString>, z.ZodObject<{
2104
+ identity: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
2105
+ roles: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>;
2106
+ requires: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodString>>>;
2107
+ }, z.core.$strip>]>;
2108
+ /**
2109
+ * A plugin once the config has assembled: its options validated and `setup`
2110
+ * run.
2111
+ */
2112
+ interface ResolvedPlugin {
2113
+ /**
2114
+ * The slug it's installed under.
2115
+ */
2116
+ slug: string;
2117
+ /**
2118
+ * The slug the plugin declared, whatever the app installed it under.
2119
+ */
2120
+ definedSlug: string;
2121
+ options: unknown;
2122
+ routes: PluginRoutes;
2123
+ exports: unknown;
2124
+ generators: readonly GeneratedFile[];
2125
+ validate: (() => void) | undefined;
2126
+ }
2127
+ /**
2128
+ * Plugins keyed by their slug, which is what `plugins.*` in handler args
2129
+ * resolves against.
2130
+ */
2131
+ type ApiPlugins = Record<string, AnyPlugin>;
2132
+ /**
2133
+ * Any plugin, whatever it declares.
2134
+ */
2135
+ type AnyPlugin = PluginDeclaration<string, any>;
2136
+ /**
2137
+ * The plugins a config installs, as a list. Each carries its own slug, which is
2138
+ * what handlers reach it under.
2139
+ */
2140
+ type PluginList = readonly AnyPlugin[];
2141
+ /**
2142
+ * A plugin list as a record keyed by each plugin's own slug.
2143
+ */
2144
+ type PluginsBySlug<Plugins extends PluginList> = { [Plugin in Plugins[number] as Plugin['slug']]: Plugin };
2145
+ type SetupOf<Declaration> = Declaration extends PluginDeclaration<string, infer Setup> ? Setup : never;
2146
+ type PluginRoutesOf<Declaration> = SetupOf<Declaration> extends {
2147
+ routes: infer R extends PluginRoutes;
2148
+ } ? R : Record<string, never>;
2149
+ type PluginExportsOf<Declaration> = SetupOf<Declaration> extends {
2150
+ exports: infer Exports;
2151
+ } ? Exports : undefined;
2152
+ type PluginExportValues<Plugins extends ApiPlugins> = { [Key in keyof Plugins]: PluginExportsOf<Plugins[Key]> };
2153
+ /**
2154
+ * The `plugins` handler argument, or nothing when no plugins are installed, so
2155
+ * handler args are unchanged without them.
2156
+ */
2157
+ type PluginArgs<Plugins extends ApiPlugins> = string extends keyof Plugins ? unknown : [keyof Plugins] extends [never] ? unknown : {
2158
+ plugins: PluginExportValues<Plugins>;
2159
+ };
2160
+ /**
2161
+ * Every plugin's routes as one tree, keyed by slug, for the adapter to walk as
2162
+ * it walks the api's own.
2163
+ */
2164
+ declare const pluginRouteTree: (plugins: Record<string, {
2165
+ routes: PluginRoutes;
2166
+ }> | undefined) => Routes;
2167
+ //#endregion
2168
+ //#region src/generator-utils.d.ts
2169
+ declare const isZodSchema: (value: unknown) => value is z.ZodType;
2170
+ /**
2171
+ * Whether a response is sent piece by piece, declared with `stream` in place of `body`.
2172
+ */
2173
+ declare const isStreamResponse: (value: ResponseDefinition | undefined) => value is StreamResponseDefinition;
2174
+ /**
2175
+ * The body schema of a response, or `undefined` for a stream, which has none.
2176
+ */
2177
+ declare const resolveResponseBody: (value: ResponseDefinition) => z.ZodType | undefined;
2178
+ declare const resolveResponseStream: (value: ResponseDefinition) => StreamDefinition | undefined;
2179
+ declare const resolveResponseHeaders: (value: ResponseDefinition) => z.ZodType | undefined;
2180
+ declare const resolveResponseContentType: (value: ResponseDefinition | undefined) => string | undefined;
2181
+ declare const resolveResponseCache: (value: ResponseDefinition | undefined) => CachePolicy | undefined;
2182
+ declare const resolveResponseEtag: (value: ResponseDefinition | undefined) => boolean;
2183
+ declare const toPascalCase: (input: string) => string;
2184
+ declare const toCamelCase: (input: string) => string;
2185
+ /**
2186
+ * The local name a type gets when nested inside its owning type: the owner's
2187
+ * name stripped from the front (`UserAvatar` inside `User` → `Avatar`).
2188
+ */
2189
+ declare const shortTypeName: (typeName: string, ownerName: string) => string;
2190
+ /**
2191
+ * A hint prefix must end on a PascalCase word boundary. Otherwise `Image` claims
2192
+ * `ImagesItem` and the nested short name becomes the mid-word slice `sItem`.
2193
+ */
2194
+ declare const isHintPrefix: (typeName: string, prefix: string) => boolean;
2195
+ /**
2196
+ * The type name local to an operation scope: the operation name stripped from
2197
+ * the front (`createUserInput` inside `createUser` → `Input`), or the full name
2198
+ * when stripping would leave nothing.
2199
+ */
2200
+ declare const localTypeName: (fullName: string, operationName: string) => string;
2201
+ /**
2202
+ * Returns a wire field key as a valid identifier: kept verbatim when already
2203
+ * valid, otherwise camelCased from its segments, with a `_` prefix when it
2204
+ * starts with a digit.
2205
+ */
2206
+ declare const sanitizeFieldName: (key: string) => string;
2207
+ /**
2208
+ * Returns the input with every non-identifier character replaced by `_`, with a
2209
+ * `_` prefix when it starts with a digit.
2210
+ */
2211
+ declare const sanitizeIdentifier: (input: string) => string;
2212
+ /**
2213
+ * Returns the camelCase name for a known HTTP error status (`404` → `notFound`),
2214
+ * or `status<code>` for unknown ones.
2215
+ */
2216
+ declare const statusToCamelCase: (status: number) => string;
2217
+ /**
2218
+ * True for 2xx status codes.
2219
+ */
2220
+ declare const isSuccessStatus: (status: number) => boolean;
2221
+ /**
2222
+ * Merges per-status response header fields into one list, marking fields that
2223
+ * are not present on every status as optional.
2224
+ */
2225
+ declare const mergeHeaderFields: <Field extends {
2226
+ name: string;
2227
+ optional: boolean;
2228
+ }>(perStatusHeaders: Field[][]) => Field[];
2229
+ /**
2230
+ * Whether a media type is JSON-serialized: `application/json` or any
2231
+ * structured-suffix `+json` type (e.g. `application/problem+json`). Any other
2232
+ * type carries a raw body that is written/read as-is.
2233
+ */
2234
+ declare const isJsonMediaType: (contentType: string) => boolean;
2235
+ //#endregion
2236
+ //#region src/plugin-server.d.ts
2237
+ /**
2238
+ * The plugin routes `assembleApi` stashed on the api. Empty without plugins, so
2239
+ * an adapter can mount it unconditionally.
2240
+ */
2241
+ declare const pluginRoutesOf: (api: unknown) => Routes;
2242
+ /**
2243
+ * Their handlers, keyed to match {@link pluginRoutesOf}.
2244
+ */
2245
+ declare const pluginRouterOf: (api: unknown) => Record<string, unknown>;
2246
+ /**
2247
+ * What each plugin exports, for the adapter to pass into the pipeline as the
2248
+ * handler args' `plugins`.
2249
+ */
2250
+ declare const pluginExportsOf: (api: unknown) => Record<string, unknown>;
2251
+ /**
2252
+ * Resolve every installed plugin, keyed by slug. Two plugins on one slug throw,
2253
+ * naming both, since handlers could only reach one of them.
2254
+ */
2255
+ declare const resolvePlugins: (declarations: readonly PluginDeclaration[] | undefined, api: PluginApi) => Record<string, ResolvedPlugin>;
2256
+ /**
2257
+ * A stand-in for the api that plugins receive in `setup`, before it exists.
2258
+ * Reading it inside a handler works once `bind` has run; reading it during
2259
+ * `setup` throws, since the api is still being assembled.
2260
+ */
2261
+ declare const createApiReference: () => {
2262
+ api: PluginApi;
2263
+ bind: (target: object) => void;
2264
+ };
2265
+ //#endregion
2266
+ //#region src/routes.d.ts
2267
+ /**
2268
+ * Validate a tree of routes and stamp its group's path, `''` for none.
2269
+ */
2270
+ declare function groupRoutes<const T extends Routes>(routes: T & PathParamsCheck<T>): T;
2271
+ declare function groupRoutes<const T extends Routes>(group: string, routes: T & PathParamsCheck<T>): T;
2272
+ //#endregion
2273
+ //#region src/response-error.d.ts
2274
+ interface ResponseErrorPayload {
2275
+ status: number;
2276
+ body: unknown;
2277
+ headers?: ResponseHeaders;
2278
+ }
2279
+ declare class ResponseError<R extends RouteDefinition = never> extends Error {
2280
+ readonly status: number;
2281
+ readonly body: unknown;
2282
+ readonly headers?: ResponseHeaders;
2283
+ constructor(response: [R] extends [never] ? ResponseErrorPayload : HandlerReturn<R>);
2284
+ }
2285
+ //#endregion
2286
+ //#region src/server-surface.d.ts
2287
+ /**
2288
+ * The handler tree for an api or route group, typed against it, with an
2289
+ * adapter's handler context substituted in. Adapter packages check their own
2290
+ * surface against this; an app types a handler by writing it on the route.
2291
+ */
2292
+ type ApiRouter<C, HandlerContext> = C extends ApiDefinition ? HandlersFromRoutes<RoutesOf<C>, HandlerContext & RequestContextValues<RequestContextOf<C>> & PluginArgs<ApiPluginsOf<C>> & JobsArg<JobsOf<C>>, SchemesOf<C>> : C extends Routes ? Router<C, HandlerContext> : never;
2293
+ //#endregion
2294
+ //#region src/adapter.d.ts
2295
+ declare class ResponseValidationError extends Error {
2296
+ readonly routeKey: string;
2297
+ readonly status: number;
2298
+ readonly issues: z.core.$ZodIssue[];
2299
+ constructor(routeKey: string, status: number, issues: z.core.$ZodIssue[]);
2300
+ }
2301
+ declare const API_META: unique symbol;
2302
+ declare const ROUTER_META: unique symbol;
2303
+ declare const GUARDS_META: unique symbol;
2304
+ declare const SCHEMES_META: unique symbol;
2305
+ declare const GUARD_SCHEMA_META: unique symbol;
2306
+ declare const REQUEST_CONTEXT_META: unique symbol;
2307
+ declare const JOBS_META: unique symbol;
2308
+ type ApiBrand = {
2309
+ readonly [API_META]: true;
2310
+ };
2311
+ type ApiWithRouter<R extends Routes = Routes> = ApiBrand & {
2312
+ /**
2313
+ * The api's route tree. Read it here rather than off the api object: the
2314
+ * api carries the parts that serve the routes, it is not the routes itself.
2315
+ */
2316
+ readonly routes: R;
2317
+ readonly [ROUTER_META]: Record<string, unknown>;
2318
+ };
2319
+ /**
2320
+ * The marker a guard's `deny` returns. Distinguishes a denial
2321
+ * from the context object a passing guard returns.
2322
+ */
2323
+ declare const GUARD_DENY: unique symbol;
2324
+ /**
2325
+ * The result of `deny` inside a guard, short-circuits the
2326
+ * request with an RFC 9457 problem details response of the given status.
2327
+ */
2328
+ interface GuardDenial {
2329
+ readonly [GUARD_DENY]: true;
2330
+ status: number;
2331
+ body: GuardDenialBody;
2332
+ /**
2333
+ * The `WWW-Authenticate` challenge RFC 9110 section 11.6.1 requires on a `401`.
2334
+ */
2335
+ headers?: ResponseHeaders;
2336
+ }
2337
+ /**
2338
+ * Reject the request from inside a guard. Extra `headers` ride on the
2339
+ * response; a `www-authenticate` among them replaces the default challenge.
2340
+ */
2341
+ type GuardDenialBody = {
2342
+ detail: string;
2343
+ } & Record<string, unknown>;
2344
+ type GuardDeny<Body = {
2345
+ detail: string;
2346
+ }, Status extends number = number> = (denial: {
2347
+ status: Status;
2348
+ body: Body;
2349
+ headers?: ResponseHeaders;
2350
+ }) => GuardDenial;
2351
+ /**
2352
+ * Format a `Bearer` challenge for a `WWW-Authenticate` header, with auth
2353
+ * parameters as RFC 9110 quoted strings (`error`, `scope`, `resource_metadata`,
2354
+ * ...). `undefined` values are omitted; with none left, the bare scheme remains.
2355
+ */
2356
+ declare const bearerChallenge: (parameters: Record<string, string | undefined>) => string;
2357
+ /**
2358
+ * The `deny` a guard for this identity receives. The challenge rides along with
2359
+ * the denial, so a `401` cannot reach the wire without one.
2360
+ */
2361
+ declare const guardDenyFor: (scheme: SecurityScheme | undefined) => GuardDeny<GuardDenialBody>;
2362
+ declare const isGuardDenial: (value: unknown) => value is GuardDenial;
2363
+ /**
2364
+ * The runtime behavior of a guard. It receives one object: the adapter's handler
2365
+ * context (e.g. `req`/`res`) plus the credential the identity's method extracted
2366
+ * from the request (or `null` if absent), a `deny` helper, and the request
2367
+ * context resolved for this request, absent
2368
+ * when the api declares none. It returns the context the scheme provides
2369
+ * (nested under `auth`, keyed by the identity's name in the handler args) or
2370
+ * `deny(...)` to reject.
2371
+ */
2372
+ type GuardRun<HandlerContext = unknown> = (args: HandlerContext & Credential & {
2373
+ params: Record<string, string>;
2374
+ deny: GuardDeny;
2375
+ requestContext?: Record<string, unknown>;
2376
+ }) => Promise<Record<string, unknown> | GuardDenial | void> | Record<string, unknown> | GuardDenial | void;
2377
+ /**
2378
+ * Guards keyed by the security scheme name they satisfy. A route's resolved
2379
+ * `security` selects which guards run before its handler.
2380
+ */
2381
+ type GuardMap<HandlerContext = unknown> = Record<string, GuardRun<HandlerContext>>;
2382
+ /**
2383
+ * The runtime behavior of a request context resolver. It runs on every route
2384
+ * before the guards, receives the handler context plus the matched route's
2385
+ * `params`, and returns the value the guards and handlers read under the
2386
+ * context's name. It never denies a request.
2387
+ */
2388
+ type RequestContextRun<HandlerContext = unknown> = (args: HandlerContext & {
2389
+ params: Record<string, string>;
2390
+ headers: Record<string, string | string[] | undefined>;
2391
+ }) => Promise<unknown> | unknown;
2392
+ /**
2393
+ * The api's own definition, for plugins needing more than the routes.
2394
+ */
2395
+ declare const contractOf: <C = unknown>(api: unknown) => C;
2396
+ /**
2397
+ * What kizuna puts in handler args. Must agree with the spread in `runPipeline`.
2398
+ */
2399
+ declare const HANDLER_ARG_KEYS: readonly ["params", "query", "body", "headers", "throwError", "auth", "requestContext", "plugins", "tools", "rawBody", "lastEventId"];
2400
+ /**
2401
+ * The adapter's own context, with kizuna's arguments removed.
2402
+ */
2403
+ declare const adapterContextOf: (args: Record<string, unknown>) => Record<string, unknown>;
2404
+ /**
2405
+ * Request context resolvers keyed by the name they were declared under in `defineConfig()`.
2406
+ */
2407
+ type RequestContextMap<HandlerContext = unknown> = Record<string, RequestContextRun<HandlerContext>>;
2408
+ interface ApiParts {
2409
+ router: unknown;
2410
+ guards?: unknown;
2411
+ requestContext?: unknown;
2412
+ }
2413
+ /**
2414
+ * Brand an api's routes with the parts that serve them, for the adapter to read back when mounting.
2415
+ */
2416
+ declare const assembleApi: <const R extends Routes>(contract: {
2417
+ routes: R;
2418
+ securitySchemes?: Record<string, SecurityScheme>;
2419
+ guardSchema?: z.ZodType;
2420
+ plugins?: Record<string, ResolvedPlugin>;
2421
+ }, parts: ApiParts) => ApiWithRouter<R>;
2422
+ /**
2423
+ * The endpoints jobs are served on, in the {@link Routes} shape the request
2424
+ * pipeline takes. None when the jobs run in process.
2425
+ */
2426
+ declare const jobRoutes: (meta: JobsMeta) => Routes;
2427
+ /**
2428
+ * Their handlers, in the {@link Router} shape the request pipeline takes.
2429
+ */
2430
+ declare const jobRouter: <HandlerContext>(meta: JobsMeta) => Router<Routes, HandlerContext>;
2431
+ /**
2432
+ * Type-only key under which an {@link Adapter} carries the handler context its
2433
+ * framework hands to every handler. Never present at runtime.
2434
+ */
2435
+ declare const ADAPTER_CONTEXT: unique symbol;
2436
+ /**
2437
+ * What serves an API on one framework. Name it under `adapter` in
2438
+ * `defineConfig`, and the `api` you get back mounts onto that framework's app,
2439
+ * hands every handler that framework's own request, and types both.
2440
+ *
2441
+ * @example
2442
+ * // kizuna.config.ts
2443
+ * export default defineConfig({
2444
+ * adapter: expressAdapter(),
2445
+ * routes,
2446
+ * });
2447
+ *
2448
+ * // src/index.ts
2449
+ * kizuna.api.mount(app);
2450
+ */
2451
+ interface Adapter<HandlerContext = unknown, MountArgs extends readonly unknown[] = readonly unknown[], Mounted = unknown> {
2452
+ /**
2453
+ * The framework this serves, for error messages.
2454
+ */
2455
+ readonly name: string;
2456
+ /**
2457
+ * Register every route of an api on the framework. What it takes after the
2458
+ * api, and what it hands back, is the framework's own.
2459
+ */
2460
+ readonly mount: (api: ApiWithRouter, ...args: MountArgs) => Mounted;
2461
+ readonly [ADAPTER_CONTEXT]?: HandlerContext;
2462
+ }
2463
+ /**
2464
+ * Any adapter, whatever its framework takes. A `mount` reads its own arguments,
2465
+ * so a concrete adapter is not assignable to a widened one; this stands in
2466
+ * wherever an adapter is a constraint rather than a value.
2467
+ */
2468
+ type AnyAdapter = Adapter<any, any, any>;
2469
+ /**
2470
+ * The handler context an adapter hands to every handler, `{}` when none is
2471
+ * declared.
2472
+ */
2473
+ type HandlerContextOf<A> = A extends Adapter<infer HandlerContext, any, any> ? HandlerContext : {};
2474
+ /**
2475
+ * What an adapter's `mount` takes after the api.
2476
+ */
2477
+ type MountArgsOf<A> = A extends Adapter<any, infer MountArgs, any> ? MountArgs : readonly unknown[];
2478
+ /**
2479
+ * What an adapter's `mount` hands back.
2480
+ */
2481
+ type MountedOf<A> = A extends Adapter<any, any, infer Mounted> ? Mounted : never;
2482
+ interface ServerOptions {
2483
+ /**
2484
+ * Carries a queued job to whatever runs it. Without one, `queue` runs the job
2485
+ * in this process and it is lost on a crash.
2486
+ */
2487
+ jobTransport?: JobTransport;
2488
+ onJobError?: JobErrorHandler;
2489
+ }
2490
+ /**
2491
+ * Warn when a job asks for something its transport will drop.
2492
+ */
2493
+ declare const warnUnsupportedJobOptions: (jobs: Jobs | undefined, transport: JobTransport | undefined, logger?: Pick<Console, "warn">) => void;
2494
+ /**
2495
+ * What `JOBS_META` carries: the api's jobs, the handler for each, and how
2496
+ * this deployment runs them.
2497
+ */
2498
+ interface JobsMeta extends JobRunnerOptions {
2499
+ jobs: Jobs;
2500
+ handlers: Record<string, unknown>;
2501
+ config?: JobsConfig;
2502
+ }
2503
+ /**
2504
+ * Namespaced so it cannot collide with a route key of your own.
2505
+ */
2506
+ declare const DISPATCH_ROUTE_KEY = "kizuna:dispatch";
2507
+ /**
2508
+ * The endpoint a scheduler ticks to run whichever jobs are due.
2509
+ */
2510
+ declare const dispatchRoute: (meta: JobsMeta) => RouteDefinition;
2511
+ /**
2512
+ * Runs each due job rather than queueing it, so the transport never sees a tick.
2513
+ */
2514
+ declare const dispatchHandler: <HandlerContext>(meta: JobsMeta) => RouteHandler<RouteDefinition, HandlerContext>;
2515
+ /**
2516
+ * Namespaced so it cannot collide with a route key of your own.
2517
+ */
2518
+ declare const RUN_ROUTE_KEY = "kizuna:run";
2519
+ /**
2520
+ * The endpoint a queue delivers one job to, naming it in the body.
2521
+ */
2522
+ declare const runRoute: (meta: JobsMeta) => RouteDefinition;
2523
+ /**
2524
+ * Answers with whatever the job answered, so a queue reads its own retry
2525
+ * contract off the status.
2526
+ */
2527
+ declare const runHandler: <HandlerContext>(meta: JobsMeta) => RouteHandler<RouteDefinition, HandlerContext>;
2528
+ declare const jobRunnerFrom: (meta: JobsMeta | undefined) => JobRunner<Jobs> | undefined;
2529
+ /**
2530
+ * The dotted keys of the jobs a handler was actually bound to. A job without one
2531
+ * cannot run, so nothing should schedule or subscribe to it.
2532
+ */
2533
+ declare const boundJobKeys: (meta: JobsMeta | undefined) => Set<string>;
2534
+ type RouteMatcher = (method: string, path: string, routes: Routes, basePath?: string) => MatchResult;
2535
+ interface AdapterRequest<NativeRequest> {
2536
+ request: NativeRequest;
2537
+ method: string;
2538
+ /**
2539
+ * - `core-match`: core matches the path against the routes (Next-style catch-all routing).
2540
+ * - `pre-resolved`: adapter has already routed the request and tells core which route was matched (Express-style per-route registration).
2541
+ */
2542
+ resolution: {
2543
+ kind: 'core-match';
2544
+ path: string;
2545
+ } | {
2546
+ kind: 'pre-resolved';
2547
+ routeKey: string;
2548
+ route: RouteDefinition;
2549
+ params: Record<string, string>;
2550
+ };
2551
+ query: unknown;
2552
+ headers: unknown;
2553
+ readBody: (route: RouteDefinition) => Promise<unknown> | unknown;
2554
+ /**
2555
+ * The body as it was sent, for a route with `rawBody: true`, or `undefined`
2556
+ * when it was already consumed.
2557
+ */
2558
+ readRawBody?: (route: RouteDefinition) => Promise<string | undefined> | string | undefined;
2559
+ }
2560
+ /**
2561
+ * Outcome of `runPipeline`. The adapter's `respond` translates this to a native response.
2562
+ *
2563
+ * Note: `raw-response` is an escape hatch for `onError` overrides, its `response` is
2564
+ * cast back to the adapter's `NativeResponse` by `respond`.
2565
+ */
2566
+ type AdapterResult = {
2567
+ kind: 'not-found';
2568
+ } | {
2569
+ kind: 'method-not-allowed';
2570
+ allowed: Method[];
2571
+ } | {
2572
+ kind: 'unsupported-media-type';
2573
+ expected: string;
2574
+ received: string;
2575
+ headers?: ResponseHeaders;
2576
+ } | {
2577
+ kind: 'invalid-body';
2578
+ detail: string;
2579
+ headers?: ResponseHeaders;
2580
+ } | {
2581
+ kind: 'validation-failed';
2582
+ stage: ValidationStage;
2583
+ detail: string;
2584
+ issues: z.core.$ZodIssue[];
2585
+ headers?: ResponseHeaders;
2586
+ } | {
2587
+ kind: 'no-handler';
2588
+ routeKey: string;
2589
+ headers?: ResponseHeaders;
2590
+ } | {
2591
+ kind: 'guard-denied';
2592
+ status: number;
2593
+ body: GuardDenialBody;
2594
+ /**
2595
+ * The `WWW-Authenticate` challenge RFC 9110 requires on a `401`, or
2596
+ * the `insufficient_scope` one RFC 6750 sends on a `403`.
2597
+ */
2598
+ headers?: ResponseHeaders;
2599
+ } | {
2600
+ kind: 'handler-error';
2601
+ routeKey: string;
2602
+ route: RouteDefinition;
2603
+ error: unknown;
2604
+ headers?: ResponseHeaders;
2605
+ } | {
2606
+ kind: 'success';
2607
+ routeKey: string;
2608
+ route: RouteDefinition;
2609
+ status: number;
2610
+ body: unknown;
2611
+ headers?: ResponseHeaders;
2612
+ } | {
2613
+ kind: 'not-acceptable';
2614
+ headers?: ResponseHeaders;
2615
+ } | {
2616
+ kind: 'raw-response';
2617
+ response: unknown;
2618
+ };
2619
+ interface AdapterDefinition<NativeRequest, NativeResponse, HandlerContext, ResponseContext = Record<string, never>> {
2620
+ buildHandlerContext: (request: AdapterRequest<NativeRequest>, context: ResponseContext) => HandlerContext | Promise<HandlerContext>;
2621
+ respond: (result: AdapterResult, context: ResponseContext) => NativeResponse | Promise<NativeResponse>;
2622
+ /**
2623
+ * Return an `AdapterResult` to override the default `handler-error` outcome; return `void` to let it pass through.
2624
+ */
2625
+ onError?: (error: unknown, request: AdapterRequest<NativeRequest>) => AdapterResult | void | Promise<AdapterResult | void>;
2626
+ matcher?: RouteMatcher;
2627
+ }
2628
+ interface HandleArgs<NativeRequest, HandlerContext, ResponseContext, TRoutes extends Routes> {
2629
+ routes: TRoutes;
2630
+ router: Router<TRoutes, HandlerContext>;
2631
+ request: AdapterRequest<NativeRequest>;
2632
+ responseContext: ResponseContext;
2633
+ /**
2634
+ * Guards keyed by security scheme name. The matched route's resolved
2635
+ * `security` selects which run before its handler; their returned context is
2636
+ * merged into the handler args.
2637
+ */
2638
+ guards?: GuardMap<HandlerContext>;
2639
+ /**
2640
+ * The api's identities keyed by name. The runtime extracts each required
2641
+ * scheme's credential from the request (per its declared location) and passes
2642
+ * it to that scheme's guard.
2643
+ */
2644
+ schemes?: Record<string, SecurityScheme>;
2645
+ /**
2646
+ * What each plugin exports, reaching handlers under `plugins`.
2647
+ */
2648
+ pluginExports?: Record<string, unknown>;
2649
+ /**
2650
+ * Request context resolvers keyed by name. Each runs on every route before
2651
+ * the guards; its value lands in the guard and handler args under `requestContext`, keyed by its name.
2652
+ */
2653
+ requestContext?: RequestContextMap<HandlerContext>;
2654
+ /**
2655
+ * The api's jobs bound to their handlers. Every handler receives it as
2656
+ * `jobs`, so a route can run a job in process without an HTTP hop.
2657
+ */
2658
+ jobs?: JobRunner<Jobs>;
2659
+ basePath?: string;
2660
+ responseValidation?: boolean;
2661
+ }
2662
+ declare const getHeaderValue: (value: unknown) => string | undefined;
2663
+ /**
2664
+ * Extract the credential an identity's authentication method expects from the
2665
+ * request, labelled with its scheme kind: the value of the named
2666
+ * header/query/cookie for `apiKey`, the decoded `username`/`password` for HTTP
2667
+ * `basic`, or the bearer token for everything else. The credential is `null`
2668
+ * when it is absent or malformed.
2669
+ */
2670
+ declare const extractCredential: (scheme: SecurityScheme, request: AdapterRequest<unknown>) => Credential | NoCredential;
2671
+ /**
2672
+ * The request pipeline `defineAdapter` builds: what matches a request to a
2673
+ * route, runs the guards and the handler, and hands the result back to the
2674
+ * framework.
2675
+ */
2676
+ interface RequestPipeline<NativeRequest, NativeResponse, HandlerContext, ResponseContext> {
2677
+ handle: <T extends Routes>(args: HandleArgs<NativeRequest, HandlerContext, ResponseContext, T>) => Promise<NativeResponse>;
2678
+ eachRoute: <T extends Routes>(routes: T, router: Router<T, HandlerContext>) => Iterable<{
2679
+ routeKey: string;
2680
+ route: RouteDefinition;
2681
+ handler: RouteHandler<RouteDefinition, HandlerContext>;
2682
+ }>;
2683
+ }
2684
+ /**
2685
+ * The handler tree a routes tree already carries, mirroring its shape so
2686
+ * everything that walks a router by dotted key finds the route's own handler.
2687
+ */
2688
+ declare const routerFromRoutes: (routes: Routes) => Record<string, unknown>;
2689
+ declare const defineAdapter: <NativeRequest, NativeResponse, HandlerContext, ResponseContext = Record<string, never>>(definition: AdapterDefinition<NativeRequest, NativeResponse, HandlerContext, ResponseContext>) => RequestPipeline<NativeRequest, NativeResponse, HandlerContext, ResponseContext>;
2690
+ /**
2691
+ * Decides the bytes that go on the wire for an error (status >= 400). The default emits the
2692
+ * canonical RFC 9457 Problem Details as `application/problem+json`.
2693
+ *
2694
+ * **Most migrations don't need this.** Carrying your existing fields as Problem Details
2695
+ * extension members keeps a single body valid for both old and new clients.
2696
+ *
2697
+ * **Reach for it only when** an older client needs a different content type (plain
2698
+ * `application/json`) or a structurally different body. It receives the request, so if you
2699
+ * can tell clients apart (a version header, `Accept`, …) you can serve the legacy shape to
2700
+ * old clients and Problem Details to new ones during a transition, then delete it.
2701
+ */
2702
+ type ErrorFormatter<NativeRequest = unknown> = (problem: ProblemDetails & Record<string, unknown>, context: {
2703
+ status: number;
2704
+ request: NativeRequest;
2705
+ }) => {
2706
+ contentType: string;
2707
+ body: unknown;
2708
+ };
2709
+ /**
2710
+ * Maps an `AdapterResult` to `{ status, headers, body }` using Kizuna's default
2711
+ * JSON conventions (e.g. 405 with an `Allow` header, 400 with `{ detail, errors }`
2712
+ * for validation failures). Adapters that speak JSON delegate `respond` to this
2713
+ * instead of writing the switch by hand.
2714
+ *
2715
+ * Every error (status >= 400) is an RFC 9457 Problem Details object run through
2716
+ * `formatError`, there is no custom-error-shape passthrough. Pass an `ErrorFormatter`
2717
+ * to reshape the wire bytes for migration; the canonical problem is unchanged.
2718
+ *
2719
+ * `raw-response` is excluded, it carries a framework-specific `NativeResponse`
2720
+ * the adapter must return directly, so handle that case before calling this.
2721
+ *
2722
+ * Pass `requestMethod` where kizuna's rendering is the last stop before the
2723
+ * wire: a HEAD request then keeps GET's status and headers, gains a
2724
+ * `Content-Length`, and loses the content (RFC 9110 §9.3.2). Leave it
2725
+ * unset where the framework discards HEAD content itself (Express, Fastify, Hono).
2726
+ */
2727
+ interface RenderedResult {
2728
+ status: number;
2729
+ headers: ResponseHeaders;
2730
+ body: unknown;
2731
+ raw?: boolean;
2732
+ /**
2733
+ * A streamed response carries this in place of `body`. Check it first.
2734
+ */
2735
+ stream?: (options: EncodeStreamOptions) => ReadableStream<Uint8Array>;
2736
+ }
2737
+ declare const renderJsonResult: (result: Exclude<AdapterResult, {
2738
+ kind: "raw-response";
2739
+ }>, formatError?: ErrorFormatter, request?: unknown, requestMethod?: string) => RenderedResult;
2740
+ /**
2741
+ * Parse a body from its text, the way {@link parseFetchBody} would, for a route
2742
+ * whose text core already read.
2743
+ */
2744
+ declare const parseBodyText: (text: string, route: RouteDefinition) => unknown;
2745
+ /**
2746
+ * Content-type-aware body parser for Web Fetch `Request`.
2747
+ *
2748
+ * Reusable across any Fetch-based adapter.
2749
+ *
2750
+ * */
2751
+ declare const parseFetchBody: (request: Request, route: RouteDefinition) => Promise<unknown>;
2752
+ declare const headersToObject: (headers: Headers) => ResponseHeaders;
2753
+ //#endregion
2754
+ export { jobRunnerFrom as $, StreamContext as $i, jobAt as $n, BrandedHandlerContext as $r, ResolvedPlugin as $t, RenderedResult as A, BearerCredential as Aa, ToolRunResult as Ai, SchemesOf as An, scheduleExpression as Ar, shortTypeName as At, bearerChallenge as B, OAuth2Config as Ba, HasPathParams as Bi, JobHandlerArgs as Bn, ResolvedGroup as Br, PluginArgs as Bt, JOBS_META as C, requiresDenial as Ca, validateRequest as Ci, apiEntries as Cn, assertValidSchedule as Cr, resolveResponseCache as Ct, REQUEST_CONTEXT_META as D, BasicConfig as Da, ToolEventYield as Di, JobsOf as Dn, nextRun as Dr, resolveResponseStream as Dt, MountedOf as E, ApiKeyCredential as Ea, ToolAnswer as Ei, GuardSchemaOf as En, firesBetween as Er, resolveResponseHeaders as Et, RouteMatcher as F, GuardHoldings as Fa, describeTool as Fi, FlattenedJob as Fn, RequestContextSchema as Fr, ApiPlugins as Ft, dispatchRoute as G, buildPath as Gi, JobVoidReturn as Gn, rawResponse as Gr, PluginFactory as Gt, contractOf as H, RoleOf as Ha, PathParamsCheck as Hi, JobHandlers as Hn, isGroupSet as Hr, PluginDefinition as Ht, SCHEMES_META as I, Identity as Ia, selectToolRoutes as Ii, HttpJobsConfig as In, GroupOptions as Ir, InstallOptions as It, guardDenyFor as J, EncodeStreamOptions as Ji, JobsConfig as Jn, MatchResult as Jr, PluginRoutes as Jt, extractCredential as K, parsePath as Ki, Jobs as Kn, RouteBuilder as Kr, PluginList as Kt, ServerOptions as L, IdentityParamsOf as La, toolOptionsOf as Li, InProcessJobsConfig as Ln, GroupPaths as Lr, PLUGIN_ROUTES_META_KEY as Lt, RequestContextRun as M, CredentialOf as Ma, ToolInputSchema as Mi, AuthoredJobs as Mn, RequestContextConfig as Mr, toCamelCase as Mt, RequestPipeline as N, CustomConfig as Na, buildToolDefinitions as Ni, CompiledJob as Nn, RequestContextHeaderInputs as Nr, toPascalCase as Nt, ROUTER_META as O, BasicCredential as Oa, ToolRunCall as Oi, RequestContextOf as On, nextRuns as Or, sanitizeFieldName as Ot, ResponseValidationError as P, GrantsOf as Pa, buildToolInputSchema as Pi, CompiledJobs as Pn, RequestContextHeaderValues as Pr, AnyPlugin as Pt, jobRoutes as Q, StreamComment as Qi, isJobDefinition as Qn, AuthContextOf as Qr, PluginsBySlug as Qt, adapterContextOf as R, IdentityRole as Ra, toolRefusal as Ri, JobDefinition as Rn, GroupPathsOf as Rr, PLUGIN_SERVERS_META_KEY as Rt, HandlerContextOf as S, insufficientScope as Sa, isRouteDefinition as Si, GeneratedFile as Sn, ParsedCron as Sr, resolveResponseBody as St, MountArgsOf as T, ApiKeyConfig as Ta, StreamTools as Ti, ApiPluginsOf as Tn, dueSchedules as Tr, resolveResponseEtag as Tt, defineAdapter as U, RolesOf as Ua, PathSegment as Ui, JobResponses as Un, RawResponse as Ur, PluginExportValues as Ut, boundJobKeys as V, OpenIdConnectConfig as Va, PathParamName as Vi, JobHandlerReturn as Vn, createGroups as Vr, PluginDeclaration as Vt, dispatchHandler as W, RoutePathParamsCheck as Wi, JobRunnerConfig as Wn, isRawResponse as Wr, PluginExportsOf as Wt, isGuardDenial as X, StreamBodyOf as Xi, flattenJobs as Xn, matchRoute as Xr, PluginSetup as Xt, headersToObject as Y, StreamBody as Yi, NoJobs as Yn, RouteMatch as Yr, PluginRoutesOf as Yt, jobRouter as Z, StreamChunk as Zi, isCompiledJob as Zn, sortFlattenedRoutes as Zr, PluginSetupContext as Zt, GuardDeny as _, ToolKeys as _a, ValidationFailure as _i, JobFnOf as _n, JobWorker as _r, isStreamResponse as _t, AdapterRequest as a, isNamedStream as aa, GuardSuccess as ai, route as an, JobQueueOptions as ar, runRoute as at, HANDLER_ARG_KEYS as b, toolEvents as ba, flattenRoutes as bi, ApiEntry as bn, defineJobTransport as br, localTypeName as bt, ApiBrand as c, streamContentType as ca, HandlerReturn as ci, ConfiguredAdapterValue as cn, JobRunnerOptions as cr, ResponseError as ct, DISPATCH_ROUTE_KEY as d, streamStatuses as da, RequestContextValues as di, ConfiguredGuardSchema as dn, JobDescriptor as dr, pluginExportsOf as dt, StreamMessage as ea, ContextFromAuth as ei, RouteAuthSchema as en, JobErrorHandler as er, parseBodyText as et, ErrorFormatter as f, StreamWithTools as fa, RouteGuardBrandOf as fi, ConfiguredIdentities as fn, JobDispatchError as fr, pluginRouterOf as ft, GuardDenialBody as g, ToolEvents as ga, ThrowableReturn as gi, ConfiguredRequestContextSchemas as gn, JobTransportSupports as gr, isJsonMediaType as gt, GuardDenial as h, ToolError as ha, RoutesWithHandlerContext as hi, ConfiguredRequestContext as hn, JobTransportDefinition as hr, isHintPrefix as ht, AdapterDefinition as i, encodeStreamBody as ia, GuardReturn as ii, pluginRouteTree as in, JobQueueArgs as ir, runHandler as it, RequestContextMap as j, Credential as ja, ToolDefinition as ji, AuthoredJobDefinition as jn, scheduleTimezone as jr, statusToCamelCase as jt, RUN_ROUTE_KEY as k, BearerConfig as ka, ToolRunOptions as ki, RoutesOf as kn, parseCron as kr, sanitizeIdentifier as kt, ApiParts as l, streamMode as la, HandlersFromRoutes as li, ConfiguredCodes as ln, createJobRunner as lr, groupRoutes as lt, GUARD_SCHEMA_META as m, ToolCall as ma, Router as mi, ConfiguredPlugins as mn, JobTransport as mr, resolvePlugins as mt, API_META as n, StreamMode as na, GuardAnswer as ni, SlugOption as nn, JobFnByKey as nr, renderJsonResult as nt, AdapterResult as o, routeStreams as oa, GuardedParamNames as oi, ApiContext as on, JobRunArgs as or, warnUnsupportedJobOptions as ot, GUARDS_META as p, ToolAt as pa, RouteHandler as pi, ConfiguredJobs as pn, JobMessage as pr, pluginRoutesOf as pt, getHeaderValue as q, EVENT_STREAM_MEDIA_TYPE as qi, JobsArg as qn, RouteWithHandler as qr, PluginRouteBuilder as qt, Adapter as r, StreamYield as ra, GuardParams as ri, definePlugin as rn, JobInputError as rr, routerFromRoutes as rt, AnyAdapter as s, soleStreamResponse as sa, HandlerArgs as si, ConfiguredAdapterContext as sn, JobRunner as sr, ApiRouter as st, ADAPTER_CONTEXT as t, StreamMessageOf as ta, FlattenedRoute as ti, RoutePathSchema as tn, JobFn as tr, parseFetchBody as tt, ApiWithRouter as u, streamSchemas as ua, RawInputs as ui, ConfiguredGroups as un, jobFnAt as ur, createApiReference as ut, GuardMap as v, ToolResult as va, ValidationStage as vi, JobsOfTree as vn, JobWorkerContext as vr, isSuccessStatus as vt, JobsMeta as w, withPermissions as wa, ModelToolCall as wi, ApiDefinition as wn, cron as wr, resolveResponseContentType as wt, HandleArgs as x, AccessCheckInput as xa, formatValidationError as xi, DiffSettings as xn, JobSchedule as xr, mergeHeaderFields as xt, GuardRun as y, expandStreamTools as ya, allowedMethodsForPath as yi, KizunaConfigShape as yn, ScheduledJob as yr, isZodSchema as yt, assembleApi as z, NoCredential as za, ExtractPathParams as zi, JobHandler as zn, GroupSet as zr, PluginApi as zt };