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