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
package/src/generator.ts CHANGED
@@ -3,8 +3,13 @@ import { flattenJobs, isCompiledJob, jobAt, type CompiledJob, type FlattenedJob,
3
3
  import { parsePath } from './path-params.js';
4
4
  import type { Routes, RouteDefinition } from './types.js';
5
5
  import type { ApiDefinition } from './api-definition.js';
6
+ import { isRouteDefinition } from './handler-pipeline.js';
7
+ import { describeIssue, pluginRoutesOf } from './plugin-server.js';
8
+ import { globalRegistrySchemas, readMetaDescription } from './zod-internals.js';
9
+ import type { GeneratedFile } from './config.js';
10
+ import type { z } from 'zod';
6
11
 
7
- export type { Routes, RouteDefinition };
12
+ export type { Routes, RouteDefinition, GeneratedFile };
8
13
  export { flattenJobs, isCompiledJob, jobAt };
9
14
  export type { CompiledJob, FlattenedJob, Jobs };
10
15
  export { parsePath };
@@ -24,6 +29,7 @@ export {
24
29
  readMeta,
25
30
  readMetaId,
26
31
  readMetaDescription,
32
+ readMetaBrand,
27
33
  readMetaExamples,
28
34
  readDeprecation,
29
35
  readDiscriminatorLiteral,
@@ -74,7 +80,10 @@ export {
74
80
  export interface GeneratorRouteContext {
75
81
  routeKey: string;
76
82
  route: RouteDefinition;
77
- routeTags: string[];
83
+ /**
84
+ * The route's groups, as dotted paths, its own first.
85
+ */
86
+ routeGroups: string[];
78
87
  /**
79
88
  * Whether the route is deprecated.
80
89
  */
@@ -84,56 +93,364 @@ export interface GeneratorRouteContext {
84
93
  * `undefined` when the route declares neither.
85
94
  */
86
95
  deprecationMessage: string | undefined;
96
+ /**
97
+ * Whether the route is `hidden`. Clients and the OpenAPI document leave a
98
+ * hidden route out; a generator listing every served route marks it.
99
+ */
100
+ hidden: boolean;
101
+ /**
102
+ * The plugin the route comes from, or `undefined` for the app's own. A
103
+ * plugin's routes sit under its slug.
104
+ */
105
+ plugin: GeneratorPluginInfo | undefined;
106
+ }
107
+
108
+ /**
109
+ * Where a plugin's route came from.
110
+ */
111
+ export interface GeneratorPluginInfo {
112
+ /**
113
+ * The slug the app installed the plugin under.
114
+ */
115
+ slug: string;
116
+ }
117
+
118
+ /**
119
+ * Every route the api serves, the app's and the plugins' under their slugs,
120
+ * each with the plugin it came from.
121
+ */
122
+ const servedRoutes = (
123
+ contract: ApiDefinition
124
+ ): Array<ReturnType<typeof flattenRoutes>[number] & { plugin: GeneratorPluginInfo | undefined }> => [
125
+ ...flattenRoutes(contract.routes).map((entry) => ({
126
+ ...entry,
127
+ plugin: undefined,
128
+ })),
129
+ ...Object.entries(pluginRoutesOf(contract)).flatMap(([slug, routes]) =>
130
+ flattenRoutes(routes as Routes, slug).map((entry) => ({
131
+ ...entry,
132
+ plugin: {
133
+ slug,
134
+ },
135
+ }))
136
+ ),
137
+ ];
138
+
139
+ const withoutHidden = (routes: Routes): Routes => {
140
+ const listed: Record<string | symbol, unknown> = {};
141
+ // `Object.entries` skips the group symbol.
142
+ for (const symbol of Object.getOwnPropertySymbols(routes)) {
143
+ listed[symbol] = (routes as Record<symbol, unknown>)[symbol];
144
+ }
145
+ for (const [key, value] of Object.entries(routes)) {
146
+ if (isRouteDefinition(value)) {
147
+ if ((value as RouteDefinition).hidden !== true) listed[key] = value;
148
+ continue;
149
+ }
150
+ if (value && typeof value === 'object') {
151
+ const group = withoutHidden(value as Routes);
152
+ if (Object.keys(group).length > 0) listed[key] = group;
153
+ }
154
+ }
155
+ return listed as Routes;
156
+ };
157
+
158
+ /**
159
+ * The route tree the generated clients hold: the app's routes, less every
160
+ * `hidden` one.
161
+ */
162
+ export const listedRoutes = (contract: ApiDefinition): Routes => withoutHidden(contract.routes);
163
+
164
+ /**
165
+ * A named model the api uses.
166
+ */
167
+ export interface GeneratorModelContext {
168
+ /**
169
+ * The model's title, e.g. `User`.
170
+ */
171
+ name: string;
172
+ /**
173
+ * The schema to generate a type from.
174
+ */
175
+ schema: z.ZodType;
176
+ /**
177
+ * The model's description, for a doc comment.
178
+ */
179
+ description: string | undefined;
180
+ /**
181
+ * The plugin that brought it, when only a plugin's routes use it.
182
+ */
183
+ plugin: GeneratorPluginInfo | undefined;
184
+ }
185
+
186
+ /**
187
+ * What a client's or a generator's `generate` returns: a callback for each
188
+ * model and route, then `finalize`, which returns the result.
189
+ */
190
+ export interface GeneratorWalk<Output = string> {
191
+ /**
192
+ * Called once for every named model the walked routes use, sorted by name.
193
+ */
194
+ processModel?: (model: GeneratorModelContext) => void;
195
+ /**
196
+ * Called once for every route, in the order the api declares them.
197
+ */
198
+ processRoute?: (context: GeneratorRouteContext) => void;
199
+ /**
200
+ * Called once, after the walk.
201
+ */
202
+ finalize: () => Output;
203
+ }
204
+
205
+ export interface WalkApiOptions {
206
+ /**
207
+ * Leave `hidden` routes out of the walk, and the models only they use.
208
+ *
209
+ * @default false
210
+ */
211
+ skipHidden?: boolean;
212
+ }
213
+
214
+ const isSchema = (value: unknown): value is z.core.$ZodType =>
215
+ typeof value === 'object' && value !== null && '_zod' in value && typeof (value as z.core.$ZodType)._zod?.def?.type === 'string';
216
+
217
+ /**
218
+ * Every `Kizuna.model` schema reachable from a value, found by walking its
219
+ * schemas and whatever plain objects and lists hold them.
220
+ */
221
+ const reachModels = (value: unknown, models: Map<z.core.$ZodType, string>, found: Set<z.core.$ZodType>, seen: Set<unknown>): void => {
222
+ if (typeof value !== 'object' || value === null || seen.has(value)) return;
223
+ seen.add(value);
224
+ if (isSchema(value)) {
225
+ if (models.has(value)) found.add(value);
226
+ const def = value._zod.def as unknown as Record<string, unknown>;
227
+ for (const [key, child] of Object.entries(def)) {
228
+ if (key === 'checks') continue;
229
+ if (key === 'getter' && typeof child === 'function') {
230
+ reachModels((child as () => unknown)(), models, found, seen);
231
+ continue;
232
+ }
233
+ reachModels(child, models, found, seen);
234
+ }
235
+ return;
236
+ }
237
+ for (const child of Array.isArray(value) ? value : Object.values(value)) {
238
+ reachModels(child, models, found, seen);
239
+ }
240
+ };
241
+
242
+ /**
243
+ * The named models the given routes use, sorted by name, each with the plugin
244
+ * that brought it when none of the app's own routes use it.
245
+ */
246
+ const modelsOf = (entries: ReadonlyArray<{ route: RouteDefinition; plugin: GeneratorPluginInfo | undefined }>): GeneratorModelContext[] => {
247
+ const models = new Map<z.core.$ZodType, string>();
248
+ for (const [id, schema] of globalRegistrySchemas()) models.set(schema, id);
249
+
250
+ const owners = new Map<z.core.$ZodType, GeneratorPluginInfo | undefined>();
251
+ const appFirst = [...entries].sort((left, right) => Number(left.plugin !== undefined) - Number(right.plugin !== undefined));
252
+ for (const { route, plugin } of appFirst) {
253
+ const found = new Set<z.core.$ZodType>();
254
+ reachModels(route, models, found, new Set());
255
+ for (const schema of found) {
256
+ if (!owners.has(schema)) owners.set(schema, plugin);
257
+ }
258
+ }
259
+
260
+ return [...owners]
261
+ .map(([schema, plugin]) => ({
262
+ name: models.get(schema)!,
263
+ schema: schema as z.ZodType,
264
+ description: readMetaDescription(schema),
265
+ plugin,
266
+ }))
267
+ .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
268
+ };
269
+
270
+ const deprecationMessageOf = (route: RouteDefinition): string | undefined =>
271
+ typeof route.deprecated === 'string' ? route.deprecated : typeof route.deprecated === 'object' ? route.deprecated.message : undefined;
272
+
273
+ /**
274
+ * Run a walk over an api: its models, then every route it serves, the app's
275
+ * and each plugin's under its slug. Returns what `finalize` returns.
276
+ *
277
+ * @example
278
+ * const routeList = walkApi(api, {
279
+ * processRoute: ({ route }) => lines.push(`${route.method} ${route.path}`),
280
+ * finalize: () => lines.join('\n'),
281
+ * });
282
+ */
283
+ export const walkApi = <Output>(api: ApiDefinition, walk: GeneratorWalk<Output>, options: WalkApiOptions = {}): Output => {
284
+ const entries = servedRoutes(api).filter(({ route }) => options.skipHidden !== true || route.hidden !== true);
285
+ if (walk.processModel !== undefined) {
286
+ for (const model of modelsOf(entries)) walk.processModel(model);
287
+ }
288
+ for (const { routeKey, route, routeGroups, plugin } of entries) {
289
+ walk.processRoute?.({
290
+ routeKey,
291
+ route,
292
+ routeGroups,
293
+ hidden: route.hidden === true,
294
+ plugin,
295
+ deprecated: route.deprecated !== undefined && route.deprecated !== false,
296
+ deprecationMessage: deprecationMessageOf(route),
297
+ });
298
+ }
299
+ return walk.finalize();
300
+ };
301
+
302
+ type OptionsOutput<Schema> = Schema extends z.ZodType ? z.output<Schema> : Record<string, never>;
303
+ type OptionsInput<Schema> = Schema extends z.ZodType ? z.input<Schema> : {};
304
+
305
+ /**
306
+ * What `generate` receives.
307
+ */
308
+ export interface GenerateContext<Options> {
309
+ /**
310
+ * The options the app passed, less `output`, validated against the
311
+ * `options` schema.
312
+ */
313
+ options: Options;
314
+ /**
315
+ * The api being generated from.
316
+ */
317
+ api: ApiDefinition;
87
318
  }
88
319
 
89
320
  /**
90
- * Factory for building type-safe routes generators.
321
+ * What every client and generator takes beside its own options.
322
+ */
323
+ export interface GeneratedFileOptions {
324
+ /**
325
+ * Path the file is written to, resolved against the config's directory.
326
+ */
327
+ output: string;
328
+ }
329
+
330
+ const parseOptions = <Schema extends z.ZodType | undefined>(
331
+ schema: Schema | undefined,
332
+ input: Record<string, unknown>,
333
+ name: string
334
+ ): OptionsOutput<Schema> => {
335
+ if (schema === undefined) return input as OptionsOutput<Schema>;
336
+ const parsed = schema.safeParse(input);
337
+ if (!parsed.success) {
338
+ throw new Error(`[kizuna] ${name} has invalid options: ${parsed.error.issues.map(describeIssue).join('; ')}`);
339
+ }
340
+ return parsed.data as OptionsOutput<Schema>;
341
+ };
342
+
343
+ /**
344
+ * What {@link defineClient} takes.
345
+ */
346
+ export interface ClientDefinition<Schema extends z.ZodType | undefined> {
347
+ /**
348
+ * The language this client generates, like `dart`.
349
+ */
350
+ target: string;
351
+ /**
352
+ * A Zod schema for what the app passes in, beside `output`.
353
+ */
354
+ options?: Schema;
355
+ /**
356
+ * Returns the walk. Kizuna calls it on every `kizuna generate`, and skips
357
+ * hidden routes, so one never reaches `processRoute`.
358
+ */
359
+ generate: (context: GenerateContext<OptionsOutput<Schema>>) => GeneratorWalk;
360
+ }
361
+
362
+ /**
363
+ * Declare a client for a language: the options an app passes it, and the walk
364
+ * that returns its file. Returns the function an app names under `clients`.
91
365
  *
92
- * Centralises routes walking and deprecation resolution so generator authors
93
- * only need to implement `processRoute` and `finalize`. Field-level deprecation
94
- * lives on the schemas themselves, read with `readDeprecation`.
366
+ * @example
367
+ * export const dartClient = defineClient({
368
+ * target: 'dart',
369
+ * options: z.object({
370
+ * library: z.string().default('api'),
371
+ * }),
372
+ * generate: ({ options }) => {
373
+ * const writer = new DartWriter(options.library);
95
374
  *
96
- * ```ts
97
- * const generateRouteList = createGenerator(() => {
98
- * const routeList: string[] = [];
99
- * return {
100
- * processRoute({ route, deprecated }) {
101
- * routeList.push(`${route.method} ${route.path}${deprecated ? ' (deprecated)' : ''}`);
102
- * },
103
- * finalize() {
104
- * return routeList;
105
- * },
106
- * };
375
+ * return {
376
+ * processModel: (model) => writer.model(model),
377
+ * processRoute: (context) => writer.method(context),
378
+ * finalize: () => writer.render(),
379
+ * };
380
+ * },
107
381
  * });
382
+ */
383
+ export const defineClient =
384
+ <Schema extends z.ZodType | undefined = undefined>(
385
+ definition: ClientDefinition<Schema>
386
+ ): ((options: OptionsInput<Schema> & GeneratedFileOptions) => GeneratedFile) =>
387
+ (input) => {
388
+ const { output, ...rest } = input as GeneratedFileOptions & Record<string, unknown>;
389
+ const options = parseOptions<Schema>(definition.options, rest, `Client '${definition.target}'`);
390
+ return {
391
+ target: definition.target,
392
+ output,
393
+ render: (api) =>
394
+ walkApi(
395
+ api,
396
+ definition.generate({
397
+ options,
398
+ api,
399
+ }),
400
+ {
401
+ skipHidden: true,
402
+ }
403
+ ),
404
+ };
405
+ };
406
+
407
+ /**
408
+ * What {@link defineGenerator} takes.
409
+ */
410
+ export interface GeneratorDefinition<Schema extends z.ZodType | undefined> {
411
+ /**
412
+ * A Zod schema for what the plugin passes in, beside `output`.
413
+ */
414
+ options?: Schema;
415
+ /**
416
+ * Returns the walk. It sees every served route, hidden ones included, and
417
+ * decides what to leave out.
418
+ */
419
+ generate: (context: GenerateContext<OptionsOutput<Schema>>) => GeneratorWalk;
420
+ }
421
+
422
+ /**
423
+ * Declare a generator for a file that isn't a client, like a document or a
424
+ * manifest. A plugin installs it by returning it from `setup`.
425
+ *
426
+ * @example
427
+ * export const gatewayManifest = defineGenerator({
428
+ * generate: () => {
429
+ * const entries: string[] = [];
108
430
  *
109
- * const list = generateRouteList(kizuna.api, {});
110
- * ```
431
+ * return {
432
+ * processRoute: ({ route }) => entries.push(`${route.method} ${route.path}`),
433
+ * finalize: () => entries.join('\n'),
434
+ * };
435
+ * },
436
+ * });
111
437
  */
112
- export const createGenerator =
113
- <Options, Output>(
114
- factory: (
115
- options: Options,
116
- contract: ApiDefinition
117
- ) => {
118
- processRoute: (context: GeneratorRouteContext) => void;
119
- finalize: () => Output;
120
- }
121
- ): ((contract: ApiDefinition, options: Options) => Output) =>
122
- (contract, options) => {
123
- const { processRoute, finalize } = factory(options, contract);
124
- for (const { routeKey, route, routeTags } of flattenRoutes(contract.routes)) {
125
- processRoute({
126
- routeKey,
127
- route,
128
- routeTags,
129
- deprecated: route.deprecated !== undefined && route.deprecated !== false,
130
- deprecationMessage:
131
- typeof route.deprecated === 'string'
132
- ? route.deprecated
133
- : typeof route.deprecated === 'object'
134
- ? route.deprecated.message
135
- : undefined,
136
- });
137
- }
138
- return finalize();
438
+ export const defineGenerator =
439
+ <Schema extends z.ZodType | undefined = undefined>(
440
+ definition: GeneratorDefinition<Schema>
441
+ ): ((options: OptionsInput<Schema> & GeneratedFileOptions) => GeneratedFile) =>
442
+ (input) => {
443
+ const { output, ...rest } = input as GeneratedFileOptions & Record<string, unknown>;
444
+ const options = parseOptions<Schema>(definition.options, rest, `The generator for '${output}'`);
445
+ return {
446
+ output,
447
+ render: (api) =>
448
+ walkApi(
449
+ api,
450
+ definition.generate({
451
+ options,
452
+ api,
453
+ })
454
+ ),
455
+ };
139
456
  };
@@ -0,0 +1,106 @@
1
+ import { groupRoutes } from './routes.js';
2
+ import { ROUTES_GROUP, type AuthoredRoutes, type Routes } from './types.js';
3
+ import type { PathParamsCheck } from './path-params.js';
4
+ import type { AuthCheck } from './auth-check.js';
5
+
6
+ /**
7
+ * Routes from `k.routes`, carrying their group's path, `''` for none.
8
+ */
9
+ export type DeclaredRoutes<T, Path extends string> = T & {
10
+ readonly [ROUTES_GROUP]?: Path;
11
+ };
12
+
13
+ /**
14
+ * Declare a tree of routes into one group.
15
+ */
16
+ type DeclareRoutes<Path extends string, GroupPaths extends string, Names extends string, Identities> = <
17
+ const T extends AuthoredRoutes<GroupPaths, Names>,
18
+ >(
19
+ routes: T & PathParamsCheck<T> & AuthCheck<T, Identities>
20
+ ) => DeclaredRoutes<T, Path>;
21
+
22
+ /**
23
+ * The groups nested under one.
24
+ */
25
+ type NestedOf<Options> = Options extends { groups: infer Nested } ? Nested : {};
26
+
27
+ /**
28
+ * A group on `k.routes`: callable, and indexable by its nested groups.
29
+ */
30
+ export type GroupAccessor<Options, Path extends string, GroupPaths extends string, Names extends string, Identities> = DeclareRoutes<
31
+ Path,
32
+ GroupPaths,
33
+ Names,
34
+ Identities
35
+ > & {
36
+ readonly [Key in Extract<keyof NestedOf<Options>, string>]: GroupAccessor<
37
+ NestedOf<Options>[Key],
38
+ `${Path}.${Key}`,
39
+ GroupPaths,
40
+ Names,
41
+ Identities
42
+ >;
43
+ };
44
+
45
+ /**
46
+ * `k.routes`: callable for routes in no group, and indexable by group.
47
+ */
48
+ export type GroupRoutes<Declared, GroupPaths extends string, Names extends string, Identities> = DeclareRoutes<
49
+ '',
50
+ GroupPaths,
51
+ Names,
52
+ Identities
53
+ > & {
54
+ readonly [Key in Extract<keyof Declared, string>]: GroupAccessor<Declared[Key], Key, GroupPaths, Names, Identities>;
55
+ };
56
+
57
+ /**
58
+ * A tree, nested at its group's path.
59
+ */
60
+ type NestAt<Path extends string, T> = Path extends ''
61
+ ? T
62
+ : Path extends `${infer Head}.${infer Rest}`
63
+ ? {
64
+ [Key in Head]: NestAt<Rest, T>;
65
+ }
66
+ : {
67
+ [Key in Path]: T;
68
+ };
69
+
70
+ type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (value: infer Intersection) => void
71
+ ? Intersection
72
+ : never;
73
+
74
+ type GroupOf<T> = T extends { readonly [ROUTES_GROUP]?: infer Path extends string } ? (string extends Path ? '' : Path) : '';
75
+
76
+ /**
77
+ * The route tree `defineConfig` builds from its list.
78
+ */
79
+ export type AssembledRoutes<List extends readonly unknown[]> = [List[number]] extends [never]
80
+ ? Record<string, never>
81
+ : UnionToIntersection<
82
+ {
83
+ [Index in keyof List]: NestAt<GroupOf<List[Index]>, Omit<List[Index], typeof ROUTES_GROUP>>;
84
+ }[number]
85
+ > extends infer Tree extends Routes
86
+ ? Tree
87
+ : Routes;
88
+
89
+ /**
90
+ * The runtime half of {@link GroupRoutes}. `k` never sees the groups, so
91
+ * `defineConfig` checks each path.
92
+ */
93
+ export const createGroupRoutes = (): unknown => {
94
+ const accessors = new Map<string, unknown>();
95
+ const accessorAt = (path: string): unknown => {
96
+ const cached = accessors.get(path);
97
+ if (cached !== undefined) return cached;
98
+ const accessor = new Proxy(() => {}, {
99
+ apply: (_target, _this, [routes]: [Routes]) => groupRoutes(path, routes),
100
+ get: (_target, key) => (typeof key === 'string' ? accessorAt(path === '' ? key : `${path}.${key}`) : undefined),
101
+ });
102
+ accessors.set(path, accessor);
103
+ return accessor;
104
+ };
105
+ return accessorAt('');
106
+ };
package/src/groups.ts ADDED
@@ -0,0 +1,140 @@
1
+ export interface GroupOptions {
2
+ /**
3
+ * The group's name in the docs. Unique among its siblings.
4
+ */
5
+ title: string;
6
+ /**
7
+ * Shown beside the group in the OpenAPI document.
8
+ */
9
+ description?: string;
10
+ /**
11
+ * External documentation for the group.
12
+ */
13
+ externalDocs?: {
14
+ url: string;
15
+ description?: string;
16
+ };
17
+ /**
18
+ * The groups nested under this one.
19
+ */
20
+ groups?: Record<string, GroupOptions | string>;
21
+ }
22
+
23
+ /**
24
+ * A declared group, with its place in the tree.
25
+ */
26
+ export interface ResolvedGroup {
27
+ /**
28
+ * Its dotted path, `'workspace.members'`.
29
+ */
30
+ readonly path: string;
31
+ readonly title: string;
32
+ readonly description?: string;
33
+ readonly externalDocs?: GroupOptions['externalDocs'];
34
+ /**
35
+ * Dotted paths from the top group down to this one.
36
+ */
37
+ readonly lineage: readonly string[];
38
+ }
39
+
40
+ /**
41
+ * The groups from `k.groups`.
42
+ */
43
+ export interface GroupSet<Declared extends Record<string, GroupOptions | string> = Record<string, GroupOptions | string>> {
44
+ readonly __brand: 'GroupSet';
45
+ /**
46
+ * The tree as written, for its type.
47
+ */
48
+ readonly declared: Declared;
49
+ /**
50
+ * Every group by dotted path, parents first.
51
+ */
52
+ readonly groups: ReadonlyMap<string, ResolvedGroup>;
53
+ }
54
+
55
+ /**
56
+ * Every dotted path a `k.groups` input declares.
57
+ */
58
+ export type GroupPaths<Declared> = {
59
+ [Key in Extract<keyof Declared, string>]:
60
+ | Key
61
+ | (Declared[Key] extends { groups: infer Nested } ? `${Key}.${GroupPaths<Nested>}` : never);
62
+ }[Extract<keyof Declared, string>];
63
+
64
+ /**
65
+ * The dotted group paths a {@link GroupSet} declares.
66
+ */
67
+ export type GroupPathsOf<Set extends GroupSet> = Set extends GroupSet<infer Declared> ? GroupPaths<Declared> : never;
68
+
69
+ export const isGroupSet = (value: unknown): value is GroupSet =>
70
+ typeof value === 'object' && value !== null && '__brand' in value && (value as GroupSet).__brand === 'GroupSet';
71
+
72
+ const collect = (declared: Record<string, GroupOptions | string>, ancestors: readonly string[], into: Map<string, ResolvedGroup>): void => {
73
+ for (const [key, value] of Object.entries(declared)) {
74
+ if (key.includes('.')) {
75
+ throw new Error(`The group "${key}" has a dot in its key. Nest it under \`groups\` instead.`);
76
+ }
77
+ const options = typeof value === 'string' ? { title: value } : value;
78
+ const parent = ancestors[ancestors.length - 1];
79
+ const path = parent === undefined ? key : `${parent}.${key}`;
80
+ const lineage = [...ancestors, path];
81
+ into.set(path, {
82
+ path,
83
+ title: options.title,
84
+ ...(options.description === undefined
85
+ ? {}
86
+ : {
87
+ description: options.description,
88
+ }),
89
+ ...(options.externalDocs === undefined
90
+ ? {}
91
+ : {
92
+ externalDocs: options.externalDocs,
93
+ }),
94
+ lineage,
95
+ });
96
+ if (options.groups) collect(options.groups, lineage, into);
97
+ }
98
+ };
99
+
100
+ /**
101
+ * Throw on two siblings with one title.
102
+ */
103
+ const assertUniqueTitles = (groups: ReadonlyMap<string, ResolvedGroup>): void => {
104
+ const owners = new Map<string, string>();
105
+ for (const group of groups.values()) {
106
+ const parent = group.lineage[group.lineage.length - 2] ?? '';
107
+ const sibling = `${parent}\u0000${group.title}`;
108
+ const owner = owners.get(sibling);
109
+ if (owner !== undefined) {
110
+ throw new Error(`The groups "${owner}" and "${group.path}" share the title "${group.title}". Give each group its own title.`);
111
+ }
112
+ owners.set(sibling, group.path);
113
+ }
114
+ };
115
+
116
+ /**
117
+ * Declare the groups routes are filed under. A string is shorthand for
118
+ * `{ title }`.
119
+ *
120
+ * @example
121
+ * const groups = k.groups({
122
+ * workspace: {
123
+ * title: 'Workspace',
124
+ * groups: {
125
+ * members: 'Members',
126
+ * },
127
+ * },
128
+ * health: 'Health',
129
+ * });
130
+ */
131
+ export const createGroups = <const Declared extends Record<string, GroupOptions | string>>(declared: Declared): GroupSet<Declared> => {
132
+ const groups = new Map<string, ResolvedGroup>();
133
+ collect(declared, [], groups);
134
+ assertUniqueTitles(groups);
135
+ return {
136
+ __brand: 'GroupSet',
137
+ declared,
138
+ groups,
139
+ };
140
+ };