swagger-typescript-api 13.0.19 → 13.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-Z4NI2Y3K.js → chunk-3LHF3KLG.js} +4 -4
- package/dist/chunk-3LHF3KLG.js.map +1 -0
- package/dist/{chunk-UH6TMUDA.cjs → chunk-725EVWJG.cjs} +7 -7
- package/dist/chunk-725EVWJG.cjs.map +1 -0
- package/dist/cli.cjs +4 -4
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +4 -4
- package/dist/cli.js.map +1 -1
- package/dist/lib.cjs +4 -4
- package/dist/lib.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-UH6TMUDA.cjs.map +0 -1
- package/dist/chunk-Z4NI2Y3K.js.map +0 -1
|
@@ -48,7 +48,7 @@ var N__namespace = /*#__PURE__*/_interopNamespace(N);
|
|
|
48
48
|
var gt__namespace = /*#__PURE__*/_interopNamespace(gt);
|
|
49
49
|
|
|
50
50
|
var bt=Object.defineProperty;var At=(h,e)=>{for(var t in e)bt(h,t,{get:e[t],enumerable:!0});};var Z=class{config;constructor({config:e}){this.config=e;}removeUnusedImports=e=>{let t="file.ts",s=new qe(t,e),a=g__namespace.createLanguageService(s).organizeImports({type:"file",fileName:t},{newLineCharacter:g__namespace.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 Ze__namespace.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)},qe=class{constructor(e,t){let s=g__namespace.findConfigFile(e,g__namespace.sys.fileExists);Object.assign(this,{fileName:e,content:t,compilerOptions:s?g__namespace.convertCompilerOptionsFromJson(g__namespace.readConfigFile(s,g__namespace.sys.readFile).config.compilerOptions).options:g__namespace.getDefaultCompilerOptions()});}getNewLine(){return "newLine"in g__namespace.sys?g__namespace.sys.newLine:`
|
|
51
|
-
`}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return g__namespace.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return g__namespace.version}getScriptSnapshot(){return g__namespace.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:g__namespace.sys.readFile(e,t)}fileExists(e){return g__namespace.sys.fileExists(e)}};var b=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__default.default.uniq(u__default.default.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__default.default.uniq(u__default.default.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 $t=(h=0,e=1)=>Math.random()*(e-h)+h,et=(h=0,e=1)=>h===e?h:Math.round($t(h,e));var te=class extends b{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t,s){super(e,t,s,r=>{let a=r[et(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 re={};At(re,{DEFAULT_BODY_ARG_NAME:()=>je,FILE_PREFIX:()=>Mt,HTTP_CLIENT:()=>V,PRETTIER_OPTIONS:()=>se,PROJECT_VERSION:()=>G,RESERVED_BODY_ARG_NAMES:()=>Ue,RESERVED_HEADER_ARG_NAMES:()=>ke,RESERVED_PATH_ARG_NAMES:()=>We,RESERVED_QUERY_ARG_NAMES:()=>Le,RESERVED_REQ_PARAMS_ARG_NAMES:()=>It,SCHEMA_TYPES:()=>l});var tt={name:"swagger-typescript-api",version:"13.0.
|
|
51
|
+
`}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return g__namespace.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return g__namespace.version}getScriptSnapshot(){return g__namespace.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:g__namespace.sys.readFile(e,t)}fileExists(e){return g__namespace.sys.fileExists(e)}};var b=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__default.default.uniq(u__default.default.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__default.default.uniq(u__default.default.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 $t=(h=0,e=1)=>Math.random()*(e-h)+h,et=(h=0,e=1)=>h===e?h:Math.round($t(h,e));var te=class extends b{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t,s){super(e,t,s,r=>{let a=r[et(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 re={};At(re,{DEFAULT_BODY_ARG_NAME:()=>je,FILE_PREFIX:()=>Mt,HTTP_CLIENT:()=>V,PRETTIER_OPTIONS:()=>se,PROJECT_VERSION:()=>G,RESERVED_BODY_ARG_NAMES:()=>Ue,RESERVED_HEADER_ARG_NAMES:()=>ke,RESERVED_PATH_ARG_NAMES:()=>We,RESERVED_QUERY_ARG_NAMES:()=>Le,RESERVED_REQ_PARAMS_ARG_NAMES:()=>It,SCHEMA_TYPES:()=>l});var tt={name:"swagger-typescript-api",version:"13.0.21",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 je="data",Mt=`/* eslint-disable */
|
|
52
52
|
/* tslint:disable */
|
|
53
53
|
/*
|
|
54
54
|
* ---------------------------------------------------------------
|
|
@@ -67,10 +67,10 @@ ${e}
|
|
|
67
67
|
`)?t?u__default.default._(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},
|
|
68
68
|
`,n=this.templatesWorker.renderTemplate(this.config.templatesToRender.dataContractJsDoc,{data:s}).split(`
|
|
69
69
|
`).map(o=>`${r}${o}`).join(`
|
|
70
|
-
`);n?t.push(`${n}${a}`):t.push(`${a}`);}return t.join("")}};var ce=h=>(e,t)=>e[h]>t[h]?1:e[h]<t[h]?-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 me=class extends d{parse(){let e,{type:t,description:s,items:r}=this.schema||{};if(Array.isArray(r)&&t===l.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: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 he=class extends d{parse(){let e=this.schemaUtils.getComplexType(this.schema),t=u__default.default.omit(u__default.default.clone(this.schema),u__default.default.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:l.COMPLEX,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description||u__default.default.compact(u__default.default.map(this.schema[e],"description"))[0]||""),content:this.config.Ts.IntersectionType(u__default.default.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 pe=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,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: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:a}=this.schema,i=u__default.default.entries(a.mapping),n=!e&&!!(t?.typeName&&i.length),o=[],c,m=this.createMappingPropertySchemaEnumKeys({abstractSchemaStruct:t,discPropertyName:a.propertyName});if(n){let y=`${t.typeName}_${a.propertyName}`,T=this.schemaUtils.resolveTypeName(y,{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"]),F=this.schemaParserFabric.createParsedComponent({typeName:T,schema:{type:"object",properties:{},genericArgs:[{name:"Key"},{name:"Type"}],internal:!0}});F.typeData.content=C,c=this.typeNameFormatter.format(F.typeName);}let p=(y,T)=>{let C=this.schemaParserFabric.createSchemaParser({schema:y,schemaPath:this.schemaPath}).getInlineParseContent(),F=m[T]||s.StringValue(T);return n?s.TypeWithGeneric(c,[F,C]):s.ExpressionGroup(s.IntersectionType([s.ObjectWrapper(s.TypeField({key:a.propertyName,value:F})),C]))};for(let[y,T]of i){let C=typeof T=="string"?{$ref:T}:T;this.mutateMappingDependentSchema({discPropertyName:a.propertyName,abstractSchemaStruct:t,mappingSchema:C,refPath:r,mappingPropertySchemaEnumKeysMap:m}),o.push(p(C,y));}return e?null:{content:s.ExpressionGroup(s.UnionType(o))}};createMappingPropertySchemaEnumKeys=({abstractSchemaStruct:e,discPropertyName:t})=>{let s=this.config.Ts,r={},a=u__default.default.get(e?.component?.rawTypeData,["properties",t]);return this.schemaUtils.isRefSchema(a)&&(a=this.schemaUtils.getSchemaRefType(a)),a?.rawTypeData?.$parsed?.type===l.ENUM&&(r=u__default.default.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__default.default.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)===l.OBJECT)for(let m in c.properties){let p=c.properties[m];m===e&&this.schemaUtils.getInternalSchemaType(p)===l.ENUM&&p.enum.length===1&&a[p.enum[0]]&&(c.properties[m]=this.schemaParserFabric.createSchema({content:a[p.enum[0]]}));}return c}));}};createAbstractSchemaStruct=()=>{let{discriminator:e,...t}=this.schema,s=u__default.default.keys(this.schemaParser._complexSchemaParsers),r=u__default.default.omit(structuredClone(t),s),a=this.schemaParserFabric.getInlineParseContent(structuredClone(r))===this.config.Ts.Keyword.Any;if(!u__default.default.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===l.COMPLEX_UNKNOWN?null:{content:e.ExpressionGroup(this.schemaParser._complexSchemaParsers[t](this.schema))}}};var le=class extends b{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 ue=class extends d{enumKeyResolver;constructor(...e){super(...e),this.enumKeyResolver=new le(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__default.default.size(a)?i=a.map((o,c)=>{let m=u__default.default.get(this.schema.enum,c),p=this.formatEnumKey({key:o,value:m});return this.config.enumNamesAsValues||m===void 0?{key:p,type:this.config.Ts.Keyword.String,value:this.config.Ts.StringValue(o)}:{key:p,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: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: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 fe=class extends d{parse(){let e=this.getObjectSchemaContent(this.schema);return {...typeof this.schema=="object"?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:!e.values().some(t=>t.isRequired),content:e}}getObjectSchemaContent=e=>{let{properties:t,additionalProperties:s}=e||{},r=u__default.default.map(t,(a,i)=>{let n=this.schemaUtils.isPropertyRequired(i,a,e),o=u__default.default.get(this.schemaUtils.getSchemaRefType(a),"rawTypeData",{}),c=!!(o.nullable||a.nullable),m=this.typeNameFormatter.isValidName(i)?i:this.config.Ts.StringValue(i),p=this.schemaParserFabric.createSchemaParser({schema:a,schemaPath:[...this.schemaPath,i]}).getInlineParseContent(),f=a.readOnly;return {...a,$$raw:a,title:a.title,description:a.description||u__default.default.compact(u__default.default.map(a[this.schemaUtils.getComplexType(a)],"description"))[0]||o.description||u__default.default.compact(u__default.default.map(o[this.schemaUtils.getComplexType(o)],"description"))[0]||"",isRequired:n,isNullable:c,name:m,value:p,field:this.config.Ts.TypeField({readonly:f&&this.config.addReadonly,optional:!n,key:m,value:p})}});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 ge=class extends d{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===l.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: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 de=class extends d{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 ye=class extends d{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 Te=class extends d{parse(){return this.config.Ts.Keyword.Any}};var Pe=class extends d{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 H(h){return u__default.default.camelCase(u__default.default.lowerCase(h))}function A(h){return u__default.default.upperFirst(u__default.default.camelCase(h))}var Se=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__default.default.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__default.default.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 H(t.type);if(t.enum){let s=typeof t.enum[0];return s===this.config.Ts.Keyword.Undefined?void 0:H(s)}return u__default.default.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=u__default.default.uniq([...this.getRequiredProperties(e),...this.getRequiredProperties(t)]),r=this.getSchemaRefType(t);if(r){let i=u__default.default.keys(r.rawTypeData?.properties||{}).filter(n=>s.includes(n));return i.length?{...t,$$requiredKeys:i}:t}if(t.properties){let i=u__default.default.keys(t.properties).filter(n=>s.includes(n));return i.length?{required:u__default.default.uniq([...this.getRequiredProperties(t),...i]),...t}:t}return t};filterSchemaContents=(e,t)=>u__default.default.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(A(e),i)):this.config.componentTypeNameResolver.resolve([...(r||[]).map(i=>A(`${i} ${e}`)),...(t||[]).map(i=>A(`${e} ${i}`))],a);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=>!u__default.default.isEmpty(e.enum)||!u__default.default.isEmpty(this.getEnumNames(e))?l.ENUM:e.discriminator?l.DISCRIMINATOR:e.allOf||e.oneOf||e.anyOf||e.not?l.COMPLEX:u__default.default.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 a=u__default.default.get(this.config.primitiveTypes,[r,e.format])||u__default.default.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__default.default.uniq(u__default.default.compact(e)),!e||!e[0]?null:A(u__default.default.camelCase(u__default.default.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 Ne=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||Pe;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ALL_OF]:e=>{let t=this.config.schemaParsers.complexAllOf||de;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ANY_OF]:e=>{let t=this.config.schemaParsers.complexAnyOf||ye;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_NOT]:e=>{let t=this.config.schemaParsers.complexNot||Te;return new t(this,e,null,this.schemaPath).parse()}};_baseSchemaParsers={[l.ENUM]:(e,t)=>{let s=this.config.schemaParsers.enum||ue;return new s(this,e,t,this.schemaPath).parse()},[l.OBJECT]:(e,t)=>{let s=this.config.schemaParsers.object||fe;return new s(this,e,t,this.schemaPath).parse()},[l.COMPLEX]:(e,t)=>{let s=this.config.schemaParsers.complex||he;return new s(this,e,t,this.schemaPath).parse()},[l.PRIMITIVE]:(e,t)=>{let s=this.config.schemaParsers.primitive||ge;return new s(this,e,t,this.schemaPath).parse()},[l.DISCRIMINATOR]:(e,t)=>{let s=this.config.schemaParsers.discriminator||pe;return new s(this,e,t,this.schemaPath).parse()},[l.ARRAY]:(e,t)=>{let s=this.config.schemaParsers.array||me;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),u__default.default.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(ce("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__default.default.first(u__default.default.values(t)),a=u__default.default.get(r,"schema");if(a)return {...s,...u__default.default.omit(r,"schema"),...a}}};var Ce=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 Se(this),this.schemaFormatters=new ne(this);}createSchemaParser=({schema:e,typeName:t,schemaPath:s})=>new Ne(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 _t="abcdefghijklmnopqrstuvwxyz0123456789",mt=ct__namespace.customAlphabet(_t,12);var Re=class extends b{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 x={JSON:"JSON",URL_ENCODED:"URL_ENCODED",FORM_DATA:"FORM_DATA",IMAGE:"IMAGE",OTHER:"OTHER",TEXT:"TEXT"},Ee=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__default.default.uniq([this.schemaUtils.getSchemaType({type:"string",format:"file"}),this.schemaUtils.getSchemaType({type:"string",format:"binary"})]);}createRequestsMap=e=>{let t=u__default.default.get(e,"parameters");return u__default.default.reduce(e,(s,r,a)=>(a.startsWith("x-")||["parameters","$ref"].includes(a)||(s[a]={...r,parameters:u__default.default.compact(u__default.default.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__default.default.reduce(s,(c,m)=>{let p=m.replace(/\{|\}|:/g,"");return p&&(p.includes("-")&&this.logger.warn("wrong path param name",p),c.push({$match:m,name:u__default.default.camelCase(p),required:!0,type:"string",description:"",schema:{type:"string"},in:"path"})),c},[]),a=r.reduce((c,m,p,f)=>{let y=this.config.hooks.onInsertPathParam(m.name,p,f,c)||m.name;return c.replace(m.$match,`\${${y}}`)},t||""),i=a.match(/(\{\?.*\})/g),n=[];if(i?.length){for(let m of i)a=a.replace(m,"");let c=u__default.default.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__default.default.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__default.default.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__default.default.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__default.default.uniq(u__default.default.compact([...t||[],...u__default.default.flatten(u__default.default.map(e,s=>s&&u__default.default.keys(s.content)))]));getContentKind=e=>e.some(t=>t.startsWith("application/json"))||e.some(t=>t.endsWith("+json"))?x.JSON:e.includes("application/x-www-form-urlencoded")?x.URL_ENCODED:e.includes("multipart/form-data")?x.FORM_DATA:e.some(t=>t.includes("image/"))?x.IMAGE:e.some(t=>t.startsWith("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=u__default.default.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__default.default.isEqual(f.content,o)),p=c||m;return p?this.typeNameFormatter.format(p.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__default.default.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(p=>p.isSuccess),c=n.filter(p=>!p.isSuccess&&p.type!==this.config.Ts.Keyword.Any),m=p=>{if(!p)return "headers: {},";let f=Object.fromEntries(Object.entries(p).map(([T,C])=>[T,this.schemaUtils.getSchemaType(C)]));return `headers: { ${Object.entries(f).map(([T,C])=>`"${T}": ${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(p=>p.type))||this.config.Ts.Keyword.Any},full:{types:this.config.Ts.UnionType(n.map(p=>`{
|
|
70
|
+
`);n?t.push(`${n}${a}`):t.push(`${a}`);}return t.join("")}};var ce=h=>(e,t)=>e[h]>t[h]?1:e[h]<t[h]?-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 me=class extends d{parse(){let e,{type:t,description:s,items:r}=this.schema||{};if(Array.isArray(r)&&t===l.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: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 he=class extends d{parse(){let e=this.schemaUtils.getComplexType(this.schema),t=u__default.default.omit(u__default.default.clone(this.schema),u__default.default.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:l.COMPLEX,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description||u__default.default.compact(u__default.default.map(this.schema[e],"description"))[0]||""),content:this.config.Ts.IntersectionType(u__default.default.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 pe=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,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: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:a}=this.schema,i=u__default.default.entries(a.mapping),n=!e&&!!(t?.typeName&&i.length),o=[],c,m=this.createMappingPropertySchemaEnumKeys({abstractSchemaStruct:t,discPropertyName:a.propertyName});if(n){let y=`${t.typeName}_${a.propertyName}`,T=this.schemaUtils.resolveTypeName(y,{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"]),F=this.schemaParserFabric.createParsedComponent({typeName:T,schema:{type:"object",properties:{},genericArgs:[{name:"Key"},{name:"Type"}],internal:!0}});F.typeData.content=C,c=this.typeNameFormatter.format(F.typeName);}let p=(y,T)=>{let C=this.schemaParserFabric.createSchemaParser({schema:y,schemaPath:this.schemaPath}).getInlineParseContent(),F=m[T]||s.StringValue(T);return n?s.TypeWithGeneric(c,[F,C]):s.ExpressionGroup(s.IntersectionType([s.ObjectWrapper(s.TypeField({key:a.propertyName,value:F})),C]))};for(let[y,T]of i){let C=typeof T=="string"?{$ref:T}:T;this.mutateMappingDependentSchema({discPropertyName:a.propertyName,abstractSchemaStruct:t,mappingSchema:C,refPath:r,mappingPropertySchemaEnumKeysMap:m}),o.push(p(C,y));}return e?null:{content:s.ExpressionGroup(s.UnionType(o))}};createMappingPropertySchemaEnumKeys=({abstractSchemaStruct:e,discPropertyName:t})=>{let s=this.config.Ts,r={},a=u__default.default.get(e?.component?.rawTypeData,["properties",t]);return this.schemaUtils.isRefSchema(a)&&(a=this.schemaUtils.getSchemaRefType(a)),a?.rawTypeData?.$parsed?.type===l.ENUM&&(r=u__default.default.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__default.default.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)===l.OBJECT)for(let m in c.properties){let p=c.properties[m];m===e&&this.schemaUtils.getInternalSchemaType(p)===l.ENUM&&p.enum.length===1&&a[p.enum[0]]&&(c.properties[m]=this.schemaParserFabric.createSchema({content:a[p.enum[0]]}));}return c}));}};createAbstractSchemaStruct=()=>{let{discriminator:e,...t}=this.schema,s=u__default.default.keys(this.schemaParser._complexSchemaParsers),r=u__default.default.omit(structuredClone(t),s),a=this.schemaParserFabric.getInlineParseContent(structuredClone(r))===this.config.Ts.Keyword.Any;if(!u__default.default.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===l.COMPLEX_UNKNOWN?null:{content:e.ExpressionGroup(this.schemaParser._complexSchemaParsers[t](this.schema))}}};var le=class extends b{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 ue=class extends d{enumKeyResolver;constructor(...e){super(...e),this.enumKeyResolver=new le(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__default.default.size(a)?i=a.map((o,c)=>{let m=u__default.default.get(this.schema.enum,c),p=this.formatEnumKey({key:o,value:m});return this.config.enumNamesAsValues||m===void 0?{key:p,type:this.config.Ts.Keyword.String,value:this.config.Ts.StringValue(o)}:{key:p,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: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: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 fe=class extends d{parse(){let e=this.getObjectSchemaContent(this.schema);return {...typeof this.schema=="object"?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:!e.some(t=>t.isRequired),content:e}}getObjectSchemaContent=e=>{let{properties:t,additionalProperties:s}=e||{},r=u__default.default.map(t,(a,i)=>{let n=this.schemaUtils.isPropertyRequired(i,a,e),o=u__default.default.get(this.schemaUtils.getSchemaRefType(a),"rawTypeData",{}),c=!!(o.nullable||a.nullable),m=this.typeNameFormatter.isValidName(i)?i:this.config.Ts.StringValue(i),p=this.schemaParserFabric.createSchemaParser({schema:a,schemaPath:[...this.schemaPath,i]}).getInlineParseContent(),f=a.readOnly;return {...a,$$raw:a,title:a.title,description:a.description||u__default.default.compact(u__default.default.map(a[this.schemaUtils.getComplexType(a)],"description"))[0]||o.description||u__default.default.compact(u__default.default.map(o[this.schemaUtils.getComplexType(o)],"description"))[0]||"",isRequired:n,isNullable:c,name:m,value:p,field:this.config.Ts.TypeField({readonly:f&&this.config.addReadonly,optional:!n,key:m,value:p})}});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 ge=class extends d{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===l.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: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 de=class extends d{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 ye=class extends d{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 Te=class extends d{parse(){return this.config.Ts.Keyword.Any}};var Pe=class extends d{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 H(h){return u__default.default.camelCase(u__default.default.lowerCase(h))}function A(h){return u__default.default.upperFirst(u__default.default.camelCase(h))}var Se=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__default.default.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__default.default.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 H(t.type);if(t.enum){let s=typeof t.enum[0];return s===this.config.Ts.Keyword.Undefined?void 0:H(s)}return u__default.default.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=u__default.default.uniq([...this.getRequiredProperties(e),...this.getRequiredProperties(t)]),r=this.getSchemaRefType(t);if(r){let i=u__default.default.keys(r.rawTypeData?.properties||{}).filter(n=>s.includes(n));return i.length?{...t,$$requiredKeys:i}:t}if(t.properties){let i=u__default.default.keys(t.properties).filter(n=>s.includes(n));return i.length?{required:u__default.default.uniq([...this.getRequiredProperties(t),...i]),...t}:t}return t};filterSchemaContents=(e,t)=>u__default.default.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(A(e),i)):this.config.componentTypeNameResolver.resolve([...(r||[]).map(i=>A(`${i} ${e}`)),...(t||[]).map(i=>A(`${e} ${i}`))],a);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=>!u__default.default.isEmpty(e.enum)||!u__default.default.isEmpty(this.getEnumNames(e))?l.ENUM:e.discriminator?l.DISCRIMINATOR:e.allOf||e.oneOf||e.anyOf||e.not?l.COMPLEX:u__default.default.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 a=u__default.default.get(this.config.primitiveTypes,[r,e.format])||u__default.default.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__default.default.uniq(u__default.default.compact(e)),!e||!e[0]?null:A(u__default.default.camelCase(u__default.default.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 Ne=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||Pe;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ALL_OF]:e=>{let t=this.config.schemaParsers.complexAllOf||de;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ANY_OF]:e=>{let t=this.config.schemaParsers.complexAnyOf||ye;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_NOT]:e=>{let t=this.config.schemaParsers.complexNot||Te;return new t(this,e,null,this.schemaPath).parse()}};_baseSchemaParsers={[l.ENUM]:(e,t)=>{let s=this.config.schemaParsers.enum||ue;return new s(this,e,t,this.schemaPath).parse()},[l.OBJECT]:(e,t)=>{let s=this.config.schemaParsers.object||fe;return new s(this,e,t,this.schemaPath).parse()},[l.COMPLEX]:(e,t)=>{let s=this.config.schemaParsers.complex||he;return new s(this,e,t,this.schemaPath).parse()},[l.PRIMITIVE]:(e,t)=>{let s=this.config.schemaParsers.primitive||ge;return new s(this,e,t,this.schemaPath).parse()},[l.DISCRIMINATOR]:(e,t)=>{let s=this.config.schemaParsers.discriminator||pe;return new s(this,e,t,this.schemaPath).parse()},[l.ARRAY]:(e,t)=>{let s=this.config.schemaParsers.array||me;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),u__default.default.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(ce("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__default.default.first(u__default.default.values(t)),a=u__default.default.get(r,"schema");if(a)return {...s,...u__default.default.omit(r,"schema"),...a}}};var Ce=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 Se(this),this.schemaFormatters=new ne(this);}createSchemaParser=({schema:e,typeName:t,schemaPath:s})=>new Ne(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 _t="abcdefghijklmnopqrstuvwxyz0123456789",mt=ct__namespace.customAlphabet(_t,12);var Re=class extends b{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 x={JSON:"JSON",URL_ENCODED:"URL_ENCODED",FORM_DATA:"FORM_DATA",IMAGE:"IMAGE",OTHER:"OTHER",TEXT:"TEXT"},Ee=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__default.default.uniq([this.schemaUtils.getSchemaType({type:"string",format:"file"}),this.schemaUtils.getSchemaType({type:"string",format:"binary"})]);}createRequestsMap=e=>{let t=u__default.default.get(e,"parameters");return u__default.default.reduce(e,(s,r,a)=>(a.startsWith("x-")||["parameters","$ref"].includes(a)||(s[a]={...r,parameters:u__default.default.compact(u__default.default.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__default.default.reduce(s,(c,m)=>{let p=m.replace(/\{|\}|:/g,"");return p&&(p.includes("-")&&this.logger.warn("wrong path param name",p),c.push({$match:m,name:u__default.default.camelCase(p),required:!0,type:"string",description:"",schema:{type:"string"},in:"path"})),c},[]),a=r.reduce((c,m,p,f)=>{let y=this.config.hooks.onInsertPathParam(m.name,p,f,c)||m.name;return c.replace(m.$match,`\${${y}}`)},t||""),i=a.match(/(\{\?.*\})/g),n=[];if(i?.length){for(let m of i)a=a.replace(m,"");let c=u__default.default.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__default.default.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__default.default.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__default.default.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__default.default.uniq(u__default.default.compact([...t||[],...u__default.default.flatten(u__default.default.map(e,s=>s&&u__default.default.keys(s.content)))]));getContentKind=e=>e.some(t=>t.startsWith("application/json"))||e.some(t=>t.endsWith("+json"))?x.JSON:e.includes("application/x-www-form-urlencoded")?x.URL_ENCODED:e.includes("multipart/form-data")?x.FORM_DATA:e.some(t=>t.includes("image/"))?x.IMAGE:e.some(t=>t.startsWith("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=u__default.default.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__default.default.isEqual(f.content,o)),p=c||m;return p?this.typeNameFormatter.format(p.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__default.default.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(p=>p.isSuccess),c=n.filter(p=>!p.isSuccess&&p.type!==this.config.Ts.Keyword.Any),m=p=>{if(!p)return "headers: {},";let f=Object.fromEntries(Object.entries(p).map(([T,C])=>[T,this.schemaUtils.getSchemaType(C)]));return `headers: { ${Object.entries(f).map(([T,C])=>`"${T}": ${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(p=>p.type))||this.config.Ts.Keyword.Any},full:{types:this.config.Ts.UnionType(n.map(p=>`{
|
|
71
71
|
data: ${p.type}, status: ${p.status}, statusCode: ${p.status}, statusText: "${p.description}", ${m(p.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__default.default.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,p=this.getContentTypes([a],[...i||[],e["x-contentType"]]),f=this.getContentKind(p),y=null;return this.config.extractRequestBody&&(y=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),m=this.schemaParserFabric.getInlineParseContent(c,y,[o])):f===x.FORM_DATA?(c=this.getSchemaFromRequestType(a),m=this.schemaParserFabric.getInlineParseContent(c,y,[o])):a&&(c=this.getSchemaFromRequestType(a),m=this.schemaParserFabric.schemaUtils.safeAddNullToType(a,this.getTypeFromRequestInfo({requestInfo:a,parsedSchemas:s,operationId:o,typeName:y})),this.FORM_DATA_TYPES.some(T=>m.includes(`: ${T}`))&&(f=x.FORM_DATA)),c&&!c.$ref&&this.config.extractRequestBody&&(c=this.schemaParserFabric.createParsedComponent({schema:c,typeName:y,schemaPath:[o]}),m=this.schemaParserFabric.getInlineParseContent({$ref:c.$ref})),{paramName:n||a?.name||je,contentTypes:p,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,p)=>(p.name&&(m[p.name]={...p,in:"path"}),m),{}),n=u__default.default.reduce(u__default.default.get(t,"properties",{}),(m,p,f)=>(f&&typeof p=="object"&&(m[f]={...p,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__default.default.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(`
|
|
72
72
|
`)},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}()"`,`
|
|
73
|
-
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:p,security:f,parameters:y,summary:T,description:C,tags:F,responses:Tt,requestBodyName:Vt,produces:Pt,consumes:St,...Nt}=t,{route:Ve,pathParams:Ct,queryParams:Rt}=this.parseRouteName(e),Et=mt(),Ge=F&&F.length>0?F[0]:null,Je=o&&Ge?u__default.default.camelCase(Ge):u__default.default.camelCase(u__default.default.compact(Ve.split("/"))[n]),He=!!i?.length;f&&(He=f.length>0);let E=this.getRouteParams(t,Ct,Rt),X=E.path.map(D=>({name:D.name,optional:!D.required,type:this.config.Ts.Keyword.Any,description:D.description})),wt=X.map(D=>D.name),$=this.getResponseBodyInfo(t,a),Ye={...Nt,pathArgs:X,operationId:m,method:s,route:e,moduleName:Je,responsesTypes:$.responses,description:C,tags:F,summary:T,responses:Tt,produces:Pt,requestBody:p,consumes:St,security:f},z=this.convertRouteParamsIntoObject(E.query),_e=this.convertRouteParamsIntoObject(E.path),Ke=this.convertRouteParamsIntoObject(E.header),O=this.getRouteName(Ye),M=this.getRequestBodyInfo(t,E,a,O),xt=this.createRequestParamsSchema({queryParams:E.query,pathArgsSchemas:E.path,queryObjectSchema:z,extractRequestParams:c,routeName:O});this.config.extractResponseBody&&this.extractResponseBodyIfItNeeded(t,$,O),this.config.extractResponseError&&this.extractResponseErrorIfItNeeded(t,$,O);let Q=this.schemaUtils.resolveTypeName(O.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver,shouldReserve:!1}),Xe=E.query.length?this.schemaParserFabric.getInlineParseContent(z,null,[Q]):null,ze=E.path.length?this.schemaParserFabric.getInlineParseContent(_e,null,[Q]):null,Qe=E.header.length?this.schemaParserFabric.getInlineParseContent(Ke,null,[Q]):null,L=new Re(this.config,this.logger,wt),B={query:Xe?{name:L.resolve(Le),optional:this.schemaParserFabric.parseSchema(z,null,[O.usage]).allFieldsAreOptional,type:Xe}:void 0,body:M.type?{name:L.resolve([M.paramName,...Ue]),optional:!M.required,type:M.type}:void 0,pathParams:ze?{name:L.resolve(We),optional:this.schemaParserFabric.parseSchema(_e,null,[O.usage]).allFieldsAreOptional,type:ze}:void 0,headers:Qe?{name:L.resolve(ke),optional:this.schemaParserFabric.parseSchema(Ke,null,[O.usage]).allFieldsAreOptional,type:Qe}:void 0};return X.forEach((D,Ft)=>{D.type=this.schemaParserFabric.getInlineParseContent(E.path[Ft].schema,null,[Q]);}),{id:Et,namespace:Je.replace(/^(\d)/,"v$1"),routeName:O,routeParams:E,requestBodyInfo:M,responseBodyInfo:$,specificArgs:B,queryObjectSchema:z,pathObjectSchema:_e,headersObjectSchema:Ke,responseBodySchema:$.success.schema,requestBodySchema:M.schema,specificArgNameResolver:L,request:{contentTypes:M.contentTypes,parameters:X,path:Ve,formData:M.contentKind===x.FORM_DATA,isQueryBody:M.contentKind===x.URL_ENCODED,security:He,method:s,requestParams:xt,payload:B.body,query:B.query,pathParams:B.pathParams,headers:B.headers},response:{contentTypes:$.contentTypes,type:$.success.type,errorType:$.error.type,fullTypes:$.full.types},raw:Ye}};attachSchema=({usageSchema:e,parsedSchemas:t})=>{this.config.routeNameDuplicatesMap.clear();let s=u__default.default.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 p=m||c;!this.hasSecurityRoutes&&p.security&&(this.hasSecurityRoutes=p.security),!this.hasQueryRoutes&&p.hasQuery&&(this.hasQueryRoutes=p.hasQuery),!this.hasFormDataRoutes&&p.hasFormDataParams&&(this.hasFormDataRoutes=p.hasFormDataParams),this.routes.push(p);}}}};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__default.default.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__default.default.each(t.combined,s=>{s.routes=this.sortRoutes(s.routes);})),t};sortRoutes=e=>u__default.default.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,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__default.default.get(e,s);return r&&this.caches.set(t,r),r}};var xe=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__default.default.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 Fe=class{config;logger;fileSystem;request;constructor({config:e,logger:t,fileSystem:s}){this.config=e,this.logger=t,this.fileSystem=s,this.request=new xe(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__default.default.merge({title:"No title",version:""},r.info),r.openapi?s({usageSchema:r,originalSchema:structuredClone(r)}):(r.paths=u__default.default.merge({},r.paths),pt__namespace.convertObj(r,{...t,warnOnly:!0,refSiblings:"preserve",rbname:"requestBodyName"},(a,i)=>{let n=u__default.default.get(a,"options.openapi",u__default.default.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 ht__namespace.load(e)}}fixSwaggerSchema({usageSchema:e,originalSchema:t}){let s=u__default.default.get(e,"paths"),r=u__default.default.get(t,"paths");u__default.default.each(s,(a,i)=>{let n=u__default.default.get(r,i);u__default.default.each(a,(o,c)=>{let m=u__default.default.get(n,c),p=u__default.default.get(o,"parameters",[]),f=u__default.default.get(m,"parameters",[]);typeof o=="object"&&(o.consumes=u__default.default.uniq(u__default.default.compact([...o.consumes||[],...m.consumes||[]])),o.produces=u__default.default.uniq(u__default.default.compact([...o.produces||[],...m.produces||[]]))),u__default.default.each(f,y=>{p.find(C=>y.in===C.in&&y.name===C.name)||p.push(y);});});});}};var be=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=w__namespace.dirname(ut__namespace.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-UH6TMUDA.cjs', document.baseURI).href)))),s=w__namespace.resolve(t,"../templates/base"),r=w__namespace.resolve(t,"../templates/default"),a=w__namespace.resolve(t,"../templates/modular"),i=e.modular?a:r,n=e.templates&&w__namespace.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=w__namespace.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(w__namespace.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}"`,`
|
|
73
|
+
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:p,security:f,parameters:y,summary:T,description:C,tags:F,responses:Tt,requestBodyName:Vt,produces:Pt,consumes:St,...Nt}=t,{route:Ve,pathParams:Ct,queryParams:Rt}=this.parseRouteName(e),Et=mt(),Ge=F&&F.length>0?F[0]:null,Je=o&&Ge?u__default.default.camelCase(Ge):u__default.default.camelCase(u__default.default.compact(Ve.split("/"))[n]),He=!!i?.length;f&&(He=f.length>0);let E=this.getRouteParams(t,Ct,Rt),X=E.path.map(D=>({name:D.name,optional:!D.required,type:this.config.Ts.Keyword.Any,description:D.description})),wt=X.map(D=>D.name),$=this.getResponseBodyInfo(t,a),Ye={...Nt,pathArgs:X,operationId:m,method:s,route:e,moduleName:Je,responsesTypes:$.responses,description:C,tags:F,summary:T,responses:Tt,produces:Pt,requestBody:p,consumes:St,security:f},z=this.convertRouteParamsIntoObject(E.query),_e=this.convertRouteParamsIntoObject(E.path),Ke=this.convertRouteParamsIntoObject(E.header),O=this.getRouteName(Ye),M=this.getRequestBodyInfo(t,E,a,O),xt=this.createRequestParamsSchema({queryParams:E.query,pathArgsSchemas:E.path,queryObjectSchema:z,extractRequestParams:c,routeName:O});this.config.extractResponseBody&&this.extractResponseBodyIfItNeeded(t,$,O),this.config.extractResponseError&&this.extractResponseErrorIfItNeeded(t,$,O);let Q=this.schemaUtils.resolveTypeName(O.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver,shouldReserve:!1}),Xe=E.query.length?this.schemaParserFabric.getInlineParseContent(z,null,[Q]):null,ze=E.path.length?this.schemaParserFabric.getInlineParseContent(_e,null,[Q]):null,Qe=E.header.length?this.schemaParserFabric.getInlineParseContent(Ke,null,[Q]):null,L=new Re(this.config,this.logger,wt),B={query:Xe?{name:L.resolve(Le),optional:this.schemaParserFabric.parseSchema(z,null,[O.usage]).allFieldsAreOptional,type:Xe}:void 0,body:M.type?{name:L.resolve([M.paramName,...Ue]),optional:!M.required,type:M.type}:void 0,pathParams:ze?{name:L.resolve(We),optional:this.schemaParserFabric.parseSchema(_e,null,[O.usage]).allFieldsAreOptional,type:ze}:void 0,headers:Qe?{name:L.resolve(ke),optional:this.schemaParserFabric.parseSchema(Ke,null,[O.usage]).allFieldsAreOptional,type:Qe}:void 0};return X.forEach((D,Ft)=>{D.type=this.schemaParserFabric.getInlineParseContent(E.path[Ft].schema,null,[Q]);}),{id:Et,namespace:Je.replace(/^(\d)/,"v$1"),routeName:O,routeParams:E,requestBodyInfo:M,responseBodyInfo:$,specificArgs:B,queryObjectSchema:z,pathObjectSchema:_e,headersObjectSchema:Ke,responseBodySchema:$.success.schema,requestBodySchema:M.schema,specificArgNameResolver:L,request:{contentTypes:M.contentTypes,parameters:X,path:Ve,formData:M.contentKind===x.FORM_DATA,isQueryBody:M.contentKind===x.URL_ENCODED,security:He,method:s,requestParams:xt,payload:B.body,query:B.query,pathParams:B.pathParams,headers:B.headers},response:{contentTypes:$.contentTypes,type:$.success.type,errorType:$.error.type,fullTypes:$.full.types},raw:Ye}};attachSchema=({usageSchema:e,parsedSchemas:t})=>{this.config.routeNameDuplicatesMap.clear();let s=u__default.default.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 p=m||c;!this.hasSecurityRoutes&&p.security&&(this.hasSecurityRoutes=p.security),!this.hasQueryRoutes&&p.hasQuery&&(this.hasQueryRoutes=p.hasQuery),!this.hasFormDataRoutes&&p.hasFormDataParams&&(this.hasFormDataRoutes=p.hasFormDataParams),this.routes.push(p);}}}};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__default.default.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__default.default.each(t.combined,s=>{s.routes=this.sortRoutes(s.routes);})),t};sortRoutes=e=>u__default.default.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,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__default.default.get(e,s);return r&&this.caches.set(t,r),r}};var xe=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__default.default.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 Fe=class{config;logger;fileSystem;request;constructor({config:e,logger:t,fileSystem:s}){this.config=e,this.logger=t,this.fileSystem=s,this.request=new xe(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__default.default.merge({title:"No title",version:""},r.info),r.openapi?s({usageSchema:r,originalSchema:structuredClone(r)}):(r.paths=u__default.default.merge({},r.paths),pt__namespace.convertObj(r,{...t,warnOnly:!0,refSiblings:"preserve",rbname:"requestBodyName"},(a,i)=>{let n=u__default.default.get(a,"options.openapi",u__default.default.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 ht__namespace.load(e)}}fixSwaggerSchema({usageSchema:e,originalSchema:t}){let s=u__default.default.get(e,"paths"),r=u__default.default.get(t,"paths");u__default.default.each(s,(a,i)=>{let n=u__default.default.get(r,i);u__default.default.each(a,(o,c)=>{let m=u__default.default.get(n,c),p=u__default.default.get(o,"parameters",[]),f=u__default.default.get(m,"parameters",[]);typeof o=="object"&&(o.consumes=u__default.default.uniq(u__default.default.compact([...o.consumes||[],...m.consumes||[]])),o.produces=u__default.default.uniq(u__default.default.compact([...o.produces||[],...m.produces||[]]))),u__default.default.each(f,y=>{p.find(C=>y.in===C.in&&y.name===C.name)||p.push(y);});});});}};var be=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=w__namespace.dirname(ut__namespace.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-725EVWJG.cjs', document.baseURI).href)))),s=w__namespace.resolve(t,"../templates/base"),r=w__namespace.resolve(t,"../templates/default"),a=w__namespace.resolve(t,"../templates/modular"),i=e.modular?a:r,n=e.templates&&w__namespace.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=w__namespace.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(w__namespace.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}"`,`
|
|
74
74
|
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__default.default.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__default.default.keys(this.config.templatePaths).find(n=>e.startsWith(`@${n}`)),s=w__namespace.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(w__namespace.resolve(this.config.templatePaths.custom,e));if(a)return this.fileSystem.getFileContent(a);let i=this.findTemplateWithExt(w__namespace.resolve(this.config.templatePaths.original,e));return i?this.fileSystem.getFileContent(i):""};renderTemplate=(e,t,s)=>e?ft__namespace.render(e,{...this.getRenderTemplateData(),...t},{async:!1,...s||{},includeFile:(r,a,i)=>this.renderTemplate(this.getTemplateContent(r),a,i)}):""};var Ae=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 Ae{compileTSCode=e=>{let t=`${e.fileName}${e.fileExtension}`,s={},r=g__namespace.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):g__namespace.createSourceFile(n,e.fileContent,o,!0,g__namespace.ScriptKind.TS),r.writeFile=(n,o)=>{s[n]=o;},g__namespace.createProgram(a,this.config.compilerTsConfig,r).emit(),s};translate=async e=>{let t=this.compileTSCode(e),s=`${e.fileName}${g__namespace.Extension.Js}`,r=`${e.fileName}${g__namespace.Extension.Dts}`,a=t[s],i=e.fileContent.split(`
|
|
75
75
|
`).filter(o=>o.startsWith("import ")),n=t[r].split(`
|
|
76
76
|
`).map(o=>o.startsWith("import ")?i.shift():o).join(`
|
|
@@ -92,9 +92,9 @@ ${r} ${a.replace(/\n/,"")}`:a));};log=(...e)=>this.createLogMessage({type:"log
|
|
|
92
92
|
* ---------------------------------------------------------------
|
|
93
93
|
*/
|
|
94
94
|
|
|
95
|
-
`,W=class{logger;constructor({logger:e=new v("file-system")}={}){this.logger=e;}getFileContent=e=>N__namespace.readFileSync(e,{encoding:"utf8"});readDir=e=>N__namespace.readdirSync(e);pathIsDir=e=>{if(!e)return !1;try{return N__namespace.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__namespace.rmSync=="function"?N__namespace.rmSync(e,{recursive:!0}):N__namespace.rmdirSync(e,{recursive:!0});}catch(t){this.logger.debug("failed to remove dir",t);}};createDir=e=>{try{N__namespace.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__namespace.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let a=w__namespace.dirname(ut__namespace.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-
|
|
95
|
+
`,W=class{logger;constructor({logger:e=new v("file-system")}={}){this.logger=e;}getFileContent=e=>N__namespace.readFileSync(e,{encoding:"utf8"});readDir=e=>N__namespace.readdirSync(e);pathIsDir=e=>{if(!e)return !1;try{return N__namespace.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__namespace.rmSync=="function"?N__namespace.rmSync(e,{recursive:!0}):N__namespace.rmdirSync(e,{recursive:!0});}catch(t){this.logger.debug("failed to remove dir",t);}};createDir=e=>{try{N__namespace.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__namespace.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let a=w__namespace.dirname(ut__namespace.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-725EVWJG.cjs', document.baseURI).href)))),i=w__namespace.resolve(a,e,`./${t}`),n=`${r?Ut:""}${s}`;return N__namespace.writeFileSync(i,n,u__default.default.noop)}};var kt=["schemaWalker","swaggerSchemaResolver","schemaComponentsMap","typeNameFormatter","templatesWorker","codeFormatter","schemaParserFabric","schemaRoutes","javascriptTranslator"],Ie=class{config;swaggerSchemaResolver;schemaComponentsMap;logger;typeNameFormatter;schemaParserFabric;schemaRoutes;fileSystem;codeFormatter;templatesWorker;schemaWalker;javascriptTranslator;constructor(e){this.config=new ae(e),this.logger=new v(this),this.fileSystem=new W(this),this.schemaWalker=new we(this),this.swaggerSchemaResolver=new Fe(this),this.schemaComponentsMap=new oe(this),this.typeNameFormatter=new Oe(this),this.templatesWorker=new be(this),this.codeFormatter=new Z(this),this.schemaParserFabric=new Ce(this),this.schemaRoutes=new Ee(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__default.default.each(e.usageSchema.components,(o,c)=>u__default.default.each(o,(m,p)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,p]),m);}));let s=this.schemaComponentsMap.filter(u__default.default.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:H,classNameCase:A,pascalCase:A,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?`
|
|
96
96
|
`:""}`},NameResolver:b,_:u__default.default,require:this.templatesWorker.requireFnFromTemplate},config:this.config});collectModelTypes=()=>{let e=this.schemaComponentsMap.getComponents(),t=[],s=u__default.default.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(ce("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__default.default.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,A(`${o.moduleName}_Route`),c));}if(i){let c=this.templatesWorker.renderTemplate(e.api,{...t,route:o});n.push(...await this.createOutputFileInfo(t,A(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__default.default.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(`
|
|
97
|
-
`))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),a=g__namespace.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:p}=o;return {info:t||{},servers:s||[],basePath:a,host:r,externalDocs:u__default.default.merge({url:"",description:""},i),tags:u__default.default.compact(n),baseUrl:p,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 ve=class{cleanOutput=!1;output=void 0;httpClientType=V.FETCH;modular=!1;silent=!1;version=G;rewrite=!1;constructor(e){this.update(e);}update=e=>{j(this,e);}};var Lt=w__namespace.default.dirname(ut__namespace.default.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-
|
|
97
|
+
`))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),a=g__namespace.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:p}=o;return {info:t||{},servers:s||[],basePath:a,host:r,externalDocs:u__default.default.merge({url:"",description:""},i),tags:u__default.default.compact(n),baseUrl:p,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 ve=class{cleanOutput=!1;output=void 0;httpClientType=V.FETCH;modular=!1;silent=!1;version=G;rewrite=!1;constructor(e){this.update(e);}update=e=>{j(this,e);}};var Lt=w__namespace.default.dirname(ut__namespace.default.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-725EVWJG.cjs', document.baseURI).href)))),De=class{config;fileSystem;logger;rootDir=w__namespace.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 ve(e),this.logger=new v(this),this.fileSystem=new W(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=w__namespace.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=w__namespace.default.resolve(t,`${r}.ejs`),i=w__namespace.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(w__namespace.default.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(w__namespace.default.resolve(this.rootDir,e))};async function Bt(h){return await new De(h).start()}async function Ka({name:h,prettier:e,...t}){return await new Ie({...t,fileName:h,prettierOptions:e}).start()}
|
|
98
98
|
|
|
99
99
|
exports.a = tt;
|
|
100
100
|
exports.b = V;
|
|
@@ -103,5 +103,5 @@ exports.d = ae;
|
|
|
103
103
|
exports.e = ve;
|
|
104
104
|
exports.f = Bt;
|
|
105
105
|
exports.g = Ka;
|
|
106
|
-
//# sourceMappingURL=chunk-
|
|
107
|
-
//# sourceMappingURL=chunk-
|
|
106
|
+
//# sourceMappingURL=chunk-725EVWJG.cjs.map
|
|
107
|
+
//# sourceMappingURL=chunk-725EVWJG.cjs.map
|