@kizunajs/fetch 2.0.0-beta.2 → 2.0.0-beta.20

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.
package/dist/index.mjs CHANGED
@@ -1,263 +1,1036 @@
1
- import { buildPath, isProblemDetails, isRouteDefinition, isStreamResponse, isValidationError, streamMode } from "kizunajs";
2
- //#region src/sse.ts
3
- const parseData = (text) => {
4
- try {
5
- return JSON.parse(text);
6
- } catch {
7
- return text;
8
- }
1
+ import { ValidationErrorSchema } from "kizunajs/schemas";
2
+ import { defineClient, isBinarySchema, isFileSchema, isStreamResponse, isVoidSchema, listedRoutes, readDef, readDeprecation, readDiscriminatedUnion, readMetaBrand, readMetaDescription, readMetaExamples, readMetaId, readObjectShape, resolveResponseBody, resolveResponseHeaders, sanitizeIdentifier, streamContentType, streamMode, toPascalCase, unwrapOptionalWrappers } from "kizunajs/generator";
3
+ import { z } from "zod";
4
+ //#region src/runtime.ts
5
+ /**
6
+ * The code every generated client runs, written into the file below its route
7
+ * table. It imports nothing, so a client installs nothing, and it always comes
8
+ * from the release that wrote the table it reads.
9
+ */
10
+ const runtimeSource = String.raw`/**
11
+ * What the client knows about one response: nothing for a body it reads as
12
+ * JSON, the media type for one that streams.
13
+ */
14
+ export type GeneratedResponse =
15
+ | Record<string, never>
16
+ | {
17
+ stream: true;
18
+ contentType: string;
19
+ };
20
+
21
+ /**
22
+ * One route in the table: how to reach it, and how to read each status it
23
+ * answers with.
24
+ */
25
+ export interface GeneratedRoute {
26
+ method: string;
27
+ path: string;
28
+ contentType?: string;
29
+ responses: Record<number, GeneratedResponse>;
30
+ }
31
+
32
+ /**
33
+ * The route table, nested the way the client is.
34
+ */
35
+ export interface GeneratedRoutes {
36
+ [key: string]: GeneratedRoutes | GeneratedRoute;
37
+ }
38
+
39
+ /**
40
+ * The request onRequest receives before it is sent. A header set on headers
41
+ * is sent with it.
42
+ */
43
+ export interface OutgoingRequest {
44
+ url: string;
45
+ method: string;
46
+ headers: Headers;
47
+ route: GeneratedRoute;
48
+ }
49
+
50
+ /**
51
+ * Where the client sends its requests, and what it adds to each one.
52
+ */
53
+ export interface ClientConfig {
54
+ baseUrl: string;
55
+ baseHeaders?: Record<string, string>;
56
+ credentials?: RequestCredentials;
57
+ fetch?: typeof fetch;
58
+ onRequest?: (request: OutgoingRequest) => void | Promise<void>;
59
+ retry?: RetryOptions;
60
+ }
61
+
62
+ /**
63
+ * Retries a GET, HEAD, OPTIONS, PUT or DELETE that failed on the network or
64
+ * was answered 429 or 503, waiting what Retry-After asks or backing off.
65
+ */
66
+ export interface RetryOptions {
67
+ /**
68
+ * Attempts in all, the first included.
69
+ */
70
+ maximumAttempts?: number;
71
+ /**
72
+ * Milliseconds the first backoff waits at most.
73
+ */
74
+ initialDelay?: number;
75
+ /**
76
+ * Milliseconds any wait may take.
77
+ */
78
+ maximumDelay?: number;
79
+ }
80
+
81
+ /**
82
+ * One method on the client. Its '~route' names the method it sends and
83
+ * whether its response streams, so a wrapper like @kizunajs/tanstack-query
84
+ * reads both off the client.
85
+ */
86
+ export type ClientMethod<Method extends string, Streams extends boolean, Args, Result> = ({} extends Args
87
+ ? (args?: Args) => Promise<Result>
88
+ : (args: Args) => Promise<Result>) & {
89
+ readonly '~route': GeneratedRoute & {
90
+ readonly method: Method;
91
+ readonly streams: Streams;
92
+ };
93
+ };
94
+
95
+ interface CallArgs {
96
+ params?: Record<string, unknown>;
97
+ query?: Record<string, unknown>;
98
+ body?: unknown;
99
+ headers?: Record<string, string | undefined>;
100
+ fetchOptions?: RequestInit;
101
+ }
102
+
103
+ /**
104
+ * Dates go on the wire as ISO 8601, everything else as String gives it.
105
+ */
106
+ const serializeValue = (value: unknown): string => (value instanceof Date ? value.toISOString() : String(value));
107
+
108
+ const buildPath = (path: string, params: Record<string, unknown> = {}): string =>
109
+ path.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, (_, name: string) => {
110
+ const value = params[name];
111
+ if (value === undefined) throw new Error('Missing path parameter: ' + name);
112
+ return encodeURIComponent(serializeValue(value));
113
+ });
114
+
115
+ /**
116
+ * An array repeats its key, and an undefined or null field is left out.
117
+ */
118
+ const buildSearchParams = (fields: Record<string, unknown>): URLSearchParams => {
119
+ const params = new URLSearchParams();
120
+ for (const [key, value] of Object.entries(fields)) {
121
+ if (value === undefined || value === null) continue;
122
+ for (const item of Array.isArray(value) ? value : [value]) params.append(key, serializeValue(item));
123
+ }
124
+ return params;
125
+ };
126
+
127
+ const buildFormData = (fields: Record<string, unknown>): FormData => {
128
+ const formData = new FormData();
129
+ for (const [key, value] of Object.entries(fields)) {
130
+ for (const item of Array.isArray(value) ? value : [value]) {
131
+ if (item instanceof Blob) formData.append(key, item);
132
+ else if (item !== undefined && item !== null) formData.append(key, typeof item === 'string' ? item : JSON.stringify(item));
133
+ }
134
+ }
135
+ return formData;
136
+ };
137
+
138
+ /**
139
+ * A multipart body leaves Content-Type to fetch, which adds the boundary.
140
+ */
141
+ const encodeBody = (route: GeneratedRoute, body: unknown, headers: Headers): BodyInit => {
142
+ switch (route.contentType) {
143
+ case 'multipart/form-data':
144
+ return body instanceof FormData ? body : buildFormData(body as Record<string, unknown>);
145
+ case 'application/x-www-form-urlencoded':
146
+ if (!headers.has('Content-Type')) headers.set('Content-Type', 'application/x-www-form-urlencoded');
147
+ return buildSearchParams(body as Record<string, unknown>);
148
+ default:
149
+ if (!headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
150
+ return JSON.stringify(body);
151
+ }
152
+ };
153
+
154
+ const parseJson = (text: string): unknown => {
155
+ try {
156
+ return JSON.parse(text) as unknown;
157
+ } catch {
158
+ return text;
159
+ }
160
+ };
161
+
162
+ interface ServerSentEvent {
163
+ event?: string;
164
+ data: unknown;
165
+ id?: string;
166
+ retry?: number;
167
+ }
168
+
169
+ /**
170
+ * A lone carriage return at the end may be half of CRLF, so it waits for more
171
+ * unless the stream is over.
172
+ */
173
+ const findLineEnd = (buffer: string, final: boolean): { index: number; length: number } | undefined => {
174
+ for (let index = 0; index < buffer.length; index += 1) {
175
+ const character = buffer[index];
176
+ if (character === '\n') return { index, length: 1 };
177
+ if (character === '\r') {
178
+ if (index + 1 < buffer.length) return { index, length: buffer[index + 1] === '\n' ? 2 : 1 };
179
+ if (final) return { index, length: 1 };
180
+ return undefined;
181
+ }
182
+ }
183
+ return undefined;
184
+ };
185
+
186
+ /**
187
+ * Reads text/event-stream as the WHATWG HTML specification parses it.
188
+ */
189
+ async function* readEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<ServerSentEvent> {
190
+ const reader = body.getReader();
191
+ const decoder = new TextDecoder();
192
+ let buffer = '';
193
+ let first = true;
194
+ let dataLines: string[] = [];
195
+ let eventType = '';
196
+ let lastEventId = '';
197
+ let retry: number | undefined;
198
+
199
+ const dispatch = (): ServerSentEvent | undefined => {
200
+ if (dataLines.length === 0) {
201
+ eventType = '';
202
+ return undefined;
203
+ }
204
+ const message: ServerSentEvent = {
205
+ data: parseJson(dataLines.join('\n')),
206
+ };
207
+ if (eventType !== '') message.event = eventType;
208
+ if (lastEventId !== '') message.id = lastEventId;
209
+ if (retry !== undefined) message.retry = retry;
210
+ dataLines = [];
211
+ eventType = '';
212
+ retry = undefined;
213
+ return message;
214
+ };
215
+
216
+ const processLine = (line: string): ServerSentEvent | undefined => {
217
+ if (line === '') return dispatch();
218
+ if (line.startsWith(':')) return undefined;
219
+ const separator = line.indexOf(':');
220
+ const field = separator === -1 ? line : line.slice(0, separator);
221
+ let value = separator === -1 ? '' : line.slice(separator + 1);
222
+ if (value.startsWith(' ')) value = value.slice(1);
223
+ switch (field) {
224
+ case 'event':
225
+ eventType = value;
226
+ break;
227
+ case 'data':
228
+ dataLines.push(value);
229
+ break;
230
+ case 'id':
231
+ if (!value.includes('\0')) lastEventId = value;
232
+ break;
233
+ case 'retry':
234
+ if (/^\d+$/.test(value)) retry = Number(value);
235
+ break;
236
+ }
237
+ return undefined;
238
+ };
239
+
240
+ try {
241
+ for (;;) {
242
+ const { done, value } = await reader.read();
243
+ let chunk = done ? decoder.decode() : decoder.decode(value, { stream: true });
244
+ if (first && chunk.length > 0) {
245
+ if (chunk.charCodeAt(0) === 0xfeff) chunk = chunk.slice(1);
246
+ first = false;
247
+ }
248
+ buffer += chunk;
249
+ for (;;) {
250
+ const lineEnd = findLineEnd(buffer, done);
251
+ if (lineEnd === undefined) break;
252
+ const line = buffer.slice(0, lineEnd.index);
253
+ buffer = buffer.slice(lineEnd.index + lineEnd.length);
254
+ const message = processLine(line);
255
+ if (message !== undefined) yield message;
256
+ }
257
+ if (done) return;
258
+ }
259
+ } finally {
260
+ void reader.cancel().catch(() => undefined);
261
+ }
262
+ }
263
+
264
+ async function* readText(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
265
+ const reader = body.getReader();
266
+ const decoder = new TextDecoder();
267
+ try {
268
+ for (;;) {
269
+ const { done, value } = await reader.read();
270
+ if (done) {
271
+ const tail = decoder.decode();
272
+ if (tail.length > 0) yield tail;
273
+ return;
274
+ }
275
+ const text = decoder.decode(value, { stream: true });
276
+ if (text.length > 0) yield text;
277
+ }
278
+ } finally {
279
+ void reader.cancel().catch(() => undefined);
280
+ }
281
+ }
282
+
283
+ async function* readBytes(body: ReadableStream<Uint8Array>): AsyncGenerator<Uint8Array> {
284
+ const reader = body.getReader();
285
+ try {
286
+ for (;;) {
287
+ const { done, value } = await reader.read();
288
+ if (done) return;
289
+ yield value;
290
+ }
291
+ } finally {
292
+ void reader.cancel().catch(() => undefined);
293
+ }
294
+ }
295
+
296
+ const readStream = (body: ReadableStream<Uint8Array>, contentType: string): AsyncIterable<unknown> => {
297
+ const essence = (contentType.split(';')[0] ?? '').trim().toLowerCase();
298
+ if (essence === 'text/event-stream') return readEvents(body);
299
+ if (essence.startsWith('text/')) return readText(body);
300
+ return readBytes(body);
301
+ };
302
+
303
+ const IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
304
+
305
+ const RETRY_STATUSES = new Set([429, 503]);
306
+
307
+ const retryAfter = (header: string | null): number | undefined => {
308
+ if (header === null) return undefined;
309
+ if (/^\d+$/.test(header.trim())) return Number(header.trim()) * 1000;
310
+ const date = Date.parse(header);
311
+ return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
312
+ };
313
+
314
+ const wait = (milliseconds: number, signal: AbortSignal | null | undefined): Promise<void> =>
315
+ new Promise((resolve, reject) => {
316
+ if (signal?.aborted) {
317
+ reject(signal.reason);
318
+ return;
319
+ }
320
+ const onAbort = () => {
321
+ clearTimeout(timer);
322
+ reject(signal?.reason);
323
+ };
324
+ const timer = setTimeout(() => {
325
+ signal?.removeEventListener('abort', onAbort);
326
+ resolve();
327
+ }, milliseconds);
328
+ signal?.addEventListener('abort', onAbort, {
329
+ once: true,
330
+ });
331
+ });
332
+
333
+ const send = async (url: string, init: RequestInit, route: GeneratedRoute, config: ClientConfig): Promise<Response> => {
334
+ const fetcher = config.fetch ?? fetch;
335
+ const retry = config.retry;
336
+ if (retry === undefined || !IDEMPOTENT_METHODS.has(route.method)) return fetcher(url, init);
337
+ const maximumAttempts = retry.maximumAttempts ?? 3;
338
+ const initialDelay = retry.initialDelay ?? 500;
339
+ const maximumDelay = retry.maximumDelay ?? 30_000;
340
+ for (let attempt = 1; ; attempt += 1) {
341
+ const backoff = Math.random() * Math.min(maximumDelay, initialDelay * 2 ** (attempt - 1));
342
+ let response: Response;
343
+ try {
344
+ response = await fetcher(url, init);
345
+ } catch (error) {
346
+ if (attempt >= maximumAttempts || init.signal?.aborted || !(error instanceof TypeError)) throw error;
347
+ await wait(backoff, init.signal);
348
+ continue;
349
+ }
350
+ if (attempt >= maximumAttempts || !RETRY_STATUSES.has(response.status)) return response;
351
+ const asked = retryAfter(response.headers.get('retry-after'));
352
+ if (asked !== undefined && asked > maximumDelay) return response;
353
+ await response.body?.cancel();
354
+ await wait(asked ?? backoff, init.signal);
355
+ }
356
+ };
357
+
358
+ const buildMethod = (route: GeneratedRoute, config: ClientConfig) => {
359
+ const call = async (args: CallArgs = {}) => {
360
+ const query = args.query === undefined ? '' : buildSearchParams(args.query).toString();
361
+ const url = config.baseUrl + buildPath(route.path, args.params) + (query.length > 0 ? '?' + query : '');
362
+ const headers = new Headers(config.baseHeaders);
363
+ for (const [name, value] of Object.entries(args.headers ?? {})) {
364
+ if (value !== undefined) headers.set(name, value);
365
+ }
366
+ const init: RequestInit = {
367
+ method: route.method,
368
+ headers,
369
+ };
370
+ if (args.body !== undefined) init.body = encodeBody(route, args.body, headers);
371
+ if (config.credentials !== undefined) init.credentials = config.credentials;
372
+ await config.onRequest?.({
373
+ url,
374
+ method: route.method,
375
+ headers,
376
+ route,
377
+ });
378
+
379
+ const response = await send(
380
+ url,
381
+ {
382
+ ...init,
383
+ ...args.fetchOptions,
384
+ },
385
+ route,
386
+ config
387
+ );
388
+ const responseHeaders: Record<string, string> = {};
389
+ response.headers.forEach((value, name) => {
390
+ responseHeaders[name] = value;
391
+ });
392
+ const declared = route.responses[response.status];
393
+ if (declared !== undefined && 'stream' in declared && response.body !== null) {
394
+ return {
395
+ status: response.status,
396
+ body: readStream(response.body, declared.contentType),
397
+ headers: responseHeaders,
398
+ };
399
+ }
400
+ const text = await response.text();
401
+ return {
402
+ status: response.status,
403
+ body: text.length > 0 ? parseJson(text) : undefined,
404
+ headers: responseHeaders,
405
+ };
406
+ };
407
+ const streams = Object.values(route.responses).some((response) => 'stream' in response);
408
+ return Object.defineProperty(call, '~route', {
409
+ value: {
410
+ ...route,
411
+ streams,
412
+ },
413
+ });
414
+ };
415
+
416
+ const isRoute = (node: GeneratedRoutes | GeneratedRoute): node is GeneratedRoute => typeof node['method'] === 'string';
417
+
418
+ const buildTree = (routes: GeneratedRoutes, config: ClientConfig): Record<string, unknown> => {
419
+ const tree: Record<string, unknown> = {};
420
+ for (const [key, node] of Object.entries(routes)) {
421
+ tree[key] = isRoute(node) ? buildMethod(node, config) : buildTree(node, config);
422
+ }
423
+ return tree;
9
424
  };
10
- const findLineEnd = (buffer, final) => {
11
- for (let index = 0; index < buffer.length; index += 1) {
12
- const character = buffer[index];
13
- if (character === "\n") return {
14
- index,
15
- length: 1
16
- };
17
- if (character === "\r") {
18
- if (index + 1 < buffer.length) return {
19
- index,
20
- length: buffer[index + 1] === "\n" ? 2 : 1
21
- };
22
- if (final) return {
23
- index,
24
- length: 1
25
- };
26
- return;
425
+
426
+ /**
427
+ * Sends the request context headers with every request. An explicit
428
+ * baseHeaders entry wins.
429
+ */
430
+ const buildClient = (routes: GeneratedRoutes, config: ClientConfig & { requestContext?: object }): Record<string, unknown> => {
431
+ const contextHeaders: Record<string, string> = {};
432
+ for (const [name, value] of Object.entries(config.requestContext ?? {})) {
433
+ if (value !== undefined) contextHeaders[name] = String(value);
434
+ }
435
+ return buildTree(routes, {
436
+ ...config,
437
+ baseHeaders: {
438
+ ...contextHeaders,
439
+ ...config.baseHeaders,
440
+ },
441
+ });
442
+ };
443
+ `;
444
+ //#endregion
445
+ //#region src/zod-to-typescript.ts
446
+ /**
447
+ * Collects the named types a walk produces, so a model shared by many routes is
448
+ * declared once.
449
+ */
450
+ var TypeCollector = class {
451
+ named = /* @__PURE__ */ new Map();
452
+ claimed = /* @__PURE__ */ new Set();
453
+ brands = /* @__PURE__ */ new Map();
454
+ /**
455
+ * Which side of a pipe a schema is read from: the input a request sends, or
456
+ * the output a response carries.
457
+ */
458
+ direction = "output";
459
+ /**
460
+ * Reads the schemas `read` walks from the side a request sends.
461
+ */
462
+ readingInput(read) {
463
+ const previous = this.direction;
464
+ this.direction = "input";
465
+ try {
466
+ return read();
467
+ } finally {
468
+ this.direction = previous;
27
469
  }
28
470
  }
471
+ readsInput() {
472
+ return this.direction === "input";
473
+ }
474
+ /**
475
+ * Claims a name before its body is walked, so a model that refers to itself
476
+ * resolves to its own name instead of recursing. Answers whether the caller
477
+ * is the one that has to emit it.
478
+ */
479
+ claim(name) {
480
+ if (this.claimed.has(name)) return false;
481
+ this.claimed.add(name);
482
+ return true;
483
+ }
484
+ add(type) {
485
+ this.named.set(type.name, type);
486
+ }
487
+ /**
488
+ * Declares a brand as a named type, `UserId = string & KizunaBrand<"UserId">`,
489
+ * and answers the name.
490
+ */
491
+ addBrand(brand, base, example) {
492
+ const name = sanitizeIdentifier(brand);
493
+ const existing = this.brands.get(name);
494
+ if (existing !== void 0 && (existing.brand !== brand || existing.base !== base)) throw new Error(`@kizunajs/fetch: brand ${quote(brand)} wraps both ${existing.base} and ${base}. Give each its own name.`);
495
+ if (existing === void 0) this.brands.set(name, {
496
+ brand,
497
+ base,
498
+ example
499
+ });
500
+ return name;
501
+ }
502
+ usesBrand() {
503
+ return this.brands.size > 0;
504
+ }
505
+ /**
506
+ * Each brand's name, the type it wraps, and a value for its `@example`, for
507
+ * the constructors the file exports.
508
+ */
509
+ allBrands() {
510
+ return [...this.brands].map(([name, { base, example }]) => ({
511
+ name,
512
+ base,
513
+ example
514
+ }));
515
+ }
516
+ all() {
517
+ for (const name of this.brands.keys()) if (this.named.has(name)) throw new Error(`@kizunajs/fetch: brand ${quote(name)} has the same name as a model. Give each its own name.`);
518
+ const brands = [...this.brands].map(([name, { brand, base }]) => ({
519
+ name,
520
+ description: `A branded \`${base}\`. Responses hand one back, and \`to${name}\` makes one from a plain value.`,
521
+ body: `${base} & KizunaBrand<${quote(brand)}>`
522
+ }));
523
+ return [...this.named.values(), ...brands].sort((left, right) => left.name.localeCompare(right.name));
524
+ }
29
525
  };
526
+ const quote = (value) => JSON.stringify(value);
30
527
  /**
31
- * Parses `text/event-stream` per the WHATWG HTML specification.
528
+ * What a brand wraps: the scalars, as the JSON carries them.
32
529
  */
33
- async function* parseServerSentEvents(body) {
34
- const reader = body.getReader();
35
- const decoder = new TextDecoder();
36
- let buffer = "";
37
- let first = true;
38
- let dataLines = [];
39
- let eventType = "";
40
- let lastEventId = "";
41
- let retry;
42
- const dispatch = () => {
43
- if (dataLines.length === 0) {
44
- eventType = "";
45
- return;
46
- }
47
- const message = { data: parseData(dataLines.join("\n")) };
48
- if (eventType !== "") message.event = eventType;
49
- if (lastEventId !== "") message.id = lastEventId;
50
- if (retry !== void 0) message.retry = retry;
51
- dataLines = [];
52
- eventType = "";
53
- retry = void 0;
54
- return message;
55
- };
56
- const processLine = (line) => {
57
- if (line === "") return dispatch();
58
- if (line.startsWith(":")) return void 0;
59
- const separator = line.indexOf(":");
60
- const field = separator === -1 ? line : line.slice(0, separator);
61
- let value = separator === -1 ? "" : line.slice(separator + 1);
62
- if (value.startsWith(" ")) value = value.slice(1);
63
- switch (field) {
64
- case "event":
65
- eventType = value;
66
- break;
67
- case "data":
68
- dataLines.push(value);
69
- break;
70
- case "id":
71
- if (!value.includes("\0")) lastEventId = value;
72
- break;
73
- case "retry":
74
- if (/^\d+$/.test(value)) retry = Number(value);
75
- break;
76
- }
77
- };
78
- try {
79
- for (;;) {
80
- const { done, value } = await reader.read();
81
- let chunk = done ? decoder.decode() : decoder.decode(value, { stream: true });
82
- if (first && chunk.length > 0) {
83
- if (chunk.charCodeAt(0) === 65279) chunk = chunk.slice(1);
84
- first = false;
85
- }
86
- buffer += chunk;
87
- for (;;) {
88
- const lineEnd = findLineEnd(buffer, done);
89
- if (lineEnd === void 0) break;
90
- const line = buffer.slice(0, lineEnd.index);
91
- buffer = buffer.slice(lineEnd.index + lineEnd.length);
92
- const message = processLine(line);
93
- if (message !== void 0) yield message;
94
- }
95
- if (done) return;
96
- }
97
- } finally {
98
- reader.cancel().catch(() => void 0);
530
+ const BRANDABLE_BASES = new Set([
531
+ "string",
532
+ "number",
533
+ "boolean"
534
+ ]);
535
+ /**
536
+ * A literal as the type the JSON carries, so `z.literal(true)` is `true`.
537
+ */
538
+ const literalType = (value) => {
539
+ if (typeof value === "string") return quote(value);
540
+ if (typeof value === "bigint") return `${value}n`;
541
+ if (value === void 0) return "undefined";
542
+ return String(value);
543
+ };
544
+ const indent$1 = (text, depth = 1) => text.split("\n").map((line) => line.length > 0 ? " ".repeat(depth) + line : line).join("\n");
545
+ /**
546
+ * A property name, quoted only when it is not a plain identifier.
547
+ */
548
+ const propertyKey = (key) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : quote(key);
549
+ /**
550
+ * A doc comment over the lines it is given, or nothing when there are none.
551
+ * Always multi-line, the way the rest of this repository writes them.
552
+ */
553
+ const docComment = (lines) => {
554
+ const body = lines.flatMap((line) => line.split("\n"));
555
+ if (body.length === 0) return "";
556
+ return `/**\n${body.map((line) => ` * ${line}`.trimEnd()).join("\n")}\n */\n`;
557
+ };
558
+ /**
559
+ * Renders a declared example as the TypeScript literal a caller would write.
560
+ */
561
+ const exampleLiteral = (value) => {
562
+ if (typeof value === "string") return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
563
+ if (value === void 0) return "undefined";
564
+ return JSON.stringify(value) ?? "undefined";
565
+ };
566
+ const STRING_SAMPLES = {
567
+ email: "ada@example.com",
568
+ url: "https://example.com",
569
+ uuid: "3f1c2d9e-5b6a-4c7d-8e9f-0a1b2c3d4e5f",
570
+ datetime: "2026-01-01T00:00:00Z",
571
+ date: "2026-01-01",
572
+ time: "00:00:00"
573
+ };
574
+ const stringSample = (schema, key) => {
575
+ const def = readDef(schema);
576
+ const formats = [def.format, ...(def.checks ?? []).map((check) => check.format ?? check.def?.format)];
577
+ for (const format of formats) if (format !== void 0 && format in STRING_SAMPLES) return exampleLiteral(STRING_SAMPLES[format]);
578
+ if (key !== void 0 && /id$/i.test(key)) return exampleLiteral("1");
579
+ return exampleLiteral("string");
580
+ };
581
+ /**
582
+ * A value a caller could pass for a schema, used in the `@example` on each
583
+ * client method. A schema that declares an example is taken at its word;
584
+ * anything else gets a value of the right shape.
585
+ */
586
+ const sampleValue = (schema, depth = 0, key) => {
587
+ const [declared] = readMetaExamples(schema);
588
+ if (declared !== void 0) return exampleLiteral(declared);
589
+ if (isFileSchema(schema)) return "new File([], 'upload.txt')";
590
+ if (isBinarySchema(schema)) return "new Uint8Array()";
591
+ const def = readDef(schema);
592
+ if (def.type === "default" && def.defaultValue !== void 0) return exampleLiteral(def.defaultValue);
593
+ if (def.type === "pipe") {
594
+ const side = def.in ?? def.out;
595
+ return side ? sampleValue(side, depth, key) : "undefined";
99
596
  }
100
- }
101
- async function* readTextChunks(body) {
102
- const reader = body.getReader();
103
- const decoder = new TextDecoder();
104
- try {
105
- for (;;) {
106
- const { done, value } = await reader.read();
107
- if (done) {
108
- const tail = decoder.decode();
109
- if (tail.length > 0) yield tail;
110
- return;
111
- }
112
- const text = decoder.decode(value, { stream: true });
113
- if (text.length > 0) yield text;
597
+ if (def.innerType && def.type !== "object") return sampleValue(def.innerType, depth, key);
598
+ switch (def.type) {
599
+ case "number":
600
+ case "int": return "1";
601
+ case "bigint": return exampleLiteral("1");
602
+ case "boolean": return "true";
603
+ case "date": return exampleLiteral("2026-01-01");
604
+ case "null": return "null";
605
+ case "literal": return def.values?.length ? exampleLiteral(def.values[0]) : "undefined";
606
+ case "enum": {
607
+ const [first] = Object.values(def.entries ?? {});
608
+ return first === void 0 ? "undefined" : exampleLiteral(first);
114
609
  }
115
- } finally {
116
- reader.cancel().catch(() => void 0);
117
- }
118
- }
119
- async function* readByteChunks(body) {
120
- const reader = body.getReader();
121
- try {
122
- for (;;) {
123
- const { done, value } = await reader.read();
124
- if (done) return;
125
- yield value;
610
+ case "array":
611
+ if (!def.element || depth >= SAMPLE_DEPTH) return "[]";
612
+ return `[\n${indent$1(`${sampleValue(def.element, depth + 1, key)},`)}\n]`;
613
+ case "tuple": return `[${(def.items ?? []).map((item) => sampleValue(item, depth + 1, key)).join(", ")}]`;
614
+ case "object": return sampleObject(schema, depth);
615
+ case "record": return "{}";
616
+ case "union": {
617
+ const options = readDiscriminatedUnion(schema)?.options ?? def.options ?? [];
618
+ return options[0] ? sampleValue(options[0], depth, key) : "undefined";
126
619
  }
127
- } finally {
128
- reader.cancel().catch(() => void 0);
620
+ case "string": return stringSample(schema, key);
621
+ default: return "undefined";
129
622
  }
130
- }
131
- //#endregion
132
- //#region src/client.ts
133
- const buildFormData = (body) => {
134
- const formData = new FormData();
135
- for (const [key, entry] of Object.entries(body)) {
136
- const values = Array.isArray(entry) ? entry : [entry];
137
- for (const value of values) if (value instanceof File || value instanceof Blob) formData.append(key, value);
138
- else if (value !== void 0 && value !== null) formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
623
+ };
624
+ const SAMPLE_DEPTH = 2;
625
+ /**
626
+ * The required fields of an object schema, written as the literal a caller
627
+ * would pass. Optional fields are left out, since an example shows the least
628
+ * the route needs.
629
+ */
630
+ const sampleObject = (schema, depth = 0) => {
631
+ const shape = readObjectShape(schema);
632
+ if (!shape) return "{}";
633
+ const required = Object.entries(shape).filter(([, field]) => !unwrapOptionalWrappers(field).optional);
634
+ if (required.length === 0 || depth >= SAMPLE_DEPTH) return "{}";
635
+ return `{\n${indent$1(required.map(([key, field]) => `${propertyKey(key)}: ${sampleValue(unwrapOptionalWrappers(field).inner, depth + 1, key)},`).join("\n"))}\n}`;
636
+ };
637
+ /**
638
+ * What an editor shows above a field: its description, whether it is on its way
639
+ * out, and the values the schema declares as examples.
640
+ */
641
+ const fieldDoc = (field) => {
642
+ const lines = [];
643
+ const description = readMetaDescription(field);
644
+ if (description !== void 0) lines.push(description);
645
+ const deprecation = readDeprecation(field);
646
+ if (deprecation !== void 0) {
647
+ if (lines.length > 0) lines.push("");
648
+ lines.push(`@deprecated ${deprecation.message ?? ""}`.trimEnd());
139
649
  }
140
- return formData;
650
+ for (const example of readMetaExamples(field)) {
651
+ if (lines.length > 0) lines.push("");
652
+ lines.push("@example", exampleLiteral(example));
653
+ }
654
+ return lines;
655
+ };
656
+ const objectBody = (schema, collector, hint) => {
657
+ const shape = readObjectShape(schema);
658
+ if (!shape) return "Record<string, unknown>";
659
+ const entries = Object.entries(shape);
660
+ if (entries.length === 0) return "Record<string, never>";
661
+ return `{\n${indent$1(entries.map(([key, field]) => {
662
+ const doc = docComment(fieldDoc(field));
663
+ const mark = unwrapOptionalWrappers(field).optional ? "?" : "";
664
+ return `${doc}${propertyKey(key)}${mark}: ${typeOf(field, collector, `${hint}${toPascalCase(key)}`)};`;
665
+ }).join("\n"))}\n}`;
141
666
  };
142
667
  /**
143
- * Serializes a query or path value for the URL. Dates use ISO 8601; everything
144
- * else uses `String`.
668
+ * The TypeScript type a schema describes. Named models are collected and
669
+ * referenced; anonymous shapes are inlined. A brand is named like a model.
145
670
  */
146
- const serializeValue = (value) => value instanceof Date ? value.toISOString() : String(value);
147
- const buildQueryString = (query) => {
148
- const params = new URLSearchParams();
149
- for (const [key, value] of Object.entries(query)) {
150
- if (value === void 0 || value === null) continue;
151
- if (Array.isArray(value)) for (const item of value) params.append(key, serializeValue(item));
152
- else params.append(key, serializeValue(value));
671
+ const typeOf = (schema, collector, hint) => {
672
+ const type = unbrandedTypeOf(schema, collector, hint);
673
+ const brand = readMetaBrand(schema);
674
+ if (brand === void 0 || !BRANDABLE_BASES.has(type)) return type;
675
+ return collector.addBrand(brand, type, sampleValue(schema, 0, brand));
676
+ };
677
+ const unbrandedTypeOf = (schema, collector, hint) => {
678
+ if (isFileSchema(schema)) return "File | Blob";
679
+ if (isBinarySchema(schema)) return "Uint8Array";
680
+ const def = readDef(schema);
681
+ if (def.type === "nullable" && def.innerType) return `${typeOf(def.innerType, collector, hint)} | null`;
682
+ if (def.type === "nullish" && def.innerType) return `${typeOf(def.innerType, collector, hint)} | null`;
683
+ if (def.innerType && def.type !== "object") return typeOf(def.innerType, collector, hint);
684
+ if (def.type === "pipe") {
685
+ const side = collector.readsInput() ? def.in : def.out ?? def.in;
686
+ return side ? typeOf(side, collector, hint) : "unknown";
687
+ }
688
+ const modelName = readMetaId(schema);
689
+ if (modelName !== void 0) {
690
+ if (collector.claim(modelName)) collector.add({
691
+ name: modelName,
692
+ description: readMetaDescription(schema),
693
+ body: structuralType(schema, collector, modelName)
694
+ });
695
+ return modelName;
153
696
  }
154
- const result = params.toString();
155
- return result.length > 0 ? `?${result}` : "";
697
+ return structuralType(schema, collector, hint);
156
698
  };
157
- const CLIENT_ROUTE = Symbol.for("kizuna.client-route");
158
699
  /**
159
- * The route a client method answers, or `undefined` for anything that is not
160
- * one.
700
+ * The type a schema describes by its shape, its name already spent by the caller.
161
701
  */
162
- const routeOf = (value) => typeof value === "function" ? value[CLIENT_ROUTE] : void 0;
163
- const buildRouteFn = (route, config) => {
164
- const call = async (args = {}) => {
165
- const url = config.baseUrl + buildPath(route.path, args.params) + (args.query ? buildQueryString(args.query) : "");
166
- const headers = {
167
- ...config.baseHeaders ?? {},
168
- ...args.headers ?? {}
169
- };
170
- let body;
171
- if (args.body !== void 0) {
172
- const hasContentTypeHeader = "Content-Type" in headers || "content-type" in headers;
173
- switch (route.contentType) {
174
- case "multipart/form-data":
175
- body = args.body instanceof FormData ? args.body : buildFormData(args.body);
176
- break;
177
- case "application/x-www-form-urlencoded":
178
- if (!hasContentTypeHeader) headers["Content-Type"] = "application/x-www-form-urlencoded";
179
- body = new URLSearchParams(args.body);
180
- break;
181
- default:
182
- if (!hasContentTypeHeader) headers["Content-Type"] = "application/json";
183
- body = JSON.stringify(args.body);
184
- }
702
+ const structuralType = (schema, collector, hint) => {
703
+ const def = readDef(schema);
704
+ switch (def.type) {
705
+ case "string": return "string";
706
+ case "number":
707
+ case "int": return "number";
708
+ case "bigint": return "string";
709
+ case "boolean": return "boolean";
710
+ case "date": return "string";
711
+ case "null": return "null";
712
+ case "any":
713
+ case "unknown": return "unknown";
714
+ case "never": return "never";
715
+ case "void":
716
+ case "undefined": return "undefined";
717
+ case "literal": {
718
+ const values = def.values ?? [];
719
+ return values.length > 0 ? values.map(literalType).join(" | ") : "never";
185
720
  }
186
- const requestHeaders = new Headers(headers);
187
- if (config.onRequest) await config.onRequest({
188
- url,
189
- method: route.method,
190
- headers: requestHeaders,
191
- route
192
- });
193
- const res = await (config.fetch ?? fetch)(url, {
194
- method: route.method,
195
- headers: requestHeaders,
196
- body,
197
- credentials: config.credentials,
198
- ...args.fetchOptions
199
- });
200
- const responseHeaders = {};
201
- res.headers.forEach((value, key) => {
202
- responseHeaders[key] = value;
203
- });
204
- const responseSpec = route.responses[res.status];
205
- if (isStreamResponse(responseSpec) && res.body !== null) return {
206
- status: res.status,
207
- body: readStream(res.body, responseSpec),
208
- headers: responseHeaders
209
- };
210
- const text = await res.text();
211
- let parsed;
212
- try {
213
- parsed = text.length > 0 ? JSON.parse(text) : void 0;
214
- } catch {
215
- parsed = text;
721
+ case "enum": {
722
+ const values = Object.values(def.entries ?? {});
723
+ return values.length > 0 ? values.map(literalType).join(" | ") : "never";
216
724
  }
217
- return {
218
- status: res.status,
219
- body: parsed,
220
- headers: responseHeaders
221
- };
222
- };
223
- call[CLIENT_ROUTE] = route;
224
- return call;
225
- };
226
- const readStream = (body, definition) => {
227
- switch (streamMode(definition)) {
228
- case "events": return parseServerSentEvents(body);
229
- case "text": return readTextChunks(body);
230
- case "binary": return readByteChunks(body);
725
+ case "array": return def.element ? `Array<${typeOf(def.element, collector, `${hint}Item`)}>` : "unknown[]";
726
+ case "tuple": {
727
+ const items = (def.items ?? []).map((item, index) => typeOf(item, collector, `${hint}${index}`));
728
+ const rest = def.rest ? [`...Array<${typeOf(def.rest, collector, `${hint}Rest`)}>`] : [];
729
+ return `[${[...items, ...rest].join(", ")}]`;
730
+ }
731
+ case "object": return objectBody(schema, collector, hint);
732
+ case "record": return `Record<string, ${def.valueType ? typeOf(def.valueType, collector, `${hint}Value`) : "unknown"}>`;
733
+ case "union": {
734
+ const options = readDiscriminatedUnion(schema)?.options ?? def.options ?? [];
735
+ if (options.length === 0) return "unknown";
736
+ return options.map((option, index) => typeOf(option, collector, `${hint}${index}`)).join(" | ");
737
+ }
738
+ default: return "unknown";
231
739
  }
232
740
  };
233
- const buildClientTree = (router, config) => {
234
- const result = {};
235
- for (const key of Object.keys(router)) {
236
- const node = router[key];
237
- if (isRouteDefinition(node)) result[key] = buildRouteFn(node, config);
238
- else if (node && typeof node === "object") result[key] = buildClientTree(node, config);
741
+ //#endregion
742
+ //#region src/generator.ts
743
+ const indent = (text, depth = 1) => text.split("\n").map((line) => line.length > 0 ? " ".repeat(depth) + line : line).join("\n");
744
+ const pathParamNames = (path) => [...path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1] ?? "");
745
+ /**
746
+ * One server-sent event, typed from what the response declares. A record of
747
+ * event name to schema becomes a union discriminated on `event`; a single
748
+ * schema is the only shape a message takes.
749
+ */
750
+ const eventUnion = (stream, collector, namespace) => {
751
+ const frame = "id?: string; retry?: number";
752
+ if (stream && typeof stream === "object" && !("_zod" in stream) && !("_def" in stream)) {
753
+ const arms = Object.entries(stream).map(([event, schema]) => `{ event: '${event}'; data: ${typeOf(schema, collector, `${namespace}${toPascalCase(event)}`)}; ${frame} }`);
754
+ return arms.length > 0 ? arms.join(" | ") : `{ event?: string; data: string; ${frame} }`;
239
755
  }
240
- return result;
756
+ return `{ event?: string; data: ${typeOf(stream, collector, `${namespace}Message`)}; ${frame} }`;
757
+ };
758
+ const streamBody = (mode, stream, collector, namespace) => {
759
+ if (mode === "binary") return "AsyncIterable<Uint8Array>";
760
+ if (mode === "text") return "AsyncIterable<string>";
761
+ return `AsyncIterable<${eventUnion(stream, collector, namespace)}>`;
762
+ };
763
+ /**
764
+ * The call a route's `@example` shows: the arguments it cannot be called
765
+ * without, filled with values of the shape each schema declares.
766
+ */
767
+ const exampleCall = (routeKey, route) => {
768
+ const entries = [];
769
+ const params = pathParamNames(route.path);
770
+ if (params.length > 0) {
771
+ const shape = route.pathParams ? readObjectShape(route.pathParams) : void 0;
772
+ const fields = params.map((name) => {
773
+ const declared = shape?.[name];
774
+ return `${name}: ${declared ? sampleValue(declared, 0, name) : "'1'"},`;
775
+ });
776
+ entries.push(`params: {\n${indent(fields.join("\n"))}\n},`);
777
+ }
778
+ if (route.query && requiresArgument(route.query)) entries.push(`query: ${sampleObject(route.query)},`);
779
+ if (route.body && !isVoidSchema(route.body) && requiresArgument(route.body)) entries.push(`body: ${sampleValue(route.body)},`);
780
+ if (route.headers && requiresArgument(route.headers)) entries.push(`headers: ${sampleObject(route.headers)},`);
781
+ return `const result = await client.${routeKey}(${entries.length > 0 ? `{\n${indent(entries.join("\n"))}\n}` : ""});`;
782
+ };
783
+ /**
784
+ * Whether a schema has anything a caller has to pass, so a route whose query is
785
+ * every-field-optional keeps its example to the call itself.
786
+ */
787
+ const requiresArgument = (schema) => {
788
+ const shape = readObjectShape(schema);
789
+ if (!shape) return true;
790
+ return Object.values(shape).some((field) => !unwrapOptionalWrappers(field).optional);
241
791
  };
242
792
  /**
243
- * Folds the request context headers into `baseHeaders`, so every request
244
- * carries them. An explicit `baseHeaders` entry wins.
793
+ * What an editor shows above a client method: what the route is for, whether it
794
+ * is on its way out, and how it is called.
245
795
  */
246
- const withContextHeaders = (config) => {
247
- const contextHeaders = config.requestContext;
248
- if (!contextHeaders) return config;
796
+ const routeDoc = (routeKey, route) => {
797
+ const lines = [];
798
+ if (route.summary) lines.push(route.summary);
799
+ if (route.description) {
800
+ if (lines.length > 0) lines.push("");
801
+ lines.push(route.description);
802
+ }
803
+ if (route.deprecated !== void 0 && route.deprecated !== false) {
804
+ const message = typeof route.deprecated === "string" ? route.deprecated : typeof route.deprecated === "object" ? route.deprecated.message : void 0;
805
+ if (lines.length > 0) lines.push("");
806
+ lines.push(`@deprecated ${message ?? ""}`.trimEnd());
807
+ }
808
+ if (lines.length > 0) lines.push("");
809
+ lines.push("@example", exampleCall(routeKey, route));
810
+ return docComment(lines);
811
+ };
812
+ const emitRoute = (routeKey, key, route, collector, namespaceName) => {
813
+ const namespace = routeKey.split(".").map(toPascalCase).join("");
814
+ const members = [];
815
+ const args = [];
816
+ const params = pathParamNames(route.path);
817
+ const { pathParams, query, body, headers } = route;
818
+ if (params.length > 0) {
819
+ const paramsType = pathParams ? collector.readingInput(() => typeOf(pathParams, collector, `${namespace}Params`)) : `{\n${indent(params.map((name) => `${name}: string;`).join("\n"))}\n}`;
820
+ members.push(`export type Params = ${paramsType};`);
821
+ args.push(`params: ${namespaceName}.${namespace}.Params`);
822
+ }
823
+ if (query) {
824
+ members.push(`export type Query = ${collector.readingInput(() => typeOf(query, collector, `${namespace}Query`))};`);
825
+ args.push(`query${requiresArgument(query) ? "" : "?"}: ${namespaceName}.${namespace}.Query`);
826
+ }
827
+ if (body && !isVoidSchema(body)) {
828
+ members.push(`export type Body = ${collector.readingInput(() => typeOf(body, collector, `${namespace}Body`))};`);
829
+ args.push(`body: ${namespaceName}.${namespace}.Body`);
830
+ }
831
+ if (headers) {
832
+ members.push(`export type Headers = ${collector.readingInput(() => typeOf(headers, collector, `${namespace}Headers`))};`);
833
+ args.push(`headers${requiresArgument(headers) ? "" : "?"}: ${namespaceName}.${namespace}.Headers`);
834
+ } else args.push("headers?: Record<string, string>");
835
+ args.push("fetchOptions?: RequestInit");
836
+ const validates = route.body !== void 0 || route.query !== void 0;
837
+ const declaredBadRequest = Object.keys(route.responses).includes("400");
838
+ const validationBody = validates ? typeOf(ValidationErrorSchema, collector, "ValidationError") : void 0;
839
+ const results = Object.entries(route.responses).map(([status, response]) => {
840
+ const headers = resolveResponseHeaders(response);
841
+ const headerType = headers ? typeOf(headers, collector, `${namespace}${status}Headers`) : "Record<string, string>";
842
+ if (isStreamResponse(response)) return `{ status: ${status}; body: ${streamBody(streamMode(response), response.stream, collector, `${namespace}${status}`)}; headers: ${headerType} }`;
843
+ const schema = resolveResponseBody(response);
844
+ const body = schema ? typeOf(schema, collector, `${namespace}${status}`) : "undefined";
845
+ return `{ status: ${status}; body: ${status === "400" && validationBody ? `${body} | ${validationBody}` : body}; headers: ${headerType} }`;
846
+ });
847
+ if (validationBody && !declaredBadRequest) results.push(`{ status: 400; body: ${validationBody}; headers: Record<string, string> }`);
848
+ members.push(`export type Result =\n${indent(results.map((result) => `| ${result}`).join("\n"))};`);
849
+ const argsType = `{\n${indent(args.map((arg) => `${arg};`).join("\n"))}\n}`;
850
+ const tableEntries = [`method: '${route.method}'`, `path: '${route.path}'`];
851
+ if (route.contentType) tableEntries.push(`contentType: '${route.contentType}'`);
852
+ const responses = Object.entries(route.responses).map(([status, response]) => isStreamResponse(response) ? `${status}: { stream: true, contentType: '${streamContentType(response)}' }` : `${status}: {}`);
853
+ if (validationBody && !declaredBadRequest) responses.push("400: {}");
854
+ tableEntries.push(`responses: {\n${indent(responses.map((entry) => `${entry},`).join("\n"))}\n}`);
855
+ const streams = Object.values(route.responses).some((response) => isStreamResponse(response));
249
856
  return {
250
- ...config,
251
- baseHeaders: {
252
- ...Object.fromEntries(Object.entries(contextHeaders).filter(([, value]) => value !== void 0)),
253
- ...config.baseHeaders ?? {}
857
+ namespace,
858
+ signature: `${routeDoc(routeKey, route)}${key}: ClientMethod<'${route.method}', ${streams}, ${argsType}, ${namespaceName}.${namespace}.Result>;`,
859
+ declaration: `export namespace ${namespace} {\n${indent(members.join("\n\n"))}\n}`,
860
+ table: `${key}: {\n${indent(tableEntries.map((entry) => `${entry},`).join("\n"))}\n},`
861
+ };
862
+ };
863
+ const isRoute = (value) => !!value && typeof value === "object" && typeof value.method === "string";
864
+ const emitTree = (routes, prefix, collector, namespaceName) => {
865
+ const signatures = [];
866
+ const tables = [];
867
+ const declarations = [];
868
+ for (const key of Object.keys(routes)) {
869
+ const node = routes[key];
870
+ const routeKey = prefix ? `${prefix}.${key}` : key;
871
+ if (isRoute(node)) {
872
+ const emitted = emitRoute(routeKey, key, node, collector, namespaceName);
873
+ signatures.push(emitted.signature);
874
+ tables.push(emitted.table);
875
+ declarations.push(emitted.declaration);
876
+ continue;
254
877
  }
878
+ if (node && typeof node === "object") {
879
+ const group = emitTree(node, routeKey, collector, namespaceName);
880
+ signatures.push(`${key}: {\n${indent(group.signatures)}\n};`);
881
+ tables.push(`${key}: {\n${indent(group.table)}\n},`);
882
+ declarations.push(...group.declarations);
883
+ }
884
+ }
885
+ return {
886
+ signatures: signatures.join("\n"),
887
+ table: tables.join("\n"),
888
+ declarations
889
+ };
890
+ };
891
+ /**
892
+ * Renders a TypeScript client from an api: its named types, the route table
893
+ * the runtime reads, and a `createClient` typed against both.
894
+ */
895
+ /**
896
+ * The headers a request context declares, as one interface the caller fills
897
+ * once. Absent when the API declares no request context that reads headers.
898
+ */
899
+ const emitRequestContext = (contract, collector) => {
900
+ const declarations = Object.values(contract.requestContext ?? {});
901
+ const fields = [];
902
+ let required = false;
903
+ for (const declaration of declarations) {
904
+ const headers = declaration.headers;
905
+ if (!headers) continue;
906
+ required ||= requiresArgument(headers);
907
+ const inner = collector.readingInput(() => typeOf(headers, collector, "RequestContext")).trim().replace(/^\{/, "").replace(/\}$/, "").split("\n").map((line) => line.trim()).filter((line) => line !== "").join("\n");
908
+ if (inner !== "") fields.push(inner);
909
+ }
910
+ if (fields.length === 0) return void 0;
911
+ return {
912
+ declaration: `export interface RequestContext {\n${indent(fields.join("\n"))}\n}`,
913
+ required
255
914
  };
256
915
  };
257
916
  /**
258
- * Builds the client tree a generated client exposes. The generated file owns the
259
- * types; this owns the requests.
917
+ * A constructor per brand, so a value from outside the API becomes one with
918
+ * `toUserId('usr_k7f3q9')` rather than a cast.
919
+ */
920
+ const emitBrandConstructors = (collector, namespaceName) => collector.allBrands().map(({ name, base, example }) => `
921
+ ${docComment([
922
+ `Brands a value from outside the API, like a URL segment, as \`${namespaceName}.${name}\`. A value from a response is branded already.`,
923
+ "",
924
+ "@example",
925
+ `const id = to${name}(${example});`
926
+ ])}export const to${name} = (value: ${base}): ${namespaceName}.${name} => value as ${namespaceName}.${name};
927
+ `).join("");
928
+ /**
929
+ * Tells kizuna's validation error from a 400 the route declares itself.
930
+ */
931
+ const emitValidationGuard = (namespaceName) => `
932
+ ${docComment([
933
+ `Whether a \`400\` body is the validation error kizuna sends, rather than a \`400\` the route declares itself.`,
934
+ "",
935
+ "@example",
936
+ "if (result.status === 400 && isValidationError(result.body)) {",
937
+ " console.log(result.body.errors);",
938
+ "}"
939
+ ])}export const isValidationError = (body: unknown): body is ${namespaceName}.ValidationError =>
940
+ typeof body === 'object' && body !== null && 'errors' in body && Array.isArray(body.errors);
941
+ `;
942
+ /**
943
+ * Declared in the file, so a brand needs nothing installed.
944
+ */
945
+ const BRAND_DECLARATION = `declare const kizunaBrand: unique symbol;
946
+
947
+ /**
948
+ * Tells one branded type from another with the same base.
949
+ */
950
+ type KizunaBrand<Name extends string> = {
951
+ readonly [kizunaBrand]: {
952
+ readonly [Key in Name]: true;
953
+ };
954
+ };
955
+
956
+ `;
957
+ const generateFetchClient = (contract, options = {}) => {
958
+ const { namespace: namespaceName = "API", regenerateCommand = "kizuna generate", source } = options;
959
+ const collector = new TypeCollector();
960
+ const tree = emitTree(listedRoutes(contract), "", collector, namespaceName);
961
+ const requestContext = emitRequestContext(contract, collector);
962
+ const api = [...collector.all().map((model) => {
963
+ return `${model.description ? `/**\n * ${model.description}\n */\n` : ""}export type ${model.name} = ${model.body};`;
964
+ }), ...tree.declarations].join("\n\n");
965
+ const brands = emitBrandConstructors(collector, namespaceName);
966
+ const guards = collector.all().some((model) => model.name === "ValidationError") ? emitValidationGuard(namespaceName) : "";
967
+ return `/* eslint-disable */
968
+ /**
969
+ ${[
970
+ " * Generated by @kizunajs/fetch. Do not edit.",
971
+ " *",
972
+ ...source === void 0 ? [] : [` * Source: ${source}`],
973
+ ` * Regenerate: ${regenerateCommand}`
974
+ ].join("\n")}
975
+ */
976
+ ${collector.usesBrand() ? BRAND_DECLARATION : ""}export namespace ${namespaceName} {
977
+ ${indent(api)}
978
+ }
979
+
980
+ export interface Client {
981
+ ${indent(tree.signatures)}
982
+ }
983
+
984
+ const routes: GeneratedRoutes = {
985
+ ${indent(tree.table)}
986
+ };
987
+ ${brands}${guards}
988
+ ${requestContext === void 0 ? `/**
989
+ * A client for this API. Pass the base URL and anything else the runtime takes.
990
+ */
991
+ export const createClient = (config: ClientConfig): Client => buildClient(routes, config) as unknown as Client;` : `${requestContext.declaration}
992
+
993
+ /**
994
+ * A client for this API. Pass the base URL, the request context headers this
995
+ * API declares, and anything else the runtime takes.
996
+ */
997
+ export const createClient = (config: ClientConfig & { requestContext${requestContext.required ? "" : "?"}: RequestContext }): Client =>
998
+ buildClient(routes, config) as unknown as Client;`}
999
+
1000
+ ${runtimeSource}`;
1001
+ };
1002
+ /**
1003
+ * A TypeScript client for `kizuna.config.ts`.
1004
+ *
1005
+ * @example
1006
+ * fetchClient({
1007
+ * output: './packages/api-client/src/generated.ts',
1008
+ * });
260
1009
  */
261
- const createGeneratedClient = (routes, config) => buildClientTree(routes, withContextHeaders(config));
1010
+ const fetchClient = defineClient({
1011
+ target: "fetch",
1012
+ options: z.object({
1013
+ /**
1014
+ * Name of the generated namespace holding every model and every route's
1015
+ * `Params`, `Query`, `Body`, `Headers` and `Result`.
1016
+ *
1017
+ * @default 'API'
1018
+ */
1019
+ namespace: z.string().optional(),
1020
+ /**
1021
+ * Command the file's header tells a reader to run.
1022
+ *
1023
+ * @default 'kizuna generate'
1024
+ */
1025
+ regenerateCommand: z.string().optional(),
1026
+ /**
1027
+ * Path to the api this was generated from, relative to the generated
1028
+ * file. Named in the header so tooling can tell when the client has fallen
1029
+ * behind, and so a reader knows where the API is declared.
1030
+ */
1031
+ source: z.string().optional()
1032
+ }),
1033
+ generate: ({ options, api }) => ({ finalize: () => generateFetchClient(api, options) })
1034
+ });
262
1035
  //#endregion
263
- export { CLIENT_ROUTE, createGeneratedClient, isProblemDetails, isValidationError, routeOf };
1036
+ export { fetchClient, generateFetchClient };