auto-api-hooks 1.0.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.
@@ -0,0 +1,297 @@
1
+ /**
2
+ * Intermediate Representation (IR) types.
3
+ *
4
+ * All parsers (OpenAPI, Swagger, GraphQL) produce this IR.
5
+ * All generators (fetch, axios, react-query, swr) consume it.
6
+ */
7
+ /** The complete normalized API specification. */
8
+ interface ApiSpec {
9
+ /** Human-readable title from the spec. */
10
+ title: string;
11
+ /** Base URL / server URL. */
12
+ baseUrl: string;
13
+ /** API version string. */
14
+ version: string;
15
+ /** All operations (endpoints / queries / mutations). */
16
+ operations: ApiOperation[];
17
+ /** All named types referenced by operations. */
18
+ types: Map<string, ApiType>;
19
+ }
20
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
21
+ type OperationMethod = HttpMethod | 'QUERY' | 'MUTATION' | 'SUBSCRIPTION';
22
+ /** A single API operation (REST endpoint or GraphQL field). */
23
+ interface ApiOperation {
24
+ /** Unique operation ID (from spec or auto-generated). */
25
+ operationId: string;
26
+ /** Human-readable summary. */
27
+ summary?: string;
28
+ /** HTTP method or GraphQL operation type. */
29
+ method: OperationMethod;
30
+ /** URL path with parameter placeholders, e.g. `/users/{id}`. */
31
+ path: string;
32
+ /** Tags / groups for organizing generated files. */
33
+ tags: string[];
34
+ /** Path parameters. */
35
+ pathParams: ApiParam[];
36
+ /** Query string parameters. */
37
+ queryParams: ApiParam[];
38
+ /** Header parameters. */
39
+ headerParams: ApiParam[];
40
+ /** Request body schema (if any). */
41
+ requestBody?: ApiRequestBody;
42
+ /** Response schema (success case). */
43
+ response: ApiResponse;
44
+ /** Whether this is a paginated endpoint. */
45
+ pagination?: PaginationInfo;
46
+ /** Whether this operation is deprecated. */
47
+ deprecated: boolean;
48
+ }
49
+ interface ApiParam {
50
+ name: string;
51
+ required: boolean;
52
+ type: ApiType;
53
+ description?: string;
54
+ in: 'path' | 'query' | 'header';
55
+ }
56
+ interface ApiRequestBody {
57
+ required: boolean;
58
+ contentType: string;
59
+ type: ApiType;
60
+ description?: string;
61
+ }
62
+ interface ApiResponse {
63
+ statusCode: number | 'default';
64
+ contentType: string;
65
+ type: ApiType;
66
+ description?: string;
67
+ }
68
+ type PaginationStrategy = 'cursor' | 'offset-limit' | 'page-number';
69
+ interface PaginationInfo {
70
+ /** Strategy detected. */
71
+ strategy: PaginationStrategy;
72
+ /** The query param name for the cursor / offset / page. */
73
+ pageParam: string;
74
+ /** Dot-path in the response to find the next page value. */
75
+ nextPagePath: string[];
76
+ /** Dot-path in the response to find the items array. */
77
+ itemsPath: string[];
78
+ }
79
+ /**
80
+ * Recursive type representation — a unified schema type system
81
+ * that covers JSON Schema and GraphQL types.
82
+ */
83
+ type ApiType = ApiPrimitiveType | ApiObjectType | ApiArrayType | ApiEnumType | ApiUnionType | ApiRefType;
84
+ interface ApiPrimitiveType {
85
+ kind: 'primitive';
86
+ type: 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'unknown';
87
+ /** e.g. 'date-time', 'email', 'uuid', 'int64', 'uri' */
88
+ format?: string;
89
+ description?: string;
90
+ }
91
+ interface ApiObjectType {
92
+ kind: 'object';
93
+ name?: string;
94
+ properties: ApiProperty[];
95
+ additionalProperties?: ApiType | boolean;
96
+ description?: string;
97
+ }
98
+ interface ApiProperty {
99
+ name: string;
100
+ type: ApiType;
101
+ required: boolean;
102
+ description?: string;
103
+ }
104
+ interface ApiArrayType {
105
+ kind: 'array';
106
+ items: ApiType;
107
+ description?: string;
108
+ }
109
+ interface ApiEnumType {
110
+ kind: 'enum';
111
+ name?: string;
112
+ values: (string | number)[];
113
+ description?: string;
114
+ }
115
+ interface ApiUnionType {
116
+ kind: 'union';
117
+ variants: ApiType[];
118
+ description?: string;
119
+ }
120
+ interface ApiRefType {
121
+ kind: 'ref';
122
+ /** Reference to a named type in ApiSpec.types. */
123
+ name: string;
124
+ }
125
+
126
+ interface GeneratedFile {
127
+ /** Relative path from output directory. */
128
+ path: string;
129
+ /** Generated source code. */
130
+ content: string;
131
+ }
132
+
133
+ /**
134
+ * Generator interfaces and types.
135
+ */
136
+
137
+ type FetcherStrategy = 'fetch' | 'axios' | 'react-query' | 'swr';
138
+ interface GeneratorOptions {
139
+ /** Which fetcher strategy to generate. */
140
+ fetcher: FetcherStrategy;
141
+ /** Generate Zod validation schemas for response validation. */
142
+ zod: boolean;
143
+ /** Generate MSW mock server handlers. */
144
+ mock: boolean;
145
+ /** Output directory path. */
146
+ outputDir: string;
147
+ /** Base URL override. */
148
+ baseUrl?: string;
149
+ /** Whether to generate infinite query hooks for paginated endpoints. */
150
+ infiniteQueries: boolean;
151
+ }
152
+ interface HookGenerator {
153
+ /** Generate all files for the given spec. */
154
+ generate(spec: ApiSpec, options: GeneratorOptions): GeneratedFile[];
155
+ }
156
+
157
+ interface ParseOptions {
158
+ baseUrl?: string;
159
+ }
160
+
161
+ /**
162
+ * Parses an API specification from a file path, URL, or in-memory object.
163
+ *
164
+ * Supports OpenAPI 3.x, Swagger 2.0, and GraphQL (introspection JSON or SDL).
165
+ * File formats: `.yaml`, `.yml`, `.json`, `.graphql`, `.gql`.
166
+ *
167
+ * After parsing, automatic pagination detection is applied to all GET/QUERY
168
+ * operations.
169
+ *
170
+ * @param input - A file path string, or an already-parsed object (JSON/YAML content or introspection result).
171
+ * @param options - Optional parse configuration (e.g. base URL override).
172
+ * @returns The parsed API specification in the IR format.
173
+ * @throws {ParseError} If the input format is not recognized or no parser can handle it.
174
+ *
175
+ * @example
176
+ * ```ts
177
+ * // From file
178
+ * const spec = await parseSpec('./openapi.yaml')
179
+ *
180
+ * // From object
181
+ * const spec = await parseSpec(openapiDocument, { baseUrl: 'https://api.example.com' })
182
+ *
183
+ * // From GraphQL SDL
184
+ * const spec = await parseSpec('./schema.graphql')
185
+ * ```
186
+ */
187
+ declare function parseSpec(input: string | object, options?: ParseOptions): Promise<ApiSpec>;
188
+
189
+ /**
190
+ * Generator factory and public API.
191
+ */
192
+
193
+ /**
194
+ * Create a hook generator for the specified fetcher strategy.
195
+ */
196
+ declare function createGenerator(strategy: FetcherStrategy): HookGenerator;
197
+ /**
198
+ * Generate hooks from a parsed API spec.
199
+ */
200
+ declare function generateHooks(spec: ApiSpec, options: GeneratorOptions): GeneratedFile[];
201
+
202
+ /**
203
+ * Mock generation public API.
204
+ */
205
+
206
+ /**
207
+ * Generate all mock-related files.
208
+ */
209
+ declare function generateMockFiles(spec: ApiSpec): GeneratedFile[];
210
+
211
+ /**
212
+ * TypeScript source code emitter.
213
+ *
214
+ * Converts IR types into plain TypeScript string output that can be
215
+ * written directly to a `.ts` file. No ts-morph dependency — just
216
+ * fast string concatenation.
217
+ */
218
+
219
+ /**
220
+ * Generate a complete TypeScript `types.ts` file from the API specification.
221
+ *
222
+ * The output includes:
223
+ * - All named types from `spec.types` as interfaces / type aliases
224
+ * - Per-operation params, request body, and response types
225
+ * - JSDoc comments where descriptions are available
226
+ *
227
+ * Every exported symbol is prefixed with `export`.
228
+ */
229
+ declare function emitTypeScriptTypes(spec: ApiSpec): string;
230
+ /**
231
+ * Convert an {@link ApiType} into its TypeScript string representation.
232
+ *
233
+ * Handles all discriminated union kinds recursively:
234
+ * - `primitive` -> `string`, `number`, `boolean`, `null`, `unknown`
235
+ * - `object` -> inline `{ ... }` literal
236
+ * - `array` -> `Array<T>`
237
+ * - `enum` -> string/number literal union
238
+ * - `union` -> `A | B | C`
239
+ * - `ref` -> PascalCase type name
240
+ */
241
+ declare function emitTypeString(type: ApiType): string;
242
+
243
+ /**
244
+ * Zod schema source code emitter.
245
+ *
246
+ * Converts IR types into Zod schema definitions as plain TypeScript
247
+ * strings. The output can be written directly to a `schemas.ts` file.
248
+ */
249
+
250
+ /**
251
+ * Generate a complete Zod `schemas.ts` file from the API specification.
252
+ *
253
+ * The output includes:
254
+ * - `import { z } from 'zod'`
255
+ * - A `const …Schema = z.…` for every named type in `spec.types`
256
+ * - A response schema for every operation
257
+ * - Re-exports of all schemas
258
+ */
259
+ declare function emitZodSchemas(spec: ApiSpec): string;
260
+ /**
261
+ * Convert an {@link ApiType} into its Zod schema string representation.
262
+ *
263
+ * Handles every discriminated union kind recursively:
264
+ * - `primitive` -> `z.string()`, `z.number()`, etc. with format refinements
265
+ * - `object` -> `z.object({ ... })`
266
+ * - `array` -> `z.array(...)`
267
+ * - `enum` -> `z.enum([...])` for strings, `z.union([z.literal(...), ...])` for mixed
268
+ * - `union` -> `z.union([...])`
269
+ * - `ref` -> camelCase schema variable name
270
+ */
271
+ declare function emitZodType(type: ApiType): string;
272
+
273
+ interface GenerateOptions {
274
+ /** Path to the API spec file, or a parsed object. */
275
+ spec: string | object;
276
+ /** Fetching strategy. */
277
+ fetcher: FetcherStrategy;
278
+ /** Output directory. If provided, files are written to disk. */
279
+ outputDir?: string;
280
+ /** Override base URL from the spec. */
281
+ baseUrl?: string;
282
+ /** Generate Zod validation schemas. */
283
+ zod?: boolean;
284
+ /** Generate MSW mock server handlers. */
285
+ mock?: boolean;
286
+ /** Generate infinite query hooks for paginated endpoints. */
287
+ infiniteQueries?: boolean;
288
+ }
289
+ /**
290
+ * Generate type-safe React hooks from an API specification.
291
+ *
292
+ * @param options - Generation options
293
+ * @returns Array of generated files (path + content)
294
+ */
295
+ declare function generate(options: GenerateOptions): Promise<GeneratedFile[]>;
296
+
297
+ export { type ApiArrayType, type ApiEnumType, type ApiObjectType, type ApiOperation, type ApiParam, type ApiPrimitiveType, type ApiProperty, type ApiRefType, type ApiRequestBody, type ApiResponse, type ApiSpec, type ApiType, type ApiUnionType, type FetcherStrategy, type GenerateOptions, type GeneratedFile, type GeneratorOptions, type HookGenerator, type HttpMethod, type OperationMethod, type PaginationInfo, type PaginationStrategy, type ParseOptions, createGenerator, emitTypeScriptTypes, emitTypeString, emitZodSchemas, emitZodType, generate, generateHooks, generateMockFiles, parseSpec };
@@ -0,0 +1,297 @@
1
+ /**
2
+ * Intermediate Representation (IR) types.
3
+ *
4
+ * All parsers (OpenAPI, Swagger, GraphQL) produce this IR.
5
+ * All generators (fetch, axios, react-query, swr) consume it.
6
+ */
7
+ /** The complete normalized API specification. */
8
+ interface ApiSpec {
9
+ /** Human-readable title from the spec. */
10
+ title: string;
11
+ /** Base URL / server URL. */
12
+ baseUrl: string;
13
+ /** API version string. */
14
+ version: string;
15
+ /** All operations (endpoints / queries / mutations). */
16
+ operations: ApiOperation[];
17
+ /** All named types referenced by operations. */
18
+ types: Map<string, ApiType>;
19
+ }
20
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
21
+ type OperationMethod = HttpMethod | 'QUERY' | 'MUTATION' | 'SUBSCRIPTION';
22
+ /** A single API operation (REST endpoint or GraphQL field). */
23
+ interface ApiOperation {
24
+ /** Unique operation ID (from spec or auto-generated). */
25
+ operationId: string;
26
+ /** Human-readable summary. */
27
+ summary?: string;
28
+ /** HTTP method or GraphQL operation type. */
29
+ method: OperationMethod;
30
+ /** URL path with parameter placeholders, e.g. `/users/{id}`. */
31
+ path: string;
32
+ /** Tags / groups for organizing generated files. */
33
+ tags: string[];
34
+ /** Path parameters. */
35
+ pathParams: ApiParam[];
36
+ /** Query string parameters. */
37
+ queryParams: ApiParam[];
38
+ /** Header parameters. */
39
+ headerParams: ApiParam[];
40
+ /** Request body schema (if any). */
41
+ requestBody?: ApiRequestBody;
42
+ /** Response schema (success case). */
43
+ response: ApiResponse;
44
+ /** Whether this is a paginated endpoint. */
45
+ pagination?: PaginationInfo;
46
+ /** Whether this operation is deprecated. */
47
+ deprecated: boolean;
48
+ }
49
+ interface ApiParam {
50
+ name: string;
51
+ required: boolean;
52
+ type: ApiType;
53
+ description?: string;
54
+ in: 'path' | 'query' | 'header';
55
+ }
56
+ interface ApiRequestBody {
57
+ required: boolean;
58
+ contentType: string;
59
+ type: ApiType;
60
+ description?: string;
61
+ }
62
+ interface ApiResponse {
63
+ statusCode: number | 'default';
64
+ contentType: string;
65
+ type: ApiType;
66
+ description?: string;
67
+ }
68
+ type PaginationStrategy = 'cursor' | 'offset-limit' | 'page-number';
69
+ interface PaginationInfo {
70
+ /** Strategy detected. */
71
+ strategy: PaginationStrategy;
72
+ /** The query param name for the cursor / offset / page. */
73
+ pageParam: string;
74
+ /** Dot-path in the response to find the next page value. */
75
+ nextPagePath: string[];
76
+ /** Dot-path in the response to find the items array. */
77
+ itemsPath: string[];
78
+ }
79
+ /**
80
+ * Recursive type representation — a unified schema type system
81
+ * that covers JSON Schema and GraphQL types.
82
+ */
83
+ type ApiType = ApiPrimitiveType | ApiObjectType | ApiArrayType | ApiEnumType | ApiUnionType | ApiRefType;
84
+ interface ApiPrimitiveType {
85
+ kind: 'primitive';
86
+ type: 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'unknown';
87
+ /** e.g. 'date-time', 'email', 'uuid', 'int64', 'uri' */
88
+ format?: string;
89
+ description?: string;
90
+ }
91
+ interface ApiObjectType {
92
+ kind: 'object';
93
+ name?: string;
94
+ properties: ApiProperty[];
95
+ additionalProperties?: ApiType | boolean;
96
+ description?: string;
97
+ }
98
+ interface ApiProperty {
99
+ name: string;
100
+ type: ApiType;
101
+ required: boolean;
102
+ description?: string;
103
+ }
104
+ interface ApiArrayType {
105
+ kind: 'array';
106
+ items: ApiType;
107
+ description?: string;
108
+ }
109
+ interface ApiEnumType {
110
+ kind: 'enum';
111
+ name?: string;
112
+ values: (string | number)[];
113
+ description?: string;
114
+ }
115
+ interface ApiUnionType {
116
+ kind: 'union';
117
+ variants: ApiType[];
118
+ description?: string;
119
+ }
120
+ interface ApiRefType {
121
+ kind: 'ref';
122
+ /** Reference to a named type in ApiSpec.types. */
123
+ name: string;
124
+ }
125
+
126
+ interface GeneratedFile {
127
+ /** Relative path from output directory. */
128
+ path: string;
129
+ /** Generated source code. */
130
+ content: string;
131
+ }
132
+
133
+ /**
134
+ * Generator interfaces and types.
135
+ */
136
+
137
+ type FetcherStrategy = 'fetch' | 'axios' | 'react-query' | 'swr';
138
+ interface GeneratorOptions {
139
+ /** Which fetcher strategy to generate. */
140
+ fetcher: FetcherStrategy;
141
+ /** Generate Zod validation schemas for response validation. */
142
+ zod: boolean;
143
+ /** Generate MSW mock server handlers. */
144
+ mock: boolean;
145
+ /** Output directory path. */
146
+ outputDir: string;
147
+ /** Base URL override. */
148
+ baseUrl?: string;
149
+ /** Whether to generate infinite query hooks for paginated endpoints. */
150
+ infiniteQueries: boolean;
151
+ }
152
+ interface HookGenerator {
153
+ /** Generate all files for the given spec. */
154
+ generate(spec: ApiSpec, options: GeneratorOptions): GeneratedFile[];
155
+ }
156
+
157
+ interface ParseOptions {
158
+ baseUrl?: string;
159
+ }
160
+
161
+ /**
162
+ * Parses an API specification from a file path, URL, or in-memory object.
163
+ *
164
+ * Supports OpenAPI 3.x, Swagger 2.0, and GraphQL (introspection JSON or SDL).
165
+ * File formats: `.yaml`, `.yml`, `.json`, `.graphql`, `.gql`.
166
+ *
167
+ * After parsing, automatic pagination detection is applied to all GET/QUERY
168
+ * operations.
169
+ *
170
+ * @param input - A file path string, or an already-parsed object (JSON/YAML content or introspection result).
171
+ * @param options - Optional parse configuration (e.g. base URL override).
172
+ * @returns The parsed API specification in the IR format.
173
+ * @throws {ParseError} If the input format is not recognized or no parser can handle it.
174
+ *
175
+ * @example
176
+ * ```ts
177
+ * // From file
178
+ * const spec = await parseSpec('./openapi.yaml')
179
+ *
180
+ * // From object
181
+ * const spec = await parseSpec(openapiDocument, { baseUrl: 'https://api.example.com' })
182
+ *
183
+ * // From GraphQL SDL
184
+ * const spec = await parseSpec('./schema.graphql')
185
+ * ```
186
+ */
187
+ declare function parseSpec(input: string | object, options?: ParseOptions): Promise<ApiSpec>;
188
+
189
+ /**
190
+ * Generator factory and public API.
191
+ */
192
+
193
+ /**
194
+ * Create a hook generator for the specified fetcher strategy.
195
+ */
196
+ declare function createGenerator(strategy: FetcherStrategy): HookGenerator;
197
+ /**
198
+ * Generate hooks from a parsed API spec.
199
+ */
200
+ declare function generateHooks(spec: ApiSpec, options: GeneratorOptions): GeneratedFile[];
201
+
202
+ /**
203
+ * Mock generation public API.
204
+ */
205
+
206
+ /**
207
+ * Generate all mock-related files.
208
+ */
209
+ declare function generateMockFiles(spec: ApiSpec): GeneratedFile[];
210
+
211
+ /**
212
+ * TypeScript source code emitter.
213
+ *
214
+ * Converts IR types into plain TypeScript string output that can be
215
+ * written directly to a `.ts` file. No ts-morph dependency — just
216
+ * fast string concatenation.
217
+ */
218
+
219
+ /**
220
+ * Generate a complete TypeScript `types.ts` file from the API specification.
221
+ *
222
+ * The output includes:
223
+ * - All named types from `spec.types` as interfaces / type aliases
224
+ * - Per-operation params, request body, and response types
225
+ * - JSDoc comments where descriptions are available
226
+ *
227
+ * Every exported symbol is prefixed with `export`.
228
+ */
229
+ declare function emitTypeScriptTypes(spec: ApiSpec): string;
230
+ /**
231
+ * Convert an {@link ApiType} into its TypeScript string representation.
232
+ *
233
+ * Handles all discriminated union kinds recursively:
234
+ * - `primitive` -> `string`, `number`, `boolean`, `null`, `unknown`
235
+ * - `object` -> inline `{ ... }` literal
236
+ * - `array` -> `Array<T>`
237
+ * - `enum` -> string/number literal union
238
+ * - `union` -> `A | B | C`
239
+ * - `ref` -> PascalCase type name
240
+ */
241
+ declare function emitTypeString(type: ApiType): string;
242
+
243
+ /**
244
+ * Zod schema source code emitter.
245
+ *
246
+ * Converts IR types into Zod schema definitions as plain TypeScript
247
+ * strings. The output can be written directly to a `schemas.ts` file.
248
+ */
249
+
250
+ /**
251
+ * Generate a complete Zod `schemas.ts` file from the API specification.
252
+ *
253
+ * The output includes:
254
+ * - `import { z } from 'zod'`
255
+ * - A `const …Schema = z.…` for every named type in `spec.types`
256
+ * - A response schema for every operation
257
+ * - Re-exports of all schemas
258
+ */
259
+ declare function emitZodSchemas(spec: ApiSpec): string;
260
+ /**
261
+ * Convert an {@link ApiType} into its Zod schema string representation.
262
+ *
263
+ * Handles every discriminated union kind recursively:
264
+ * - `primitive` -> `z.string()`, `z.number()`, etc. with format refinements
265
+ * - `object` -> `z.object({ ... })`
266
+ * - `array` -> `z.array(...)`
267
+ * - `enum` -> `z.enum([...])` for strings, `z.union([z.literal(...), ...])` for mixed
268
+ * - `union` -> `z.union([...])`
269
+ * - `ref` -> camelCase schema variable name
270
+ */
271
+ declare function emitZodType(type: ApiType): string;
272
+
273
+ interface GenerateOptions {
274
+ /** Path to the API spec file, or a parsed object. */
275
+ spec: string | object;
276
+ /** Fetching strategy. */
277
+ fetcher: FetcherStrategy;
278
+ /** Output directory. If provided, files are written to disk. */
279
+ outputDir?: string;
280
+ /** Override base URL from the spec. */
281
+ baseUrl?: string;
282
+ /** Generate Zod validation schemas. */
283
+ zod?: boolean;
284
+ /** Generate MSW mock server handlers. */
285
+ mock?: boolean;
286
+ /** Generate infinite query hooks for paginated endpoints. */
287
+ infiniteQueries?: boolean;
288
+ }
289
+ /**
290
+ * Generate type-safe React hooks from an API specification.
291
+ *
292
+ * @param options - Generation options
293
+ * @returns Array of generated files (path + content)
294
+ */
295
+ declare function generate(options: GenerateOptions): Promise<GeneratedFile[]>;
296
+
297
+ export { type ApiArrayType, type ApiEnumType, type ApiObjectType, type ApiOperation, type ApiParam, type ApiPrimitiveType, type ApiProperty, type ApiRefType, type ApiRequestBody, type ApiResponse, type ApiSpec, type ApiType, type ApiUnionType, type FetcherStrategy, type GenerateOptions, type GeneratedFile, type GeneratorOptions, type HookGenerator, type HttpMethod, type OperationMethod, type PaginationInfo, type PaginationStrategy, type ParseOptions, createGenerator, emitTypeScriptTypes, emitTypeString, emitZodSchemas, emitZodType, generate, generateHooks, generateMockFiles, parseSpec };