@cushin/api-codegen 1.0.4 → 1.0.6

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 CHANGED
@@ -90,8 +90,8 @@ var APIClient = class {
90
90
  this.authCallbacks = authCallbacks;
91
91
  this.hooks = {
92
92
  beforeRequest: [
93
- (request) => {
94
- const tokens = this.authCallbacks?.getTokens();
93
+ async (request) => {
94
+ const tokens = await this.authCallbacks?.getTokens();
95
95
  if (tokens?.accessToken) {
96
96
  request.headers.set(
97
97
  "Authorization",
@@ -106,7 +106,7 @@ var APIClient = class {
106
106
  if (retryCount === 1 && this.authCallbacks) {
107
107
  try {
108
108
  await this.refreshTokens();
109
- const tokens = this.authCallbacks.getTokens();
109
+ const tokens = await this.authCallbacks.getTokens();
110
110
  if (tokens?.accessToken) {
111
111
  request.headers.set(
112
112
  "Authorization",
@@ -114,12 +114,10 @@ var APIClient = class {
114
114
  );
115
115
  }
116
116
  } catch (refreshError) {
117
- this.authCallbacks.clearTokens();
118
117
  this.authCallbacks.onAuthError?.();
119
118
  throw new AuthError();
120
119
  }
121
120
  } else {
122
- this.authCallbacks?.clearTokens();
123
121
  this.authCallbacks?.onAuthError?.();
124
122
  throw new AuthError();
125
123
  }
@@ -168,10 +166,7 @@ var APIClient = class {
168
166
  this.refreshPromise = (async () => {
169
167
  try {
170
168
  if (this.authCallbacks?.onRefreshToken) {
171
- const newAccessToken = await this.authCallbacks.onRefreshToken();
172
- this.authCallbacks.setTokens({
173
- accessToken: newAccessToken
174
- });
169
+ await this.authCallbacks.onRefreshToken();
175
170
  } else {
176
171
  throw new AuthError("No refresh token handler provided");
177
172
  }
@@ -443,24 +438,12 @@ var HooksGenerator = class extends BaseGenerator {
443
438
  const endpointsPath = path6.join(this.context.config.endpointsPath);
444
439
  const relativePath = path6.relative(path6.dirname(outputPath), endpointsPath).replace(/\\/g, "/");
445
440
  const content = `${useClientDirective ? "'use client';\n" : ""}
446
- import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
447
- import type {
448
- UseQueryOptions,
449
- UseMutationOptions,
450
- QueryKey
451
- } from '@tanstack/react-query';
452
- import { apiClient } from './client';
453
- import type {
454
- APIEndpoints,
455
- ExtractBody,
456
- ExtractParams,
457
- ExtractQuery,
458
- ExtractResponse
459
- } from './types';
460
- import { queryKeys } from './query-keys';
461
- ${this.hasQueryOptions() ? "import { apiQueryOptions } from './query-options';" : ""}
462
- import { z } from 'zod';
463
- import { apiConfig } from '${relativePath}';
441
+ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
442
+ import { apiClient } from "./client";
443
+ import { queryKeys } from "./query-keys";
444
+ import { apiQueryOptions } from "./query-options";
445
+ import { z } from "zod";
446
+ import { apiConfig } from "${relativePath}";
464
447
 
465
448
  ${this.generateQueryHooks()}
466
449
  ${this.generateMutationHooks()}
@@ -771,25 +754,27 @@ ${this.generateEndpointTypes()}
771
754
  }
772
755
  generateEndpointTypes() {
773
756
  const types = [];
774
- Object.entries(this.context.apiConfig.endpoints).forEach(([name, endpoint]) => {
775
- const cap = this.capitalize(name);
776
- if (endpoint.response)
777
- types.push(
778
- `export type ${cap}Response = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.response`)};`
779
- );
780
- if (endpoint.body)
781
- types.push(
782
- `export type ${cap}Input = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.body`)};`
783
- );
784
- if (endpoint.query)
785
- types.push(
786
- `export type ${cap}Query = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.query`)};`
787
- );
788
- if (endpoint.params)
789
- types.push(
790
- `export type ${cap}Params = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.params`)};`
791
- );
792
- });
757
+ Object.entries(this.context.apiConfig.endpoints).forEach(
758
+ ([name, endpoint]) => {
759
+ const cap = this.capitalize(name);
760
+ if (endpoint.response)
761
+ types.push(
762
+ `export type ${cap}Response = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.response`)};`
763
+ );
764
+ if (endpoint.body)
765
+ types.push(
766
+ `export type ${cap}Input = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.body`)};`
767
+ );
768
+ if (endpoint.query)
769
+ types.push(
770
+ `export type ${cap}Query = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.query`)};`
771
+ );
772
+ if (endpoint.params)
773
+ types.push(
774
+ `export type ${cap}Params = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.params`)};`
775
+ );
776
+ }
777
+ );
793
778
  return types.join("\n");
794
779
  }
795
780
  };
@@ -808,7 +793,10 @@ var ClientGenerator = class extends BaseGenerator {
808
793
  }
809
794
  async generateServerClientFile() {
810
795
  const content = this.generateServerClientContent();
811
- const outputPath = path6.join(this.context.config.outputDir, "server-client.ts");
796
+ const outputPath = path6.join(
797
+ this.context.config.outputDir,
798
+ "server-client.ts"
799
+ );
812
800
  await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
813
801
  await fs5.writeFile(outputPath, content, "utf-8");
814
802
  }
@@ -821,36 +809,36 @@ var ClientGenerator = class extends BaseGenerator {
821
809
  import { createAPIClient } from '@cushin/api-codegen/client';
822
810
  import type { AuthCallbacks } from '@cushin/api-codegen/client';
823
811
  import { apiConfig } from '${relativePath}';
824
- import type { APIEndpoints } from './types';
825
812
  import { z } from 'zod';
826
813
 
827
- // Type-safe API client methods
814
+ // Type the methods based on endpoints
828
815
  type APIClientMethods = {
829
- [K in keyof APIEndpoints]: APIEndpoints[K] extends {
816
+ [K in keyof typeof apiConfig.endpoints]: (typeof apiConfig.endpoints)[K] extends {
830
817
  method: infer M;
831
818
  params?: infer P;
832
819
  query?: infer Q;
833
820
  body?: infer B;
834
821
  response: infer R;
835
822
  }
836
- ? M extends 'GET'
837
- ? P extends { _type: any }
838
- ? Q extends { _type: any }
839
- ? (params: P['_type'], query?: Q['_type']) => Promise<R['_type']>
840
- : (params: P['_type']) => Promise<R['_type']>
841
- : Q extends { _type: any }
842
- ? (query?: Q['_type']) => Promise<R['_type']>
843
- : () => Promise<R['_type']>
844
- : P extends { _type: any }
845
- ? B extends { _type: any }
846
- ? (params: P['_type'], body: B['_type']) => Promise<R['_type']>
847
- : (params: P['_type']) => Promise<R['_type']>
848
- : B extends { _type: any }
849
- ? (body: B['_type']) => Promise<R['_type']>
850
- : () => Promise<R['_type']>
823
+ ? M extends "GET"
824
+ ? P extends z.ZodJSONSchema
825
+ ? Q extends z.ZodJSONSchema
826
+ ? (params: z.infer<P>, query?: z.infer<Q>) => Promise<z.infer<R>>
827
+ : (params: z.infer<P>) => Promise<z.infer<R>>
828
+ : Q extends z.ZodJSONSchema
829
+ ? (query?: z.infer<Q>) => Promise<z.infer<R>>
830
+ : () => Promise<z.infer<R>>
831
+ : P extends z.ZodJSONSchema
832
+ ? B extends z.ZodJSONSchema
833
+ ? (params: z.infer<P>, body: z.infer<B>) => Promise<z.infer<R>>
834
+ : (params: z.infer<P>) => Promise<z.infer<R>>
835
+ : B extends z.ZodJSONSchema
836
+ ? (body: z.infer<B>) => Promise<z.infer<R>>
837
+ : () => Promise<z.infer<R>>
851
838
  : never;
852
839
  };
853
840
 
841
+
854
842
  // Export singleton instance (will be initialized later)
855
843
  export let baseClient: APIClientMethods & {
856
844
  refreshAuth: () => Promise<void>;
@@ -930,49 +918,51 @@ export const serverClient = createAPIClient(apiConfig) as APIClientMethods;
930
918
  }
931
919
  generateApiClientMethods() {
932
920
  const methods = [];
933
- Object.entries(this.context.apiConfig.endpoints).forEach(([name, endpoint]) => {
934
- const inferParams = this.inferNonNull(
935
- `typeof apiConfig.endpoints.${name}.params`
936
- );
937
- const inferQuery = this.inferNonNull(
938
- `typeof apiConfig.endpoints.${name}.query`
939
- );
940
- const inferBody = this.inferNonNull(
941
- `typeof apiConfig.endpoints.${name}.body`
942
- );
943
- const inferResponse = this.inferNonNull(
944
- `typeof apiConfig.endpoints.${name}.response`
945
- );
946
- if (endpoint.method === "GET") {
947
- if (endpoint.params && endpoint.query) {
948
- methods.push(` ${name}: (params: ${inferParams}, query?: ${inferQuery}): Promise<${inferResponse}> =>
921
+ Object.entries(this.context.apiConfig.endpoints).forEach(
922
+ ([name, endpoint]) => {
923
+ const inferParams = this.inferNonNull(
924
+ `typeof apiConfig.endpoints.${name}.params`
925
+ );
926
+ const inferQuery = this.inferNonNull(
927
+ `typeof apiConfig.endpoints.${name}.query`
928
+ );
929
+ const inferBody = this.inferNonNull(
930
+ `typeof apiConfig.endpoints.${name}.body`
931
+ );
932
+ const inferResponse = this.inferNonNull(
933
+ `typeof apiConfig.endpoints.${name}.response`
934
+ );
935
+ if (endpoint.method === "GET") {
936
+ if (endpoint.params && endpoint.query) {
937
+ methods.push(` ${name}: (params: ${inferParams}, query?: ${inferQuery}): Promise<${inferResponse}> =>
949
938
  (baseClient as any).${name}(params, query),`);
950
- } else if (endpoint.params) {
951
- methods.push(` ${name}: (params: ${inferParams}): Promise<${inferResponse}> =>
939
+ } else if (endpoint.params) {
940
+ methods.push(` ${name}: (params: ${inferParams}): Promise<${inferResponse}> =>
952
941
  (baseClient as any).${name}(params),`);
953
- } else if (endpoint.query) {
954
- methods.push(` ${name}: (query?: ${inferQuery}): Promise<${inferResponse}> =>
942
+ } else if (endpoint.query) {
943
+ methods.push(` ${name}: (query?: ${inferQuery}): Promise<${inferResponse}> =>
955
944
  (baseClient as any).${name}(query),`);
956
- } else {
957
- methods.push(` ${name}: (): Promise<${inferResponse}> =>
945
+ } else {
946
+ methods.push(` ${name}: (): Promise<${inferResponse}> =>
958
947
  (baseClient as any).${name}(),`);
959
- }
960
- } else {
961
- if (endpoint.params && endpoint.body) {
962
- methods.push(` ${name}: (params: ${inferParams}, body: ${inferBody}): Promise<${inferResponse}> =>
948
+ }
949
+ } else {
950
+ if (endpoint.params && endpoint.body) {
951
+ methods.push(` ${name}: (params: ${inferParams}, body: ${inferBody}): Promise<${inferResponse}> =>
963
952
  (baseClient as any).${name}(params, body),`);
964
- } else if (endpoint.params) {
965
- methods.push(` ${name}: (params: ${inferParams}): Promise<${inferResponse}> =>
953
+ } else if (endpoint.params) {
954
+ methods.push(` ${name}: (params: ${inferParams}): Promise<${inferResponse}> =>
966
955
  (baseClient as any).${name}(params),`);
967
- } else if (endpoint.body) {
968
- methods.push(` ${name}: (body: ${inferBody}): Promise<${inferResponse}> =>
956
+ } else if (endpoint.body) {
957
+ methods.push(` ${name}: (body: ${inferBody}): Promise<${inferResponse}> =>
969
958
  (baseClient as any).${name}(body),`);
970
- } else {
971
- methods.push(` ${name}: (): Promise<${inferResponse}> =>
959
+ } else {
960
+ methods.push(` ${name}: (): Promise<${inferResponse}> =>
972
961
  (baseClient as any).${name}(),`);
962
+ }
973
963
  }
974
964
  }
975
- });
965
+ );
976
966
  return methods.join("\n");
977
967
  }
978
968
  };