swagger-typescript-api 13.0.17 → 13.0.18

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.
@@ -0,0 +1,67 @@
1
+ import * as u from 'lodash';
2
+ import * as d from 'typescript';
3
+ import * as at from 'prettier';
4
+ import * as ct from 'cosmiconfig';
5
+ import * as mt from 'nanoid';
6
+ import * as ut from 'js-yaml';
7
+ import * as ft from 'swagger2openapi';
8
+ import * as b from 'node:path';
9
+ import b__default from 'node:path';
10
+ import * as dt from 'node:url';
11
+ import dt__default from 'node:url';
12
+ import * as gt from 'eta';
13
+ import * as N from 'node:fs';
14
+ import * as yt from 'node-emoji';
15
+
16
+ var Ot=Object.defineProperty;var Mt=(h,e)=>{for(var t in e)Ot(h,t,{get:e[t],enumerable:!0});};var te=class{config;constructor({config:e}){this.config=e;}removeUnusedImports=e=>{let t="file.ts",s=new Be(t,e),a=d.createLanguageService(s).organizeImports({type:"file",fileName:t},{newLineCharacter:d.sys.newLine})[0];return a?.textChanges.length?a.textChanges.reduceRight((i,{span:n,newText:o})=>`${i.slice(0,n.start)}${o}${i.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)},Be=class{constructor(e,t){let s=d.findConfigFile(e,d.sys.fileExists);Object.assign(this,{fileName:e,content:t,compilerOptions:s?d.convertCompilerOptionsFromJson(d.readConfigFile(s,d.sys.readFile).config.compilerOptions).options:d.getDefaultCompilerOptions()});}getNewLine(){return "newLine"in d.sys?d.sys.newLine:`
17
+ `}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 M=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=u.uniq(u.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=!0){if(typeof t=="function"){let a=null;for(;a===null;){let i=t(e,s);if(i===void 0)return this.logger.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=u.uniq(u.compact(e));for(let n of i)!a&&(!r||!this.isReserved(n))&&(a=n);return a?(r&&this.reserve([a]),a):(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 It=(h=0,e=1)=>Math.random()*(e-h)+h,it=(h=0,e=1)=>h===e?h:Math.round(It(h,e));var se=class extends M{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t,s){super(e,t,s,r=>{let a=r[it(0,r.length-1)];if(a){this.countersByVariant.has(a)||this.countersByVariant.set(a,0);let n=this.countersByVariant.get(a)+1;this.countersByVariant.set(a,n);let o=`${a}${n}`;return this.logger.debug("generated dirty resolved type name for component - ",o),o}let i=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return this.logger.debug("generated fallback type name for component - ",i),i});}};var ae={};Mt(ae,{DEFAULT_BODY_ARG_NAME:()=>Ve,FILE_PREFIX:()=>Dt,HTTP_CLIENT:()=>H,PRETTIER_OPTIONS:()=>re,PROJECT_VERSION:()=>Y,RESERVED_BODY_ARG_NAMES:()=>Ge,RESERVED_HEADER_ARG_NAMES:()=>Je,RESERVED_PATH_ARG_NAMES:()=>He,RESERVED_QUERY_ARG_NAMES:()=>Ye,RESERVED_REQ_PARAMS_ARG_NAMES:()=>_t,SCHEMA_TYPES:()=>p});var ot={name:"swagger-typescript-api",version:"13.0.18",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",prepack:"tsup",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.2.0","@types/swagger2openapi":"7.0.4",axios:"1.7.3",shx:"0.3.4",tsup:"8.2.4",vitest:"2.0.5"},packageManager:"yarn@4.4.0",engines:{node:">=18.0.0"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"}};var Ve="data",Dt=`/* eslint-disable */
18
+ /* tslint:disable */
19
+ /*
20
+ * ---------------------------------------------------------------
21
+ * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
22
+ * ## ##
23
+ * ## AUTHOR: acacode ##
24
+ * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
25
+ * ---------------------------------------------------------------
26
+ */
27
+
28
+ `,H={FETCH:"fetch",AXIOS:"axios"},re={printWidth:120,tabWidth:2,trailingComma:"all",parser:"typescript"},Y=ot.version,Ge=["data","body","reqBody"],Je=["headers","headersParams"],He=["path","pathParams"],Ye=["query","queryParams","queryArg"],_t=["params","requestParams","reqParams","httpParams"],p={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 B=(h,e)=>{if(!e)return;let t=typeof e=="function"?e(h):e,s=u.map(t,(r,a)=>r===void 0&&a).filter(Boolean);Object.assign(h,u.merge(h,t));for(let r of s)h[r]=void 0;};var Kt={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:"|"},qt={UtilRequiredKeys:"UtilRequiredKeys"},oe=class{version=Y;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={...re};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=H.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:d.ModuleKind.ESNext,noImplicitReturns:!0,alwaysStrict:!0,target:d.ScriptTarget.ESNext,declaration:!0,noImplicitAny:!1,sourceMap:!1,removeComments:!1,disableSizeLimit:!0,esModuleInterop:!0,emitDecoratorMetadata:!0,skipLibCheck:!0};customTranslator;Ts={Keyword:structuredClone(Kt),CodeGenKeyword:structuredClone(qt),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=>u.join(u.uniq(e),` ${this.Ts.Keyword.Union} `),ExpressionGroup:e=>e?`(${e})`:"",IntersectionType:e=>u.join(u.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})=>u.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=>u.map(e,({key:t,value:s})=>` ${this.Ts.EnumField(t,s)}`).join(`,
29
+ `),ObjectWrapper:e=>`{
30
+ ${e}
31
+ }`,MultilineComment:(e,t)=>[...e.length===1?[`/** ${e[0]} */`]:["/**",...e.map(s=>` * ${s}`)," */"]].map(s=>`${t?t(s):s}
32
+ `),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=nt(),codeGenConstructs:t,primitiveTypeConstructs:s,constants:r,templateInfos:a,hooks:i,...n}){B(this.Ts,t),B(this.primitiveTypes,s),this.defaultResponseType=this.Ts.Keyword.Void,this.update({...n,prettierOptions:e===void 0?nt():e,hooks:u.merge(this.hooks,i||{}),constants:{...ae,...r},templateInfos:a||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 se(this,null,[]);}update=e=>{B(this,e);}},nt=()=>{let h=ct.cosmiconfigSync("prettier",{searchStrategy:"global"}).search();return h?{...h.config,parser:"typescript"}:{...re}};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],a=s[s.length-2],i={$ref:e,typeName:r,rawTypeData:t,componentName:a,typeData:null},n=this.config.hooks.onCreateComponent(i)||i,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 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;logger;templatesWorker;schemaUtils;constructor(e){this.config=e.config,this.logger=e.logger,this.schemaUtils=e.schemaUtils,this.templatesWorker=e.templatesWorker;}base={[p.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)},[p.OBJECT]:e=>e.nullable?this.inline[p.OBJECT](e):{...e,$content:e.content,content:this.formatObjectContent(e.content)},[p.PRIMITIVE]:e=>({...e,$content:e.content})};inline={[p.ENUM]:e=>({...e,content:e.$ref?e.typeName:this.config.Ts.UnionType(u.compact([...e.content.map(({value:t})=>`${t}`),e.nullable&&this.config.Ts.Keyword.Null]))||this.config.Ts.Keyword.Any}),[p.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=u.get(e,["schemaType"])||u.get(e,["$parsed","schemaType"]);return u.get(this,[t,s])?.(e)||e};formatDescription=(e,t)=>e?e.includes(`
33
+ `)?t?u._(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},
34
+ `,n=this.templatesWorker.renderTemplate(this.config.templatesToRender.dataContractJsDoc,{data:s}).split(`
35
+ `).map(o=>`${r}${o}`).join(`
36
+ `);n?t.push(`${n}${a}`):t.push(`${a}`);}return t.join("")}};var he=h=>(e,t)=>e[h]>t[h]?1:e[h]<t[h]?-1:0;var y=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 le=class extends y{parse(){let e,{type:t,description:s,items:r}=this.schema||{};if(Array.isArray(r)&&t===p.ARRAY){let a=[];for(let i of r)a.push(this.schemaParserFabric.createSchemaParser({schema:i,schemaPath:this.schemaPath}).getInlineParseContent());e=this.config.Ts.Tuple(a);}else {let a=this.schemaParserFabric.createSchemaParser({schema:r,schemaPath:this.schemaPath}).getInlineParseContent();e=this.config.Ts.ArrayType(a);}return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:p.PRIMITIVE,type:p.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(s),content:this.schemaUtils.safeAddNullToType(this.schema,e)}}};var pe=class extends y{parse(){let e=this.schemaUtils.getComplexType(this.schema),t=u.omit(u.clone(this.schema),u.keys(this.schemaParser._complexSchemaParsers)),s=this.schemaParser._complexSchemaParsers[e](this.schema);return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:p.COMPLEX,type:p.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description||u.compact(u.map(this.schema[e],"description"))[0]||""),content:this.config.Ts.IntersectionType(u.compact([this.config.Ts.ExpressionGroup(s),this.schemaUtils.getInternalSchemaType(t)===p.OBJECT&&this.config.Ts.ExpressionGroup(this.schemaParserFabric.createSchemaParser({schema:t,schemaPath:this.schemaPath}).getInlineParseContent())]))||this.config.Ts.Keyword.Any}}};var ue=class extends y{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,a=this.createAbstractSchemaStruct(),i=this.createDiscriminatorSchema({skipMappingType:r,abstractSchemaStruct:a}),n=e.IntersectionType([a?.content,i?.content].filter(Boolean));return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:p.COMPLEX,type:p.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:a}=this.schema,i=u.entries(a.mapping),n=!e&&!!(t?.typeName&&i.length),o=[],c,m=this.createMappingPropertySchemaEnumKeys({abstractSchemaStruct:t,discPropertyName:a.propertyName});if(n){let P=`${t.typeName}_${a.propertyName}`,S=this.schemaUtils.resolveTypeName(P,{suffixes:this.config.extractingOptions.discriminatorMappingSuffix,resolver:this.config.extractingOptions.discriminatorMappingNameResolver}),C=s.IntersectionType([s.ObjectWrapper(s.TypeField({key:s.StringValue(a.propertyName),value:"Key"})),"Type"]),O=this.schemaParserFabric.createParsedComponent({typeName:S,schema:{type:"object",properties:{},genericArgs:[{name:"Key"},{name:"Type"}],internal:!0}});O.typeData.content=C,c=this.typeNameFormatter.format(O.typeName);}let l=(P,S)=>{let C=this.schemaParserFabric.createSchemaParser({schema:P,schemaPath:this.schemaPath}).getInlineParseContent(),O=m[S]||s.StringValue(S);return n?s.TypeWithGeneric(c,[O,C]):s.ExpressionGroup(s.IntersectionType([s.ObjectWrapper(s.TypeField({key:a.propertyName,value:O})),C]))};for(let[P,S]of i){let C=typeof S=="string"?{$ref:S}:S;this.mutateMappingDependentSchema({discPropertyName:a.propertyName,abstractSchemaStruct:t,mappingSchema:C,refPath:r,mappingPropertySchemaEnumKeysMap:m}),o.push(l(C,P));}return e?null:{content:s.ExpressionGroup(s.UnionType(o))}};createMappingPropertySchemaEnumKeys=({abstractSchemaStruct:e,discPropertyName:t})=>{let s=this.config.Ts,r={},a=u.get(e?.component?.rawTypeData,["properties",t]);return this.schemaUtils.isRefSchema(a)&&(a=this.schemaUtils.getSchemaRefType(a)),a?.rawTypeData?.$parsed?.type===p.ENUM&&(r=u.reduce(a.rawTypeData.$parsed.enum,(i,n,o)=>{let c=a.rawTypeData.$parsed.content[o].key;return i[n]=s.EnumUsageKey(a.rawTypeData.$parsed.typeName,c),i},{})),r};mutateMappingDependentSchema=({discPropertyName:e,abstractSchemaStruct:t,mappingSchema:s,refPath:r,mappingPropertySchemaEnumKeysMap:a})=>{let i=u.keys(this.schemaParser._complexSchemaParsers);if(s.$ref&&t?.component?.$ref){let n=this.schemaUtils.getSchemaRefType(s)?.rawTypeData;if(n)for(let o of i)Array.isArray(n[o])&&(n[o]=n[o].map(c=>{if(c.$ref===r)return {...c,$ref:t.component.$ref};if(this.schemaUtils.getInternalSchemaType(c)===p.OBJECT)for(let m in c.properties){let l=c.properties[m];m===e&&this.schemaUtils.getInternalSchemaType(l)===p.ENUM&&l.enum.length===1&&a[l.enum[0]]&&(c.properties[m]=this.schemaParserFabric.createSchema({content:a[l.enum[0]]}));}return c}));}};createAbstractSchemaStruct=()=>{let{discriminator:e,...t}=this.schema,s=u.keys(this.schemaParser._complexSchemaParsers),r=u.omit(structuredClone(t),s),a=this.schemaParserFabric.getInlineParseContent(structuredClone(r))===this.config.Ts.Keyword.Any;if(!u.keys(r).length||a)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===p.COMPLEX_UNKNOWN?null:{content:e.ExpressionGroup(this.schemaParser._complexSchemaParsers[t](this.schema))}}};var fe=class extends M{counter=1;constructor(e,t,s){super(e,t,s,r=>{let a=r[0]&&`${r[0]}${this.counter++}`||`${this.config.enumKeyResolverName}${this.counter++}`;return this.logger.debug("generated fallback type name for enum key - ",a),a});}};var de=class extends y{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),a=this.schemaUtils.getEnumNames(this.schema),i=null,n=o=>o===null?this.config.Ts.NullValue(o):r.includes(this.schemaUtils.getSchemaType({type:"number"}))?this.config.Ts.NumberValue(o):r.includes(this.schemaUtils.getSchemaType({type:"boolean"}))?this.config.Ts.BooleanValue(o):this.config.Ts.StringValue(o);return Array.isArray(a)&&u.size(a)?i=a.map((o,c)=>{let m=u.get(this.schema.enum,c),l=this.formatEnumKey({key:o,value:m});return this.config.enumNamesAsValues||m===void 0?{key:l,type:this.config.Ts.Keyword.String,value:this.config.Ts.StringValue(o)}:{key:l,type:r,value:n(m)}}):i=this.schema.enum.map(o=>({key:this.formatEnumKey({value:o}),type:r,value:n(o)})),{...typeof this.schema=="object"?this.schema:{},$ref:s,typeName:this.typeName||s&&t.typeName||null,$parsedSchema:!0,schemaType:p.ENUM,type:p.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:i}}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 ye=class extends y{parse(){let e=this.getObjectSchemaContent(this.schema);return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:p.OBJECT,type:p.OBJECT,typeIdentifier:this.config.Ts.Keyword.Interface,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),allFieldsAreOptional:!e.values().some(t=>t.isRequired),content:e}}getObjectSchemaContent=e=>{let{properties:t,additionalProperties:s}=e||{},r=u.map(t,(a,i)=>{let n=this.schemaUtils.isPropertyRequired(i,a,e),o=u.get(this.schemaUtils.getSchemaRefType(a),"rawTypeData",{}),c=!!(o.nullable||a.nullable),m=this.typeNameFormatter.isValidName(i)?i:this.config.Ts.StringValue(i),l=this.schemaParserFabric.createSchemaParser({schema:a,schemaPath:[...this.schemaPath,i]}).getInlineParseContent(),f=a.readOnly;return {...a,$$raw:a,title:a.title,description:a.description||u.compact(u.map(a[this.schemaUtils.getComplexType(a)],"description"))[0]||o.description||u.compact(u.map(o[this.schemaUtils.getComplexType(o)],"description"))[0]||"",isRequired:n,isNullable:c,name:m,value:l,field:this.config.Ts.TypeField({readonly:f&&this.config.addReadonly,optional:!n,key:m,value:l})}});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 Te=class extends y{parse(){let e=null,{additionalProperties:t,type:s,description:r,items:a}=this.schema||{};if(s===this.config.Ts.Keyword.Object&&t){let i=typeof t=="object"?this.schemaParserFabric.createSchemaParser({schema:t,schemaPath:this.schemaPath}).getInlineParseContent():this.config.Ts.Keyword.Any;e=this.config.Ts.RecordType(this.config.Ts.Keyword.String,i);}return Array.isArray(s)&&s.length&&(e=this.schemaParser._complexSchemaParsers.oneOf({...typeof this.schema=="object"?this.schema:{},oneOf:s.map(i=>({type:i}))})),Array.isArray(a)&&s===p.ARRAY&&(e=this.config.Ts.Tuple(a.map(i=>this.schemaParserFabric.createSchemaParser({schema:i,schemaPath:this.schemaPath}).getInlineParseContent()))),{...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:p.PRIMITIVE,type:p.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 Pe=class extends y{parse(){let e=[this.config.Ts.Keyword.Any],t=this.schema.allOf.map(a=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,a),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,a=>!e.includes(a)),r=this.config.Ts.IntersectionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};var Se=class extends y{parse(){let e=[this.config.Ts.Keyword.Any],t=this.schema.anyOf.map(a=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,a),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,a=>!e.includes(a)),r=this.config.Ts.UnionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};var Ne=class extends y{parse(){return this.config.Ts.Keyword.Any}};var Ce=class extends y{parse(){let e=[this.config.Ts.Keyword.Any],t=this.schema.oneOf.map(a=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,a),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,a=>!e.includes(a)),r=this.config.Ts.UnionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};function X(h){return u.camelCase(u.lowerCase(h))}function I(h){return u.upperFirst(u.camelCase(h))}var we=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=>u.uniq(e&&Array.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=typeof t.required=="boolean"?!!t.required:Array.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||!!u.get(e,"x-nullable")||r===this.config.Ts.Keyword.Null)&&typeof t=="string"&&!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 X(t.type);if(t.enum){let s=typeof t.enum[0];return s===this.config.Ts.Keyword.Undefined?void 0:X(s)}return u.keys(t.properties).length?p.OBJECT:t.items?p.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=u.uniq([...this.getRequiredProperties(e),...this.getRequiredProperties(t)]),r=this.getSchemaRefType(t);if(r){let i=u.keys(r.rawTypeData?.properties||{}).filter(n=>s.includes(n));return i.length?{...t,$$requiredKeys:i}:t}if(t.properties){let i=u.keys(t.properties).filter(n=>s.includes(n));return i.length?{required:u.uniq([...this.getRequiredProperties(t),...i]),...t}:t}return t};filterSchemaContents=(e,t)=>u.uniq(e.filter(s=>t(s)));resolveTypeName=(e,{suffixes:t,resolver:s,prefixes:r,shouldReserve:a=!0})=>s?this.config.componentTypeNameResolver.resolve(null,i=>s(I(e),i)):this.config.componentTypeNameResolver.resolve([...(r||[]).map(i=>I(`${i} ${e}`)),...(t||[]).map(i=>I(`${e} ${i}`))],a);getComplexType=e=>e.oneOf?p.COMPLEX_ONE_OF:e.allOf?p.COMPLEX_ALL_OF:e.anyOf?p.COMPLEX_ANY_OF:e.not?p.COMPLEX_NOT:p.COMPLEX_UNKNOWN;getInternalSchemaType=e=>!u.isEmpty(e.enum)||!u.isEmpty(this.getEnumNames(e))?p.ENUM:e.discriminator?p.DISCRIMINATOR:e.allOf||e.oneOf||e.anyOf||e.not?p.COMPLEX:u.isEmpty(e.properties)?e.type===p.ARRAY?p.ARRAY:p.PRIMITIVE:p.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 a=u.get(this.config.primitiveTypes,[r,e.format])||u.get(this.config.primitiveTypes,[r,"$default"])||this.config.primitiveTypes[r];typeof a=="function"?s=a(e,this):s=a||r;}return s?this.checkAndAddRequiredKeys(e,this.safeAddNullToType(e,s)):this.config.Ts.Keyword.Any};buildTypeNameFromPath=e=>(e=u.uniq(u.compact(e)),!e||!e[0]?null:I(u.camelCase(u.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 xe=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={[p.COMPLEX_ONE_OF]:e=>{let t=this.config.schemaParsers.complexOneOf||Ce;return new t(this,e,null,this.schemaPath).parse()},[p.COMPLEX_ALL_OF]:e=>{let t=this.config.schemaParsers.complexAllOf||Pe;return new t(this,e,null,this.schemaPath).parse()},[p.COMPLEX_ANY_OF]:e=>{let t=this.config.schemaParsers.complexAnyOf||Se;return new t(this,e,null,this.schemaPath).parse()},[p.COMPLEX_NOT]:e=>{let t=this.config.schemaParsers.complexNot||Ne;return new t(this,e,null,this.schemaPath).parse()}};_baseSchemaParsers={[p.ENUM]:(e,t)=>{let s=this.config.schemaParsers.enum||de;return new s(this,e,t,this.schemaPath).parse()},[p.OBJECT]:(e,t)=>{let s=this.config.schemaParsers.object||ye;return new s(this,e,t,this.schemaPath).parse()},[p.COMPLEX]:(e,t)=>{let s=this.config.schemaParsers.complex||pe;return new s(this,e,t,this.schemaPath).parse()},[p.PRIMITIVE]:(e,t)=>{let s=this.config.schemaParsers.primitive||Te;return new s(this,e,t,this.schemaPath).parse()},[p.DISCRIMINATOR]:(e,t)=>{let s=this.config.schemaParsers.discriminator||ue;return new s(this,e,t,this.schemaPath).parse()},[p.ARRAY]:(e,t)=>{let s=this.config.schemaParsers.array||le;return new s(this,e,t,this.schemaPath).parse()}};parseSchema=()=>{if(!this.schema)return this._baseSchemaParsers[p.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=p.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),u.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=u.first(u.values(t)),a=u.get(r,"schema");if(a)return {...s,...u.omit(r,"schema"),...a}}};var Fe=class{config;logger;schemaComponentsMap;typeNameFormatter;schemaFormatters;templatesWorker;schemaUtils;schemaWalker;constructor({config:e,logger:t,templatesWorker:s,schemaComponentsMap:r,typeNameFormatter:a,schemaWalker:i}){this.config=e,this.logger=t,this.schemaComponentsMap=r,this.typeNameFormatter=a,this.templatesWorker=s,this.schemaWalker=i,this.schemaUtils=new we(this),this.schemaFormatters=new me(this);}createSchemaParser=({schema:e,typeName:t,schemaPath:s})=>new xe(this,{schema:e,typeName:t,schemaPath:s});createSchema=({content:e,linkedSchema:t={},linkedComponent:s,schemaPath:r,...a})=>{let i=this.createSchemaParser({schema:s||t,schemaPath:r}),n=i.parseSchema();return n.content=e,Object.assign(n,a),s&&(s.typeData=n),i.schema};createParsedComponent=({typeName:e,schema:t,schemaPath:s})=>{let r=structuredClone(t),a=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",e]),r),i=this.parseSchema(r,null,s);return i.name=e,a.typeData=i,a};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 jt="abcdefghijklmnopqrstuvwxyz0123456789",ht=mt.customAlphabet(jt,12);var be=class extends M{counter=1;constructor(e,t,s){super(e,t,s,r=>{let a=r[0]&&`${r[0]}${this.counter++}`||`${this.config.specificArgNameResolverName}${this.counter++}`;return this.logger.debug("generated fallback type name for specific arg - ",a),a});}};var $={JSON:"JSON",URL_ENCODED:"URL_ENCODED",FORM_DATA:"FORM_DATA",IMAGE:"IMAGE",OTHER:"OTHER",TEXT:"TEXT"},Ae=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:a,typeNameFormatter:i}){this.config=e,this.schemaParserFabric=t,this.schemaUtils=this.schemaParserFabric.schemaUtils,this.typeNameFormatter=i,this.schemaComponentsMap=s,this.logger=r,this.templatesWorker=a,this.FORM_DATA_TYPES=u.uniq([this.schemaUtils.getSchemaType({type:"string",format:"file"}),this.schemaUtils.getSchemaType({type:"string",format:"binary"})]);}createRequestsMap=e=>{let t=u.get(e,"parameters");return u.reduce(e,(s,r,a)=>(a.startsWith("x-")||["parameters","$ref"].includes(a)||(s[a]={...r,parameters:u.compact(u.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=u.reduce(s,(c,m)=>{let l=m.replace(/\{|\}|:/g,"");return l&&(l.includes("-")&&this.logger.warn("wrong path param name",l),c.push({$match:m,name:u.camelCase(l),required:!0,type:"string",description:"",schema:{type:"string"},in:"path"})),c},[]),a=r.reduce((c,m,l,f)=>{let P=this.config.hooks.onInsertPathParam(m.name,l,f,c)||m.name;return c.replace(m.$match,`\${${P}}`)},t||""),i=a.match(/(\{\?.*\})/g),n=[];if(i?.length){for(let m of i)a=a.replace(m,"");let c=u.uniq(i.join(",").replace(/(\{\?)|(\})|\s/g,"").split(","));for(let m of c)m.includes("-")&&this.logger.warn("wrong query param name",m),n.push({$match:m,name:u.camelCase(m),required:!0,type:"string",description:"",schema:{type:"string"},in:"query"});}let o={originalRoute:e||"",route:a,pathParams:r,queryParams:n};return this.config.hooks.onBuildRoutePath(o)||o};getRouteParams=(e,t,s)=>{let{parameters:r}=e,a={path:[],header:[],body:[],query:[],formData:[],cookie:[]};u.each(r,i=>{let n=this.schemaParserFabric.schemaUtils.getSchemaRefType(i),o=null;if(n?.rawTypeData.in&&n.rawTypeData)a[n.rawTypeData.in]||(a[n.rawTypeData.in]=[]),o={...n.rawTypeData,...n.rawTypeData.schema||{}};else {if(!i.in)return;a[i.in]||(a[i.in]=[]),o={...i,...i.schema||{}};}if(o.in==="path"){if(!o.name)return;o.name=u.camelCase(o.name);}o&&a[o.in].push(o);});for(let i of t)a.path.some(o=>o.name===i.name)||a.path.push(i);for(let i of s)a.query.some(o=>o.name===i.name)||a.query.push(i);return a};getContentTypes=(e,t)=>u.uniq(u.compact([...t||[],...u.flatten(u.map(e,s=>s&&u.keys(s.content)))]));getContentKind=e=>e.some(t=>t.startsWith("application/json"))||e.some(t=>t.endsWith("+json"))?$.JSON:e.includes("application/x-www-form-urlencoded")?$.URL_ENCODED:e.includes("multipart/form-data")?$.FORM_DATA:e.some(t=>t.includes("image/"))?$.IMAGE:e.some(t=>t.startsWith("text/"))?$.TEXT:$.OTHER;isSuccessStatus=e=>this.config.defaultResponseAsSuccess&&e==="default"||+e>=this.config.successResponseStatusRange[0]&&+e<=this.config.successResponseStatusRange[1]||e==="2xx";getSchemaFromRequestType=e=>{let t=u.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:a})=>{let i=this.getSchemaFromRequestType(e),n=this.schemaParserFabric.schemaUtils.getSchemaRefType(e);if(i){let o=this.schemaParserFabric.getInlineParseContent(i,a,[s]),c=t.find(f=>this.typeNameFormatter.format(f.name)===o),m=t.find(f=>u.isEqual(f.content,o)),l=c||m;return l?this.typeNameFormatter.format(l.name):o}if(n){let o=n.typeName.replace(s,"");if(t.find(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})=>u.reduce(e,(a,i,n)=>{let o=this.getContentTypes([i]);return [...a,{...i||{},contentTypes:o,contentKind:this.getContentKind(o),type:this.schemaParserFabric.schemaUtils.safeAddNullToType(i,this.getTypeFromRequestInfo({requestInfo:i,parsedSchemas:t,operationId:s,defaultType:r})),description:this.schemaParserFabric.schemaFormatters.formatDescription(i.description||"",!0),status:Number.isNaN(+n)?n:+n,isSuccess:this.isSuccessStatus(n)}]},[]);getResponseBodyInfo=(e,t)=>{let{produces:s,operationId:r,responses:a}=e,i=this.getContentTypes(a,[...s||[],e["x-accepts"]]),n=this.getRequestInfoTypes({requestInfos:a,parsedSchemas:t,operationId:r,defaultType:this.config.defaultResponseType}),o=n.find(l=>l.isSuccess),c=n.filter(l=>!l.isSuccess&&l.type!==this.config.Ts.Keyword.Any),m=l=>{if(!l)return "headers: {},";let f=Object.fromEntries(Object.entries(l).map(([S,C])=>[S,this.schemaUtils.getSchemaType(C)]));return `headers: { ${Object.entries(f).map(([S,C])=>`"${S}": ${C}`).join(",")} },`};return {contentTypes:i,responses:n,success:{schema:o,type:o?.type||this.config.Ts.Keyword.Any},error:{schemas:c,type:this.config.Ts.UnionType(c.map(l=>l.type))||this.config.Ts.Keyword.Any},full:{types:this.config.Ts.UnionType(n.map(l=>`{
37
+ data: ${l.type}, status: ${l.status}, statusCode: ${l.status}, statusText: "${l.description}", ${m(l.headers)} config: {} }`))||this.config.Ts.Keyword.Any}}};convertRouteParamsIntoObject=e=>e.reduce((t,s)=>{if(!s||!s.name)return t;let r=`${s.name}`;return r.includes(".")&&(r=u.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:a,consumes:i,requestBodyName:n,operationId:o}=e,c=null,m=null,l=this.getContentTypes([a],[...i||[],e["x-contentType"]]),f=this.getContentKind(l),P=null;return this.config.extractRequestBody&&(P=this.schemaUtils.resolveTypeName(r.usage,{suffixes:this.config.extractingOptions.requestBodySuffix,resolver:this.config.extractingOptions.requestBodyNameResolver})),t.formData.length?(f=$.FORM_DATA,c=this.convertRouteParamsIntoObject(t.formData),m=this.schemaParserFabric.getInlineParseContent(c,P,[o])):f===$.FORM_DATA?(c=this.getSchemaFromRequestType(a),m=this.schemaParserFabric.getInlineParseContent(c,P,[o])):a&&(c=this.getSchemaFromRequestType(a),m=this.schemaParserFabric.schemaUtils.safeAddNullToType(a,this.getTypeFromRequestInfo({requestInfo:a,parsedSchemas:s,operationId:o,typeName:P})),this.FORM_DATA_TYPES.some(S=>m.includes(`: ${S}`))&&(f=$.FORM_DATA)),c&&!c.$ref&&this.config.extractRequestBody&&(c=this.schemaParserFabric.createParsedComponent({schema:c,typeName:P,schemaPath:[o]}),m=this.schemaParserFabric.getInlineParseContent({$ref:c.$ref})),{paramName:n||a?.name||Ve,contentTypes:l,contentKind:f,schema:c,type:m,required:a&&(typeof a.required>"u"||!!a.required)}};createRequestParamsSchema=({queryParams:e,queryObjectSchema:t,pathArgsSchemas:s,extractRequestParams:r,routeName:a})=>{if(!e||!e.length)return null;let i=s.reduce((m,l)=>(l.name&&(m[l.name]={...l,in:"path"}),m),{}),n=u.reduce(u.get(t,"properties",{}),(m,l,f)=>(f&&typeof l=="object"&&(m[f]={...l,in:"query"}),m),{}),o={...t,properties:{...n,...i}},c=this.config.hooks.onCreateRequestParams(o);if(c)return c;if(r){let m=this.schemaUtils.resolveTypeName(a.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver});return this.schemaParserFabric.createParsedComponent({typeName:m,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}),a=t.responses.indexOf(t.success.schema),i=t.success;if(i.schema&&!i.schema.$ref){let n=i.schema.contentKind,o=this.getSchemaFromRequestType(i.schema);i.schema=this.schemaParserFabric.createParsedComponent({schema:o,typeName:r,schemaPath:[e.operationId]}),i.schema.contentKind=n,i.type=this.schemaParserFabric.getInlineParseContent({$ref:i.schema.$ref}),a>-1&&u.assign(t.responses[a],{...i.schema,type:i.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}),a=t.error.schemas.map(this.getSchemaFromRequestType).filter(Boolean);if(!a.length)return;let i=this.schemaParserFabric.parseSchema({oneOf:a,title:a.map(o=>o.title).filter(Boolean).join(" "),description:a.map(o=>o.description).filter(Boolean).join(`
38
+ `)},null,[e.operationId]),n=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",r]),{...i});t.error.schemas=[n],t.error.type=this.typeNameFormatter.format(n.typeName);}};getRouteName=e=>{let{moduleName:t}=e,{routeNameDuplicatesMap:s,templatesToRender:r}=this.config,a=r.routeName,i=this.templatesWorker.renderTemplate(a,{routeInfo:e}),n=this.config.hooks.onFormatRouteName(e,i)||i,o=`${t}|${n}`;s.has(o)?(s.set(o,s.get(o)+1),this.logger.warn(`Module "${t}" already has method "${n}()"`,`
39
+ This method has been renamed to "${n+s.get(o)}()" to solve conflict names.`)):s.set(o,1);let c=s.get(o),m={usage:n+(c>1?c:""),original:n,duplicate:c>1};return this.config.hooks.onCreateRouteName(m,e)||m};parseRouteInfo=(e,t,s,r,a)=>{let{security:i}=r,{moduleNameIndex:n,moduleNameFirstTag:o,extractRequestParams:c}=this.config,{operationId:m,requestBody:l,security:f,parameters:P,summary:S,description:C,tags:O,responses:Nt,requestBodyName:Vt,produces:Ct,consumes:Rt,...Et}=t,{route:Xe,pathParams:wt,queryParams:xt}=this.parseRouteName(e),Ft=ht(),ze=O&&O.length>0?O[0]:null,Qe=o&&ze?u.camelCase(ze):u.camelCase(u.compact(Xe.split("/"))[n]),Ze=!!i?.length;f&&(Ze=f.length>0);let w=this.getRouteParams(t,wt,xt),Q=w.path.map(k=>({name:k.name,optional:!k.required,type:this.config.Ts.Keyword.Any,description:k.description})),bt=Q.map(k=>k.name),D=this.getResponseBodyInfo(t,a),et={...Et,pathArgs:Q,operationId:m,method:s,route:e,moduleName:Qe,responsesTypes:D.responses,description:C,tags:O,summary:S,responses:Nt,produces:Ct,requestBody:l,consumes:Rt,security:f},Z=this.convertRouteParamsIntoObject(w.query),We=this.convertRouteParamsIntoObject(w.path),Le=this.convertRouteParamsIntoObject(w.header),_=this.getRouteName(et),K=this.getRequestBodyInfo(t,w,a,_),At=this.createRequestParamsSchema({queryParams:w.query,pathArgsSchemas:w.path,queryObjectSchema:Z,extractRequestParams:c,routeName:_});this.config.extractResponseBody&&this.extractResponseBodyIfItNeeded(t,D,_),this.config.extractResponseError&&this.extractResponseErrorIfItNeeded(t,D,_);let ee=this.schemaUtils.resolveTypeName(_.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver,shouldReserve:!1}),tt=w.query.length?this.schemaParserFabric.getInlineParseContent(Z,null,[ee]):null,st=w.path.length?this.schemaParserFabric.getInlineParseContent(We,null,[ee]):null,rt=w.header.length?this.schemaParserFabric.getInlineParseContent(Le,null,[ee]):null,G=new be(this.config,this.logger,bt),J={query:tt?{name:G.resolve(Ye),optional:this.schemaParserFabric.parseSchema(Z,null,[_.usage]).allFieldsAreOptional,type:tt}:void 0,body:K.type?{name:G.resolve([K.paramName,...Ge]),optional:!K.required,type:K.type}:void 0,pathParams:st?{name:G.resolve(He),optional:this.schemaParserFabric.parseSchema(We,null,[_.usage]).allFieldsAreOptional,type:st}:void 0,headers:rt?{name:G.resolve(Je),optional:this.schemaParserFabric.parseSchema(Le,null,[_.usage]).allFieldsAreOptional,type:rt}:void 0};return Q.forEach((k,$t)=>{k.type=this.schemaParserFabric.getInlineParseContent(w.path[$t].schema,null,[ee]);}),{id:Ft,namespace:Qe.replace(/^(\d)/,"v$1"),routeName:_,routeParams:w,requestBodyInfo:K,responseBodyInfo:D,specificArgs:J,queryObjectSchema:Z,pathObjectSchema:We,headersObjectSchema:Le,responseBodySchema:D.success.schema,requestBodySchema:K.schema,specificArgNameResolver:G,request:{contentTypes:K.contentTypes,parameters:Q,path:Xe,formData:K.contentKind===$.FORM_DATA,isQueryBody:K.contentKind===$.URL_ENCODED,security:Ze,method:s,requestParams:At,payload:J.body,query:J.query,pathParams:J.pathParams,headers:J.headers},response:{contentTypes:D.contentTypes,type:D.success.type,errorType:D.error.type,fullTypes:D.full.types},raw:et}};attachSchema=({usageSchema:e,parsedSchemas:t})=>{this.config.routeNameDuplicatesMap.clear();let s=u.entries(e.paths);for(let[r,a]of s){let i=this.createRequestsMap(a);for(let[n,o]of Object.entries(i)){let c=this.parseRouteInfo(r,o,n,e,t),m=this.config.hooks.onCreateRoute(c);if(m!==!1){let l=m||c;!this.hasSecurityRoutes&&l.security&&(this.hasSecurityRoutes=l.security),!this.hasQueryRoutes&&l.hasQuery&&(this.hasQueryRoutes=l.hasQuery),!this.hasFormDataRoutes&&l.hasFormDataParams&&(this.hasFormDataRoutes=l.hasFormDataParams),this.routes.push(l);}}}};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=u.reduce(e,(s,r,a)=>(a==="$outOfModule"?s.outOfModule=r:(s.combined||(s.combined=[]),s.combined.push({moduleName:a,routes:r.map(i=>{let{original:n,usage:o}=i.routeName;return r.length>1&&o!==n&&!r.some(({routeName:c,id:m})=>m!==i.id&&n===c.original)?{...i,routeName:{...i.routeName,usage:n}}:i})})),s),{});return this.config.sortRoutes&&(t.outOfModule&&(t.outOfModule=this.sortRoutes(t.outOfModule)),t.combined&&u.each(t.combined,s=>{s.routes=this.sortRoutes(s.routes);})),t};sortRoutes=e=>u.slice(e).sort((t,s)=>t.routeName.usage.localeCompare(s.routeName.usage))};var $e=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,structuredClone(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("#"),a;if(this.schemas.has(s))a=this.schemas.get(s);else {let i=r.resolve(process.cwd(),s),n=this.swaggerSchemaResolver.getSwaggerSchemaByPath(i);a=this.swaggerSchemaResolver.processSwaggerSchemaFile(n),this.schemas.set(s,a);}return this._getRefDataFromSchema(a,r)}}};_isLocalRef=e=>e.startsWith("#");_isRemoteRef=e=>e.startsWith("http://")||e.startsWith("https://");_getRefDataFromSchema=(e,t)=>{let s=t.replace("#","").split("/"),r=u.get(e,s);return r&&this.caches.set(t,r),r}};var Oe=class{config;logger;constructor(e,t){this.config=e,this.logger=t;}async download({url:e,disableStrictSSL:t,authToken:s,...r}){let a={};if(t&&!e.startsWith("http://")){let i=global[Symbol.for("undici.globalDispatcher.1")];if(!i)throw new Error("Could not find the global Undici dispatcher");let n=new i.constructor({connect:{rejectUnauthorized:!1}});global[unidiciGlobalDispatcherSymbol]=n;}s&&(a.headers={Authorization:s}),u.merge(a,r,this.config.requestOptions);try{return await(await fetch(e,a)).text()}catch(i){let n=`error while fetching data from URL "${e}"`;return this.logger.error(n,"response"in i?i.response:i),n}}};var Me=class{config;logger;fileSystem;request;constructor({config:e,logger:t,fileSystem:s}){this.config=e,this.logger=t,this.fileSystem=s,this.request=new Oe(e,t);}async create(){let{spec:e,patch:t,input:s,url:r,disableStrictSSL:a,disableProxy:i,authorizationToken:n}=this.config;if(this.config.spec)return await this.convertSwaggerObject(e,{patch:t});let o=await this.fetchSwaggerSchemaFile(s,r,a,i,n),c=this.processSwaggerSchemaFile(o);return await this.convertSwaggerObject(c,{patch:t})}convertSwaggerObject(e,t){return new Promise(s=>{let r=structuredClone(e);r.info=u.merge({title:"No title",version:""},r.info),r.openapi?s({usageSchema:r,originalSchema:structuredClone(r)}):(r.paths=u.merge({},r.paths),ft.convertObj(r,{...t,warnOnly:!0,refSiblings:"preserve",rbname:"requestBodyName"},(a,i)=>{let n=u.get(a,"options.openapi",u.get(i,"openapi"));if(!n&&a)throw new Error(a);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,a){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:a,disableProxy:r}))}processSwaggerSchemaFile(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return ut.load(e)}}fixSwaggerSchema({usageSchema:e,originalSchema:t}){let s=u.get(e,"paths"),r=u.get(t,"paths");u.each(s,(a,i)=>{let n=u.get(r,i);u.each(a,(o,c)=>{let m=u.get(n,c),l=u.get(o,"parameters",[]),f=u.get(m,"parameters",[]);typeof o=="object"&&(o.consumes=u.uniq(u.compact([...o.consumes||[],...m.consumes||[]])),o.produces=u.uniq(u.compact([...o.produces||[],...m.produces||[]]))),u.each(f,P=>{l.find(C=>P.in===C.in&&P.name===C.name)||l.push(P);});});});}};var Ie=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=b.dirname(dt.fileURLToPath(import.meta.url)),s=b.resolve(t,"../templates/base"),r=b.resolve(t,"../templates/default"),a=b.resolve(t,"../templates/modular"),i=e.modular?a:r,n=e.templates&&b.resolve(process.cwd(),e.templates)||null;return {base:s,default:r,modular:a,original:i,custom:n}};cropExtension=e=>this.config.templateExtensions.reduce((t,s)=>t.endsWith(s)?t.replace(s,""):t,e);getTemplateFullPath=(e,t)=>{let s=b.resolve(e,"./",this.cropExtension(t));return this.config.templateExtensions.map(a=>`${s}${a}`).find(a=>!!this.fileSystem.pathIsExist(a))};requireFnFromTemplate=async e=>e.startsWith("./")||e.startsWith("../")?await import(b.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 a=r.custom&&this.getTemplateFullPath(r.custom,e),i=a&&this.fileSystem.getFileContent(a);if(i)return this.logger.log(`"${t.toLowerCase()}" template found in "${r.custom}"`),i;let n=this.getTemplateFullPath(r.base,e);n?i=this.fileSystem.getFileContent(n):r.custom?this.logger.warn(`"${t.toLowerCase()}" template not found in "${r.custom}"`,`
40
+ Code generator will use the default template`):this.logger.log(`Code generator will use the default template for "${t.toLowerCase()}"`);let o=this.getTemplateFullPath(r.original,e);return o&&(i=this.fileSystem.getFileContent(o)),i};getTemplates=({templatePaths:e})=>(e.custom&&this.logger.log(`try to read templates from directory "${e.custom}"`),u.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=u.keys(this.config.templatePaths).find(n=>e.startsWith(`@${n}`)),s=b.resolve(e.replace(`@${t}`,this.config.templatePaths[t])),r=this.findTemplateWithExt(s);if(r)return this.fileSystem.getFileContent(r);let a=this.config.templatePaths.custom&&this.findTemplateWithExt(b.resolve(this.config.templatePaths.custom,e));if(a)return this.fileSystem.getFileContent(a);let i=this.findTemplateWithExt(b.resolve(this.config.templatePaths.original,e));return i?this.fileSystem.getFileContent(i):""};renderTemplate=(e,t,s)=>e?gt.render(e,{...this.getRenderTemplateData(),...t},{async:!1,...s||{},includeFile:(r,a,i)=>this.renderTemplate(this.getTemplateContent(r),a,i)}):""};var De=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 _e=class extends De{compileTSCode=e=>{let t=`${e.fileName}${e.fileExtension}`,s={},r=d.createCompilerHost(this.config.compilerTsConfig,!0),a=[t],i=r.getSourceFile.bind(r);return r.getSourceFile=(n,o,c,m)=>n!==t?i(n,o,c,m):d.createSourceFile(n,e.fileContent,o,!0,d.ScriptKind.TS),r.writeFile=(n,o)=>{s[n]=o;},d.createProgram(a,this.config.compilerTsConfig,r).emit(),s};translate=async e=>{let t=this.compileTSCode(e),s=`${e.fileName}${d.Extension.Js}`,r=`${e.fileName}${d.Extension.Dts}`,a=t[s],i=e.fileContent.split(`
41
+ `).filter(o=>o.startsWith("import ")),n=t[r].split(`
42
+ `).map(o=>o.startsWith("import ")?i.shift():o).join(`
43
+ `);return [{fileName:e.fileName,fileExtension:d.Extension.Js,fileContent:await this.codeFormatter.formatCode(a)},{fileName:e.fileName,fileExtension:d.Extension.Dts,fileContent:await this.codeFormatter.formatCode(n)}]}};var Ke=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,a=s==="enum-key"?this.config.enumKeySuffix:this.config.typeSuffix,i=`${r}_${e}_${a}`;if(typeof e!="string")return this.logger.warn("wrong name of the model name",e),e;if(/^([A-Z_]{1,})$/g.test(e))return u.compact([r,e,a]).join("_");if(this.formattedModelNamesMap.has(i))return this.formattedModelNamesMap.get(i);let n=this.fixModelName(e,{type:s}),o=u.startCase(`${r}_${n}_${a}`).replace(/\s/g,""),c=this.config.hooks.onFormatTypeName(o,e,s)||o;return this.formattedModelNamesMap.set(i,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=u.startCase(e).replace(/ /g,""))),e}};var U=class{firstLog=!0;config;constructor({config:e}){this.config=e;}createLogMessage=({type:e,emojiName:t,messages:s})=>{if(this.config.silent)return;let r=yt.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 a=new Error().stack.split(`
44
+ `).splice(3).filter(n=>!n.includes("swagger-typescript-api\\node_modules")&&!n.includes("swagger-typescript-api/node_modules")).slice(0,10),i=console[e]||console.log;i(`${r} [${e}]`,new Date().toISOString()),this.config.debugExtras&&Array.isArray(this.config.debugExtras)&&i(`[${this.config.debugExtras.join(" ")}]`),i("[message]",...s.map(n=>n.startsWith(`
45
+ `)?`
46
+ ${n.replace(/\n/,"")}`:n)),i(`${a.join(`
47
+ `)}
48
+ ---`);return}console[e](r," ",...s.map(a=>a.startsWith(`
49
+ `)?`
50
+ ${r} ${a.replace(/\n/,"")}`:a));};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 Ut=`/* eslint-disable */
51
+ /* tslint:disable */
52
+ /*
53
+ * ---------------------------------------------------------------
54
+ * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
55
+ * ## ##
56
+ * ## AUTHOR: acacode ##
57
+ * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
58
+ * ---------------------------------------------------------------
59
+ */
60
+
61
+ `,V=class{logger;constructor({logger:e=new U("file-system")}={}){this.logger=e;}getFileContent=e=>N.readFileSync(e,{encoding:"utf8"});readDir=e=>N.readdirSync(e);pathIsDir=e=>{if(!e)return !1;try{return N.statSync(e).isDirectory()}catch{return !1}};cropExtension=e=>{let t=e.split(".");return t.length>1&&t.pop(),t.join(".")};removeDir=e=>{try{typeof N.rmSync=="function"?N.rmSync(e,{recursive:!0}):N.rmdirSync(e,{recursive:!0});}catch(t){this.logger.debug("failed to remove dir",t);}};createDir=e=>{try{N.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&&N.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let a=b.dirname(dt.fileURLToPath(import.meta.url)),i=b.resolve(a,e,`./${t}`),n=`${r?Ut:""}${s}`;return N.writeFileSync(i,n,u.noop)}};var kt=["schemaWalker","swaggerSchemaResolver","schemaComponentsMap","typeNameFormatter","templatesWorker","codeFormatter","schemaParserFabric","schemaRoutes","javascriptTranslator"],je=class{config;swaggerSchemaResolver;schemaComponentsMap;logger;typeNameFormatter;schemaParserFabric;schemaRoutes;fileSystem;codeFormatter;templatesWorker;schemaWalker;javascriptTranslator;constructor(e){this.config=new oe(e),this.logger=new U(this),this.fileSystem=new V(this),this.schemaWalker=new $e(this),this.swaggerSchemaResolver=new Me(this),this.schemaComponentsMap=new ce(this),this.typeNameFormatter=new Ke(this),this.templatesWorker=new Ie(this),this.codeFormatter=new te(this),this.schemaParserFabric=new Fe(this),this.schemaRoutes=new Ae(this),this.javascriptTranslator=new _e(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(),u.each(e.usageSchema.components,(o,c)=>u.each(o,(m,l)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,l]),m);}));let s=this.schemaComponentsMap.filter(u.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},a=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 i=await this.generateOutputFiles({configuration:a});if(this.fileSystem.pathIsDir(this.config.output))for(let o of i)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}`);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:X,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:function(t,{eol:s=!0}){return ` * ${t}${s?`
62
+ `:""}`},NameResolver:M,_:u,require:this.templatesWorker.requireFnFromTemplate},config:this.config});collectModelTypes=()=>{let e=this.schemaComponentsMap.getComponents(),t=[],s=u.compact(["schemas",this.config.extractResponses&&"responses"]),r=()=>this.schemaComponentsMap.filter(...s).length,a=r(),i=0;for(;i<a;){t=[],i=0;for(let n of e)if(s.includes(n.componentName)){let o=this.prepareModelType(n);o&&t.push(o),i++;}a=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:a,content:i,description:n}=s,o=this.typeNameFormatter.format(a);if(o===null)return null;let c={...s,typeIdentifier:r,name:o,description:n,$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(!u.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,n=[];if(s.$outOfModule){if(a){let o=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:t.routes.$outOfModule});n.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,o));}if(i){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(a){let c=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:o});n.push(...await this.createOutputFileInfo(t,I(`${o.moduleName}_Route`),c));}if(i){let c=this.templatesWorker.renderTemplate(e.api,{...t,route:o});n.push(...await this.createOutputFileInfo(t,I(o.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)):[],...n]};createSingleFileInfo=async(e,t)=>{let{generateRouteTypes:s,generateClient:r}=t.config;return await this.createOutputFileInfo(t,t.fileName,u.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(`
63
+ `))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),a=d.Extension.Ts;return e.translateToJavaScript?(this.logger.debug("using js translator for",r),await this.javascriptTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):e.customTranslator?(this.logger.debug("using custom translator for",r),await e.customTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):(this.logger.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:n}=e,o=s?.[0]||{url:""},{title:c="No title",version:m}=t||{},{url:l}=o;return {info:t||{},servers:s||[],basePath:a,host:r,externalDocs:u.merge({url:"",description:""},i),tags:u.compact(n),baseUrl:l,title:c,version:m}};injectClassInstance=(e,t)=>{this[e]=t;for(let s of kt)s!==e&&e in this[s]&&(this[s][e]=t);}};var Ue=class{cleanOutput=!1;output=void 0;httpClientType=H.FETCH;modular=!1;silent=!1;version=Y;rewrite=!1;constructor(e){this.update(e);}update=e=>{B(this,e);}};var Lt=b__default.dirname(dt__default.fileURLToPath(import.meta.url)),ke=class{config;fileSystem;logger;rootDir=b__default.resolve(Lt,"../../../");paths={baseTemplates:"templates/base",httpClientTemplates:"templates/base/http-clients",moduleApiTemplates:"templates/modular",defaultApiTemplates:"templates/default"};importTemplatePrefixes=["@base","@modular","@default"];constructor(e){this.config=new Ue(e),this.logger=new U(this),this.fileSystem=new V(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=b__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=b__default.resolve(t,`${r}.ejs`),i=b__default.resolve(t,`${r}.eta`),n=this.fileSystem.pathIsExist(a),o=this.fileSystem.pathIsExist(i);!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,a=this.getTemplateNamesFromDir(r),i=s.find(o=>o.startsWith(`${this.config.httpClientType}-`)),n="";i&&(n=this.fixTemplateContent(this.getTemplateContent(`${this.paths.httpClientTemplates}/${i}`)));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 a)e.push({name:o,content:this.fixTemplateContent(this.getTemplateContent(`${r}/${o}`))});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(b__default.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(b__default.resolve(this.rootDir,e))};async function Bt(h){return await new ke(h).start()}async function pa({name:h,prettier:e,...t}){return await new je({...t,fileName:h,prettierOptions:e}).start()}
64
+
65
+ export { ot as a, H as b, ae as c, oe as d, Ue as e, Bt as f, pa as g };
66
+ //# sourceMappingURL=chunk-4S2WGBLV.js.map
67
+ //# sourceMappingURL=chunk-4S2WGBLV.js.map