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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +3 -2
  2. package/dist/{adapter-CZW-unqX.mjs → adapter-BSqNrxhq.mjs} +522 -104
  3. package/dist/adapter-C3WYdSfx.d.cts +2754 -0
  4. package/dist/{adapter-DDR_yo9L.cjs → adapter-ClaFZoab.cjs} +638 -196
  5. package/dist/adapter-D4bTPElA.d.mts +2754 -0
  6. package/dist/adapter.cjs +37 -29
  7. package/dist/adapter.d.cts +3 -5
  8. package/dist/adapter.d.mts +3 -5
  9. package/dist/adapter.mjs +5 -5
  10. package/dist/{error-response-C8Ragjcd.cjs → error-response-C9ymqSU4.cjs} +25 -5
  11. package/dist/{error-response-C839d8By.mjs → error-response-CNQaKVYd.mjs} +20 -6
  12. package/dist/{security-scheme-BrszwGD5.d.cts → error-response-NoOGdh8H.d.mts} +151 -24
  13. package/dist/{security-scheme-D3nb4XKj.d.mts → error-response-YbkRMKno.d.cts} +151 -24
  14. package/dist/generator.cjs +190 -95
  15. package/dist/generator.d.cts +189 -28
  16. package/dist/generator.d.mts +189 -28
  17. package/dist/generator.mjs +151 -60
  18. package/dist/index.cjs +159 -84
  19. package/dist/index.d.cts +193 -253
  20. package/dist/index.d.mts +193 -253
  21. package/dist/index.mjs +112 -38
  22. package/dist/jobs-entry.cjs +12 -11
  23. package/dist/jobs-entry.d.cts +1 -1
  24. package/dist/jobs-entry.d.mts +1 -1
  25. package/dist/jobs-entry.mjs +3 -2
  26. package/dist/plugin-Dw-yCjTY.cjs +233 -0
  27. package/dist/{cache-CLN5y0Xp.mjs → plugin-server-BztlE1fz.mjs} +188 -49
  28. package/dist/{cache-BgohRj0i.cjs → plugin-server-kUsK7thV.cjs} +238 -93
  29. package/dist/plugin-xxCxibmu.mjs +138 -0
  30. package/dist/plugin.cjs +8 -72
  31. package/dist/plugin.d.cts +3 -3
  32. package/dist/plugin.d.mts +3 -3
  33. package/dist/plugin.mjs +2 -68
  34. package/dist/{protected-resource-metadata-CA0v5cjg.d.mts → protected-resource-metadata-B9hMFQ9N.d.cts} +1 -1
  35. package/dist/{protected-resource-metadata-Cprrv0mt.d.cts → protected-resource-metadata-CfBVsqIk.d.mts} +1 -1
  36. package/dist/{schemas-C56no6bv.cjs → schemas-DNPVDvkd.cjs} +28 -1
  37. package/dist/{schemas-CJQcc97N.mjs → schemas-HW2FDsvz.mjs} +23 -2
  38. package/dist/schemas.cjs +3 -2
  39. package/dist/schemas.d.cts +24 -3
  40. package/dist/schemas.d.mts +24 -3
  41. package/dist/schemas.mjs +3 -3
  42. package/package.json +1 -1
  43. package/src/adapter.ts +245 -29
  44. package/src/api-definition.ts +12 -16
  45. package/src/api.ts +7 -3
  46. package/src/brand.ts +29 -0
  47. package/src/config.ts +51 -10
  48. package/src/configured.ts +13 -6
  49. package/src/define-config.ts +118 -39
  50. package/src/generator.ts +363 -46
  51. package/src/group-routes.ts +106 -0
  52. package/src/groups.ts +140 -0
  53. package/src/handler-pipeline.ts +78 -19
  54. package/src/index.ts +15 -6
  55. package/src/job-runner.ts +5 -0
  56. package/src/job-transport.ts +3 -3
  57. package/src/job.ts +8 -6
  58. package/src/jobs-dev-runner.ts +6 -0
  59. package/src/jobs.ts +61 -8
  60. package/src/kizuna.ts +56 -33
  61. package/src/plugin-server.ts +129 -19
  62. package/src/plugin.ts +269 -127
  63. package/src/routes.ts +80 -32
  64. package/src/schemas.ts +1 -0
  65. package/src/tool-answer.ts +21 -0
  66. package/src/tool-definitions.ts +166 -0
  67. package/src/tool-events.ts +90 -18
  68. package/src/tool-records.ts +11 -3
  69. package/src/tool-runner.ts +298 -0
  70. package/src/types.ts +90 -24
  71. package/src/zod-internals.ts +22 -5
  72. package/src/zod-meta.ts +7 -2
  73. package/dist/adapter-BGfMqEkM.d.cts +0 -563
  74. package/dist/adapter-Ci3cfcoT.d.mts +0 -563
  75. package/dist/api-definition-BHnh15zD.d.mts +0 -803
  76. package/dist/api-definition-DQj-ewHy.d.cts +0 -803
  77. package/dist/error-response-BBGSdgYw.d.mts +0 -67
  78. package/dist/error-response-Do38sr-9.d.cts +0 -67
  79. package/dist/plugin-Cz0kn6Lk.d.mts +0 -830
  80. package/dist/plugin-DhKvx_T0.d.cts +0 -830
  81. package/src/tags.ts +0 -67
@@ -1,6 +1,6 @@
1
1
  import type { z } from 'zod';
2
2
  import {
3
- ROUTES_TAG,
3
+ ROUTES_GROUP,
4
4
  HANDLER_CONTEXT_BRAND,
5
5
  type HandlerContextBrand,
6
6
  type AutoResponsesBrand,
@@ -19,6 +19,7 @@ import type { ContextOf } from './security-scheme.js';
19
19
  import type { GuardHoldings, IdentityRole } from './identity.js';
20
20
  import { applyCoercion, coercionPlanFor } from './coercion.js';
21
21
  import type { ProblemDetails, StripProblemEnvelope } from './problem-details.js';
22
+ import type { StreamTools } from './tool-runner.js';
22
23
 
23
24
  /**
24
25
  * True when a literal status key is in the 4xx/5xx range. Widened `number` keys (no
@@ -70,18 +71,69 @@ export type ThrowableReturn<R extends Pick<RouteDefinition, 'responses'>> = {
70
71
  [Status in Exclude<keyof R['responses'], StreamStatuses<R>>]: ResponseReturn<R, Status>;
71
72
  }[Exclude<keyof R['responses'], StreamStatuses<R>>];
72
73
 
73
- export type HandlerArgs<R extends RouteDefinition> = {
74
- params: R extends { pathParams: z.ZodType } ? z.output<R['pathParams']> : ExtractPathParams<R['path']>;
75
- query: R extends { query: z.ZodType } ? z.output<R['query']> : undefined;
76
- body: R extends { body: z.ZodType } ? z.output<R['body']> : undefined;
77
- headers: R extends { headers: z.ZodType } ? z.output<R['headers']> : Record<string, string | string[] | undefined>;
78
- /**
79
- * Throws a typed error response. Takes the same `{ status, body }` shape as a handler return.
80
- *
81
- * This function throws internally and never returns.
82
- */
83
- throwError: (response: ThrowableReturn<R> | GuardAnswer<R>) => never;
84
- };
74
+ type StreamToolsOf<R extends RouteDefinition> = {
75
+ [Status in keyof R['responses']]: R['responses'][Status] extends { stream: unknown; tools: infer Tools extends Routes } ? Tools : never;
76
+ }[keyof R['responses']];
77
+
78
+ type ToolsArg<R extends RouteDefinition> = [StreamToolsOf<R>] extends [never]
79
+ ? {}
80
+ : {
81
+ /**
82
+ * Runs the routes this response names under `tools`, as the caller.
83
+ */
84
+ tools: StreamTools<StreamToolsOf<R>>;
85
+ };
86
+
87
+ /**
88
+ * The body as sent, for a route with `rawBody: true`, or nothing.
89
+ */
90
+ type RawBodyArg<R> = R extends { rawBody: true }
91
+ ? {
92
+ /**
93
+ * The body exactly as it was sent, before any parsing. Check a
94
+ * sender's signature against this, not against `body`.
95
+ */
96
+ rawBody: string;
97
+ }
98
+ : unknown;
99
+
100
+ type EventStreamStatuses<R extends Pick<RouteDefinition, 'responses'>> = {
101
+ [Status in keyof R['responses']]: R['responses'][Status] extends { stream: unknown }
102
+ ? R['responses'][Status] extends { contentType: infer ContentType extends string }
103
+ ? 'text/event-stream' extends ContentType
104
+ ? Status
105
+ : never
106
+ : Status
107
+ : never;
108
+ }[keyof R['responses']];
109
+
110
+ /**
111
+ * Where a client that lost an event stream asks it to resume, for a route that streams events.
112
+ */
113
+ type LastEventIdArg<R extends RouteDefinition> = [EventStreamStatuses<R>] extends [never]
114
+ ? unknown
115
+ : {
116
+ /**
117
+ * The `id` of the last event the client received before it reconnected, from its `Last-Event-ID`
118
+ * header. Send what follows it.
119
+ */
120
+ lastEventId: string | undefined;
121
+ };
122
+
123
+ export type HandlerArgs<R extends RouteDefinition> = ToolsArg<R> &
124
+ RawBodyArg<R> &
125
+ LastEventIdArg<R> & {
126
+ params: R extends { pathParams: z.ZodType } ? z.output<R['pathParams']> : ExtractPathParams<R['path']>;
127
+ query: R extends { query: z.ZodType } ? z.output<R['query']> : undefined;
128
+ body: R extends { body: z.ZodType } ? z.output<R['body']> : undefined;
129
+ headers: R extends { headers: z.ZodType } ? z.output<R['headers']> : Record<string, string | string[] | undefined>;
130
+ /**
131
+ * Throws a typed error response. Takes the same `{ status, body }` shape as a handler return.
132
+ *
133
+ * This function throws internally and never returns.
134
+ */
135
+ throwError: (response: ThrowableReturn<R> | GuardAnswer<R>) => never;
136
+ };
85
137
 
86
138
  export type RouteHandler<R extends RouteDefinition, HandlerContext = unknown> = (
87
139
  args: HandlerArgs<R> & HandlerContext & BrandedHandlerContext<R>
@@ -284,12 +336,19 @@ export const isRouteDefinition = (value: unknown): value is RouteDefinition => {
284
336
  export interface FlattenedRoute {
285
337
  routeKey: string;
286
338
  route: RouteDefinition;
287
- routeTags: string[];
339
+ /**
340
+ * The route's groups, as dotted paths, its own first.
341
+ */
342
+ routeGroups: string[];
288
343
  }
289
344
 
290
- export const flattenRoutes = (routes: Routes, prefix?: string, inheritedTags: string[] = []): FlattenedRoute[] => {
291
- const ownTag = (routes as Record<typeof ROUTES_TAG, string | undefined>)[ROUTES_TAG];
292
- const activeTags = ownTag ? [...inheritedTags, ownTag] : inheritedTags;
345
+ /**
346
+ * Flatten a tree of routes, each with its groups.
347
+ */
348
+ export const flattenRoutes = (routes: Routes, prefix?: string, inheritedGroup?: string): FlattenedRoute[] => {
349
+ const declared = (routes as Record<typeof ROUTES_GROUP, string | undefined>)[ROUTES_GROUP];
350
+ // `''` is no group, so the group around it applies.
351
+ const group = declared === undefined || declared === '' ? inheritedGroup : declared;
293
352
  const collected: FlattenedRoute[] = [];
294
353
  for (const [key, value] of Object.entries(routes)) {
295
354
  const fullKey = prefix ? `${prefix}.${key}` : key;
@@ -297,10 +356,10 @@ export const flattenRoutes = (routes: Routes, prefix?: string, inheritedTags: st
297
356
  collected.push({
298
357
  routeKey: fullKey,
299
358
  route: value,
300
- routeTags: activeTags,
359
+ routeGroups: [...new Set([...(group === undefined ? [] : [group]), ...(value.groups ?? [])])],
301
360
  });
302
361
  } else if (value && typeof value === 'object') {
303
- collected.push(...flattenRoutes(value as Routes, fullKey, activeTags));
362
+ collected.push(...flattenRoutes(value as Routes, fullKey, group));
304
363
  }
305
364
  }
306
365
  return collected;
package/src/index.ts CHANGED
@@ -4,7 +4,7 @@ export {
4
4
  Kizuna,
5
5
  type K,
6
6
  type KizunaSpec,
7
- type TagNamesOf,
7
+ type GroupNamesOf,
8
8
  type IdentityNamesOf,
9
9
  type RouteAuthValue,
10
10
  type RouteAuthRule,
@@ -19,19 +19,22 @@ export {
19
19
  type GuardSchemaOf,
20
20
  } from './api-definition.js';
21
21
  export {
22
- createPlugin,
22
+ definePlugin,
23
23
  type PluginDeclaration,
24
24
  type PluginDefinition,
25
+ type PluginFactory,
26
+ type PluginSetup,
27
+ type PluginSetupContext,
28
+ type PluginApi,
25
29
  type PluginRoutes,
26
30
  type ApiPlugins,
27
31
  type PluginExportValues,
28
32
  type PluginArgs,
29
33
  type PluginRoutesOf,
30
- type PluginPropsOf,
31
34
  type PluginExportsOf,
32
35
  } from './plugin.js';
33
36
  export { type ModelOptions } from './model.js';
34
- export { type TagOptions, type TagSet, type TagKeysOf, type NormalizeTags } from './tags.js';
37
+ export { type GroupOptions, type GroupSet, type GroupPaths, type GroupPathsOf, type ResolvedGroup } from './groups.js';
35
38
  export {
36
39
  type Identity,
37
40
  type Credential,
@@ -92,6 +95,8 @@ export {
92
95
  type JobHandlerReturn,
93
96
  type JobsArg,
94
97
  type JobsConfig,
98
+ type HttpJobsConfig,
99
+ type InProcessJobsConfig,
95
100
  type CompiledJobs,
96
101
  type FlattenedJob,
97
102
  type NoJobs,
@@ -136,8 +141,10 @@ export {
136
141
  type ToolAt,
137
142
  } from './tool-events.js';
138
143
  export { readToolCalls, type ToolCallRecord, type ToolCallState, type ToolCallMessage } from './tool-records.js';
144
+ export type { ModelToolCall, StreamTools, ToolAnswer, ToolEventYield, ToolRunCall, ToolRunOptions, ToolRunResult } from './tool-runner.js';
145
+ export type { ToolDefinition } from './tool-definitions.js';
139
146
  export {
140
- createJobTransport,
147
+ defineJobTransport,
141
148
  JobDispatchError,
142
149
  type JobTransport,
143
150
  type JobTransportDefinition,
@@ -222,6 +229,8 @@ export { type AuthCheck, type RouteAuthCheck } from './auth-check.js';
222
229
  export { type JobFnOf, type JobsOfTree, type KizunaConfigShape } from './configured.js';
223
230
  export { defineConfig, type KizunaConfigInput, type ConfiguredApi } from './define-config.js';
224
231
  export { DECLARATION, type DeclarationKind, type RouteToolOptions } from './types.js';
232
+ export { ROUTES_GROUP } from './types.js';
233
+ export { type DeclaredRoutes, type AssembledRoutes } from './group-routes.js';
225
234
  export { isRouteDefinition } from './handler-pipeline.js';
226
235
  export { type Api, type ApiImplementations } from './api.js';
227
236
  export { type RouteBuilder, type RouteWithHandler } from './route.js';
@@ -240,7 +249,7 @@ export {
240
249
  } from './handler-pipeline.js';
241
250
  export { type HandlerContextBrand, HANDLER_CONTEXT_BRAND } from './types.js';
242
251
  export { type AutoResponsesBrand, AUTO_RESPONSES_BRAND, AUTO_GUARD_BRAND, AUTO_GUARD_WRITTEN_BRAND, type GuardStatus } from './types.js';
243
- export { apiEntries, type ApiEntry, type ClientTarget } from './config.js';
252
+ export { apiEntries, type ApiEntry, type DiffSettings, type GeneratedFile } from './config.js';
244
253
  export { type AnyPlugin, type PluginList, type PluginsBySlug } from './plugin.js';
245
254
  export { RESOLVER, type RequestContextBuilder, type RequestContextWithHandler } from './request-context-builder.js';
246
255
  export { GUARD, type IdentityBuilder, type IdentityWithGuard, type GuardFor, type IdentityFactories } from './identity-builder.js';
package/src/job-runner.ts CHANGED
@@ -95,6 +95,10 @@ export interface JobRunnerOptions {
95
95
  */
96
96
  transport?: JobTransport;
97
97
  onError?: JobErrorHandler;
98
+ /**
99
+ * What each plugin exports, handed to every job handler as `plugins`.
100
+ */
101
+ plugins?: Record<string, unknown>;
98
102
  }
99
103
 
100
104
  /**
@@ -180,6 +184,7 @@ export const createJobRunner = <Jobs_ extends Jobs>(
180
184
  throw new ResponseError(response);
181
185
  },
182
186
  jobs: tree,
187
+ plugins: options?.plugins ?? {},
183
188
  })
184
189
  );
185
190
  };
@@ -112,7 +112,7 @@ export class JobDispatchError extends Error {
112
112
  *
113
113
  * @example
114
114
  * export const pgBoss = (boss: PgBoss) =>
115
- * createJobTransport({
115
+ * defineJobTransport({
116
116
  * name: 'pg-boss',
117
117
  * supports: {
118
118
  * retry: true,
@@ -141,8 +141,8 @@ export class JobDispatchError extends Error {
141
141
  * },
142
142
  * });
143
143
  */
144
- export const createJobTransport = (definition: JobTransportDefinition): JobTransport => {
145
- if (!definition.name) throw new Error('createJobTransport needs a `name`.');
144
+ export const defineJobTransport = (definition: JobTransportDefinition): JobTransport => {
145
+ if (!definition.name) throw new Error('defineJobTransport needs a `name`.');
146
146
  return {
147
147
  ...definition,
148
148
  supports: definition.supports ?? {},
package/src/job.ts CHANGED
@@ -4,8 +4,8 @@ import { DECLARATION, HANDLER } from './types.js';
4
4
  /**
5
5
  * A job's handler, typed against the job it answers.
6
6
  */
7
- export type JobHandlerFor<Definition extends AuthoredJobDefinition> = (
8
- args: JobHandlerArgs<Definition>
7
+ export type JobHandlerFor<Definition extends AuthoredJobDefinition, HandlerContext = unknown> = (
8
+ args: JobHandlerArgs<Definition> & HandlerContext
9
9
  ) => Promise<JobHandlerReturn<Definition> | JobVoidReturn<Definition>> | JobHandlerReturn<Definition> | JobVoidReturn<Definition>;
10
10
 
11
11
  /**
@@ -19,14 +19,16 @@ export type JobWithHandler<Definition extends AuthoredJobDefinition> = Definitio
19
19
  * What `k.job` returns: the job itself, and the `handler` that runs it. A job
20
20
  * nothing runs, one a generator reads, needs no handler.
21
21
  */
22
- export type JobBuilder<Definition extends AuthoredJobDefinition> = Definition & JobHandlerStep<Definition>;
22
+ export type JobBuilder<Definition extends AuthoredJobDefinition, HandlerContext = unknown> = Definition &
23
+ JobHandlerStep<Definition, HandlerContext>;
23
24
 
24
- interface JobHandlerStep<Definition extends AuthoredJobDefinition> {
25
+ interface JobHandlerStep<Definition extends AuthoredJobDefinition, HandlerContext> {
25
26
  /**
26
27
  * The handler that runs this job. `input` is typed from the job's schema,
27
- * and the return is checked against its `result`.
28
+ * `plugins` from the config, and the return is checked against its
29
+ * `result`.
28
30
  */
29
- handler(fn: JobHandlerFor<Definition>): JobWithHandler<Definition>;
31
+ handler(fn: JobHandlerFor<Definition, HandlerContext>): JobWithHandler<Definition>;
30
32
  }
31
33
 
32
34
  export const createJob = <const Definition extends AuthoredJobDefinition>(definition: Definition): JobBuilder<Definition> =>
@@ -70,6 +70,12 @@ export const startJobsDevRunner = (contract: ApiDefinition, options: JobsDevRunn
70
70
  );
71
71
  }
72
72
 
73
+ if (contract.jobsConfig?.mode === 'in-process') {
74
+ throw new Error(
75
+ "[kizuna/schedule] startJobsDevRunner ticks the dispatch endpoint, which `mode: 'in-process'` does not serve. " +
76
+ 'Run the schedules in this process with `startJobs` instead.'
77
+ );
78
+ }
73
79
  const method = contract.jobsConfig?.method ?? 'POST';
74
80
  const path = `${options.basePath ?? ''}${contract.jobsConfig?.path ?? DEFAULT_JOBS_PATH}/dispatch`;
75
81
  const url = `${stripTrailingSlash(options.baseUrl)}${path}`;
package/src/jobs.ts CHANGED
@@ -8,16 +8,28 @@ import type { JobTransport } from './job-transport.js';
8
8
  import type { PathClaim } from './path-claims.js';
9
9
 
10
10
  /**
11
- * The namespace the job endpoints are mounted under when `jobs.path` says
11
+ * The namespace the job endpoints are mounted under when `jobRunner.path` says
12
12
  * nothing.
13
13
  */
14
14
  export const DEFAULT_JOBS_PATH = '/jobs';
15
15
 
16
16
  /**
17
- * Settings shared by every job, named in `defineConfig` under `jobsConfig`. The jobs
17
+ * Settings shared by every job, named in `defineConfig` under `jobRunner`. The jobs
18
18
  * themselves are declared with `k.jobs`.
19
19
  */
20
- export interface JobsConfig {
20
+ export type JobsConfig = HttpJobsConfig | InProcessJobsConfig;
21
+
22
+ /**
23
+ * Jobs triggered over HTTP, by platform cron ticking `/jobs/dispatch` or a
24
+ * transport delivering to `/jobs/run`.
25
+ */
26
+ export interface HttpJobsConfig {
27
+ /**
28
+ * `'http'` serves `/jobs/dispatch` and `/jobs/run`, guarded by the jobs'
29
+ * identity. `'in-process'` is for a long-running server whose schedules
30
+ * `startJobs` ticks, and serves neither.
31
+ */
32
+ mode: 'http';
21
33
  /**
22
34
  * The namespace both job endpoints are mounted under, `dispatch` and `run`
23
35
  * beneath it. Nothing is served on the namespace itself.
@@ -49,11 +61,30 @@ export interface JobsConfig {
49
61
  }
50
62
 
51
63
  /**
52
- * How a deployment runs the jobs it declares: where the two endpoints sit, what
64
+ * Jobs a long-running server runs itself, its schedules ticked by `startJobs`.
65
+ * No job endpoint is served, so the jobs need no identity.
66
+ */
67
+ export interface InProcessJobsConfig {
68
+ mode: 'in-process';
69
+ path?: never;
70
+ method?: never;
71
+ windowMs?: never;
72
+ only?: never;
73
+ exclude?: never;
74
+ }
75
+
76
+ /**
77
+ * How a deployment runs the jobs it declares: how they are triggered, what
53
78
  * carries queued work out of the process, and where a failure that happened
54
79
  * after the response went out is reported.
55
80
  */
56
- export interface JobRunnerConfig extends JobsConfig {
81
+ export type JobRunnerConfig = JobsConfig & JobDeliveryConfig;
82
+
83
+ /**
84
+ * Where queued work goes and where a late failure is reported, whichever way
85
+ * the jobs are triggered.
86
+ */
87
+ export interface JobDeliveryConfig {
57
88
  /**
58
89
  * Carries a queued job to whatever runs it. Without one, `queue` runs the
59
90
  * job in this process and it is lost on a crash.
@@ -181,8 +212,9 @@ export type JobHandlerReturn<Definition extends JobDefinition> = HandlerReturn<{
181
212
  }>;
182
213
 
183
214
  /**
184
- * The single object a job handler receives: its own input and `throwError`, and
185
- * nothing else. Anything more it imports, as a route handler would.
215
+ * The input and `throwError` every job handler receives. It also receives the
216
+ * api's `jobs` and, when the config installs any, the plugins' exports as
217
+ * `plugins`.
186
218
  */
187
219
  export type JobHandlerArgs<Definition extends JobDefinition> = {
188
220
  /**
@@ -402,8 +434,29 @@ export const isCompiledJob = (value: unknown): value is CompiledJob => {
402
434
  * Throws when either job endpoint lands on a path an API route already serves.
403
435
  * Called by `defineConfig`, the one place that sees both.
404
436
  */
437
+ /**
438
+ * Throw when declared jobs do not say how they run, or when the job endpoints
439
+ * would be served with no identity guarding them.
440
+ */
441
+ export const assertJobRunner = (jobs: Jobs | undefined, config: JobsConfig | undefined): void => {
442
+ const flattened = jobs ? flattenJobs(jobs) : [];
443
+ if (flattened.length === 0) return;
444
+ if (config?.mode === undefined) {
445
+ throw new Error(
446
+ "The jobs do not say how they run. Set `jobRunner: { mode: 'http' }` to serve `/jobs/dispatch` and `/jobs/run`, " +
447
+ "or `jobRunner: { mode: 'in-process' }` when `startJobs` ticks them in this process."
448
+ );
449
+ }
450
+ if (config.mode === 'in-process' || flattened.some(({ job }) => job.identity !== undefined)) return;
451
+ const base = config.path ?? DEFAULT_JOBS_PATH;
452
+ throw new Error(
453
+ `The jobs declare no identity, so \`${base}/dispatch\` and \`${base}/run\` would let anyone trigger them. ` +
454
+ "Pass an identity to `k.jobs`, or set `jobRunner: { mode: 'in-process' }` when the jobs run in this process with `startJobs`."
455
+ );
456
+ };
457
+
405
458
  export const jobClaims = (jobs: Jobs | undefined, config: JobsConfig | undefined): PathClaim[] => {
406
- if (!jobs || flattenJobs(jobs).length === 0) return [];
459
+ if (!jobs || config?.mode === 'in-process' || flattenJobs(jobs).length === 0) return [];
407
460
  const base = config?.path ?? DEFAULT_JOBS_PATH;
408
461
  return [
409
462
  {
package/src/kizuna.ts CHANGED
@@ -1,20 +1,21 @@
1
1
  import type { z } from 'zod';
2
- import { tagRoutes } from './routes.js';
2
+ import { createGroupRoutes, type GroupRoutes } from './group-routes.js';
3
3
  import { addCodedIssue, type RegisteredIssue } from './coded-issue.js';
4
4
  import { buildJobs, type AuthoredJobs, type AuthoredJobDefinition, type CompiledJobs } from './jobs.js';
5
- import { createTags, type TagOptions } from './tags.js';
5
+ import { createGroups, type GroupOptions, type GroupPaths } from './groups.js';
6
6
  import type { RolesOf } from './identity.js';
7
7
  import { createPermissions, createRoles, type CatalogOf, type PermissionSet, type RoleNamesOf } from './permissions.js';
8
8
  import { createRequestContext, type RequestContextConfig } from './request-context.js';
9
9
  import { createRequestContextBuilder, type RequestContextBuilder } from './request-context-builder.js';
10
10
  import { identityFactories, type IdentityFactories } from './identity-builder.js';
11
11
  import { createModel } from './model.js';
12
+ import { createBrand } from './brand.js';
12
13
  import { type GuardBody, type GuardOutput } from './problem-details.js';
13
- import type { Routes, AuthoredRoutes, AuthoredRouteDefinition } from './types.js';
14
+ import type { AuthoredRouteDefinition, RouteHiddenToolCheck } from './types.js';
14
15
  import type { SecurityScheme } from './security-scheme.js';
15
16
  import type { RequestContextSchema } from './request-context.js';
16
- import type { PathParamsCheck, RoutePathParamsCheck } from './path-params.js';
17
- import type { AuthCheck, RouteAuthCheck } from './auth-check.js';
17
+ import type { RoutePathParamsCheck } from './path-params.js';
18
+ import type { RouteAuthCheck } from './auth-check.js';
18
19
  import { createRoute, type RouteBuilder } from './route.js';
19
20
  import { createJob, type JobBuilder } from './job.js';
20
21
  import type { AnyAdapter } from './adapter.js';
@@ -29,7 +30,7 @@ import type {
29
30
  ConfiguredPlugins,
30
31
  ConfiguredRequestContext,
31
32
  ConfiguredRequestContextSchemas,
32
- ConfiguredTags,
33
+ ConfiguredGroups,
33
34
  KizunaConfigShape,
34
35
  } from './configured.js';
35
36
 
@@ -86,7 +87,7 @@ export type RouteAuthRule<Id extends string = string, Identities = Record<string
86
87
  * What a {@link Kizuna} instance declares.
87
88
  */
88
89
  export interface KizunaSpec {
89
- tags: Record<string, TagOptions>;
90
+ groups: Record<string, GroupOptions | string>;
90
91
  codes: string;
91
92
  identities: Record<string, SecurityScheme>;
92
93
  requestContext: Record<string, RequestContextSchema>;
@@ -96,9 +97,9 @@ export interface KizunaSpec {
96
97
  }
97
98
 
98
99
  /**
99
- * The tag names declared on a spec, e.g. `'health' | 'users'`.
100
+ * The dotted group paths a spec declares.
100
101
  */
101
- export type TagNamesOf<Spec extends KizunaSpec> = Extract<keyof Spec['tags'], string>;
102
+ export type GroupNamesOf<Spec extends KizunaSpec> = GroupPaths<Spec['groups']>;
102
103
 
103
104
  /**
104
105
  * The identity names declared on a spec, e.g. `'user' | 'member'`.
@@ -114,7 +115,7 @@ export interface K<Spec extends KizunaSpec = KizunaSpec> {
114
115
  * `query` and `headers` are typed from the route, and the return is checked
115
116
  * against its `responses`.
116
117
  *
117
- * Group routes with `k.routes`, which takes the routes this returns.
118
+ * File routes into a group with `k.routes`.
118
119
  *
119
120
  * @example
120
121
  * export const createUser = k
@@ -133,23 +134,26 @@ export interface K<Spec extends KizunaSpec = KizunaSpec> {
133
134
  * body: await db.users.create(body.name),
134
135
  * }));
135
136
  */
136
- route<const Definition extends AuthoredRouteDefinition<TagNamesOf<Spec>, IdentityNamesOf<Spec>>>(
137
- definition: Definition & RoutePathParamsCheck<Definition> & RouteAuthCheck<Definition, Spec['identities']>
137
+ route<const Definition extends AuthoredRouteDefinition<GroupNamesOf<Spec>, IdentityNamesOf<Spec>>>(
138
+ definition: Definition &
139
+ RoutePathParamsCheck<Definition> &
140
+ RouteAuthCheck<Definition, Spec['identities']> &
141
+ RouteHiddenToolCheck<Definition>
138
142
  ): RouteBuilder<
139
143
  Definition & RouteGuardBrandOf<Definition, GuardOutput<Spec['guardSchema']>, GuardBody<Spec['guardSchema']>>,
140
144
  HandlerContextFor<Spec, Definition>
141
145
  >;
142
146
  /**
143
- * Define a group of routes. Pass a tag (one of the keys from `k.tags`)
144
- * to group them in the OpenAPI document, or omit it for an untagged group.
147
+ * Declare routes into a group. Call `k.routes` itself for routes in no
148
+ * group.
149
+ *
150
+ * @example
151
+ * export const memberRoutes = k.routes.workspace.members({
152
+ * listMembers,
153
+ * removeMember,
154
+ * });
145
155
  */
146
- routes<const T extends AuthoredRoutes<TagNamesOf<Spec>, IdentityNamesOf<Spec>>>(
147
- tag: TagNamesOf<Spec>,
148
- defs: T & PathParamsCheck<T> & AuthCheck<T, Spec['identities']>
149
- ): T;
150
- routes<const T extends AuthoredRoutes<string, IdentityNamesOf<Spec>>>(
151
- defs: T & PathParamsCheck<T> & AuthCheck<T, Spec['identities']>
152
- ): T;
156
+ routes: GroupRoutes<Spec['groups'], GroupNamesOf<Spec>, IdentityNamesOf<Spec>, Spec['identities']>;
153
157
  /**
154
158
  * Declare one job and the handler that runs it. `input` is typed from the
155
159
  * job's schema, and the return is checked against its `result`.
@@ -169,7 +173,7 @@ export interface K<Spec extends KizunaSpec = KizunaSpec> {
169
173
  * },
170
174
  * }));
171
175
  */
172
- job<const Definition extends AuthoredJobDefinition>(definition: Definition): JobBuilder<Definition>;
176
+ job<const Definition extends AuthoredJobDefinition>(definition: Definition): JobBuilder<Definition, JobHandlerContextFor<Spec>>;
173
177
  /**
174
178
  * Declare scheduled jobs. Pass the identity every job requires, the one
175
179
  * credential your scheduler sends, then the jobs themselves.
@@ -220,10 +224,19 @@ export interface K<Spec extends KizunaSpec = KizunaSpec> {
220
224
  * });
221
225
  */
222
226
  /**
223
- * Declare the OpenAPI tags routes are grouped under. `k.routes` takes one of
224
- * these names.
227
+ * Declare the groups routes are filed under.
228
+ *
229
+ * @example
230
+ * export const groups = k.groups({
231
+ * workspace: {
232
+ * title: 'Workspace',
233
+ * groups: {
234
+ * members: 'Members',
235
+ * },
236
+ * },
237
+ * });
225
238
  */
226
- tags: typeof createTags;
239
+ groups: typeof createGroups;
227
240
  identity: IdentityFactories<
228
241
  ConfiguredAdapterContext<Spec['config']>,
229
242
  ConfiguredRequestContext<Spec['config']>,
@@ -275,7 +288,7 @@ export interface K<Spec extends KizunaSpec = KizunaSpec> {
275
288
  * is checked against.
276
289
  */
277
290
  type SpecOf<Config> = {
278
- tags: ConfiguredTags<Config>;
291
+ groups: ConfiguredGroups<Config>;
279
292
  codes: ConfiguredCodes<Config>;
280
293
  identities: ConfiguredIdentities<Config>;
281
294
  requestContext: ConfiguredRequestContextSchemas<Config>;
@@ -295,21 +308,26 @@ export type HandlerContextFor<Spec extends KizunaSpec, Definition> = AuthContext
295
308
  ConfiguredPlugins<Spec['config']> &
296
309
  ConfiguredAdapterContext<Spec['config']>;
297
310
 
311
+ /**
312
+ * What every job's handler receives beyond its input, typed: the installed
313
+ * plugins' exports. `jobs` reaches it at runtime too, but stays untyped here,
314
+ * since the generated `Config` holds `typeof jobs` and a job typed from it would
315
+ * depend on itself.
316
+ */
317
+ export type JobHandlerContextFor<Spec extends KizunaSpec> = ConfiguredPlugins<Spec['config']>;
318
+
298
319
  const createSurface = <Config>(): K<SpecOf<Config>> => {
299
320
  type Spec = SpecOf<Config>;
300
321
 
301
- const routes = ((tagOrDefs: string | Routes, defs?: Routes) =>
302
- defs === undefined ? tagRoutes(tagOrDefs as Routes) : tagRoutes(tagOrDefs as string, defs as Routes)) as K<Spec>['routes'];
303
-
304
322
  const jobs = ((identityOrDefinitions: string | AuthoredJobs, definitions?: AuthoredJobs) =>
305
323
  definitions === undefined
306
324
  ? buildJobs(undefined, identityOrDefinitions as AuthoredJobs)
307
325
  : buildJobs(identityOrDefinitions as string, definitions)) as K<Spec>['jobs'];
308
326
 
309
327
  return {
310
- tags: createTags,
328
+ groups: createGroups,
311
329
  route: createRoute as K<Spec>['route'],
312
- routes,
330
+ routes: createGroupRoutes() as K<Spec>['routes'],
313
331
  job: createJob as K<Spec>['job'],
314
332
  jobs,
315
333
  identity: identityFactories as unknown as K<Spec>['identity'],
@@ -324,7 +342,7 @@ const createSurface = <Config>(): K<SpecOf<Config>> => {
324
342
  * `kizuna generate` writes, which is what every name on `k` is checked against
325
343
  * and what types everything a handler receives.
326
344
  *
327
- * `k.route` declares a route with its handler, `k.routes` groups them, and
345
+ * `k.route` declares a route with its handler, `k.routes` files them into groups, and
328
346
  * `k.job` and `k.jobs` do the same for jobs.
329
347
  * `defineConfig` assembles them.
330
348
  *
@@ -339,6 +357,11 @@ export class Kizuna<Config extends KizunaConfigShape = Record<string, never>> im
339
357
  * the one type rather than inlining it.
340
358
  */
341
359
  static readonly model = createModel;
360
+ /**
361
+ * Brand a schema, so the server and every generated client type its values
362
+ * as that brand.
363
+ */
364
+ static readonly brand = createBrand;
342
365
  /**
343
366
  * Declare the permissions callers hold, as a catalog of resources and the
344
367
  * verbs each allows.
@@ -349,7 +372,7 @@ export class Kizuna<Config extends KizunaConfigShape = Record<string, never>> im
349
372
  */
350
373
  static readonly roles = createRoles;
351
374
 
352
- declare readonly tags: K<SpecOf<Config>>['tags'];
375
+ declare readonly groups: K<SpecOf<Config>>['groups'];
353
376
  declare readonly route: K<SpecOf<Config>>['route'];
354
377
  declare readonly routes: K<SpecOf<Config>>['routes'];
355
378
  declare readonly job: K<SpecOf<Config>>['job'];