@blimu/codegen 0.5.1 → 0.5.3

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/main.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var ft=Object.create;var de=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty;var f=(o,e)=>de(o,"name",{value:e,configurable:!0});var gt=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ut(e))!mt.call(o,n)&&n!==t&&de(o,n,{get:()=>e[n],enumerable:!(r=lt(e,n))||r.enumerable});return o};var k=(o,e,t)=>(t=o!=null?ft(dt(o)):{},gt(e||!o||!o.__esModule?de(t,"default",{value:o,enumerable:!0}):t,o));var pt=require("nest-commander");var ct=require("@nestjs/common");var pe=require("@nestjs/common"),x=require("nest-commander");var ie=require("@nestjs/common"),Re=k(require("fs")),O=k(require("path"));var xe=require("url"),oe=k(require("path"));var g=require("zod"),ht=g.z.object({type:g.z.string().min(1,"Type name is required"),package:g.z.string().min(1,"Package name is required"),importPath:g.z.string().optional()}),Pe=["client.ts.hbs","index.ts.hbs","package.json.hbs","README.md.hbs","schema.ts.hbs","schema.zod.ts.hbs","service.ts.hbs","tsconfig.json.hbs","utils.ts.hbs"],yt=g.z.object({type:g.z.string().min(1,"Type is required"),outDir:g.z.string().min(1,"OutDir is required"),name:g.z.string().min(1,"Name is required"),includeTags:g.z.array(g.z.string()).optional(),excludeTags:g.z.array(g.z.string()).optional(),operationIdParser:g.z.custom().optional(),preCommand:g.z.array(g.z.string()).optional(),postCommand:g.z.array(g.z.string()).optional(),defaultBaseURL:g.z.string().optional(),exclude:g.z.array(g.z.string()).optional()}),bt=yt.extend({type:g.z.literal("typescript"),packageName:g.z.string().min(1,"PackageName is required"),moduleName:g.z.string().optional(),srcDir:g.z.string().optional(),includeQueryKeys:g.z.boolean().optional(),predefinedTypes:g.z.array(ht).optional(),dependencies:g.z.record(g.z.string(),g.z.string()).optional(),devDependencies:g.z.record(g.z.string(),g.z.string()).optional(),formatCode:g.z.boolean().optional(),templates:g.z.record(g.z.string(),g.z.string()).refine(o=>Object.keys(o).every(e=>Pe.includes(e)),{message:`Template names must be one of: ${Pe.join(", ")}`}).optional()}),St=g.z.discriminatedUnion("type",[bt]),ke=g.z.object({spec:g.z.string().min(1,"Spec is required"),name:g.z.string().optional(),clients:g.z.array(St).min(1,"At least one client is required")});async function je(o){try{let e=oe.isAbsolute(o)?o:oe.resolve(o),r=await import((0,xe.pathToFileURL)(e).href),n=r.default||r;if(!n)throw new Error(`Config file must export a default export or named export: ${o}`);return ke.parse(n)}catch(e){throw e instanceof Error?new Error(`Failed to load MJS config from ${o}: ${e.message}`):e}}f(je,"loadMjsConfig");function wt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(wt,"_ts_decorate");var j=class o{static{f(this,"ConfigService")}logger=new ie.Logger(o.name);DEFAULT_CONFIG_FILE="chunkflow-codegen.config.mjs";async findDefaultConfig(){let e=process.cwd(),t=O.parse(e).root;for(;e!==t;){let r=O.join(e,this.DEFAULT_CONFIG_FILE);try{return await Re.promises.access(r),r}catch{}e=O.dirname(e)}return null}async load(e){try{let t=await je(e);return this.normalizePaths(t,e)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}normalizePaths(e,t){let r=O.dirname(O.resolve(t)),n=e.spec;this.isUrl(n)||O.isAbsolute(n)||(n=O.resolve(r,n));let s=e.clients.map(i=>{let a=i.outDir;return O.isAbsolute(a)||(a=O.resolve(r,a)),{...i,outDir:a}});return{...e,spec:n,clients:s}}isUrl(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}getPreCommand(e){return e.preCommand||[]}getPostCommand(e){return e.postCommand||[]}shouldExcludeFile(e,t){if(!e.exclude||e.exclude.length===0)return!1;let r;try{r=O.relative(e.outDir,t)}catch{return!1}r=O.posix.normalize(r),r==="."&&(r="");for(let n of e.exclude){let s=O.posix.normalize(n);if(r===s||s!==""&&r.startsWith(s+"/"))return!0}return!1}};j=wt([(0,ie.Injectable)()],j);var ce=require("@nestjs/common");var Ae=require("@nestjs/common");var De=require("@nestjs/common");var l=(function(o){return o.Unknown="unknown",o.String="string",o.Number="number",o.Integer="integer",o.Boolean="boolean",o.Null="null",o.Array="array",o.Object="object",o.Enum="enum",o.Ref="ref",o.OneOf="oneOf",o.AnyOf="anyOf",o.AllOf="allOf",o.Not="not",o})({});function Ce(o){let e=o.openapi;return typeof e!="string"?"unknown":e.startsWith("3.1")?"3.1":e.startsWith("3.0")?"3.0":"unknown"}f(Ce,"detectOpenAPIVersion");function He(o){return o==="3.0"||o==="3.1"}f(He,"isSupportedVersion");function me(o,e){if(!(!e||typeof e!="object")){if("$ref"in e&&e.$ref){let t=e.$ref;if(t.startsWith("#/components/schemas/")){let r=t.replace("#/components/schemas/","");if(o.components?.schemas?.[r]){let n=o.components.schemas[r];return"$ref"in n?me(o,n):n}}return}return e}}f(me,"getSchemaFromRef");function $e(o){return o?"nullable"in o&&o.nullable===!0?!0:"type"in o&&Array.isArray(o.type)?o.type.includes("null"):!1:!1}f($e,"isSchemaNullable");function ge(o){if(!(!o||!("type"in o)))return o.type}f(ge,"getSchemaType");function Tt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(Tt,"_ts_decorate");var D=class{static{f(this,"SchemaConverterService")}schemaRefToIR(e,t){if(!t)return{kind:l.Unknown,nullable:!1};if("$ref"in t&&t.$ref){let c=t.$ref;if(c.startsWith("#/components/schemas/")){let u=c.replace("#/components/schemas/","");return{kind:l.Ref,ref:u,nullable:!1}}let p=c.split("/");if(p.length>0){let u=p[p.length-1];if(u)return{kind:l.Ref,ref:u,nullable:!1}}return{kind:l.Unknown,nullable:!1}}let r=me(e,t);if(!r)return{kind:l.Unknown,nullable:!1};let n=$e(r),s;if(r.discriminator&&(s={propertyName:r.discriminator.propertyName,mapping:r.discriminator.mapping}),r.oneOf&&r.oneOf.length>0){let c=r.oneOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.OneOf,oneOf:c,nullable:n,discriminator:s}}if(r.anyOf&&r.anyOf.length>0){let c=r.anyOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.AnyOf,anyOf:c,nullable:n,discriminator:s}}if(r.allOf&&r.allOf.length>0){let c=r.allOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.AllOf,allOf:c,nullable:n,discriminator:s}}if(r.not){let c=this.schemaRefToIR(e,r.not);return{kind:l.Not,not:c,nullable:n,discriminator:s}}if(r.enum&&r.enum.length>0){let c=r.enum.map(u=>String(u)),p=this.inferEnumBaseKind(r);return{kind:l.Enum,enumValues:c,enumRaw:r.enum,enumBase:p,nullable:n,discriminator:s}}let i=ge(r),a=Array.isArray(i)?i.filter(c=>c!=="null")[0]:i;if(a)switch(a){case"string":return{kind:l.String,nullable:n,format:r.format,discriminator:s};case"integer":return{kind:l.Integer,nullable:n,discriminator:s};case"number":return{kind:l.Number,nullable:n,discriminator:s};case"boolean":return{kind:l.Boolean,nullable:n,discriminator:s};case"array":{let c=r,p=this.schemaRefToIR(e,c.items);return{kind:l.Array,items:p,nullable:n,discriminator:s}}case"object":{let c=[];if(r.properties){let u=Object.keys(r.properties).sort();for(let y of u){let m=r.properties[y],b=this.schemaRefToIR(e,m),$=r.required?.includes(y)||!1;c.push({name:y,type:b,required:$,annotations:this.extractAnnotations(m)})}}let p;return r.additionalProperties&&typeof r.additionalProperties=="object"&&(p=this.schemaRefToIR(e,r.additionalProperties)),{kind:l.Object,properties:c,additionalProperties:p,nullable:n,discriminator:s}}}return{kind:l.Unknown,nullable:n,discriminator:s}}extractAnnotations(e){if(!e||"$ref"in e)return{};let t=e;return{title:t.title,description:t.description,deprecated:t.deprecated,readOnly:t.readOnly,writeOnly:t.writeOnly,default:t.default,examples:t.example?Array.isArray(t.example)?t.example:[t.example]:void 0}}inferEnumBaseKind(e){let t=ge(e);if(t){let r=Array.isArray(t)?t.filter(n=>n!=="null")[0]:t;if(r)switch(r){case"string":return l.String;case"integer":return l.Integer;case"number":return l.Number;case"boolean":return l.Boolean}}if(e.enum&&e.enum.length>0){let r=e.enum[0];if(typeof r=="string")return l.String;if(typeof r=="number")return Number.isInteger(r)?l.Integer:l.Number;if(typeof r=="boolean")return l.Boolean}return l.Unknown}};D=Tt([(0,De.Injectable)()],D);function v(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let n=ye(r);t.push(...n)}return t.filter(r=>r!=="").map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}f(v,"toPascalCase");function A(o){let e=v(o);return e===""?"":e.charAt(0).toLowerCase()+e.slice(1)}f(A,"toCamelCase");function ee(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let n=ye(r);t.push(...n)}return t.filter(r=>r!=="").map(r=>r.toLowerCase()).join("_")}f(ee,"toSnakeCase");function qe(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let n=ye(r);t.push(...n)}return t.filter(r=>r!=="").map(r=>r.toLowerCase()).join("-")}f(qe,"toKebabCase");function ye(o){if(o==="")return[];let e=[],t="",r=Array.from(o);for(let n=0;n<r.length;n++){let s=r[n];if(!s)continue;let i=!1;if(n>0&&he(s)){let a=r[n-1];if(a&&!he(a))i=!0;else if(n<r.length-1){let c=r[n+1];c&&!he(c)&&(i=!0)}}i&&t.length>0&&(e.push(t),t=""),t+=s}return t.length>0&&e.push(t),e}f(ye,"splitCamelCase");function he(o){return o>="A"&&o<="Z"}f(he,"isUppercase");function Ot(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(Ot,"_ts_decorate");function Ie(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(Ie,"_ts_metadata");var q=class{static{f(this,"IrBuilderService")}schemaConverter;constructor(e){this.schemaConverter=e}buildIR(e){let t=this.collectTags(e),r=this.collectSecuritySchemes(e),n=this.buildStructuredModels(e),s={};for(let a of t)s[a]=!0;let i=this.buildIRFromDoc(e,s);return i.securitySchemes=r,i.modelDefs=[...n,...i.modelDefs],i.openApiDocument=e,i}filterIR(e,t){let r=this.compileTagFilters(t.includeTags||[]),n=this.compileTagFilters(t.excludeTags||[]),s=[];for(let a of e.services){let c=[];for(let p of a.operations)this.shouldIncludeOperation(p.originalTags,r,n)&&c.push(p);c.length>0&&s.push({...a,operations:c})}let i={services:s,models:e.models,securitySchemes:e.securitySchemes,modelDefs:e.modelDefs,openApiDocument:e.openApiDocument};return i.modelDefs=this.filterUnusedModelDefs(i,e.modelDefs),i}detectStreamingContentType(e){let t=e.toLowerCase().split(";")[0]?.trim();return t?t==="text/event-stream"?{isStreaming:!0,format:"sse"}:t==="application/x-ndjson"||t==="application/x-jsonlines"||t==="application/jsonl"?{isStreaming:!0,format:"ndjson"}:t.includes("stream")||t.includes("chunked")?{isStreaming:!0,format:"chunked"}:{isStreaming:!1}:{isStreaming:!1}}collectTags(e){let t=new Set;if(t.add("misc"),e.paths)for(let[r,n]of Object.entries(e.paths)){if(!n)continue;let s=[n.get,n.post,n.put,n.patch,n.delete,n.options,n.head,n.trace];for(let i of s)if(!(!i||!i.tags))for(let a of i.tags)t.add(a)}return Array.from(t).sort()}compileTagFilters(e){return e.map(t=>{try{return new RegExp(t)}catch(r){throw new Error(`Invalid tag filter pattern "${t}": ${r instanceof Error?r.message:String(r)}`)}})}shouldIncludeOperation(e,t,r){let n=t.length===0;if(t.length>0)for(let s of e){for(let i of t)if(i.test(s)){n=!0;break}if(n)break}if(!n)return!1;if(r.length>0){for(let s of e)for(let i of r)if(i.test(s))return!1}return!0}buildIRFromDoc(e,t){let r={};r.misc={tag:"misc",operations:[]};let n=[],s=new Set;if(e.components?.schemas)for(let c of Object.keys(e.components.schemas))s.add(c);let i=f((c,p,u,y)=>{r[c]||(r[c]={tag:c,operations:[]});let m=p.operationId||"",{pathParams:b,queryParams:$}=this.collectParams(e,p),{requestBody:Q,extractedTypes:W}=this.extractRequestBodyWithTypes(e,p,c,m,u,s);n.push(...W);let{response:N,extractedTypes:J}=this.extractResponseWithTypes(e,p,c,m,u,s);n.push(...J);let Y=p.tags&&p.tags.length>0?[...p.tags]:["misc"];r[c].operations.push({operationID:m,method:u,path:y,tag:c,originalTags:Y,summary:p.summary||"",description:p.description||"",deprecated:p.deprecated||!1,pathParams:b,queryParams:$,requestBody:Q,response:N})},"addOp");if(e.paths)for(let[c,p]of Object.entries(e.paths)){if(!p)continue;let u=[{op:p.get,method:"GET"},{op:p.post,method:"POST"},{op:p.put,method:"PUT"},{op:p.patch,method:"PATCH"},{op:p.delete,method:"DELETE"},{op:p.options,method:"OPTIONS"},{op:p.head,method:"HEAD"},{op:p.trace,method:"TRACE"}];for(let{op:y,method:m}of u){if(!y)continue;let b=this.firstAllowedTag(y.tags||[],t);b&&i(b,y,m,c)}}let a=Object.values(r);for(let c of a)c.operations.sort((p,u)=>p.path===u.path?p.method.localeCompare(u.method):p.path.localeCompare(u.path));return a.sort((c,p)=>c.tag.localeCompare(p.tag)),{services:a,models:[],securitySchemes:[],modelDefs:n}}deriveMethodName(e,t,r){if(e){let s=e.indexOf("Controller_"),i=s>=0?e.substring(s+11):e;return A(i)}let n=r.includes("{")&&r.includes("}");switch(t){case"GET":return n?"get":"list";case"POST":return"create";case"PUT":case"PATCH":return"update";case"DELETE":return"delete";default:return t.toLowerCase()}}firstAllowedTag(e,t){for(let r of e)if(t[r])return r;return e.length===0&&t.misc?"misc":""}collectSecuritySchemes(e){if(!e.components?.securitySchemes)return[];let t=Object.keys(e.components.securitySchemes).sort(),r=[];for(let n of t){let s=e.components.securitySchemes[n];if(!s||"$ref"in s)continue;let i={key:n,type:s.type};switch(s.type){case"http":i.scheme=s.scheme,s.bearerFormat&&(i.bearerFormat=s.bearerFormat);break;case"apiKey":i.in=s.in,i.name=s.name;break;case"oauth2":case"openIdConnect":break}r.push(i)}return r}collectParams(e,t){let r=[],n=[];if(t.parameters)for(let s of t.parameters){if(!s||"$ref"in s)continue;let i=s,a=this.schemaConverter.schemaRefToIR(e,i.schema),c={name:i.name,required:i.required||!1,schema:a,description:i.description||""};i.in==="path"?r.push(c):i.in==="query"&&n.push(c)}return r.sort((s,i)=>s.name.localeCompare(i.name)),n.sort((s,i)=>s.name.localeCompare(i.name)),{pathParams:r,queryParams:n}}findMatchingComponentSchema(e,t){if(!t||!e.components?.schemas)return null;if("$ref"in t&&t.$ref){let n=t.$ref;if(n.startsWith("#/components/schemas/")){let s=n.replace("#/components/schemas/","");if(e.components.schemas[s])return s}}let r=this.schemaConverter.schemaRefToIR(e,t);for(let[n,s]of Object.entries(e.components.schemas)){let i=this.schemaConverter.schemaRefToIR(e,s);if(this.compareSchemas(r,i))return n}return null}compareSchemas(e,t){if(e.kind!==t.kind)return!1;if(e.kind===l.Ref&&t.kind===l.Ref)return e.ref===t.ref;if(e.kind===l.Object&&t.kind===l.Object){let r=e.properties||[],n=t.properties||[];if(r.length!==n.length)return!1;let s=new Map(r.map(a=>[a.name,{type:a.type,required:a.required}])),i=new Map(n.map(a=>[a.name,{type:a.type,required:a.required}]));if(s.size!==i.size)return!1;for(let[a,c]of s){let p=i.get(a);if(!p||c.required!==p.required||!this.compareSchemas(c.type,p.type))return!1}return!0}return e.kind===l.Array&&t.kind===l.Array?!e.items||!t.items?e.items===t.items:this.compareSchemas(e.items,t.items):!0}extractModelNameFromSchema(e){return e.kind===l.Ref&&e.ref?e.ref:e.kind===l.Array&&e.items&&e.items.kind===l.Ref&&e.items.ref?e.items.ref:null}generateTypeName(e,t,r,n,s,i){let a=this.extractModelNameFromSchema(e);if(a)return a;let c=this.deriveMethodName(r,n,s);return`${v(t)}${v(c)}${i}`}extractRequestBodyWithTypes(e,t,r,n,s,i){let a=[];if(!t.requestBody||"$ref"in t.requestBody)return{requestBody:null,extractedTypes:[]};let c=t.requestBody;if(c.content?.["application/json"]){let u=c.content["application/json"],y=this.schemaConverter.schemaRefToIR(e,u.schema),m=this.findMatchingComponentSchema(e,u.schema);if(m)return{requestBody:{contentType:"application/json",typeTS:"",schema:{kind:l.Ref,ref:m,nullable:!1},required:c.required||!1},extractedTypes:[]};let b=this.generateTypeName(y,r,n,s,t.path,"RequestBody");return y.kind===l.Object&&!i.has(b)?(i.add(b),a.push({name:b,schema:y,annotations:this.schemaConverter.extractAnnotations(u.schema)}),{requestBody:{contentType:"application/json",typeTS:"",schema:{kind:l.Ref,ref:b,nullable:!1},required:c.required||!1},extractedTypes:a}):{requestBody:{contentType:"application/json",typeTS:"",schema:y,required:c.required||!1},extractedTypes:[]}}return{requestBody:this.extractRequestBody(e,t),extractedTypes:[]}}extractRequestBody(e,t){if(!t.requestBody||"$ref"in t.requestBody)return null;let r=t.requestBody;if(r.content?.["application/json"]){let n=r.content["application/json"];return{contentType:"application/json",typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,n.schema),required:r.required||!1}}if(r.content?.["application/x-www-form-urlencoded"]){let n=r.content["application/x-www-form-urlencoded"];return{contentType:"application/x-www-form-urlencoded",typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,n.schema),required:r.required||!1}}if(r.content?.["multipart/form-data"])return{contentType:"multipart/form-data",typeTS:"",schema:{kind:l.Unknown,nullable:!1},required:r.required||!1};if(r.content){let n=Object.keys(r.content)[0];if(!n)return null;let s=r.content[n];return s?{contentType:n,typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,s.schema),required:r.required||!1}:null}return null}extractResponseWithTypes(e,t,r,n,s,i){let a=[];if(!t.responses)return{response:{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""},extractedTypes:[]};let c=["200","201"];for(let u of c){let y=t.responses[u];if(y&&!("$ref"in y)){let m=y;if(m.content){for(let[N,J]of Object.entries(m.content)){let Y=this.detectStreamingContentType(N),X=this.schemaConverter.schemaRefToIR(e,J.schema);if(Y.isStreaming)return{response:{typeTS:"",schema:X,description:m.description||"",isStreaming:!0,contentType:N,...Y.format&&{streamingFormat:Y.format}},extractedTypes:[]};if(N==="application/json"){let ve=this.findMatchingComponentSchema(e,J.schema);if(ve)return{response:{typeTS:"",schema:{kind:l.Ref,ref:ve,nullable:!1},description:m.description||"",isStreaming:!1,contentType:N},extractedTypes:[]};let se=this.generateTypeName(X,r,n,s,t.path,"Response");return X.kind===l.Object&&!i.has(se)?(i.add(se),a.push({name:se,schema:X,annotations:this.schemaConverter.extractAnnotations(J.schema)}),{response:{typeTS:"",schema:{kind:l.Ref,ref:se,nullable:!1},description:m.description||"",isStreaming:!1,contentType:N},extractedTypes:a}):{response:{typeTS:"",schema:X,description:m.description||"",isStreaming:!1,contentType:N},extractedTypes:[]}}}let b=Object.keys(m.content)[0];if(!b)return{response:{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:m.description||"",isStreaming:!1,contentType:""},extractedTypes:[]};let $=m.content[b];if(!$)return{response:{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:m.description||"",isStreaming:!1,contentType:""},extractedTypes:[]};let Q=this.schemaConverter.schemaRefToIR(e,$.schema),W=this.detectStreamingContentType(b);return{response:{typeTS:"",schema:Q,description:m.description||"",isStreaming:W.isStreaming,contentType:b,streamingFormat:W.format},extractedTypes:[]}}return{response:{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:m.description||"",isStreaming:!1,contentType:""},extractedTypes:[]}}}return{response:this.extractResponse(e,t),extractedTypes:[]}}extractResponse(e,t){if(!t.responses)return{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""};let r=["200","201"];for(let n of r){let s=t.responses[n];if(s&&!("$ref"in s)){let i=s;if(i.content){for(let[u,y]of Object.entries(i.content)){let m=this.detectStreamingContentType(u);if(m.isStreaming)return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,y.schema),description:i.description||"",isStreaming:!0,contentType:u,streamingFormat:m.format}}if(i.content["application/json"]){let u=i.content["application/json"];return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,u.schema),description:i.description||"",isStreaming:!1,contentType:"application/json"}}let[a,c]=Object.entries(i.content)[0]??[];if(!a||!c)return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:i.description||"",isStreaming:!1,contentType:""};let p=this.detectStreamingContentType(a);return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,c.schema),description:i.description||"",isStreaming:p.isStreaming,contentType:a,streamingFormat:p.format}}return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:i.description||"",isStreaming:!1,contentType:""}}}for(let[n,s]of Object.entries(t.responses))if(n.length===3&&n[0]==="2"&&s&&!("$ref"in s)){let i=s;if(n==="204")return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:i.description||"",isStreaming:!1,contentType:""};if(i.content){for(let[u,y]of Object.entries(i.content)){let m=this.detectStreamingContentType(u);if(m.isStreaming)return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,y.schema),description:i.description||"",isStreaming:!0,contentType:u,streamingFormat:m.format}}if(i.content["application/json"]){let u=i.content["application/json"];return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,u.schema),description:i.description||"",isStreaming:!1,contentType:"application/json"}}let[a,c]=Object.entries(i.content)[0]??[];if(!a||!c)return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:i.description||"",isStreaming:!1,contentType:""};let p=this.detectStreamingContentType(a);return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,c.schema),description:i.description||"",isStreaming:p.isStreaming,contentType:a,streamingFormat:p.format}}}return{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""}}buildStructuredModels(e){let t=[];if(!e.components?.schemas)return t;let r=Object.keys(e.components.schemas).sort(),n=new Set;for(let s of r)n.add(s);for(let s of r){let i=e.components.schemas[s],a=this.schemaConverter.schemaRefToIR(e,i);t.push({name:s,schema:a,annotations:this.schemaConverter.extractAnnotations(i)})}return t}filterUnusedModelDefs(e,t){let r=new Map;for(let a of t)r.set(a.name,a);let n=new Set,s=new Set,i=f(a=>{if(a.kind==="ref"&&a.ref){let c=a.ref;if(n.add(c),!s.has(c)){s.add(c);let p=r.get(c);p&&i(p.schema)}}if(a.items&&i(a.items),a.additionalProperties&&i(a.additionalProperties),a.oneOf)for(let c of a.oneOf)i(c);if(a.anyOf)for(let c of a.anyOf)i(c);if(a.allOf)for(let c of a.allOf)i(c);if(a.not&&i(a.not),a.properties)for(let c of a.properties)i(c.type)},"collectRefs");for(let a of e.services)for(let c of a.operations){for(let p of c.pathParams)i(p.schema);for(let p of c.queryParams)i(p.schema);c.requestBody&&i(c.requestBody.schema),i(c.response.schema)}return t.filter(a=>n.has(a.name))}};q=Ot([(0,Ae.Injectable)(),Ie("design:type",Function),Ie("design:paramtypes",[typeof D>"u"?Object:D])],q);var ae=require("@nestjs/common"),E=k(require("@apidevtools/swagger-parser")),be=k(require("fs")),Se=k(require("path"));function vt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(vt,"_ts_decorate");var R=class o{static{f(this,"OpenApiService")}logger=new ae.Logger(o.name);async loadDocument(e){try{let t=null;try{t=new URL(e)}catch{}let r;if(t&&(t.protocol==="http:"||t.protocol==="https:")){this.logger.debug(`Loading OpenAPI spec from URL: ${e}`);let s=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error(`Failed to fetch OpenAPI spec: HTTP ${s.status} ${s.statusText}`);let i=await s.text(),a;try{a=JSON.parse(i)}catch{throw new Error("OpenAPI spec is not valid JSON")}try{let c=await E.default.parse(a);r=await E.default.bundle(c)}catch(c){this.logger.debug(`Bundle failed: ${c instanceof Error?c.message:String(c)}`),this.logger.debug("Attempting dereference directly");let p=await E.default.parse(a);r=await E.default.dereference(p)}}else{let s=Se.resolve(e);if(!be.existsSync(s))throw new Error(`OpenAPI spec file not found: ${s}`);this.logger.debug(`Loading OpenAPI spec from file: ${s}`);try{r=await E.default.bundle(s)}catch(i){this.logger.debug(`Bundle failed: ${i instanceof Error?i.message:String(i)}`),this.logger.debug("Attempting dereference directly"),r=await E.default.dereference(s)}}let n=Ce(r);if(!He(n))throw new Error(`Unsupported OpenAPI version: ${r.openapi}. Only versions 3.0.x and 3.1.0 are supported.`);return this.logger.log(`Detected OpenAPI version: ${n} (${r.openapi})`),r}catch(t){throw t instanceof Error?new Error(`Failed to load OpenAPI document from ${e}: ${t.message}`):t}}async validateDocument(e){try{let t=null;try{t=new URL(e)}catch{}if(t&&(t.protocol==="http:"||t.protocol==="https:"))await E.default.validate(e);else{let r=Se.resolve(e);if(!be.existsSync(r))throw new Error(`OpenAPI spec file not found: ${r}`);await E.default.validate(r)}}catch(t){throw t instanceof Error?new Error(`Invalid OpenAPI document: ${t.message}`):t}}};R=vt([(0,ae.Injectable)()],R);function Pt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(Pt,"_ts_decorate");function Ee(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(Ee,"_ts_metadata");var C=class o{static{f(this,"GeneratorService")}irBuilder;openApiService;logger=new ce.Logger(o.name);generators=new Map;constructor(e,t){this.irBuilder=e,this.openApiService=t}register(e){this.generators.set(e.getType(),e),this.logger.debug(`Registered generator: ${e.getType()}`)}getGenerator(e){return this.generators.get(e)}getAvailableTypes(){return Array.from(this.generators.keys())}async generate(e,t){let r=this.getGenerator(t.type);if(!r)throw new Error(`Unsupported client type: ${t.type}`);let n=await this.openApiService.loadDocument(e),s=this.irBuilder.buildIR(n),i=this.irBuilder.filterIR(s,t);await r.generate(t,i)}};C=Pt([(0,ce.Injectable)(),Ee("design:type",Function),Ee("design:paramtypes",[typeof q>"u"?Object:q,typeof R>"u"?Object:R])],C);var Fe=require("child_process"),Ne=require("util"),te=k(require("path")),Be=k(require("fs"));function I(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(I,"_ts_decorate");function w(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(w,"_ts_metadata");var kt=(0,Ne.promisify)(Fe.exec),P=class o extends x.CommandRunner{static{f(this,"GenerateCommand")}generatorService;configService;logger=new pe.Logger(o.name);constructor(e,t){super(),this.generatorService=e,this.configService=t}async run(e,t){try{let r=null,n=null;if(this.logger.debug(`Received options: ${JSON.stringify(t)}`),t.config)n=t.config,r=await this.configService.load(n);else{let p=await this.configService.findDefaultConfig();p&&(this.logger.debug(`Found default config file: ${p}`),n=p,r=await this.configService.load(p))}let s=t["package-name"]||t.packageName||"",i=t["client-name"]||t.clientName||"",a=t["include-tags"]||t.includeTags,c=t["exclude-tags"]||t.excludeTags;if(t.input&&t.type&&t.out&&s&&i)if(r)if(r.spec=t.input,r.clients.length>0){let p=r.clients[0];if(t.type==="typescript"){if(!s||!i)throw new Error("package-name and client-name are required");r.clients[0]={...p,type:"typescript",outDir:te.resolve(t.out),packageName:s,name:i,includeTags:a,excludeTags:c}}else r.clients[0]={...p,type:t.type,outDir:te.resolve(t.out),name:i,includeTags:a,excludeTags:c}}else if(t.type==="typescript"){if(!s||!i)throw new Error("package-name and client-name are required");r.clients.push({type:"typescript",outDir:te.resolve(t.out),packageName:s,name:i,includeTags:a,excludeTags:c})}else throw new Error(`Unsupported client type: ${t.type}`);else if(t.type==="typescript")r={spec:t.input,name:i,clients:[{type:"typescript",outDir:te.resolve(t.out),packageName:s,name:i,includeTags:t.includeTags,excludeTags:t.excludeTags}]};else throw new Error(`Unsupported client type: ${t.type}`);else r||(this.logger.error("\u274C Error: Either --config, chunkflow-codegen.config.mjs, or all fallback options (--input, --type, --out, --package-name, --client-name) must be provided"),process.exit(1));if(!r)throw new Error("Config is required");for(let p of r.clients)if(!(t.client&&p.name!==t.client)){if(await Be.promises.mkdir(p.outDir,{recursive:!0}),await this.executePreCommands(p),this.logger.log(`Generating ${p.type} SDK for ${p.name}...`),!r)throw new Error("Config is required");await this.generatorService.generate(r.spec,p),await this.executePostGenCommands(p),this.logger.log(`\u2705 SDK generated successfully for ${p.name}`)}}catch(r){let n=r instanceof Error?r.message:String(r);this.logger.error(`\u274C Error during SDK generation: ${n}`),r instanceof Error&&r.stack&&this.logger.error(r.stack),process.exit(1)}}parseConfig(e){return e}parseClient(e){return e}parseInput(e){return e}parseType(e){return e}parseOut(e){return e}parsePackageName(e){return e}parseClientName(e){return e}parseIncludeTags(e,t=[]){return[...t,e]}parseExcludeTags(e,t=[]){return[...t,e]}async executePreCommands(e){let t=this.configService.getPreCommand(e);t.length!==0&&await this.executeCommand(t,e.outDir,"pre-command")}async executePostGenCommands(e){let t=this.configService.getPostCommand(e);t.length!==0&&await this.executeCommand(t,e.outDir,"post-command")}async executeCommand(e,t,r){try{let[n,...s]=e;this.logger.debug(`Executing ${r}: ${n} ${s.join(" ")}`);let{stdout:i,stderr:a}=await kt(`${n} ${s.map(c=>`"${c}"`).join(" ")}`,{cwd:t,maxBuffer:10*1024*1024});i&&this.logger.debug(i),a&&!a.includes("warning")&&this.logger.warn(a)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`${r} failed: ${s}`)}}};I([(0,x.Option)({flags:"-c, --config <path>",description:"Path to chunkflow-codegen.config.mjs config file"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseConfig",null);I([(0,x.Option)({flags:"--client <name>",description:"Generate only the named client from config"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseClient",null);I([(0,x.Option)({flags:"--input <path>",description:"OpenAPI spec file or URL (yaml/json)"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseInput",null);I([(0,x.Option)({flags:"--type <type>",description:"Client type (e.g., typescript)"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseType",null);I([(0,x.Option)({flags:"--out <dir>",description:"Output directory"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseOut",null);I([(0,x.Option)({flags:"--package-name <name>",description:"Package name"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parsePackageName",null);I([(0,x.Option)({flags:"--client-name <name>",description:"Client class name"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseClientName",null);I([(0,x.Option)({flags:"--include-tags <tags>",description:"Regex patterns for tags to include (can be specified multiple times)"}),w("design:type",Function),w("design:paramtypes",[String,Array]),w("design:returntype",Array)],P.prototype,"parseIncludeTags",null);I([(0,x.Option)({flags:"--exclude-tags <tags>",description:"Regex patterns for tags to exclude (can be specified multiple times)"}),w("design:type",Function),w("design:paramtypes",[String,Array]),w("design:returntype",Array)],P.prototype,"parseExcludeTags",null);P=I([(0,pe.Injectable)(),(0,x.Command)({name:"generate",description:"Generate client SDKs from OpenAPI specifications",aliases:["gen"]}),w("design:type",Function),w("design:paramtypes",[typeof C>"u"?Object:C,typeof j>"u"?Object:j])],P);var fe=require("@nestjs/common"),K=require("nest-commander");function _e(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(_e,"_ts_decorate");function re(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(re,"_ts_metadata");var U=class o extends K.CommandRunner{static{f(this,"ValidateCommand")}openApiService;logger=new fe.Logger(o.name);constructor(e){super(),this.openApiService=e}async run(e,t){try{t.input||(this.logger.error("\u274C Error: --input is required"),process.exit(1)),this.logger.log(`Validating OpenAPI spec: ${t.input}`),await this.openApiService.validateDocument(t.input),this.logger.log("\u2705 OpenAPI spec is valid")}catch(r){let n=r instanceof Error?r.message:String(r);this.logger.error(`\u274C Invalid OpenAPI spec: ${n}`),r instanceof Error&&r.stack&&this.logger.error(r.stack),process.exit(1)}}parseInput(e){return e}};_e([(0,K.Option)({flags:"--input <path>",description:"OpenAPI spec file or URL (yaml/json)",required:!0}),re("design:type",Function),re("design:paramtypes",[String]),re("design:returntype",String)],U.prototype,"parseInput",null);U=_e([(0,fe.Injectable)(),(0,K.Command)({name:"validate",description:"Validate an OpenAPI spec"}),re("design:type",Function),re("design:paramtypes",[typeof R>"u"?Object:R])],U);var at=require("@nestjs/common");var Me=require("@nestjs/common");function xt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(xt,"_ts_decorate");var B=class{static{f(this,"OpenApiModule")}};B=xt([(0,Me.Module)({providers:[R],exports:[R]})],B);var ze=require("@nestjs/common");function jt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(jt,"_ts_decorate");var _=class{static{f(this,"ConfigModule")}};_=jt([(0,ze.Module)({providers:[j],exports:[j]})],_);var ue=require("@nestjs/common"),T=k(require("fs")),h=k(require("path")),d=k(require("handlebars"));var S=k(require("handlebars"));function Ue(){S.registerHelper("pascal",o=>v(o)),S.registerHelper("camel",o=>A(o)),S.registerHelper("kebab",o=>qe(o)),S.registerHelper("snake",o=>ee(o)),S.registerHelper("serviceName",o=>v(o)+"Service"),S.registerHelper("serviceProp",o=>A(o)),S.registerHelper("fileBase",o=>ee(o).toLowerCase()),S.registerHelper("eq",(o,e)=>o===e),S.registerHelper("ne",(o,e)=>o!==e),S.registerHelper("gt",(o,e)=>o>e),S.registerHelper("lt",(o,e)=>o<e),S.registerHelper("sub",(o,e)=>o-e),S.registerHelper("subtract",(o,e)=>o-e),S.registerHelper("len",o=>Array.isArray(o)?o.length:0),S.registerHelper("lte",(o,e)=>o<=e),S.registerHelper("or",function(...o){let e=o[o.length-1];return e&&"fn"in e&&e.fn?o.slice(0,-1).some(t=>t)?e.fn(this):e.inverse?.(this):o.slice(0,-1).some(t=>t)}),S.registerHelper("and",function(...o){let e=o[o.length-1];return e&&"fn"in e&&e.fn?o.slice(0,-1).every(t=>t)?e.fn(this):e.inverse?.(this):o.slice(0,-1).every(t=>t)}),S.registerHelper("replace",(o,e,t)=>typeof o!="string"?o:o.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),t)),S.registerHelper("index",(o,e)=>o?.[e]),S.registerHelper("getServiceName",o=>{let e=o.split(".");return e.length>1?e[1]:o}),S.registerHelper("groupByNamespace",o=>{let e={};for(let t of o){let r=t.tag.split(".");if(r.length===1)e[""]||(e[""]=[]),e[""]?.push(t);else{let n=r[0];n&&!e[n]&&(e[n]=[]),n&&e[n]?.push(t)}}return e}),S.registerHelper("getRootServices",o=>o.filter(e=>!e.tag.includes("."))),S.registerHelper("dict",()=>({})),S.registerHelper("setVar",(o,e,t)=>(t?.data?.root&&typeof t.data.root=="object"&&(t.data.root[`_${o}`]=e),"")),S.registerHelper("getVar",(o,e)=>e?.data?.root&&typeof e.data.root=="object"&&e.data.root[`_${o}`]||!1),S.registerHelper("set",(o,e,t)=>(o&&typeof o=="object"&&(o[e]=t),"")),S.registerHelper("hasKey",(o,e)=>o&&typeof o=="object"&&e in o),S.registerHelper("lookup",(o,e)=>o&&typeof o=="object"?o[e]:void 0),S.registerHelper("reMatch",(o,e)=>{try{return new RegExp(o).test(e)}catch{return!1}})}f(Ue,"registerCommonHandlebarsHelpers");function Rt(o){return o.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#x60;/g,"`").replace(/&#96;/g,"`").replace(/&amp;/g,"&")}f(Rt,"decodeHtmlEntities");function H(o,e,t,r=!1){let n;switch(o.kind){case l.String:o.format==="binary"?n="Blob":n="string";break;case l.Number:case l.Integer:n="number";break;case l.Boolean:n="boolean";break;case l.Null:n="null";break;case l.Ref:o.ref?e?.some(s=>s.type===o.ref)||r&&t&&t.find(i=>i.name===o.ref)?n=o.ref:n="Schema."+o.ref:n="unknown";break;case l.Array:if(o.items){let s=H(o.items,e,t);s.includes(" | ")||s.includes(" & ")?n=`(${s})[]`:n=`${s}[]`}else n="unknown[]";break;case l.OneOf:o.oneOf?n=o.oneOf.map(i=>H(i,e,t)).join(" | "):n="unknown";break;case l.AnyOf:o.anyOf?n=o.anyOf.map(i=>H(i,e,t)).join(" | "):n="unknown";break;case l.AllOf:o.allOf?n=o.allOf.map(i=>H(i,e,t)).join(" & "):n="unknown";break;case l.Enum:if(o.enumValues&&o.enumValues.length>0){let s=[];switch(o.enumBase){case l.Number:case l.Integer:for(let i of o.enumValues)s.push(i);break;case l.Boolean:for(let i of o.enumValues)i==="true"||i==="false"?s.push(i):s.push(`"${i}"`);break;default:for(let i of o.enumValues)s.push(`"${i}"`)}n=s.join(" | ")}else n="unknown";break;case l.Object:if(!o.properties||o.properties.length===0)n="Record<string, unknown>";else{let s=[];for(let i of o.properties){let a=H(i.type,e,t,r);i.required?s.push(`${i.name}: ${a}`):s.push(`${i.name}?: ${a}`)}n="{ "+s.join("; ")+" }"}break;default:n="unknown"}return o.nullable&&n!=="null"&&(n+=" | null"),Rt(n)}f(H,"schemaToTSType");function G(o){let e=o.path,t=e.includes("{")&&e.includes("}");if(o.operationID)return A(o.operationID);switch(o.method){case"GET":return t?"get":"list";case"POST":return"create";case"PUT":case"PATCH":return"update";case"DELETE":return"delete";default:return o.method.toLowerCase()}}f(G,"deriveMethodName");async function Le(o,e){if(o.operationIdParser)try{let r=await o.operationIdParser(e.operationID,e.method,e.path);if(r)return A(r)}catch{}let t=Ct(e.operationID);return t?A(t):G(e)}f(Le,"resolveMethodName");function Ct(o){if(!o)return"";let e=o.indexOf("Controller_");return e>=0?o.substring(e+11):o}f(Ct,"defaultParseOperationID");function Ge(o){let e=o.path,t="`";for(let r=0;r<e.length;r++){if(e[r]==="{"){let n=r+1;for(;n<e.length&&e[n]!=="}";)n++;if(n<e.length){let s=e.substring(r+1,n);t+=`\${encodeURIComponent(${s})}`,r=n;continue}}t+=e[r]}return t+="`",t}f(Ge,"buildPathTemplate");function we(o){let t=o.path.split("/"),r=[];for(let s of t)s!==""&&(s.startsWith("{")&&s.endsWith("}")||r.push(s));return`'${r.join("/")}'`}f(we,"buildQueryKeyBase");function ne(o){let e=[],t=new Map;for(let n=0;n<o.pathParams.length;n++){let s=o.pathParams[n];s&&t.set(s.name,n)}let r=o.path;for(let n=0;n<r.length;n++)if(r[n]==="{"){let s=n+1;for(;s<r.length&&r[s]!=="}";)s++;if(s<r.length){let i=r.substring(n+1,s),a=t.get(i);if(a!==void 0){let c=o.pathParams[a];c&&e.push(c)}n=s;continue}}return e}f(ne,"orderPathParams");function L(o,e,t,r=!1){return H(o,t,e,r)}f(L,"schemaToTSTypeWithSimpleTypes");function Te(o,e,t,r,n=!1){let s=[];for(let i of ne(o))s.push(`${i.name}: ${L(i.schema,t,r,n)}`);if(o.queryParams.length>0){let i=v(o.tag)+v(e)+"Query";s.push(`query?: Schema.${i}`)}if(o.requestBody){let i=o.requestBody.required===!0?"":"?";s.push(`body${i}: ${L(o.requestBody.schema,t,r,n)}`)}return s.push('init?: Omit<RequestInit, "method" | "body">'),s}f(Te,"buildMethodSignature");function We(o,e){if(!e||e.length===0)return[];let t=new Set,r=f(s=>{let i=o.find(a=>a.name===s);return i?i.schema:null},"resolveRef"),n=f(s=>{if(s.kind==="ref"&&s.ref)if(e.some(a=>a.type===s.ref))t.add(s.ref);else{let a=r(s.ref);a&&n(a)}else if(s.kind==="array"&&s.items)n(s.items);else if(s.kind==="object"&&s.properties)for(let i of s.properties)n(i.type);else if(s.kind==="oneOf"&&s.oneOf)for(let i of s.oneOf)n(i);else if(s.kind==="anyOf"&&s.anyOf)for(let i of s.anyOf)n(i);else if(s.kind==="allOf"&&s.allOf)for(let i of s.allOf)n(i)},"checkSchema");for(let s of o)n(s.schema);return e.filter(s=>t.has(s.type))}f(We,"collectPredefinedTypesUsedInSchema");function Ke(o,e,t){if(!e||e.length===0)return[];let r=new Set,n=f(i=>{if(!t)return null;let a=t.find(c=>c.name===i);return a?a.schema:null},"resolveRef"),s=f(i=>{if(i.kind==="ref"&&i.ref)if(e.some(c=>c.type===i.ref))r.add(i.ref);else{let c=n(i.ref);c&&s(c)}else if(i.kind==="array"&&i.items)s(i.items);else if(i.kind==="object"&&i.properties)for(let a of i.properties)s(a.type);else if(i.kind==="oneOf"&&i.oneOf)for(let a of i.oneOf)s(a);else if(i.kind==="anyOf"&&i.anyOf)for(let a of i.anyOf)s(a);else if(i.kind==="allOf"&&i.allOf)for(let a of i.allOf)s(a)},"checkSchema");for(let i of o.operations)for(let a of i.pathParams)s(a.schema);return e.filter(i=>r.has(i.type))}f(Ke,"collectPredefinedTypesUsedInService");function Ve(o){let e=[];for(let t of ne(o))e.push(t.name);return o.queryParams.length>0&&e.push("query"),o.requestBody&&e.push("body"),e}f(Ve,"queryKeyArgs");function Ze(o,e,t,r,n=!1){let s=we(o),i=[];for(let m of ne(o)){let b=L(m.schema,t,r,n);i.push(b)}let a=o.queryParams.length>0,c=o.requestBody&&!o.requestBody.required,p=o.requestBody&&o.requestBody.required,u=f(m=>`readonly [${[s,...m].join(", ")}]`,"buildTuple");if(!a&&!c){if(p){if(!o.requestBody?.schema)throw new Error("Request body schema is required");let m=L(o.requestBody.schema,t,r,n);return u([...i,m])}return u(i)}let y=[];if(a&&c){let m=`Schema.${v(o.tag)}${v(e)}Query`,b=L(o.requestBody.schema,t,r,n);y.push(u(i)),y.push(u([...i,m])),y.push(u([...i,b])),y.push(u([...i,m,b]))}else if(a){let m=`Schema.${v(o.tag)}${v(e)}Query`;if(p){if(!o.requestBody?.schema)throw new Error("Request body schema is required");let b=L(o.requestBody.schema,t,r,n);y.push(u([...i,b])),y.push(u([...i,b,m]))}else y.push(u(i)),y.push(u([...i,m]))}else if(c){if(!o.requestBody?.schema)throw new Error("Request body schema is required");let m=L(o.requestBody.schema,t,r,n);y.push(u(i)),y.push(u([...i,m]))}return y.join(" | ")}f(Ze,"buildQueryKeyReturnType");function Oe(o){return o.queryParams.length>0||o.requestBody!==null&&!o.requestBody.required}f(Oe,"hasOptionalQueryKeyParams");function le(o){let e=!1;for(let r of o)if(!(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="_"||r==="$")){e=!0;break}let t=o[0];return t&&t>="0"&&t<="9"&&(e=!0),e?`"${o}"`:o}f(le,"quoteTSPropertyName");function M(o,e=new Set){let t=new Set;if(o.kind==="ref"&&o.ref){let r=o.ref;e.has(r)||(e.add(r),t.add(r))}else if(o.kind==="array"&&o.items)M(o.items,e).forEach(n=>t.add(n));else if(o.kind==="object"&&o.properties){for(let r of o.properties)M(r.type,e).forEach(s=>t.add(s));o.additionalProperties&&M(o.additionalProperties,e).forEach(n=>t.add(n))}else if(o.kind==="oneOf"&&o.oneOf)for(let r of o.oneOf)M(r,e).forEach(s=>t.add(s));else if(o.kind==="anyOf"&&o.anyOf)for(let r of o.anyOf)M(r,e).forEach(s=>t.add(s));else if(o.kind==="allOf"&&o.allOf)for(let r of o.allOf)M(r,e).forEach(s=>t.add(s));else o.kind==="not"&&o.not&&M(o.not,e).forEach(n=>t.add(n));return t}f(M,"extractRefDependencies");function Qe(o){let e=new Map;for(let i of o)e.set(i.name,i);let t=new Map;for(let i of o){let a=M(i.schema),c=new Set;for(let p of a)e.has(p)&&c.add(p);t.set(i.name,c)}let r=[],n=new Map,s=[];for(let i of o)n.set(i.name,t.get(i.name)?.size||0),n.get(i.name)===0&&s.push(i.name);for(;s.length>0;){let i=s.shift();if(!i)continue;let a=e.get(i);a&&r.push(a);for(let c of o)if(t.get(c.name)?.has(i)){let u=(n.get(c.name)||0)-1;n.set(c.name,u),u===0&&s.push(c.name)}}if(r.length<o.length){let i=new Set(r.map(a=>a.name));for(let a of o)i.has(a.name)||r.push(a)}return r}f(Qe,"sortModelDefsByDependencies");function Je(o){return o.response.isStreaming===!0}f(Je,"isStreamingOperation");function Ye(o){let e=o.response.schema;return e.kind===l.Array&&e.items?H(e.items):o.response.streamingFormat==="sse"?"string":H(e)}f(Ye,"getStreamingItemType");function F(o,e="",t,r=!1){let n=e+" ",s;switch(o.kind){case l.String:s="z.string()",o.format==="date"||o.format==="date-time"?s="z.iso.datetime()":o.format==="email"?s="z.email()":o.format==="uri"||o.format==="url"?s="z.url()":o.format==="uuid"&&(s="z.uuid()");break;case l.Number:s="z.number()";break;case l.Integer:s="z.number().int()";break;case l.Boolean:s="z.boolean()";break;case l.Null:s="z.null()";break;case l.Ref:o.ref?s=r?`${o.ref}Schema`:`Schema.${o.ref}Schema`:s="z.unknown()";break;case l.Array:o.items?s=`${F(o.items,n,t,r)}.array()`:s="z.unknown().array()";break;case l.Object:if(!o.properties||o.properties.length===0)o.additionalProperties?s=`z.record(z.string(), ${F(o.additionalProperties,n,t,r)})`:s="z.record(z.string(), z.unknown())";else{let i=[];for(let c of o.properties){let p=F(c.type,n,t,r),u=le(c.name);c.required?i.push(`${n}${u}: ${p}`):i.push(`${n}${u}: ${p}.optional()`)}let a=`z.object({
2
+ "use strict";var ft=Object.create;var de=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty;var f=(o,e)=>de(o,"name",{value:e,configurable:!0});var gt=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ut(e))!mt.call(o,n)&&n!==t&&de(o,n,{get:()=>e[n],enumerable:!(r=lt(e,n))||r.enumerable});return o};var k=(o,e,t)=>(t=o!=null?ft(dt(o)):{},gt(e||!o||!o.__esModule?de(t,"default",{value:o,enumerable:!0}):t,o));var pt=require("nest-commander");var ct=require("@nestjs/common");var pe=require("@nestjs/common"),x=require("nest-commander");var ie=require("@nestjs/common"),Re=k(require("fs")),O=k(require("path"));var xe=require("url"),oe=k(require("path"));var g=require("zod"),ht=g.z.object({type:g.z.string().min(1,"Type name is required"),package:g.z.string().min(1,"Package name is required"),importPath:g.z.string().optional()}),Pe=["client.ts.hbs","index.ts.hbs","package.json.hbs","README.md.hbs","schema.ts.hbs","schema.zod.ts.hbs","service.ts.hbs","tsconfig.json.hbs","utils.ts.hbs"],yt=g.z.object({type:g.z.string().min(1,"Type is required"),outDir:g.z.string().min(1,"OutDir is required"),name:g.z.string().min(1,"Name is required"),includeTags:g.z.array(g.z.string()).optional(),excludeTags:g.z.array(g.z.string()).optional(),operationIdParser:g.z.custom().optional(),preCommand:g.z.array(g.z.string()).optional(),postCommand:g.z.array(g.z.string()).optional(),defaultBaseURL:g.z.string().optional(),exclude:g.z.array(g.z.string()).optional()}),bt=yt.extend({type:g.z.literal("typescript"),packageName:g.z.string().min(1,"PackageName is required"),moduleName:g.z.string().optional(),srcDir:g.z.string().optional(),includeQueryKeys:g.z.boolean().optional(),predefinedTypes:g.z.array(ht).optional(),dependencies:g.z.record(g.z.string(),g.z.string()).optional(),devDependencies:g.z.record(g.z.string(),g.z.string()).optional(),formatCode:g.z.boolean().optional(),templates:g.z.record(g.z.string(),g.z.string()).refine(o=>Object.keys(o).every(e=>Pe.includes(e)),{message:`Template names must be one of: ${Pe.join(", ")}`}).optional()}),St=g.z.discriminatedUnion("type",[bt]),ke=g.z.object({spec:g.z.string().min(1,"Spec is required"),name:g.z.string().optional(),clients:g.z.array(St).min(1,"At least one client is required")});async function je(o){try{let e=oe.isAbsolute(o)?o:oe.resolve(o),r=await import((0,xe.pathToFileURL)(e).href),n=r.default||r;if(!n)throw new Error(`Config file must export a default export or named export: ${o}`);return ke.parse(n)}catch(e){throw e instanceof Error?new Error(`Failed to load MJS config from ${o}: ${e.message}`):e}}f(je,"loadMjsConfig");function wt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(wt,"_ts_decorate");var j=class o{static{f(this,"ConfigService")}logger=new ie.Logger(o.name);DEFAULT_CONFIG_FILE="chunkflow-codegen.config.mjs";async findDefaultConfig(){let e=process.cwd(),t=O.parse(e).root;for(;e!==t;){let r=O.join(e,this.DEFAULT_CONFIG_FILE);try{return await Re.promises.access(r),r}catch{}e=O.dirname(e)}return null}async load(e){try{let t=await je(e);return this.normalizePaths(t,e)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}normalizePaths(e,t){let r=O.dirname(O.resolve(t)),n=e.spec;this.isUrl(n)||O.isAbsolute(n)||(n=O.resolve(r,n));let s=e.clients.map(i=>{let a=i.outDir;return O.isAbsolute(a)||(a=O.resolve(r,a)),{...i,outDir:a}});return{...e,spec:n,clients:s}}isUrl(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}getPreCommand(e){return e.preCommand||[]}getPostCommand(e){return e.postCommand||[]}shouldExcludeFile(e,t){if(!e.exclude||e.exclude.length===0)return!1;let r;try{r=O.relative(e.outDir,t)}catch{return!1}r=O.posix.normalize(r),r==="."&&(r="");for(let n of e.exclude){let s=O.posix.normalize(n);if(r===s||s!==""&&r.startsWith(s+"/"))return!0}return!1}};j=wt([(0,ie.Injectable)()],j);var ce=require("@nestjs/common");var Ae=require("@nestjs/common");var $e=require("@nestjs/common");var l=(function(o){return o.Unknown="unknown",o.String="string",o.Number="number",o.Integer="integer",o.Boolean="boolean",o.Null="null",o.Array="array",o.Object="object",o.Enum="enum",o.Ref="ref",o.OneOf="oneOf",o.AnyOf="anyOf",o.AllOf="allOf",o.Not="not",o})({});function Ce(o){let e=o.openapi;return typeof e!="string"?"unknown":e.startsWith("3.1")?"3.1":e.startsWith("3.0")?"3.0":"unknown"}f(Ce,"detectOpenAPIVersion");function He(o){return o==="3.0"||o==="3.1"}f(He,"isSupportedVersion");function me(o,e){if(!(!e||typeof e!="object")){if("$ref"in e&&e.$ref){let t=e.$ref;if(t.startsWith("#/components/schemas/")){let r=t.replace("#/components/schemas/","");if(o.components?.schemas?.[r]){let n=o.components.schemas[r];return"$ref"in n?me(o,n):n}}return}return e}}f(me,"getSchemaFromRef");function De(o){return o?"nullable"in o&&o.nullable===!0?!0:"type"in o&&Array.isArray(o.type)?o.type.includes("null"):!1:!1}f(De,"isSchemaNullable");function ge(o){if(!(!o||!("type"in o)))return o.type}f(ge,"getSchemaType");function Tt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(Tt,"_ts_decorate");var $=class{static{f(this,"SchemaConverterService")}schemaRefToIR(e,t){if(!t)return{kind:l.Unknown,nullable:!1};if("$ref"in t&&t.$ref){let c=t.$ref;if(c.startsWith("#/components/schemas/")){let u=c.replace("#/components/schemas/","");return{kind:l.Ref,ref:u,nullable:!1}}let p=c.split("/");if(p.length>0){let u=p[p.length-1];if(u)return{kind:l.Ref,ref:u,nullable:!1}}return{kind:l.Unknown,nullable:!1}}let r=me(e,t);if(!r)return{kind:l.Unknown,nullable:!1};let n=De(r),s;if(r.discriminator&&(s={propertyName:r.discriminator.propertyName,mapping:r.discriminator.mapping}),r.oneOf&&r.oneOf.length>0){let c=r.oneOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.OneOf,oneOf:c,nullable:n,discriminator:s}}if(r.anyOf&&r.anyOf.length>0){let c=r.anyOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.AnyOf,anyOf:c,nullable:n,discriminator:s}}if(r.allOf&&r.allOf.length>0){let c=r.allOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.AllOf,allOf:c,nullable:n,discriminator:s}}if(r.not){let c=this.schemaRefToIR(e,r.not);return{kind:l.Not,not:c,nullable:n,discriminator:s}}if(r.enum&&r.enum.length>0){let c=r.enum.map(u=>String(u)),p=this.inferEnumBaseKind(r);return{kind:l.Enum,enumValues:c,enumRaw:r.enum,enumBase:p,nullable:n,discriminator:s}}let i=ge(r),a=Array.isArray(i)?i.filter(c=>c!=="null")[0]:i;if(a)switch(a){case"string":return{kind:l.String,nullable:n,format:r.format,discriminator:s};case"integer":return{kind:l.Integer,nullable:n,discriminator:s};case"number":return{kind:l.Number,nullable:n,discriminator:s};case"boolean":return{kind:l.Boolean,nullable:n,discriminator:s};case"array":{let c=r,p=this.schemaRefToIR(e,c.items);return{kind:l.Array,items:p,nullable:n,discriminator:s}}case"object":{let c=[];if(r.properties){let u=Object.keys(r.properties).sort();for(let y of u){let m=r.properties[y],b=this.schemaRefToIR(e,m),D=r.required?.includes(y)||!1;c.push({name:y,type:b,required:D,annotations:this.extractAnnotations(m)})}}let p;return r.additionalProperties&&typeof r.additionalProperties=="object"&&(p=this.schemaRefToIR(e,r.additionalProperties)),{kind:l.Object,properties:c,additionalProperties:p,nullable:n,discriminator:s}}}return{kind:l.Unknown,nullable:n,discriminator:s}}extractAnnotations(e){if(!e||"$ref"in e)return{};let t=e;return{title:t.title,description:t.description,deprecated:t.deprecated,readOnly:t.readOnly,writeOnly:t.writeOnly,default:t.default,examples:t.example?Array.isArray(t.example)?t.example:[t.example]:void 0}}inferEnumBaseKind(e){let t=ge(e);if(t){let r=Array.isArray(t)?t.filter(n=>n!=="null")[0]:t;if(r)switch(r){case"string":return l.String;case"integer":return l.Integer;case"number":return l.Number;case"boolean":return l.Boolean}}if(e.enum&&e.enum.length>0){let r=e.enum[0];if(typeof r=="string")return l.String;if(typeof r=="number")return Number.isInteger(r)?l.Integer:l.Number;if(typeof r=="boolean")return l.Boolean}return l.Unknown}};$=Tt([(0,$e.Injectable)()],$);function v(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let n=ye(r);t.push(...n)}return t.filter(r=>r!=="").map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}f(v,"toPascalCase");function A(o){let e=v(o);return e===""?"":e.charAt(0).toLowerCase()+e.slice(1)}f(A,"toCamelCase");function ee(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let n=ye(r);t.push(...n)}return t.filter(r=>r!=="").map(r=>r.toLowerCase()).join("_")}f(ee,"toSnakeCase");function qe(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let n=ye(r);t.push(...n)}return t.filter(r=>r!=="").map(r=>r.toLowerCase()).join("-")}f(qe,"toKebabCase");function ye(o){if(o==="")return[];let e=[],t="",r=Array.from(o);for(let n=0;n<r.length;n++){let s=r[n];if(!s)continue;let i=!1;if(n>0&&he(s)){let a=r[n-1];if(a&&!he(a))i=!0;else if(n<r.length-1){let c=r[n+1];c&&!he(c)&&(i=!0)}}i&&t.length>0&&(e.push(t),t=""),t+=s}return t.length>0&&e.push(t),e}f(ye,"splitCamelCase");function he(o){return o>="A"&&o<="Z"}f(he,"isUppercase");function Ot(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(Ot,"_ts_decorate");function Ie(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(Ie,"_ts_metadata");var q=class{static{f(this,"IrBuilderService")}schemaConverter;constructor(e){this.schemaConverter=e}buildIR(e){let t=this.collectTags(e),r=this.collectSecuritySchemes(e),n=this.buildStructuredModels(e),s={};for(let a of t)s[a]=!0;let i=this.buildIRFromDoc(e,s);return i.securitySchemes=r,i.modelDefs=[...n,...i.modelDefs],i.openApiDocument=e,i}filterIR(e,t){let r=this.compileTagFilters(t.includeTags||[]),n=this.compileTagFilters(t.excludeTags||[]),s=[];for(let a of e.services){let c=[];for(let p of a.operations)this.shouldIncludeOperation(p.originalTags,r,n)&&c.push(p);c.length>0&&s.push({...a,operations:c})}let i={services:s,models:e.models,securitySchemes:e.securitySchemes,modelDefs:e.modelDefs,openApiDocument:e.openApiDocument};return i.modelDefs=this.filterUnusedModelDefs(i,e.modelDefs),i}detectStreamingContentType(e){let t=e.toLowerCase().split(";")[0]?.trim();return t?t==="text/event-stream"?{isStreaming:!0,format:"sse"}:t==="application/x-ndjson"||t==="application/x-jsonlines"||t==="application/jsonl"?{isStreaming:!0,format:"ndjson"}:t.includes("stream")||t.includes("chunked")?{isStreaming:!0,format:"chunked"}:{isStreaming:!1}:{isStreaming:!1}}collectTags(e){let t=new Set;if(t.add("misc"),e.paths)for(let[r,n]of Object.entries(e.paths)){if(!n)continue;let s=[n.get,n.post,n.put,n.patch,n.delete,n.options,n.head,n.trace];for(let i of s)if(!(!i||!i.tags))for(let a of i.tags)t.add(a)}return Array.from(t).sort()}compileTagFilters(e){return e.map(t=>{try{return new RegExp(t)}catch(r){throw new Error(`Invalid tag filter pattern "${t}": ${r instanceof Error?r.message:String(r)}`)}})}shouldIncludeOperation(e,t,r){let n=t.length===0;if(t.length>0)for(let s of e){for(let i of t)if(i.test(s)){n=!0;break}if(n)break}if(!n)return!1;if(r.length>0){for(let s of e)for(let i of r)if(i.test(s))return!1}return!0}buildIRFromDoc(e,t){let r={};r.misc={tag:"misc",operations:[]};let n=[],s=new Set;if(e.components?.schemas)for(let c of Object.keys(e.components.schemas))s.add(c);let i=f((c,p,u,y)=>{r[c]||(r[c]={tag:c,operations:[]});let m=p.operationId||"",{pathParams:b,queryParams:D}=this.collectParams(e,p),{requestBody:Q,extractedTypes:W}=this.extractRequestBodyWithTypes(e,p,c,m,u,s);n.push(...W);let{response:N,extractedTypes:J}=this.extractResponseWithTypes(e,p,c,m,u,s);n.push(...J);let Y=p.tags&&p.tags.length>0?[...p.tags]:["misc"];r[c].operations.push({operationID:m,method:u,path:y,tag:c,originalTags:Y,summary:p.summary||"",description:p.description||"",deprecated:p.deprecated||!1,pathParams:b,queryParams:D,requestBody:Q,response:N})},"addOp");if(e.paths)for(let[c,p]of Object.entries(e.paths)){if(!p)continue;let u=[{op:p.get,method:"GET"},{op:p.post,method:"POST"},{op:p.put,method:"PUT"},{op:p.patch,method:"PATCH"},{op:p.delete,method:"DELETE"},{op:p.options,method:"OPTIONS"},{op:p.head,method:"HEAD"},{op:p.trace,method:"TRACE"}];for(let{op:y,method:m}of u){if(!y)continue;let b=this.firstAllowedTag(y.tags||[],t);b&&i(b,y,m,c)}}let a=Object.values(r);for(let c of a)c.operations.sort((p,u)=>p.path===u.path?p.method.localeCompare(u.method):p.path.localeCompare(u.path));return a.sort((c,p)=>c.tag.localeCompare(p.tag)),{services:a,models:[],securitySchemes:[],modelDefs:n}}deriveMethodName(e,t,r){if(e){let s=e.indexOf("Controller_"),i=s>=0?e.substring(s+11):e;return A(i)}let n=r.includes("{")&&r.includes("}");switch(t){case"GET":return n?"get":"list";case"POST":return"create";case"PUT":case"PATCH":return"update";case"DELETE":return"delete";default:return t.toLowerCase()}}firstAllowedTag(e,t){for(let r of e)if(t[r])return r;return e.length===0&&t.misc?"misc":""}collectSecuritySchemes(e){if(!e.components?.securitySchemes)return[];let t=Object.keys(e.components.securitySchemes).sort(),r=[];for(let n of t){let s=e.components.securitySchemes[n];if(!s||"$ref"in s)continue;let i={key:n,type:s.type};switch(s.type){case"http":i.scheme=s.scheme,s.bearerFormat&&(i.bearerFormat=s.bearerFormat);break;case"apiKey":i.in=s.in,i.name=s.name;break;case"oauth2":case"openIdConnect":break}r.push(i)}return r}collectParams(e,t){let r=[],n=[];if(t.parameters)for(let s of t.parameters){if(!s||"$ref"in s)continue;let i=s,a=this.schemaConverter.schemaRefToIR(e,i.schema),c={name:i.name,required:i.required||!1,schema:a,description:i.description||""};i.in==="path"?r.push(c):i.in==="query"&&n.push(c)}return r.sort((s,i)=>s.name.localeCompare(i.name)),n.sort((s,i)=>s.name.localeCompare(i.name)),{pathParams:r,queryParams:n}}findMatchingComponentSchema(e,t){if(!t||!e.components?.schemas)return null;if("$ref"in t&&t.$ref){let n=t.$ref;if(n.startsWith("#/components/schemas/")){let s=n.replace("#/components/schemas/","");if(e.components.schemas[s])return s}}let r=this.schemaConverter.schemaRefToIR(e,t);for(let[n,s]of Object.entries(e.components.schemas)){let i=this.schemaConverter.schemaRefToIR(e,s);if(this.compareSchemas(r,i))return n}return null}compareSchemas(e,t){if(e.kind!==t.kind)return!1;if(e.kind===l.Ref&&t.kind===l.Ref)return e.ref===t.ref;if(e.kind===l.Object&&t.kind===l.Object){let r=e.properties||[],n=t.properties||[];if(r.length!==n.length)return!1;let s=new Map(r.map(a=>[a.name,{type:a.type,required:a.required}])),i=new Map(n.map(a=>[a.name,{type:a.type,required:a.required}]));if(s.size!==i.size)return!1;for(let[a,c]of s){let p=i.get(a);if(!p||c.required!==p.required||!this.compareSchemas(c.type,p.type))return!1}return!0}return e.kind===l.Array&&t.kind===l.Array?!e.items||!t.items?e.items===t.items:this.compareSchemas(e.items,t.items):!0}extractModelNameFromSchema(e){return e.kind===l.Ref&&e.ref?e.ref:e.kind===l.Array&&e.items&&e.items.kind===l.Ref&&e.items.ref?e.items.ref:null}generateTypeName(e,t,r,n,s,i){let a=this.extractModelNameFromSchema(e);if(a)return a;let c=this.deriveMethodName(r,n,s);return`${v(t)}${v(c)}${i}`}extractRequestBodyWithTypes(e,t,r,n,s,i){let a=[];if(!t.requestBody||"$ref"in t.requestBody)return{requestBody:null,extractedTypes:[]};let c=t.requestBody;if(c.content?.["application/json"]){let u=c.content["application/json"],y=this.schemaConverter.schemaRefToIR(e,u.schema),m=this.findMatchingComponentSchema(e,u.schema);if(m)return{requestBody:{contentType:"application/json",typeTS:"",schema:{kind:l.Ref,ref:m,nullable:!1},required:c.required||!1},extractedTypes:[]};let b=this.generateTypeName(y,r,n,s,t.path,"RequestBody");return y.kind===l.Object&&!i.has(b)?(i.add(b),a.push({name:b,schema:y,annotations:this.schemaConverter.extractAnnotations(u.schema)}),{requestBody:{contentType:"application/json",typeTS:"",schema:{kind:l.Ref,ref:b,nullable:!1},required:c.required||!1},extractedTypes:a}):{requestBody:{contentType:"application/json",typeTS:"",schema:y,required:c.required||!1},extractedTypes:[]}}return{requestBody:this.extractRequestBody(e,t),extractedTypes:[]}}extractRequestBody(e,t){if(!t.requestBody||"$ref"in t.requestBody)return null;let r=t.requestBody;if(r.content?.["application/json"]){let n=r.content["application/json"];return{contentType:"application/json",typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,n.schema),required:r.required||!1}}if(r.content?.["application/x-www-form-urlencoded"]){let n=r.content["application/x-www-form-urlencoded"];return{contentType:"application/x-www-form-urlencoded",typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,n.schema),required:r.required||!1}}if(r.content?.["multipart/form-data"])return{contentType:"multipart/form-data",typeTS:"",schema:{kind:l.Unknown,nullable:!1},required:r.required||!1};if(r.content){let n=Object.keys(r.content)[0];if(!n)return null;let s=r.content[n];return s?{contentType:n,typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,s.schema),required:r.required||!1}:null}return null}extractResponseWithTypes(e,t,r,n,s,i){let a=[];if(!t.responses)return{response:{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""},extractedTypes:[]};let c=["200","201"];for(let u of c){let y=t.responses[u];if(y&&!("$ref"in y)){let m=y;if(m.content){for(let[N,J]of Object.entries(m.content)){let Y=this.detectStreamingContentType(N),X=this.schemaConverter.schemaRefToIR(e,J.schema);if(Y.isStreaming)return{response:{typeTS:"",schema:X,description:m.description||"",isStreaming:!0,contentType:N,...Y.format&&{streamingFormat:Y.format}},extractedTypes:[]};if(N==="application/json"){let ve=this.findMatchingComponentSchema(e,J.schema);if(ve)return{response:{typeTS:"",schema:{kind:l.Ref,ref:ve,nullable:!1},description:m.description||"",isStreaming:!1,contentType:N},extractedTypes:[]};let se=this.generateTypeName(X,r,n,s,t.path,"Response");return X.kind===l.Object&&!i.has(se)?(i.add(se),a.push({name:se,schema:X,annotations:this.schemaConverter.extractAnnotations(J.schema)}),{response:{typeTS:"",schema:{kind:l.Ref,ref:se,nullable:!1},description:m.description||"",isStreaming:!1,contentType:N},extractedTypes:a}):{response:{typeTS:"",schema:X,description:m.description||"",isStreaming:!1,contentType:N},extractedTypes:[]}}}let b=Object.keys(m.content)[0];if(!b)return{response:{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:m.description||"",isStreaming:!1,contentType:""},extractedTypes:[]};let D=m.content[b];if(!D)return{response:{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:m.description||"",isStreaming:!1,contentType:""},extractedTypes:[]};let Q=this.schemaConverter.schemaRefToIR(e,D.schema),W=this.detectStreamingContentType(b);return{response:{typeTS:"",schema:Q,description:m.description||"",isStreaming:W.isStreaming,contentType:b,streamingFormat:W.format},extractedTypes:[]}}return{response:{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:m.description||"",isStreaming:!1,contentType:""},extractedTypes:[]}}}return{response:this.extractResponse(e,t),extractedTypes:[]}}extractResponse(e,t){if(!t.responses)return{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""};let r=["200","201"];for(let n of r){let s=t.responses[n];if(s&&!("$ref"in s)){let i=s;if(i.content){for(let[u,y]of Object.entries(i.content)){let m=this.detectStreamingContentType(u);if(m.isStreaming)return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,y.schema),description:i.description||"",isStreaming:!0,contentType:u,streamingFormat:m.format}}if(i.content["application/json"]){let u=i.content["application/json"];return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,u.schema),description:i.description||"",isStreaming:!1,contentType:"application/json"}}let[a,c]=Object.entries(i.content)[0]??[];if(!a||!c)return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:i.description||"",isStreaming:!1,contentType:""};let p=this.detectStreamingContentType(a);return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,c.schema),description:i.description||"",isStreaming:p.isStreaming,contentType:a,streamingFormat:p.format}}return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:i.description||"",isStreaming:!1,contentType:""}}}for(let[n,s]of Object.entries(t.responses))if(n.length===3&&n[0]==="2"&&s&&!("$ref"in s)){let i=s;if(n==="204")return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:i.description||"",isStreaming:!1,contentType:""};if(i.content){for(let[u,y]of Object.entries(i.content)){let m=this.detectStreamingContentType(u);if(m.isStreaming)return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,y.schema),description:i.description||"",isStreaming:!0,contentType:u,streamingFormat:m.format}}if(i.content["application/json"]){let u=i.content["application/json"];return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,u.schema),description:i.description||"",isStreaming:!1,contentType:"application/json"}}let[a,c]=Object.entries(i.content)[0]??[];if(!a||!c)return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:i.description||"",isStreaming:!1,contentType:""};let p=this.detectStreamingContentType(a);return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,c.schema),description:i.description||"",isStreaming:p.isStreaming,contentType:a,streamingFormat:p.format}}}return{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""}}buildStructuredModels(e){let t=[];if(!e.components?.schemas)return t;let r=Object.keys(e.components.schemas).sort(),n=new Set;for(let s of r)n.add(s);for(let s of r){let i=e.components.schemas[s],a=this.schemaConverter.schemaRefToIR(e,i);t.push({name:s,schema:a,annotations:this.schemaConverter.extractAnnotations(i)})}return t}filterUnusedModelDefs(e,t){let r=new Map;for(let a of t)r.set(a.name,a);let n=new Set,s=new Set,i=f(a=>{if(a.kind==="ref"&&a.ref){let c=a.ref;if(n.add(c),!s.has(c)){s.add(c);let p=r.get(c);p&&i(p.schema)}}if(a.items&&i(a.items),a.additionalProperties&&i(a.additionalProperties),a.oneOf)for(let c of a.oneOf)i(c);if(a.anyOf)for(let c of a.anyOf)i(c);if(a.allOf)for(let c of a.allOf)i(c);if(a.not&&i(a.not),a.properties)for(let c of a.properties)i(c.type)},"collectRefs");for(let a of e.services)for(let c of a.operations){for(let p of c.pathParams)i(p.schema);for(let p of c.queryParams)i(p.schema);c.requestBody&&i(c.requestBody.schema),i(c.response.schema)}return t.filter(a=>n.has(a.name))}};q=Ot([(0,Ae.Injectable)(),Ie("design:type",Function),Ie("design:paramtypes",[typeof $>"u"?Object:$])],q);var ae=require("@nestjs/common"),E=k(require("@apidevtools/swagger-parser")),be=k(require("fs")),Se=k(require("path"));function vt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(vt,"_ts_decorate");var R=class o{static{f(this,"OpenApiService")}logger=new ae.Logger(o.name);async loadDocument(e){try{let t=null;try{t=new URL(e)}catch{}let r;if(t&&(t.protocol==="http:"||t.protocol==="https:")){this.logger.debug(`Loading OpenAPI spec from URL: ${e}`);let s=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error(`Failed to fetch OpenAPI spec: HTTP ${s.status} ${s.statusText}`);let i=await s.text(),a;try{a=JSON.parse(i)}catch{throw new Error("OpenAPI spec is not valid JSON")}try{let c=await E.default.parse(a);r=await E.default.bundle(c)}catch(c){this.logger.debug(`Bundle failed: ${c instanceof Error?c.message:String(c)}`),this.logger.debug("Attempting dereference directly");let p=await E.default.parse(a);r=await E.default.dereference(p)}}else{let s=Se.resolve(e);if(!be.existsSync(s))throw new Error(`OpenAPI spec file not found: ${s}`);this.logger.debug(`Loading OpenAPI spec from file: ${s}`);try{r=await E.default.bundle(s)}catch(i){this.logger.debug(`Bundle failed: ${i instanceof Error?i.message:String(i)}`),this.logger.debug("Attempting dereference directly"),r=await E.default.dereference(s)}}let n=Ce(r);if(!He(n))throw new Error(`Unsupported OpenAPI version: ${r.openapi}. Only versions 3.0.x and 3.1.0 are supported.`);return this.logger.log(`Detected OpenAPI version: ${n} (${r.openapi})`),r}catch(t){throw t instanceof Error?new Error(`Failed to load OpenAPI document from ${e}: ${t.message}`):t}}async validateDocument(e){try{let t=null;try{t=new URL(e)}catch{}if(t&&(t.protocol==="http:"||t.protocol==="https:"))await E.default.validate(e);else{let r=Se.resolve(e);if(!be.existsSync(r))throw new Error(`OpenAPI spec file not found: ${r}`);await E.default.validate(r)}}catch(t){throw t instanceof Error?new Error(`Invalid OpenAPI document: ${t.message}`):t}}};R=vt([(0,ae.Injectable)()],R);function Pt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(Pt,"_ts_decorate");function Ee(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(Ee,"_ts_metadata");var C=class o{static{f(this,"GeneratorService")}irBuilder;openApiService;logger=new ce.Logger(o.name);generators=new Map;constructor(e,t){this.irBuilder=e,this.openApiService=t}register(e){this.generators.set(e.getType(),e),this.logger.debug(`Registered generator: ${e.getType()}`)}getGenerator(e){return this.generators.get(e)}getAvailableTypes(){return Array.from(this.generators.keys())}async generate(e,t){let r=this.getGenerator(t.type);if(!r)throw new Error(`Unsupported client type: ${t.type}`);let n=await this.openApiService.loadDocument(e),s=this.irBuilder.buildIR(n),i=this.irBuilder.filterIR(s,t);await r.generate(t,i)}};C=Pt([(0,ce.Injectable)(),Ee("design:type",Function),Ee("design:paramtypes",[typeof q>"u"?Object:q,typeof R>"u"?Object:R])],C);var Fe=require("child_process"),Ne=require("util"),te=k(require("path")),Be=k(require("fs"));function I(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(I,"_ts_decorate");function w(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(w,"_ts_metadata");var kt=(0,Ne.promisify)(Fe.exec),P=class o extends x.CommandRunner{static{f(this,"GenerateCommand")}generatorService;configService;logger=new pe.Logger(o.name);constructor(e,t){super(),this.generatorService=e,this.configService=t}async run(e,t){try{let r=null,n=null;if(this.logger.debug(`Received options: ${JSON.stringify(t)}`),t.config)n=t.config,r=await this.configService.load(n);else{let p=await this.configService.findDefaultConfig();p&&(this.logger.debug(`Found default config file: ${p}`),n=p,r=await this.configService.load(p))}let s=t["package-name"]||t.packageName||"",i=t["client-name"]||t.clientName||"",a=t["include-tags"]||t.includeTags,c=t["exclude-tags"]||t.excludeTags;if(t.input&&t.type&&t.out&&s&&i)if(r)if(r.spec=t.input,r.clients.length>0){let p=r.clients[0];if(t.type==="typescript"){if(!s||!i)throw new Error("package-name and client-name are required");r.clients[0]={...p,type:"typescript",outDir:te.resolve(t.out),packageName:s,name:i,includeTags:a,excludeTags:c}}else r.clients[0]={...p,type:t.type,outDir:te.resolve(t.out),name:i,includeTags:a,excludeTags:c}}else if(t.type==="typescript"){if(!s||!i)throw new Error("package-name and client-name are required");r.clients.push({type:"typescript",outDir:te.resolve(t.out),packageName:s,name:i,includeTags:a,excludeTags:c})}else throw new Error(`Unsupported client type: ${t.type}`);else if(t.type==="typescript")r={spec:t.input,name:i,clients:[{type:"typescript",outDir:te.resolve(t.out),packageName:s,name:i,includeTags:t.includeTags,excludeTags:t.excludeTags}]};else throw new Error(`Unsupported client type: ${t.type}`);else r||(this.logger.error("\u274C Error: Either --config, chunkflow-codegen.config.mjs, or all fallback options (--input, --type, --out, --package-name, --client-name) must be provided"),process.exit(1));if(!r)throw new Error("Config is required");for(let p of r.clients)if(!(t.client&&p.name!==t.client)){if(await Be.promises.mkdir(p.outDir,{recursive:!0}),await this.executePreCommands(p),this.logger.log(`Generating ${p.type} SDK for ${p.name}...`),!r)throw new Error("Config is required");await this.generatorService.generate(r.spec,p),await this.executePostGenCommands(p),this.logger.log(`\u2705 SDK generated successfully for ${p.name}`)}}catch(r){let n=r instanceof Error?r.message:String(r);this.logger.error(`\u274C Error during SDK generation: ${n}`),r instanceof Error&&r.stack&&this.logger.error(r.stack),process.exit(1)}}parseConfig(e){return e}parseClient(e){return e}parseInput(e){return e}parseType(e){return e}parseOut(e){return e}parsePackageName(e){return e}parseClientName(e){return e}parseIncludeTags(e,t=[]){return[...t,e]}parseExcludeTags(e,t=[]){return[...t,e]}async executePreCommands(e){let t=this.configService.getPreCommand(e);t.length!==0&&await this.executeCommand(t,e.outDir,"pre-command")}async executePostGenCommands(e){let t=this.configService.getPostCommand(e);t.length!==0&&await this.executeCommand(t,e.outDir,"post-command")}async executeCommand(e,t,r){try{let[n,...s]=e;this.logger.debug(`Executing ${r}: ${n} ${s.join(" ")}`);let{stdout:i,stderr:a}=await kt(`${n} ${s.map(c=>`"${c}"`).join(" ")}`,{cwd:t,maxBuffer:10*1024*1024});i&&this.logger.debug(i),a&&!a.includes("warning")&&this.logger.warn(a)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`${r} failed: ${s}`)}}};I([(0,x.Option)({flags:"-c, --config <path>",description:"Path to chunkflow-codegen.config.mjs config file"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseConfig",null);I([(0,x.Option)({flags:"--client <name>",description:"Generate only the named client from config"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseClient",null);I([(0,x.Option)({flags:"--input <path>",description:"OpenAPI spec file or URL (yaml/json)"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseInput",null);I([(0,x.Option)({flags:"--type <type>",description:"Client type (e.g., typescript)"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseType",null);I([(0,x.Option)({flags:"--out <dir>",description:"Output directory"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseOut",null);I([(0,x.Option)({flags:"--package-name <name>",description:"Package name"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parsePackageName",null);I([(0,x.Option)({flags:"--client-name <name>",description:"Client class name"}),w("design:type",Function),w("design:paramtypes",[String]),w("design:returntype",String)],P.prototype,"parseClientName",null);I([(0,x.Option)({flags:"--include-tags <tags>",description:"Regex patterns for tags to include (can be specified multiple times)"}),w("design:type",Function),w("design:paramtypes",[String,Array]),w("design:returntype",Array)],P.prototype,"parseIncludeTags",null);I([(0,x.Option)({flags:"--exclude-tags <tags>",description:"Regex patterns for tags to exclude (can be specified multiple times)"}),w("design:type",Function),w("design:paramtypes",[String,Array]),w("design:returntype",Array)],P.prototype,"parseExcludeTags",null);P=I([(0,pe.Injectable)(),(0,x.Command)({name:"generate",description:"Generate client SDKs from OpenAPI specifications",aliases:["gen"]}),w("design:type",Function),w("design:paramtypes",[typeof C>"u"?Object:C,typeof j>"u"?Object:j])],P);var fe=require("@nestjs/common"),K=require("nest-commander");function _e(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(_e,"_ts_decorate");function re(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(re,"_ts_metadata");var U=class o extends K.CommandRunner{static{f(this,"ValidateCommand")}openApiService;logger=new fe.Logger(o.name);constructor(e){super(),this.openApiService=e}async run(e,t){try{t.input||(this.logger.error("\u274C Error: --input is required"),process.exit(1)),this.logger.log(`Validating OpenAPI spec: ${t.input}`),await this.openApiService.validateDocument(t.input),this.logger.log("\u2705 OpenAPI spec is valid")}catch(r){let n=r instanceof Error?r.message:String(r);this.logger.error(`\u274C Invalid OpenAPI spec: ${n}`),r instanceof Error&&r.stack&&this.logger.error(r.stack),process.exit(1)}}parseInput(e){return e}};_e([(0,K.Option)({flags:"--input <path>",description:"OpenAPI spec file or URL (yaml/json)",required:!0}),re("design:type",Function),re("design:paramtypes",[String]),re("design:returntype",String)],U.prototype,"parseInput",null);U=_e([(0,fe.Injectable)(),(0,K.Command)({name:"validate",description:"Validate an OpenAPI spec"}),re("design:type",Function),re("design:paramtypes",[typeof R>"u"?Object:R])],U);var at=require("@nestjs/common");var Me=require("@nestjs/common");function xt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(xt,"_ts_decorate");var B=class{static{f(this,"OpenApiModule")}};B=xt([(0,Me.Module)({providers:[R],exports:[R]})],B);var ze=require("@nestjs/common");function jt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(jt,"_ts_decorate");var _=class{static{f(this,"ConfigModule")}};_=jt([(0,ze.Module)({providers:[j],exports:[j]})],_);var ue=require("@nestjs/common"),T=k(require("fs")),h=k(require("path")),d=k(require("handlebars"));var S=k(require("handlebars"));function Ue(){S.registerHelper("pascal",o=>v(o)),S.registerHelper("camel",o=>A(o)),S.registerHelper("kebab",o=>qe(o)),S.registerHelper("snake",o=>ee(o)),S.registerHelper("serviceName",o=>v(o)+"Service"),S.registerHelper("serviceProp",o=>A(o)),S.registerHelper("fileBase",o=>ee(o).toLowerCase()),S.registerHelper("eq",(o,e)=>o===e),S.registerHelper("ne",(o,e)=>o!==e),S.registerHelper("gt",(o,e)=>o>e),S.registerHelper("lt",(o,e)=>o<e),S.registerHelper("sub",(o,e)=>o-e),S.registerHelper("subtract",(o,e)=>o-e),S.registerHelper("len",o=>Array.isArray(o)?o.length:0),S.registerHelper("lte",(o,e)=>o<=e),S.registerHelper("or",function(...o){let e=o[o.length-1];return e&&"fn"in e&&e.fn?o.slice(0,-1).some(t=>t)?e.fn(this):e.inverse?.(this):o.slice(0,-1).some(t=>t)}),S.registerHelper("and",function(...o){let e=o[o.length-1];return e&&"fn"in e&&e.fn?o.slice(0,-1).every(t=>t)?e.fn(this):e.inverse?.(this):o.slice(0,-1).every(t=>t)}),S.registerHelper("replace",(o,e,t)=>typeof o!="string"?o:o.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),t)),S.registerHelper("index",(o,e)=>o?.[e]),S.registerHelper("getServiceName",o=>{let e=o.split(".");return e.length>1?e[1]:o}),S.registerHelper("groupByNamespace",o=>{let e={};for(let t of o){let r=t.tag.split(".");if(r.length===1)e[""]||(e[""]=[]),e[""]?.push(t);else{let n=r[0];n&&!e[n]&&(e[n]=[]),n&&e[n]?.push(t)}}return e}),S.registerHelper("getRootServices",o=>o.filter(e=>!e.tag.includes("."))),S.registerHelper("dict",()=>({})),S.registerHelper("setVar",(o,e,t)=>(t?.data?.root&&typeof t.data.root=="object"&&(t.data.root[`_${o}`]=e),"")),S.registerHelper("getVar",(o,e)=>e?.data?.root&&typeof e.data.root=="object"&&e.data.root[`_${o}`]||!1),S.registerHelper("set",(o,e,t)=>(o&&typeof o=="object"&&(o[e]=t),"")),S.registerHelper("hasKey",(o,e)=>o&&typeof o=="object"&&e in o),S.registerHelper("lookup",(o,e)=>o&&typeof o=="object"?o[e]:void 0),S.registerHelper("reMatch",(o,e)=>{try{return new RegExp(o).test(e)}catch{return!1}})}f(Ue,"registerCommonHandlebarsHelpers");function Rt(o){return o.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#x60;/g,"`").replace(/&#96;/g,"`").replace(/&amp;/g,"&")}f(Rt,"decodeHtmlEntities");function H(o,e,t,r=!1){let n;switch(o.kind){case l.String:o.format==="binary"?n="Blob":n="string";break;case l.Number:case l.Integer:n="number";break;case l.Boolean:n="boolean";break;case l.Null:n="null";break;case l.Ref:o.ref?e?.some(s=>s.type===o.ref)||r&&t&&t.find(i=>i.name===o.ref)?n=o.ref:n="Schema."+o.ref:n="unknown";break;case l.Array:if(o.items){let s=H(o.items,e,t);s.includes(" | ")||s.includes(" & ")?n=`(${s})[]`:n=`${s}[]`}else n="unknown[]";break;case l.OneOf:o.oneOf?n=o.oneOf.map(i=>H(i,e,t)).join(" | "):n="unknown";break;case l.AnyOf:o.anyOf?n=o.anyOf.map(i=>H(i,e,t)).join(" | "):n="unknown";break;case l.AllOf:o.allOf?n=o.allOf.map(i=>H(i,e,t)).join(" & "):n="unknown";break;case l.Enum:if(o.enumValues&&o.enumValues.length>0){let s=[];switch(o.enumBase){case l.Number:case l.Integer:for(let i of o.enumValues)s.push(i);break;case l.Boolean:for(let i of o.enumValues)i==="true"||i==="false"?s.push(i):s.push(`"${i}"`);break;default:for(let i of o.enumValues)s.push(`"${i}"`)}n=s.join(" | ")}else n="unknown";break;case l.Object:if(!o.properties||o.properties.length===0)n="Record<string, unknown>";else{let s=[];for(let i of o.properties){let a=H(i.type,e,t,r);i.required?s.push(`${i.name}: ${a}`):s.push(`${i.name}?: ${a}`)}n="{ "+s.join("; ")+" }"}break;default:n="unknown"}return o.nullable&&n!=="null"&&(n+=" | null"),Rt(n)}f(H,"schemaToTSType");function G(o){let e=o.path,t=e.includes("{")&&e.includes("}");if(o.operationID)return A(o.operationID);switch(o.method){case"GET":return t?"get":"list";case"POST":return"create";case"PUT":case"PATCH":return"update";case"DELETE":return"delete";default:return o.method.toLowerCase()}}f(G,"deriveMethodName");async function Le(o,e){if(o.operationIdParser)try{let r=await o.operationIdParser(e.operationID,e.method,e.path);if(r)return A(r)}catch{}let t=Ct(e.operationID);return t?A(t):G(e)}f(Le,"resolveMethodName");function Ct(o){if(!o)return"";let e=o.indexOf("Controller_");return e>=0?o.substring(e+11):o}f(Ct,"defaultParseOperationID");function Ge(o){let e=o.path,t="`";for(let r=0;r<e.length;r++){if(e[r]==="{"){let n=r+1;for(;n<e.length&&e[n]!=="}";)n++;if(n<e.length){let s=e.substring(r+1,n);t+=`\${encodeURIComponent(${s})}`,r=n;continue}}t+=e[r]}return t+="`",t}f(Ge,"buildPathTemplate");function we(o){let t=o.path.split("/"),r=[];for(let s of t)s!==""&&(s.startsWith("{")&&s.endsWith("}")||r.push(s));return`'${r.join("/")}'`}f(we,"buildQueryKeyBase");function ne(o){let e=[],t=new Map;for(let n=0;n<o.pathParams.length;n++){let s=o.pathParams[n];s&&t.set(s.name,n)}let r=o.path;for(let n=0;n<r.length;n++)if(r[n]==="{"){let s=n+1;for(;s<r.length&&r[s]!=="}";)s++;if(s<r.length){let i=r.substring(n+1,s),a=t.get(i);if(a!==void 0){let c=o.pathParams[a];c&&e.push(c)}n=s;continue}}return e}f(ne,"orderPathParams");function L(o,e,t,r=!1){return H(o,t,e,r)}f(L,"schemaToTSTypeWithSimpleTypes");function Te(o,e,t,r,n=!1){let s=[];for(let i of ne(o))s.push(`${i.name}: ${L(i.schema,t,r,n)}`);if(o.queryParams.length>0){let i=v(o.tag)+v(e)+"Query";s.push(`query?: Schema.${i}`)}if(o.requestBody){let i=o.requestBody.required===!0?"":"?";s.push(`body${i}: ${L(o.requestBody.schema,t,r,n)}`)}return s.push('init?: Omit<RequestInit, "method" | "body">'),s}f(Te,"buildMethodSignature");function We(o,e){if(!e||e.length===0)return[];let t=new Set,r=f(s=>{let i=o.find(a=>a.name===s);return i?i.schema:null},"resolveRef"),n=f(s=>{if(s.kind==="ref"&&s.ref)if(e.some(a=>a.type===s.ref))t.add(s.ref);else{let a=r(s.ref);a&&n(a)}else if(s.kind==="array"&&s.items)n(s.items);else if(s.kind==="object"&&s.properties)for(let i of s.properties)n(i.type);else if(s.kind==="oneOf"&&s.oneOf)for(let i of s.oneOf)n(i);else if(s.kind==="anyOf"&&s.anyOf)for(let i of s.anyOf)n(i);else if(s.kind==="allOf"&&s.allOf)for(let i of s.allOf)n(i)},"checkSchema");for(let s of o)n(s.schema);return e.filter(s=>t.has(s.type))}f(We,"collectPredefinedTypesUsedInSchema");function Ke(o,e,t){if(!e||e.length===0)return[];let r=new Set,n=f(i=>{if(!t)return null;let a=t.find(c=>c.name===i);return a?a.schema:null},"resolveRef"),s=f(i=>{if(i.kind==="ref"&&i.ref)if(e.some(c=>c.type===i.ref))r.add(i.ref);else{let c=n(i.ref);c&&s(c)}else if(i.kind==="array"&&i.items)s(i.items);else if(i.kind==="object"&&i.properties)for(let a of i.properties)s(a.type);else if(i.kind==="oneOf"&&i.oneOf)for(let a of i.oneOf)s(a);else if(i.kind==="anyOf"&&i.anyOf)for(let a of i.anyOf)s(a);else if(i.kind==="allOf"&&i.allOf)for(let a of i.allOf)s(a)},"checkSchema");for(let i of o.operations)for(let a of i.pathParams)s(a.schema);return e.filter(i=>r.has(i.type))}f(Ke,"collectPredefinedTypesUsedInService");function Ve(o){let e=[];for(let t of ne(o))e.push(t.name);return o.queryParams.length>0&&e.push("query"),o.requestBody&&e.push("body"),e}f(Ve,"queryKeyArgs");function Ze(o,e,t,r,n=!1){let s=we(o),i=[];for(let m of ne(o)){let b=L(m.schema,t,r,n);i.push(b)}let a=o.queryParams.length>0,c=o.requestBody&&!o.requestBody.required,p=o.requestBody&&o.requestBody.required,u=f(m=>`readonly [${[s,...m].join(", ")}]`,"buildTuple");if(!a&&!c){if(p){if(!o.requestBody?.schema)throw new Error("Request body schema is required");let m=L(o.requestBody.schema,t,r,n);return u([...i,m])}return u(i)}let y=[];if(a&&c){let m=`Schema.${v(o.tag)}${v(e)}Query`,b=L(o.requestBody.schema,t,r,n);y.push(u(i)),y.push(u([...i,m])),y.push(u([...i,b])),y.push(u([...i,m,b]))}else if(a){let m=`Schema.${v(o.tag)}${v(e)}Query`;if(p){if(!o.requestBody?.schema)throw new Error("Request body schema is required");let b=L(o.requestBody.schema,t,r,n);y.push(u([...i,b])),y.push(u([...i,b,m]))}else y.push(u(i)),y.push(u([...i,m]))}else if(c){if(!o.requestBody?.schema)throw new Error("Request body schema is required");let m=L(o.requestBody.schema,t,r,n);y.push(u(i)),y.push(u([...i,m]))}return y.join(" | ")}f(Ze,"buildQueryKeyReturnType");function Oe(o){return o.queryParams.length>0||o.requestBody!==null&&!o.requestBody.required}f(Oe,"hasOptionalQueryKeyParams");function le(o){let e=!1;for(let r of o)if(!(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="_"||r==="$")){e=!0;break}let t=o[0];return t&&t>="0"&&t<="9"&&(e=!0),e?`"${o}"`:o}f(le,"quoteTSPropertyName");function M(o,e=new Set){let t=new Set;if(o.kind==="ref"&&o.ref){let r=o.ref;e.has(r)||(e.add(r),t.add(r))}else if(o.kind==="array"&&o.items)M(o.items,e).forEach(n=>t.add(n));else if(o.kind==="object"&&o.properties){for(let r of o.properties)M(r.type,e).forEach(s=>t.add(s));o.additionalProperties&&M(o.additionalProperties,e).forEach(n=>t.add(n))}else if(o.kind==="oneOf"&&o.oneOf)for(let r of o.oneOf)M(r,e).forEach(s=>t.add(s));else if(o.kind==="anyOf"&&o.anyOf)for(let r of o.anyOf)M(r,e).forEach(s=>t.add(s));else if(o.kind==="allOf"&&o.allOf)for(let r of o.allOf)M(r,e).forEach(s=>t.add(s));else o.kind==="not"&&o.not&&M(o.not,e).forEach(n=>t.add(n));return t}f(M,"extractRefDependencies");function Qe(o){let e=new Map;for(let i of o)e.set(i.name,i);let t=new Map;for(let i of o){let a=M(i.schema),c=new Set;for(let p of a)e.has(p)&&c.add(p);t.set(i.name,c)}let r=[],n=new Map,s=[];for(let i of o)n.set(i.name,t.get(i.name)?.size||0),n.get(i.name)===0&&s.push(i.name);for(;s.length>0;){let i=s.shift();if(!i)continue;let a=e.get(i);a&&r.push(a);for(let c of o)if(t.get(c.name)?.has(i)){let u=(n.get(c.name)||0)-1;n.set(c.name,u),u===0&&s.push(c.name)}}if(r.length<o.length){let i=new Set(r.map(a=>a.name));for(let a of o)i.has(a.name)||r.push(a)}return r}f(Qe,"sortModelDefsByDependencies");function Je(o){return o.response.isStreaming===!0}f(Je,"isStreamingOperation");function Ye(o){let e=o.response.schema;return e.kind===l.Array&&e.items?H(e.items):o.response.streamingFormat==="sse"?"string":H(e)}f(Ye,"getStreamingItemType");function F(o,e="",t,r=!1){let n=e+" ",s;switch(o.kind){case l.String:s="z.string()",o.format==="date"||o.format==="date-time"?s="z.iso.datetime()":o.format==="email"?s="z.email()":o.format==="uri"||o.format==="url"?s="z.url()":o.format==="uuid"&&(s="z.uuid()");break;case l.Number:s="z.number()";break;case l.Integer:s="z.number().int()";break;case l.Boolean:s="z.boolean()";break;case l.Null:s="z.null()";break;case l.Ref:o.ref?s=r?`${o.ref}Schema`:`Schema.${o.ref}Schema`:s="z.unknown()";break;case l.Array:o.items?s=`${F(o.items,n,t,r)}.array()`:s="z.unknown().array()";break;case l.Object:if(!o.properties||o.properties.length===0)o.additionalProperties?s=`z.record(z.string(), ${F(o.additionalProperties,n,t,r)})`:s="z.record(z.string(), z.unknown())";else{let i=[];for(let c of o.properties){let p=F(c.type,n,t,r),u=le(c.name);c.required?i.push(`${n}${u}: ${p}`):i.push(`${n}${u}: ${p}.optional()`)}let a=`z.object({
3
3
  ${i.join(`,
4
4
  `)}
5
- ${e}})`;if(o.additionalProperties){let c=F(o.additionalProperties,n,t,r);s=`${a}.catchall(${c})`}else s=a}break;case l.Enum:o.enumValues&&o.enumValues.length>0?s=`z.enum([${o.enumValues.map(a=>a==="true"||a==="false"||/^-?[0-9]+(\.[0-9]+)?$/.test(a)?a:JSON.stringify(a)).join(", ")}])`:s="z.string()";break;case l.OneOf:o.oneOf&&o.oneOf.length>0?s=`z.union([${o.oneOf.map(a=>F(a,n,t,r)).join(", ")}])`:s="z.unknown()";break;case l.AnyOf:o.anyOf&&o.anyOf.length>0?s=`z.union([${o.anyOf.map(a=>F(a,n,t,r)).join(", ")}])`:s="z.unknown()";break;case l.AllOf:if(o.allOf&&o.allOf.length>0){let i=o.allOf.map(a=>F(a,n,t,r));s=i.join(".and(")+")".repeat(i.length-1)}else s="z.unknown()";break;default:s="z.unknown()"}return o.nullable&&s!=="z.null()"&&(s=`${s}.nullable()`),s}f(F,"schemaToZodSchema");var et=require("child_process"),tt=require("util"),rt=k(require("path")),nt=k(require("fs"));var Xe=(0,tt.promisify)(et.exec);async function st(o,e,t){let r=t||console;try{try{await Xe("npx --yes prettier --version",{cwd:o,maxBuffer:10*1024*1024})}catch{r.warn?.("Prettier is not available. Skipping code formatting. Install prettier to enable formatting.");return}let n=[];for(let a of e)if(a.endsWith(".ts")||a.endsWith(".tsx")){let c=rt.join(o,a);nt.existsSync(c)&&n.push(a)}if(n.length===0){r.debug?.("No TypeScript files to format.");return}let s=n.map(a=>`"${a.replace(/\\/g,"/")}"`).join(" "),{stderr:i}=await Xe(`npx --yes prettier --write --log-level=error ${s}`,{cwd:o,maxBuffer:10*1024*1024});i&&!i.includes("warning")&&r.warn?.(i)}catch(n){let s=n instanceof Error?n.message:String(n);r.warn?.(`Failed to format code with Prettier: ${s}. Generated code will not be formatted.`)}}f(st,"formatWithPrettier");function Ht(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(Ht,"_ts_decorate");function ot(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(ot,"_ts_metadata");var z=class o{static{f(this,"TypeScriptGeneratorService")}configService;logger=new ue.Logger(o.name);constructor(e){this.configService=e}getType(){return"typescript"}async generate(e,t){if(!e.defaultBaseURL&&t.openApiDocument){let u=t.openApiDocument.servers;Array.isArray(u)&&u.length>0&&(e.defaultBaseURL=u[0]?.url||"")}e.srcDir||(e.srcDir="src");let r=e.srcDir,n=h.join(e.outDir,r),s=h.join(n,"services");await T.promises.mkdir(s,{recursive:!0});let i=await this.preprocessIR(e,t);this.registerHandlebarsHelpers(e);let a=[];a.push(...await this.generateClient(e,i,n)),a.push(...await this.generateAuthStrategies(e,i,n)),a.push(...await this.generateIndex(e,i,n)),a.push(...await this.generateUtils(e,i,n)),a.push(...await this.generateServices(e,i,s)),a.push(...await this.generateSchema(e,i,n)),a.push(...await this.generateZodSchema(e,i,n)),await this.generatePackageJson(e),await this.generateTsConfig(e),a.push(...await this.generateTsupConfig(e)),await this.generateReadme(e,i),e.formatCode!==!1?(await this.generatePrettierConfig(e),this.logger.debug("Formatting generated TypeScript files with Prettier...",e.packageName),await st(e.outDir,a,this.logger)):this.logger.debug("Code formatting is disabled for this client.",e.packageName)}async preprocessIR(e,t){let r=await Promise.all(t.services.map(async n=>({...n,operations:await Promise.all(n.operations.map(async s=>{let i=await Le(e,s);return{...s,_resolvedMethodName:i}}))})));return{...t,services:r}}registerHandlebarsHelpers(e){Ue(),d.registerHelper("methodName",t=>t._resolvedMethodName||G(t)),d.registerHelper("queryTypeName",t=>{let r=t._resolvedMethodName||G(t);return v(t.tag)+v(r)+"Query"}),d.registerHelper("pathTemplate",t=>{let r=Ge(t);return new d.SafeString(r)}),d.registerHelper("queryKeyBase",t=>{let r=we(t);return new d.SafeString(r)}),d.registerHelper("pathParamsInOrder",t=>ne(t)),d.registerHelper("methodSignature",(t,r)=>{let n=t._resolvedMethodName||G(t),s=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.PredefinedTypes||[],a=r?.data?.root?.isSameFile||!1;return Te(t,n,s,i,a).map(p=>new d.SafeString(p))}),d.registerHelper("methodSignatureNoInit",(t,r)=>{let n=t._resolvedMethodName||G(t),s=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.PredefinedTypes||[],a=r?.data?.root?.isSameFile||!1;return Te(t,n,s,i,a).slice(0,-1)}),d.registerHelper("queryKeyArgs",t=>Ve(t).map(n=>new d.SafeString(n))),d.registerHelper("queryKeyReturnType",(t,r)=>{let n=t._resolvedMethodName||G(t),s=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.PredefinedTypes||[],a=r?.data?.root?.isSameFile||!1,c=Ze(t,n,s,i,a);return new d.SafeString(c)}),d.registerHelper("hasOptionalQueryKeyParams",t=>Oe(t)),d.registerHelper("hasAnyOptionalQueryKeyParams",t=>t.operations.some(r=>Oe(r))),d.registerHelper("tsType",(t,r)=>{if(t&&typeof t=="object"&&"kind"in t){let n=r?.data?.root?.PredefinedTypes||[],s=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.isSameFile||!1;return H(t,n,s,i)}return"unknown"}),d.registerHelper("stripSchemaNs",t=>t.replace(/^Schema\./,"")),d.registerHelper("tsTypeStripNs",(t,r)=>{let n=r?.data?.root?.PredefinedTypes||[],s=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.isSameFile||!1;if(t&&typeof t=="object"&&"kind"in t){let c=H(t,n,s,i).replace(/Schema\./g,"");return new d.SafeString(c)}if(typeof t=="string"){if(t.startsWith("Schema.")){let a=t.replace(/^Schema\./,"");return n.find(p=>p.type===a)?new d.SafeString(a):new d.SafeString(a)}return new d.SafeString(t)}return"unknown"}),d.registerHelper("isPredefinedType",(t,r)=>(r?.data?.root?.PredefinedTypes||[]).some(s=>s.type===t)),d.registerHelper("getPredefinedType",(t,r)=>(r?.data?.root?.PredefinedTypes||[]).find(s=>s.type===t)),d.registerHelper("groupByPackage",t=>{let r={};for(let n of t||[])r[n.package]||(r[n.package]={package:n.package,types:[]}),r[n.package]?.types.push(n.type);return Object.values(r)}),d.registerHelper("getServicePredefinedTypes",(t,r)=>{let n=r?.data?.root?.PredefinedTypes||[],s=r?.data?.root?.IR?.modelDefs||[];return Ke(t,n,s)}),d.registerHelper("getSchemaPredefinedTypes",t=>{let r=t?.data?.root?.PredefinedTypes||[],n=t?.data?.root?.IR?.modelDefs||[];return We(n,r)}),d.registerHelper("joinTypes",t=>t.join(", ")),d.registerHelper("uniquePackages",t=>{let r=new Set;for(let n of t||[])n.package&&r.add(n.package);return Array.from(r)}),d.registerHelper("isPredefinedPackage",(t,r)=>r?r.some(n=>n.package===t):!1),d.registerHelper("getAllDependencies",t=>{let r={"@blimu/fetch":"^0.4.0",zod:"^4.3.5"};if(t.predefinedTypes)for(let n of t.predefinedTypes)n.package&&!r[n.package]&&(r[n.package]=t.dependencies?.[n.package]||"*");if(t.dependencies)for(let[n,s]of Object.entries(t.dependencies))n!=="zod"&&!r[n]&&(r[n]=s);return r}),d.registerHelper("decodeHtml",t=>{if(typeof t!="string")return t;let r=t.replace(/&amp;#x60;/g,"&#x60;").replace(/&amp;#96;/g,"&#96;").replace(/&amp;quot;/g,"&quot;").replace(/&amp;lt;/g,"&lt;").replace(/&amp;gt;/g,"&gt;");return r=r.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#x60;/g,"`").replace(/&#96;/g,"`").replace(/&amp;/g,"&"),new d.SafeString(r)}),d.registerHelper("quotePropName",t=>le(t)),d.registerHelper("zodSchema",(t,r)=>{if(t&&typeof t=="object"&&"kind"in t){let n=r?.data?.root?.IR?.modelDefs||[],s=r?.data?.root?._templateName==="schema.zod.ts.hbs";return new d.SafeString(F(t,"",n,s))}return"z.unknown()"}),d.registerHelper("isStreaming",t=>Je(t)),d.registerHelper("hasBearerScheme",t=>Array.isArray(t)?t.some(r=>r.type==="http"&&r.scheme==="bearer"):!1),d.registerHelper("hasApiKeyScheme",t=>Array.isArray(t)?t.some(r=>r.type==="apiKey"):!1),d.registerHelper("serviceUsesSchema",t=>!t||!t.operations||!Array.isArray(t.operations)?!1:t.operations.some(r=>{if(r.response?.schema){let n=r.response.schema;if(n.kind==="ref"||n.kind==="object"||n.kind==="array"||n.kind==="oneOf"||n.kind==="anyOf"||n.kind==="allOf")return!0}if(r.requestBody?.schema){let n=r.requestBody.schema;if(n.kind==="ref"||n.kind==="object"||n.kind==="array"||n.kind==="oneOf"||n.kind==="anyOf"||n.kind==="allOf")return!0}return!!(r.queryParams&&r.queryParams.length>0)})),d.registerHelper("streamingItemType",t=>new d.SafeString(Ye(t)))}async renderTemplate(e,t,r,n){let s=n.templates?.[e];if(s){this.logger.debug(`Using template override for ${e}: ${s}`);try{await T.promises.access(s,T.constants.R_OK);let b=await T.promises.readFile(s,"utf-8"),$=d.compile(b),Q={...t,_templateName:e},W=$(Q);await T.promises.writeFile(r,W,"utf-8");return}catch(b){let $=b instanceof Error?b.message:String(b);throw this.logger.error(`Template override file not found or not readable: ${s}. Error: ${$}`),new Error(`Template override file not found or not readable: ${s}`)}}let i=[h.join(__dirname,"generator/typescript/templates",e),h.join(__dirname,"templates",e),h.join(__dirname,"../typescript/templates",e),h.join(process.cwd(),"src/generator/typescript/templates",e),h.join(process.cwd(),"packages/codegen/src/generator/typescript/templates",e)],a=null;for(let b of i)try{await T.promises.access(b),a=b;break}catch{this.logger.debug(`Template not found at: ${b}`)}if(!a)throw this.logger.error(`Template not found: ${e}`),this.logger.error(`Checked paths: ${i.join(", ")}`),this.logger.error(`__dirname: ${__dirname}`),new Error(`Template not found: ${e}`);let c=await T.promises.readFile(a,"utf-8"),p=d.compile(c),u={...t,_templateName:e},y=p(u),m=h.dirname(r);await T.promises.mkdir(m,{recursive:!0}),await T.promises.writeFile(r,y,"utf-8")}async generateClient(e,t,r){let n=h.join(r,"client.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{return await this.renderTemplate("client.ts.hbs",{Client:e,IR:t},n,e),[h.relative(e.outDir,n)]}catch(s){let i=s instanceof Error?s.message:String(s);return this.logger.warn(`Template client.ts.hbs not found: ${i}, using placeholder`),await T.promises.writeFile(n,"// Generated client - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generateAuthStrategies(e,t,r){let n=h.join(r,"auth-strategies.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{return await this.renderTemplate("auth-strategies.ts.hbs",{Client:e,IR:t},n,e),[h.relative(e.outDir,n)]}catch{return this.logger.warn("Template auth-strategies.ts.hbs not found, using placeholder"),await T.promises.writeFile(n,"// Generated auth-strategies - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generateIndex(e,t,r){let n=h.join(r,"index.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{return await T.promises.access(n),this.logger.debug(`index.ts already exists at ${n}, skipping generation to preserve customizations`),[]}catch{}try{return await this.renderTemplate("index.ts.hbs",{Client:e,IR:t},n,e),[h.relative(e.outDir,n)]}catch{return this.logger.warn("Template index.ts.hbs not found, using placeholder"),await T.promises.writeFile(n,"// Generated index - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generateUtils(e,t,r){let n=h.join(r,"utils.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{return await this.renderTemplate("utils.ts.hbs",{Client:e,IR:t},n,e),[h.relative(e.outDir,n)]}catch{return this.logger.warn("Template utils.ts.hbs not found, using placeholder"),await T.promises.writeFile(n,"// Generated utils - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generateServices(e,t,r){let n=[];for(let s of t.services){let i=h.join(r,`${ee(s.tag).toLowerCase()}.ts`);if(!this.configService.shouldExcludeFile(e,i))try{await this.renderTemplate("service.ts.hbs",{Client:e,Service:s,IR:t,PredefinedTypes:e.predefinedTypes||[],isSameFile:!1},i,e),n.push(h.relative(e.outDir,i))}catch{this.logger.warn("Template service.ts.hbs not found, using placeholder");let a=`// Generated service ${s.tag} - template rendering to be implemented`;await T.promises.writeFile(i,a,"utf-8"),n.push(h.relative(e.outDir,i))}}return n}async generateSchema(e,t,r){let n=h.join(r,"schema.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{return await this.renderTemplate("schema.ts.hbs",{Client:e,IR:t,PredefinedTypes:e.predefinedTypes||[],isSameFile:!0},n,e),[h.relative(e.outDir,n)]}catch(s){let i=s instanceof Error?s.message:String(s);return this.logger.warn(`Template schema.ts.hbs error: ${i}, using placeholder`),await T.promises.writeFile(n,"// Generated schema - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generateZodSchema(e,t,r){let n=h.join(r,"schema.zod.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{let s=Qe(t.modelDefs),i={...t,modelDefs:s};return await this.renderTemplate("schema.zod.ts.hbs",{Client:e,IR:i},n,e),[h.relative(e.outDir,n)]}catch(s){let i=s instanceof Error?s.message:String(s);return this.logger.warn(`Template schema.zod.ts.hbs error: ${i}, using placeholder`),await T.promises.writeFile(n,"// Generated Zod schemas - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generatePackageJson(e){let t=h.join(e.outDir,"package.json");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate("package.json.hbs",{Client:e},t,e)}catch{this.logger.warn("Template package.json.hbs not found, using fallback");let r=JSON.stringify({name:e.packageName,version:"0.0.1",main:"dist/index.js",types:"dist/index.d.ts"},null,2);await T.promises.writeFile(t,r,"utf-8")}}async generateTsConfig(e){let t=h.join(e.outDir,"tsconfig.json");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate("tsconfig.json.hbs",{Client:e},t,e)}catch{this.logger.warn("Template tsconfig.json.hbs not found, using fallback");let r=e.srcDir||"src",n=JSON.stringify({compilerOptions:{target:"ES2020",module:"commonjs",lib:["ES2020"],declaration:!0,outDir:"./dist",rootDir:`./${r}`,strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0},include:[`${r}/**/*`]},null,2),s=h.dirname(t);await T.promises.mkdir(s,{recursive:!0}),await T.promises.writeFile(t,n,"utf-8")}}async generateTsupConfig(e){let t=h.join(e.outDir,"tsup.config.ts");if(this.configService.shouldExcludeFile(e,t))return[];try{await this.renderTemplate("tsup.config.ts.hbs",{Client:e},t,e)}catch{this.logger.warn("Template tsup.config.ts.hbs not found, using fallback");let n=`import { defineConfig } from "tsup";
5
+ ${e}})`;if(o.additionalProperties){let c=F(o.additionalProperties,n,t,r);s=`${a}.catchall(${c})`}else s=a}break;case l.Enum:o.enumValues&&o.enumValues.length>0?s=`z.enum([${o.enumValues.map(a=>a==="true"||a==="false"||/^-?[0-9]+(\.[0-9]+)?$/.test(a)?a:JSON.stringify(a)).join(", ")}])`:s="z.string()";break;case l.OneOf:o.oneOf&&o.oneOf.length>0?s=`z.union([${o.oneOf.map(a=>F(a,n,t,r)).join(", ")}])`:s="z.unknown()";break;case l.AnyOf:o.anyOf&&o.anyOf.length>0?s=`z.union([${o.anyOf.map(a=>F(a,n,t,r)).join(", ")}])`:s="z.unknown()";break;case l.AllOf:if(o.allOf&&o.allOf.length>0){let i=o.allOf.map(a=>F(a,n,t,r));s=i.join(".and(")+")".repeat(i.length-1)}else s="z.unknown()";break;default:s="z.unknown()"}return o.nullable&&s!=="z.null()"&&(s=`${s}.nullable()`),s}f(F,"schemaToZodSchema");var et=require("child_process"),tt=require("util"),rt=k(require("path")),nt=k(require("fs"));var Xe=(0,tt.promisify)(et.exec);async function st(o,e,t){let r=t||console;try{try{await Xe("npx --yes prettier --version",{cwd:o,maxBuffer:10*1024*1024})}catch{r.warn?.("Prettier is not available. Skipping code formatting. Install prettier to enable formatting.");return}let n=[];for(let a of e)if(a.endsWith(".ts")||a.endsWith(".tsx")){let c=rt.join(o,a);nt.existsSync(c)&&n.push(a)}if(n.length===0){r.debug?.("No TypeScript files to format.");return}let s=n.map(a=>`"${a.replace(/\\/g,"/")}"`).join(" "),{stderr:i}=await Xe(`npx --yes prettier --write --log-level=error ${s}`,{cwd:o,maxBuffer:10*1024*1024});i&&!i.includes("warning")&&r.warn?.(i)}catch(n){let s=n instanceof Error?n.message:String(n);r.warn?.(`Failed to format code with Prettier: ${s}. Generated code will not be formatted.`)}}f(st,"formatWithPrettier");function Ht(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(Ht,"_ts_decorate");function ot(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(ot,"_ts_metadata");var z=class o{static{f(this,"TypeScriptGeneratorService")}configService;logger=new ue.Logger(o.name);constructor(e){this.configService=e}getType(){return"typescript"}async generate(e,t){if(!e.defaultBaseURL&&t.openApiDocument){let u=t.openApiDocument.servers;Array.isArray(u)&&u.length>0&&(e.defaultBaseURL=u[0]?.url||"")}e.srcDir||(e.srcDir="src");let r=e.srcDir,n=h.join(e.outDir,r),s=h.join(n,"services");await T.promises.mkdir(s,{recursive:!0});let i=await this.preprocessIR(e,t);this.registerHandlebarsHelpers(e);let a=[];a.push(...await this.generateClient(e,i,n)),a.push(...await this.generateAuthStrategies(e,i,n)),a.push(...await this.generateIndex(e,i,n)),a.push(...await this.generateUtils(e,i,n)),a.push(...await this.generateServices(e,i,s)),a.push(...await this.generateSchema(e,i,n)),a.push(...await this.generateZodSchema(e,i,n)),await this.generatePackageJson(e),await this.generateTsConfig(e),a.push(...await this.generateTsupConfig(e)),await this.generateReadme(e,i),e.formatCode!==!1?(await this.generatePrettierConfig(e),this.logger.debug("Formatting generated TypeScript files with Prettier...",e.packageName),await st(e.outDir,a,this.logger)):this.logger.debug("Code formatting is disabled for this client.",e.packageName)}async preprocessIR(e,t){let r=await Promise.all(t.services.map(async n=>({...n,operations:await Promise.all(n.operations.map(async s=>{let i=await Le(e,s);return{...s,_resolvedMethodName:i}}))})));return{...t,services:r}}registerHandlebarsHelpers(e){Ue(),d.registerHelper("methodName",t=>t._resolvedMethodName||G(t)),d.registerHelper("queryTypeName",t=>{let r=t._resolvedMethodName||G(t);return v(t.tag)+v(r)+"Query"}),d.registerHelper("pathTemplate",t=>{let r=Ge(t);return new d.SafeString(r)}),d.registerHelper("queryKeyBase",t=>{let r=we(t);return new d.SafeString(r)}),d.registerHelper("pathParamsInOrder",t=>ne(t)),d.registerHelper("methodSignature",(t,r)=>{let n=t._resolvedMethodName||G(t),s=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.PredefinedTypes||[],a=r?.data?.root?.isSameFile||!1;return Te(t,n,s,i,a).map(p=>new d.SafeString(p))}),d.registerHelper("methodSignatureNoInit",(t,r)=>{let n=t._resolvedMethodName||G(t),s=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.PredefinedTypes||[],a=r?.data?.root?.isSameFile||!1;return Te(t,n,s,i,a).slice(0,-1)}),d.registerHelper("queryKeyArgs",t=>Ve(t).map(n=>new d.SafeString(n))),d.registerHelper("queryKeyReturnType",(t,r)=>{let n=t._resolvedMethodName||G(t),s=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.PredefinedTypes||[],a=r?.data?.root?.isSameFile||!1,c=Ze(t,n,s,i,a);return new d.SafeString(c)}),d.registerHelper("hasOptionalQueryKeyParams",t=>Oe(t)),d.registerHelper("hasAnyOptionalQueryKeyParams",t=>t.operations.some(r=>Oe(r))),d.registerHelper("tsType",(t,r)=>{if(t&&typeof t=="object"&&"kind"in t){let n=r?.data?.root?.PredefinedTypes||[],s=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.isSameFile||!1;return H(t,n,s,i)}return"unknown"}),d.registerHelper("stripSchemaNs",t=>t.replace(/^Schema\./,"")),d.registerHelper("tsTypeStripNs",(t,r)=>{let n=r?.data?.root?.PredefinedTypes||[],s=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.isSameFile||!1;if(t&&typeof t=="object"&&"kind"in t){let c=H(t,n,s,i).replace(/Schema\./g,"");return new d.SafeString(c)}if(typeof t=="string"){if(t.startsWith("Schema.")){let a=t.replace(/^Schema\./,"");return n.find(p=>p.type===a)?new d.SafeString(a):new d.SafeString(a)}return new d.SafeString(t)}return"unknown"}),d.registerHelper("isPredefinedType",(t,r)=>(r?.data?.root?.PredefinedTypes||[]).some(s=>s.type===t)),d.registerHelper("getPredefinedType",(t,r)=>(r?.data?.root?.PredefinedTypes||[]).find(s=>s.type===t)),d.registerHelper("groupByPackage",t=>{let r={};for(let n of t||[])r[n.package]||(r[n.package]={package:n.package,types:[]}),r[n.package]?.types.push(n.type);return Object.values(r)}),d.registerHelper("getServicePredefinedTypes",(t,r)=>{let n=r?.data?.root?.PredefinedTypes||[],s=r?.data?.root?.IR?.modelDefs||[];return Ke(t,n,s)}),d.registerHelper("getSchemaPredefinedTypes",t=>{let r=t?.data?.root?.PredefinedTypes||[],n=t?.data?.root?.IR?.modelDefs||[];return We(n,r)}),d.registerHelper("joinTypes",t=>t.join(", ")),d.registerHelper("uniquePackages",t=>{let r=new Set;for(let n of t||[])n.package&&r.add(n.package);return Array.from(r)}),d.registerHelper("isPredefinedPackage",(t,r)=>r?r.some(n=>n.package===t):!1),d.registerHelper("getAllDependencies",t=>{let r={"@blimu/fetch":"^0.4.0",zod:"^4.3.5"};if(t.predefinedTypes)for(let n of t.predefinedTypes)n.package&&!r[n.package]&&(r[n.package]=t.dependencies?.[n.package]||"*");if(t.dependencies)for(let[n,s]of Object.entries(t.dependencies))n!=="zod"&&!r[n]&&(r[n]=s);return r}),d.registerHelper("decodeHtml",t=>{if(typeof t!="string")return t;let r=t.replace(/&amp;#x60;/g,"&#x60;").replace(/&amp;#96;/g,"&#96;").replace(/&amp;quot;/g,"&quot;").replace(/&amp;lt;/g,"&lt;").replace(/&amp;gt;/g,"&gt;");return r=r.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#x60;/g,"`").replace(/&#96;/g,"`").replace(/&amp;/g,"&"),new d.SafeString(r)}),d.registerHelper("quotePropName",t=>le(t)),d.registerHelper("zodSchema",(t,r)=>{if(t&&typeof t=="object"&&"kind"in t){let n=r?.data?.root?.IR?.modelDefs||[],s=r?.data?.root?._templateName==="schema.zod.ts.hbs";return new d.SafeString(F(t,"",n,s))}return"z.unknown()"}),d.registerHelper("isStreaming",t=>Je(t)),d.registerHelper("hasBearerScheme",t=>Array.isArray(t)?t.some(r=>r.type==="http"&&r.scheme==="bearer"):!1),d.registerHelper("hasApiKeyScheme",t=>Array.isArray(t)?t.some(r=>r.type==="apiKey"):!1),d.registerHelper("serviceUsesSchema",t=>!t||!t.operations||!Array.isArray(t.operations)?!1:t.operations.some(r=>{if(r.response?.schema){let n=r.response.schema;if(n.kind==="ref"||n.kind==="object"||n.kind==="array"||n.kind==="oneOf"||n.kind==="anyOf"||n.kind==="allOf")return!0}if(r.requestBody?.schema){let n=r.requestBody.schema;if(n.kind==="ref"||n.kind==="object"||n.kind==="array"||n.kind==="oneOf"||n.kind==="anyOf"||n.kind==="allOf")return!0}return!!(r.queryParams&&r.queryParams.length>0)})),d.registerHelper("streamingItemType",t=>new d.SafeString(Ye(t)))}async renderTemplate(e,t,r,n){let s=n.templates?.[e];if(s){this.logger.debug(`Using template override for ${e}: ${s}`);try{await T.promises.access(s,T.constants.R_OK);let b=await T.promises.readFile(s,"utf-8"),D=d.compile(b),Q={...t,_templateName:e},W=D(Q);await T.promises.writeFile(r,W,"utf-8");return}catch(b){let D=b instanceof Error?b.message:String(b);throw this.logger.error(`Template override file not found or not readable: ${s}. Error: ${D}`),new Error(`Template override file not found or not readable: ${s}`)}}let i=[h.join(__dirname,"generator/typescript/templates",e),h.join(__dirname,"templates",e),h.join(__dirname,"../typescript/templates",e),h.join(process.cwd(),"src/generator/typescript/templates",e),h.join(process.cwd(),"packages/codegen/src/generator/typescript/templates",e)],a=null;for(let b of i)try{await T.promises.access(b),a=b;break}catch{}if(!a)throw this.logger.error(`Template not found: ${e}`),this.logger.error(`Checked paths: ${i.join(", ")}`),this.logger.error(`__dirname: ${__dirname}`),new Error(`Template not found: ${e}`);let c=await T.promises.readFile(a,"utf-8"),p=d.compile(c),u={...t,_templateName:e},y=p(u),m=h.dirname(r);await T.promises.mkdir(m,{recursive:!0}),await T.promises.writeFile(r,y,"utf-8")}async generateClient(e,t,r){let n=h.join(r,"client.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{return await this.renderTemplate("client.ts.hbs",{Client:e,IR:t},n,e),[h.relative(e.outDir,n)]}catch(s){let i=s instanceof Error?s.message:String(s);return this.logger.warn(`Template client.ts.hbs not found: ${i}, using placeholder`),await T.promises.writeFile(n,"// Generated client - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generateAuthStrategies(e,t,r){let n=h.join(r,"auth-strategies.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{return await this.renderTemplate("auth-strategies.ts.hbs",{Client:e,IR:t},n,e),[h.relative(e.outDir,n)]}catch{return this.logger.warn("Template auth-strategies.ts.hbs not found, using placeholder"),await T.promises.writeFile(n,"// Generated auth-strategies - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generateIndex(e,t,r){let n=h.join(r,"index.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{return await T.promises.access(n),this.logger.debug(`index.ts already exists at ${n}, skipping generation to preserve customizations`),[]}catch{}try{return await this.renderTemplate("index.ts.hbs",{Client:e,IR:t},n,e),[h.relative(e.outDir,n)]}catch{return this.logger.warn("Template index.ts.hbs not found, using placeholder"),await T.promises.writeFile(n,"// Generated index - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generateUtils(e,t,r){let n=h.join(r,"utils.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{return await this.renderTemplate("utils.ts.hbs",{Client:e,IR:t},n,e),[h.relative(e.outDir,n)]}catch{return this.logger.warn("Template utils.ts.hbs not found, using placeholder"),await T.promises.writeFile(n,"// Generated utils - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generateServices(e,t,r){let n=[];for(let s of t.services){let i=h.join(r,`${ee(s.tag).toLowerCase()}.ts`);if(!this.configService.shouldExcludeFile(e,i))try{await this.renderTemplate("service.ts.hbs",{Client:e,Service:s,IR:t,PredefinedTypes:e.predefinedTypes||[],isSameFile:!1},i,e),n.push(h.relative(e.outDir,i))}catch{this.logger.warn("Template service.ts.hbs not found, using placeholder");let a=`// Generated service ${s.tag} - template rendering to be implemented`;await T.promises.writeFile(i,a,"utf-8"),n.push(h.relative(e.outDir,i))}}return n}async generateSchema(e,t,r){let n=h.join(r,"schema.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{return await this.renderTemplate("schema.ts.hbs",{Client:e,IR:t,PredefinedTypes:e.predefinedTypes||[],isSameFile:!0},n,e),[h.relative(e.outDir,n)]}catch(s){let i=s instanceof Error?s.message:String(s);return this.logger.warn(`Template schema.ts.hbs error: ${i}, using placeholder`),await T.promises.writeFile(n,"// Generated schema - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generateZodSchema(e,t,r){let n=h.join(r,"schema.zod.ts");if(this.configService.shouldExcludeFile(e,n))return[];try{let s=Qe(t.modelDefs),i={...t,modelDefs:s};return await this.renderTemplate("schema.zod.ts.hbs",{Client:e,IR:i},n,e),[h.relative(e.outDir,n)]}catch(s){let i=s instanceof Error?s.message:String(s);return this.logger.warn(`Template schema.zod.ts.hbs error: ${i}, using placeholder`),await T.promises.writeFile(n,"// Generated Zod schemas - template rendering to be implemented","utf-8"),[h.relative(e.outDir,n)]}}async generatePackageJson(e){let t=h.join(e.outDir,"package.json");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate("package.json.hbs",{Client:e},t,e)}catch{this.logger.warn("Template package.json.hbs not found, using fallback");let r=JSON.stringify({name:e.packageName,version:"0.0.1",main:"dist/index.js",types:"dist/index.d.ts"},null,2);await T.promises.writeFile(t,r,"utf-8")}}async generateTsConfig(e){let t=h.join(e.outDir,"tsconfig.json");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate("tsconfig.json.hbs",{Client:e},t,e)}catch{this.logger.warn("Template tsconfig.json.hbs not found, using fallback");let r=e.srcDir||"src",n=JSON.stringify({compilerOptions:{target:"ES2020",module:"commonjs",lib:["ES2020"],declaration:!0,outDir:"./dist",rootDir:`./${r}`,strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0},include:[`${r}/**/*`]},null,2),s=h.dirname(t);await T.promises.mkdir(s,{recursive:!0}),await T.promises.writeFile(t,n,"utf-8")}}async generateTsupConfig(e){let t=h.join(e.outDir,"tsup.config.ts");if(this.configService.shouldExcludeFile(e,t))return[];try{await this.renderTemplate("tsup.config.ts.hbs",{Client:e},t,e)}catch{this.logger.warn("Template tsup.config.ts.hbs not found, using fallback");let n=`import { defineConfig } from "tsup";
6
6
 
7
7
  export default defineConfig({
8
8
  entry: ["${e.srcDir||"src"}/index.ts"],
@@ -19,5 +19,5 @@ export default defineConfig({
19
19
  });
20
20
  `;await T.promises.writeFile(t,n,"utf-8")}return["tsup.config.ts"]}async generateReadme(e,t){let r=h.join(e.outDir,"README.md");if(!this.configService.shouldExcludeFile(e,r))try{await this.renderTemplate("README.md.hbs",{Client:e,IR:t},r,e)}catch{this.logger.warn("Template README.md.hbs not found, using fallback");let n=`# ${e.name}
21
21
 
22
- Generated SDK from OpenAPI specification.`;await T.promises.writeFile(r,n,"utf-8")}}async generatePrettierConfig(e){let t=h.join(e.outDir,".prettierrc");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate(".prettierrc.hbs",{Client:e},t,e)}catch{this.logger.warn("Template .prettierrc.hbs not found, using fallback");let r=JSON.stringify({semi:!0,trailingComma:"es5",singleQuote:!0,printWidth:80,tabWidth:2,useTabs:!1},null,2);await T.promises.writeFile(t,r,"utf-8")}}};z=Ht([(0,ue.Injectable)(),ot("design:type",Function),ot("design:paramtypes",[typeof j>"u"?Object:j])],z);function $t(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f($t,"_ts_decorate");function it(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(it,"_ts_metadata");var V=class{static{f(this,"GeneratorModule")}generatorService;typeScriptGenerator;constructor(e,t){this.generatorService=e,this.typeScriptGenerator=t,this.generatorService.register(this.typeScriptGenerator)}};V=$t([(0,at.Module)({imports:[B,_],providers:[C,q,D,z],exports:[C,q,D]}),it("design:type",Function),it("design:paramtypes",[typeof C>"u"?Object:C,typeof z>"u"?Object:z])],V);function Dt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(Dt,"_ts_decorate");var Z=class{static{f(this,"CliModule")}};Z=Dt([(0,ct.Module)({imports:[_,V,B],providers:[P,U]})],Z);async function qt(){await pt.CommandFactory.run(Z,{logger:["error","warn","log"]})}f(qt,"bootstrap");qt().catch(o=>{console.error("CLI Error:",o),process.exit(1)});
22
+ Generated SDK from OpenAPI specification.`;await T.promises.writeFile(r,n,"utf-8")}}async generatePrettierConfig(e){let t=h.join(e.outDir,".prettierrc");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate(".prettierrc.hbs",{Client:e},t,e)}catch{this.logger.warn("Template .prettierrc.hbs not found, using fallback");let r=JSON.stringify({semi:!0,trailingComma:"es5",singleQuote:!0,printWidth:80,tabWidth:2,useTabs:!1},null,2);await T.promises.writeFile(t,r,"utf-8")}}};z=Ht([(0,ue.Injectable)(),ot("design:type",Function),ot("design:paramtypes",[typeof j>"u"?Object:j])],z);function Dt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f(Dt,"_ts_decorate");function it(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(it,"_ts_metadata");var V=class{static{f(this,"GeneratorModule")}generatorService;typeScriptGenerator;constructor(e,t){this.generatorService=e,this.typeScriptGenerator=t,this.generatorService.register(this.typeScriptGenerator)}};V=Dt([(0,at.Module)({imports:[B,_],providers:[C,q,$,z],exports:[C,q,$]}),it("design:type",Function),it("design:paramtypes",[typeof C>"u"?Object:C,typeof z>"u"?Object:z])],V);function $t(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(s=(n<3?i(s):n>3?i(e,t,s):i(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}f($t,"_ts_decorate");var Z=class{static{f(this,"CliModule")}};Z=$t([(0,ct.Module)({imports:[_,V,B],providers:[P,U]})],Z);async function qt(){await pt.CommandFactory.run(Z,{logger:["error","warn","log"]})}f(qt,"bootstrap");qt().catch(o=>{console.error("CLI Error:",o),process.exit(1)});
23
23
  //# sourceMappingURL=main.js.map