@fxri/swagger2api 1.3.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,20 +1,22 @@
1
- var le=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import yr from"axios";import{execSync as hr}from"child_process";import tt from"os";import L from"fs";import R from"path";import rt from"prompts";import{generateApi as xr}from"swagger-typescript-api";var Y=e=>/^(https?:\/\/|:?\/\/)/.test(e);import X from"fs";import it from"url";import Z from"path";var Q={param:process.argv.filter((e,t)=>t>1)};function ue(e,t="value",r={}){Array.isArray(e)||(e=[e]);let n;return Q.param.forEach((s,o)=>{if(e.includes(s))["value"].includes(t)?n=Q.param[o+1]:["array"].includes(t)?n=Array.from({length:r.length??1}).map((i,a)=>Q.param[o+a+1]):n=!["false"].includes(Q.param[o+1]);else return}),n}function S(e){return ue(e,"key")}function D(e){return ue(e,"value")}function Fe(e,t={}){return ue(e,"array",t)??[]}function pe(e,t){let r=Z.dirname(e);X.existsSync(r)||X.mkdirSync(r,{recursive:!0}),X.writeFileSync(e,t)}function at(){return typeof le<"u"&&typeof module<"u"?__filename:it.fileURLToPath(import.meta.url)}function Ae(){return typeof le<"u"&&typeof module<"u"?__dirname:Z.dirname(at())}function Oe(e=process.cwd()){let t=[],r=n=>{for(let s of X.readdirSync(n,{withFileTypes:!0})){if(s.name.startsWith("."))continue;let o=Z.join(n,s.name);if(s.isDirectory()){if(s.name==="node_modules")continue;r(o)}else s.isFile()&&s.name.startsWith("saconfig")&&s.name.endsWith(".json")&&t.push(Z.relative(e,o))}};return r(e),t.sort()}function ee(e){return JSON.stringify(e).slice(1,-1)}function Le(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}import*as De from"dns/promises";import*as me from"net";var ct=5,z=async e=>{try{return(await De.lookup(e,{all:!0,verbatim:!0})).map(r=>r.address)}catch{return[]}};function fe(e){let t=e.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return!1;let r=t.slice(1).map(Number);if(r.some(o=>o>255))return!1;let[n,s]=r;return n===0||n===10||n===127||n===169&&s===254||n===172&&s>=16&&s<=31||n===192&&s===168}function lt(e){let t=e.toLowerCase();if(t==="::"||t==="::1"||t.startsWith("fe80:"))return!0;let r=t.split(":")[0]??"";if(r>="fc00"&&r<="fdff")return!0;let n=t.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);if(n?.[1])return fe(n[1]);let s=t.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(s?.[1]&&s?.[2]){let o=parseInt(s[1],16),i=parseInt(s[2],16);return fe(`${o>>8&255}.${o&255}.${i>>8&255}.${i&255}`)}return!1}function Pe(e){let t=me.isIP(e);return t===4?fe(e):t===6?lt(e):!1}function ut(e){let t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")}async function pt(e,t=z){let r;try{r=new URL(e)}catch{return!1}if(r.protocol!=="http:"&&r.protocol!=="https:")return!1;let n=r.hostname.startsWith("[")&&r.hostname.endsWith("]")?r.hostname.slice(1,-1):r.hostname;if(ut(n))return!1;if(me.isIP(n))return!Pe(n);let s=await t(n);return s.length===0?!1:s.every(o=>!Pe(o))}function ft(e,t){if(typeof t!="string")return!1;try{let r=new URL(e),n=new URL(t);return r.protocol===n.protocol&&r.host===n.host}catch{return!1}}function Ie(e){return e.split("#")[0]||e}async function ge(e,t,r=z){let{specSourceUrl:n,allowExplicitSpecUrl:s=!1}=t;return s&&typeof n=="string"&&Ie(e)===Ie(n)||typeof n=="string"&&ft(e,n)?!0:pt(e,r)}function mt(e,t){try{return new URL(e,t).toString()}catch{return null}}async function Me(e,t,r,n=z,s=fetch){let o=e,i=0;for(;;){if(!await ge(o,{specSourceUrl:r.specSourceUrl,allowExplicitSpecUrl:r.allowExplicitSpecUrl&&i===0},n))return null;let l=await s(o,{...t,redirect:"manual"});if(l.status>=300&&l.status<400){let u=l.headers.get("location");if(!u||i>=ct)return null;let p=mt(u,o);if(!p)return null;o=p,i+=1;continue}return l}}var te=/["\\\u0000-\u001f]/;function gt(e){if(e.paths&&typeof e.paths=="object"){let t={};for(let[r,n]of Object.entries(e.paths))t[Le(r)]=n;e.paths=t}if(Array.isArray(e.servers))for(let t of e.servers)t&&typeof t.url=="string"&&(t.url=ee(t.url));de(e)}function de(e){if(Array.isArray(e)){e.forEach(t=>de(t));return}if(!(!e||typeof e!="object"))for(let t of Object.keys(e)){let r=e[t];t==="enum"&&Array.isArray(r)?e[t]=r.map(n=>typeof n=="string"?ee(n):n):t==="default"&&typeof r=="string"?e[t]=ee(r):de(r)}}function dt(e){let t=[],r=(n,s)=>{if(Array.isArray(n)){n.forEach((o,i)=>r(o,`${s}[${i}]`));return}if(!(!n||typeof n!="object")){if(n.properties&&typeof n.properties=="object")for(let o of Object.keys(n.properties))te.test(o)&&t.push(`${s}.properties\uFF1A\u5C5E\u6027\u540D\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);if(Array.isArray(n.required))for(let o of n.required)typeof o=="string"&&te.test(o)&&t.push(`${s}.required\uFF1A\u5FC5\u586B\u5B57\u6BB5\u540D\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);if(n.discriminator&&typeof n.discriminator=="object"&&(typeof n.discriminator.propertyName=="string"&&te.test(n.discriminator.propertyName)&&t.push(`${s}.discriminator.propertyName\uFF1A\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(n.discriminator.propertyName)}`),n.discriminator.mapping&&typeof n.discriminator.mapping=="object"))for(let o of Object.keys(n.discriminator.mapping))te.test(o)&&t.push(`${s}.discriminator.mapping\uFF1A\u952E\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);for(let o of Object.keys(n))r(n[o],`${s}.${o}`)}};return r(e,"#"),t}async function yt(e,t={}){let r=[],n={baseUrl:t.baseUrl,resolve:t.resolve??z,fetchImpl:t.fetchImpl??fetch,docs:new Map,errors:r},s=async(i,a,l)=>{if(Array.isArray(i)){let p=[];for(let c=0;c<i.length;c+=1)p.push(await s(i[c],`${a}[${c}]`,l));return p}if(!i||typeof i!="object")return i;let u=i.$ref;if(typeof u=="string"&&!u.startsWith("#")){let p=await o(u,a,l);return p===null?i:s(p,a,l)}for(let p of Object.keys(i))i[p]=await s(i[p],`${a}.${p}`,l);return i},o=async(i,a,l)=>{if(!/^https?:\/\//i.test(i))return r.push(`${a}\uFF1A\u4E0D\u652F\u6301\u7684\u5916\u90E8\u5F15\u7528\uFF08\u4EC5\u5141\u8BB8\u6587\u6863\u5185 #/ \u6216 http(s)\uFF09\uFF1A${i}`),null;let u=i.indexOf("#"),p=u===-1?i:i.slice(0,u),c=u===-1?"":i.slice(u+1),m;try{m=n.baseUrl?new URL(p,n.baseUrl).toString():p}catch{return r.push(`${a}\uFF1A\u65E0\u6CD5\u89E3\u6790\u7684\u5F15\u7528\u5730\u5740\uFF1A${i}`),null}let f=`${m}#${c}`;if(l.includes(f))return r.push(`${a}\uFF1A\u68C0\u6D4B\u5230\u5F15\u7528\u73AF\uFF1A${[...l,f].join(" -> ")}`),null;if(!await ge(m,{specSourceUrl:n.baseUrl},n.resolve))return r.push(`${a}\uFF1A\u62D2\u7EDD\u62C9\u53D6\u975E\u516C\u7F51\u6216\u975E\u4FE1\u4EFB\u6765\u6E90\u7684\u5916\u90E8\u5F15\u7528\uFF1A${i}`),null;let h=await ht(m,n);if(!h)return null;let w=xt(h,c);if(w===void 0)return r.push(`${a}\uFF1A\u5F15\u7528\u7247\u6BB5\u4E0D\u5B58\u5728\uFF1A${i}`),null;let k=await s(structuredClone(w),a,[...l,f]),b=St(e,c,k,m);return b?{$ref:`#/components/schemas/${b}`}:k};return await s(e,"#",[]),r}async function ht(e,t){if(t.docs.has(e))return t.docs.get(e);let r=await Me(e,{},{specSourceUrl:t.baseUrl},t.resolve,t.fetchImpl);if(!r?.ok)return t.errors.push(`\u5916\u90E8\u5F15\u7528\u62C9\u53D6\u5931\u8D25\uFF1A${e}`),null;let n=await r.text();try{let s=JSON.parse(n);return t.docs.set(e,s),s}catch{return t.errors.push(`\u5916\u90E8\u5F15\u7528\u6587\u6863\u4EC5\u652F\u6301 JSON \u683C\u5F0F\uFF1A${e}`),null}}function xt(e,t){if(!t||t==="/")return e;let r=e;for(let n of t.replace(/^\//,"").split("/")){if(r===null||typeof r!="object")return;let s=decodeURIComponent(n).replace(/~1/g,"/").replace(/~0/g,"~");r=r[s]}return r}function St(e,t,r,n){let s=t.match(/^\/components\/schemas\/([^/]+)$/);if(!s)return null;let o=decodeURIComponent(s[1]).replace(/~1/g,"/").replace(/~0/g,"~");e.components=e.components??{},e.components.schemas=e.components.schemas??{};let i=e.components.schemas;if(i[o]===void 0)return i[o]=r,o;if(JSON.stringify(i[o])===JSON.stringify(r))return o;let a=(n.split("/").pop()??"ref").replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_$]/g,"_")||"ref",l=`${o}_${a}`,u=2;for(;i[l]!==void 0&&JSON.stringify(i[l])!==JSON.stringify(r);)l=`${o}_${a}_${u}`,u+=1;return i[l]=r,l}async function Te(e,t={}){let r=await yt(e,t);return gt(e),{errors:[...r,...dt(e)]}}import H from"fs";import $t from"os";import U from"path";var wt="swagger2api.json",Nt=".swagger2apirc.json",Rt="swagger2api.local.json",bt=".swagger2apirc.local.json",Ct=".swagger2api.json",kt=".swagger2apirc.json";function ye(e,t,r){let n={layer:t,file:e,hit:!1,sections:[],config:null};if(!e||!H.existsSync(e))return n;try{let s=JSON.parse(H.readFileSync(e,"utf8"));return!s||typeof s!="object"||Array.isArray(s)?(r.push(`${e}\uFF1A\u6839\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5C42`),{...n,hit:!1}):{layer:t,file:e,hit:!0,sections:Object.keys(s),config:s}}catch(s){return r.push(`${e}\uFF1A\u89E3\u6790\u5931\u8D25\uFF08${s.message}\uFF09\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5C42`),n}}function Et(e,t){if(!e)return t?{...t}:null;if(!t)return{...e};let r={...e};for(let[n,s]of Object.entries(t))r[n]=s;return r}function vt(e,t){if(!e)return t?{...t}:null;if(!t)return{...e};let r={...e};for(let[n,s]of Object.entries(t)){let o=r[n];r[n]=o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?{...o,...s}:s}return r}function Ge(e,t){let[r,...n]=e,s=U.resolve(t);for(;;){let o=U.join(s,r);if(H.existsSync(o)){let l=n.map(u=>U.join(s,u)).find(u=>H.existsSync(u))??null;return{file:o,ignored:l}}let i=n.map(l=>U.join(s,l)).find(l=>H.existsSync(l));if(i)return{file:i,ignored:null};let a=U.dirname(s);if(a===s)return null;s=a}}function _e(e=process.cwd(),t={}){let r=[],n=t.homeDir??$t.homedir(),s=U.join(n,Ct),o=U.join(n,kt),i=H.existsSync(s)?{file:s,ignored:H.existsSync(o)?o:null}:H.existsSync(o)?{file:o,ignored:null}:null,a=t.projectFile?{file:U.resolve(t.projectFile),ignored:null}:Ge([wt,Nt],e),l=Ge([Rt,bt],e);for(let f of[i,a,l])f?.ignored&&r.push(`${f.file}\uFF1A\u540C\u65F6\u5B58\u5728\u65E7\u914D\u7F6E ${f.ignored}\uFF0C\u5DF2\u6309\u65B0\u6587\u4EF6\u540D\u751F\u6548\uFF0C\u5EFA\u8BAE\u5220\u9664\u65E7\u6587\u4EF6`);let u=ye(i?.file??null,"\u5168\u5C40\u5C42",r),p=ye(a?.file??null,"\u9879\u76EE\u5C42",r),c=ye(l?.file??null,"\u672C\u5730\u5C42",r),m=vt(Et(u.config,p.config),c.config);return{global:u,project:p,local:c,merged:m,warnings:r}}var jt=[{env:"FX_S2A_INPUT",key:"input.url",type:"string"},{env:"FX_S2A_OUTPUT",key:"output.dir",type:"string"},{env:"FX_S2A_NAME",key:"output.name",type:"string"},{env:"FX_S2A_CLIENT",key:"client.type",type:"string"},{env:"FX_S2A_LANGUAGE",key:"language.target",type:"string"},{env:"FX_S2A_CLEAN",key:"output.clean",type:"boolean"}];function Ft(e,t,r){let n=t.split("."),s=e;n.forEach((o,i)=>{if(i===n.length-1){s[o]=r;return}(!s[o]||typeof s[o]!="object")&&(s[o]={}),s=s[o]})}function Be(e,t=process.env){let r=e?structuredClone(e):{};for(let n of jt){let s=t[n.env];s===void 0||s===""||Ft(r,n.key,n.type==="boolean"?!["0","false"].includes(s.toLowerCase()):s)}return r}var At=["url","file","name","mode","responses","query","extractResponseRaw","pathPrefixIndex","convertGetToQuery","dropPathParams","tagRewrite"];function he(e){if(!e||typeof e!="object"||Array.isArray(e))return{};if(typeof e.url!="string"&&typeof e.file!="string")return e;let t={...e};t.input={...e.input&&typeof e.input=="object"?e.input:{},...typeof e.url=="string"?{url:e.url}:{},...typeof e.file=="string"?{file:e.file}:{}};let r={...e.output&&typeof e.output=="object"?e.output:{},...typeof e.output=="string"?{dir:e.output}:{}};r.name=e.name??r.name??"index",r.mode=e.mode??r.mode??"single",r.prune=r.prune??r.mode==="grouped",t.output=r,t.client=typeof e.client=="string"?{type:e.client}:{...e.client??{}},t.language=typeof e.language=="string"?{target:e.language}:{...e.language??{}},t.types={...e.types??{}},e.responses!==void 0&&(t.types.responses=e.responses),e.extractResponseRaw!==void 0&&(t.types.extractResponseRaw=e.extractResponseRaw),e.query!==void 0&&(t.types.extractQuery=Array.isArray(e.query)?e.query.join(","):e.query),t.naming={...e.naming??{}};for(let n of["pathPrefixIndex","convertGetToQuery","dropPathParams","tagRewrite"])e[n]!==void 0&&(t.naming[n]=e[n]);if(r.mode==="grouped"){let n={...e.grouping??{}};n.strategy=n.strategy??["path"],n.pathDepth=n.pathDepth??t.naming.pathPrefixIndex??0,n.split=n.split??!0,t.grouping=n}for(let n of At)delete t[n];return t}function Ue(e,t){let r=e?structuredClone(e):{};if(!t)return r;let n=r.profiles?.[t];if(!n||typeof n!="object")return r;for(let[s,o]of Object.entries(n)){if(s==="profiles")continue;let i=r[s];r[s]=i&&typeof i=="object"&&!Array.isArray(i)&&o&&typeof o=="object"&&!Array.isArray(o)?{...i,...o}:o}return r}function He(e=process.argv.slice(2)){let t=r=>r.reduce((n,s)=>n??(e.includes(s)?e[e.indexOf(s)+1]:void 0),void 0);return{configFile:t(["--config","-c"]),profile:t(["--profile"])}}import{createHash as Gt}from"crypto";import C from"fs";import _t from"os";import F from"path";var j="client",E="types",q="shared",ne=["data-contracts","http-client"],Ot=new Set(["index",j,E,q]),Lt=new Set(["HttpClient","RequestParams","ContentType","AxiosRequestConfig","AxiosResponse","Array","ArrayBuffer","Blob","Boolean","Date","Document","Element","Error","Event","File","FileList","FormData","Headers","Image","Map","Node","Number","Object","Promise","ReadableStream","RegExp","Request","Response","Set","String","URL","Window"]),Je=new Set(["instance","request","setSecurityData","mergeRequestParams","stringifyFormItem","createFormData","securityData","securityWorker","secure","format","constructor","prototype"]),Pt=new Set(["con","prn","aux","nul",...Array.from({length:9},(e,t)=>`com${t+1}`),...Array.from({length:9},(e,t)=>`lpt${t+1}`)]),qe=64;function _(e){return String(e).normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"")}function It(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(" ").filter(Boolean)}function Dt(e){let t=e.normalize("NFKC"),r=[];for(let n of t.matchAll(/[A-Za-z0-9]+|[\p{L}\p{N}]+/gu)){let s=n[0];/^[A-Za-z0-9]+$/.test(s)?r.push(...It(s)):r.push(s)}return r}function Mt(e){return e.map((t,r)=>{if(/^[A-Za-z0-9]+$/.test(t)){let n=t.toLowerCase();return r===0?n:n.charAt(0).toUpperCase()+n.slice(1)}return t}).join("")}function Tt(e){let t=2166136261;for(let r of e)t^=r.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").slice(0,6)}function re(e){let t=[],r=Dt(e),n=Mt(r);return n?(/^[0-9]/.test(n)&&(n=`g${n}`,t.push("\u6570\u5B57\u5F00\u5934")),[...n].length>qe&&(n=[...n].slice(0,qe-6).join("")+Tt(e),t.push("\u8D85\u957F\u622A\u65AD")),{slug:n,reason:t.join("\u3001")}):{slug:"",reason:"\u540D\u79F0\u4E0D\u542B\u53EF\u7528\u5B57\u7B26"}}function K(e){return e.charAt(0).toUpperCase()+e.slice(1)}function xe(e,t={}){let r=[],n=[],s=[...new Set(e)].sort((d,h)=>d<h?-1:d>h?1:0),o=new Map,i=new Set;for(let[d,h]of Object.entries(t))o.set(d,h),o.set(_(d),h);let a=new Set,l=new Set,u=[],p=(d,h=2)=>{let w=d,k=h;for(;a.has(w.toLowerCase());)w=`${d}${k}`,k+=1;return a.add(w.toLowerCase()),w},c=d=>{let h=d,w=2;for(;l.has(h)||Je.has(h.toLowerCase());)h=`${d}${w}`,w+=1;return l.add(h),h},m=new Map;for(let d of s){let h=o.get(d)??o.get(_(d));if(h===void 0)continue;i.add(d),i.add(_(d));let{slug:w}=re(h);if(!w){r.push(`\u624B\u5DE5\u540D\u4E0D\u53EF\u7528\uFF1A${d} \u2192 ${h}`);continue}let k=m.get(w.toLowerCase());k?r.push(`\u624B\u5DE5\u540D\u51B2\u7A81\uFF1A${k} \u4E0E ${d} \u90FD\u6307\u5411 ${w}`):m.set(w.toLowerCase(),d);let b=p(w);l.add(b);let I=K(b);u.push({raw:d,key:_(d),fileName:I,className:I,property:b,reason:b===w?"\u624B\u5DE5\u6307\u5B9A":"\u624B\u5DE5\u6307\u5B9A\u3001\u4E0E\u5DF2\u6709\u7EC4\u91CD\u540D",source:"manual"})}let f=1;for(let d of s){if(u.some(ot=>ot.raw===d))continue;let{slug:h,reason:w}=re(d),k=!h,b=h;if(k){for(;a.has(`group${f}`.toLowerCase());)f+=1;b=`group${f}`,f+=1}let I=Ot.has(b.toLowerCase())||Pt.has(b.toLowerCase()),g=Lt.has(K(b)),N=Je.has(b.toLowerCase()),A=[w],v,J;N||I?(v=p(`${b}2`,3),J=c(v),A.push(N?"\u4E0E\u805A\u5408\u6210\u5458\u540C\u540D":"\u4E0E\u4FDD\u7559\u540D\u51B2\u7A81")):g?(v=p(`${b}2`,3),J=c(b),A.push("\u4E0E\u5168\u5C40\u7C7B\u578B\u540C\u540D")):(v=p(b),J=c(v),v!==b&&A.push("\u4E0E\u5DF2\u6709\u7EC4\u91CD\u540D"));let je=K(v);u.push({raw:d,key:_(d),fileName:je,className:je,property:J,reason:A.filter(Boolean).join("\u3001"),source:k?"fallback":"auto"})}for(let d of Object.keys(t))!i.has(d)&&!i.has(_(d))&&n.push(`grouping.names \u4E2D\u7684\u952E\u672A\u51FA\u73B0\u5728\u672C\u6B21\u5206\u7EC4\u7ED3\u679C\uFF1A${d}`);return{entries:u,errors:r,warnings:n}}function We(e){let t={};for(let r of e)t[r.fileName]=r.className,t[r.fileName.charAt(0).toLowerCase()+r.fileName.slice(1)]=r.className;return t}function se(e,t,r,n=[]){let s=new Set([...t.flatMap(i=>[`${i.fileName}${r}`,`${i.importFrom??i.fileName}${r}`]),...n.map(i=>`${i}${r}`)]),o=new Set([`index${r}`,"index.d.ts",`${j}${r}`,`route-types${r}`,`${E}/index${r}`,...ne.flatMap(i=>[`${i}${r}`,`${i}.d.ts`])]);return e.filter(i=>i.endsWith(r)&&!i.endsWith(`.d${r}`)&&!s.has(i)&&!o.has(i)&&!i.endsWith(`_Route${r}`))}var Bt=new Set(["index","shared","types",j,...ne]);function W(e){let t=Gt("sha1").update(F.resolve(e)).digest("hex").slice(0,12);return F.join(_t.tmpdir(),"swagger2api",`${t}.json`)}function Ut(e){return String(e).split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Ht(e,t){if(!C.existsSync(e))return[];let r=[];for(let n of C.readdirSync(e)){if(!n.endsWith(t)||n.endsWith(`.d${t}`))continue;let s=n.slice(0,-t.length);if(Bt.has(s.toLowerCase())||s.endsWith("Route"))continue;let o=Ut(s);r.push({base:s,className:o,property:o.charAt(0).toLowerCase()+o.slice(1)})}return r.sort((n,s)=>n.base.localeCompare(s.base))}function ze(e){return e.map(t=>({base:t.fileName,className:t.className,property:t.property,importFrom:t.importFrom}))}function oe(e){if(!C.existsSync(e))return null;try{let t=JSON.parse(C.readFileSync(e,"utf8"));return{files:Array.isArray(t.files)?t.files.map(String):[]}}catch{return null}}function ie(e,t,r,n=[]){let s=r?".js":".ts",i=["index",`${E}/index`,j,"route-types",...t.flatMap(u=>[u.fileName,u.importFrom??u.fileName]),...n].flatMap(u=>r?[`${u}${s}`,`${u}.d.ts`]:[`${u}${s}`]),a=F.join(e,E),l=C.existsSync(a)?C.readdirSync(a).filter(u=>u.endsWith(".ts")||u.endsWith(".js")).map(u=>`${E}/${u}`):[];return[...new Set([...i,...l])].filter(u=>C.existsSync(F.join(e,u))).sort()}function Ke(e,t){let r=t?[".js",".d.ts"]:[".ts"],n=[];for(let s of ne)for(let o of r){let i=`${s}${o}`;C.existsSync(F.join(e,i))&&(C.rmSync(F.join(e,i)),n.push(i))}return n}function Se(e,t){C.mkdirSync(F.dirname(e),{recursive:!0}),C.writeFileSync(e,`${JSON.stringify({files:t},null,2)}
2
- `)}function $e(e,t,r){if(!t)return[];let n=new Set(r),s=[];for(let o of t.files){if(n.has(o))continue;let i=F.join(e,o);C.existsSync(i)&&(C.rmSync(i),s.push(o))}return s}function Ve(e,t,r,n,s=[]){let o=r?".js":".ts",i=new Set(n?.files??[]);return[...new Set([j,`${E}/index`,...t.flatMap(l=>[l.fileName,l.importFrom??l.fileName]),...s])].flatMap(l=>r?[`${l}${o}`,`${l}.d.ts`]:[`${l}${o}`]).filter(l=>C.existsSync(F.join(e,l))&&!i.has(l))}function Jt(e,t,r,n){let s=t||"Api",o=p=>p.className===s?`${p.className}Module`:p.className,i=new Map;for(let p of e){let c=p.importFrom??p.base,m=i.get(c);m?m.push(p):i.set(c,[p])}let a=[...i.entries()].map(([p,c])=>{let m=`${r?`${r.replace(/\\/g,"/")}/`:""}${p}`;return`import { ${c.map(d=>{let h=o(d);return h===d.className?d.className:`${d.className} as ${h}`}).join(", ")} } from "./${m}"`}),l=e.map(p=>`${p.property} = new ${o(p)}(this)`);return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${j}"`,...a,`export * from "./${E}"`,`export * from "./${j}"`,"","/** \u805A\u5408\u5165\u53E3\uFF1A\u5404\u6A21\u5757\u5171\u4EAB\u540C\u4E00\u4E2A\u8BF7\u6C42\u5B9E\u4F8B */",n?`export class ${s} extends HttpClient {`:`export class ${s}<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {`,...l.map(p=>` ${p}`),"",n?" constructor(config) {":" constructor(config?: any) {"," super(config)"," }","}",""].join(`
3
- `)}function we(e,t,r,n){let s=r?".js":".ts",o=n??Ht(e,s);if(o.length===0)return[];let i=Jt(o,t,"",r),a=[],l=F.join(e,`index${s}`);if(C.writeFileSync(l,i),a.push(l),r){let u=qt(o,t),p=F.join(e,"index.d.ts");C.writeFileSync(p,u),a.push(p)}return a}function Ne(e,t,r,n={}){let s=r?".js":".ts",o=[],i=new Map;for(let u of t){let p=u.importFrom??u.fileName,c=i.get(p);c?c.push(u):i.set(p,[u])}for(let[u,p]of i){let c=F.join(e,`${u}${s}`);if(!C.existsSync(c)){p.forEach(f=>o.push(`\u7F3A\u5C11\u6A21\u5757\u6587\u4EF6\uFF1A\u671F\u671B ${u}${s}\uFF08\u539F\u59CB\u7EC4\u540D ${f.raw}\uFF09`));continue}let m=C.readFileSync(c,"utf8");for(let f of p)m.includes(`class ${f.className}`)||o.push(`\u7C7B\u540D\u4E0E\u547D\u540D\u8868\u4E0D\u4E00\u81F4\uFF1A${u}${s} \u671F\u671B ${f.className}`)}let a=[`${j}${s}`,`${E}/index${s}`,...r?[`${j}.d.ts`,`${E}/index.d.ts`]:[]];for(let u of a)C.existsSync(F.join(e,u))||o.push(`\u7F3A\u5C11\u56FA\u5B9A\u4EA7\u7269\uFF1A${u}`);if(n.aggregate!==!1){let u=F.join(e,`index${s}`);if(!C.existsSync(u))o.push(`\u7F3A\u5C11\u805A\u5408\u5165\u53E3\uFF1Aindex${s}`);else{let p=C.readFileSync(u,"utf8");for(let c of t)p.includes(`${c.property} = new `)||o.push(`\u805A\u5408\u5165\u53E3\u7F3A\u5C11\u6A21\u5757\u6302\u8F7D\uFF1A${c.property}`)}}let l=C.existsSync(e)?se(C.readdirSync(e),t,s,n.extraFiles??[]):[];return{errors:o,orphans:l}}function qt(e,t){let r=t||"Api",n=a=>a.className===r?`${a.className}Module`:a.className,s=new Map;for(let a of e){let l=a.importFrom??a.base,u=s.get(l);u?u.push(a):s.set(l,[a])}let o=[...s.entries()].map(([a,l])=>`import { ${l.map(p=>{let c=n(p);return c===p.className?p.className:`${p.className} as ${c}`}).join(", ")} } from "./${a}"`),i=e.map(a=>` ${a.property}: ${n(a)}`);return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${j}"`,...o,`export * from "./${E}"`,`export * from "./${j}"`,"",`export declare class ${r}<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {`,...i," constructor(config?: any)","}",""].join(`
4
- `)}function Wt(e){return e.filter(t=>t.chunks.length>0).map(t=>({fileName:t.fileName,className:t.className,title:t.raw,chunks:t.chunks.map(r=>({fileName:r.fileName,className:r.className}))}))}function zt(e){let t=e.chunks.map(s=>`import { ${s.className} } from "./${s.fileName}"`),r=e.chunks.map(s=>`new ${s.className}(http)`).join(", "),n=e.chunks.map(s=>`${s.className}<SecurityDataType>`).join(", ");return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${j}"`,...t,"",`/** ${e.title} \u6A21\u5757\uFF1A\u7531\u5206\u7247\u5408\u5E76\uFF0C\u5BF9\u5916\u4E0E\u5355\u6587\u4EF6\u4EA7\u7269\u4E00\u81F4 */`,`export class ${e.className}<SecurityDataType = unknown> {`," /** \u5171\u4EAB\u8BF7\u6C42\u5668\uFF1A\u7531\u805A\u5408\u5165\u53E3\u6CE8\u5165\uFF1B\u4EC5\u4F9B\u6A21\u5757\u5185\u90E8\u8C03\u7528\uFF0C\u52FF\u5728\u4E1A\u52A1\u4FA7\u76F4\u63A5\u4F7F\u7528 */"," http: HttpClient<SecurityDataType>",""," constructor(http: HttpClient<SecurityDataType>) {"," this.http = http",` Object.assign(this, ${r})`," }",""," /** \u5E95\u5C42\u8BF7\u6C42\u5B9E\u4F8B\uFF1A\u4E0E\u805A\u5408\u5165\u53E3\u4FDD\u6301\u540C\u4E00\u4E2A */",' get instance(): HttpClient<SecurityDataType>["instance"] {'," return this.http.instance"," }","}","","/** \u7C7B\u578B\u5408\u5E76\uFF1A\u5206\u7247\u6210\u5458\u4E0E\u5355\u6587\u4EF6\u4EA7\u7269\u4FDD\u6301\u540C\u4E00\u547D\u540D\u7A7A\u95F4 */",`export interface ${e.className}<SecurityDataType = unknown> extends ${n} {}`,""].join(`
5
- `)}function Kt(e){let t=e.chunks.map(n=>`import { ${n.className} } from "./${n.fileName}"`),r=e.chunks.map(n=>`new ${n.className}(http)`).join(", ");return["/* eslint-disable */","/* tslint:disable */",...t,"",`/** ${e.title} \u6A21\u5757\uFF1A\u7531\u5206\u7247\u5408\u5E76\uFF0C\u5BF9\u5916\u4E0E\u5355\u6587\u4EF6\u4EA7\u7269\u4E00\u81F4 */`,`export class ${e.className} {`," constructor(http) {"," this.http = http",` Object.assign(this, ${r})`," }",""," get instance() {"," return this.http.instance"," }","}",""].join(`
6
- `)}function Vt(e){let t=e.chunks.map(n=>`import { ${n.className} } from "./${n.fileName}"`),r=e.chunks.map(n=>`${n.className}<SecurityDataType>`).join(", ");return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${j}"`,...t,"",`export interface ${e.className}<SecurityDataType = unknown> extends ${r} {}`,`export declare class ${e.className}<SecurityDataType = unknown> {`," constructor(http: HttpClient<SecurityDataType>)","}",""].join(`
7
- `)}function Ye(e,t,r){let n=[];for(let s of Wt(t))if(r){let o=`${s.fileName}.js`;C.writeFileSync(F.join(e,o),Kt(s)),n.push(o);let i=`${s.fileName}.d.ts`;C.writeFileSync(F.join(e,i),Vt(s)),n.push(i)}else{let o=`${s.fileName}.ts`;C.writeFileSync(F.join(e,o),zt(s)),n.push(o)}return n}var Yt=["get","post","put","delete","patch","head","options"],Qt=["index","data-contracts","http-client","route-types"];function Xt(e,t,r){let n=r.strategy?.length?r.strategy:["rules","tag","path"],s=r.fallback??"misc";for(let o of n)if(o==="rules")for(let[i,a]of(r.rules??[]).entries()){let l=a.match??{};if(l.prefix&&e.startsWith(l.prefix))return{group:a.group,source:"rules",ruleIndex:i};if(l.regex&&new RegExp(l.regex).test(e))return{group:a.group,source:"rules",ruleIndex:i};if(l.tag&&(t.tags??[]).includes(l.tag))return{group:a.group,source:"rules",ruleIndex:i};if(l.operationId&&t.operationId===l.operationId)return{group:a.group,source:"rules",ruleIndex:i}}else if(o==="tag"){let i=(t.tags??[])[0];if(i)return{group:String(i),source:"tag"}}else if(o==="path"){let i=e.split("/").filter(Boolean),a=r.pathDepth??0;if(i[a])return{group:i[a],source:"path"}}return{group:s,source:"fallback"}}function Qe(e,t){let r=t.fallback??"misc",n=[],s=new Set;for(let[c,m]of Object.entries(e.paths??{}))for(let f of Yt){let d=m[f];if(!d||typeof d!="object")continue;let h=Xt(c,d,t);h.ruleIndex!==void 0&&s.add(h.ruleIndex),n.push({path:c,method:f,operation:d,group:h.group,ruleIndex:h.ruleIndex})}if(t.collapse){let c=new Map;for(let m of[...new Set(n.map(f=>f.group))].sort()){let f=_(m);f&&!c.has(f)&&c.set(f,m)}n.forEach(m=>{let f=c.get(_(m.group));f&&(m.group=f)})}if(t.split!==void 0&&t.split!==!1){let c=xe(n.map(f=>f.group),t.names),m=typeof t.split=="object"?t.split:{};return er(n,t,m,c,s)}let o=new Map;n.forEach(({group:c})=>o.set(c,(o.get(c)??0)+1));for(let c of n){let m=o.get(c.group)??0;if(t.minRoutes&&m<t.minRoutes&&c.group!==r)c.group=r;else if(t.maxRoutes&&m>t.maxRoutes){let d=c.path.split("/").filter(Boolean)[(t.pathDepth??0)+1];d&&(c.group=`${c.group}_${d}`)}}let i=xe(n.map(c=>c.group),t.names),a=new Map(i.entries.map(c=>[c.raw,c])),l={},u={};for(let c of n){let m=Array.isArray(c.operation.tags)?c.operation.tags.join(", "):"";m&&(l[`${c.method.toUpperCase()}:${c.path}`]=m);let f=a.get(c.group);f&&(c.operation.tags=[f.fileName]),u[c.group]=(u[c.group]??0)+1}let p=Array.from({length:t.rules?.length??0},(c,m)=>m).filter(c=>!s.has(c));return{counts:u,originalTags:l,entries:i.entries,unmatchedRules:p,errors:i.errors,warnings:i.warnings}}function Zt(e,t){let r=(s,o,i)=>s===void 0?o:!Number.isFinite(s)||s<1?(t.push(`grouping.split.${i} \u65E0\u6548\uFF08${s}\uFF09\uFF0C\u56DE\u843D\u5230 ${o}`),o):Math.floor(s),n=[];if(e.categories!==void 0&&!Array.isArray(e.categories))t.push("grouping.split.categories \u5FC5\u987B\u662F\u6570\u7EC4\uFF0C\u5DF2\u5FFD\u7565");else for(let s of e.categories??[]){if(!s||typeof s.name!="string"||!s.name){t.push("grouping.split.categories \u5B58\u5728\u7F3A\u5C11 name \u7684\u9879\uFF0C\u5DF2\u5FFD\u7565");continue}let o=s.match?.regex;if(o)try{new RegExp(o)}catch{t.push(`grouping.split.categories \u7684\u6B63\u5219\u65E0\u6548\uFF08${s.name}\uFF1A${o}\uFF09\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u9879`);continue}n.push(s)}return{minRoutes:r(e.minRoutes,150,"minRoutes"),targetRoutes:r(e.targetRoutes,300,"targetRoutes"),maxRoutes:r(e.maxRoutes,450,"maxRoutes"),minBucketRoutes:r(e.minBucketRoutes,60,"minBucketRoutes"),categories:n,fallback:typeof e.fallback=="string"&&e.fallback?e.fallback:"misc"}}function er(e,t,r,n,s){let o=[...n.warnings];(t.minRoutes!==void 0||t.maxRoutes!==void 0)&&o.push("\u5DF2\u542F\u7528 grouping.split\uFF0C\u5FFD\u7565 grouping.minRoutes / grouping.maxRoutes\uFF0C\u9608\u503C\u6539\u7531 grouping.split \u63D0\u4F9B");let i=Zt(r,o),a=new Map(n.entries.map(g=>[g.raw,g])),l=new Map;for(let g of e){let N=l.get(g.group);N?N.push(g):l.set(g.group,[g])}let u=n.entries.map(g=>({raw:g.raw,fileName:g.fileName,className:g.className,routes:l.get(g.raw)?.length??0,bucket:null,chunks:[]})),p=new Set(Qt.map(g=>g.toLowerCase()));u.filter(g=>g.routes>i.maxRoutes).forEach(g=>p.add(g.fileName.toLowerCase()));for(let g of u){if(g.routes<=i.maxRoutes)continue;let N=l.get(g.raw)??[];g.chunks=rr(g,N,t.pathDepth??0,i,p)}let c=e.length,m=or(u.filter(g=>g.chunks.length===0),c,i,p,o),f=new Map(u.map(g=>[g.raw,g]));for(let g of m)g.namespaces.forEach(N=>{let A=f.get(N);A&&(A.bucket=g.fileName)});let d={},h={};for(let g of e){let N=a.get(g.group),A=f.get(g.group);if(!N||!A)continue;let v=Array.isArray(g.operation.tags)?g.operation.tags.join(", "):"";v&&(d[`${g.method.toUpperCase()}:${g.path}`]=v);let J=g.splitTag??A.bucket;J&&(g.operation.tags=[J,N.fileName]),h[g.group]=(h[g.group]??0)+1}for(let g of u){let N=a.get(g.raw);N&&(N.importFrom=g.chunks.length?g.fileName:g.bucket??g.fileName)}let w={},k=(g,N)=>{w[g]=N,w[g.charAt(0).toLowerCase()+g.slice(1)]=N};n.entries.forEach(g=>k(g.fileName,g.className)),u.forEach(g=>g.chunks.forEach(N=>k(N.fileName,N.className)));let b={};for(let g of m){let N=g.namespaces.map(A=>{let v=f.get(A);return{tag:v.fileName,className:v.className,title:v.raw,routes:v.routes}});b[g.fileName]=N,b[g.fileName.charAt(0).toLowerCase()+g.fileName.slice(1)]=N}let I=Array.from({length:t.rules?.length??0},(g,N)=>N).filter(g=>!s.has(g));return{counts:h,originalTags:d,entries:n.entries,unmatchedRules:I,errors:n.errors,warnings:o,split:{total:c,buckets:m,namespaces:u,bucketLayout:b},moduleClassNames:w}}function tr(e,t,r){let n=e.split("/").filter(Boolean),s=n.indexOf(t),o=s>=0?s+1:r+1;for(let i=o;i<n.length;i+=1){let a=n[i];if(!/^v\d+$/i.test(a)&&!/^\{.*\}$/.test(a))return a}return"rest"}function rr(e,t,r,n,s){let o=new Map;for(let l of t){let u=tr(l.path,e.raw,r),p=o.get(u);p?p.push(l):o.set(u,[l])}let i=[],a={items:[],categories:new Set};for(let[l,u]of[...o.entries()].sort(([p],[c])=>p<c?-1:p>c?1:0))for(let p of u)a.items.length>=n.targetRoutes&&(i.push(a),a={items:[],categories:new Set}),a.items.push(p),a.categories.add(l);return a.items.length&&i.push(a),i.map((l,u)=>{let p=u+1,c=`${e.className}Part${p}`;for(;s.has(c.toLowerCase());)p+=1,c=`${e.className}Part${p}`;return s.add(c.toLowerCase()),l.items.forEach(m=>{m.splitTag=c}),{tag:c,fileName:c,className:c,routes:l.items.length,categories:[...l.categories].sort()}})}function nr(e,t){let r=t.match??{};return!!(r.prefix&&e.raw.startsWith(r.prefix)||r.regex&&new RegExp(r.regex).test(e.raw))}function Xe(e,t){let r=e,n=2;for(;t.has(r.toLowerCase());)r=`${e}${n}`,n+=1;return t.add(r.toLowerCase()),r}function sr(e,t){let r=0;for(;e.length>1&&r<e.length;){let n=e[r];if(n.routes>=t.minBucketRoutes){r+=1;continue}let s=e[r-1];if(s&&s.routes+n.routes<=t.maxRoutes){s.plans.push(...n.plans),s.routes+=n.routes,e.splice(r,1),r=Math.max(r-1,0);continue}let o=e[r+1];if(o&&o.routes+n.routes<=t.maxRoutes){o.plans.unshift(...n.plans),o.routes+=n.routes,e.splice(r,1);continue}r+=1}}function Re(e,t,r,n){let s=[],o=[],i=0;for(let a of e)i>0&&i+a.routes>r.targetRoutes&&(s.push({plans:o,routes:i}),o=[],i=0),o.push(a),i+=a.routes;return o.length&&s.push({plans:o,routes:i}),sr(s,r),s.map(a=>{let l=t?K(re(t).slug||"bucket"):s.length===1?"Modules":a.plans[0].fileName,u=Xe(l,n);return{fileName:u,className:u,category:t,routes:a.routes,namespaces:a.plans.map(p=>p.raw)}})}function or(e,t,r,n,s){if(e.length===0)return[];if(t<=r.minRoutes){let l=Xe("Modules",n),u=e.reduce((p,c)=>p+c.routes,0);return[{fileName:l,className:l,category:"",routes:u,namespaces:e.map(p=>p.raw)}]}if(r.categories.length===0)return Re(e,"",r,n);let o=[],i=new Set(e.map(l=>l.raw));for(let l of r.categories){let u=e.filter(p=>i.has(p.raw)&&nr(p,l));u.forEach(p=>i.delete(p.raw)),u.length&&o.push(...Re(u,l.name,r,n))}let a=e.filter(l=>i.has(l.raw));return a.length&&(s.push(`\u672A\u547D\u4E2D\u5206\u7C7B\u7684\u547D\u540D\u7A7A\u95F4\u5F52\u5165 ${r.fallback}\uFF1A${a.map(l=>l.raw).join("\u3001")}`),o.push(...Re(a,r.fallback,r,n))),o}import V from"fs";import B from"path";import $ from"typescript";var Ee=`${E}/index`;function ir(e){return $.isInterfaceDeclaration(e)||$.isTypeAliasDeclaration(e)||$.isEnumDeclaration(e)||$.isClassDeclaration(e)||$.isFunctionDeclaration(e)||$.isVariableStatement(e)}function ke(e){if($.isVariableStatement(e)){let r=e.declarationList.declarations[0];return r&&$.isIdentifier(r.name)?r.name.text:null}let t=e;return t.name&&$.isIdentifier(t.name)?t.name.text:null}function ar(e){return $.canHaveModifiers(e)?!!$.getModifiers(e)?.some(t=>t.kind===$.SyntaxKind.ExportKeyword):!1}function cr(e,t){let r={target:$.ScriptTarget.ESNext,module:$.ModuleKind.ESNext,noResolve:!0,skipLibCheck:!0,noEmit:!0},n=$.createCompilerHost(r),s=n.getSourceFile.bind(n),o=$.createSourceFile(e,t,$.ScriptTarget.Latest,!0,$.ScriptKind.TS);n.getSourceFile=(a,l,u,p)=>a===e?o:s(a,l,u,p);let i=$.createProgram({rootNames:[e],options:r,host:n});return{sourceFile:o,checker:i.getTypeChecker()}}function lr(e,t=`${E}/index.ts`){let{sourceFile:r,checker:n}=cr(t,e),s=new Map,o=r.statements.filter(ir),i=new Set;for(let p of o){let c=ke(p);c&&(s.set(p,c),i.add(c))}let a=r.statements[0],l=a?e.slice(0,a.getStart(r)).trimEnd():"",u=[];for(let p of o){let c=ke(p);if(!c)continue;let m=ar(p),f=p.getStart(r,!0),d=p.getStart(r)-f,h=e.slice(f,p.getEnd()),w=m?h:`${h.slice(0,d)}export ${h.slice(d)}`,k=new Set,b=I=>{if($.isIdentifier(I)&&I.text!==c&&i.has(I.text)){let N=n.getSymbolAtLocation(I)?.declarations?.find(v=>s.has(v)),A=N?s.get(N):void 0;A&&A!==c&&k.add(A)}$.forEachChild(I,b)};b(p),u.push({name:c,value:$.isEnumDeclaration(p),exported:m,text:w,refs:k})}return{header:l,declarations:u}}function ur(e,t="module.ts"){let r=$.createSourceFile(t,e,$.ScriptTarget.Latest,!0,$.ScriptKind.TS),n=new Set;for(let s of r.statements){if(!$.isImportDeclaration(s)||!$.isStringLiteral(s.moduleSpecifier)||!s.moduleSpecifier.text.endsWith(Ee))continue;let i=s.importClause?.namedBindings;if(!(!i||!$.isNamedImports(i)))for(let a of i.elements)n.add((a.propertyName??a.name).text)}return n}function pr(e,t){let r=new Set(e.map(i=>i.name)),n=new Map;for(let i of e)n.set(i.name,new Set);for(let i of t)for(let a of ur(i.source,`${i.file}.ts`))r.has(a)&&n.get(a)?.add(i.file);let s=!0;for(;s;){s=!1;for(let i of e){let a=n.get(i.name);if(a)for(let l of i.refs){let u=n.get(l);if(u)for(let p of a)u.has(p)||(u.add(p),s=!0)}}}let o=new Map;for(let i of e){let a=n.get(i.name)??new Set;o.set(i.name,a.size===1?[...a][0]:q)}return o}function fr(e,t,r,n,s){let o=new Map;for(let a of t)for(let l of a.refs){let u=r.get(l);if(!u||u===e)continue;let p=o.get(u)??{values:[],types:[]};!s&&n.has(l)?p.values.push(l):p.types.push(l),o.set(u,p)}let i=[];for(let[a,l]of[...o.entries()].sort(([u],[p])=>u.localeCompare(p)))l.values.length&&i.push(`import { ${[...new Set(l.values)].sort().join(", ")} } from "./${a}"`),l.types.length&&i.push(`import type { ${[...new Set(l.types)].sort().join(", ")} } from "./${a}"`);return i}function be(e,t,r){let n=new Map;for(let o of e){if(!o.exported||r.runtimeOnly&&!o.value)continue;let i=t.get(o.name)??q,a=n.get(i)??{values:[],types:[]};o.value?a.values.push(o.name):a.types.push(o.name),n.set(i,a)}let s=[];for(let[o,i]of[...n.entries()].sort(([a],[l])=>a.localeCompare(l)))i.values.length&&s.push(`export { ${i.values.join(", ")} } from "./${o}"`),i.types.length&&s.push(`export type { ${i.types.join(", ")} } from "./${o}"`);return s}function mr(e,t,r){let n=new Map;for(let l of e.declarations){let u=t.get(l.name)??q,p=n.get(u);p?p.push(l):n.set(u,[l])}let s=new Set(e.declarations.filter(l=>l.value).map(l=>l.name)),o=new Map,i=e.header?`${e.header}
8
- `:"",a=r.toJS?".d.ts":".ts";for(let[l,u]of n){let p=fr(l,u,t,s,r.toJS),c=u.map(m=>m.text.trimEnd()).join(`
1
+ var de=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import Dr from"axios";import{execSync as Ir}from"child_process";import gt from"os";import I from"fs";import b from"path";import mt from"prompts";import{generateApi as Tr}from"swagger-typescript-api";var Z=e=>/^(https?:\/\/|:?\/\/)/.test(e);import te from"fs";import Rt from"url";import re from"path";var ee={param:process.argv.filter((e,t)=>t>1)};function he(e,t="value",r={}){Array.isArray(e)||(e=[e]);let n;return ee.param.forEach((s,o)=>{if(e.includes(s))["value"].includes(t)?n=ee.param[o+1]:["array"].includes(t)?n=Array.from({length:r.length??1}).map((i,a)=>ee.param[o+a+1]):n=!["false"].includes(ee.param[o+1]);else return}),n}function $(e){return he(e,"key")}function M(e){return he(e,"value")}function Me(e,t={}){return he(e,"array",t)??[]}function ye(e,t){let r=re.dirname(e);te.existsSync(r)||te.mkdirSync(r,{recursive:!0}),te.writeFileSync(e,t)}function Nt(){return typeof de<"u"&&typeof module<"u"?__filename:Rt.fileURLToPath(import.meta.url)}function Ge(){return typeof de<"u"&&typeof module<"u"?__dirname:re.dirname(Nt())}function _e(e=process.cwd()){let t=[],r=n=>{for(let s of te.readdirSync(n,{withFileTypes:!0})){if(s.name.startsWith("."))continue;let o=re.join(n,s.name);if(s.isDirectory()){if(s.name==="node_modules")continue;r(o)}else s.isFile()&&s.name.startsWith("saconfig")&&s.name.endsWith(".json")&&t.push(re.relative(e,o))}};return r(e),t.sort()}function ne(e){return JSON.stringify(e).slice(1,-1)}function Be(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}import*as He from"dns/promises";import*as Se from"net";var bt=5,Y=async e=>{try{return(await He.lookup(e,{all:!0,verbatim:!0})).map(r=>r.address)}catch{return[]}};function xe(e){let t=e.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return!1;let r=t.slice(1).map(Number);if(r.some(o=>o>255))return!1;let[n,s]=r;return n===0||n===10||n===127||n===169&&s===254||n===172&&s>=16&&s<=31||n===192&&s===168}function Ct(e){let t=e.toLowerCase();if(t==="::"||t==="::1"||t.startsWith("fe80:"))return!0;let r=t.split(":")[0]??"";if(r>="fc00"&&r<="fdff")return!0;let n=t.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);if(n?.[1])return xe(n[1]);let s=t.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(s?.[1]&&s?.[2]){let o=parseInt(s[1],16),i=parseInt(s[2],16);return xe(`${o>>8&255}.${o&255}.${i>>8&255}.${i&255}`)}return!1}function Ue(e){let t=Se.isIP(e);return t===4?xe(e):t===6?Ct(e):!1}function kt(e){let t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")}async function Et(e,t=Y){let r;try{r=new URL(e)}catch{return!1}if(r.protocol!=="http:"&&r.protocol!=="https:")return!1;let n=r.hostname.startsWith("[")&&r.hostname.endsWith("]")?r.hostname.slice(1,-1):r.hostname;if(kt(n))return!1;if(Se.isIP(n))return!Ue(n);let s=await t(n);return s.length===0?!1:s.every(o=>!Ue(o))}function vt(e,t){if(typeof t!="string")return!1;try{let r=new URL(e),n=new URL(t);return r.protocol===n.protocol&&r.host===n.host}catch{return!1}}function Je(e){return e.split("#")[0]||e}async function $e(e,t,r=Y){let{specSourceUrl:n,allowExplicitSpecUrl:s=!1}=t;return s&&typeof n=="string"&&Je(e)===Je(n)||typeof n=="string"&&vt(e,n)?!0:Et(e,r)}function jt(e,t){try{return new URL(e,t).toString()}catch{return null}}async function qe(e,t,r,n=Y,s=fetch){let o=e,i=0;for(;;){if(!await $e(o,{specSourceUrl:r.specSourceUrl,allowExplicitSpecUrl:r.allowExplicitSpecUrl&&i===0},n))return null;let l=await s(o,{...t,redirect:"manual"});if(l.status>=300&&l.status<400){let c=l.headers.get("location");if(!c||i>=bt)return null;let u=jt(c,o);if(!u)return null;o=u,i+=1;continue}return l}}var se=/["\\\u0000-\u001f]/;function Ft(e){if(e.paths&&typeof e.paths=="object"){let t={};for(let[r,n]of Object.entries(e.paths))t[Be(r)]=n;e.paths=t}if(Array.isArray(e.servers))for(let t of e.servers)t&&typeof t.url=="string"&&(t.url=ne(t.url));we(e)}function we(e){if(Array.isArray(e)){e.forEach(t=>we(t));return}if(!(!e||typeof e!="object"))for(let t of Object.keys(e)){let r=e[t];t==="enum"&&Array.isArray(r)?e[t]=r.map(n=>typeof n=="string"?ne(n):n):t==="default"&&typeof r=="string"?e[t]=ne(r):we(r)}}function At(e){let t=[],r=(n,s)=>{if(Array.isArray(n)){n.forEach((o,i)=>r(o,`${s}[${i}]`));return}if(!(!n||typeof n!="object")){if(n.properties&&typeof n.properties=="object")for(let o of Object.keys(n.properties))se.test(o)&&t.push(`${s}.properties\uFF1A\u5C5E\u6027\u540D\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);if(Array.isArray(n.required))for(let o of n.required)typeof o=="string"&&se.test(o)&&t.push(`${s}.required\uFF1A\u5FC5\u586B\u5B57\u6BB5\u540D\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);if(n.discriminator&&typeof n.discriminator=="object"&&(typeof n.discriminator.propertyName=="string"&&se.test(n.discriminator.propertyName)&&t.push(`${s}.discriminator.propertyName\uFF1A\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(n.discriminator.propertyName)}`),n.discriminator.mapping&&typeof n.discriminator.mapping=="object"))for(let o of Object.keys(n.discriminator.mapping))se.test(o)&&t.push(`${s}.discriminator.mapping\uFF1A\u952E\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);for(let o of Object.keys(n))r(n[o],`${s}.${o}`)}};return r(e,"#"),t}async function Ot(e,t={}){let r=[],n={baseUrl:t.baseUrl,resolve:t.resolve??Y,fetchImpl:t.fetchImpl??fetch,docs:new Map,errors:r},s=async(i,a,l)=>{if(Array.isArray(i)){let u=[];for(let p=0;p<i.length;p+=1)u.push(await s(i[p],`${a}[${p}]`,l));return u}if(!i||typeof i!="object")return i;let c=i.$ref;if(typeof c=="string"&&!c.startsWith("#")){let u=await o(c,a,l);return u===null?i:s(u,a,l)}for(let u of Object.keys(i))i[u]=await s(i[u],`${a}.${u}`,l);return i},o=async(i,a,l)=>{if(!/^https?:\/\//i.test(i))return r.push(`${a}\uFF1A\u4E0D\u652F\u6301\u7684\u5916\u90E8\u5F15\u7528\uFF08\u4EC5\u5141\u8BB8\u6587\u6863\u5185 #/ \u6216 http(s)\uFF09\uFF1A${i}`),null;let c=i.indexOf("#"),u=c===-1?i:i.slice(0,c),p=c===-1?"":i.slice(c+1),f;try{f=n.baseUrl?new URL(u,n.baseUrl).toString():u}catch{return r.push(`${a}\uFF1A\u65E0\u6CD5\u89E3\u6790\u7684\u5F15\u7528\u5730\u5740\uFF1A${i}`),null}let m=`${f}#${p}`;if(l.includes(m))return r.push(`${a}\uFF1A\u68C0\u6D4B\u5230\u5F15\u7528\u73AF\uFF1A${[...l,m].join(" -> ")}`),null;if(!await $e(f,{specSourceUrl:n.baseUrl},n.resolve))return r.push(`${a}\uFF1A\u62D2\u7EDD\u62C9\u53D6\u975E\u516C\u7F51\u6216\u975E\u4FE1\u4EFB\u6765\u6E90\u7684\u5916\u90E8\u5F15\u7528\uFF1A${i}`),null;let y=await Pt(f,n);if(!y)return null;let w=Lt(y,p);if(w===void 0)return r.push(`${a}\uFF1A\u5F15\u7528\u7247\u6BB5\u4E0D\u5B58\u5728\uFF1A${i}`),null;let k=await s(structuredClone(w),a,[...l,m]),S=Dt(e,p,k,f);return S?{$ref:`#/components/schemas/${S}`}:k};return await s(e,"#",[]),r}async function Pt(e,t){if(t.docs.has(e))return t.docs.get(e);let r=await qe(e,{},{specSourceUrl:t.baseUrl},t.resolve,t.fetchImpl);if(!r?.ok)return t.errors.push(`\u5916\u90E8\u5F15\u7528\u62C9\u53D6\u5931\u8D25\uFF1A${e}`),null;let n=await r.text();try{let s=JSON.parse(n);return t.docs.set(e,s),s}catch{return t.errors.push(`\u5916\u90E8\u5F15\u7528\u6587\u6863\u4EC5\u652F\u6301 JSON \u683C\u5F0F\uFF1A${e}`),null}}function Lt(e,t){if(!t||t==="/")return e;let r=e;for(let n of t.replace(/^\//,"").split("/")){if(r===null||typeof r!="object")return;let s=decodeURIComponent(n).replace(/~1/g,"/").replace(/~0/g,"~");r=r[s]}return r}function Dt(e,t,r,n){let s=t.match(/^\/components\/schemas\/([^/]+)$/);if(!s)return null;let o=decodeURIComponent(s[1]).replace(/~1/g,"/").replace(/~0/g,"~");e.components=e.components??{},e.components.schemas=e.components.schemas??{};let i=e.components.schemas;if(i[o]===void 0)return i[o]=r,o;if(JSON.stringify(i[o])===JSON.stringify(r))return o;let a=(n.split("/").pop()??"ref").replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_$]/g,"_")||"ref",l=`${o}_${a}`,c=2;for(;i[l]!==void 0&&JSON.stringify(i[l])!==JSON.stringify(r);)l=`${o}_${a}_${c}`,c+=1;return i[l]=r,l}async function We(e,t={}){let r=await Ot(e,t);return Ft(e),{errors:[...r,...At(e)]}}import H from"fs";import It from"os";import J from"path";var Tt="swagger2api.json",Mt=".swagger2apirc.json",Gt="swagger2api.local.json",_t=".swagger2apirc.local.json",Bt=".swagger2api.json",Ut=".swagger2apirc.json";function Re(e,t,r){let n={layer:t,file:e,hit:!1,sections:[],config:null};if(!e||!H.existsSync(e))return n;try{let s=JSON.parse(H.readFileSync(e,"utf8"));return!s||typeof s!="object"||Array.isArray(s)?(r.push(`${e}\uFF1A\u6839\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5C42`),{...n,hit:!1}):{layer:t,file:e,hit:!0,sections:Object.keys(s),config:s}}catch(s){return r.push(`${e}\uFF1A\u89E3\u6790\u5931\u8D25\uFF08${s.message}\uFF09\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5C42`),n}}function Jt(e,t){if(!e)return t?{...t}:null;if(!t)return{...e};let r={...e};for(let[n,s]of Object.entries(t))r[n]=s;return r}function Ht(e,t){if(!e)return t?{...t}:null;if(!t)return{...e};let r={...e};for(let[n,s]of Object.entries(t)){let o=r[n];r[n]=o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?{...o,...s}:s}return r}function ze(e,t){let[r,...n]=e,s=J.resolve(t);for(;;){let o=J.join(s,r);if(H.existsSync(o)){let l=n.map(c=>J.join(s,c)).find(c=>H.existsSync(c))??null;return{file:o,ignored:l}}let i=n.map(l=>J.join(s,l)).find(l=>H.existsSync(l));if(i)return{file:i,ignored:null};let a=J.dirname(s);if(a===s)return null;s=a}}function Ke(e=process.cwd(),t={}){let r=[],n=t.homeDir??It.homedir(),s=J.join(n,Bt),o=J.join(n,Ut),i=H.existsSync(s)?{file:s,ignored:H.existsSync(o)?o:null}:H.existsSync(o)?{file:o,ignored:null}:null,a=t.projectFile?{file:J.resolve(t.projectFile),ignored:null}:ze([Tt,Mt],e),l=ze([Gt,_t],e);for(let m of[i,a,l])m?.ignored&&r.push(`${m.file}\uFF1A\u540C\u65F6\u5B58\u5728\u65E7\u914D\u7F6E ${m.ignored}\uFF0C\u5DF2\u6309\u65B0\u6587\u4EF6\u540D\u751F\u6548\uFF0C\u5EFA\u8BAE\u5220\u9664\u65E7\u6587\u4EF6`);let c=Re(i?.file??null,"\u5168\u5C40\u5C42",r),u=Re(a?.file??null,"\u9879\u76EE\u5C42",r),p=Re(l?.file??null,"\u672C\u5730\u5C42",r),f=Ht(Jt(c.config,u.config),p.config);return{global:c,project:u,local:p,merged:f,warnings:r}}var qt=[{env:"FX_S2A_INPUT",key:"input.url",type:"string"},{env:"FX_S2A_OUTPUT",key:"output.dir",type:"string"},{env:"FX_S2A_NAME",key:"output.name",type:"string"},{env:"FX_S2A_CLIENT",key:"client.type",type:"string"},{env:"FX_S2A_LANGUAGE",key:"language.target",type:"string"},{env:"FX_S2A_CLEAN",key:"output.clean",type:"boolean"}];function Wt(e,t,r){let n=t.split("."),s=e;n.forEach((o,i)=>{if(i===n.length-1){s[o]=r;return}(!s[o]||typeof s[o]!="object")&&(s[o]={}),s=s[o]})}function oe(e,t=process.env){let r=e?structuredClone(e):{};for(let n of qt){let s=t[n.env];s===void 0||s===""||Wt(r,n.key,n.type==="boolean"?!["0","false"].includes(s.toLowerCase()):s)}return r}var zt=["url","file","name","mode","typeCheck","responses","query","extractResponseRaw","pathPrefixIndex","convertGetToQuery","dropPathParams","tagRewrite"];function z(e){if(!e||typeof e!="object"||Array.isArray(e))return{};if(typeof e.url!="string"&&typeof e.file!="string")return e;let t={...e};t.input={...e.input&&typeof e.input=="object"?e.input:{},...typeof e.url=="string"?{url:e.url}:{},...typeof e.file=="string"?{file:e.file}:{}};let r={...e.output&&typeof e.output=="object"?e.output:{},...typeof e.output=="string"?{dir:e.output}:{}};r.name=e.name??r.name??"index",r.mode=e.mode??r.mode??"single",r.prune=r.prune??r.mode==="grouped",e.typeCheck!==void 0&&(r.typeCheck=e.typeCheck),t.output=r,t.client=typeof e.client=="string"?{type:e.client}:{...e.client??{}},t.language=typeof e.language=="string"?{target:e.language}:{...e.language??{}},t.types={...e.types??{}},e.responses!==void 0&&(t.types.responses=e.responses),e.extractResponseRaw!==void 0&&(t.types.extractResponseRaw=e.extractResponseRaw),e.query!==void 0&&(t.types.extractQuery=Array.isArray(e.query)?e.query.join(","):e.query),t.naming={...e.naming??{}};for(let n of["pathPrefixIndex","convertGetToQuery","dropPathParams","tagRewrite"])e[n]!==void 0&&(t.naming[n]=e[n]);if(r.mode==="grouped"){let n={...e.grouping??{}};n.strategy=n.strategy??["path"],n.pathDepth=n.pathDepth??t.naming.pathPrefixIndex??0,n.split=n.split??!0,t.grouping=n}for(let n of zt)delete t[n];return t}function ie(e,t){let r=e?structuredClone(e):{};if(!t)return r;let n=r.profiles?.[t];if(!n||typeof n!="object")return r;for(let[s,o]of Object.entries(n)){if(s==="profiles")continue;let i=r[s];r[s]=i&&typeof i=="object"&&!Array.isArray(i)&&o&&typeof o=="object"&&!Array.isArray(o)?{...i,...o}:o}return r}function Ve(e=process.argv.slice(2)){let t=r=>r.reduce((n,s)=>n??(e.includes(s)?e[e.indexOf(s)+1]:void 0),void 0);return{configFile:t(["--config","-c"]),profile:t(["--profile"])}}import Kt from"fs";import ae from"path";function q(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Qe(e,t){if(!q(e))return t===void 0?t:structuredClone(t);let r=structuredClone(e);if(!q(t))return r;for(let[n,s]of Object.entries(t))r[n]=q(s)&&q(r[n])?Qe(r[n],s):structuredClone(s);return r}function Xe(e){return!!(e&&Object.prototype.hasOwnProperty.call(e,"targets"))}function Vt(e,t){return process.platform==="win32"?e.toLowerCase()===t.toLowerCase():e===t}function Ye(e,t){let r=ae.relative(e,t);return!!r&&!r.startsWith("..")&&!ae.isAbsolute(r)}function Ne(e=process.argv.slice(2)){let t=[];return e.forEach((r,n)=>{r==="--target"&&t.push(e[n+1]??"")}),t.length>1?{errors:["--target \u53EA\u80FD\u6307\u5B9A\u4E00\u4E2A\u76EE\u6807 id"]}:t.length===1&&(!t[0]||t[0].startsWith("-"))?{errors:["--target \u7F3A\u5C11\u76EE\u6807 id"]}:{id:t[0],errors:[]}}function Ze(e,t){let r=[],n=[],s=e.targets;if(!Array.isArray(s)||s.length===0)return{targets:[],errors:["targets \u5FC5\u987B\u662F\u975E\u7A7A\u6570\u7EC4"],warnings:n};e.defaults!==void 0&&!q(e.defaults)&&r.push("defaults \u5FC5\u987B\u662F\u5BF9\u8C61");let o=q(e.defaults)?e.defaults:{},i=q(e.profiles)?e.profiles:void 0;for(let c of["url","file","input","output"])e[c]!==void 0&&n.push(`\u591A\u76EE\u6807\u914D\u7F6E\u5FFD\u7565\u6839\u4E0A\u7684 ${c}\uFF0C\u76EE\u6807\u8F93\u5165\u8F93\u51FA\u8BF7\u5199\u5728 targets \u6216 defaults \u5185`);let a=new Set,l=[];s.forEach((c,u)=>{let p=`targets[${u}]`;if(!q(c)){r.push(`${p}\uFF1A\u5FC5\u987B\u662F\u5BF9\u8C61`);return}let f=typeof c.id=="string"?c.id.trim():"";if(!f){r.push(`${p}\uFF1A\u7F3A\u5C11 id`);return}if(a.has(f)){r.push(`\u76EE\u6807 id \u91CD\u590D\uFF1A${f}`);return}a.add(f);let{id:m,...h}=c,y={...Qe(o,h),...i?{profiles:i}:{}},w=oe(z(ie(z(y),t.profile)),t.env),k=w.input??{},S=k.url??k.file;if(typeof S!="string"||!S.trim()){r.push(`\u76EE\u6807 ${f}\uFF1A\u7F3A\u5C11 input.url \u6216 input.file`);return}let v=/^https?:\/\//i.test(S)?S:ae.resolve(t.configDir,S);if(!/^https?:\/\//i.test(v)&&!Kt.existsSync(v)){r.push(`\u76EE\u6807 ${f}\uFF1A\u8F93\u5165\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${v}`);return}let d=w.output,N=typeof d=="string"?d:d?.dir??"./src/api",j=typeof d=="string"?"index":d?.name??w.name??"index";l.push({id:f,input:v,outputDir:ae.resolve(t.configDir,N),name:j,config:w})});for(let c=0;c<l.length;c+=1)for(let u=c+1;u<l.length;u+=1){let p=l[c],f=l[u];Vt(p.outputDir,f.outputDir)?r.push(`\u76EE\u6807 ${p.id} \u4E0E ${f.id} \u7684\u8F93\u51FA\u76EE\u5F55\u76F8\u540C\uFF1A${p.outputDir}`):(Ye(p.outputDir,f.outputDir)||Ye(f.outputDir,p.outputDir))&&r.push(`\u76EE\u6807 ${p.id} \u4E0E ${f.id} \u7684\u8F93\u51FA\u76EE\u5F55\u4E92\u76F8\u5D4C\u5957\uFF1A${p.outputDir} / ${f.outputDir}`)}return{targets:l,errors:r,warnings:n}}import be from"fs";import ce from"path";var et="// @ts-nocheck",Yt=[".d.ts",".ts",".js"];function tt(e,t=e){let r=[];for(let n of be.readdirSync(e,{withFileTypes:!0})){let s=ce.join(e,n.name);if(n.isDirectory()){if(n.name==="node_modules")continue;r.push(...tt(s,t));continue}Yt.some(o=>n.name.endsWith(o))&&r.push(ce.relative(t,s).split(ce.sep).join("/"))}return r.sort()}function rt(e){let t=[];for(let r of tt(e)){let n=ce.join(e,r),s=be.readFileSync(n,"utf8");if(!s.includes(et))continue;let o=s.split(/\r?\n/),i=o.filter(a=>a.trim()!==et);i.length!==o.length&&(be.writeFileSync(n,i.join(`
2
+ `)),t.push(r))}return t}import{createHash as sr}from"crypto";import C from"fs";import or from"os";import O from"path";var A="client",E="types",K="shared",ue=["data-contracts","http-client"],Qt=new Set(["index",A,E,K]),Xt=new Set(["HttpClient","RequestParams","ContentType","AxiosRequestConfig","AxiosResponse","Array","ArrayBuffer","Blob","Boolean","Date","Document","Element","Error","Event","File","FileList","FormData","Headers","Image","Map","Node","Number","Object","Promise","ReadableStream","RegExp","Request","Response","Set","String","URL","Window"]),nt=new Set(["instance","request","setSecurityData","mergeRequestParams","stringifyFormItem","createFormData","securityData","securityWorker","secure","format","constructor","prototype"]),Zt=new Set(["con","prn","aux","nul",...Array.from({length:9},(e,t)=>`com${t+1}`),...Array.from({length:9},(e,t)=>`lpt${t+1}`)]),st=64;function B(e){return String(e).normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"")}function er(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(" ").filter(Boolean)}function tr(e){let t=e.normalize("NFKC"),r=[];for(let n of t.matchAll(/[A-Za-z0-9]+|[\p{L}\p{N}]+/gu)){let s=n[0];/^[A-Za-z0-9]+$/.test(s)?r.push(...er(s)):r.push(s)}return r}function rr(e){return e.map((t,r)=>{if(/^[A-Za-z0-9]+$/.test(t)){let n=t.toLowerCase();return r===0?n:n.charAt(0).toUpperCase()+n.slice(1)}return t}).join("")}function nr(e){let t=2166136261;for(let r of e)t^=r.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").slice(0,6)}function le(e){let t=[],r=tr(e),n=rr(r);return n?(/^[0-9]/.test(n)&&(n=`g${n}`,t.push("\u6570\u5B57\u5F00\u5934")),[...n].length>st&&(n=[...n].slice(0,st-6).join("")+nr(e),t.push("\u8D85\u957F\u622A\u65AD")),{slug:n,reason:t.join("\u3001")}):{slug:"",reason:"\u540D\u79F0\u4E0D\u542B\u53EF\u7528\u5B57\u7B26"}}function Q(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ce(e,t={}){let r=[],n=[],s=[...new Set(e)].sort((h,y)=>h<y?-1:h>y?1:0),o=new Map,i=new Set;for(let[h,y]of Object.entries(t))o.set(h,y),o.set(B(h),y);let a=new Set,l=new Set,c=[],u=(h,y=2)=>{let w=h,k=y;for(;a.has(w.toLowerCase());)w=`${h}${k}`,k+=1;return a.add(w.toLowerCase()),w},p=h=>{let y=h,w=2;for(;l.has(y)||nt.has(y.toLowerCase());)y=`${h}${w}`,w+=1;return l.add(y),y},f=new Map;for(let h of s){let y=o.get(h)??o.get(B(h));if(y===void 0)continue;i.add(h),i.add(B(h));let{slug:w}=le(y);if(!w){r.push(`\u624B\u5DE5\u540D\u4E0D\u53EF\u7528\uFF1A${h} \u2192 ${y}`);continue}let k=f.get(w.toLowerCase());k?r.push(`\u624B\u5DE5\u540D\u51B2\u7A81\uFF1A${k} \u4E0E ${h} \u90FD\u6307\u5411 ${w}`):f.set(w.toLowerCase(),h);let S=u(w);l.add(S);let v=Q(S);c.push({raw:h,key:B(h),fileName:v,className:v,property:S,reason:S===w?"\u624B\u5DE5\u6307\u5B9A":"\u624B\u5DE5\u6307\u5B9A\u3001\u4E0E\u5DF2\u6709\u7EC4\u91CD\u540D",source:"manual"})}let m=1;for(let h of s){if(c.some(wt=>wt.raw===h))continue;let{slug:y,reason:w}=le(h),k=!y,S=y;if(k){for(;a.has(`group${m}`.toLowerCase());)m+=1;S=`group${m}`,m+=1}let v=Qt.has(S.toLowerCase())||Zt.has(S.toLowerCase()),d=Xt.has(Q(S)),N=nt.has(S.toLowerCase()),j=[w],F,W;N||v?(F=u(`${S}2`,3),W=p(F),j.push(N?"\u4E0E\u805A\u5408\u6210\u5458\u540C\u540D":"\u4E0E\u4FDD\u7559\u540D\u51B2\u7A81")):d?(F=u(`${S}2`,3),W=p(S),j.push("\u4E0E\u5168\u5C40\u7C7B\u578B\u540C\u540D")):(F=u(S),W=p(F),F!==S&&j.push("\u4E0E\u5DF2\u6709\u7EC4\u91CD\u540D"));let Te=Q(F);c.push({raw:h,key:B(h),fileName:Te,className:Te,property:W,reason:j.filter(Boolean).join("\u3001"),source:k?"fallback":"auto"})}for(let h of Object.keys(t))!i.has(h)&&!i.has(B(h))&&n.push(`grouping.names \u4E2D\u7684\u952E\u672A\u51FA\u73B0\u5728\u672C\u6B21\u5206\u7EC4\u7ED3\u679C\uFF1A${h}`);return{entries:c,errors:r,warnings:n}}function ot(e){let t={};for(let r of e)t[r.fileName]=r.className,t[r.fileName.charAt(0).toLowerCase()+r.fileName.slice(1)]=r.className;return t}function pe(e,t,r,n=[]){let s=new Set([...t.flatMap(i=>[`${i.fileName}${r}`,`${i.importFrom??i.fileName}${r}`]),...n.map(i=>`${i}${r}`)]),o=new Set([`index${r}`,"index.d.ts",`${A}${r}`,`route-types${r}`,`${E}/index${r}`,...ue.flatMap(i=>[`${i}${r}`,`${i}.d.ts`])]);return e.filter(i=>i.endsWith(r)&&!i.endsWith(`.d${r}`)&&!s.has(i)&&!o.has(i)&&!i.endsWith(`_Route${r}`))}var ir=new Set(["index","shared","types",A,...ue]);function V(e){let t=sr("sha1").update(O.resolve(e)).digest("hex").slice(0,12);return O.join(or.tmpdir(),"swagger2api",`${t}.json`)}function ar(e){return String(e).split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function cr(e,t){if(!C.existsSync(e))return[];let r=[];for(let n of C.readdirSync(e)){if(!n.endsWith(t)||n.endsWith(`.d${t}`))continue;let s=n.slice(0,-t.length);if(ir.has(s.toLowerCase())||s.endsWith("Route"))continue;let o=ar(s);r.push({base:s,className:o,property:o.charAt(0).toLowerCase()+o.slice(1)})}return r.sort((n,s)=>n.base.localeCompare(s.base))}function it(e){return e.map(t=>({base:t.fileName,className:t.className,property:t.property,importFrom:t.importFrom}))}function fe(e){if(!C.existsSync(e))return null;try{let t=JSON.parse(C.readFileSync(e,"utf8"));return{files:Array.isArray(t.files)?t.files.map(String):[]}}catch{return null}}function ge(e,t,r,n=[]){let s=r?".js":".ts",i=["index",`${E}/index`,A,"route-types",...t.flatMap(c=>[c.fileName,c.importFrom??c.fileName]),...n].flatMap(c=>r?[`${c}${s}`,`${c}.d.ts`]:[`${c}${s}`]),a=O.join(e,E),l=C.existsSync(a)?C.readdirSync(a).filter(c=>c.endsWith(".ts")||c.endsWith(".js")).map(c=>`${E}/${c}`):[];return[...new Set([...i,...l])].filter(c=>C.existsSync(O.join(e,c))).sort()}function at(e,t){let r=t?[".js",".d.ts"]:[".ts"],n=[];for(let s of ue)for(let o of r){let i=`${s}${o}`;C.existsSync(O.join(e,i))&&(C.rmSync(O.join(e,i)),n.push(i))}return n}function ke(e,t){C.mkdirSync(O.dirname(e),{recursive:!0}),C.writeFileSync(e,`${JSON.stringify({files:t},null,2)}
3
+ `)}function Ee(e,t,r){if(!t)return[];let n=new Set(r),s=[];for(let o of t.files){if(n.has(o))continue;let i=O.join(e,o);C.existsSync(i)&&(C.rmSync(i),s.push(o))}return s}function ct(e,t,r,n,s=[]){let o=r?".js":".ts",i=new Set(n?.files??[]);return[...new Set([A,`${E}/index`,...t.flatMap(l=>[l.fileName,l.importFrom??l.fileName]),...s])].flatMap(l=>r?[`${l}${o}`,`${l}.d.ts`]:[`${l}${o}`]).filter(l=>C.existsSync(O.join(e,l))&&!i.has(l))}function lr(e,t,r,n){let s=t||"Api",o=u=>u.className===s?`${u.className}Module`:u.className,i=new Map;for(let u of e){let p=u.importFrom??u.base,f=i.get(p);f?f.push(u):i.set(p,[u])}let a=[...i.entries()].map(([u,p])=>{let f=`${r?`${r.replace(/\\/g,"/")}/`:""}${u}`;return`import { ${p.map(h=>{let y=o(h);return y===h.className?h.className:`${h.className} as ${y}`}).join(", ")} } from "./${f}"`}),l=e.map(u=>`${u.property} = new ${o(u)}(this)`);return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${A}"`,...a,`export * from "./${E}"`,`export * from "./${A}"`,"","/** \u805A\u5408\u5165\u53E3\uFF1A\u5404\u6A21\u5757\u5171\u4EAB\u540C\u4E00\u4E2A\u8BF7\u6C42\u5B9E\u4F8B */",n?`export class ${s} extends HttpClient {`:`export class ${s}<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {`,...l.map(u=>` ${u}`),"",n?" constructor(config) {":" constructor(config?: any) {"," super(config)"," }","}",""].join(`
4
+ `)}function ve(e,t,r,n){let s=r?".js":".ts",o=n??cr(e,s);if(o.length===0)return[];let i=lr(o,t,"",r),a=[],l=O.join(e,`index${s}`);if(C.writeFileSync(l,i),a.push(l),r){let c=ur(o,t),u=O.join(e,"index.d.ts");C.writeFileSync(u,c),a.push(u)}return a}function je(e,t,r,n={}){let s=r?".js":".ts",o=[],i=new Map;for(let c of t){let u=c.importFrom??c.fileName,p=i.get(u);p?p.push(c):i.set(u,[c])}for(let[c,u]of i){let p=O.join(e,`${c}${s}`);if(!C.existsSync(p)){u.forEach(m=>o.push(`\u7F3A\u5C11\u6A21\u5757\u6587\u4EF6\uFF1A\u671F\u671B ${c}${s}\uFF08\u539F\u59CB\u7EC4\u540D ${m.raw}\uFF09`));continue}let f=C.readFileSync(p,"utf8");for(let m of u)f.includes(`class ${m.className}`)||o.push(`\u7C7B\u540D\u4E0E\u547D\u540D\u8868\u4E0D\u4E00\u81F4\uFF1A${c}${s} \u671F\u671B ${m.className}`)}let a=[`${A}${s}`,`${E}/index${s}`,...r?[`${A}.d.ts`,`${E}/index.d.ts`]:[]];for(let c of a)C.existsSync(O.join(e,c))||o.push(`\u7F3A\u5C11\u56FA\u5B9A\u4EA7\u7269\uFF1A${c}`);if(n.aggregate!==!1){let c=O.join(e,`index${s}`);if(!C.existsSync(c))o.push(`\u7F3A\u5C11\u805A\u5408\u5165\u53E3\uFF1Aindex${s}`);else{let u=C.readFileSync(c,"utf8");for(let p of t)u.includes(`${p.property} = new `)||o.push(`\u805A\u5408\u5165\u53E3\u7F3A\u5C11\u6A21\u5757\u6302\u8F7D\uFF1A${p.property}`)}}let l=C.existsSync(e)?pe(C.readdirSync(e),t,s,n.extraFiles??[]):[];return{errors:o,orphans:l}}function ur(e,t){let r=t||"Api",n=a=>a.className===r?`${a.className}Module`:a.className,s=new Map;for(let a of e){let l=a.importFrom??a.base,c=s.get(l);c?c.push(a):s.set(l,[a])}let o=[...s.entries()].map(([a,l])=>`import { ${l.map(u=>{let p=n(u);return p===u.className?u.className:`${u.className} as ${p}`}).join(", ")} } from "./${a}"`),i=e.map(a=>` ${a.property}: ${n(a)}`);return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${A}"`,...o,`export * from "./${E}"`,`export * from "./${A}"`,"",`export declare class ${r}<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {`,...i," constructor(config?: any)","}",""].join(`
5
+ `)}function pr(e){return e.filter(t=>t.chunks.length>0).map(t=>({fileName:t.fileName,className:t.className,title:t.raw,chunks:t.chunks.map(r=>({fileName:r.fileName,className:r.className}))}))}function fr(e){let t=e.chunks.map(s=>`import { ${s.className} } from "./${s.fileName}"`),r=e.chunks.map(s=>`new ${s.className}(http)`).join(", "),n=e.chunks.map(s=>`${s.className}<SecurityDataType>`).join(", ");return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${A}"`,...t,"",`/** ${e.title} \u6A21\u5757\uFF1A\u7531\u5206\u7247\u5408\u5E76\uFF0C\u5BF9\u5916\u4E0E\u5355\u6587\u4EF6\u4EA7\u7269\u4E00\u81F4 */`,`export class ${e.className}<SecurityDataType = unknown> {`," /** \u5171\u4EAB\u8BF7\u6C42\u5668\uFF1A\u7531\u805A\u5408\u5165\u53E3\u6CE8\u5165\uFF1B\u4EC5\u4F9B\u6A21\u5757\u5185\u90E8\u8C03\u7528\uFF0C\u52FF\u5728\u4E1A\u52A1\u4FA7\u76F4\u63A5\u4F7F\u7528 */"," http: HttpClient<SecurityDataType>",""," constructor(http: HttpClient<SecurityDataType>) {"," this.http = http",` Object.assign(this, ${r})`," }",""," /** \u5E95\u5C42\u8BF7\u6C42\u5B9E\u4F8B\uFF1A\u4E0E\u805A\u5408\u5165\u53E3\u4FDD\u6301\u540C\u4E00\u4E2A */",' get instance(): HttpClient<SecurityDataType>["instance"] {'," return this.http.instance"," }","}","","/** \u7C7B\u578B\u5408\u5E76\uFF1A\u5206\u7247\u6210\u5458\u4E0E\u5355\u6587\u4EF6\u4EA7\u7269\u4FDD\u6301\u540C\u4E00\u547D\u540D\u7A7A\u95F4 */",`export interface ${e.className}<SecurityDataType = unknown> extends ${n} {}`,""].join(`
6
+ `)}function gr(e){let t=e.chunks.map(n=>`import { ${n.className} } from "./${n.fileName}"`),r=e.chunks.map(n=>`new ${n.className}(http)`).join(", ");return["/* eslint-disable */","/* tslint:disable */",...t,"",`/** ${e.title} \u6A21\u5757\uFF1A\u7531\u5206\u7247\u5408\u5E76\uFF0C\u5BF9\u5916\u4E0E\u5355\u6587\u4EF6\u4EA7\u7269\u4E00\u81F4 */`,`export class ${e.className} {`," constructor(http) {"," this.http = http",` Object.assign(this, ${r})`," }",""," get instance() {"," return this.http.instance"," }","}",""].join(`
7
+ `)}function mr(e){let t=e.chunks.map(n=>`import { ${n.className} } from "./${n.fileName}"`),r=e.chunks.map(n=>`${n.className}<SecurityDataType>`).join(", ");return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${A}"`,...t,"",`export interface ${e.className}<SecurityDataType = unknown> extends ${r} {}`,`export declare class ${e.className}<SecurityDataType = unknown> {`," constructor(http: HttpClient<SecurityDataType>)","}",""].join(`
8
+ `)}function lt(e,t,r){let n=[];for(let s of pr(t))if(r){let o=`${s.fileName}.js`;C.writeFileSync(O.join(e,o),gr(s)),n.push(o);let i=`${s.fileName}.d.ts`;C.writeFileSync(O.join(e,i),mr(s)),n.push(i)}else{let o=`${s.fileName}.ts`;C.writeFileSync(O.join(e,o),fr(s)),n.push(o)}return n}var dr=["get","post","put","delete","patch","head","options"],hr=["index","data-contracts","http-client","route-types"];function yr(e,t,r){let n=r.strategy?.length?r.strategy:["rules","tag","path"],s=r.fallback??"misc";for(let o of n)if(o==="rules")for(let[i,a]of(r.rules??[]).entries()){let l=a.match??{};if(l.prefix&&e.startsWith(l.prefix))return{group:a.group,source:"rules",ruleIndex:i};if(l.regex&&new RegExp(l.regex).test(e))return{group:a.group,source:"rules",ruleIndex:i};if(l.tag&&(t.tags??[]).includes(l.tag))return{group:a.group,source:"rules",ruleIndex:i};if(l.operationId&&t.operationId===l.operationId)return{group:a.group,source:"rules",ruleIndex:i}}else if(o==="tag"){let i=(t.tags??[])[0];if(i)return{group:String(i),source:"tag"}}else if(o==="path"){let i=e.split("/").filter(Boolean),a=r.pathDepth??0;if(i[a])return{group:i[a],source:"path"}}return{group:s,source:"fallback"}}function ut(e,t){let r=t.fallback??"misc",n=[],s=new Set;for(let[p,f]of Object.entries(e.paths??{}))for(let m of dr){let h=f[m];if(!h||typeof h!="object")continue;let y=yr(p,h,t);y.ruleIndex!==void 0&&s.add(y.ruleIndex),n.push({path:p,method:m,operation:h,group:y.group,ruleIndex:y.ruleIndex})}if(t.collapse){let p=new Map;for(let f of[...new Set(n.map(m=>m.group))].sort()){let m=B(f);m&&!p.has(m)&&p.set(m,f)}n.forEach(f=>{let m=p.get(B(f.group));m&&(f.group=m)})}if(t.split!==void 0&&t.split!==!1){let p=Ce(n.map(m=>m.group),t.names),f=typeof t.split=="object"?t.split:{};return Sr(n,t,f,p,s)}let o=new Map;n.forEach(({group:p})=>o.set(p,(o.get(p)??0)+1));for(let p of n){let f=o.get(p.group)??0;if(t.minRoutes&&f<t.minRoutes&&p.group!==r)p.group=r;else if(t.maxRoutes&&f>t.maxRoutes){let h=p.path.split("/").filter(Boolean)[(t.pathDepth??0)+1];h&&(p.group=`${p.group}_${h}`)}}let i=Ce(n.map(p=>p.group),t.names),a=new Map(i.entries.map(p=>[p.raw,p])),l={},c={};for(let p of n){let f=Array.isArray(p.operation.tags)?p.operation.tags.join(", "):"";f&&(l[`${p.method.toUpperCase()}:${p.path}`]=f);let m=a.get(p.group);m&&(p.operation.tags=[m.fileName]),c[p.group]=(c[p.group]??0)+1}let u=Array.from({length:t.rules?.length??0},(p,f)=>f).filter(p=>!s.has(p));return{counts:c,originalTags:l,entries:i.entries,unmatchedRules:u,errors:i.errors,warnings:i.warnings}}function xr(e,t){let r=(s,o,i)=>s===void 0?o:!Number.isFinite(s)||s<1?(t.push(`grouping.split.${i} \u65E0\u6548\uFF08${s}\uFF09\uFF0C\u56DE\u843D\u5230 ${o}`),o):Math.floor(s),n=[];if(e.categories!==void 0&&!Array.isArray(e.categories))t.push("grouping.split.categories \u5FC5\u987B\u662F\u6570\u7EC4\uFF0C\u5DF2\u5FFD\u7565");else for(let s of e.categories??[]){if(!s||typeof s.name!="string"||!s.name){t.push("grouping.split.categories \u5B58\u5728\u7F3A\u5C11 name \u7684\u9879\uFF0C\u5DF2\u5FFD\u7565");continue}let o=s.match?.regex;if(o)try{new RegExp(o)}catch{t.push(`grouping.split.categories \u7684\u6B63\u5219\u65E0\u6548\uFF08${s.name}\uFF1A${o}\uFF09\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u9879`);continue}n.push(s)}return{minRoutes:r(e.minRoutes,150,"minRoutes"),targetRoutes:r(e.targetRoutes,300,"targetRoutes"),maxRoutes:r(e.maxRoutes,450,"maxRoutes"),minBucketRoutes:r(e.minBucketRoutes,60,"minBucketRoutes"),categories:n,fallback:typeof e.fallback=="string"&&e.fallback?e.fallback:"misc"}}function Sr(e,t,r,n,s){let o=[...n.warnings];(t.minRoutes!==void 0||t.maxRoutes!==void 0)&&o.push("\u5DF2\u542F\u7528 grouping.split\uFF0C\u5FFD\u7565 grouping.minRoutes / grouping.maxRoutes\uFF0C\u9608\u503C\u6539\u7531 grouping.split \u63D0\u4F9B");let i=xr(r,o),a=new Map(n.entries.map(d=>[d.raw,d])),l=new Map;for(let d of e){let N=l.get(d.group);N?N.push(d):l.set(d.group,[d])}let c=n.entries.map(d=>({raw:d.raw,fileName:d.fileName,className:d.className,routes:l.get(d.raw)?.length??0,bucket:null,chunks:[]})),u=new Set(hr.map(d=>d.toLowerCase()));c.filter(d=>d.routes>i.maxRoutes).forEach(d=>u.add(d.fileName.toLowerCase()));for(let d of c){if(d.routes<=i.maxRoutes)continue;let N=l.get(d.raw)??[];d.chunks=wr(d,N,t.pathDepth??0,i,u)}let p=e.length,f=br(c.filter(d=>d.chunks.length===0),p,i,u,o),m=new Map(c.map(d=>[d.raw,d]));for(let d of f)d.namespaces.forEach(N=>{let j=m.get(N);j&&(j.bucket=d.fileName)});let h={},y={};for(let d of e){let N=a.get(d.group),j=m.get(d.group);if(!N||!j)continue;let F=Array.isArray(d.operation.tags)?d.operation.tags.join(", "):"";F&&(h[`${d.method.toUpperCase()}:${d.path}`]=F);let W=d.splitTag??j.bucket;W&&(d.operation.tags=[W,N.fileName]),y[d.group]=(y[d.group]??0)+1}for(let d of c){let N=a.get(d.raw);N&&(N.importFrom=d.chunks.length?d.fileName:d.bucket??d.fileName)}let w={},k=(d,N)=>{w[d]=N,w[d.charAt(0).toLowerCase()+d.slice(1)]=N};n.entries.forEach(d=>k(d.fileName,d.className)),c.forEach(d=>d.chunks.forEach(N=>k(N.fileName,N.className)));let S={};for(let d of f){let N=d.namespaces.map(j=>{let F=m.get(j);return{tag:F.fileName,className:F.className,title:F.raw,routes:F.routes}});S[d.fileName]=N,S[d.fileName.charAt(0).toLowerCase()+d.fileName.slice(1)]=N}let v=Array.from({length:t.rules?.length??0},(d,N)=>N).filter(d=>!s.has(d));return{counts:y,originalTags:h,entries:n.entries,unmatchedRules:v,errors:n.errors,warnings:o,split:{total:p,buckets:f,namespaces:c,bucketLayout:S},moduleClassNames:w}}function $r(e,t,r){let n=e.split("/").filter(Boolean),s=n.indexOf(t),o=s>=0?s+1:r+1;for(let i=o;i<n.length;i+=1){let a=n[i];if(!/^v\d+$/i.test(a)&&!/^\{.*\}$/.test(a))return a}return"rest"}function wr(e,t,r,n,s){let o=new Map;for(let l of t){let c=$r(l.path,e.raw,r),u=o.get(c);u?u.push(l):o.set(c,[l])}let i=[],a={items:[],categories:new Set};for(let[l,c]of[...o.entries()].sort(([u],[p])=>u<p?-1:u>p?1:0))for(let u of c)a.items.length>=n.targetRoutes&&(i.push(a),a={items:[],categories:new Set}),a.items.push(u),a.categories.add(l);return a.items.length&&i.push(a),i.map((l,c)=>{let u=c+1,p=`${e.className}Part${u}`;for(;s.has(p.toLowerCase());)u+=1,p=`${e.className}Part${u}`;return s.add(p.toLowerCase()),l.items.forEach(f=>{f.splitTag=p}),{tag:p,fileName:p,className:p,routes:l.items.length,categories:[...l.categories].sort()}})}function Rr(e,t){let r=t.match??{};return!!(r.prefix&&e.raw.startsWith(r.prefix)||r.regex&&new RegExp(r.regex).test(e.raw))}function pt(e,t){let r=e,n=2;for(;t.has(r.toLowerCase());)r=`${e}${n}`,n+=1;return t.add(r.toLowerCase()),r}function Nr(e,t){let r=0;for(;e.length>1&&r<e.length;){let n=e[r];if(n.routes>=t.minBucketRoutes){r+=1;continue}let s=e[r-1];if(s&&s.routes+n.routes<=t.maxRoutes){s.plans.push(...n.plans),s.routes+=n.routes,e.splice(r,1),r=Math.max(r-1,0);continue}let o=e[r+1];if(o&&o.routes+n.routes<=t.maxRoutes){o.plans.unshift(...n.plans),o.routes+=n.routes,e.splice(r,1);continue}r+=1}}function Fe(e,t,r,n){let s=[],o=[],i=0;for(let a of e)i>0&&i+a.routes>r.targetRoutes&&(s.push({plans:o,routes:i}),o=[],i=0),o.push(a),i+=a.routes;return o.length&&s.push({plans:o,routes:i}),Nr(s,r),s.map(a=>{let l=t?Q(le(t).slug||"bucket"):s.length===1?"Modules":a.plans[0].fileName,c=pt(l,n);return{fileName:c,className:c,category:t,routes:a.routes,namespaces:a.plans.map(u=>u.raw)}})}function br(e,t,r,n,s){if(e.length===0)return[];if(t<=r.minRoutes){let l=pt("Modules",n),c=e.reduce((u,p)=>u+p.routes,0);return[{fileName:l,className:l,category:"",routes:c,namespaces:e.map(u=>u.raw)}]}if(r.categories.length===0)return Fe(e,"",r,n);let o=[],i=new Set(e.map(l=>l.raw));for(let l of r.categories){let c=e.filter(u=>i.has(u.raw)&&Rr(u,l));c.forEach(u=>i.delete(u.raw)),c.length&&o.push(...Fe(c,l.name,r,n))}let a=e.filter(l=>i.has(l.raw));return a.length&&(s.push(`\u672A\u547D\u4E2D\u5206\u7C7B\u7684\u547D\u540D\u7A7A\u95F4\u5F52\u5165 ${r.fallback}\uFF1A${a.map(l=>l.raw).join("\u3001")}`),o.push(...Fe(a,r.fallback,r,n))),o}import X from"fs";import U from"path";import R from"typescript";var Le=`${E}/index`;function Cr(e){return R.isInterfaceDeclaration(e)||R.isTypeAliasDeclaration(e)||R.isEnumDeclaration(e)||R.isClassDeclaration(e)||R.isFunctionDeclaration(e)||R.isVariableStatement(e)}function Pe(e){if(R.isVariableStatement(e)){let r=e.declarationList.declarations[0];return r&&R.isIdentifier(r.name)?r.name.text:null}let t=e;return t.name&&R.isIdentifier(t.name)?t.name.text:null}function kr(e){return R.canHaveModifiers(e)?!!R.getModifiers(e)?.some(t=>t.kind===R.SyntaxKind.ExportKeyword):!1}function Er(e,t){let r={target:R.ScriptTarget.ESNext,module:R.ModuleKind.ESNext,noResolve:!0,skipLibCheck:!0,noEmit:!0},n=R.createCompilerHost(r),s=n.getSourceFile.bind(n),o=R.createSourceFile(e,t,R.ScriptTarget.Latest,!0,R.ScriptKind.TS);n.getSourceFile=(a,l,c,u)=>a===e?o:s(a,l,c,u);let i=R.createProgram({rootNames:[e],options:r,host:n});return{sourceFile:o,checker:i.getTypeChecker()}}function vr(e,t=`${E}/index.ts`){let{sourceFile:r,checker:n}=Er(t,e),s=new Map,o=r.statements.filter(Cr),i=new Set;for(let u of o){let p=Pe(u);p&&(s.set(u,p),i.add(p))}let a=r.statements[0],l=a?e.slice(0,a.getStart(r)).trimEnd():"",c=[];for(let u of o){let p=Pe(u);if(!p)continue;let f=kr(u),m=u.getStart(r,!0),h=u.getStart(r)-m,y=e.slice(m,u.getEnd()),w=f?y:`${y.slice(0,h)}export ${y.slice(h)}`,k=new Set,S=v=>{if(R.isIdentifier(v)&&v.text!==p&&i.has(v.text)){let N=n.getSymbolAtLocation(v)?.declarations?.find(F=>s.has(F)),j=N?s.get(N):void 0;j&&j!==p&&k.add(j)}R.forEachChild(v,S)};S(u),c.push({name:p,value:R.isEnumDeclaration(u),exported:f,text:w,refs:k})}return{header:l,declarations:c}}function jr(e,t="module.ts"){let r=R.createSourceFile(t,e,R.ScriptTarget.Latest,!0,R.ScriptKind.TS),n=new Set;for(let s of r.statements){if(!R.isImportDeclaration(s)||!R.isStringLiteral(s.moduleSpecifier)||!s.moduleSpecifier.text.endsWith(Le))continue;let i=s.importClause?.namedBindings;if(!(!i||!R.isNamedImports(i)))for(let a of i.elements)n.add((a.propertyName??a.name).text)}return n}function Fr(e,t){let r=new Set(e.map(i=>i.name)),n=new Map;for(let i of e)n.set(i.name,new Set);for(let i of t)for(let a of jr(i.source,`${i.file}.ts`))r.has(a)&&n.get(a)?.add(i.file);let s=!0;for(;s;){s=!1;for(let i of e){let a=n.get(i.name);if(a)for(let l of i.refs){let c=n.get(l);if(c)for(let u of a)c.has(u)||(c.add(u),s=!0)}}}let o=new Map;for(let i of e){let a=n.get(i.name)??new Set;o.set(i.name,a.size===1?[...a][0]:K)}return o}function Ar(e,t,r,n,s){let o=new Map;for(let a of t)for(let l of a.refs){let c=r.get(l);if(!c||c===e)continue;let u=o.get(c)??{values:[],types:[]};!s&&n.has(l)?u.values.push(l):u.types.push(l),o.set(c,u)}let i=[];for(let[a,l]of[...o.entries()].sort(([c],[u])=>c.localeCompare(u)))l.values.length&&i.push(`import { ${[...new Set(l.values)].sort().join(", ")} } from "./${a}"`),l.types.length&&i.push(`import type { ${[...new Set(l.types)].sort().join(", ")} } from "./${a}"`);return i}function Ae(e,t,r){let n=new Map;for(let o of e){if(!o.exported||r.runtimeOnly&&!o.value)continue;let i=t.get(o.name)??K,a=n.get(i)??{values:[],types:[]};o.value?a.values.push(o.name):a.types.push(o.name),n.set(i,a)}let s=[];for(let[o,i]of[...n.entries()].sort(([a],[l])=>a.localeCompare(l)))i.values.length&&s.push(`export { ${i.values.join(", ")} } from "./${o}"`),i.types.length&&s.push(`export type { ${i.types.join(", ")} } from "./${o}"`);return s}function Or(e,t,r){let n=new Map;for(let l of e.declarations){let c=t.get(l.name)??K,u=n.get(c);u?u.push(l):n.set(c,[l])}let s=new Set(e.declarations.filter(l=>l.value).map(l=>l.name)),o=new Map,i=e.header?`${e.header}
9
+ `:"",a=r.toJS?".d.ts":".ts";for(let[l,c]of n){let u=Ar(l,c,t,s,r.toJS),p=c.map(f=>f.text.trimEnd()).join(`
9
10
 
10
- `);o.set(`${l}${a}`,[i,p.length?`${p.join(`
11
+ `);o.set(`${l}${a}`,[i,u.length?`${u.join(`
11
12
  `)}
12
- `:"",c,""].filter(Boolean).join(`
13
- `))}return r.toJS?(o.set("index.js",[i,...be(e.declarations,t,{runtimeOnly:!0}),""].filter(Boolean).join(`
14
- `)),o.set("index.d.ts",[i,...be(e.declarations,t,{runtimeOnly:!1}),""].filter(Boolean).join(`
15
- `))):o.set("index.ts",[i,...be(e.declarations,t,{runtimeOnly:!1}),""].filter(Boolean).join(`
16
- `)),o}function gr(e){let t=$.createSourceFile(`${Ee}.js`,e,$.ScriptTarget.Latest,!0,$.ScriptKind.JS),r=new Map;for(let n=0;n<t.statements.length;n+=1){let s=t.statements[n];if(!$.isVariableStatement(s))continue;let o=ke(s);if(!o)continue;let i=s.getEnd(),a=t.statements[n+1];a&&$.isExpressionStatement(a)&&a.expression.getText(t).includes(o)&&(i=a.getEnd(),n+=1),r.set(o,e.slice(s.getStart(t),i))}return r}function dr(e,t,r){let n=gr(e),s=new Map;for(let[i,a]of n){let l=t.get(i)??q,u=s.get(l);u?u.push(a):s.set(l,[a])}let o=new Map;for(let[i,a]of s)o.set(i,[r,...a,""].filter(Boolean).join(`
17
- `));return o}function Ce(e){return V.existsSync(e)?V.readFileSync(e,"utf8"):null}function ve(e){let t=B.join(e.dir,E),r=e.toJS?"index.d.ts":"index.ts",n=Ce(B.join(t,r));if(!n)return{written:[],errors:[`\u7F3A\u5C11\u5951\u7EA6\u51FA\u53E3\uFF1A${E}/${r}`]};let s=lr(n,`${Ee}${B.extname(r)}`),o=e.moduleFiles.map(c=>({file:c,source:Ce(B.join(e.dir,`${c}${e.toJS?".d.ts":".ts"}`))})).filter(c=>!!c.source),i=pr(s.declarations,o),a=mr(s,i,{toJS:e.toJS});if(e.toJS){let c=Ce(B.join(t,"index.js"));if(c)for(let[m,f]of dr(c,i,s.header))a.set(`${m}.js`,f)}let l=[],u=new Set(["index.ts","index.js","index.d.ts"]);for(let c of a.keys()){if(u.has(c)||!e.knownFiles)continue;let m=`${E}/${c}`;V.existsSync(B.join(e.dir,m))&&!e.knownFiles.has(m)&&l.push(`\u8F93\u51FA\u76EE\u5F55\u5B58\u5728\u540C\u540D\u624B\u5199\u6587\u4EF6\uFF1A${m}\uFF08\u4E0D\u5C5E\u4E8E\u4E0A\u4E00\u8F6E\u751F\u6210\u6E05\u5355\uFF09`)}if(l.length>0)return{written:[],errors:l};let p=[];for(let[c,m]of a){let f=`${E}/${c}`;V.mkdirSync(B.dirname(B.join(e.dir,f)),{recursive:!0}),V.writeFileSync(B.join(e.dir,f),m),p.push(f)}return{written:p,errors:l}}var x={files:[],param:{}},y={home:tt.homedir(),enum:{}},G=0,P=[],M=null,Sr=()=>process.argv.includes("--dry-run"),$r=()=>process.argv.includes("--json"),T=()=>process.argv.includes("--check");function Ze(){return R.join(tt.tmpdir(),`swagger2api-${process.pid}-${Date.now()}.json`)}function ce(e,t=0){e&&console.log(e),process.exit(t)}async function wr(){y.param={config:D(["--config","-c"]),configScan:S(["--config-scan","-cs"])??!0,configAll:S(["--config-all","-ca"]),quick:S(["--quick","-q"]),replaceTags:Fe(["--replace-tags","-rt"],{length:2}),convertGet:S(["--convert-get","-cg"]),removeParam:S(["--remove-param","-rp"]),removePrefixIndex:D(["--remove-prefix-index","-rpi"]),removeDts:S(["--remove-dts","-rd"]),removeEmptyComponents:S(["--remove-empty-components","-rec"])??!0,extractRequestQuery:D(["--extract-request-query","-erq"]),extractResponseRaw:S(["--extract-response-raw","-err"]),template:R.resolve(Ae(),"./templates")},y.config={templates:D(["--templates","-t"])??y.param.template,defaultResponseAsSuccess:S(["--default-as-success","-d"]),generateResponses:S(["--responses","-r"]),generateUnionEnums:S("--union-enums"),addReadonly:S("--add-readonly"),generateRouteTypes:S("--route-types"),generateClient:!S("--no-client"),enumNamesAsValues:S("--enum-names-as-values"),extractRequestParams:S("--extract-request-params"),extractRequestBody:S("--extract-request-body"),extractResponseBody:S("--extract-response-body"),extractResponseError:S("--extract-response-error"),modular:S("--modular"),toJS:S("--js"),moduleNameIndex:Number(D("--module-name-index")??0),moduleNameFirstTag:S("--module-name-first-tag"),httpClientType:S("--axios")?"axios":"fetch",unwrapResponseData:S("--unwrap-response-data"),disableThrowOnError:S("--disable-throw-on-error"),singleHttpClient:S("--single-http-client"),silent:S("--silent")??!0,defaultResponseType:D("--default-response")??"void",typePrefix:D("--type-prefix")??"",typeSuffix:D("--type-suffix")??"",cleanOutput:S("--clean-output"),pruneOutput:S("--prune-output"),...D("--api-class-name")?{apiClassName:D("--api-class-name")}:{},patch:S("--patch"),debug:S("--debug"),anotherArrayType:S("--another-array-type"),sortTypes:S("--sort-types"),extractEnums:S("--extract-enums")},Nr()}function O(e){let t=process.argv.slice(2);return e.some(r=>t.includes(r))}function Nr(){let e=He(),t=_e(process.cwd(),{projectFile:e.configFile});t.warnings.forEach(m=>console.error("\u26A0\uFE0F",m));let r=Be(he(Ue(he(t.merged),e.profile))),n=r.input??{},s=r.output??{},o=r.types??{},i=r.naming??{},a=r.grouping??{},l=n.url??n.file;if(!l)return;let u=t.project.file?R.dirname(R.resolve(t.project.file)):process.cwd();y.rcDriven=!0,y.rcUrl=Y(l)?l:R.resolve(u,l),y.rcOutput=R.resolve(u,s.dir??"./src/api"),y.rcName=s.name??"index";let p=y.param;p.quick=!0,!O(["--remove-prefix-index","-rpi"])&&i.pathPrefixIndex!==void 0&&(p.removePrefixIndex=String(i.pathPrefixIndex)),!O(["--convert-get","-cg"])&&i.convertGetToQuery!==void 0&&(p.convertGet=i.convertGetToQuery),!O(["--remove-param","-rp"])&&i.dropPathParams!==void 0&&(p.removeParam=i.dropPathParams),!O(["--extract-request-query","-erq"])&&o.extractQuery!==void 0&&(p.extractRequestQuery=o.extractQuery),!O(["--extract-response-raw","-err"])&&o.extractResponseRaw!==void 0&&(p.extractResponseRaw=!!o.extractResponseRaw),!O(["--remove-dts","-rd"])&&o.removeDts!==void 0&&(p.removeDts=o.removeDts),!O(["--replace-tags","-rt"])&&i.tagRewrite&&(p.replaceTags=i.tagRewrite);let c=y.config;!O(["--axios"])&&r.client?.type&&(c.httpClientType=r.client.type==="axios"?"axios":"fetch"),!O(["--js"])&&r.language?.target&&(c.toJS=r.language.target==="js"),!O(["--responses","-r"])&&o.responses!==void 0&&(c.generateResponses=!!o.responses),!O(["--unwrap-response-data"])&&o.unwrapData!==void 0&&(c.unwrapResponseData=!!o.unwrapData),!O(["--extract-request-params"])&&o.extractParams!==void 0&&(c.extractRequestParams=!!o.extractParams),!O(["--clean-output"])&&s.clean!==void 0&&(c.cleanOutput=!!s.clean),!O(["--modular"])&&s.mode==="grouped"&&(c.modular=!0),O(["--prune-output"])||(c.pruneOutput=s.prune===void 0?!!c.modular:!!s.prune),!O(["--module-name-index"])&&a.pathDepth!==void 0&&(c.moduleNameIndex=Number(a.pathDepth)),Object.keys(a).length&&(c.grouping=a)}async function Rr(){if(y.rcDriven){x.files=["(swagger2apirc)"];return}y.param.config?x.files=y.param.config.split(","):y.param.configScan&&(x.files=Oe()),x.files.length==0&&(x.files=["saconfig.json"]),!y.param.configAll&&x.files.length>1&&(x.files=(await rt({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:x.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:ce("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),x.files?.length>0||ce("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function br(){if(y.rcDriven){x.param={url:y.rcUrl,output:y.rcOutput,name:y.rcName},y.docFile=Ze();return}try{x.param={},x.param=JSON.parse(L.readFileSync(x.file,"utf-8"))}catch{}(!y.param.quick||[x.param.url,x.param.output,x.param.name].includes(void 0))&&(x.param=await rt([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:x.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:x.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:x.param.name??"index"}])),[x.param.url,x.param.output,x.param.name].includes(void 0)&&ce("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),y.docFile=Ze()}async function nt(e=0){if(x.file=x.files[e],await br(),Y(x.param.url))await yr.get(x.param.url).then(t=>et(t.data)).catch(t=>console.log("\u5931\u8D25\uFF1A",t));else try{await et(JSON.parse(L.readFileSync(R.resolve(x.param.url),"utf8")))}catch(t){console.log("\u5931\u8D25\uFF1A",t)}x.files[e+1]?await nt(e+1):G>0&&ce(`\u7ED3\u675F\uFF1A${G} \u4E2A\u6587\u6863\u672A\u751F\u6210\uFF0C\u5931\u8D25\u539F\u56E0\u89C1\u4E0A\u65B9\u8F93\u51FA`,1)}function Cr(e){let t=y.param.replaceTags;if(!t?.length)return;let[r,n]=t;if(!r||typeof n!="string"){console.error("\u26A0\uFE0F \u5DF2\u5FFD\u7565 --replace-tags\uFF1A\u9700\u8981\u300C\u5339\u914D + \u66FF\u6362\u300D\u4E24\u4E2A\u503C\uFF0C\u56DE\u843D\u5230\u4FDD\u7559\u539F\u59CB\u6807\u7B7E");return}Object.values(e.paths??{}).forEach(s=>{Object.values(s).forEach(o=>{Array.isArray(o?.tags)&&(o.tags=o.tags.map(i=>i.replace(new RegExp(`^${r}$`,"g"),n)))})})}function ae(e,t){let r=t?[...t.buckets.map(n=>n.fileName),...t.namespaces.flatMap(n=>n.chunks.map(s=>s.fileName)),...t.namespaces.filter(n=>n.chunks.length>0).map(n=>n.fileName)]:e.map(n=>n.fileName);return[...new Set(r)]}function st(e,t=e){let r=[];for(let n of L.readdirSync(e,{withFileTypes:!0})){let s=R.join(e,n.name);n.isDirectory()?r.push(...st(s,t)):r.push(R.relative(t,s).split(R.sep).join("/"))}return r.sort()}function kr(e,t){let r=st(t),n=[];for(let o of r){let i=R.join(e,o);if(!L.existsSync(i)){n.push(`\u7F3A\u5C11\u4EA7\u7269\uFF1A${o}`);continue}let a=L.readFileSync(R.join(t,o),"utf8").replace(/\r\n/g,`
18
- `),l=L.readFileSync(i,"utf8").replace(/\r\n/g,`
19
- `);a!==l&&n.push(`\u4EA7\u7269\u4E0D\u4E00\u81F4\uFF1A${o}`)}let s=oe(W(e));for(let o of s?.files??[])r.includes(o)||n.push(`\u4EA7\u7269\u5DF2\u8FC7\u671F\uFF1A${o}`);if(n.length>0){G+=1,console.error(`
20
- \u2716 \u4EA7\u7269\u6821\u9A8C\u672A\u901A\u8FC7\uFF1A${n.length} \u9879`),n.forEach(o=>console.error(` - ${o}`));return}console.log("\u6821\u9A8C\uFF1A\u4EA7\u7269\u4E0E\u5F53\u524D\u914D\u7F6E\u4E00\u81F4")}function Er(e,t,r){let n=!!y.config.toJS,s=n?".js":".ts",o=R.resolve(x.param.output??"./src/api"),i=L.existsSync(o)?L.readdirSync(o):[],a=ae(e,r),u=a.flatMap(c=>n?[`${c}${s}`,`${c}.d.ts`]:[`${c}${s}`]).filter(c=>!i.includes(c)),p=se(i,e,s,a);if($r()){console.log(JSON.stringify({groups:e.map(({raw:c,fileName:m,className:f,property:d,importFrom:h,reason:w,source:k})=>({raw:c,fileName:m,className:f,property:d,importFrom:h,reason:w,source:k})),unmatchedRules:t,add:u,orphans:p,split:r?{total:r.total,buckets:r.buckets.map(({fileName:c,category:m,routes:f,namespaces:d})=>({fileName:c,category:m,routes:f,namespaces:d})),shards:r.namespaces.filter(c=>c.chunks.length>0).map(({raw:c,fileName:m,className:f,routes:d,chunks:h})=>({raw:c,fileName:m,className:f,routes:d,chunks:h.map(({fileName:w,routes:k,categories:b})=>({fileName:w,routes:k,categories:b}))}))}:void 0},null,2));return}e.forEach(c=>console.log(`\u547D\u540D\uFF1A${c.raw} \u2192 ${c.fileName}\uFF08\u7C7B ${c.className}${c.reason?`\uFF0C${c.reason}`:""}\uFF09`)),r?.buckets.forEach(c=>console.log(`\u6876\uFF1A${c.fileName}\uFF08${c.namespaces.length} \u4E2A\u547D\u540D\u7A7A\u95F4 / ${c.routes} \u6761${c.category?`\uFF0C\u5206\u7C7B ${c.category}`:""}\uFF09`)),r?.namespaces.filter(c=>c.chunks.length>0).forEach(c=>console.log(`\u5206\u7247\uFF1A${c.raw} \u2192 ${c.chunks.map(m=>`${m.fileName}\uFF08${m.routes} \u6761\uFF09`).join("\u3001")}`)),t.length&&console.error(`\u26A0\uFE0F \u672A\u547D\u4E2D\u89C4\u5219\uFF1A${t.map(c=>c+1).join("\u3001")}`),u.length&&console.log(`\u9884\u8BA1\u65B0\u589E\uFF1A${u.join("\u3001")}`),p.length&&console.error(`\u26A0\uFE0F \u8868\u5916\u4EA7\u7269\uFF08\u5EFA\u8BAE\u5F00\u542F output.prune\uFF09\uFF1A${p.join("\u3001")}`)}function vr(){let e=new Map;return{onCreateRouteName(t,r){let n=`${r?.tags?.[1]??""}|${t.original}`,s=(e.get(n)??0)+1;return e.set(n,s),{...t,usage:s>1?`${t.original}${s}`:t.original,duplicate:s>1}}}}async function et(e){let t=null;if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");let r=await Te(e,{baseUrl:Y(x.param.url)?x.param.url:void 0});if(r.errors.length>0){r.errors.forEach(a=>console.error("\u5931\u8D25\uFF1A",a)),G+=1;return}let n=R.resolve(x.param.output),s=null;if(T()){if(!L.existsSync(n)){console.error(`\u5931\u8D25\uFF1A--check \u9700\u8981\u5DF2\u6709\u4EA7\u7269\u76EE\u5F55\uFF1A${n}`),G+=1;return}s=L.mkdtempSync(R.join(R.dirname(n),".swagger2api-check-")),x.param.output=s,process.once("exit",()=>L.rmSync(s,{recursive:!0,force:!0}))}P=[],M=null,y.param.moduleClassNames=void 0,y.param.splitBuckets=void 0,Cr(e);let o=y.config.grouping;if(y.config.modular&&o&&(o.strategy?.length||o.rules?.length||o.split)){let a=Qe(e,o);if(a.warnings.forEach(l=>console.error("\u26A0\uFE0F",l)),a.errors.length>0){a.errors.forEach(l=>console.error("\u5931\u8D25\uFF1A",l)),G+=1;return}if(P=a.entries,M=a.split??null,y.config.moduleNameFirstTag=!0,y.param.moduleClassNames=a.moduleClassNames??We(a.entries),y.param.splitBuckets=a.split?.bucketLayout,o.preserveTags!==!1&&(y.param.groupOriginalTags=a.originalTags),console.log("\u5206\u7EC4\uFF1A",...Object.entries(a.counts).map(([l,u])=>`${l}-${u}`)),Sr()){Er(a.entries,a.unmatchedRules,M);return}}if(y.config.modular&&P.length){let a=R.resolve(x.param.output);t=oe(W(a));let u=Ve(a,M?[]:P,!!y.config.toJS,t,ae(P,M));if(u.length>0){u.forEach(p=>console.error(`\u5931\u8D25\uFF1A\u8F93\u51FA\u76EE\u5F55\u5B58\u5728\u540C\u540D\u624B\u5199\u6587\u4EF6\uFF1A${p}\uFF08\u4E0D\u5C5E\u4E8E\u4E0A\u4E00\u8F6E\u751F\u6210\u6E05\u5355\uFF09\uFF0C\u5DF2\u7EC8\u6B62\u751F\u6210\uFF1B\u786E\u8BA4\u53EF\u8986\u76D6\u540E\u5220\u9664\u8BE5\u6587\u4EF6\u6216\u8C03\u6574\u5206\u7EC4\u540D`)),G+=1;return}}if(Object.entries(e.paths).forEach(a=>{Object.keys(a[1]).forEach(l=>{let u=`${a[0]}/${l}`;if(y.param.convertGet&&(u=u.replace(/([^\}]\/)get$/g,"$1query")),y.param.removeParam&&(u=u.replace(/\/\{.+?\}/g,"")),y.param.removePrefixIndex){let c=u.split("/");c=c.slice(0,1).concat(c.slice(Number(y.param.removePrefixIndex)+2)),u=c.join("/")}u=u.replace(/["\\`\r\n]/g,"_").replace(/\$\{/g,"_"),e.paths[a[0]][l].operationId=u;let p=u.split("/").slice(-1)[0];typeof y.enum[p]=="number"?y.enum[p]++:y.enum[p]=1})}),Object.entries(e.components).forEach(a=>{Object.keys(a[1]).forEach(l=>{y.param.removeEmptyComponents&&!Object.keys(e.components[a[0]][l]).length&&delete e.components[a[0]][l]})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(y.enum).map(a=>a.join("-"))),pe(y.docFile,JSON.stringify(e)),y.config.modular){let a=y.config;a.fileNames={...a.fileNames??{},dataContracts:`${E}/index`,httpClient:j},L.mkdirSync(R.join(R.resolve(x.param.output),E),{recursive:!0})}console.log("\u6267\u884C\uFF1A",x.file);let i=await xr({fileName:`${x.param.name}.ts`,output:R.resolve(x.param.output),input:y.docFile,...y.config,...M?{hooks:vr()}:{},param:y.param});if(console.log(T()?"\u6821\u9A8C\uFF1A":"\u5B8C\u6210\uFF1A",R.resolve(T()?n:x.param.output,`${x.param.name}${y.config.toJS?".js":".ts"}`)),y.config.modular){let a=R.resolve(x.param.output),l=String(y.config.apiClassName??"Api"),u=!!y.config.toJS;if(P.length){let p=ae(P,M);M&&Ye(a,M.namespaces,u);let c=ve({dir:a,moduleFiles:p,toJS:u,knownFiles:new Set(t?.files??[])});if(c.errors.length>0){c.errors.forEach(h=>console.error("\u5931\u8D25\uFF1A",h)),G+=1;return}let m=Ne(a,P,u,{aggregate:!1,extraFiles:p});if(m.errors.length>0){m.errors.forEach(h=>console.error("\u5931\u8D25\uFF1A",h)),G+=1;return}we(a,l,u,ze(P));let{errors:f,orphans:d}=Ne(a,P,u,{extraFiles:p});if(f.length>0){f.forEach(h=>console.error("\u5931\u8D25\uFF1A",h)),G+=1;return}d.forEach(h=>console.error("\u26A0\uFE0F \u8868\u5916\u4EA7\u7269\uFF08\u5EFA\u8BAE\u5F00\u542F output.prune\uFF09\uFF1A",h))}else{let p=(i.files??[]).map(f=>`${String(f.fileName??"").replace(/\\/g,"/")}${f.fileExtension??""}`).filter(f=>!!f&&!f.startsWith(".")),c=p.filter(f=>!f.includes("/")&&!f.endsWith(".d.ts")).map(f=>f.slice(0,f.lastIndexOf("."))).filter(f=>!!f&&!["index",j,"route-types"].includes(f)&&!f.endsWith("Route"));if(!T()){let f=oe(W(a));$e(a,f,p.length>0?p:ie(a,[],u)).forEach(d=>console.log("\u6E05\u7406\uFF1A",R.resolve(a,d)))}let m=ve({dir:a,moduleFiles:c,toJS:u,knownFiles:null});if(m.errors.length>0){m.errors.forEach(f=>console.error("\u5931\u8D25\uFF1A",f)),G+=1;return}we(a,l,u),T()||Se(W(a),ie(a,[],u,c))}if(T()||Ke(a,u).forEach(p=>console.log("\u6E05\u7406\uFF1A",R.resolve(a,p))),P.length){let p=ie(a,M?[]:P,u,ae(P,M));(y.config.pruneOutput&&!T()?$e(a,t,p):[]).forEach(m=>console.log("\u6E05\u7406\uFF1A",R.resolve(a,m))),T()||Se(W(a),p)}}y.config.toJS&&console.log(T()?"\u6821\u9A8C\uFF1A":"\u5B8C\u6210\uFF1A",R.resolve(T()?n:x.param.output,`${x.param.name}.d.ts`)),s&&kr(n,s),L.existsSync(y.docFile)&&L.unlinkSync(y.docFile),y.param.removeDts&&!T()&&(console.log("\u6E05\u7406\uFF1A",R.resolve(x.param.output,`${x.param.name}.d.ts`)),hr(`npx rimraf ${R.resolve(x.param.output,`${x.param.name}.d.ts`)}`,{cwd:y.home}).toString()),y.rcDriven||pe(x.file,JSON.stringify(x.param,null,2))}async function En(){await wr(),await Rr(),nt()}export{En as generateApi};
13
+ `:"",p,""].filter(Boolean).join(`
14
+ `))}return r.toJS?(o.set("index.js",[i,...Ae(e.declarations,t,{runtimeOnly:!0}),""].filter(Boolean).join(`
15
+ `)),o.set("index.d.ts",[i,...Ae(e.declarations,t,{runtimeOnly:!1}),""].filter(Boolean).join(`
16
+ `))):o.set("index.ts",[i,...Ae(e.declarations,t,{runtimeOnly:!1}),""].filter(Boolean).join(`
17
+ `)),o}function Pr(e){let t=R.createSourceFile(`${Le}.js`,e,R.ScriptTarget.Latest,!0,R.ScriptKind.JS),r=new Map;for(let n=0;n<t.statements.length;n+=1){let s=t.statements[n];if(!R.isVariableStatement(s))continue;let o=Pe(s);if(!o)continue;let i=s.getEnd(),a=t.statements[n+1];a&&R.isExpressionStatement(a)&&a.expression.getText(t).includes(o)&&(i=a.getEnd(),n+=1),r.set(o,e.slice(s.getStart(t),i))}return r}function Lr(e,t,r){let n=Pr(e),s=new Map;for(let[i,a]of n){let l=t.get(i)??K,c=s.get(l);c?c.push(a):s.set(l,[a])}let o=new Map;for(let[i,a]of s)o.set(i,[r,...a,""].filter(Boolean).join(`
18
+ `));return o}function Oe(e){return X.existsSync(e)?X.readFileSync(e,"utf8"):null}function De(e){let t=U.join(e.dir,E),r=e.toJS?"index.d.ts":"index.ts",n=Oe(U.join(t,r));if(!n)return{written:[],errors:[`\u7F3A\u5C11\u5951\u7EA6\u51FA\u53E3\uFF1A${E}/${r}`]};let s=vr(n,`${Le}${U.extname(r)}`),o=e.moduleFiles.map(p=>({file:p,source:Oe(U.join(e.dir,`${p}${e.toJS?".d.ts":".ts"}`))})).filter(p=>!!p.source),i=Fr(s.declarations,o),a=Or(s,i,{toJS:e.toJS});if(e.toJS){let p=Oe(U.join(t,"index.js"));if(p)for(let[f,m]of Lr(p,i,s.header))a.set(`${f}.js`,m)}let l=[],c=new Set(["index.ts","index.js","index.d.ts"]);for(let p of a.keys()){if(c.has(p)||!e.knownFiles)continue;let f=`${E}/${p}`;X.existsSync(U.join(e.dir,f))&&!e.knownFiles.has(f)&&l.push(`\u8F93\u51FA\u76EE\u5F55\u5B58\u5728\u540C\u540D\u624B\u5199\u6587\u4EF6\uFF1A${f}\uFF08\u4E0D\u5C5E\u4E8E\u4E0A\u4E00\u8F6E\u751F\u6210\u6E05\u5355\uFF09`)}if(l.length>0)return{written:[],errors:l};let u=[];for(let[p,f]of a){let m=`${E}/${p}`;X.mkdirSync(U.dirname(U.join(e.dir,m)),{recursive:!0}),X.writeFileSync(U.join(e.dir,m),f),u.push(m)}return{written:u,errors:l}}var x={files:[],param:{}},g={home:gt.homedir(),enum:{}},L=0,D=[],T=null,dt=()=>process.argv.includes("--dry-run"),ht=()=>process.argv.includes("--json"),G=()=>process.argv.includes("--check");function Ie(){return b.join(gt.tmpdir(),`swagger2api-${process.pid}-${Date.now()}.json`)}function _(e,t=0){e&&console.log(e),process.exit(t)}async function Mr(){g.param={config:M(["--config","-c"]),configScan:$(["--config-scan","-cs"])??!0,configAll:$(["--config-all","-ca"]),quick:$(["--quick","-q"]),replaceTags:Me(["--replace-tags","-rt"],{length:2}),convertGet:$(["--convert-get","-cg"]),removeParam:$(["--remove-param","-rp"]),removePrefixIndex:M(["--remove-prefix-index","-rpi"]),removeDts:$(["--remove-dts","-rd"]),removeEmptyComponents:$(["--remove-empty-components","-rec"])??!0,extractRequestQuery:M(["--extract-request-query","-erq"]),extractResponseRaw:$(["--extract-response-raw","-err"]),template:b.resolve(Ge(),"./templates")},g.config={templates:M(["--templates","-t"])??g.param.template,defaultResponseAsSuccess:$(["--default-as-success","-d"]),generateResponses:$(["--responses","-r"]),generateUnionEnums:$("--union-enums"),addReadonly:$("--add-readonly"),generateRouteTypes:$("--route-types"),generateClient:!$("--no-client"),enumNamesAsValues:$("--enum-names-as-values"),extractRequestParams:$("--extract-request-params"),extractRequestBody:$("--extract-request-body"),extractResponseBody:$("--extract-response-body"),extractResponseError:$("--extract-response-error"),modular:$("--modular"),toJS:$("--js"),moduleNameIndex:Number(M("--module-name-index")??0),moduleNameFirstTag:$("--module-name-first-tag"),httpClientType:$("--axios")?"axios":"fetch",unwrapResponseData:$("--unwrap-response-data"),disableThrowOnError:$("--disable-throw-on-error"),singleHttpClient:$("--single-http-client"),silent:$("--silent")??!0,defaultResponseType:M("--default-response")??"void",typePrefix:M("--type-prefix")??"",typeSuffix:M("--type-suffix")??"",cleanOutput:$("--clean-output"),pruneOutput:$("--prune-output"),...M("--api-class-name")?{apiClassName:M("--api-class-name")}:{},patch:$("--patch"),debug:$("--debug"),anotherArrayType:$("--another-array-type"),sortTypes:$("--sort-types"),extractEnums:$("--extract-enums")},g.baseParam=structuredClone(g.param),g.baseConfig=structuredClone(g.config),Gr()}function P(e){let t=process.argv.slice(2);return e.some(r=>t.includes(r))}function yt(e){let t=e.input??{},r=e.output??{},n=e.types??{},s=e.naming??{},o=e.grouping??{},i=t.url??t.file;if(!i)return;let a=g.configDir??process.cwd();g.rcDriven=!0,g.rcUrl=Z(i)?i:b.resolve(a,i),g.rcOutput=b.resolve(a,r.dir??"./src/api"),g.rcName=r.name??"index",r.typeCheck!==void 0&&r.typeCheck!=="skip"&&r.typeCheck!=="enforce"&&console.error(`\u26A0\uFE0F \u5DF2\u5FFD\u7565 output.typeCheck=${JSON.stringify(r.typeCheck)}\uFF1A\u4EC5\u652F\u6301 skip / enforce\uFF0C\u56DE\u843D\u5230 skip`),g.typeCheck=r.typeCheck==="enforce"?"enforce":"skip";let l=g.param;l.quick=!0,!P(["--remove-prefix-index","-rpi"])&&s.pathPrefixIndex!==void 0&&(l.removePrefixIndex=String(s.pathPrefixIndex)),!P(["--convert-get","-cg"])&&s.convertGetToQuery!==void 0&&(l.convertGet=s.convertGetToQuery),!P(["--remove-param","-rp"])&&s.dropPathParams!==void 0&&(l.removeParam=s.dropPathParams),!P(["--extract-request-query","-erq"])&&n.extractQuery!==void 0&&(l.extractRequestQuery=n.extractQuery),!P(["--extract-response-raw","-err"])&&n.extractResponseRaw!==void 0&&(l.extractResponseRaw=!!n.extractResponseRaw),!P(["--remove-dts","-rd"])&&n.removeDts!==void 0&&(l.removeDts=n.removeDts),!P(["--replace-tags","-rt"])&&s.tagRewrite&&(l.replaceTags=s.tagRewrite);let c=g.config;!P(["--axios"])&&e.client?.type&&(c.httpClientType=e.client.type==="axios"?"axios":"fetch"),!P(["--js"])&&e.language?.target&&(c.toJS=e.language.target==="js"),!P(["--responses","-r"])&&n.responses!==void 0&&(c.generateResponses=!!n.responses),!P(["--unwrap-response-data"])&&n.unwrapData!==void 0&&(c.unwrapResponseData=!!n.unwrapData),!P(["--extract-request-params"])&&n.extractParams!==void 0&&(c.extractRequestParams=!!n.extractParams),!P(["--clean-output"])&&r.clean!==void 0&&(c.cleanOutput=!!r.clean),!P(["--modular"])&&r.mode==="grouped"&&(c.modular=!0),P(["--prune-output"])||(c.pruneOutput=r.prune===void 0?!!c.modular:!!r.prune),!P(["--module-name-index"])&&o.pathDepth!==void 0&&(c.moduleNameIndex=Number(o.pathDepth)),Object.keys(o).length&&(c.grouping=o)}function Gr(){let e=Ve(),t=Ke(process.cwd(),{projectFile:e.configFile});if(t.warnings.forEach(s=>console.error("\u26A0\uFE0F",s)),g.configDir=t.project.file?b.dirname(b.resolve(t.project.file)):process.cwd(),Xe(t.merged)){String(e.configFile??"").includes(",")&&(console.error("\u5931\u8D25\uFF1A\u591A\u76EE\u6807\u914D\u7F6E\u53EA\u63A5\u53D7\u5355\u4E2A --config \u6587\u4EF6"),_("\u7ED3\u675F\uFF1A--config \u4E0D\u63A5\u53D7\u591A\u4E2A\u6587\u4EF6",2));let s=Ne();s.errors.length>0&&(s.errors.forEach(i=>console.error("\u5931\u8D25\uFF1A",i)),_("\u7ED3\u675F\uFF1A\u76EE\u6807\u53C2\u6570\u4E0D\u5408\u6CD5",2));let o=Ze(t.merged,{profile:e.profile,configDir:g.configDir});o.warnings.forEach(i=>console.error("\u26A0\uFE0F",i)),o.errors.length>0&&(o.errors.forEach(i=>console.error("\u5931\u8D25\uFF1A",i)),_(`\u7ED3\u675F\uFF1A\u591A\u76EE\u6807\u914D\u7F6E\u6709 ${o.errors.length} \u5904\u95EE\u9898\uFF0C\u672A\u751F\u6210\u4EFB\u4F55\u76EE\u6807`,2)),s.id&&!o.targets.some(i=>i.id===s.id)&&(console.error(`\u5931\u8D25\uFF1A\u672A\u77E5\u76EE\u6807 ${s.id}\uFF08\u53EF\u9009\uFF1A${o.targets.map(i=>i.id).join("\u3001")}\uFF09`),_("\u7ED3\u675F\uFF1A--target \u672A\u5339\u914D\u4EFB\u4F55\u76EE\u6807",2)),g.targetMode=!0,g.rcDriven=!0,g.targets=s.id?o.targets.filter(i=>i.id===s.id):o.targets;return}let r=Ne();r.errors.length>0&&(r.errors.forEach(s=>console.error("\u5931\u8D25\uFF1A",s)),_("\u7ED3\u675F\uFF1A\u76EE\u6807\u53C2\u6570\u4E0D\u5408\u6CD5",2)),r.id&&(console.error("\u5931\u8D25\uFF1A\u5F53\u524D\u914D\u7F6E\u6CA1\u6709 targets\uFF0C--target \u65E0\u6CD5\u4F7F\u7528"),_("\u7ED3\u675F\uFF1A--target \u9700\u8981\u591A\u76EE\u6807\u914D\u7F6E",2));let n=oe(z(ie(z(t.merged),e.profile)));yt(n)}async function _r(){if(g.rcDriven){x.files=["(swagger2apirc)"];return}g.param.config?x.files=g.param.config.split(","):g.param.configScan&&(x.files=_e()),x.files.length==0&&(x.files=["saconfig.json"]),!g.param.configAll&&x.files.length>1&&(x.files=(await mt({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:x.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:_("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),x.files?.length>0||_("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function Br(){if(g.rcDriven){x.param={url:g.rcUrl,output:g.rcOutput,name:g.rcName},g.docFile=Ie();return}try{x.param={},x.param=JSON.parse(I.readFileSync(x.file,"utf-8"))}catch{}(!g.param.quick||[x.param.url,x.param.output,x.param.name].includes(void 0))&&(x.param=await mt([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:x.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:x.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:x.param.name??"index"}])),[x.param.url,x.param.output,x.param.name].includes(void 0)&&_("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),g.docFile=Ie()}async function xt(e){if(Z(e)){let t=await Dr.get(e);await ft(t.data);return}await ft(JSON.parse(I.readFileSync(b.resolve(e),"utf8")))}async function St(e=0){x.file=x.files[e],await Br();try{await xt(x.param.url)}catch(t){L+=1,console.error("\u5931\u8D25\uFF1A",t)}x.files[e+1]?await St(e+1):L>0&&_(`\u7ED3\u675F\uFF1A${L} \u4E2A\u6587\u6863\u672A\u751F\u6210\uFF0C\u5931\u8D25\u539F\u56E0\u89C1\u4E0A\u65B9\u8F93\u51FA`,1)}function Ur(e){let t=g.param.replaceTags;if(!t?.length)return;let[r,n]=t;if(!r||typeof n!="string"){console.error("\u26A0\uFE0F \u5DF2\u5FFD\u7565 --replace-tags\uFF1A\u9700\u8981\u300C\u5339\u914D + \u66FF\u6362\u300D\u4E24\u4E2A\u503C\uFF0C\u56DE\u843D\u5230\u4FDD\u7559\u539F\u59CB\u6807\u7B7E");return}Object.values(e.paths??{}).forEach(s=>{Object.values(s).forEach(o=>{Array.isArray(o?.tags)&&(o.tags=o.tags.map(i=>i.replace(new RegExp(`^${r}$`,"g"),n)))})})}function me(e,t){let r=t?[...t.buckets.map(n=>n.fileName),...t.namespaces.flatMap(n=>n.chunks.map(s=>s.fileName)),...t.namespaces.filter(n=>n.chunks.length>0).map(n=>n.fileName)]:e.map(n=>n.fileName);return[...new Set(r)]}function $t(e,t=e){let r=[];for(let n of I.readdirSync(e,{withFileTypes:!0})){let s=b.join(e,n.name);n.isDirectory()?r.push(...$t(s,t)):r.push(b.relative(t,s).split(b.sep).join("/"))}return r.sort()}function Jr(e,t){let r=$t(t),n=[];for(let o of r){let i=b.join(e,o);if(!I.existsSync(i)){n.push(`\u7F3A\u5C11\u4EA7\u7269\uFF1A${o}`);continue}let a=I.readFileSync(b.join(t,o),"utf8").replace(/\r\n/g,`
19
+ `),l=I.readFileSync(i,"utf8").replace(/\r\n/g,`
20
+ `);a!==l&&n.push(`\u4EA7\u7269\u4E0D\u4E00\u81F4\uFF1A${o}`)}let s=fe(V(e));for(let o of s?.files??[])r.includes(o)||n.push(`\u4EA7\u7269\u5DF2\u8FC7\u671F\uFF1A${o}`);if(n.length>0){L+=1,console.error(`
21
+ \u2716 \u4EA7\u7269\u6821\u9A8C\u672A\u901A\u8FC7\uFF1A${n.length} \u9879`),n.forEach(o=>console.error(` - ${o}`));return}console.log("\u6821\u9A8C\uFF1A\u4EA7\u7269\u4E0E\u5F53\u524D\u914D\u7F6E\u4E00\u81F4")}function Hr(e,t,r){let n=!!g.config.toJS,s=n?".js":".ts",o=b.resolve(x.param.output??"./src/api"),i=I.existsSync(o)?I.readdirSync(o):[],a=me(e,r),c=a.flatMap(f=>n?[`${f}${s}`,`${f}.d.ts`]:[`${f}${s}`]).filter(f=>!i.includes(f)),u=pe(i,e,s,a),p={groups:e.map(({raw:f,fileName:m,className:h,property:y,importFrom:w,reason:k,source:S})=>({raw:f,fileName:m,className:h,property:y,importFrom:w,reason:k,source:S})),unmatchedRules:t,add:c,orphans:u,split:r?{total:r.total,buckets:r.buckets.map(({fileName:f,category:m,routes:h,namespaces:y})=>({fileName:f,category:m,routes:h,namespaces:y})),shards:r.namespaces.filter(f=>f.chunks.length>0).map(({raw:f,fileName:m,className:h,routes:y,chunks:w})=>({raw:f,fileName:m,className:h,routes:y,chunks:w.map(({fileName:k,routes:S,categories:v})=>({fileName:k,routes:S,categories:v}))}))}:void 0};if(ht()){if(g.targetMode){(g.groupReports??=[]).push({id:g.currentTarget??"",report:p});return}console.log(JSON.stringify(p,null,2));return}e.forEach(f=>console.log(`\u547D\u540D\uFF1A${f.raw} \u2192 ${f.fileName}\uFF08\u7C7B ${f.className}${f.reason?`\uFF0C${f.reason}`:""}\uFF09`)),r?.buckets.forEach(f=>console.log(`\u6876\uFF1A${f.fileName}\uFF08${f.namespaces.length} \u4E2A\u547D\u540D\u7A7A\u95F4 / ${f.routes} \u6761${f.category?`\uFF0C\u5206\u7C7B ${f.category}`:""}\uFF09`)),r?.namespaces.filter(f=>f.chunks.length>0).forEach(f=>console.log(`\u5206\u7247\uFF1A${f.raw} \u2192 ${f.chunks.map(m=>`${m.fileName}\uFF08${m.routes} \u6761\uFF09`).join("\u3001")}`)),t.length&&console.error(`\u26A0\uFE0F \u672A\u547D\u4E2D\u89C4\u5219\uFF1A${t.map(f=>f+1).join("\u3001")}`),c.length&&console.log(`\u9884\u8BA1\u65B0\u589E\uFF1A${c.join("\u3001")}`),u.length&&console.error(`\u26A0\uFE0F \u8868\u5916\u4EA7\u7269\uFF08\u5EFA\u8BAE\u5F00\u542F output.prune\uFF09\uFF1A${u.join("\u3001")}`)}function qr(){let e=new Map;return{onCreateRouteName(t,r){let n=`${r?.tags?.[1]??""}|${t.original}`,s=(e.get(n)??0)+1;return e.set(n,s),{...t,usage:s>1?`${t.original}${s}`:t.original,duplicate:s>1}}}}async function ft(e){let t=null;if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");let r=await We(e,{baseUrl:Z(x.param.url)?x.param.url:void 0});if(r.errors.length>0){r.errors.forEach(a=>console.error("\u5931\u8D25\uFF1A",a)),L+=1;return}let n=b.resolve(x.param.output),s=null;if(G()){if(!I.existsSync(n)){console.error(`\u5931\u8D25\uFF1A--check \u9700\u8981\u5DF2\u6709\u4EA7\u7269\u76EE\u5F55\uFF1A${n}`),L+=1;return}s=I.mkdtempSync(b.join(b.dirname(n),".swagger2api-check-")),x.param.output=s,process.once("exit",()=>I.rmSync(s,{recursive:!0,force:!0}))}D=[],T=null,g.param.moduleClassNames=void 0,g.param.splitBuckets=void 0,Ur(e);let o=g.config.grouping;if(g.config.modular&&o&&(o.strategy?.length||o.rules?.length||o.split)){let a=ut(e,o);if(a.warnings.forEach(l=>console.error("\u26A0\uFE0F",l)),a.errors.length>0){a.errors.forEach(l=>console.error("\u5931\u8D25\uFF1A",l)),L+=1;return}if(D=a.entries,T=a.split??null,g.config.moduleNameFirstTag=!0,g.param.moduleClassNames=a.moduleClassNames??ot(a.entries),g.param.splitBuckets=a.split?.bucketLayout,o.preserveTags!==!1&&(g.param.groupOriginalTags=a.originalTags),console.log("\u5206\u7EC4\uFF1A",...Object.entries(a.counts).map(([l,c])=>`${l}-${c}`)),dt()){Hr(a.entries,a.unmatchedRules,T);return}}if(g.config.modular&&D.length){let a=b.resolve(x.param.output);t=fe(V(a));let c=ct(a,T?[]:D,!!g.config.toJS,t,me(D,T));if(c.length>0){c.forEach(u=>console.error(`\u5931\u8D25\uFF1A\u8F93\u51FA\u76EE\u5F55\u5B58\u5728\u540C\u540D\u624B\u5199\u6587\u4EF6\uFF1A${u}\uFF08\u4E0D\u5C5E\u4E8E\u4E0A\u4E00\u8F6E\u751F\u6210\u6E05\u5355\uFF09\uFF0C\u5DF2\u7EC8\u6B62\u751F\u6210\uFF1B\u786E\u8BA4\u53EF\u8986\u76D6\u540E\u5220\u9664\u8BE5\u6587\u4EF6\u6216\u8C03\u6574\u5206\u7EC4\u540D`)),L+=1;return}}if(Object.entries(e.paths).forEach(a=>{Object.keys(a[1]).forEach(l=>{let c=`${a[0]}/${l}`;if(g.param.convertGet&&(c=c.replace(/([^\}]\/)get$/g,"$1query")),g.param.removeParam&&(c=c.replace(/\/\{.+?\}/g,"")),g.param.removePrefixIndex){let p=c.split("/");p=p.slice(0,1).concat(p.slice(Number(g.param.removePrefixIndex)+2)),c=p.join("/")}c=c.replace(/["\\`\r\n]/g,"_").replace(/\$\{/g,"_"),e.paths[a[0]][l].operationId=c;let u=c.split("/").slice(-1)[0];typeof g.enum[u]=="number"?g.enum[u]++:g.enum[u]=1})}),Object.entries(e.components).forEach(a=>{Object.keys(a[1]).forEach(l=>{g.param.removeEmptyComponents&&!Object.keys(e.components[a[0]][l]).length&&delete e.components[a[0]][l]})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(g.enum).map(a=>a.join("-"))),ye(g.docFile,JSON.stringify(e)),g.config.modular){let a=g.config;a.fileNames={...a.fileNames??{},dataContracts:`${E}/index`,httpClient:A},I.mkdirSync(b.join(b.resolve(x.param.output),E),{recursive:!0})}console.log("\u6267\u884C\uFF1A",x.file);let i=await Tr({fileName:`${x.param.name}.ts`,output:b.resolve(x.param.output),input:g.docFile,...g.config,...T?{hooks:qr()}:{},param:g.param});if(console.log(G()?"\u6821\u9A8C\uFF1A":"\u5B8C\u6210\uFF1A",b.resolve(G()?n:x.param.output,`${x.param.name}${g.config.toJS?".js":".ts"}`)),g.config.modular){let a=b.resolve(x.param.output),l=String(g.config.apiClassName??"Api"),c=!!g.config.toJS;if(D.length){let u=me(D,T);T&&lt(a,T.namespaces,c);let p=De({dir:a,moduleFiles:u,toJS:c,knownFiles:new Set(t?.files??[])});if(p.errors.length>0){p.errors.forEach(y=>console.error("\u5931\u8D25\uFF1A",y)),L+=1;return}let f=je(a,D,c,{aggregate:!1,extraFiles:u});if(f.errors.length>0){f.errors.forEach(y=>console.error("\u5931\u8D25\uFF1A",y)),L+=1;return}ve(a,l,c,it(D));let{errors:m,orphans:h}=je(a,D,c,{extraFiles:u});if(m.length>0){m.forEach(y=>console.error("\u5931\u8D25\uFF1A",y)),L+=1;return}h.forEach(y=>console.error("\u26A0\uFE0F \u8868\u5916\u4EA7\u7269\uFF08\u5EFA\u8BAE\u5F00\u542F output.prune\uFF09\uFF1A",y))}else{let u=(i.files??[]).map(m=>`${String(m.fileName??"").replace(/\\/g,"/")}${m.fileExtension??""}`).filter(m=>!!m&&!m.startsWith(".")),p=u.filter(m=>!m.includes("/")&&!m.endsWith(".d.ts")).map(m=>m.slice(0,m.lastIndexOf("."))).filter(m=>!!m&&!["index",A,"route-types"].includes(m)&&!m.endsWith("Route"));if(!G()){let m=fe(V(a));Ee(a,m,u.length>0?u:ge(a,[],c)).forEach(h=>console.log("\u6E05\u7406\uFF1A",b.resolve(a,h)))}let f=De({dir:a,moduleFiles:p,toJS:c,knownFiles:null});if(f.errors.length>0){f.errors.forEach(m=>console.error("\u5931\u8D25\uFF1A",m)),L+=1;return}ve(a,l,c),G()||ke(V(a),ge(a,[],c,p))}if(G()||at(a,c).forEach(u=>console.log("\u6E05\u7406\uFF1A",b.resolve(a,u))),D.length){let u=ge(a,T?[]:D,c,me(D,T));(g.config.pruneOutput&&!G()?Ee(a,t,u):[]).forEach(f=>console.log("\u6E05\u7406\uFF1A",b.resolve(a,f))),G()||ke(V(a),u)}}if(g.typeCheck==="enforce"){let a=b.resolve(x.param.output);rt(a).forEach(l=>console.log("\u5904\u7406\uFF1A",b.resolve(a,l)))}g.config.toJS&&console.log(G()?"\u6821\u9A8C\uFF1A":"\u5B8C\u6210\uFF1A",b.resolve(G()?n:x.param.output,`${x.param.name}.d.ts`)),s&&Jr(n,s),I.existsSync(g.docFile)&&I.unlinkSync(g.docFile),g.param.removeDts&&!G()&&(console.log("\u6E05\u7406\uFF1A",b.resolve(x.param.output,`${x.param.name}.d.ts`)),Ir(`npx rimraf ${b.resolve(x.param.output,`${x.param.name}.d.ts`)}`,{cwd:g.home}).toString()),g.rcDriven||ye(x.file,JSON.stringify(x.param,null,2))}async function Wr(){let e=g.targets??[],t=[],r=0;for(let n of e){g.param=structuredClone(g.baseParam),g.config=structuredClone(g.baseConfig),g.enum={},D=[],T=null,g.groupReports=[],g.currentTarget=n.id,yt(n.config),x.file=`(targets:${n.id})`,x.param={url:g.rcUrl,output:g.rcOutput,name:g.rcName},g.docFile=Ie(),console.log(`
22
+ \u76EE\u6807\uFF1A${n.id}\uFF08${n.input} \u2192 ${n.outputDir}\uFF09`);let s=L;try{await xt(n.input)}catch(i){L+=1,console.error(`\u5931\u8D25\uFF1A\u76EE\u6807 ${n.id}\uFF1A${i.message}`)}let o=L===s;o||(r+=1),t.push({id:n.id,ok:o,report:g.groupReports?.[0]?.report})}dt()&&ht()&&console.log(JSON.stringify({targets:t},null,2)),r>0&&_(`\u7ED3\u675F\uFF1A${r} \u4E2A\u76EE\u6807\u5931\u8D25\uFF08\u5171 ${e.length} \u4E2A\uFF09\uFF0C\u5176\u4F59\u76EE\u6807\u5DF2\u5B8C\u6210`,1)}async function es(){if(await Mr(),g.targetMode){await Wr();return}await _r(),await St()}export{es as generateApi};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fxri/swagger2api",
3
- "version": "1.3.1",
3
+ "version": "1.3.2",
4
4
  "description": "基于 swagger-typescript-api,将 Swagger 文档自动转为 TypeScript 格式的 API 文件。",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -3,7 +3,7 @@ name: fxri-swagger2api
3
3
  description: 首次为项目初始化 swagger2api 配置、迁移旧脚本配置或调整产物结构时加载:给出最小配置、先预览再落盘、说明分组产物与验收方式。日常生成、--check 与验收不加载。不用于一般 TypeScript / axios 用法或接口文档编写。
4
4
  license: MIT
5
5
  metadata:
6
- version: "1.0.0"
6
+ version: "1.1.2"
7
7
  tier: optional
8
8
  author: fxri
9
9
  source: https://github.com/fxri-net/swagger2api
@@ -11,7 +11,7 @@ metadata:
11
11
 
12
12
  # swagger2api 接入
13
13
 
14
- > 本技能版本 1.0.0(随 @fxri/swagger2api 分发)。被问版本时即报此值(不读磁盘、不跑 CLI);与已安装依赖的技能版本不一致即说明会话上下文已过期,开新会话即可。
14
+ > 本技能版本 1.1.2(随 @fxri/swagger2api 分发)。被问版本时即报此值(不读磁盘、不跑 CLI);与已安装依赖的技能版本不一致即说明会话上下文已过期,开新会话即可。
15
15
 
16
16
  ## 何时使用
17
17
 
@@ -32,11 +32,11 @@ metadata:
32
32
  单文件模式可先 `--dry-run` 看报表。发现拆法不符合预期时改分组规则,不要生成后再手改。
33
33
  5. **生成**:用项目既有脚本或 `swagger2api`(本地安装后)执行;首次生成后确认产物目录与配置一致。
34
34
  6. **验收**:跑 `swagger2api --check` 确认产物与配置一致;再跑项目类型检查。产物结构与验收口径见 `references/output.md`。
35
- 7. **记录边界**:生成物沿用 `// @ts-nocheck`,类型错误不进入下游检查;需要更强约束时在项目侧单独加类型探针,不要手改生成物。
35
+ 7. **记录边界**:生成物默认沿用 `// @ts-nocheck`,类型错误不进入下游检查;需要类型检查接管时配置 `typeCheck: "enforce"`,由工具统一剥离,不要手改生成物。
36
36
 
37
37
  ## 不做
38
38
 
39
- - 不手改生成物,也不删除 `@ts-nocheck` 后提交;下次生成会覆盖。
39
+ - 不手改生成物;需要去掉 `@ts-nocheck` 时用 `typeCheck: "enforce"` 由工具剥离,不要手删后提交。
40
40
  - 不在日常生成、`--check` 或验收时加载本技能,避免把低频能力写成常驻流程。
41
41
  - 不猜分桶 / 分片阈值:阈值属于工具默认,业务配置只决定分组策略与命名。
42
42
  - 不把本机绝对路径、令牌或私网地址写进配置与示例。
@@ -6,11 +6,14 @@
6
6
 
7
7
  ```bash
8
8
  swagger2api # 按最近的 swagger2api.json 生成
9
+ swagger2api --target lc # 多目标配置下只生成指定目标
9
10
  swagger2api --check # 生成到临时目录并与现有产物比对,不写真实目录
10
11
  swagger2api init # 交互生成 swagger2api.json
11
12
  swagger2api init --from-script package.json # 从既有 npm script 迁移参数
12
13
  swagger2api grouping # 查看分组分布并写入分组配置
13
14
  swagger2api config status # 查看配置分层与生效结果
15
+ swagger2api surface --out .swagger2api/surface.json # 写接口面基线
16
+ swagger2api surface --compare .swagger2api/surface.json # 与基线比对接口与类型增删
14
17
  swagger2api skill # 输出包内技能入口绝对路径
15
18
  swagger2api skill --print # 输出技能入口全文
16
19
  swagger2api skill --json # 输出入口、references 目录与技能版本
@@ -25,6 +28,7 @@ swagger2api skill --json # 输出入口、references 目录与技能版
25
28
  | `--json` | 与 `--dry-run` 组合时输出结构化报表 |
26
29
  | `--prune-output` | 按上一轮清单清理已消失模块,不触碰手写文件 |
27
30
  | `--config <path>` | 显式指定项目层配置 |
31
+ | `--target <id>` | 多目标配置下只执行指定目标;未知目标退出码 2 |
28
32
  | `--profile <name>` | 选用配置内的命名预设 |
29
33
 
30
34
  ## 使用顺序
@@ -21,12 +21,31 @@
21
21
  | `output.mode` | `single`(默认)/ `grouped` | 接口多、单文件过大时切 `grouped` |
22
22
  | `client.type` | `fetch`(默认)/ `axios` | 项目已用 axios 或需要拦截器时选 `axios` |
23
23
  | `language.target` | `ts`(默认)/ `js` | 产物要与现有 JS 代码共存时选 `js`(同时生成声明) |
24
+ | `output.typeCheck` | `skip`(默认)/ `enforce` | 需要项目类型检查覆盖生成物时选 `enforce`(工具剥离 `@ts-nocheck`) |
24
25
  | `types.responses` | 布尔 | 需要响应类型信息时开启 |
25
26
  | `types.extractQuery` | 字段名数组 | 后端把分页 / 筛选包在 query 对象里,需要提到根部时 |
26
27
  | `types.extractResponseRaw` | 布尔 | 需要在响应里保留原始 `raw` 时 |
27
28
  | `naming.pathPrefixIndex` | 非负整数 | 路径首段是网关前缀、不该进命名时去掉 |
28
29
  | `naming.tagRewrite` | `[匹配, 替换]` | 标签带环境前缀或需要统一命名时 |
29
30
 
31
+ ## 多目标
32
+
33
+ 同一仓多个 Swagger 文档用一份配置,公共口径写 `defaults`:
34
+
35
+ ```json
36
+ {
37
+ "defaults": { "mode": "grouped", "client": "axios" },
38
+ "targets": [
39
+ { "id": "base", "url": "https://example.com/base/v3/api-docs", "output": "./src/api/base" },
40
+ { "id": "lc", "url": "https://example.com/lc/v3/api-docs", "output": "./src/api/lc" }
41
+ ]
42
+ }
43
+ ```
44
+
45
+ - `id` 唯一,`name` 仍是入口文件名;目标项覆盖 `defaults`
46
+ - 无参数跑全部,`--target <id>` 跑单个,`--check` 校验全部
47
+ - 输出目录相同或互相嵌套会被拒绝(退出码 2,不落盘);目标内相对路径按配置文件所在目录解析
48
+
30
49
  ## 分层
31
50
 
32
51
  - 项目层 `swagger2api.json`:随仓库提交,团队共用。
@@ -18,6 +18,21 @@ swagger2api init --from-script package.json
18
18
  - 迁移时只搬实际生效的字段,不照抄整份旧配置。
19
19
  - 路径、输出目录与名字按新项目重定;旧项目的绝对路径不要带过来。
20
20
 
21
+ ## 跨版本迁移比对
22
+
23
+ 迁移工具版本或产物结构前,先固定接口面基线:
24
+
25
+ ```bash
26
+ swagger2api surface --out .swagger2api/surface.json
27
+ # 迁移后
28
+ swagger2api surface --compare .swagger2api/surface.json
29
+ ```
30
+
31
+ - 从产物目录的 `.ts` / `.d.ts` / `.js` 提取 `@request`、`@name` 与导出类型,结果带 `formatVersion`,默认不提交
32
+ - 比对一致退出 0;有增删逐条输出 `+` / `-` 并非 0 退出;`--requests-only` 只锁接口集合,忽略方法名与类型名
33
+ - 多目标配置按 `id` 分组比对,目标新增 / 缺失同样报错;`--target <id>` 只处理单个目标
34
+ - 基线建议放 `.swagger2api/` 并加入忽略清单;需要长期回归时由 CI 生成后临时比对
35
+
21
36
  ## 迁移后的验收
22
37
 
23
38
  1. `--dry-run --json` 对比迁移前后的命名与预计文件。
@@ -20,7 +20,7 @@
20
20
 
21
21
  ## 边界
22
22
 
23
- - 生成物沿用 `// @ts-nocheck`:类型错误不进入下游检查,不要靠手改生成物修类型。
23
+ - 生成物默认沿用 `// @ts-nocheck`:类型错误不进入下游检查,不要靠手改生成物修类型;需要类型检查接管时配置 `typeCheck: "enforce"`,由工具统一剥离该行,`--check` 走同一处理。
24
24
  - 生成清单落在系统临时目录,不进入仓库;`--check` 据此判断缺失、多出与内容不一致。
25
25
  - 旧版 `data-contracts.ts` / `http-client.ts` 不再生成,重新生成成功后会清理残留。
26
26
  - 手写文件不在清单内时不会被清理;同名冲突会终止生成并提示。
@@ -28,5 +28,5 @@
28
28
  ## 验收
29
29
 
30
30
  1. `swagger2api --check` 通过(产物与配置一致)。
31
- 2. 项目类型检查通过;需要更强约束时在项目侧写类型探针,不改生成物。
31
+ 2. 项目类型检查通过;未开启 `typeCheck: "enforce"` 时需要更强约束就在项目侧写类型探针,不改生成物。
32
32
  3. 抽查聚合入口:模块挂载、`export * from "./types"`、`export * from "./client"` 均存在。