@sdk-it/typescript 0.46.8 → 0.46.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +97 -137
- package/dist/index.js.map +3 -3
- package/dist/lib/generate.d.ts.map +1 -1
- package/dist/lib/generator.d.ts +1 -1
- package/dist/lib/generator.d.ts.map +1 -1
- package/dist/lib/pagination-emit.d.ts.map +1 -1
- package/dist/lib/sdk.d.ts +4 -5
- package/dist/lib/sdk.d.ts.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
} from "@sdk-it/core/file-system.js";
|
|
13
13
|
import {
|
|
14
14
|
cleanFiles,
|
|
15
|
+
forEachOperation as forEachOperation6,
|
|
15
16
|
readWriteMetadata,
|
|
16
17
|
sanitizeTag as sanitizeTag4,
|
|
17
18
|
toIR
|
|
@@ -249,7 +250,7 @@ export async function request<const E extends keyof typeof schemas>(
|
|
|
249
250
|
),
|
|
250
251
|
${securitySchemeNames.length ? " createSecurityInterceptor(route.security, options.credentials),\n" : ""} createBaseUrlInterceptor(options.baseUrl),
|
|
251
252
|
],
|
|
252
|
-
signal: requestOptions
|
|
253
|
+
...(requestOptions?.signal ? { signal: requestOptions.signal } : {}),
|
|
253
254
|
});
|
|
254
255
|
return result as Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>;
|
|
255
256
|
}
|
|
@@ -330,7 +331,7 @@ var TypeScriptEmitter = class {
|
|
|
330
331
|
const propEntries = Object.entries(properties).map(([key, propSchema]) => {
|
|
331
332
|
const isRequired = (schema.required ?? []).includes(key);
|
|
332
333
|
const tsType = this.handle(propSchema, isRequired);
|
|
333
|
-
return `${this.#stringifyKey(key)}: ${tsType}`;
|
|
334
|
+
return `${this.#stringifyKey(key)}${isRequired ? "" : "?"}: ${tsType}`;
|
|
334
335
|
});
|
|
335
336
|
if (schema.additionalProperties) {
|
|
336
337
|
if (typeof schema.additionalProperties === "object") {
|
|
@@ -502,7 +503,7 @@ import { join } from "node:path";
|
|
|
502
503
|
import { camelcase as camelcase4, spinalcase as spinalcase2 } from "stringcase";
|
|
503
504
|
import {
|
|
504
505
|
followRef as followRef3,
|
|
505
|
-
isEmpty as
|
|
506
|
+
isEmpty as isEmpty3,
|
|
506
507
|
isRef as isRef3,
|
|
507
508
|
resolveRef as resolveRef2,
|
|
508
509
|
sortArray
|
|
@@ -795,16 +796,8 @@ function appendDefault(defaultValue) {
|
|
|
795
796
|
|
|
796
797
|
// packages/typescript/src/lib/sdk.ts
|
|
797
798
|
import { camelcase as camelcase3 } from "stringcase";
|
|
799
|
+
import { pascalcase as pascalcase3 } from "@sdk-it/core";
|
|
798
800
|
import {
|
|
799
|
-
isEmpty as isEmpty3,
|
|
800
|
-
pascalcase as pascalcase3
|
|
801
|
-
} from "@sdk-it/core";
|
|
802
|
-
import {
|
|
803
|
-
isBinaryContentType,
|
|
804
|
-
isSseContentType,
|
|
805
|
-
isStreamingContentType,
|
|
806
|
-
isTextContentType,
|
|
807
|
-
parseJsonContentType,
|
|
808
801
|
sanitizeTag as sanitizeTag3
|
|
809
802
|
} from "@sdk-it/spec";
|
|
810
803
|
|
|
@@ -831,8 +824,8 @@ function describe(p) {
|
|
|
831
824
|
hasMore: p.hasMore,
|
|
832
825
|
statusCode: p.statusCode,
|
|
833
826
|
sameInputNames: p.cursorParamName === "cursor",
|
|
834
|
-
initialOverride: `cursor: input
|
|
835
|
-
nextPageMapping:
|
|
827
|
+
initialOverride: `cursor: input[${JSON.stringify(p.cursorParamName)}]`,
|
|
828
|
+
nextPageMapping: `[${JSON.stringify(p.cursorParamName)}]: nextPageParams.cursor ?? input[${JSON.stringify(p.cursorParamName)}]`
|
|
836
829
|
};
|
|
837
830
|
case "page":
|
|
838
831
|
return {
|
|
@@ -850,7 +843,8 @@ function describe(p) {
|
|
|
850
843
|
function paginationOperation(pagination) {
|
|
851
844
|
const shape = describe(pagination);
|
|
852
845
|
const initialParams = shape.sameInputNames ? "input" : `{...input, ${shape.initialOverride}}`;
|
|
853
|
-
const nextPageParams = shape.sameInputNames ? "...nextPageParams" : shape.nextPageMapping;
|
|
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;
|
|
854
848
|
return `{
|
|
855
849
|
const pagination = new ${shape.className}(${initialParams}, async (nextPageParams, requestOptions) => {
|
|
856
850
|
const dispatcher = new Dispatcher(options.interceptors, options.fetch);
|
|
@@ -860,13 +854,15 @@ function paginationOperation(pagination) {
|
|
|
860
854
|
requestOptions?.signal ?? options.signal,
|
|
861
855
|
);
|
|
862
856
|
if (result.status !== ${shape.statusCode}) { throw result; }
|
|
857
|
+
${nextCursor ? `const nextCursor = ${nextCursor};` : ""}
|
|
863
858
|
return {
|
|
864
859
|
data: result.data.${shape.items},
|
|
865
860
|
meta: {
|
|
866
861
|
hasMore: Boolean(result.data.${shape.hasMore}),
|
|
862
|
+
${nextCursor ? '...(typeof nextCursor === "string" ? { nextCursor } : {}),' : ""}
|
|
867
863
|
},
|
|
868
864
|
};
|
|
869
|
-
}, { signal: options.signal });
|
|
865
|
+
}, options.signal ? { signal: options.signal } : {});
|
|
870
866
|
await pagination.getNextPage();
|
|
871
867
|
return pagination
|
|
872
868
|
}}`;
|
|
@@ -900,18 +896,13 @@ var status_map_default = {
|
|
|
900
896
|
};
|
|
901
897
|
|
|
902
898
|
// packages/typescript/src/lib/sdk.ts
|
|
903
|
-
function toEndpoint(groupName,
|
|
899
|
+
function toEndpoint(groupName, specOperation, operation) {
|
|
904
900
|
const schemaName = camelcase3(`${specOperation.operationId} schema`);
|
|
905
901
|
const schemaRef = `${camelcase3(groupName)}.${schemaName}`;
|
|
906
902
|
const schemas = [];
|
|
907
903
|
specOperation.responses ??= {};
|
|
908
|
-
const outputs = Object.keys(specOperation.responses).
|
|
909
|
-
(status) => toHttpOutput(
|
|
910
|
-
spec,
|
|
911
|
-
specOperation.operationId,
|
|
912
|
-
status,
|
|
913
|
-
specOperation.responses[status]
|
|
914
|
-
)
|
|
904
|
+
const outputs = Object.keys(specOperation.responses).map(
|
|
905
|
+
(status) => toHttpOutput(status, specOperation.responses[status])
|
|
915
906
|
);
|
|
916
907
|
const addTypeParser = Object.keys(operation.schemas).length > 1;
|
|
917
908
|
for (const type in operation.schemas ?? {}) {
|
|
@@ -949,87 +940,44 @@ function normalOperation() {
|
|
|
949
940
|
},
|
|
950
941
|
}`;
|
|
951
942
|
}
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
const generic = withGenerics ? `<outputs.${interfaceName}>` : "";
|
|
970
|
-
if (status.endsWith("XX")) {
|
|
971
|
-
outputs.push(`http.APIError${generic}`);
|
|
972
|
-
} else {
|
|
973
|
-
if (parser !== "buffered") {
|
|
974
|
-
outputs.push(`{type: ${statusName}${generic}, parser: ${parser}}`);
|
|
975
|
-
} else {
|
|
976
|
-
outputs.push(`${statusName}${generic}`);
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
}
|
|
980
|
-
return outputs;
|
|
981
|
-
}
|
|
982
|
-
return [];
|
|
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"}`;
|
|
954
|
+
if (status === "204") {
|
|
955
|
+
return type;
|
|
956
|
+
}
|
|
957
|
+
const data = dataType(status, response);
|
|
958
|
+
const parser = bodyParser[body];
|
|
959
|
+
return parser === "buffered" ? `${type}<${data}>` : `{type: ${type}<${data}>, parser: ${parser}}`;
|
|
983
960
|
}
|
|
984
|
-
function
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
return
|
|
994
|
-
}
|
|
995
|
-
if (isBinary) {
|
|
996
|
-
return {
|
|
997
|
-
parser: "buffered",
|
|
998
|
-
responseSchema: response.content[type].schema ? typeScriptDeserialzer.handle(response.content[type].schema, true) : "Blob"
|
|
999
|
-
};
|
|
1000
|
-
}
|
|
1001
|
-
if (parseJsonContentType(type)) {
|
|
1002
|
-
const schema = response.content[type].schema;
|
|
1003
|
-
return {
|
|
1004
|
-
parser: "buffered",
|
|
1005
|
-
responseSchema: schema ? typeScriptDeserialzer.handle(schema, true) : "void"
|
|
1006
|
-
};
|
|
1007
|
-
}
|
|
1008
|
-
if (isSseContentType(type)) {
|
|
1009
|
-
return {
|
|
1010
|
-
parser: "sse",
|
|
1011
|
-
responseSchema: "SSEListener"
|
|
1012
|
-
};
|
|
1013
|
-
}
|
|
1014
|
-
if (isTextContentType(type)) {
|
|
1015
|
-
return {
|
|
1016
|
-
parser: "buffered",
|
|
1017
|
-
responseSchema: response.content[type].schema ? typeScriptDeserialzer.handle(response.content[type].schema, true) : "void"
|
|
1018
|
-
};
|
|
1019
|
-
}
|
|
961
|
+
function dataType(status, response) {
|
|
962
|
+
switch (response["x-body"]) {
|
|
963
|
+
case "empty":
|
|
964
|
+
return "null";
|
|
965
|
+
case "stream":
|
|
966
|
+
return "ReadableStream";
|
|
967
|
+
case "sse":
|
|
968
|
+
return "SSEListener";
|
|
969
|
+
default:
|
|
970
|
+
return `outputs.${pascalcase3(sanitizeTag3(outputName(status, response)))}`;
|
|
1020
971
|
}
|
|
1021
|
-
return streamedOutput();
|
|
1022
972
|
}
|
|
1023
|
-
function
|
|
1024
|
-
const
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
}
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
responseSchema: "ReadableStream"
|
|
1032
|
-
};
|
|
973
|
+
function outputName(status, response) {
|
|
974
|
+
const name = response["x-response-name"];
|
|
975
|
+
if (!name) {
|
|
976
|
+
throw new Error(
|
|
977
|
+
`Response ${status} has a ${response["x-body"]} body but no output name; generate with responses.flattenErrorResponses so every response is normalized`
|
|
978
|
+
);
|
|
979
|
+
}
|
|
980
|
+
return name;
|
|
1033
981
|
}
|
|
1034
982
|
function inputToPath(operation, inputs) {
|
|
1035
983
|
const inputHeaders = [];
|
|
@@ -1075,7 +1023,7 @@ function coearceRequestInput(spec, operation, type) {
|
|
|
1075
1023
|
if (type === "application/empty") {
|
|
1076
1024
|
objectSchema = {
|
|
1077
1025
|
type: "object",
|
|
1078
|
-
additionalProperties:
|
|
1026
|
+
additionalProperties: isEmpty3(xProperties)
|
|
1079
1027
|
};
|
|
1080
1028
|
} else {
|
|
1081
1029
|
if (objectSchema.type !== "object") {
|
|
@@ -1132,7 +1080,7 @@ function generateCode(config) {
|
|
|
1132
1080
|
);
|
|
1133
1081
|
}
|
|
1134
1082
|
const details = buildInput(config.spec, operation);
|
|
1135
|
-
const endpoint = toEndpoint(entry.tag,
|
|
1083
|
+
const endpoint = toEndpoint(entry.tag, operation, {
|
|
1136
1084
|
method: entry.method,
|
|
1137
1085
|
path: entry.path,
|
|
1138
1086
|
operationId: operation.operationId,
|
|
@@ -1177,25 +1125,26 @@ ${allSchemas.map((it) => it.use).join(",\n")}
|
|
|
1177
1125
|
`.trim(),
|
|
1178
1126
|
...Object.fromEntries(
|
|
1179
1127
|
Object.entries(endpoints).map(([name, endpoint]) => {
|
|
1128
|
+
const operations = endpoint.flatMap((it) => it.schemas).join(",\n");
|
|
1180
1129
|
return [
|
|
1181
1130
|
[
|
|
1182
1131
|
join("api", `${spinalcase2(name)}.ts`),
|
|
1183
1132
|
`${[
|
|
1184
1133
|
`import z from 'zod';`,
|
|
1185
1134
|
`import * as http from '${config.makeImport("../http/response")}';`,
|
|
1186
|
-
|
|
1135
|
+
...operations.includes("outputs.") ? [
|
|
1136
|
+
`import * as outputs from '${config.makeImport("../outputs/index")}';`
|
|
1137
|
+
] : [],
|
|
1187
1138
|
`import { toRequest, json, urlencoded, empty, formdata, type HeadersInit } from '${config.makeImport("../http/request")}';`,
|
|
1188
|
-
`import { chunked, buffered } from "${config.makeImport("../http/parse-response")}";`,
|
|
1189
|
-
`import { sse } from "${config.makeImport("../http/sse")}";`,
|
|
1139
|
+
`import { chunked, buffered, bodyless } from "${config.makeImport("../http/parse-response")}";`,
|
|
1140
|
+
`import { sse, type SSEListener } from "${config.makeImport("../http/sse")}";`,
|
|
1190
1141
|
`import * as ${camelcase4(name)} from '../inputs/${config.makeImport(spinalcase2(name))}';`,
|
|
1191
1142
|
`import { createBaseUrlInterceptor, createHeadersInterceptor, type Interceptor } from '${config.makeImport("../http/interceptors")}';`,
|
|
1192
1143
|
`import { Dispatcher, fetchType, type InstanceType } from '${config.makeImport("../http/dispatcher")}';`,
|
|
1193
1144
|
`import { Pagination, OffsetPagination, CursorPagination } from "${config.makeImport("../pagination/index")}";`
|
|
1194
|
-
].join(
|
|
1195
|
-
"\n"
|
|
1196
|
-
)}
|
|
1145
|
+
].join("\n")}
|
|
1197
1146
|
export default {
|
|
1198
|
-
${
|
|
1147
|
+
${operations}
|
|
1199
1148
|
}`
|
|
1200
1149
|
]
|
|
1201
1150
|
];
|
|
@@ -1315,37 +1264,37 @@ function operationSchema(ir, operation, type) {
|
|
|
1315
1264
|
}
|
|
1316
1265
|
|
|
1317
1266
|
// packages/typescript/src/lib/http/dispatcher.txt
|
|
1318
|
-
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 | null = null;\n let parser: Parser = buffered;\n for (const outputType of outputs) {\n
|
|
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";
|
|
1319
1268
|
|
|
1320
1269
|
// packages/typescript/src/lib/http/interceptors.txt
|
|
1321
|
-
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
|
|
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";
|
|
1322
1271
|
|
|
1323
1272
|
// packages/typescript/src/lib/http/parse-response.txt
|
|
1324
|
-
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\
|
|
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';
|
|
1325
1274
|
|
|
1326
1275
|
// packages/typescript/src/lib/http/parser.txt
|
|
1327
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";
|
|
1328
1277
|
|
|
1329
1278
|
// packages/typescript/src/lib/http/request.txt
|
|
1330
|
-
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
|
|
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";
|
|
1331
1280
|
|
|
1332
1281
|
// packages/typescript/src/lib/http/response.txt
|
|
1333
|
-
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 APIResponse<\n Body,\n Status\n> {\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(status, headers, data);\n }\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";
|
|
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";
|
|
1334
1283
|
|
|
1335
1284
|
// packages/typescript/src/lib/http/sse.txt
|
|
1336
|
-
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\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
|
|
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';
|
|
1337
1286
|
|
|
1338
1287
|
// packages/typescript/src/lib/paginations/cursor-pagination.txt
|
|
1339
|
-
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 = {
|
|
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";
|
|
1340
1289
|
|
|
1341
1290
|
// packages/typescript/src/lib/paginations/offset-pagination.txt
|
|
1342
|
-
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:
|
|
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";
|
|
1343
1292
|
|
|
1344
1293
|
// packages/typescript/src/lib/paginations/page-pagination.txt
|
|
1345
|
-
var page_pagination_default = "type InferPage<T> = T extends Page<infer U> ? U : never;\ntype PaginationParams<P extends number | bigint, S extends number | bigint> = {\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,\n S extends number | bigint,\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,\n S extends number | bigint,\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:
|
|
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";
|
|
1346
1295
|
|
|
1347
1296
|
// packages/typescript/src/lib/readme/readme.ts
|
|
1348
|
-
import { isEmpty as
|
|
1297
|
+
import { isEmpty as isEmpty4 } from "@sdk-it/core";
|
|
1349
1298
|
import { forEachOperation as forEachOperation4 } from "@sdk-it/spec";
|
|
1350
1299
|
|
|
1351
1300
|
// packages/typescript/src/lib/readme/prop.emitter.ts
|
|
@@ -1673,7 +1622,7 @@ function toReadme(spec, generator) {
|
|
|
1673
1622
|
markdown.push(`#### Output`);
|
|
1674
1623
|
for (const status in operation.responses) {
|
|
1675
1624
|
const response = operation.responses[status];
|
|
1676
|
-
if (!
|
|
1625
|
+
if (!isEmpty4(response.content)) {
|
|
1677
1626
|
const contentEntries = Object.entries(response.content);
|
|
1678
1627
|
if (contentEntries.length === 1) {
|
|
1679
1628
|
const [contentType, mediaType] = contentEntries[0];
|
|
@@ -1952,7 +1901,7 @@ function expandServerUrls(servers) {
|
|
|
1952
1901
|
// packages/typescript/src/lib/typescript-snippet.ts
|
|
1953
1902
|
import { camelcase as camelcase5, spinalcase as spinalcase3 } from "stringcase";
|
|
1954
1903
|
import {
|
|
1955
|
-
isEmpty as
|
|
1904
|
+
isEmpty as isEmpty5,
|
|
1956
1905
|
pascalcase as pascalcase4,
|
|
1957
1906
|
resolveRef as resolveRef4
|
|
1958
1907
|
} from "@sdk-it/core";
|
|
@@ -2165,7 +2114,7 @@ var TypeScriptSnippet = class {
|
|
|
2165
2114
|
}
|
|
2166
2115
|
succinct(entry, operation, values) {
|
|
2167
2116
|
let payload = "{}";
|
|
2168
|
-
if (!
|
|
2117
|
+
if (!isEmpty5(operation.requestBody)) {
|
|
2169
2118
|
const contentTypes = Object.keys(operation.requestBody.content || {});
|
|
2170
2119
|
const schema = resolveRef4(
|
|
2171
2120
|
this.#spec,
|
|
@@ -2222,7 +2171,7 @@ var TypeScriptSnippet = class {
|
|
|
2222
2171
|
return this.#streamDownload(entry, payload);
|
|
2223
2172
|
}
|
|
2224
2173
|
}
|
|
2225
|
-
if (!
|
|
2174
|
+
if (!isEmpty5(operation["x-pagination"])) {
|
|
2226
2175
|
return this.#pagination(operation, entry, payload);
|
|
2227
2176
|
}
|
|
2228
2177
|
return this.#normal(entry, payload);
|
|
@@ -2332,7 +2281,7 @@ const result = await ${camelcase5(this.#clientName)}.request('${entry.method.toU
|
|
|
2332
2281
|
options.baseUrl = servers[0] ?? "http://localhost:3000";
|
|
2333
2282
|
}
|
|
2334
2283
|
const authOptions = this.#authentication();
|
|
2335
|
-
if (!
|
|
2284
|
+
if (!isEmpty5(authOptions)) {
|
|
2336
2285
|
const [firstAuth] = authOptions;
|
|
2337
2286
|
options.credentials = {
|
|
2338
2287
|
[firstAuth.name]: this.#credentialExample(firstAuth.scheme)
|
|
@@ -2373,7 +2322,7 @@ ${client.use}`;
|
|
|
2373
2322
|
);
|
|
2374
2323
|
const baseUrl = expandServerUrls(this.#spec.servers ?? [])[0] || "https://api.example.com";
|
|
2375
2324
|
const authOptions = this.#authentication();
|
|
2376
|
-
const hasApiKey = !
|
|
2325
|
+
const hasApiKey = !isEmpty5(authOptions);
|
|
2377
2326
|
sections.push("### Configuration Options");
|
|
2378
2327
|
sections.push("");
|
|
2379
2328
|
sections.push("| Option | Type | Required | Description |");
|
|
@@ -2758,7 +2707,7 @@ ${client.use}`;
|
|
|
2758
2707
|
}
|
|
2759
2708
|
authenticationDocs() {
|
|
2760
2709
|
const authOptions = this.#authentication();
|
|
2761
|
-
if (
|
|
2710
|
+
if (isEmpty5(authOptions)) {
|
|
2762
2711
|
return "";
|
|
2763
2712
|
}
|
|
2764
2713
|
const only = authOptions.length === 1;
|
|
@@ -2801,7 +2750,7 @@ ${client.use}`;
|
|
|
2801
2750
|
const initialClientOptions = {
|
|
2802
2751
|
baseUrl: "https://api.production-service.com"
|
|
2803
2752
|
};
|
|
2804
|
-
if (!
|
|
2753
|
+
if (!isEmpty5(authOptions)) {
|
|
2805
2754
|
const [primaryAuth] = authOptions;
|
|
2806
2755
|
initialClientOptions.credentials = {
|
|
2807
2756
|
[primaryAuth.name]: this.#credentialExample(primaryAuth.scheme)
|
|
@@ -2816,7 +2765,7 @@ ${client.use}`;
|
|
|
2816
2765
|
"client.setOptions({",
|
|
2817
2766
|
" baseUrl: 'https://api.staging-service.com',"
|
|
2818
2767
|
];
|
|
2819
|
-
if (!
|
|
2768
|
+
if (!isEmpty5(authOptions)) {
|
|
2820
2769
|
const [primaryAuth] = authOptions;
|
|
2821
2770
|
configurationUpdateCode.push(
|
|
2822
2771
|
` credentials: ${JSON.stringify({
|
|
@@ -3124,23 +3073,34 @@ ${utils_default}`
|
|
|
3124
3073
|
function serializeModels(spec) {
|
|
3125
3074
|
const filesMap = {};
|
|
3126
3075
|
const files = {};
|
|
3076
|
+
const responseBodies = /* @__PURE__ */ new Map();
|
|
3077
|
+
forEachOperation6(spec, (_, operation) => {
|
|
3078
|
+
for (const response of Object.values(operation.responses)) {
|
|
3079
|
+
const name = response["x-response-name"];
|
|
3080
|
+
if (name) {
|
|
3081
|
+
responseBodies.set(name, response["x-body"]);
|
|
3082
|
+
}
|
|
3083
|
+
}
|
|
3084
|
+
});
|
|
3127
3085
|
for (const [name, schema] of Object.entries(spec.components.schemas)) {
|
|
3128
3086
|
const isResponseBody = schema["x-responsebody"];
|
|
3129
3087
|
const isRequestBody = schema["x-requestbody"];
|
|
3130
3088
|
const responseGroup = schema["x-response-group"];
|
|
3131
|
-
const
|
|
3089
|
+
const body = responseGroup ? responseBodies.get(name) : void 0;
|
|
3132
3090
|
if (isRequestBody) {
|
|
3133
3091
|
continue;
|
|
3134
3092
|
}
|
|
3135
3093
|
const folder = isResponseBody ? "outputs" : "models";
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
typeContent =
|
|
3094
|
+
let typeContent;
|
|
3095
|
+
if (body === "sse") {
|
|
3096
|
+
typeContent = "SSEListener";
|
|
3097
|
+
} else if (body === "stream") {
|
|
3098
|
+
typeContent = "ReadableStream";
|
|
3099
|
+
} else {
|
|
3100
|
+
typeContent = new TypeScriptEmitter(spec).handle(schema, true);
|
|
3141
3101
|
}
|
|
3142
3102
|
const imports = [];
|
|
3143
|
-
if (
|
|
3103
|
+
if (body === "sse") {
|
|
3144
3104
|
imports.push(`import type { SSEListener } from '../http/sse.ts';`);
|
|
3145
3105
|
}
|
|
3146
3106
|
const fileContent = [
|