@kizunajs/fetch 2.0.0-beta.13 → 2.0.0-beta.15

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