swagger-typescript-api 13.0.16 → 13.0.17

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swagger-typescript-api",
3
- "version": "13.0.16",
3
+ "version": "13.0.17",
4
4
  "description": "Generate the API client for Fetch or Axios from an OpenAPI Specification",
5
5
  "homepage": "https://github.com/acacode/swagger-typescript-api",
6
6
  "bugs": "https://github.com/acacode/swagger-typescript-api/issues",
@@ -34,6 +34,17 @@
34
34
  "dist",
35
35
  "templates"
36
36
  ],
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "cli:help": "node index.js -h",
40
+ "cli:json": "node index.js -r -d -p ./swagger-test-cli.json -n swagger-test-cli.ts",
41
+ "cli:yaml": "node index.js -r -d -p ./swagger-test-cli.yaml -n swagger-test-cli.ts",
42
+ "format": "biome format --write .",
43
+ "format:check": "biome format .",
44
+ "lint": "biome check",
45
+ "prepublishOnly": "pnpm build",
46
+ "test": "vitest run"
47
+ },
37
48
  "dependencies": {
38
49
  "@types/swagger-schema-official": "^2.0.25",
39
50
  "cosmiconfig": "^9.0.0",
@@ -55,29 +66,19 @@
55
66
  "@types/didyoumean": "1.2.2",
56
67
  "@types/js-yaml": "4.0.9",
57
68
  "@types/lodash": "4.17.7",
58
- "@types/node": "22.1.0",
69
+ "@types/node": "22.2.0",
59
70
  "@types/swagger2openapi": "7.0.4",
60
71
  "axios": "1.7.3",
61
72
  "shx": "0.3.4",
62
73
  "tsup": "8.2.4",
63
74
  "vitest": "2.0.5"
64
75
  },
76
+ "packageManager": "yarn@4.4.0",
65
77
  "engines": {
66
78
  "node": ">=18.0.0"
67
79
  },
68
80
  "publishConfig": {
69
81
  "access": "public",
70
- "provenance": true,
71
82
  "registry": "https://registry.npmjs.org"
72
- },
73
- "scripts": {
74
- "build": "tsup",
75
- "cli:help": "node index.js -h",
76
- "cli:json": "node index.js -r -d -p ./swagger-test-cli.json -n swagger-test-cli.ts",
77
- "cli:yaml": "node index.js -r -d -p ./swagger-test-cli.yaml -n swagger-test-cli.ts",
78
- "format": "biome format --write .",
79
- "format:check": "biome format .",
80
- "lint": "biome check",
81
- "test": "vitest run"
82
83
  }
83
84
  }
@@ -1,65 +0,0 @@
1
- import p from 'lodash';
2
- import N from 'typescript';
3
- import At from 'prettier';
4
- import { cosmiconfigSync } from 'cosmiconfig';
5
- import { customAlphabet } from 'nanoid';
6
- import Lt from 'js-yaml';
7
- import Bt from 'swagger2openapi';
8
- import L, { resolve, dirname } from 'node:path';
9
- import Vt from 'node:url';
10
- import * as ft from 'eta';
11
- import v from 'node:fs';
12
- import { emojify } from 'node-emoji';
13
-
14
- var Ft=Object.defineProperty;var wt=(m,e)=>{for(var t in e)Ft(m,t,{get:e[t],enumerable:!0});};var re=class{config;constructor({config:e}){this.config=e;}removeUnusedImports=e=>{let t="file.ts",s=new ke(t,e),i=N.createLanguageService(s).organizeImports({type:"file",fileName:t},{newLineCharacter:N.sys.newLine})[0];return i?.textChanges.length?p.reduceRight(i.textChanges,(a,{span:n,newText:o})=>`${a.slice(0,n.start)}${o}${a.slice(n.start+n.length)}`,e):e};prettierFormat=async e=>await At.format(e,this.config.prettierOptions);formatCode=async(e,{removeUnusedImports:t=!0,prettierFormat:s=!0}={})=>(t&&(e=this.removeUnusedImports(e)),s&&(e=await this.prettierFormat(e)),e)},ke=class{constructor(e,t){let s=N.findConfigFile(e,N.sys.fileExists);Object.assign(this,{fileName:e,content:t,compilerOptions:s?N.convertCompilerOptionsFromJson(N.readConfigFile(s,N.sys.readFile).config.compilerOptions).options:N.getDefaultCompilerOptions()});}getNewLine(){return "newLine"in N.sys?N.sys.newLine:`
15
- `}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return N.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return N.version}getScriptSnapshot(){return N.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:N.sys.readFile(e,t)}fileExists(e){return N.sys.fileExists(e)}};var w=class{reservedNames=[];getFallbackName=null;config;logger;constructor(e,t,s,r){this.config=e,this.logger=t,this.getFallbackName=r,this.reserve(s);}reserve(e){let t=p.uniq(p.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 p.some(this.reservedNames,t=>t===e)}resolve(e,t,s,r=!0){if(typeof t=="function"){let i=null;for(;i===null;){let a=t(e,s);if(a===void 0)return this.logger.warn("unable to resolve name. current reserved names: ",this.reservedNames),null;(!r||!this.isReserved(a))&&(i=a);}return r&&this.reserve([i]),i}else if(Array.isArray(e)){let i=null,a=p.uniq(p.compact(e));return p.forEach(a,n=>{!i&&(!r||!this.isReserved(n))&&(i=n);}),i?(r&&this.reserve([i]),i):(this.logger.debug("trying to resolve name with using fallback name generator using variants",e),this.resolve(e,this.getFallbackName,s))}return this.logger.debug("problem with reserving names. current reserved names: ",this.reservedNames),null}};var Ot=(m=0,e=1)=>Math.random()*(e-m)+m,tt=(m=0,e=1)=>m===e?m:Math.round(Ot(m,e));var ie=class extends w{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t,s){super(e,t,s,r=>{let i=r[tt(0,r.length-1)];if(i){this.countersByVariant.has(i)||this.countersByVariant.set(i,0);let n=this.countersByVariant.get(i)+1;this.countersByVariant.set(i,n);let o=`${i}${n}`;return this.logger.debug("generated dirty resolved type name for component - ",o),o}let a=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return this.logger.debug("generated fallback type name for component - ",a),a});}};var oe={};wt(oe,{DEFAULT_BODY_ARG_NAME:()=>We,FILE_PREFIX:()=>Mt,HTTP_CLIENT:()=>Y,PRETTIER_OPTIONS:()=>ae,PROJECT_VERSION:()=>X,RESERVED_BODY_ARG_NAMES:()=>Le,RESERVED_HEADER_ARG_NAMES:()=>Be,RESERVED_PATH_ARG_NAMES:()=>Ve,RESERVED_QUERY_ARG_NAMES:()=>Ge,RESERVED_REQ_PARAMS_ARG_NAMES:()=>It,SCHEMA_TYPES:()=>l});var st={name:"swagger-typescript-api",version:"13.0.16",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>",contributors:["Sora Morimoto <sora@morimoto.io>"],type:"module",exports:{".":{import:{types:"./dist/types.d.ts",default:"./dist/lib.js"},require:{types:"./dist/types.d.cts",default:"./dist/lib.cjs"}}},main:"./dist/lib.cjs",module:"./dist/lib.js",types:"./dist/types.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",prepublishOnly:"pnpm build",test:"vitest run"},dependencies:{"@types/swagger-schema-official":"^2.0.25",cosmiconfig:"^9.0.0",didyoumean:"^1.2.2",eta:"^2.2.0","js-yaml":"^4.1.0",lodash:"^4.17.21",nanoid:"^3.3.7","node-emoji":"^2.1.3",prettier:"~3.3.3","swagger-schema-official":"2.0.0-bab6bed",swagger2openapi:"^7.0.8",typescript:"~5.5.4"},devDependencies:{"@biomejs/biome":"1.8.3","@tsconfig/node18":"18.2.4","@tsconfig/strictest":"2.0.5","@types/didyoumean":"1.2.2","@types/js-yaml":"4.0.9","@types/lodash":"4.17.7","@types/node":"22.1.0","@types/swagger2openapi":"7.0.4",axios:"1.7.3",shx:"0.3.4",tsup:"8.2.4",vitest:"2.0.5"},packageManager:"pnpm@9.6.0",engines:{node:">=18.0.0"},publishConfig:{access:"public",provenance:!0,registry:"https://registry.npmjs.org"}};var We="data",Mt=`/* eslint-disable */
16
- /* tslint:disable */
17
- /*
18
- * ---------------------------------------------------------------
19
- * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
20
- * ## ##
21
- * ## AUTHOR: acacode ##
22
- * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
23
- * ---------------------------------------------------------------
24
- */
25
-
26
- `,Y={FETCH:"fetch",AXIOS:"axios"},ae={printWidth:120,tabWidth:2,trailingComma:"all",parser:"typescript"},X=st.version,Le=["data","body","reqBody"],Be=["headers","headersParams"],Ve=["path","pathParams"],Ge=["query","queryParams","queryArg"],It=["params","requestParams","reqParams","httpParams"],l={ARRAY:"array",OBJECT:"object",ENUM:"enum",REF:"$ref",PRIMITIVE:"primitive",COMPLEX:"complex",DISCRIMINATOR:"discriminator",COMPLEX_ONE_OF:"oneOf",COMPLEX_ANY_OF:"anyOf",COMPLEX_ALL_OF:"allOf",COMPLEX_NOT:"not",COMPLEX_UNKNOWN:"__unknown"};var V=(m,e)=>{if(!e)return;let t=typeof e=="function"?e(m):e,s=p.map(t,(r,i)=>r===void 0&&i).filter(Boolean);Object.assign(m,p.merge(m,t)),s.forEach(r=>{m[r]=void 0;});};var Dt={Number:"number",String:"string",Boolean:"boolean",Any:"any",Void:"void",Unknown:"unknown",Null:"null",Undefined:"undefined",Object:"object",File:"File",Date:"Date",Type:"type",Enum:"enum",Interface:"interface",Array:"Array",Record:"Record",Intersection:"&",Union:"|"},vt={UtilRequiredKeys:"UtilRequiredKeys"},ne=class{version=X;templates="";generateResponses=!1;defaultResponseAsSuccess=!1;generateRouteTypes=!1;generateClient=!0;generateUnionEnums=!1;addReadonly=!1;enumNamesAsValues=!1;swaggerSchema=null;originalSchema=null;componentsMap={};convertedFromSwagger2=!1;moduleNameIndex=0;moduleNameFirstTag=!1;disableStrictSSL=!1;disableProxy=!1;extractRequestParams=!1;extractRequestBody=!1;extractResponseBody=!1;extractResponseError=!1;extractResponses=!1;extractEnums=!1;fileNames={dataContracts:"data-contracts",routeTypes:"route-types",httpClient:"http-client",outOfModuleApi:"Common"};routeNameDuplicatesMap=new Map;prettierOptions={...ae};hooks={onPreBuildRoutePath:e=>{},onBuildRoutePath:e=>{},onInsertPathParam:e=>{},onCreateComponent:e=>e,onPreParseSchema:(e,t,s)=>{},onParseSchema:(e,t)=>t,onCreateRoute:e=>e,onInit:(e,t)=>e,onPrepareConfig:e=>e,onCreateRequestParams:e=>{},onCreateRouteName:()=>{},onFormatTypeName:(e,t,s)=>{},onFormatRouteName:(e,t)=>{}};defaultResponseType;singleHttpClient=!1;httpClientType=Y.FETCH;unwrapResponseData=!1;disableThrowOnError=!1;sortTypes=!1;sortRoutes=!1;templatePaths={base:"",default:"",modular:"",original:"",custom:""};templatesToRender={api:"",dataContracts:"",dataContractJsDoc:"",interfaceDataContract:"",typeDataContract:"",enumDataContract:"",objectFieldJsDoc:"",httpClient:"",routeTypes:"",routeName:""};schemaParsers={};toJS=!1;silent=!1;typePrefix="";typeSuffix="";enumKeyPrefix="";enumKeySuffix="";patch=!1;componentTypeNameResolver;apiClassName="Api";debug=!1;anotherArrayType=!1;internalTemplateOptions={addUtilRequiredKeysType:!1};extraTemplates=[];input="";modular=!1;output="";url="";cleanOutput=!1;spec=null;fileName="Api.ts";authorizationToken=void 0;requestOptions=null;jsPrimitiveTypes=[];jsEmptyTypes=[];fixInvalidTypeNamePrefix="Type";fixInvalidEnumKeyPrefix="Value";enumKeyResolverName="Value";typeNameResolverName="ComponentType";specificArgNameResolverName="arg";successResponseStatusRange=[200,299];extractingOptions={requestBodySuffix:["Payload","Body","Input"],requestParamsSuffix:["Params"],responseBodySuffix:["Data","Result","Output"],responseErrorSuffix:["Error","Fail","Fails","ErrorData","HttpError","BadResponse"],enumSuffix:["Enum"],discriminatorMappingSuffix:["Mapping","Mapper","MapType"],discriminatorAbstractPrefix:["Base","Abstract","Discriminator","Internal","Polymorph"]};compilerTsConfig={module:N.ModuleKind.ESNext,noImplicitReturns:!0,alwaysStrict:!0,target:N.ScriptTarget.ESNext,declaration:!0,noImplicitAny:!1,sourceMap:!1,removeComments:!1,disableSizeLimit:!0,esModuleInterop:!0,emitDecoratorMetadata:!0,skipLibCheck:!0};customTranslator;Ts={Keyword:p.cloneDeep(Dt),CodeGenKeyword:p.cloneDeep(vt),ArrayType:e=>this.anotherArrayType?this.Ts.TypeWithGeneric(this.Ts.Keyword.Array,[e]):`${this.Ts.ExpressionGroup(e)}[]`,StringValue:e=>`"${e}"`,BooleanValue:e=>`${e}`,NumberValue:e=>`${e}`,NullValue:e=>"null",UnionType:e=>p.join(p.uniq(e),` ${this.Ts.Keyword.Union} `),ExpressionGroup:e=>e?`(${e})`:"",IntersectionType:e=>p.join(p.uniq(e),` ${this.Ts.Keyword.Intersection} `),RecordType:(e,t)=>this.Ts.TypeWithGeneric(this.Ts.Keyword.Record,[e,t]),TypeField:({readonly:e,key:t,optional:s,value:r})=>p.compact([e&&"readonly ",t,s&&"?",": ",r]).join(""),InterfaceDynamicField:(e,t)=>`[key: ${e}]: ${t}`,EnumUsageKey:(e,t)=>`${e}.${t}`,EnumField:(e,t)=>`${e} = ${t}`,EnumFieldsWrapper:e=>p.map(e,({key:t,value:s})=>` ${this.Ts.EnumField(t,s)}`).join(`,
27
- `),ObjectWrapper:e=>`{
28
- ${e}
29
- }`,MultilineComment:(e,t)=>[...e.length===1?[`/** ${e[0]} */`]:["/**",...e.map(s=>` * ${s}`)," */"]].map(s=>`${t?t(s):s}
30
- `),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({prettierOptions:e=at(),codeGenConstructs:t,primitiveTypeConstructs:s,constants:r,templateInfos:i,hooks:a,...n}){V(this.Ts,t),V(this.primitiveTypes,s),this.defaultResponseType=this.Ts.Keyword.Void,this.update({...n,prettierOptions:e===void 0?at():e,hooks:p.merge(this.hooks,a||{}),constants:{...oe,...r},templateInfos:i||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 ie(this,null,[]);}update=e=>{V(this,e);}},at=()=>{let m=cosmiconfigSync("prettier",{searchStrategy:"global"}).search();return m?{...m.config,parser:"typescript"}:{...ae}};var ce=class{_data=[];config;constructor({config: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],i=s[s.length-2],a={$ref:e,typeName:r,rawTypeData:t,componentName:i,typeData:null},n=this.config.hooks.onCreateComponent(a)||a,o=this._data.findIndex(c=>c.$ref===e);return o===-1?this._data.push(n):this._data[o]=n,n}getComponents(){return this._data}filter(...e){return p.filter(this._data,t=>e.some(s=>p.startsWith(t.$ref,`#/components/${s}`)))}get(e){return this._data.find(t=>t.$ref===e)||null}};var me=class{config;logger;templatesWorker;schemaUtils;constructor(e){this.config=e.config,this.logger=e.logger,this.schemaUtils=e.schemaUtils,this.templatesWorker=e.templatesWorker;}base={[l.ENUM]:e=>this.config.generateUnionEnums?{...e,$content:e.content,content:this.config.Ts.UnionType(p.map(e.content,({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(p.compact([...p.map(e.content,({value:t})=>`${t}`),e.nullable&&this.config.Ts.Keyword.Null]))||this.config.Ts.Keyword.Any}),[l.OBJECT]:e=>p.isString(e.content)?{...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=p.get(e,["schemaType"])||p.get(e,["$parsed","schemaType"]);return p.get(this,[t,s])?.(e)||e};formatDescription=(e,t)=>{if(!e)return "";let s=e;return s=p.replace(s,/\*\//g,"*/"),p.includes(s,`
31
- `)?t?p(s).split(/\n/g).map(i=>p.trim(i)).compact().join(" ").valueOf():p.replace(s,/\n$/g,""):s};formatObjectContent=e=>{let t=[];for(let s of e){let r=" ",i=`${r}${s.field},
32
- `,n=this.templatesWorker.renderTemplate(this.config.templatesToRender.dataContractJsDoc,{data:s}).split(`
33
- `).map(o=>`${r}${o}`).join(`
34
- `);n?t.push(`${n}${i}`):t.push(`${i}`);}return t.join("")}};var he=m=>(e,t)=>e[m]>t[m]?1:e[m]<t[m]?-1:0;var d=class{schema;typeName;schemaPath;logger;schemaParser;schemaParserFabric;typeNameFormatter;schemaComponentsMap;schemaUtils;config;schemaFormatters;constructor(e,t,s=null,r=[]){this.schemaParser=e,this.schemaParserFabric=e.schemaParserFabric,this.logger=e.logger,this.schema=t,this.typeName=s,this.typeNameFormatter=e.typeNameFormatter,this.schemaPath=r,this.schemaComponentsMap=this.schemaParser.schemaComponentsMap,this.schemaUtils=this.schemaParser.schemaUtils,this.config=this.schemaParser.config,this.schemaFormatters=this.schemaParser.schemaFormatters;}parse(){throw new Error("not implemented")}buildTypeNameFromPath=()=>this.schemaUtils.buildTypeNameFromPath(this.schemaPath)};var pe=class extends d{parse(){let e,{type:t,description:s,items:r}=this.schema||{};if(p.isArray(r)&&t===l.ARRAY){let i=[];for(let a of r)i.push(this.schemaParserFabric.createSchemaParser({schema:a,schemaPath:this.schemaPath}).getInlineParseContent());e=this.config.Ts.Tuple(i);}else {let i=this.schemaParserFabric.createSchemaParser({schema:r,schemaPath:this.schemaPath}).getInlineParseContent();e=this.config.Ts.ArrayType(i);}return {...p.isObject(this.schema)?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:l.PRIMITIVE,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(s),content:this.schemaUtils.safeAddNullToType(this.schema,e)}}};var le=class extends d{parse(){let e=this.schemaUtils.getComplexType(this.schema),t=p.omit(p.clone(this.schema),p.keys(this.schemaParser._complexSchemaParsers)),s=this.schemaParser._complexSchemaParsers[e](this.schema);return {...p.isObject(this.schema)?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:l.COMPLEX,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description||p.compact(p.map(this.schema[e],"description"))[0]||""),content:this.config.Ts.IntersectionType(p.compact([this.config.Ts.ExpressionGroup(s),this.schemaUtils.getInternalSchemaType(t)===l.OBJECT&&this.config.Ts.ExpressionGroup(this.schemaParserFabric.createSchemaParser({schema:t,schemaPath:this.schemaPath}).getInlineParseContent())]))||this.config.Ts.Keyword.Any}}};var ue=class extends d{parse(){let e=this.config.Ts,{discriminator:t,...s}=this.schema;if(!t.mapping)return this.schemaParserFabric.createSchemaParser({schema:s,typeName:this.typeName,schemaPath:this.schemaPath}).parseSchema();let r=!1,i=this.createAbstractSchemaStruct(),a=this.createDiscriminatorSchema({skipMappingType:r,abstractSchemaStruct:i}),n=e.IntersectionType([i?.content,a?.content].filter(Boolean));return {...p.isObject(this.schema)?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:l.COMPLEX,type:l.PRIMITIVE,typeIdentifier:e.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),content:n}}createDiscriminatorSchema=({skipMappingType:e,abstractSchemaStruct:t})=>{let s=this.config.Ts,r=this.schemaComponentsMap.createRef(["components","schemas",this.typeName]),{discriminator:i}=this.schema,a=p.entries(i.mapping),n=!e&&!!(t?.typeName&&a.length),o=[],c,u=this.createMappingPropertySchemaEnumKeys({abstractSchemaStruct:t,discPropertyName:i.propertyName});if(n){let T=`${t.typeName}_${i.propertyName}`,P=this.schemaUtils.resolveTypeName(T,{suffixes:this.config.extractingOptions.discriminatorMappingSuffix,resolver:this.config.extractingOptions.discriminatorMappingNameResolver}),S=s.IntersectionType([s.ObjectWrapper(s.TypeField({key:s.StringValue(i.propertyName),value:"Key"})),"Type"]),F=this.schemaParserFabric.createParsedComponent({typeName:P,schema:{type:"object",properties:{},genericArgs:[{name:"Key"},{name:"Type"}],internal:!0}});F.typeData.content=S,c=this.typeNameFormatter.format(F.typeName);}let h=(T,P)=>{let S=this.schemaParserFabric.createSchemaParser({schema:T,schemaPath:this.schemaPath}).getInlineParseContent(),F=u[P]||s.StringValue(P);return n?s.TypeWithGeneric(c,[F,S]):s.ExpressionGroup(s.IntersectionType([s.ObjectWrapper(s.TypeField({key:i.propertyName,value:F})),S]))};for(let[T,P]of a){let S=typeof P=="string"?{$ref:P}:P;this.mutateMappingDependentSchema({discPropertyName:i.propertyName,abstractSchemaStruct:t,mappingSchema:S,refPath:r,mappingPropertySchemaEnumKeysMap:u}),o.push(h(S,T));}return e?null:{content:s.ExpressionGroup(s.UnionType(o))}};createMappingPropertySchemaEnumKeys=({abstractSchemaStruct:e,discPropertyName:t})=>{let s=this.config.Ts,r={},i=p.get(e?.component?.rawTypeData,["properties",t]);return this.schemaUtils.isRefSchema(i)&&(i=this.schemaUtils.getSchemaRefType(i)),i?.rawTypeData?.$parsed?.type===l.ENUM&&(r=p.reduce(i.rawTypeData.$parsed.enum,(a,n,o)=>{let c=i.rawTypeData.$parsed.content[o].key;return a[n]=s.EnumUsageKey(i.rawTypeData.$parsed.typeName,c),a},{})),r};mutateMappingDependentSchema=({discPropertyName:e,abstractSchemaStruct:t,mappingSchema:s,refPath:r,mappingPropertySchemaEnumKeysMap:i})=>{let a=p.keys(this.schemaParser._complexSchemaParsers);if(s.$ref&&t?.component?.$ref){let n=this.schemaUtils.getSchemaRefType(s)?.rawTypeData;n&&a.forEach(o=>{p.isArray(n[o])&&(n[o]=n[o].map(c=>{if(c.$ref===r)return {...c,$ref:t.component.$ref};if(this.schemaUtils.getInternalSchemaType(c)===l.OBJECT)for(let u in c.properties){let h=c.properties[u];u===e&&this.schemaUtils.getInternalSchemaType(h)===l.ENUM&&h.enum.length===1&&i[h.enum[0]]&&(c.properties[u]=this.schemaParserFabric.createSchema({content:i[h.enum[0]]}));}return c}));});}};createAbstractSchemaStruct=()=>{let{discriminator:e,...t}=this.schema,s=p.keys(this.schemaParser._complexSchemaParsers),r=p.omit(p.clone(t),s),i=this.schemaParserFabric.getInlineParseContent(p.cloneDeep(r))===this.config.Ts.Keyword.Any;if(!p.keys(r).length||i)return null;let n=this.schemaUtils.resolveTypeName(this.typeName,{prefixes:this.config.extractingOptions.discriminatorAbstractPrefix,resolver:this.config.extractingOptions.discriminatorAbstractResolver}),o=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",n]),{...r,internal:!0}),c=this.schemaParserFabric.createSchemaParser({schema:o,schemaPath:this.schemaPath}).getInlineParseContent();return {typeName:n,component:o,content:c}};createComplexSchemaStruct=()=>{let e=this.config.Ts,t=this.schemaUtils.getComplexType(this.schema);return t===l.COMPLEX_UNKNOWN?null:{content:e.ExpressionGroup(this.schemaParser._complexSchemaParsers[t](this.schema))}}};var fe=class extends w{counter=1;constructor(e,t,s){super(e,t,s,r=>{let i=r[0]&&`${r[0]}${this.counter++}`||`${this.config.enumKeyResolverName}${this.counter++}`;return this.logger.debug("generated fallback type name for enum key - ",i),i});}};var ge=class extends d{enumKeyResolver;constructor(...e){super(...e),this.enumKeyResolver=new fe(this.config,this.logger,[]);}extractEnum=e=>{let t=this.schemaUtils.resolveTypeName(e,{suffixes:this.config.extractingOptions.enumSuffix,resolver:this.config.extractingOptions.enumNameResolver}),s=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",t]),{...this.schema});return this.schemaParserFabric.parseSchema(s)};parse(){let e=this.buildTypeNameFromPath();if(this.config.extractEnums&&!this.typeName&&e!=null)return this.extractEnum(e);let t=this.schemaUtils.getSchemaRefType(this.schema),s=t?.$ref||null;if(Array.isArray(this.schema.enum)&&(this.schema.enum=this.schema.enum.filter(o=>o!=null)),Array.isArray(this.schema.enum)&&Array.isArray(this.schema.enum[0]))return this.schemaParserFabric.parseSchema({oneOf:this.schema.enum.map(o=>({type:"array",items:o.map(c=>({type:"string",enum:[c]}))}))},this.typeName,this.schemaPath);let r=this.schemaUtils.getSchemaType(this.schema),i=this.schemaUtils.getEnumNames(this.schema),a=null,n=o=>o===null?this.config.Ts.NullValue(o):p.includes(r,this.schemaUtils.getSchemaType({type:"number"}))?this.config.Ts.NumberValue(o):p.includes(r,this.schemaUtils.getSchemaType({type:"boolean"}))?this.config.Ts.BooleanValue(o):this.config.Ts.StringValue(o);return p.isArray(i)&&p.size(i)?a=p.map(i,(o,c)=>{let u=p.get(this.schema.enum,c),h=this.formatEnumKey({key:o,value:u});return this.config.enumNamesAsValues||p.isUndefined(u)?{key:h,type:this.config.Ts.Keyword.String,value:this.config.Ts.StringValue(o)}:{key:h,type:r,value:n(u)}}):a=p.map(this.schema.enum,o=>({key:this.formatEnumKey({value:o}),type:r,value:n(o)})),{...p.isObject(this.schema)?this.schema:{},$ref:s,typeName:this.typeName||s&&t.typeName||null,$parsedSchema:!0,schemaType:l.ENUM,type:l.ENUM,keyType:r,typeIdentifier:this.config.generateUnionEnums?this.config.Ts.Keyword.Type:this.config.Ts.Keyword.Enum,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),content:a}}formatEnumKey=({key:e,value:t})=>{let s;return e&&(s=this.typeNameFormatter.format(e,{type:"enum-key"})),s||(s=this.typeNameFormatter.format(`${t}`,{type:"enum-key"})),this.enumKeyResolver.resolve([s])}};var de=class extends d{parse(){let e=this.getObjectSchemaContent(this.schema);return {...p.isObject(this.schema)?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:l.OBJECT,type:l.OBJECT,typeIdentifier:this.config.Ts.Keyword.Interface,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),allFieldsAreOptional:!p.some(p.values(e),t=>t.isRequired),content:e}}getObjectSchemaContent=e=>{let{properties:t,additionalProperties:s}=e||{},r=p.map(t,(i,a)=>{let n=this.schemaUtils.isPropertyRequired(a,i,e),o=p.get(this.schemaUtils.getSchemaRefType(i),"rawTypeData",{}),c=!!(o.nullable||i.nullable),u=this.typeNameFormatter.isValidName(a)?a:this.config.Ts.StringValue(a),h=this.schemaParserFabric.createSchemaParser({schema:i,schemaPath:[...this.schemaPath,a]}).getInlineParseContent(),f=i.readOnly;return {...i,$$raw:i,title:i.title,description:i.description||p.compact(p.map(i[this.schemaUtils.getComplexType(i)],"description"))[0]||o.description||p.compact(p.map(o[this.schemaUtils.getComplexType(o)],"description"))[0]||"",isRequired:n,isNullable:c,name:u,value:h,field:this.config.Ts.TypeField({readonly:f&&this.config.addReadonly,optional:!n,key:u,value:h})}});return s&&r.push({$$raw:{additionalProperties:s},description:"",isRequired:!1,field:this.config.Ts.InterfaceDynamicField(this.config.Ts.Keyword.String,this.config.Ts.Keyword.Any)}),r}};var ye=class extends d{parse(){let e=null,{additionalProperties:t,type:s,description:r,items:i}=this.schema||{};if(s===this.config.Ts.Keyword.Object&&t){let a=p.isObject(t)?this.schemaParserFabric.createSchemaParser({schema:t,schemaPath:this.schemaPath}).getInlineParseContent():this.config.Ts.Keyword.Any;e=this.config.Ts.RecordType(this.config.Ts.Keyword.String,a);}return p.isArray(s)&&s.length&&(e=this.schemaParser._complexSchemaParsers.oneOf({...p.isObject(this.schema)?this.schema:{},oneOf:s.map(a=>({type:a}))})),p.isArray(i)&&s===l.ARRAY&&(e=this.config.Ts.Tuple(i.map(a=>this.schemaParserFabric.createSchemaParser({schema:a,schemaPath:this.schemaPath}).getInlineParseContent()))),{...p.isObject(this.schema)?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:l.PRIMITIVE,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(r),content:s===this.config.Ts.Keyword.Null?s:e||this.schemaUtils.getSchemaType(this.schema)}}};var Te=class extends d{parse(){let e=[this.config.Ts.Keyword.Any],t=p.map(this.schema.allOf,i=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,i),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,i=>!e.includes(i)),r=this.config.Ts.IntersectionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};var Pe=class extends d{parse(){let e=[this.config.Ts.Keyword.Any],t=p.map(this.schema.anyOf,i=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,i),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,i=>!e.includes(i)),r=this.config.Ts.UnionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};var Se=class extends d{parse(){return this.config.Ts.Keyword.Any}};var Ne=class extends d{parse(){let e=[this.config.Ts.Keyword.Any],t=p.map(this.schema.oneOf,i=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,i),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,i=>!e.includes(i)),r=this.config.Ts.UnionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};function Q(m){return p.camelCase(p.lowerCase(m))}function b(m){return p.upperFirst(p.camelCase(m))}var Re=class{config;schemaComponentsMap;typeNameFormatter;schemaWalker;constructor({config:e,schemaComponentsMap:t,typeNameFormatter:s,schemaWalker:r}){this.config=e,this.schemaComponentsMap=t,this.typeNameFormatter=s,this.schemaWalker=r;}getRequiredProperties=e=>p.uniq(e&&p.isArray(e.required)&&e.required||[]);isRefSchema=e=>!!e?.$ref;getEnumNames=e=>e["x-enumNames"]||e.xEnumNames||e["x-enumnames"]||e["x-enum-varnames"];getSchemaRefType=e=>this.isRefSchema(e)?this.schemaComponentsMap.get(e.$ref):null;isPropertyRequired=(e,t,s)=>{if(t["x-omitempty"]===!1)return !0;let r=p.isBoolean(t.required)?!!t.required:p.isArray(s.required)?s.required.includes(e):!!s.required;return this.config.convertedFromSwagger2?typeof t.nullable===this.config.Ts.Keyword.Undefined?r:!t.nullable:r};isNullMissingInType=(e,t)=>{let{nullable:s,type:r}=e||{};return (s||!!p.get(e,"x-nullable")||r===this.config.Ts.Keyword.Null)&&p.isString(t)&&!t.includes(` ${this.config.Ts.Keyword.Null}`)&&!t.includes(`${this.config.Ts.Keyword.Null} `)};safeAddNullToType=(e,t)=>this.isNullMissingInType(e,t)?this.config.Ts.UnionType([t,this.config.Ts.Keyword.Null]):t;getSchemaPrimitiveType=e=>{let t=e||{};if(t.type)return Q(t.type);if(t.enum){let s=typeof t.enum[0];return s===this.config.Ts.Keyword.Undefined?void 0:Q(s)}return p.keys(t.properties).length?l.OBJECT:t.items?l.ARRAY:null};checkAndAddRequiredKeys=(e,t)=>"$$requiredKeys"in e&&e.$$requiredKeys.length?(this.config.update({internalTemplateOptions:{addUtilRequiredKeysType:!0}}),this.config.Ts.TypeWithGeneric(this.config.Ts.CodeGenKeyword.UtilRequiredKeys,[t,this.config.Ts.UnionType(e.$$requiredKeys.map(this.config.Ts.StringValue))])):t;makeAddRequiredToChildSchema=(e,t)=>{if(!t)return t;let s=p.uniq([...this.getRequiredProperties(e),...this.getRequiredProperties(t)]),r=this.getSchemaRefType(t);if(r){let a=p.keys(r.rawTypeData?.properties||{}).filter(n=>s.includes(n));return a.length?{...t,$$requiredKeys:a}:t}else if(t.properties){let a=p.keys(t.properties).filter(n=>s.includes(n));return a.length?{required:p.uniq([...this.getRequiredProperties(t),...a]),...t}:t}return t};filterSchemaContents=(e,t)=>p.uniq(p.filter(e,s=>t(s)));resolveTypeName=(e,{suffixes:t,resolver:s,prefixes:r,shouldReserve:i=!0})=>s?this.config.componentTypeNameResolver.resolve(null,a=>s(b(e),a)):this.config.componentTypeNameResolver.resolve([...(r||[]).map(a=>b(`${a} ${e}`)),...(t||[]).map(a=>b(`${e} ${a}`))],i);getComplexType=e=>e.oneOf?l.COMPLEX_ONE_OF:e.allOf?l.COMPLEX_ALL_OF:e.anyOf?l.COMPLEX_ANY_OF:e.not?l.COMPLEX_NOT:l.COMPLEX_UNKNOWN;getInternalSchemaType=e=>!p.isEmpty(e.enum)||!p.isEmpty(this.getEnumNames(e))?l.ENUM:e.discriminator?l.DISCRIMINATOR:e.allOf||e.oneOf||e.anyOf||e.not?l.COMPLEX:p.isEmpty(e.properties)?e.type===l.ARRAY?l.ARRAY:l.PRIMITIVE:l.OBJECT;getSchemaType=e=>{if(!e)return this.config.Ts.Keyword.Any;let t=this.getSchemaRefType(e);if(t)return this.checkAndAddRequiredKeys(e,this.safeAddNullToType(e,this.typeNameFormatter.format(t.typeName)));let s;if(this.isConstantSchema(e))s=this.formatJsValue(e.const);else {let r=this.getSchemaPrimitiveType(e);if(r==null)return this.config.Ts.Keyword.Any;let i=p.get(this.config.primitiveTypes,[r,e.format])||p.get(this.config.primitiveTypes,[r,"$default"])||this.config.primitiveTypes[r];p.isFunction(i)?s=i(e,this):s=i||r;}return s?this.checkAndAddRequiredKeys(e,this.safeAddNullToType(e,s)):this.config.Ts.Keyword.Any};buildTypeNameFromPath=e=>(e=p.uniq(p.compact(e)),!e||!e[0]?null:b(p.camelCase(p.uniq([e[0],e[e.length-1]]).join("_"))));isConstantSchema(e){return "const"in e}formatJsValue=e=>{switch(typeof e){case"string":return this.config.Ts.StringValue(e);case"boolean":return this.config.Ts.BooleanValue(e);case"number":return this.config.Ts.NumberValue(e);default:return e===null?this.config.Ts.NullValue(e):this.config.Ts.Keyword.Any}}};var Ce=class{schemaParserFabric;config;logger;schemaComponentsMap;typeNameFormatter;schemaFormatters;schemaUtils;templatesWorker;schemaWalker;typeName;schema;schemaPath=[];constructor(e,{typeName:t,schema:s,schemaPath:r}={}){this.schemaParserFabric=e,this.config=e.config,this.logger=e.logger,this.templatesWorker=e.templatesWorker,this.schemaComponentsMap=e.schemaComponentsMap,this.typeNameFormatter=e.typeNameFormatter,this.schemaWalker=e.schemaWalker,this.schemaFormatters=e.schemaFormatters,this.schemaUtils=e.schemaUtils,this.typeName=t||null,this.schema=s,this.schemaPath=[...r||[]];}_complexSchemaParsers={[l.COMPLEX_ONE_OF]:e=>{let t=this.config.schemaParsers.complexOneOf||Ne;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ALL_OF]:e=>{let t=this.config.schemaParsers.complexAllOf||Te;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ANY_OF]:e=>{let t=this.config.schemaParsers.complexAnyOf||Pe;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_NOT]:e=>{let t=this.config.schemaParsers.complexNot||Se;return new t(this,e,null,this.schemaPath).parse()}};_baseSchemaParsers={[l.ENUM]:(e,t)=>{let s=this.config.schemaParsers.enum||ge;return new s(this,e,t,this.schemaPath).parse()},[l.OBJECT]:(e,t)=>{let s=this.config.schemaParsers.object||de;return new s(this,e,t,this.schemaPath).parse()},[l.COMPLEX]:(e,t)=>{let s=this.config.schemaParsers.complex||le;return new s(this,e,t,this.schemaPath).parse()},[l.PRIMITIVE]:(e,t)=>{let s=this.config.schemaParsers.primitive||ye;return new s(this,e,t,this.schemaPath).parse()},[l.DISCRIMINATOR]:(e,t)=>{let s=this.config.schemaParsers.discriminator||ue;return new s(this,e,t,this.schemaPath).parse()},[l.ARRAY]:(e,t)=>{let s=this.config.schemaParsers.array||pe;return new s(this,e,t,this.schemaPath).parse()}};parseSchema=()=>{if(!this.schema)return this._baseSchemaParsers[l.PRIMITIVE](null,this.typeName);let e=null,t=null;if(typeof this.schema=="string")return this.schema;if(!this.schema.$parsed){if(!this.typeName&&this.schemaUtils.isRefSchema(this.schema)&&(this.typeName=this.schemaUtils.getSchemaType(this.schema)),this.schema.items&&!Array.isArray(this.schema.items)&&!this.schema.type&&(this.schema.type=l.ARRAY),Array.isArray(this.schema.enum)&&this.schema.enum.length===1&&this.schema.enum[0]==null&&(this.logger.debug("invalid enum schema",this.schema),this.schema={type:this.config.Ts.Keyword.Null}),"content"in this.schema&&typeof this.schema.content=="object"){let s=this.extractSchemaFromResponseStruct(this.schema),r=this.schemaParserFabric.createSchemaParser({schema:s,typeName:this.typeName,schemaPath:this.schemaPath});return this.schema.$parsed=r.parseSchema(),this.schema.$parsed}e=this.schemaUtils.getInternalSchemaType(this.schema),this.schemaPath.push(this.typeName),p.merge(this.schema,this.config.hooks.onPreParseSchema(this.schema,this.typeName,e)),t=this._baseSchemaParsers[e](this.schema,this.typeName),this.schema.$parsed=this.config.hooks.onParseSchema(this.schema,t)||t,this.config.sortTypes&&Array.isArray(this.schema.$parsed?.content)&&(this.schema.$parsed.content=this.schema.$parsed.content.sort(he("name")));}return this.schemaPath.pop(),this.schema.$parsed};getInlineParseContent=()=>{let e=this.parseSchema();return this.schemaFormatters.formatSchema(e,"inline").content};getParseContent=()=>{let e=this.parseSchema();return this.schemaFormatters.formatSchema(e,"base").content};extractSchemaFromResponseStruct=e=>{let{content:t,...s}=e,r=p.first(p.values(t)),i=p.get(r,"schema");if(i)return {...s,...p.omit(r,"schema"),...i}}};var Ee=class{config;logger;schemaComponentsMap;typeNameFormatter;schemaFormatters;templatesWorker;schemaUtils;schemaWalker;constructor({config:e,logger:t,templatesWorker:s,schemaComponentsMap:r,typeNameFormatter:i,schemaWalker:a}){this.config=e,this.logger=t,this.schemaComponentsMap=r,this.typeNameFormatter=i,this.templatesWorker=s,this.schemaWalker=a,this.schemaUtils=new Re(this),this.schemaFormatters=new me(this);}createSchemaParser=({schema:e,typeName:t,schemaPath:s})=>new Ce(this,{schema:e,typeName:t,schemaPath:s});createSchema=({content:e,linkedSchema:t={},linkedComponent:s,schemaPath:r,...i})=>{let a=this.createSchemaParser({schema:s||t,schemaPath:r}),n=a.parseSchema();return n.content=e,Object.assign(n,i),s&&(s.typeData=n),a.schema};createParsedComponent=({typeName:e,schema:t,schemaPath:s})=>{let r=p.cloneDeep(t),i=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",e]),r),a=this.parseSchema(r,null,s);return a.name=e,i.typeData=a,i};parseSchema=(e,t=null,s=[])=>this.createSchemaParser({schema:e,typeName:t,schemaPath:s}).parseSchema();getInlineParseContent=(e,t,s)=>this.createSchemaParser({schema:e,typeName:t,schemaPath:s}).getInlineParseContent();getParseContent=(e,t,s)=>this.createSchemaParser({schema:e,typeName:t,schemaPath:s}).getParseContent()};var Wt="abcdefghijklmnopqrstuvwxyz0123456789",ht=customAlphabet(Wt,12);var xe=class extends w{counter=1;constructor(e,t,s){super(e,t,s,r=>{let i=r[0]&&`${r[0]}${this.counter++}`||`${this.config.specificArgNameResolverName}${this.counter++}`;return this.logger.debug("generated fallback type name for specific arg - ",i),i});}};var x={JSON:"JSON",URL_ENCODED:"URL_ENCODED",FORM_DATA:"FORM_DATA",IMAGE:"IMAGE",OTHER:"OTHER",TEXT:"TEXT"},Fe=class{config;schemaParserFabric;schemaUtils;typeNameFormatter;schemaComponentsMap;logger;templatesWorker;FORM_DATA_TYPES=[];routes=[];hasSecurityRoutes=!1;hasQueryRoutes=!1;hasFormDataRoutes=!1;constructor({config:e,schemaParserFabric:t,schemaComponentsMap:s,logger:r,templatesWorker:i,typeNameFormatter:a}){this.config=e,this.schemaParserFabric=t,this.schemaUtils=this.schemaParserFabric.schemaUtils,this.typeNameFormatter=a,this.schemaComponentsMap=s,this.logger=r,this.templatesWorker=i,this.FORM_DATA_TYPES=p.uniq([this.schemaUtils.getSchemaType({type:"string",format:"file"}),this.schemaUtils.getSchemaType({type:"string",format:"binary"})]);}createRequestsMap=e=>{let t=p.get(e,"parameters");return p.reduce(e,(s,r,i)=>(p.startsWith(i,"x-")||["parameters","$ref"].includes(i)||(s[i]={...r,parameters:p.compact(p.concat(t,r.parameters))}),s),{})};parseRouteName=e=>{let t=this.config.hooks.onPreBuildRoutePath(e)||e,s=(t||"").match(/({(([A-z]){1}([a-zA-Z0-9]-?_?\.?)+)([0-9]+)?})|(:(([A-z]){1}([a-zA-Z0-9]-?_?\.?)+)([0-9]+)?:?)/g),r=p.reduce(s,(c,u)=>{let h=p.replace(u,/\{|\}|:/g,"");return h&&(p.includes(h,"-")&&this.logger.warn("wrong path param name",h),c.push({$match:u,name:p.camelCase(h),required:!0,type:"string",description:"",schema:{type:"string"},in:"path"})),c},[]),i=p.reduce(r,(c,u,h,f)=>{let T=this.config.hooks.onInsertPathParam(u.name,h,f,c)||u.name;return p.replace(c,u.$match,`\${${T}}`)},t||""),a=i.match(/(\{\?.*\})/g),n=[];a?.length&&(a.forEach(c=>{i=i.replace(c,"");}),p.uniq(a.join(",").replace(/(\{\?)|(\})|\s/g,"").split(",")).forEach(c=>{p.includes(c,"-")&&this.logger.warn("wrong query param name",c),n.push({$match:c,name:p.camelCase(c),required:!0,type:"string",description:"",schema:{type:"string"},in:"query"});}));let o={originalRoute:e||"",route:i,pathParams:r,queryParams:n};return this.config.hooks.onBuildRoutePath(o)||o};getRouteParams=(e,t,s)=>{let{parameters:r}=e,i={path:[],header:[],body:[],query:[],formData:[],cookie:[]};return p.each(r,a=>{let n=this.schemaParserFabric.schemaUtils.getSchemaRefType(a),o=null;if(n?.rawTypeData.in&&n.rawTypeData)i[n.rawTypeData.in]||(i[n.rawTypeData.in]=[]),o={...n.rawTypeData,...n.rawTypeData.schema||{}};else {if(!a.in)return;i[a.in]||(i[a.in]=[]),o={...a,...a.schema||{}};}if(o.in==="path"){if(!o.name)return;o.name=p.camelCase(o.name);}o&&i[o.in].push(o);}),p.each(t,a=>{p.some(i.path,o=>o.name===a.name)||i.path.push(a);}),p.each(s,a=>{p.some(i.query,o=>o.name===a.name)||i.query.push(a);}),i};getContentTypes=(e,t)=>p.uniq(p.compact([...t||[],...p.flatten(p.map(e,s=>s&&p.keys(s.content)))]));getContentKind=e=>p.some(e,t=>p.startsWith(t,"application/json"))||p.some(e,t=>p.endsWith(t,"+json"))?x.JSON:e.includes("application/x-www-form-urlencoded")?x.URL_ENCODED:e.includes("multipart/form-data")?x.FORM_DATA:p.some(e,t=>p.includes(t,"image/"))?x.IMAGE:p.some(e,t=>p.startsWith(t,"text/"))?x.TEXT:x.OTHER;isSuccessStatus=e=>this.config.defaultResponseAsSuccess&&e==="default"||+e>=this.config.successResponseStatusRange[0]&&+e<=this.config.successResponseStatusRange[1]||e==="2xx";getSchemaFromRequestType=e=>{let t=p.get(e,"content");if(!t)return null;for(let s in t)if(t[s]?.schema)return {...t[s].schema,dataType:s};return null};getTypeFromRequestInfo=({requestInfo:e,parsedSchemas:t,operationId:s,defaultType:r,typeName:i})=>{let a=this.getSchemaFromRequestType(e),n=this.schemaParserFabric.schemaUtils.getSchemaRefType(e);if(a){let o=this.schemaParserFabric.getInlineParseContent(a,i,[s]),c=p.find(t,f=>this.typeNameFormatter.format(f.name)===o),u=p.find(t,f=>p.isEqual(f.content,o)),h=c||u;return h?this.typeNameFormatter.format(h.name):o}if(n){let o=p.replace(n.typeName,s,"");if(p.find(t,c=>c.name===o))return this.typeNameFormatter.format(o);switch(n.componentName){case"schemas":return this.typeNameFormatter.format(n.typeName);case"responses":case"requestBodies":return this.schemaParserFabric.getInlineParseContent(this.getSchemaFromRequestType(n.rawTypeData),n.typeName||null,[s]);default:return this.schemaParserFabric.getInlineParseContent(n.rawTypeData,n.typeName||null,[s])}}return r||this.config.Ts.Keyword.Any};getRequestInfoTypes=({requestInfos:e,parsedSchemas:t,operationId:s,defaultType:r})=>p.reduce(e,(i,a,n)=>{let o=this.getContentTypes([a]);return [...i,{...a||{},contentTypes:o,contentKind:this.getContentKind(o),type:this.schemaParserFabric.schemaUtils.safeAddNullToType(a,this.getTypeFromRequestInfo({requestInfo:a,parsedSchemas:t,operationId:s,defaultType:r})),description:this.schemaParserFabric.schemaFormatters.formatDescription(a.description||"",!0),status:p.isNaN(+n)?n:+n,isSuccess:this.isSuccessStatus(n)}]},[]);getResponseBodyInfo=(e,t)=>{let{produces:s,operationId:r,responses:i}=e,a=this.getContentTypes(i,[...s||[],e["x-accepts"]]),n=this.getRequestInfoTypes({requestInfos:i,parsedSchemas:t,operationId:r,defaultType:this.config.defaultResponseType}),o=n.find(h=>h.isSuccess),c=n.filter(h=>!h.isSuccess&&h.type!==this.config.Ts.Keyword.Any),u=h=>{if(!h)return "headers: {},";let f=Object.fromEntries(Object.entries(h).map(([P,S])=>[P,this.schemaUtils.getSchemaType(S)]));return `headers: { ${Object.entries(f).map(([P,S])=>`"${P}": ${S}`).join(",")} },`};return {contentTypes:a,responses:n,success:{schema:o,type:o?.type||this.config.Ts.Keyword.Any},error:{schemas:c,type:this.config.Ts.UnionType(c.map(h=>h.type))||this.config.Ts.Keyword.Any},full:{types:this.config.Ts.UnionType(n.map(h=>`{
35
- data: ${h.type}, status: ${h.status}, statusCode: ${h.status}, statusText: "${h.description}", ${u(h.headers)} config: {} }`))||this.config.Ts.Keyword.Any}}};convertRouteParamsIntoObject=e=>p.reduce(e,(t,s)=>{if(!s||!s.name)return t;let r=`${s.name}`;return r.includes(".")&&(r=p.camelCase(r)),{...t,properties:{...t.properties,[r]:{...s,...s.schema||{},$origName:s.name,name:r}}}},{properties:{},type:"object"});getRequestBodyInfo=(e,t,s,r)=>{let{requestBody:i,consumes:a,requestBodyName:n,operationId:o}=e,c=null,u=null,h=this.getContentTypes([i],[...a||[],e["x-contentType"]]),f=this.getContentKind(h),T=null;return this.config.extractRequestBody&&(T=this.schemaUtils.resolveTypeName(r.usage,{suffixes:this.config.extractingOptions.requestBodySuffix,resolver:this.config.extractingOptions.requestBodyNameResolver})),t.formData.length?(f=x.FORM_DATA,c=this.convertRouteParamsIntoObject(t.formData),u=this.schemaParserFabric.getInlineParseContent(c,T,[o])):f===x.FORM_DATA?(c=this.getSchemaFromRequestType(i),u=this.schemaParserFabric.getInlineParseContent(c,T,[o])):i&&(c=this.getSchemaFromRequestType(i),u=this.schemaParserFabric.schemaUtils.safeAddNullToType(i,this.getTypeFromRequestInfo({requestInfo:i,parsedSchemas:s,operationId:o,typeName:T})),this.FORM_DATA_TYPES.some(P=>p.includes(u,`: ${P}`))&&(f=x.FORM_DATA)),c&&!c.$ref&&this.config.extractRequestBody&&(c=this.schemaParserFabric.createParsedComponent({schema:c,typeName:T,schemaPath:[o]}),u=this.schemaParserFabric.getInlineParseContent({$ref:c.$ref})),{paramName:n||i?.name||We,contentTypes:h,contentKind:f,schema:c,type:u,required:i&&(typeof i.required>"u"||!!i.required)}};createRequestParamsSchema=({queryParams:e,queryObjectSchema:t,pathArgsSchemas:s,extractRequestParams:r,routeName:i})=>{if(!e||!e.length)return null;let a=p.reduce(s,(u,h)=>(h.name&&(u[h.name]={...h,in:"path"}),u),{}),n=p.reduce(p.get(t,"properties",{}),(u,h,f)=>(f&&p.isObject(h)&&(u[f]={...h,in:"query"}),u),{}),o={...t,properties:{...n,...a}},c=this.config.hooks.onCreateRequestParams(o);if(c)return c;if(r){let u=this.schemaUtils.resolveTypeName(i.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver});return this.schemaParserFabric.createParsedComponent({typeName:u,schema:o})}return o};extractResponseBodyIfItNeeded=(e,t,s)=>{if(t.responses.length&&t.success&&t.success.schema){let r=this.schemaUtils.resolveTypeName(s.usage,{suffixes:this.config.extractingOptions.responseBodySuffix,resolver:this.config.extractingOptions.responseBodyNameResolver}),i=t.responses.indexOf(t.success.schema),a=t.success;if(a.schema&&!a.schema.$ref){let n=a.schema.contentKind,o=this.getSchemaFromRequestType(a.schema);a.schema=this.schemaParserFabric.createParsedComponent({schema:o,typeName:r,schemaPath:[e.operationId]}),a.schema.contentKind=n,a.type=this.schemaParserFabric.getInlineParseContent({$ref:a.schema.$ref}),i>-1&&p.assign(t.responses[i],{...a.schema,type:a.type});}}};extractResponseErrorIfItNeeded=(e,t,s)=>{if(t.responses.length&&t.error.schemas&&t.error.schemas.length){let r=this.schemaUtils.resolveTypeName(s.usage,{suffixes:this.config.extractingOptions.responseErrorSuffix,resolver:this.config.extractingOptions.responseErrorNameResolver}),i=t.error.schemas.map(this.getSchemaFromRequestType).filter(Boolean);if(!i.length)return;let a=this.schemaParserFabric.parseSchema({oneOf:i,title:i.map(o=>o.title).filter(Boolean).join(" "),description:i.map(o=>o.description).filter(Boolean).join(`
36
- `)},null,[e.operationId]),n=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",r]),{...a});t.error.schemas=[n],t.error.type=this.typeNameFormatter.format(n.typeName);}};getRouteName=e=>{let{moduleName:t}=e,{routeNameDuplicatesMap:s,templatesToRender:r}=this.config,i=r.routeName,a=this.templatesWorker.renderTemplate(i,{routeInfo:e}),n=this.config.hooks.onFormatRouteName(e,a)||a,o=`${t}|${n}`;s.has(o)?(s.set(o,s.get(o)+1),this.logger.warn(`Module "${t}" already has method "${n}()"`,`
37
- This method has been renamed to "${n+s.get(o)}()" to solve conflict names.`)):s.set(o,1);let c=s.get(o),u={usage:n+(c>1?c:""),original:n,duplicate:c>1};return this.config.hooks.onCreateRouteName(u,e)||u};parseRouteInfo=(e,t,s,r,i)=>{let{security:a}=r,{moduleNameIndex:n,moduleNameFirstTag:o,extractRequestParams:c}=this.config,{operationId:u,requestBody:h,security:f,parameters:T,summary:P,description:S,tags:F,responses:dt,requestBodyName:ss,produces:yt,consumes:Tt,...Pt}=t,{route:Je,pathParams:St,queryParams:Nt}=this.parseRouteName(e),Rt=ht(),He=F&&F.length>0?F[0]:null,Ye=o&&He?p.camelCase(He):p.camelCase(p.compact(p.split(Je,"/"))[n]),Xe=!!a?.length;f&&(Xe=f.length>0);let R=this.getRouteParams(t,St,Nt),ee=R.path.map(k=>({name:k.name,optional:!k.required,type:this.config.Ts.Keyword.Any,description:k.description})),Ct=ee.map(k=>k.name),O=this.getResponseBodyInfo(t,i),ze={...Pt,pathArgs:ee,operationId:u,method:s,route:e,moduleName:Ye,responsesTypes:O.responses,description:S,tags:F,summary:P,responses:dt,produces:yt,requestBody:h,consumes:Tt,security:f},te=this.convertRouteParamsIntoObject(R.query),Ue=this.convertRouteParamsIntoObject(R.path),je=this.convertRouteParamsIntoObject(R.header),$=this.getRouteName(ze),M=this.getRequestBodyInfo(t,R,i,$),Et=this.createRequestParamsSchema({queryParams:R.query,pathArgsSchemas:R.path,queryObjectSchema:te,extractRequestParams:c,routeName:$});this.config.extractResponseBody&&this.extractResponseBodyIfItNeeded(t,O,$),this.config.extractResponseError&&this.extractResponseErrorIfItNeeded(t,O,$);let se=this.schemaUtils.resolveTypeName($.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver,shouldReserve:!1}),Qe=R.query.length?this.schemaParserFabric.getInlineParseContent(te,null,[se]):null,Ze=R.path.length?this.schemaParserFabric.getInlineParseContent(Ue,null,[se]):null,et=R.header.length?this.schemaParserFabric.getInlineParseContent(je,null,[se]):null,J=new xe(this.config,this.logger,Ct),H={query:Qe?{name:J.resolve(Ge),optional:this.schemaParserFabric.parseSchema(te,null,[$.usage]).allFieldsAreOptional,type:Qe}:void 0,body:M.type?{name:J.resolve([M.paramName,...Le]),optional:!M.required,type:M.type}:void 0,pathParams:Ze?{name:J.resolve(Ve),optional:this.schemaParserFabric.parseSchema(Ue,null,[$.usage]).allFieldsAreOptional,type:Ze}:void 0,headers:et?{name:J.resolve(Be),optional:this.schemaParserFabric.parseSchema(je,null,[$.usage]).allFieldsAreOptional,type:et}:void 0};return ee.forEach((k,xt)=>{k.type=this.schemaParserFabric.getInlineParseContent(R.path[xt].schema,null,[se]);}),{id:Rt,namespace:p.replace(Ye,/^(\d)/,"v$1"),routeName:$,routeParams:R,requestBodyInfo:M,responseBodyInfo:O,specificArgs:H,queryObjectSchema:te,pathObjectSchema:Ue,headersObjectSchema:je,responseBodySchema:O.success.schema,requestBodySchema:M.schema,specificArgNameResolver:J,request:{contentTypes:M.contentTypes,parameters:ee,path:Je,formData:M.contentKind===x.FORM_DATA,isQueryBody:M.contentKind===x.URL_ENCODED,security:Xe,method:s,requestParams:Et,payload:H.body,query:H.query,pathParams:H.pathParams,headers:H.headers},response:{contentTypes:O.contentTypes,type:O.success.type,errorType:O.error.type,fullTypes:O.full.types},raw:ze}};attachSchema=({usageSchema:e,parsedSchemas:t})=>{this.config.routeNameDuplicatesMap.clear();let s=p.entries(e.paths);p.forEach(s,([r,i])=>{let a=this.createRequestsMap(i);p.forEach(a,(n,o)=>{let c=this.parseRouteInfo(r,n,o,e,t),u=this.config.hooks.onCreateRoute(c);if(u!==!1){let h=u||c;!this.hasSecurityRoutes&&h.security&&(this.hasSecurityRoutes=h.security),!this.hasQueryRoutes&&h.hasQuery&&(this.hasQueryRoutes=h.hasQuery),!this.hasFormDataRoutes&&h.hasFormDataParams&&(this.hasFormDataRoutes=h.hasFormDataParams),this.routes.push(h);}});});};getGroupedRoutes=()=>{let e=this.routes.reduce((s,r)=>(r.namespace?(s[r.namespace]||(s[r.namespace]=[]),s[r.namespace].push(r)):s.$outOfModule.push(r),s),{$outOfModule:[]}),t=p.reduce(e,(s,r,i)=>(i==="$outOfModule"?s.outOfModule=r:(s.combined||(s.combined=[]),s.combined.push({moduleName:i,routes:p.map(r,a=>{let{original:n,usage:o}=a.routeName;return r.length>1&&o!==n&&!p.some(r,({routeName:c,id:u})=>u!==a.id&&n===c.original)?{...a,routeName:{...a.routeName,usage:n}}:a})})),s),{});return this.config.sortRoutes&&(t.outOfModule&&(t.outOfModule=this.sortRoutes(t.outOfModule)),t.combined&&p.each(t.combined,s=>{s.routes=this.sortRoutes(s.routes);})),t};sortRoutes=e=>p.slice(e).sort((t,s)=>t.routeName.usage.localeCompare(s.routeName.usage))};var we=class{logger;config;swaggerSchemaResolver;schemas=new Map;caches=new Map;constructor({config:e,logger:t}){this.logger=t,this.config=e;}addSchema=(e,t)=>{this.schemas.set(e,p.cloneDeep(t));};findByRef=e=>{if(this.logger.debug("try to resolve ref by path",e),this.caches.has(e))return this.caches.get(e);let t=Array.from(this.schemas.values());if(this._isLocalRef(e))for(let s of t){let r=this._getRefDataFromSchema(s,e);if(r)return r}else {if(this._isRemoteRef(e))return this.logger.debug("remote refs not supported",e),null;{let[s,r]=r.split("#"),i;if(this.schemas.has(s))i=this.schemas.get(s);else {let a=r.resolve(process.cwd(),s),n=this.swaggerSchemaResolver.getSwaggerSchemaByPath(a);i=this.swaggerSchemaResolver.processSwaggerSchemaFile(n),this.schemas.set(s,i);}return this._getRefDataFromSchema(i,r)}}};_isLocalRef=e=>e.startsWith("#");_isRemoteRef=e=>e.startsWith("http://")||e.startsWith("https://");_getRefDataFromSchema=(e,t)=>{let s=t.replace("#","").split("/"),r=p.get(e,s);return r&&this.caches.set(t,r),r}};var be=class{config;logger;constructor(e,t){this.config=e,this.logger=t;}async download({url:e,disableStrictSSL:t,authToken:s,...r}){let i={};if(t&&!p.startsWith(e,"http://")){let a=global[Symbol.for("undici.globalDispatcher.1")];if(!a)throw new Error("Could not find the global Undici dispatcher");let n=new a.constructor({connect:{rejectUnauthorized:!1}});global[unidiciGlobalDispatcherSymbol]=n;}s&&(i.headers={Authorization:s}),p.merge(i,r,this.config.requestOptions);try{return await(await fetch(e,i)).text()}catch(a){let n=`error while fetching data from URL "${e}"`;return this.logger.error(n,"response"in a?a.response:a),n}}};var Ae=class{config;logger;fileSystem;request;constructor({config:e,logger:t,fileSystem:s}){this.config=e,this.logger=t,this.fileSystem=s,this.request=new be(e,t);}async create(){let{spec:e,patch:t,input:s,url:r,disableStrictSSL:i,disableProxy:a,authorizationToken:n}=this.config;if(this.config.spec)return await this.convertSwaggerObject(e,{patch:t});let o=await this.fetchSwaggerSchemaFile(s,r,i,a,n),c=this.processSwaggerSchemaFile(o);return await this.convertSwaggerObject(c,{patch:t})}convertSwaggerObject(e,t){return new Promise(s=>{let r=p.cloneDeep(e);r.info=p.merge({title:"No title",version:""},r.info),r.openapi?s({usageSchema:r,originalSchema:p.cloneDeep(r)}):(r.paths=p.merge({},r.paths),Bt.convertObj(r,{...t,warnOnly:!0,refSiblings:"preserve",rbname:"requestBodyName"},(i,a)=>{let n=p.get(i,"options.openapi",p.get(a,"openapi"));if(!n&&i)throw new Error(i);this.config.update({convertedFromSwagger2:!0}),s({usageSchema:n,originalSchema:r});}));})}getSwaggerSchemaByPath=e=>(this.logger.log(`try to get swagger by path "${e}"`),this.fileSystem.getFileContent(e));async fetchSwaggerSchemaFile(e,t,s,r,i){return this.fileSystem.pathIsExist(e)?this.getSwaggerSchemaByPath(e):(this.logger.log(`try to get swagger by URL "${t}"`),await this.request.download({url:t,disableStrictSSL:s,authToken:i,disableProxy:r}))}processSwaggerSchemaFile(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return Lt.load(e)}}fixSwaggerSchema({usageSchema:e,originalSchema:t}){let s=p.get(e,"paths"),r=p.get(t,"paths");p.each(s,(i,a)=>{let n=p.get(r,a);p.each(i,(o,c)=>{let u=p.get(n,c),h=p.get(o,"parameters",[]),f=p.get(u,"parameters",[]);typeof o=="object"&&(o.consumes=p.uniq(p.compact([...o.consumes||[],...u.consumes||[]])),o.produces=p.uniq(p.compact([...o.produces||[],...u.produces||[]]))),p.each(f,T=>{p.find(h,S=>T.in===S.in&&T.name===S.name)||h.push(T);});});});}};var Oe=class{config;logger;fileSystem;getRenderTemplateData;constructor({config:e,logger:t,fileSystem:s,getRenderTemplateData:r}){this.config=e,this.logger=t,this.fileSystem=s,this.getRenderTemplateData=r;}getTemplatePaths=e=>{let t=L.dirname(Vt.fileURLToPath(import.meta.url)),s=resolve(t,"../templates/base"),r=resolve(t,"../templates/default"),i=resolve(t,"../templates/modular"),a=e.modular?i:r,n=e.templates&&resolve(process.cwd(),e.templates)||null;return {base:s,default:r,modular:i,original:a,custom:n}};cropExtension=e=>this.config.templateExtensions.reduce((t,s)=>p.endsWith(t,s)?t.replace(s,""):t,e);getTemplateFullPath=(e,t)=>{let s=resolve(e,"./",this.cropExtension(t));return this.config.templateExtensions.map(i=>`${s}${i}`).find(i=>!!this.fileSystem.pathIsExist(i))};requireFnFromTemplate=async e=>p.startsWith(e,"./")||p.startsWith(e,"../")?await import(L.resolve(this.config.templatePaths.custom||this.config.templatePaths.original,e)):await import(e);getTemplate=({fileName:e,name:t,path:s})=>{let{templatePaths:r}=this.config;if(s)return this.fileSystem.getFileContent(s);if(!e)return "";let i=r.custom&&this.getTemplateFullPath(r.custom,e),a=i&&this.fileSystem.getFileContent(i);if(a)return this.logger.log(`"${p.lowerCase(t)}" template found in "${r.custom}"`),a;let n=this.getTemplateFullPath(r.base,e);n?a=this.fileSystem.getFileContent(n):r.custom?this.logger.warn(`"${p.lowerCase(t)}" template not found in "${r.custom}"`,`
38
- Code generator will use the default template`):this.logger.log(`Code generator will use the default template for "${p.lowerCase(t)}"`);let o=this.getTemplateFullPath(r.original,e);return o&&(a=this.fileSystem.getFileContent(o)),a};getTemplates=({templatePaths:e})=>(e.custom&&this.logger.log(`try to read templates from directory "${e.custom}"`),p.reduce(this.config.templateInfos,(t,{fileName:s,name:r})=>({...t,[r]:this.getTemplate({fileName:s,name:r})}),{}));findTemplateWithExt=e=>{let t=this.cropExtension(e);return this.config.templateExtensions.map(r=>`${t}${r}`).find(r=>this.fileSystem.pathIsExist(r))};getTemplateContent=e=>{let t=p.keys(this.config.templatePaths).find(n=>p.startsWith(e,`@${n}`)),s=resolve(p.replace(e,`@${t}`,this.config.templatePaths[t])),r=this.findTemplateWithExt(s);if(r)return this.fileSystem.getFileContent(r);let i=this.config.templatePaths.custom&&this.findTemplateWithExt(resolve(this.config.templatePaths.custom,e));if(i)return this.fileSystem.getFileContent(i);let a=this.findTemplateWithExt(resolve(this.config.templatePaths.original,e));return a?this.fileSystem.getFileContent(a):""};renderTemplate=(e,t,s)=>e?ft.render(e,{...this.getRenderTemplateData(),...t},{async:!1,...s||{},includeFile:(r,i,a)=>this.renderTemplate(this.getTemplateContent(r),i,a)}):""};var $e=class{logger;config;codeFormatter;constructor(e){this.logger=e.logger,this.config=e.config,this.codeFormatter=e.codeFormatter;}translate(e){throw new Error("not implemented")}};var Me=class extends $e{compileTSCode=e=>{let t=`${e.fileName}${e.fileExtension}`,s={},r=N.createCompilerHost(this.config.compilerTsConfig,!0),i=[t],a=r.getSourceFile.bind(r);return r.getSourceFile=(n,o,c,u)=>n!==t?a(n,o,c,u):N.createSourceFile(n,e.fileContent,o,!0,N.ScriptKind.TS),r.writeFile=(n,o)=>{s[n]=o;},N.createProgram(i,this.config.compilerTsConfig,r).emit(),s};translate=async e=>{let t=this.compileTSCode(e),s=`${e.fileName}${N.Extension.Js}`,r=`${e.fileName}${N.Extension.Dts}`,i=t[s],a=e.fileContent.split(`
39
- `).filter(o=>o.startsWith("import ")),n=t[r].split(`
40
- `).map(o=>o.startsWith("import ")?a.shift():o).join(`
41
- `);return [{fileName:e.fileName,fileExtension:N.Extension.Js,fileContent:await this.codeFormatter.formatCode(i)},{fileName:e.fileName,fileExtension:N.Extension.Dts,fileContent:await this.codeFormatter.formatCode(n)}]}};var _e=class{formattedModelNamesMap=new Map;config;logger;constructor({config:e,logger:t}){this.config=e,this.logger=t;}format=(e,t)=>{t=t||{};let s=t.type||"type-name",r=s==="enum-key"?this.config.enumKeyPrefix:this.config.typePrefix,i=s==="enum-key"?this.config.enumKeySuffix:this.config.typeSuffix,a=`${r}_${e}_${i}`;if(typeof e!="string")return this.logger.warn("wrong name of the model name",e),e;if(/^([A-Z_]{1,})$/g.test(e))return p.compact([r,e,i]).join("_");if(this.formattedModelNamesMap.has(a))return this.formattedModelNamesMap.get(a);let n=this.fixModelName(e,{type:s}),o=p.replace(p.startCase(`${r}_${n}_${i}`),/\s/g,""),c=this.config.hooks.onFormatTypeName(o,e,s)||o;return this.formattedModelNamesMap.set(a,c),c};isValidName=e=>/^([A-Za-z$_]{1,})$/g.test(e);fixModelName=(e,t)=>{let{type:s}=t||{};return this.isValidName(e)||(/^[a-zA-Z_$]/g.test(e)||(e=`${s==="enum-key"?this.config.fixInvalidEnumKeyPrefix:this.config.fixInvalidTypeNamePrefix} ${e}`),e.includes(".")&&(e=e.replace(/Exclude_keyof[A-Za-z]+/g,()=>"ExcludeKeys").replace(/%22~AND~%22/g,"And").replace(/%22~OR~%22/g,"Or").replace(/(\.?%22)|\./g,"_").replace(/__+$/,"")),e.includes("-")&&(e=p.startCase(e).replace(/ /g,""))),e}};var j=class{firstLog=!0;config;constructor({config:e}){this.config=e;}createLogMessage=({type:e,emojiName:t,messages:s})=>{if(this.config.silent)return;let r=emojify(t);if(this.firstLog&&(this.firstLog=!1,this.log(`swagger-typescript-api(${this.config.version}),${process.env.npm_config_user_agent||`nodejs(${process.version})`},debug mode ${this.config.debug?"ENABLED":"DISABLED"}`)),e==="debug"||this.config.debug){let i=new Error().stack.split(`
42
- `).splice(3).filter(n=>!n.includes("swagger-typescript-api\\node_modules")&&!n.includes("swagger-typescript-api/node_modules")).slice(0,10),a=console[e]||console.log;a(`${r} [${e}]`,new Date().toISOString()),this.config.debugExtras&&Array.isArray(this.config.debugExtras)&&a(`[${this.config.debugExtras.join(" ")}]`),a("[message]",...p.map(s,n=>p.startsWith(n,`
43
- `)?`
44
- ${n.replace(/\n/,"")}`:n)),a(i.join(`
45
- `)+`
46
- ---`);return}console[e](r," ",...p.map(s,i=>p.startsWith(i,`
47
- `)?`
48
- ${r} ${i.replace(/\n/,"")}`:i));};log=(...e)=>this.createLogMessage({type:"log",emojiName:":sparkles:",messages:e});event=(...e)=>this.createLogMessage({type:"log",emojiName:":star:",messages:e});success=(...e)=>this.createLogMessage({type:"log",emojiName:":white_check_mark:",messages:e});warn=(...e)=>this.createLogMessage({type:"warn",emojiName:":exclamation:",messages:e});error=(...e)=>this.createLogMessage({type:"error",emojiName:":no_entry:",messages:e});debug=(...e)=>{this.config.debug&&this.createLogMessage({type:"debug",emojiName:":black_large_square:",messages:e});}};var Xt=`/* eslint-disable */
49
- /* tslint:disable */
50
- /*
51
- * ---------------------------------------------------------------
52
- * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
53
- * ## ##
54
- * ## AUTHOR: acacode ##
55
- * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
56
- * ---------------------------------------------------------------
57
- */
58
-
59
- `,G=class{logger;constructor({logger:e=new j("file-system")}={}){this.logger=e;}getFileContent=e=>v.readFileSync(e,{encoding:"utf8"});readDir=e=>v.readdirSync(e);pathIsDir=e=>{if(!e)return !1;try{return v.statSync(e).isDirectory()}catch{return !1}};cropExtension=e=>{let t=p.split(e,".");return t.length>1&&t.pop(),t.join(".")};removeDir=e=>{try{typeof v.rmSync=="function"?v.rmSync(e,{recursive:!0}):v.rmdirSync(e,{recursive:!0});}catch(t){this.logger.debug("failed to remove dir",t);}};createDir=e=>{try{v.mkdirSync(e,{recursive:!0});}catch(t){this.logger.debug("failed to create dir",t);}};cleanDir=e=>{this.removeDir(e),this.createDir(e);};pathIsExist=e=>!!e&&v.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let i=dirname(Vt.fileURLToPath(import.meta.url)),a=resolve(i,e,`./${t}`),n=`${r?Xt:""}${s}`;return v.writeFileSync(a,n,p.noop)}};var Qt=["schemaWalker","swaggerSchemaResolver","schemaComponentsMap","typeNameFormatter","templatesWorker","codeFormatter","schemaParserFabric","schemaRoutes","javascriptTranslator"],ve=class{config;swaggerSchemaResolver;schemaComponentsMap;logger;typeNameFormatter;schemaParserFabric;schemaRoutes;fileSystem;codeFormatter;templatesWorker;schemaWalker;javascriptTranslator;constructor(e){this.config=new ne(e),this.logger=new j(this),this.fileSystem=new G(this),this.schemaWalker=new we(this),this.swaggerSchemaResolver=new Ae(this),this.schemaComponentsMap=new ce(this),this.typeNameFormatter=new _e(this),this.templatesWorker=new Oe(this),this.codeFormatter=new re(this),this.schemaParserFabric=new Ee(this),this.schemaRoutes=new Fe(this),this.javascriptTranslator=new Me(this),this.config.componentTypeNameResolver.logger=this.logger;}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),this.logger.event("start generating your typescript api"),this.config.update(this.config.hooks.onInit(this.config,this)||this.config),this.schemaComponentsMap.clear(),p.each(e.usageSchema.components,(o,c)=>p.each(o,(u,h)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,h]),u);}));let s=this.schemaComponentsMap.filter(p.compact(["schemas",this.config.extractResponses&&"responses"])).map(o=>{let c=this.schemaParserFabric.parseSchema(o.rawTypeData,o.typeName);return o.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(this):null,utils:this.getRenderTemplateData().utils},i=this.config.hooks.onPrepareConfig(r)||r;this.fileSystem.pathIsExist(this.config.output)?this.config.cleanOutput&&(this.logger.debug(`cleaning dir ${this.config.output}`),this.fileSystem.cleanDir(this.config.output)):(this.logger.debug(`path ${this.config.output} is not exist. creating dir by this path`),this.fileSystem.createDir(this.config.output));let a=await this.generateOutputFiles({configuration:i});return this.fileSystem.pathIsDir(this.config.output)&&a.forEach(o=>{this.fileSystem.createFile({path:this.config.output,fileName:`${o.fileName}${o.fileExtension}`,content:o.fileContent,withPrefix:!0}),this.logger.success("api file",`"${o.fileName}${o.fileExtension}"`,`created in ${this.config.output}`);}),{files:a,configuration:i,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:Q,classNameCase:b,pascalCase:b,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:function(t,{eol:s=!0}){return ` * ${t}${s?`
60
- `:""}`},NameResolver:w,_:p,require:this.templatesWorker.requireFnFromTemplate},config:this.config});collectModelTypes=()=>{let e=this.schemaComponentsMap.getComponents(),t=[],s=p.compact(["schemas",this.config.extractResponses&&"responses"]),r=()=>this.schemaComponentsMap.filter(...s).length,i=r(),a=0;for(;a<i;){t=[],a=0;for(let n of e)if(s.includes(n.componentName)){let o=this.prepareModelType(n);o&&t.push(o),a++;}i=r();}return this.config.sortTypes?t.sort(he("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:i,content:a,description:n}=s,o=this.typeNameFormatter.format(i);if(o===null)return null;let c={...s,typeIdentifier:r,name:o,description:n,$content:t.content,rawContent:t.content,content:a,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(!p.isEmpty(e.extraTemplates))for(let i of e.extraTemplates){let a=this.templatesWorker.renderTemplate(this.fileSystem.getFileContent(i.path),e);r.push(...await this.createOutputFileInfo(e,i.name,a));}return r.filter(i=>!!i&&!!i.fileContent)};createMultipleFileInfos=async(e,t)=>{let{routes:s}=t,{fileNames:r,generateRouteTypes:i,generateClient:a}=t.config,n=[];if(s.$outOfModule){if(i){let o=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:t.routes.$outOfModule});n.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,o));}if(a){let o=this.templatesWorker.renderTemplate(e.api,{...t,route:t.routes.$outOfModule});n.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,o));}}if(s.combined)for(let o of s.combined){if(i){let c=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:o});n.push(...await this.createOutputFileInfo(t,b(`${o.moduleName}_Route`),c));}if(a){let c=this.templatesWorker.renderTemplate(e.api,{...t,route:o});n.push(...await this.createOutputFileInfo(t,b(o.moduleName),c));}}return [...await this.createOutputFileInfo(t,r.dataContracts,this.templatesWorker.renderTemplate(e.dataContracts,t)),...a?await this.createOutputFileInfo(t,r.httpClient,this.templatesWorker.renderTemplate(e.httpClient,t)):[],...n]};createSingleFileInfo=async(e,t)=>{let{generateRouteTypes:s,generateClient:r}=t.config;return await this.createOutputFileInfo(t,t.fileName,p.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(`
61
- `))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),i=N.Extension.Ts;return e.translateToJavaScript?(this.logger.debug("using js translator for",r),await this.javascriptTranslator.translate({fileName:r,fileExtension:i,fileContent:s})):e.customTranslator?(this.logger.debug("using custom translator for",r),await e.customTranslator.translate({fileName:r,fileExtension:i,fileContent:s})):(this.logger.debug("generating output for",`${r}${i}`),[{fileName:r,fileExtension:i,fileContent:await this.codeFormatter.formatCode(s)}])};createApiConfig=e=>{let{info:t,servers:s,host:r,basePath:i,externalDocs:a,tags:n}=e,o=s?.[0]||{url:""},{title:c="No title",version:u}=t||{},{url:h}=o;return {info:t||{},servers:s||[],basePath:i,host:r,externalDocs:p.merge({url:"",description:""},a),tags:p.compact(n),baseUrl:h,title:c,version:u}};injectClassInstance=(e,t)=>{this[e]=t,Qt.forEach(s=>{s!==e&&e in this[s]&&(this[s][e]=t);});}};var Ke=class{cleanOutput=!1;output=void 0;httpClientType=Y.FETCH;modular=!1;silent=!1;version=X;rewrite=!1;constructor(e){this.update(e);}update=e=>{V(this,e);}};var es=L.dirname(Vt.fileURLToPath(import.meta.url)),qe=class{config;fileSystem;logger;rootDir=L.resolve(es,"../../../");paths={baseTemplates:"templates/base",httpClientTemplates:"templates/base/http-clients",moduleApiTemplates:"templates/modular",defaultApiTemplates:"templates/default"};importTemplatePrefixes=["@base","@modular","@default"];constructor(e){this.config=new Ke(e),this.logger=new j(this),this.fileSystem=new G(this);}async start(){this.logger.event('start generating source templates ".ejs" for code generator');let e=this.getTemplates();if(this.config.output){this.logger.log("preparing output directory for source templates");let t=L.resolve(process.cwd(),this.config.output);this.fileSystem.pathIsExist(t)?this.config.cleanOutput&&this.fileSystem.cleanDir(t):this.fileSystem.createDir(t),e.forEach(s=>{let r=this.fileSystem.cropExtension(s.name),i=L.resolve(t,`${r}.ejs`),a=L.resolve(t,`${r}.eta`),n=this.fileSystem.pathIsExist(i),o=this.fileSystem.pathIsExist(a);!n&&!o?this.fileSystem.createFile({path:t,fileName:s.name,content:s.content,withPrefix:!1}):this.config.rewrite&&(n?this.fileSystem.createFile({path:t,fileName:`${r}.ejs`,content:s.content,withPrefix:!1}):o&&this.fileSystem.createFile({path:t,fileName:`${r}.eta`,content:s.content,withPrefix:!1}));}),this.logger.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,i=this.getTemplateNamesFromDir(r),a=s.find(o=>o.startsWith(`${this.config.httpClientType}-`)),n="";a&&(n=this.fixTemplateContent(this.getTemplateContent(`${this.paths.httpClientTemplates}/${a}`)));for(let o of t){let c=o==="http-client.ejs"&&n||this.fixTemplateContent(this.getTemplateContent(`${this.paths.baseTemplates}/${o}`));e.push({name:o,content:c});}for(let o of i)e.push({name:o,content:this.fixTemplateContent(this.getTemplateContent(`${r}/${o}`))});return e};fixTemplateContent=e=>{let t=new RegExp(`includeFile\\("(${this.importTemplatePrefixes.map(i=>`(${i})`).join("|")})/`,"g"),s=new RegExp(`includeFile\\(\`(${this.importTemplatePrefixes.map(i=>`(${i})`).join("|")})/`,"g"),r=new RegExp(`includeFile\\('(${this.importTemplatePrefixes.map(i=>`(${i})`).join("|")})/`,"g");return e.replace(t,'includeFile("./').replace(s,"includeFile(`./").replace(r,"includeFile('./")};getTemplateNamesFromDir=e=>this.fileSystem.readDir(L.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(L.resolve(this.rootDir,e))};async function ts(m){return await new qe(m).start()}async function ma({name:m,prettier:e,...t}){return await new ve({...t,fileName:m,prettierOptions:e}).start()}
62
-
63
- export { st as a, Y as b, oe as c, ne as d, Ke as e, ts as f, ma as g };
64
- //# sourceMappingURL=chunk-J5EMB2ZI.js.map
65
- //# sourceMappingURL=chunk-J5EMB2ZI.js.map