{"id":32846820,"url":"https://github.com/knight174/swagger2ts","last_synced_at":"2025-11-08T08:02:22.549Z","repository":{"id":322793797,"uuid":"1087097887","full_name":"knight174/swagger2ts","owner":"knight174","description":"Generate type-safe TypeScript API clients from OpenAPI/Swagger specifications with incremental generation support.","archived":false,"fork":false,"pushed_at":"2025-11-06T10:09:42.000Z","size":164,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-11-06T12:10:34.696Z","etag":null,"topics":["api-generator","code-generator","kubb","openapi","swagger","swagger2ts","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/knight174.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-31T11:26:44.000Z","updated_at":"2025-11-06T10:09:46.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/knight174/swagger2ts","commit_stats":null,"previous_names":["knight174/swagger2ts"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/knight174/swagger2ts","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/knight174%2Fswagger2ts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/knight174%2Fswagger2ts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/knight174%2Fswagger2ts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/knight174%2Fswagger2ts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/knight174","download_url":"https://codeload.github.com/knight174/swagger2ts/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/knight174%2Fswagger2ts/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":283320032,"owners_count":26816393,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-08T02:00:06.281Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-generator","code-generator","kubb","openapi","swagger","swagger2ts","typescript"],"created_at":"2025-11-08T08:00:56.826Z","updated_at":"2025-11-08T08:02:22.539Z","avatar_url":"https://github.com/knight174.png","language":"TypeScript","readme":"# Swagger2TS\n\nGenerate type-safe TypeScript API clients from OpenAPI/Swagger specifications with incremental generation support.\n\n## Features\n\n- **Type-Safe**: Generates TypeScript types and fully-typed API clients using [Kubb](https://kubb.dev/)\n- **Incremental Generation**: Smart caching system skips regeneration when Swagger hasn't changed\n- **Swagger 2.0 Support**: Automatic conversion to OpenAPI 3.x when needed\n- **Flexible Configuration**: CLI arguments, environment variables, or config files\n- **Custom Patches**: Built-in and extensible patch system for non-standard Swagger formats\n- **Multiple API Sources**: Support for managing multiple API sources via config file\n\n## Quick Start\n\n### Using npx (No Installation Required)\n\n```bash\n# Basic command structure\nnpx @miaoosi/swagger2ts -i \u003cpath-to-swagger-or-url\u003e -o \u003coutput-directory\u003e\n\n# Generate API client from a Swagger file\nnpx @miaoosi/swagger2ts -i ./swagger.json -o ./src/api\n\n# Generate from a URL\nnpx @miaoosi/swagger2ts -i https://api.example.com/swagger.json -o ./src/api\n\n# Convert Swagger 2.0 to OpenAPI 3.x\nnpx @miaoosi/swagger2ts -i ./swagger-v2.json -o ./src/api --convert-to-v3\n```\n\n### Installation\n\n\u003e Node version \u003e= 20 is required. If your project is using an older version, consider using `npx` instead. Or install it in another directory with node \u003e= 20.\n\n```bash\n# Using pnpm\npnpm add -D @miaoosi/swagger2ts\n\n# Using npm\nnpm install --save-dev @miaoosi/swagger2ts\n\n# Using yarn\nyarn add -D @miaoosi/swagger2ts\n```\n\nThen run:\n\n```bash\nnpx swagger2ts -i \u003cpath-to-swagger-or-url\u003e -o \u003coutput-directory\u003e\n```\n\n## CLI Options\n\n| Option | Alias | Description |\n|--------|-------|-------------|\n| `--input \u003cpath\u003e` | `-i` | Swagger file path or URL |\n| `--output \u003cpath\u003e` | `-o` | Output directory |\n| `--config \u003cpath\u003e` | `-c` | Config file path |\n| `--source \u003cnames\u003e` | `-s` | Source names to generate (comma-separated, e.g., v5,v7) |\n| `--convert-to-v3` | | Convert Swagger 2.0 to OpenAPI 3.x |\n| `--force` | | Force regeneration (skip cache check) |\n| `--no-cache` | | Same as `--force` |\n| `--clean` | | Clean output directory before generation |\n| `--env \u003cpath\u003e` | | Load specific `.env` file |\n\n## Configuration Methods\n\nSwagger2TS supports three configuration methods, with the following priority order:\n\n### 1. Config File (Recommended for Multiple Sources)\n\nCreate a `swagger2ts.config.ts` (or `.js`) file in your project root:\n\n```typescript\nimport { defineConfig } from '@miaoosi/swagger2ts';\nimport { builtinPatches } from '@miaoosi/swagger2ts/swagger-processor';\n\nexport default defineConfig({\n  sources: {\n    // API v5\n    v5: {\n      input: 'https://api.example.com/v5/swagger.json',\n      output: './src/api/v5',\n      convertToV3: true,\n    },\n    // API v7\n    v7: {\n      input: 'https://api.example.com/v7/swagger.json',\n      output: './src/api/v7',\n      convertToV3: true,\n    },\n    // Admin API\n    admin: {\n      input: './swagger/admin.json',\n      output: './src/api/admin',\n      patches: [builtinPatches.giteeTimestamp],\n    },\n  },\n  // Global settings\n  convertToV3: true,\n  cache: true,\n});\n```\n\nThen run:\n\n```bash\n# Generate all sources\nnpx swagger2ts\n\n# Generate specific sources only\nnpx swagger2ts --source v5,v7\n\n# Override config with CLI flags\nnpx swagger2ts --source v5 --force\n```\n\n**Supported config file names** (searched in this order):\n- `swagger2ts.config.ts`\n- `swagger2ts.config.mts`\n- `swagger2ts.config.js`\n- `swagger2ts.config.mjs`\n- `.swagger2tsrc.ts`\n- `.swagger2tsrc.mts`\n- `.swagger2tsrc.js`\n- `.swagger2tsrc.mjs`\n\n### 2. CLI Arguments\n\nPass input/output directly via command line:\n\n```bash\nnpx swagger2ts -i ./swagger.json -o ./src/api\nnpx swagger2ts -i https://api.com/swagger.json -o ./src/api --clean\n```\n\n### 3. Environment Variables\n\nCreate a `.env` file in your project root:\n\n```env\nSWAGGER_INPUT=https://api.example.com/swagger.json\nOUTPUT_PATH=./src/api\nCONVERT_TO_V3=true\n```\n\nThen run:\n\n```bash\nnpx swagger2ts\n```\n\nYou can also specify a custom `.env` file:\n\n```bash\nnpx swagger2ts --env .env.production\n```\n\n## Multi-Environment Setup\n\nFor managing multiple API versions or environments, use the config file approach:\n\n```typescript\n// swagger2ts.config.ts\nimport { defineConfig } from '@miaoosi/swagger2ts';\n\nexport default defineConfig({\n  sources: {\n    dev: {\n      input: 'https://dev-api.example.com/swagger.json',\n      output: './src/api/dev',\n    },\n    staging: {\n      input: 'https://staging-api.example.com/swagger.json',\n      output: './src/api/staging',\n    },\n    production: {\n      input: 'https://api.example.com/swagger.json',\n      output: './src/api/prod',\n    },\n  },\n});\n```\n\nUsage:\n```bash\n# Generate all environments\nnpx swagger2ts\n\n# Generate only dev\nnpx swagger2ts --source dev\n\n# Generate dev and staging\nnpx swagger2ts --source dev,staging\n```\n\n## Custom Swagger Patches\n\nPatches are functions that transform Swagger JSON content before generation. Useful for fixing non-standard formats.\n\n**Built-in patches:**\n\n- `builtinPatches.giteeTimestamp`: Fixes Gitee's non-standard \"Timestamp\" type\n\nFor examples of creating custom patches, see [examples/04-custom-patches.ts](./examples/04-custom-patches.ts).\n\n## Generated Code Structure\n\nRunning the generator creates the following structure:\n\n```bash\n{output}/\n├── .api-gen-cache/\n│   └── metadata.json              # Cache metadata for incremental generation\n├── .temp/\n│   └── swagger.json               # Processed Swagger (after patches/conversion)\n├── types/\n│   ├── {Tag}Controller/\n│   │   ├── {OperationId}.ts       # Type definitions per operation\n│   │   └── index.ts\n│   └── index.ts\n├── clients/fetch/\n│   ├── {Tag}Service/\n│   │   ├── {operationId}Client.ts # Individual client functions\n│   │   ├── {tag}Service.ts\n│   │   └── index.ts\n│   └── index.ts\n└── schemas/\n    └── {schema}.json              # JSON schemas\n```\n\n## Usage Examples\n\nFor detailed examples and code samples, see the **[examples/](./examples/)** directory.\n\n**Quick examples:**\n\n- **[Basic Usage](./examples/01-basic-usage.ts)** - Simple API calls with type safety\n- **[Authentication](./examples/02-with-authentication.ts)** - Adding auth headers\n- **[Multiple API Sources](./examples/03-multiple-api-sources.ts)** - Managing multiple APIs\n- **[Custom Patches](./examples/04-custom-patches.ts)** - Fixing non-standard Swagger formats\n- **[Environment Variables](./examples/06-env-variables.sh)** - Using `.env` files\n- **[Axios Client](./examples/07-axios-client.ts)** - Using Axios instead of Fetch\n\n### Quick Start Example\n\n```typescript\n// Import generated types and client\nimport type { GetUsersId } from \"./api/types\";\nimport { getUsersIdClient } from \"./api/clients/fetch\";\n\n// Make a type-safe API call\nconst response = await getUsersIdClient({\n  params: { id: \"123\" }\n});\n\nif (response.ok) {\n  const user: GetUsersId[\"response\"] = await response.json();\n  console.log(user);\n}\n```\n\nSee the [examples/README.md](./examples/README.md) for complete documentation of all examples.\n\n## Incremental Generation\n\nThe tool uses MD5 hashing to detect changes in Swagger files:\n\n- **First run**: Generates all files and stores hash in `.api-gen-cache/metadata.json`\n- **Subsequent runs**: Skips generation if Swagger content hasn't changed\n- **Force regeneration**: Use `--force` or `--no-cache` flag\n\n```bash\n# Normal run - will skip if unchanged\nnpx swagger2ts -i \u003cpath-to-swagger-or-url\u003e -o \u003coutput-directory\u003e\n\n# Force regeneration\nnpx swagger2ts -i \u003cpath-to-swagger-or-url\u003e -o \u003coutput-directory\u003e --force\n```\n\n## Swagger 2.0 Support\n\nThe tool can automatically convert Swagger 2.0 specifications to OpenAPI 3.x:\n\n```bash\nnpx swagger2ts -i \u003cpath-to-swagger-or-url\u003e -o \u003coutput-directory\u003e --convert-to-v3\n```\n\nThis uses the [swagger2openapi](https://github.com/Mermade/oas-kit) library with automatic patching for common issues.\n\n## Development\n\n### Project Setup\n\n```bash\ngit clone \u003crepo-url\u003e\ncd swagger2ts\n\n# Install dependencies\npnpm install\n\n# Build the project\npnpm run build\n\n# Run in development mode\npnpm run dev -- -i ./__mock__/swagger.json -o ./api/test\n```\n\n### Scripts\n\n- `pnpm run build`: Compile TypeScript to `dist/`\n- `pnpm run dev`: Run CLI in development mode with tsx\n- `pnpm run prepublishOnly`: Pre-publish build check\n\n### Project Structure\n\n```bash\nswagger2ts/\n├── bin/\n│   └── swagger2ts.ts              # CLI entry point\n├── src/\n│   ├── cli.ts                     # CLI argument parsing\n│   ├── generator.ts               # Kubb wrapper\n│   ├── incremental.ts             # Cache system\n│   ├── swagger-processor.ts       # Swagger patching \u0026 conversion\n│   └── types.ts                   # TypeScript definitions\n├── templates/\n│   ├── base.config.ts             # Reusable Kubb config (Fetch)\n│   └── axios-client.config.ts     # Axios client configuration\n├── examples/\n│   ├── 01-basic-usage.ts          # Basic usage example\n│   ├── 02-with-authentication.ts\n│   ├── 03-multiple-api-sources.ts\n│   ├── 04-custom-patches.ts\n│   ├── 05-config-file.ts\n│   ├── 06-env-variables.sh\n│   ├── 07-axios-client.ts\n│   └── README.md                  # Examples documentation\n└── __mock__/\n    └── swagger.json               # Demo Swagger file\n```\n\n## Troubleshooting\n\n### \"Timestamp\" Type Errors\n\nIf you encounter errors with non-standard \"Timestamp\" types (common with Gitee API), you can create custom patches. See [examples/04-custom-patches.ts](./examples/04-custom-patches.ts) for how to implement patch functions.\n\n\u003e **Note:** Built-in patch support via configuration file is planned for a future release.\n\n### Cache Issues\n\nIf you suspect cache corruption:\n\n```bash\n# Force regeneration\nnpx swagger2ts -i ./swagger.json -o ./src/api --force\n\n# Or delete cache directory\nrm -rf ./src/api/.api-gen-cache\n```\n\n### Validation Errors\n\nFor Swagger 2.0 validation errors:\n\n```bash\n# Convert to OpenAPI 3.x first\nnpx swagger2ts -i ./swagger.json -o ./src/api --convert-to-v3\n```\n\n## Migration Guide\n\n### From Direct Kubb Usage\n\nReplace your Kubb configuration with Swagger2TS CLI:\n\n**Before:**\n\n```typescript\n// kubb.config.ts\nexport default {\n  input: { path: './swagger.json' },\n  output: { path: './src/api' },\n  // ... complex plugin config\n}\n```\n\n**After:**\n\n```bash\nnpx swagger2ts -i ./swagger.json -o ./src/api\n```\n\nAll plugin configurations are handled by `templates/base.config.ts`.\n\n## Contributing\n\nContributions are welcome! Please feel free to submit issues or pull requests.\n\n## License\n\nMIT\n\n## Credits\n\nBuilt with [Kubb](https://kubb.dev/) - The ultimate OpenAPI code generator.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fknight174%2Fswagger2ts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fknight174%2Fswagger2ts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fknight174%2Fswagger2ts/lists"}