@sdk-it/typescript 0.37.1 → 0.39.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 (51) hide show
  1. package/dist/connect.d.ts +1 -0
  2. package/dist/connect.d.ts.map +1 -0
  3. package/dist/global.d.js +1 -0
  4. package/dist/global.d.js.map +7 -0
  5. package/dist/index.js +102 -541
  6. package/dist/index.js.map +2 -2
  7. package/dist/lib/client.d.ts +1 -2
  8. package/dist/lib/client.d.ts.map +1 -1
  9. package/dist/lib/connect.d.ts +162 -0
  10. package/dist/lib/connect.d.ts.map +1 -0
  11. package/dist/lib/generate.d.ts.map +1 -1
  12. package/dist/lib/generator.d.ts.map +1 -1
  13. package/dist/lib/sdk.d.ts +1 -5
  14. package/dist/lib/sdk.d.ts.map +1 -1
  15. package/dist/lib/style.d.ts +0 -3
  16. package/dist/lib/style.d.ts.map +1 -1
  17. package/dist/src/index.js +5 -0
  18. package/dist/src/index.js.map +7 -0
  19. package/dist/src/lib/agent/ai-sdk.js +60 -0
  20. package/dist/src/lib/agent/ai-sdk.js.map +7 -0
  21. package/dist/src/lib/agent/openai-agents.js +42 -0
  22. package/dist/src/lib/agent/openai-agents.js.map +7 -0
  23. package/dist/src/lib/client.js +152 -0
  24. package/dist/src/lib/client.js.map +7 -0
  25. package/dist/src/lib/emitters/interface.js +169 -0
  26. package/dist/src/lib/emitters/interface.js.map +7 -0
  27. package/dist/src/lib/emitters/snippet.js +191 -0
  28. package/dist/src/lib/emitters/snippet.js.map +7 -0
  29. package/dist/src/lib/emitters/zod.js +271 -0
  30. package/dist/src/lib/emitters/zod.js.map +7 -0
  31. package/dist/src/lib/generate.js +382 -0
  32. package/dist/src/lib/generate.js.map +7 -0
  33. package/dist/src/lib/generator.js +268 -0
  34. package/dist/src/lib/generator.js.map +7 -0
  35. package/dist/src/lib/import-utilities.js +56 -0
  36. package/dist/src/lib/import-utilities.js.map +7 -0
  37. package/dist/src/lib/options.js +3 -0
  38. package/dist/src/lib/options.js.map +7 -0
  39. package/dist/src/lib/readme/prop.emitter.js +283 -0
  40. package/dist/src/lib/readme/prop.emitter.js.map +7 -0
  41. package/dist/src/lib/readme/readme.js +105 -0
  42. package/dist/src/lib/readme/readme.js.map +7 -0
  43. package/dist/src/lib/sdk.js +236 -0
  44. package/dist/src/lib/sdk.js.map +7 -0
  45. package/dist/src/lib/status-map.js +28 -0
  46. package/dist/src/lib/status-map.js.map +7 -0
  47. package/dist/src/lib/style.js +1 -0
  48. package/dist/src/lib/style.js.map +7 -0
  49. package/dist/src/lib/typescript-snippet.js +738 -0
  50. package/dist/src/lib/typescript-snippet.js.map +7 -0
  51. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -391,7 +391,7 @@ function toZod(schema, required) {
391
391
  }
392
392
 
393
393
  // packages/typescript/src/lib/client.ts
394
- var client_default = (spec, style) => {
394
+ var client_default = (spec) => {
395
395
  const defaultHeaders = `{${spec.options.filter((value) => value.in === "header").map(
396
396
  (value) => `'${value.name}': options['${value["x-optionName"] ?? value.name}']`
397
397
  ).join(",\n")}}`;
@@ -429,9 +429,11 @@ var client_default = (spec, style) => {
429
429
  }
430
430
  };
431
431
  return `import z from 'zod';
432
+ import { APIResponse } from '${spec.makeImport("./http/response")}';
432
433
  import type { HeadersInit, RequestConfig } from './http/${spec.makeImport("request")}';
433
434
  import { fetchType, parse } from './http/${spec.makeImport("dispatcher")}';
434
435
  import schemas from './api/${spec.makeImport("schemas")}';
436
+ import type { InferData } from '${spec.makeImport("./api/endpoints")}';
435
437
  import {
436
438
  createBaseUrlInterceptor,
437
439
  createHeadersInterceptor,
@@ -454,56 +456,33 @@ export class ${spec.name} {
454
456
  async request<const E extends keyof typeof schemas>(
455
457
  endpoint: E,
456
458
  input: z.input<(typeof schemas)[E]['schema']>,
457
- options?: { signal?: AbortSignal, headers?: HeadersInit },
458
- ) ${style.errorAsValue ? `: Promise<Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>| [never, ParseError<(typeof schemas)[E]['schema']>]>` : `: Promise<Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>>`} {
459
- const route = schemas[endpoint];
460
- const withDefaultInputs = Object.assign({}, await this.#defaultInputs(), input);
461
- const [parsedInput, parseError] = parseInput(route.schema, withDefaultInputs);
462
- if (parseError) {
463
- ${style.errorAsValue ? "return [null as never, parseError as never] as const;" : "throw parseError;"}
464
- }
465
- const clientOptions = await optionsSchema.parseAsync(this.options);
466
- const result = await route.dispatch(parsedInput as never, {
467
- fetch: clientOptions.fetch,
468
- interceptors: [
469
- createHeadersInterceptor(
470
- await this.#defaultHeaders(),
471
- options?.headers ?? {},
472
- ),
473
- createBaseUrlInterceptor(clientOptions.baseUrl),
474
- ],
475
- signal: options?.signal,
459
+ options?: { signal?: AbortSignal; headers?: HeadersInit },
460
+ ) {
461
+ return request(this, endpoint, input, options).then(function unwrap(it) {
462
+ if (it instanceof APIResponse) {
463
+ return it.data as InferData<E>;
464
+ }
465
+ return it as InferData<E>;
476
466
  });
477
- return result as Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>;
478
467
  }
479
468
 
480
469
  async prepare<const E extends keyof typeof schemas>(
481
470
  endpoint: E,
482
471
  input: z.input<(typeof schemas)[E]['schema']>,
483
472
  options?: { headers?: HeadersInit },
484
- ): ${style.errorAsValue ? `Promise<
485
- readonly [
486
- RequestConfig & {
487
- parse: (response: Response) => ReturnType<typeof parse>;
488
- },
489
- ParseError<(typeof schemas)[E]['schema']> | null,
490
- ]
491
- >` : `Promise<RequestConfig & {
492
- parse: (response: Response) => ReturnType<typeof parse>;
493
- }>`} {
473
+ ): Promise<RequestConfig & {
474
+ parse: (response: Response) => ReturnType<typeof parse>;
475
+ }> {
494
476
  const clientOptions = await optionsSchema.parseAsync(this.options);
495
477
  const route = schemas[endpoint];
496
478
  const interceptors = [
497
479
  createHeadersInterceptor(
498
- await this.#defaultHeaders(),
480
+ await this.defaultHeaders(),
499
481
  options?.headers ?? {},
500
482
  ),
501
483
  createBaseUrlInterceptor(clientOptions.baseUrl),
502
484
  ];
503
- const [parsedInput, parseError] = parseInput(route.schema, input);
504
- if (parseError) {
505
- ${style.errorAsValue ? "return [null as never, parseError as never] as const;" : "throw parseError;"}
506
- }
485
+ const parsedInput = parseInput(route.schema, input);
507
486
 
508
487
  let config = route.toRequest(parsedInput as never);
509
488
  for (const interceptor of interceptors) {
@@ -511,11 +490,11 @@ export class ${spec.name} {
511
490
  config = await interceptor.before(config);
512
491
  }
513
492
  }
514
- const prepared = { ...config, parse: (response: Response) => parse(route.output, response) as never };
515
- return ${style.errorAsValue ? "[prepared, null as never] as const;" : "prepared as any"}
493
+ const prepared = { ...config, parse: (response: Response) => parse(route.output, response, (d) => d) as never };
494
+ return prepared as any;
516
495
  }
517
496
 
518
- async #defaultHeaders() {
497
+ async defaultHeaders() {
519
498
  const options = await optionsSchema.parseAsync(this.options);
520
499
  return {
521
500
  ...${defaultHeaders},
@@ -523,7 +502,7 @@ export class ${spec.name} {
523
502
  };
524
503
  }
525
504
 
526
- async #defaultInputs() {
505
+ async defaultInputs() {
527
506
  const options = await optionsSchema.parseAsync(this.options);
528
507
  return ${defaultInputs}
529
508
  }
@@ -535,7 +514,38 @@ export class ${spec.name} {
535
514
  };
536
515
  }
537
516
 
538
- }`;
517
+ }
518
+
519
+ export async function request<const E extends keyof typeof schemas>(
520
+ client: ${spec.name},
521
+ endpoint: E,
522
+ input: z.input<(typeof schemas)[E]['schema']>,
523
+ options?: { signal?: AbortSignal; headers?: HeadersInit },
524
+ ): Promise<Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>> {
525
+ const route = schemas[endpoint];
526
+ const withDefaultInputs = Object.assign(
527
+ {},
528
+ await client.defaultInputs(),
529
+ input,
530
+ );
531
+ const parsedInput = parseInput(route.schema, withDefaultInputs);
532
+ const clientOptions = await optionsSchema.parseAsync(client.options);
533
+ const result = await route.dispatch(parsedInput as never, {
534
+ fetch: clientOptions.fetch,
535
+ interceptors: [
536
+ createHeadersInterceptor(
537
+ await client.defaultHeaders(),
538
+ options?.headers ?? {},
539
+ ),
540
+ createBaseUrlInterceptor(clientOptions.baseUrl),
541
+ ],
542
+ signal: options?.signal,
543
+ });
544
+ return result as Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>;
545
+ }
546
+
547
+
548
+ `;
539
549
  };
540
550
 
541
551
  // packages/typescript/src/lib/emitters/interface.ts
@@ -709,7 +719,7 @@ function appendOptional2(type, isRequired) {
709
719
  import { merge, template } from "lodash-es";
710
720
  import { join } from "node:path";
711
721
  import { camelcase as camelcase4, spinalcase as spinalcase2 } from "stringcase";
712
- import { followRef as followRef3, isEmpty as isEmpty2, isRef as isRef3, resolveRef } from "@sdk-it/core";
722
+ import { followRef as followRef3, isEmpty as isEmpty2, isRef as isRef3, resolveRef, sortArray } from "@sdk-it/core";
713
723
  import {
714
724
  forEachOperation as forEachOperation3
715
725
  } from "@sdk-it/spec";
@@ -754,7 +764,7 @@ var status_map_default = {
754
764
  };
755
765
 
756
766
  // packages/typescript/src/lib/sdk.ts
757
- function toEndpoint(groupName, spec, specOperation, operation, utils) {
767
+ function toEndpoint(groupName, spec, specOperation, operation) {
758
768
  const schemaName = camelcase3(`${specOperation.operationId} schema`);
759
769
  const schemaRef = `${camelcase3(groupName)}.${schemaName}`;
760
770
  const schemas = [];
@@ -790,23 +800,22 @@ function toEndpoint(groupName, spec, specOperation, operation, utils) {
790
800
  signal?: AbortSignal;
791
801
  interceptors: Interceptor[];
792
802
  fetch: z.infer<typeof fetchType>;
793
- })${specOperation["x-pagination"] ? paginationOperation(specOperation, utils.style) : normalOperation(utils.style)}`
803
+ })${specOperation["x-pagination"] ? paginationOperation(specOperation) : normalOperation()}`
794
804
  );
795
805
  }
796
806
  return { schemas };
797
807
  }
798
- function normalOperation(style) {
808
+ function normalOperation() {
799
809
  return `{
800
810
  const dispatcher = new Dispatcher(options.interceptors, options.fetch);
801
- const result = await dispatcher.send(this.toRequest(input), this.output);
802
- return ${style?.outputType === "status" ? "result" : style?.errorAsValue ? `result` : "result.data;"}
811
+ return dispatcher.send(this.toRequest(input), this.output, options?.signal);
803
812
  },
804
813
  }`;
805
814
  }
806
- function paginationOperation(operation, style) {
815
+ function paginationOperation(operation) {
807
816
  const pagination = operation["x-pagination"];
808
- const data = `${style?.errorAsValue ? `result[0]${style.outputType === "status" ? "" : ""}` : `${style?.outputType === "default" ? "result.data" : "result.data"}`}`;
809
- const returnValue = `${style?.errorAsValue ? `[${style?.outputType === "status" ? "new http.Ok(pagination)" : "pagination"}, null]` : `${style?.outputType === "status" ? "new http.Ok(pagination);" : "pagination"}`}`;
817
+ const data = `result.data`;
818
+ const returnValue = `pagination`;
810
819
  if (pagination.type === "offset") {
811
820
  const sameInputNames = pagination.limitParamName === "limit" && pagination.offsetParamName === "offset";
812
821
  const initialParams = sameInputNames ? "input" : `{...input, limit: input.${pagination.limitParamName}, offset: input.${pagination.offsetParamName}}`;
@@ -816,6 +825,7 @@ function paginationOperation(operation, style) {
816
825
  const result = await dispatcher.send(
817
826
  this.toRequest({...input, ${nextPageParams}}),
818
827
  this.output,
828
+ options.signal,
819
829
  );
820
830
  return {
821
831
  data: ${data}.${pagination.items},
@@ -827,7 +837,7 @@ function paginationOperation(operation, style) {
827
837
  await pagination.getNextPage();
828
838
  return ${returnValue}
829
839
  `;
830
- return style?.errorAsValue ? `{try {${logic}} catch (error) {return [null as never, error] as const;}}}` : `{${logic}}}`;
840
+ return `{${logic}}}`;
831
841
  }
832
842
  if (pagination.type === "cursor") {
833
843
  const sameInputNames = pagination.cursorParamName === "cursor";
@@ -839,8 +849,8 @@ function paginationOperation(operation, style) {
839
849
  const result = await dispatcher.send(
840
850
  this.toRequest({...input, ${nextPageParams}}),
841
851
  this.output,
852
+ options.signal,
842
853
  );
843
- ${style?.errorAsValue ? `if (result[1]) {throw result[1];}` : ""}
844
854
  return {
845
855
  data: ${data}.${pagination.items},
846
856
  meta: {
@@ -851,7 +861,7 @@ function paginationOperation(operation, style) {
851
861
  await pagination.getNextPage();
852
862
  return ${returnValue}
853
863
  `;
854
- return style?.errorAsValue ? `{try {${logic}} catch (error) {return [null as never, error] as const;}}}` : `{${logic}}}`;
864
+ return `{${logic}}}`;
855
865
  }
856
866
  if (pagination.type === "page") {
857
867
  const sameInputNames = pagination.pageNumberParamName === "page" && pagination.pageSizeParamName === "pageSize";
@@ -863,8 +873,8 @@ function paginationOperation(operation, style) {
863
873
  const result = await dispatcher.send(
864
874
  this.toRequest({...input, ${nextPageParams}}),
865
875
  this.output,
876
+ options.signal,
866
877
  );
867
- ${style?.errorAsValue ? `if (result[1]) {throw result[1];}` : ""}
868
878
  return {
869
879
  data: ${data}.${pagination.items},
870
880
  meta: {
@@ -872,12 +882,11 @@ function paginationOperation(operation, style) {
872
882
  },
873
883
  };
874
884
  });
875
- await pagination.getNextPage();
876
885
  return ${returnValue}
877
886
  `;
878
- return style?.errorAsValue ? `{try {${logic}} catch (error) {return [null as never, error] as const;}}}` : `{${logic}}}`;
887
+ return `{${logic}}}`;
879
888
  }
880
- return normalOperation(style);
889
+ return normalOperation();
881
890
  }
882
891
  function toHttpOutput(spec, operationName, status, response, withGenerics = true) {
883
892
  const typeScriptDeserialzer = new TypeScriptEmitter(spec);
@@ -975,7 +984,7 @@ function inputToPath(operation, inputs) {
975
984
  }
976
985
 
977
986
  // packages/typescript/src/lib/styles/github/endpoints.txt
978
- var endpoints_default = "type 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 [K in keyof typeof schemas]: {\n input: z.input<(typeof schemas)[K]['schema']>;\n output: <% if (outputType === 'default') { %>EndpointOutput<K>['data']<% } else { %>EndpointOutput<K><% } %>;\n error: EndpointError<K> | ParseError<(typeof schemas)[K]['schema']>;\n };\n};";
987
+ 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";
979
988
 
980
989
  // packages/typescript/src/lib/generator.ts
981
990
  function coearceRequestInput(spec, operation, type) {
@@ -1045,20 +1054,14 @@ function generateCode(config) {
1045
1054
  );
1046
1055
  }
1047
1056
  const details = buildInput(config.spec, operation);
1048
- const endpoint = toEndpoint(
1049
- entry.tag,
1050
- config.spec,
1051
- operation,
1052
- {
1053
- method: entry.method,
1054
- path: entry.path,
1055
- operationId: operation.operationId,
1056
- schemas,
1057
- outgoingContentType: details.outgoingContentType,
1058
- inputs: details.inputs
1059
- },
1060
- config
1061
- );
1057
+ const endpoint = toEndpoint(entry.tag, config.spec, operation, {
1058
+ method: entry.method,
1059
+ path: entry.path,
1060
+ operationId: operation.operationId,
1061
+ schemas,
1062
+ outgoingContentType: details.outgoingContentType,
1063
+ inputs: details.inputs
1064
+ });
1062
1065
  endpoints[entry.tag].push(endpoint);
1063
1066
  groups[entry.tag].push({
1064
1067
  method: entry.method,
@@ -1078,19 +1081,17 @@ function generateCode(config) {
1078
1081
  commonZod,
1079
1082
  endpoints: {
1080
1083
  [join("api", "endpoints.ts")]: `
1081
-
1082
-
1083
1084
  import type z from 'zod';
1084
1085
  import type { ParseError } from '${config.makeImport("../http/parser")}';
1085
- import type { ProblematicResponse, SuccessfulResponse } from '${config.makeImport(
1086
+ import type { ProblematicResponse, SuccessfulResponse, APIResponse } from '${config.makeImport(
1086
1087
  "../http/response"
1087
1088
  )}';
1088
1089
 
1089
1090
  import schemas from '${config.makeImport("./schemas")}';
1090
1091
  import type { Unionize } from '${config.makeImport("../http/dispatcher")}';
1091
- ${template(endpoints_default)({ outputType: config.style?.outputType })}`,
1092
+ ${template(endpoints_default)({})}`,
1092
1093
  [`${join("api", "schemas.ts")}`]: `${allSchemas.map((it) => it.import).join("\n")}
1093
- import { KIND } from "${config.makeImport("../http/index")}";
1094
+
1094
1095
  export default {
1095
1096
  ${allSchemas.map((it) => it.use).join(",\n")}
1096
1097
  };
@@ -1158,15 +1159,18 @@ function toProps(spec, schemaOrRef, aggregator = []) {
1158
1159
  function bodyInputs(spec, ctSchema) {
1159
1160
  const props = [];
1160
1161
  toProps(spec, ctSchema, props);
1161
- return props.reduce(
1162
- (acc, prop) => ({
1163
- ...acc,
1164
- [prop]: {
1165
- in: "body",
1166
- schema: ""
1167
- }
1168
- }),
1169
- {}
1162
+ return (
1163
+ // TODO: should we preproccess the sort at spec level instead of generator's?
1164
+ sortArray(props).reduce(
1165
+ (acc, prop) => ({
1166
+ ...acc,
1167
+ [prop]: {
1168
+ in: "body",
1169
+ schema: ""
1170
+ }
1171
+ }),
1172
+ {}
1173
+ )
1170
1174
  );
1171
1175
  }
1172
1176
  var contentTypeSerializerMap = {
@@ -1232,7 +1236,7 @@ function operationSchema(ir, operation, type) {
1232
1236
  }
1233
1237
 
1234
1238
  // packages/typescript/src/lib/http/dispatcher.txt
1235
- 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\nexport interface Type<T> {\n new (...args: any[]): T;\n}\nexport type Parser = (\n response: Response,\n) => Promise<unknown> | ReadableStream<any>;\nexport type OutputType =\n | Type<APIResponse>\n | { parser: Parser; type: Type<APIResponse> };\n\nexport const fetchType = z\n .function()\n .args(z.instanceof(Request))\n .returns(z.promise(z.instanceof(Response)))\n .optional();\n\nexport async function parse<T extends OutputType[]>(\n outputs: T,\n response: Response,\n) <% if(!throwError) { %>\n: Promise<\n [\n Extract<InstanceType<T>, SuccessfulResponse>['data'],\n Extract<InstanceType<T>, ProblematicResponse>['data'],\n ]\n>\n <% } %>\n\n\n\n {\n let output: typeof APIResponse | null = null;\n let parser: Parser = buffered;\n for (const outputType of outputs) {\n if ('parser' in outputType) {\n parser = outputType.parser;\n if (isTypeOf(outputType.type, APIResponse)) {\n if (response.status === outputType.type.status) {\n output = outputType.type;\n break;\n }\n }\n } else if (isTypeOf(outputType, APIResponse)) {\n if (response.status === outputType.status) {\n output = outputType;\n break;\n }\n }\n }\n\n\n if (response.ok) {\n const apiresponse = (output || APIResponse).create(\n response.status,\n await parser(response),\n );\n <% if(throwError) { %>\n return <% if (outputType === 'default') { %>apiresponse as Extract<InstanceType<T>, SuccessfulResponse><% } else { %>apiresponse as Extract<InstanceType<T>, SuccessfulResponse>;<% } %>;\n <% } else { %>\n return [<% if (outputType === 'default') { %>apiresponse.data as Extract<InstanceType<T>, SuccessfulResponse>['data']<% } else { %>apiresponse as Extract<InstanceType<T>, SuccessfulResponse><% } %>, null] as const;\n <% } %>\n }\n<% if(throwError) { %>\n throw (output || APIError).create(\n response.status,\n await parser(response),\n );\n<% } else { %>\n const data = (output || APIError).create(\n response.status,\n await parser(response),\n );\n return [null, data] as const;\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 ) {\n for (const interceptor of this.#interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n\n let response = await (this.#fetch ?? fetch)(\n new Request(config.url, config.init),\n {\n ...config.init,\n signal: signal,\n },\n );\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 return await parse(outputs, response);\n }\n}\n";
1239
+ 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>;\nexport type OutputType =\n | Type<APIResponse>\n | { parser: Parser; type: Type<APIResponse> };\n\nexport const fetchType = z\n .function()\n .args(z.instanceof(Request))\n .returns(z.promise(z.instanceof(Response)))\n .optional();\n\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 if ('parser' in outputType) {\n parser = outputType.parser;\n if (isTypeOf(outputType.type, APIResponse)) {\n if (response.status === outputType.type.status) {\n output = outputType.type;\n break;\n }\n }\n } else if (isTypeOf(outputType, APIResponse)) {\n if (response.status === outputType.status) {\n output = outputType;\n break;\n }\n }\n }\n\n if (response.ok) {\n const apiresponse = (output || APIResponse).create(\n response.status,\n response.headers,\n mapper((await parser(response)) as ResponseData<T>),\n );\n\n return apiresponse as RebindSuccessPayload<Extract<InstanceType<T>, SuccessfulResponse<unknown>>, R>;\n }\n\n throw (output || APIError).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[], 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 let response = await (this.#fetch ?? fetch)(\n new Request(config.url, config.init),\n {\n ...config.init,\n signal: signal,\n },\n );\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 return await parse(\n outputs,\n response,\n mapper ?? ((data: ResponseData<T>) => data as unknown as R),\n );\n }\n}\n";
1236
1240
 
1237
1241
  // packages/typescript/src/lib/http/interceptors.txt
1238
1242
  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\nexport const logInterceptor: Interceptor = {\n before({ url, init }) {\n console.log('Request:', { url, init });\n return { url, init };\n },\n after(response) {\n console.log('Response:', response);\n return response;\n },\n};\n\n/**\n * Creates an interceptor that logs detailed information about requests and responses.\n * @param options Configuration options for the logger\n * @returns An interceptor object with before and after handlers\n */\nexport const createDetailedLogInterceptor = (options?: {\n logLevel?: 'debug' | 'info' | 'warn' | 'error';\n includeRequestBody?: boolean;\n includeResponseBody?: boolean;\n}) => {\n const logLevel = options?.logLevel || 'info';\n const includeRequestBody = options?.includeRequestBody || false;\n const includeResponseBody = options?.includeResponseBody || false;\n\n return {\n async before(request: Request) {\n const logData = {\n url: request.url,\n method: request.method,\n contentType: request.headers.get('Content-Type'),\n headers: Object.fromEntries([...request.headers.entries()]),\n };\n\n console[logLevel]('\u{1F680} Outgoing Request:', logData);\n\n if (includeRequestBody) {\n try {\n // Clone the request to avoid consuming the body stream\n const clonedRequest = request.clone();\n if (clonedRequest.headers.get('Content-Type')?.includes('application/json')) {\n const body = await clonedRequest.json().catch(() => null);\n console[logLevel]('Request Body:', body);\n } else {\n const body = await clonedRequest.text().catch(() => null);\n console[logLevel]('Request Body:', body);\n }\n } catch (error) {\n console.error('Could not log request body:', error);\n }\n }\n\n return request;\n },\n\n async after(response: Response) {\n const logData = {\n status: response.status,\n statusText: response.statusText,\n url: response.url,\n headers: Object.fromEntries([...response.headers.entries()]),\n };\n\n console[logLevel]('\u{1F4E5} Incoming Response:', logData);\n\n if (includeResponseBody && response.body) {\n try {\n // Clone the response to avoid consuming the body stream\n const clonedResponse = response.clone();\n if (clonedResponse.headers.get('Content-Type')?.includes('application/json')) {\n const body = await clonedResponse.json().catch(() => null);\n console[logLevel]('Response Body:', body);\n } else {\n const body = await clonedResponse.text().catch(() => null);\n if (body) {\n console[logLevel]('Response Body:', body.substring(0, 500) + (body.length > 500 ? '...' : ''));\n } else {\n console[logLevel]('No response body');\n }\n }\n } catch (error) {\n console.error('Could not log response body:', error);\n }\n }\n\n return response;\n },\n };\n};\n";
@@ -1241,445 +1245,13 @@ var interceptors_default = "export interface Interceptor {\n before?: (config:
1241
1245
  var parse_response_default = 'import { parse } from "fast-content-type-parse";\n\nasync function handleChunkedResponse(response: Response, contentType: string) {\n const { type } = parse(contentType);\n\n switch (type) {\n case "application/json": {\n let buffer = "";\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value);\n }\n return JSON.parse(buffer);\n }\n case "text/html":\n case "text/plain": {\n let buffer = "";\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value);\n }\n return buffer;\n }\n default:\n return response.body;\n }\n}\n\nexport function chunked(response: Response) {\n return response.body!;\n}\n\nexport async function buffered(response: Response) {\n const contentType = response.headers.get("Content-Type");\n if (!contentType) {\n throw new Error("Content-Type header is missing");\n }\n\n if (response.status === 204) {\n return null;\n }\n\n const { type } = parse(contentType);\n switch (type) {\n case "application/json":\n return response.json();\n case "text/plain":\n return response.text();\n case "text/html":\n return response.text();\n case "text/xml":\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';
1242
1246
 
1243
1247
  // packages/typescript/src/lib/http/parser.txt
1244
- var parser_default = "import { z } from 'zod';\n\nexport class ParseError<T extends z.ZodType<any, any, any>> {\n public data: z.typeToFlattenedError<T, z.ZodIssue>;\n constructor(data: z.typeToFlattenedError<T, z.ZodIssue>) {\n this.data = data;\n }\n}\n\nexport function parseInput<T extends z.ZodType<any, any, any>>(\n schema: T,\n input: unknown,\n) {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = result.error.flatten((issue) => issue);\n return [null, new ParseError(error)];\n }\n return [result.data as z.infer<T>, null];\n}\n";
1248
+ var parser_default = "import { z } from 'zod';\n\nexport class ParseError<T extends z.ZodType<any, any, any>> extends Error {\n public data: z.typeToFlattenedError<T, z.ZodIssue>;\n constructor(data: z.typeToFlattenedError<T, z.ZodIssue>) {\n super('Validation failed');\n this.name = 'ParseError';\n this.data = data;\n }\n}\n\nexport function parseInput<T extends z.ZodType<any, any, any>>(\n schema: T,\n input: unknown,\n): z.infer<T> {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = result.error.flatten((issue) => issue);\n throw new ParseError(error);\n }\n return result.data as z.infer<T>;\n}\n";
1245
1249
 
1246
1250
  // packages/typescript/src/lib/http/request.txt
1247
1251
  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 ? '' : String(result);\n });\n}\n\ntype Input = Record<string, any>;\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 = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\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, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n return {\n body: this.getBody(),\n url,\n headers: this.getHeaders(),\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, 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 body: method === 'GET' ? undefined : input.body,\n },\n };\n}\n";
1248
1252
 
1249
1253
  // packages/typescript/src/lib/http/response.txt
1250
- var response_default = `export const KIND = Symbol('APIDATA');
1251
-
1252
- export class APIResponse<Body = unknown, Status extends number = number> {
1253
- static readonly status: number;
1254
- static readonly kind: symbol = Symbol.for("APIResponse");
1255
- status: Status;
1256
- data: Body;
1257
-
1258
- constructor(status: Status, data: Body) {
1259
- this.status = status;
1260
- this.data = data;
1261
- }
1262
-
1263
- static create<Body = unknown>(status: number, data: Body) {
1264
- return new this(status, data);
1265
- }
1266
-
1267
- }
1268
-
1269
- export class APIError<Body, Status extends number = number> extends APIResponse<
1270
- Body,
1271
- Status
1272
- > {
1273
- static override create<T>(status: number, data: T) {
1274
- return new this(status, data);
1275
- }
1276
- }
1277
-
1278
-
1279
- // 2xx Success
1280
- export class Ok<T> extends APIResponse<T, 200> {
1281
- static override readonly kind = Symbol.for("Ok");
1282
- static override readonly status = 200 as const;
1283
- constructor(data: T) {
1284
- super(Ok.status, data);
1285
- }
1286
- static override create<T>(status: number, data: T) {
1287
- Object.defineProperty(data, KIND, { value: this.kind });
1288
- return new this(data);
1289
- }
1290
-
1291
- static is<T extends {[KIND]:typeof Ok['kind']}>(value: unknown): value is T {
1292
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1293
- }
1294
- }
1295
-
1296
-
1297
- export class Created<T> extends APIResponse<T, 201> {
1298
- static override readonly kind = Symbol.for("Created");
1299
- static override status = 201 as const;
1300
- constructor(data: T) {
1301
- super(Created.status, data);
1302
- }
1303
- static override create<T>(status: number, data: T) {
1304
- Object.defineProperty(data, KIND, { value: this.kind });
1305
- return new this(data);
1306
- }
1307
-
1308
- static is<T extends {[KIND]: typeof Created['kind']}>(value: unknown): value is T {
1309
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1310
- }
1311
- }
1312
- export class Accepted<T> extends APIResponse<T, 202> {
1313
- static override readonly kind = Symbol.for("Accepted");
1314
- static override status = 202 as const;
1315
- constructor(data: T) {
1316
- super(Accepted.status, data);
1317
- }
1318
- static override create<T>(status: number, data: T) {
1319
- Object.defineProperty(data, KIND, { value: this.kind });
1320
- return new this(data);
1321
- }
1322
-
1323
- static is<T extends {[KIND]: typeof Accepted['kind']}>(value: unknown): value is T {
1324
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1325
- }
1326
- }
1327
- export class NoContent extends APIResponse<never, 204> {
1328
- static override readonly kind = Symbol.for("NoContent");
1329
- static override status = 204 as const;
1330
- constructor() {
1331
- super(NoContent.status, null as never);
1332
- }
1333
- static override create(status: number, data: never): NoContent {
1334
- return new this();
1335
- }
1336
-
1337
- static is<T extends {[KIND]: typeof NoContent['kind']}>(value: unknown): value is T {
1338
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1339
- }
1340
- }
1341
-
1342
- // 4xx Client Errors
1343
- export class BadRequest<T> extends APIError<T, 400> {
1344
- static override readonly kind = Symbol.for("BadRequest");
1345
- static override status = 400 as const;
1346
- constructor(data: T) {
1347
- super(BadRequest.status, data);
1348
- }
1349
- static override create<T>(status: number, data: T) {
1350
- Object.defineProperty(data, KIND, { value: this.kind });
1351
- return new this(data);
1352
- }
1353
-
1354
- static is<T extends {[KIND]: typeof BadRequest['kind']}>(value: unknown): value is T {
1355
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1356
- }
1357
- }
1358
- export class Unauthorized<T = { message: string }> extends APIError<T, 401> {
1359
- static override readonly kind = Symbol.for("Unauthorized");
1360
- static override status = 401 as const;
1361
- constructor(data: T) {
1362
- super(Unauthorized.status, data);
1363
- }
1364
- static override create<T>(status: number, data: T) {
1365
- Object.defineProperty(data, KIND, { value: this.kind });
1366
- return new this(data);
1367
- }
1368
-
1369
- static is<T extends {[KIND]: typeof Unauthorized['kind']}>(value: unknown): value is T {
1370
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1371
- }
1372
- }
1373
- export class PaymentRequired<T = { message: string }> extends APIError<T, 402> {
1374
- static override readonly kind = Symbol.for("PaymentRequired");
1375
- static override status = 402 as const;
1376
- constructor(data: T) {
1377
- super(PaymentRequired.status, data);
1378
- }
1379
- static override create<T>(status: number, data: T) {
1380
- Object.defineProperty(data, KIND, { value: this.kind });
1381
- return new this(data);
1382
- }
1383
-
1384
- static is<T extends {[KIND]: typeof PaymentRequired['kind']}>(value: unknown): value is T {
1385
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1386
- }
1387
- }
1388
- export class Forbidden<T = { message: string }> extends APIError<T, 403> {
1389
- static override readonly kind = Symbol.for("Forbidden");
1390
- static override status = 403 as const;
1391
- constructor(data: T) {
1392
- super(Forbidden.status, data);
1393
- }
1394
- static override create<T>(status: number, data: T) {
1395
- Object.defineProperty(data, KIND, { value: this.kind });
1396
- return new this(data);
1397
- }
1398
-
1399
- static is<T extends {[KIND]: typeof Forbidden['kind']}>(value: unknown): value is T {
1400
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1401
- }
1402
- }
1403
- export class NotFound<T = { message: string }> extends APIError<T, 404> {
1404
- static override readonly kind = Symbol.for("NotFound");
1405
- static override status = 404 as const;
1406
- constructor(data: T) {
1407
- super(NotFound.status, data);
1408
- }
1409
- static override create<T>(status: number, data: T) {
1410
- Object.defineProperty(data, KIND, { value: this.kind });
1411
- return new this(data);
1412
- }
1413
-
1414
- static is<T extends {[KIND]: typeof NotFound['kind']}>(value: unknown): value is T {
1415
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1416
- }
1417
- }
1418
- export class MethodNotAllowed<T = { message: string }> extends APIError<
1419
- T,
1420
- 405
1421
- > {
1422
- static override readonly kind = Symbol.for("MethodNotAllowed");
1423
- static override status = 405 as const;
1424
- constructor(data: T) {
1425
- super(MethodNotAllowed.status, data);
1426
- }
1427
- static override create<T>(status: number, data: T) {
1428
- Object.defineProperty(data, KIND, { value: this.kind });
1429
- return new this(data);
1430
- }
1431
-
1432
- static is<T extends {[KIND]: typeof MethodNotAllowed['kind']}>(value: unknown): value is T {
1433
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1434
- }
1435
- }
1436
- export class NotAcceptable<T = { message: string }> extends APIError<T, 406> {
1437
- static override readonly kind = Symbol.for("NotAcceptable");
1438
- static override status = 406 as const;
1439
- constructor(data: T) {
1440
- super(NotAcceptable.status, data);
1441
- }
1442
- static override create<T>(status: number, data: T) {
1443
- Object.defineProperty(data, KIND, { value: this.kind });
1444
- return new this(data);
1445
- }
1446
-
1447
- static is<T extends {[KIND]: typeof NotAcceptable['kind']}>(value: unknown): value is T {
1448
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1449
- }
1450
- }
1451
- export class Conflict<T = { message: string }> extends APIError<T, 409> {
1452
- static override readonly kind = Symbol.for("Conflict");
1453
- static override status = 409 as const;
1454
- constructor(data: T) {
1455
- super(Conflict.status, data);
1456
- }
1457
- static override create<T>(status: number, data: T) {
1458
- Object.defineProperty(data, KIND, { value: this.kind });
1459
- return new this(data);
1460
- }
1461
-
1462
- static is<T extends {[KIND]: typeof Conflict['kind']}>(value: unknown): value is T {
1463
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1464
- }
1465
- }
1466
- export class Gone<T = { message: string }> extends APIError<T, 410> {
1467
- static override readonly kind = Symbol.for("Gone");
1468
- static override status = 410 as const;
1469
- constructor(data: T) {
1470
- super(Gone.status, data);
1471
- }
1472
- static override create<T>(status: number, data: T) {
1473
- Object.defineProperty(data, KIND, { value: this.kind });
1474
- return new this(data);
1475
- }
1476
-
1477
- static is<T extends {[KIND]: typeof Gone['kind']}>(value: unknown): value is T {
1478
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1479
- }
1480
- }
1481
- export class PreconditionFailed<T = { message: string }> extends APIError<T, 412> {
1482
- static override readonly kind = Symbol.for('PreconditionFailed');
1483
- static override status = 412 as const;
1484
- constructor(data: T) {
1485
- super(PreconditionFailed.status, data);
1486
- }
1487
- static override create<T>(status: number, data: T) {
1488
- Object.defineProperty(data, KIND, { value: this.kind });
1489
- return new this(data);
1490
- }
1491
-
1492
- static is<T extends { [KIND]: (typeof PreconditionFailed)['kind'] }>(
1493
- value: unknown,
1494
- ): value is T {
1495
- return (
1496
- typeof value === 'object' &&
1497
- value !== null &&
1498
- KIND in value &&
1499
- value[KIND] === this.kind
1500
- );
1501
- }
1502
- }
1503
- export class UnprocessableEntity<
1504
- T = { message: string; errors?: Record<string, string[]> },
1505
- > extends APIError<T, 422> {
1506
- static override readonly kind = Symbol.for("UnprocessableEntity");
1507
- static override status = 422 as const;
1508
- constructor(data: T) {
1509
- super(UnprocessableEntity.status, data);
1510
- }
1511
- static override create<T>(status: number, data: T) {
1512
- Object.defineProperty(data, KIND, { value: this.kind });
1513
- return new this(data);
1514
- }
1515
-
1516
- static is<T extends {[KIND]: typeof UnprocessableEntity['kind']}>(value: unknown): value is T {
1517
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1518
- }
1519
- }
1520
- export class TooManyRequests<
1521
- T = { message: string; retryAfter?: string },
1522
- > extends APIError<T, 429> {
1523
- static override readonly kind = Symbol.for("TooManyRequests");
1524
- static override status = 429 as const;
1525
- constructor(data: T) {
1526
- super(TooManyRequests.status, data);
1527
- }
1528
- static override create<T>(status: number, data: T) {
1529
- Object.defineProperty(data, KIND, { value: this.kind });
1530
- return new this(data);
1531
- }
1532
-
1533
- static is<T extends {[KIND]: typeof TooManyRequests['kind']}>(value: unknown): value is T {
1534
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1535
- }
1536
- }
1537
- export class PayloadTooLarge<T = { message: string }> extends APIError<T, 413> {
1538
- static override readonly kind = Symbol.for("PayloadTooLarge");
1539
- static override status = 413 as const;
1540
- constructor(data: T) {
1541
- super(PayloadTooLarge.status, data);
1542
- }
1543
- static override create<T>(status: number, data: T) {
1544
- Object.defineProperty(data, KIND, { value: this.kind });
1545
- return new this(data);
1546
- }
1547
-
1548
- static is<T extends {[KIND]: typeof PayloadTooLarge['kind']}>(value: unknown): value is T {
1549
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1550
- }
1551
- }
1552
- export class UnsupportedMediaType<T = { message: string }> extends APIError<
1553
- T,
1554
- 415
1555
- > {
1556
- static override readonly kind = Symbol.for("UnsupportedMediaType");
1557
- static override status = 415 as const;
1558
- constructor(data: T) {
1559
- super(UnsupportedMediaType.status, data);
1560
- }
1561
- static override create<T>(status: number, data: T) {
1562
- Object.defineProperty(data, KIND, { value: this.kind });
1563
- return new this(data);
1564
- }
1565
-
1566
- static is<T extends {[KIND]: typeof UnsupportedMediaType['kind']}>(value: unknown): value is T {
1567
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1568
- }
1569
- }
1570
-
1571
- // 5xx Server Errors
1572
- export class InternalServerError<T = { message: string }> extends APIError<
1573
- T,
1574
- 500
1575
- > {
1576
- static override readonly kind = Symbol.for("InternalServerError");
1577
- static override status = 500 as const;
1578
- constructor(data: T) {
1579
- super(InternalServerError.status, data);
1580
- }
1581
- static override create<T>(status: number, data: T) {
1582
- Object.defineProperty(data, KIND, { value: this.kind });
1583
- return new this(data);
1584
- }
1585
-
1586
- static is<T extends {[KIND]: typeof InternalServerError['kind']}>(value: unknown): value is T {
1587
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1588
- }
1589
- }
1590
- export class NotImplemented<T = { message: string }> extends APIError<T, 501> {
1591
- static override readonly kind = Symbol.for("NotImplemented");
1592
- static override status = 501 as const;
1593
- constructor(data: T) {
1594
- super(NotImplemented.status, data);
1595
- }
1596
- static override create<T>(status: number, data: T) {
1597
- Object.defineProperty(data, KIND, { value: this.kind });
1598
- return new this(data);
1599
- }
1600
-
1601
- static is<T extends {[KIND]: typeof NotImplemented['kind']}>(value: unknown): value is T {
1602
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1603
- }
1604
- }
1605
- export class BadGateway<T = { message: string }> extends APIError<T, 502> {
1606
- static override readonly kind = Symbol.for("BadGateway");
1607
- static override status = 502 as const;
1608
- constructor(data: T) {
1609
- super(BadGateway.status, data);
1610
- }
1611
- static override create<T>(status: number, data: T) {
1612
- Object.defineProperty(data, KIND, { value: this.kind });
1613
- return new this(data);
1614
- }
1615
-
1616
- static is<T extends {[KIND]: typeof BadGateway['kind']}>(value: unknown): value is T {
1617
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1618
- }
1619
- }
1620
- export class ServiceUnavailable<
1621
- T = { message: string; retryAfter?: string },
1622
- > extends APIError<T, 503> {
1623
- static override readonly kind = Symbol.for("ServiceUnavailable");
1624
- static override status = 503 as const;
1625
- constructor(data: T) {
1626
- super(ServiceUnavailable.status, data);
1627
- }
1628
- static override create<T>(status: number, data: T) {
1629
- Object.defineProperty(data, KIND, { value: this.kind });
1630
- return new this(data);
1631
- }
1632
-
1633
- static is<T extends {[KIND]: typeof ServiceUnavailable['kind']}>(value: unknown): value is T {
1634
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1635
- }
1636
- }
1637
- export class GatewayTimeout<T = { message: string }> extends APIError<T, 504> {
1638
- static override readonly kind = Symbol.for("GatewayTimeout");
1639
- static override status = 504 as const;
1640
- constructor(data: T) {
1641
- super(GatewayTimeout.status, data);
1642
- }
1643
- static override create<T>(status: number, data: T) {
1644
- Object.defineProperty(data, KIND, { value: this.kind });
1645
- return new this(data);
1646
- }
1647
-
1648
- static is<T extends {[KIND]: typeof GatewayTimeout['kind']}>(value: unknown): value is T {
1649
- return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;
1650
- }
1651
- }
1652
-
1653
- export type ClientError =
1654
- | BadRequest<unknown>
1655
- | Unauthorized<unknown>
1656
- | PaymentRequired<unknown>
1657
- | Forbidden<unknown>
1658
- | NotFound<unknown>
1659
- | MethodNotAllowed<unknown>
1660
- | NotAcceptable<unknown>
1661
- | Conflict<unknown>
1662
- | Gone<unknown>
1663
- | PreconditionFailed<unknown>
1664
- | PayloadTooLarge<unknown>
1665
- | UnsupportedMediaType<unknown>
1666
- | UnprocessableEntity<unknown>
1667
- | TooManyRequests<unknown>;
1668
-
1669
- export type ServerError =
1670
- | InternalServerError<unknown>
1671
- | NotImplemented<unknown>
1672
- | BadGateway<unknown>
1673
- | ServiceUnavailable<unknown>
1674
- | GatewayTimeout<unknown>;
1675
-
1676
- export type ProblematicResponse = ClientError | ServerError;
1677
-
1678
- export type SuccessfulResponse =
1679
- | Ok<unknown>
1680
- | Created<unknown>
1681
- | Accepted<unknown>
1682
- | NoContent;`;
1254
+ 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(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\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";
1683
1255
 
1684
1256
  // packages/typescript/src/lib/paginations/cursor-pagination.txt
1685
1257
  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 PaginationResult<T, M extends CursorMetadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<T, M extends CursorMetadata> = (\n input: CursorPaginationParams,\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\n constructor(\n initialParams: PartialNullable<CursorPaginationParams>,\n fetchFn: FetchFn<T, M>,\n ) {\n this.#fetchFn = fetchFn;\n this.#params = {\n cursor: initialParams.cursor ?? undefined,\n };\n }\n\n async getNextPage() {\n const result = await this.#fetchFn(this.#params);\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = {\n ...this.#params,\n cursor: result.meta.nextCursor,\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() {\n if (!this.#currentPage) {\n yield await this.getNextPage();\n }\n\n while (this.hasMore) {\n yield await this.getNextPage();\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;\n};\n";
@@ -3036,15 +2608,7 @@ async function generate(openapi, settings) {
3036
2608
  },
3037
2609
  false
3038
2610
  );
3039
- const style = Object.assign(
3040
- {},
3041
- {
3042
- errorAsValue: false,
3043
- name: "github",
3044
- outputType: "default"
3045
- },
3046
- settings.style ?? {}
3047
- );
2611
+ const style = Object.assign({}, { name: "github" }, settings.style ?? {});
3048
2612
  const output = settings.mode === "full" ? join2(settings.output, "src") : settings.output;
3049
2613
  settings.useTsExtension ??= true;
3050
2614
  settings.readme ??= true;
@@ -3087,23 +2651,20 @@ async function generate(openapi, settings) {
3087
2651
  import { type Interceptor } from '${makeImport("../http/interceptors")}';
3088
2652
  import { type RequestConfig } from '${makeImport("../http/request")}';
3089
2653
  import { buffered } from '${makeImport("./parse-response")}';
3090
- import { APIError, APIResponse, type SuccessfulResponse, type ProblematicResponse } from '${makeImport("./response")}';
2654
+ import { APIError, APIResponse, type SuccessfulResponse, type RebindSuccessPayload } from '${makeImport("./response")}';
3091
2655
 
3092
- ${template2(dispatcher_default, {})({ throwError: !style.errorAsValue, outputType: style.outputType })}`,
2656
+ ${template2(dispatcher_default, {})()}`,
3093
2657
  "interceptors.ts": `
3094
2658
  import type { RequestConfig, HeadersInit } from './${makeImport("request")}';
3095
2659
  ${interceptors_default}`
3096
2660
  });
3097
2661
  await settings.writer(output, {
3098
- "client.ts": client_default(
3099
- {
3100
- name: clientName,
3101
- servers: (spec.servers ?? []).map((server) => server.url) || [],
3102
- options: security(spec),
3103
- makeImport
3104
- },
3105
- style
3106
- ),
2662
+ "client.ts": client_default({
2663
+ name: clientName,
2664
+ servers: (spec.servers ?? []).map((server) => server.url) || [],
2665
+ options: security(spec),
2666
+ makeImport
2667
+ }),
3107
2668
  ...inputs,
3108
2669
  ...endpoints
3109
2670
  });