@apinni/client-ts 0.0.0 → 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Apinni
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # @apinni/client-ts
2
+
3
+ Type-safe API client generator with decorators for TypeScript
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @apinni/client-ts
9
+ # or
10
+ yarn add @apinni/client-ts
11
+ # or
12
+ pnpm add @apinni/client-ts
13
+ ```
14
+
15
+ ## Documentation
16
+
17
+ For full documentation, visit [https://apinni.github.io/client-ts](https://apinni.github.io/client-ts)
18
+
19
+ ## License
20
+
21
+ MIT
22
+
package/dist/cli.js ADDED
@@ -0,0 +1,235 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';var commander=require('commander'),listr2=require('listr2'),tsMorph=require('ts-morph'),He=require('path'),be=require('fs/promises'),Ge=require('crypto'),Le=require('fs'),Nt=require('chokidar'),bundleRequire=require('bundle-require');require('reflect-metadata');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var He__namespace=/*#__PURE__*/_interopNamespace(He);var be__default=/*#__PURE__*/_interopDefault(be);var Ge__default=/*#__PURE__*/_interopDefault(Ge);var Le__namespace=/*#__PURE__*/_interopNamespace(Le);var Nt__default=/*#__PURE__*/_interopDefault(Nt);var fe=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});function ye(s){switch(s.getKind()){case tsMorph.SyntaxKind.StringLiteral:return s.getLiteralText();case tsMorph.SyntaxKind.NumericLiteral:return Number(s.getText());case tsMorph.SyntaxKind.TrueKeyword:return true;case tsMorph.SyntaxKind.FalseKeyword:return false;case tsMorph.SyntaxKind.ArrayLiteralExpression:return s.getElements().map(e=>ye(e));case tsMorph.SyntaxKind.ObjectLiteralExpression:return G(s);default:return s.getText()}}function G(s){let e={};return s.getProperties().forEach(t=>{if(t.isKind(tsMorph.SyntaxKind.PropertyAssignment)){let n=t,r=n.getNameNode(),o;r.isKind(tsMorph.SyntaxKind.StringLiteral)?o=r.getLiteralText():o=r.getText();let i=n.getInitializer();i&&(e[o]=ye(i));}}),e}function C(s){let e=s==null?void 0:s.getCallExpression(),t=e==null?void 0:e.getArguments()[0],n=s.getSourceFile();if(!t)return null;if(t.getKindName()==="ObjectLiteralExpression")return G(t);if(t.getKindName()==="Identifier"){let r=t,o=n.getVariableDeclaration(r.getText());if(o){let a=o.getInitializer();if(a&&a.getKindName()==="ObjectLiteralExpression")return G(a)}let i=n.getImportDeclarations().flatMap(a=>a.getNamedImports()).find(a=>a.getName()===r.getText());if(i){let c=i.getImportDeclaration().getModuleSpecifierSourceFile();if(c){let d=c.getVariableDeclaration(r.getText());if(d){let u=d.getInitializer();if(u&&u.getKindName()==="ObjectLiteralExpression")return G(u)}}}}return null}function We(s,e){let t=(s==null?void 0:s.replace(/\/+$/,""))||"",n=e==null?void 0:e.replace(/^\/+/,""),r=He.join(...[t,n].filter(Boolean)),o={};return r.replace(/:([a-zA-Z0-9_]+)/g,(i,a)=>o[a]===void 0?(o[a]=0,`:${a}`):(o[a]++,`:${a}_${o[a]}`))}var he=s=>Object.fromEntries(Object.entries(s).filter(([e,t])=>t!==void 0).map(([e,t])=>e==="responses"?[e,Object.fromEntries(Object.entries(t).map(([n,r])=>[n.replace(/[^0-9]/g,""),r]))]:[e,t])),M=class s{static instance=null;classMetadata=[];methodMetadata=[];static getInstance(){return s.instance||(s.instance=new s),s.instance}removeMetadataByTarget(e){this.classMetadata=this.classMetadata.filter(t=>t.target!==e),this.methodMetadata=this.methodMetadata.filter(t=>t.target!==e);}unregisterClass(e){this.classMetadata=this.classMetadata.filter(t=>t.target!==e);}unregisterMethod(e,t){this.methodMetadata=this.methodMetadata.filter(n=>!(n.target===e&&n.propertyKey===t));}registerClassMetadata(e,t){let n=this.classMetadata.find(r=>r.target===e);n?this.classMetadata.splice(this.classMetadata.indexOf(n),1,{...n,...Object.fromEntries(Object.entries(t).filter(([r,o])=>o!==void 0))}):this.classMetadata.push({target:e,...t});}registerMethodMetadata(e,t,n){let r=this.methodMetadata.find(o=>o.target===e&&o.propertyKey===t);r?this.methodMetadata.splice(this.methodMetadata.indexOf(r),1,{...r,...he(n)}):this.methodMetadata.push({target:e,propertyKey:t,...he(n)});}getClassMetadata(){return this.classMetadata}getMethodMetadata(){return this.methodMetadata}getPreparedData(){return this.methodMetadata.map(t=>{var o;let n=this.classMetadata.find(i=>i.target===t.target),r={...n==null?void 0:n.disabledDomains};return typeof((o=t.disabledDomains)==null?void 0:o["*"])=="boolean"?r={...t.disabledDomains}:r={...r,...t.disabledDomains},{...t,path:We(n==null?void 0:n.path,t.path),domains:n==null?void 0:n.domains,...Object.keys(r).length&&{disabledDomains:r,disabledReason:t.disabledReason||(n==null?void 0:n.disabledReason)}}})}filterEnabled(){this.methodMetadata=this.methodMetadata.filter(e=>{let t=this.classMetadata.find(i=>{var a;return i.target===e.target||i.target===((a=e.target.prototype)==null?void 0:a.constructor)}),n=(t==null?void 0:t.disabled)??false,r=e.disabled??false;return !(n||r)}),this.classMetadata=this.classMetadata.filter(e=>!e.disabled);}clear(){this.classMetadata=[],this.methodMetadata=[];}};var Te=(s,{target:e,decorator:t})=>{if(s!=="register")return;let n=M.getInstance(),r=C(t);n.registerClassMetadata(e,{...r});};var xe=(s,{target:e,decorator:t})=>{if(s!=="register")return;let n=M.getInstance(),r=C(t)||{disabled:true};if("domains"in r)return n.registerClassMetadata(e,{disabledDomains:r.domains,disabledReason:r.reason});n.registerClassMetadata(e,{disabledDomains:{"*":r.disabled},disabledReason:r.reason});},Ae=(s,{target:e,propertyKey:t,decorator:n})=>{if(s!=="register")return;let r=M.getInstance(),o=C(n)||{disabled:true};if("domains"in o)return r.registerMethodMetadata(e,t,{disabledDomains:o.domains,disabledReason:o.reason});r.registerMethodMetadata(e,t,{disabledDomains:{"*":o.disabled},disabledReason:o.reason});};var Se=(s,{target:e,decorator:t})=>{if(s!=="register")return;let n=M.getInstance(),r=C(t);n.registerClassMetadata(e,{...r&&{domains:Array.isArray(r.domains)?r.domains:[r.domains]}});};function ze(s){return s&&s.replace(/^["']|["']$/g,"")}function Qe(s){let t=s.getParentOrThrow().getType().getCallSignatures()[0];return t?{type:t.getReturnType(),node:t.getDeclaration()}:null}var oe=(s,e)=>{var r,o,i;let t=(r=s.getProperty("type"))==null?void 0:r.getTypeAtLocation(e),n=(i=(o=s.getProperty("name"))==null?void 0:o.getTypeAtLocation(e))==null?void 0:i.getText();return t?{type:t,node:e,name:n&&ze(n)}:null},ie=(s,e)=>{var i;let t=(i=s.getType().getProperty(e))==null?void 0:i.getTypeAtLocation(s);if(!e||!t)return null;if(e==="request"||e==="query"){let a=oe(t,s);return a||null}let n=t.getProperties().filter(a=>/^\d+/.test(a.getName())),r={};if(n.length>0){for(let a of n){let c=parseInt(a.getName(),10),d=a.getTypeAtLocation(s),u=oe(d,s);u&&(r[c]=u);}return Object.keys(r).length===0?null:r}let o=oe(t,s);return o?(r[200]=o,r):null},Me=(s,{target:e,propertyKey:t,decorator:n})=>{if(s!=="register")return;let r=M.getInstance(),o=C(n);if(!(o!=null&&o.responses)){let c=Qe(n);c&&r.registerMethodMetadata(e,t,{responses:{200:{type:c.type,node:c.node}}});}if(o){let{query:c,...d}=o;r.registerMethodMetadata(e,t,{...d,...Array.isArray(c)?{query:{inline:`{ ${c.map(u=>`${u}: string;`).join(" ")} }`}}:{query:c}});}let i=n==null?void 0:n.getCallExpression(),[a]=(i==null?void 0:i.getTypeArguments())||[];if(a){let c=ie(a,"query"),d=ie(a,"request"),u=ie(a,"responses");r.registerMethodMetadata(e,t,{...c&&{query:c},...d&&{request:d},...u&&{responses:u}});}};var j=class{decorators=new Map;constructor(){this.register({name:"ApinniController",variant:"class",type:"compile-time",handler:Te}),this.register({name:"ApinniDomain",variant:"class",type:"compile-time",handler:Se}),this.register({name:"ApinniDisabled",variant:"class",type:"compile-time",handler:xe}),this.register({name:"ApinniDisabled",variant:"method",type:"compile-time",handler:Ae}),this.register({name:"ApinniEndpoint",variant:"method",type:"compile-time",handler:Me});}register(e){let t=`${e.name}:${e.variant}`,n=this.decorators.get(t)??[];this.decorators.set(t,[...n,e]);}getRegisteredDecorators(){return Array.from(this.decorators.values()).map(([e])=>({name:e.name,type:e.type}))}getOriginalDecoratorName(e){var n;let t=e.getSourceFile();for(let r of t.getImportDeclarations())for(let o of r.getNamedImports()){let i=o.getNameNode().getText(),a=((n=o.getAliasNode())==null?void 0:n.getText())??i;if(e.getName()===a)return i}return e.getName()}processEvent(e,{target:t,decorator:n,propertyKey:r}){let o=this.getOriginalDecoratorName(n),a=`${o}:${r?"method":"class"}`,c=this.decorators.get(a)||this.decorators.get(`${o}:class`);return c?(c.forEach(d=>d.handler(e,{target:t,decorator:n,propertyKey:r})),true):false}};var se="/.apinni/.build-cache.json";var ae=s=>Ge__default.default.createHash("sha256").update(s).digest("hex");var k=class{project;constructor(e){this.project=e??new tsMorph.Project({tsConfigFilePath:He.join(process.cwd(),"tsconfig.json"),skipAddingFilesFromTsConfig:true,skipFileDependencyResolution:true,compilerOptions:{module:tsMorph.ModuleKind.CommonJS,moduleResolution:tsMorph.ModuleResolutionKind.Node16,outDir:"./.apinni/build"}});}getReferencedFiles(e){let t=new Map,n=[...e];for(;n.length>0;){let r=n.pop(),o=r.getFilePath();if(t.has(o)||o.endsWith(".d.ts"))continue;t.set(o,r);let i=r.getReferencedSourceFiles();n.push(...i.filter(a=>{let c=a.getFilePath();return !(t.has(c)||c.endsWith(".d.ts"))}));}return Array.from(t.values())}async compileFiles(e,t={}){let{force:n=false,includeReferenced:r=true}=t,o=r?this.getReferencedFiles(e):e,i=await this.loadCache(),a=n?o:this.extractChangedFiles(o,i);if(a.length===0)return 0;let c=a.map(u=>this.project.createSourceFile(u.getFilePath(),u.getFullText(),{overwrite:true}));await Promise.all(this.project.getSourceFiles().map(u=>u.emit()));let d=a.length;return a.forEach(u=>{let g=u.getFilePath();i[g]=ae(u.getFullText());}),c.forEach(u=>this.project.removeSourceFile(u)),await this.saveCache(i),d}async loadCache(){try{let e=await be__default.default.readFile(He.join(process.cwd(),se),"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return {};throw e}}async saveCache(e){await be__default.default.writeFile(He.join(process.cwd(),se),JSON.stringify(e,null,2),"utf8");}extractChangedFiles(e,t){return e.filter(n=>{let r=n.getFilePath(),o=ae(n.getFullText());return t[r]!==o})}};var _=class{constructor(){}processDecorators(e,t){let n=0;for(let{sourceFile:r,type:o}of e.filesWithDecorators){if(o==="run-time"&&!e.modules.get(r.getFilePath()))continue;let i=e.modules.get(r.getFilePath());for(let a of r.getClasses()){let c=a.getName(),d=o==="run-time"?c&&i[c]||i.default:`${r.getFilePath()}_${c}`;if(d){for(let u of a.getDecorators())t({target:d,decorator:u,sourceFile:r})&&n++;for(let u of a.getMethods()){let g=u.getName();for(let p of u.getDecorators())t({target:d,propertyKey:g,decorator:p,sourceFile:r})&&n++;}}}}return n}};var Pe=`type IApi = Record<
3
+ string,
4
+ Partial<
5
+ Record<
6
+ ApiMethod,
7
+ {
8
+ request?: unknown;
9
+ responses?: Record<number, unknown>;
10
+ query?: unknown;
11
+ }
12
+ >
13
+ >
14
+ >;
15
+
16
+ export type BuildApi<T extends IApi> = T;`,De=`type _ApiPaths<TApi extends IApi> = Extract<keyof TApi, string>;
17
+
18
+ type _ApiAvailableMethods<
19
+ TApi extends IApi,
20
+ T extends _ApiPaths<TApi>
21
+ > = keyof TApi[T] & ApiMethod;
22
+
23
+ type _ApiResponses<
24
+ TApi extends IApi,
25
+ T extends _ApiPaths<TApi>,
26
+ M extends _ApiAvailableMethods<TApi, T> = _ApiAvailableMethods<TApi, T>
27
+ > = TApi[T][M] extends { responses: infer R } ? R : never;
28
+
29
+ type ExtractStatusCodeStrings<
30
+ TApi extends IApi,
31
+ T extends _ApiPaths<TApi>,
32
+ M extends _ApiAvailableMethods<TApi, T>
33
+ > = _ApiResponses<TApi, T, M> extends infer Responses
34
+ ? Responses extends Record<number, any>
35
+ ? \`\${keyof Responses & number}\`
36
+ : never
37
+ : never;
38
+
39
+ type _ApiResponsesByStatus<
40
+ TApi extends IApi,
41
+ T extends _ApiPaths<TApi>,
42
+ M extends _ApiAvailableMethods<TApi, T> = _ApiAvailableMethods<TApi, T>,
43
+ S extends ExtractStatusCodeStrings<TApi, T, M> = ExtractStatusCodeStrings<
44
+ TApi,
45
+ T,
46
+ M
47
+ >
48
+ > = _ApiResponses<TApi, T, M> extends infer Responses
49
+ ? Responses extends Record<number, any>
50
+ ? S extends \`\${infer Index extends keyof Responses & number}\`
51
+ ? Responses[Index]
52
+ : Responses[keyof Responses]
53
+ : never
54
+ : never;
55
+
56
+ // Extract request type
57
+ type _ApiRequest<
58
+ TApi extends IApi,
59
+ T extends _ApiPaths<TApi>,
60
+ M extends _ApiAvailableMethods<TApi, T> = _ApiAvailableMethods<TApi, T>
61
+ > = TApi[T][M] extends { request: infer R } ? R : never;
62
+
63
+ // Extract query type
64
+ type _ApiQuery<
65
+ TApi extends IApi,
66
+ T extends _ApiPaths<TApi>,
67
+ M extends _ApiAvailableMethods<TApi, T> = _ApiAvailableMethods<TApi, T>
68
+ > = TApi[T][M] extends { query: infer Q } ? Q : never;
69
+
70
+ type MakePathSegments<T extends string> =
71
+ T extends \`\${infer Start}/:\${infer Param}\`
72
+ ? Param extends \`\${infer _}/\${infer Rest}\`
73
+ ? [\`\${Start}/\`, string, ...MakePathSegments<\`/\${Rest}\`>]
74
+ : [\`\${Start}/\`, string]
75
+ : [T];
76
+
77
+ type ExtractParams<T extends string> = T extends \`\${infer _}/:\${infer Param}\`
78
+ ? Param extends \`\${infer Name}/\${infer Rest}\`
79
+ ? {
80
+ [key in Name | keyof ExtractParams<\`/\${Rest}\`>]: string;
81
+ }
82
+ : {
83
+ [key in Param]: string;
84
+ }
85
+ : unknown;
86
+
87
+ type TypedJoin<T extends Array<string>> = T extends [
88
+ infer First,
89
+ ...infer Rest extends Array<string>
90
+ ]
91
+ ? \`\${First & string}\${TypedJoin<Rest>}\`
92
+ : "";
93
+
94
+ type ResolveArgs<
95
+ TApi extends IApi,
96
+ P extends _ApiPaths<TApi>,
97
+ M extends _ApiAvailableMethods<TApi, P> = _ApiAvailableMethods<TApi, P>
98
+ > = keyof ExtractParams<P> extends never
99
+ ? _ApiQuery<TApi, P, M> extends never
100
+ ? []
101
+ : [{ query: _ApiQuery<TApi, P, M> }]
102
+ : _ApiQuery<TApi, P, M> extends never
103
+ ? [{ params: ExtractParams<P> }]
104
+ : [{ params: ExtractParams<P>; query: _ApiQuery<TApi, P, M> }];
105
+
106
+ type _ApiPathBuilder<
107
+ TApi extends IApi,
108
+ P extends _ApiPaths<TApi>,
109
+ M extends _ApiAvailableMethods<TApi, P> = _ApiAvailableMethods<TApi, P>
110
+ > = ResolveArgs<TApi, P, M> extends []
111
+ ? () => \`\${TypedJoin<MakePathSegments<P>>}\`
112
+ : (
113
+ args: ResolveArgs<TApi, P, M>[0]
114
+ ) => \`\${TypedJoin<MakePathSegments<P>>}\${_ApiQuery<
115
+ TApi,
116
+ P,
117
+ M
118
+ > extends never
119
+ ? ""
120
+ : "" | \`?\${string}\`}\`;
121
+
122
+ // Public API path keys (e.g., "/users/:id")
123
+ export type ApiPaths = _ApiPaths<Api>;
124
+ export type ApiPathsProxy<T extends IApi> = _ApiPaths<T>;
125
+
126
+ // Get methods available on a path
127
+ export type ApiAvailableMethods<T extends ApiPaths> = _ApiAvailableMethods<
128
+ Api,
129
+ T
130
+ >;
131
+ export type ApiAvailableMethodsProxy<
132
+ A extends IApi,
133
+ T extends ApiPathsProxy<A>
134
+ > = _ApiAvailableMethods<A, T>;
135
+
136
+ // Extract responses type
137
+ export type ApiResponses<
138
+ T extends ApiPaths,
139
+ M extends ApiAvailableMethods<T> = ApiAvailableMethods<T>
140
+ > = _ApiResponses<Api, T, M>;
141
+ export type ApiResponsesProxy<
142
+ A extends IApi,
143
+ T extends ApiPathsProxy<A>,
144
+ M extends ApiAvailableMethodsProxy<A, T> = ApiAvailableMethodsProxy<A, T>
145
+ > = _ApiResponses<A, T, M>;
146
+
147
+ // Extract response type by status
148
+ export type ApiResponsesByStatus<
149
+ T extends ApiPaths,
150
+ M extends ApiAvailableMethods<T> = ApiAvailableMethods<T>,
151
+ S extends ExtractStatusCodeStrings<Api, T, M> = ExtractStatusCodeStrings<
152
+ Api,
153
+ T,
154
+ M
155
+ >
156
+ > = _ApiResponsesByStatus<Api, T, M, S>;
157
+ export type ApiResponsesByStatusProxy<
158
+ A extends IApi,
159
+ T extends ApiPathsProxy<A>,
160
+ M extends ApiAvailableMethodsProxy<A, T> = ApiAvailableMethodsProxy<A, T>,
161
+ S extends ExtractStatusCodeStrings<A, T, M> = ExtractStatusCodeStrings<
162
+ A,
163
+ T,
164
+ M
165
+ >
166
+ > = _ApiResponsesByStatus<A, T, M, S>;
167
+
168
+ // Extract request type
169
+ export type ApiRequest<
170
+ T extends ApiPaths,
171
+ M extends ApiAvailableMethods<T> = ApiAvailableMethods<T>
172
+ > = _ApiRequest<Api, T, M>;
173
+ export type ApiRequestProxy<
174
+ A extends IApi,
175
+ T extends ApiPathsProxy<A>,
176
+ M extends ApiAvailableMethodsProxy<A, T> = ApiAvailableMethodsProxy<A, T>
177
+ > = _ApiRequest<A, T, M>;
178
+
179
+ // Extract query type
180
+ export type ApiQuery<
181
+ T extends ApiPaths,
182
+ M extends ApiAvailableMethods<T> = ApiAvailableMethods<T>
183
+ > = _ApiQuery<Api, T, M>;
184
+ export type ApiQueryProxy<
185
+ A extends IApi,
186
+ T extends ApiPathsProxy<A>,
187
+ M extends ApiAvailableMethodsProxy<A, T> = ApiAvailableMethodsProxy<A, T>
188
+ > = _ApiQuery<A, T, M>;
189
+
190
+ export type ApiPathBuilder<
191
+ P extends ApiPaths,
192
+ M extends ApiAvailableMethods<P> = ApiAvailableMethods<P>
193
+ > = _ApiPathBuilder<Api, P, M>;
194
+ export type ApiPathBuilderProxy<
195
+ A extends IApi,
196
+ P extends ApiPathsProxy<A>,
197
+ M extends ApiAvailableMethodsProxy<A, P> = ApiAvailableMethodsProxy<A, P>
198
+ > = _ApiPathBuilder<A, P, M>;
199
+ `;var pe=["description","example","deprecated","default"],U=s=>s.flatMap(t=>[t.getCommentText(),...t.getTags().filter(n=>pe.includes(n.getTagName())).map(n=>n.getStructure())]).filter(Boolean).reduce((t,n)=>{let r=typeof n=="string"?"global":n==null?void 0:n.tagName,o=typeof n=="string"?n:n==null?void 0:n.text;return {...t,[r]:t[r]?`${t[r]}
200
+ ${o}`:o}},{}),I=s=>{var t,n;return ((t=s.getAliasSymbol())==null?void 0:t.getDeclarations()[0])||((n=s.getSymbol())==null?void 0:n.getDeclarations()[0])},q=(s,e)=>{let t=I(e);return {...s,...tsMorph.Node.isJSDocable(t)&&U(t.getJsDocs())}};var K=class{generate(e){let t=[];for(let[n,r]of Object.entries(e.refs)){let o=this.schemaToTypeInternal(r,0),i=this.schemaToJSDoc(r);i&&t.push(i),t.push(`export type ${n} = ${o};`);}for(let[n,r]of Object.entries(e.schema)){let o=this.schemaToTypeInternal(r,0),i=this.schemaToJSDoc(r);i&&t.push(i),t.push(`export type ${n} = ${o};`);}return t.join(`
201
+ `)}schemaToJSDoc(e){if(!e||typeof e!="object")return "";let t=e,n=[];return t.global&&n.push(` * ${String(t.global)}`),Object.keys(t).filter(r=>pe.includes(r)).forEach(r=>{n.push(` * @${r} ${String(t[r])}`);}),n.length?`/**
202
+ ${n.join(`
203
+ `)}
204
+ */`:""}schemaToTypeInternal(e,t){return !e||typeof e!="object"?"any":e.type==="ref"&&e.name?e.name:e.type==="string"?e.const?`'${e.const}'`:"string":e.type==="number"?e.const?`${e.const}`:"number":e.type==="boolean"?e.const?`${e.const}`:"boolean":e.type==="null"?"null":Object.keys(e).length===0?"any":e.type==="array"?this.handleArraySchema(e,t):e.type==="object"?this.handleObjectSchema(e,t):e.type==="enum"&&e.values?this.handleEnumSchema(e):"anyOf"in e&&e.anyOf?this.handleUnionSchema(e,t):"allOf"in e&&e.allOf?this.handleIntersectionSchema(e,t):"not"in e?"never":"any"}getIndent(e){return " ".repeat(e)}handleArraySchema(e,t){if(Array.isArray(e.items))return `[${e.items.map(i=>{let a=this.schemaToTypeInternal(i,t);if(i.optional)return i.name?`${i.name}?: ${a}`:`${a}?`;let c=i.name?`${i.name}: `:"";return i.rest?`...${c}(${a})[]`:`${c}${a}`}).join(", ")}]`;let n=this.schemaToTypeInternal(e.items,t);return n.includes(" & ")||n.includes(" | ")?`(${n})[]`:`${n}[]`}handleObjectSchema(e,t){let n=e.properties||{},r=new Set(e.required||[]),o=[];if(e.indexedProperties){let a=this.schemaToTypeInternal(e.indexedProperties,t+1);o.push(`${this.getIndent(t+1)}[key: string]: ${a};`);}for(let[a,c]of Object.entries(n)){let d=!r.has(a),u=this.schemaToTypeInternal(c,t+1),g=this.schemaToJSDoc(c),p=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(a)?a:`"${a}"`;g.split(`
205
+ `).filter(Boolean).forEach(l=>o.push(`${this.getIndent(t+1)}${l}`)),o.push(`${this.getIndent(t+1)}${p}${d?"?":""}: ${u};`);}return `{
206
+ ${o.join(`
207
+ `)}
208
+ ${this.getIndent(t)}}`}handleEnumSchema(e){return e.values.map(t=>typeof t=="string"?`"${t}"`:t).join(" | ")}handleUnionSchema(e,t){return e.anyOf.map(r=>{let o=this.schemaToTypeInternal(r,t);return "anyOf"in r&&Array.isArray(r.anyOf)||r.type==="complex"?`(${o})`:o}).join(" | ")}handleIntersectionSchema(e,t){let n=e.allOf.map(o=>{let i=this.schemaToTypeInternal(o,t);return "anyOf"in o&&Array.isArray(o.anyOf)?`(${i})`:i}),r=this.getIndent(t);return n.join(` &
209
+ ${r}`)}};var Xe=s=>{let e=(s==null?void 0:s.getDeclarations())||[];return e.length?e.some(t=>t.getSourceFile().getFilePath().includes("node_modules/typescript/lib/lib")):false};function Ne(s,e,t){return t?s.getTypeOfSymbolAtLocation(e,t):null}function et(s,e,t){if(!s)return null;let n=s.getTypeAlias(e);if(n)return {type:n.getType(),node:n.getTypeNode()};let r=s.getInterface(e);if(r)return {type:r.getType(),node:r};let o=s.getClass(e);if(o)return {type:o.getType(),node:o};let i=s.getVariableDeclaration(e);if(i&&i.getTypeNode())return {type:i.getType(),node:i.getTypeNode()};let a=`Internal_${t||Date.now()}`,c=s.addTypeAlias({name:a,type:e});return c?{type:c.getType(),node:c.getTypeNode()}:null}var tt=s=>{let e=s.getTargetType();if(!e)return null;let t=e.compilerType;if(!((t.flags&tsMorph.ts.TypeFlags.Object)!==0&&(t.objectFlags&tsMorph.ts.ObjectFlags.Tuple)!==0))return null;let r=t;return r.elementFlags.reduce((i,a,c)=>{var d;return {...i,[c]:{rest:(a&tsMorph.ts.ElementFlags.Rest)!==0,optional:(a&tsMorph.ts.ElementFlags.Optional)!==0,...((d=r.labeledElementDeclarations)==null?void 0:d[c])&&{name:r.labeledElementDeclarations[c].name.getText()}}}},{})},Z=class{checker;project;referencesMaps=new Map;collectedTypes="";constructor(e){this.project=e,this.checker=this.project.getTypeChecker();}storeCollectedTypes(e){this.collectedTypes=e;}handlers=[{condition:e=>e.isAny()||e.isUnknown(),resolver:()=>({type:"any"})},{condition:e=>e.isNever(),resolver:()=>({type:"never"})},{condition:e=>e.isUndefined(),resolver:()=>({type:"undefined"})},{condition:e=>e.isNull(),resolver:()=>({type:"null"})},{condition:e=>e.isString()||e.isTemplateLiteral(),resolver:()=>({type:"string"})},{condition:e=>e.isNumber(),resolver:()=>({type:"number"})},{condition:e=>e.isBoolean(),resolver:()=>({type:"boolean"})},{condition:e=>e.isStringLiteral(),resolver:({type:e})=>({type:"string",const:e.getLiteralValue()})},{condition:e=>e.isNumberLiteral(),resolver:({type:e})=>({type:"number",const:e.getLiteralValue()})},{condition:e=>e.isBooleanLiteral(),resolver:({type:e})=>({type:"boolean",const:e.getText()==="true"})},{condition:e=>e.isEnum(),resolver:({type:e})=>{let t=e.getUnionTypes().map(n=>n.getLiteralValue()).filter(n=>n!==void 0);return q({type:"enum",values:t},e)}},{condition:e=>e.getText()==="Date",resolver:()=>({type:"string"})},{condition:e=>{var t;return ((t=e.getSymbol())==null?void 0:t.getName())==="Promise"},resolver:({type:e,...t})=>{let n=e.getTypeArguments()[0],r=I(n);return this.convert({type:n,...t,node:r})}},{condition:e=>e.isArray(),resolver:this.handleArray.bind(this)},{condition:e=>e.isTuple(),resolver:this.handleTuple.bind(this)},{condition:e=>e.isUnion(),resolver:this.handleUnion.bind(this)},{condition:e=>e.isIntersection(),resolver:this.handleIntersection.bind(this)},{condition:e=>e.isObject(),resolver:this.handleObject.bind(this)}];generateSchema(e){var g;this.referencesMaps=new Map;let t={},n=e.filter(p=>"type"in p),r=e.filter(p=>"model"in p),o=e.filter(p=>"inline"in p);for(let p of n){if(!p.name)continue;let l=p.type.getAliasSymbol(),m=(g=p.type.getTargetType())==null?void 0:g.getAliasSymbol();if((l||m)&&l===m&&p.node){let f=p.node.getSourceFile().addTypeAlias({name:`__temp__${Date.now()}`,type:p.type.getText()}),h=f.getType(),y=f.getTypeNode();t[p.name]=this.convert({type:h,node:y,name:p.name}),f.remove();}else t[p.name]=this.convert(p);}let i=this.project,a=new tsMorph.Project({useInMemoryFileSystem:true,compilerOptions:{lib:["lib.es2024.d.ts"],strictNullChecks:true}});this.project=a,this.checker=this.project.getTypeChecker();let c=this.project.createSourceFile(`__temp__${Date.now()}.ts`,this.collectedTypes);for(let p of o){if(!p.name)continue;let l=c.addTypeAlias({name:`__temp__${Date.now()}`,type:p.inline});t[p.name]=this.convert({type:l==null?void 0:l.getType(),node:l,name:p.name}),l.remove();}for(let p of r){if(!p.name)continue;let l=et(c,p.model,p.name);l&&(t[p.name]=this.convert({...l,name:p.name}));}this.project.removeSourceFile(c),this.project=i,this.checker=this.project.getTypeChecker();let d={};for(let[p,l]of this.referencesMaps.entries())for(let[m,f]of l.entries())d[m]||(d[m]=f);let u={};for(let p in t)if(d[p]){let l=1;for(;d[`${p}_${l}`]||t[`${p}_${l}`];)l+=1;let m=`${p}_${l}`;t[m]=t[p],delete t[p],u[p]=m;}return {schema:t,refs:d,mappedReferences:u}}convert({type:e,node:t,name:n,reference:r,seenSymbols:o=new Set,trace:i=[]}){var f,h,y,x,b,v,P;let a=e.getAliasSymbol(),c=(f=e.getTargetType())==null?void 0:f.getAliasSymbol(),d=e.getSymbol(),u=n||"__default";if(this.referencesMaps.has(u)||this.referencesMaps.set(u,new Map),i.length>100)return {type:"any"};let g=(!c||c===a)&&((a==null?void 0:a.getName())||(d==null?void 0:d.getName())),p=(!c||c===a)&&(a||d);if(g&&!["__type","__object"].includes(g)&&!g.includes("__temp__")&&!Xe(e.getSymbol())&&g!==r){let E=e.getAliasTypeArguments();if(E.length>0){let N=new Set(o);p&&N.add(p);for(let A of E){let $=(h=A.getAliasSymbol())==null?void 0:h.getName();!$||(y=this.referencesMaps.get(u))!=null&&y.has($)||(x=this.referencesMaps.get(u))==null||x.set($,this.convert({type:A,node:t,name:u,reference:$,seenSymbols:N}));}let re=e.getApparentType();return this.convert({type:re,node:t,name:u,reference:g,seenSymbols:N,trace:[...i,u]})}if(!((b=this.referencesMaps.get(u))!=null&&b.has(g))){let N=new Set(o);p&&N.add(p),(v=this.referencesMaps.get(u))==null||v.set(g,this.convert({type:e,node:t,name:u,reference:g,seenSymbols:N,trace:[...i,g]}));}return {type:"ref",name:g}}let l=(P=this.handlers.find(E=>E.condition(e)))==null?void 0:P.resolver;if(!l)return {type:"any"};let m=l({type:e,node:t,name:u,seenSymbols:o,trace:[...i,u]});return q(m,e)}handleArray({type:e,...t}){let n=e.getArrayElementTypeOrThrow();return {type:"array",items:this.convert({type:n,...t,node:I(n)})}}handleTuple({type:e,...t}){let n=e.getTupleElements(),r=tt(e);return {type:"array",items:n.map((i,a)=>({...this.convert({type:i,...t,node:I(i)}),...r==null?void 0:r[a]}))}}handleUnion({type:e,...t}){let n=e.getUnionTypes().filter(c=>!c.isUndefined());if(n.length===1)return this.convert({type:n[0],...t,node:I(n[0])||t.node});let r=n.some(c=>c.isBooleanLiteral()&&c.getText()==="false")&&n.some(c=>c.isBooleanLiteral()&&c.getText()==="true"),o=n;if(r&&(o=n.filter(c=>!c.isBooleanLiteral())),o.length>0&&o.every(c=>c.isLiteral()))return {type:"enum",values:o.map(c=>c.getLiteralValue()).filter(Boolean)};if(!o.length&&r)return q({type:"boolean"},e);let a=[...o.map(c=>this.convert({type:c,...t,node:I(c)||t.node})),...r?[{type:"boolean"}]:[]];return q({type:"complex",anyOf:a},e)}handleIntersection({type:e,...t}){let r=e.getIntersectionTypes().map(o=>this.convert({type:o,...t,node:I(o)||t.node}));return q({type:"complex",allOf:r},e)}handleObject({type:e,seenSymbols:t=new Set,trace:n=[],...r}){var u;let o={},i=[],a=!!e.getTargetType();for(let g of e.getProperties()){let p=null;if(a&&!e.isClass()&&r.node)p=Ne(this.checker,g,r.node);else {let f=g.getDeclarations()[0];if(f&&f.isKind(tsMorph.SyntaxKind.MethodDeclaration))continue;f&&(f.isKind(tsMorph.SyntaxKind.PropertySignature)||f.isKind(tsMorph.SyntaxKind.PropertyAssignment)||f.isKind(tsMorph.SyntaxKind.PropertyDeclaration))&&(p=f.getType()),p||(p=Ne(this.checker,g,r.node));}if(!p)continue;let l=g.getEscapedName(),m=g.getDeclarations()[0]||((u=p.getAliasSymbol())==null?void 0:u.getDeclarations()[0])||null;o[l]={...this.convert({type:p,trace:[...n,l],seenSymbols:t,...r,node:m||void 0}),...tsMorph.Node.isJSDocable(m)&&U(m.getJsDocs())},g.isOptional()||i.push(l);}let c={type:"object",properties:o};i.length>0&&(c.required=i);let d=e.getStringIndexType()||e.getNumberIndexType();return d&&(c.indexedProperties=this.convert({type:d,trace:[...n,"index_type"],...r})),{...c,...tsMorph.Node.isJSDocable(r.node)&&U(r.node.getJsDocs())}}};var ot=new Set(["Omit","Pick","Partial","Readonly","Array","Record","any","string","number","boolean","unknown","void","never","Object","Date","Promise","Error","Map","Set","Uint8Array","Buffer","null","undefined","bigint","symbol","Function","RegExp","Iterable","Iterator","ReadonlyArray","TemplateStringsArray","ThisType","Required","InstanceType","ReturnType","Parameters","ConstructorParameters","NonNullable","Extract","Exclude","Awaited","Uppercase","Lowercase","Capitalize","Uncapitalize"]),O=s=>ot.has(s),B=s=>{if(s.getKindName()!=="TypeQuery")return;let e=s.getExprName?s.getExprName():s.getFirstChildByKind(tsMorph.SyntaxKind.Identifier),t=e?e.getText():void 0;if(t)for(let n of s.getProject().getSourceFiles()){let r=n.getVariableDeclaration(t);if(r)return r.getType().getText(void 0,tsMorph.TypeFormatFlags.NoTruncation);let o=n.getEnum(t);if(o)return o.getName();let i=n.getClass(t);if(i){let d=i.getName();if(d)return d}let a=n.getTypeAlias(t);if(a)return a.getName();let c=n.getInterface(t);if(c)return c.getName()}};function it(s){var t,n,r,o;let e=[`export type ${s.getName()} = {`];for(let i of s.getProperties()){if(i.hasModifier("private")||i.hasModifier("protected")||i.isStatic())continue;let a=((t=i.getTypeNode())==null?void 0:t.getText())??"any";if((n=i.getTypeNode())!=null&&n.getText().startsWith("typeof ")){let c=B(i.getTypeNode());c&&(a=c);}e.push(` ${i.getName()}${i.hasQuestionToken()?"?":""}: ${a};`);}for(let i of s.getGetAccessors())i.hasModifier("private")||i.hasModifier("protected")||i.isStatic()||e.push(` readonly ${i.getName()}: ${((r=i.getReturnTypeNode())==null?void 0:r.getText())??"any"};`);for(let i of s.getMethods()){if(i.hasModifier("private")||i.hasModifier("protected")||i.isStatic()||i.getName()==="constructor")continue;let a=i.getParameters().map(c=>{var d;return `${c.getName()}: ${((d=c.getTypeNode())==null?void 0:d.getText())??"any"}`}).join(", ");e.push(` ${i.getName()}(${a}): ${((o=i.getReturnTypeNode())==null?void 0:o.getText())??"any"};`);}return e.push("}"),e.join(`
210
+ `)}var Ee=[{getDeclaration:(s,e)=>s.getInterface(e),getText:s=>tsMorph.Node.isInterfaceDeclaration(s)?st(s):s.getText()},{getDeclaration:(s,e)=>s.getClass(e),getText:s=>tsMorph.Node.isClassDeclaration(s)?it(s):s.getText()},{getDeclaration:(s,e)=>s.getTypeAlias(e),getText:s=>tsMorph.Node.isTypeAliasDeclaration(s)?at(s):s.getText()},{getDeclaration:(s,e)=>s.getEnum(e),getText:s=>s.getText()}];function st(s){var n,r,o;let e=s.getExtends().map(i=>i.getText()).join(" & "),t=[`export type ${s.getName()} = ${e?`${e} & `:""}{`];for(let i of s.getProperties()){let a=((n=i.getTypeNode())==null?void 0:n.getText())??"any";if((r=i.getTypeNode())!=null&&r.getText().startsWith("typeof ")){let c=B(i.getTypeNode());c&&(a=c);}t.push(` ${i.getName()}${i.hasQuestionToken()?"?":""}: ${a};`);}for(let i of s.getCallSignatures())t.push(` ${i.getText()}`);for(let i of s.getIndexSignatures())t.push(` ${i.getText()}`);for(let i of s.getMethods()){let a=i.getParameters().map(c=>{var d;return `${c.getName()}: ${((d=c.getTypeNode())==null?void 0:d.getText())??"any"}`}).join(", ");t.push(` ${i.getName()}(${a}): ${((o=i.getReturnTypeNode())==null?void 0:o.getText())??"any"};`);}return t.push("}"),t.join(`
211
+ `)}function at(s){var o,i,a,c,d,u,g;let e=s.getTypeNode(),t=(e==null?void 0:e.getText())??"any";if(e&&t.startsWith("typeof ")){let p=B(e);p&&(t=p);}if(e&&e.getKindName()==="TypeLiteral"){let p=["{"];for(let l of ((o=e.getProperties)==null?void 0:o.call(e))||[]){let m=((a=(i=l.getTypeNode)==null?void 0:i.call(l))==null?void 0:a.getText())??"any";if((d=(c=l.getTypeNode)==null?void 0:c.call(l))!=null&&d.getText().startsWith("typeof ")){let f=B(l.getTypeNode());f&&(m=f);}p.push(` ${((u=l.getName)==null?void 0:u.call(l))??""}${(g=l.hasQuestionToken)!=null&&g.call(l)?"?":""}: ${m};`);}p.push("}");}let n=s.getTypeParameters(),r="";return n.length>0&&(r=`<${n.map(p=>{var y,x;let l=p.getName(),m=(y=p.getConstraint())==null?void 0:y.getText(),f=(x=p.getDefault())==null?void 0:x.getText(),h=l;return m&&(h+=` extends ${m}`),f&&(h+=` = ${f}`),h}).join(", ")}>`),`export type ${s.getName()}${r} = ${t};`}var X=class{project;typeIndex=new Map;qualifiedNames=new Map;typeIndexQualified=new Map;constructor(e){this.project=e??new tsMorph.Project({tsConfigFilePath:He.join(process.cwd(),"tsconfig.json"),skipAddingFilesFromTsConfig:false,skipFileDependencyResolution:true});}buildTypeIndexes(){for(let e of this.project.getSourceFiles())e.getFullText().includes("Auto-generated API types")||(e.getInterfaces().forEach(t=>{let n=t.getName();this.addToTypeIndex(n,t,t.getType(),e);}),e.getClasses().forEach(t=>{let n=t.getName();n&&this.addToTypeIndex(n,t,t.getType(),e);}),e.getTypeAliases().forEach(t=>{let n=t.getName();this.addToTypeIndex(n,t.getTypeNode(),t.getType(),e);}),e.getEnums().forEach(t=>{let n=t.getName();this.addToTypeIndex(n,t,t.getType(),e);}),e.getVariableDeclarations().forEach(t=>{var r;let n=t.getName();(r=t.getTypeNode())!=null&&r.getText().startsWith("typeof ")&&B(t.getTypeNode())&&this.addToTypeIndex(n,t.getTypeNode(),t.getType(),e);}));for(let[e,t]of this.typeIndex)t.length>1?t.forEach((n,r)=>{let o=`${e}_${r+1}`;this.qualifiedNames.set(n.node,o),this.typeIndexQualified.set(o,n);}):t.forEach(n=>{let r=e;this.qualifiedNames.set(n.node,r),this.typeIndexQualified.set(r,n);});}addToTypeIndex(e,t,n,r){let o=this.typeIndex.get(e)||[];this.typeIndex.set(e,[...o,{node:t,type:n,sourceFile:r}]);}lookup(e){let t=this.extractTypeNames(e);return this.searchTypeDefinitions(t)}lookupNode(e){var n;let t=[];for(let r of e){if((((n=this.typeIndex.get(r.model))==null?void 0:n.length)||0)>1)throw new Error(`Multiple definition declarations found for ${r.model} [${r.name}]`);let o=this.typeIndexQualified.get(r.model);if(!o){t.push({name:r.name,inline:"any"});continue}t.push({type:o.type,node:o.node,name:r.name});}return t}getNodeName(e){if(tsMorph.Node.isInterfaceDeclaration(e)||tsMorph.Node.isTypeAliasDeclaration(e)||tsMorph.Node.isEnumDeclaration(e)||tsMorph.Node.isClassDeclaration(e)||tsMorph.Node.isVariableDeclaration(e))return e.getName()}searchTypeDefinitions(e){var o;for(let i of e)if((((o=this.typeIndex.get(i))==null?void 0:o.length)||0)>1&&!this.typeIndexQualified.has(i))throw new Error(`Multiple definition declarations found for ${i}`);let t=[],n=new Set,r=[...e];for(;r.length>0;){let i=r.shift();if(n.has(i))continue;let a=this.typeIndexQualified.get(i);if(!a){let m=this.typeIndex.get(i);m&&m.length>0&&m.forEach(f=>{let h=this.qualifiedNames.get(f.node);h&&!n.has(h)&&!r.includes(h)&&r.push(h);});continue}let c=this.getNodeName(a.node)??i,d=this.qualifiedNames.get(a.node)??i,g=(Ee.find(m=>m.getDeclaration(a.sourceFile,c))||{getText:m=>m.getType().getText(void 0,tsMorph.TypeFormatFlags.NoTruncation)}).getText(a.node);d!==c&&(g=g.replace(new RegExp(`\\b${c}\\b`,"g"),d));let p=new Map;a.node.forEachDescendant(m=>{if(tsMorph.Node.isTypeReference(m)){let f=m.getTypeName();if(tsMorph.Node.isIdentifier(f)){let h=f.getText();if(O(h)||p.has(h))return;let y=f.getSymbol();if(!y)return;let b=(y.getAliasedSymbol()||y).getDeclarations();if(b.length===0)return;let v=b[0],P=this.qualifiedNames.get(v);P&&P!==h&&p.set(h,P);}m.getTypeArguments().forEach(h=>{if(tsMorph.Node.isTypeReference(h)){let y=h.getTypeName();if(tsMorph.Node.isIdentifier(y)){let x=y.getText();if(O(x)||p.has(x))return;let b=y.getSymbol();if(!b)return;let P=(b.getAliasedSymbol()||b).getDeclarations();if(P.length===0)return;let E=P[0],N=this.qualifiedNames.get(E);N&&N!==x&&p.set(x,N);}}});}});for(let[m,f]of p)g=g.replace(new RegExp(`\\b${m}\\b`,"g"),f);t.push(g),this.extractTypeReferences(a.node).forEach(m=>{!n.has(m)&&!r.includes(m)&&!O(m)&&r.push(m);}),n.add(i);}return t}extractTypeNames(e){let t=/([a-zA-Z_][a-zA-Z0-9_]*)/g,n=new Set;for(let r of e)if(r){let o=r.match(t);o&&o.forEach(i=>{if(!O(i)){let a=this.typeIndex.get(i);a?a.forEach(c=>{let d=this.qualifiedNames.get(c.node)??i;n.add(d);}):n.add(i);}});}return [...n]}extractTypeReferences(e){let t=new Set;return e.forEachDescendant(n=>{if(tsMorph.Node.isTypeReference(n)){let r=n.getTypeName();if(tsMorph.Node.isIdentifier(r)){let o=r.getText();if(O(o))return;let i=r.getSymbol();if(!i)return;let c=(i.getAliasedSymbol()||i).getDeclarations();if(c.length===0)return;let d=c[0],u=this.qualifiedNames.get(d)??o;t.add(u);}n.getTypeArguments().forEach(o=>{if(tsMorph.Node.isTypeReference(o)){let i=o.getTypeName();if(tsMorph.Node.isIdentifier(i)){let a=i.getText();if(O(a))return;let c=i.getSymbol();if(!c)return;let u=(c.getAliasedSymbol()||c).getDeclarations();if(u.length===0)return;let g=u[0],p=this.qualifiedNames.get(g)??a;t.add(p);}}});}}),[...t]}};var mt=s=>"model"in s,ft=s=>"inline"in s,yt=s=>"type"in s,ht=s=>ft(s)||yt(s);function Tt(s){let e={};for(let{path:t,method:n,query:r,request:o,responses:i}of s)n&&(e[t]||(e[t]={}),e[t][n.toUpperCase()]={query:r??"never",request:o??"never",responses:i??"never"});return e}var w=s=>" ".repeat(s),xt=s=>{let e=`{
212
+ `;for(let[t,n]of Object.entries(s)){e+=`${w(1)}["${t}"]: {
213
+ `;for(let[r,o]of Object.entries(n))e+=`${w(2)}${r}: {
214
+ `,o.query&&(e+=`${w(3)}query: ${o.query};
215
+ `),e+=`${w(3)}request: ${o.request};
216
+ `,typeof o.responses=="string"||!Object.keys(o.responses||{}).length?e+=`${w(3)}responses: never;
217
+ `:(e+=`${w(3)}responses: {
218
+ `,Object.entries(o.responses||{}).forEach(([i,a])=>{e+=`${w(4)}${i.replace(/[^0-9]/g,"")}: ${a};
219
+ `;}),e+=`${w(3)}};
220
+ `),e+=`${w(2)}};
221
+ `;e+=`${w(1)}};
222
+ `;}return e+="}",e};function de(s){let t=s.path.replace(/^\/+|\/+$/g,"").split("?")[0].split("/").flatMap(r=>r.split(/[-_]/)).map(r=>{if(r.startsWith(":")){let o=r.slice(1);return "By"+o.charAt(0).toUpperCase()+o.slice(1)}return r}),n=r=>r.charAt(0).toUpperCase()+r.slice(1);return [n(s.method.toLowerCase()),...t.map(n)].join("")}var L=class{constructor(e,t){this.config=e;this.typesLookupModule=new X(t),this.schemaBuilderModule=new Z(t),this.definitionsResolverModule=new K;}typesLookupModule;schemaBuilderModule;definitionsResolverModule;async generate(e){this.typesLookupModule.buildTypeIndexes();let t=new Map,n=new Map;e.forEach((m,f)=>{t.set(m.path,f);});for(let m of e){let f=m.domains||["api"],h=m.disabledDomains||{};f.forEach(y=>{var x;h[y]||typeof h[y]!="boolean"&&h["*"]||(n.get(y)||n.set(y,[]),(x=n.get(y))==null||x.push(m.path));});}let r=process.cwd(),o=this.config.outputPath?He.resolve(r,this.config.outputPath):r;await be.mkdir(o,{recursive:true});let i=[],{resolvedEndpoints:a,typesToResolve:c}=this.prepareEndpointsWithTypes(e,Array.from(n.keys())),d=this.typesLookupModule.lookupNode(c.filter(mt)),u=[...c.filter(ht),...d],g=this.schemaBuilderModule.generateSchema(u),p=Object.keys(g.mappedReferences).length>0?a.map(m=>{let{request:f,responses:h,query:y}=m,x=g.mappedReferences[y||""]||y,b=g.mappedReferences[f||""]||f,v=h&&Object.fromEntries(Object.entries(h).map(([P,E])=>[P,g.mappedReferences[E||""]||E]));return {...m,...x&&{query:x},...b&&{request:b},...v&&{responses:v}}}):a,l={endpoints:p,schema:g};this.config.generateSchemaFiles!==false&&await be.writeFile("api-schema.json",JSON.stringify(l,null,2),"utf-8");for(let[m,f]of n.entries()){let h=p.filter(A=>f.includes(A.path)),y=new Set,x=new Set;h.forEach(A=>{typeof A.query=="string"&&A.query&&x.add(A.query),typeof A.request=="string"&&A.request&&x.add(A.request),A.responses&&Object.values(A.responses).forEach($=>{typeof $=="string"&&$&&x.add($);});});let b={...g.schema,...g.refs};for(;x.size>0;){let A=x.values().next().value;if(x.delete(A),y.has(A))continue;y.add(A);let $=b[A];if(!$)continue;let R=S=>{if("type"in S&&S.type==="ref"&&"name"in S&&S.name){y.has(S.name)||x.add(S.name);return}"anyOf"in S&&Array.isArray(S.anyOf)&&S.anyOf.forEach(R),"allOf"in S&&Array.isArray(S.allOf)&&S.allOf.forEach(R),"properties"in S&&S.properties&&Object.values(S.properties).forEach(R),"indexedProperties"in S&&S.indexedProperties&&R(S.indexedProperties),"items"in S&&(Array.isArray(S.items)?S.items.forEach(R):S.items&&R(S.items));};R($);}let v={schema:{},refs:{}};for(let A of y)g.schema[A]&&(v.schema[A]=g.schema[A]),g.refs[A]&&(v.refs[A]=g.refs[A]);let P=this.definitionsResolverModule.generate(v),E=this.assemblyOutput({domain:m,endpoints:h,typesDefinitions:P}),N=`${m}-types.d.ts`,re=He.join(o,N);i.push(be.writeFile(re,E,"utf-8"));}return await Promise.all(i),l}prepareEndpointsWithTypes(e,t){let n=[],r=[];for(let o of e){let i=o.query?{...o.query,name:"name"in o.query&&o.query.name||`${de(o)}Query`}:null,a=o.request?{name:o.request.name||`${de(o)}Request`,..."model"in o.request?{model:o.request.model}:{type:o.request.type,node:o.request.node}}:null,c=o.responses?Object.fromEntries(Object.entries(o.responses).map(([p,l])=>[p,{name:l.name||`${de(o)}${Object.keys(o.responses||{}).length>0?p:""}Response`,..."model"in l?{model:l.model}:{type:l.type,node:l.node}}])):null,d=o.disabledDomains||{},u=d["*"]===true,g=t.filter(p=>{let l=d[p];return l!==void 0?l:u});n.push({path:o.path,method:o.method,query:i==null?void 0:i.name,domains:o.domains||["api"],disabledDomains:g,request:a==null?void 0:a.name,responses:c?Object.fromEntries(Object.entries(c).map(([p,{name:l}])=>[p,l])):void 0}),i&&r.push(i),a&&r.push(a),c&&r.push(...Object.values(c));}return {resolvedEndpoints:n,typesToResolve:r}}assemblyOutput({domain:e,endpoints:t,typesDefinitions:n}){let r=Array.from(new Set(t.map(a=>{var c;return (c=a.method)==null?void 0:c.toUpperCase()}).filter(Boolean))),o=[`// Auto-generated API types for domain: ${e}
223
+
224
+ `];o.push(`${n}
225
+
226
+ `),r.length>0?o.push(`export type ApiMethod = ${r.map(a=>`'${a}'`).join(" | ")};
227
+
228
+ `):o.push(`export type ApiMethod = never;
229
+
230
+ `),o.push(`${Pe}
231
+
232
+ `);let i=Tt(t);return o.push(`export type Api = BuildApi<${xt(i)}>;
233
+
234
+ `),o.push(De),o.join("")}};var Mt=s=>{let e=s.getEmitOutput({emitOnlyDtsFiles:false});for(let t of e.getOutputFiles()){let n=t.getFilePath();if(n.endsWith(".js"))return n}return null},H=class{constructor(){}async import(e,t=false){let n=new Map,r=Array.from(e).map(async o=>{let i=o.getFilePath();try{let a=await this.importFile(o,t);a&&n.set(i,a);}catch(a){console.error(`Unable to load file at path: ${i}`,a);}});return await Promise.all(r),n}async importFile(e,t=false){let n=Mt(e);if(!n)return null;await be__default.default.access(n,Le.constants.R_OK),t&&delete fe.cache[n];let r=`${n}${t?`?v=${Date.now()}`:""}`;if(!r.startsWith(process.cwd()))throw new Error("Invalid path");let o=await import(r);return o.default||o}};var J=class{constructor(e){this.config=e;this.plugins=this.resolveDependencies();}plugins=[];getPluginsCount(){return this.plugins.length}resolveDependencies(){let e=new Map,t=new Map,n=new Set,r=new Set,o=[],i=c=>{var d,u;if(!c.name)throw new Error("Plugin missing name");e.has(c.name)||(e.set(c.name,c),t.set(c.name,((d=c.dependencies)==null?void 0:d.map(g=>{var p;if(!((p=g.plugin.config)!=null&&p.shareable))throw new Error(`Dependency ${g.plugin.name} is not a ShareablePlugin`);return g.plugin.name}))||[]),(u=c.dependencies)==null||u.forEach(g=>i(g.plugin)));};this.config.plugins.forEach(c=>i(c));let a=c=>{if(r.has(c))throw new Error(`Circular dependency detected involving plugin: ${c}`);if(n.has(c))return;r.add(c),(t.get(c)||[]).forEach(g=>{if(!e.has(g))throw new Error(`Dependency ${g} not found`);a(g);}),r.delete(c),n.add(c);let u=e.get(c);o.push(u);};return e.forEach((c,d)=>a(d)),o}async executeHook(e,...t){if(e==="onInitialize")return this.runOnInitializeHook(...t);if(e==="onAfterDecoratorsProcessed")return this.runOnAfterDecoratorProcessed();if(e==="onRegisterMetadata")return this.runOnRegisterMetadata(...t);if(e==="onConsumeDependencyContexts")return this.runOnConsumeDependencies();if(e==="onGenerateTypes")return this.runOnGenerateTypes(...t)}async runOnInitializeHook(...e){await Promise.all(this.plugins.map(t=>t.hooks.onInitialize(...e)));}runOnAfterDecoratorProcessed(){this.plugins.forEach(e=>{var t,n;return (n=(t=e.hooks).onAfterDecoratorsProcessed)==null?void 0:n.call(t)});}runOnRegisterMetadata(...e){this.plugins.forEach(t=>{var o;(!this.config.plugins.every(i=>i.name!==t.name)||((o=t.dependencies)==null?void 0:o.some(i=>{var a;return (a=i.options)==null?void 0:a.allowContextManipulation})))&&t.hooks.onRegisterMetadata&&t.hooks.onRegisterMetadata(...e);});}runOnGenerateTypes(...e){this.plugins.forEach(t=>{var o;(!this.config.plugins.every(i=>i.name!==t.name)||((o=t.dependencies)==null?void 0:o.some(i=>{var a;return (a=i.options)==null?void 0:a.allowContextManipulation})))&&t.hooks.onGenerateTypes&&t.hooks.onGenerateTypes(...e);});}runOnConsumeDependencies(){let e=new WeakMap;this.plugins.filter(t=>{var n;return ((n=t.dependencies)==null?void 0:n.length)&&"onConsumeDependencyContexts"in t.hooks}).forEach(t=>{let n=t,r=n.dependencies.map(o=>{e.has(o.plugin)||e.set(o.plugin,o.plugin.hooks.onProvideSharedContext());let i=e.get(o.plugin);if(!i)throw new Error(`Shared context not found for dependency ${o.plugin.name}`);return i});n.hooks.onConsumeDependencyContexts(r);});}};var we=["ApinniController","ApinniEndpoint","ApinniDomain","ApinniDisabled"];var W=class{project;constructor(e){var t;this.project=(e==null?void 0:e.project)??new tsMorph.Project({tsConfigFilePath:He.join(process.cwd(),"tsconfig.json"),skipAddingFilesFromTsConfig:false,skipFileDependencyResolution:true,compilerOptions:{lib:["lib.es2024.d.ts"],strictNullChecks:true,strict:true,...!((t=e==null?void 0:e.options)!=null&&t.useExistingBuild)&&{module:tsMorph.ModuleKind.CommonJS,moduleResolution:tsMorph.ModuleResolutionKind.Node16,outDir:"./.apinni/build"}}});}getProject(){return this.project}restartProject(){this.project=new tsMorph.Project({tsConfigFilePath:He.join(process.cwd(),"tsconfig.json"),skipAddingFilesFromTsConfig:false,skipFileDependencyResolution:true,compilerOptions:this.project.getCompilerOptions()});}async traverseAndCacheTsMorph(){return new Promise(e=>{this.project.getSourceFiles().forEach(t=>{t.getReferencedSourceFiles(),t.getReferencingSourceFiles(),t.getClasses().map(n=>n.getMethods());}),e(true);})}getFileTypeOfSourceFile(e,t=[]){let{decoratorTypeMap:n,decoratorNames:r}=this.prepareDecoratorsMap(t),o=null;return this.processDecoratorsInSourceFile(e,r,i=>(o=n.get(i),o==="run-time")),{type:o}}getSourceFilesWithDecorators(e=[]){let{decoratorTypeMap:t,decoratorNames:n}=this.prepareDecoratorsMap(e),r=[];for(let o of this.project.getSourceFiles()){let i=null;this.processDecoratorsInSourceFile(o,n,a=>(i=t.get(a),i==="run-time")),i&&r.push({sourceFile:o,type:i});}return r}buildDecoratorImportMapForSourceFile(e,t){var o;let n=new Map,r=new Set(t);for(let i of e.getImportDeclarations())for(let a of i.getNamedImports()){let c=a.getNameNode().getText(),d=((o=a.getAliasNode())==null?void 0:o.getText())??c;r.has(c)&&(n.set(d,c),r.delete(c));}return r.forEach(i=>n.set(i,i)),n}processDecoratorsInSourceFile(e,t,n){let r=this.buildDecoratorImportMapForSourceFile(e,t);for(let o of e.getClasses()){for(let i of o.getDecorators()){let a=r.get(i.getName());if(a&&n(a))return}for(let i of o.getMethods())for(let a of i.getDecorators()){let c=r.get(a.getName());if(c&&n(c))return}}}prepareDecoratorsMap(e=[]){let t=new Map([...we.map(r=>[r,"compile-time"]),...e.map(r=>[r.name,r.type])]),n=new Set(t.keys());return {decoratorTypeMap:t,decoratorNames:n}}};var ee=class{constructor(e,t){this.options=t;this.decoratorRegistry=new j,this.pluginManager=new J(e),this.scannerModule=new W,this.compilerModule=new k,this.importerModule=new H,this.decoratorsModule=new _,this.generatorModule=new L(e,this.scannerModule.getProject());}decoratorRegistry;pluginManager;scannerModule;compilerModule;importerModule;decoratorsModule;generatorModule;async run(){await new listr2.Listr([{title:"Preparation Phase",task:(t,n)=>n.newListr([{title:"Caching referencing files",task:async()=>{await this.scannerModule.traverseAndCacheTsMorph();}},{title:"Initializing plugins",task:async(r,o)=>{await this.pluginManager.executeHook("onInitialize",{register:a=>this.decoratorRegistry.register(a)},"default");let i=this.pluginManager.getPluginsCount();o.title+=` (${i} plugin${i===1?"":"s"} loaded)`;}}])},{title:"Core Processing",task:(t,n)=>n.newListr([{title:"Scanning for decorators",task:(r,o)=>{let i=this.scannerModule.getSourceFilesWithDecorators(this.decoratorRegistry.getRegisteredDecorators());t.filesWithDecorators=i,r.filesToImport=i.filter(({type:c})=>c==="run-time").map(({sourceFile:c})=>c);let a=i.length;o.title+=`(${a} file${a===1?"":"s"} found)`;}},{title:"Compiling files with decorators",task:async(r,o)=>{if(this.options.useExistingBuild)return o.skip("Skipped compilation (using existing build)");let i=await this.compilerModule.compileFiles(r.filesToImport,{force:false});o.title+=` (${i} file${i===1?"":"s"} compiled)`;}},{title:"Resolving decorators",task:async(r,o)=>o.newListr([{title:"Loading modules",task:async(i,a)=>{i.modules=await this.importerModule.import(r.filesToImport);let c=i.modules.size;a.title+=` (${c} module${c===1?"":"s"} loaded)`;}},{title:"Processing decorators",task:async(i,a)=>{let c=this.decoratorsModule.processDecorators({filesWithDecorators:t.filesWithDecorators,modules:i.modules},d=>this.decoratorRegistry.processEvent("register",d));a.title+=` (${c} decorator${c===1?"":"s"} processed)`;}}],{ctx:{modules:new Map}})}],{ctx:{filesToImport:[]}})},{title:"Finalization",task:(t,n)=>n.newListr([{title:"Executing plugin hooks",task:async()=>{await this.pluginManager.executeHook("onAfterDecoratorsProcessed"),await this.pluginManager.executeHook("onConsumeDependencyContexts");let r=M.getInstance();await this.pluginManager.executeHook("onRegisterMetadata",{registerClassMetadata:(...o)=>r.registerClassMetadata(...o),registerMethodMetadata:(...o)=>r.registerMethodMetadata(...o)});}},{title:"Generating types",task:async()=>{let r=M.getInstance(),o=await this.generatorModule.generate(r.getPreparedData());await this.pluginManager.executeHook("onGenerateTypes",o);}}])}],{rendererOptions:{timer:listr2.PRESET_TIMER,collapseSubtasks:false},ctx:{filesWithDecorators:[]}}).run();}};var T={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",gray:"\x1B[90m"},z=`${T.bold}${T.cyan}[Apinni]${T.reset}`;function Re(s){return s?`${T.green}${s}${T.reset}`:""}function Ie(s=44){return `${T.cyan}${"─".repeat(s)}${T.reset}`}function Oe(s){console.log(Ie()),console.log(`${T.bold}${T.cyan}đŸ› ī¸ Apinni${T.reset} | ${T.green}TypeScript ${s}${T.reset}`),console.log(Ie());}function je(){console.log(""),console.log(`${z} â–ļ ${T.bold}Watching for file changes${T.reset} — press ${T.bold}Ctrl+C${T.reset} to exit.`),console.log("");}function ke(s,e){let n={add:"➕",change:"âœī¸ ",unlink:"đŸ—‘ī¸ ",coldStart:"🚀"}[s]??"â„šī¸";console.log(`${z} ${n} ${T.bold}${s.toUpperCase()}${T.reset} ${Re(e)}`);}function _e(s,e,t,n){let o={coldStart:`Initialized with ${n??0} endpoints`,add:"New file analyzed",change:"Changes processed",unlink:"File removed"}[s]??"Done";console.log(`${z} ✅ ${o} ${Re(e)} ${T.gray}(${t.toFixed(2)}s)${T.reset}`),console.log("");}function ue(s){console.log(`${z} ℹ ${T.dim}${s}${T.reset}`);}function qe(s){console.warn(`${z} ⚠ ${T.yellow}${s}${T.reset}`);}function Be(s){console.error(`${z} ✖ ${T.red}${s}${T.reset}`);}var ne=class{constructor(e){this.config=e;this.decoratorRegistry=new j,this.pluginManager=new J(e),this.scannerModule=new W,this.compilerModule=new k,this.importerModule=new H,this.decoratorsModule=new _;}decoratorRegistry;pluginManager;scannerModule;compilerModule;importerModule;decoratorsModule;localModuleContext=new Map;registeredParams=new Map;isProcessing=false;actionsQueue=[];async run(){Oe("1.0.0"),await this.coldStart(),je();let e=Nt__default.default.watch(".",{persistent:true,ignoreInitial:true,ignored:["node_modules",".apinni","build","dist",(t,n)=>!!(n!=null&&n.isFile()&&(t.endsWith(".d.ts")||!t.endsWith(".ts")))]});e.on("add",async t=>{this.actionsQueue.push({event:"add",path:t}),await this.processChanges();}),e.on("change",async t=>{this.actionsQueue.push({event:"change",path:t}),await this.processChanges();}),e.on("unlink",async t=>{this.actionsQueue.push({event:"unlink",path:t}),await this.processChanges();});}async coldStart(){this.actionsQueue.push({event:"coldStart"}),await this.processChanges();}async processChanges(){if(this.isProcessing||this.actionsQueue.length===0)return;this.isProcessing=true;let e=this.actionsQueue.shift();try{e&&await this.handleEvent(e);}catch(t){console.error(`Error processing event: ${t}`);}finally{this.isProcessing=false,this.actionsQueue.length>0&&await this.processChanges();}}async handleEvent(e){let t=performance.now(),{event:n,path:r}=e;if(ke(n,r),n==="coldStart")try{await this.pluginManager.executeHook("onInitialize",{register:l=>this.decoratorRegistry.register(l)},"watch"),ue(`Initialized plugins: ${this.pluginManager.getPluginsCount()}`);try{let l=this.decoratorRegistry.getRegisteredDecorators(),m=this.scannerModule.getSourceFilesWithDecorators(l);ue(`Found ${m.length} files with decorators`);}catch(l){qe(`Could not evaluate files with decorators: ${String(l)}`);}}catch(l){Be(`Plugin initialization failed: ${String(l)}`);}let o=[],i;if(r&&(i=He.join(process.cwd(),r)),["add","change","unlink"].includes(n)&&i){let l=this.getAffectedFilePaths(n,r);for(let m of l){let f=this.registeredParams.get(m)||[];for(let y of f)this.decoratorRegistry.processEvent("unregister",y);let h=new Set(f.map(({target:y})=>y));for(let y of h)M.getInstance().removeMetadataByTarget(y);this.registeredParams.delete(m);}}await this.updateProject(n,r),o=this.getAffectedFilesWithDecorators(n,r);let a=new Map;if(n!=="unlink"||o.length>0){let l=this.filterRuntimeFiles(o);l.length>0&&(await this.compilerModule.compileFiles(l,{force:n==="coldStart"}),a=await this.importerModule.import(l),a.forEach((m,f)=>this.localModuleContext.set(f,m)));}else n==="unlink"&&i&&this.localModuleContext.has(i)&&this.localModuleContext.delete(i);o.length>0&&this.decoratorsModule.processDecorators({filesWithDecorators:o,modules:n==="coldStart"?this.localModuleContext:a},l=>{this.decoratorRegistry.processEvent("register",l);let m=l.sourceFile.getFilePath();return this.registeredParams.has(m)||this.registeredParams.set(m,[]),this.registeredParams.get(m).push(l),true}),await this.pluginManager.executeHook("onAfterDecoratorsProcessed"),await this.pluginManager.executeHook("onConsumeDependencyContexts");let c=M.getInstance();await this.pluginManager.executeHook("onRegisterMetadata",{registerClassMetadata:(...l)=>c.registerClassMetadata(...l),registerMethodMetadata:(...l)=>c.registerMethodMetadata(...l)});let d=c.getPreparedData(),g=await new L(this.config,this.scannerModule.getProject()).generate(d);await this.pluginManager.executeHook("onGenerateTypes",g);let p=(performance.now()-t)/1e3;_e(n,r,p,d.length);}async updateProject(e,t){let n=this.scannerModule.getProject();if(e==="coldStart"){await this.scannerModule.traverseAndCacheTsMorph();return}if(!t)return;let r=He.join(process.cwd(),t),o=n.getSourceFile(r);e==="add"||e==="change"?o?this.scannerModule.restartProject():o=n.addSourceFileAtPath(r):e==="unlink"&&o&&n.removeSourceFile(o);}getAffectedFilePaths(e,t){if(e==="coldStart"||!t)return [];let n=He.join(process.cwd(),t),o=this.scannerModule.getProject().getSourceFile(n);if(!o)return [n];let i=[];try{i=o.getReferencingSourceFiles().map(c=>c.getFilePath());}catch(c){console.warn(`Error getting referencing files for ${n}: ${c}`);}let a=new Set([n,...i]);return Array.from(a)}getAffectedFilesWithDecorators(e,t){let n=this.decoratorRegistry.getRegisteredDecorators();if(e==="coldStart")return this.scannerModule.getSourceFilesWithDecorators(n);if(!t)return [];let r=He.join(process.cwd(),t),o=this.scannerModule.getProject(),i=[],a=o.getSourceFile(r);a&&e!=="unlink"&&(i=[a]);let c=[];if(a)try{c=a.getReferencingSourceFiles();}catch(u){console.warn(`Error getting referencing files for ${r}: ${u}`);}return [...i,...c].map(u=>{try{let{type:g}=this.scannerModule.getFileTypeOfSourceFile(u,n);return g?{sourceFile:u,type:g}:null}catch(g){return console.warn(`Error accessing source file ${u.getFilePath()}: ${g}`),null}}).filter(u=>u!==null)}filterRuntimeFiles(e){return e.filter(({type:t})=>t==="run-time").map(({sourceFile:t})=>t)}};async function ge(s,e){await(e.watch?new ne(s):new ee(s,e)).run();}var $t=["apinni.config.ts","apinni.config.js","apinni.config.mjs","apinni.config.cjs"];async function me(s=process.cwd()){for(let e of $t){let t=He__namespace.join(s,e);if(Le__namespace.existsSync(t)){let{mod:n}=await bundleRequire.bundleRequire({filepath:t});return n.default||n}}throw new Error("No apinni.config.ts, .js, cjs or .mjs found in project root")}commander.program.version("1.0.0").description("Apinni CLI for generating types with decorators").option("-u, --use-existing-build","use existing project build instead of building it");commander.program.command("generate").description("Generate types with decorators").action(async()=>{let{useExistingBuild:s}=commander.program.opts();try{let e=await me();await ge(e,{useExistingBuild:s,watch:!1});}catch(e){console.error("Error:",e.message),process.exit(1);}});commander.program.command("watch").description("Run in watch mode for generating types with decorators").action(async()=>{try{let s=await me();await ge(s,{watch:!0});}catch(s){console.error("Error:",s.message),process.exit(1);}});commander.program.exitOverride(s=>{s.code==="commander.unknownOption"&&commander.program.outputHelp();}).parse(process.argv);//# sourceMappingURL=cli.js.map
235
+ //# sourceMappingURL=cli.js.map