swagger-typescript-api 13.1.0 → 13.1.1
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/CHANGELOG.md +8 -0
- package/dist/_tsup-dts-rollup.d.cts +1 -0
- package/dist/_tsup-dts-rollup.d.ts +1 -0
- package/dist/{chunk-NO753Z7P.cjs → chunk-E5FI32CM.cjs} +16 -16
- package/dist/chunk-E5FI32CM.cjs.map +1 -0
- package/dist/{chunk-TVX6OCDM.js → chunk-EBM4FZTJ.js} +5 -5
- package/dist/chunk-EBM4FZTJ.js.map +1 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.js +1 -1
- package/dist/lib.cjs +1 -1
- package/dist/lib.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-NO753Z7P.cjs.map +0 -1
- package/dist/chunk-TVX6OCDM.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import {consola}from'consola';import g from'lodash';import*as d from'typescript';import*as E from'node:path';import E__default from'node:path';import {Biome,Distribution}from'@biomejs/js-api';import*as nt from'nanoid';import*as dt from'js-yaml';import*as Tt from'swagger2openapi';import*as Pt from'node:url';import Pt__default from'node:url';import*as Ct from'eta';import*as R from'node:fs';var jt=Object.defineProperty;var Dt=(h,e)=>{for(var t in e)jt(h,t,{get:e[t],enumerable:true});};var se=class{config;constructor(e){this.config=e;}removeUnusedImports=e=>{let t="file.ts",s=new qe(t,e),a=d.createLanguageService(s).organizeImports({type:"file",fileName:t},{newLineCharacter:d.sys.newLine},void 0)[0];return a?.textChanges.length?a.textChanges.reduceRight((i,{span:o,newText:n})=>`${i.slice(0,o.start)}${n}${i.slice(o.start+o.length)}`,e):e};format=async e=>{let t=await Biome.create({distribution:Distribution.NODE});return t.applyConfiguration({files:{maxSize:Number.MAX_SAFE_INTEGER},formatter:{indentStyle:"space"}}),t.formatContent(e,{filePath:E.format({name:nt.nanoid(),ext:"ts"})}).content};formatCode=async(e,{removeUnusedImports:t=true,format:s=true}={})=>(t&&(e=this.removeUnusedImports(e)),s&&(e=await this.format(e)),e)},qe=class{fileName;content;compilerOptions;constructor(e,t){this.fileName=e,this.content=t;let s=d.findConfigFile(e,d.sys.fileExists);this.compilerOptions=s?d.convertCompilerOptionsFromJson(d.readConfigFile(s,d.sys.readFile).config.compilerOptions,"").options:d.getDefaultCompilerOptions();}getNewLine(){return "newLine"in d.sys?d.sys.newLine:`
|
|
2
|
-
`}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return d.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return d.version}getScriptSnapshot(){return d.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:d.sys.readFile(e,t)}fileExists(e){return d.sys.fileExists(e)}};var O=class{reservedNames=[];getFallbackName;config;constructor(e,t,s){this.config=e,this.getFallbackName=s,this.reserve(t);}reserve(e){let t=g.uniq(g.compact(e));for(let s of t)this.reservedNames.indexOf(s)===-1&&this.reservedNames.push(s);}unreserve(e){this.reservedNames.filter(t=>!e.some(s=>s===t));}isReserved(e){return this.reservedNames.some(t=>t===e)}resolve(e,t,s,r=true){if(typeof t=="function"){let a=null;for(;a===null;){let i=t(e,s);if(i===void 0)return consola.warn("unable to resolve name. current reserved names: ",...this.reservedNames),null;(!r||!this.isReserved(i))&&(a=i);}return r&&this.reserve([a]),a}if(Array.isArray(e)){let a=null,i=g.uniq(g.compact(e));for(let o of i)!a&&(!r||!this.isReserved(o))&&(a=o);return a?(r&&this.reserve([a]),a):(consola.debug("trying to resolve name with using fallback name generator using variants",...e),this.resolve(e,this.getFallbackName,s))}return consola.debug("problem with reserving names. current reserved names: ",...this.reservedNames),null}};var qt=(h=0,e=1)=>Math.random()*(e-h)+h,ot=(h=0,e=1)=>h===e?h:Math.round(qt(h,e));var ae=class extends O{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t){super(e,t,s=>{let r=s[ot(0,s.length-1)];if(r){this.countersByVariant.has(r)||this.countersByVariant.set(r,0);let i=this.countersByVariant.get(r)+1;this.countersByVariant.set(r,i);let o=`${r}${i}`;return consola.debug("generated dirty resolved type name for component - ",o),o}let a=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return consola.debug("generated fallback type name for component - ",a),a});}};var ie={};Dt(ie,{DEFAULT_BODY_ARG_NAME:()=>Ge,FILE_PREFIX:()=>Gt,HTTP_CLIENT:()=>J,PROJECT_VERSION:()=>Y,RESERVED_BODY_ARG_NAMES:()=>We,RESERVED_HEADER_ARG_NAMES:()=>Ve,RESERVED_PATH_ARG_NAMES:()=>Be,RESERVED_QUERY_ARG_NAMES:()=>Le,RESERVED_REQ_PARAMS_ARG_NAMES:()=>Wt,SCHEMA_TYPES:()=>l});var mt={name:"swagger-typescript-api",version:"13.1.
|
|
2
|
+
`}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return d.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return d.version}getScriptSnapshot(){return d.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:d.sys.readFile(e,t)}fileExists(e){return d.sys.fileExists(e)}};var O=class{reservedNames=[];getFallbackName;config;constructor(e,t,s){this.config=e,this.getFallbackName=s,this.reserve(t);}reserve(e){let t=g.uniq(g.compact(e));for(let s of t)this.reservedNames.indexOf(s)===-1&&this.reservedNames.push(s);}unreserve(e){this.reservedNames.filter(t=>!e.some(s=>s===t));}isReserved(e){return this.reservedNames.some(t=>t===e)}resolve(e,t,s,r=true){if(typeof t=="function"){let a=null;for(;a===null;){let i=t(e,s);if(i===void 0)return consola.warn("unable to resolve name. current reserved names: ",...this.reservedNames),null;(!r||!this.isReserved(i))&&(a=i);}return r&&this.reserve([a]),a}if(Array.isArray(e)){let a=null,i=g.uniq(g.compact(e));for(let o of i)!a&&(!r||!this.isReserved(o))&&(a=o);return a?(r&&this.reserve([a]),a):(consola.debug("trying to resolve name with using fallback name generator using variants",...e),this.resolve(e,this.getFallbackName,s))}return consola.debug("problem with reserving names. current reserved names: ",...this.reservedNames),null}};var qt=(h=0,e=1)=>Math.random()*(e-h)+h,ot=(h=0,e=1)=>h===e?h:Math.round(qt(h,e));var ae=class extends O{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t){super(e,t,s=>{let r=s[ot(0,s.length-1)];if(r){this.countersByVariant.has(r)||this.countersByVariant.set(r,0);let i=this.countersByVariant.get(r)+1;this.countersByVariant.set(r,i);let o=`${r}${i}`;return consola.debug("generated dirty resolved type name for component - ",o),o}let a=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return consola.debug("generated fallback type name for component - ",a),a});}};var ie={};Dt(ie,{DEFAULT_BODY_ARG_NAME:()=>Ge,FILE_PREFIX:()=>Gt,HTTP_CLIENT:()=>J,PROJECT_VERSION:()=>Y,RESERVED_BODY_ARG_NAMES:()=>We,RESERVED_HEADER_ARG_NAMES:()=>Ve,RESERVED_PATH_ARG_NAMES:()=>Be,RESERVED_QUERY_ARG_NAMES:()=>Le,RESERVED_REQ_PARAMS_ARG_NAMES:()=>Wt,SCHEMA_TYPES:()=>l});var mt={name:"swagger-typescript-api",version:"13.1.1",description:"Generate the API client for Fetch or Axios from an OpenAPI Specification",homepage:"https://github.com/acacode/swagger-typescript-api",bugs:"https://github.com/acacode/swagger-typescript-api/issues",repository:"github:acacode/swagger-typescript-api",license:"MIT",author:"Sergey Volkov <js2me@outlook.com>",maintainers:["Sora Morimoto <sora@morimoto.io>"],type:"module",exports:{".":{import:{types:"./dist/lib.d.ts",default:"./dist/lib.js"},require:{types:"./dist/lib.d.cts",default:"./dist/lib.cjs"}}},main:"./dist/lib.cjs",module:"./dist/lib.js",types:"./dist/lib.d.cts",bin:{sta:"./dist/cli.js","swagger-typescript-api":"./dist/cli.js"},files:["dist","templates"],scripts:{build:"tsup","cli:help":"node index.js -h","cli:json":"node index.js -r -d -p ./swagger-test-cli.json -n swagger-test-cli.ts","cli:yaml":"node index.js -r -d -p ./swagger-test-cli.yaml -n swagger-test-cli.ts",format:"biome format --write .","format:check":"biome format .",lint:"biome check",prepack:"tsup",test:"vitest run",typedoc:"typedoc"},dependencies:{"@biomejs/js-api":"^0.7.1","@biomejs/wasm-nodejs":"^1.9.4","@types/swagger-schema-official":"^2.0.25",c12:"^3.0.3",citty:"^0.1.6",consola:"^3.4.2",eta:"^2.2.0","js-yaml":"^4.1.0",lodash:"^4.17.21",nanoid:"^5.1.5","swagger-schema-official":"2.0.0-bab6bed",swagger2openapi:"^7.0.8",typescript:"~5.8.3"},devDependencies:{"@biomejs/biome":"1.9.4","@changesets/changelog-github":"0.5.1","@changesets/cli":"2.28.1","@microsoft/api-extractor":"7.52.3","@tsconfig/node18":"18.2.4","@tsconfig/strictest":"2.0.5","@types/js-yaml":"4.0.9","@types/lodash":"4.17.16","@types/node":"22.14.1","@types/swagger2openapi":"7.0.4",axios:"1.8.4","openapi-types":"12.1.3",tsup:"8.4.0",typedoc:"0.28.2",vitest:"3.1.1"},packageManager:"yarn@4.9.1",engines:{node:">=18.0.0"},publishConfig:{access:"public",provenance:true,registry:"https://registry.npmjs.org"},typedocOptions:{entryPoints:["src/index.ts"],skipErrorChecking:true}};var Ge="data",Gt=`/* eslint-disable */
|
|
3
3
|
/* tslint:disable */
|
|
4
4
|
// @ts-nocheck
|
|
5
5
|
/*
|
|
@@ -15,7 +15,7 @@ import {consola}from'consola';import g from'lodash';import*as d from'typescript'
|
|
|
15
15
|
`),ObjectWrapper:e=>`{
|
|
16
16
|
${e}
|
|
17
17
|
}`,MultilineComment:(e,t)=>[...e.length===1?[`/** ${e[0]} */`]:["/**",...e.map(s=>` * ${s}`)," */"]].map(s=>`${t?t(s):s}
|
|
18
|
-
`),TypeWithGeneric:(e,t)=>`${e}${t.length?`<${t.join(",")}>`:""}`,Tuple:e=>`[${e.join(", ")}]`};primitiveTypes={integer:()=>this.Ts.Keyword.Number,number:()=>this.Ts.Keyword.Number,boolean:()=>this.Ts.Keyword.Boolean,object:()=>this.Ts.Keyword.Object,file:()=>this.Ts.Keyword.File,string:{$default:this.Ts.Keyword.String,binary:()=>this.Ts.Keyword.File,file:()=>this.Ts.Keyword.File,"date-time":()=>this.Ts.Keyword.String,time:()=>this.Ts.Keyword.String,date:()=>this.Ts.Keyword.String,duration:()=>this.Ts.Keyword.String,email:()=>this.Ts.Keyword.String,"idn-email":()=>this.Ts.Keyword.String,"idn-hostname":()=>this.Ts.Keyword.String,ipv4:()=>this.Ts.Keyword.String,ipv6:()=>this.Ts.Keyword.String,uuid:()=>this.Ts.Keyword.String,uri:()=>this.Ts.Keyword.String,"uri-reference":()=>this.Ts.Keyword.String,"uri-template":()=>this.Ts.Keyword.String,"json-pointer":()=>this.Ts.Keyword.String,"relative-json-pointer":()=>this.Ts.Keyword.String,regex:()=>this.Ts.Keyword.String}};templateInfos=[{name:"api",fileName:"api"},{name:"dataContracts",fileName:"data-contracts"},{name:"dataContractJsDoc",fileName:"data-contract-jsdoc"},{name:"interfaceDataContract",fileName:"interface-data-contract"},{name:"typeDataContract",fileName:"type-data-contract"},{name:"enumDataContract",fileName:"enum-data-contract"},{name:"objectFieldJsDoc",fileName:"object-field-jsdoc"},{name:"httpClient",fileName:"http-client"},{name:"routeTypes",fileName:"route-types"},{name:"routeName",fileName:"route-name"}];templateExtensions=[".eta",".ejs"];constructor({codeGenConstructs:e,primitiveTypeConstructs:t,constants:s,templateInfos:r,hooks:a,...i}){U(this.Ts,e),U(this.primitiveTypes,t),this.defaultResponseType=this.Ts.Keyword.Void,this.update({...i,hooks:g.merge(this.hooks,a||{}),constants:{...ie,...s},templateInfos:r||this.templateInfos}),this.jsPrimitiveTypes=[this.Ts.Keyword.Number,this.Ts.Keyword.String,this.Ts.Keyword.Boolean],this.jsEmptyTypes=[this.Ts.Keyword.Null,this.Ts.Keyword.Undefined],this.componentTypeNameResolver=new ae(this,[]);}update=e=>{U(this,e);}};var ce=class{_data=[];config;constructor(e){this.config=e;}clear(){this._data=[];}createRef=e=>["#",...e].join("/");parseRef=e=>e.split("/");createComponent(e,t){let s=this.parseRef(e),r=s[s.length-1],a=s[s.length-2],i={$ref:e,typeName:r,rawTypeData:t,componentName:a,typeData:null},o=this.config.hooks.onCreateComponent(i)||i,n=this._data.findIndex(c=>c.$ref===e);return n===-1?this._data.push(o):this._data[n]=o,o}getComponents(){return this._data}filter(...e){return this._data.filter(t=>e.some(s=>t.$ref.startsWith(`#/components/${s}`)))}get(e){return this._data.find(t=>t.$ref===e)||null}};var me=class{config;templatesWorker;schemaUtils;constructor(e){this.config=e.config,this.schemaUtils=e.schemaUtils,this.templatesWorker=e.templatesWorker;}base={[l.ENUM]:e=>this.config.generateUnionEnums?{...e,$content:e.content,content:this.config.Ts.UnionType(e.content.map(({value:t})=>t))}:{...e,$content:e.content,content:this.config.Ts.EnumFieldsWrapper(e.content)},[l.OBJECT]:e=>e.nullable?this.inline[l.OBJECT](e):{...e,$content:e.content,content:this.formatObjectContent(e.content)},[l.PRIMITIVE]:e=>({...e,$content:e.content})};inline={[l.ENUM]:e=>({...e,content:e.$ref?e.typeName:this.config.Ts.UnionType(g.compact([...e.content.map(({value:t})=>`${t}`),e.nullable&&this.config.Ts.Keyword.Null]))||this.config.Ts.Keyword.Any}),[l.OBJECT]:e=>typeof e.content=="string"?{...e,typeIdentifier:this.config.Ts.Keyword.Type,content:this.schemaUtils.safeAddNullToType(e.content)}:{...e,typeIdentifier:this.config.Ts.Keyword.Type,content:this.schemaUtils.safeAddNullToType(e,e.content.length?this.config.Ts.ObjectWrapper(this.formatObjectContent(e.content)):this.config.Ts.RecordType(this.config.Ts.Keyword.String,this.config.Ts.Keyword.Any))}};formatSchema=(e,t="base")=>{let s=g.get(e,["schemaType"])||g.get(e,["$parsed","schemaType"]);return g.get(this,[t,s])?.(e)||e};formatDescription=(e,t)=>e?e.includes(`
|
|
18
|
+
`),TypeWithGeneric:(e,t)=>`${e}${t.length?`<${t.join(",")}>`:""}`,Tuple:e=>`[${e.join(", ")}]`};primitiveTypes={integer:()=>this.Ts.Keyword.Number,number:()=>this.Ts.Keyword.Number,boolean:()=>this.Ts.Keyword.Boolean,object:()=>this.Ts.Keyword.Object,file:()=>this.Ts.Keyword.File,string:{$default:this.Ts.Keyword.String,binary:()=>this.Ts.Keyword.File,file:()=>this.Ts.Keyword.File,"date-time":()=>this.Ts.Keyword.String,time:()=>this.Ts.Keyword.String,date:()=>this.Ts.Keyword.String,duration:()=>this.Ts.Keyword.String,email:()=>this.Ts.Keyword.String,"idn-email":()=>this.Ts.Keyword.String,"idn-hostname":()=>this.Ts.Keyword.String,ipv4:()=>this.Ts.Keyword.String,ipv6:()=>this.Ts.Keyword.String,uuid:()=>this.Ts.Keyword.String,uri:()=>this.Ts.Keyword.String,"uri-reference":()=>this.Ts.Keyword.String,"uri-template":()=>this.Ts.Keyword.String,"json-pointer":()=>this.Ts.Keyword.String,"relative-json-pointer":()=>this.Ts.Keyword.String,regex:()=>this.Ts.Keyword.String}};templateInfos=[{name:"api",fileName:"api"},{name:"dataContracts",fileName:"data-contracts"},{name:"dataContractJsDoc",fileName:"data-contract-jsdoc"},{name:"interfaceDataContract",fileName:"interface-data-contract"},{name:"typeDataContract",fileName:"type-data-contract"},{name:"enumDataContract",fileName:"enum-data-contract"},{name:"objectFieldJsDoc",fileName:"object-field-jsdoc"},{name:"httpClient",fileName:"http-client"},{name:"routeTypes",fileName:"route-types"},{name:"routeName",fileName:"route-name"}];templateExtensions=[".eta",".ejs"];constructor({codeGenConstructs:e,primitiveTypeConstructs:t,constants:s,templateInfos:r,hooks:a,...i}){U(this.Ts,e),U(this.primitiveTypes,t),this.defaultResponseType=this.Ts.Keyword.Void,this.update({...i,hooks:g.merge(this.hooks,a||{}),constants:{...ie,...s},templateInfos:r||this.templateInfos}),this.jsPrimitiveTypes=[this.Ts.Keyword.Number,this.Ts.Keyword.String,this.Ts.Keyword.Boolean],this.jsEmptyTypes=[this.Ts.Keyword.Null,this.Ts.Keyword.Undefined],this.componentTypeNameResolver=new ae(this,[]);}update=e=>{U(this,e);}};var ce=class{_data=[];config;constructor(e){this.config=e;}clear(){this._data=[];}createRef=e=>["#",...e].join("/");parseRef=e=>e.split("/");createComponent(e,t){let s=this.parseRef(e),r=s[s.length-1],a=s[s.length-2],i={$ref:e,typeName:r,rawTypeData:t,componentName:a,typeData:null},o=this.config.hooks.onCreateComponent(i)||i,n=this._data.findIndex(c=>c.$ref===e);return n===-1?this._data.push(o):this._data[n]=o,o}getComponents(){return this._data}filter(...e){return this._data.filter(t=>e.some(s=>t.$ref.startsWith(`#/components/${s}`)))}get(e){return this._data.find(t=>t.$ref===e)||null}enumsFirst(){this._data.sort((e,t)=>Object.keys(e.rawTypeData||{}).includes("enum")?-1:Object.keys(t.rawTypeData||{}).includes("enum")?1:0);}};var me=class{config;templatesWorker;schemaUtils;constructor(e){this.config=e.config,this.schemaUtils=e.schemaUtils,this.templatesWorker=e.templatesWorker;}base={[l.ENUM]:e=>this.config.generateUnionEnums?{...e,$content:e.content,content:this.config.Ts.UnionType(e.content.map(({value:t})=>t))}:{...e,$content:e.content,content:this.config.Ts.EnumFieldsWrapper(e.content)},[l.OBJECT]:e=>e.nullable?this.inline[l.OBJECT](e):{...e,$content:e.content,content:this.formatObjectContent(e.content)},[l.PRIMITIVE]:e=>({...e,$content:e.content})};inline={[l.ENUM]:e=>({...e,content:e.$ref?e.typeName:this.config.Ts.UnionType(g.compact([...e.content.map(({value:t})=>`${t}`),e.nullable&&this.config.Ts.Keyword.Null]))||this.config.Ts.Keyword.Any}),[l.OBJECT]:e=>typeof e.content=="string"?{...e,typeIdentifier:this.config.Ts.Keyword.Type,content:this.schemaUtils.safeAddNullToType(e.content)}:{...e,typeIdentifier:this.config.Ts.Keyword.Type,content:this.schemaUtils.safeAddNullToType(e,e.content.length?this.config.Ts.ObjectWrapper(this.formatObjectContent(e.content)):this.config.Ts.RecordType(this.config.Ts.Keyword.String,this.config.Ts.Keyword.Any))}};formatSchema=(e,t="base")=>{let s=g.get(e,["schemaType"])||g.get(e,["$parsed","schemaType"]);return g.get(this,[t,s])?.(e)||e};formatDescription=(e,t)=>e?e.includes(`
|
|
19
19
|
`)?t?g._(e).split(/\n/g).map(r=>r.trim()).compact().join(" ").valueOf():e.replace(/\n$/g,""):e:"";formatObjectContent=e=>{let t=[];for(let s of e){let r=" ",a=`${r}${s.field},
|
|
20
20
|
`,o=this.templatesWorker.renderTemplate(this.config.templatesToRender.dataContractJsDoc,{data:s}).split(`
|
|
21
21
|
`).map(n=>`${r}${n}`).join(`
|
|
@@ -36,7 +36,7 @@ ${e}
|
|
|
36
36
|
* ---------------------------------------------------------------
|
|
37
37
|
*/
|
|
38
38
|
|
|
39
|
-
`,B=class{getFileContent=e=>R.readFileSync(e,{encoding:"utf8"});readDir=e=>R.readdirSync(e);pathIsDir=e=>{if(!e)return false;try{return R.statSync(e).isDirectory()}catch{return false}};cropExtension=e=>{let t=e.split(".");return t.length>1&&t.pop(),t.join(".")};removeDir=e=>{try{typeof R.rmSync=="function"?R.rmSync(e,{recursive:!0}):R.rmdirSync(e,{recursive:!0});}catch(t){consola.debug("failed to remove dir",t);}};createDir=e=>{try{R.mkdirSync(e,{recursive:!0});}catch(t){consola.debug("failed to create dir",t);}};cleanDir=e=>{this.removeDir(e),this.createDir(e);};pathIsExist=e=>!!e&&R.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let a=E.dirname(Pt.fileURLToPath(import.meta.url)),i=E.resolve(a,e,`./${t}`),o=`${r?es:""}${s}`;return R.writeFileSync(i,o)}};var ts=["schemaWalker","swaggerSchemaResolver","schemaComponentsMap","typeNameFormatter","templatesWorker","codeFormatter","schemaParserFabric","schemaRoutes","javascriptTranslator"],ke=class{config;swaggerSchemaResolver;schemaComponentsMap;typeNameFormatter;schemaParserFabric;schemaRoutes;fileSystem;codeFormatter;templatesWorker;schemaWalker;javascriptTranslator;constructor(e){this.config=new ne(e),this.fileSystem=new B,this.swaggerSchemaResolver=new Ae(this.config,this.fileSystem),this.schemaWalker=new Ee(this.config,this.swaggerSchemaResolver),this.schemaComponentsMap=new ce(this.config),this.typeNameFormatter=new $e(this.config),this.templatesWorker=new Oe(this.config,this.fileSystem,this.getRenderTemplateData),this.codeFormatter=new se(this.config),this.schemaParserFabric=new we(this.config,this.templatesWorker,this.schemaComponentsMap,this.typeNameFormatter,this.schemaWalker),this.schemaRoutes=new xe(this.config,this.schemaParserFabric,this.schemaComponentsMap,this.templatesWorker,this.typeNameFormatter),this.javascriptTranslator=new Me(this.config,this.codeFormatter);}async start(){this.config.update({templatePaths:this.templatesWorker.getTemplatePaths(this.config)}),this.config.update({templatesToRender:this.templatesWorker.getTemplates(this.config)});let e=await this.swaggerSchemaResolver.create();this.swaggerSchemaResolver.fixSwaggerSchema(e),this.config.update({swaggerSchema:e.usageSchema,originalSchema:e.originalSchema}),this.schemaWalker.addSchema("$usage",e.usageSchema),this.schemaWalker.addSchema("$original",e.originalSchema),consola.info("start generating your typescript api"),this.config.update(this.config.hooks.onInit(this.config,this)||this.config),this.schemaComponentsMap.clear(),g.each(e.usageSchema.components,(n,c)=>g.each(n,(p,m)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,m]),p);}));let s=this.schemaComponentsMap.filter(g.compact(["schemas",this.config.extractResponses&&"responses"])).map(n=>{let c=this.schemaParserFabric.parseSchema(n.rawTypeData,n.typeName);return n.typeData=c,c});this.schemaRoutes.attachSchema({usageSchema:e.usageSchema,parsedSchemas:s});let r={apiConfig:this.createApiConfig(e.usageSchema),config:this.config,modelTypes:this.collectModelTypes(),hasSecurityRoutes:this.schemaRoutes.hasSecurityRoutes,hasQueryRoutes:this.schemaRoutes.hasQueryRoutes,hasFormDataRoutes:this.schemaRoutes.hasFormDataRoutes,generateResponses:this.config.generateResponses,routes:this.schemaRoutes.getGroupedRoutes(),extraTemplates:this.config.extraTemplates,fileName:this.config.fileName,translateToJavaScript:this.config.toJS,customTranslator:this.config.customTranslator?new this.config.customTranslator:null,utils:this.getRenderTemplateData().utils},a=this.config.hooks.onPrepareConfig(r)||r;this.fileSystem.pathIsExist(this.config.output)?this.config.cleanOutput&&(consola.debug("cleaning dir",this.config.output),this.fileSystem.cleanDir(this.config.output)):(consola.debug(`path ${this.config.output} is not exist. creating dir by this path`),this.fileSystem.createDir(this.config.output));let i=await this.generateOutputFiles({configuration:a});if(this.fileSystem.pathIsDir(this.config.output))for(let n of i)this.fileSystem.createFile({path:this.config.output,fileName:`${n.fileName}${n.fileExtension}`,content:n.fileContent,withPrefix:true}),consola.success("api file",`"${n.fileName}${n.fileExtension}"`,`created in ${this.config.output}`);return {files:i,configuration:a,getTemplate:this.templatesWorker.getTemplate,renderTemplate:this.templatesWorker.renderTemplate,createFile:this.fileSystem.createFile,formatTSContent:this.codeFormatter.formatCode}}getRenderTemplateData=()=>({utils:{Ts:this.config.Ts,formatDescription:this.schemaParserFabric.schemaFormatters.formatDescription,internalCase:z,classNameCase:I,pascalCase:I,getInlineParseContent:this.schemaParserFabric.getInlineParseContent,getParseContent:this.schemaParserFabric.getParseContent,getComponentByRef:this.schemaComponentsMap.get,parseSchema:this.schemaParserFabric.parseSchema,checkAndAddNull:this.schemaParserFabric.schemaUtils.safeAddNullToType,safeAddNullToType:this.schemaParserFabric.schemaUtils.safeAddNullToType,isNeedToAddNull:this.schemaParserFabric.schemaUtils.isNullMissingInType,inlineExtraFormatters:this.schemaParserFabric.schemaFormatters.inline,formatters:this.schemaParserFabric.schemaFormatters.base,formatModelName:this.typeNameFormatter.format,fmtToJSDocLine:(e,{eol:t=true})=>` * ${e}${t?`
|
|
39
|
+
`,B=class{getFileContent=e=>R.readFileSync(e,{encoding:"utf8"});readDir=e=>R.readdirSync(e);pathIsDir=e=>{if(!e)return false;try{return R.statSync(e).isDirectory()}catch{return false}};cropExtension=e=>{let t=e.split(".");return t.length>1&&t.pop(),t.join(".")};removeDir=e=>{try{typeof R.rmSync=="function"?R.rmSync(e,{recursive:!0}):R.rmdirSync(e,{recursive:!0});}catch(t){consola.debug("failed to remove dir",t);}};createDir=e=>{try{R.mkdirSync(e,{recursive:!0});}catch(t){consola.debug("failed to create dir",t);}};cleanDir=e=>{this.removeDir(e),this.createDir(e);};pathIsExist=e=>!!e&&R.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let a=E.dirname(Pt.fileURLToPath(import.meta.url)),i=E.resolve(a,e,`./${t}`),o=`${r?es:""}${s}`;return R.writeFileSync(i,o)}};var ts=["schemaWalker","swaggerSchemaResolver","schemaComponentsMap","typeNameFormatter","templatesWorker","codeFormatter","schemaParserFabric","schemaRoutes","javascriptTranslator"],ke=class{config;swaggerSchemaResolver;schemaComponentsMap;typeNameFormatter;schemaParserFabric;schemaRoutes;fileSystem;codeFormatter;templatesWorker;schemaWalker;javascriptTranslator;constructor(e){this.config=new ne(e),this.fileSystem=new B,this.swaggerSchemaResolver=new Ae(this.config,this.fileSystem),this.schemaWalker=new Ee(this.config,this.swaggerSchemaResolver),this.schemaComponentsMap=new ce(this.config),this.typeNameFormatter=new $e(this.config),this.templatesWorker=new Oe(this.config,this.fileSystem,this.getRenderTemplateData),this.codeFormatter=new se(this.config),this.schemaParserFabric=new we(this.config,this.templatesWorker,this.schemaComponentsMap,this.typeNameFormatter,this.schemaWalker),this.schemaRoutes=new xe(this.config,this.schemaParserFabric,this.schemaComponentsMap,this.templatesWorker,this.typeNameFormatter),this.javascriptTranslator=new Me(this.config,this.codeFormatter);}async start(){this.config.update({templatePaths:this.templatesWorker.getTemplatePaths(this.config)}),this.config.update({templatesToRender:this.templatesWorker.getTemplates(this.config)});let e=await this.swaggerSchemaResolver.create();this.swaggerSchemaResolver.fixSwaggerSchema(e),this.config.update({swaggerSchema:e.usageSchema,originalSchema:e.originalSchema}),this.schemaWalker.addSchema("$usage",e.usageSchema),this.schemaWalker.addSchema("$original",e.originalSchema),consola.info("start generating your typescript api"),this.config.update(this.config.hooks.onInit(this.config,this)||this.config),this.schemaComponentsMap.clear(),g.each(e.usageSchema.components,(n,c)=>g.each(n,(p,m)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,m]),p);})),this.schemaComponentsMap.enumsFirst();let s=this.schemaComponentsMap.filter(g.compact(["schemas",this.config.extractResponses&&"responses"])).map(n=>{let c=this.schemaParserFabric.parseSchema(n.rawTypeData,n.typeName);return n.typeData=c,c});this.schemaRoutes.attachSchema({usageSchema:e.usageSchema,parsedSchemas:s});let r={apiConfig:this.createApiConfig(e.usageSchema),config:this.config,modelTypes:this.collectModelTypes(),hasSecurityRoutes:this.schemaRoutes.hasSecurityRoutes,hasQueryRoutes:this.schemaRoutes.hasQueryRoutes,hasFormDataRoutes:this.schemaRoutes.hasFormDataRoutes,generateResponses:this.config.generateResponses,routes:this.schemaRoutes.getGroupedRoutes(),extraTemplates:this.config.extraTemplates,fileName:this.config.fileName,translateToJavaScript:this.config.toJS,customTranslator:this.config.customTranslator?new this.config.customTranslator:null,utils:this.getRenderTemplateData().utils},a=this.config.hooks.onPrepareConfig(r)||r;this.fileSystem.pathIsExist(this.config.output)?this.config.cleanOutput&&(consola.debug("cleaning dir",this.config.output),this.fileSystem.cleanDir(this.config.output)):(consola.debug(`path ${this.config.output} is not exist. creating dir by this path`),this.fileSystem.createDir(this.config.output));let i=await this.generateOutputFiles({configuration:a});if(this.fileSystem.pathIsDir(this.config.output))for(let n of i)this.fileSystem.createFile({path:this.config.output,fileName:`${n.fileName}${n.fileExtension}`,content:n.fileContent,withPrefix:true}),consola.success("api file",`"${n.fileName}${n.fileExtension}"`,`created in ${this.config.output}`);return {files:i,configuration:a,getTemplate:this.templatesWorker.getTemplate,renderTemplate:this.templatesWorker.renderTemplate,createFile:this.fileSystem.createFile,formatTSContent:this.codeFormatter.formatCode}}getRenderTemplateData=()=>({utils:{Ts:this.config.Ts,formatDescription:this.schemaParserFabric.schemaFormatters.formatDescription,internalCase:z,classNameCase:I,pascalCase:I,getInlineParseContent:this.schemaParserFabric.getInlineParseContent,getParseContent:this.schemaParserFabric.getParseContent,getComponentByRef:this.schemaComponentsMap.get,parseSchema:this.schemaParserFabric.parseSchema,checkAndAddNull:this.schemaParserFabric.schemaUtils.safeAddNullToType,safeAddNullToType:this.schemaParserFabric.schemaUtils.safeAddNullToType,isNeedToAddNull:this.schemaParserFabric.schemaUtils.isNullMissingInType,inlineExtraFormatters:this.schemaParserFabric.schemaFormatters.inline,formatters:this.schemaParserFabric.schemaFormatters.base,formatModelName:this.typeNameFormatter.format,fmtToJSDocLine:(e,{eol:t=true})=>` * ${e}${t?`
|
|
40
40
|
`:""}`,NameResolver:O,_:g,require:this.templatesWorker.requireFnFromTemplate},config:this.config});collectModelTypes=()=>{let e=this.schemaComponentsMap.getComponents(),t=[],s=g.compact(["schemas",this.config.extractResponses&&"responses"]),r=()=>this.schemaComponentsMap.filter(...s).length,a=r(),i=0;for(;i<a;){t=[],i=0;for(let o of e)if(s.includes(o.componentName)){let n=this.prepareModelType(o);n&&t.push(n),i++;}a=r();}return this.config.sortTypes?t.sort(pe("name")):t};prepareModelType=e=>{if(e.$prepared)return e.$prepared;e.typeData||(e.typeData=this.schemaParserFabric.parseSchema(e.rawTypeData,e.typeName));let t=e.typeData,s=this.schemaParserFabric.schemaFormatters.base[t.type]?this.schemaParserFabric.schemaFormatters.base[t.type](t):t,{typeIdentifier:r,name:a,content:i,description:o}=s,n=this.typeNameFormatter.format(a);if(n===null)return null;let c={...s,typeIdentifier:r,name:n,description:o,$content:t.content,rawContent:t.content,content:i,typeData:s};return e.$prepared=c,c};generateOutputFiles=async({configuration:e})=>{let{modular:t,templatesToRender:s}=this.config,r=t?await this.createMultipleFileInfos(s,e):await this.createSingleFileInfo(s,e);if(!g.isEmpty(e.extraTemplates))for(let a of e.extraTemplates){let i=this.templatesWorker.renderTemplate(this.fileSystem.getFileContent(a.path),e);r.push(...await this.createOutputFileInfo(e,a.name,i));}return r.filter(a=>!!a&&!!a.fileContent)};createMultipleFileInfos=async(e,t)=>{let{routes:s}=t,{fileNames:r,generateRouteTypes:a,generateClient:i}=t.config,o=[];if(s.$outOfModule){if(a){let n=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:t.routes.$outOfModule});o.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,n));}if(i){let n=this.templatesWorker.renderTemplate(e.api,{...t,route:t.routes.$outOfModule});o.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,n));}}if(s.combined)for(let n of s.combined){if(a){let c=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:n});o.push(...await this.createOutputFileInfo(t,I(`${n.moduleName}_Route`),c));}if(i){let c=this.templatesWorker.renderTemplate(e.api,{...t,route:n});o.push(...await this.createOutputFileInfo(t,I(n.moduleName),c));}}return [...await this.createOutputFileInfo(t,r.dataContracts,this.templatesWorker.renderTemplate(e.dataContracts,t)),...i?await this.createOutputFileInfo(t,r.httpClient,this.templatesWorker.renderTemplate(e.httpClient,t)):[],...o]};createSingleFileInfo=async(e,t)=>{let{generateRouteTypes:s,generateClient:r}=t.config;return await this.createOutputFileInfo(t,t.fileName,g.compact([this.templatesWorker.renderTemplate(e.dataContracts,t),s&&this.templatesWorker.renderTemplate(e.routeTypes,t),r&&this.templatesWorker.renderTemplate(e.httpClient,t),r&&this.templatesWorker.renderTemplate(e.api,t)]).join(`
|
|
41
|
-
`))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),a=d.Extension.Ts;return e.translateToJavaScript?(consola.debug("using js translator for",r),await this.javascriptTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):e.customTranslator?(consola.debug("using custom translator for",r),await e.customTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):(consola.debug("generating output for",`${r}${a}`),[{fileName:r,fileExtension:a,fileContent:await this.codeFormatter.formatCode(s)}])};createApiConfig=e=>{let{info:t,servers:s,host:r,basePath:a,externalDocs:i,tags:o}=e,n=s?.[0]||{url:""},{title:c="No title",version:p}=t||{},{url:m}=n;return {info:t||{},servers:s||[],basePath:a,host:r,externalDocs:g.merge({url:"",description:""},i),tags:g.compact(o),baseUrl:m,title:c,version:p}};injectClassInstance=(e,t)=>{this[e]=t;for(let s of ts)s!==e&&e in this[s]&&(this[s][e]=t);}};var je=class{cleanOutput=false;debug=false;httpClientType=J.FETCH;modular=false;output=void 0;rewrite=false;silent=false;version=Y;constructor(e){this.update(e);}update=e=>{U(this,e);}};var rs=E__default.dirname(Pt__default.fileURLToPath(import.meta.url)),De=class{config;fileSystem;rootDir=E__default.resolve(rs,"..");paths={baseTemplates:"templates/base",httpClientTemplates:"templates/base/http-clients",moduleApiTemplates:"templates/modular",defaultApiTemplates:"templates/default"};importTemplatePrefixes=["@base","@modular","@default"];constructor(e){this.config=new je(e),this.fileSystem=new B;}async start(){consola.info('start generating source templates ".ejs" for code generator');let e=this.getTemplates();if(this.config.output){consola.info("preparing output directory for source templates");let t=E__default.resolve(process.cwd(),this.config.output);this.fileSystem.pathIsExist(t)?this.config.cleanOutput&&this.fileSystem.cleanDir(t):this.fileSystem.createDir(t);for(let s of e){let r=this.fileSystem.cropExtension(s.name),a=E__default.resolve(t,`${r}.ejs`),i=E__default.resolve(t,`${r}.eta`),o=this.fileSystem.pathIsExist(a),n=this.fileSystem.pathIsExist(i);!o&&!n?this.fileSystem.createFile({path:t,fileName:s.name,content:s.content,withPrefix:false}):this.config.rewrite&&(o?this.fileSystem.createFile({path:t,fileName:`${r}.ejs`,content:s.content,withPrefix:false}):n&&this.fileSystem.createFile({path:t,fileName:`${r}.eta`,content:s.content,withPrefix:false}));}consola.success(`source templates has been successfully created in "${t}"`);}return {files:e,configuration:this.config,createFile:this.fileSystem.createFile}}getTemplates=()=>{let e=[],t=this.getTemplateNamesFromDir(this.paths.baseTemplates),s=this.getTemplateNamesFromDir(this.paths.httpClientTemplates),r=this.config.modular?this.paths.moduleApiTemplates:this.paths.defaultApiTemplates,a=this.getTemplateNamesFromDir(r),i=s.find(n=>n.startsWith(`${this.config.httpClientType}-`)),o="";i&&(o=this.fixTemplateContent(this.getTemplateContent(`${this.paths.httpClientTemplates}/${i}`)));for(let n of t){let c=n==="http-client.ejs"&&o||this.fixTemplateContent(this.getTemplateContent(`${this.paths.baseTemplates}/${n}`));e.push({name:n,content:c});}for(let n of a)e.push({name:n,content:this.fixTemplateContent(this.getTemplateContent(`${r}/${n}`))});return e};fixTemplateContent=e=>{let t=new RegExp(`includeFile\\("(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g"),s=new RegExp(`includeFile\\(\`(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g"),r=new RegExp(`includeFile\\('(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g");return e.replace(t,'includeFile("./').replace(s,"includeFile(`./").replace(r,"includeFile('./")};getTemplateNamesFromDir=e=>this.fileSystem.readDir(E__default.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(E__default.resolve(this.rootDir,e))};async function as(h){return h.debug&&(consola.level=Number.MAX_SAFE_INTEGER),h.silent&&(consola.level=0),await new De(h).start()}async function ki(h){return h.debug&&(consola.level=Number.MAX_SAFE_INTEGER),h.silent&&(consola.level=0),await new ke(h).start()}export{mt as a,J as b,ie as c,ne as d,je as e,as as f,ki as g};//# sourceMappingURL=chunk-
|
|
42
|
-
//# sourceMappingURL=chunk-
|
|
41
|
+
`))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),a=d.Extension.Ts;return e.translateToJavaScript?(consola.debug("using js translator for",r),await this.javascriptTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):e.customTranslator?(consola.debug("using custom translator for",r),await e.customTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):(consola.debug("generating output for",`${r}${a}`),[{fileName:r,fileExtension:a,fileContent:await this.codeFormatter.formatCode(s)}])};createApiConfig=e=>{let{info:t,servers:s,host:r,basePath:a,externalDocs:i,tags:o}=e,n=s?.[0]||{url:""},{title:c="No title",version:p}=t||{},{url:m}=n;return {info:t||{},servers:s||[],basePath:a,host:r,externalDocs:g.merge({url:"",description:""},i),tags:g.compact(o),baseUrl:m,title:c,version:p}};injectClassInstance=(e,t)=>{this[e]=t;for(let s of ts)s!==e&&e in this[s]&&(this[s][e]=t);}};var je=class{cleanOutput=false;debug=false;httpClientType=J.FETCH;modular=false;output=void 0;rewrite=false;silent=false;version=Y;constructor(e){this.update(e);}update=e=>{U(this,e);}};var rs=E__default.dirname(Pt__default.fileURLToPath(import.meta.url)),De=class{config;fileSystem;rootDir=E__default.resolve(rs,"..");paths={baseTemplates:"templates/base",httpClientTemplates:"templates/base/http-clients",moduleApiTemplates:"templates/modular",defaultApiTemplates:"templates/default"};importTemplatePrefixes=["@base","@modular","@default"];constructor(e){this.config=new je(e),this.fileSystem=new B;}async start(){consola.info('start generating source templates ".ejs" for code generator');let e=this.getTemplates();if(this.config.output){consola.info("preparing output directory for source templates");let t=E__default.resolve(process.cwd(),this.config.output);this.fileSystem.pathIsExist(t)?this.config.cleanOutput&&this.fileSystem.cleanDir(t):this.fileSystem.createDir(t);for(let s of e){let r=this.fileSystem.cropExtension(s.name),a=E__default.resolve(t,`${r}.ejs`),i=E__default.resolve(t,`${r}.eta`),o=this.fileSystem.pathIsExist(a),n=this.fileSystem.pathIsExist(i);!o&&!n?this.fileSystem.createFile({path:t,fileName:s.name,content:s.content,withPrefix:false}):this.config.rewrite&&(o?this.fileSystem.createFile({path:t,fileName:`${r}.ejs`,content:s.content,withPrefix:false}):n&&this.fileSystem.createFile({path:t,fileName:`${r}.eta`,content:s.content,withPrefix:false}));}consola.success(`source templates has been successfully created in "${t}"`);}return {files:e,configuration:this.config,createFile:this.fileSystem.createFile}}getTemplates=()=>{let e=[],t=this.getTemplateNamesFromDir(this.paths.baseTemplates),s=this.getTemplateNamesFromDir(this.paths.httpClientTemplates),r=this.config.modular?this.paths.moduleApiTemplates:this.paths.defaultApiTemplates,a=this.getTemplateNamesFromDir(r),i=s.find(n=>n.startsWith(`${this.config.httpClientType}-`)),o="";i&&(o=this.fixTemplateContent(this.getTemplateContent(`${this.paths.httpClientTemplates}/${i}`)));for(let n of t){let c=n==="http-client.ejs"&&o||this.fixTemplateContent(this.getTemplateContent(`${this.paths.baseTemplates}/${n}`));e.push({name:n,content:c});}for(let n of a)e.push({name:n,content:this.fixTemplateContent(this.getTemplateContent(`${r}/${n}`))});return e};fixTemplateContent=e=>{let t=new RegExp(`includeFile\\("(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g"),s=new RegExp(`includeFile\\(\`(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g"),r=new RegExp(`includeFile\\('(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g");return e.replace(t,'includeFile("./').replace(s,"includeFile(`./").replace(r,"includeFile('./")};getTemplateNamesFromDir=e=>this.fileSystem.readDir(E__default.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(E__default.resolve(this.rootDir,e))};async function as(h){return h.debug&&(consola.level=Number.MAX_SAFE_INTEGER),h.silent&&(consola.level=0),await new De(h).start()}async function ki(h){return h.debug&&(consola.level=Number.MAX_SAFE_INTEGER),h.silent&&(consola.level=0),await new ke(h).start()}export{mt as a,J as b,ie as c,ne as d,je as e,as as f,ki as g};//# sourceMappingURL=chunk-EBM4FZTJ.js.map
|
|
42
|
+
//# sourceMappingURL=chunk-EBM4FZTJ.js.map
|