@moccona/apicodegen 0.1.1 → 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.
package/npm/index.d.mts CHANGED
@@ -1,8 +1,6 @@
1
- import { Block, Node, ParameterDeclaration, Statement, TypeNode } from "typescript";
1
+ import { Block, Expression, Node, ObjectLiteralElementLike, ParameterDeclaration, Statement, TypeNode } from "typescript";
2
2
  import { OpenAPIV3 } from "openapi-types";
3
3
  import { PluginOption } from "vite";
4
-
5
- //#region src/core/interface.d.ts
6
4
  /**
7
5
  * Simple represenration for JSON object
8
6
  */
@@ -46,21 +44,39 @@ declare enum ParameterIn {
46
44
  interface ReferenceObject {
47
45
  $ref: string;
48
46
  }
47
+ /** OpenAPI 3 discriminator: property name plus value → schema ref map. */
48
+ interface DiscriminatorObject {
49
+ propertyName: string;
50
+ mapping?: Record<string, string>;
51
+ }
49
52
  interface EnumSchemaObject {
50
53
  name: string;
51
54
  enum: (string | number)[];
52
55
  }
53
56
  interface SingleTypeSchemaObject {
54
57
  type: keyof typeof NonArraySchemaType | string;
58
+ /** Explicit union from a JSON Schema `type` array (OpenAPI 3.1). */
59
+ types?: string[];
60
+ /** JSON Schema `nullable` (OpenAPI 3.0) or `null` in a type array. */
61
+ nullable?: boolean;
62
+ /** JSON Schema `const`: the only allowed value. */
63
+ const?: string | number | boolean;
64
+ /** Index signature for objects without fixed properties. */
65
+ additionalProperties?: boolean | SchemaObject;
55
66
  description?: string;
56
67
  allOf?: SchemaObject[];
57
68
  anyOf?: SchemaObject[];
58
69
  deprecated?: boolean;
70
+ discriminator?: DiscriminatorObject;
59
71
  enum?: (string | number)[];
60
72
  format?: keyof typeof SchemaFormatType;
61
73
  oneOf?: SchemaObject[];
62
74
  properties?: Record<string, SchemaObject>;
63
75
  readonly?: boolean;
76
+ /** Present in requests only; omitted from generated response types (OpenAPI `writeOnly`). */
77
+ writeOnly?: boolean;
78
+ /** Present in responses only; omitted from generated request types (OpenAPI `readOnly`). */
79
+ readOnly?: boolean;
64
80
  required?: string[] | boolean;
65
81
  ref?: string;
66
82
  isRef?: boolean;
@@ -69,29 +85,39 @@ interface ArrayTypeSchemaObject {
69
85
  type: keyof typeof ArraySchemaType;
70
86
  items?: SchemaObject;
71
87
  required?: boolean;
88
+ nullable?: boolean;
72
89
  description?: string;
73
90
  ref?: string;
74
91
  }
75
92
  type SchemaObject = SingleTypeSchemaObject | ArrayTypeSchemaObject;
76
93
  type ParameterObject = {
77
94
  name: string;
78
- in: keyof typeof ParameterIn;
95
+ /** Where the parameter is sent. A missing `in` is treated as a body parameter. */
96
+ in?: keyof typeof ParameterIn;
79
97
  schema?: SchemaObject;
80
98
  required?: boolean;
81
99
  description?: string;
82
100
  deprecated?: boolean;
101
+ /** OpenAPI serialization style (e.g. `form`, `spaceDelimited`, `pipeDelimited`). */
102
+ style?: string;
103
+ /** Whether array/object values use repeated keys instead of one joined value. */
104
+ explode?: boolean;
83
105
  ref?: string;
84
106
  };
85
107
  declare enum MediaTypes {
86
108
  JSON = "application/json",
87
- EVENT_STREAM = "text/event-stream",
88
109
  TEXT = "text",
89
110
  IMAGE = "image",
90
111
  AUDIO = "audio",
91
112
  VIDEO = "video"
92
113
  }
93
114
  type MediaTypeObject = {
94
- type: MediaTypes | keyof typeof MediaTypes;
115
+ /**
116
+ * Media type of the payload, e.g. `application/json`,
117
+ * `multipart/form-data`. Known types keep autocomplete, any other media
118
+ * type is accepted.
119
+ */
120
+ type: MediaTypes | `${MediaTypes}` | (string & {});
95
121
  schema?: SchemaObject;
96
122
  };
97
123
  type ResponsesObject = Record<string, MediaTypeObject[]>;
@@ -106,6 +132,18 @@ declare enum HttpMethods {
106
132
  PATCH = "patch",
107
133
  TRACE = "trace"
108
134
  }
135
+ type SecuritySchemeObject = {
136
+ /** `apiKey`, `http`, `oauth2`, `openIdConnect`, or Swagger 2.0 `basic`. */
137
+ type: string;
138
+ /** HTTP auth scheme (`bearer` / `basic`). */
139
+ scheme?: string;
140
+ /** apiKey location. */
141
+ in?: 'header' | 'query' | 'cookie';
142
+ /** apiKey header/query/cookie name. */
143
+ name?: string;
144
+ };
145
+ /** A security requirement: scheme name → required scopes. */
146
+ type SecurityRequirementObject = Record<string, string[]>;
109
147
  type OperationObject = {
110
148
  method: string;
111
149
  summary?: string;
@@ -117,7 +155,14 @@ type OperationObject = {
117
155
  }[];
118
156
  parameters?: ParameterObject[];
119
157
  requestBody?: MediaTypeObject[];
158
+ /** Media type chosen for the function return value (first 2xx). */
120
159
  responses: MediaTypeObject[];
160
+ /** Every declared status code, including error responses. */
161
+ responseTypes?: ResponsesObject;
162
+ /** OpenAPI tags (first tag selects the output file in split mode). */
163
+ tags?: string[];
164
+ /** Effective security requirements (operation-level, else document-level). */
165
+ security?: SecurityRequirementObject[];
121
166
  deprecated?: boolean;
122
167
  };
123
168
  type PathObject = {
@@ -131,11 +176,32 @@ type FetchDocRequestInit = {
131
176
  method?: string;
132
177
  body?: string | FormData;
133
178
  headers?: Record<string, string>;
179
+ /**
180
+ * Skip TLS certificate verification when fetching the spec.
181
+ * Only use this for trusted local/self-signed endpoints.
182
+ */
183
+ insecure?: boolean;
184
+ /** Milliseconds to wait for response headers (undici). */
185
+ headersTimeout?: number;
186
+ /** Milliseconds to wait for the response body (undici). */
187
+ bodyTimeout?: number;
134
188
  };
135
189
  declare enum Adaptors {
136
190
  fetch = "fetch",
137
191
  axios = "axios"
138
192
  }
193
+ /**
194
+ * How generated clients handle non-2xx responses.
195
+ *
196
+ * - `throw` — reject with an error carrying `status` and `body`.
197
+ * - `result` — resolve a `{ ok, status, data | error }` discriminated union.
198
+ *
199
+ * Omitted keeps the adaptor's current behaviour (fetch returns the response
200
+ * as-is; axios rejects on non-2xx).
201
+ */
202
+ type ErrorMode = 'throw' | 'result';
203
+ /** Output layout: one file for everything, or one file per OpenAPI tag. */
204
+ type SplitBy = 'tag';
139
205
  type ProviderInitOptions = {
140
206
  docURL: string;
141
207
  output: string;
@@ -144,6 +210,18 @@ type ProviderInitOptions = {
144
210
  requestOptions?: FetchDocRequestInit;
145
211
  verbose?: boolean;
146
212
  adaptor?: keyof typeof Adaptors;
213
+ /** How generated clients handle non-2xx responses (default: leave as-is). */
214
+ errorMode?: ErrorMode;
215
+ /** Split output into one file per tag (default: single file). */
216
+ splitBy?: SplitBy;
217
+ /** Keep only operations carrying at least one of these tags. */
218
+ includeTags?: string[];
219
+ /** Drop operations carrying any of these tags. */
220
+ excludeTags?: string[];
221
+ /** Keep only paths starting with one of these prefixes. */
222
+ includePaths?: string[];
223
+ /** Drop paths starting with one of these prefixes. */
224
+ excludePaths?: string[];
147
225
  };
148
226
  interface ProviderInitResult {
149
227
  readonly enums: EnumSchemaObject[];
@@ -151,10 +229,63 @@ interface ProviderInitResult {
151
229
  readonly parameters: Record<string, ParameterObject>;
152
230
  readonly responses: Record<string, ResponsesObject>;
153
231
  readonly requestBodies: Record<string, RequestBodyObject>;
232
+ readonly securitySchemes: Record<string, SecuritySchemeObject>;
154
233
  readonly apis: PathsObject;
155
234
  }
156
- //#endregion
157
- //#region src/core/base/Adaptor.d.ts
235
+ /**
236
+ * How a security scheme is injected into a generated request.
237
+ */
238
+ type AuthInjection = {
239
+ /** Key into the generated `AuthOptions` object. */
240
+ scheme: string;
241
+ location: 'header' | 'query' | 'cookie';
242
+ /** Header / query / cookie name. */
243
+ name: string;
244
+ /** `raw` = direct value, `bearer` = `Bearer <token>`, `basic` = base64 pair. */
245
+ kind: 'raw' | 'bearer' | 'basic';
246
+ };
247
+ /** The generated auth argument: parameter name plus its injections. */
248
+ type AuthArgument = {
249
+ name: string;
250
+ injections: AuthInjection[];
251
+ };
252
+ /** The generated request-options argument (`signal`, `headers`, `timeout`). */
253
+ type RequestControl = {
254
+ /** Parameter name in the generated function, e.g. `options`. */
255
+ name: string;
256
+ };
257
+ /** `options?.name` */
258
+ declare function optionalAccess(control: RequestControl, name: string): Expression;
259
+ /**
260
+ * `options?.signal && options?.timeout ? AbortSignal.any([...]) : ...`,
261
+ * combining a caller signal with a timeout when both are present.
262
+ */
263
+ declare function fetchSignalExpression(control: RequestControl): Expression;
264
+ /**
265
+ * Header entries plus a spread of caller-supplied headers.
266
+ */
267
+ declare function withRequestHeaders(entries: ObjectLiteralElementLike[], control: RequestControl | undefined): ObjectLiteralElementLike[];
268
+ /** `auth?.["scheme"]` */
269
+ declare function authAccess(auth: AuthArgument, scheme: string): Expression;
270
+ /**
271
+ * Header entries (conditional spreads) for auth schemes sent as headers.
272
+ */
273
+ declare function authHeaderEntries(auth: AuthArgument): ObjectLiteralElementLike[];
274
+ /**
275
+ * Builds a `Cookie` header value from OpenAPI cookie parameters.
276
+ * Undefined/null values are filtered out at runtime.
277
+ */
278
+ declare function cookieHeaderExpression(parameters: ParameterObject[], auth?: AuthArgument): Expression;
279
+ /**
280
+ * Body shape used to encode the request payload.
281
+ *
282
+ * - `json` — `application/json` (or unknown textual type): serialise via `JSON.stringify`.
283
+ * - `form-data` — `multipart/form-data` (or any request containing files): build `FormData`.
284
+ * - `urlencoded` — `application/x-www-form-urlencoded`: build `URLSearchParams`.
285
+ * - `binary` — single binary/blob parameter: pass the value directly.
286
+ * - `none` — no body.
287
+ */
288
+ type BodyKind = 'json' | 'form-data' | 'urlencoded' | 'binary' | 'none';
158
289
  /**
159
290
  * Base adapter for tool
160
291
  * This abstract class serves as the foundation for implementing adapters for different code generation tools
@@ -188,15 +319,16 @@ declare abstract class Adapter {
188
319
  * @param {MediaTypeObject | undefined} requestBody - The request body payload (if applicable)
189
320
  * @param {MediaTypeObject | undefined} response - The expected response format (if applicable)
190
321
  * @param {Adapter} adapter - An instance of the adapter being used
191
- * @param {boolean} useFormData - Flag indicating whether to use FormData for the request body
322
+ * @param {BodyKind} bodyKind - How the request body should be encoded
323
+ * @param {string | undefined} bodyContentType - The Content-Type header to set (undefined means "let the runtime decide", e.g. for multipart with boundary)
192
324
  * @param {boolean} useJSONResponse - Flag indicating whether the response should be parsed as JSON
193
- * @param {boolean} isEventStream - Flag indicating whether the response is a text/event-stream (SSE) stream; when true, the adapter must return the raw response without parsing
325
+ * @param {ErrorMode | undefined} errorMode - Non-2xx handling (undefined keeps current behaviour)
326
+ * @param {AuthArgument} auth - Security credentials to inject (if any)
327
+ * @param {RequestControl} requestControl - Request options argument (if any)
194
328
  * @returns {Statement[]} An array of TypeScript AST statements representing the generated code
195
329
  */
196
- abstract client(uri: string, method: string, parameters: ParameterObject[], requestBody: MediaTypeObject | undefined, response: MediaTypeObject | undefined, adapter: Adapter, useFormData: boolean, useJSONResponse: boolean, isEventStream: boolean): Statement[];
330
+ abstract client(uri: string, method: string, parameters: ParameterObject[], requestBody: MediaTypeObject | undefined, response: MediaTypeObject | undefined, adapter: Adapter, bodyKind: BodyKind, bodyContentType: string | undefined, useJSONResponse: boolean, errorMode?: ErrorMode, auth?: AuthArgument, requestControl?: RequestControl): Statement[];
197
331
  }
198
- //#endregion
199
- //#region src/core/base/Base.d.ts
200
332
  /**
201
333
  * Represents success HTTP status codes.
202
334
  * Each key is a string representation of a success HTTP status code.
@@ -232,13 +364,35 @@ declare abstract class Base {
232
364
  * @param [operationId] - Unique identifier for the operation.
233
365
  * @returns - The generated function name.
234
366
  */
235
- static pathToFnName(path: string, method?: string, _operationId?: string): string;
367
+ static pathToFnName(path: string, method?: string, operationId?: string): string;
368
+ /**
369
+ * Converts arbitrary text into a legal TypeScript variable identifier.
370
+ * Keywords keep the `_` suffix that `normalize` adds, since `camelCase`
371
+ * would otherwise strip it and emit a reserved word.
372
+ * @param text - Input text.
373
+ * @returns - A legal identifier.
374
+ */
375
+ static toIdentifier(text: string): string;
236
376
  /**
237
377
  * Normalizes a string by replacing special characters and avoiding TypeScript keywords.
238
378
  * @param text - Input text to normalize.
239
379
  * @returns - The normalized string.
240
380
  */
241
381
  static normalize(text: string): string;
382
+ /**
383
+ * Map a request body media type to a stable function-name suffix.
384
+ *
385
+ * Used to disambiguate sibling operations sharing the same path+method
386
+ * but different request body media types. The result is appended (in
387
+ * upperCamelCase) to the operation's base function name.
388
+ *
389
+ * Known types are mapped to short, human-readable names. Unknown types
390
+ * fall back to `camelCase(normalize(<sub-type>))`.
391
+ *
392
+ * @param mediaType - The OpenAPI media type (e.g. `application/json`).
393
+ * @returns - The suffix without leading underscore, or empty string.
394
+ */
395
+ static mediaTypeToSuffix(mediaType: string): string;
242
396
  /**
243
397
  * Capitalizes the first character of a string.
244
398
  * @param text - Input string.
@@ -257,13 +411,81 @@ declare abstract class Base {
257
411
  * @returns - UpperCamelCase string.
258
412
  */
259
413
  static upperCamelCase(text: string): string;
414
+ /**
415
+ * Classify a spec location string into a transport + source pair.
416
+ *
417
+ * Returns:
418
+ * - `{ transport: 'file', source }` when `input` looks like a local
419
+ * filesystem path (`file://...`, POSIX absolute, Windows absolute).
420
+ * - `{ transport: 'http', source }` for `http(s)://...` URLs.
421
+ *
422
+ * Relative paths are treated as `http` so that callers (CLI / Vite
423
+ * plugin) must resolve them against cwd first. This makes intent
424
+ * explicit and avoids accidentally reading from process.cwd().
425
+ */
426
+ static resolveSpecURL(input: string): {
427
+ transport: 'file' | 'http';
428
+ source: string;
429
+ };
430
+ /**
431
+ * Read and parse a local OpenAPI document from the filesystem.
432
+ *
433
+ * @param filePath - Absolute filesystem path to the spec.
434
+ * @returns - A promise resolving to the parsed document.
435
+ */
436
+ private static readLocalDoc;
437
+ /**
438
+ * Parses an OpenAPI document from JSON or YAML text.
439
+ *
440
+ * JSON is attempted first for a clearer syntax error on JSON files; YAML
441
+ * then handles `.yaml` / `.yml` specs. Any failure is reported as
442
+ * `E_SPEC_PARSE_FAILED` with the source path attached.
443
+ *
444
+ * @param raw - Raw spec content.
445
+ * @param source - Path or URL used in error messages.
446
+ * @returns - The parsed document.
447
+ */
448
+ static parseDoc<T = unknown>(raw: string, source: string): T;
260
449
  /**
261
450
  * Fetches documentation from a given URL.
262
- * @param url - The URL to fetch the documentation from.
263
- * @param requestInit - Additional request parameters.
451
+ *
452
+ * Supports three transport modes:
453
+ * - `file://...` URLs → read from filesystem (JSON or YAML)
454
+ * - absolute filesystem paths → read from filesystem (JSON or YAML)
455
+ * - `http(s)://...` URLs (and unrecognised inputs like relative paths)
456
+ * → fetched via undici (existing behavior)
457
+ *
458
+ * Callers should pass an already-resolved absolute path or URL. Relative
459
+ * paths fall through to undici by design — CLI / Vite plugin should
460
+ * resolve them against cwd first.
461
+ *
462
+ * @param url - The URL or filesystem path to fetch the documentation from.
463
+ * @param requestInit - Additional request parameters (only used for http(s)).
464
+ * TLS certificates are verified by default; set `insecure: true` to opt out.
264
465
  * @returns - A promise resolving to the fetched documentation data.
265
466
  */
266
467
  static fetchDoc<T = unknown>(url: string, requestInit?: FetchDocRequestInit): Promise<T>;
468
+ /**
469
+ * Copies external `$ref` targets (other files or remote URLs) into the root
470
+ * document and rewrites the refs to local ones. Objects are registered
471
+ * before their children are walked, so cycles keep working.
472
+ *
473
+ * External refs are placed in the component section implied by their
474
+ * fragment (`schemas` by default); a generated local `$ref` points at the
475
+ * copy.
476
+ *
477
+ * @param doc - Parsed root document (mutated in place).
478
+ * @param source - Absolute path or URL of the root document.
479
+ * @param requestInit - Request options for remote refs.
480
+ * @returns - The same document with external refs resolved.
481
+ */
482
+ static bundleExternalRefs<T>(doc: T, source: string, requestInit?: FetchDocRequestInit): Promise<T>;
483
+ /** Component section an external ref belongs to. */
484
+ private static externalRefSection;
485
+ /** Local component name derived from the ref fragment or file name. */
486
+ private static externalRefName;
487
+ /** Resolves a `#/a/b` JSON pointer inside a parsed document. */
488
+ private static resolveJSONPointer;
267
489
  /**
268
490
  * Determines the media type from a given media type string.
269
491
  * @param mediaType - The media type string to evaluate.
@@ -309,8 +531,6 @@ declare abstract class Base {
309
531
  */
310
532
  static isRef(schema: unknown): schema is ReferenceObject;
311
533
  }
312
- //#endregion
313
- //#region src/core/base/Provider.d.ts
314
534
  /**
315
535
  * Abstract Provider Class.
316
536
  *
@@ -354,6 +574,8 @@ declare abstract class Provider implements ProviderInitResult, ProviderInitOptio
354
574
  readonly responses: Record<string, ResponsesObject>;
355
575
  /** collection of request bodies indexed by name */
356
576
  readonly requestBodies: Record<string, RequestBodyObject>;
577
+ /** security schemes declared by the document */
578
+ readonly securitySchemes: Record<string, SecuritySchemeObject>;
357
579
  /** collection of API endpoints (operations) indexed by path */
358
580
  readonly apis: Record<string, OperationObject[]>;
359
581
  /** URL for fetching API documentation */
@@ -382,11 +604,9 @@ declare abstract class Provider implements ProviderInitResult, ProviderInitOptio
382
604
  */
383
605
  abstract parse(doc: unknown): ProviderInitResult;
384
606
  }
385
- //#endregion
386
- //#region src/core/client/axios.d.ts
387
607
  /**
388
608
  * Adapter class implementing support for generating code that makes use of the Axios HTTP client library.
389
- * This class defines custom behavior and field mappings specific to the Axios client.
609
+ * This adapter defines custom behavior and field mappings specific to the Axios client.
390
610
  */
391
611
  declare class AxiosAdapter extends Adapter {
392
612
  /**
@@ -410,22 +630,12 @@ declare class AxiosAdapter extends Adapter {
410
630
  */
411
631
  readonly name = "axios";
412
632
  /**
413
- * Generates client code for making API requests using Axios.
414
- * @param uri - The API endpoint URI
415
- * @param method - The HTTP method (GET, POST, etc.)
416
- * @param parameters - Array of parameters to include in the request
417
- * @param requestBody - The request body media type definition
418
- * @param response - The response media type definition
419
- * @param adapter - The adapter instance
420
- * @param shouldUseFormData - Flag to use FormData for the request body
421
- * @param shouldUseJSONResponse - Unused by AxiosAdapter; present to align with the abstract signature so positional args bind correctly
422
- * @param isEventStream - Flag indicating a text/event-stream response; when true the raw AxiosResponse is returned without JSON parsing
423
- * @return - An array of generated TypeScript statements
633
+ * Method that should generate and return the client-specific configuration statements.
634
+ *
635
+ * @returns {Statement[]} An array of TypeScript statements that define the client configuration.
424
636
  */
425
- client(uri: string, method: string, parameters: ParameterObject[], requestBody: MediaTypeObject | undefined, response: MediaTypeObject | undefined, adapter: Adapter, shouldUseFormData: boolean, _shouldUseJSONResponse: boolean, isEventStream: boolean): Statement[];
637
+ client(uri: string, method: string, parameters: ParameterObject[], requestBody: MediaTypeObject | undefined, response: MediaTypeObject | undefined, adapter: Adapter, bodyKind: BodyKind, bodyContentType: string | undefined, _shouldUseJSONResponse: boolean, errorMode?: ErrorMode, auth?: AuthArgument, requestControl?: RequestControl): Statement[];
426
638
  }
427
- //#endregion
428
- //#region src/core/client/fetch.d.ts
429
639
  /**
430
640
  * FetchAdapter is an adapter class that generates client-side fetch requests.
431
641
  * It handles parameters, headers, and request bodies to construct proper fetch calls.
@@ -444,15 +654,13 @@ declare class FetchAdapter extends Adapter {
444
654
  * @param requestBody - The request body media type definition
445
655
  * @param response - The response media type definition
446
656
  * @param adapter - The adapter instance
447
- * @param shouldUseFormData - Flag to use FormData for the request body
657
+ * @param bodyKind - How the body should be encoded (json / form-data / urlencoded / binary / none)
658
+ * @param bodyContentType - Content-Type header to inject (undefined means "let runtime decide", e.g. multipart boundary)
448
659
  * @param shouldUseJSONResponse - Flag to use JSON parsing for the response
449
- * @param isEventStream - Flag indicating a text/event-stream response; when true the raw Response is returned unparsed
450
660
  * @return - An array of generated TypeScript statements
451
661
  */
452
- client(uri: string, method: string, parameters: ParameterObject[], requestBody: MediaTypeObject | undefined, response: MediaTypeObject | undefined, adapter: Adapter, shouldUseFormData: boolean, shouldUseJSONResponse: boolean, isEventStream: boolean): Statement[];
662
+ client(uri: string, method: string, parameters: ParameterObject[], requestBody: MediaTypeObject | undefined, response: MediaTypeObject | undefined, adapter: Adapter, bodyKind: BodyKind, bodyContentType: string | undefined, shouldUseJSONResponse: boolean, errorMode?: ErrorMode, auth?: AuthArgument, requestControl?: RequestControl): Statement[];
453
663
  }
454
- //#endregion
455
- //#region src/core/config.d.ts
456
664
  /**
457
665
  * Adaptor type for HTTP client
458
666
  */
@@ -461,6 +669,8 @@ type ConfigAdaptor = keyof typeof Adaptors;
461
669
  * Shared config interface for CLI and Vite plugin
462
670
  */
463
671
  interface ApicodegenConfig {
672
+ /** Display name used in logs and multi-spec configs */
673
+ name?: string;
464
674
  /** OpenAPI spec file path or URL (required) */
465
675
  spec: string;
466
676
  /** Output file path */
@@ -477,8 +687,22 @@ interface ApicodegenConfig {
477
687
  typeCheck?: boolean;
478
688
  /** Watch for file changes */
479
689
  watch?: boolean;
690
+ /** Fail when generated output differs from what is on disk */
691
+ check?: boolean;
480
692
  /** Request options for fetching spec */
481
693
  requestOptions?: FetchDocRequestInit;
694
+ /** Non-2xx handling for generated clients (throw|result; default: as-is) */
695
+ errorMode?: ErrorMode;
696
+ /** Split output into one file per tag (default: single file) */
697
+ splitBy?: SplitBy;
698
+ /** Keep only operations carrying at least one of these tags */
699
+ includeTags?: string[];
700
+ /** Drop operations carrying any of these tags */
701
+ excludeTags?: string[];
702
+ /** Keep only paths starting with one of these prefixes */
703
+ includePaths?: string[];
704
+ /** Drop paths starting with one of these prefixes */
705
+ excludePaths?: string[];
482
706
  }
483
707
  /**
484
708
  * Options for loading config
@@ -503,9 +727,31 @@ interface ResolvedConfig extends ApicodegenConfig {
503
727
  name: string;
504
728
  }
505
729
  /**
506
- * Load and resolve config from multiple sources
730
+ * Merge multiple config sources with priority
731
+ * Priority: defaults < env vars < config file < CLI args
732
+ */
733
+ declare function mergeConfigs(base: ApicodegenConfig, ...sources: (Partial<ApicodegenConfig> | undefined)[]): ApicodegenConfig;
734
+ /**
735
+ * Validate field types before the values reach the generator.
736
+ */
737
+ declare function validateConfigShape(config: Partial<ApicodegenConfig>): void;
738
+ /**
739
+ * Validate config has required fields
740
+ */
741
+ declare function validateConfig(config: Partial<ApicodegenConfig>): config is ApicodegenConfig;
742
+ /**
743
+ * Load and resolve every config entry. A config file may define a single
744
+ * object or a `specs` array for multi-spec projects.
745
+ */
746
+ declare function loadConfigs(options?: LoadConfigOptions): Promise<ResolvedConfig[]>;
747
+ /**
748
+ * Load a single config. Throws when the file defines no entries.
507
749
  */
508
750
  declare function loadConfig(options?: LoadConfigOptions): Promise<ResolvedConfig>;
751
+ /**
752
+ * Create CLI options from config for commander
753
+ */
754
+ declare function configToCLIOptions(config: ApicodegenConfig): Record<string, unknown>;
509
755
  /**
510
756
  * Convert resolved config to provider options format
511
757
  */
@@ -517,9 +763,13 @@ declare function toProviderOptions(config: ResolvedConfig): {
517
763
  importClientSource: string | undefined;
518
764
  verbose: boolean | undefined;
519
765
  requestOptions: FetchDocRequestInit | undefined;
766
+ errorMode: ErrorMode | undefined;
767
+ splitBy: "tag" | undefined;
768
+ includeTags: string[] | undefined;
769
+ excludeTags: string[] | undefined;
770
+ includePaths: string[] | undefined;
771
+ excludePaths: string[] | undefined;
520
772
  };
521
- //#endregion
522
- //#region src/core/errors.d.ts
523
773
  /**
524
774
  * Error handling utilities for api-codegen
525
775
  */
@@ -580,16 +830,16 @@ declare class ApicodegenError extends Error {
580
830
  * ANSI color codes for terminal output
581
831
  */
582
832
  declare const Colors: {
583
- readonly reset: "\u001B[0m";
584
- readonly bold: "\u001B[1m";
585
- readonly red: "\u001B[31m";
586
- readonly green: "\u001B[32m";
587
- readonly yellow: "\u001B[33m";
588
- readonly blue: "\u001B[34m";
589
- readonly cyan: "\u001B[36m";
590
- readonly gray: "\u001B[90m";
591
- readonly brightRed: "\u001B[91m";
592
- readonly brightGreen: "\u001B[92m";
833
+ readonly reset: "";
834
+ readonly bold: "";
835
+ readonly red: "";
836
+ readonly green: "";
837
+ readonly yellow: "";
838
+ readonly blue: "";
839
+ readonly cyan: "";
840
+ readonly gray: "";
841
+ readonly brightRed: "";
842
+ readonly brightGreen: "";
593
843
  };
594
844
  /**
595
845
  * Format error for CLI output
@@ -610,6 +860,7 @@ declare const createErrors: {
610
860
  configInvalid(path: string, cause?: Error): ApicodegenError;
611
861
  validationFailed(path: string, details: string, cause?: Error): ApicodegenError;
612
862
  generationFailed(cause?: Error): ApicodegenError;
863
+ writeFailed(path: string, cause?: Error): ApicodegenError;
613
864
  typeCheckFailed(path: string, _errors: string[], cause?: Error): ApicodegenError;
614
865
  missingRequiredField(field: string, context?: string): ApicodegenError;
615
866
  };
@@ -621,8 +872,6 @@ declare function wrapError(error: unknown, context?: Partial<ApicodegenErrorCont
621
872
  * Check if error is an ApicodegenError
622
873
  */
623
874
  declare function isApicodegenError(error: unknown): error is ApicodegenError;
624
- //#endregion
625
- //#region src/core/generator/index.d.ts
626
875
  /**
627
876
  * Represents a comment object with optional tag and message.
628
877
  */
@@ -655,7 +904,16 @@ declare class Generator {
655
904
  * @param basePath - Optional base path to prepend (default: "").
656
905
  * @returns A TypeScript template expressi
657
906
  */
658
- static toUrlTemplate(path: string, parameters: ParameterObject[], basePath?: string): import("typescript").NoSubstitutionTemplateLiteral | import("typescript").TemplateExpression;
907
+ static toUrlTemplate(path: string, parameters: ParameterObject[], basePath?: string, auth?: AuthArgument): Expression;
908
+ /**
909
+ * Builds the path part of a URL, encoding every `{param}` interpolation.
910
+ */
911
+ private static toPathTemplate;
912
+ /**
913
+ * Emits an IIFE that builds a query string, omitting undefined/null
914
+ * values and honouring array `explode` / delimiter styles.
915
+ */
916
+ private static toQueryStringExpression;
659
917
  /**
660
918
  * Adds synthetic comments to a TypeScript AST node.
661
919
  *
@@ -670,42 +928,70 @@ declare class Generator {
670
928
  * @returns true if the schema is a binary type, false otherwise.
671
929
  */
672
930
  static isBinarySchema(schema: SchemaObject): boolean;
931
+ /** Whether a schema is a primitive text part (not binary, ref, or object). */
932
+ static isTextSchema(schema: SchemaObject): boolean;
673
933
  static schemaToTypeString(schema: SchemaObject): string;
674
934
  static generateParamTags(parameters: ParameterObject[], requestBody?: MediaTypeObject): CommentObject[];
675
935
  static toRequestBodyTypeNode(schema: SchemaObject): ParameterDeclaration;
936
+ /**
937
+ * Narrows a `oneOf` member with its discriminator mapping value:
938
+ * `Cat & { petType: 'cat' }`.
939
+ */
940
+ private static discriminatedMember;
676
941
  static toTypeNode(schema: SchemaObject): TypeNode;
942
+ private static toLiteralTypeNode;
943
+ private static primitiveTypeNode;
944
+ private static toTypeNodeInner;
945
+ static toResponsesTypeNode(responses: ResponsesObject): TypeNode;
946
+ static deduplicateTypes(types: TypeNode[]): TypeNode[];
947
+ static getTypeNodeKey(type: TypeNode): string;
677
948
  static toDeclarationNodes(parameters: ParameterObject[]): ParameterDeclaration[];
949
+ /** Property keys listed in a parent schema's `required` array. */
950
+ private static requiredPropertyKeys;
678
951
  static toFormDataStatement(parameters: ParameterObject[], requestBody?: SchemaObject): Statement[];
679
- static bodyBlock(uri: string, method: string, parameters: ParameterObject[], requestBody: MediaTypeObject | undefined, response: MediaTypeObject | undefined, adapter: Adapter): Block;
952
+ /**
953
+ * Build statements that construct a `URLSearchParams` from request body
954
+ * fields for an `application/x-www-form-urlencoded` request.
955
+ *
956
+ * Skips `undefined` / `null` values so optional fields don't end up as
957
+ * the literal string `"undefined"` in the URL (fixes #8).
958
+ *
959
+ * The resulting `sp` variable is referenced by the adapter as the
960
+ * `body` payload.
961
+ */
962
+ static toURLSearchParamsStatement(parameters: ParameterObject[], requestBody?: SchemaObject): Statement[];
963
+ /**
964
+ * Render `expr` as a string suitable for `FormData.append` /
965
+ * `URLSearchParams.append`. Object/array schemas are JSON-stringified,
966
+ * everything else is coerced via `String(...)`.
967
+ */
968
+ private static toFormDataCompatibleString;
969
+ static bodyBlock(uri: string, method: string, parameters: ParameterObject[], requestBody: MediaTypeObject | undefined, response: MediaTypeObject | undefined, adapter: Adapter, errorMode?: ErrorMode, auth?: AuthArgument, requestControl?: RequestControl): Block;
970
+ /**
971
+ * Resolves effective security requirements into concrete injections.
972
+ * Requirements are OR-ed by the spec; we inject every credential the
973
+ * caller provides, so either branch of an OR works.
974
+ */
975
+ static toAuthInjections(security: SecurityRequirementObject[] | undefined, schemes: Record<string, SecuritySchemeObject>): AuthInjection[];
976
+ /** `{ [scheme: string]: string | { username: string; password: string } }` */
977
+ private static authOptionsTypeNode;
978
+ /** `{ signal?: AbortSignal; headers?: Record<string, string>; timeout?: number }` */
979
+ private static requestOptionsTypeNode;
680
980
  static schemaToStatemets(parsedDoc: ProviderInitResult, adaptor: Adapter, options: Omit<ProviderInitOptions, 'docURL' | 'output' | 'requestOptions'>): Statement[];
681
981
  static prettier(code: string): Promise<string>;
982
+ /**
983
+ * Splits generated code into `types.ts`, one file per tag, and `index.ts`.
984
+ * Shared type declarations live in `types.ts`; tag files import them and
985
+ * export only their functions.
986
+ */
987
+ static genCodeMulti(schema: ProviderInitResult, initOptions: ProviderInitOptions, adaptor: Adapter): Promise<{
988
+ code: string;
989
+ files: Record<string, string>;
990
+ }>;
991
+ /** Lower-case file stem that cannot collide with reserved or earlier names. */
992
+ private static uniqueFileName;
682
993
  static genCode(schema: ProviderInitResult, initOptions: ProviderInitOptions, adaptor: Adapter): Promise<string>;
683
994
  }
684
- //#endregion
685
- //#region src/core/logger.d.ts
686
- declare const logger: {
687
- success(msg: string): void;
688
- error(err: unknown, verbose?: boolean): void;
689
- info(msg: string): void;
690
- warn(msg: string): void;
691
- loading(msg: string): void;
692
- watching(msg: string): void;
693
- fileChange(filePath: string): void;
694
- fileAdd(filePath: string): void;
695
- shutdown(): void;
696
- divider(width?: number): void;
697
- heading(text: string, mode: string, width?: number): void;
698
- item(label: string, color?: "green" | "red" | "yellow"): void;
699
- summary(stats: {
700
- succeeded: number;
701
- failed: number;
702
- endpoints: number;
703
- schemas: number;
704
- duration: number;
705
- }): void;
706
- };
707
- //#endregion
708
- //#region src/openapi/index.d.ts
709
995
  declare enum OpenAPIVersion {
710
996
  v2 = "v2",
711
997
  v3 = "v3",
@@ -717,6 +1003,8 @@ declare class OpenAPIProvider extends Provider {
717
1003
  }
718
1004
  interface CodeGenResult {
719
1005
  code: string;
1006
+ /** Additional files when `splitBy` is enabled (name → content). */
1007
+ files?: Record<string, string>;
720
1008
  stats: {
721
1009
  endpoints: number;
722
1010
  schemas: number;
@@ -724,17 +1012,46 @@ interface CodeGenResult {
724
1012
  };
725
1013
  }
726
1014
  declare function codeGen(initOptions: ProviderInitOptions): Promise<CodeGenResult>;
727
- //#endregion
728
- //#region src/vite-plugin/index.d.ts
729
1015
  type ApiCodeGenPluginOptions = {
730
- /** Human-readable name for this API config (required) */name: string; /** OpenAPI spec file path or URL */
731
- spec?: string; /** Output file path */
732
- output?: string; /** HTTP client adaptor */
733
- adaptor?: 'fetch' | 'axios'; /** Base URL for API endpoints */
734
- baseURL?: string; /** Custom client import source path */
735
- importClientSource?: string; /** Enable verbose logging */
736
- verbose?: boolean; /** Run type check after generation (default: true) */
1016
+ /** Human-readable name for this API config (required) */
1017
+ name: string;
1018
+ /** OpenAPI spec file path or URL */
1019
+ spec?: string;
1020
+ /** Output file path */
1021
+ output?: string;
1022
+ /** HTTP client adaptor */
1023
+ adaptor?: 'fetch' | 'axios';
1024
+ /** Non-2xx handling in generated clients (throw|result; default: as-is) */
1025
+ errorMode?: 'throw' | 'result';
1026
+ /** Split output into one file per tag (default: single file) */
1027
+ splitBy?: 'tag';
1028
+ /** Keep only operations carrying at least one of these tags */
1029
+ includeTags?: string[];
1030
+ /** Drop operations carrying any of these tags */
1031
+ excludeTags?: string[];
1032
+ /** Keep only paths starting with one of these prefixes */
1033
+ includePaths?: string[];
1034
+ /** Drop paths starting with one of these prefixes */
1035
+ excludePaths?: string[];
1036
+ /** Base URL for API endpoints */
1037
+ baseURL?: string;
1038
+ /** Custom client import source path */
1039
+ importClientSource?: string;
1040
+ /** Enable verbose logging */
1041
+ verbose?: boolean;
1042
+ /** Run type check after generation (default: true) */
737
1043
  typeCheck?: boolean;
1044
+ /**
1045
+ * Enable on-disk caching of generated code (default: true).
1046
+ * Subsequent vite invocations skip codegen when neither the spec file
1047
+ * nor the options have changed. Disable to force a fresh generation.
1048
+ */
1049
+ cache?: boolean;
1050
+ /**
1051
+ * Directory to store cache entries (default: `node_modules/.cache/apicodegen`).
1052
+ * Ignored when `cache === false`.
1053
+ */
1054
+ cacheDir?: string;
738
1055
  };
739
1056
  /**
740
1057
  * Main Vite plugin function
@@ -759,6 +1076,5 @@ type ApiCodeGenPluginOptions = {
759
1076
  * ```
760
1077
  */
761
1078
  declare function apiCodeGenPlugin(options: ApiCodeGenPluginOptions[]): PluginOption;
762
- //#endregion
763
- export { Adapter, Adaptors, ApiCodeGenPluginOptions, ApicodegenConfig, ApicodegenError, ApicodegenErrorContext, ArraySchemaType, ArrayTypeSchemaObject, AxiosAdapter, Base, CodeGenResult, Colors, CommentObject, Comments, ConfigAdaptor, EnumSchemaObject, ErrorCode, ErrorCodes, FetchAdapter, FetchDocRequestInit, Generator, HttpMethods, JSONValue, LoadConfigOptions, MediaTypeObject, MediaTypes, NonArraySchemaType, OpenAPIProvider, OpenAPIVersion, OperationObject, ParameterIn, ParameterObject, PathObject, PathsObject, Provider, ProviderInitOptions, ProviderInitResult, ReferenceObject, RequestBodyObject, ResolvedConfig, ResponsesObject, SchemaFormatType, SchemaObject, SchemaType, SingleTypeSchemaObject, SuccessHttpStatusCode, apiCodeGenPlugin, codeGen, createErrors, formatError, isApicodegenError, loadConfig, logger, printError, toProviderOptions, wrapError };
1079
+ export { Adapter, Adaptors, ApiCodeGenPluginOptions, ApicodegenConfig, ApicodegenError, ApicodegenErrorContext, ArraySchemaType, ArrayTypeSchemaObject, AuthArgument, AuthInjection, AxiosAdapter, Base, BodyKind, CodeGenResult, Colors, CommentObject, Comments, ConfigAdaptor, DiscriminatorObject, EnumSchemaObject, ErrorCode, ErrorCodes, ErrorMode, FetchAdapter, FetchDocRequestInit, Generator, HttpMethods, JSONValue, LoadConfigOptions, MediaTypeObject, MediaTypes, NonArraySchemaType, OpenAPIProvider, OpenAPIVersion, OperationObject, ParameterIn, ParameterObject, PathObject, PathsObject, Provider, ProviderInitOptions, ProviderInitResult, ReferenceObject, RequestBodyObject, RequestControl, ResolvedConfig, ResponsesObject, SchemaFormatType, SchemaObject, SchemaType, SecurityRequirementObject, SecuritySchemeObject, SingleTypeSchemaObject, SplitBy, SuccessHttpStatusCode, apiCodeGenPlugin, authAccess, authHeaderEntries, codeGen, configToCLIOptions, cookieHeaderExpression, createErrors, fetchSignalExpression, formatError, isApicodegenError, loadConfig, loadConfigs, mergeConfigs, optionalAccess, printError, toProviderOptions, validateConfig, validateConfigShape, withRequestHeaders, wrapError };
764
1080
  //# sourceMappingURL=index.d.mts.map