GitHub Raw JSON API

davila7 / claude-code-templates

30,218 Python

CLI tool for configuring and monitoring Claude Code

claude-code-templates Specification

Located in dashboard/public/component-content/skills/development/openapi-to-typescript.json on branch HEAD

Unknown JSON 8.3 KB
Raw JSON Specification
{
  "content": "---\nname: openapi-to-typescript\ndescription: Converts OpenAPI 3.0 JSON/YAML to TypeScript interfaces and type guards. This skill should be used when the user asks to generate types from OpenAPI, convert schema to TS, create API interfaces, or generate TypeScript types from an API specification.\n---\n\n# OpenAPI to TypeScript\n\nConverts OpenAPI 3.0 specifications to TypeScript interfaces and type guards.\n\n**Input:** OpenAPI file (JSON or YAML)\n**Output:** TypeScript file with interfaces and type guards\n\n## When to Use\n\n- \"generate types from openapi\"\n- \"convert openapi to typescript\"\n- \"create API interfaces\"\n- \"generate types from spec\"\n\n## Workflow\n\n1. Request the OpenAPI file path (if not provided)\n2. Read and validate the file (must be OpenAPI 3.0.x)\n3. Extract schemas from `components/schemas`\n4. Extract endpoints from `paths` (request/response types)\n5. Generate TypeScript (interfaces + type guards)\n6. Ask where to save (default: `types/api.ts` in current directory)\n7. Write the file\n\n## OpenAPI Validation\n\nCheck before processing:\n\n```\n- Field \"openapi\" must exist and start with \"3.0\"\n- Field \"paths\" must exist\n- Field \"components.schemas\" must exist (if there are types)\n```\n\nIf invalid, report the error and stop.\n\n## Type Mapping\n\n### Primitives\n\n| OpenAPI     | TypeScript   |\n|-------------|--------------|\n| `string`    | `string`     |\n| `number`    | `number`     |\n| `integer`   | `number`     |\n| `boolean`   | `boolean`    |\n| `null`      | `null`       |\n\n### Format Modifiers\n\n| Format        | TypeScript              |\n|---------------|-------------------------|\n| `uuid`        | `string` (comment UUID) |\n| `date`        | `string` (comment date) |\n| `date-time`   | `string` (comment ISO)  |\n| `email`       | `string` (comment email)|\n| `uri`         | `string` (comment URI)  |\n\n### Complex Types\n\n**Object:**\n```typescript\n// OpenAPI: type: object, properties: {id, name}, required: [id]\ninterface Example {\n  id: string;      // required: no ?\n  name?: string;   // optional: with ?\n}\n```\n\n**Array:**\n```typescript\n// OpenAPI: type: array, items: {type: string}\ntype Names = string[];\n```\n\n**Enum:**\n```typescript\n// OpenAPI: type: string, enum: [active, draft]\ntype Status = \"active\" | \"draft\";\n```\n\n**oneOf (Union):**\n```typescript\n// OpenAPI: oneOf: [{$ref: Cat}, {$ref: Dog}]\ntype Pet = Cat | Dog;\n```\n\n**allOf (Intersection/Extends):**\n```typescript\n// OpenAPI: allOf: [{$ref: Base}, {type: object, properties: ...}]\ninterface Extended extends Base {\n  extraField: string;\n}\n```\n\n## Code Generation\n\n### File Header\n\n```typescript\n/**\n * Auto-generated from: {source_file}\n * Generated at: {timestamp}\n *\n * DO NOT EDIT MANUALLY - Regenerate from OpenAPI schema\n */\n```\n\n### Interfaces (from components/schemas)\n\nFor each schema in `components/schemas`:\n\n```typescript\nexport interface Product {\n  /** Product unique identifier */\n  id: string;\n\n  /** Product title */\n  title: string;\n\n  /** Product price */\n  price: number;\n\n  /** Created timestamp */\n  created_at?: string;\n}\n```\n\n- Use OpenAPI description as JSDoc\n- Fields in `required[]` have no `?`\n- Fields outside `required[]` have `?`\n\n### Request/Response Types (from paths)\n\nFor each endpoint in `paths`:\n\n```typescript\n// GET /products - query params\nexport interface GetProductsRequest {\n  page?: number;\n  limit?: number;\n}\n\n// GET /products - response 200\nexport type GetProductsResponse = ProductList;\n\n// POST /products - request body\nexport interface CreateProductRequest {\n  title: string;\n  price: number;\n}\n\n// POST /products - response 201\nexport type CreateProductResponse = Product;\n```\n\nNaming convention:\n- `{Method}{Path}Request` for params/body\n- `{Method}{Path}Response` for response\n\n### Type Guards\n\nFor each main interface, generate a type guard:\n\n```typescript\nexport function isProduct(value: unknown): value is Product {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    'id' in value &&\n    typeof (value as any).id === 'string' &&\n    'title' in value &&\n    typeof (value as any).title === 'string' &&\n    'price' in value &&\n    typeof (value as any).price === 'number'\n  );\n}\n```\n\nType guard rules:\n- Check `typeof value === 'object' && value !== null`\n- For each required field: check `'field' in value`\n- For primitive fields: check `typeof`\n- For arrays: check `Array.isArray()`\n- For enums: check `.includes()`\n\n### Error Type (always include)\n\n```typescript\nexport interface ApiError {\n  status: number;\n  error: string;\n  detail?: string;\n}\n\nexport function isApiError(value: unknown): value is ApiError {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    'status' in value &&\n    typeof (value as any).status === 'number' &&\n    'error' in value &&\n    typeof (value as any).error === 'string'\n  );\n}\n```\n\n## $ref Resolution\n\nWhen encountering `{\"$ref\": \"#/components/schemas/Product\"}`:\n1. Extract the schema name (`Product`)\n2. Use the type directly (don't resolve inline)\n\n```typescript\n// OpenAPI: items: {$ref: \"#/components/schemas/Product\"}\n// TypeScript:\nitems: Product[]  // reference, not inline\n```\n\n## Complete Example\n\n**Input (OpenAPI):**\n```json\n{\n  \"openapi\": \"3.0.0\",\n  \"components\": {\n    \"schemas\": {\n      \"User\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\"type\": \"string\", \"format\": \"uuid\"},\n          \"email\": {\"type\": \"string\", \"format\": \"email\"},\n          \"role\": {\"type\": \"string\", \"enum\": [\"admin\", \"user\"]}\n        },\n        \"required\": [\"id\", \"email\", \"role\"]\n      }\n    }\n  },\n  \"paths\": {\n    \"/users/{id}\": {\n      \"get\": {\n        \"parameters\": [{\"name\": \"id\", \"in\": \"path\", \"required\": true}],\n        \"responses\": {\n          \"200\": {\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\"$ref\": \"#/components/schemas/User\"}\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n```\n\n**Output (TypeScript):**\n```typescript\n/**\n * Auto-generated from: api.openapi.json\n * Generated at: 2025-01-15T10:30:00Z\n *\n * DO NOT EDIT MANUALLY - Regenerate from OpenAPI schema\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type UserRole = \"admin\" | \"user\";\n\nexport interface User {\n  /** UUID */\n  id: string;\n\n  /** Email */\n  email: string;\n\n  role: UserRole;\n}\n\n// ============================================================================\n// Request/Response Types\n// ============================================================================\n\nexport interface GetUserByIdRequest {\n  id: string;\n}\n\nexport type GetUserByIdResponse = User;\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport function isUser(value: unknown): value is User {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    'id' in value &&\n    typeof (value as any).id === 'string' &&\n    'email' in value &&\n    typeof (value as any).email === 'string' &&\n    'role' in value &&\n    ['admin', 'user'].includes((value as any).role)\n  );\n}\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\nexport interface ApiError {\n  status: number;\n  error: string;\n  detail?: string;\n}\n\nexport function isApiError(value: unknown): value is ApiError {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    'status' in value &&\n    typeof (value as any).status === 'number' &&\n    'error' in value &&\n    typeof (value as any).error === 'string'\n  );\n}\n```\n\n## Common Errors\n\n| Error | Action |\n|-------|--------|\n| OpenAPI version != 3.0.x | Report that only 3.0 is supported |\n| $ref not found | List missing refs |\n| Unknown type | Use `unknown` and warn |\n| Circular reference | Use type alias with lazy reference |\n"
}