@fxri/swagger2api 1.1.6 → 1.1.7
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/cli.cjs +1 -0
- package/dist/cli.js +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/templates/api.ejs +69 -0
- package/dist/templates/data-contract-jsdoc.ejs +37 -0
- package/dist/templates/data-contracts.ejs +40 -0
- package/dist/templates/enum-data-contract.ejs +18 -0
- package/dist/templates/http-client.ejs +155 -0
- package/dist/templates/interface-data-contract.ejs +10 -0
- package/dist/templates/object-field-jsdoc.ejs +28 -0
- package/dist/templates/procedure-call.ejs +109 -0
- package/dist/templates/route-docs.ejs +30 -0
- package/dist/templates/route-name.ejs +43 -0
- package/dist/templates/route-type.ejs +24 -0
- package/dist/templates/route-types.ejs +32 -0
- package/dist/templates/type-data-contract.ejs +15 -0
- package/package.json +6 -5
- package/dist/bin/index.cjs +0 -1
- package/dist/bin/index.js +0 -1
- /package/dist/{bin/index.d.cts → cli.d.cts} +0 -0
- /package/dist/{bin/index.d.ts → cli.d.ts} +0 -0
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var $=Object.create;var v=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var E=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var C=(e,r,s,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of k(r))!_.call(e,i)&&i!==s&&v(e,i,{get:()=>r[i],enumerable:!(o=T(r,i))||o.enumerable});return e};var l=(e,r,s)=>(s=e!=null?$(E(e)):{},C(r||!e||!e.__esModule?v(s,"default",{value:e,enumerable:!0}):s,e));var R=l(require("axios"),1),j=require("child_process"),A=l(require("os"),1),g=l(require("fs"),1),c=l(require("path"),1),h=l(require("prompts"),1),F=require("swagger-typescript-api");var b=e=>/^(https?:\/\/|:?\/\/)/.test(e);var f=l(require("fs"),1),w=l(require("url"),1),d=l(require("path"),1),L={},u={param:process.argv.filter((e,r)=>r>1),used:{}};function S(e,r=!0,s=!0){Array.isArray(e)||(e=[e]);let o;return u.param.forEach((i,p)=>{if(e.includes(i))r?(o=u.param[p+1],s&&Object.assign(u.used,{[p+1]:!0})):["true","false"].includes(u.param[p+1])?(o=u.param[p+1].toLowerCase()=="true",s&&Object.assign(u.used,{[p+1]:!0})):o=!0;else return;s&&Object.assign(u.used,{[p]:!0})}),o}function t(e,r=!0){return S(e,!1,r)}function m(e,r=!0){return S(e,!0,r)}function y(e,r){let s=d.default.dirname(e);f.default.existsSync(s)||f.default.mkdirSync(s,{recursive:!0}),f.default.writeFileSync(e,r)}function I(){return typeof require<"u"&&typeof module<"u"?__filename:w.default.fileURLToPath(L.url)}function P(){return typeof require<"u"&&typeof module<"u"?__dirname:d.default.dirname(I())}var O=require("glob"),a={files:[],param:{}},n={home:A.default.homedir(),enum:{}};function x(e){e&&console.log(e),process.exit()}async function J(){n.param={config:m(["--config","-c"]),configScan:t(["--config-scan","-cs"]),configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:m(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),extractRequestQuery:m(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"]),template:c.default.resolve(P(),"./templates")},n.config={templates:m(["--templates","-t"])??n.param.template,defaultResponseAsSuccess:t(["--default-as-success","-d"]),generateResponses:t(["--responses","-r"]),generateUnionEnums:t("--union-enums"),addReadonly:t("--add-readonly"),generateRouteTypes:t("--route-types"),generateClient:!t("--no-client"),enumNamesAsValues:t("--enum-names-as-values"),extractRequestParams:t("--extract-request-params"),extractRequestBody:t("--extract-request-body"),extractResponseBody:t("--extract-response-body"),extractResponseError:t("--extract-response-error"),modular:t("--modular"),toJS:t("--js"),moduleNameIndex:Number(m("--module-name-index")??0),moduleNameFirstTag:t("--module-name-first-tag"),httpClientType:t("--axios")?"axios":"fetch",unwrapResponseData:t("--unwrap-response-data"),disableThrowOnError:t("--disable-throw-on-error"),singleHttpClient:t("--single-http-client"),silent:t("--silent"),defaultResponseType:m("--default-response")??"void",typePrefix:m("--type-prefix")??"",typeSuffix:m("--type-suffix")??"",cleanOutput:t("--clean-output"),...m("--api-class-name")?{apiClassName:m("--api-class-name")}:{},patch:t("--patch"),debug:t("--debug"),anotherArrayType:t("--another-array-type"),sortTypes:t("--sort-types"),extractEnums:t("--extract-enums")}}async function U(){n.param.config?a.files=n.param.config.split(","):(n.param.configScan??!0)&&(a.files=O.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!n.param.configAll&&a.files.length>1&&(a.files=(await(0,h.default)({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:a.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:x("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||x("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function G(){try{a.param={},a.param=JSON.parse(g.default.readFileSync(a.file,"utf-8"))}catch{}(!n.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await(0,h.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&x("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),n.docFile=c.default.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function D(e=0){if(a.file=a.files[e],await G(),b(a.param.url))await R.default.get(a.param.url).then(r=>q(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await q(JSON.parse(g.default.readFileSync(c.default.resolve(a.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}a.files[e+1]&&D(e+1)}async function q(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(r=>{Object.keys(r[1]).forEach(s=>{let o=`${r[0]}/${s}`;if(n.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),n.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),n.param.removePrefixIndex){let p=o.split("/");p=p.slice(0,1).concat(p.slice(Number(n.param.removePrefixIndex)+2)),o=p.join("/")}e.paths[r[0]][s].operationId=o;let i=o.split("/").slice(-1)[0];typeof n.enum[i]=="number"?n.enum[i]++:n.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(n.enum).map(r=>r.join("-"))),y(n.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await(0,F.generateApi)({fileName:`${a.param.name}.ts`,output:c.default.resolve(a.param.output),input:n.docFile,...n.config,param:n.param}),g.default.unlinkSync(n.docFile),n.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",c.default.resolve(a.param.output,`${a.param.name}.d.ts`)),(0,j.execSync)(`npx rimraf ${c.default.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:n.home}).toString()),y(a.file,JSON.stringify(a.param,null,2))}async function N(){await J(),await U(),D()}N();
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,s)=>(typeof require<"u"?require:n)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import A from"axios";import{execSync as F}from"child_process";import O from"os";import y from"fs";import l from"path";import S from"prompts";import{generateApi as D}from"swagger-typescript-api";var x=e=>/^(https?:\/\/|:?\/\/)/.test(e);import f from"fs";import R from"url";import h from"path";var m={param:process.argv.filter((e,n)=>n>1),used:{}};function v(e,n=!0,s=!0){Array.isArray(e)||(e=[e]);let o;return m.param.forEach((u,i)=>{if(e.includes(u))n?(o=m.param[i+1],s&&Object.assign(m.used,{[i+1]:!0})):["true","false"].includes(m.param[i+1])?(o=m.param[i+1].toLowerCase()=="true",s&&Object.assign(m.used,{[i+1]:!0})):o=!0;else return;s&&Object.assign(m.used,{[i]:!0})}),o}function t(e,n=!0){return v(e,!1,n)}function p(e,n=!0){return v(e,!0,n)}function g(e,n){let s=h.dirname(e);f.existsSync(s)||f.mkdirSync(s,{recursive:!0}),f.writeFileSync(e,n)}function j(){return typeof c<"u"&&typeof module<"u"?__filename:R.fileURLToPath(import.meta.url)}function b(){return typeof c<"u"&&typeof module<"u"?__dirname:h.dirname(j())}import{glob as N}from"glob";var a={files:[],param:{}},r={home:O.homedir(),enum:{}};function d(e){e&&console.log(e),process.exit()}async function $(){r.param={config:p(["--config","-c"]),configScan:t(["--config-scan","-cs"]),configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:p(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),extractRequestQuery:p(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"]),template:l.resolve(b(),"./templates")},r.config={templates:p(["--templates","-t"])??r.param.template,defaultResponseAsSuccess:t(["--default-as-success","-d"]),generateResponses:t(["--responses","-r"]),generateUnionEnums:t("--union-enums"),addReadonly:t("--add-readonly"),generateRouteTypes:t("--route-types"),generateClient:!t("--no-client"),enumNamesAsValues:t("--enum-names-as-values"),extractRequestParams:t("--extract-request-params"),extractRequestBody:t("--extract-request-body"),extractResponseBody:t("--extract-response-body"),extractResponseError:t("--extract-response-error"),modular:t("--modular"),toJS:t("--js"),moduleNameIndex:Number(p("--module-name-index")??0),moduleNameFirstTag:t("--module-name-first-tag"),httpClientType:t("--axios")?"axios":"fetch",unwrapResponseData:t("--unwrap-response-data"),disableThrowOnError:t("--disable-throw-on-error"),singleHttpClient:t("--single-http-client"),silent:t("--silent"),defaultResponseType:p("--default-response")??"void",typePrefix:p("--type-prefix")??"",typeSuffix:p("--type-suffix")??"",cleanOutput:t("--clean-output"),...p("--api-class-name")?{apiClassName:p("--api-class-name")}:{},patch:t("--patch"),debug:t("--debug"),anotherArrayType:t("--another-array-type"),sortTypes:t("--sort-types"),extractEnums:t("--extract-enums")}}async function T(){r.param.config?a.files=r.param.config.split(","):(r.param.configScan??!0)&&(a.files=N.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!r.param.configAll&&a.files.length>1&&(a.files=(await S({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:a.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:d("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||d("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function k(){try{a.param={},a.param=JSON.parse(y.readFileSync(a.file,"utf-8"))}catch{}(!r.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await S([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&d("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),r.docFile=l.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function P(e=0){if(a.file=a.files[e],await k(),x(a.param.url))await A.get(a.param.url).then(n=>w(n.data)).catch(n=>console.log("\u5931\u8D25\uFF1A",n));else try{await w(JSON.parse(y.readFileSync(l.resolve(a.param.url),"utf8")))}catch(n){console.log("\u5931\u8D25\uFF1A",n)}a.files[e+1]&&P(e+1)}async function w(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(n=>{Object.keys(n[1]).forEach(s=>{let o=`${n[0]}/${s}`;if(r.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),r.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),r.param.removePrefixIndex){let i=o.split("/");i=i.slice(0,1).concat(i.slice(Number(r.param.removePrefixIndex)+2)),o=i.join("/")}e.paths[n[0]][s].operationId=o;let u=o.split("/").slice(-1)[0];typeof r.enum[u]=="number"?r.enum[u]++:r.enum[u]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(r.enum).map(n=>n.join("-"))),g(r.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await D({fileName:`${a.param.name}.ts`,output:l.resolve(a.param.output),input:r.docFile,...r.config,param:r.param}),y.unlinkSync(r.docFile),r.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",l.resolve(a.param.output,`${a.param.name}.d.ts`)),F(`npx rimraf ${l.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:r.home}).toString()),g(a.file,JSON.stringify(a.param,null,2))}async function q(){await $(),await T(),P()}q();
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var $=Object.create;var f=Object.defineProperty;var
|
|
1
|
+
var $=Object.create;var f=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var E=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var C=(e,t)=>{for(var o in t)f(e,o,{get:t[o],enumerable:!0})},b=(e,t,o,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of k(t))!_.call(e,i)&&i!==o&&f(e,i,{get:()=>t[i],enumerable:!(s=T(t,i))||s.enumerable});return e};var l=(e,t,o)=>(o=e!=null?$(E(e)):{},b(t||!e||!e.__esModule?f(o,"default",{value:e,enumerable:!0}):o,e)),I=e=>b(f({},"__esModule",{value:!0}),e);var K={};C(K,{generateApi:()=>B});module.exports=I(K);var j=l(require("axios"),1),F=require("child_process"),O=l(require("os"),1),d=l(require("fs"),1),c=l(require("path"),1),v=l(require("prompts"),1),A=require("swagger-typescript-api");var w=e=>/^(https?:\/\/|:?\/\/)/.test(e);var g=l(require("fs"),1),S=l(require("url"),1),y=l(require("path"),1),J={},u={param:process.argv.filter((e,t)=>t>1),used:{}};function P(e,t=!0,o=!0){Array.isArray(e)||(e=[e]);let s;return u.param.forEach((i,p)=>{if(e.includes(i))t?(s=u.param[p+1],o&&Object.assign(u.used,{[p+1]:!0})):["true","false"].includes(u.param[p+1])?(s=u.param[p+1].toLowerCase()=="true",o&&Object.assign(u.used,{[p+1]:!0})):s=!0;else return;o&&Object.assign(u.used,{[p]:!0})}),s}function r(e,t=!0){return P(e,!1,t)}function m(e,t=!0){return P(e,!0,t)}function x(e,t){let o=y.default.dirname(e);g.default.existsSync(o)||g.default.mkdirSync(o,{recursive:!0}),g.default.writeFileSync(e,t)}function L(){return typeof require<"u"&&typeof module<"u"?__filename:S.default.fileURLToPath(J.url)}function q(){return typeof require<"u"&&typeof module<"u"?__dirname:y.default.dirname(L())}var D=require("glob"),a={files:[],param:{}},n={home:O.default.homedir(),enum:{}};function h(e){e&&console.log(e),process.exit()}async function U(){n.param={config:m(["--config","-c"]),configScan:r(["--config-scan","-cs"]),configAll:r(["--config-all","-ca"]),quick:r(["--quick","-q"]),convertGet:r(["--convert-get","-cg"]),removeParam:r(["--remove-param","-rp"]),removePrefixIndex:m(["--remove-prefix-index","-rpi"]),removeDts:r(["--remove-dts","-rd"]),extractRequestQuery:m(["--extract-request-query","-erq"]),extractResponseRaw:r(["--extract-response-raw","-err"]),template:c.default.resolve(q(),"./templates")},n.config={templates:m(["--templates","-t"])??n.param.template,defaultResponseAsSuccess:r(["--default-as-success","-d"]),generateResponses:r(["--responses","-r"]),generateUnionEnums:r("--union-enums"),addReadonly:r("--add-readonly"),generateRouteTypes:r("--route-types"),generateClient:!r("--no-client"),enumNamesAsValues:r("--enum-names-as-values"),extractRequestParams:r("--extract-request-params"),extractRequestBody:r("--extract-request-body"),extractResponseBody:r("--extract-response-body"),extractResponseError:r("--extract-response-error"),modular:r("--modular"),toJS:r("--js"),moduleNameIndex:Number(m("--module-name-index")??0),moduleNameFirstTag:r("--module-name-first-tag"),httpClientType:r("--axios")?"axios":"fetch",unwrapResponseData:r("--unwrap-response-data"),disableThrowOnError:r("--disable-throw-on-error"),singleHttpClient:r("--single-http-client"),silent:r("--silent"),defaultResponseType:m("--default-response")??"void",typePrefix:m("--type-prefix")??"",typeSuffix:m("--type-suffix")??"",cleanOutput:r("--clean-output"),...m("--api-class-name")?{apiClassName:m("--api-class-name")}:{},patch:r("--patch"),debug:r("--debug"),anotherArrayType:r("--another-array-type"),sortTypes:r("--sort-types"),extractEnums:r("--extract-enums")}}async function G(){n.param.config?a.files=n.param.config.split(","):(n.param.configScan??!0)&&(a.files=D.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!n.param.configAll&&a.files.length>1&&(a.files=(await(0,v.default)({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:a.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:h("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||h("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function V(){try{a.param={},a.param=JSON.parse(d.default.readFileSync(a.file,"utf-8"))}catch{}(!n.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await(0,v.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&h("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),n.docFile=c.default.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function N(e=0){if(a.file=a.files[e],await V(),w(a.param.url))await j.default.get(a.param.url).then(t=>R(t.data)).catch(t=>console.log("\u5931\u8D25\uFF1A",t));else try{await R(JSON.parse(d.default.readFileSync(c.default.resolve(a.param.url),"utf8")))}catch(t){console.log("\u5931\u8D25\uFF1A",t)}a.files[e+1]&&N(e+1)}async function R(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(t=>{Object.keys(t[1]).forEach(o=>{let s=`${t[0]}/${o}`;if(n.param.convertGet&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),n.param.removeParam&&(s=s.replace(/\/\{.+?\}/g,"")),n.param.removePrefixIndex){let p=s.split("/");p=p.slice(0,1).concat(p.slice(Number(n.param.removePrefixIndex)+2)),s=p.join("/")}e.paths[t[0]][o].operationId=s;let i=s.split("/").slice(-1)[0];typeof n.enum[i]=="number"?n.enum[i]++:n.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(n.enum).map(t=>t.join("-"))),x(n.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await(0,A.generateApi)({fileName:`${a.param.name}.ts`,output:c.default.resolve(a.param.output),input:n.docFile,...n.config,param:n.param}),d.default.unlinkSync(n.docFile),n.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",c.default.resolve(a.param.output,`${a.param.name}.d.ts`)),(0,F.execSync)(`npx rimraf ${c.default.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:n.home}).toString()),x(a.file,JSON.stringify(a.param,null,2))}async function B(){await U(),await G(),N()}0&&(module.exports={generateApi});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
var c=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,s)=>(typeof require<"u"?require:n)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import j from"axios";import{execSync as F}from"child_process";import O from"os";import y from"fs";import l from"path";import S from"prompts";import{generateApi as A}from"swagger-typescript-api";var x=e=>/^(https?:\/\/|:?\/\/)/.test(e);import f from"fs";import q from"url";import h from"path";var m={param:process.argv.filter((e,n)=>n>1),used:{}};function v(e,n=!0,s=!0){Array.isArray(e)||(e=[e]);let o;return m.param.forEach((u,i)=>{if(e.includes(u))n?(o=m.param[i+1],s&&Object.assign(m.used,{[i+1]:!0})):["true","false"].includes(m.param[i+1])?(o=m.param[i+1].toLowerCase()=="true",s&&Object.assign(m.used,{[i+1]:!0})):o=!0;else return;s&&Object.assign(m.used,{[i]:!0})}),o}function t(e,n=!0){return v(e,!1,n)}function p(e,n=!0){return v(e,!0,n)}function g(e,n){let s=h.dirname(e);f.existsSync(s)||f.mkdirSync(s,{recursive:!0}),f.writeFileSync(e,n)}function R(){return typeof c<"u"&&typeof module<"u"?__filename:q.fileURLToPath(import.meta.url)}function b(){return typeof c<"u"&&typeof module<"u"?__dirname:h.dirname(R())}import{glob as D}from"glob";var a={files:[],param:{}},r={home:O.homedir(),enum:{}};function d(e){e&&console.log(e),process.exit()}async function N(){r.param={config:p(["--config","-c"]),configScan:t(["--config-scan","-cs"]),configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:p(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),extractRequestQuery:p(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"]),template:l.resolve(b(),"./templates")},r.config={templates:p(["--templates","-t"])??r.param.template,defaultResponseAsSuccess:t(["--default-as-success","-d"]),generateResponses:t(["--responses","-r"]),generateUnionEnums:t("--union-enums"),addReadonly:t("--add-readonly"),generateRouteTypes:t("--route-types"),generateClient:!t("--no-client"),enumNamesAsValues:t("--enum-names-as-values"),extractRequestParams:t("--extract-request-params"),extractRequestBody:t("--extract-request-body"),extractResponseBody:t("--extract-response-body"),extractResponseError:t("--extract-response-error"),modular:t("--modular"),toJS:t("--js"),moduleNameIndex:Number(p("--module-name-index")??0),moduleNameFirstTag:t("--module-name-first-tag"),httpClientType:t("--axios")?"axios":"fetch",unwrapResponseData:t("--unwrap-response-data"),disableThrowOnError:t("--disable-throw-on-error"),singleHttpClient:t("--single-http-client"),silent:t("--silent"),defaultResponseType:p("--default-response")??"void",typePrefix:p("--type-prefix")??"",typeSuffix:p("--type-suffix")??"",cleanOutput:t("--clean-output"),...p("--api-class-name")?{apiClassName:p("--api-class-name")}:{},patch:t("--patch"),debug:t("--debug"),anotherArrayType:t("--another-array-type"),sortTypes:t("--sort-types"),extractEnums:t("--extract-enums")}}async function $(){r.param.config?a.files=r.param.config.split(","):(r.param.configScan??!0)&&(a.files=D.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!r.param.configAll&&a.files.length>1&&(a.files=(await S({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:a.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:d("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||d("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function T(){try{a.param={},a.param=JSON.parse(y.readFileSync(a.file,"utf-8"))}catch{}(!r.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await S([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&d("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),r.docFile=l.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function P(e=0){if(a.file=a.files[e],await T(),x(a.param.url))await j.get(a.param.url).then(n=>w(n.data)).catch(n=>console.log("\u5931\u8D25\uFF1A",n));else try{await w(JSON.parse(y.readFileSync(l.resolve(a.param.url),"utf8")))}catch(n){console.log("\u5931\u8D25\uFF1A",n)}a.files[e+1]&&P(e+1)}async function w(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(n=>{Object.keys(n[1]).forEach(s=>{let o=`${n[0]}/${s}`;if(r.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),r.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),r.param.removePrefixIndex){let i=o.split("/");i=i.slice(0,1).concat(i.slice(Number(r.param.removePrefixIndex)+2)),o=i.join("/")}e.paths[n[0]][s].operationId=o;let u=o.split("/").slice(-1)[0];typeof r.enum[u]=="number"?r.enum[u]++:r.enum[u]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(r.enum).map(n=>n.join("-"))),g(r.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await A({fileName:`${a.param.name}.ts`,output:l.resolve(a.param.output),input:r.docFile,...r.config,param:r.param}),y.unlinkSync(r.docFile),r.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",l.resolve(a.param.output,`${a.param.name}.d.ts`)),F(`npx rimraf ${l.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:r.home}).toString()),g(a.file,JSON.stringify(a.param,null,2))}async function te(){await N(),await $(),P()}export{te as generateApi};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { apiConfig, routes, utils, config } = it;
|
|
3
|
+
const { info, servers, externalDocs } = apiConfig;
|
|
4
|
+
const { _, require, formatDescription } = utils;
|
|
5
|
+
|
|
6
|
+
const server = (servers && servers[0]) || { url: "" };
|
|
7
|
+
|
|
8
|
+
const descriptionLines = _.compact([
|
|
9
|
+
`@title ${info.title || "No title"}`,
|
|
10
|
+
info.version && `@version ${info.version}`,
|
|
11
|
+
info.license && `@license ${_.compact([
|
|
12
|
+
info.license.name,
|
|
13
|
+
info.license.url && `(${info.license.url})`,
|
|
14
|
+
]).join(" ")}`,
|
|
15
|
+
info.termsOfService && `@termsOfService ${info.termsOfService}`,
|
|
16
|
+
server.url && `@baseUrl ${server.url}`,
|
|
17
|
+
externalDocs.url && `@externalDocs ${externalDocs.url}`,
|
|
18
|
+
info.contact && `@contact ${_.compact([
|
|
19
|
+
info.contact.name,
|
|
20
|
+
info.contact.email && `<${info.contact.email}>`,
|
|
21
|
+
info.contact.url && `(${info.contact.url})`,
|
|
22
|
+
]).join(" ")}`,
|
|
23
|
+
info.description && " ",
|
|
24
|
+
info.description && _.replace(formatDescription(info.description), /\n/g, "\n * "),
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
%>
|
|
28
|
+
|
|
29
|
+
<% if (config.httpClientType === config.constants.HTTP_CLIENT.AXIOS) { %> import type { AxiosRequestConfig, AxiosResponse } from "axios"; <% } %>
|
|
30
|
+
|
|
31
|
+
<% if (descriptionLines.length) { %>
|
|
32
|
+
/**
|
|
33
|
+
<% descriptionLines.forEach((descriptionLine) => { %>
|
|
34
|
+
* <%~ descriptionLine %>
|
|
35
|
+
|
|
36
|
+
<% }) %>
|
|
37
|
+
*/
|
|
38
|
+
<% } %>
|
|
39
|
+
export class <%~ config.apiClassName %><SecurityDataType extends unknown><% if (!config.singleHttpClient) { %> extends HttpClient<SecurityDataType> <% } %> {
|
|
40
|
+
|
|
41
|
+
<% if(config.singleHttpClient) { %>
|
|
42
|
+
http: HttpClient<SecurityDataType>;
|
|
43
|
+
|
|
44
|
+
constructor (http: HttpClient<SecurityDataType>) {
|
|
45
|
+
this.http = http;
|
|
46
|
+
}
|
|
47
|
+
<% } %>
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
<% if (routes.outOfModule) { %>
|
|
51
|
+
<% for (const route of routes.outOfModule) { %>
|
|
52
|
+
|
|
53
|
+
<%~ includeFile('./procedure-call.ejs', { ...it, route }) %>
|
|
54
|
+
|
|
55
|
+
<% } %>
|
|
56
|
+
<% } %>
|
|
57
|
+
|
|
58
|
+
<% if (routes.combined) { %>
|
|
59
|
+
<% for (const { routes: combinedRoutes = [], moduleName } of routes.combined) { %>
|
|
60
|
+
<%~ moduleName %> = {
|
|
61
|
+
<% for (const route of combinedRoutes) { %>
|
|
62
|
+
|
|
63
|
+
<%~ includeFile('./procedure-call.ejs', { ...it, route }) %>
|
|
64
|
+
|
|
65
|
+
<% } %>
|
|
66
|
+
}
|
|
67
|
+
<% } %>
|
|
68
|
+
<% } %>
|
|
69
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { data, utils } = it;
|
|
3
|
+
const { formatDescription, require, _ } = utils;
|
|
4
|
+
|
|
5
|
+
const stringify = (value) => _.isObject(value) ? JSON.stringify(value) : _.isString(value) ? `"${value}"` : value;
|
|
6
|
+
|
|
7
|
+
const jsDocLines = _.compact([
|
|
8
|
+
data.title,
|
|
9
|
+
data.description && formatDescription(data.description),
|
|
10
|
+
!_.isUndefined(data.deprecated) && data.deprecated && '@deprecated',
|
|
11
|
+
!_.isUndefined(data.format) && `@format ${data.format}`,
|
|
12
|
+
!_.isUndefined(data.minimum) && `@min ${data.minimum}`,
|
|
13
|
+
!_.isUndefined(data.multipleOf) && `@multipleOf ${data.multipleOf}`,
|
|
14
|
+
!_.isUndefined(data.exclusiveMinimum) && `@exclusiveMin ${data.exclusiveMinimum}`,
|
|
15
|
+
!_.isUndefined(data.maximum) && `@max ${data.maximum}`,
|
|
16
|
+
!_.isUndefined(data.minLength) && `@minLength ${data.minLength}`,
|
|
17
|
+
!_.isUndefined(data.maxLength) && `@maxLength ${data.maxLength}`,
|
|
18
|
+
!_.isUndefined(data.exclusiveMaximum) && `@exclusiveMax ${data.exclusiveMaximum}`,
|
|
19
|
+
!_.isUndefined(data.maxItems) && `@maxItems ${data.maxItems}`,
|
|
20
|
+
!_.isUndefined(data.minItems) && `@minItems ${data.minItems}`,
|
|
21
|
+
!_.isUndefined(data.uniqueItems) && `@uniqueItems ${data.uniqueItems}`,
|
|
22
|
+
!_.isUndefined(data.default) && `@default ${stringify(data.default)}`,
|
|
23
|
+
!_.isUndefined(data.pattern) && `@pattern ${data.pattern}`,
|
|
24
|
+
!_.isUndefined(data.example) && `@example ${stringify(data.example)}`
|
|
25
|
+
]).join('\n').split('\n');
|
|
26
|
+
%>
|
|
27
|
+
<% if (jsDocLines.every(_.isEmpty)) { %>
|
|
28
|
+
<% } else if (jsDocLines.length === 1) { %>
|
|
29
|
+
/** <%~ jsDocLines[0] %> */
|
|
30
|
+
<% } else if (jsDocLines.length) { %>
|
|
31
|
+
/**
|
|
32
|
+
<% for (jsDocLine of jsDocLines) { %>
|
|
33
|
+
* <%~ jsDocLine %>
|
|
34
|
+
|
|
35
|
+
<% } %>
|
|
36
|
+
*/
|
|
37
|
+
<% } %>
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { modelTypes, utils, config } = it;
|
|
3
|
+
const { formatDescription, require, _, Ts } = utils;
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
const buildGenerics = (contract) => {
|
|
7
|
+
if (!contract.genericArgs || !contract.genericArgs.length) return '';
|
|
8
|
+
|
|
9
|
+
return '<' + contract.genericArgs.map(({ name, default: defaultType, extends: extendsType }) => {
|
|
10
|
+
return [
|
|
11
|
+
name,
|
|
12
|
+
extendsType && `extends ${extendsType}`,
|
|
13
|
+
defaultType && `= ${defaultType}`,
|
|
14
|
+
].join('')
|
|
15
|
+
}).join(',') + '>'
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const dataContractTemplates = {
|
|
19
|
+
enum: (contract) => {
|
|
20
|
+
return `enum ${contract.name} {\r\n${contract.content} \r\n }`;
|
|
21
|
+
},
|
|
22
|
+
interface: (contract) => {
|
|
23
|
+
return `interface ${contract.name}${buildGenerics(contract)} {\r\n${contract.content}}`;
|
|
24
|
+
},
|
|
25
|
+
type: (contract) => {
|
|
26
|
+
return `type ${contract.name}${buildGenerics(contract)} = ${contract.content}`;
|
|
27
|
+
},
|
|
28
|
+
}
|
|
29
|
+
%>
|
|
30
|
+
|
|
31
|
+
<% if (config.internalTemplateOptions.addUtilRequiredKeysType) { %>
|
|
32
|
+
type <%~ config.Ts.CodeGenKeyword.UtilRequiredKeys %><T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>
|
|
33
|
+
<% } %>
|
|
34
|
+
|
|
35
|
+
<% for (const contract of modelTypes) { %>
|
|
36
|
+
<%~ includeFile('./data-contract-jsdoc.ejs', { ...it, data: { ...contract, ...contract.typeData } }) %>
|
|
37
|
+
<%~ contract.internal ? '' : 'export'%> <%~ (dataContractTemplates[contract.typeIdentifier] || dataContractTemplates.type)(contract) %>
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
<% } %>
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { contract, utils, config } = it;
|
|
3
|
+
const { formatDescription, require, _ } = utils;
|
|
4
|
+
const { name, $content } = contract;
|
|
5
|
+
%>
|
|
6
|
+
<% if (config.generateUnionEnums) { %>
|
|
7
|
+
export type <%~ name %> = <%~ _.map($content, ({ value }) => value).join(" | ") %>
|
|
8
|
+
<% } else { %>
|
|
9
|
+
export enum <%~ name %> {
|
|
10
|
+
<%~ _.map($content, ({ key, value, description }) => {
|
|
11
|
+
let formattedDescription = description && formatDescription(description, true);
|
|
12
|
+
return [
|
|
13
|
+
formattedDescription && `/** ${formattedDescription} */`,
|
|
14
|
+
`${key} = ${value}`
|
|
15
|
+
].filter(Boolean).join("\n");
|
|
16
|
+
}).join(",\n") %>
|
|
17
|
+
}
|
|
18
|
+
<% } %>
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { apiConfig, generateResponses, config } = it;
|
|
3
|
+
%>
|
|
4
|
+
|
|
5
|
+
import type { AxiosInstance, AxiosRequestConfig, HeadersDefaults, ResponseType, AxiosResponse } from "axios";
|
|
6
|
+
import axios from "axios";
|
|
7
|
+
|
|
8
|
+
export type QueryParamsType = Record<string | number, any>;
|
|
9
|
+
|
|
10
|
+
<% if (config.param?.extractResponseRaw) { %>
|
|
11
|
+
/** 提取响应 */
|
|
12
|
+
export interface AxiosResponseRaw<T = any> {
|
|
13
|
+
/** 原始数据 */
|
|
14
|
+
raw: AxiosResponse<T>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
<% } %>
|
|
18
|
+
export interface FullRequestParams extends Omit<AxiosRequestConfig, "data" | "params" | "url" | "responseType"> {
|
|
19
|
+
/** set parameter to `true` for call `securityWorker` for this request */
|
|
20
|
+
secure?: boolean;
|
|
21
|
+
/** request path */
|
|
22
|
+
path: string;
|
|
23
|
+
/** content type of request body */
|
|
24
|
+
type?: ContentType;
|
|
25
|
+
/** query params */
|
|
26
|
+
query?: QueryParamsType;
|
|
27
|
+
/** format of response (i.e. response.json() -> format: "json") */
|
|
28
|
+
format?: ResponseType;
|
|
29
|
+
/** request body */
|
|
30
|
+
body?: unknown;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
|
|
34
|
+
|
|
35
|
+
export interface ApiConfig<SecurityDataType = unknown> extends Omit<AxiosRequestConfig, "data" | "cancelToken"> {
|
|
36
|
+
securityWorker?: (securityData: SecurityDataType | null) => Promise<AxiosRequestConfig | void> | AxiosRequestConfig | void;
|
|
37
|
+
secure?: boolean;
|
|
38
|
+
format?: ResponseType;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export enum ContentType {
|
|
42
|
+
Json = "application/json",
|
|
43
|
+
JsonApi = "application/vnd.api+json",
|
|
44
|
+
FormData = "multipart/form-data",
|
|
45
|
+
UrlEncoded = "application/x-www-form-urlencoded",
|
|
46
|
+
Text = "text/plain",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class HttpClient<SecurityDataType = unknown> {
|
|
50
|
+
public instance: AxiosInstance;
|
|
51
|
+
private securityData: SecurityDataType | null = null;
|
|
52
|
+
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
|
|
53
|
+
private secure?: boolean;
|
|
54
|
+
private format?: ResponseType;
|
|
55
|
+
|
|
56
|
+
constructor({ securityWorker, secure, format, ...axiosConfig }: ApiConfig<SecurityDataType> = {}) {
|
|
57
|
+
this.instance = axios.create({ ...axiosConfig, baseURL: axiosConfig.baseURL || "<%~ apiConfig.baseUrl %>" })
|
|
58
|
+
this.secure = secure;
|
|
59
|
+
this.format = format;
|
|
60
|
+
this.securityWorker = securityWorker;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
public setSecurityData = (data: SecurityDataType | null) => {
|
|
64
|
+
this.securityData = data
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
protected mergeRequestParams(params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfig {
|
|
68
|
+
const method = params1.method || (params2 && params2.method)
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
...this.instance.defaults,
|
|
72
|
+
...params1,
|
|
73
|
+
...(params2 || {}),
|
|
74
|
+
headers: {
|
|
75
|
+
...((method && this.instance.defaults.headers[method.toLowerCase() as keyof HeadersDefaults]) || {}),
|
|
76
|
+
...(params1.headers || {}),
|
|
77
|
+
...((params2 && params2.headers) || {}),
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
protected stringifyFormItem(formItem: unknown) {
|
|
83
|
+
if (typeof formItem === "object" && formItem !== null) {
|
|
84
|
+
return JSON.stringify(formItem);
|
|
85
|
+
} else {
|
|
86
|
+
return `${formItem}`;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
protected createFormData(input: Record<string, unknown>): FormData {
|
|
91
|
+
if (input instanceof FormData) {
|
|
92
|
+
return input;
|
|
93
|
+
}
|
|
94
|
+
return Object.keys(input || {}).reduce((formData, key) => {
|
|
95
|
+
const property = input[key];
|
|
96
|
+
const propertyContent: any[] = (property instanceof Array) ? property : [property]
|
|
97
|
+
|
|
98
|
+
for (const formItem of propertyContent) {
|
|
99
|
+
const isFileType = formItem instanceof Blob || formItem instanceof File;
|
|
100
|
+
formData.append(
|
|
101
|
+
key,
|
|
102
|
+
isFileType ? formItem : this.stringifyFormItem(formItem)
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return formData;
|
|
107
|
+
}, new FormData());
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
public request = async <T = any, _E = any>({
|
|
111
|
+
secure,
|
|
112
|
+
path,
|
|
113
|
+
type,
|
|
114
|
+
query,
|
|
115
|
+
format,
|
|
116
|
+
body,
|
|
117
|
+
...params
|
|
118
|
+
<% if (config.unwrapResponseData) { %>
|
|
119
|
+
}: FullRequestParams): Promise<T> => {
|
|
120
|
+
<% } else if (config.param?.extractResponseRaw) { %>
|
|
121
|
+
}: FullRequestParams): Promise<AxiosResponseRaw<T>> => {
|
|
122
|
+
<% } else { %>
|
|
123
|
+
}: FullRequestParams): Promise<AxiosResponse<T>> => {
|
|
124
|
+
<% } %>
|
|
125
|
+
const secureParams = ((typeof secure === 'boolean' ? secure : this.secure) && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
|
|
126
|
+
const requestParams = this.mergeRequestParams(params, secureParams);
|
|
127
|
+
const responseFormat = (format || this.format) || undefined;
|
|
128
|
+
|
|
129
|
+
if (type === ContentType.FormData && body && body !== null && typeof body === "object") {
|
|
130
|
+
body = this.createFormData(body as Record<string, unknown>);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (type === ContentType.Text && body && body !== null && typeof body !== "string") {
|
|
134
|
+
body = JSON.stringify(body);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return this.instance.request({
|
|
138
|
+
...requestParams,
|
|
139
|
+
headers: {
|
|
140
|
+
...(requestParams.headers || {}),
|
|
141
|
+
...(type ? { "Content-Type": type } : {}),
|
|
142
|
+
},
|
|
143
|
+
params: query,
|
|
144
|
+
responseType: responseFormat,
|
|
145
|
+
data: body,
|
|
146
|
+
url: path,
|
|
147
|
+
<% if (config.unwrapResponseData) { %>
|
|
148
|
+
}).then(response => response.data);
|
|
149
|
+
<% } else if (config.param?.extractResponseRaw) { %>
|
|
150
|
+
}).then(response => { raw: response });
|
|
151
|
+
<% } else { %>
|
|
152
|
+
});
|
|
153
|
+
<% } %>
|
|
154
|
+
};
|
|
155
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { contract, utils } = it;
|
|
3
|
+
const { formatDescription, require, _ } = utils;
|
|
4
|
+
%>
|
|
5
|
+
export interface <%~ contract.name %> {
|
|
6
|
+
<% for (const field of contract.$content) { %>
|
|
7
|
+
<%~ includeFile('./object-field-jsdoc.ejs', { ...it, field }) %>
|
|
8
|
+
<%~ field.name %><%~ field.isRequired ? '' : '?' %>: <%~ field.value %><%~ field.isNullable ? ' | null' : ''%>;
|
|
9
|
+
<% } %>
|
|
10
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { field, utils } = it;
|
|
3
|
+
const { formatDescription, require, _ } = utils;
|
|
4
|
+
|
|
5
|
+
const comments = _.uniq(
|
|
6
|
+
_.compact([
|
|
7
|
+
field.title,
|
|
8
|
+
field.description,
|
|
9
|
+
field.deprecated && ` * @deprecated`,
|
|
10
|
+
!_.isUndefined(field.format) && `@format ${field.format}`,
|
|
11
|
+
!_.isUndefined(field.minimum) && `@min ${field.minimum}`,
|
|
12
|
+
!_.isUndefined(field.maximum) && `@max ${field.maximum}`,
|
|
13
|
+
!_.isUndefined(field.pattern) && `@pattern ${field.pattern}`,
|
|
14
|
+
!_.isUndefined(field.example) &&
|
|
15
|
+
`@example ${_.isObject(field.example) ? JSON.stringify(field.example) : field.example}`,
|
|
16
|
+
]).reduce((acc, comment) => [...acc, ...comment.split(/\n/g)], []),
|
|
17
|
+
);
|
|
18
|
+
%>
|
|
19
|
+
<% if (comments.length === 1) { %>
|
|
20
|
+
/** <%~ comments[0] %> */
|
|
21
|
+
<% } else if (comments.length) { %>
|
|
22
|
+
/**
|
|
23
|
+
<% comments.forEach(comment => { %>
|
|
24
|
+
* <%~ comment %>
|
|
25
|
+
|
|
26
|
+
<% }) %>
|
|
27
|
+
*/
|
|
28
|
+
<% } %>
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { utils, route, config } = it;
|
|
3
|
+
const { requestBodyInfo, responseBodyInfo, specificArgNameResolver } = route;
|
|
4
|
+
const { _, getInlineParseContent, getParseContent, parseSchema, getComponentByRef, require } = utils;
|
|
5
|
+
const { parameters, path, method, payload, query, formData, security, requestParams } = route.request;
|
|
6
|
+
const { type, errorType, contentTypes } = route.response;
|
|
7
|
+
const { HTTP_CLIENT, RESERVED_REQ_PARAMS_ARG_NAMES } = config.constants;
|
|
8
|
+
const routeDocs = includeFile("./route-docs", { config, route, utils });
|
|
9
|
+
const queryName = (query && query.name) || "query";
|
|
10
|
+
const pathParams = _.values(parameters);
|
|
11
|
+
const pathParamsNames = _.map(pathParams, "name");
|
|
12
|
+
|
|
13
|
+
// 提取参数
|
|
14
|
+
if (config.param?.extractRequestQuery && query && query.type) {
|
|
15
|
+
const queryExtract = config.param?.extractRequestQuery?.split(",")
|
|
16
|
+
query.type = query.type.replace(new RegExp(`[\\s\\S\\n]+ (${queryExtract.join("|")}): ([a-z]+),[\\s\\S\\n]+`, "i"), "$2")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const isFetchTemplate = config.httpClientType === HTTP_CLIENT.FETCH;
|
|
20
|
+
|
|
21
|
+
const requestConfigParam = {
|
|
22
|
+
name: specificArgNameResolver.resolve(RESERVED_REQ_PARAMS_ARG_NAMES),
|
|
23
|
+
optional: true,
|
|
24
|
+
type: "RequestParams",
|
|
25
|
+
defaultValue: "{}",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const argToTmpl = ({ name, optional, type, defaultValue }) => `${name}${!defaultValue && optional ? '?' : ''}: ${type}${defaultValue ? ` = ${defaultValue}` : ''}`;
|
|
29
|
+
|
|
30
|
+
const rawWrapperArgs = config.extractRequestParams ?
|
|
31
|
+
_.compact([
|
|
32
|
+
requestParams && {
|
|
33
|
+
name: pathParams.length ? `{ ${_.join(pathParamsNames, ", ")}, ...${queryName} }` : queryName,
|
|
34
|
+
optional: false,
|
|
35
|
+
type: getInlineParseContent(requestParams),
|
|
36
|
+
},
|
|
37
|
+
...(!requestParams ? pathParams : []),
|
|
38
|
+
payload,
|
|
39
|
+
requestConfigParam,
|
|
40
|
+
]) :
|
|
41
|
+
_.compact([
|
|
42
|
+
...pathParams,
|
|
43
|
+
query,
|
|
44
|
+
payload,
|
|
45
|
+
requestConfigParam,
|
|
46
|
+
])
|
|
47
|
+
|
|
48
|
+
const wrapperArgs = _
|
|
49
|
+
// Sort by optionality
|
|
50
|
+
.sortBy(rawWrapperArgs, [o => o.optional])
|
|
51
|
+
.map(argToTmpl)
|
|
52
|
+
.join(', ')
|
|
53
|
+
|
|
54
|
+
// RequestParams["type"]
|
|
55
|
+
const requestContentKind = {
|
|
56
|
+
"JSON": "ContentType.Json",
|
|
57
|
+
"JSON_API": "ContentType.JsonApi",
|
|
58
|
+
"URL_ENCODED": "ContentType.UrlEncoded",
|
|
59
|
+
"FORM_DATA": "ContentType.FormData",
|
|
60
|
+
"TEXT": "ContentType.Text",
|
|
61
|
+
}
|
|
62
|
+
// RequestParams["format"]
|
|
63
|
+
const responseContentKind = {
|
|
64
|
+
"JSON": '"json"',
|
|
65
|
+
"IMAGE": '"blob"',
|
|
66
|
+
"FORM_DATA": isFetchTemplate ? '"formData"' : '"document"'
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const bodyTmpl = _.get(payload, "name") || null;
|
|
70
|
+
const queryTmpl = (query != null && queryName) || null;
|
|
71
|
+
const bodyContentKindTmpl = requestContentKind[requestBodyInfo.contentKind] || null;
|
|
72
|
+
const responseFormatTmpl = responseContentKind[responseBodyInfo.success && responseBodyInfo.success.schema && responseBodyInfo.success.schema.contentKind] || null;
|
|
73
|
+
const securityTmpl = security ? 'true' : null;
|
|
74
|
+
|
|
75
|
+
const describeReturnType = () => {
|
|
76
|
+
if (!config.toJS) return "";
|
|
77
|
+
|
|
78
|
+
switch(config.httpClientType) {
|
|
79
|
+
case HTTP_CLIENT.AXIOS: {
|
|
80
|
+
return `Promise<AxiosResponse<${type}>>`
|
|
81
|
+
}
|
|
82
|
+
default: {
|
|
83
|
+
return `Promise<HttpResponse<${type}, ${errorType}>`
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const isValidIdentifier = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
|
|
89
|
+
|
|
90
|
+
%>
|
|
91
|
+
/**
|
|
92
|
+
<%~ routeDocs.description %>
|
|
93
|
+
|
|
94
|
+
*<% /* Here you can add some other JSDoc tags */ %>
|
|
95
|
+
|
|
96
|
+
<%~ routeDocs.lines %>
|
|
97
|
+
|
|
98
|
+
*/
|
|
99
|
+
<% if (isValidIdentifier(route.routeName.usage)) { %><%~ route.routeName.usage %><%~ route.namespace ? ': ' : ' = ' %><% } else { %>"<%~ route.routeName.usage %>"<%~ route.namespace ? ': ' : ' = ' %><% } %>(<%~ wrapperArgs %>)<%~ config.toJS ? `: ${describeReturnType()}` : "" %> =>
|
|
100
|
+
<%~ config.singleHttpClient ? 'this.http.request' : 'this.request' %><<%~ type %>, <%~ errorType %>>({
|
|
101
|
+
path: `<%~ path %>`,
|
|
102
|
+
method: '<%~ _.upperCase(method) %>',
|
|
103
|
+
<%~ queryTmpl ? `query: ${queryTmpl},` : '' %>
|
|
104
|
+
<%~ bodyTmpl ? `body: ${bodyTmpl},` : '' %>
|
|
105
|
+
<%~ securityTmpl ? `secure: ${securityTmpl},` : '' %>
|
|
106
|
+
<%~ bodyContentKindTmpl ? `type: ${bodyContentKindTmpl},` : '' %>
|
|
107
|
+
<%~ responseFormatTmpl ? `format: ${responseFormatTmpl},` : '' %>
|
|
108
|
+
...<%~ _.get(requestConfigParam, "name") %>,
|
|
109
|
+
})<%~ route.namespace ? ',' : '' %>
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { config, route, utils } = it;
|
|
3
|
+
const { _, formatDescription, fmtToJSDocLine, pascalCase, require } = utils;
|
|
4
|
+
const { raw, request, routeName } = route;
|
|
5
|
+
|
|
6
|
+
const jsDocDescription = raw.description ?
|
|
7
|
+
` * @description ${formatDescription(raw.description, true)}` :
|
|
8
|
+
fmtToJSDocLine('No description', { eol: false });
|
|
9
|
+
const jsDocLines = _.compact([
|
|
10
|
+
_.size(raw.tags) && ` * @tags ${raw.tags.join(", ")}`,
|
|
11
|
+
` * @name ${pascalCase(routeName.usage)}`,
|
|
12
|
+
raw.summary && ` * @summary ${raw.summary}`,
|
|
13
|
+
` * @request ${_.upperCase(request.method)}:${raw.route}`,
|
|
14
|
+
raw.deprecated && ` * @deprecated`,
|
|
15
|
+
routeName.duplicate && ` * @originalName ${routeName.original}`,
|
|
16
|
+
routeName.duplicate && ` * @duplicate`,
|
|
17
|
+
request.security && ` * @secure`,
|
|
18
|
+
...(config.generateResponses && raw.responsesTypes.length
|
|
19
|
+
? raw.responsesTypes.map(
|
|
20
|
+
({ type, status, description, isSuccess }) =>
|
|
21
|
+
` * @response \`${status}\` \`${_.replace(_.replace(type, /\/\*/g, "\\*"), /\*\//g, "*\\")}\` ${description}`,
|
|
22
|
+
)
|
|
23
|
+
: []),
|
|
24
|
+
]).map(str => str.trimEnd()).join("\n");
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
description: jsDocDescription,
|
|
28
|
+
lines: jsDocLines,
|
|
29
|
+
}
|
|
30
|
+
%>
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { routeInfo, utils } = it;
|
|
3
|
+
const {
|
|
4
|
+
operationId,
|
|
5
|
+
method,
|
|
6
|
+
route,
|
|
7
|
+
moduleName,
|
|
8
|
+
responsesTypes,
|
|
9
|
+
description,
|
|
10
|
+
tags,
|
|
11
|
+
summary,
|
|
12
|
+
pathArgs,
|
|
13
|
+
} = routeInfo;
|
|
14
|
+
const { _, fmtToJSDocLine, require } = utils;
|
|
15
|
+
|
|
16
|
+
const methodAliases = {
|
|
17
|
+
get: (pathName, hasPathInserts) =>
|
|
18
|
+
_.camelCase(`${pathName}_${hasPathInserts ? "detail" : "list"}`),
|
|
19
|
+
post: (pathName, hasPathInserts) => _.camelCase(`${pathName}_create`),
|
|
20
|
+
put: (pathName, hasPathInserts) => _.camelCase(`${pathName}_update`),
|
|
21
|
+
patch: (pathName, hasPathInserts) => _.camelCase(`${pathName}_partial_update`),
|
|
22
|
+
delete: (pathName, hasPathInserts) => _.camelCase(`${pathName}_delete`),
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const createCustomOperationId = (method, route, moduleName) => {
|
|
26
|
+
const hasPathInserts = /\{(\w){1,}\}$/g.test(route);
|
|
27
|
+
const splittedRouteBySlash = _.compact(_.replace(route, /\{(\w){1,}\}/g, "").split("/"));
|
|
28
|
+
const routeParts = (splittedRouteBySlash.length > 1
|
|
29
|
+
? splittedRouteBySlash.splice(1)
|
|
30
|
+
: splittedRouteBySlash
|
|
31
|
+
).join("_");
|
|
32
|
+
return routeParts.length > 3 && methodAliases[method]
|
|
33
|
+
? methodAliases[method](routeParts, hasPathInserts)
|
|
34
|
+
: _.camelCase(_.lowerCase(method) + "_" + [moduleName].join("_")) || "index";
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
if (operationId)
|
|
38
|
+
return _.camelCase(operationId);
|
|
39
|
+
if (route === "/")
|
|
40
|
+
return _.camelCase(`${_.lowerCase(method)}Root`);
|
|
41
|
+
|
|
42
|
+
return createCustomOperationId(method, route, moduleName);
|
|
43
|
+
%>
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { route, utils, config } = it;
|
|
3
|
+
const { _, pascalCase, require } = utils;
|
|
4
|
+
const { query, payload, pathParams, headers } = route.request;
|
|
5
|
+
|
|
6
|
+
const routeDocs = includeFile("./route-docs", { config, route, utils });
|
|
7
|
+
const isValidIdentifier = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
|
|
8
|
+
const routeNamespace = pascalCase(route.routeName.usage);
|
|
9
|
+
|
|
10
|
+
%>
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
<%~ routeDocs.description %>
|
|
14
|
+
|
|
15
|
+
<%~ routeDocs.lines %>
|
|
16
|
+
|
|
17
|
+
*/
|
|
18
|
+
export namespace <% if (isValidIdentifier(routeNamespace)) { %><%~ routeNamespace %><% } else { %>"<%~ routeNamespace %>"<% } %> {
|
|
19
|
+
export type RequestParams = <%~ (pathParams && pathParams.type) || '{}' %>;
|
|
20
|
+
export type RequestQuery = <%~ (query && query.type) || '{}' %>;
|
|
21
|
+
export type RequestBody = <%~ (payload && payload.type) || 'never' %>;
|
|
22
|
+
export type RequestHeaders = <%~ (headers && headers.type) || '{}' %>;
|
|
23
|
+
export type ResponseBody = <%~ route.response.type %>;
|
|
24
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { utils, config, routes, modelTypes } = it;
|
|
3
|
+
const { _, pascalCase } = utils;
|
|
4
|
+
const dataContracts = config.modular ? _.map(modelTypes, "name") : [];
|
|
5
|
+
%>
|
|
6
|
+
|
|
7
|
+
<% if (dataContracts.length) { %>
|
|
8
|
+
import { <%~ dataContracts.join(", ") %> } from "./<%~ config.fileNames.dataContracts %>"
|
|
9
|
+
<% } %>
|
|
10
|
+
|
|
11
|
+
<%
|
|
12
|
+
/* TODO: outOfModule, combined should be attributes of route, which will allow to avoid duplication of code */
|
|
13
|
+
%>
|
|
14
|
+
|
|
15
|
+
<% if (routes.outOfModule) { %>
|
|
16
|
+
<% for (const { routes: outOfModuleRoutes = [] } of routes.outOfModule) { %>
|
|
17
|
+
<% for (const route of outOfModuleRoutes) { %>
|
|
18
|
+
<%~ includeFile('./route-type.ejs', { ...it, route }) %>
|
|
19
|
+
<% } %>
|
|
20
|
+
<% } %>
|
|
21
|
+
<% } %>
|
|
22
|
+
|
|
23
|
+
<% if (routes.combined) { %>
|
|
24
|
+
<% for (const { routes: combinedRoutes = [], moduleName } of routes.combined) { %>
|
|
25
|
+
export namespace <%~ pascalCase(moduleName) %> {
|
|
26
|
+
<% for (const route of combinedRoutes) { %>
|
|
27
|
+
<%~ includeFile('./route-type.ejs', { ...it, route }) %>
|
|
28
|
+
<% } %>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
<% } %>
|
|
32
|
+
<% } %>
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
<%
|
|
2
|
+
const { contract, utils } = it;
|
|
3
|
+
const { formatDescription, require, _ } = utils;
|
|
4
|
+
|
|
5
|
+
%>
|
|
6
|
+
<% if (contract.$content.length) { %>
|
|
7
|
+
export type <%~ contract.name %> = {
|
|
8
|
+
<% for (const field of contract.$content) { %>
|
|
9
|
+
<%~ includeFile('./object-field-jsdoc.ejs', { ...it, field }) %>
|
|
10
|
+
<%~ field.field %>;
|
|
11
|
+
<% } %>
|
|
12
|
+
}<%~ utils.isNeedToAddNull(contract) ? ' | null' : ''%>
|
|
13
|
+
<% } else { %>
|
|
14
|
+
export type <%~ contract.name %> = Record<string, any>;
|
|
15
|
+
<% } %>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fxri/swagger2api",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.7",
|
|
4
4
|
"description": "基于 swagger-typescript-api,将 Swagger 文档自动转为 TypeScript 格式的 API 文件。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
},
|
|
11
11
|
"type": "module",
|
|
12
12
|
"main": "./dist/index.js",
|
|
13
|
-
"bin": "./dist/
|
|
13
|
+
"bin": "./dist/cli.js",
|
|
14
14
|
"files": [
|
|
15
15
|
"dist",
|
|
16
16
|
"README.md",
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"@types/prompts": "^2.4.9",
|
|
33
33
|
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
|
34
34
|
"@typescript-eslint/parser": "^6.21.0",
|
|
35
|
+
"esbuild-plugin-copy": "^2.1.1",
|
|
35
36
|
"eslint": "^8.57.1",
|
|
36
37
|
"eslint-config-prettier": "^9.1.2",
|
|
37
38
|
"eslint-plugin-vue": "^9.33.0",
|
|
@@ -53,10 +54,10 @@
|
|
|
53
54
|
"url": "https://github.com/fxri-net/swagger2api/issues"
|
|
54
55
|
},
|
|
55
56
|
"scripts": {
|
|
56
|
-
"dev": "pnpm build:debug && node ./dist/
|
|
57
|
+
"dev": "pnpm build:debug && node ./dist/cli.js",
|
|
57
58
|
"build": "NODE_ENV=production tsup",
|
|
58
|
-
"build:debug": "NODE_ENV=development tsup --config tsup.
|
|
59
|
+
"build:debug": "NODE_ENV=development tsup --config tsup.dev.config.ts",
|
|
59
60
|
"release": "pnpm build && pnpm publish",
|
|
60
|
-
"api": "pnpm dev --axios --responses --remove-prefix-index 0 --quick"
|
|
61
|
+
"api": "pnpm dev --axios --responses --remove-prefix-index 0 --quick --extract-request-query param --extract-response-raw"
|
|
61
62
|
}
|
|
62
63
|
}
|
package/dist/bin/index.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var $=Object.create;var h=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty;var T=(e,r,n,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of D(r))!E.call(e,i)&&i!==n&&h(e,i,{get:()=>r[i],enumerable:!(o=F(r,i))||o.enumerable});return e};var l=(e,r,n)=>(n=e!=null?$(k(e)):{},T(r||!e||!e.__esModule?h(n,"default",{value:e,enumerable:!0}):n,e));var P=l(require("axios"),1),j=require("child_process"),q=l(require("os"),1),g=l(require("fs"),1),u=l(require("path"),1),x=l(require("prompts"),1),R=require("swagger-typescript-api");var v=e=>/^(https?:\/\/|:?\/\/)/.test(e);var f=l(require("fs"),1),b=l(require("path"),1),c={param:process.argv.filter((e,r)=>r>1),used:{}};function w(e,r=!0,n=!0){Array.isArray(e)||(e=[e]);let o;return c.param.forEach((i,p)=>{if(e.includes(i))r?(o=c.param[p+1],n&&Object.assign(c.used,{[p+1]:!0})):["true","false"].includes(c.param[p+1])?(o=c.param[p+1].toLowerCase()=="true",n&&Object.assign(c.used,{[p+1]:!0})):o=!0;else return;n&&Object.assign(c.used,{[p]:!0})}),o}function t(e,r=!0){return w(e,!1,r)}function m(e,r=!0){return w(e,!0,r)}function d(e,r){let n=b.default.dirname(e);f.default.existsSync(n)||f.default.mkdirSync(n,{recursive:!0}),f.default.writeFileSync(e,r)}var A=require("glob"),a={files:[],param:{}},s={home:q.default.homedir(),enum:{}};function y(e){e&&console.log(e),process.exit()}async function C(){s.config={templates:m(["--templates","-t"])??"./src/templates",defaultResponseAsSuccess:t(["--default-as-success","-d"]),generateResponses:t(["--responses","-r"]),generateUnionEnums:t("--union-enums"),addReadonly:t("--add-readonly"),generateRouteTypes:t("--route-types"),generateClient:!t("--no-client"),enumNamesAsValues:t("--enum-names-as-values"),extractRequestParams:t("--extract-request-params"),extractRequestBody:t("--extract-request-body"),extractResponseBody:t("--extract-response-body"),extractResponseError:t("--extract-response-error"),modular:t("--modular"),toJS:t("--js"),moduleNameIndex:Number(m("--module-name-index")??0),moduleNameFirstTag:t("--module-name-first-tag"),httpClientType:t("--axios")?"axios":"fetch",unwrapResponseData:t("--unwrap-response-data"),disableThrowOnError:t("--disable-throw-on-error"),singleHttpClient:t("--single-http-client"),silent:t("--silent"),defaultResponseType:m("--default-response")??"void",typePrefix:m("--type-prefix")??"",typeSuffix:m("--type-suffix")??"",cleanOutput:t("--clean-output"),...m("--api-class-name")?{apiClassName:m("--api-class-name")}:{},patch:t("--patch"),debug:t("--debug"),anotherArrayType:t("--another-array-type"),sortTypes:t("--sort-types"),extractEnums:t("--extract-enums")},s.param={config:m(["--config","-c"]),configScan:t(["--config-scan","-cs"]),configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:m(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),extractRequestQuery:m(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"])}}async function I(){s.param.config?a.files=s.param.config.split(","):(s.param.configScan??!0)&&(a.files=A.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!s.param.configAll&&a.files.length>1&&(a.files=(await(0,x.default)({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:a.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:y("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function J(){try{a.param={},a.param=JSON.parse(g.default.readFileSync(a.file,"utf-8"))}catch{}(!s.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await(0,x.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),s.docFile=u.default.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function O(e=0){if(a.file=a.files[e],await J(),v(a.param.url))await P.default.get(a.param.url).then(r=>S(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await S(JSON.parse(g.default.readFileSync(u.default.resolve(a.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}a.files[e+1]&&O(e+1)}async function S(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(r=>{Object.keys(r[1]).forEach(n=>{let o=`${r[0]}/${n}`;if(s.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),s.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),s.param.removePrefixIndex){let p=o.split("/");p=p.slice(0,1).concat(p.slice(Number(s.param.removePrefixIndex)+2)),o=p.join("/")}e.paths[r[0]][n].operationId=o;let i=o.split("/").slice(-1)[0];typeof s.enum[i]=="number"?s.enum[i]++:s.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(s.enum).map(r=>r.join("-"))),d(s.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await(0,R.generateApi)({fileName:`${a.param.name}.ts`,output:u.default.resolve(a.param.output),input:s.docFile,...s.config,param:s.param}),g.default.unlinkSync(s.docFile),s.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",u.default.resolve(a.param.output,`${a.param.name}.d.ts`)),(0,j.execSync)(`npx rimraf ${u.default.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:s.home}).toString()),d(a.file,JSON.stringify(a.param,null,2))}async function N(){await C(),await I(),O()}N();
|
package/dist/bin/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import P from"axios";import{execSync as j}from"child_process";import q from"os";import d from"fs";import c from"path";import v from"prompts";import{generateApi as R}from"swagger-typescript-api";var y=a=>/^(https?:\/\/|:?\/\/)/.test(a);import u from"fs";import S from"path";var m={param:process.argv.filter((a,s)=>s>1),used:{}};function x(a,s=!0,p=!0){Array.isArray(a)||(a=[a]);let o;return m.param.forEach((l,n)=>{if(a.includes(l))s?(o=m.param[n+1],p&&Object.assign(m.used,{[n+1]:!0})):["true","false"].includes(m.param[n+1])?(o=m.param[n+1].toLowerCase()=="true",p&&Object.assign(m.used,{[n+1]:!0})):o=!0;else return;p&&Object.assign(m.used,{[n]:!0})}),o}function t(a,s=!0){return x(a,!1,s)}function i(a,s=!0){return x(a,!0,s)}function f(a,s){let p=S.dirname(a);u.existsSync(p)||u.mkdirSync(p,{recursive:!0}),u.writeFileSync(a,s)}import{glob as A}from"glob";var e={files:[],param:{}},r={home:q.homedir(),enum:{}};function g(a){a&&console.log(a),process.exit()}async function O(){r.config={templates:i(["--templates","-t"])??"./src/templates",defaultResponseAsSuccess:t(["--default-as-success","-d"]),generateResponses:t(["--responses","-r"]),generateUnionEnums:t("--union-enums"),addReadonly:t("--add-readonly"),generateRouteTypes:t("--route-types"),generateClient:!t("--no-client"),enumNamesAsValues:t("--enum-names-as-values"),extractRequestParams:t("--extract-request-params"),extractRequestBody:t("--extract-request-body"),extractResponseBody:t("--extract-response-body"),extractResponseError:t("--extract-response-error"),modular:t("--modular"),toJS:t("--js"),moduleNameIndex:Number(i("--module-name-index")??0),moduleNameFirstTag:t("--module-name-first-tag"),httpClientType:t("--axios")?"axios":"fetch",unwrapResponseData:t("--unwrap-response-data"),disableThrowOnError:t("--disable-throw-on-error"),singleHttpClient:t("--single-http-client"),silent:t("--silent"),defaultResponseType:i("--default-response")??"void",typePrefix:i("--type-prefix")??"",typeSuffix:i("--type-suffix")??"",cleanOutput:t("--clean-output"),...i("--api-class-name")?{apiClassName:i("--api-class-name")}:{},patch:t("--patch"),debug:t("--debug"),anotherArrayType:t("--another-array-type"),sortTypes:t("--sort-types"),extractEnums:t("--extract-enums")},r.param={config:i(["--config","-c"]),configScan:t(["--config-scan","-cs"]),configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:i(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),extractRequestQuery:i(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"])}}async function N(){r.param.config?e.files=r.param.config.split(","):(r.param.configScan??!0)&&(e.files=A.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),e.files.length==0&&(e.files=["saconfig.json"]),!r.param.configAll&&e.files.length>1&&(e.files=(await v({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:e.files.map(a=>({title:a.replace(/\\/g,"/"),value:a}))}).then(a=>a.files?.length!=0?a:g("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),e.files?.length>0||g("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function $(){try{e.param={},e.param=JSON.parse(d.readFileSync(e.file,"utf-8"))}catch{}(!r.param.quick||[e.param.url,e.param.output,e.param.name].includes(void 0))&&(e.param=await v([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:e.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:e.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:e.param.name??"index"}])),[e.param.url,e.param.output,e.param.name].includes(void 0)&&g("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),r.docFile=c.resolve(`${e.param.output}/${e.param.name}-${new Date().getTime()}.json`)}async function b(a=0){if(e.file=e.files[a],await $(),y(e.param.url))await P.get(e.param.url).then(s=>h(s.data)).catch(s=>console.log("\u5931\u8D25\uFF1A",s));else try{await h(JSON.parse(d.readFileSync(c.resolve(e.param.url),"utf8")))}catch(s){console.log("\u5931\u8D25\uFF1A",s)}e.files[a+1]&&b(a+1)}async function h(a){if(typeof a?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(a.paths).forEach(s=>{Object.keys(s[1]).forEach(p=>{let o=`${s[0]}/${p}`;if(r.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),r.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),r.param.removePrefixIndex){let n=o.split("/");n=n.slice(0,1).concat(n.slice(Number(r.param.removePrefixIndex)+2)),o=n.join("/")}a.paths[s[0]][p].operationId=o;let l=o.split("/").slice(-1)[0];typeof r.enum[l]=="number"?r.enum[l]++:r.enum[l]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(r.enum).map(s=>s.join("-"))),f(r.docFile,JSON.stringify(a)),console.log("\u6267\u884C\uFF1A",e.file),await R({fileName:`${e.param.name}.ts`,output:c.resolve(e.param.output),input:r.docFile,...r.config,param:r.param}),d.unlinkSync(r.docFile),r.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",c.resolve(e.param.output,`${e.param.name}.d.ts`)),j(`npx rimraf ${c.resolve(e.param.output,`${e.param.name}.d.ts`)}`,{cwd:r.home}).toString()),f(e.file,JSON.stringify(e.param,null,2))}async function w(){await O(),await N(),b()}w();
|
|
File without changes
|
|
File without changes
|