@kizunajs/fetch 2.0.0-beta.12 → 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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kizunajs/fetch",
3
- "version": "2.0.0-beta.12",
4
- "description": "Typed fetch client for Kizuna.js APIs",
3
+ "version": "2.0.0-beta.14",
4
+ "description": "Fetch client generation for Kizuna.js APIs",
5
5
  "keywords": [
6
6
  "kizunajs",
7
7
  "typescript",
@@ -42,22 +42,11 @@
42
42
  "types": "./dist/index.d.cts",
43
43
  "default": "./dist/index.cjs"
44
44
  }
45
- },
46
- "./server": {
47
- "import": {
48
- "types": "./dist/server.d.mts",
49
- "default": "./dist/server.mjs"
50
- },
51
- "require": {
52
- "types": "./dist/server.d.cts",
53
- "default": "./dist/server.cjs"
54
- }
55
45
  }
56
46
  },
57
47
  "kizuna": {
58
48
  "entries": {
59
- ".": "client",
60
- "./server": "server"
49
+ ".": "server"
61
50
  }
62
51
  },
63
52
  "files": [
@@ -68,7 +57,7 @@
68
57
  },
69
58
  "peerDependencies": {
70
59
  "zod": "^4.0.0",
71
- "kizunajs": "2.0.0-beta.12"
60
+ "kizunajs": "2.0.0-beta.14"
72
61
  },
73
62
  "devDependencies": {
74
63
  "@types/express": "^5.0.0",
@@ -76,11 +65,11 @@
76
65
  "tsdown": "^0.21.0",
77
66
  "typescript": "^6.0.3",
78
67
  "zod": "^4.0.0",
79
- "kizunajs": "2.0.0-beta.12",
80
- "@kizunajs/express": "2.0.0-beta.12"
68
+ "kizunajs": "2.0.0-beta.14",
69
+ "@kizunajs/express": "2.0.0-beta.14"
81
70
  },
82
71
  "scripts": {
83
- "build": "tsdown src/index.ts src/server.ts --format esm,cjs --dts --clean --external kizunajs --external zod",
72
+ "build": "tsdown src/index.ts --format esm,cjs --dts --clean --external kizunajs --external zod",
84
73
  "typecheck": "tsc --noEmit"
85
74
  }
86
75
  }
package/dist/server.cjs DELETED
@@ -1,479 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let kizunajs_schemas = require("kizunajs/schemas");
3
- let kizunajs_generator = require("kizunajs/generator");
4
- let zod = require("zod");
5
- //#region src/zod-to-typescript.ts
6
- /**
7
- * Collects the named types a walk produces, so a model shared by many routes is
8
- * declared once.
9
- */
10
- var TypeCollector = class {
11
- named = /* @__PURE__ */ new Map();
12
- claimed = /* @__PURE__ */ new Set();
13
- /**
14
- * Claims a name before its body is walked, so a model that refers to itself
15
- * resolves to its own name instead of recursing. Answers whether the caller
16
- * is the one that has to emit it.
17
- */
18
- claim(name) {
19
- if (this.claimed.has(name)) return false;
20
- this.claimed.add(name);
21
- return true;
22
- }
23
- add(type) {
24
- this.named.set(type.name, type);
25
- }
26
- all() {
27
- return [...this.named.values()].sort((left, right) => left.name.localeCompare(right.name));
28
- }
29
- };
30
- const quote = (value) => JSON.stringify(value);
31
- /**
32
- * A literal as the type the JSON carries, so `z.literal(true)` is `true`.
33
- */
34
- const literalType = (value) => {
35
- if (typeof value === "string") return quote(value);
36
- if (typeof value === "bigint") return `${value}n`;
37
- if (value === void 0) return "undefined";
38
- return String(value);
39
- };
40
- const indent$1 = (text, depth = 1) => text.split("\n").map((line) => line.length > 0 ? " ".repeat(depth) + line : line).join("\n");
41
- /**
42
- * A property name, quoted only when it is not a plain identifier.
43
- */
44
- const propertyKey = (key) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : quote(key);
45
- /**
46
- * A doc comment over the lines it is given, or nothing when there are none.
47
- * Always multi-line, the way the rest of this repository writes them.
48
- */
49
- const docComment = (lines) => {
50
- const body = lines.flatMap((line) => line.split("\n"));
51
- if (body.length === 0) return "";
52
- return `/**\n${body.map((line) => ` * ${line}`.trimEnd()).join("\n")}\n */\n`;
53
- };
54
- /**
55
- * Renders a declared example as the TypeScript literal a caller would write.
56
- */
57
- const exampleLiteral = (value) => {
58
- if (typeof value === "string") return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
59
- if (value === void 0) return "undefined";
60
- return JSON.stringify(value) ?? "undefined";
61
- };
62
- const STRING_SAMPLES = {
63
- email: "ada@example.com",
64
- url: "https://example.com",
65
- uuid: "3f1c2d9e-5b6a-4c7d-8e9f-0a1b2c3d4e5f",
66
- datetime: "2026-01-01T00:00:00Z",
67
- date: "2026-01-01",
68
- time: "00:00:00"
69
- };
70
- const stringSample = (schema, key) => {
71
- const def = (0, kizunajs_generator.readDef)(schema);
72
- const formats = [def.format, ...(def.checks ?? []).map((check) => check.format ?? check.def?.format)];
73
- for (const format of formats) if (format !== void 0 && format in STRING_SAMPLES) return exampleLiteral(STRING_SAMPLES[format]);
74
- if (key !== void 0 && /id$/i.test(key)) return exampleLiteral("1");
75
- return exampleLiteral("string");
76
- };
77
- /**
78
- * A value a caller could pass for a schema, used in the `@example` on each
79
- * client method. A schema that declares an example is taken at its word;
80
- * anything else gets a value of the right shape.
81
- */
82
- const sampleValue = (schema, depth = 0, key) => {
83
- const [declared] = (0, kizunajs_generator.readMetaExamples)(schema);
84
- if (declared !== void 0) return exampleLiteral(declared);
85
- if ((0, kizunajs_generator.isFileSchema)(schema)) return "new File([], 'upload.txt')";
86
- if ((0, kizunajs_generator.isBinarySchema)(schema)) return "new Uint8Array()";
87
- const def = (0, kizunajs_generator.readDef)(schema);
88
- if (def.type === "default" && def.defaultValue !== void 0) return exampleLiteral(def.defaultValue);
89
- if (def.type === "pipe") {
90
- const side = def.out ?? def.in;
91
- return side ? sampleValue(side, depth, key) : "undefined";
92
- }
93
- if (def.innerType && def.type !== "object") return sampleValue(def.innerType, depth, key);
94
- switch (def.type) {
95
- case "number":
96
- case "int": return "1";
97
- case "bigint": return "1n";
98
- case "boolean": return "true";
99
- case "date": return exampleLiteral("2026-01-01");
100
- case "null": return "null";
101
- case "literal": return def.values?.length ? exampleLiteral(def.values[0]) : "undefined";
102
- case "enum": {
103
- const [first] = Object.values(def.entries ?? {});
104
- return first === void 0 ? "undefined" : exampleLiteral(first);
105
- }
106
- case "array":
107
- if (!def.element || depth >= SAMPLE_DEPTH) return "[]";
108
- return `[\n${indent$1(`${sampleValue(def.element, depth + 1, key)},`)}\n]`;
109
- case "object": return sampleObject(schema, depth);
110
- case "record": return "{}";
111
- case "union": {
112
- const options = (0, kizunajs_generator.readDiscriminatedUnion)(schema)?.options ?? def.options ?? [];
113
- return options[0] ? sampleValue(options[0], depth, key) : "undefined";
114
- }
115
- case "string": return stringSample(schema, key);
116
- default: return "undefined";
117
- }
118
- };
119
- const SAMPLE_DEPTH = 2;
120
- /**
121
- * The required fields of an object schema, written as the literal a caller
122
- * would pass. Optional fields are left out, since an example shows the least
123
- * the route needs.
124
- */
125
- const sampleObject = (schema, depth = 0) => {
126
- const shape = (0, kizunajs_generator.readObjectShape)(schema);
127
- if (!shape) return "{}";
128
- const required = Object.entries(shape).filter(([, field]) => !(0, kizunajs_generator.unwrapOptionalWrappers)(field).optional);
129
- if (required.length === 0 || depth >= SAMPLE_DEPTH) return "{}";
130
- return `{\n${indent$1(required.map(([key, field]) => `${propertyKey(key)}: ${sampleValue((0, kizunajs_generator.unwrapOptionalWrappers)(field).inner, depth + 1, key)},`).join("\n"))}\n}`;
131
- };
132
- /**
133
- * What an editor shows above a field: its description, whether it is on its way
134
- * out, and the values the schema declares as examples.
135
- */
136
- const fieldDoc = (field) => {
137
- const lines = [];
138
- const description = (0, kizunajs_generator.readMetaDescription)(field);
139
- if (description !== void 0) lines.push(description);
140
- const deprecation = (0, kizunajs_generator.readDeprecation)(field);
141
- if (deprecation !== void 0) {
142
- if (lines.length > 0) lines.push("");
143
- lines.push(`@deprecated ${deprecation.message ?? ""}`.trimEnd());
144
- }
145
- for (const example of (0, kizunajs_generator.readMetaExamples)(field)) {
146
- if (lines.length > 0) lines.push("");
147
- lines.push("@example", exampleLiteral(example));
148
- }
149
- return lines;
150
- };
151
- const objectBody = (schema, collector, hint) => {
152
- const shape = (0, kizunajs_generator.readObjectShape)(schema);
153
- if (!shape) return "Record<string, unknown>";
154
- const entries = Object.entries(shape);
155
- if (entries.length === 0) return "Record<string, never>";
156
- return `{\n${indent$1(entries.map(([key, field]) => {
157
- const doc = docComment(fieldDoc(field));
158
- const mark = (0, kizunajs_generator.unwrapOptionalWrappers)(field).optional ? "?" : "";
159
- return `${doc}${propertyKey(key)}${mark}: ${typeOf(field, collector, `${hint}${(0, kizunajs_generator.toPascalCase)(key)}`)};`;
160
- }).join("\n"))}\n}`;
161
- };
162
- /**
163
- * The TypeScript type a schema describes. Named models are collected and
164
- * referenced; anonymous shapes are inlined.
165
- */
166
- const typeOf = (schema, collector, hint) => {
167
- if ((0, kizunajs_generator.isFileSchema)(schema)) return "File | Blob";
168
- if ((0, kizunajs_generator.isBinarySchema)(schema)) return "Uint8Array";
169
- const def = (0, kizunajs_generator.readDef)(schema);
170
- if (def.type === "nullable" && def.innerType) return `${typeOf(def.innerType, collector, hint)} | null`;
171
- if (def.type === "nullish" && def.innerType) return `${typeOf(def.innerType, collector, hint)} | null`;
172
- if (def.innerType && def.type !== "object") return typeOf(def.innerType, collector, hint);
173
- if (def.type === "pipe") {
174
- const side = def.out ?? def.in;
175
- return side ? typeOf(side, collector, hint) : "unknown";
176
- }
177
- const modelName = (0, kizunajs_generator.readMetaId)(schema);
178
- if (modelName !== void 0) {
179
- if (collector.claim(modelName)) collector.add({
180
- name: modelName,
181
- description: (0, kizunajs_generator.readMetaDescription)(schema),
182
- body: structuralType(schema, collector, modelName)
183
- });
184
- return modelName;
185
- }
186
- return structuralType(schema, collector, hint);
187
- };
188
- /**
189
- * The type a schema describes by its shape, its name already spent by the caller.
190
- */
191
- const structuralType = (schema, collector, hint) => {
192
- const def = (0, kizunajs_generator.readDef)(schema);
193
- switch (def.type) {
194
- case "string": return "string";
195
- case "number":
196
- case "int": return "number";
197
- case "bigint": return "string";
198
- case "boolean": return "boolean";
199
- case "date": return "string";
200
- case "null": return "null";
201
- case "any":
202
- case "unknown": return "unknown";
203
- case "never": return "never";
204
- case "void":
205
- case "undefined": return "undefined";
206
- case "literal": {
207
- const values = def.values ?? [];
208
- return values.length > 0 ? values.map(literalType).join(" | ") : "never";
209
- }
210
- case "enum": {
211
- const values = Object.values(def.entries ?? {});
212
- return values.length > 0 ? values.map(literalType).join(" | ") : "never";
213
- }
214
- case "array": return def.element ? `Array<${typeOf(def.element, collector, `${hint}Item`)}>` : "unknown[]";
215
- case "object": return objectBody(schema, collector, hint);
216
- case "record": return `Record<string, ${def.valueType ? typeOf(def.valueType, collector, `${hint}Value`) : "unknown"}>`;
217
- case "union": {
218
- const options = (0, kizunajs_generator.readDiscriminatedUnion)(schema)?.options ?? def.options ?? [];
219
- if (options.length === 0) return "unknown";
220
- return options.map((option, index) => typeOf(option, collector, `${hint}${index}`)).join(" | ");
221
- }
222
- default: return "unknown";
223
- }
224
- };
225
- //#endregion
226
- //#region src/generator.ts
227
- const indent = (text, depth = 1) => text.split("\n").map((line) => line.length > 0 ? " ".repeat(depth) + line : line).join("\n");
228
- const pathParamNames = (path) => [...path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1] ?? "");
229
- /**
230
- * One server-sent event, typed from what the response declares. A record of
231
- * event name to schema becomes a union discriminated on `event`; a single
232
- * schema is the only shape a message takes.
233
- */
234
- const eventUnion = (stream, collector, namespace) => {
235
- const frame = "id?: string; retry?: number";
236
- if (stream && typeof stream === "object" && !("_zod" in stream) && !("_def" in stream)) {
237
- const arms = Object.entries(stream).map(([event, schema]) => `{ event: '${event}'; data: ${typeOf(schema, collector, `${namespace}${(0, kizunajs_generator.toPascalCase)(event)}`)}; ${frame} }`);
238
- return arms.length > 0 ? arms.join(" | ") : `{ event?: string; data: string; ${frame} }`;
239
- }
240
- return `{ event?: string; data: ${typeOf(stream, collector, `${namespace}Message`)}; ${frame} }`;
241
- };
242
- const streamBody = (mode, stream, collector, namespace) => {
243
- if (mode === "binary") return "AsyncIterable<Uint8Array>";
244
- if (mode === "text") return "AsyncIterable<string>";
245
- return `AsyncIterable<${eventUnion(stream, collector, namespace)}>`;
246
- };
247
- /**
248
- * The call a route's `@example` shows: the arguments it cannot be called
249
- * without, filled with values of the shape each schema declares.
250
- */
251
- const exampleCall = (routeKey, route) => {
252
- const entries = [];
253
- const params = pathParamNames(route.path);
254
- if (params.length > 0) {
255
- const shape = route.pathParams ? (0, kizunajs_generator.readObjectShape)(route.pathParams) : void 0;
256
- const fields = params.map((name) => {
257
- const declared = shape?.[name];
258
- return `${name}: ${declared ? sampleValue(declared, 0, name) : "'1'"},`;
259
- });
260
- entries.push(`params: {\n${indent(fields.join("\n"))}\n},`);
261
- }
262
- if (route.query && requiresArgument(route.query)) entries.push(`query: ${sampleObject(route.query)},`);
263
- if (route.body && !(0, kizunajs_generator.isVoidSchema)(route.body) && requiresArgument(route.body)) entries.push(`body: ${sampleValue(route.body)},`);
264
- return `const result = await client.${routeKey}(${entries.length > 0 ? `{\n${indent(entries.join("\n"))}\n}` : ""});`;
265
- };
266
- /**
267
- * Whether a schema has anything a caller has to pass, so a route whose query is
268
- * every-field-optional keeps its example to the call itself.
269
- */
270
- const requiresArgument = (schema) => {
271
- const shape = (0, kizunajs_generator.readObjectShape)(schema);
272
- if (!shape) return true;
273
- return Object.values(shape).some((field) => !(0, kizunajs_generator.unwrapOptionalWrappers)(field).optional);
274
- };
275
- /**
276
- * What an editor shows above a client method: what the route is for, whether it
277
- * is on its way out, and how it is called.
278
- */
279
- const routeDoc = (routeKey, route) => {
280
- const lines = [];
281
- if (route.summary) lines.push(route.summary);
282
- if (route.description) {
283
- if (lines.length > 0) lines.push("");
284
- lines.push(route.description);
285
- }
286
- if (route.deprecated !== void 0 && route.deprecated !== false) {
287
- const message = typeof route.deprecated === "string" ? route.deprecated : typeof route.deprecated === "object" ? route.deprecated.message : void 0;
288
- if (lines.length > 0) lines.push("");
289
- lines.push(`@deprecated ${message ?? ""}`.trimEnd());
290
- }
291
- if (lines.length > 0) lines.push("");
292
- lines.push("@example", exampleCall(routeKey, route));
293
- return docComment(lines);
294
- };
295
- const emitRoute = (routeKey, key, route, collector, namespaceName) => {
296
- const namespace = routeKey.split(".").map(kizunajs_generator.toPascalCase).join("");
297
- const members = [];
298
- const args = [];
299
- const params = pathParamNames(route.path);
300
- if (params.length > 0) {
301
- const body = route.pathParams ? typeOf(route.pathParams, collector, `${namespace}Params`) : `{\n${indent(params.map((name) => `${name}: string;`).join("\n"))}\n}`;
302
- members.push(`export type Params = ${body};`);
303
- args.push(`params: ${namespaceName}.${namespace}.Params`);
304
- }
305
- if (route.query) {
306
- members.push(`export type Query = ${typeOf(route.query, collector, `${namespace}Query`)};`);
307
- args.push(`query?: ${namespaceName}.${namespace}.Query`);
308
- }
309
- if (route.body && !(0, kizunajs_generator.isVoidSchema)(route.body)) {
310
- members.push(`export type Body = ${typeOf(route.body, collector, `${namespace}Body`)};`);
311
- args.push(`body: ${namespaceName}.${namespace}.Body`);
312
- }
313
- if (route.headers) {
314
- members.push(`export type Headers = ${typeOf(route.headers, collector, `${namespace}Headers`)};`);
315
- args.push(`headers?: ${namespaceName}.${namespace}.Headers`);
316
- } else args.push("headers?: Record<string, string>");
317
- args.push("fetchOptions?: RequestInit");
318
- const validates = route.body !== void 0 || route.query !== void 0;
319
- const declaredBadRequest = Object.keys(route.responses).includes("400");
320
- const validationBody = validates ? typeOf(kizunajs_schemas.ValidationErrorSchema, collector, "ValidationError") : void 0;
321
- const results = Object.entries(route.responses).map(([status, response]) => {
322
- const headers = (0, kizunajs_generator.resolveResponseHeaders)(response);
323
- const headerType = headers ? typeOf(headers, collector, `${namespace}${status}Headers`) : "Record<string, string>";
324
- if ((0, kizunajs_generator.isStreamResponse)(response)) return `{ status: ${status}; body: ${streamBody((0, kizunajs_generator.streamContentType)(response).includes("event-stream") ? "events" : (0, kizunajs_generator.streamContentType)(response).startsWith("text/") ? "text" : "binary", response.stream, collector, `${namespace}${status}`)}; headers: ${headerType} }`;
325
- const schema = (0, kizunajs_generator.resolveResponseBody)(response);
326
- const body = schema ? typeOf(schema, collector, `${namespace}${status}`) : "undefined";
327
- return `{ status: ${status}; body: ${status === "400" && validationBody ? `${body} | ${validationBody}` : body}; headers: ${headerType} }`;
328
- });
329
- if (validationBody && !declaredBadRequest) results.push(`{ status: 400; body: ${validationBody}; headers: Record<string, string> }`);
330
- members.push(`export type Result =\n${indent(results.map((result) => `| ${result}`).join("\n"))};`);
331
- const argsType = `{\n${indent(args.map((arg) => `${arg};`).join("\n"))}\n}`;
332
- const tableEntries = [`method: '${route.method}'`, `path: '${route.path}'`];
333
- if (route.contentType) tableEntries.push(`contentType: '${route.contentType}'`);
334
- const responses = Object.entries(route.responses).map(([status, response]) => (0, kizunajs_generator.isStreamResponse)(response) ? `${status}: { stream: { contentType: '${(0, kizunajs_generator.streamContentType)(response)}' } }` : `${status}: {}`);
335
- tableEntries.push(`responses: {\n${indent(responses.map((entry) => `${entry},`).join("\n"))}\n}`);
336
- const streams = Object.values(route.responses).some((response) => (0, kizunajs_generator.isStreamResponse)(response));
337
- return {
338
- namespace,
339
- signature: `${routeDoc(routeKey, route)}${key}: ClientMethod<'${route.method}', ${streams}, ${argsType}, ${namespaceName}.${namespace}.Result>;`,
340
- declaration: `export namespace ${namespace} {\n${indent(members.join("\n\n"))}\n}`,
341
- table: `${key}: {\n${indent(tableEntries.map((entry) => `${entry},`).join("\n"))}\n},`
342
- };
343
- };
344
- const isRoute = (value) => !!value && typeof value === "object" && typeof value.method === "string";
345
- const emitTree = (routes, prefix, collector, namespaceName) => {
346
- const signatures = [];
347
- const tables = [];
348
- const declarations = [];
349
- for (const key of Object.keys(routes)) {
350
- const node = routes[key];
351
- const routeKey = prefix ? `${prefix}.${key}` : key;
352
- if (isRoute(node)) {
353
- const emitted = emitRoute(routeKey, key, node, collector, namespaceName);
354
- signatures.push(emitted.signature);
355
- tables.push(emitted.table);
356
- declarations.push(emitted.declaration);
357
- continue;
358
- }
359
- if (node && typeof node === "object") {
360
- const group = emitTree(node, routeKey, collector, namespaceName);
361
- signatures.push(`${key}: {\n${indent(group.signatures)}\n};`);
362
- tables.push(`${key}: {\n${indent(group.table)}\n},`);
363
- declarations.push(...group.declarations);
364
- }
365
- }
366
- return {
367
- signatures: signatures.join("\n"),
368
- table: tables.join("\n"),
369
- declarations
370
- };
371
- };
372
- /**
373
- * Renders a TypeScript client from an api: its named types, the route table
374
- * the runtime reads, and a `createClient` typed against both.
375
- */
376
- /**
377
- * The headers a request context declares, as one interface the caller fills
378
- * once. Absent when the API declares no request context that reads headers.
379
- */
380
- const emitRequestContext = (contract, collector) => {
381
- const declarations = Object.values(contract.requestContext ?? {});
382
- const fields = [];
383
- for (const declaration of declarations) {
384
- const headers = declaration.headers;
385
- if (!headers) continue;
386
- const inner = typeOf(headers, collector, "RequestContext").trim().replace(/^\{/, "").replace(/\}$/, "").split("\n").map((line) => line.trim()).filter((line) => line !== "").join("\n");
387
- if (inner !== "") fields.push(inner);
388
- }
389
- return fields.length > 0 ? `export interface RequestContext {\n${indent(fields.join("\n"))}\n}` : void 0;
390
- };
391
- const generateFetchClient = (contract, options = {}) => {
392
- const { namespace: namespaceName = "API", runtimeModule = "@kizunajs/fetch", regenerateCommand = "kizuna generate", source } = options;
393
- const collector = new TypeCollector();
394
- const tree = emitTree((0, kizunajs_generator.listedRoutes)(contract), "", collector, namespaceName);
395
- const api = [...collector.all().map((model) => {
396
- return `${model.description ? `/**\n * ${model.description}\n */\n` : ""}export type ${model.name} = ${model.body};`;
397
- }), ...tree.declarations].join("\n\n");
398
- const requestContext = emitRequestContext(contract, collector);
399
- return `/* eslint-disable */
400
- /**
401
- ${[
402
- " * Generated by @kizunajs/fetch. Do not edit.",
403
- " *",
404
- ...source === void 0 ? [] : [` * Source: ${source}`],
405
- ` * Regenerate: ${regenerateCommand}`
406
- ].join("\n")}
407
- */
408
- import { createGeneratedClient, type ClientConfig, type ClientMethod, type GeneratedRoutes } from '${runtimeModule}';
409
-
410
- export namespace ${namespaceName} {
411
- ${indent(api)}
412
- }
413
-
414
- export interface Client {
415
- ${indent(tree.signatures)}
416
- }
417
-
418
- const routes: GeneratedRoutes = {
419
- ${indent(tree.table)}
420
- };
421
-
422
- ${requestContext === void 0 ? `/**
423
- * A client for this API. Pass the base URL and anything else the runtime takes.
424
- */
425
- export const createClient = (config: ClientConfig): Client => createGeneratedClient(routes, config) as unknown as Client;` : `${requestContext}
426
-
427
- /**
428
- * A client for this API. Pass the base URL, the request context headers this
429
- * API declares, and anything else the runtime takes.
430
- */
431
- export const createClient = (config: ClientConfig & { requestContext?: RequestContext }): Client =>
432
- createGeneratedClient(routes, config) as unknown as Client;`}
433
- `;
434
- };
435
- //#endregion
436
- //#region src/client-target.ts
437
- const FetchClientOptionsSchema = zod.z.object({
438
- /**
439
- * Name of the generated namespace holding every model and every route's
440
- * `Params`, `Query`, `Body`, `Headers` and `Result`.
441
- *
442
- * @default 'API'
443
- */
444
- namespace: zod.z.string().optional(),
445
- /**
446
- * Module the generated file imports its runtime from.
447
- *
448
- * @default '@kizunajs/fetch'
449
- */
450
- runtimeModule: zod.z.string().optional(),
451
- /**
452
- * Command the file's header tells a reader to run.
453
- *
454
- * @default 'kizuna generate'
455
- */
456
- regenerateCommand: zod.z.string().optional(),
457
- /**
458
- * Path to the api this was generated from, relative to the generated
459
- * file. Named in the header so tooling can tell when the client has fallen
460
- * behind, and so a reader knows where the API is declared.
461
- */
462
- source: zod.z.string().optional()
463
- });
464
- /**
465
- * A TypeScript client for `kizuna.config.ts`.
466
- *
467
- * @example
468
- * fetchClient({
469
- * output: './packages/api-client/src/generated.ts',
470
- * });
471
- */
472
- const fetchClient = (0, kizunajs_generator.defineClient)({
473
- target: "fetch",
474
- options: FetchClientOptionsSchema,
475
- generate: ({ options, api }) => ({ finalize: () => generateFetchClient(api, options) })
476
- });
477
- //#endregion
478
- exports.fetchClient = fetchClient;
479
- exports.generateFetchClient = generateFetchClient;
package/dist/server.d.cts DELETED
@@ -1,65 +0,0 @@
1
- import { z } from "zod";
2
- import * as _$kizunajs from "kizunajs";
3
- import { ApiDefinition } from "kizunajs";
4
- import { GeneratedFileOptions } from "kizunajs/generator";
5
-
6
- //#region src/generator.d.ts
7
- /**
8
- * What a generated client is called and where its runtime comes from.
9
- */
10
- interface FetchClientOptions {
11
- /**
12
- * Name of the generated namespace holding every model and every route's
13
- * `Params`, `Query`, `Body`, `Headers` and `Result`.
14
- *
15
- * @default 'API'
16
- */
17
- namespace?: string;
18
- /**
19
- * Module the generated file imports its runtime from.
20
- *
21
- * @default '@kizunajs/fetch'
22
- */
23
- runtimeModule?: string;
24
- /**
25
- * Command the file's header tells a reader to run.
26
- *
27
- * @default 'kizuna generate'
28
- */
29
- regenerateCommand?: string;
30
- /**
31
- * Path to the api this was generated from, relative to the generated
32
- * file. Named in the header so tooling can tell when the client has fallen
33
- * behind, and so a reader knows where the API is declared.
34
- */
35
- source?: string;
36
- }
37
- declare const generateFetchClient: (contract: ApiDefinition, options?: FetchClientOptions) => string;
38
- //#endregion
39
- //#region src/client-target.d.ts
40
- declare const FetchClientOptionsSchema: z.ZodObject<{
41
- namespace: z.ZodOptional<z.ZodString>;
42
- runtimeModule: z.ZodOptional<z.ZodString>;
43
- regenerateCommand: z.ZodOptional<z.ZodString>;
44
- source: z.ZodOptional<z.ZodString>;
45
- }, z.core.$strip>;
46
- /**
47
- * Where a generated TypeScript client is written.
48
- */
49
- type FetchClientTargetOptions = z.input<typeof FetchClientOptionsSchema> & GeneratedFileOptions;
50
- /**
51
- * A TypeScript client for `kizuna.config.ts`.
52
- *
53
- * @example
54
- * fetchClient({
55
- * output: './packages/api-client/src/generated.ts',
56
- * });
57
- */
58
- declare const fetchClient: (options: {
59
- namespace?: string | undefined;
60
- runtimeModule?: string | undefined;
61
- regenerateCommand?: string | undefined;
62
- source?: string | undefined;
63
- } & GeneratedFileOptions) => _$kizunajs.GeneratedFile;
64
- //#endregion
65
- export { type FetchClientOptions, type FetchClientTargetOptions, fetchClient, generateFetchClient };
package/dist/server.d.mts DELETED
@@ -1,65 +0,0 @@
1
- import * as _$kizunajs from "kizunajs";
2
- import { ApiDefinition } from "kizunajs";
3
- import { GeneratedFileOptions } from "kizunajs/generator";
4
- import { z } from "zod";
5
-
6
- //#region src/generator.d.ts
7
- /**
8
- * What a generated client is called and where its runtime comes from.
9
- */
10
- interface FetchClientOptions {
11
- /**
12
- * Name of the generated namespace holding every model and every route's
13
- * `Params`, `Query`, `Body`, `Headers` and `Result`.
14
- *
15
- * @default 'API'
16
- */
17
- namespace?: string;
18
- /**
19
- * Module the generated file imports its runtime from.
20
- *
21
- * @default '@kizunajs/fetch'
22
- */
23
- runtimeModule?: string;
24
- /**
25
- * Command the file's header tells a reader to run.
26
- *
27
- * @default 'kizuna generate'
28
- */
29
- regenerateCommand?: string;
30
- /**
31
- * Path to the api this was generated from, relative to the generated
32
- * file. Named in the header so tooling can tell when the client has fallen
33
- * behind, and so a reader knows where the API is declared.
34
- */
35
- source?: string;
36
- }
37
- declare const generateFetchClient: (contract: ApiDefinition, options?: FetchClientOptions) => string;
38
- //#endregion
39
- //#region src/client-target.d.ts
40
- declare const FetchClientOptionsSchema: z.ZodObject<{
41
- namespace: z.ZodOptional<z.ZodString>;
42
- runtimeModule: z.ZodOptional<z.ZodString>;
43
- regenerateCommand: z.ZodOptional<z.ZodString>;
44
- source: z.ZodOptional<z.ZodString>;
45
- }, z.core.$strip>;
46
- /**
47
- * Where a generated TypeScript client is written.
48
- */
49
- type FetchClientTargetOptions = z.input<typeof FetchClientOptionsSchema> & GeneratedFileOptions;
50
- /**
51
- * A TypeScript client for `kizuna.config.ts`.
52
- *
53
- * @example
54
- * fetchClient({
55
- * output: './packages/api-client/src/generated.ts',
56
- * });
57
- */
58
- declare const fetchClient: (options: {
59
- namespace?: string | undefined;
60
- runtimeModule?: string | undefined;
61
- regenerateCommand?: string | undefined;
62
- source?: string | undefined;
63
- } & GeneratedFileOptions) => _$kizunajs.GeneratedFile;
64
- //#endregion
65
- export { type FetchClientOptions, type FetchClientTargetOptions, fetchClient, generateFetchClient };