@sdk-it/typescript 0.46.11 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +79 -12
  2. package/dist/index.d.ts +2 -2
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1399 -1538
  5. package/dist/index.js.map +4 -4
  6. package/dist/lib/agent/ai-sdk.d.ts +2 -1
  7. package/dist/lib/agent/ai-sdk.d.ts.map +1 -1
  8. package/dist/lib/agent/openai-agents.d.ts +2 -1
  9. package/dist/lib/agent/openai-agents.d.ts.map +1 -1
  10. package/dist/lib/client-name.d.ts +16 -0
  11. package/dist/lib/client-name.d.ts.map +1 -0
  12. package/dist/lib/client.d.ts +25 -1
  13. package/dist/lib/client.d.ts.map +1 -1
  14. package/dist/lib/emitters/interface.d.ts +4 -2
  15. package/dist/lib/emitters/interface.d.ts.map +1 -1
  16. package/dist/lib/emitters/snippet.d.ts.map +1 -1
  17. package/dist/lib/emitters/zod.d.ts +13 -3
  18. package/dist/lib/emitters/zod.d.ts.map +1 -1
  19. package/dist/lib/folder-index.d.ts +7 -0
  20. package/dist/lib/folder-index.d.ts.map +1 -0
  21. package/dist/lib/generate.d.ts +28 -3
  22. package/dist/lib/generate.d.ts.map +1 -1
  23. package/dist/lib/generator.d.ts +28 -29
  24. package/dist/lib/generator.d.ts.map +1 -1
  25. package/dist/lib/group-identifier.d.ts +7 -0
  26. package/dist/lib/group-identifier.d.ts.map +1 -0
  27. package/dist/lib/import-utilities.d.ts.map +1 -1
  28. package/dist/lib/input-schema-name.d.ts +4 -0
  29. package/dist/lib/input-schema-name.d.ts.map +1 -0
  30. package/dist/lib/model-name.d.ts +7 -0
  31. package/dist/lib/model-name.d.ts.map +1 -0
  32. package/dist/lib/module-file.d.ts +7 -0
  33. package/dist/lib/module-file.d.ts.map +1 -0
  34. package/dist/lib/one-module.d.ts +57 -0
  35. package/dist/lib/one-module.d.ts.map +1 -0
  36. package/dist/lib/options.d.ts +4 -6
  37. package/dist/lib/options.d.ts.map +1 -1
  38. package/dist/lib/readme/prop.emitter.d.ts +4 -4
  39. package/dist/lib/readme/prop.emitter.d.ts.map +1 -1
  40. package/dist/lib/readme/readme.d.ts.map +1 -1
  41. package/dist/lib/references.d.ts +43 -0
  42. package/dist/lib/references.d.ts.map +1 -0
  43. package/dist/lib/root-exports.d.ts +6 -0
  44. package/dist/lib/root-exports.d.ts.map +1 -0
  45. package/dist/lib/sdk.d.ts +17 -27
  46. package/dist/lib/sdk.d.ts.map +1 -1
  47. package/dist/lib/security.d.ts +2 -3
  48. package/dist/lib/security.d.ts.map +1 -1
  49. package/dist/lib/server-urls.d.ts.map +1 -1
  50. package/dist/lib/status-map.d.ts +2 -2
  51. package/dist/lib/status-map.d.ts.map +1 -1
  52. package/dist/lib/typescript-snippet.d.ts +4 -8
  53. package/dist/lib/typescript-snippet.d.ts.map +1 -1
  54. package/package.json +19 -6
  55. package/dist/lib/pagination-emit.d.ts +0 -3
  56. package/dist/lib/pagination-emit.d.ts.map +0 -1
  57. package/dist/lib/response-shape.d.ts +0 -22
  58. package/dist/lib/response-shape.d.ts.map +0 -1
  59. package/dist/lib/style.d.ts +0 -4
  60. package/dist/lib/style.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,312 +1,386 @@
1
+ // packages/typescript/src/lib/client-name.ts
2
+ import { camelcase as camelcase3 } from "stringcase";
3
+ import { pascalcase } from "@sdk-it/core";
4
+
5
+ // packages/typescript/src/lib/client.ts
6
+ import { camelcase as camelcase2 } from "stringcase";
7
+
8
+ // packages/typescript/src/lib/group-identifier.ts
9
+ import { camelcase } from "stringcase";
10
+ import { sanitizeTag } from "@sdk-it/spec";
11
+ function groupIdentifier(group) {
12
+ return sanitizeTag(camelcase(group));
13
+ }
14
+
15
+ // packages/typescript/src/lib/references.ts
16
+ function fileReferences(modelNamespace) {
17
+ return {
18
+ model: (typeName) => `${modelNamespace}.${typeName}`,
19
+ input: (group, schemaName) => `${groupIdentifier(group)}.${schemaName}`,
20
+ status: (className) => `http.${className}`,
21
+ runtime: (name) => name,
22
+ global: (name) => name,
23
+ located: (text) => text
24
+ };
25
+ }
26
+ var inputFileReferences = {
27
+ ...fileReferences("models"),
28
+ global: (name) => `\0${name}\0`
29
+ };
30
+ function inputGlobals(text, schemaNames) {
31
+ return text.replaceAll(
32
+ /\0(\w+)\0/g,
33
+ (_, name) => schemaNames.has(name) ? `globalThis.${name}` : name
34
+ );
35
+ }
36
+
37
+ // packages/typescript/src/lib/security.ts
38
+ var securityTypeExports = [
39
+ "SecurityContext",
40
+ "SecurityCredential",
41
+ "SecurityCredentialProvider",
42
+ "SecurityCredentialValue"
43
+ ];
44
+
45
+ // packages/typescript/src/lib/client.ts
46
+ var credentialSchemaNames = [
47
+ "stringCredentialSchema",
48
+ "basicCredentialSchema",
49
+ "mutualTlsCredentialSchema"
50
+ ];
51
+ function credentialSchemaName(scheme) {
52
+ if (scheme.type === "mutualTLS") {
53
+ return "mutualTlsCredentialSchema";
54
+ }
55
+ if (scheme.type === "http" && scheme.scheme?.toLowerCase() === "basic") {
56
+ return "basicCredentialSchema";
57
+ }
58
+ return "stringCredentialSchema";
59
+ }
60
+ function credentialSchemas(spec) {
61
+ return Object.entries(spec.securitySchemes).map(
62
+ ([scheme, definition]) => [scheme, credentialSchemaName(definition)]
63
+ );
64
+ }
65
+ function clientExports(name) {
66
+ return [
67
+ `${name}Client`,
68
+ `${name}Credentials`,
69
+ `${name}Endpoints`,
70
+ `${name}Servers`,
71
+ `${name}Settings`
72
+ ];
73
+ }
74
+ function clientNamedExports(name) {
75
+ return [...clientExports(name), `create${name}`, camelcase2(name)];
76
+ }
77
+ var clientDeclarationBindings = [
78
+ "servers",
79
+ "__securitySchemes",
80
+ "__credentialsSchema",
81
+ "__api"
82
+ ];
83
+ function clientDeclaredNames(name) {
84
+ return [...clientNamedExports(name), ...clientDeclarationBindings];
85
+ }
86
+ var clientRuntimeExports = ["prepare", "request"];
87
+ function clientRuntimeTypeExports(spec) {
88
+ return credentialSchemas(spec).length > 0 ? securityTypeExports : [];
89
+ }
90
+ function clientDeclarations(spec, refs, routes) {
91
+ const { name } = spec;
92
+ const credentials = credentialSchemas(spec);
93
+ return `${spec.servers.length ? "export " : ""}const servers = ${JSON.stringify(spec.servers, null, 2)} as const;
94
+ ${spec.servers.length ? `export type ${name}Servers = (typeof servers)[number];` : ""}
95
+ const __securitySchemes = ${JSON.stringify(spec.securitySchemes, null, 2)} as const;
96
+ const __credentialsSchema = z.object({
97
+ ${credentials.map(([scheme, schema]) => ` ${JSON.stringify(scheme)}: ${refs.runtime(schema)}.optional(),`).join("\n")}
98
+ });
99
+ const __api = { routes: ${routes}, servers, securitySchemes: __securitySchemes, credentials: __credentialsSchema };
100
+
101
+ export interface ${name}Client extends ${refs.runtime("Client")}<typeof __api> {}
102
+ export type ${name}Settings = ${refs.runtime("ClientSettings")}<typeof __api>;
103
+ export type ${name}Endpoints = ${refs.runtime("EndpointsOf")}<typeof __api>;
104
+ ${credentials.length ? `export type ${name}Credentials = z.input<typeof __credentialsSchema>;` : ""}
105
+
106
+ export function ${refs.located(`create${name}`, title)}(settings: ${name}Settings): ${name}Client {
107
+ return ${refs.runtime("createClient")}(__api, settings);
108
+ }
109
+ ${spec.servers.length <= 1 ? `
110
+ export const ${refs.located(camelcase2(name), title)} = create${name}({});
111
+ ` : ""}`;
112
+ }
113
+ var title = ["info", "title"];
114
+ var aliased = /* @__PURE__ */ new Set([
115
+ "Client",
116
+ "ClientSettings",
117
+ "EndpointsOf",
118
+ "createClient"
119
+ ]);
120
+ var clientFileBindings = [
121
+ "z",
122
+ "__schemas",
123
+ ...[...aliased].map((name) => `__${name}`),
124
+ ...credentialSchemaNames,
125
+ ...clientRuntimeExports
126
+ ];
127
+ var clientFileReferences = {
128
+ ...fileReferences("outputs"),
129
+ runtime: (name) => aliased.has(name) ? `__${name}` : name
130
+ };
131
+ var client_default = (spec) => {
132
+ const { makeImport } = spec;
133
+ const typeExports = clientRuntimeTypeExports(spec);
134
+ const credentialImports = [
135
+ ...new Set(credentialSchemas(spec).map(([, schema]) => schema))
136
+ ].sort();
137
+ return `import { z } from 'zod';
138
+ import __schemas from './api/${makeImport("schemas")}';
139
+ import { type Client as __Client, type ClientSettings as __ClientSettings, type EndpointsOf as __EndpointsOf, createClient as __createClient } from './http/${makeImport("client")}';${typeExports.length ? `
140
+ import { ${credentialImports.join(", ")} } from './http/${makeImport("security")}';
141
+ export type {
142
+ ${typeExports.map((type) => ` ${type},`).join("\n")}
143
+ } from './http/${makeImport("security")}';` : ""}
144
+ export { ${clientRuntimeExports.join(", ")} } from './http/${makeImport("client")}';
145
+
146
+ ${clientDeclarations(spec, clientFileReferences, "__schemas")}`;
147
+ };
148
+
149
+ // runtime-module:runtime-module
150
+ var runtime_module_default = { "text": "type Init = Omit<RequestInit, 'headers'> & { headers: Headers };\ntype RequestConfig = { init: Init; url: URL };\n/** The methods an OpenAPI operation uses, as an HTTP request line writes them. */\ntype Method =\n 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'TRACE' | 'HEAD';\ntype HeadersInit = [string, string][] | Record<string, string>;\n\ntype BodyInit =\n ArrayBuffer | Blob | FormData | URLSearchParams | null | string;\n\nfunction template(\n templateString: string,\n templateVariables: Record<string, any>,\n): string {\n const nargs = /{([0-9a-zA-Z_]+)}/g;\n return templateString.replace(nargs, (match, key: string, index: number) => {\n // Handle escaped double braces\n if (\n templateString[index - 1] === '{' &&\n templateString[index + match.length] === '}'\n ) {\n return key;\n }\n\n const result = key in templateVariables ? templateVariables[key] : null;\n return result === null || result === undefined\n ? ''\n : encodeURIComponent(String(result));\n });\n}\n\ntype Input = Record<string, any>;\n\n// Validated inputs can carry Date (coerce-date) values; String(new Date())\n// yields a local-time RFC 2822 string, so serialize Dates as ISO 8601.\nfunction toWireValue(value: any): string {\n return value instanceof Date ? value.toISOString() : String(value);\n}\n\n/** The values a field sends: none when the caller left it out, one per item of an array. */\nfunction wireItems(value: any): any[] {\n if (value === undefined) {\n return [];\n }\n return Array.isArray(value) ? value : [value];\n}\n\ntype Props = {\n /** The media type the body is sent as. */\n contentType: string;\n inputHeaders: string[];\n inputQuery: string[];\n inputBody: string[];\n inputParams: string[];\n};\n\nabstract class Serializer {\n protected input: Input;\n protected props: Props;\n\n constructor(input: Input, props: Props) {\n this.input = input;\n this.props = props;\n }\n\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(path: string, baseUrl: string): Serialized {\n const params = this.props.inputParams.reduce<Record<string, any>>(\n (acc, key) => {\n acc[key] = this.input[key];\n return acc;\n },\n {},\n );\n const url = new URL(`${baseUrl}${template(path, params)}`);\n\n const headers: Record<string, string> = { ...this.getHeaders() };\n for (const header of this.props.inputHeaders) {\n const value = this.input[header];\n if (value !== undefined) {\n headers[header] = toWireValue(value);\n }\n }\n\n for (const key of this.props.inputQuery) {\n for (const item of wireItems(this.input[key])) {\n url.searchParams.append(key, toWireValue(item));\n }\n }\n\n return {\n body: this.getBody(),\n url,\n headers,\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n headers: Record<string, string>;\n url: URL;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\n if (\n this.props.inputBody.length === 1 &&\n this.props.inputBody[0] === '$body'\n ) {\n return JSON.stringify(this.input.$body);\n }\n\n for (const prop of this.props.inputBody) {\n body[prop] = this.input[prop];\n }\n return JSON.stringify(body);\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': this.props.contentType,\n Accept: 'application/json',\n };\n }\n}\n\nclass UrlencodedSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new URLSearchParams();\n for (const prop of this.props.inputBody) {\n for (const item of wireItems(this.input[prop])) {\n body.append(prop, toWireValue(item));\n }\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': this.props.contentType,\n Accept: 'application/json',\n };\n }\n}\n\nclass EmptySerializer extends Serializer {\n getBody(): BodyInit | null {\n return null;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass FormDataSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new FormData();\n for (const prop of this.props.inputBody) {\n for (const item of wireItems(this.input[prop])) {\n body.append(prop, item);\n }\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n Accept: 'application/json',\n };\n }\n}\n\n// A text or binary body is the caller's own string or Blob, sent as is.\nclass RawSerializer extends Serializer {\n getBody(): BodyInit | null {\n return this.input.$body;\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': this.props.contentType,\n };\n }\n}\n\nfunction json(input: Input, props: Props) {\n return new JsonSerializer(input, props);\n}\nfunction urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props);\n}\nfunction empty(input: Input, props: Props) {\n return new EmptySerializer(input, props);\n}\nfunction formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props);\n}\nfunction text(input: Input, props: Props) {\n return new RawSerializer(input, props);\n}\nfunction binary(input: Input, props: Props) {\n return new RawSerializer(input, props);\n}\n\nfunction toRequest(\n method: Method,\n path: string,\n serializer: Serializer,\n baseUrl: string,\n): RequestConfig {\n const input = serializer.serialize(path, baseUrl);\n return {\n url: input.url,\n init: {\n method: method,\n headers: new Headers(input.headers),\n ...(method === 'GET' ? {} : { body: input.body }),\n },\n };\n}\n\n\n\ninterface Interceptor {\n before?: (config: RequestConfig) => Promise<RequestConfig> | RequestConfig;\n after?: (response: Response) => Promise<Response> | Response;\n}\n\nconst createHeadersInterceptor = (\n headers: Record<string, string | undefined>,\n requestHeaders: HeadersInit,\n): Interceptor => {\n return {\n before({ init, url }) {\n // Priority Levels\n // 1. Headers Input\n // 2. Request Headers\n // 3. Default Headers\n\n for (const [key, value] of new Headers(requestHeaders)) {\n // Only set the header if it doesn't already exist and has a value\n // even though these headers are passed at operation level\n // still they are lower priority compared to the headers input\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n for (const [key, value] of Object.entries(headers)) {\n // Only set the header if it doesn't already exist and has a value\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n return { init, url };\n },\n };\n};\n\n\n\nfunction isBinaryContentType(contentType: string) {\n const type = contentType.toLowerCase();\n if (type.startsWith('image/')) {\n return true;\n }\n if (type.startsWith('audio/')) {\n return true;\n }\n if (type.startsWith('video/')) {\n return true;\n }\n switch (type) {\n case 'application/pdf':\n case 'application/zip':\n case 'application/gzip':\n case 'application/x-7z-compressed':\n case 'application/x-tar':\n case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':\n case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':\n case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':\n case 'application/vnd.ms-excel':\n case 'application/vnd.ms-powerpoint':\n case 'application/msword':\n case 'application/octet-stream':\n return true;\n default:\n return false;\n }\n}\n\nfunction chunked(response: Response) {\n return response.body!;\n}\n\n// The operation declares no body; release the unread stream so the\n// connection is not held until garbage collection.\nasync function bodyless(response: Response) {\n await response.body?.cancel();\n return null;\n}\n\n/** The body kinds the buffered parser reads: what the spec declares for a status. */\ntype BufferedBody = 'json' | 'text' | 'binary';\n\n/**\n * Reads a body by its Content-Type. A response without one reads as the body\n * the spec declares for its status, or, with none declared, as the\n * application/octet-stream that RFC 9110 \xA78.3 lets a recipient assume.\n */\nfunction buffered(declared?: BufferedBody) {\n return async (response: Response): Promise<unknown> => {\n // Statuses that, per the HTTP spec, carry no message body. These\n // responses usually omit Content-Type entirely.\n if (\n response.status === 204 ||\n response.status === 205 ||\n response.status === 304\n ) {\n return null;\n }\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return byContentType(response, contentType);\n }\n const bytes = await response.bytes();\n if (bytes.byteLength === 0) {\n return null;\n }\n switch (declared) {\n case 'json':\n return JSON.parse(new TextDecoder().decode(bytes));\n case 'text':\n return new TextDecoder().decode(bytes);\n default:\n return new Blob([bytes], { type: 'application/octet-stream' });\n }\n };\n}\n\nasync function byContentType(response: Response, contentType: string) {\n const { type } = parse(contentType);\n if (isBinaryContentType(type)) {\n return response.blob();\n }\n if (type.startsWith('text/')) {\n return response.text();\n }\n if (type === 'application/json' || type.endsWith('+json')) {\n return response.json();\n }\n switch (type) {\n case 'application/xml':\n return response.text();\n case 'application/x-www-form-urlencoded': {\n const text = await response.text();\n return Object.fromEntries(new URLSearchParams(text));\n }\n case 'multipart/form-data':\n return response.formData();\n default:\n throw new Error(`Unsupported content type: ${contentType}`);\n }\n}\n\n/** The status ranges an OpenAPI 3.2 Responses Object may declare. */\ntype StatusRange = '1XX' | '2XX' | '3XX' | '4XX' | '5XX';\ntype Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';\ntype ToNumber<S> = S extends `${infer N extends number}` ? N : never;\n/** Every status code a range covers: `RangeStatus<'4XX'>` is 400 | 401 | \u2026 | 499. */\ntype RangeStatus<R extends StatusRange> = R extends `${infer C}XX`\n ? ToNumber<`${C}${Digit}${Digit}`>\n : never;\nclass APIResponse<Body = unknown, Status extends number = number> {\n static readonly status: number;\n readonly status: Status;\n data: Body;\n readonly headers: Headers;\n\n constructor(status: Status, headers: Headers, data: Body) {\n this.status = status;\n this.headers = headers;\n this.data = data;\n }\n\n static create(status: number, headers: Headers, data: unknown) {\n return new this(status, headers, data);\n }\n}\n\nclass APIError<Body, Status extends number = number> extends Error {\n static readonly status: number;\n readonly status: Status;\n data: Body;\n readonly headers: Headers;\n\n constructor(status: Status, headers: Headers, data: Body) {\n super(failureMessage(status, data));\n this.name = 'APIError';\n this.status = status;\n this.headers = headers;\n this.data = data;\n }\n\n static create<T>(status: number, headers: Headers, data: T) {\n return new this(status, headers, data);\n }\n}\n\nfunction failureMessage(status: number, data: unknown) {\n const summary = bodySummary(data);\n return summary\n ? `Request failed with status code ${status}: ${summary}`\n : `Request failed with status code ${status}`;\n}\n\n// Only text and JSON bodies read as a summary; a Blob, stream or FormData body\n// has none. The tag check holds across realms, where prototype checks do not.\nfunction bodySummary(data: unknown) {\n const tag = Object.prototype.toString.call(data);\n let text = '';\n if (typeof data === 'string') {\n text = data;\n } else if (tag === '[object Object]' || tag === '[object Array]') {\n text = JSON.stringify(data);\n }\n const line = text.replace(/\\s+/g, ' ').trim();\n return line.length > 200 ? `${line.slice(0, 200)}\u2026` : line;\n}\n\n// 2xx Success\nclass Ok<T> extends APIResponse<T, 200> {\n static override readonly status = 200 as const;\n constructor(headers: Headers, data: T) {\n super(Ok.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\nclass Created<T> extends APIResponse<T, 201> {\n static override status = 201 as const;\n constructor(headers: Headers, data: T) {\n super(Created.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass Accepted<T> extends APIResponse<T, 202> {\n static override status = 202 as const;\n constructor(headers: Headers, data: T) {\n super(Accepted.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass NoContent extends APIResponse<null, 204> {\n static override status = 204 as const;\n constructor(headers: Headers) {\n super(NoContent.status, headers, null);\n }\n static override create(status: number, headers: Headers): NoContent {\n return new this(headers);\n }\n}\n\n// 4xx Client Errors\nclass BadRequest<T> extends APIError<T, 400> {\n static override status = 400 as const;\n constructor(headers: Headers, data: T) {\n super(BadRequest.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass Unauthorized<T = { message: string }> extends APIError<T, 401> {\n static override status = 401 as const;\n constructor(headers: Headers, data: T) {\n super(Unauthorized.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass PaymentRequired<T = { message: string }> extends APIError<T, 402> {\n static override status = 402 as const;\n constructor(headers: Headers, data: T) {\n super(PaymentRequired.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass Forbidden<T = { message: string }> extends APIError<T, 403> {\n static override status = 403 as const;\n constructor(headers: Headers, data: T) {\n super(Forbidden.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass NotFound<T = { message: string }> extends APIError<T, 404> {\n static override status = 404 as const;\n constructor(headers: Headers, data: T) {\n super(NotFound.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass MethodNotAllowed<T = { message: string }> extends APIError<\n T,\n 405\n> {\n static override status = 405 as const;\n constructor(headers: Headers, data: T) {\n super(MethodNotAllowed.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass NotAcceptable<T = { message: string }> extends APIError<T, 406> {\n static override status = 406 as const;\n constructor(headers: Headers, data: T) {\n super(NotAcceptable.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass Conflict<T = { message: string }> extends APIError<T, 409> {\n static override status = 409 as const;\n constructor(headers: Headers, data: T) {\n super(Conflict.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass Gone<T = { message: string }> extends APIError<T, 410> {\n static override status = 410 as const;\n constructor(headers: Headers, data: T) {\n super(Gone.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass PreconditionFailed<T = { message: string }> extends APIError<\n T,\n 412\n> {\n static override status = 412 as const;\n constructor(headers: Headers, data: T) {\n super(PreconditionFailed.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass UnprocessableEntity<\n T = { message: string; errors?: Record<string, string[]> },\n> extends APIError<T, 422> {\n static override status = 422 as const;\n constructor(headers: Headers, data: T) {\n super(UnprocessableEntity.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass TooManyRequests<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 429> {\n static override status = 429 as const;\n constructor(headers: Headers, data: T) {\n super(TooManyRequests.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass PayloadTooLarge<T = { message: string }> extends APIError<T, 413> {\n static override status = 413 as const;\n constructor(headers: Headers, data: T) {\n super(PayloadTooLarge.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass UnsupportedMediaType<T = { message: string }> extends APIError<\n T,\n 415\n> {\n static override status = 415 as const;\n constructor(headers: Headers, data: T) {\n super(UnsupportedMediaType.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\n// 5xx Server Errors\nclass InternalServerError<T = { message: string }> extends APIError<\n T,\n 500\n> {\n static override status = 500 as const;\n constructor(headers: Headers, data: T) {\n super(InternalServerError.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass NotImplemented<T = { message: string }> extends APIError<T, 501> {\n static override status = 501 as const;\n constructor(headers: Headers, data: T) {\n super(NotImplemented.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass BadGateway<T = { message: string }> extends APIError<T, 502> {\n static override status = 502 as const;\n constructor(headers: Headers, data: T) {\n super(BadGateway.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass ServiceUnavailable<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 503> {\n static override status = 503 as const;\n constructor(headers: Headers, data: T) {\n super(ServiceUnavailable.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nclass GatewayTimeout<T = { message: string }> extends APIError<T, 504> {\n static override status = 504 as const;\n constructor(headers: Headers, data: T) {\n super(GatewayTimeout.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\ntype ClientError =\n | BadRequest<unknown>\n | Unauthorized<unknown>\n | PaymentRequired<unknown>\n | Forbidden<unknown>\n | NotFound<unknown>\n | MethodNotAllowed<unknown>\n | NotAcceptable<unknown>\n | Conflict<unknown>\n | Gone<unknown>\n | PreconditionFailed<unknown>\n | PayloadTooLarge<unknown>\n | UnsupportedMediaType<unknown>\n | UnprocessableEntity<unknown>\n | TooManyRequests<unknown>\n | APIError<unknown, RangeStatus<'4XX'>>;\n\ntype ServerError =\n | InternalServerError<unknown>\n | NotImplemented<unknown>\n | BadGateway<unknown>\n | ServiceUnavailable<unknown>\n | GatewayTimeout<unknown>\n | APIError<unknown, RangeStatus<'5XX'>>;\n\ntype ProblematicResponse = ClientError | ServerError;\n\ntype SuccessfulResponse<T = unknown> =\n | Ok<T>\n | Created<T>\n | Accepted<T>\n | NoContent\n | APIResponse<T, RangeStatus<'2XX'>>;\n\ntype RebindSuccessPayload<Resp, New> =\n Resp extends Ok<infer _>\n ? Ok<New>\n : Resp extends Created<infer _>\n ? Created<New>\n : Resp extends Accepted<infer _>\n ? Accepted<New>\n : Resp extends NoContent\n ? NoContent\n : Resp extends SuccessfulResponse<infer _>\n ? APIResponse<New, Resp['status']>\n : never;\n\ntype SSEListener = (eventType: string) => AsyncIterable<string>;\n\nfunction sse(response: Response): SSEListener {\n // Every iterator of an event type reads one queue. Each waiting next() keeps\n // its own wake-up in `waiters`, and a push or the end of the stream wakes all\n // of them: a woken next() that finds the queue empty waits again. One shared\n // wake-up slot would let a second iterator overwrite the first one's, which\n // then never wakes.\n const subscribers = new Map<\n string,\n { queue: string[]; waiters: Set<() => void> }\n >();\n let started = false;\n let streamDone = false;\n let streamFailure: { error: unknown } | null = null;\n\n function wake(waiters: Set<() => void>) {\n for (const resolve of waiters) resolve();\n waiters.clear();\n }\n\n function dispatch(eventType: string, data: string) {\n const sub = subscribers.get(eventType);\n if (sub) {\n sub.queue.push(data);\n wake(sub.waiters);\n }\n }\n\n function endAll() {\n streamDone = true;\n for (const sub of subscribers.values()) {\n wake(sub.waiters);\n }\n }\n\n function startReading() {\n if (started) return;\n started = true;\n const decoder = new TextDecoder();\n let buffer = '';\n\n // The pump never rejects: the catch below hands a stream failure to the\n // listeners, so nothing awaits it. `void` states that, and keeps generated\n // output clean under @typescript-eslint/no-floating-promises.\n void (async () => {\n try {\n for await (const value of response.body!) {\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split('\\n\\n');\n buffer = parts.pop()!;\n\n for (const part of parts) {\n if (!part.trim()) continue;\n let eventType = 'message';\n let data = '';\n for (const line of part.split('\\n')) {\n if (line.startsWith('event:')) {\n eventType = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n data += (data ? '\\n' : '') + line.slice(5).trim();\n }\n }\n if (data) dispatch(eventType, data);\n }\n }\n } catch (error) {\n streamFailure = { error };\n }\n endAll();\n })();\n }\n\n return function listen(eventType: string): AsyncIterable<string> {\n if (!subscribers.has(eventType)) {\n subscribers.set(eventType, { queue: [], waiters: new Set() });\n }\n const sub = subscribers.get(eventType)!;\n startReading();\n\n return {\n [Symbol.asyncIterator]() {\n return {\n async next(): Promise<IteratorResult<string>> {\n while (sub.queue.length === 0) {\n if (streamFailure) throw streamFailure.error;\n if (streamDone) return { value: undefined, done: true };\n const { promise, resolve } = Promise.withResolvers<void>();\n sub.waiters.add(resolve);\n await promise;\n }\n return { value: sub.queue.shift()!, done: false };\n },\n async return(): Promise<IteratorResult<string>> {\n return { value: undefined, done: true };\n },\n };\n },\n };\n };\n}\n\n\n\ntype Unionize<T> = T extends [infer Single extends OutputType]\n ? InstanceType<Single>\n : T extends readonly [...infer Tuple extends OutputType[]]\n ? { [I in keyof Tuple]: InstanceType<Tuple[I]> }[number]\n : never;\n\ntype InstanceType<T> =\n T extends Type<infer U>\n ? U\n : T extends { type: Type<infer U> }\n ? U\n : T extends Array<unknown>\n ? Unionize<T>\n : never;\n\ntype ResponseData<T extends OutputType[]> =\n Extract<InstanceType<T>, SuccessfulResponse> extends SuccessfulResponse<\n infer P\n >\n ? P\n : unknown;\n\ntype ResponseMapper<T extends OutputType[], R> = (data: ResponseData<T>) => R;\n\ninterface Type<T> {\n new (...args: any[]): T;\n}\ntype Parser = (\n response: Response,\n) => Promise<unknown> | ReadableStream<any> | SSEListener;\n/** An output that `range` declares reads every status of the range that no exact output declares. */\ntype OutputType =\n | Type<APIResponse>\n | { parser: Parser; type: Type<APIResponse>; range?: StatusRange };\n\n// Bare z.custom (no predicate) on purpose: Request/Response from another\n// realm (undici vs global fetch) fail instanceof checks. The output is\n// typed as a Promise directly \u2014 zod 4 deprecated z.promise.\nconst fetchType = z\n .function({\n input: [z.custom<Request>()],\n output: z.custom<Promise<Response>>(),\n })\n .optional();\n\n/** Reads the body of a status the operation declares no output for. */\nconst undeclared: Parser = buffered();\n\nasync function parse<T extends OutputType[]>(\n outputs: T,\n response: Response,\n): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\nasync function parse<T extends OutputType[], R>(\n outputs: T,\n response: Response,\n mapper: ResponseMapper<T, R>,\n): Promise<\n RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>\n>;\nasync function parse(\n outputs: OutputType[],\n response: Response,\n mapper?: (data: unknown) => unknown,\n): Promise<APIResponse> {\n const declared = match(outputs, response.status);\n const output = declared ? typeOf(declared) : null;\n const parser =\n declared && 'parser' in declared ? declared.parser : undeclared;\n\n if (response.ok) {\n const data = await parser(response);\n const mapped = mapper ? mapper(data) : data;\n const success =\n output && isTypeOf(output, APIResponse) ? output : APIResponse;\n return success.create(response.status, response.headers, mapped);\n }\n\n const failure = output && isTypeOf(output, APIError) ? output : APIError;\n throw failure.create(\n response.status,\n response.headers,\n await parser(response),\n );\n}\n\n// OpenAPI 3.2 Responses Object: an explicit code takes precedence over the\n// range that covers it.\nfunction match(outputs: OutputType[], status: number) {\n const range = `${Math.trunc(status / 100)}XX`;\n return (\n outputs.find(\n (output) => !('range' in output) && statusOf(output) === status,\n ) ?? outputs.find((output) => 'range' in output && output.range === range)\n );\n}\n\nfunction typeOf(output: OutputType) {\n return 'parser' in output ? output.type : output;\n}\n\nfunction statusOf(output: OutputType) {\n const type = typeOf(output);\n return isTypeOf(type, APIResponse) || isTypeOf(type, APIError)\n ? type.status\n : undefined;\n}\n\nfunction isTypeOf<T extends Type<APIResponse>>(\n instance: any,\n baseType: T,\n): instance is T {\n return (\n instance === baseType ||\n Object.prototype.isPrototypeOf.call(baseType, instance)\n );\n}\n\nclass Dispatcher {\n #interceptors: Interceptor[] = [];\n #fetch: z.infer<typeof fetchType>;\n constructor(interceptors: Interceptor[], fetch?: z.infer<typeof fetchType>) {\n this.#interceptors = interceptors;\n this.#fetch = fetch;\n }\n\n async send<T extends OutputType[]>(\n config: RequestConfig,\n outputs: T,\n signal?: AbortSignal,\n ): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\n async send<T extends OutputType[], R>(\n config: RequestConfig,\n outputs: T,\n signal: AbortSignal | undefined,\n mapper: ResponseMapper<T, R>,\n ): Promise<\n RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>\n >;\n async send<T extends OutputType[], R = ResponseData<T>>(\n config: RequestConfig,\n outputs: T,\n signal?: AbortSignal,\n mapper?: ResponseMapper<T, R>,\n ) {\n for (const interceptor of this.#interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n\n const init =\n signal === undefined ? config.init : { ...config.init, signal };\n\n let response = await (this.#fetch ?? fetch)(new Request(config.url, init));\n\n for (const interceptor of this.#interceptors.toReversed()) {\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n\n if (mapper) {\n return await parse(outputs, response, mapper);\n }\n return await parse(outputs, response);\n }\n}\n\n/** How an operation pages, as the spec IR records it. Paths are dot-separated paths into the response body. */\ntype Pagination =\n | {\n type: 'offset';\n offsetParamName: string;\n limitParamName: string;\n items: string;\n hasMore: string;\n statusCode: number;\n /** The offset parameter's default in the spec. */\n start?: number;\n }\n | {\n type: 'page';\n pageNumberParamName: string;\n pageSizeParamName: string;\n items: string;\n hasMore: string;\n statusCode: number;\n /** The page parameter's default in the spec. */\n start?: number;\n }\n | {\n type: 'cursor';\n cursorParamName: string;\n items: string;\n hasMore: string;\n statusCode: number;\n /** Path of the cursor that requests the next page. */\n nextCursor?: string;\n };\n\ntype PathValue<T, P extends string> = P extends `${infer K}.${infer Rest}`\n ? K extends keyof NonNullable<T>\n ? PathValue<NonNullable<T>[K], Rest>\n : never\n : P extends keyof NonNullable<T>\n ? NonNullable<T>[P]\n : never;\n\n/** The item type of the array at `P` in `Data`. */\ntype ItemOf<Data, P extends string> =\n NonNullable<PathValue<Data, P>> extends readonly (infer I)[] ? I : never;\n\n/** Options for the request a page fetch sends; they override the first request's. */\ninterface PageRequestOptions {\n signal?: AbortSignal;\n}\n\n/**\n * The way from a page to the next. A next page has the type of the page it\n * comes from, so generic code over one endpoint keeps that endpoint's type.\n */\ninterface PageControls<Item> extends AsyncIterable<Item> {\n hasNextPage(): boolean;\n getNextPage<P extends PageControls<unknown>>(\n this: P,\n options?: PageRequestOptions,\n ): Promise<P>;\n /** This page, then each following page. */\n iterPages<P extends PageControls<unknown>>(\n this: P,\n options?: PageRequestOptions,\n ): AsyncGenerator<P>;\n}\n\n/** A page: the response body's fields, and the way to the next page. */\ntype Page<Data, Item> = Data & PageControls<Item>;\n\ntype FetchPage = (\n input: Record<string, unknown>,\n options: PageRequestOptions | undefined,\n) => Promise<ResponsePage>;\n\nfunction at(data: unknown, path: string): unknown {\n let value = data;\n for (const key of path.split('.')) {\n if (typeof value !== 'object' || value === null) return undefined;\n value = Reflect.get(value, key);\n }\n return value;\n}\n\n/**\n * The position an omitted offset or page parameter stands for: the spec's\n * default, else the first offset (0) or the first page (1).\n */\nfunction position(sent: unknown, start: number | undefined, first: number) {\n if (typeof sent === 'number') return sent;\n return start ?? first;\n}\n\nclass ResponsePage {\n readonly #input: Record<string, unknown>;\n readonly #pagination: Pagination;\n readonly #fetchPage: FetchPage;\n readonly #items: unknown[];\n\n constructor(\n data: object,\n input: Record<string, unknown>,\n pagination: Pagination,\n fetchPage: FetchPage,\n ) {\n Object.assign(this, data);\n this.#input = input;\n this.#pagination = pagination;\n this.#fetchPage = fetchPage;\n const items = at(data, pagination.items);\n // A spec may declare the items array nullable; a page without one is empty.\n this.#items = Array.isArray(items) ? items : [];\n }\n\n hasNextPage() {\n return Boolean(at(this, this.#pagination.hasMore));\n }\n\n async getNextPage(options?: PageRequestOptions) {\n return this.#fetchPage(this.#nextInput(), options);\n }\n\n async *iterPages(options?: PageRequestOptions) {\n yield this;\n let page = this.hasNextPage() ? await this.getNextPage(options) : undefined;\n while (page) {\n yield page;\n page = page.hasNextPage() ? await page.getNextPage(options) : undefined;\n }\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iterPages()) {\n yield* page.#items;\n }\n }\n\n #nextInput(): Record<string, unknown> {\n const pagination = this.#pagination;\n switch (pagination.type) {\n case 'offset': {\n const offset = position(\n this.#input[pagination.offsetParamName],\n pagination.start,\n 0,\n );\n return {\n ...this.#input,\n [pagination.offsetParamName]: offset + this.#items.length,\n };\n }\n case 'page': {\n const page = position(\n this.#input[pagination.pageNumberParamName],\n pagination.start,\n 1,\n );\n return { ...this.#input, [pagination.pageNumberParamName]: page + 1 };\n }\n case 'cursor': {\n const cursor = pagination.nextCursor\n ? at(this, pagination.nextCursor)\n : undefined;\n if (typeof cursor !== 'string') {\n throw new Error(\n 'The response says more pages exist but names no next cursor',\n );\n }\n return { ...this.#input, [pagination.cursorParamName]: cursor };\n }\n }\n }\n}\n\n/** Builds the Page for `data`, the body of a response to `input`. */\nfunction createPage(\n data: object,\n input: Record<string, unknown>,\n pagination: Pagination,\n fetchPage: FetchPage,\n): ResponsePage {\n return new ResponsePage(data, input, pagination, fetchPage);\n}\n\n/**\n * The promise of a page that is also an async iterable of every item across\n * pages, so `for await (const item of client.request(\u2026))` needs no `await`.\n */\nclass PagePromise<P extends AsyncIterable<Item>, Item>\n extends Promise<P>\n implements AsyncIterable<Item>\n{\n static override get [Symbol.species]() {\n return Promise;\n }\n\n constructor(page: Promise<P>) {\n super((resolve, reject) => {\n page.then(resolve, reject);\n });\n }\n\n async *[Symbol.asyncIterator]() {\n yield* await this;\n }\n}\n\n\n\nclass ParseError<T extends z.ZodType> extends Error {\n public data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>;\n constructor(data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>) {\n super('Validation failed');\n this.name = 'ParseError';\n this.data = data;\n }\n}\n\nfunction parseInput<T extends z.ZodType>(\n schema: T,\n input: unknown,\n): z.infer<T> {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = z.flattenError(result.error, (issue) => issue);\n throw new ParseError<T>(error);\n }\n return result.data;\n}\n\n\n\ntype SecurityContext = {\n scheme: string;\n scopes: readonly string[];\n roles: readonly string[];\n};\ntype SecurityCredentialValue =\n | string\n | true\n | {\n username: string;\n password: string;\n };\ntype SecurityCredentialProvider<T extends SecurityCredentialValue> = (\n context: SecurityContext,\n) => T | Promise<T>;\ntype SecurityCredential<\n T extends SecurityCredentialValue = SecurityCredentialValue,\n> = T | SecurityCredentialProvider<T>;\n\nconst providerSchema = <T extends SecurityCredentialValue>() =>\n z.custom<SecurityCredentialProvider<T>>(\n (value) => typeof value === 'function',\n );\nconst stringCredentialSchema = z.union([\n z.string(),\n z.literal(true),\n providerSchema<string | true>(),\n]);\nconst basicCredentialValueSchema = z.object({\n username: z.string(),\n password: z.string(),\n});\nconst basicCredentialSchema = z.union([\n basicCredentialValueSchema,\n z.literal(true),\n providerSchema<{ username: string; password: string } | true>(),\n]);\nconst mutualTlsCredentialSchema = z.union([\n z.literal(true),\n providerSchema<true>(),\n]);\n\ntype RuntimeSecurityScheme =\n | { type: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string }\n | { type: 'http'; scheme: string }\n | { type: 'oauth2' }\n | { type: 'openIdConnect' }\n | { type: 'mutualTLS' };\n\n/** The spec's components.securitySchemes; a requirement can name a scheme it lacks (an unresolved external one). */\ntype RuntimeSecuritySchemes = {\n readonly [name: string]: RuntimeSecurityScheme | undefined;\n};\n\nfunction createSecurityInterceptor(\n requirements: readonly Record<string, readonly string[]>[],\n credentials: Record<string, SecurityCredential | undefined> | undefined,\n schemes: RuntimeSecuritySchemes,\n): Interceptor {\n return {\n async before(config) {\n if (requirements.length === 0) return config;\n const secured = requirements.filter(\n (requirement) => Object.keys(requirement).length > 0,\n );\n const selected = secured.find((requirement) =>\n Object.keys(requirement).every(\n (name) => credentials?.[name] !== undefined,\n ),\n );\n if (!selected) {\n if (\n requirements.some(\n (requirement) => Object.keys(requirement).length === 0,\n )\n )\n return config;\n throw new Error(\n `Missing credentials for security requirements: ${secured\n .map((requirement) => Object.keys(requirement).join(' + '))\n .join(' or ')}`,\n );\n }\n for (const [name, values] of Object.entries(selected)) {\n const scheme = schemes[name];\n if (!scheme) {\n throw new Error(`Unsupported external security scheme: ${name}`);\n }\n const configured = credentials?.[name];\n const isOAuth =\n scheme.type === 'oauth2' || scheme.type === 'openIdConnect';\n const credential =\n typeof configured === 'function'\n ? await configured({\n scheme: name,\n scopes: isOAuth ? values : [],\n roles: isOAuth ? [] : values,\n })\n : configured;\n applyCredential(config, scheme, credential);\n }\n return config;\n },\n };\n}\n\nfunction applyCredential(\n config: RequestConfig,\n scheme: RuntimeSecurityScheme,\n credential: SecurityCredentialValue | undefined,\n) {\n if (credential === undefined) {\n throw new Error('Security credential provider returned no credential');\n }\n // true declares a transport-owned credential: the configured fetch, a host\n // proxy, or the browser's cookie jar supplies it, so nothing is set here.\n if (credential === true) return;\n if (scheme.type === 'apiKey') {\n if (typeof credential !== 'string') {\n throw new TypeError('API key credentials must be strings');\n }\n if (scheme.in === 'header') {\n if (!config.init.headers.has(scheme.name)) {\n config.init.headers.set(scheme.name, credential);\n }\n } else if (scheme.in === 'query') {\n if (!config.url.searchParams.has(scheme.name)) {\n config.url.searchParams.set(scheme.name, credential);\n }\n } else if (scheme.in === 'cookie') {\n if ('document' in globalThis) {\n throw new Error(\n `Cannot send the ${scheme.name} cookie credential: browsers forbid setting the Cookie header. Let the browser send the cookie and pass a fetch that sets credentials: 'include'.`,\n );\n }\n const cookie = `${scheme.name}=${encodeURIComponent(credential)}`;\n const existing = config.init.headers.get('Cookie');\n if (\n !existing\n ?.split(';')\n .some((part) => part.trim().startsWith(`${scheme.name}=`))\n ) {\n config.init.headers.set(\n 'Cookie',\n existing ? `${existing}; ${cookie}` : cookie,\n );\n }\n } else {\n throw new TypeError(`Unsupported apiKey location: ${String(scheme.in)}`);\n }\n return;\n }\n if (scheme.type === 'mutualTLS') {\n throw new TypeError(\n 'mutualTLS credentials must be true when the custom fetch owns the client certificate',\n );\n }\n if (scheme.type === 'http' && scheme.scheme.toLowerCase() === 'basic') {\n if (\n typeof credential !== 'object' ||\n !('username' in credential) ||\n !('password' in credential)\n ) {\n throw new TypeError('Basic credentials require username and password');\n }\n const bytes = new TextEncoder().encode(\n `${credential.username}:${credential.password}`,\n );\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n if (!config.init.headers.has('Authorization')) {\n config.init.headers.set('Authorization', `Basic ${btoa(binary)}`);\n }\n return;\n }\n if (typeof credential !== 'string') {\n throw new TypeError(`${scheme.type} credentials must be strings`);\n }\n const prefix =\n scheme.type === 'http' ? authorizationScheme(scheme.scheme) : 'Bearer';\n if (!config.init.headers.has('Authorization')) {\n config.init.headers.set('Authorization', `${prefix} ${credential}`);\n }\n}\n\n// OpenAPI carries the lowercase registry name, while servers routinely match the\n// Authorization prefix case-sensitively (`header.startsWith('Bearer ')`).\nconst authorizationSchemes: Record<string, string> = {\n basic: 'Basic',\n bearer: 'Bearer',\n digest: 'Digest',\n hoba: 'HOBA',\n mutual: 'Mutual',\n negotiate: 'Negotiate',\n oauth: 'OAuth',\n 'scram-sha-1': 'SCRAM-SHA-1',\n 'scram-sha-256': 'SCRAM-SHA-256',\n};\n\nfunction authorizationScheme(scheme: string) {\n return authorizationSchemes[scheme.toLowerCase()] ?? scheme;\n}\n\n\n\ninterface DispatchOptions {\n interceptors: Interceptor[];\n fetch: z.infer<typeof fetchType>;\n baseUrl: string;\n signal?: AbortSignal;\n}\n\n/** One operation of a generated SDK's endpoint table. */\ninterface Route {\n schema: z.ZodType;\n output: OutputType[];\n security: readonly Record<string, readonly string[]>[];\n toRequest(input: unknown, baseUrl: string): RequestConfig;\n dispatch(input: unknown, options: DispatchOptions): Promise<unknown>;\n /** Present when the operation pages; `request()` then resolves to a Page. */\n pagination?: Pagination;\n}\n\n/** What a generated SDK knows about its API: its endpoint table, servers and security. */\ninterface Api {\n routes: Record<string, Route>;\n /** The spec's server URLs with their variables' defaults. */\n servers: readonly string[];\n securitySchemes: RuntimeSecuritySchemes;\n /** Validates `credentials`: one optional entry per security scheme. */\n credentials: z.ZodType<Record<string, SecurityCredential | undefined>>;\n}\n\ntype BaseUrl = string | (() => string | Promise<string>);\n\n/** A spec with two or more servers has no single default, so the caller picks one. */\ntype BaseUrlSetting<A extends Api> = A['servers'] extends readonly [\n unknown,\n unknown,\n ...unknown[],\n]\n ? { baseUrl: BaseUrl }\n : { baseUrl?: BaseUrl };\n\ntype CredentialsSetting<A extends Api> =\n keyof A['securitySchemes'] extends never\n ? unknown\n : { credentials?: z.input<A['credentials']> };\n\ntype ClientSettings<A extends Api> = BaseUrlSetting<A> &\n CredentialsSetting<A> & {\n headers?: Record<string, string>;\n fetch?: (request: Request) => Promise<Response>;\n /** Skip request input validation. Settings and TypeScript types still enforce correct usage. */\n skipValidation?: boolean;\n };\n\ninterface RequestOptions {\n signal?: AbortSignal;\n headers?: HeadersInit;\n}\n\ntype DispatchReturn<A extends Api, E extends keyof A['routes']> = Awaited<\n ReturnType<A['routes'][E]['dispatch']>\n>;\n\ntype InferData<A extends Api, E extends keyof A['routes']> =\n DispatchReturn<A, E> extends APIResponse<infer D> ? D : DispatchReturn<A, E>;\n\n/**\n * What `request()` resolves to: the first Page for an operation that pages,\n * its output otherwise. Distributive over `E`, so for a generic `E` TypeScript\n * reads it through `E`'s constraint.\n */\ntype RouteResult<A extends Api, E extends keyof A['routes']> = E extends unknown\n ? A['routes'][E] extends { pagination: { items: infer P extends string } }\n ? Page<InferData<A, E>, ItemOf<InferData<A, E>, P>>\n : InferData<A, E>\n : never;\n\n/**\n * What `client.request(endpoint)` returns: a promise of the result that, for\n * an operation that pages, is also an async iterable of every item. An\n * interface, not an intersection, so TypeScript awaits it for a generic\n * endpoint too.\n */\ninterface RequestPromise<Result> extends Promise<Result> {\n [Symbol.asyncIterator]: Result extends AsyncIterable<infer Item>\n ? () => AsyncIterator<Item>\n : undefined;\n}\n\ntype EndpointsOf<A extends Api> = {\n [E in keyof A['routes']]: {\n input: z.input<A['routes'][E]['schema']>;\n output: InferData<A, E>;\n /** What `request()` resolves to: the first Page for an operation that pages, its output otherwise. */\n result: RouteResult<A, E>;\n error:\n | Extract<Unionize<A['routes'][E]['output']>, ProblematicResponse>\n | ParseError<A['routes'][E]['schema']>;\n };\n};\n\nconst baseUrlSchema = z\n .union([\n z.string(),\n z.custom<() => string | Promise<string>>(\n (value) => typeof value === 'function',\n ),\n ])\n .transform(async (baseUrl, ctx) => {\n const value = typeof baseUrl === 'function' ? await baseUrl() : baseUrl;\n if (typeof value !== 'string') {\n ctx.addIssue({\n code: 'custom',\n message: 'baseUrl must resolve to a string',\n });\n return z.NEVER;\n }\n if (/^[a-z][a-z\\d+.-]*:/i.test(value)) {\n return value;\n }\n const page: { href: string } | undefined = Reflect.get(\n globalThis,\n 'location',\n );\n if (page === undefined) {\n throw new TypeError(\n `baseUrl \"${value}\" is relative, and there is no page location to resolve it against.`,\n );\n }\n return new URL(value, page.href).href;\n });\n\nfunction settingsSchema(api: Api) {\n const [server, ...others] = api.servers;\n return z.object({\n // OpenAPI 3.2: a spec without servers is served from \"/\".\n baseUrl:\n others.length > 0 ? baseUrlSchema : baseUrlSchema.prefault(server ?? '/'),\n headers: z.record(z.string(), z.string()).optional(),\n fetch: fetchType,\n skipValidation: z.boolean().optional(),\n credentials: api.credentials.optional(),\n });\n}\n\nclass Client<A extends Api> {\n readonly api: A;\n options: ClientSettings<A>;\n readonly #settings: ReturnType<typeof settingsSchema>;\n\n constructor(api: A, options: ClientSettings<A>) {\n this.api = api;\n this.options = options;\n this.#settings = settingsSchema(api);\n }\n\n /** The settings, validated, with baseUrl resolved. */\n async settings() {\n return this.#settings.parseAsync(this.options);\n }\n\n /**\n * Sends a request and returns the unwrapped response data, or, for an\n * operation that pages, its first Page.\n */\n request<const E extends keyof A['routes'] & string>(\n endpoint: E,\n input: z.input<A['routes'][E]['schema']>,\n options?: RequestOptions,\n ): RequestPromise<EndpointsOf<A>[E]['result']>;\n request(\n endpoint: string,\n input: unknown,\n options?: RequestOptions,\n ): Promise<unknown> {\n const pagination = this.api.routes[endpoint]?.pagination;\n if (pagination) {\n return new PagePromise(\n firstPage(this, endpoint, input, pagination, options),\n );\n }\n return send(this, endpoint, input, options).then((result) =>\n result instanceof APIResponse ? result.data : result,\n );\n }\n\n /** Builds a ready-to-send request without sending it. */\n async prepare<const E extends keyof A['routes'] & string>(\n endpoint: E,\n input: z.input<A['routes'][E]['schema']>,\n options?: RequestOptions,\n ) {\n return prepare(this, endpoint, input, options);\n }\n\n async defaultHeaders() {\n const settings = await this.settings();\n return { ...settings.headers };\n }\n\n setOptions(options: Partial<ClientSettings<A>>) {\n this.options = { ...this.options, ...options };\n }\n}\n\nfunction createClient<A extends Api>(\n api: A,\n settings: ClientSettings<A>,\n): Client<A> {\n return new Client(api, settings);\n}\n\nasync function firstPage(\n client: Client<Api>,\n endpoint: string,\n input: unknown,\n pagination: Pagination,\n options: RequestOptions | undefined,\n) {\n if (typeof input !== 'object' || input === null) {\n throw new TypeError(\n `${endpoint} pages through its input, so the input must be an object`,\n );\n }\n const fetchPage = async (\n pageInput: Record<string, unknown>,\n pageOptions: PageRequestOptions | undefined,\n ) => {\n const result = await send(client, endpoint, pageInput, {\n ...options,\n ...pageOptions,\n });\n if (\n !(result instanceof APIResponse) ||\n result.status !== pagination.statusCode\n ) {\n throw result;\n }\n const data: unknown = result.data;\n if (typeof data !== 'object' || data === null) {\n throw new TypeError(`${endpoint} answered a page that is not an object`);\n }\n return createPage(data, pageInput, pagination, fetchPage);\n };\n return fetchPage(Object.fromEntries(Object.entries(input)), undefined);\n}\n\nfunction interceptorsFor(\n route: Route,\n settings: Awaited<ReturnType<Client<Api>['settings']>>,\n api: Api,\n options: RequestOptions | undefined,\n) {\n return [\n createHeadersInterceptor({ ...settings.headers }, options?.headers ?? {}),\n createSecurityInterceptor(\n route.security,\n settings.credentials,\n api.securitySchemes,\n ),\n ];\n}\n\n/**\n * Sends a validated request with the client's settings and returns the\n * response status class (status, headers, data). Throws `APIError` on\n * non-ok responses.\n */\nasync function request<\n A extends Api,\n const E extends keyof A['routes'] & string,\n>(\n client: Client<A>,\n endpoint: E,\n input: z.input<A['routes'][E]['schema']>,\n options?: RequestOptions,\n): Promise<DispatchReturn<A, E>>;\nasync function request(\n client: Client<Api>,\n endpoint: string,\n input: unknown,\n options?: RequestOptions,\n): Promise<unknown> {\n return send(client, endpoint, input, options);\n}\n\nfunction routeOf(api: Api, endpoint: string) {\n const route = api.routes[endpoint];\n if (route === undefined) {\n throw new Error(`The api has no endpoint '${endpoint}'`);\n }\n return route;\n}\n\nasync function send(\n client: Client<Api>,\n endpoint: string,\n input: unknown,\n options: RequestOptions | undefined,\n) {\n const route = routeOf(client.api, endpoint);\n const settings = await client.settings();\n const parsedInput = settings.skipValidation\n ? input\n : parseInput(route.schema, input);\n return route.dispatch(parsedInput, {\n fetch: settings.fetch,\n baseUrl: settings.baseUrl,\n interceptors: interceptorsFor(route, settings, client.api, options),\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n}\n\n/**\n * Builds a validated `RequestConfig` (url + init) with a `parse` function\n * attached, without sending it.\n */\nasync function prepare<\n A extends Api,\n const E extends keyof A['routes'] & string,\n>(\n client: Client<A>,\n endpoint: E,\n input: z.input<A['routes'][E]['schema']>,\n options?: RequestOptions,\n): Promise<\n RequestConfig & {\n parse: (response: Response) => Promise<DispatchReturn<A, E>>;\n }\n>;\nasync function prepare(\n client: Client<Api>,\n endpoint: string,\n input: unknown,\n options?: RequestOptions,\n): Promise<\n RequestConfig & { parse: (response: Response) => Promise<unknown> }\n> {\n const route = routeOf(client.api, endpoint);\n const settings = await client.settings();\n const parsedInput = settings.skipValidation\n ? input\n : parseInput(route.schema, input);\n let config = route.toRequest(parsedInput, settings.baseUrl);\n if (options?.signal) {\n config = { ...config, init: { ...config.init, signal: options.signal } };\n }\n for (const interceptor of interceptorsFor(\n route,\n settings,\n client.api,\n options,\n )) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n return {\n ...config,\n parse: (response: Response) => parse(route.output, response),\n };\n}\n", "bindings": [{ "kind": "declared", "name": "Init", "file": "http/request.ts", "exported": false, "type": true, "occurrences": [5, 94], "shorthands": [] }, { "kind": "declared", "name": "RequestConfig", "file": "http/request.ts", "exported": true, "type": true, "occurrences": [70, 5383, 5678, 5704, 5721, 27744, 27919, 28190, 38498, 42224, 51389, 51607], "shorthands": [] }, { "kind": "declared", "name": "Method", "file": "http/request.ts", "exported": true, "type": true, "occurrences": [200, 5311], "shorthands": [] }, { "kind": "declared", "name": "HeadersInit", "file": "http/request.ts", "exported": true, "type": true, "occurrences": [280, 5903, 43683], "shorthands": [] }, { "kind": "declared", "name": "BodyInit", "file": "http/request.ts", "exported": true, "type": true, "occurrences": [345, 1922, 2827, 2949, 3501, 3947, 4108, 4559], "shorthands": [] }, { "kind": "declared", "name": "template", "file": "http/request.ts", "exported": false, "type": false, "occurrences": [433, 2257], "shorthands": [] }, { "kind": "declared", "name": "Input", "file": "http/request.ts", "exported": false, "type": true, "occurrences": [1010, 1769, 1824, 4745, 4840, 4936, 5030, 5123, 5213], "shorthands": [] }, { "kind": "declared", "name": "toWireValue", "file": "http/request.ts", "exported": false, "type": false, "occurrences": [1197, 2506, 2680, 3688], "shorthands": [] }, { "kind": "declared", "name": "wireItems", "file": "http/request.ts", "exported": false, "type": false, "occurrences": [1406, 2613, 3631, 4231], "shorthands": [] }, { "kind": "declared", "name": "Props", "file": "http/request.ts", "exported": false, "type": true, "occurrences": [1542, 1795, 1838, 4759, 4854, 4950, 5044, 5137, 5227], "shorthands": [] }, { "kind": "declared", "name": "Serializer", "file": "http/request.ts", "exported": false, "type": false, "occurrences": [1737, 2923, 3475, 3921, 4082, 4533, 5349], "shorthands": [] }, { "kind": "declared", "name": "Serialized", "file": "http/request.ts", "exported": false, "type": true, "occurrences": [2032, 2806], "shorthands": [] }, { "kind": "declared", "name": "JsonSerializer", "file": "http/request.ts", "exported": false, "type": false, "occurrences": [2900, 4781], "shorthands": [] }, { "kind": "declared", "name": "UrlencodedSerializer", "file": "http/request.ts", "exported": false, "type": false, "occurrences": [3446, 4876], "shorthands": [] }, { "kind": "declared", "name": "EmptySerializer", "file": "http/request.ts", "exported": false, "type": false, "occurrences": [3897, 4972], "shorthands": [] }, { "kind": "declared", "name": "FormDataSerializer", "file": "http/request.ts", "exported": false, "type": false, "occurrences": [4055, 5066], "shorthands": [] }, { "kind": "declared", "name": "RawSerializer", "file": "http/request.ts", "exported": false, "type": false, "occurrences": [4511, 5159, 5249], "shorthands": [] }, { "kind": "declared", "name": "json", "file": "http/request.ts", "exported": true, "type": false, "occurrences": [4733], "shorthands": [] }, { "kind": "declared", "name": "urlencoded", "file": "http/request.ts", "exported": true, "type": false, "occurrences": [4822], "shorthands": [] }, { "kind": "declared", "name": "empty", "file": "http/request.ts", "exported": true, "type": false, "occurrences": [4923], "shorthands": [] }, { "kind": "declared", "name": "formdata", "file": "http/request.ts", "exported": true, "type": false, "occurrences": [5014], "shorthands": [] }, { "kind": "declared", "name": "text", "file": "http/request.ts", "exported": true, "type": false, "occurrences": [5111], "shorthands": [] }, { "kind": "declared", "name": "binary", "file": "http/request.ts", "exported": true, "type": false, "occurrences": [5199], "shorthands": [] }, { "kind": "declared", "name": "toRequest", "file": "http/request.ts", "exported": true, "type": false, "occurrences": [5290], "shorthands": [] }, { "kind": "declared", "name": "Interceptor", "file": "http/interceptors.ts", "exported": true, "type": true, "occurrences": [5644, 5919, 27488, 27573, 36964, 41902], "shorthands": [] }, { "kind": "declared", "name": "createHeadersInterceptor", "file": "http/interceptors.ts", "exported": true, "type": false, "occurrences": [5809, 49521], "shorthands": [] }, { "kind": "declared", "name": "isBinaryContentType", "file": "http/parse-response.ts", "exported": false, "type": false, "occurrences": [6790, 9311], "shorthands": [] }, { "kind": "declared", "name": "chunked", "file": "http/parse-response.ts", "exported": true, "type": false, "occurrences": [7679], "shorthands": [] }, { "kind": "declared", "name": "bodyless", "file": "http/parse-response.ts", "exported": true, "type": false, "occurrences": [7872], "shorthands": [] }, { "kind": "declared", "name": "BufferedBody", "file": "http/parse-response.ts", "exported": true, "type": true, "occurrences": [8045, 8344], "shorthands": [] }, { "kind": "declared", "name": "buffered", "file": "http/parse-response.ts", "exported": true, "type": false, "occurrences": [8324, 25437], "shorthands": [] }, { "kind": "declared", "name": "byContentType", "file": "http/parse-response.ts", "exported": false, "type": false, "occurrences": [8778, 9209], "shorthands": [] }, { "kind": "external", "name": "parse", "module": "fast-content-type-parse", "occurrences": [9285], "shorthands": [] }, { "kind": "declared", "name": "StatusRange", "file": "http/response.ts", "exported": true, "type": true, "occurrences": [9993, 10301, 24983], "shorthands": [] }, { "kind": "declared", "name": "Digit", "file": "http/response.ts", "exported": false, "type": true, "occurrences": [10051, 10361, 10369], "shorthands": [] }, { "kind": "declared", "name": "ToNumber", "file": "http/response.ts", "exported": false, "type": true, "occurrences": [10123, 10345], "shorthands": [] }, { "kind": "declared", "name": "RangeStatus", "file": "http/response.ts", "exported": true, "type": true, "occurrences": [10279, 19977, 20185, 20375], "shorthands": [] }, { "kind": "declared", "name": "APIResponse", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [10395, 12124, 12421, 12714, 13006, 20360, 20719, 24915, 24961, 25923, 26294, 26318, 27166, 27278, 43911, 47659, 48932], "shorthands": [] }, { "kind": "declared", "name": "APIError", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [10829, 13312, 13631, 13955, 14276, 14590, 14911, 15243, 15561, 15870, 16189, 16569, 16926, 17253, 17585, 17949, 18285, 18606, 18957, 19286, 19959, 20167, 26451, 26472, 27197], "shorthands": [] }, { "kind": "declared", "name": "failureMessage", "file": "http/response.ts", "exported": false, "type": false, "occurrences": [11069, 11333], "shorthands": [] }, { "kind": "declared", "name": "bodySummary", "file": "http/response.ts", "exported": false, "type": false, "occurrences": [11399, 11719], "shorthands": [] }, { "kind": "declared", "name": "Ok", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [12110, 12249, 20305, 20451, 20469], "shorthands": [] }, { "kind": "declared", "name": "Created", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [12402, 12537, 20315, 20496, 20521], "shorthands": [] }, { "kind": "declared", "name": "Accepted", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [12694, 12830, 20330, 20555, 20583], "shorthands": [] }, { "kind": "declared", "name": "NoContent", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [12988, 13116, 13214, 20346, 20620, 20642], "shorthands": [] }, { "kind": "declared", "name": "BadRequest", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [13290, 13425, 19581], "shorthands": [] }, { "kind": "declared", "name": "Unauthorized", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [13585, 13744, 19605], "shorthands": [] }, { "kind": "declared", "name": "PaymentRequired", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [13906, 14068, 19631], "shorthands": [] }, { "kind": "declared", "name": "Forbidden", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [14233, 14389, 19660], "shorthands": [] }, { "kind": "declared", "name": "NotFound", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [14548, 14703, 19683], "shorthands": [] }, { "kind": "declared", "name": "MethodNotAllowed", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [14861, 15030, 19705], "shorthands": [] }, { "kind": "declared", "name": "NotAcceptable", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [15196, 15356, 19735], "shorthands": [] }, { "kind": "declared", "name": "Conflict", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [15519, 15674, 19762], "shorthands": [] }, { "kind": "declared", "name": "Gone", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [15832, 15983, 19784], "shorthands": [] }, { "kind": "declared", "name": "PreconditionFailed", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [16137, 16308, 19802], "shorthands": [] }, { "kind": "declared", "name": "UnprocessableEntity", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [16476, 16682, 19897], "shorthands": [] }, { "kind": "declared", "name": "TooManyRequests", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [16851, 17039, 19930], "shorthands": [] }, { "kind": "declared", "name": "PayloadTooLarge", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [17204, 17366, 19834], "shorthands": [] }, { "kind": "declared", "name": "UnsupportedMediaType", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [17531, 17704, 19863], "shorthands": [] }, { "kind": "declared", "name": "InternalServerError", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [17896, 18068, 20022], "shorthands": [] }, { "kind": "declared", "name": "NotImplemented", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [18237, 18398, 20055], "shorthands": [] }, { "kind": "declared", "name": "BadGateway", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [18562, 18719, 20083], "shorthands": [] }, { "kind": "declared", "name": "ServiceUnavailable", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [18879, 19070, 20107], "shorthands": [] }, { "kind": "declared", "name": "GatewayTimeout", "file": "http/response.ts", "exported": true, "type": false, "occurrences": [19238, 19399, 20139], "shorthands": [] }, { "kind": "declared", "name": "ClientError", "file": "http/response.ts", "exported": true, "type": true, "occurrences": [19563, 20234], "shorthands": [] }, { "kind": "declared", "name": "ServerError", "file": "http/response.ts", "exported": true, "type": true, "occurrences": [20004, 20248], "shorthands": [] }, { "kind": "declared", "name": "ProblematicResponse", "file": "http/response.ts", "exported": true, "type": true, "occurrences": [20212, 45180], "shorthands": [] }, { "kind": "declared", "name": "SuccessfulResponse", "file": "http/response.ts", "exported": true, "type": true, "occurrences": [20267, 20677, 24472, 24500, 25564, 25768, 27835, 28081], "shorthands": [] }, { "kind": "declared", "name": "RebindSuccessPayload", "file": "http/response.ts", "exported": true, "type": true, "occurrences": [20402, 25726, 28039], "shorthands": [] }, { "kind": "declared", "name": "SSEListener", "file": "http/sse.ts", "exported": true, "type": true, "occurrences": [20779, 20874, 24773], "shorthands": [] }, { "kind": "declared", "name": "sse", "file": "http/sse.ts", "exported": true, "type": false, "occurrences": [20849], "shorthands": [] }, { "kind": "declared", "name": "Unionize", "file": "http/dispatcher.ts", "exported": true, "type": true, "occurrences": [24002, 24371, 25551, 25755, 27822, 28068, 45144], "shorthands": [] }, { "kind": "declared", "name": "InstanceType", "file": "http/dispatcher.ts", "exported": true, "type": true, "occurrences": [24064, 24174, 24226, 24455], "shorthands": [] }, { "kind": "declared", "name": "ResponseData", "file": "http/dispatcher.ts", "exported": false, "type": true, "occurrences": [24406, 24616, 28160], "shorthands": [] }, { "kind": "declared", "name": "ResponseMapper", "file": "http/dispatcher.ts", "exported": false, "type": true, "occurrences": [24565, 25690, 27999, 28260], "shorthands": [] }, { "kind": "declared", "name": "Type", "file": "http/dispatcher.ts", "exported": true, "type": true, "occurrences": [24256, 24302, 24650, 24910, 24956, 27273], "shorthands": [] }, { "kind": "declared", "name": "Parser", "file": "http/dispatcher.ts", "exported": true, "type": true, "occurrences": [24694, 24942, 25428], "shorthands": [] }, { "kind": "declared", "name": "OutputType", "file": "http/dispatcher.ts", "exported": true, "type": true, "occurrences": [24048, 24132, 24429, 24590, 24893, 25481, 25626, 25837, 26710, 27002, 27097, 27717, 27889, 28142, 42106], "shorthands": [] }, { "kind": "declared", "name": "fetchType", "file": "http/dispatcher.ts", "exported": true, "type": false, "occurrences": [25212, 27533, 27611, 41941, 46417], "shorthands": [] }, { "kind": "declared", "name": "undeclared", "file": "http/dispatcher.ts", "exported": false, "type": false, "occurrences": [25416, 26117], "shorthands": [] }, { "kind": "declared", "name": "parse", "file": "http/dispatcher.ts", "exported": true, "type": false, "occurrences": [25465, 25610, 25819, 28818, 28875, 52293], "shorthands": [] }, { "kind": "declared", "name": "match", "file": "http/dispatcher.ts", "exported": false, "type": false, "occurrences": [25957, 26695], "shorthands": [] }, { "kind": "declared", "name": "typeOf", "file": "http/dispatcher.ts", "exported": false, "type": false, "occurrences": [26018, 26987, 27126], "shorthands": [] }, { "kind": "declared", "name": "statusOf", "file": "http/dispatcher.ts", "exported": false, "type": false, "occurrences": [26862, 27080], "shorthands": [] }, { "kind": "declared", "name": "isTypeOf", "file": "http/dispatcher.ts", "exported": true, "type": false, "occurrences": [26277, 26434, 27151, 27182, 27254], "shorthands": [] }, { "kind": "declared", "name": "Dispatcher", "file": "http/dispatcher.ts", "exported": true, "type": false, "occurrences": [27458], "shorthands": [] }, { "kind": "external", "name": "z", "module": "zod", "occurrences": [25224, 25252, 25286, 27518, 27596, 34675, 34717, 34743, 34756, 34795, 34821, 34834, 34976, 35022, 35120, 35764, 35885, 35897, 35911, 36002, 36025, 36049, 36095, 36137, 36259, 36271, 41926, 42085, 42787, 43277, 44915, 45278, 45295, 45311, 45685, 46180, 46361, 46370, 46382, 46448, 47156, 47856, 50026, 51312], "shorthands": [] }, { "kind": "declared", "name": "Pagination", "file": "http/page.ts", "exported": true, "type": true, "occurrences": [29025, 31700, 31862, 34005, 42406, 48441], "shorthands": [] }, { "kind": "declared", "name": "PathValue", "file": "http/page.ts", "exported": false, "type": true, "occurrences": [29759, 29870, 30094], "shorthands": [] }, { "kind": "declared", "name": "ItemOf", "file": "http/page.ts", "exported": true, "type": true, "occurrences": [30047, 44350], "shorthands": [] }, { "kind": "declared", "name": "PageRequestOptions", "file": "http/page.ts", "exported": true, "type": true, "occurrences": [30253, 30622, 30778, 31014, 32324, 32436, 48747], "shorthands": [] }, { "kind": "declared", "name": "PageControls", "file": "http/page.ts", "exported": true, "type": true, "occurrences": [30472, 30571, 30727, 30929], "shorthands": [] }, { "kind": "declared", "name": "Page", "file": "http/page.ts", "exported": true, "type": true, "occurrences": [30903, 44328], "shorthands": [] }, { "kind": "declared", "name": "FetchPage", "file": "http/page.ts", "exported": false, "type": true, "occurrences": [30955, 31735, 31889, 34030], "shorthands": [] }, { "kind": "declared", "name": "at", "file": "http/page.ts", "exported": false, "type": false, "occurrences": [31084, 32048, 32252, 33534], "shorthands": [] }, { "kind": "declared", "name": "position", "file": "http/page.ts", "exported": false, "type": false, "occurrences": [31470, 32964, 33250], "shorthands": [] }, { "kind": "declared", "name": "ResponsePage", "file": "http/page.ts", "exported": false, "type": false, "occurrences": [31059, 31617, 34044, 34072], "shorthands": [] }, { "kind": "declared", "name": "createPage", "file": "http/page.ts", "exported": true, "type": false, "occurrences": [33929, 49217], "shorthands": [] }, { "kind": "declared", "name": "PagePromise", "file": "http/page.ts", "exported": true, "type": false, "occurrences": [34293, 47479], "shorthands": [] }, { "kind": "declared", "name": "ParseError", "file": "http/parser.ts", "exported": true, "type": false, "occurrences": [34654, 35182, 45209], "shorthands": [] }, { "kind": "declared", "name": "parseInput", "file": "http/parser.ts", "exported": true, "type": false, "occurrences": [34955, 50789, 51834], "shorthands": [] }, { "kind": "declared", "name": "SecurityContext", "file": "http/security.ts", "exported": true, "type": true, "occurrences": [35240, 35532], "shorthands": [] }, { "kind": "declared", "name": "SecurityCredentialValue", "file": "http/security.ts", "exported": true, "type": true, "occurrences": [35343, 35492, 35607, 35633, 35732, 38560], "shorthands": [] }, { "kind": "declared", "name": "SecurityCredentialProvider", "file": "http/security.ts", "exported": true, "type": true, "occurrences": [35455, 35666, 35773], "shorthands": [] }, { "kind": "declared", "name": "SecurityCredential", "file": "http/security.ts", "exported": true, "type": true, "occurrences": [35575, 36881, 42812], "shorthands": [] }, { "kind": "declared", "name": "providerSchema", "file": "http/security.ts", "exported": false, "type": false, "occurrences": [35704, 35930, 36156, 36290], "shorthands": [] }, { "kind": "declared", "name": "stringCredentialSchema", "file": "http/security.ts", "exported": true, "type": false, "occurrences": [35860], "shorthands": [] }, { "kind": "declared", "name": "basicCredentialValueSchema", "file": "http/security.ts", "exported": false, "type": false, "occurrences": [35973, 36107], "shorthands": [] }, { "kind": "declared", "name": "basicCredentialSchema", "file": "http/security.ts", "exported": true, "type": false, "occurrences": [36071], "shorthands": [] }, { "kind": "declared", "name": "mutualTlsCredentialSchema", "file": "http/security.ts", "exported": true, "type": false, "occurrences": [36231], "shorthands": [] }, { "kind": "declared", "name": "RuntimeSecurityScheme", "file": "http/security.ts", "exported": true, "type": true, "occurrences": [36324, 36714, 38523], "shorthands": [] }, { "kind": "declared", "name": "RuntimeSecuritySchemes", "file": "http/security.ts", "exported": true, "type": true, "occurrences": [36660, 36937, 42674], "shorthands": [] }, { "kind": "declared", "name": "createSecurityInterceptor", "file": "http/security.ts", "exported": true, "type": false, "occurrences": [36762, 49600], "shorthands": [] }, { "kind": "declared", "name": "applyCredential", "file": "http/security.ts", "exported": false, "type": false, "occurrences": [38373, 38471], "shorthands": [] }, { "kind": "declared", "name": "authorizationSchemes", "file": "http/security.ts", "exported": false, "type": false, "occurrences": [41484, 41799], "shorthands": [] }, { "kind": "declared", "name": "authorizationScheme", "file": "http/security.ts", "exported": false, "type": false, "occurrences": [41143, 41752], "shorthands": [] }, { "kind": "declared", "name": "DispatchOptions", "file": "http/client.ts", "exported": true, "type": true, "occurrences": [41868, 42275], "shorthands": [] }, { "kind": "declared", "name": "Route", "file": "http/client.ts", "exported": true, "type": true, "occurrences": [42067, 42553, 49386], "shorthands": [] }, { "kind": "declared", "name": "Api", "file": "http/client.ts", "exported": true, "type": true, "occurrences": [42522, 43025, 43191, 43337, 43729, 43844, 44191, 44865, 46121, 46549, 48239, 48383, 49431, 49458, 49927, 50164, 50332, 50547, 51213, 51521], "shorthands": [] }, { "kind": "declared", "name": "BaseUrl", "file": "http/client.ts", "exported": false, "type": true, "occurrences": [42854, 43119, 43145], "shorthands": [] }, { "kind": "declared", "name": "BaseUrlSetting", "file": "http/client.ts", "exported": false, "type": true, "occurrences": [43e3, 43344], "shorthands": [] }, { "kind": "declared", "name": "CredentialsSetting", "file": "http/client.ts", "exported": false, "type": true, "occurrences": [43162, 43366], "shorthands": [] }, { "kind": "declared", "name": "ClientSettings", "file": "http/client.ts", "exported": true, "type": true, "occurrences": [43312, 46586, 46694, 48126, 48267], "shorthands": [] }, { "kind": "declared", "name": "RequestOptions", "file": "http/client.ts", "exported": true, "type": true, "occurrences": [43630, 47205, 47338, 47905, 48464, 49474, 50073, 50220, 50602, 51359, 51577], "shorthands": [] }, { "kind": "declared", "name": "DispatchReturn", "file": "http/client.ts", "exported": false, "type": true, "occurrences": [43704, 43882, 43938, 50100, 51450], "shorthands": [] }, { "kind": "declared", "name": "InferData", "file": "http/client.ts", "exported": true, "type": true, "occurrences": [43824, 44333, 44357, 44384, 44962], "shorthands": [] }, { "kind": "declared", "name": "RouteResult", "file": "http/client.ts", "exported": false, "type": true, "occurrences": [44169, 45098], "shorthands": [] }, { "kind": "declared", "name": "RequestPromise", "file": "http/client.ts", "exported": true, "type": true, "occurrences": [44670, 47226], "shorthands": [] }, { "kind": "declared", "name": "EndpointsOf", "file": "http/client.ts", "exported": true, "type": true, "occurrences": [44843, 47241], "shorthands": [] }, { "kind": "declared", "name": "baseUrlSchema", "file": "http/client.ts", "exported": false, "type": false, "occurrences": [45262, 46293, 46309], "shorthands": [] }, { "kind": "declared", "name": "settingsSchema", "file": "http/client.ts", "exported": false, "type": false, "occurrences": [46101, 46645, 46784], "shorthands": [] }, { "kind": "declared", "name": "Client", "file": "http/client.ts", "exported": true, "type": false, "occurrences": [46532, 48289, 48314, 48376, 49424, 49991, 50157, 50540, 51277, 51514], "shorthands": [] }, { "kind": "declared", "name": "createClient", "file": "http/client.ts", "exported": true, "type": false, "occurrences": [48216], "shorthands": [] }, { "kind": "declared", "name": "firstPage", "file": "http/client.ts", "exported": false, "type": false, "occurrences": [47500, 48355], "shorthands": [] }, { "kind": "declared", "name": "interceptorsFor", "file": "http/client.ts", "exported": false, "type": false, "occurrences": [49360, 50937, 52065], "shorthands": [] }, { "kind": "declared", "name": "request", "file": "http/client.ts", "exported": true, "type": false, "occurrences": [49906, 50138], "shorthands": [] }, { "kind": "declared", "name": "routeOf", "file": "http/client.ts", "exported": false, "type": false, "occurrences": [50319, 50650, 51695], "shorthands": [] }, { "kind": "declared", "name": "send", "file": "http/client.ts", "exported": false, "type": false, "occurrences": [47581, 48813, 50267, 50524], "shorthands": [] }, { "kind": "declared", "name": "prepare", "file": "http/client.ts", "exported": true, "type": false, "occurrences": [47938, 51192, 51495], "shorthands": [] }], "globals": [{ "name": "Omit", "occurrences": [12] }, { "name": "RequestInit", "occurrences": [17] }, { "name": "Headers", "occurrences": [54, 5536, 6120, 10552, 10601, 10746, 10987, 11036, 11253, 12219, 12333, 12507, 12626, 12800, 12920, 13095, 13204, 13395, 13517, 13714, 13838, 14038, 14165, 14359, 14480, 14673, 14793, 15e3, 15128, 15326, 15451, 15644, 15764, 15953, 16069, 16278, 16408, 16652, 16783, 17009, 17136, 17336, 17463, 17674, 17806, 18038, 18169, 18368, 18494, 18689, 18811, 19040, 19170, 19369, 19495] }, { "name": "URL", "occurrences": [105, 2240, 2886, 46057] }, { "name": "Record", "occurrences": [315, 490, 1018, 1964, 2094, 2304, 2855, 2983, 3308, 3759, 4002, 4346, 4626, 5849, 16531, 30978, 31651, 31821, 32820, 33966, 36814, 36866, 41506, 42141, 42538, 42797, 43406, 48705] }, { "name": "ArrayBuffer", "occurrences": [358] }, { "name": "Blob", "occurrences": [372, 9127] }, { "name": "FormData", "occurrences": [379, 4147] }, { "name": "URLSearchParams", "occurrences": [390, 3540, 9735] }, { "name": "encodeURIComponent", "occurrences": [960, 39720] }, { "name": "String", "occurrences": [979, 1286, 40142, 40807] }, { "name": "Date", "occurrences": [1257] }, { "name": "Array", "occurrences": [1494, 24346, 32175] }, { "name": "JSON", "occurrences": [3124, 3266, 8981, 11949] }, { "name": "Promise", "occurrences": [5696, 5770, 8397, 23391, 23644, 23860, 24732, 25295, 25535, 25715, 25915, 27806, 28026, 30647, 31051, 34352, 34452, 34486, 35558, 42293, 42889, 43464, 44701, 45335, 47359, 50092, 50239, 51378, 51442, 51596, 51656] }, { "name": "Response", "occurrences": [5757, 5778, 5790, 7697, 7891, 8386, 9233, 20863, 24717, 25303, 25522, 25670, 25863, 43472, 51429, 51643, 52280] }, { "name": "Object", "occurrences": [6513, 9712, 11762, 27388, 31910, 37136, 37243, 37444, 37657, 37778, 49293, 49312] }, { "name": "TextDecoder", "occurrences": [8996, 9064, 21954] }, { "name": "Error", "occurrences": [9860, 10884, 33651, 34694, 37548, 37887, 38649, 39466, 50438] }, { "name": "AsyncIterable", "occurrences": [20816, 23100, 30499, 34315, 34376, 44760] }, { "name": "Map", "occurrences": [21257] }, { "name": "Set", "occurrences": [21306, 21461, 23222] }, { "name": "Symbol", "occurrences": [23324, 32692, 34421, 34590, 44722] }, { "name": "IteratorResult", "occurrences": [23399, 23868] }, { "name": "Extract", "occurrences": [24447, 25543, 25747, 27814, 28060, 45136] }, { "name": "ReadableStream", "occurrences": [24751] }, { "name": "Request", "occurrences": [25261, 28579, 43452] }, { "name": "Math", "occurrences": [26761] }, { "name": "AbortSignal", "occurrences": [27788, 27962, 28234, 30285, 41983, 43658] }, { "name": "fetch", "occurrences": [28568] }, { "name": "NonNullable", "occurrences": [29849, 29880, 29937, 29958, 30082] }, { "name": "AsyncGenerator", "occurrences": [30803] }, { "name": "Reflect", "occurrences": [31269, 45818] }, { "name": "Boolean", "occurrences": [32244] }, { "name": "TypeError", "occurrences": [38997, 40100, 40237, 40572, 41036, 45920, 48563, 49136] }, { "name": "TextEncoder", "occurrences": [40662] }, { "name": "btoa", "occurrences": [40943] }, { "name": "Awaited", "occurrences": [43765, 49405] }, { "name": "ReturnType", "occurrences": [43776, 46627, 49413] }, { "name": "AsyncIterator", "occurrences": [44798] }, { "name": "Partial", "occurrences": [48118] }] };
151
+
152
+ // packages/typescript/src/lib/root-exports.ts
153
+ var rootRuntimeFiles = ["http/response.ts", "http/parser.ts"];
154
+ var runtimeRootExports = runtime_module_default.bindings.filter(
155
+ (binding) => binding.kind === "declared" && binding.exported && rootRuntimeFiles.includes(binding.file)
156
+ );
157
+
158
+ // packages/typescript/src/lib/client-name.ts
159
+ var reservedWords = /* @__PURE__ */ new Set([
160
+ "arguments",
161
+ "await",
162
+ "break",
163
+ "case",
164
+ "catch",
165
+ "class",
166
+ "const",
167
+ "continue",
168
+ "debugger",
169
+ "default",
170
+ "delete",
171
+ "do",
172
+ "else",
173
+ "enum",
174
+ "eval",
175
+ "export",
176
+ "extends",
177
+ "false",
178
+ "finally",
179
+ "for",
180
+ "function",
181
+ "if",
182
+ "implements",
183
+ "import",
184
+ "in",
185
+ "instanceof",
186
+ "interface",
187
+ "let",
188
+ "new",
189
+ "null",
190
+ "package",
191
+ "private",
192
+ "protected",
193
+ "public",
194
+ "return",
195
+ "static",
196
+ "super",
197
+ "switch",
198
+ "this",
199
+ "throw",
200
+ "true",
201
+ "try",
202
+ "typeof",
203
+ "var",
204
+ "void",
205
+ "while",
206
+ "with",
207
+ "yield"
208
+ ]);
209
+ var sdkNames = /* @__PURE__ */ new Set([
210
+ ...runtimeRootExports.map((binding) => binding.name),
211
+ ...securityTypeExports,
212
+ ...clientFileBindings,
213
+ ...clientDeclarationBindings
214
+ ]);
215
+ function clientName(name) {
216
+ const pascal = pascalcase(name.trim());
217
+ if (!/^[\p{ID_Start}_$][\p{ID_Continue}$‌‍]*$/u.test(pascal)) {
218
+ throw new TypeError(
219
+ `The client name "${name}" becomes ${pascal ? `"${pascal}"` : "an empty name"}, which is not a TypeScript identifier. A client name starts with a letter, _ or $, and has only letters, digits, _ and $.`
220
+ );
221
+ }
222
+ const instance = camelcase3(pascal);
223
+ if (reservedWords.has(instance)) {
224
+ throw new TypeError(
225
+ `The client name "${name}" makes the default instance ${instance}, which is a reserved word. Rename the client.`
226
+ );
227
+ }
228
+ refuseTakenNames(name, pascal, sdkNames);
229
+ return pascal;
230
+ }
231
+ function refuseTakenNames(name, pascal, taken) {
232
+ const clash = clientNamedExports(pascal).find((built) => taken.has(built));
233
+ if (clash !== void 0) {
234
+ throw new TypeError(
235
+ `The client name "${name}" makes ${clash}, a name the SDK already declares or exports. Rename the client.`
236
+ );
237
+ }
238
+ }
239
+
1
240
  // packages/typescript/src/lib/generate.ts
2
- import { template as template2 } from "lodash-es";
3
- import { readdir } from "node:fs/promises";
241
+ import { readFile } from "node:fs/promises";
4
242
  import { join as join2 } from "node:path";
5
243
  import { npmRunPathEnv } from "npm-run-path";
6
- import { camelcase as camelcase6, spinalcase as spinalcase4 } from "stringcase";
7
- import { pascalcase as pascalcase5, toLitObject as toLitObject2 } from "@sdk-it/core";
244
+
245
+ // runtime-sources:runtime-sources
246
+ var runtime_sources_default = { "http/client.ts": "import { z } from 'zod';\n\nimport {\n type OutputType,\n type Unionize,\n fetchType,\n parse,\n} from './dispatcher.ts';\nimport { type Interceptor, createHeadersInterceptor } from './interceptors.ts';\nimport {\n type ItemOf,\n type Page,\n PagePromise,\n type PageRequestOptions,\n type Pagination,\n createPage,\n} from './page.ts';\nimport { type ParseError, parseInput } from './parser.ts';\nimport type { HeadersInit, RequestConfig } from './request.ts';\nimport {\n APIResponse,\n type ProblematicResponse,\n type SuccessfulResponse,\n} from './response.ts';\nimport {\n type RuntimeSecuritySchemes,\n type SecurityCredential,\n createSecurityInterceptor,\n} from './security.ts';\n\nexport interface DispatchOptions {\n interceptors: Interceptor[];\n fetch: z.infer<typeof fetchType>;\n baseUrl: string;\n signal?: AbortSignal;\n}\n\n/** One operation of a generated SDK's endpoint table. */\nexport interface Route {\n schema: z.ZodType;\n output: OutputType[];\n security: readonly Record<string, readonly string[]>[];\n toRequest(input: unknown, baseUrl: string): RequestConfig;\n dispatch(input: unknown, options: DispatchOptions): Promise<unknown>;\n /** Present when the operation pages; `request()` then resolves to a Page. */\n pagination?: Pagination;\n}\n\n/** What a generated SDK knows about its API: its endpoint table, servers and security. */\nexport interface Api {\n routes: Record<string, Route>;\n /** The spec's server URLs with their variables' defaults. */\n servers: readonly string[];\n securitySchemes: RuntimeSecuritySchemes;\n /** Validates `credentials`: one optional entry per security scheme. */\n credentials: z.ZodType<Record<string, SecurityCredential | undefined>>;\n}\n\ntype BaseUrl = string | (() => string | Promise<string>);\n\n/** A spec with two or more servers has no single default, so the caller picks one. */\ntype BaseUrlSetting<A extends Api> = A['servers'] extends readonly [\n unknown,\n unknown,\n ...unknown[],\n]\n ? { baseUrl: BaseUrl }\n : { baseUrl?: BaseUrl };\n\ntype CredentialsSetting<A extends Api> =\n keyof A['securitySchemes'] extends never\n ? unknown\n : { credentials?: z.input<A['credentials']> };\n\nexport type ClientSettings<A extends Api> = BaseUrlSetting<A> &\n CredentialsSetting<A> & {\n headers?: Record<string, string>;\n fetch?: (request: Request) => Promise<Response>;\n /** Skip request input validation. Settings and TypeScript types still enforce correct usage. */\n skipValidation?: boolean;\n };\n\nexport interface RequestOptions {\n signal?: AbortSignal;\n headers?: HeadersInit;\n}\n\ntype DispatchReturn<A extends Api, E extends keyof A['routes']> = Awaited<\n ReturnType<A['routes'][E]['dispatch']>\n>;\n\nexport type InferData<A extends Api, E extends keyof A['routes']> =\n DispatchReturn<A, E> extends APIResponse<infer D> ? D : DispatchReturn<A, E>;\n\n/**\n * What `request()` resolves to: the first Page for an operation that pages,\n * its output otherwise. Distributive over `E`, so for a generic `E` TypeScript\n * reads it through `E`'s constraint.\n */\ntype RouteResult<A extends Api, E extends keyof A['routes']> = E extends unknown\n ? A['routes'][E] extends { pagination: { items: infer P extends string } }\n ? Page<InferData<A, E>, ItemOf<InferData<A, E>, P>>\n : InferData<A, E>\n : never;\n\n/**\n * What `client.request(endpoint)` returns: a promise of the result that, for\n * an operation that pages, is also an async iterable of every item. An\n * interface, not an intersection, so TypeScript awaits it for a generic\n * endpoint too.\n */\nexport interface RequestPromise<Result> extends Promise<Result> {\n [Symbol.asyncIterator]: Result extends AsyncIterable<infer Item>\n ? () => AsyncIterator<Item>\n : undefined;\n}\n\nexport type EndpointsOf<A extends Api> = {\n [E in keyof A['routes']]: {\n input: z.input<A['routes'][E]['schema']>;\n output: InferData<A, E>;\n /** What `request()` resolves to: the first Page for an operation that pages, its output otherwise. */\n result: RouteResult<A, E>;\n error:\n | Extract<Unionize<A['routes'][E]['output']>, ProblematicResponse>\n | ParseError<A['routes'][E]['schema']>;\n };\n};\n\nconst baseUrlSchema = z\n .union([\n z.string(),\n z.custom<() => string | Promise<string>>(\n (value) => typeof value === 'function',\n ),\n ])\n .transform(async (baseUrl, ctx) => {\n const value = typeof baseUrl === 'function' ? await baseUrl() : baseUrl;\n if (typeof value !== 'string') {\n ctx.addIssue({\n code: 'custom',\n message: 'baseUrl must resolve to a string',\n });\n return z.NEVER;\n }\n if (/^[a-z][a-z\\d+.-]*:/i.test(value)) {\n return value;\n }\n const page: { href: string } | undefined = Reflect.get(\n globalThis,\n 'location',\n );\n if (page === undefined) {\n throw new TypeError(\n `baseUrl \"${value}\" is relative, and there is no page location to resolve it against.`,\n );\n }\n return new URL(value, page.href).href;\n });\n\nfunction settingsSchema(api: Api) {\n const [server, ...others] = api.servers;\n return z.object({\n // OpenAPI 3.2: a spec without servers is served from \"/\".\n baseUrl:\n others.length > 0 ? baseUrlSchema : baseUrlSchema.prefault(server ?? '/'),\n headers: z.record(z.string(), z.string()).optional(),\n fetch: fetchType,\n skipValidation: z.boolean().optional(),\n credentials: api.credentials.optional(),\n });\n}\n\nexport class Client<A extends Api> {\n readonly api: A;\n options: ClientSettings<A>;\n readonly #settings: ReturnType<typeof settingsSchema>;\n\n constructor(api: A, options: ClientSettings<A>) {\n this.api = api;\n this.options = options;\n this.#settings = settingsSchema(api);\n }\n\n /** The settings, validated, with baseUrl resolved. */\n async settings() {\n return this.#settings.parseAsync(this.options);\n }\n\n /**\n * Sends a request and returns the unwrapped response data, or, for an\n * operation that pages, its first Page.\n */\n request<const E extends keyof A['routes'] & string>(\n endpoint: E,\n input: z.input<A['routes'][E]['schema']>,\n options?: RequestOptions,\n ): RequestPromise<EndpointsOf<A>[E]['result']>;\n request(\n endpoint: string,\n input: unknown,\n options?: RequestOptions,\n ): Promise<unknown> {\n const pagination = this.api.routes[endpoint]?.pagination;\n if (pagination) {\n return new PagePromise(\n firstPage(this, endpoint, input, pagination, options),\n );\n }\n return send(this, endpoint, input, options).then((result) =>\n result instanceof APIResponse ? result.data : result,\n );\n }\n\n /** Builds a ready-to-send request without sending it. */\n async prepare<const E extends keyof A['routes'] & string>(\n endpoint: E,\n input: z.input<A['routes'][E]['schema']>,\n options?: RequestOptions,\n ) {\n return prepare(this, endpoint, input, options);\n }\n\n async defaultHeaders() {\n const settings = await this.settings();\n return { ...settings.headers };\n }\n\n setOptions(options: Partial<ClientSettings<A>>) {\n this.options = { ...this.options, ...options };\n }\n}\n\nexport function createClient<A extends Api>(\n api: A,\n settings: ClientSettings<A>,\n): Client<A> {\n return new Client(api, settings);\n}\n\nasync function firstPage(\n client: Client<Api>,\n endpoint: string,\n input: unknown,\n pagination: Pagination,\n options: RequestOptions | undefined,\n) {\n if (typeof input !== 'object' || input === null) {\n throw new TypeError(\n `${endpoint} pages through its input, so the input must be an object`,\n );\n }\n const fetchPage = async (\n pageInput: Record<string, unknown>,\n pageOptions: PageRequestOptions | undefined,\n ) => {\n const result = await send(client, endpoint, pageInput, {\n ...options,\n ...pageOptions,\n });\n if (\n !(result instanceof APIResponse) ||\n result.status !== pagination.statusCode\n ) {\n throw result;\n }\n const data: unknown = result.data;\n if (typeof data !== 'object' || data === null) {\n throw new TypeError(`${endpoint} answered a page that is not an object`);\n }\n return createPage(data, pageInput, pagination, fetchPage);\n };\n return fetchPage(Object.fromEntries(Object.entries(input)), undefined);\n}\n\nfunction interceptorsFor(\n route: Route,\n settings: Awaited<ReturnType<Client<Api>['settings']>>,\n api: Api,\n options: RequestOptions | undefined,\n) {\n return [\n createHeadersInterceptor({ ...settings.headers }, options?.headers ?? {}),\n createSecurityInterceptor(\n route.security,\n settings.credentials,\n api.securitySchemes,\n ),\n ];\n}\n\n/**\n * Sends a validated request with the client's settings and returns the\n * response status class (status, headers, data). Throws `APIError` on\n * non-ok responses.\n */\nexport async function request<\n A extends Api,\n const E extends keyof A['routes'] & string,\n>(\n client: Client<A>,\n endpoint: E,\n input: z.input<A['routes'][E]['schema']>,\n options?: RequestOptions,\n): Promise<DispatchReturn<A, E>>;\nexport async function request(\n client: Client<Api>,\n endpoint: string,\n input: unknown,\n options?: RequestOptions,\n): Promise<unknown> {\n return send(client, endpoint, input, options);\n}\n\nfunction routeOf(api: Api, endpoint: string) {\n const route = api.routes[endpoint];\n if (route === undefined) {\n throw new Error(`The api has no endpoint '${endpoint}'`);\n }\n return route;\n}\n\nasync function send(\n client: Client<Api>,\n endpoint: string,\n input: unknown,\n options: RequestOptions | undefined,\n) {\n const route = routeOf(client.api, endpoint);\n const settings = await client.settings();\n const parsedInput = settings.skipValidation\n ? input\n : parseInput(route.schema, input);\n return route.dispatch(parsedInput, {\n fetch: settings.fetch,\n baseUrl: settings.baseUrl,\n interceptors: interceptorsFor(route, settings, client.api, options),\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n}\n\n/**\n * Builds a validated `RequestConfig` (url + init) with a `parse` function\n * attached, without sending it.\n */\nexport async function prepare<\n A extends Api,\n const E extends keyof A['routes'] & string,\n>(\n client: Client<A>,\n endpoint: E,\n input: z.input<A['routes'][E]['schema']>,\n options?: RequestOptions,\n): Promise<\n RequestConfig & {\n parse: (response: Response) => Promise<DispatchReturn<A, E>>;\n }\n>;\nexport async function prepare(\n client: Client<Api>,\n endpoint: string,\n input: unknown,\n options?: RequestOptions,\n): Promise<\n RequestConfig & { parse: (response: Response) => Promise<unknown> }\n> {\n const route = routeOf(client.api, endpoint);\n const settings = await client.settings();\n const parsedInput = settings.skipValidation\n ? input\n : parseInput(route.schema, input);\n let config = route.toRequest(parsedInput, settings.baseUrl);\n if (options?.signal) {\n config = { ...config, init: { ...config.init, signal: options.signal } };\n }\n for (const interceptor of interceptorsFor(\n route,\n settings,\n client.api,\n options,\n )) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n return {\n ...config,\n parse: (response: Response) => parse(route.output, response),\n };\n}\n", "http/dispatcher.ts": "import { z } from 'zod';\n\nimport { type Interceptor } from './interceptors.ts';\nimport { buffered } from './parse-response.ts';\nimport { type RequestConfig } from './request.ts';\nimport {\n APIError,\n APIResponse,\n type RebindSuccessPayload,\n type StatusRange,\n type SuccessfulResponse,\n} from './response.ts';\nimport { type SSEListener } from './sse.ts';\n\nexport type Unionize<T> = T extends [infer Single extends OutputType]\n ? InstanceType<Single>\n : T extends readonly [...infer Tuple extends OutputType[]]\n ? { [I in keyof Tuple]: InstanceType<Tuple[I]> }[number]\n : never;\n\nexport type InstanceType<T> =\n T extends Type<infer U>\n ? U\n : T extends { type: Type<infer U> }\n ? U\n : T extends Array<unknown>\n ? Unionize<T>\n : never;\n\ntype ResponseData<T extends OutputType[]> =\n Extract<InstanceType<T>, SuccessfulResponse> extends SuccessfulResponse<\n infer P\n >\n ? P\n : unknown;\n\ntype ResponseMapper<T extends OutputType[], R> = (data: ResponseData<T>) => R;\n\nexport interface Type<T> {\n new (...args: any[]): T;\n}\nexport type Parser = (\n response: Response,\n) => Promise<unknown> | ReadableStream<any> | SSEListener;\n/** An output that `range` declares reads every status of the range that no exact output declares. */\nexport type OutputType =\n | Type<APIResponse>\n | { parser: Parser; type: Type<APIResponse>; range?: StatusRange };\n\n// Bare z.custom (no predicate) on purpose: Request/Response from another\n// realm (undici vs global fetch) fail instanceof checks. The output is\n// typed as a Promise directly \u2014 zod 4 deprecated z.promise.\nexport const fetchType = z\n .function({\n input: [z.custom<Request>()],\n output: z.custom<Promise<Response>>(),\n })\n .optional();\n\n/** Reads the body of a status the operation declares no output for. */\nconst undeclared: Parser = buffered();\n\nexport async function parse<T extends OutputType[]>(\n outputs: T,\n response: Response,\n): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\nexport async function parse<T extends OutputType[], R>(\n outputs: T,\n response: Response,\n mapper: ResponseMapper<T, R>,\n): Promise<\n RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>\n>;\nexport async function parse(\n outputs: OutputType[],\n response: Response,\n mapper?: (data: unknown) => unknown,\n): Promise<APIResponse> {\n const declared = match(outputs, response.status);\n const output = declared ? typeOf(declared) : null;\n const parser =\n declared && 'parser' in declared ? declared.parser : undeclared;\n\n if (response.ok) {\n const data = await parser(response);\n const mapped = mapper ? mapper(data) : data;\n const success =\n output && isTypeOf(output, APIResponse) ? output : APIResponse;\n return success.create(response.status, response.headers, mapped);\n }\n\n const failure = output && isTypeOf(output, APIError) ? output : APIError;\n throw failure.create(\n response.status,\n response.headers,\n await parser(response),\n );\n}\n\n// OpenAPI 3.2 Responses Object: an explicit code takes precedence over the\n// range that covers it.\nfunction match(outputs: OutputType[], status: number) {\n const range = `${Math.trunc(status / 100)}XX`;\n return (\n outputs.find(\n (output) => !('range' in output) && statusOf(output) === status,\n ) ?? outputs.find((output) => 'range' in output && output.range === range)\n );\n}\n\nfunction typeOf(output: OutputType) {\n return 'parser' in output ? output.type : output;\n}\n\nfunction statusOf(output: OutputType) {\n const type = typeOf(output);\n return isTypeOf(type, APIResponse) || isTypeOf(type, APIError)\n ? type.status\n : undefined;\n}\n\nexport function isTypeOf<T extends Type<APIResponse>>(\n instance: any,\n baseType: T,\n): instance is T {\n return (\n instance === baseType ||\n Object.prototype.isPrototypeOf.call(baseType, instance)\n );\n}\n\nexport class Dispatcher {\n #interceptors: Interceptor[] = [];\n #fetch: z.infer<typeof fetchType>;\n constructor(interceptors: Interceptor[], fetch?: z.infer<typeof fetchType>) {\n this.#interceptors = interceptors;\n this.#fetch = fetch;\n }\n\n async send<T extends OutputType[]>(\n config: RequestConfig,\n outputs: T,\n signal?: AbortSignal,\n ): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\n async send<T extends OutputType[], R>(\n config: RequestConfig,\n outputs: T,\n signal: AbortSignal | undefined,\n mapper: ResponseMapper<T, R>,\n ): Promise<\n RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>\n >;\n async send<T extends OutputType[], R = ResponseData<T>>(\n config: RequestConfig,\n outputs: T,\n signal?: AbortSignal,\n mapper?: ResponseMapper<T, R>,\n ) {\n for (const interceptor of this.#interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n\n const init =\n signal === undefined ? config.init : { ...config.init, signal };\n\n let response = await (this.#fetch ?? fetch)(new Request(config.url, init));\n\n for (const interceptor of this.#interceptors.toReversed()) {\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n\n if (mapper) {\n return await parse(outputs, response, mapper);\n }\n return await parse(outputs, response);\n }\n}\n", "http/interceptors.ts": "import type { HeadersInit, RequestConfig } from './request.ts';\n\nexport interface Interceptor {\n before?: (config: RequestConfig) => Promise<RequestConfig> | RequestConfig;\n after?: (response: Response) => Promise<Response> | Response;\n}\n\nexport const createHeadersInterceptor = (\n headers: Record<string, string | undefined>,\n requestHeaders: HeadersInit,\n): Interceptor => {\n return {\n before({ init, url }) {\n // Priority Levels\n // 1. Headers Input\n // 2. Request Headers\n // 3. Default Headers\n\n for (const [key, value] of new Headers(requestHeaders)) {\n // Only set the header if it doesn't already exist and has a value\n // even though these headers are passed at operation level\n // still they are lower priority compared to the headers input\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n for (const [key, value] of Object.entries(headers)) {\n // Only set the header if it doesn't already exist and has a value\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n return { init, url };\n },\n };\n};\n", "http/page.ts": "/** How an operation pages, as the spec IR records it. Paths are dot-separated paths into the response body. */\nexport type Pagination =\n | {\n type: 'offset';\n offsetParamName: string;\n limitParamName: string;\n items: string;\n hasMore: string;\n statusCode: number;\n /** The offset parameter's default in the spec. */\n start?: number;\n }\n | {\n type: 'page';\n pageNumberParamName: string;\n pageSizeParamName: string;\n items: string;\n hasMore: string;\n statusCode: number;\n /** The page parameter's default in the spec. */\n start?: number;\n }\n | {\n type: 'cursor';\n cursorParamName: string;\n items: string;\n hasMore: string;\n statusCode: number;\n /** Path of the cursor that requests the next page. */\n nextCursor?: string;\n };\n\ntype PathValue<T, P extends string> = P extends `${infer K}.${infer Rest}`\n ? K extends keyof NonNullable<T>\n ? PathValue<NonNullable<T>[K], Rest>\n : never\n : P extends keyof NonNullable<T>\n ? NonNullable<T>[P]\n : never;\n\n/** The item type of the array at `P` in `Data`. */\nexport type ItemOf<Data, P extends string> =\n NonNullable<PathValue<Data, P>> extends readonly (infer I)[] ? I : never;\n\n/** Options for the request a page fetch sends; they override the first request's. */\nexport interface PageRequestOptions {\n signal?: AbortSignal;\n}\n\n/**\n * The way from a page to the next. A next page has the type of the page it\n * comes from, so generic code over one endpoint keeps that endpoint's type.\n */\nexport interface PageControls<Item> extends AsyncIterable<Item> {\n hasNextPage(): boolean;\n getNextPage<P extends PageControls<unknown>>(\n this: P,\n options?: PageRequestOptions,\n ): Promise<P>;\n /** This page, then each following page. */\n iterPages<P extends PageControls<unknown>>(\n this: P,\n options?: PageRequestOptions,\n ): AsyncGenerator<P>;\n}\n\n/** A page: the response body's fields, and the way to the next page. */\nexport type Page<Data, Item> = Data & PageControls<Item>;\n\ntype FetchPage = (\n input: Record<string, unknown>,\n options: PageRequestOptions | undefined,\n) => Promise<ResponsePage>;\n\nfunction at(data: unknown, path: string): unknown {\n let value = data;\n for (const key of path.split('.')) {\n if (typeof value !== 'object' || value === null) return undefined;\n value = Reflect.get(value, key);\n }\n return value;\n}\n\n/**\n * The position an omitted offset or page parameter stands for: the spec's\n * default, else the first offset (0) or the first page (1).\n */\nfunction position(sent: unknown, start: number | undefined, first: number) {\n if (typeof sent === 'number') return sent;\n return start ?? first;\n}\n\nclass ResponsePage {\n readonly #input: Record<string, unknown>;\n readonly #pagination: Pagination;\n readonly #fetchPage: FetchPage;\n readonly #items: unknown[];\n\n constructor(\n data: object,\n input: Record<string, unknown>,\n pagination: Pagination,\n fetchPage: FetchPage,\n ) {\n Object.assign(this, data);\n this.#input = input;\n this.#pagination = pagination;\n this.#fetchPage = fetchPage;\n const items = at(data, pagination.items);\n // A spec may declare the items array nullable; a page without one is empty.\n this.#items = Array.isArray(items) ? items : [];\n }\n\n hasNextPage() {\n return Boolean(at(this, this.#pagination.hasMore));\n }\n\n async getNextPage(options?: PageRequestOptions) {\n return this.#fetchPage(this.#nextInput(), options);\n }\n\n async *iterPages(options?: PageRequestOptions) {\n yield this;\n let page = this.hasNextPage() ? await this.getNextPage(options) : undefined;\n while (page) {\n yield page;\n page = page.hasNextPage() ? await page.getNextPage(options) : undefined;\n }\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iterPages()) {\n yield* page.#items;\n }\n }\n\n #nextInput(): Record<string, unknown> {\n const pagination = this.#pagination;\n switch (pagination.type) {\n case 'offset': {\n const offset = position(\n this.#input[pagination.offsetParamName],\n pagination.start,\n 0,\n );\n return {\n ...this.#input,\n [pagination.offsetParamName]: offset + this.#items.length,\n };\n }\n case 'page': {\n const page = position(\n this.#input[pagination.pageNumberParamName],\n pagination.start,\n 1,\n );\n return { ...this.#input, [pagination.pageNumberParamName]: page + 1 };\n }\n case 'cursor': {\n const cursor = pagination.nextCursor\n ? at(this, pagination.nextCursor)\n : undefined;\n if (typeof cursor !== 'string') {\n throw new Error(\n 'The response says more pages exist but names no next cursor',\n );\n }\n return { ...this.#input, [pagination.cursorParamName]: cursor };\n }\n }\n }\n}\n\n/** Builds the Page for `data`, the body of a response to `input`. */\nexport function createPage(\n data: object,\n input: Record<string, unknown>,\n pagination: Pagination,\n fetchPage: FetchPage,\n): ResponsePage {\n return new ResponsePage(data, input, pagination, fetchPage);\n}\n\n/**\n * The promise of a page that is also an async iterable of every item across\n * pages, so `for await (const item of client.request(\u2026))` needs no `await`.\n */\nexport class PagePromise<P extends AsyncIterable<Item>, Item>\n extends Promise<P>\n implements AsyncIterable<Item>\n{\n static override get [Symbol.species]() {\n return Promise;\n }\n\n constructor(page: Promise<P>) {\n super((resolve, reject) => {\n page.then(resolve, reject);\n });\n }\n\n async *[Symbol.asyncIterator]() {\n yield* await this;\n }\n}\n", "http/parse-response.ts": "import { parse } from 'fast-content-type-parse';\n\nfunction isBinaryContentType(contentType: string) {\n const type = contentType.toLowerCase();\n if (type.startsWith('image/')) {\n return true;\n }\n if (type.startsWith('audio/')) {\n return true;\n }\n if (type.startsWith('video/')) {\n return true;\n }\n switch (type) {\n case 'application/pdf':\n case 'application/zip':\n case 'application/gzip':\n case 'application/x-7z-compressed':\n case 'application/x-tar':\n case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':\n case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':\n case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':\n case 'application/vnd.ms-excel':\n case 'application/vnd.ms-powerpoint':\n case 'application/msword':\n case 'application/octet-stream':\n return true;\n default:\n return false;\n }\n}\n\nexport function chunked(response: Response) {\n return response.body!;\n}\n\n// The operation declares no body; release the unread stream so the\n// connection is not held until garbage collection.\nexport async function bodyless(response: Response) {\n await response.body?.cancel();\n return null;\n}\n\n/** The body kinds the buffered parser reads: what the spec declares for a status. */\nexport type BufferedBody = 'json' | 'text' | 'binary';\n\n/**\n * Reads a body by its Content-Type. A response without one reads as the body\n * the spec declares for its status, or, with none declared, as the\n * application/octet-stream that RFC 9110 \xA78.3 lets a recipient assume.\n */\nexport function buffered(declared?: BufferedBody) {\n return async (response: Response): Promise<unknown> => {\n // Statuses that, per the HTTP spec, carry no message body. These\n // responses usually omit Content-Type entirely.\n if (\n response.status === 204 ||\n response.status === 205 ||\n response.status === 304\n ) {\n return null;\n }\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return byContentType(response, contentType);\n }\n const bytes = await response.bytes();\n if (bytes.byteLength === 0) {\n return null;\n }\n switch (declared) {\n case 'json':\n return JSON.parse(new TextDecoder().decode(bytes));\n case 'text':\n return new TextDecoder().decode(bytes);\n default:\n return new Blob([bytes], { type: 'application/octet-stream' });\n }\n };\n}\n\nasync function byContentType(response: Response, contentType: string) {\n const { type } = parse(contentType);\n if (isBinaryContentType(type)) {\n return response.blob();\n }\n if (type.startsWith('text/')) {\n return response.text();\n }\n if (type === 'application/json' || type.endsWith('+json')) {\n return response.json();\n }\n switch (type) {\n case 'application/xml':\n return response.text();\n case 'application/x-www-form-urlencoded': {\n const text = await response.text();\n return Object.fromEntries(new URLSearchParams(text));\n }\n case 'multipart/form-data':\n return response.formData();\n default:\n throw new Error(`Unsupported content type: ${contentType}`);\n }\n}\n", "http/parser.ts": "import { z } from 'zod';\n\nexport class ParseError<T extends z.ZodType> extends Error {\n public data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>;\n constructor(data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>) {\n super('Validation failed');\n this.name = 'ParseError';\n this.data = data;\n }\n}\n\nexport function parseInput<T extends z.ZodType>(\n schema: T,\n input: unknown,\n): z.infer<T> {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = z.flattenError(result.error, (issue) => issue);\n throw new ParseError<T>(error);\n }\n return result.data;\n}\n", "http/request.ts": "type Init = Omit<RequestInit, 'headers'> & { headers: Headers };\nexport type RequestConfig = { init: Init; url: URL };\n/** The methods an OpenAPI operation uses, as an HTTP request line writes them. */\nexport type Method =\n 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'TRACE' | 'HEAD';\nexport type HeadersInit = [string, string][] | Record<string, string>;\n\nexport type BodyInit =\n ArrayBuffer | Blob | FormData | URLSearchParams | null | string;\n\nfunction template(\n templateString: string,\n templateVariables: Record<string, any>,\n): string {\n const nargs = /{([0-9a-zA-Z_]+)}/g;\n return templateString.replace(nargs, (match, key: string, index: number) => {\n // Handle escaped double braces\n if (\n templateString[index - 1] === '{' &&\n templateString[index + match.length] === '}'\n ) {\n return key;\n }\n\n const result = key in templateVariables ? templateVariables[key] : null;\n return result === null || result === undefined\n ? ''\n : encodeURIComponent(String(result));\n });\n}\n\ntype Input = Record<string, any>;\n\n// Validated inputs can carry Date (coerce-date) values; String(new Date())\n// yields a local-time RFC 2822 string, so serialize Dates as ISO 8601.\nfunction toWireValue(value: any): string {\n return value instanceof Date ? value.toISOString() : String(value);\n}\n\n/** The values a field sends: none when the caller left it out, one per item of an array. */\nfunction wireItems(value: any): any[] {\n if (value === undefined) {\n return [];\n }\n return Array.isArray(value) ? value : [value];\n}\n\ntype Props = {\n /** The media type the body is sent as. */\n contentType: string;\n inputHeaders: string[];\n inputQuery: string[];\n inputBody: string[];\n inputParams: string[];\n};\n\nabstract class Serializer {\n protected input: Input;\n protected props: Props;\n\n constructor(input: Input, props: Props) {\n this.input = input;\n this.props = props;\n }\n\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(path: string, baseUrl: string): Serialized {\n const params = this.props.inputParams.reduce<Record<string, any>>(\n (acc, key) => {\n acc[key] = this.input[key];\n return acc;\n },\n {},\n );\n const url = new URL(`${baseUrl}${template(path, params)}`);\n\n const headers: Record<string, string> = { ...this.getHeaders() };\n for (const header of this.props.inputHeaders) {\n const value = this.input[header];\n if (value !== undefined) {\n headers[header] = toWireValue(value);\n }\n }\n\n for (const key of this.props.inputQuery) {\n for (const item of wireItems(this.input[key])) {\n url.searchParams.append(key, toWireValue(item));\n }\n }\n\n return {\n body: this.getBody(),\n url,\n headers,\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n headers: Record<string, string>;\n url: URL;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\n if (\n this.props.inputBody.length === 1 &&\n this.props.inputBody[0] === '$body'\n ) {\n return JSON.stringify(this.input.$body);\n }\n\n for (const prop of this.props.inputBody) {\n body[prop] = this.input[prop];\n }\n return JSON.stringify(body);\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': this.props.contentType,\n Accept: 'application/json',\n };\n }\n}\n\nclass UrlencodedSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new URLSearchParams();\n for (const prop of this.props.inputBody) {\n for (const item of wireItems(this.input[prop])) {\n body.append(prop, toWireValue(item));\n }\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': this.props.contentType,\n Accept: 'application/json',\n };\n }\n}\n\nclass EmptySerializer extends Serializer {\n getBody(): BodyInit | null {\n return null;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass FormDataSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new FormData();\n for (const prop of this.props.inputBody) {\n for (const item of wireItems(this.input[prop])) {\n body.append(prop, item);\n }\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n Accept: 'application/json',\n };\n }\n}\n\n// A text or binary body is the caller's own string or Blob, sent as is.\nclass RawSerializer extends Serializer {\n getBody(): BodyInit | null {\n return this.input.$body;\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': this.props.contentType,\n };\n }\n}\n\nexport function json(input: Input, props: Props) {\n return new JsonSerializer(input, props);\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props);\n}\nexport function empty(input: Input, props: Props) {\n return new EmptySerializer(input, props);\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props);\n}\nexport function text(input: Input, props: Props) {\n return new RawSerializer(input, props);\n}\nexport function binary(input: Input, props: Props) {\n return new RawSerializer(input, props);\n}\n\nexport function toRequest(\n method: Method,\n path: string,\n serializer: Serializer,\n baseUrl: string,\n): RequestConfig {\n const input = serializer.serialize(path, baseUrl);\n return {\n url: input.url,\n init: {\n method: method,\n headers: new Headers(input.headers),\n ...(method === 'GET' ? {} : { body: input.body }),\n },\n };\n}\n", "http/response.ts": "/** The status ranges an OpenAPI 3.2 Responses Object may declare. */\nexport type StatusRange = '1XX' | '2XX' | '3XX' | '4XX' | '5XX';\ntype Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';\ntype ToNumber<S> = S extends `${infer N extends number}` ? N : never;\n/** Every status code a range covers: `RangeStatus<'4XX'>` is 400 | 401 | \u2026 | 499. */\nexport type RangeStatus<R extends StatusRange> = R extends `${infer C}XX`\n ? ToNumber<`${C}${Digit}${Digit}`>\n : never;\nexport class APIResponse<Body = unknown, Status extends number = number> {\n static readonly status: number;\n readonly status: Status;\n data: Body;\n readonly headers: Headers;\n\n constructor(status: Status, headers: Headers, data: Body) {\n this.status = status;\n this.headers = headers;\n this.data = data;\n }\n\n static create(status: number, headers: Headers, data: unknown) {\n return new this(status, headers, data);\n }\n}\n\nexport class APIError<Body, Status extends number = number> extends Error {\n static readonly status: number;\n readonly status: Status;\n data: Body;\n readonly headers: Headers;\n\n constructor(status: Status, headers: Headers, data: Body) {\n super(failureMessage(status, data));\n this.name = 'APIError';\n this.status = status;\n this.headers = headers;\n this.data = data;\n }\n\n static create<T>(status: number, headers: Headers, data: T) {\n return new this(status, headers, data);\n }\n}\n\nfunction failureMessage(status: number, data: unknown) {\n const summary = bodySummary(data);\n return summary\n ? `Request failed with status code ${status}: ${summary}`\n : `Request failed with status code ${status}`;\n}\n\n// Only text and JSON bodies read as a summary; a Blob, stream or FormData body\n// has none. The tag check holds across realms, where prototype checks do not.\nfunction bodySummary(data: unknown) {\n const tag = Object.prototype.toString.call(data);\n let text = '';\n if (typeof data === 'string') {\n text = data;\n } else if (tag === '[object Object]' || tag === '[object Array]') {\n text = JSON.stringify(data);\n }\n const line = text.replace(/\\s+/g, ' ').trim();\n return line.length > 200 ? `${line.slice(0, 200)}\u2026` : line;\n}\n\n// 2xx Success\nexport class Ok<T> extends APIResponse<T, 200> {\n static override readonly status = 200 as const;\n constructor(headers: Headers, data: T) {\n super(Ok.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\nexport class Created<T> extends APIResponse<T, 201> {\n static override status = 201 as const;\n constructor(headers: Headers, data: T) {\n super(Created.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Accepted<T> extends APIResponse<T, 202> {\n static override status = 202 as const;\n constructor(headers: Headers, data: T) {\n super(Accepted.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NoContent extends APIResponse<null, 204> {\n static override status = 204 as const;\n constructor(headers: Headers) {\n super(NoContent.status, headers, null);\n }\n static override create(status: number, headers: Headers): NoContent {\n return new this(headers);\n }\n}\n\n// 4xx Client Errors\nexport class BadRequest<T> extends APIError<T, 400> {\n static override status = 400 as const;\n constructor(headers: Headers, data: T) {\n super(BadRequest.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Unauthorized<T = { message: string }> extends APIError<T, 401> {\n static override status = 401 as const;\n constructor(headers: Headers, data: T) {\n super(Unauthorized.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class PaymentRequired<T = { message: string }> extends APIError<T, 402> {\n static override status = 402 as const;\n constructor(headers: Headers, data: T) {\n super(PaymentRequired.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Forbidden<T = { message: string }> extends APIError<T, 403> {\n static override status = 403 as const;\n constructor(headers: Headers, data: T) {\n super(Forbidden.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NotFound<T = { message: string }> extends APIError<T, 404> {\n static override status = 404 as const;\n constructor(headers: Headers, data: T) {\n super(NotFound.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class MethodNotAllowed<T = { message: string }> extends APIError<\n T,\n 405\n> {\n static override status = 405 as const;\n constructor(headers: Headers, data: T) {\n super(MethodNotAllowed.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NotAcceptable<T = { message: string }> extends APIError<T, 406> {\n static override status = 406 as const;\n constructor(headers: Headers, data: T) {\n super(NotAcceptable.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Conflict<T = { message: string }> extends APIError<T, 409> {\n static override status = 409 as const;\n constructor(headers: Headers, data: T) {\n super(Conflict.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Gone<T = { message: string }> extends APIError<T, 410> {\n static override status = 410 as const;\n constructor(headers: Headers, data: T) {\n super(Gone.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class PreconditionFailed<T = { message: string }> extends APIError<\n T,\n 412\n> {\n static override status = 412 as const;\n constructor(headers: Headers, data: T) {\n super(PreconditionFailed.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class UnprocessableEntity<\n T = { message: string; errors?: Record<string, string[]> },\n> extends APIError<T, 422> {\n static override status = 422 as const;\n constructor(headers: Headers, data: T) {\n super(UnprocessableEntity.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class TooManyRequests<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 429> {\n static override status = 429 as const;\n constructor(headers: Headers, data: T) {\n super(TooManyRequests.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class PayloadTooLarge<T = { message: string }> extends APIError<T, 413> {\n static override status = 413 as const;\n constructor(headers: Headers, data: T) {\n super(PayloadTooLarge.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class UnsupportedMediaType<T = { message: string }> extends APIError<\n T,\n 415\n> {\n static override status = 415 as const;\n constructor(headers: Headers, data: T) {\n super(UnsupportedMediaType.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\n// 5xx Server Errors\nexport class InternalServerError<T = { message: string }> extends APIError<\n T,\n 500\n> {\n static override status = 500 as const;\n constructor(headers: Headers, data: T) {\n super(InternalServerError.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NotImplemented<T = { message: string }> extends APIError<T, 501> {\n static override status = 501 as const;\n constructor(headers: Headers, data: T) {\n super(NotImplemented.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class BadGateway<T = { message: string }> extends APIError<T, 502> {\n static override status = 502 as const;\n constructor(headers: Headers, data: T) {\n super(BadGateway.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class ServiceUnavailable<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 503> {\n static override status = 503 as const;\n constructor(headers: Headers, data: T) {\n super(ServiceUnavailable.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class GatewayTimeout<T = { message: string }> extends APIError<T, 504> {\n static override status = 504 as const;\n constructor(headers: Headers, data: T) {\n super(GatewayTimeout.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\nexport type ClientError =\n | BadRequest<unknown>\n | Unauthorized<unknown>\n | PaymentRequired<unknown>\n | Forbidden<unknown>\n | NotFound<unknown>\n | MethodNotAllowed<unknown>\n | NotAcceptable<unknown>\n | Conflict<unknown>\n | Gone<unknown>\n | PreconditionFailed<unknown>\n | PayloadTooLarge<unknown>\n | UnsupportedMediaType<unknown>\n | UnprocessableEntity<unknown>\n | TooManyRequests<unknown>\n | APIError<unknown, RangeStatus<'4XX'>>;\n\nexport type ServerError =\n | InternalServerError<unknown>\n | NotImplemented<unknown>\n | BadGateway<unknown>\n | ServiceUnavailable<unknown>\n | GatewayTimeout<unknown>\n | APIError<unknown, RangeStatus<'5XX'>>;\n\nexport type ProblematicResponse = ClientError | ServerError;\n\nexport type SuccessfulResponse<T = unknown> =\n | Ok<T>\n | Created<T>\n | Accepted<T>\n | NoContent\n | APIResponse<T, RangeStatus<'2XX'>>;\n\nexport type RebindSuccessPayload<Resp, New> =\n Resp extends Ok<infer _>\n ? Ok<New>\n : Resp extends Created<infer _>\n ? Created<New>\n : Resp extends Accepted<infer _>\n ? Accepted<New>\n : Resp extends NoContent\n ? NoContent\n : Resp extends SuccessfulResponse<infer _>\n ? APIResponse<New, Resp['status']>\n : never;\n", "http/security.ts": "import { z } from 'zod';\n\nimport type { Interceptor } from './interceptors.ts';\nimport type { RequestConfig } from './request.ts';\n\nexport type SecurityContext = {\n scheme: string;\n scopes: readonly string[];\n roles: readonly string[];\n};\nexport type SecurityCredentialValue =\n | string\n | true\n | {\n username: string;\n password: string;\n };\nexport type SecurityCredentialProvider<T extends SecurityCredentialValue> = (\n context: SecurityContext,\n) => T | Promise<T>;\nexport type SecurityCredential<\n T extends SecurityCredentialValue = SecurityCredentialValue,\n> = T | SecurityCredentialProvider<T>;\n\nconst providerSchema = <T extends SecurityCredentialValue>() =>\n z.custom<SecurityCredentialProvider<T>>(\n (value) => typeof value === 'function',\n );\nexport const stringCredentialSchema = z.union([\n z.string(),\n z.literal(true),\n providerSchema<string | true>(),\n]);\nconst basicCredentialValueSchema = z.object({\n username: z.string(),\n password: z.string(),\n});\nexport const basicCredentialSchema = z.union([\n basicCredentialValueSchema,\n z.literal(true),\n providerSchema<{ username: string; password: string } | true>(),\n]);\nexport const mutualTlsCredentialSchema = z.union([\n z.literal(true),\n providerSchema<true>(),\n]);\n\nexport type RuntimeSecurityScheme =\n | { type: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string }\n | { type: 'http'; scheme: string }\n | { type: 'oauth2' }\n | { type: 'openIdConnect' }\n | { type: 'mutualTLS' };\n\n/** The spec's components.securitySchemes; a requirement can name a scheme it lacks (an unresolved external one). */\nexport type RuntimeSecuritySchemes = {\n readonly [name: string]: RuntimeSecurityScheme | undefined;\n};\n\nexport function createSecurityInterceptor(\n requirements: readonly Record<string, readonly string[]>[],\n credentials: Record<string, SecurityCredential | undefined> | undefined,\n schemes: RuntimeSecuritySchemes,\n): Interceptor {\n return {\n async before(config) {\n if (requirements.length === 0) return config;\n const secured = requirements.filter(\n (requirement) => Object.keys(requirement).length > 0,\n );\n const selected = secured.find((requirement) =>\n Object.keys(requirement).every(\n (name) => credentials?.[name] !== undefined,\n ),\n );\n if (!selected) {\n if (\n requirements.some(\n (requirement) => Object.keys(requirement).length === 0,\n )\n )\n return config;\n throw new Error(\n `Missing credentials for security requirements: ${secured\n .map((requirement) => Object.keys(requirement).join(' + '))\n .join(' or ')}`,\n );\n }\n for (const [name, values] of Object.entries(selected)) {\n const scheme = schemes[name];\n if (!scheme) {\n throw new Error(`Unsupported external security scheme: ${name}`);\n }\n const configured = credentials?.[name];\n const isOAuth =\n scheme.type === 'oauth2' || scheme.type === 'openIdConnect';\n const credential =\n typeof configured === 'function'\n ? await configured({\n scheme: name,\n scopes: isOAuth ? values : [],\n roles: isOAuth ? [] : values,\n })\n : configured;\n applyCredential(config, scheme, credential);\n }\n return config;\n },\n };\n}\n\nfunction applyCredential(\n config: RequestConfig,\n scheme: RuntimeSecurityScheme,\n credential: SecurityCredentialValue | undefined,\n) {\n if (credential === undefined) {\n throw new Error('Security credential provider returned no credential');\n }\n // true declares a transport-owned credential: the configured fetch, a host\n // proxy, or the browser's cookie jar supplies it, so nothing is set here.\n if (credential === true) return;\n if (scheme.type === 'apiKey') {\n if (typeof credential !== 'string') {\n throw new TypeError('API key credentials must be strings');\n }\n if (scheme.in === 'header') {\n if (!config.init.headers.has(scheme.name)) {\n config.init.headers.set(scheme.name, credential);\n }\n } else if (scheme.in === 'query') {\n if (!config.url.searchParams.has(scheme.name)) {\n config.url.searchParams.set(scheme.name, credential);\n }\n } else if (scheme.in === 'cookie') {\n if ('document' in globalThis) {\n throw new Error(\n `Cannot send the ${scheme.name} cookie credential: browsers forbid setting the Cookie header. Let the browser send the cookie and pass a fetch that sets credentials: 'include'.`,\n );\n }\n const cookie = `${scheme.name}=${encodeURIComponent(credential)}`;\n const existing = config.init.headers.get('Cookie');\n if (\n !existing\n ?.split(';')\n .some((part) => part.trim().startsWith(`${scheme.name}=`))\n ) {\n config.init.headers.set(\n 'Cookie',\n existing ? `${existing}; ${cookie}` : cookie,\n );\n }\n } else {\n throw new TypeError(`Unsupported apiKey location: ${String(scheme.in)}`);\n }\n return;\n }\n if (scheme.type === 'mutualTLS') {\n throw new TypeError(\n 'mutualTLS credentials must be true when the custom fetch owns the client certificate',\n );\n }\n if (scheme.type === 'http' && scheme.scheme.toLowerCase() === 'basic') {\n if (\n typeof credential !== 'object' ||\n !('username' in credential) ||\n !('password' in credential)\n ) {\n throw new TypeError('Basic credentials require username and password');\n }\n const bytes = new TextEncoder().encode(\n `${credential.username}:${credential.password}`,\n );\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n if (!config.init.headers.has('Authorization')) {\n config.init.headers.set('Authorization', `Basic ${btoa(binary)}`);\n }\n return;\n }\n if (typeof credential !== 'string') {\n throw new TypeError(`${scheme.type} credentials must be strings`);\n }\n const prefix =\n scheme.type === 'http' ? authorizationScheme(scheme.scheme) : 'Bearer';\n if (!config.init.headers.has('Authorization')) {\n config.init.headers.set('Authorization', `${prefix} ${credential}`);\n }\n}\n\n// OpenAPI carries the lowercase registry name, while servers routinely match the\n// Authorization prefix case-sensitively (`header.startsWith('Bearer ')`).\nconst authorizationSchemes: Record<string, string> = {\n basic: 'Basic',\n bearer: 'Bearer',\n digest: 'Digest',\n hoba: 'HOBA',\n mutual: 'Mutual',\n negotiate: 'Negotiate',\n oauth: 'OAuth',\n 'scram-sha-1': 'SCRAM-SHA-1',\n 'scram-sha-256': 'SCRAM-SHA-256',\n};\n\nfunction authorizationScheme(scheme: string) {\n return authorizationSchemes[scheme.toLowerCase()] ?? scheme;\n}\n", "http/sse.ts": "export type SSEListener = (eventType: string) => AsyncIterable<string>;\n\nexport function sse(response: Response): SSEListener {\n // Every iterator of an event type reads one queue. Each waiting next() keeps\n // its own wake-up in `waiters`, and a push or the end of the stream wakes all\n // of them: a woken next() that finds the queue empty waits again. One shared\n // wake-up slot would let a second iterator overwrite the first one's, which\n // then never wakes.\n const subscribers = new Map<\n string,\n { queue: string[]; waiters: Set<() => void> }\n >();\n let started = false;\n let streamDone = false;\n let streamFailure: { error: unknown } | null = null;\n\n function wake(waiters: Set<() => void>) {\n for (const resolve of waiters) resolve();\n waiters.clear();\n }\n\n function dispatch(eventType: string, data: string) {\n const sub = subscribers.get(eventType);\n if (sub) {\n sub.queue.push(data);\n wake(sub.waiters);\n }\n }\n\n function endAll() {\n streamDone = true;\n for (const sub of subscribers.values()) {\n wake(sub.waiters);\n }\n }\n\n function startReading() {\n if (started) return;\n started = true;\n const decoder = new TextDecoder();\n let buffer = '';\n\n // The pump never rejects: the catch below hands a stream failure to the\n // listeners, so nothing awaits it. `void` states that, and keeps generated\n // output clean under @typescript-eslint/no-floating-promises.\n void (async () => {\n try {\n for await (const value of response.body!) {\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split('\\n\\n');\n buffer = parts.pop()!;\n\n for (const part of parts) {\n if (!part.trim()) continue;\n let eventType = 'message';\n let data = '';\n for (const line of part.split('\\n')) {\n if (line.startsWith('event:')) {\n eventType = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n data += (data ? '\\n' : '') + line.slice(5).trim();\n }\n }\n if (data) dispatch(eventType, data);\n }\n }\n } catch (error) {\n streamFailure = { error };\n }\n endAll();\n })();\n }\n\n return function listen(eventType: string): AsyncIterable<string> {\n if (!subscribers.has(eventType)) {\n subscribers.set(eventType, { queue: [], waiters: new Set() });\n }\n const sub = subscribers.get(eventType)!;\n startReading();\n\n return {\n [Symbol.asyncIterator]() {\n return {\n async next(): Promise<IteratorResult<string>> {\n while (sub.queue.length === 0) {\n if (streamFailure) throw streamFailure.error;\n if (streamDone) return { value: undefined, done: true };\n const { promise, resolve } = Promise.withResolvers<void>();\n sub.waiters.add(resolve);\n await promise;\n }\n return { value: sub.queue.shift()!, done: false };\n },\n async return(): Promise<IteratorResult<string>> {\n return { value: undefined, done: true };\n },\n };\n },\n };\n };\n}\n" };
247
+
248
+ // packages/typescript/src/lib/generate.ts
249
+ import {
250
+ isRef as isRef5,
251
+ parseRef as parseRef3,
252
+ pointerTokens,
253
+ valueAtPointer
254
+ } from "@sdk-it/core";
8
255
  import {
9
- createWriterProxy,
10
- getFolderExports,
256
+ addLeadingSlash,
257
+ readFolder,
11
258
  writeFiles
12
259
  } from "@sdk-it/core/file-system.js";
13
260
  import {
14
261
  cleanFiles,
15
262
  forEachOperation as forEachOperation6,
16
263
  readWriteMetadata,
17
- sanitizeTag as sanitizeTag4,
18
264
  toIR
19
265
  } from "@sdk-it/spec";
20
266
 
21
267
  // packages/typescript/src/lib/agent/ai-sdk.ts
22
- import { camelcase } from "stringcase";
23
268
  import {
24
- forEachOperation
269
+ carriesBinary,
270
+ forEachOperation,
271
+ inputEndpoint,
272
+ inputName as inputName2,
273
+ operationInputs
25
274
  } from "@sdk-it/spec";
26
- function generateAISDKTools(ir) {
275
+
276
+ // packages/typescript/src/lib/import-utilities.ts
277
+ import { removeDuplicates } from "@sdk-it/core";
278
+
279
+ // packages/typescript/src/lib/input-schema-name.ts
280
+ import { camelcase as camelcase4 } from "stringcase";
281
+ import { inputName } from "@sdk-it/spec";
282
+ function inputSchemaName(operationId, input) {
283
+ return camelcase4(`${inputName(operationId, input)} schema`);
284
+ }
285
+
286
+ // packages/typescript/src/lib/agent/ai-sdk.ts
287
+ function generateAISDKTools(ir, makeImport) {
27
288
  const groups = {};
28
289
  forEachOperation(ir, (entry, operation) => {
29
290
  const tagDef = ir.tags.find((tag) => tag.name === entry.tag);
30
291
  if (!tagDef) {
31
- console.warn(`No tag details found for tag: ${entry.tag}`);
32
- return;
33
- }
34
- groups[entry.tag] ??= {
35
- tools: [],
36
- instructions: "",
37
- displayName: "",
38
- name: ""
39
- };
40
- groups[entry.tag].tools.push(createTool(entry, operation));
41
- groups[entry.tag].instructions = tagDef["x-instructions"];
42
- groups[entry.tag].name = tagDef.name;
43
- groups[entry.tag].displayName = tagDef["x-name"];
292
+ throw new Error(`The IR defines no tag ${entry.tag}`);
293
+ }
294
+ groups[entry.tag] ??= { tools: [], definition: tagDef };
295
+ groups[entry.tag].tools.push(...createTools(ir, entry, operation));
44
296
  });
45
297
  const imports = [
46
298
  `import { z } from 'zod';`,
47
299
  `import { tool } from 'ai';`,
48
- `import * as schemas from './inputs/index.ts';`
300
+ `import * as schemas from '${makeImport("./inputs/index")}';`
49
301
  ];
50
- const agent = Object.entries(groups).map(
51
- ([group, { instructions, tools, displayName }]) => {
52
- return `export const ${camelcase(group)} = {
53
- name: '${displayName}',
54
- instructions: \`${instructions}\`,
55
- tools: { ${tools.join(", ")} }
56
- }`;
57
- }
58
- );
302
+ const agent = Object.entries(groups).map(([group, { tools, definition }]) => {
303
+ const { id, instructions } = agentSettings(definition);
304
+ const instructionsLine = instructions === void 0 ? "" : `
305
+ instructions: ${JSON.stringify(instructions)},`;
306
+ return `export const ${groupIdentifier(group)} = {
307
+ id: ${JSON.stringify(id)},${instructionsLine}
308
+ tools: { ${tools.join(", ")} },
309
+ };`;
310
+ });
59
311
  return [...imports, ...agent].join("\n\n");
60
312
  }
61
- function createTool(entry, operation) {
62
- const schemaName = camelcase(`${operation.operationId} schema`);
313
+ function agentSettings(definition) {
314
+ const id = definition["x-name"] ?? definition.summary ?? definition.name;
315
+ const instructions = definition["x-instructions"] ?? definition.description;
316
+ return { id, instructions };
317
+ }
318
+ function createTools(ir, entry, operation) {
63
319
  const toolInfo = operation["x-tool"];
64
- return `'${toolInfo?.name || operation["x-fn-name"]}': tool({
320
+ const name = toolInfo?.name || operation["x-fn-name"];
321
+ const endpoint = `${entry.method.toUpperCase()} ${entry.path}`;
322
+ return operationInputs(ir, operation).filter((input) => !carriesBinary(ir, input)).map(
323
+ (input) => `'${inputName2(name, input)}': tool({
65
324
  description: \`${toolInfo?.description || operation.description || operation.summary}\`,
66
- inputSchema: schemas.${schemaName},
325
+ inputSchema: schemas.${inputSchemaName(operation.operationId, input)},
67
326
  execute: async (input, options) => {
68
- console.log('Executing ${operation.operationId} tool with input:', input);
69
327
  const context = coerceContext(options.context);
70
328
  const response = await context.client.request(
71
- '${entry.method.toUpperCase()} ${entry.path}' ,
329
+ '${inputEndpoint(endpoint, input)}' ,
72
330
  input,
73
331
  );
74
332
  return JSON.stringify(response);
75
333
  },
76
- })`;
334
+ })`
335
+ );
77
336
  }
78
337
 
79
338
  // packages/typescript/src/lib/agent/openai-agents.ts
80
- import { camelcase as camelcase2, spinalcase } from "stringcase";
81
339
  import {
82
- forEachOperation as forEachOperation2
340
+ carriesBinary as carriesBinary2,
341
+ forEachOperation as forEachOperation2,
342
+ inputEndpoint as inputEndpoint2,
343
+ inputName as inputName3,
344
+ operationInputs as operationInputs2
83
345
  } from "@sdk-it/spec";
84
- function generateOpenAIAgentTools(spec) {
346
+ function generateOpenAIAgentTools(spec, makeImport) {
85
347
  const groups = {};
86
348
  forEachOperation2(spec, (entry, operation) => {
87
349
  groups[entry.tag] ??= [];
88
- groups[entry.tag].push(createTool2(entry, operation));
350
+ groups[entry.tag].push(...createTools2(spec, entry, operation));
89
351
  });
90
352
  const imports = [
91
353
  `import { z } from 'zod';`,
92
354
  `import { tool } from '@openai/agents';`,
93
- `import * as schemas from './inputs/index.ts';`
355
+ `import * as schemas from '${makeImport("./inputs/index")}';`
94
356
  ];
95
357
  const tools = Object.entries(groups).map(([group, tools2]) => {
96
- return `export const ${spinalcase(group)} = [${tools2.join(", ")}];`;
358
+ return `export const ${groupIdentifier(group)} = [${tools2.join(", ")}];`;
97
359
  });
98
360
  return [...imports, ...tools].join("\n\n");
99
361
  }
100
- function createTool2(entry, operation) {
101
- const schemaName = camelcase2(`${operation.operationId} schema`);
102
- return `tool({
362
+ function createTools2(spec, entry, operation) {
363
+ const endpoint = `${entry.method.toUpperCase()} ${entry.path}`;
364
+ return operationInputs2(spec, operation).filter((input) => !carriesBinary2(spec, input)).map(
365
+ (input) => `tool({
103
366
  description: \`${operation.description || operation.summary}\`,
104
- name: '${operation["x-fn-name"]}',
105
- parameters: makeOptionalPropsNullable(schemas.${schemaName}),
367
+ name: '${inputName3(operation["x-fn-name"], input)}',
368
+ parameters: schemas.${inputSchemaName(operation.operationId, input)},
106
369
  execute: async (input, maybeContext) => {
107
- console.log('Executing ${operation.operationId} tool with input:', input);
108
370
  const context = coerceContext(maybeContext?.context);
109
371
  const client = context.client;
110
372
  const response = await client.request(
111
- '${entry.method.toUpperCase()} ${entry.path}' ,
373
+ '${inputEndpoint2(endpoint, input)}' ,
112
374
  input as any,
113
375
  );
114
376
  return JSON.stringify(response);
115
377
  },
116
- })`;
378
+ })`
379
+ );
117
380
  }
118
381
 
119
382
  // packages/typescript/src/lib/agent/utils.txt
120
- var utils_default = "function coerceContext(context?: any) {\n if (!context) {\n throw new Error('Context is required');\n }\n return context as {\n client: any\n };\n}\n/**\n * Takes a Zod object schema and makes all optional properties nullable as well.\n * This is useful for APIs where optional fields can be explicitly set to null.\n *\n * @param schema - The Zod object schema to transform\n * @returns A new Zod schema with optional properties made nullable\n */\nfunction makeOptionalPropsNullable<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n) {\n const shape = schema.shape;\n const newShape = {} as Record<string, z.ZodType>;\n\n for (const [key, value] of Object.entries(shape) as [string, z.ZodType][]) {\n if (value instanceof z.ZodOptional) {\n // Make optional properties also nullable\n newShape[key] = value.nullable();\n } else {\n // Keep non-optional properties as they are\n newShape[key] = value;\n }\n }\n\n return z.object(newShape);\n}\n";
121
-
122
- // packages/typescript/src/lib/client.ts
123
- import { toLitObject } from "@sdk-it/core";
124
- var client_default = (spec) => {
125
- const callableString = `z.custom<() => string | Promise<string>>((value) => typeof value === 'function')`;
126
- const baseUrlSchema = `z.union([z.string(),${callableString},])${spec.servers.length === 1 ? ".default(servers[0])" : ""}`;
127
- const securitySchemeNames = Object.keys(spec.securitySchemes);
128
- const specOptions = {
129
- ...securitySchemeNames.length ? {
130
- credentials: {
131
- schema: `credentialsSchema.optional().describe('Credentials keyed by OpenAPI security scheme name.')`
132
- }
133
- } : {},
134
- fetch: {
135
- schema: `fetchType.describe('Custom fetch implementation. Defaults to globalThis.fetch.')`
136
- },
137
- baseUrl: {
138
- schema: `${baseUrlSchema}.transform(async (baseUrl, ctx) => {
139
- const value = typeof baseUrl === 'function' ? await baseUrl() : baseUrl;
140
- if (typeof value !== 'string') {
141
- ctx.addIssue({ code: 'custom', message: 'baseUrl must resolve to a string' });
142
- return z.NEVER;
143
- }
144
- return value;
145
- }).describe('Base URL of the API server. Can be a string or a function that returns a string.')`
146
- },
147
- headers: {
148
- schema: `z.record(z.string(), z.string()).optional().describe('Default headers to include in all requests.')`
149
- },
150
- skipValidation: {
151
- schema: `z.boolean().optional().describe('Skip request input validation. Client options and TypeScript types still enforce correct usage.')`
152
- }
153
- };
154
- return `import z from 'zod';
155
- import { APIResponse } from '${spec.makeImport("./http/response")}';
156
- import type { HeadersInit, RequestConfig } from './http/${spec.makeImport("request")}';
157
- import { fetchType, parse } from './http/${spec.makeImport("dispatcher")}';
158
- import schemas from './api/${spec.makeImport("schemas")}';
159
- import type { InferData } from '${spec.makeImport("./api/endpoints")}';
160
- import {
161
- createBaseUrlInterceptor,
162
- createHeadersInterceptor,
163
- } from './http/${spec.makeImport("interceptors")}';
164
-
165
- import { type ParseError, parseInput } from './http/${spec.makeImport("parser")}';${securitySchemeNames.length ? `
166
- import { credentialsSchema, createSecurityInterceptor } from './http/${spec.makeImport("security")}';
167
- export type {
168
- SecurityContext,
169
- SecurityCredential,
170
- SecurityCredentialProvider,
171
- SecurityCredentialValue,
172
- } from './http/${spec.makeImport("security")}';` : ""}
173
-
174
- ${spec.servers.length ? `export const servers = ${JSON.stringify(spec.servers, null, 2)} as const` : ""}
175
- const optionsSchema = z.object(${toLitObject(specOptions, (x) => x.schema)});
176
- ${spec.servers.length ? `export type Servers = typeof servers[number];` : ""}
177
-
178
- type ${spec.name}Options = z.input<typeof optionsSchema>;
179
-
180
- export class ${spec.name} {
181
- public options: ${spec.name}Options;
182
- constructor(options: ${spec.name}Options) {
183
- this.options = options;
184
- }
185
-
186
- /** Sends a request and returns the unwrapped response data. Delegates to the standalone {@link request} function. */
187
- async request<const E extends keyof typeof schemas>(
188
- endpoint: E,
189
- input: z.input<(typeof schemas)[E]['schema']>,
190
- options?: { signal?: AbortSignal; headers?: HeadersInit },
191
- ) {
192
- return request(this, endpoint, input, options).then(function unwrap(
193
- it: unknown,
194
- ) {
195
- if (it instanceof APIResponse) {
196
- return it.data as InferData<E>;
197
- }
198
- return it as InferData<E>;
199
- });
200
- }
201
-
202
- /** Builds a ready-to-send request without sending it. Delegates to the standalone {@link prepare} function. */
203
- async prepare<const E extends keyof typeof schemas>(
204
- endpoint: E,
205
- input: z.input<(typeof schemas)[E]['schema']>,
206
- options?: { signal?: AbortSignal; headers?: HeadersInit },
207
- ) {
208
- return prepare(this, endpoint, input, options);
209
- }
210
-
211
- async defaultHeaders() {
212
- const options = await optionsSchema.parseAsync(this.options);
213
- return { ...options.headers };
214
- }
215
-
216
- setOptions(options: Partial<${spec.name}Options>) {
217
- this.options = {
218
- ...this.options,
219
- ...options,
220
- };
221
- }
222
-
223
- }
224
-
225
- /**
226
- * Sends a validated request using the client's configuration and returns the parsed response.
227
- * Applies the client's default headers before sending.
228
- * Throws \`APIError\` on non-ok responses.
229
- *
230
- * @example
231
- * \`\`\`ts
232
- * const result = await request(client, 'GET /users', { limit: 10 });
233
- * \`\`\`
234
- */
235
- export async function request<const E extends keyof typeof schemas>(
236
- client: ${spec.name},
237
- endpoint: E,
238
- input: z.input<(typeof schemas)[E]['schema']>,
239
- requestOptions?: { signal?: AbortSignal; headers?: HeadersInit },
240
- ): Promise<Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>> {
241
- const route = schemas[endpoint];
242
- const options = await optionsSchema.parseAsync(client.options);
243
- const parsedInput = options.skipValidation ? input : parseInput(route.schema, input);
244
- const result = await route.dispatch(parsedInput as never, {
245
- fetch: options.fetch,
246
- interceptors: [
247
- createHeadersInterceptor(
248
- { ...options.headers },
249
- requestOptions?.headers ?? {},
250
- ),
251
- ${securitySchemeNames.length ? " createSecurityInterceptor(route.security, options.credentials),\n" : ""} createBaseUrlInterceptor(options.baseUrl),
252
- ],
253
- ...(requestOptions?.signal ? { signal: requestOptions.signal } : {}),
254
- });
255
- return result as Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>;
256
- }
257
-
258
- /**
259
- * Builds a validated \`RequestConfig\` (url + init) with a \`parse\` function attached, without sending.
260
- * Use when you need control over the fetch call \u2014 framework integration (Next.js, SvelteKit),
261
- * custom retry/logging, request batching, or testing.
262
- *
263
- * @example
264
- * \`\`\`ts
265
- * const { url, init, parse } = await prepare(client, 'GET /users', { limit: 10 });
266
- * const response = await fetch(new Request(url, init));
267
- * const result = await parse(response);
268
- * \`\`\`
269
- */
270
- export async function prepare<const E extends keyof typeof schemas>(
271
- client: ${spec.name},
272
- endpoint: E,
273
- input: z.input<(typeof schemas)[E]['schema']>,
274
- requestOptions?: { signal?: AbortSignal; headers?: HeadersInit },
275
- ): Promise<RequestConfig & {
276
- parse: (response: Response) => ReturnType<typeof parse>;
277
- }> {
278
- const route = schemas[endpoint];
279
- const options = await optionsSchema.parseAsync(client.options);
280
- const parsedInput = options.skipValidation ? input : parseInput(route.schema, input);
281
- const interceptors = [
282
- createHeadersInterceptor(
283
- { ...options.headers },
284
- requestOptions?.headers ?? {},
285
- ),
286
- ${securitySchemeNames.length ? " createSecurityInterceptor(route.security, options.credentials),\n" : ""} createBaseUrlInterceptor(options.baseUrl),
287
- ];
288
-
289
- let config = route.toRequest(parsedInput as never);
290
- if (requestOptions?.signal) {
291
- config = {
292
- ...config,
293
- init: {
294
- ...config.init,
295
- signal: requestOptions.signal,
296
- },
297
- };
298
- }
299
- for (const interceptor of interceptors) {
300
- if (interceptor.before) {
301
- config = await interceptor.before(config);
302
- }
303
- }
304
- return { ...config, parse: (response: Response) => parse(route.output as never, response, (d) => d) as never } as any;
305
- }
306
-
307
-
308
- `;
309
- };
383
+ var utils_default = "function coerceContext(context?: any) {\n if (!context) {\n throw new Error('Context is required');\n }\n return context as {\n client: any\n };\n}\n";
310
384
 
311
385
  // packages/typescript/src/lib/emitters/interface.ts
312
386
  import {
@@ -314,14 +388,17 @@ import {
314
388
  isEmpty,
315
389
  isRef,
316
390
  parseRef,
317
- pascalcase,
318
391
  resolveRef
319
392
  } from "@sdk-it/core";
320
- import { isPrimitiveSchema, sanitizeTag } from "@sdk-it/spec";
393
+ import { isInlinable } from "@sdk-it/spec";
321
394
  var TypeScriptEmitter = class {
322
395
  #spec;
323
- constructor(spec) {
396
+ #modelName;
397
+ #refs;
398
+ constructor(spec, modelName, refs) {
324
399
  this.#spec = spec;
400
+ this.#modelName = modelName;
401
+ this.#refs = refs;
325
402
  }
326
403
  #stringifyKey = (value) => {
327
404
  return `'${value}'`;
@@ -382,12 +459,11 @@ var TypeScriptEmitter = class {
382
459
  }
383
460
  }
384
461
  #ref($ref, required) {
385
- const schemaName = pascalcase(sanitizeTag(parseRef($ref).model));
386
- const schema = followRef(this.#spec, $ref);
387
- if (isPrimitiveSchema(schema)) {
388
- return this.handle(schema, required);
462
+ const schemaName = this.#modelName(parseRef($ref).model);
463
+ if (isInlinable(this.#spec, $ref)) {
464
+ return this.handle(followRef(this.#spec, $ref), required);
389
465
  }
390
- return `models.${appendOptional(schemaName, required)}`;
466
+ return appendOptional(this.#refs.model(schemaName), required);
391
467
  }
392
468
  allOf(schemas) {
393
469
  const allOfTypes = schemas.map((sub) => this.handle(sub, true));
@@ -429,7 +505,7 @@ var TypeScriptEmitter = class {
429
505
  string(schema, required) {
430
506
  let type;
431
507
  if (schema.contentEncoding === "binary") {
432
- return appendOptional("Blob", required);
508
+ return appendOptional(this.#refs.global("Blob"), required);
433
509
  }
434
510
  switch (schema.format) {
435
511
  case "date-time":
@@ -439,7 +515,7 @@ var TypeScriptEmitter = class {
439
515
  break;
440
516
  case "binary":
441
517
  case "byte":
442
- type = "Blob";
518
+ type = this.#refs.global("Blob");
443
519
  break;
444
520
  default:
445
521
  type = "string";
@@ -497,19 +573,75 @@ function appendOptional(type, isRequired) {
497
573
  return isRequired ? type : `${type} | undefined`;
498
574
  }
499
575
 
576
+ // packages/typescript/src/lib/folder-index.ts
577
+ import { extname } from "node:path";
578
+ var folders = [
579
+ { folder: "outputs" },
580
+ {
581
+ folder: "inputs",
582
+ ignore: (entry) => entry.isFolder && entry.name === "schemas"
583
+ },
584
+ { folder: "api" },
585
+ {
586
+ folder: "http",
587
+ ignore: (entry) => !rootRuntimeFiles.includes(`http/${entry.name}`)
588
+ },
589
+ { folder: "models" }
590
+ ];
591
+ var root = {
592
+ folder: "",
593
+ ignore: (entry) => entry.name === "agents.ts"
594
+ };
595
+ function indexFiles(paths, contentOf, useTsExtension) {
596
+ const listed = [...paths];
597
+ const indexes = {};
598
+ const content = (path) => path in indexes ? indexes[path] : contentOf(path);
599
+ for (const folder of folders) {
600
+ indexes[`${folder.folder}/index.ts`] = folderExports(
601
+ listed,
602
+ folder,
603
+ content,
604
+ useTsExtension
605
+ );
606
+ }
607
+ if (indexes["inputs/index.ts"] === "") delete indexes["inputs/index.ts"];
608
+ indexes["index.ts"] = folderExports(listed, root, content, useTsExtension);
609
+ return indexes;
610
+ }
611
+ function folderExports(paths, { folder, ignore }, contentOf, useTsExtension) {
612
+ const prefix = folder ? `${folder}/` : "";
613
+ const entries = /* @__PURE__ */ new Map();
614
+ for (const path of paths) {
615
+ if (!path.startsWith(prefix)) continue;
616
+ const [name, ...rest] = path.slice(prefix.length).split("/");
617
+ entries.set(name, { name, isFolder: rest.length > 0 });
618
+ }
619
+ const exports = [];
620
+ for (const entry of [...entries.values()].sort(
621
+ (a, b) => a.name < b.name ? -1 : 1
622
+ )) {
623
+ if (ignore?.(entry)) continue;
624
+ if (entry.isFolder) {
625
+ if (contentOf(`${prefix}${entry.name}/index.ts`)) {
626
+ exports.push(
627
+ `export * from './${entry.name}/index${useTsExtension ? ".ts" : ""}';`
628
+ );
629
+ }
630
+ } else if (entry.name !== "index.ts" && extname(entry.name) === ".ts") {
631
+ exports.push(
632
+ `export * from './${useTsExtension ? entry.name : entry.name.slice(0, -".ts".length)}';`
633
+ );
634
+ }
635
+ }
636
+ return exports.join("\n");
637
+ }
638
+
500
639
  // packages/typescript/src/lib/generator.ts
501
- import { merge, template } from "lodash-es";
502
640
  import { join } from "node:path";
503
- import { camelcase as camelcase4, spinalcase as spinalcase2 } from "stringcase";
504
641
  import {
505
- followRef as followRef3,
506
- isEmpty as isEmpty3,
507
- isRef as isRef3,
508
- resolveRef as resolveRef2,
509
- sortArray
510
- } from "@sdk-it/core";
511
- import {
512
- forEachOperation as forEachOperation3
642
+ forEachOperation as forEachOperation3,
643
+ inputEndpoint as inputEndpoint3,
644
+ operationInputs as operationInputs3
513
645
  } from "@sdk-it/spec";
514
646
 
515
647
  // packages/typescript/src/lib/emitters/zod.ts
@@ -517,16 +649,21 @@ import {
517
649
  followRef as followRef2,
518
650
  isEmpty as isEmpty2,
519
651
  isRef as isRef2,
520
- parseRef as parseRef2,
521
- pascalcase as pascalcase2
652
+ parseRef as parseRef2
522
653
  } from "@sdk-it/core";
523
- import { isPrimitiveSchema as isPrimitiveSchema2, sanitizeTag as sanitizeTag2 } from "@sdk-it/spec";
654
+ import { isInlinable as isInlinable2, isRecursiveRef } from "@sdk-it/spec";
524
655
  var ZodEmitter = class {
525
656
  #generatedRefs = /* @__PURE__ */ new Set();
526
657
  #spec;
658
+ #modelName;
659
+ #refs;
527
660
  #onRef;
528
- constructor(spec, onRef) {
661
+ /** The shared schemas each schema being emitted references, innermost last. */
662
+ #references = [];
663
+ constructor(spec, modelName, refs, onRef) {
529
664
  this.#spec = spec;
665
+ this.#modelName = modelName;
666
+ this.#refs = refs;
530
667
  this.#onRef = onRef;
531
668
  }
532
669
  #object(schema) {
@@ -569,7 +706,7 @@ var ZodEmitter = class {
569
706
  normal(type, schema, required = false, nullable = false) {
570
707
  switch (type) {
571
708
  case "string": {
572
- const defaultVal = (schema["x-zod-type"] === "date" || schema["x-zod-type"] === "coerce-date") && schema.default ? `new Date(${JSON.stringify(schema.default)})` : JSON.stringify(schema.default);
709
+ const defaultVal = (schema["x-zod-type"] === "date" || schema["x-zod-type"] === "coerce-date") && schema.default ? `new ${this.#refs.global("Date")}(${JSON.stringify(schema.default)})` : JSON.stringify(schema.default);
573
710
  return `${this.string(schema)}${this.#suffixes(defaultVal, required, nullable)}`;
574
711
  }
575
712
  case "number":
@@ -591,20 +728,39 @@ var ZodEmitter = class {
591
728
  }
592
729
  }
593
730
  #ref($ref, required) {
594
- const schemaName = pascalcase2(sanitizeTag2(parseRef2($ref).model));
731
+ const schemaName = this.#modelName(parseRef2($ref).model);
595
732
  const schema = followRef2(this.#spec, $ref);
596
- if (isPrimitiveSchema2(schema)) {
597
- const result = this.handle(schema, required);
598
- this.#onRef?.(schemaName, result);
599
- return result;
733
+ if (isInlinable2(this.#spec, $ref)) {
734
+ const inlined = this.emit(schema, required);
735
+ for (const name of inlined.references) {
736
+ this.#references.at(-1)?.add(name);
737
+ }
738
+ this.#onRef?.(schemaName, inlined);
739
+ return inlined.zod;
600
740
  }
741
+ this.#references.at(-1)?.add(schemaName);
601
742
  if (this.#generatedRefs.has(schemaName)) {
602
743
  return schemaName;
603
744
  }
604
745
  this.#generatedRefs.add(schemaName);
605
- this.#onRef?.(schemaName, this.handle(schema, required));
746
+ const body = this.emit(schema, required);
747
+ const modelType = this.#refs.model(schemaName);
748
+ this.#onRef?.(schemaName, {
749
+ zod: isRecursiveRef(this.#spec, $ref) ? `z.lazy((): z.ZodType<${modelType}, ${modelType}> => ${body.zod})` : body.zod,
750
+ references: body.references
751
+ });
606
752
  return schemaName;
607
753
  }
754
+ /** `schema` as zod source, with the shared schemas that source references. */
755
+ emit(schema, required) {
756
+ const references = /* @__PURE__ */ new Set();
757
+ this.#references.push(references);
758
+ try {
759
+ return { zod: this.handle(schema, required), references };
760
+ } finally {
761
+ this.#references.pop();
762
+ }
763
+ }
608
764
  #toIntersection(schemas) {
609
765
  const [left, ...right] = schemas;
610
766
  if (!right.length) {
@@ -636,7 +792,7 @@ var ZodEmitter = class {
636
792
  }
637
793
  return `z.xor([${oneOfSchemas.join(", ")}])${appendOptional2(required)}`;
638
794
  }
639
- enum(type, values) {
795
+ enum(values) {
640
796
  if (values.length === 1) {
641
797
  return `z.literal(${values.join(", ")})`;
642
798
  }
@@ -651,11 +807,12 @@ var ZodEmitter = class {
651
807
  string(schema) {
652
808
  let base = schema["x-zod-type"] === "coerce-string" ? "z.coerce.string()" : "z.string()";
653
809
  if (schema.contentEncoding === "binary") {
654
- base = "z.custom<Blob>()";
810
+ base = `z.custom<${this.#refs.global("Blob")}>()`;
655
811
  return base;
656
812
  }
657
813
  const coerced = schema["x-zod-type"] === "coerce-string";
658
- const withFormat = (format) => coerced ? `${base}.pipe(${format})` : format;
814
+ const limits = stringLimits(schema);
815
+ const withFormat = (format) => coerced ? `${base}.pipe(${format}${limits})` : `${format}${limits}`;
659
816
  switch (schema.format) {
660
817
  case "date-time":
661
818
  case "datetime":
@@ -698,13 +855,14 @@ var ZodEmitter = class {
698
855
  base = withFormat("z.cidrv6()");
699
856
  break;
700
857
  case "phone":
701
- base += " /* or add .regex(...) for phone formats */";
858
+ base += `${limits} /* or add .regex(...) for phone formats */`;
702
859
  break;
703
860
  case "byte":
704
861
  case "binary":
705
- base = "z.custom<Blob>()";
862
+ base = `z.custom<${this.#refs.global("Blob")}>()`;
706
863
  break;
707
864
  default:
865
+ base += limits;
708
866
  break;
709
867
  }
710
868
  return base;
@@ -758,7 +916,7 @@ var ZodEmitter = class {
758
916
  if (schema.enum && Array.isArray(schema.enum)) {
759
917
  const enumVals = schema.enum.map((val) => JSON.stringify(val));
760
918
  const defaultValue = enumVals.includes(JSON.stringify(schema.default)) ? JSON.stringify(schema.default) : void 0;
761
- return `${this.enum(schema.type, enumVals)}${this.#suffixes(defaultValue, required, false)}`;
919
+ return `${this.enum(enumVals)}${this.#suffixes(defaultValue, required, false)}`;
762
920
  }
763
921
  const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
764
922
  if (!types.length) {
@@ -793,83 +951,48 @@ function appendOptional2(isRequired) {
793
951
  function appendDefault(defaultValue) {
794
952
  return defaultValue !== void 0 || typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
795
953
  }
954
+ function stringLimits(schema) {
955
+ let limits = "";
956
+ if (typeof schema.minLength === "number") {
957
+ limits += `.min(${schema.minLength})`;
958
+ }
959
+ if (typeof schema.maxLength === "number") {
960
+ limits += `.max(${schema.maxLength})`;
961
+ }
962
+ if (typeof schema.pattern === "string") {
963
+ limits += `.regex(${regexLiteral(schema.pattern)})`;
964
+ }
965
+ return limits;
966
+ }
967
+ function regexLiteral(pattern) {
968
+ try {
969
+ return `/${new RegExp(pattern).source}/`;
970
+ } catch (error) {
971
+ if (error instanceof SyntaxError) {
972
+ throw new SyntaxError(
973
+ `The pattern ${JSON.stringify(pattern)} is not an ECMA-262 regular expression: ${error.message}`,
974
+ { cause: error }
975
+ );
976
+ }
977
+ throw error;
978
+ }
979
+ }
980
+
981
+ // packages/typescript/src/lib/module-file.ts
982
+ import { spinalcase } from "stringcase";
983
+ function moduleFileName(name) {
984
+ const file = spinalcase(name);
985
+ return file === "index" ? "index-" : file;
986
+ }
796
987
 
797
988
  // packages/typescript/src/lib/sdk.ts
798
- import { camelcase as camelcase3 } from "stringcase";
799
- import { pascalcase as pascalcase3 } from "@sdk-it/core";
989
+ import "@sdk-it/core";
800
990
  import {
801
- sanitizeTag as sanitizeTag3
991
+ statusRange
802
992
  } from "@sdk-it/spec";
803
993
 
804
- // packages/typescript/src/lib/import-utilities.ts
805
- import { removeDuplicates } from "@sdk-it/core";
806
-
807
- // packages/typescript/src/lib/pagination-emit.ts
808
- function describe(p) {
809
- switch (p.type) {
810
- case "offset":
811
- return {
812
- className: "OffsetPagination",
813
- items: p.items,
814
- hasMore: p.hasMore,
815
- statusCode: p.statusCode,
816
- sameInputNames: p.limitParamName === "limit" && p.offsetParamName === "offset",
817
- initialOverride: `limit: input.${p.limitParamName}, offset: input.${p.offsetParamName}`,
818
- nextPageMapping: `${p.offsetParamName}: nextPageParams.offset, ${p.limitParamName}: nextPageParams.limit`
819
- };
820
- case "cursor":
821
- return {
822
- className: "CursorPagination",
823
- items: p.items,
824
- hasMore: p.hasMore,
825
- statusCode: p.statusCode,
826
- sameInputNames: p.cursorParamName === "cursor",
827
- initialOverride: `cursor: input[${JSON.stringify(p.cursorParamName)}]`,
828
- nextPageMapping: `[${JSON.stringify(p.cursorParamName)}]: nextPageParams.cursor ?? input[${JSON.stringify(p.cursorParamName)}]`
829
- };
830
- case "page":
831
- return {
832
- className: "Pagination",
833
- items: p.items,
834
- hasMore: p.hasMore,
835
- statusCode: p.statusCode,
836
- sameInputNames: p.pageNumberParamName === "page" && p.pageSizeParamName === "pageSize",
837
- initialOverride: `page: input.${p.pageNumberParamName}, pageSize: input.${p.pageSizeParamName}`,
838
- nextPageMapping: `${p.pageNumberParamName}: nextPageParams.page, ${p.pageSizeParamName}: nextPageParams.pageSize`
839
- };
840
- }
841
- throw new Error(`Unknown pagination type: ${p.type}`);
842
- }
843
- function paginationOperation(pagination) {
844
- const shape = describe(pagination);
845
- const initialParams = shape.sameInputNames ? "input" : `{...input, ${shape.initialOverride}}`;
846
- const nextPageParams = shape.sameInputNames && pagination.type !== "cursor" ? "...nextPageParams" : shape.nextPageMapping;
847
- const nextCursor = pagination.type === "cursor" && pagination.nextCursor ? `result.data${pagination.nextCursor.split(".").map((key) => `?.[${JSON.stringify(key)}]`).join("")}` : void 0;
848
- return `{
849
- const pagination = new ${shape.className}(${initialParams}, async (nextPageParams, requestOptions) => {
850
- const dispatcher = new Dispatcher(options.interceptors, options.fetch);
851
- const result = await dispatcher.send(
852
- this.toRequest({...input, ${nextPageParams}}),
853
- this.output,
854
- requestOptions?.signal ?? options.signal,
855
- );
856
- if (result.status !== ${shape.statusCode}) { throw result; }
857
- ${nextCursor ? `const nextCursor = ${nextCursor};` : ""}
858
- return {
859
- data: result.data.${shape.items},
860
- meta: {
861
- hasMore: Boolean(result.data.${shape.hasMore}),
862
- ${nextCursor ? '...(typeof nextCursor === "string" ? { nextCursor } : {}),' : ""}
863
- },
864
- };
865
- }, options.signal ? { signal: options.signal } : {});
866
- await pagination.getNextPage();
867
- return pagination
868
- }}`;
869
- }
870
-
871
994
  // packages/typescript/src/lib/status-map.ts
872
- var status_map_default = {
995
+ var statusMap = {
873
996
  "200": "Ok",
874
997
  "201": "Created",
875
998
  "202": "Accepted",
@@ -894,80 +1017,125 @@ var status_map_default = {
894
1017
  "503": "ServiceUnavailable",
895
1018
  "504": "GatewayTimeout"
896
1019
  };
1020
+ var status_map_default = statusMap;
897
1021
 
898
1022
  // packages/typescript/src/lib/sdk.ts
899
- function toEndpoint(groupName, specOperation, operation) {
900
- const schemaName = camelcase3(`${specOperation.operationId} schema`);
901
- const schemaRef = `${camelcase3(groupName)}.${schemaName}`;
1023
+ function toEndpoint(groupName, specOperation, operation, modelName, refs) {
902
1024
  const schemas = [];
903
1025
  specOperation.responses ??= {};
904
1026
  const outputs = Object.keys(specOperation.responses).map(
905
- (status) => toHttpOutput(status, specOperation.responses[status])
1027
+ (status) => toHttpOutput(status, specOperation.responses[status], modelName, refs)
906
1028
  );
907
- const addTypeParser = Object.keys(operation.schemas).length > 1;
908
- for (const type in operation.schemas ?? {}) {
909
- let typePrefix = "";
910
- if (addTypeParser && type !== "json") {
911
- typePrefix = `${type} `;
912
- }
913
- const paths = inputToPath(specOperation, operation.inputs);
914
- const endpoint = `${typePrefix}${operation.method.toUpperCase()} ${operation.path}`;
1029
+ for (const route of operation.inputs) {
1030
+ const schemaRef = refs.input(groupName, route.schemaName);
1031
+ const key = refs.located(`"${route.endpoint}"`, [
1032
+ "paths",
1033
+ operation.path,
1034
+ operation.method
1035
+ ]);
915
1036
  schemas.push(
916
- `"${endpoint}": {
917
- security: ${JSON.stringify(specOperation.security ?? [])} as readonly Record<string, readonly string[]>[],
918
- schema: ${schemaRef}${addTypeParser ? `.${type}` : ""},
1037
+ `${key}: {
1038
+ security: ${JSON.stringify(specOperation.security)} as readonly ${refs.global("Record")}<string, readonly string[]>[],
1039
+ schema: ${schemaRef},
919
1040
  output:[${outputs.join(",")}],
920
- toRequest(input: z.input<typeof ${schemaRef}${addTypeParser ? `.${type}` : ""}>) {
921
- return toRequest('${endpoint}', ${operation.outgoingContentType || "empty"}(input, {
922
- inputHeaders: [${paths.inputHeaders}],
923
- inputQuery: [${paths.inputQuery}],
924
- inputBody: [${paths.inputBody}],
925
- inputParams: [${paths.inputParams}],
926
- }));},
927
- async dispatch(input: z.input<typeof ${schemaRef}${addTypeParser ? `.${type}` : ""}>,options: {
928
- signal?: AbortSignal;
929
- interceptors: Interceptor[];
930
- fetch: z.infer<typeof fetchType>;
931
- })${specOperation["x-pagination"] ? paginationOperation(specOperation["x-pagination"]) : normalOperation()}`
1041
+ toRequest(input: z.input<typeof ${schemaRef}>, baseUrl: string) {
1042
+ return ${refs.runtime("toRequest")}('${operation.method.toUpperCase()}', '${operation.path}', ${refs.runtime(route.input.encoding)}(input, {
1043
+ contentType: ${JSON.stringify(route.input.contentType)},
1044
+ inputHeaders: [${quoted(route.input.header)}],
1045
+ inputQuery: [${quoted(route.input.query)}],
1046
+ inputBody: [${quoted(route.input.body)}],
1047
+ inputParams: [${quoted(route.input.path)}],
1048
+ }), baseUrl);},
1049
+ async dispatch(input: z.output<typeof ${schemaRef}>,options: {
1050
+ signal?: ${refs.global("AbortSignal")};
1051
+ interceptors: ${refs.runtime("Interceptor")}[];
1052
+ fetch: z.infer<typeof ${refs.runtime("fetchType")}>;
1053
+ baseUrl: string;
1054
+ })${normalOperation(specOperation["x-pagination"], refs)}`
932
1055
  );
933
1056
  }
934
1057
  return { schemas };
935
1058
  }
936
- function normalOperation() {
1059
+ function normalOperation(pagination, refs) {
937
1060
  return `{
938
- const dispatcher = new Dispatcher(options.interceptors, options.fetch);
939
- return dispatcher.send(this.toRequest(input), this.output, options?.signal);
940
- },
1061
+ const dispatcher = new ${refs.runtime("Dispatcher")}(options.interceptors, options.fetch);
1062
+ return dispatcher.send(this.toRequest(input, options.baseUrl), this.output, options?.signal);
1063
+ },${pagination ? `
1064
+ pagination: ${JSON.stringify(runtimePagination(pagination))} as const,` : ""}
941
1065
  }`;
942
1066
  }
943
- var bodyParser = {
944
- json: "buffered",
945
- text: "buffered",
946
- binary: "buffered",
947
- empty: "bodyless",
948
- stream: "chunked",
949
- sse: "sse"
950
- };
951
- function toHttpOutput(status, response) {
952
- const body = response["x-body"];
953
- const type = status.endsWith("XX") ? "http.APIError" : `http.${status_map_default[status] || "APIResponse"}`;
1067
+ function runtimePagination(pagination) {
1068
+ const { items, hasMore, statusCode } = pagination;
1069
+ switch (pagination.type) {
1070
+ case "offset":
1071
+ return {
1072
+ type: pagination.type,
1073
+ offsetParamName: pagination.offsetParamName,
1074
+ limitParamName: pagination.limitParamName,
1075
+ items,
1076
+ hasMore,
1077
+ statusCode,
1078
+ start: pagination.start
1079
+ };
1080
+ case "page":
1081
+ return {
1082
+ type: pagination.type,
1083
+ pageNumberParamName: pagination.pageNumberParamName,
1084
+ pageSizeParamName: pagination.pageSizeParamName,
1085
+ items,
1086
+ hasMore,
1087
+ statusCode,
1088
+ start: pagination.start
1089
+ };
1090
+ case "cursor":
1091
+ return {
1092
+ type: pagination.type,
1093
+ cursorParamName: pagination.cursorParamName,
1094
+ items,
1095
+ hasMore,
1096
+ statusCode,
1097
+ nextCursor: pagination.nextCursor
1098
+ };
1099
+ }
1100
+ }
1101
+ function bodyParser(body, refs) {
1102
+ switch (body) {
1103
+ case "json":
1104
+ case "text":
1105
+ case "binary":
1106
+ return `${refs.runtime("buffered")}(${JSON.stringify(body)})`;
1107
+ case "empty":
1108
+ return refs.runtime("bodyless");
1109
+ case "stream":
1110
+ return refs.runtime("chunked");
1111
+ case "sse":
1112
+ return refs.runtime("sse");
1113
+ }
1114
+ }
1115
+ function toHttpOutput(status, response, modelName, refs) {
954
1116
  if (status === "204") {
955
- return type;
1117
+ return refs.status("NoContent");
956
1118
  }
957
- const data = dataType(status, response);
958
- const parser = bodyParser[body];
959
- return parser === "buffered" ? `${type}<${data}>` : `{type: ${type}<${data}>, parser: ${parser}}`;
1119
+ const data = dataType(status, response, modelName, refs);
1120
+ const parser = bodyParser(response["x-body"], refs);
1121
+ const range = statusRange(status);
1122
+ if (range) {
1123
+ const type2 = refs.status(range === "2XX" ? "APIResponse" : "APIError");
1124
+ return `{type: ${type2}<${data}, ${refs.status("RangeStatus")}<'${range}'>>, parser: ${parser}, range: '${range}' as const}`;
1125
+ }
1126
+ const type = refs.status(status_map_default[status] || "APIResponse");
1127
+ return `{type: ${type}<${data}>, parser: ${parser}}`;
960
1128
  }
961
- function dataType(status, response) {
1129
+ function dataType(status, response, modelName, refs) {
962
1130
  switch (response["x-body"]) {
963
1131
  case "empty":
964
1132
  return "null";
965
1133
  case "stream":
966
- return "ReadableStream";
1134
+ return refs.global("ReadableStream");
967
1135
  case "sse":
968
- return "SSEListener";
1136
+ return refs.runtime("SSEListener");
969
1137
  default:
970
- return `outputs.${pascalcase3(sanitizeTag3(outputName(status, response)))}`;
1138
+ return refs.model(modelName(outputName(status, response)));
971
1139
  }
972
1140
  }
973
1141
  function outputName(status, response) {
@@ -979,143 +1147,66 @@ function outputName(status, response) {
979
1147
  }
980
1148
  return name;
981
1149
  }
982
- function inputToPath(operation, inputs) {
983
- const inputHeaders = [];
984
- const inputQuery = [];
985
- const inputBody = [];
986
- const inputParams = [];
987
- for (const [name, prop] of Object.entries(inputs)) {
988
- if (prop.in === "headers" || prop.in === "header") {
989
- inputHeaders.push(`"${name}"`);
990
- } else if (prop.in === "query") {
991
- inputQuery.push(`"${name}"`);
992
- } else if (prop.in === "body") {
993
- inputBody.push(`"${name}"`);
994
- } else if (prop.in === "path") {
995
- inputParams.push(`"${name}"`);
996
- } else {
997
- throw new Error(
998
- `Unknown source ${prop.in} in ${name} ${JSON.stringify(
999
- prop
1000
- )} in ${operation.operationId}`
1001
- );
1002
- }
1003
- }
1004
- return {
1005
- inputHeaders,
1006
- inputQuery,
1007
- inputBody,
1008
- inputParams
1009
- };
1150
+ function quoted(names) {
1151
+ return names.map((name) => `"${name}"`);
1010
1152
  }
1011
1153
 
1012
- // packages/typescript/src/lib/styles/github/endpoints.txt
1013
- var endpoints_default = "type DispatchReturn<E extends keyof typeof schemas> = Awaited<\n ReturnType<(typeof schemas)[E]['dispatch']>\n>;\n\nexport type InferData<E extends keyof typeof schemas> =\n DispatchReturn<E> extends APIResponse<infer D> ? D : DispatchReturn<E>;\n\ntype EndpointOutput<K extends keyof typeof schemas> = Extract<\n Unionize<(typeof schemas)[K]['output']>,\n SuccessfulResponse\n>;\n\ntype EndpointError<K extends keyof typeof schemas> = Extract<\n Unionize<(typeof schemas)[K]['output']>,\n ProblematicResponse\n>;\n\nexport type Endpoints = {\n [E in keyof typeof schemas]: {\n input: z.input<(typeof schemas)[E]['schema']>;\n output: InferData<E>;\n error: EndpointError<E> | ParseError<(typeof schemas)[E]['schema']>;\n };\n};\n";
1014
-
1015
1154
  // packages/typescript/src/lib/generator.ts
1016
- function coearceRequestInput(spec, operation, type) {
1017
- let objectSchema = resolveRef2(
1018
- spec,
1019
- operation.requestBody.content[type].schema
1020
- );
1021
- const xProperties = objectSchema["x-properties"] ?? {};
1022
- const xRequired = objectSchema["x-required"] ?? [];
1023
- if (type === "application/empty") {
1024
- objectSchema = {
1025
- type: "object",
1026
- additionalProperties: isEmpty3(xProperties)
1027
- };
1028
- } else {
1029
- if (objectSchema.type !== "object") {
1030
- objectSchema = {
1031
- type: "object",
1032
- required: [operation.requestBody.required ? "$body" : ""],
1033
- properties: {
1034
- $body: objectSchema
1035
- }
1036
- };
1037
- }
1038
- }
1039
- return {
1040
- objectSchema,
1041
- xProperties,
1042
- xRequired
1043
- };
1044
- }
1045
- function generateCode(config) {
1155
+ function operationFragments(config) {
1046
1156
  const commonZod = /* @__PURE__ */ new Map();
1047
- const commonZodImports = [];
1048
- const zodDeserialzer = new ZodEmitter(config.spec, (model, schema) => {
1049
- commonZod.set(model, schema);
1050
- commonZodImports.push({
1051
- defaultImport: void 0,
1052
- isTypeOnly: true,
1053
- moduleSpecifier: `./${config.makeImport(model)}`,
1054
- namedImports: [{ isTypeOnly: true, name: model }],
1055
- namespaceImport: void 0
1056
- });
1057
- });
1157
+ const zodDeserialzer = new ZodEmitter(
1158
+ config.spec,
1159
+ config.modelName,
1160
+ config.zodRefs,
1161
+ (model, schema) => {
1162
+ commonZod.set(model, schema);
1163
+ }
1164
+ );
1058
1165
  const groups = {};
1059
1166
  const endpoints = {};
1060
1167
  forEachOperation3(config.spec, (entry, operation) => {
1061
- console.log(`Processing ${entry.method} ${entry.path}`);
1062
1168
  groups[entry.tag] ??= [];
1063
1169
  endpoints[entry.tag] ??= [];
1064
- const schemas = {};
1065
- const shortContenTypeMap = {
1066
- "application/json": "json",
1067
- "application/*+json": "json",
1068
- // type specific of json like application/vnd.api+json (from the generation pov it shouldn't matter)
1069
- "text/json": "json",
1070
- // non standard - later standardized to application/json
1071
- "application/x-www-form-urlencoded": "urlencoded",
1072
- "multipart/form-data": "formdata",
1073
- "application/xml": "xml",
1074
- "text/plain": "text"
1075
- };
1076
- for (const type in operation.requestBody.content) {
1077
- schemas[shortContenTypeMap[type]] = zodDeserialzer.handle(
1078
- operationSchema(config.spec, operation, type),
1079
- true
1080
- );
1081
- }
1082
- const details = buildInput(config.spec, operation);
1083
- const endpoint = toEndpoint(entry.tag, operation, {
1084
- method: entry.method,
1085
- path: entry.path,
1086
- operationId: operation.operationId,
1087
- schemas,
1088
- outgoingContentType: details.outgoingContentType,
1089
- inputs: details.inputs
1090
- });
1091
- endpoints[entry.tag].push(endpoint);
1092
- groups[entry.tag].push({
1170
+ const endpoint = `${entry.method.toUpperCase()} ${entry.path}`;
1171
+ const route = {
1093
1172
  method: entry.method,
1094
1173
  path: entry.path,
1095
1174
  operationId: operation.operationId,
1096
- schemas,
1097
- outgoingContentType: details.outgoingContentType,
1098
- inputs: details.inputs
1099
- });
1175
+ inputs: operationInputs3(config.spec, operation).map((input) => ({
1176
+ endpoint: inputEndpoint3(endpoint, input),
1177
+ schemaName: inputSchemaName(operation.operationId, input),
1178
+ ...zodDeserialzer.emit(input.schema, true),
1179
+ input
1180
+ }))
1181
+ };
1182
+ endpoints[entry.tag].push(
1183
+ ...toEndpoint(
1184
+ entry.tag,
1185
+ operation,
1186
+ route,
1187
+ config.modelName,
1188
+ config.endpointRefs
1189
+ ).schemas
1190
+ );
1191
+ groups[entry.tag].push(route);
1192
+ });
1193
+ return { groups, commonZod, endpoints };
1194
+ }
1195
+ function generateCode(config) {
1196
+ const { groups, commonZod, endpoints } = operationFragments({
1197
+ spec: config.spec,
1198
+ modelName: config.modelName,
1199
+ zodRefs: inputFileReferences,
1200
+ endpointRefs: fileReferences("outputs")
1100
1201
  });
1101
1202
  const allSchemas = Object.keys(endpoints).map((it) => ({
1102
- import: `import ${camelcase4(it)} from './${config.makeImport(spinalcase2(it))}';`,
1103
- use: ` ...${camelcase4(it)}`
1203
+ import: `import ${groupIdentifier(it)} from './${config.makeImport(moduleFileName(it))}';`,
1204
+ use: ` ...${groupIdentifier(it)}`
1104
1205
  }));
1105
1206
  return {
1106
1207
  groups,
1107
1208
  commonZod,
1108
1209
  endpoints: {
1109
- [join("api", "endpoints.ts")]: `
1110
- import type z from 'zod';
1111
- import type { ParseError } from '${config.makeImport("../http/parser")}';
1112
- import type { ProblematicResponse, SuccessfulResponse, APIResponse } from '${config.makeImport(
1113
- "../http/response"
1114
- )}';
1115
-
1116
- import schemas from '${config.makeImport("./schemas")}';
1117
- import type { Unionize } from '${config.makeImport("../http/dispatcher")}';
1118
- ${template(endpoints_default)({})}`,
1119
1210
  [`${join("api", "schemas.ts")}`]: `${allSchemas.map((it) => it.import).join("\n")}
1120
1211
 
1121
1212
  export default {
@@ -1124,181 +1215,193 @@ ${allSchemas.map((it) => it.use).join(",\n")}
1124
1215
 
1125
1216
  `.trim(),
1126
1217
  ...Object.fromEntries(
1127
- Object.entries(endpoints).map(([name, endpoint]) => {
1128
- const operations = endpoint.flatMap((it) => it.schemas).join(",\n");
1218
+ Object.entries(endpoints).flatMap(([name, entries]) => {
1219
+ const operations = entries.join(",\n");
1129
1220
  return [
1130
1221
  [
1131
- join("api", `${spinalcase2(name)}.ts`),
1222
+ join("api", `${moduleFileName(name)}.ts`),
1132
1223
  `${[
1133
- `import z from 'zod';`,
1224
+ `import { z } from 'zod';`,
1134
1225
  `import * as http from '${config.makeImport("../http/response")}';`,
1135
1226
  ...operations.includes("outputs.") ? [
1136
1227
  `import * as outputs from '${config.makeImport("../outputs/index")}';`
1137
1228
  ] : [],
1138
- `import { toRequest, json, urlencoded, empty, formdata, type HeadersInit } from '${config.makeImport("../http/request")}';`,
1229
+ `import { toRequest, json, urlencoded, formdata, text, binary, empty, type HeadersInit } from '${config.makeImport("../http/request")}';`,
1139
1230
  `import { chunked, buffered, bodyless } from "${config.makeImport("../http/parse-response")}";`,
1140
1231
  `import { sse, type SSEListener } from "${config.makeImport("../http/sse")}";`,
1141
- `import * as ${camelcase4(name)} from '../inputs/${config.makeImport(spinalcase2(name))}';`,
1142
- `import { createBaseUrlInterceptor, createHeadersInterceptor, type Interceptor } from '${config.makeImport("../http/interceptors")}';`,
1143
- `import { Dispatcher, fetchType, type InstanceType } from '${config.makeImport("../http/dispatcher")}';`,
1144
- `import { Pagination, OffsetPagination, CursorPagination } from "${config.makeImport("../pagination/index")}";`
1232
+ `import * as ${groupIdentifier(name)} from '../inputs/${config.makeImport(moduleFileName(name))}';`,
1233
+ `import { createHeadersInterceptor, type Interceptor } from '${config.makeImport("../http/interceptors")}';`,
1234
+ `import { Dispatcher, fetchType, type InstanceType } from '${config.makeImport("../http/dispatcher")}';`
1145
1235
  ].join("\n")}
1146
1236
  export default {
1147
1237
  ${operations}
1148
1238
  }`
1149
1239
  ]
1150
1240
  ];
1151
- }).flat()
1241
+ })
1152
1242
  )
1153
1243
  }
1154
1244
  };
1155
1245
  }
1156
- function toProps(spec, schemaOrRef, aggregator = []) {
1157
- if (isRef3(schemaOrRef)) {
1158
- const schema = followRef3(spec, schemaOrRef.$ref);
1159
- return toProps(spec, schema, aggregator);
1160
- } else if (schemaOrRef.type === "object") {
1161
- for (const [name] of Object.entries(schemaOrRef.properties ?? {})) {
1162
- aggregator.push(name);
1246
+
1247
+ // packages/typescript/src/lib/model-name.ts
1248
+ import { pascalcase as pascalcase2 } from "@sdk-it/core";
1249
+ import { sanitizeTag as sanitizeTag2 } from "@sdk-it/spec";
1250
+ function createModelNamer(clientName2) {
1251
+ const reserved = /* @__PURE__ */ new Set([
1252
+ ...runtimeRootExports.map(({ name }) => name),
1253
+ ...securityTypeExports,
1254
+ ...clientExports(clientName2)
1255
+ ]);
1256
+ const owners = /* @__PURE__ */ new Map();
1257
+ return (schemaName) => {
1258
+ const base = pascalcase2(sanitizeTag2(schemaName));
1259
+ const name = reserved.has(base) ? `${base}_` : base;
1260
+ const owner = owners.getOrInsert(name, schemaName);
1261
+ if (owner !== schemaName) {
1262
+ throw new TypeError(
1263
+ `Schemas "${owner}" and "${schemaName}" both become the TypeScript type ${name}; rename one of them in the spec`
1264
+ );
1163
1265
  }
1164
- return void 0;
1165
- } else if ((schemaOrRef.type === "array" || schemaOrRef.type?.includes("array")) && schemaOrRef.items) {
1166
- toProps(spec, schemaOrRef.items, aggregator);
1167
- return void 0;
1168
- } else if (schemaOrRef.allOf) {
1169
- for (const it of schemaOrRef.allOf) {
1170
- toProps(spec, it, aggregator);
1266
+ return name;
1267
+ };
1268
+ }
1269
+
1270
+ // packages/typescript/src/lib/one-module.ts
1271
+ var moduleReferences = {
1272
+ model: (typeName) => typeName,
1273
+ input: (_group, schemaName) => schemaName,
1274
+ status: (className) => `\0${className}\0`,
1275
+ runtime: (name) => `\0${name}\0`,
1276
+ global: (name) => `\0globalThis.${name}\0`,
1277
+ located: (text, location) => `\0@${JSON.stringify(location)}\0${text}\0`
1278
+ };
1279
+ function assembleModule(parts) {
1280
+ const specNames = /* @__PURE__ */ new Set([
1281
+ ...parts.commonZod.keys(),
1282
+ ...parts.inputs.map(({ name }) => name),
1283
+ ...parts.models.map(({ typeName }) => typeName),
1284
+ ...parts.clientNames,
1285
+ "__routes"
1286
+ ]);
1287
+ const names = runtimeNames(specNames);
1288
+ const declaredName = new Map(
1289
+ runtime_module_default.bindings.flatMap(
1290
+ (binding, index) => binding.kind === "declared" ? [[binding.name, names[index]]] : []
1291
+ )
1292
+ );
1293
+ const nameOf = (name, global) => {
1294
+ if (global) {
1295
+ return specNames.has(name) ? `globalThis.${name}` : name;
1171
1296
  }
1172
- return void 0;
1173
- } else if (schemaOrRef.oneOf) {
1174
- for (const it of schemaOrRef.oneOf) {
1175
- toProps(spec, it, aggregator);
1297
+ const finalName = declaredName.get(name);
1298
+ if (finalName === void 0) {
1299
+ throw new TypeError(`The runtime declares no ${name}`);
1176
1300
  }
1177
- return void 0;
1178
- } else if (schemaOrRef.anyOf) {
1179
- for (const it of schemaOrRef.anyOf) {
1180
- toProps(spec, it, aggregator);
1301
+ return finalName;
1302
+ };
1303
+ const values = runtimeRootExports.filter(({ type }) => !type).map(({ name }) => name);
1304
+ const types = runtimeRootExports.filter(({ type }) => type).map(({ name }) => name);
1305
+ const pieces = [
1306
+ externalImports(names),
1307
+ runtimeText(names, specNames),
1308
+ ...[...parts.commonZod].map(([name, { zod }]) => `const ${name} = ${zod};`),
1309
+ ...parts.inputs.map(({ name, zod }) => `export const ${name} = ${zod};`),
1310
+ ...parts.models.map(
1311
+ ({ typeName, doc, type, location }) => `${doc}export type ${location ? moduleReferences.located(typeName, location) : typeName} = ${type};`
1312
+ ),
1313
+ `const __routes = {
1314
+ ${parts.endpoints.join(",\n")}
1315
+ };`,
1316
+ parts.client,
1317
+ `export { ${[...values, ...parts.runtimeExports].join(", ")} };`,
1318
+ `export type { ${[...types, ...parts.runtimeTypeExports].join(", ")} };`
1319
+ ];
1320
+ let text = "";
1321
+ const spans = [];
1322
+ for (const [index, piece] of pieces.entries()) {
1323
+ if (index > 0) text += "\n";
1324
+ let cursor = 0;
1325
+ for (const mark of piece.matchAll(marks)) {
1326
+ text += piece.slice(cursor, mark.index);
1327
+ const [, location, located, global, name] = mark;
1328
+ if (location !== void 0) {
1329
+ const start = text.length;
1330
+ text += located;
1331
+ spans.push({ start, end: text.length, location: JSON.parse(location) });
1332
+ } else {
1333
+ text += nameOf(name, global !== void 0);
1334
+ }
1335
+ cursor = mark.index + mark[0].length;
1181
1336
  }
1182
- return void 0;
1337
+ text += piece.slice(cursor);
1183
1338
  }
1184
- console.warn("Unknown schema in body", schemaOrRef);
1185
- return void 0;
1186
- }
1187
- function bodyInputs(spec, ctSchema) {
1188
- const props = [];
1189
- toProps(spec, ctSchema, props);
1190
- return (
1191
- // TODO: should we preproccess the sort at spec level instead of generator's?
1192
- sortArray(props).reduce(
1193
- (acc, prop) => ({
1194
- ...acc,
1195
- [prop]: {
1196
- in: "body",
1197
- schema: ""
1198
- }
1199
- }),
1200
- {}
1201
- )
1202
- );
1339
+ return { text, spans };
1203
1340
  }
1204
- var contentTypeSerializerMap = {
1205
- "application/json": "json",
1206
- "application/x-www-form-urlencoded": "urlencoded",
1207
- "multipart/form-data": "formdata",
1208
- "application/xml": "xml",
1209
- "text/plain": "text",
1210
- "application/empty": "empty"
1211
- };
1212
- var serializerContentTypeMap = Object.fromEntries(
1213
- Object.entries(contentTypeSerializerMap).map(([k, v]) => [v, k])
1214
- );
1215
- function buildInput(spec, operation) {
1216
- const inputs = {};
1217
- let outgoingContentType = "empty";
1218
- for (const [ct, value] of Object.entries(contentTypeSerializerMap)) {
1219
- if (operation.requestBody.content[ct]) {
1220
- outgoingContentType = value;
1221
- const { objectSchema, xProperties } = coearceRequestInput(
1222
- spec,
1223
- operation,
1224
- ct
1225
- );
1226
- for (const [name, prop] of Object.entries(xProperties)) {
1227
- inputs[name] = {
1228
- in: prop["x-in"],
1229
- schema: ""
1230
- };
1231
- }
1232
- Object.assign(inputs, bodyInputs(spec, objectSchema));
1233
- break;
1341
+ var marks = /\0@([^\0]*)\0([^\0]*)\0|\0(globalThis\.)?([A-Za-z_$][\w$]*)\0/g;
1342
+ function runtimeNames(specNames) {
1343
+ const ownNames = new Set(runtime_module_default.bindings.map(({ name }) => name));
1344
+ const taken = new Set(specNames);
1345
+ const names = runtime_module_default.bindings.map(({ name }) => name);
1346
+ const order = [...runtime_module_default.bindings.keys()].sort(
1347
+ (a, b) => rank(runtime_module_default.bindings[a]) - rank(runtime_module_default.bindings[b])
1348
+ );
1349
+ for (const index of order) {
1350
+ const own = runtime_module_default.bindings[index].name;
1351
+ let name = own;
1352
+ while (taken.has(name) || name !== own && ownNames.has(name)) {
1353
+ name = `__${name}`;
1234
1354
  }
1355
+ taken.add(name);
1356
+ names[index] = name;
1235
1357
  }
1236
- return {
1237
- inputs,
1238
- outgoingContentType,
1239
- ct: serializerContentTypeMap[outgoingContentType]
1240
- };
1358
+ return names;
1241
1359
  }
1242
- function operationSchema(ir, operation, type) {
1243
- const { objectSchema, xProperties, xRequired } = coearceRequestInput(
1244
- ir,
1245
- operation,
1246
- type
1247
- );
1248
- const additionalProperties = {};
1249
- for (const [name, prop] of Object.entries(xProperties)) {
1250
- additionalProperties[name] = {
1251
- name,
1252
- required: xRequired?.includes(name),
1253
- schema: prop,
1254
- in: prop["x-in"]
1255
- };
1256
- }
1257
- return merge({}, objectSchema, {
1258
- required: Object.values(additionalProperties).filter((p) => p.required).map((p) => p.name),
1259
- properties: Object.entries(additionalProperties).reduce(
1260
- (acc, [, p]) => ({ ...acc, [p.name]: p.schema }),
1261
- {}
1262
- )
1263
- });
1360
+ function rank(binding) {
1361
+ return binding.kind === "declared" ? 0 : 1;
1362
+ }
1363
+ function externalImports(names) {
1364
+ return runtime_module_default.bindings.flatMap((binding, index) => {
1365
+ if (binding.kind !== "external") return [];
1366
+ const local = names[index];
1367
+ const name = local === binding.name ? local : `${binding.name} as ${local}`;
1368
+ return [`import { ${name} } from '${binding.module}';`];
1369
+ }).join("\n");
1370
+ }
1371
+ function runtimeText(names, specNames) {
1372
+ const edits = [];
1373
+ for (const [index, binding] of runtime_module_default.bindings.entries()) {
1374
+ const name = names[index];
1375
+ if (name === binding.name) continue;
1376
+ const length = binding.name.length;
1377
+ for (const at of binding.occurrences)
1378
+ edits.push({ at, length, text: name });
1379
+ for (const at of binding.shorthands) {
1380
+ edits.push({ at, length, text: `${binding.name}: ${name}` });
1381
+ }
1382
+ }
1383
+ for (const global of runtime_module_default.globals) {
1384
+ if (!specNames.has(global.name)) continue;
1385
+ for (const at of global.occurrences) {
1386
+ edits.push({ at, length: 0, text: "globalThis." });
1387
+ }
1388
+ }
1389
+ edits.sort((a, b) => a.at - b.at);
1390
+ let text = "";
1391
+ let cursor = 0;
1392
+ for (const { at, length, text: replacement } of edits) {
1393
+ text += runtime_module_default.text.slice(cursor, at) + replacement;
1394
+ cursor = at + length;
1395
+ }
1396
+ return text + runtime_module_default.text.slice(cursor);
1264
1397
  }
1265
-
1266
- // packages/typescript/src/lib/http/dispatcher.txt
1267
- var dispatcher_default = "export type Unionize<T> = T extends [infer Single extends OutputType]\n ? InstanceType<Single>\n : T extends readonly [...infer Tuple extends OutputType[]]\n ? { [I in keyof Tuple]: InstanceType<Tuple[I]> }[number]\n : never;\n\nexport type InstanceType<T> =\n T extends Type<infer U>\n ? U\n : T extends { type: Type<infer U> }\n ? U\n : T extends Array<unknown>\n ? Unionize<T>\n : never;\n\ntype ResponseData<T extends OutputType[]> =\n Extract<InstanceType<T>, SuccessfulResponse> extends SuccessfulResponse<\n infer P\n >\n ? P\n : unknown;\n\ntype ResponseMapper<T extends OutputType[], R> = (data: ResponseData<T>) => R;\n\nexport interface Type<T> {\n new (...args: any[]): T;\n}\nexport type Parser = (\n response: Response,\n) => Promise<unknown> | ReadableStream<any> | SSEListener;\nexport type OutputType =\n | Type<APIResponse>\n | { parser: Parser; type: Type<APIResponse> };\n\n// Bare z.custom (no predicate) on purpose: Request/Response from another\n// realm (undici vs global fetch) fail instanceof checks. The output is\n// typed as a Promise directly \u2014 zod 4 deprecated z.promise.\nexport const fetchType = z\n .function({\n input: [z.custom<Request>()],\n output: z.custom<Promise<Response>>(),\n })\n .optional();\n\nexport async function parse<T extends OutputType[]>(\n outputs: T,\n response: Response,\n): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\nexport async function parse<T extends OutputType[], R>(\n outputs: T,\n response: Response,\n mapper: ResponseMapper<T, R>,\n): Promise<RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>>;\nexport async function parse<T extends OutputType[], R = ResponseData<T>>(\n outputs: T,\n response: Response,\n mapper?: ResponseMapper<T, R>,\n) {\n let output: typeof APIResponse | typeof APIError | null = null;\n let parser: Parser = buffered;\n for (const outputType of outputs) {\n const type = 'parser' in outputType ? outputType.type : outputType;\n if (\n (isTypeOf(type, APIResponse) || isTypeOf(type, APIError)) &&\n response.status === type.status\n ) {\n output = type;\n if ('parser' in outputType) {\n parser = outputType.parser;\n }\n break;\n }\n }\n\n if (response.ok) {\n const data = (await parser(response)) as ResponseData<T>;\n const mapped = mapper ? mapper(data) : data;\n const apiresponse = (output || APIResponse).create(\n response.status,\n response.headers,\n mapped,\n );\n\n return apiresponse as Extract<Unionize<T>, SuccessfulResponse<unknown>>;\n }\n\n const failure = output && isTypeOf(output, APIError) ? output : APIError;\n throw failure.create(\n response.status,\n response.headers,\n await parser(response),\n );\n}\n\nexport function isTypeOf<T extends Type<APIResponse>>(\n instance: any,\n baseType: T,\n): instance is T {\n if (instance === baseType) {\n return true;\n }\n const prototype = Object.getPrototypeOf(instance);\n if (prototype === null) {\n return false;\n }\n return isTypeOf(prototype, baseType);\n}\n\nexport class Dispatcher {\n #interceptors: Interceptor[] = [];\n #fetch: z.infer<typeof fetchType>;\n constructor(interceptors: Interceptor[], fetch?: z.infer<typeof fetchType>) {\n this.#interceptors = interceptors;\n this.#fetch = fetch;\n }\n\n async send<T extends OutputType[]>(\n config: RequestConfig,\n outputs: T,\n signal?: AbortSignal,\n ): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\n async send<T extends OutputType[], R>(\n config: RequestConfig,\n outputs: T,\n signal: AbortSignal | undefined,\n mapper: ResponseMapper<T, R>,\n ): Promise<RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>>;\n async send<T extends OutputType[], R = ResponseData<T>>(\n config: RequestConfig,\n outputs: T,\n signal?: AbortSignal,\n mapper?: ResponseMapper<T, R>,\n ) {\n for (const interceptor of this.#interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n\n const init = signal === undefined ? config.init : { ...config.init, signal };\n\n let response = await (this.#fetch ?? fetch)(new Request(config.url, init));\n\n for (let i = this.#interceptors.length - 1; i >= 0; i--) {\n const interceptor = this.#interceptors[i];\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n\n if (mapper) {\n return await parse(outputs, response, mapper);\n }\n return await parse(outputs, response);\n }\n}\n";
1268
-
1269
- // packages/typescript/src/lib/http/interceptors.txt
1270
- var interceptors_default = "export interface Interceptor {\n before?: (config: RequestConfig) => Promise<RequestConfig> | RequestConfig;\n after?: (response: Response) => Promise<Response> | Response;\n}\n\nexport const createHeadersInterceptor = (\n headers: Record<string, string | undefined>,\n requestHeaders: HeadersInit,\n):Interceptor => {\n return {\n before({init, url}) {\n // Priority Levels\n // 1. Headers Input\n // 2. Request Headers\n // 3. Default Headers\n\n for (const [key, value] of new Headers(requestHeaders)) {\n // Only set the header if it doesn't already exist and has a value\n // even though these headers are passed at operation level\n // still they are lower priority compared to the headers input\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n for (const [key, value] of Object.entries(headers)) {\n // Only set the header if it doesn't already exist and has a value\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n return {init, url};\n },\n };\n};\n\nexport const createBaseUrlInterceptor = (baseUrl: string): Interceptor => {\n return {\n before({ init, url }) {\n if (url.protocol === 'local:') {\n return {\n init,\n url: new URL(url.href.replace('local://', baseUrl))\n };\n }\n return { init, url };\n },\n };\n};\n";
1271
-
1272
- // packages/typescript/src/lib/http/parse-response.txt
1273
- var parse_response_default = 'import { parse } from "fast-content-type-parse";\n\nfunction isBinaryContentType(contentType: string) {\n const type = contentType.toLowerCase();\n if (type.startsWith("image/")) {\n return true;\n }\n if (type.startsWith("audio/")) {\n return true;\n }\n if (type.startsWith("video/")) {\n return true;\n }\n switch (type) {\n case "application/pdf":\n case "application/zip":\n case "application/gzip":\n case "application/x-7z-compressed":\n case "application/x-tar":\n case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":\n case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":\n case "application/vnd.openxmlformats-officedocument.presentationml.presentation":\n case "application/vnd.ms-excel":\n case "application/vnd.ms-powerpoint":\n case "application/msword":\n case "application/octet-stream":\n return true;\n default:\n return false;\n }\n}\n\nfunction isAttachment(response: Response) {\n const contentDisposition = response.headers.get("Content-Disposition");\n const dispositionType = contentDisposition?.split(";", 1)[0];\n return dispositionType?.trim().toLowerCase() === "attachment";\n}\n\nexport function chunked(response: Response) {\n return response.body!;\n}\n\n// The operation declares no body; release the unread stream so the\n// connection is not held until garbage collection.\nexport async function bodyless(response: Response) {\n await response.body?.cancel();\n return null;\n}\n\nexport async function buffered(response: Response) {\n // Statuses that, per the HTTP spec, carry no message body. These responses\n // usually omit Content-Type entirely, so this must run before the guard below.\n if (\n response.status === 204 ||\n response.status === 205 ||\n response.status === 304\n ) {\n return null;\n }\n if (isAttachment(response)) {\n return response.blob();\n }\n\n const contentType = response.headers.get("Content-Type");\n if (!contentType) {\n throw new Error("Content-Type header is missing");\n }\n\n const { type } = parse(contentType);\n if (isBinaryContentType(type)) {\n return response.blob();\n }\n if (type.startsWith("text/")) {\n return response.text();\n }\n switch (type) {\n case "application/json":\n return response.json();\n case "application/xml":\n return response.text();\n case "application/x-www-form-urlencoded": {\n const text = await response.text();\n return Object.fromEntries(new URLSearchParams(text));\n }\n case "multipart/form-data":\n return response.formData();\n default:\n throw new Error(`Unsupported content type: ${contentType}`);\n }\n}\n';
1274
-
1275
- // packages/typescript/src/lib/http/parser.txt
1276
- var parser_default = "import { z } from 'zod';\n\nexport class ParseError<T extends z.ZodType> extends Error {\n public data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>;\n constructor(\n data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>,\n ) {\n super('Validation failed');\n this.name = 'ParseError';\n this.data = data;\n }\n}\n\nexport function parseInput<T extends z.ZodType>(\n schema: T,\n input: unknown,\n): z.infer<T> {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = z.flattenError(result.error, (issue) => issue);\n throw new ParseError<T>(error);\n }\n return result.data as z.infer<T>;\n}\n";
1277
-
1278
- // packages/typescript/src/lib/http/request.txt
1279
- var request_default = "type Init = Omit<RequestInit, 'headers'> & { headers: Headers };\nexport type RequestConfig = { init: Init; url: URL };\nexport type Method =\n | 'GET'\n | 'POST'\n | 'PUT'\n | 'PATCH'\n | 'DELETE'\n | 'HEAD'\n | 'OPTIONS';\nexport type ContentType =\n | 'xml'\n | 'json'\n | 'urlencoded'\n | 'multipart'\n | 'formdata';\nexport type HeadersInit = [string, string][] | Record<string, string>;\nexport type Endpoint =\n | `${ContentType} ${Method} ${string}`\n | `${Method} ${string}`;\n\nexport type BodyInit =\n | ArrayBuffer\n | Blob\n | FormData\n | URLSearchParams\n | null\n | string;\n\nfunction template(\n templateString: string,\n templateVariables: Record<string, any>,\n): string {\n const nargs = /{([0-9a-zA-Z_]+)}/g;\n return templateString.replace(nargs, (match, key: string, index: number) => {\n // Handle escaped double braces\n if (\n templateString[index - 1] === '{' &&\n templateString[index + match.length] === '}'\n ) {\n return key;\n }\n\n const result = key in templateVariables ? templateVariables[key] : null;\n return result === null || result === undefined\n ? ''\n : encodeURIComponent(String(result));\n });\n}\n\ntype Input = Record<string, any>;\n\n// Validated inputs can carry Date (coerce-date) values; String(new Date())\n// yields a local-time RFC 2822 string, so serialize Dates as ISO 8601.\nfunction toWireValue(value: any): string {\n return value instanceof Date ? value.toISOString() : String(value);\n}\n\ntype Props = {\n inputHeaders: string[];\n inputQuery: string[];\n inputBody: string[];\n inputParams: string[];\n};\n\nabstract class Serializer {\n protected input: Input;\n protected props: Props;\n\n constructor(input: Input, props: Props) {\n this.input = input;\n this.props = props;\n }\n\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(path: string): Serialized {\n const params = this.props.inputParams.reduce<Record<string, any>>(\n (acc, key) => {\n acc[key] = this.input[key];\n return acc;\n },\n {},\n );\n const url = new URL(template(path, params), `local://`);\n\n const headers: Record<string, string> = { ...this.getHeaders() };\n for (const header of this.props.inputHeaders) {\n const value = this.input[header];\n if (value !== undefined) {\n headers[header] = toWireValue(value);\n }\n }\n\n for (const key of this.props.inputQuery) {\n const value = this.input[key];\n if (value !== undefined) {\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, toWireValue(item));\n }\n } else {\n url.searchParams.set(key, toWireValue(value));\n }\n }\n }\n\n return {\n body: this.getBody(),\n url,\n headers,\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n headers: Record<string, string>;\n url: URL;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\n if (\n this.props.inputBody.length === 1 &&\n this.props.inputBody[0] === '$body'\n ) {\n return JSON.stringify(this.input.$body);\n }\n\n for (const prop of this.props.inputBody) {\n body[prop] = this.input[prop];\n }\n return JSON.stringify(body);\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n }\n}\n\nclass UrlencodedSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new URLSearchParams();\n for (const prop of this.props.inputBody) {\n body.set(prop, toWireValue(this.input[prop]));\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n };\n }\n}\n\nclass EmptySerializer extends Serializer {\n getBody(): BodyInit | null {\n return null;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass FormDataSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new FormData();\n for (const prop of this.props.inputBody) {\n body.append(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n Accept: 'application/json',\n };\n }\n}\n\nexport function json(input: Input, props: Props) {\n return new JsonSerializer(input, props);\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props);\n}\nexport function empty(input: Input, props: Props) {\n return new EmptySerializer(input, props);\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props);\n}\n\nexport function toRequest<T extends Endpoint>(\n endpoint: T,\n serializer: Serializer,\n): RequestConfig {\n const [method, path] = endpoint.split(' ');\n const input = serializer.serialize(path);\n return {\n url: input.url,\n init: {\n method: method,\n headers: new Headers(input.headers),\n ...(method === 'GET' ? {} : { body: input.body }),\n },\n };\n}\n";
1280
-
1281
- // packages/typescript/src/lib/http/response.txt
1282
- var response_default = "export class APIResponse<Body = unknown, Status extends number = number> {\n static readonly status: number;\n readonly status: Status;\n data: Body;\n readonly headers: Headers;\n\n constructor(status: Status, headers: Headers, data: Body) {\n this.status = status;\n this.headers = headers;\n this.data = data;\n }\n\n static create<Body = unknown>(status: number, headers: Headers, data: Body) {\n return new this(status, headers, data);\n }\n}\n\nexport class APIError<Body, Status extends number = number> extends Error {\n static readonly status: number;\n readonly status: Status;\n data: Body;\n readonly headers: Headers;\n\n constructor(status: Status, headers: Headers, data: Body) {\n super(failureMessage(status, data));\n this.name = 'APIError';\n this.status = status;\n this.headers = headers;\n this.data = data;\n }\n\n static create<T>(status: number, headers: Headers, data: T) {\n return new this(status, headers, data);\n }\n}\n\nfunction failureMessage(status: number, data: unknown) {\n const summary = bodySummary(data);\n return summary\n ? `Request failed with status code ${status}: ${summary}`\n : `Request failed with status code ${status}`;\n}\n\n// Only text and JSON bodies read as a summary; a Blob, stream or FormData body\n// has none. The tag check holds across realms, where prototype checks do not.\nfunction bodySummary(data: unknown) {\n const tag = Object.prototype.toString.call(data);\n let text = '';\n if (typeof data === 'string') {\n text = data;\n } else if (tag === '[object Object]' || tag === '[object Array]') {\n text = JSON.stringify(data);\n }\n const line = text.replace(/\\s+/g, ' ').trim();\n return line.length > 200 ? `${line.slice(0, 200)}\u2026` : line;\n}\n\n// 2xx Success\nexport class Ok<T> extends APIResponse<T, 200> {\n static override readonly status = 200 as const;\n constructor(headers: Headers, data: T) {\n super(Ok.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\nexport class Created<T> extends APIResponse<T, 201> {\n static override status = 201 as const;\n constructor(headers: Headers, data: T) {\n super(Created.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Accepted<T> extends APIResponse<T, 202> {\n static override status = 202 as const;\n constructor(headers: Headers, data: T) {\n super(Accepted.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NoContent extends APIResponse<never, 204> {\n static override status = 204 as const;\n constructor(headers: Headers) {\n super(NoContent.status, headers, null as never);\n }\n static override create(\n status: number,\n headers: Headers,\n data?: unknown,\n ): NoContent {\n return new this(headers);\n }\n}\n\n// 4xx Client Errors\nexport class BadRequest<T> extends APIError<T, 400> {\n static override status = 400 as const;\n constructor(headers: Headers, data: T) {\n super(BadRequest.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Unauthorized<T = { message: string }> extends APIError<T, 401> {\n static override status = 401 as const;\n constructor(headers: Headers, data: T) {\n super(Unauthorized.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class PaymentRequired<T = { message: string }> extends APIError<T, 402> {\n static override status = 402 as const;\n constructor(headers: Headers, data: T) {\n super(PaymentRequired.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Forbidden<T = { message: string }> extends APIError<T, 403> {\n static override status = 403 as const;\n constructor(headers: Headers, data: T) {\n super(Forbidden.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NotFound<T = { message: string }> extends APIError<T, 404> {\n static override status = 404 as const;\n constructor(headers: Headers, data: T) {\n super(NotFound.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class MethodNotAllowed<T = { message: string }> extends APIError<\n T,\n 405\n> {\n static override status = 405 as const;\n constructor(headers: Headers, data: T) {\n super(MethodNotAllowed.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NotAcceptable<T = { message: string }> extends APIError<T, 406> {\n static override status = 406 as const;\n constructor(headers: Headers, data: T) {\n super(NotAcceptable.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Conflict<T = { message: string }> extends APIError<T, 409> {\n static override status = 409 as const;\n constructor(headers: Headers, data: T) {\n super(Conflict.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Gone<T = { message: string }> extends APIError<T, 410> {\n static override status = 410 as const;\n constructor(headers: Headers, data: T) {\n super(Gone.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class PreconditionFailed<T = { message: string }> extends APIError<\n T,\n 412\n> {\n static override status = 412 as const;\n constructor(headers: Headers, data: T) {\n super(PreconditionFailed.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class UnprocessableEntity<\n T = { message: string; errors?: Record<string, string[]> },\n> extends APIError<T, 422> {\n static override status = 422 as const;\n constructor(headers: Headers, data: T) {\n super(UnprocessableEntity.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class TooManyRequests<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 429> {\n static override status = 429 as const;\n constructor(headers: Headers, data: T) {\n super(TooManyRequests.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class PayloadTooLarge<T = { message: string }> extends APIError<T, 413> {\n static override status = 413 as const;\n constructor(headers: Headers, data: T) {\n super(PayloadTooLarge.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class UnsupportedMediaType<T = { message: string }> extends APIError<\n T,\n 415\n> {\n static override status = 415 as const;\n constructor(headers: Headers, data: T) {\n super(UnsupportedMediaType.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\n// 5xx Server Errors\nexport class InternalServerError<T = { message: string }> extends APIError<\n T,\n 500\n> {\n static override status = 500 as const;\n constructor(headers: Headers, data: T) {\n super(InternalServerError.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NotImplemented<T = { message: string }> extends APIError<T, 501> {\n static override status = 501 as const;\n constructor(headers: Headers, data: T) {\n super(NotImplemented.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class BadGateway<T = { message: string }> extends APIError<T, 502> {\n static override status = 502 as const;\n constructor(headers: Headers, data: T) {\n super(BadGateway.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class ServiceUnavailable<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 503> {\n static override status = 503 as const;\n constructor(headers: Headers, data: T) {\n super(ServiceUnavailable.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class GatewayTimeout<T = { message: string }> extends APIError<T, 504> {\n static override status = 504 as const;\n constructor(headers: Headers, data: T) {\n super(GatewayTimeout.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\nexport type ClientError =\n | BadRequest<unknown>\n | Unauthorized<unknown>\n | PaymentRequired<unknown>\n | Forbidden<unknown>\n | NotFound<unknown>\n | MethodNotAllowed<unknown>\n | NotAcceptable<unknown>\n | Conflict<unknown>\n | Gone<unknown>\n | PreconditionFailed<unknown>\n | PayloadTooLarge<unknown>\n | UnsupportedMediaType<unknown>\n | UnprocessableEntity<unknown>\n | TooManyRequests<unknown>;\n\nexport type ServerError =\n | InternalServerError<unknown>\n | NotImplemented<unknown>\n | BadGateway<unknown>\n | ServiceUnavailable<unknown>\n | GatewayTimeout<unknown>;\n\nexport type ProblematicResponse = ClientError | ServerError;\n\nexport type SuccessfulResponse<T = unknown> =\n | Ok<T>\n | Created<T>\n | Accepted<T>\n | NoContent;\n\nexport type RebindSuccessPayload<Resp, New> =\n Resp extends Ok<infer _>\n ? Ok<New>\n : Resp extends Created<infer _>\n ? Created<New>\n : Resp extends Accepted<infer _>\n ? Accepted<New>\n : Resp extends NoContent\n ? NoContent\n : Resp extends SuccessfulResponse<infer _>\n ? APIResponse<New, Resp['status']>\n : never;\n";
1283
-
1284
- // packages/typescript/src/lib/http/sse.txt
1285
- var sse_default = 'export type SSEListener = (eventType: string) => AsyncIterable<string>;\n\nexport function sse(response: Response): SSEListener {\n const subscribers = new Map<\n string,\n { queue: string[]; resolve: (() => void) | null }\n >();\n let started = false;\n let streamDone = false;\n let streamFailure: { error: unknown } | null = null;\n\n function dispatch(eventType: string, data: string) {\n const sub = subscribers.get(eventType);\n if (sub) {\n sub.queue.push(data);\n sub.resolve?.();\n sub.resolve = null;\n }\n }\n\n function endAll() {\n streamDone = true;\n for (const sub of subscribers.values()) {\n sub.resolve?.();\n }\n }\n\n function startReading() {\n if (started) return;\n started = true;\n const decoder = new TextDecoder();\n let buffer = "";\n\n // The pump never rejects: the catch below hands a stream failure to the\n // listeners, so nothing awaits it. `void` states that, and keeps generated\n // output clean under @typescript-eslint/no-floating-promises.\n void (async () => {\n try {\n for await (const value of response.body!) {\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split("\\n\\n");\n buffer = parts.pop()!;\n\n for (const part of parts) {\n if (!part.trim()) continue;\n let eventType = "message";\n let data = "";\n for (const line of part.split("\\n")) {\n if (line.startsWith("event:")) {\n eventType = line.slice(6).trim();\n } else if (line.startsWith("data:")) {\n data += (data ? "\\n" : "") + line.slice(5).trim();\n }\n }\n if (data) dispatch(eventType, data);\n }\n }\n } catch (error) {\n streamFailure = { error };\n }\n endAll();\n })();\n }\n\n return function listen(eventType: string): AsyncIterable<string> {\n if (!subscribers.has(eventType)) {\n subscribers.set(eventType, { queue: [], resolve: null });\n }\n const sub = subscribers.get(eventType)!;\n startReading();\n\n return {\n [Symbol.asyncIterator]() {\n return {\n async next(): Promise<IteratorResult<string>> {\n while (sub.queue.length === 0) {\n if (streamFailure) throw streamFailure.error;\n if (streamDone) return { value: undefined as any, done: true };\n const { promise, resolve } = Promise.withResolvers<void>();\n sub.resolve = resolve;\n await promise;\n }\n return { value: sub.queue.shift()!, done: false };\n },\n async return(): Promise<IteratorResult<string>> {\n return { value: undefined as any, done: true };\n },\n };\n },\n };\n };\n}\n';
1286
-
1287
- // packages/typescript/src/lib/paginations/cursor-pagination.txt
1288
- var cursor_pagination_default = "type CursorPaginationParams = {\n cursor?: string;\n};\n\ninterface CursorMetadata extends Metadata {\n nextCursor?: string;\n}\n\ninterface Metadata {\n hasMore?: boolean;\n}\n\ntype PaginationRequestOptions = {\n signal?: AbortSignal;\n};\n\ntype PaginationResult<T, M extends CursorMetadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<T, M extends CursorMetadata> = (\n input: CursorPaginationParams,\n requestOptions?: PaginationRequestOptions,\n) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class CursorPagination<T, M extends CursorMetadata> {\n #meta: PaginationResult<T, M>['meta'] | null = null;\n #params: CursorPaginationParams;\n #currentPage: Page<T> | null = null;\n readonly #fetchFn: FetchFn<T, M>;\n readonly #requestOptions: PaginationRequestOptions;\n\n constructor(\n initialParams: PartialNullable<CursorPaginationParams>,\n fetchFn: FetchFn<T, M>,\n requestOptions: PaginationRequestOptions = {},\n ) {\n this.#fetchFn = fetchFn;\n this.#requestOptions = requestOptions;\n this.#params = initialParams.cursor == null ? {} : { cursor: initialParams.cursor };\n }\n\n async getNextPage(requestOptions?: PaginationRequestOptions) {\n if (this.#meta?.hasMore && this.#meta.nextCursor == null) {\n throw new Error('Cannot fetch the next page: the response has more items but no next cursor.');\n }\n const result = await this.#fetchFn(this.#params, {\n ...this.#requestOptions,\n ...requestOptions,\n });\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = result.meta.nextCursor === undefined ? {} : { cursor: result.meta.nextCursor };\n return this;\n }\n\n getCurrentPage() {\n if (!this.#currentPage) {\n throw new Error(\n 'No page data available. Please call getNextPage() first.',\n );\n }\n return this.#currentPage;\n }\n\n get hasMore() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta.hasMore;\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iter()) {\n yield page.getCurrentPage();\n }\n }\n\n async *iter(requestOptions?: PaginationRequestOptions) {\n if (!this.#currentPage) {\n yield await this.getNextPage(requestOptions);\n }\n\n while (this.hasMore) {\n yield await this.getNextPage(requestOptions);\n }\n }\n\n get metadata() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta;\n }\n}\n\nclass Page<T> {\n data: T[];\n constructor(data: T[]) {\n this.data = data;\n }\n}\n\ntype PartialNullable<T> = {\n [K in keyof T]?: T[K] | null | undefined;\n};\n";
1289
-
1290
- // packages/typescript/src/lib/paginations/offset-pagination.txt
1291
- var offset_pagination_default = "type OffsetPaginationParams = {\n offset: number;\n limit: number;\n};\n\ninterface Metadata {\n hasMore?: boolean;\n}\n\ntype PaginationRequestOptions = {\n signal?: AbortSignal;\n};\n\ntype PaginationResult<T, M extends Metadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<T, M extends Metadata> = (\n input: OffsetPaginationParams,\n requestOptions?: PaginationRequestOptions,\n) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class OffsetPagination<T, M extends Metadata> {\n #meta: PaginationResult<T, M>['meta'] | null = null;\n #params: OffsetPaginationParams;\n #currentPage: Page<T> | null = null;\n readonly #fetchFn: FetchFn<T, M>;\n readonly #requestOptions: PaginationRequestOptions;\n\n constructor(\n initialParams: { offset?: number | null | undefined; limit?: number | null | undefined },\n fetchFn: FetchFn<T, M>,\n requestOptions: PaginationRequestOptions = {},\n ) {\n this.#fetchFn = fetchFn;\n this.#requestOptions = requestOptions;\n this.#params = {\n limit: initialParams.limit ?? 0,\n offset: initialParams.offset ?? 0,\n };\n }\n\n async getNextPage(requestOptions?: PaginationRequestOptions) {\n const result = await this.#fetchFn(this.#params, {\n ...this.#requestOptions,\n ...requestOptions,\n });\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = {\n ...this.#params,\n offset: this.#params.offset + this.#params.limit,\n };\n return this;\n }\n\n getCurrentPage() {\n if (!this.#currentPage) {\n throw new Error(\n 'No page data available. Please call getNextPage() first.',\n );\n }\n return this.#currentPage;\n }\n\n get hasMore() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta.hasMore;\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iter()) {\n yield page.getCurrentPage();\n }\n }\n\n async *iter(requestOptions?: PaginationRequestOptions) {\n if (!this.#currentPage) {\n yield await this.getNextPage(requestOptions);\n }\n\n while (this.hasMore) {\n yield await this.getNextPage(requestOptions);\n }\n }\n\n get metadata() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta;\n }\n\n reset(params?: Partial<OffsetPaginationParams>) {\n this.#meta = null;\n this.#currentPage = null;\n if (params) {\n this.#params = { ...this.#params, ...params };\n } else {\n this.#params.offset = 0;\n }\n return this;\n }\n}\n\nclass Page<T> {\n data: T[];\n constructor(data: T[]) {\n this.data = data;\n }\n}\n";
1292
-
1293
- // packages/typescript/src/lib/paginations/page-pagination.txt
1294
- var page_pagination_default = "type InferPage<T> = T extends Page<infer U> ? U : never;\ntype PaginationParams<P extends number | bigint | null, S extends number | bigint | null> = {\n page?: P;\n pageSize?: S;\n};\n\ninterface Metadata {\n hasMore?: boolean;\n}\n\ntype PaginationRequestOptions = {\n signal?: AbortSignal;\n};\n\ntype PaginationResult<T, M extends Metadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<\n T,\n M extends Metadata,\n P extends number | bigint | null,\n S extends number | bigint | null,\n> = (\n input: Partial<PaginationParams<P, S>>,\n requestOptions?: PaginationRequestOptions,\n) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class Pagination<\n T,\n M extends Metadata,\n P extends number | bigint | null,\n S extends number | bigint | null,\n> {\n #meta: PaginationResult<T, M>['meta'] | null = null;\n #params: PaginationParams<P, S>;\n #currentPage: Page<T> | null = null;\n readonly #fetchFn: FetchFn<T, M, P, S>;\n readonly #requestOptions: PaginationRequestOptions;\n\n constructor(\n initialParams: { page?: P | undefined; pageSize?: S | undefined },\n fetchFn: FetchFn<T, M, P, S>,\n requestOptions: PaginationRequestOptions = {},\n ) {\n this.#fetchFn = fetchFn;\n this.#requestOptions = requestOptions;\n this.#params = {\n ...(initialParams.page === undefined ? {} : { page: initialParams.page }),\n ...(initialParams.pageSize === undefined ? {} : { pageSize: initialParams.pageSize }),\n };\n }\n\n async getNextPage(requestOptions?: PaginationRequestOptions) {\n const result = await this.#fetchFn(this.#params, {\n ...this.#requestOptions,\n ...requestOptions,\n });\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = {\n ...this.#params,\n page: (((this.#params.page as number) || 0) + 1) as never,\n };\n return this;\n }\n\n getCurrentPage() {\n if (!this.#currentPage) {\n throw new Error(\n 'No page data available. Please call getNextPage() first.',\n );\n }\n return this.#currentPage;\n }\n\n get hasMore() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta.hasMore;\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iter()) {\n yield page.getCurrentPage();\n }\n }\n\n async *iter(requestOptions?: PaginationRequestOptions) {\n if (!this.#currentPage) {\n yield await this.getNextPage(requestOptions);\n }\n\n while (this.hasMore) {\n yield await this.getNextPage(requestOptions);\n }\n }\n\n get metadata() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta;\n }\n}\n\nclass Page<T> {\n data: T[];\n constructor(data: T[]) {\n this.data = data;\n }\n}\n";
1295
1398
 
1296
1399
  // packages/typescript/src/lib/readme/readme.ts
1297
- import { isEmpty as isEmpty4 } from "@sdk-it/core";
1298
- import { forEachOperation as forEachOperation4 } from "@sdk-it/spec";
1400
+ import { isEmpty as isEmpty3 } from "@sdk-it/core";
1401
+ import { forEachOperation as forEachOperation4, operationInputs as operationInputs4 } from "@sdk-it/spec";
1299
1402
 
1300
1403
  // packages/typescript/src/lib/readme/prop.emitter.ts
1301
- import { followRef as followRef4, isRef as isRef4 } from "@sdk-it/core";
1404
+ import { followRef as followRef3, isRef as isRef3 } from "@sdk-it/core";
1302
1405
  import { coerceTypes } from "@sdk-it/spec";
1303
1406
  var PropEmitter = class {
1304
1407
  #spec;
@@ -1336,7 +1439,7 @@ var PropEmitter = class {
1336
1439
  #property(name, schema, required) {
1337
1440
  const docs = this.handle(schema);
1338
1441
  const rawType = docs[0].replace("**Type:** ", "").replace(" (nullable)", "|null");
1339
- const defaultVal = !isRef4(schema) && schema.default !== void 0 ? ` default: ${JSON.stringify(schema.default)}` : "";
1442
+ const defaultVal = !isRef3(schema) && schema.default !== void 0 ? ` default: ${JSON.stringify(schema.default)}` : "";
1340
1443
  const reqMark = required ? " required" : "";
1341
1444
  const summary = `- \`${name}\` ${rawType}${reqMark}${defaultVal}:`;
1342
1445
  const detailLines = docs.slice(1).filter((it) => !it.startsWith("**Default:**")).map((it) => ` ${it}`);
@@ -1363,7 +1466,7 @@ var PropEmitter = class {
1363
1466
  }
1364
1467
  #ref($ref) {
1365
1468
  const schemaName = $ref.split("/").pop() || "object";
1366
- const resolved = followRef4(this.#spec, $ref);
1469
+ const resolved = followRef3(this.#spec, $ref);
1367
1470
  const lines = [
1368
1471
  `**Type:** [\`${schemaName}\`](#${schemaName.toLowerCase()})`
1369
1472
  ];
@@ -1498,7 +1601,7 @@ var PropEmitter = class {
1498
1601
  * Handle schemas by resolving references and delegating to appropriate handler
1499
1602
  */
1500
1603
  handle(schemaOrRef) {
1501
- if (isRef4(schemaOrRef)) {
1604
+ if (isRef3(schemaOrRef)) {
1502
1605
  return this.#ref(schemaOrRef.$ref);
1503
1606
  }
1504
1607
  const schema = schemaOrRef;
@@ -1545,42 +1648,62 @@ var PropEmitter = class {
1545
1648
  lines.push(`**Default:** \`${JSON.stringify(schema.default)}\``);
1546
1649
  return lines;
1547
1650
  }
1548
- /**
1549
- * Process a request body and return markdown documentation
1550
- */
1651
+ /** The documentation of a request body, one block per content type. */
1551
1652
  requestBody(requestBody) {
1552
1653
  const lines = [];
1553
- lines.push(`#### Input`);
1554
- lines.push(requestBody.description || "");
1654
+ if (requestBody.description) {
1655
+ lines.push(requestBody.description);
1656
+ }
1555
1657
  const contentEntries = Object.entries(requestBody.content);
1556
- const multipleContentTypes = contentEntries.length > 1;
1557
- if (multipleContentTypes) {
1558
- for (const [contentType, mediaType] of contentEntries) {
1658
+ if (contentEntries.length > 1) {
1659
+ for (const [contentType2, mediaType2] of contentEntries) {
1559
1660
  lines.push(`<details>`);
1560
- lines.push(`<summary>Content Type: \`${contentType}\`</summary>`);
1661
+ lines.push(`<summary>Content Type: \`${contentType2}\`</summary>`);
1561
1662
  lines.push("");
1562
- if (mediaType.schema) {
1563
- const schemaDocs = this.handle(mediaType.schema);
1564
- lines.push(...schemaDocs.map((l) => l));
1663
+ if (mediaType2.schema) {
1664
+ lines.push(...this.handle(mediaType2.schema));
1565
1665
  }
1566
1666
  lines.push("");
1567
1667
  lines.push(`</details>`);
1568
1668
  }
1569
- } else {
1570
- const [contentType, mediaType] = contentEntries[0];
1571
- lines.push(`Content Type: \`${contentType}\``);
1572
- if (mediaType.schema) {
1573
- const schemaDocs = this.handle(mediaType.schema);
1574
- lines.push(...schemaDocs);
1575
- }
1669
+ return lines;
1670
+ }
1671
+ const [[contentType, mediaType]] = contentEntries;
1672
+ lines.push(`Content Type: \`${contentType}\``);
1673
+ if (mediaType.schema) {
1674
+ lines.push(...this.handle(mediaType.schema));
1576
1675
  }
1577
1676
  return lines;
1578
1677
  }
1678
+ /** A table of the operation's path, query, header and cookie parameters. */
1679
+ parameters(parameters) {
1680
+ if (parameters.length === 0) {
1681
+ return [];
1682
+ }
1683
+ return [
1684
+ [
1685
+ "| Name | In | Type | Required | Description |",
1686
+ "|------|----|------|----------|-------------|",
1687
+ ...parameters.map(
1688
+ (parameter) => [
1689
+ "",
1690
+ `\`${parameter.name}\``,
1691
+ parameter.in,
1692
+ parameter.schema ? this.handle(parameter.schema)[0].replace("**Type:** ", "") : "",
1693
+ parameter.required ? "Yes" : "No",
1694
+ (parameter.description ?? "").replaceAll("\n", " "),
1695
+ ""
1696
+ ].map((cell) => cell.replaceAll("|", "\\|")).join(" | ").trim()
1697
+ )
1698
+ ].join("\n")
1699
+ ];
1700
+ }
1579
1701
  };
1580
1702
 
1581
1703
  // packages/typescript/src/lib/readme/readme.ts
1582
1704
  function toReadme(spec, generator) {
1583
1705
  const propEmitter = new PropEmitter(spec);
1706
+ const bodylessInputs = /* @__PURE__ */ new Set();
1584
1707
  const markdown = [];
1585
1708
  markdown.push(`# ${spec.info.title} TypeScript SDK`);
1586
1709
  markdown.push("");
@@ -1615,14 +1738,22 @@ function toReadme(spec, generator) {
1615
1738
  const snippet = generator.snippet(entry, operation);
1616
1739
  markdown.push(`#### Example usage`);
1617
1740
  markdown.push(snippet);
1618
- const requestBodyContent = propEmitter.requestBody(operation.requestBody);
1619
- if (requestBodyContent.length > 1) {
1620
- markdown.push(requestBodyContent.join("\n\n"));
1741
+ const [preferred] = operationInputs4(spec, operation);
1742
+ const input = propEmitter.parameters(operation.parameters);
1743
+ if (preferred.encoding === "empty") {
1744
+ bodylessInputs.add(
1745
+ operation.requestBody.content[preferred.contentType].schema.$ref
1746
+ );
1747
+ } else {
1748
+ input.push(...propEmitter.requestBody(operation.requestBody));
1749
+ }
1750
+ if (input.length > 0) {
1751
+ markdown.push(["#### Input", ...input].join("\n\n"));
1621
1752
  }
1622
1753
  markdown.push(`#### Output`);
1623
1754
  for (const status in operation.responses) {
1624
1755
  const response = operation.responses[status];
1625
- if (!isEmpty4(response.content)) {
1756
+ if (!isEmpty3(response.content)) {
1626
1757
  const contentEntries = Object.entries(response.content);
1627
1758
  if (contentEntries.length === 1) {
1628
1759
  const [contentType, mediaType] = contentEntries[0];
@@ -1660,7 +1791,9 @@ ${l}`));
1660
1791
  for (const [schemaName, schema] of Object.entries(
1661
1792
  spec.components.schemas
1662
1793
  )) {
1663
- if (schemaName === "ValidationError") {
1794
+ if (schemaName === "ValidationError" || bodylessInputs.has(
1795
+ `#/components/schemas/${schemaName.replaceAll("~", "~0").replaceAll("/", "~1")}`
1796
+ )) {
1664
1797
  continue;
1665
1798
  }
1666
1799
  markdown.push(`<details>`);
@@ -1678,200 +1811,6 @@ ${l}`));
1678
1811
  return markdown.join("\n\n");
1679
1812
  }
1680
1813
 
1681
- // packages/typescript/src/lib/security.ts
1682
- var security_default = (spec) => {
1683
- const securitySchemes = JSON.stringify(spec.securitySchemes, null, 2);
1684
- const credentialProperties = Object.entries(spec.securitySchemes).map(([name, scheme]) => {
1685
- const schema = scheme.type === "mutualTLS" ? "mutualTlsCredentialSchema" : scheme.type === "http" && scheme.scheme?.toLowerCase() === "basic" ? "basicCredentialSchema" : "stringCredentialSchema";
1686
- return `${JSON.stringify(name)}: ${schema}.optional()`;
1687
- }).join(",\n");
1688
- return `import z from 'zod';
1689
- import type { Interceptor } from './${spec.makeImport("interceptors")}';
1690
- import type { RequestConfig } from './${spec.makeImport("request")}';
1691
-
1692
- export type SecurityContext = {
1693
- scheme: string;
1694
- scopes: readonly string[];
1695
- roles: readonly string[];
1696
- };
1697
- export type SecurityCredentialValue = string | true | {
1698
- username: string;
1699
- password: string;
1700
- };
1701
- export type SecurityCredentialProvider<T extends SecurityCredentialValue> = (
1702
- context: SecurityContext
1703
- ) => T | Promise<T>;
1704
- export type SecurityCredential<
1705
- T extends SecurityCredentialValue = SecurityCredentialValue,
1706
- > = T | SecurityCredentialProvider<T>;
1707
-
1708
- const providerSchema = <T extends SecurityCredentialValue>() =>
1709
- z.custom<SecurityCredentialProvider<T>>((value) => typeof value === 'function');
1710
- const stringCredentialSchema = z.union([
1711
- z.string(),
1712
- z.literal(true),
1713
- providerSchema<string | true>(),
1714
- ]);
1715
- const basicCredentialValueSchema = z.object({
1716
- username: z.string(),
1717
- password: z.string(),
1718
- });
1719
- const basicCredentialSchema = z.union([
1720
- basicCredentialValueSchema,
1721
- z.literal(true),
1722
- providerSchema<{ username: string; password: string } | true>(),
1723
- ]);
1724
- const mutualTlsCredentialSchema = z.union([
1725
- z.literal(true),
1726
- providerSchema<true>(),
1727
- ]);
1728
- export const credentialsSchema = z.object({${credentialProperties}});
1729
-
1730
- type RuntimeSecurityScheme =
1731
- | { type: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string }
1732
- | { type: 'http'; scheme: string }
1733
- | { type: 'oauth2' }
1734
- | { type: 'openIdConnect' }
1735
- | { type: 'mutualTLS' };
1736
- const securitySchemes = ${securitySchemes} as const;
1737
-
1738
- export function createSecurityInterceptor(
1739
- requirements: readonly Record<string, readonly string[]>[],
1740
- credentials: Record<string, SecurityCredential | undefined> | undefined,
1741
- ): Interceptor {
1742
- return {
1743
- async before(config) {
1744
- if (requirements.length === 0) return config;
1745
- const secured = requirements.filter(
1746
- (requirement) => Object.keys(requirement).length > 0,
1747
- );
1748
- const selected = secured.find((requirement) =>
1749
- Object.keys(requirement).every(
1750
- (name) => credentials?.[name] !== undefined,
1751
- ),
1752
- );
1753
- if (!selected) {
1754
- if (requirements.some(
1755
- (requirement) => Object.keys(requirement).length === 0,
1756
- )) return config;
1757
- throw new Error(
1758
- \`Missing credentials for security requirements: \${secured
1759
- .map((requirement) => Object.keys(requirement).join(' + '))
1760
- .join(' or ')}\`,
1761
- );
1762
- }
1763
- for (const [name, values] of Object.entries(selected)) {
1764
- const scheme = securitySchemes[
1765
- name as keyof typeof securitySchemes
1766
- ] as RuntimeSecurityScheme | undefined;
1767
- if (!scheme) {
1768
- throw new Error(\`Unsupported external security scheme: \${name}\`);
1769
- }
1770
- const configured = credentials?.[name];
1771
- const isOAuth = scheme.type === 'oauth2' || scheme.type === 'openIdConnect';
1772
- const credential = typeof configured === 'function'
1773
- ? await configured({
1774
- scheme: name,
1775
- scopes: isOAuth ? values : [],
1776
- roles: isOAuth ? [] : values,
1777
- })
1778
- : configured;
1779
- applyCredential(config, scheme, credential);
1780
- }
1781
- return config;
1782
- },
1783
- };
1784
- }
1785
-
1786
- function applyCredential(
1787
- config: RequestConfig,
1788
- scheme: RuntimeSecurityScheme,
1789
- credential: SecurityCredentialValue | undefined,
1790
- ) {
1791
- if (credential === undefined) {
1792
- throw new Error('Security credential provider returned no credential');
1793
- }
1794
- // true declares a transport-owned credential: the configured fetch, a host
1795
- // proxy, or the browser's cookie jar supplies it, so nothing is set here.
1796
- if (credential === true) return;
1797
- if (scheme.type === 'apiKey') {
1798
- if (typeof credential !== 'string') {
1799
- throw new TypeError('API key credentials must be strings');
1800
- }
1801
- if (scheme.in === 'header') {
1802
- if (!config.init.headers.has(scheme.name)) {
1803
- config.init.headers.set(scheme.name, credential);
1804
- }
1805
- } else if (scheme.in === 'query') {
1806
- if (!config.url.searchParams.has(scheme.name)) {
1807
- config.url.searchParams.set(scheme.name, credential);
1808
- }
1809
- } else if (scheme.in === 'cookie') {
1810
- if ('document' in globalThis) {
1811
- throw new Error(
1812
- \`Cannot send the \${scheme.name} cookie credential: browsers forbid setting the Cookie header. Let the browser send the cookie and pass a fetch that sets credentials: 'include'.\`,
1813
- );
1814
- }
1815
- const cookie = \`\${scheme.name}=\${encodeURIComponent(credential)}\`;
1816
- const existing = config.init.headers.get('Cookie');
1817
- if (!existing?.split(';').some((part) => part.trim().startsWith(\`\${scheme.name}=\`))) {
1818
- config.init.headers.set('Cookie', existing ? \`\${existing}; \${cookie}\` : cookie);
1819
- }
1820
- } else {
1821
- throw new TypeError(\`Unsupported apiKey location: \${String(scheme.in)}\`);
1822
- }
1823
- return;
1824
- }
1825
- if (scheme.type === 'mutualTLS') {
1826
- throw new TypeError('mutualTLS credentials must be true when the custom fetch owns the client certificate');
1827
- }
1828
- if (scheme.type === 'http' && scheme.scheme.toLowerCase() === 'basic') {
1829
- if (
1830
- typeof credential !== 'object' ||
1831
- !('username' in credential) ||
1832
- !('password' in credential)
1833
- ) {
1834
- throw new TypeError('Basic credentials require username and password');
1835
- }
1836
- const bytes = new TextEncoder().encode(
1837
- \`\${credential.username}:\${credential.password}\`,
1838
- );
1839
- let binary = '';
1840
- for (const byte of bytes) binary += String.fromCharCode(byte);
1841
- if (!config.init.headers.has('Authorization')) {
1842
- config.init.headers.set('Authorization', \`Basic \${btoa(binary)}\`);
1843
- }
1844
- return;
1845
- }
1846
- if (typeof credential !== 'string') {
1847
- throw new TypeError(\`\${scheme.type} credentials must be strings\`);
1848
- }
1849
- const prefix = scheme.type === 'http' ? authorizationScheme(scheme.scheme) : 'Bearer';
1850
- if (!config.init.headers.has('Authorization')) {
1851
- config.init.headers.set('Authorization', \`\${prefix} \${credential}\`);
1852
- }
1853
- }
1854
-
1855
- // OpenAPI carries the lowercase registry name, while servers routinely match the
1856
- // Authorization prefix case-sensitively (\`header.startsWith('Bearer ')\`).
1857
- const authorizationSchemes: Record<string, string> = {
1858
- basic: 'Basic',
1859
- bearer: 'Bearer',
1860
- digest: 'Digest',
1861
- hoba: 'HOBA',
1862
- mutual: 'Mutual',
1863
- negotiate: 'Negotiate',
1864
- oauth: 'OAuth',
1865
- 'scram-sha-1': 'SCRAM-SHA-1',
1866
- 'scram-sha-256': 'SCRAM-SHA-256',
1867
- };
1868
-
1869
- function authorizationScheme(scheme: string) {
1870
- return authorizationSchemes[scheme.toLowerCase()] ?? scheme;
1871
- }
1872
- `;
1873
- };
1874
-
1875
1814
  // packages/typescript/src/lib/server-urls.ts
1876
1815
  function expandServerUrls(servers) {
1877
1816
  return servers.flatMap((server) => {
@@ -1899,20 +1838,20 @@ function expandServerUrls(servers) {
1899
1838
  }
1900
1839
 
1901
1840
  // packages/typescript/src/lib/typescript-snippet.ts
1902
- import { camelcase as camelcase5, spinalcase as spinalcase3 } from "stringcase";
1841
+ import { camelcase as camelcase5 } from "stringcase";
1903
1842
  import {
1904
- isEmpty as isEmpty5,
1905
- pascalcase as pascalcase4,
1906
- resolveRef as resolveRef4
1843
+ isEmpty as isEmpty4,
1844
+ pascalcase as pascalcase3,
1845
+ resolveRef as resolveRef3
1907
1846
  } from "@sdk-it/core";
1908
1847
  import "@sdk-it/readme";
1909
1848
  import {
1910
1849
  forEachOperation as forEachOperation5,
1911
- patchParameters
1850
+ operationInputs as operationInputs5
1912
1851
  } from "@sdk-it/spec";
1913
1852
 
1914
1853
  // packages/typescript/src/lib/emitters/snippet.ts
1915
- import { followRef as followRef5, isRef as isRef5, resolveRef as resolveRef3 } from "@sdk-it/core";
1854
+ import { followRef as followRef4, isRef as isRef4, resolveRef as resolveRef2 } from "@sdk-it/core";
1916
1855
  var SnippetEmitter = class {
1917
1856
  spec;
1918
1857
  generatedRefs = /* @__PURE__ */ new Set();
@@ -1921,12 +1860,12 @@ var SnippetEmitter = class {
1921
1860
  this.spec = spec;
1922
1861
  }
1923
1862
  object(schema) {
1924
- const schemaObj = resolveRef3(this.spec, schema);
1863
+ const schemaObj = resolveRef2(this.spec, schema);
1925
1864
  const result = {};
1926
1865
  const properties = schemaObj.properties || {};
1927
1866
  for (const [propName, propSchema] of Object.entries(properties)) {
1928
1867
  const isRequired = (schemaObj.required ?? []).includes(propName);
1929
- const resolvedProp = resolveRef3(this.spec, propSchema);
1868
+ const resolvedProp = resolveRef2(this.spec, propSchema);
1930
1869
  if (isRequired || resolvedProp.example !== void 0 || resolvedProp.default !== void 0) {
1931
1870
  result[propName] = this.handle(propSchema);
1932
1871
  }
@@ -1939,7 +1878,7 @@ var SnippetEmitter = class {
1939
1878
  return result;
1940
1879
  }
1941
1880
  array(schema) {
1942
- const schemaObj = resolveRef3(this.spec, schema);
1881
+ const schemaObj = resolveRef2(this.spec, schema);
1943
1882
  const itemsSchema = schemaObj.items;
1944
1883
  if (!itemsSchema) {
1945
1884
  return [];
@@ -2016,12 +1955,12 @@ var SnippetEmitter = class {
2016
1955
  }
2017
1956
  ref($ref) {
2018
1957
  const parts = $ref.split("/");
2019
- const refKey = parts[parts.length - 1] || "";
1958
+ const refKey = parts.at(-1) || "";
2020
1959
  if (this.cache.has($ref)) {
2021
1960
  return this.cache.get($ref);
2022
1961
  }
2023
1962
  this.cache.set($ref, { _ref: refKey });
2024
- const resolved = followRef5(this.spec, $ref);
1963
+ const resolved = followRef4(this.spec, $ref);
2025
1964
  const result = this.handle(resolved);
2026
1965
  this.cache.set($ref, result);
2027
1966
  return result;
@@ -2048,10 +1987,10 @@ var SnippetEmitter = class {
2048
1987
  return Array.isArray(schema.enum) && schema.enum.length > 0 ? schema.enum[0] : void 0;
2049
1988
  }
2050
1989
  handle(schemaOrRef) {
2051
- if (isRef5(schemaOrRef)) {
1990
+ if (isRef4(schemaOrRef)) {
2052
1991
  return this.ref(schemaOrRef.$ref);
2053
1992
  }
2054
- const schema = resolveRef3(this.spec, schemaOrRef);
1993
+ const schema = resolveRef2(this.spec, schemaOrRef);
2055
1994
  if (schema.example !== void 0) {
2056
1995
  return schema.example;
2057
1996
  }
@@ -2109,45 +2048,57 @@ var TypeScriptSnippet = class {
2109
2048
  constructor(spec, settings) {
2110
2049
  this.#spec = spec;
2111
2050
  this.#snippetEmitter = new SnippetEmitter(spec);
2112
- this.#clientName = settings.name?.trim() ? pascalcase4(settings.name) : "Client";
2113
- this.#packageName = settings.name ? `@${spinalcase3(this.#clientName.toLowerCase())}/sdk` : "sdk";
2114
- }
2115
- succinct(entry, operation, values) {
2116
- let payload = "{}";
2117
- if (!isEmpty5(operation.requestBody)) {
2118
- const contentTypes = Object.keys(operation.requestBody.content || {});
2119
- const schema = resolveRef4(
2120
- this.#spec,
2121
- operation.requestBody.content[contentTypes[0]].schema
2122
- );
2123
- const examplePayload = this.#snippetEmitter.handle({
2124
- ...schema,
2125
- properties: Object.assign({}, schema.properties, schema.properties)
2126
- });
2127
- Object.assign(
2128
- examplePayload,
2129
- values.requestBody ?? {},
2130
- values.pathParameters ?? {},
2131
- values.queryParameters ?? {},
2132
- values.headers ?? {},
2133
- values.cookies ?? {}
2134
- );
2135
- payload = examplePayload;
2136
- } else {
2137
- const requestBody = { type: "object", properties: {} };
2138
- patchParameters(this.#spec, requestBody, operation.parameters);
2139
- const examplePayload = this.#snippetEmitter.handle(requestBody);
2140
- Object.assign(
2141
- examplePayload,
2142
- values.pathParameters ?? {},
2143
- values.queryParameters ?? {},
2144
- values.headers ?? {},
2145
- values.cookies ?? {}
2146
- );
2147
- payload = examplePayload;
2051
+ this.#clientName = pascalcase3(settings.name.trim());
2052
+ this.#packageName = settings.packageName;
2053
+ }
2054
+ succinct(entry, operation) {
2055
+ const payload = this.#render(this.#example(operation));
2056
+ const success = Object.entries(operation.responses).find(
2057
+ ([status]) => status.startsWith("2")
2058
+ )?.[1];
2059
+ if (success?.["x-body"] === "stream") {
2060
+ return this.#stream(entry, payload);
2061
+ }
2062
+ if (operation["x-pagination"]) {
2063
+ return this.#pagination(entry, payload);
2148
2064
  }
2149
- payload = JSON.stringify(
2150
- payload,
2065
+ return this.#normal(entry, payload);
2066
+ }
2067
+ /** An input the operation's preferred input schema accepts: its required fields, and the fields that declare an example or a default. */
2068
+ #example(operation) {
2069
+ const [preferred] = operationInputs5(this.#spec, operation);
2070
+ return this.#snippetEmitter.handle(preferred.schema);
2071
+ }
2072
+ /**
2073
+ * The operation's example input with its first required field set to a value
2074
+ * of a type the field does not accept, so the client refuses it with a
2075
+ * `ParseError`; undefined when no such value exists.
2076
+ */
2077
+ #invalidInput(operation) {
2078
+ const [preferred] = operationInputs5(this.#spec, operation);
2079
+ const [field] = preferred.schema.required ?? [];
2080
+ const property = field === void 0 ? void 0 : preferred.schema.properties?.[field];
2081
+ const example = this.#example(operation);
2082
+ if (property === void 0 || !isRecord(example)) {
2083
+ return void 0;
2084
+ }
2085
+ const value = wrongTypeValue(
2086
+ resolveRef3(this.#spec, property)
2087
+ );
2088
+ if (value === void 0) {
2089
+ return void 0;
2090
+ }
2091
+ const key = JSON.stringify(field);
2092
+ return this.#render({ ...example, [field]: value }).split("\n").flatMap(
2093
+ (line) => line.startsWith(` ${key}:`) ? [
2094
+ ` // @ts-expect-error ${key} does not accept ${JSON.stringify(value)}`,
2095
+ line
2096
+ ] : [line]
2097
+ ).join("\n");
2098
+ }
2099
+ #render(example) {
2100
+ return JSON.stringify(
2101
+ example,
2151
2102
  (key, value) => {
2152
2103
  if (value?.startsWith && value.startsWith("new")) {
2153
2104
  return `__REPLACE_${Math.random().toString(36).substring(2, 11)}__${value}__REPLACE_END__`;
@@ -2156,69 +2107,23 @@ var TypeScriptSnippet = class {
2156
2107
  },
2157
2108
  2
2158
2109
  ).replace(/"__REPLACE_[^"]*__([^"]*?)__REPLACE_END__"/g, "$1");
2159
- let successResponse;
2160
- for (const status in operation.responses) {
2161
- if (status.startsWith("2")) {
2162
- successResponse = operation.responses[status];
2163
- break;
2164
- }
2165
- }
2166
- if (successResponse) {
2167
- if (successResponse.headers?.["Transfer-Encoding"]) {
2168
- return this.#httpStreaming(entry, payload);
2169
- }
2170
- if (successResponse.content && successResponse.content["application/octet-stream"]) {
2171
- return this.#streamDownload(entry, payload);
2172
- }
2173
- }
2174
- if (!isEmpty5(operation["x-pagination"])) {
2175
- return this.#pagination(operation, entry, payload);
2176
- }
2177
- return this.#normal(entry, payload);
2178
2110
  }
2179
- #pagination(operation, entry, payload) {
2180
- const pagination = operation["x-pagination"];
2181
- switch (pagination.type) {
2182
- case "page":
2183
- return {
2184
- content: `const controller = new AbortController();
2185
- const result = await ${camelcase5(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload}, { signal: controller.signal });`,
2186
- footer: `for await (const page of result.iter({ signal: controller.signal })) {
2187
- console.log(page);
2188
- }`
2189
- };
2190
- case "offset":
2191
- return {
2192
- content: `const controller = new AbortController();
2193
- const result = await ${camelcase5(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload}, { signal: controller.signal });`,
2194
- footer: `for await (const page of result.iter({ signal: controller.signal })) {
2195
- console.log(page);
2196
- }`
2197
- };
2198
- case "cursor":
2199
- return {
2200
- content: `const controller = new AbortController();
2201
- const result = await ${camelcase5(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload}, { signal: controller.signal });`,
2202
- footer: `for await (const page of result.iter({ signal: controller.signal })) {
2111
+ #pagination(entry, payload) {
2112
+ return {
2113
+ content: `const controller = new AbortController();
2114
+ const result = await ${camelcase5(this.#clientName)}.request('${endpointOf(entry)}', ${payload}, { signal: controller.signal });`,
2115
+ footer: `for await (const page of result.iterPages({ signal: controller.signal })) {
2203
2116
  console.log(page);
2204
2117
  }`
2205
- };
2206
- }
2207
- return this.#normal(entry, payload);
2208
- }
2209
- #normal(entry, payload) {
2210
- return {
2211
- content: `const result = ${this.#toRequest(entry, payload)};`,
2212
- footer: "console.log(result.data)"
2213
2118
  };
2214
2119
  }
2215
- #streamDownload(entry, payload) {
2120
+ #normal(entry, payload) {
2216
2121
  return {
2217
- content: `const stream = ${this.#toRequest(entry, payload)}`,
2218
- footer: `await writeFile('./report.pdf', stream);`
2122
+ content: `const result = ${this.#toRequest(entry, payload)}`,
2123
+ footer: "console.log(result);"
2219
2124
  };
2220
2125
  }
2221
- #httpStreaming(entry, payload) {
2126
+ #stream(entry, payload) {
2222
2127
  return {
2223
2128
  content: `const stream = ${this.#toRequest(entry, payload)}`,
2224
2129
  footer: `for await (const chunk of stream) {
@@ -2227,10 +2132,10 @@ const result = await ${camelcase5(this.#clientName)}.request('${entry.method.toU
2227
2132
  };
2228
2133
  }
2229
2134
  #toRequest(entry, payload) {
2230
- return `await ${camelcase5(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload});`;
2135
+ return `await ${camelcase5(this.#clientName)}.request('${endpointOf(entry)}', ${payload});`;
2231
2136
  }
2232
2137
  snippet(entry, operation, config = {}) {
2233
- const payload = this.succinct(entry, operation, config);
2138
+ const payload = this.succinct(entry, operation);
2234
2139
  const content = [
2235
2140
  this.client(),
2236
2141
  "",
@@ -2258,7 +2163,7 @@ const result = await ${camelcase5(this.#clientName)}.request('${entry.method.toU
2258
2163
  return scheme ? [
2259
2164
  {
2260
2165
  name,
2261
- scheme: resolveRef4(
2166
+ scheme: resolveRef3(
2262
2167
  this.#spec,
2263
2168
  scheme
2264
2169
  )
@@ -2275,27 +2180,48 @@ const result = await ${camelcase5(this.#clientName)}.request('${entry.method.toU
2275
2180
  return "test_access_token_1234567890abcdef";
2276
2181
  }
2277
2182
  client() {
2183
+ const client = this.#clientSetup();
2184
+ return client.use ? `${client.import}
2185
+
2186
+ ${client.use}` : client.import;
2187
+ }
2188
+ /** The client setup with `names` imported beside the client. */
2189
+ #clientWith(names) {
2190
+ const client = this.#clientSetup();
2191
+ return [
2192
+ `import { ${[client.name, ...names].join(", ")} } from '${this.#packageName}';`,
2193
+ ...client.use ? ["", client.use] : []
2194
+ ];
2195
+ }
2196
+ #clientSetup() {
2278
2197
  const servers = expandServerUrls(this.#spec.servers ?? []);
2279
2198
  const options = {};
2280
2199
  if (servers.length !== 1) {
2281
2200
  options.baseUrl = servers[0] ?? "http://localhost:3000";
2282
2201
  }
2283
2202
  const authOptions = this.#authentication();
2284
- if (!isEmpty5(authOptions)) {
2203
+ if (!isEmpty4(authOptions)) {
2285
2204
  const [firstAuth] = authOptions;
2286
2205
  options.credentials = {
2287
2206
  [firstAuth.name]: this.#credentialExample(firstAuth.scheme)
2288
2207
  };
2289
2208
  }
2290
- const client = this.#constructClient(options);
2291
- return `${client.import}
2292
-
2293
- ${client.use}`;
2209
+ return this.#constructClient(options);
2294
2210
  }
2295
- #constructClient(options = {}) {
2211
+ /** The default instance when the README needs no settings, else a client created with them. */
2212
+ #constructClient(options) {
2213
+ const instance = camelcase5(this.#clientName);
2214
+ if (isEmpty4(options)) {
2215
+ return {
2216
+ name: instance,
2217
+ import: `import { ${instance} } from '${this.#packageName}';`,
2218
+ use: ""
2219
+ };
2220
+ }
2296
2221
  return {
2297
- import: `import { ${this.#clientName} } from '${this.#packageName}';`,
2298
- use: `const ${camelcase5(this.#clientName)} = new ${this.#clientName}({
2222
+ name: `create${this.#clientName}`,
2223
+ import: `import { create${this.#clientName} } from '${this.#packageName}';`,
2224
+ use: `const ${instance} = create${this.#clientName}({
2299
2225
  ${Object.entries(
2300
2226
  options
2301
2227
  ).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(",\n ")}
@@ -2322,7 +2248,7 @@ ${client.use}`;
2322
2248
  );
2323
2249
  const baseUrl = expandServerUrls(this.#spec.servers ?? [])[0] || "https://api.example.com";
2324
2250
  const authOptions = this.#authentication();
2325
- const hasApiKey = !isEmpty5(authOptions);
2251
+ const hasApiKey = !isEmpty4(authOptions);
2326
2252
  sections.push("### Configuration Options");
2327
2253
  sections.push("");
2328
2254
  sections.push("| Option | Type | Required | Description |");
@@ -2353,235 +2279,127 @@ ${client.use}`;
2353
2279
  return sections.join("\n");
2354
2280
  }
2355
2281
  paginationDocs() {
2356
- const paginationTypes = availablePaginationTypes(this.#spec);
2357
- if (!paginationTypes.offset && !paginationTypes.page && !paginationTypes.cursor) {
2282
+ const paginated = this.#paginatedOperations();
2283
+ const [first] = paginated;
2284
+ if (!first) {
2358
2285
  return "";
2359
2286
  }
2360
- const sections = [];
2361
- sections.push("## Pagination");
2362
- sections.push("");
2363
- sections.push(
2364
- "This SDK automatically handles pagination for endpoints that return multiple items."
2365
- );
2366
- sections.push("");
2367
- sections.push("### How it Works");
2368
- sections.push("");
2369
- sections.push(
2370
- "When you call a paginated endpoint, the SDK returns a pagination object that allows you to iterate through all results:"
2371
- );
2372
- sections.push("");
2373
- const availableTypes = [];
2374
- if (paginationTypes.offset) availableTypes.push("offset");
2375
- if (paginationTypes.page) availableTypes.push("page");
2376
- if (paginationTypes.cursor) availableTypes.push("cursor");
2377
- const primaryPaginationType = availableTypes[0];
2378
- const mockPaginatedOperation = {
2379
- "x-pagination": { type: primaryPaginationType },
2380
- tags: ["Products"],
2381
- operationId: "listProducts",
2382
- parameters: [],
2383
- "x-fn-name": "listProducts",
2384
- responses: {},
2385
- requestBody: {}
2386
- };
2387
- const mockOperationEntry = {
2388
- method: "get",
2389
- path: "/products",
2390
- tag: "Products"
2391
- };
2392
- const initialRequestPayload = createObjectLiteral({ limit: 20 });
2393
- const paginationExample = this.#pagination(
2394
- mockPaginatedOperation,
2395
- mockOperationEntry,
2396
- initialRequestPayload
2397
- );
2398
- sections.push(
2287
+ const { entry, operation } = first;
2288
+ const payload = this.#render(this.#example(operation));
2289
+ const request = this.#pagination(entry, payload);
2290
+ const sections = [
2291
+ "## Pagination",
2292
+ "",
2293
+ "A paginated endpoint resolves to a page: the response body, plus `hasNextPage()`, `getNextPage()` and `iterPages()`. `for await` over the request or the page yields every item across pages:",
2294
+ "",
2399
2295
  createCodeBlock("typescript", [
2400
- "// The SDK automatically handles pagination",
2401
- paginationExample.content,
2296
+ this.client(),
2402
2297
  "",
2403
- "// Access the current page data",
2404
- "const currentPage = result.getCurrentPage();",
2405
- "console.log(currentPage.data); // Array of product items",
2298
+ request.content,
2299
+ "console.log(result); // the response body of the first page",
2406
2300
  "",
2407
- "// Check if more pages exist",
2408
- "if (result.hasMore) {",
2409
- " await result.getNextPage({ signal: controller.signal });",
2301
+ "if (result.hasNextPage()) {",
2302
+ " const next = await result.getNextPage({ signal: controller.signal });",
2303
+ " console.log(next);",
2410
2304
  "}",
2411
2305
  "",
2412
- "// Or iterate through all pages with cancellable page fetches",
2413
- paginationExample.footer
2414
- ])
2415
- );
2416
- sections.push("");
2417
- sections.push("### Iterating Through All Pages");
2418
- sections.push("");
2419
- const iterationExample = this.#pagination(
2420
- mockPaginatedOperation,
2421
- mockOperationEntry,
2422
- createObjectLiteral({ limit: 100 })
2423
- );
2424
- sections.push(
2306
+ "// Or iterate through every page, each fetch cancellable",
2307
+ request.footer
2308
+ ]),
2309
+ "",
2310
+ "### Iterating Through All Items",
2311
+ "",
2425
2312
  createCodeBlock("typescript", [
2426
- "// Using async iteration to process all pages",
2427
- iterationExample.content,
2313
+ this.client(),
2428
2314
  "",
2429
- iterationExample.footer
2430
- ])
2431
- );
2432
- sections.push("");
2433
- if (availableTypes.length > 1) {
2434
- sections.push("### Pagination Types");
2435
- sections.push("");
2436
- sections.push(
2437
- "Your API uses the following pagination strategies, automatically detected by the SDK:"
2438
- );
2439
- sections.push("");
2440
- } else {
2441
- sections.push("### Pagination Strategy");
2442
- sections.push("");
2443
- sections.push(
2444
- "Your API uses the following pagination strategy, automatically detected by the SDK:"
2445
- );
2446
- sections.push("");
2447
- }
2448
- for (const paginationType of availableTypes) {
2449
- const typeSpecificOperation = {
2450
- "x-pagination": { type: paginationType },
2451
- tags: ["Products"],
2452
- operationId: "listProducts",
2453
- parameters: [],
2454
- "x-fn-name": "listProducts",
2455
- responses: {},
2456
- requestBody: {}
2457
- };
2458
- const typeSpecificEntry = {
2459
- method: "get",
2460
- path: "/products",
2461
- tag: "Products"
2462
- };
2463
- if (paginationType === "cursor") {
2464
- sections.push("#### Cursor Pagination");
2465
- sections.push("");
2466
- sections.push("Uses a cursor token to fetch the next page:");
2467
- sections.push("");
2468
- const cursorPaginationExample = this.#pagination(
2469
- typeSpecificOperation,
2470
- typeSpecificEntry,
2471
- createObjectLiteral({ limit: 20 })
2472
- );
2473
- sections.push(
2474
- createCodeBlock("typescript", [
2475
- cursorPaginationExample.content,
2476
- "",
2477
- "// Iterate through all pages using cursor",
2478
- cursorPaginationExample.footer
2479
- ])
2480
- );
2481
- sections.push("");
2482
- }
2483
- if (paginationType === "offset") {
2484
- sections.push("#### Offset Pagination");
2485
- sections.push("");
2486
- sections.push("Uses offset and limit parameters:");
2487
- sections.push("");
2488
- const offsetPaginationExample = this.#pagination(
2489
- typeSpecificOperation,
2490
- typeSpecificEntry,
2491
- createObjectLiteral({ limit: 20, offset: 0 })
2492
- );
2493
- sections.push(
2494
- createCodeBlock("typescript", [
2495
- offsetPaginationExample.content,
2496
- "",
2497
- "// Iterate through all pages using offset",
2498
- offsetPaginationExample.footer
2499
- ])
2500
- );
2501
- sections.push("");
2502
- }
2503
- if (paginationType === "page") {
2504
- sections.push("#### Page Pagination");
2505
- sections.push("");
2506
- sections.push("Uses page number and page size:");
2507
- sections.push("");
2508
- const pagePaginationExample = this.#pagination(
2509
- typeSpecificOperation,
2510
- typeSpecificEntry,
2511
- createObjectLiteral({ page: 1, pageSize: 20 })
2512
- );
2513
- sections.push(
2514
- createCodeBlock("typescript", [
2515
- pagePaginationExample.content,
2516
- "",
2517
- "// Iterate through all pages using page numbers",
2518
- pagePaginationExample.footer
2519
- ])
2520
- );
2521
- sections.push("");
2522
- }
2523
- }
2524
- if (availableTypes.length > 1) {
2525
- sections.push(
2526
- "The SDK handles the differences transparently, providing a consistent interface regardless of the underlying pagination type."
2527
- );
2528
- }
2315
+ `for await (const item of ${camelcase5(this.#clientName)}.request('${endpointOf(entry)}', ${payload})) {`,
2316
+ " console.log(item);",
2317
+ "}"
2318
+ ]),
2319
+ "",
2320
+ "### Pagination Strategies",
2321
+ "",
2322
+ ...paginated.map(
2323
+ ({ entry: entry2, pagination }) => `- \`${endpointOf(entry2)}\`: ${paginationStrategy(pagination)}`
2324
+ )
2325
+ ];
2529
2326
  return sections.join("\n");
2530
2327
  }
2328
+ /** The first paginated operation of each pagination type, in README order. */
2329
+ #paginatedOperations() {
2330
+ const paginated = /* @__PURE__ */ new Map();
2331
+ forEachOperation5(this.#spec, (entry, operation) => {
2332
+ const pagination = operation["x-pagination"];
2333
+ if (pagination && !paginated.has(pagination.type)) {
2334
+ paginated.set(pagination.type, { entry, operation, pagination });
2335
+ }
2336
+ });
2337
+ return [...paginated.values()];
2338
+ }
2339
+ /** The operation the README lists first. */
2340
+ #firstOperation() {
2341
+ let first;
2342
+ forEachOperation5(this.#spec, (entry, operation) => {
2343
+ first ??= { entry, operation };
2344
+ });
2345
+ return first;
2346
+ }
2531
2347
  errorHandlingDocs() {
2532
2348
  const sections = [];
2349
+ const first = this.#firstOperation();
2533
2350
  sections.push("## Error Handling");
2534
2351
  sections.push("");
2535
2352
  sections.push(
2536
2353
  "The SDK provides structured error handling with typed HTTP error responses."
2537
2354
  );
2538
2355
  sections.push("");
2539
- sections.push("### Error Response Types");
2540
- sections.push("");
2541
- sections.push(
2542
- "All API errors extend from `APIError` and include the HTTP status code and response data:"
2543
- );
2544
- sections.push("");
2545
- sections.push(
2546
- createCodeBlock("typescript", [
2547
- `import { BadRequest, Unauthorized, NotFound, TooManyRequests, InternalServerError, ParseError } from "${this.#packageName}";`,
2548
- "try {",
2549
- "const usersList = ",
2550
- this.#toRequest(
2551
- {
2552
- method: "get",
2553
- path: "/users",
2554
- tag: "Users"
2555
- },
2556
- createObjectLiteral({})
2557
- ),
2558
- " // Handle successful response",
2559
- "} catch (error) {",
2560
- " // Handle different error types",
2561
- " if (error instanceof BadRequest) {",
2562
- ' console.error("Bad request:", error.data);',
2563
- ' console.log("Status:", error.status); // 400',
2564
- " } else if (error instanceof Unauthorized) {",
2565
- ' console.error("Authentication failed:", error.data);',
2566
- ' console.log("Status:", error.status); // 401',
2567
- " } else if (error instanceof NotFound) {",
2568
- ' console.error("Resource not found:", error.data);',
2569
- ' console.log("Status:", error.status); // 404',
2570
- " } else if (error instanceof TooManyRequests) {",
2571
- ' console.error("Rate limited:", error.data);',
2572
- " if (error.data.retryAfter) {",
2573
- ' console.log("Retry after:", error.data.retryAfter);',
2574
- " }",
2575
- " } else if (error instanceof InternalServerError) {",
2576
- ' console.error("Server error:", error.data);',
2577
- ' console.log("Status:", error.status); // 500',
2578
- " } else if (error instanceof ParseError) {",
2579
- ' console.error("Input validation failed:", error.data);',
2580
- " }",
2581
- "}"
2582
- ])
2583
- );
2584
- sections.push("");
2356
+ if (first) {
2357
+ const { entry: entry2, operation: operation2 } = first;
2358
+ const payload = this.#render(this.#example(operation2));
2359
+ sections.push("### Error Response Types");
2360
+ sections.push("");
2361
+ sections.push(
2362
+ "All API errors extend from `APIError` and include the HTTP status code, the response headers and the response body:"
2363
+ );
2364
+ sections.push("");
2365
+ sections.push(
2366
+ createCodeBlock("typescript", [
2367
+ ...this.#clientWith([
2368
+ "BadRequest",
2369
+ "Unauthorized",
2370
+ "NotFound",
2371
+ "TooManyRequests",
2372
+ "InternalServerError",
2373
+ "ParseError"
2374
+ ]),
2375
+ "",
2376
+ "try {",
2377
+ ` const result = ${this.#toRequest(entry2, payload)}`,
2378
+ " console.log(result);",
2379
+ "} catch (error) {",
2380
+ " if (error instanceof BadRequest) {",
2381
+ ' console.error("Bad request:", error.data);',
2382
+ ' console.log("Status:", error.status); // 400',
2383
+ " } else if (error instanceof Unauthorized) {",
2384
+ ' console.error("Authentication failed:", error.data);',
2385
+ ' console.log("Status:", error.status); // 401',
2386
+ " } else if (error instanceof NotFound) {",
2387
+ ' console.error("Resource not found:", error.data);',
2388
+ ' console.log("Status:", error.status); // 404',
2389
+ " } else if (error instanceof TooManyRequests) {",
2390
+ ' console.error("Rate limited:", error.data);',
2391
+ ` console.log("Retry after:", error.headers.get('Retry-After'));`,
2392
+ " } else if (error instanceof InternalServerError) {",
2393
+ ' console.error("Server error:", error.data);',
2394
+ ' console.log("Status:", error.status); // 500',
2395
+ " } else if (error instanceof ParseError) {",
2396
+ ' console.error("Input validation failed:", error.data);',
2397
+ " }",
2398
+ "}"
2399
+ ])
2400
+ );
2401
+ sections.push("");
2402
+ }
2585
2403
  sections.push("### Available Error Classes");
2586
2404
  sections.push("");
2587
2405
  sections.push("#### Input Validation Errors");
@@ -2611,94 +2429,60 @@ ${client.use}`;
2611
2429
  sections.push("- `BadGateway` (502) - Bad gateway");
2612
2430
  sections.push("- `ServiceUnavailable` (503) - Service unavailable");
2613
2431
  sections.push("- `GatewayTimeout` (504) - Gateway timeout");
2614
- sections.push("");
2615
- sections.push("### Validation Errors");
2616
- sections.push("");
2617
- sections.push(
2618
- "Validation errors (422) include detailed field-level error information:"
2619
- );
2620
- sections.push("### Input Validation Errors");
2621
- sections.push("");
2622
- sections.push(
2623
- "When request input fails validation against the API schema, a `ParseError` is thrown:"
2624
- );
2625
- sections.push("");
2626
- sections.push(
2627
- createCodeBlock("typescript", [
2628
- `import { ParseError } from "${this.#packageName}";`,
2629
- "",
2630
- "try {",
2631
- " // Invalid input that doesn't match the expected schema",
2632
- " const newUser = ",
2633
- this.#toRequest(
2634
- {
2635
- method: "post",
2636
- path: "/users",
2637
- tag: "Users"
2638
- },
2639
- createObjectLiteral({
2640
- email: 123,
2641
- // should be string
2642
- firstName: "",
2643
- // empty required field
2644
- age: -5
2645
- // invalid age value
2646
- })
2647
- ),
2648
- "} catch (error) {",
2649
- " if (error instanceof ParseError) {",
2650
- ' console.log("Input validation failed:");',
2651
- " ",
2652
- " // Field-level errors",
2653
- " if (error.data.fieldErrors) {",
2654
- " Object.entries(error.data.fieldErrors).forEach(([fieldName, validationIssues]) => {",
2655
- ' console.log(` ${fieldName}: ${validationIssues.map(issue => issue.message).join(", ")}`);',
2656
- " });",
2657
- " }",
2658
- " ",
2659
- " // Form-level errors",
2660
- " if (error.data.formErrors.length > 0) {",
2661
- ' console.log(` Form errors: ${error.data.formErrors.map(issue => issue.message).join(", ")}`);',
2662
- " }",
2663
- " }",
2664
- "}"
2665
- ])
2666
- );
2667
- sections.push("");
2668
- sections.push(
2669
- "`ParseError` contains detailed validation information using Zod's flattened error format, providing specific field-level and form-level validation messages."
2670
- );
2432
+ if (!first) {
2433
+ return sections.join("\n");
2434
+ }
2435
+ const { entry, operation } = first;
2436
+ const invalidInput = this.#invalidInput(operation);
2437
+ if (invalidInput !== void 0) {
2438
+ sections.push("");
2439
+ sections.push("### Input Validation Errors");
2440
+ sections.push("");
2441
+ sections.push(
2442
+ "When request input fails validation against the API schema, a `ParseError` is thrown before the request is sent:"
2443
+ );
2444
+ sections.push("");
2445
+ sections.push(
2446
+ createCodeBlock("typescript", [
2447
+ ...this.#clientWith(["ParseError"]),
2448
+ "",
2449
+ "try {",
2450
+ ` const result = ${this.#toRequest(entry, invalidInput)}`,
2451
+ " console.log(result);",
2452
+ "} catch (error) {",
2453
+ " if (error instanceof ParseError) {",
2454
+ " for (const [fieldName, issues] of Object.entries(error.data.fieldErrors)) {",
2455
+ " console.log(`${fieldName}: ${(issues ?? []).map((issue) => issue.message).join(', ')}`);",
2456
+ " }",
2457
+ " if (error.data.formErrors.length > 0) {",
2458
+ " console.log(`Form errors: ${error.data.formErrors.map((issue) => issue.message).join(', ')}`);",
2459
+ " }",
2460
+ " }",
2461
+ "}"
2462
+ ])
2463
+ );
2464
+ sections.push("");
2465
+ sections.push(
2466
+ "`ParseError` contains detailed validation information using Zod's flattened error format, providing specific field-level and form-level validation messages."
2467
+ );
2468
+ }
2671
2469
  sections.push("");
2672
2470
  sections.push("### Rate Limiting");
2673
2471
  sections.push("");
2674
2472
  sections.push(
2675
- "Rate limit responses may include a `retryAfter` field indicating when to retry:"
2473
+ "A `TooManyRequests` error carries the response headers, so a `Retry-After` header tells when to retry:"
2676
2474
  );
2677
2475
  sections.push("");
2678
2476
  sections.push(
2679
2477
  createCodeBlock("typescript", [
2680
- `import { TooManyRequests } from "${this.#packageName}";`,
2478
+ ...this.#clientWith(["TooManyRequests"]),
2681
2479
  "",
2682
2480
  "try {",
2683
- " const apiResponse = ",
2684
- this.#toRequest(
2685
- {
2686
- method: "get",
2687
- path: "/api/data",
2688
- tag: "Data"
2689
- },
2690
- createObjectLiteral({})
2691
- ),
2481
+ ` const result = ${this.#toRequest(entry, this.#render(this.#example(operation)))}`,
2482
+ " console.log(result);",
2692
2483
  "} catch (error) {",
2693
2484
  " if (error instanceof TooManyRequests) {",
2694
- " const retryAfterSeconds = error.data.retryAfter;",
2695
- " if (retryAfterSeconds) {",
2696
- " console.log(`Rate limited. Retry after: ${retryAfterSeconds} seconds`);",
2697
- " // Implement your own retry logic",
2698
- " setTimeout(() => {",
2699
- " // Retry the request",
2700
- " }, retryAfterSeconds * 1000);",
2701
- " }",
2485
+ " console.log(`Rate limited. Retry after: ${error.headers.get('Retry-After')}`);",
2702
2486
  " }",
2703
2487
  "}"
2704
2488
  ])
@@ -2707,7 +2491,7 @@ ${client.use}`;
2707
2491
  }
2708
2492
  authenticationDocs() {
2709
2493
  const authOptions = this.#authentication();
2710
- if (isEmpty5(authOptions)) {
2494
+ if (isEmpty4(authOptions)) {
2711
2495
  return "";
2712
2496
  }
2713
2497
  const only = authOptions.length === 1;
@@ -2729,7 +2513,9 @@ ${client.use}`;
2729
2513
  const client = this.#constructClient({
2730
2514
  credentials: { [name]: this.#credentialExample(scheme) }
2731
2515
  });
2732
- sections.push(createCodeBlock("typescript", [client.use]));
2516
+ sections.push(
2517
+ createCodeBlock("typescript", [client.import, "", client.use])
2518
+ );
2733
2519
  sections.push("");
2734
2520
  }
2735
2521
  return sections.join("\n");
@@ -2750,7 +2536,7 @@ ${client.use}`;
2750
2536
  const initialClientOptions = {
2751
2537
  baseUrl: "https://api.production-service.com"
2752
2538
  };
2753
- if (!isEmpty5(authOptions)) {
2539
+ if (!isEmpty4(authOptions)) {
2754
2540
  const [primaryAuth] = authOptions;
2755
2541
  initialClientOptions.credentials = {
2756
2542
  [primaryAuth.name]: this.#credentialExample(primaryAuth.scheme)
@@ -2758,14 +2544,16 @@ ${client.use}`;
2758
2544
  }
2759
2545
  const initialClientSetup = this.#constructClient(initialClientOptions);
2760
2546
  const configurationUpdateCode = [
2547
+ initialClientSetup.import,
2548
+ "",
2761
2549
  "// Initial client setup",
2762
2550
  initialClientSetup.use,
2763
2551
  "",
2764
2552
  "// Later, update specific options",
2765
- "client.setOptions({",
2553
+ `${camelcase5(this.#clientName)}.setOptions({`,
2766
2554
  " baseUrl: 'https://api.staging-service.com',"
2767
2555
  ];
2768
- if (!isEmpty5(authOptions)) {
2556
+ if (!isEmpty4(authOptions)) {
2769
2557
  const [primaryAuth] = authOptions;
2770
2558
  configurationUpdateCode.push(
2771
2559
  ` credentials: ${JSON.stringify({
@@ -2800,207 +2588,181 @@ function authenticationHeading(name, scheme, only) {
2800
2588
  function createCodeBlock(language, content) {
2801
2589
  return ["```" + language, ...content, "```"].join("\n");
2802
2590
  }
2803
- function createObjectLiteral(obj, indent = " ") {
2804
- return "{\n" + Object.entries(obj).map(([key, value]) => `${indent}${key}: ${JSON.stringify(value)}`).join(",\n") + `
2805
- ${indent.slice(0, -1)}}`;
2591
+ function endpointOf(entry) {
2592
+ return `${entry.method.toUpperCase()} ${entry.path}`;
2806
2593
  }
2807
- function availablePaginationTypes(spec) {
2808
- let offset = false;
2809
- let page = false;
2810
- let cursor = false;
2811
- forEachOperation5(spec, (entry, operation) => {
2812
- if (operation["x-pagination"]) {
2813
- switch (operation["x-pagination"].type) {
2814
- case "offset":
2815
- offset = true;
2816
- break;
2817
- case "page":
2818
- page = true;
2819
- break;
2820
- case "cursor":
2821
- cursor = true;
2822
- break;
2823
- }
2824
- }
2594
+ function paginationStrategy(pagination) {
2595
+ switch (pagination.type) {
2596
+ case "offset":
2597
+ return `offset pagination, with the \`${pagination.offsetParamName}\` and \`${pagination.limitParamName}\` parameters.`;
2598
+ case "page":
2599
+ return `page pagination, with the \`${pagination.pageNumberParamName}\` and \`${pagination.pageSizeParamName}\` parameters.`;
2600
+ case "cursor":
2601
+ return `cursor pagination, with the \`${pagination.cursorParamName}\` and \`${pagination.limitParamName}\` parameters.`;
2602
+ }
2603
+ }
2604
+ function isRecord(value) {
2605
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2606
+ }
2607
+ function wrongTypeValue(schema) {
2608
+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
2609
+ if (types.length === 0 || schema.format === "binary" || schema.format === "byte" || schema.contentEncoding === "binary") {
2610
+ return void 0;
2611
+ }
2612
+ const candidates = [
2613
+ { value: 123, types: ["number", "integer"] },
2614
+ { value: "text", types: ["string"] },
2615
+ { value: true, types: ["boolean"] }
2616
+ ];
2617
+ return candidates.find(
2618
+ (candidate) => candidate.types.every((type) => !types.includes(type))
2619
+ )?.value;
2620
+ }
2621
+
2622
+ // packages/typescript/src/lib/generate.ts
2623
+ async function render(openapi, options) {
2624
+ return renderFiles(await toSdkIR(openapi, options), options);
2625
+ }
2626
+ async function renderModule(openapi, options) {
2627
+ const spec = await toSdkIR(openapi, {});
2628
+ const name = clientName(options.name);
2629
+ const modelName = createModelNamer(name);
2630
+ const { groups, commonZod, endpoints } = operationFragments({
2631
+ spec,
2632
+ modelName,
2633
+ zodRefs: moduleReferences,
2634
+ endpointRefs: moduleReferences
2635
+ });
2636
+ refuseTakenNames(options.name, name, inputSchemaNames(groups));
2637
+ const client = {
2638
+ name,
2639
+ servers: expandServerUrls(spec.servers),
2640
+ securitySchemes: spec.components.securitySchemes
2641
+ };
2642
+ const bodies = inlineBodyLocations(spec);
2643
+ const { text, spans } = assembleModule({
2644
+ commonZod,
2645
+ inputs: Object.values(groups).flat().flatMap(
2646
+ (operation) => operation.inputs.map(({ schemaName, zod }) => ({
2647
+ name: schemaName,
2648
+ zod
2649
+ }))
2650
+ ),
2651
+ models: modelDeclarations(spec, modelName, moduleReferences).map(
2652
+ ({ schemaName, inline, typeName, doc, type }) => ({
2653
+ typeName,
2654
+ doc,
2655
+ type,
2656
+ location: inline ? bodies.get(schemaName) : ["components", "schemas", schemaName]
2657
+ })
2658
+ ),
2659
+ endpoints: Object.values(endpoints).flat(),
2660
+ client: clientDeclarations(client, moduleReferences, "__routes"),
2661
+ clientNames: clientDeclaredNames(name),
2662
+ runtimeExports: clientRuntimeExports,
2663
+ runtimeTypeExports: clientRuntimeTypeExports(client)
2825
2664
  });
2826
2665
  return {
2827
- offset,
2828
- page,
2829
- cursor
2666
+ text,
2667
+ spans: spans.flatMap((span) => {
2668
+ const location = documentLocation(openapi, span.location);
2669
+ return location ? [{ ...span, location }] : [];
2670
+ })
2830
2671
  };
2831
2672
  }
2832
-
2833
- // packages/typescript/src/lib/generate.ts
2834
- async function generate(openapi, settings) {
2835
- const unresolvedSecuritySchemes = /* @__PURE__ */ new Set();
2836
- const spec = await toIR(
2837
- {
2838
- spec: openapi,
2839
- responses: { flattenErrorResponses: true },
2840
- pagination: settings.pagination,
2841
- onDiagnostic: ({ code, message }) => {
2842
- if (code === "unresolved-security-scheme") {
2843
- unresolvedSecuritySchemes.add(message);
2673
+ function documentLocation(document, location) {
2674
+ let current = document;
2675
+ let path = [];
2676
+ for (const token of location) {
2677
+ while (isRef5(current)) {
2678
+ path = pointerTokens(current.$ref.slice(1));
2679
+ current = valueAtPointer(document, path);
2680
+ }
2681
+ if (!hasMember(current, token)) {
2682
+ return void 0;
2683
+ }
2684
+ current = Reflect.get(current, token);
2685
+ path = [...path, token];
2686
+ }
2687
+ return path;
2688
+ }
2689
+ function hasMember(value, token) {
2690
+ return typeof value === "object" && value !== null && token in value;
2691
+ }
2692
+ function inlineBodyLocations(spec) {
2693
+ const locations = /* @__PURE__ */ new Map();
2694
+ forEachOperation6(spec, (entry, operation) => {
2695
+ for (const [status, response] of Object.entries(operation.responses)) {
2696
+ for (const [type, media] of Object.entries(response.content)) {
2697
+ if (isRef5(media.schema)) {
2698
+ locations.set(parseRef3(media.schema.$ref).model, [
2699
+ "paths",
2700
+ entry.path,
2701
+ entry.method,
2702
+ "responses",
2703
+ status,
2704
+ "content",
2705
+ type,
2706
+ "schema"
2707
+ ]);
2844
2708
  }
2845
2709
  }
2846
- },
2847
- false
2848
- );
2849
- if (unresolvedSecuritySchemes.size) {
2850
- throw new TypeError([...unresolvedSecuritySchemes].join("\n"));
2710
+ }
2711
+ });
2712
+ return locations;
2713
+ }
2714
+ async function generate(openapi, settings) {
2715
+ const { packageName } = settings;
2716
+ if (!packageName.trim()) {
2717
+ throw new TypeError(
2718
+ `packageName must name the generated npm package (packageName: '@acme/pets'); got ${JSON.stringify(packageName)}.`
2719
+ );
2851
2720
  }
2852
- const style = Object.assign({}, { name: "github" }, settings.style ?? {});
2721
+ const options = {
2722
+ name: settings.name,
2723
+ useTsExtension: settings.useTsExtension ?? true,
2724
+ pagination: settings.pagination,
2725
+ agentTools: settings.agentTools
2726
+ };
2727
+ const spec = await toSdkIR(openapi, options);
2728
+ const files = renderFiles(spec, options);
2853
2729
  const output = settings.mode === "full" ? join2(settings.output, "src") : settings.output;
2854
- settings.useTsExtension ??= true;
2855
- settings.readme ??= true;
2856
- const { writer, files: writtenFiles } = createWriterProxy(
2857
- settings.writer ?? writeFiles,
2858
- output
2730
+ const writer = settings.writer ?? writeFiles;
2731
+ await writer(output, files);
2732
+ const metadata = await readWriteMetadata(
2733
+ output,
2734
+ Object.keys(files).map(addLeadingSlash),
2735
+ writer
2859
2736
  );
2860
- settings.writer = writer;
2861
- settings.readFolder ??= async (folder) => {
2862
- const files = await readdir(folder, { withFileTypes: true });
2863
- return files.map((file) => ({
2864
- fileName: file.name,
2865
- filePath: join2(file.parentPath, file.name),
2866
- isFolder: file.isDirectory()
2867
- }));
2868
- };
2869
- const makeImport = (moduleSpecifier) => {
2870
- return settings.useTsExtension ? `${moduleSpecifier}.ts` : moduleSpecifier;
2871
- };
2872
- const { endpoints, groups, commonZod } = generateCode({
2873
- spec,
2874
- style,
2875
- makeImport
2876
- });
2877
- const clientName = pascalcase5((settings.name || "client").trim());
2878
- const packageName = settings.packageName ?? (settings.name ? `@${spinalcase4(settings.name.trim().toLowerCase())}/sdk` : "sdk");
2879
- const inputs = toInputs(groups, commonZod, makeImport);
2880
- const models = serializeModels(spec);
2881
- await settings.writer(output, {
2882
- "outputs/.gitkeep": "",
2883
- "inputs/.gitkeep": "",
2884
- "models/.getkeep": ""
2885
- });
2886
- await settings.writer(join2(output, "http"), {
2887
- "parse-response.ts": parse_response_default,
2888
- "response.ts": response_default,
2889
- "parser.ts": parser_default,
2890
- "request.ts": request_default,
2891
- "sse.ts": sse_default,
2892
- "dispatcher.ts": `import z from 'zod';
2893
- import { type Interceptor } from '${makeImport("../http/interceptors")}';
2894
- import { type RequestConfig } from '${makeImport("../http/request")}';
2895
- import { buffered } from '${makeImport("./parse-response")}';
2896
- import { type SSEListener } from '${makeImport("./sse")}';
2897
- import { APIError, APIResponse, type SuccessfulResponse, type RebindSuccessPayload } from '${makeImport("./response")}';
2898
-
2899
- ${template2(dispatcher_default, {})()}`,
2900
- "interceptors.ts": `
2901
- import type { RequestConfig, HeadersInit } from './${makeImport("request")}';
2902
- ${interceptors_default}`,
2903
- "security.ts": Object.keys(spec.components.securitySchemes).length ? security_default({
2904
- makeImport,
2905
- securitySchemes: spec.components.securitySchemes
2906
- }) : null
2907
- });
2908
- await settings.writer(output, {
2909
- "client.ts": client_default({
2910
- name: clientName,
2911
- servers: expandServerUrls(spec.servers ?? []),
2912
- securitySchemes: spec.components.securitySchemes,
2913
- makeImport
2914
- }),
2915
- ...inputs,
2916
- ...endpoints
2917
- });
2918
- await settings.writer(output, models);
2919
- await settings.writer(join2(output, "pagination"), {
2920
- "cursor-pagination.ts": cursor_pagination_default,
2921
- "offset-pagination.ts": offset_pagination_default,
2922
- "page-pagination.ts": page_pagination_default
2923
- });
2924
- const metadata = await readWriteMetadata(output, Array.from(writtenFiles));
2925
- if (settings.cleanup !== false && writtenFiles.size > 0) {
2926
- await cleanFiles(metadata.content, output, [
2737
+ if (settings.cleanup !== false) {
2738
+ await cleanFiles(metadata, output, [
2927
2739
  "/tsconfig*.json",
2928
2740
  "/package.json",
2929
2741
  "/metadata.json",
2930
2742
  "/**/index.ts"
2931
2743
  ]);
2932
2744
  }
2933
- const folders = [
2934
- getFolderExports(
2935
- join2(output, "outputs"),
2936
- settings.readFolder,
2937
- settings.useTsExtension
2938
- ),
2939
- getFolderExports(
2940
- join2(output, "inputs"),
2941
- settings.readFolder,
2942
- settings.useTsExtension,
2943
- ["ts"],
2944
- (dirent) => dirent.isFolder && ["schemas"].includes(dirent.fileName)
2945
- ),
2946
- getFolderExports(
2947
- join2(output, "api"),
2948
- settings.readFolder,
2949
- settings.useTsExtension
2950
- ),
2951
- getFolderExports(
2952
- join2(output, "http"),
2953
- settings.readFolder,
2954
- settings.useTsExtension,
2955
- ["ts"],
2956
- (dirent) => !["response.ts", "parser.ts"].includes(dirent.fileName)
2957
- ),
2958
- getFolderExports(
2959
- join2(output, "models"),
2960
- settings.readFolder,
2961
- settings.useTsExtension
2962
- )
2963
- ];
2964
- const [outputIndex, inputsIndex, apiIndex, httpIndex, modelsIndex] = await Promise.all(folders);
2965
- await settings.writer(join2(output, "pagination"), {
2966
- "index.ts": await getFolderExports(
2967
- join2(output, "pagination"),
2968
- settings.readFolder,
2969
- settings.useTsExtension,
2970
- ["ts"]
2745
+ const listed = await readFolder(output, true);
2746
+ const userIndexes = new Map(
2747
+ await Promise.all(
2748
+ listed.filter((path) => path.endsWith("/index.ts") && !(path in files)).map(
2749
+ async (path) => [path, await readFile(join2(output, path), "utf-8")]
2750
+ )
2971
2751
  )
2972
- });
2973
- await settings.writer(output, {
2974
- "api/index.ts": apiIndex,
2975
- "outputs/index.ts": outputIndex,
2976
- "inputs/index.ts": inputsIndex || null,
2977
- "http/index.ts": httpIndex,
2978
- "models/index.ts": modelsIndex
2979
- // ...(modelsImports.length ? { 'models/index.ts': modelsIndex } : {}),
2980
- });
2981
- switch (settings.agentTools) {
2982
- case "openai-agents":
2983
- await settings.writer(output, {
2984
- "agents.ts": `${generateOpenAIAgentTools(spec)}
2985
- ${utils_default}`
2986
- });
2987
- break;
2988
- case "ai-sdk":
2989
- await settings.writer(output, {
2990
- "agents.ts": `${generateAISDKTools(spec)}
2991
- ${utils_default}`
2992
- });
2993
- break;
2994
- }
2995
- await settings.writer(output, {
2996
- "index.ts": await getFolderExports(
2997
- output,
2998
- settings.readFolder,
2999
- settings.useTsExtension,
3000
- ["ts"],
3001
- (config) => config.fileName.endsWith("pagination") || config.fileName.endsWith("agents")
2752
+ );
2753
+ const indexes = indexFiles(
2754
+ /* @__PURE__ */ new Set([...Object.keys(files), ...listed]),
2755
+ (path) => files[path] ?? userIndexes.get(path),
2756
+ options.useTsExtension
2757
+ );
2758
+ const changedIndexes = Object.fromEntries(
2759
+ Object.entries(indexes).filter(
2760
+ ([path, content]) => files[path] !== content
3002
2761
  )
3003
- });
2762
+ );
2763
+ if (Object.keys(changedIndexes).length) {
2764
+ await writer(output, changedIndexes);
2765
+ }
3004
2766
  if (settings.mode === "full") {
3005
2767
  const configFiles = {
3006
2768
  "package.json": {
@@ -3010,7 +2772,6 @@ ${utils_default}`
3010
2772
  name: packageName,
3011
2773
  version: "0.0.1",
3012
2774
  type: "module",
3013
- ...settings.agentTools === "ai-sdk" ? { engines: { node: ">=22" } } : {},
3014
2775
  main: "./src/index.ts",
3015
2776
  module: "./src/index.ts",
3016
2777
  types: "./src/index.ts",
@@ -3027,9 +2788,9 @@ ${utils_default}`
3027
2788
  },
3028
2789
  dependencies: {
3029
2790
  "fast-content-type-parse": "^3.0.0",
3030
- zod: "^4.3.0",
2791
+ zod: "^4.6.7",
3031
2792
  ...settings.agentTools === "ai-sdk" ? { ai: "^7.0.29" } : {},
3032
- ...settings.agentTools === "openai-agents" ? { "@openai/agents": "^0.13.4" } : {}
2793
+ ...settings.agentTools === "openai-agents" ? { "@openai/agents": "^0.21.0" } : {}
3033
2794
  }
3034
2795
  },
3035
2796
  null,
@@ -3056,11 +2817,12 @@ ${utils_default}`
3056
2817
  )
3057
2818
  }
3058
2819
  };
3059
- await settings.writer(settings.output, configFiles);
2820
+ await writer(settings.output, configFiles);
3060
2821
  }
3061
- if (settings.readme) {
3062
- const path = typeof settings.readme === "string" ? settings.readme : "README.md";
3063
- await settings.writer(settings.output, {
2822
+ const readme = settings.readme ?? true;
2823
+ if (readme) {
2824
+ const path = typeof readme === "string" ? readme : "README.md";
2825
+ await writer(settings.output, {
3064
2826
  [path]: toReadme(spec, new TypeScriptSnippet(spec, settings))
3065
2827
  });
3066
2828
  }
@@ -3070,9 +2832,111 @@ ${utils_default}`
3070
2832
  });
3071
2833
  return { packageName };
3072
2834
  }
3073
- function serializeModels(spec) {
2835
+ async function toSdkIR(openapi, options) {
2836
+ const unresolvedSecuritySchemes = /* @__PURE__ */ new Set();
2837
+ const spec = await toIR(
2838
+ {
2839
+ spec: openapi,
2840
+ responses: { flattenErrorResponses: true },
2841
+ pagination: options.pagination,
2842
+ onDiagnostic: ({ code, message }) => {
2843
+ if (code === "unresolved-security-scheme") {
2844
+ unresolvedSecuritySchemes.add(message);
2845
+ }
2846
+ }
2847
+ },
2848
+ false
2849
+ );
2850
+ if (unresolvedSecuritySchemes.size) {
2851
+ throw new TypeError([...unresolvedSecuritySchemes].join("\n"));
2852
+ }
2853
+ return spec;
2854
+ }
2855
+ var agentTools = {
2856
+ "ai-sdk": generateAISDKTools,
2857
+ "openai-agents": generateOpenAIAgentTools
2858
+ };
2859
+ function withSdkImports(source, makeImport) {
2860
+ return source.replaceAll(
2861
+ /(from ')(\.\.?\/[^']+)\.ts(')/g,
2862
+ (_, from, path, quote) => `${from}${makeImport(path)}${quote}`
2863
+ );
2864
+ }
2865
+ function renderFiles(spec, options) {
2866
+ const { useTsExtension } = options;
2867
+ const makeImport = (moduleSpecifier) => {
2868
+ return useTsExtension ? `${moduleSpecifier}.ts` : moduleSpecifier;
2869
+ };
2870
+ const name = clientName(options.name);
2871
+ const modelName = createModelNamer(name);
2872
+ const { endpoints, groups, commonZod } = generateCode({
2873
+ spec,
2874
+ makeImport,
2875
+ modelName
2876
+ });
2877
+ refuseTakenNames(options.name, name, inputSchemaNames(groups));
2878
+ const files = {
2879
+ ...Object.fromEntries(
2880
+ Object.entries(runtime_sources_default).map(([path, source]) => [
2881
+ path,
2882
+ withSdkImports(source, makeImport)
2883
+ ])
2884
+ ),
2885
+ "client.ts": client_default({
2886
+ name,
2887
+ servers: expandServerUrls(spec.servers ?? []),
2888
+ securitySchemes: spec.components.securitySchemes,
2889
+ makeImport
2890
+ }),
2891
+ ...toInputs(groups, commonZod, makeImport),
2892
+ ...endpoints,
2893
+ ...serializeModels(spec, modelName),
2894
+ ...options.agentTools ? {
2895
+ "agents.ts": `${agentTools[options.agentTools](spec, makeImport)}
2896
+ ${utils_default}`
2897
+ } : {}
2898
+ };
2899
+ return {
2900
+ ...files,
2901
+ ...indexFiles(Object.keys(files), (path) => files[path], useTsExtension)
2902
+ };
2903
+ }
2904
+ function inputSchemaNames(groups) {
2905
+ return new Set(
2906
+ Object.values(groups).flat().flatMap(
2907
+ (operation) => operation.inputs.map(({ schemaName }) => schemaName)
2908
+ )
2909
+ );
2910
+ }
2911
+ function serializeModels(spec, modelName) {
3074
2912
  const filesMap = {};
3075
2913
  const files = {};
2914
+ for (const model of modelDeclarations(
2915
+ spec,
2916
+ modelName,
2917
+ fileReferences("models")
2918
+ )) {
2919
+ const fileContent = [
2920
+ ...model.sse ? [`import type { SSEListener } from '../http/sse.ts';`] : [],
2921
+ `
2922
+ ${model.doc}`,
2923
+ `export type ${model.typeName} = ${model.type};`
2924
+ ];
2925
+ filesMap[model.file] ??= [];
2926
+ filesMap[model.file].push(fileContent.join("\n"));
2927
+ }
2928
+ for (const [group, contents] of Object.entries(filesMap)) {
2929
+ let fileContent = contents.join("\n");
2930
+ if (fileContent.includes("models.")) {
2931
+ fileContent = `import type * as models from '../index.ts';
2932
+ ${fileContent}`;
2933
+ }
2934
+ files[group] = fileContent;
2935
+ }
2936
+ return files;
2937
+ }
2938
+ function modelDeclarations(spec, modelName, refs) {
2939
+ const models = [];
3076
2940
  const responseBodies = /* @__PURE__ */ new Map();
3077
2941
  forEachOperation6(spec, (_, operation) => {
3078
2942
  for (const response of Object.values(operation.responses)) {
@@ -3083,9 +2947,9 @@ function serializeModels(spec) {
3083
2947
  }
3084
2948
  });
3085
2949
  for (const [name, schema] of Object.entries(spec.components.schemas)) {
3086
- const isResponseBody = schema["x-responsebody"];
3087
- const isRequestBody = schema["x-requestbody"];
3088
- const responseGroup = schema["x-response-group"];
2950
+ const isResponseBody = "x-responsebody" in schema && schema["x-responsebody"];
2951
+ const isRequestBody = "x-requestbody" in schema && schema["x-requestbody"];
2952
+ const responseGroup = "x-response-group" in schema && typeof schema["x-response-group"] === "string" ? schema["x-response-group"] : void 0;
3089
2953
  const body = responseGroup ? responseBodies.get(name) : void 0;
3090
2954
  if (isRequestBody) {
3091
2955
  continue;
@@ -3093,74 +2957,73 @@ function serializeModels(spec) {
3093
2957
  const folder = isResponseBody ? "outputs" : "models";
3094
2958
  let typeContent;
3095
2959
  if (body === "sse") {
3096
- typeContent = "SSEListener";
2960
+ typeContent = refs.runtime("SSEListener");
3097
2961
  } else if (body === "stream") {
3098
- typeContent = "ReadableStream";
2962
+ typeContent = refs.global("ReadableStream");
3099
2963
  } else {
3100
- typeContent = new TypeScriptEmitter(spec).handle(schema, true);
3101
- }
3102
- const imports = [];
3103
- if (body === "sse") {
3104
- imports.push(`import type { SSEListener } from '../http/sse.ts';`);
2964
+ typeContent = new TypeScriptEmitter(spec, modelName, refs).handle(
2965
+ schema,
2966
+ true
2967
+ );
3105
2968
  }
3106
- const fileContent = [
3107
- ...imports,
3108
- `
3109
- ${schema.description ? `
2969
+ models.push({
2970
+ schemaName: name,
2971
+ inline: responseGroup !== void 0,
2972
+ typeName: modelName(name),
2973
+ doc: schema.description ? `
3110
2974
  /**
3111
2975
  * ${schema.description}
3112
2976
  */
3113
- ` : ""}`,
3114
- `export type ${pascalcase5(sanitizeTag4(name))} = ${typeContent};`
3115
- ];
3116
- const fileName = responseGroup ? join2(folder, `${spinalcase4(responseGroup)}.ts`) : join2(folder, `${spinalcase4(name)}.ts`);
3117
- filesMap[fileName] ??= [];
3118
- filesMap[fileName].push(fileContent.join("\n"));
3119
- }
3120
- for (const [group, contents] of Object.entries(filesMap)) {
3121
- let fileContent = contents.join("\n");
3122
- if (fileContent.includes("models.")) {
3123
- fileContent = `import type * as models from '../index.ts';
3124
- ${fileContent}`;
3125
- }
3126
- files[group] = fileContent;
2977
+ ` : "",
2978
+ type: typeContent,
2979
+ file: responseGroup ? join2(folder, `${moduleFileName(responseGroup)}.ts`) : join2(folder, `${moduleFileName(name)}.ts`),
2980
+ sse: body === "sse"
2981
+ });
3127
2982
  }
3128
- return files;
2983
+ return models;
3129
2984
  }
3130
2985
  function toInputs(operationsSet, commonZod, makeImport) {
3131
- const commonImports = commonZod.keys().toArray();
2986
+ const schemaNames = new Set(commonZod.keys());
3132
2987
  const inputs = {};
3133
2988
  for (const [name, operations] of Object.entries(operationsSet)) {
3134
2989
  const output = [];
3135
2990
  const imports = /* @__PURE__ */ new Set(['import { z } from "zod";']);
3136
- for (const operation of operations) {
3137
- const schemaName = camelcase6(`${operation.operationId} schema`);
3138
- const schema = `export const ${schemaName} = ${Object.keys(operation.schemas).length === 1 ? Object.values(operation.schemas)[0] : toLitObject2(operation.schemas)};`;
3139
- for (const it of commonImports) {
3140
- if (schema.includes(it)) {
3141
- imports.add(
3142
- `import { ${it} } from './schemas/${makeImport(spinalcase4(it))}';`
3143
- );
3144
- }
2991
+ for (const route of operations.flatMap((operation) => operation.inputs)) {
2992
+ for (const reference of route.references) {
2993
+ imports.add(
2994
+ `import { ${reference} } from './schemas/${makeImport(moduleFileName(reference))}';`
2995
+ );
3145
2996
  }
3146
- output.push(schema);
2997
+ output.push(
2998
+ inputGlobals(
2999
+ `export const ${route.schemaName} = ${route.zod};`,
3000
+ schemaNames
3001
+ )
3002
+ );
3147
3003
  }
3148
- inputs[`inputs/${spinalcase4(name)}.ts`] = [...imports, ...output].join("\n") + "\n";
3004
+ inputs[`inputs/${moduleFileName(name)}.ts`] = [...imports, ...output].join("\n") + "\n";
3149
3005
  }
3150
- const schemas = commonZod.entries().reduce((acc, [name, schema]) => {
3006
+ const schemas = commonZod.entries().reduce((acc, [name, { zod, references }]) => {
3151
3007
  const output = [`import { z } from 'zod';`];
3152
- const content = `export const ${name} = ${schema};`;
3153
- for (const schema2 of commonImports) {
3154
- const preciseMatch = new RegExp(`\\b${schema2}\\b`);
3155
- if (preciseMatch.test(content) && schema2 !== name) {
3008
+ const content = inputGlobals(
3009
+ `export const ${name} = ${zod};`,
3010
+ schemaNames
3011
+ );
3012
+ if (content.includes("z.ZodType<models.")) {
3013
+ output.push(
3014
+ `import type * as models from '${makeImport("../../models/index")}';`
3015
+ );
3016
+ }
3017
+ for (const reference of references) {
3018
+ if (reference !== name) {
3156
3019
  output.push(
3157
- `import { ${schema2} } from './${makeImport(spinalcase4(schema2))}';`
3020
+ `import { ${reference} } from './${makeImport(moduleFileName(reference))}';`
3158
3021
  );
3159
3022
  }
3160
3023
  }
3161
3024
  output.push(content);
3162
3025
  return [
3163
- [`inputs/schemas/${spinalcase4(name)}.ts`, output.join("\n")],
3026
+ [`inputs/schemas/${moduleFileName(name)}.ts`, output.join("\n")],
3164
3027
  ...acc
3165
3028
  ];
3166
3029
  }, []);
@@ -3171,13 +3034,11 @@ function toInputs(operationsSet, commonZod, makeImport) {
3171
3034
  }
3172
3035
  export {
3173
3036
  TypeScriptSnippet,
3174
- buildInput,
3037
+ clientName,
3038
+ createModelNamer,
3175
3039
  generate,
3176
- generateCode,
3177
- inputToPath,
3178
- operationSchema,
3179
- toEndpoint,
3180
- toHttpOutput,
3181
- toInputs
3040
+ refuseTakenNames,
3041
+ render,
3042
+ renderModule
3182
3043
  };
3183
3044
  //# sourceMappingURL=index.js.map