UNPKG

@shixinde/apifox-swagger

Version:

从 Apifox 导出 Swagger/OpenAPI 文档并生成 TypeScript 类型定义的工具

2 lines (1 loc) 4.36 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("fs-extra"),m=require("openapi-typescript"),h=require("tiny-invariant");require("undici");const S=require("./index-ac01765d.cjs");function l(t){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(o,n,a.get?a:{enumerable:!0,get:()=>t[n]})}}return o.default=t,Object.freeze(o)}const c=l(A),_=l(m),y=l(h),d=[4523,4524,4525,4526,4527],u=["127.0.0.1","localhost"],p=async t=>{let o;const n=t&&t.length>0?t:[0,1,2,3,4,5];console.log(`Trying to connect to local Apifox client on hosts: ${u.join(", ")} and ports: ${d.join(", ")}`);for(const a of u)for(const r of d){console.log(`Checking ${a}:${r}...`);for(const i of n)try{const e=`http://${a}:${r}/export/openapi/${i}?version=3.0`;console.log(`Trying URL: ${e}`);const s=await fetch(e,{method:"GET",timeout:3e3});if(console.log(`Response status: ${s.status}`),s.status===200)return console.log(`Successfully fetched swagger from ${e}`),o=await s.json(),o}catch(e){console.log(`Failed to connect to ${a}:${r}/export/openapi/${i}: ${e.message}`);continue}}return console.log("All connection attempts failed."),o},f=async(t,o,n)=>{(0,y.default)(n,"APIFOX_ACCESS_TOKEN is required");const a=o?{type:"SELECTED_FOLDERS",selectedFolderIds:[o]}:{type:"ALL"};return await(await fetch(`https://api.apifox.com/v1/projects/${t}/export-openapi?locale=zh-CN`,{method:"POST",headers:{"X-Apifox-Api-Version":"2024-03-28","Content-Type":"application/json",Authorization:`Bearer ${n}`},redirect:"follow",body:JSON.stringify({scope:a,options:{includeApifoxExtensionProperties:!1,addFoldersToTags:!1},oasVersion:"3.1",exportFormat:"JSON"})})).json()},w=async({projectId:t,outdir:o,folderId:n,folderName:a,useLocal:r,token:i})=>{let e;if(r){if(console.log("Fetching swagger from local Apifox client..."),e=await p(t?[t]:void 0),!e)throw new Error("Failed to fetch swagger from local Apifox client. Please ensure Apifox is running and has projects loaded.")}else{const E=n?`folder [${n}] to <${a}>`:"to <all>";console.log(`Fetching swagger from apifox project [${t}] ${E}...`),e=await f(t,n,i)}const s=`${o}/swagger/${a??"all"}.json`,g=`${o}/swagger/${a??"all"}.ts`;!e.openapi&&e.swagger&&(console.log("Converting Swagger 2.0 to OpenAPI 3.0 format..."),e.openapi="3.0.0",delete e.swagger,e.info||(e.info={title:"API",version:"1.0.0"}),e.paths||(e.paths={})),e.openapi||(e.openapi="3.0.0"),e.info||(e.info={title:"API",version:"1.0.0"}),e.paths||(e.paths={}),console.log(`Swagger format: ${e.openapi||e.swagger||"unknown"}`);const x=await(0,_.default)(e,{});return c.default.ensureDirSync(`${o}/swagger`),c.default.writeJsonSync(s,e,{spaces:2}),c.default.writeFileSync(g,(0,_.astToString)(x)),console.log(`Exported swagger [json] to ${s}`),console.log(`Exported swagger [type] to ${g}`),e},T=Object.freeze(Object.defineProperty({__proto__:null,exportSwagger:w,fetchSwagger:f,fetchSwaggerLocal:p},Symbol.toStringTag,{value:"Module"})),$=t=>{console.log("cli ===>",t),t.command("apifox-swagger").description("Fetch apifox client").option("--projectId <projectId>","The project id of the apifox").option("-o, --outdir <outdir>","The outdir format of the apifox",{default:`./.${t.name}/apifox`}).option("--folderId <folderId>","The folder id of the apifox").option("--folderName <folderName>","The folder name of the apifox").option("--local","Fetch from local Apifox client instead of cloud API").option("--token <token>","Apifox access token (alternative to APIFOX_ACCESS_TOKEN env var)").action(async o=>{var r,i;console.log("options ===>",o),o.local?console.log("Fetching apifox client from local Apifox application..."):(h(o.projectId,"projectId is required when not using --local option"),console.log(`Fetching apifox client https://api.apifox.com/v1/projects/${o.projectId}/export-openapi?locale=zh-CN...`));const n=o.token||((i=(r=globalThis.process)==null?void 0:r.env)==null?void 0:i.APIFOX_ACCESS_TOKEN),{exportSwagger:a}=await Promise.resolve().then(()=>T);await a({projectId:o.projectId,outputDir:o.outdir,folderId:o.folderId,folderName:o.folderName,useLocal:o.local,token:n})})};exports.apiTypes=S.index;exports.exportSwagger=w;exports.fetchSwagger=f;exports.fetchSwaggerLocal=p;exports.initCommandApifox=$;