### Install and Generate API using CLI Source: https://github.com/acacode/swagger-typescript-api/blob/main/README.md Install swagger-typescript-api as a dev dependency and then use npx to generate the API client from a local swagger.json file. ```bash npm install --save-dev swagger-typescript-api npx swagger-typescript-api generate --path ./swagger.json ``` -------------------------------- ### Install Dependencies Source: https://github.com/acacode/swagger-typescript-api/blob/main/CLAUDE.md Installs project dependencies using bun. Ensures the lockfile is frozen for reproducible builds. ```bash bun install --frozen-lockfile ``` -------------------------------- ### Install CLI Globally Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Installs the swagger-typescript-api CLI globally on your system for command-line access. ```bash npm install -g swagger-typescript-api ``` -------------------------------- ### JavaScript Configuration File Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Use a JavaScript file for configuration. This example sets input, output, and HTTP client type. ```javascript // swagger-typescript-api.config.js export default { input: "./swagger.json", output: "./generated", httpClientType: "fetch", generateResponses: true, extractRequestBody: true, extractResponseBody: true, }; ``` -------------------------------- ### Initialize and Use SwaggerSchemaResolver Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/swagger-schema-resolver.md Example of initializing the SwaggerSchemaResolver with configuration and a file system, creating the resolved schema, and accessing its properties. ```typescript import { SwaggerSchemaResolver } from "swagger-typescript-api"; import { CodeGenConfig } from "./configuration.js"; import { FileSystem } from "./util/file-system.js"; const config = new CodeGenConfig({ input: "./openapi.json" }); const fileSystem = new FileSystem(); const resolver = new SwaggerSchemaResolver(config, fileSystem); const resolved = await resolver.create(); console.log(resolved.usageSchema.info.title); console.log(resolved.usageSchema.openapi); // Access resolved references const userSchema = resolved.getRef("#/components/schemas/User"); console.log(userSchema.type); // "object" ``` -------------------------------- ### Generate Starter Templates Command Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/generate-templates.md Use the `generate-templates` command to create starter templates in a specified output directory. This example uses `fetch` as the http-client-type. ```bash npx swagger-typescript-api generate-templates \ --output ./templates \ --http-client-type fetch ``` -------------------------------- ### Configuration Priority Example Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/swagger-schema-resolver.md Demonstrates the priority order for configuration sources. The 'spec' object takes precedence over 'input' file path and 'url'. ```typescript const config = { spec: myObject, // Used (highest priority) input: "./swagger.json", // Ignored url: "https://..." // Ignored }; ``` -------------------------------- ### CodeFormatter Usage Examples Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/code-formatter.md Demonstrates how to instantiate and use the CodeFormatter for different formatting tasks. Import the class and initialize it with a configuration object. ```typescript import { CodeFormatter } from "swagger-typescript-api"; const formatter = new CodeFormatter(config); // Option 1: Format completely const result = await formatter.formatCode(generatedCode); // Option 2: Only remove imports const cleaned = formatter.removeUnusedImports(generatedCode); // Option 3: Only format const formatted = await formatter.format(generatedCode); ``` -------------------------------- ### Install CLI as Project Dependency Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Installs the swagger-typescript-api CLI as a development dependency within your project. ```bash npm install --save-dev swagger-typescript-api ``` -------------------------------- ### start() Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/code-gen-process.md Executes the entire code generation pipeline. This method handles loading templates, resolving the schema, parsing routes, rendering templates, formatting code, and writing the output. It returns generated files and metadata. ```APIDOC ## start() ### Description Executes the entire code generation pipeline and returns generated files and metadata. ### Method ```typescript async start(): Promise ``` ### Process Flow 1. Load Templates 2. Load Templates to Memory 3. Resolve Swagger Schema 4. Initialize Hooks 5. Register Components 6. Parse Routes 7. Sort Data 8. Prepare Config 9. Render Templates 10. Format Code 11. Translate to JS 12. Write Output ### Returns ```typescript GenerateApiOutput { configuration: GenerateApiConfiguration; files: Array<{ fileName: string; fileExtension: string; fileContent: string; }>; createFile: (params: {...}) => void; renderTemplate: (templateContent: string, data: {...}) => string; getTemplate: (params: {...}) => string; formatTSContent: (content: string) => Promise; } ``` ### Throws - `Error` if schema is invalid or cannot be parsed - `Error` if input file/URL cannot be accessed - `Error` if output directory cannot be created ``` -------------------------------- ### Loop Template Example Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/templates-worker.md Shows how to iterate over model types in an EJS template to generate interface definitions for each type. ```ejs <% it.modelTypes.forEach(type => { %> export interface <%= type.name %> { <%= type.content %> } <% }) %> ``` -------------------------------- ### Simple Template Example Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/templates-worker.md Demonstrates basic variable interpolation in an EJS template to extract API version and title from configuration. ```ejs export const apiVersion = "<%= it.config.version %>"; export const apiTitle = "<%= it.config.apiConfig.title %>"; ``` -------------------------------- ### Generate API Client (Library Usage) Source: https://github.com/acacode/swagger-typescript-api/blob/main/CLAUDE.md Example of how to use the generateApi function from the library to generate an API client. This is the programmatic way to use the tool. ```typescript import { generateApi } from 'swagger-typescript-api'; generateApi({ name: 'MyApiClient', spec: './my-api.yaml', output: './src/api', // ... other options }); ``` -------------------------------- ### TemplatesWorker Initialization and Usage Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/templates-worker.md Demonstrates how to initialize the TemplatesWorker and use its methods to get template paths, load individual or all templates, and render a template with provided data. ```typescript import { TemplatesWorker } from "swagger-typescript-api"; const worker = new TemplatesWorker(config, fileSystem, getRenderData); // Get template paths const paths = worker.getTemplatePaths(config); console.log(paths.custom); // Load single template const apiTemplate = worker.getTemplate("api", "api.ejs"); // Load all templates const templates = worker.getTemplates(config); console.log(Object.keys(templates)); // Render template const rendered = await worker.renderTemplate( "Version: <%= it.version %>", { version: "1.0.0" } ); console.log(rendered); ``` -------------------------------- ### onInit Hook Example Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md The onInit hook runs after schema loading and before processing. It can initialize state, validate configuration, or set up custom logic. It can also modify the config object before generation begins. ```typescript onInit: (config, codeGenProcess) => { console.log("Starting code generation..."); console.log(`Schema title: ${config.apiConfig.title}`); console.log(`Found ${config.componentsMap.length} components`); // Can modify config before generation config.typePrefix = "API_"; // Can access internal instances console.log(codeGenProcess.schemaComponentsMap.getComponents()?.length); return config; // Return modified config or undefined }; ``` -------------------------------- ### Execute Code Generation Pipeline Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/code-gen-process.md Use the `start()` method to execute the entire code generation pipeline. It returns generated files and metadata. The process involves loading templates, resolving schemas, initializing hooks, parsing routes, rendering templates, formatting code, and writing output. ```typescript async start(): Promise ``` -------------------------------- ### Template Inclusion Example Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/templates-worker.md Demonstrates how to include other templates within an EJS template, passing data to the included partials. This example includes a JSDoc partial and procedure call partials for each route. ```ejs <%~ include('@base/jsdoc', {description: it.config.apiConfig.description}) %> export class <%= it.utils.pascalCase(it.config.apiClassName) %> { <% it.routes.forEach(route => { %> <%~ include('./procedure-call', {route}) %> <% }) %> } ``` -------------------------------- ### Check Formatting Source: https://github.com/acacode/swagger-typescript-api/blob/main/CLAUDE.md Checks the code formatting without making changes. Reports files that do not adhere to the style guide. ```bash bun run format:check ``` -------------------------------- ### JSON Configuration File Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md A JSON configuration file can be used for simpler setups, specifying input, output, and other generation options. ```json { "input": "./swagger.json", "output": "./generated", "httpClientType": "fetch", "generateResponses": true, "extractRequestBody": true, "extractResponseBody": true, "enumStyle": "union" } ``` -------------------------------- ### Generate Modular Templates with Axios Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/generate-templates.md This example demonstrates generating modular API templates, where each route is in its own file, using the `axios` HTTP client. The output is directed to a specified directory. ```typescript import { generateTemplates } from "swagger-typescript-api"; const output = await generateTemplates({ output: "./modular-templates", modular: true, httpClientType: "axios", }); ``` -------------------------------- ### Generate API using CLI Source: https://github.com/acacode/swagger-typescript-api/blob/main/README.md Use the npx command to generate an API client from a local swagger.json file via the CLI. Ensure the package is installed globally or locally. ```bash npx swagger-typescript-api generate --path ./swagger.json ``` -------------------------------- ### Type Extraction Examples Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/configuration.md Illustrates the difference in generated types when type extraction options are enabled versus disabled. ```typescript // With extracting enabled: export type CreateUserRequest = { ... }; export type CreateUserResponse = { ... }; export type CreateUserError = { ... }; // Without extracting: // Types defined inline within method signatures ``` -------------------------------- ### TypeScript Configuration File Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/configuration.md Configure the generator using a TypeScript file, leveraging type safety and custom hooks. This example shows how to format type names with a prefix. ```typescript import type { GenerateApiConfiguration } from "swagger-typescript-api"; export default { input: "./swagger.json", output: "./generated", httpClientType: "fetch", hooks: { onFormatTypeName: (name: string) => { return `API${name}`; } } } satisfies Partial; ``` -------------------------------- ### onPrepareConfig Hook Example Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md The onPrepareConfig hook is executed before template rendering, after all parsing is complete. It allows for final configuration adjustments, such as filtering routes or customizing model types. ```typescript onPrepareConfig: (config) => { console.log("Preparing configuration for rendering..."); // Adjust routes if (config.routes.outOfModule) { config.routes.outOfModule = config.routes.outOfModule.filter( r => !r.raw.tags?.includes("deprecated") ); } // Customize model types config.modelTypes.forEach(type => { type.description = type.description?.toUpperCase(); }); return config; }; ``` -------------------------------- ### TypeScript Code Formatting Example Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/code-formatter.md Demonstrates the transformation of code style and import organization according to defined rules. Input code shows inconsistent spacing and import order, while output code is standardized. ```typescript // Input const users:User[]=getSomeUsers() ;import {x,y} from"./types.js"; // Output import { x, y } from "./types.js"; const users: User[] = getSomeUsers(); ``` -------------------------------- ### Generate API using Library Source: https://github.com/acacode/swagger-typescript-api/blob/main/README.md Import and use the generateApi function from the swagger-typescript-api library to programmatically generate an API client. Requires installation as a dev dependency. ```typescript import * as path from "node:path"; import * as process from "node:process"; import { generateApi } from "swagger-typescript-api"; await generateApi({ input: path.resolve(process.cwd(), "./swagger.json") }); ``` -------------------------------- ### onInit Hook Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md Called after the schema is loaded and before any processing begins. Use this hook to initialize state, validate configuration, or set up custom logic. It can also modify the configuration object before generation starts. ```APIDOC ## onInit(config, codeGenProcess): config | undefined ### Description Initializes state, validates configuration, and sets up custom logic after the schema is loaded but before any processing begins. It can also modify the configuration object before generation starts. ### Parameters #### Parameters - **config** (`GenerateApiConfiguration["config"]`) - Configuration object with loaded schema. - **codeGenProcess** (`CodeGenProcess`) - Access to internal generators and resolvers. ### Returns Modified config or undefined (undefined means no change). ### Request Example ```typescript onInit: (config, codeGenProcess) => { console.log("Starting code generation..."); console.log(`Schema title: ${config.apiConfig.title}`); console.log(`Found ${config.componentsMap.length} components`); // Can modify config before generation config.typePrefix = "API_"; // Can access internal instances console.log(codeGenProcess.schemaComponentsMap.getComponents()?.length); return config; // Return modified config or undefined } ``` ``` -------------------------------- ### Generate API Client with Custom Hooks Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/README.md Generates an API client with custom logic applied via hooks. This example shows how to format type names and conditionally skip routes. ```typescript const result = await generateApi({ input: "./swagger.json", output: "./generated", hooks: { onFormatTypeName: (name) => { return name.replace(/Request$/, "Req"); }, onCreateRoute: (route) => { if (route.raw.deprecated) return false; // Skip return route; }, }, }); ``` -------------------------------- ### Custom Templates Directory Structure Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/templates-worker.md Provides an example directory structure for organizing custom EJS templates, including overrides for built-in templates and new custom templates. ```tree my-templates/ ├── api.ejs # Override main API class ├── data-contracts.ejs # Override type definitions ├── http-client.ejs # Override HTTP client ├── my-custom.ejs # New custom template └── partial/ └── header.ejs ``` -------------------------------- ### Output Configuration: Modular Generation Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/configuration.md Set 'modular' to 'true' to generate separate files per route module, or 'false' for a single combined API file. The example illustrates the directory structure for both options. ```javascript // Single file output (modular: false) Api.ts ├── export class Api { ... } ├── export type User = { ... } └── export enum Status { ... } // Modular output (modular: true) api/ ├── index.ts ├── data-contracts.ts ├── http-client.ts ├── Users.ts └── Posts.ts ``` -------------------------------- ### getType Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/schema-components-map.md Gets the parsed type data for a schema component identified by its JSON Pointer reference. ```APIDOC ## getType(ref: string): SchemaComponent["typeData"] | null ### Description Gets the parsed type data for a schema component. ### Parameters #### Path Parameters - **ref** (string) - Required - JSON Pointer reference ### Returns `SchemaComponent["typeData"] | null` - Parsed type information or null ``` -------------------------------- ### Reference Normalization Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/resolved-swagger-schema.md Examples illustrating how the ResolvedSwaggerSchema normalizes various input reference formats to a consistent output. ```APIDOC ## Reference Normalization Examples | Input | Output | Notes | |-------|--------|-------| | `#components/schemas/User` | `#/components/schemas/User` | Adds leading `/` | | `./file.yaml/#/components/...` | `./file.yaml#/components/...` | Removes `/#` | | `#/definitions/User` | `#/components/schemas/User` | Swagger 2.0 → OpenAPI 3.0 | | `./path~1to~1file.yaml#...` | Handled correctly | Decodes URI-encoded paths | ``` -------------------------------- ### Initialize and Use SchemaComponentsMap Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/schema-components-map.md Demonstrates how to initialize the SchemaComponentsMap with configuration, register a component, and retrieve components by type name. Requires importing SchemaComponentsMap and CodeGenConfig. ```typescript import { SchemaComponentsMap } from "swagger-typescript-api"; import { CodeGenConfig } from "./configuration.js"; const config = new CodeGenConfig({ input: "./swagger.json" }); const map = new SchemaComponentsMap(config); // Register a component map.put("#/components/schemas/User", { $ref: "#/components/schemas/User", typeName: "User", componentName: "schemas", }); // Retrieve all components const components = map.getComponents(); const sorted = map.sortComponents(components || []); // Find by name const user = map.getByTypeName("User"); console.log(user?.typeName); ``` -------------------------------- ### Generate Starter Templates Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/README.md Generates starter templates for an API client using the 'fetch' HTTP client. Specify the output directory for the templates. ```typescript import { generateTemplates } from "swagger-typescript-api"; const output = await generateTemplates({ output: "./templates", httpClientType: "fetch", }); ``` -------------------------------- ### CLI Generation in Debug Mode Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Enable debug mode during API generation to get more verbose output for troubleshooting. ```bash sta generate \ --path ./swagger.json \ --output ./generated \ --debug ``` -------------------------------- ### Display CLI Help Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Access help information for the main CLI command or specific subcommands like 'generate'. ```bash sta --help ``` ```bash sta generate --help ``` -------------------------------- ### Conditional Template Example Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/templates-worker.md Illustrates conditional rendering in EJS. This snippet generates response types only if 'generateResponses' is true in the configuration. ```ejs <% if (it.config.generateResponses) { %> export type ResponseTypes = { <% it.routes.forEach(route => { %> <%= route.routeName.usage %>: <%= route.response.type %>; <% }) %> }; <% } %> ``` -------------------------------- ### Basic Configuration Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/configuration.md Use this basic configuration for simple API generation. Specify the input Swagger file and the output directory. ```javascript export default { input: "./swagger.json", output: "./generated", httpClientType: "fetch" }; ``` -------------------------------- ### CLI Generation with Custom Templates Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Generate API client using custom templates by specifying the path to the template directory. ```bash sta generate \ --path ./swagger.json \ --output ./generated \ --templates ./my-templates ``` -------------------------------- ### Filter Routes by Schema Type Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/constants.md Use the `onParseSchema` hook to filter or process schemas during generation. This example logs enum schemas. ```typescript import { generateApi, SCHEMA_TYPES } from "swagger-typescript-api"; const result = await generateApi({ input: "./swagger.json", hooks: { onParseSchema: (original, parsed) => { if (parsed.schemaType === SCHEMA_TYPES.ENUM) { console.log(`Enum found: ${parsed.name}`); } return parsed; }, }, }); ``` -------------------------------- ### Initialize SwaggerSchemaResolver Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/swagger-schema-resolver.md Instantiate the SwaggerSchemaResolver with configuration and a file system implementation. ```typescript constructor(config: CodeGenConfig, fileSystem: FileSystem) ``` -------------------------------- ### Configuration File Names Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/configuration.md Supported configuration file names, listed in order of precedence. ```bash # Supported file names (in order of precedence) swagger-typescript-api.config.ts swagger-typescript-api.config.js swagger-typescript-api.config.json swagger-typescript-api.config.mjs swagger-typescript-api.config.cjs ``` -------------------------------- ### get Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/schema-components-map.md Retrieves raw schema data by a given JSON Pointer reference. It can follow `$ref` pointers to resolve nested references. ```APIDOC ## get(ref: string): T | null ### Description Retrieves raw schema data by reference, following `$ref` pointers. ### Parameters #### Path Parameters - **ref** (string) - Required - JSON Pointer reference to retrieve ### Returns `T | null` - The referenced schema object or null if not found. **Note:** This method resolves the full OpenAPI schema object, not the `SchemaComponent` wrapper. ``` -------------------------------- ### Basic CLI Generation Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Generate API client using basic CLI flags for input path and output directory. ```bash sta generate --path ./swagger.json --output ./api ``` -------------------------------- ### CodeFormatter Constructor Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/code-formatter.md Initializes the formatter with configuration context, including formatting settings. ```APIDOC ## Constructor ```typescript constructor(config: CodeGenConfig) ``` ### Description Initializes the formatter with configuration context. ### Parameters #### Path Parameters - **config** (`CodeGenConfig`) - Required - Configuration with formatting settings ``` -------------------------------- ### Instantiate and Parse Schema Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/schema-parser.md Instantiate SchemaParser with a fabric, type name, and schema object, then call parse() to get structured type information. ```typescript const parser = new SchemaParser(fabric, { typeName: "User", schema: { type: "object", properties: { id: { type: "integer" }, name: { type: "string" }, }, required: ["id"], }, }); const parsed = parser.parse(); ``` -------------------------------- ### Detect Schema Format (JSON/YAML) Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/swagger-schema-resolver.md Automatically detect whether the schema content is in JSON or YAML format based on its starting characters or keywords. ```typescript // YAML detection if (content.includes("swagger:") || content.includes("openapi:")) { // Parse as YAML } // JSON detection if (content.startsWith("{")) { // Parse as JSON } ``` -------------------------------- ### onInsertPathParam Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md This hook customizes the insertion of individual path parameters. It allows for altering the parameter name as it's being added to the route, for example, by adding a prefix. ```APIDOC ## onInsertPathParam(paramName, index, arr, route): string | undefined ### Description Customize individual path parameter name insertion. ### Parameters #### Path Parameters - **paramName** (string) - Required - Parameter name from path - **index** (number) - Required - Parameter index in path - **arr** (BuildRouteParam[]) - Required - All path parameters - **route** (string) - Required - Current interpolated route ### Returns Custom parameter name or undefined ### Example ```typescript onInsertPathParam: (paramName, index, arr, route) => { // Prefix all params return `param${index}_${paramName}`; }; ``` ``` -------------------------------- ### CLI Command Aliases Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Demonstrates the two equivalent command aliases for invoking the CLI's generate command. ```bash sta generate --path ./swagger.json ``` ```bash swagger-typescript-api generate --path ./swagger.json ``` -------------------------------- ### Generate Custom Templates Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Use this command to generate custom template files. Specify the output directory and the desired HTTP client type. ```bash sta generate-templates --output ./templates --http-client-type fetch ``` -------------------------------- ### Output Configuration: Directory Path Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/configuration.md Set the 'output' option to a directory path to specify where generated files should be written. Set to 'false' to skip disk writing and receive content in-memory. ```javascript { output: "./generated" // or output: false } ``` -------------------------------- ### Get Non-Referenced Component Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/schema-components-map.md Retrieves a schema component directly by its reference, without resolving any `$ref` pointers. Use this when you need the immediate component definition. ```typescript const component = schemaComponentsMap.getNonRefComponent("#/components/schemas/User"); // Returns the direct component, even if it references another component ``` -------------------------------- ### Inline Object Input Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/swagger-schema-resolver.md Provides an example of using an inline object as the schema source. This method avoids file I/O and is useful for testing or dynamic generation. ```typescript { spec: { openapi: "3.0.0", info: { title: "My API", version: "1.0.0" }, paths: { ... } } } ``` -------------------------------- ### Package.json Bin Configuration Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Shows the package.json configuration that defines the 'sta' and 'swagger-typescript-api' command aliases. ```json { "bin": { "sta": "./dist/cli.mjs", "swagger-typescript-api": "./dist/cli.mjs" } } ``` -------------------------------- ### Get Reference Details Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/resolved-swagger-schema.md Use `getRefDetails` to obtain metadata about a JSON Pointer reference, such as whether it's local or external, and its associated file path or name. ```typescript const details = resolved.getRefDetails("./external.yaml#/components/schemas/Item"); // Returns: { // ref: "external.yaml#/components/schemas/Item", // isLocal: false, // externalUrlOrPath: "./external.yaml", // externalOpenapiFileName: "external" // } ``` -------------------------------- ### Generate API with Environment Variables Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Configure API generation using environment variables for input, output, and HTTP client type before running the generate command. ```bash INPUT=./swagger.json \ OUTPUT=./generated \ HTTP_CLIENT_TYPE=axios \ sta generate ``` -------------------------------- ### generateTemplates Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/generate-templates.md Generates starter template files for custom template development. It copies the built-in ETA templates (base, default/modular) to a specified output directory, allowing developers to customize code generation templates without modifying the library itself. ```APIDOC ## generateTemplates ### Description Generates starter template files for custom template development. It copies the built-in ETA templates (base, default/modular) to a specified output directory, allowing developers to customize code generation templates without modifying the library itself. ### Function Signature ```typescript export async function generateTemplates( params: GenerateTemplatesParams ): Promise ``` ### Parameters #### params (`GenerateTemplatesParams`) - Required Configuration for template generation - **output** (`string`) - Optional - Directory path where templates will be written. Default: `"./templates"` - **httpClientType** (`HttpClientType`) - Optional - HTTP client type to generate templates for (`"fetch"` or `"axios"`). Default: `"fetch"` - **modular** (`boolean`) - Optional - Include modular template variants (separate files per route module). Default: `false` - **cleanOutput** (`boolean`) - Optional - Delete output directory before generating. Default: `false` - **rewrite** (`boolean`) - Optional - Overwrite existing template files. Default: `false` - **silent** (`boolean`) - Optional - Suppress console output. Default: `false` - **debug** (`boolean`) - Optional - Enable debug-level logging. Default: `false` ### Return Type `GenerateTemplatesOutput` #### Output Properties - **files** (Array of `FileInfo`) - Array of generated template files with `fileName`, `fileExtension`, and `fileContent` - **createFile** (Function) - Function to manually write additional files. It accepts a `params` object with `path`, `fileName`, `content`, and `withPrefix` properties. ``` -------------------------------- ### Intercept Schema Parsing Before It Starts Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md The `onPreParseSchema` hook allows for early interception of schema parsing for inspection or validation. It is called before any schema is processed and does not return a value. ```typescript onPreParseSchema: (schema, typeName, schemaType) => { if (schemaType === "enum" && !schema.enum) { console.warn(`Enum ${typeName} missing values`); } if (schemaType === "object" && !schema.properties) { console.warn(`Object ${typeName} missing properties`); } // This hook doesn't return a value } ``` -------------------------------- ### Instantiate SchemaParser Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/schema-parser.md Demonstrates how to create an instance of SchemaParser with a given schema and configuration. Use this to parse a specific OpenAPI schema object into a structured type definition. ```typescript import { SchemaParser } from "swagger-typescript-api"; // Create parser for a schema const schema = { type: "object", properties: { id: { type: "integer" }, email: { type: "string", format: "email" }, role: { type: "string", enum: ["admin", "user", "guest"] }, }, required: ["id", "email"], }; const parser = new SchemaParser(fabric, { typeName: "User", schema, }); const parsed = parser.parse(); console.log(parsed.type); // "interface" console.log(parsed.name); // "User" console.log(parsed.content.length); // 3 (properties) ``` -------------------------------- ### Customize Type Names with Prefixes or Transformations Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md The `onFormatTypeName` hook allows you to modify generated type names. This example prefixes all types with 'I' and converts enum keys to uppercase. ```typescript onFormatTypeName: (name, rawName, schemaType) => { if (schemaType === "enum-key") { return name.toUpperCase(); } return `I${name}`; } ``` -------------------------------- ### Generate Basic Templates with Fetch Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/generate-templates.md Use this snippet to generate default API templates using the `fetch` HTTP client. It outputs files to the specified directory and logs the number of generated files. ```typescript import { generateTemplates } from "swagger-typescript-api"; const output = await generateTemplates({ output: "./my-templates", httpClientType: "fetch", }); console.log(`Generated ${output.files.length} template files`); ``` -------------------------------- ### Import Cleanup and Formatting Transformation Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/code-formatter.md Demonstrates the effect of `removeUnusedImports()` followed by `format()` on TypeScript code. The example shows the removal of unused imports and subsequent code standardization. ```typescript // Input code import { readFile, writeFile } from "fs/promises"; import type { TypeA, TypeB } from "./types.js"; import { unused1, used } from "./helpers.js"; import { ComponentA } from "react"; import "./polyfill.js"; // Side effect export function myFunction(a: TypeA): TypeB { return used(a); } // After removeUnusedImports() import type { TypeA, TypeB } from "./types.js"; import { used } from "./helpers.js"; import "./polyfill.js"; export function myFunction(a: TypeA): TypeB { return used(a); } // After format() import type { TypeA, TypeB } from "./types.js"; import { used } from "./helpers.js"; import "./polyfill.js"; export function myFunction(a: TypeA): TypeB { return used(a); } ``` -------------------------------- ### Use Custom Templates Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Specify a custom template directory using the --templates flag. This allows for customization of the generated API code. ```bash sta generate --path ./swagger.json --templates ./my-templates ``` -------------------------------- ### Get Parsed Schema Type Data Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/schema-components-map.md Retrieves the parsed type information for a given schema component reference. Returns the type data or null if the component is not found. ```typescript const typeData = schemaComponentsMap.getType("#/components/schemas/User"); // Returns { $parsedSchema: true, schemaType: "object", type: "interface", ... } ``` -------------------------------- ### Custom Hooks During Generation Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/code-gen-process.md Integrate custom logic into the code generation pipeline using hooks. This example shows how to log messages and conditionally skip routes based on tags. ```typescript const process = new CodeGenProcess({ input: "./api.yaml", output: "./api", hooks: { onInit: (config) => { console.log("Starting code generation..."); return config; }, onCreateComponent: (component) => { // Modify component before parsing return component; }, onCreateRoute: (route) => { // Skip routes matching a pattern if (route.raw.tags?.includes("deprecated")) { return false; // Skip this route } return route; }, onPrepareConfig: (config) => { console.log("Generation complete, preparing output..."); return config; }, }, }); const result = await process.start(); ``` -------------------------------- ### Generate API with Path Input Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Generates API client code using a local OpenAPI/Swagger JSON file as input. ```bash sta generate --path ./swagger.json ``` -------------------------------- ### Editing Templates with ETA Syntax Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/generate-templates.md Modify the generated `.ejs` files using ETA syntax. This example shows how to include base templates and define an API class with routes. ```ejs <%~ include(`@base/api`, {config: it.config}) %> export class <%= it.utils.pascalCase(it.config.apiClassName) %> { <% it.routes.forEach(route => { %> <%= route.routeName.usage %>() { ... } <% }) %> } ``` -------------------------------- ### Configure HTTP Client Type Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/configuration.md Specify the HTTP client library to be used. Defaults to 'fetch'. ```javascript { httpClientType: "fetch" // Generates code for Fetch API // or httpClientType: "axios" // Generates code for Axios } ``` -------------------------------- ### Output Configuration: Clean Output Directory Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/configuration.md Set 'cleanOutput' to 'true' to delete the output directory before generation begins. Defaults to 'false'. ```javascript { cleanOutput: true } ``` -------------------------------- ### Run All Tests Source: https://github.com/acacode/swagger-typescript-api/blob/main/CLAUDE.md Executes all tests in the project using vitest with a 30-second timeout. ```bash bun run test ``` -------------------------------- ### Load All Templates Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/templates-worker.md Loads all built-in and custom templates into a map where keys are template names and values are their content. This is useful for getting a complete set of templates to be used in the generation process. ```typescript const templates = templatesWorker.getTemplates(config); // Returns: // { // api: "export class <%= apiClassName %> { ... }", // dataContracts: "export interface <%= name %> { ... }", // httpClient: "class HttpClient { ... }", // routeTypes: "...", // routeName: "...", // dataContractJsDoc: "...", // interfaceDataContract: "...", // typeDataContract: "...", // enumDataContract: "...", // objectFieldJsDoc: "..." // } ``` -------------------------------- ### Initialize and Parse Routes Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/schema-routes.md Demonstrates how to initialize the SchemaRoutes class and parse API routes from a resolved schema. Accesses HTTP method, path, route name, request body type, response type, and module grouping. ```typescript import { SchemaRoutes } from "swagger-typescript-api"; const schemaRoutes = new SchemaRoutes( config, parserFabric, componentMap, templatesWorker, typeNameFormatter, ); // Parse all routes from schema const routes = schemaRoutes.parseRoutes(resolvedSchema); // Access route information routes.forEach(route => { // HTTP method and path const endpoint = `${route.request.method?.toUpperCase()} ${route.request.path}`; console.log(endpoint); // Route name for generated method console.log(`Method name: ${route.routeName.usage}`); // Request body type if (route.requestBodyInfo) { console.log(`Request: ${route.requestBodyInfo.type}`); } // Response type console.log(`Response: ${route.response.type}`); // Module grouping console.log(`Module: ${route.namespace}`); }); ``` -------------------------------- ### GitLab Repository File URL Resolution Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/resolved-swagger-schema.md Demonstrates how external schemas from GitLab repositories are resolved using their REST API file endpoints. This example assumes a base URL and a relative path. ```typescript // Base URL: https://gitlab.com/api/v4/projects/123/repository/files/spec.yaml/raw // Relative: ./other.yaml // Resolves to: https://gitlab.com/api/v4/projects/123/repository/files/other.yaml/raw ``` -------------------------------- ### Build Project Source: https://github.com/acacode/swagger-typescript-api/blob/main/CLAUDE.md Builds the project using tsdown, generating both ESM and CJS formats for the output files. ```bash bun run build ``` -------------------------------- ### Basic API Generation Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/generate-api.md Generates an API client and writes it to the specified output directory. Requires input OpenAPI spec and output path. Sets http client to fetch and enables response generation. ```typescript import { generateApi } from "swagger-typescript-api"; import * as path from "node:path"; const result = await generateApi({ input: path.resolve(process.cwd(), "./swagger.json"), output: path.resolve(process.cwd(), "./generated"), httpClientType: "fetch", generateClient: true, generateResponses: true, }); console.log(`Generated ${result.files.length} files`); ``` -------------------------------- ### Specify Output Directory Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Generates API client code and places the output files in a specified directory. ```bash sta generate --path ./swagger.json --output ./generated ``` ```bash sta generate -p ./swagger.json -o ./api ``` -------------------------------- ### getTemplates Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/templates-worker.md Loads all built-in and custom templates available based on the configuration. ```APIDOC ## getTemplates(config: CodeGenConfig): Record ### Description Loads all built-in and custom templates, returning them as a map of template names to their content. ### Parameters #### Path Parameters - **config** (CodeGenConfig) - Required - The configuration context. ### Returns #### Success Response - **Record** - A map where keys are template names (e.g., `"api"`, `"dataContracts"`) and values are the template content strings. ### Loaded Templates - `api` — Main API client class - `dataContracts` — Type definitions container - `httpClient` — HTTP client implementation - `routeTypes` — Route request/response types - `routeName` — Individual route method - `dataContractJsDoc` — Type documentation - `interfaceDataContract` — Interface formatting - `typeDataContract` — Type alias formatting - `enumDataContract` — Enum formatting - `objectFieldJsDoc` — Field documentation ### Request Example ```typescript const templates = templatesWorker.getTemplates(config); // Returns: // { // api: "export class <%= apiClassName %> { ... }", // dataContracts: "export interface <%= name %> { ... }", // httpClient: "class HttpClient { ... }", // routeTypes: "...", // routeName: "...", // dataContractJsDoc: "...", // interfaceDataContract: "...", // typeDataContract: "...", // enumDataContract: "...", // objectFieldJsDoc: "..." // } ``` ``` -------------------------------- ### Add Custom Metadata to Route Parameters Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md The `onCreateRoute` hook can be used to enrich route objects with custom metadata. This example adds `isPublic` and `isDeprecated` flags to `routeParams` based on route tags and deprecation status. ```typescript onCreateRoute: (route) => { if (!route.routeParams) route.routeParams = {}; route.routeParams.isPublic = !route.raw.tags?.includes("admin"); route.routeParams.isDeprecated = route.raw.deprecated || false; return route; } ``` -------------------------------- ### CLI Generation Using Configuration File Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Run the generation command without explicit flags, relying on an automatically detected configuration file (e.g., swagger-typescript-api.config.js). ```bash # Uses ./swagger-typescript-api.config.js or similar sta generate ``` -------------------------------- ### Override Route Name Formatting with onFormatRouteName Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md Use onFormatRouteName to completely override the default route name formatting. This example converts camelCase names to snake_case. Return the custom formatted name or `undefined` to use the default. ```typescript onFormatRouteName: (routeInfo, templateRouteName) => { // Convert to snake_case instead of camelCase return templateRouteName.replace(/([A-Z])/g, "_$1").toLowerCase(); } ``` -------------------------------- ### Modify Parsed Path Structure with onBuildRoutePath Hook Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md This hook allows modification of the parsed path structure after path parameters have been extracted. You can alter path parameters, such as making them all required, or change the final route string, for example, by converting it to uppercase. ```typescript onBuildRoutePath: (buildData) => { // Transform path parameters buildData.pathParams.forEach(param => { param.required = true; // Make all path params required }); // Modify final path buildData.route = buildData.route.toUpperCase(); return buildData; }; ``` -------------------------------- ### Output Configuration: Custom Templates Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/configuration.md Provide a path to a custom ETA template directory using the 'templates' option. Custom templates in this directory will override built-in templates with the same filename. ```javascript { templates: "./my-templates" // Custom templates in ./my-templates override templates/ files } ``` -------------------------------- ### Enable Single HTTP Client Instance Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Allows an HttpClient instance to be passed into the API constructor, useful for centralized configuration. ```bash sta generate --path ./swagger.json --single-http-client ``` -------------------------------- ### Customize Route Names with onCreateRouteName Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md Modify route names before they are finalized using onCreateRouteName. This hook allows prefixing names or adding suffixes based on the HTTP method, such as 'Query' for GET requests or 'Mutation' for POST requests. Return the modified name info or `undefined`. ```typescript onCreateRouteName: (nameInfo, rawInfo) => { // Prefix all names with "api" nameInfo.usage = `api${nameInfo.usage[0].toUpperCase()}${nameInfo.usage.slice(1)}`; // Add operation type suffix if (rawInfo.method === "get") { nameInfo.usage += "Query"; } else if (rawInfo.method === "post") { nameInfo.usage += "Mutation"; } return nameInfo; } ``` -------------------------------- ### Local File Input Options Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/api-reference/swagger-schema-resolver.md Shows how to specify local file paths for schema input. Supports absolute and relative paths, JSON and YAML formats, and automatic format detection. ```typescript { input: "./swagger.json" // or input: "./api.yaml" // or input: "./spec/openapi.json" } ``` -------------------------------- ### Format Code Source: https://github.com/acacode/swagger-typescript-api/blob/main/CLAUDE.md Formats the codebase using Biome. This command automatically applies code style fixes. ```bash bun run format ``` -------------------------------- ### Generate API Client with Fetch Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/README.md Generates an API client using the 'fetch' HTTP client. Specify the input OpenAPI definition and the output directory. ```typescript import { generateApi } from "swagger-typescript-api"; const result = await generateApi({ input: "./swagger.json", output: "./generated", httpClientType: "fetch", }); ``` -------------------------------- ### Generate API with URL Input Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Generates API client code by fetching the OpenAPI schema from a remote URL. ```bash sta generate --url https://api.example.com/openapi.json ``` -------------------------------- ### Enable Client Generation Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Explicitly enables the generation of the API client class with route methods. This is the default behavior. ```bash sta generate --path ./swagger.json --generate-client ``` -------------------------------- ### Specify HTTP Client Type Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/cli-reference.md Configures the generation to use a specific HTTP client library, such as 'axios'. Defaults to 'fetch'. ```bash sta generate --path ./swagger.json --http-client-type axios ``` -------------------------------- ### onPrepareConfig Hook Source: https://github.com/acacode/swagger-typescript-api/blob/main/_autodocs/hooks-reference.md Called before template rendering and after all parsing is complete. Use this hook for final configuration adjustments before output generation, such as filtering routes or customizing model types. ```APIDOC ## onPrepareConfig(config): config | undefined ### Description Performs final configuration adjustments before output generation, after all parsing is complete. This is useful for modifying routes or customizing model types before rendering. ### Parameters #### Parameters - **config** (`GenerateApiConfiguration["config"]`) - Configuration object with loaded schema and processed data. ### Returns Modified config or undefined (undefined means no change). ### Request Example ```typescript onPrepareConfig: (config) => { console.log("Preparing configuration for rendering..."); // Adjust routes if (config.routes.outOfModule) { config.routes.outOfModule = config.routes.outOfModule.filter( r => !r.raw.tags?.includes("deprecated") ); } // Customize model types config.modelTypes.forEach(type => { type.description = type.description?.toUpperCase(); }); return config; } ``` ```