|
| 1 | +#!/usr/bin/env tsx |
| 2 | +import * as fs from "fs"; |
| 3 | +import * as http from "http"; |
| 4 | +import * as https from "https"; |
| 5 | +import openapiTS, { astToString } from "openapi-typescript"; |
| 6 | +import * as path from "path"; |
| 7 | +import ts from "typescript"; |
| 8 | +import { URL } from "url"; |
| 9 | + |
| 10 | +const DATE = ts.factory.createTypeReferenceNode( |
| 11 | + ts.factory.createIdentifier("Date") |
| 12 | +); // `Date` |
| 13 | +const FILE = ts.factory.createTypeReferenceNode( |
| 14 | + ts.factory.createIdentifier("File") |
| 15 | +); // `Blob |
| 16 | +const NULL = ts.factory.createLiteralTypeNode(ts.factory.createNull()); // `null` |
| 17 | + |
| 18 | +// Get environment type from command line arguments |
| 19 | +const envType = process.argv[2]; |
| 20 | + |
| 21 | +if (!envType) { |
| 22 | + console.error( |
| 23 | + "Usage: tsx gen-openapi-types.ts <environment_type> (development|production)" |
| 24 | + ); |
| 25 | + process.exit(1); |
| 26 | +} |
| 27 | + |
| 28 | +const envFile = path.join(process.cwd(), `.env.${envType}`); |
| 29 | + |
| 30 | +// Check if the environment file exists |
| 31 | +if (!fs.existsSync(envFile)) { |
| 32 | + console.error(`Error: Environment file .env.${envType} does not exist`); |
| 33 | + process.exit(1); |
| 34 | +} |
| 35 | + |
| 36 | +// Read the environment file |
| 37 | +const envContent = fs.readFileSync(envFile, "utf8"); |
| 38 | + |
| 39 | +// Extract API base URL from environment file |
| 40 | +const apiBaseUrlMatch = envContent.match(/VITE_API_BASE_URL=(.+)/); |
| 41 | +const apiBaseUrl = apiBaseUrlMatch ? apiBaseUrlMatch[1].trim() : null; |
| 42 | + |
| 43 | +if (!apiBaseUrl) { |
| 44 | + console.error(`Error: VITE_API_BASE_URL not found in .env.${envType}`); |
| 45 | + process.exit(1); |
| 46 | +} |
| 47 | + |
| 48 | +console.log(`Using API base URL: ${apiBaseUrl}`); |
| 49 | + |
| 50 | +// Fetch OpenAPI schema |
| 51 | +const openApiUrl = `${apiBaseUrl}/openapi.json`; |
| 52 | +console.log(`Fetching OpenAPI schema from: ${openApiUrl}`); |
| 53 | + |
| 54 | +const tempFilePath = path.join(process.cwd(), "openapi.json"); |
| 55 | +const outputDir = path.join(process.cwd(), "src", "lib", "types"); |
| 56 | +const outputPath = path.join(outputDir, "openapi-fetch.d.ts"); |
| 57 | + |
| 58 | +// Create output directory if it doesn't exist |
| 59 | +if (!fs.existsSync(outputDir)) { |
| 60 | + fs.mkdirSync(outputDir, { recursive: true }); |
| 61 | +} |
| 62 | + |
| 63 | +// Function to download the OpenAPI schema |
| 64 | +function downloadSchema(): Promise<void> { |
| 65 | + return new Promise((resolve, reject) => { |
| 66 | + const urlObj = new URL(openApiUrl); |
| 67 | + const client = urlObj.protocol === "https:" ? https : http; |
| 68 | + |
| 69 | + const req = client.get(openApiUrl, (res) => { |
| 70 | + if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) { |
| 71 | + reject(new Error(`Failed to fetch OpenAPI schema: ${res.statusCode}`)); |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + const fileStream = fs.createWriteStream(tempFilePath); |
| 76 | + res.pipe(fileStream); |
| 77 | + |
| 78 | + fileStream.on("finish", () => { |
| 79 | + fileStream.close(); |
| 80 | + resolve(); |
| 81 | + }); |
| 82 | + }); |
| 83 | + |
| 84 | + req.on("error", (error) => { |
| 85 | + reject(error); |
| 86 | + }); |
| 87 | + }); |
| 88 | +} |
| 89 | + |
| 90 | +// Main execution |
| 91 | +async function main(): Promise<void> { |
| 92 | + try { |
| 93 | + // Download schema |
| 94 | + await downloadSchema(); |
| 95 | + |
| 96 | + // Generate TypeScript types |
| 97 | + console.log("Generating TypeScript types"); |
| 98 | + const openApiSchema = fs.readFileSync(tempFilePath, "utf8"); |
| 99 | + const ast = await openapiTS(openApiSchema, { |
| 100 | + transform(schemaObject) { |
| 101 | + // handle date-time type |
| 102 | + if (schemaObject.format === "date-time") { |
| 103 | + return { |
| 104 | + schema: schemaObject.nullable |
| 105 | + ? ts.factory.createUnionTypeNode([DATE, NULL]) |
| 106 | + : DATE, |
| 107 | + questionToken: true, |
| 108 | + }; |
| 109 | + } |
| 110 | + |
| 111 | + // handle File type |
| 112 | + if (schemaObject.format === "binary") { |
| 113 | + return { |
| 114 | + schema: schemaObject.nullable |
| 115 | + ? ts.factory.createUnionTypeNode([FILE, NULL]) |
| 116 | + : FILE, |
| 117 | + questionToken: true, |
| 118 | + }; |
| 119 | + } |
| 120 | + }, |
| 121 | + }); |
| 122 | + const contents = astToString(ast); |
| 123 | + fs.writeFileSync(outputPath, contents); |
| 124 | + |
| 125 | + // Clean up |
| 126 | + fs.unlinkSync(tempFilePath); |
| 127 | + |
| 128 | + console.log( |
| 129 | + `TypeScript types successfully generated at src/lib/types/openapi-fetch.d.ts` |
| 130 | + ); |
| 131 | + } catch (error) { |
| 132 | + console.error(error instanceof Error ? error.message : String(error)); |
| 133 | + |
| 134 | + // Clean up temp file if it exists |
| 135 | + if (fs.existsSync(tempFilePath)) { |
| 136 | + fs.unlinkSync(tempFilePath); |
| 137 | + } |
| 138 | + |
| 139 | + process.exit(1); |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +main(); |
0 commit comments