@cushin/api-codegen 1.0.9 → 1.1.1

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/cli.js CHANGED
@@ -459,7 +459,7 @@ import { apiConfig } from '${relativePath}';
459
459
 
460
460
 
461
461
  // Re-export endpoint configuration types
462
- export type { APIConfig, APIEndpoint, HTTPMethod } from '@cushin/api-codegen/schema';
462
+ export type { APIConfig, APIEndpoint, HTTPMethod } from './schema';
463
463
 
464
464
  /**
465
465
  * Type helper to extract params schema from an endpoint
@@ -552,8 +552,8 @@ var ClientGenerator = class extends BaseGenerator {
552
552
  const endpointsPath = path6.join(this.context.config.endpointsPath);
553
553
  const relativePath = path6.relative(path6.dirname(outputPath), endpointsPath).replace(/\\/g, "/");
554
554
  return `${useClientDirective ? "'use client';\n" : ""}
555
- import { createAPIClient } from '@cushin/api-codegen/client';
556
- import type { AuthCallbacks } from '@cushin/api-codegen/client';
555
+ import { createAPIClient } from './core';
556
+ import type { AuthCallbacks } from './core';
557
557
  import { apiConfig } from '${relativePath}';
558
558
  import { z } from 'zod';
559
559
 
@@ -621,7 +621,7 @@ export type { AuthCallbacks };
621
621
  `;
622
622
  }
623
623
  generateServerClientContent() {
624
- return `import { createAPIClient } from '@cushin/api-codegen/client';
624
+ return `import { createAPIClient } from './core';
625
625
  import { apiConfig } from '../config/endpoints';
626
626
  import type { APIEndpoints } from './types';
627
627
 
@@ -720,9 +720,12 @@ var QueryKeysGenerator = class extends BaseGenerator {
720
720
  await fs5.writeFile(outputPath, content, "utf-8");
721
721
  }
722
722
  generateContent() {
723
+ const outputPath = path6.join(this.context.config.outputDir, "types.ts");
724
+ const endpointsPath = path6.join(this.context.config.endpointsPath);
725
+ const relativePath = path6.relative(path6.dirname(outputPath), endpointsPath).replace(/\\/g, "/");
723
726
  const content = `// Auto-generated query keys
724
727
  import { z } from 'zod';
725
- import { apiConfig } from '../config/endpoints';
728
+ import { apiConfig } from '${relativePath}';
726
729
 
727
730
  export const queryKeys = {
728
731
  ${this.generateQueryKeysContent()}
@@ -780,12 +783,15 @@ var QueryOptionsGenerator = class extends BaseGenerator {
780
783
  await fs5.writeFile(outputPath, content, "utf-8");
781
784
  }
782
785
  generateContent() {
786
+ const outputPath = path6.join(this.context.config.outputDir, "types.ts");
787
+ const endpointsPath = path6.join(this.context.config.endpointsPath);
788
+ const relativePath = path6.relative(path6.dirname(outputPath), endpointsPath).replace(/\\/g, "/");
783
789
  const content = `// Auto-generated query options
784
790
  import { queryOptions } from '@tanstack/react-query';
785
- import { apiClient } from './api-client';
791
+ import { apiClient } from './client';
786
792
  import { queryKeys } from './query-keys';
787
793
  import { z } from 'zod';
788
- import { apiConfig } from '../config/endpoints';
794
+ import { apiConfig } from '${relativePath}';
789
795
 
790
796
  ${this.generateQueryOptionsContent()}
791
797
 
@@ -911,6 +917,419 @@ ${this.generatePrefetchFunctions()}
911
917
  };`;
912
918
  }
913
919
  };
920
+ var SchemaGenerator = class extends BaseGenerator {
921
+ async generate() {
922
+ const content = this.generateContent();
923
+ const outputPath = path6.join(this.context.config.outputDir, "schema.ts");
924
+ await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
925
+ await fs5.writeFile(outputPath, content, "utf-8");
926
+ }
927
+ generateContent() {
928
+ const content = `// Auto-generated schema definitions
929
+
930
+ import type { z } from 'zod';
931
+
932
+ export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
933
+
934
+ export interface APIEndpoint {
935
+ path: string;
936
+ method: HTTPMethod;
937
+ baseUrl?: string;
938
+ params?: z.ZodType<any>;
939
+ query?: z.ZodType<any>;
940
+ body?: z.ZodType<any>;
941
+ response: z.ZodType<any>;
942
+ tags?: string[];
943
+ description?: string;
944
+ }
945
+
946
+ export interface APIConfig {
947
+ baseUrl?: string;
948
+ endpoints: Record<string, APIEndpoint>;
949
+ }
950
+
951
+ export type EndpointConfig<
952
+ TPath extends string = string,
953
+ TMethod extends HTTPMethod = HTTPMethod,
954
+ TParams = undefined,
955
+ TQuery = undefined,
956
+ TBody = undefined,
957
+ TResponse = any,
958
+ > = {
959
+ path: TPath;
960
+ method: TMethod;
961
+ baseUrl?: string;
962
+ params?: z.ZodType<TParams>;
963
+ query?: z.ZodType<TQuery>;
964
+ body?: z.ZodType<TBody>;
965
+ response: z.ZodType<TResponse>;
966
+ tags?: string[];
967
+ description?: string;
968
+ };
969
+
970
+ /**
971
+ * Helper function to define API configuration with type safety
972
+ */
973
+ export function defineConfig<T extends APIConfig>(config: T): T {
974
+ return config;
975
+ }
976
+
977
+ /**
978
+ * Helper function to define a single endpoint with type inference
979
+ */
980
+ export function defineEndpoint<
981
+ TPath extends string,
982
+ TMethod extends HTTPMethod,
983
+ TParams = undefined,
984
+ TQuery = undefined,
985
+ TBody = undefined,
986
+ TResponse = any,
987
+ >(
988
+ config: EndpointConfig<TPath, TMethod, TParams, TQuery, TBody, TResponse>,
989
+ ): EndpointConfig<TPath, TMethod, TParams, TQuery, TBody, TResponse> {
990
+ return config;
991
+ }
992
+
993
+ /**
994
+ * Helper to define multiple endpoints
995
+ */
996
+ export function defineEndpoints<
997
+ T extends Record<string, APIEndpoint>,
998
+ >(endpoints: T): T {
999
+ return endpoints;
1000
+ }
1001
+ }
1002
+ `;
1003
+ return content;
1004
+ }
1005
+ };
1006
+ var CoreGenerator = class extends BaseGenerator {
1007
+ async generate() {
1008
+ const content = this.generateContent();
1009
+ const outputPath = path6.join(this.context.config.outputDir, "core.ts");
1010
+ await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
1011
+ await fs5.writeFile(outputPath, content, "utf-8");
1012
+ }
1013
+ generateContent() {
1014
+ const content = `// Auto-generated schema definitions
1015
+
1016
+ import ky, { HTTPError } from "ky";
1017
+ import type { APIConfig, APIEndpoint } from "../config/schema.js";
1018
+
1019
+ export interface AuthTokens {
1020
+ accessToken: string;
1021
+ refreshToken?: string;
1022
+ }
1023
+
1024
+ export interface AuthCallbacks {
1025
+ getTokens: () => Promise<AuthTokens | null>;
1026
+ onAuthError?: () => void;
1027
+ onRefreshToken?: () => Promise<void>;
1028
+ }
1029
+
1030
+ export class APIError extends Error {
1031
+ constructor(
1032
+ message: string,
1033
+ public status: number,
1034
+ public response?: any,
1035
+ ) {
1036
+ super(message);
1037
+ this.name = "APIError";
1038
+ }
1039
+ }
1040
+
1041
+ export class AuthError extends APIError {
1042
+ constructor(message: string = "Authentication failed") {
1043
+ super(message, 401);
1044
+ this.name = "AuthError";
1045
+ }
1046
+ }
1047
+
1048
+ export class APIClient {
1049
+ private client: typeof ky;
1050
+ private isRefreshing = false;
1051
+ private refreshPromise: Promise<void> | null = null;
1052
+ private hooks: any;
1053
+
1054
+ constructor(
1055
+ private config: APIConfig,
1056
+ private authCallbacks?: AuthCallbacks,
1057
+ ) {
1058
+ this.hooks = {
1059
+ beforeRequest: [
1060
+ async (request: Request) => {
1061
+ const tokens = await this.authCallbacks?.getTokens();
1062
+ if (tokens?.accessToken) {
1063
+ request.headers.set(
1064
+ "Authorization",
1065
+ \`Bearer \${tokens.accessToken}\`,
1066
+ );
1067
+ }
1068
+ },
1069
+ ],
1070
+ beforeRetry: [
1071
+ async ({ request, error, retryCount }: any) => {
1072
+ if (error instanceof HTTPError && error.response.status === 401) {
1073
+ if (retryCount === 1 && this.authCallbacks) {
1074
+ try {
1075
+ await this.refreshTokens();
1076
+ const tokens = await this.authCallbacks.getTokens();
1077
+ if (tokens?.accessToken) {
1078
+ request.headers.set(
1079
+ "Authorization",
1080
+ \`Bearer \${tokens.accessToken}\`,
1081
+ );
1082
+ }
1083
+ } catch (refreshError) {
1084
+ this.authCallbacks.onAuthError?.();
1085
+ throw new AuthError();
1086
+ }
1087
+ } else {
1088
+ this.authCallbacks?.onAuthError?.();
1089
+ throw new AuthError();
1090
+ }
1091
+ }
1092
+ },
1093
+ ],
1094
+ beforeError: [
1095
+ async (error: any) => {
1096
+ const { response } = error;
1097
+ if (response?.body) {
1098
+ try {
1099
+ const body = await response.json();
1100
+ error.message =
1101
+ (body as Error).message || \`HTTP \${response.status}\`;
1102
+ } catch {
1103
+ // Keep original message
1104
+ }
1105
+ }
1106
+ return error;
1107
+ },
1108
+ ],
1109
+ };
1110
+
1111
+ this.client = ky.create({
1112
+ prefixUrl: this.config.baseUrl,
1113
+ headers: {
1114
+ "Content-Type": "application/json",
1115
+ },
1116
+ retry: {
1117
+ limit: 2,
1118
+ methods: ["get", "post", "put", "delete", "patch"],
1119
+ statusCodes: [401],
1120
+ },
1121
+ hooks: this.hooks,
1122
+ });
1123
+ }
1124
+
1125
+ private async refreshTokens(): Promise<void> {
1126
+ if (!this.authCallbacks) {
1127
+ throw new AuthError("No auth callbacks provided");
1128
+ }
1129
+
1130
+ if (this.isRefreshing && this.refreshPromise) {
1131
+ return this.refreshPromise;
1132
+ }
1133
+
1134
+ this.isRefreshing = true;
1135
+
1136
+ this.refreshPromise = (async () => {
1137
+ try {
1138
+ if (this.authCallbacks?.onRefreshToken) {
1139
+ await this.authCallbacks.onRefreshToken();
1140
+ } else {
1141
+ throw new AuthError("No refresh token handler provided");
1142
+ }
1143
+ } catch (error) {
1144
+ throw error;
1145
+ } finally {
1146
+ this.isRefreshing = false;
1147
+ this.refreshPromise = null;
1148
+ }
1149
+ })();
1150
+
1151
+ return this.refreshPromise;
1152
+ }
1153
+
1154
+ private buildPath(path: string, params?: Record<string, any>): string {
1155
+ if (!params) return path;
1156
+
1157
+ let finalPath = path;
1158
+ Object.entries(params).forEach(([key, value]) => {
1159
+ finalPath = finalPath.replace(
1160
+ \`:\${key}\`,
1161
+ encodeURIComponent(String(value)),
1162
+ );
1163
+ });
1164
+
1165
+ return finalPath;
1166
+ }
1167
+
1168
+ private getEndpointBaseUrl(endpoint: APIEndpoint): string {
1169
+ return endpoint.baseUrl || this.config.baseUrl!;
1170
+ }
1171
+
1172
+ private getClientForEndpoint(endpoint: APIEndpoint): typeof ky {
1173
+ const endpointBaseUrl = this.getEndpointBaseUrl(endpoint);
1174
+
1175
+ if (endpointBaseUrl === this.config.baseUrl) {
1176
+ return this.client;
1177
+ }
1178
+
1179
+ return ky.create({
1180
+ prefixUrl: endpointBaseUrl,
1181
+ headers: {
1182
+ "Content-Type": "application/json",
1183
+ },
1184
+ retry: {
1185
+ limit: 2,
1186
+ methods: ["get", "post", "put", "delete", "patch"],
1187
+ statusCodes: [401],
1188
+ },
1189
+ hooks: this.hooks,
1190
+ });
1191
+ }
1192
+
1193
+ async request<T>(
1194
+ endpoint: APIEndpoint,
1195
+ params?: Record<string, any>,
1196
+ query?: Record<string, any>,
1197
+ body?: any,
1198
+ ): Promise<T> {
1199
+ try {
1200
+ const path = this.buildPath(endpoint.path, params);
1201
+ const client = this.getClientForEndpoint(endpoint);
1202
+
1203
+ const options: Record<string, any> = {
1204
+ method: endpoint.method,
1205
+ };
1206
+
1207
+ if (query && Object.keys(query).length > 0) {
1208
+ const searchParams = new URLSearchParams();
1209
+ Object.entries(query).forEach(([key, value]) => {
1210
+ if (value !== undefined && value !== null) {
1211
+ searchParams.append(key, String(value));
1212
+ }
1213
+ });
1214
+ if (searchParams.toString()) {
1215
+ options.searchParams = searchParams;
1216
+ }
1217
+ }
1218
+
1219
+ if (body && endpoint.method !== "GET") {
1220
+ if (endpoint.body) {
1221
+ const validatedBody = endpoint.body.parse(body);
1222
+ options.json = validatedBody;
1223
+ } else {
1224
+ options.json = body;
1225
+ }
1226
+ }
1227
+
1228
+ const response = await client(path, options);
1229
+ const data = await response.json();
1230
+
1231
+ if (endpoint.response) {
1232
+ return endpoint.response.parse(data);
1233
+ }
1234
+
1235
+ return data as T;
1236
+ } catch (error) {
1237
+ if (error instanceof HTTPError) {
1238
+ const errorData = await error.response.json().catch(() => ({}));
1239
+ throw new APIError(
1240
+ errorData.message || error.message,
1241
+ error.response.status,
1242
+ errorData,
1243
+ );
1244
+ }
1245
+
1246
+ if (error instanceof AuthError) {
1247
+ throw error;
1248
+ }
1249
+
1250
+ throw new APIError(
1251
+ error instanceof Error ? error.message : "Network error",
1252
+ 0,
1253
+ );
1254
+ }
1255
+ }
1256
+
1257
+ updateAuthCallbacks(authCallbacks: AuthCallbacks) {
1258
+ this.authCallbacks = authCallbacks;
1259
+ }
1260
+
1261
+ async refreshAuth(): Promise<void> {
1262
+ if (!this.authCallbacks) {
1263
+ throw new AuthError("No auth callbacks provided");
1264
+ }
1265
+ await this.refreshTokens();
1266
+ }
1267
+
1268
+ generateMethods() {
1269
+ const methods: any = {};
1270
+
1271
+ Object.entries(this.config.endpoints).forEach(([name, endpoint]) => {
1272
+ if (endpoint.method === "GET") {
1273
+ if (endpoint.params && endpoint.query) {
1274
+ methods[name] = (params: any, query?: any): Promise<any> => {
1275
+ return this.request(endpoint, params, query);
1276
+ };
1277
+ } else if (endpoint.params) {
1278
+ methods[name] = (params: any): Promise<any> => {
1279
+ return this.request(endpoint, params);
1280
+ };
1281
+ } else if (endpoint.query) {
1282
+ methods[name] = (query?: any): Promise<any> => {
1283
+ return this.request(endpoint, undefined, query);
1284
+ };
1285
+ } else {
1286
+ methods[name] = (): Promise<any> => {
1287
+ return this.request(endpoint);
1288
+ };
1289
+ }
1290
+ } else {
1291
+ if (endpoint.params && endpoint.body) {
1292
+ methods[name] = (params: any, body: any): Promise<any> => {
1293
+ return this.request(endpoint, params, undefined, body);
1294
+ };
1295
+ } else if (endpoint.params) {
1296
+ methods[name] = (params: any): Promise<any> => {
1297
+ return this.request(endpoint, params);
1298
+ };
1299
+ } else if (endpoint.body) {
1300
+ methods[name] = (body: any): Promise<any> => {
1301
+ return this.request(endpoint, undefined, undefined, body);
1302
+ };
1303
+ } else {
1304
+ methods[name] = (): Promise<any> => {
1305
+ return this.request(endpoint);
1306
+ };
1307
+ }
1308
+ }
1309
+ });
1310
+
1311
+ return methods;
1312
+ }
1313
+ }
1314
+
1315
+ export function createAPIClient(
1316
+ config: APIConfig,
1317
+ authCallbacks?: AuthCallbacks,
1318
+ ) {
1319
+ const instance = new APIClient(config, authCallbacks);
1320
+ const methods = instance.generateMethods();
1321
+
1322
+ return {
1323
+ ...methods,
1324
+ refreshAuth: () => instance.refreshAuth(),
1325
+ updateAuthCallbacks: (newCallbacks: AuthCallbacks) =>
1326
+ instance.updateAuthCallbacks(newCallbacks),
1327
+ };
1328
+ }
1329
+ `;
1330
+ return content;
1331
+ }
1332
+ };
914
1333
 
915
1334
  // src/generators/index.ts
916
1335
  var CodeGenerator = class {
@@ -926,6 +1345,8 @@ var CodeGenerator = class {
926
1345
  getGenerators() {
927
1346
  const generators = [];
928
1347
  generators.push(new TypesGenerator(this.context));
1348
+ generators.push(new SchemaGenerator(this.context));
1349
+ generators.push(new CoreGenerator(this.context));
929
1350
  if (this.context.config.generateClient) {
930
1351
  generators.push(new ClientGenerator(this.context));
931
1352
  }