swagger2api-v3 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.
@@ -0,0 +1,30 @@
1
+ import { SwaggerConfig } from './types';
2
+ /**
3
+ * Swagger2API 主类
4
+ */
5
+ export declare class Swagger2API {
6
+ private config;
7
+ constructor(config: SwaggerConfig);
8
+ /**
9
+ * 生成API接口文件
10
+ */
11
+ generate(): Promise<void>;
12
+ /**
13
+ * 验证配置
14
+ */
15
+ validateConfig(): boolean;
16
+ }
17
+ /**
18
+ * 从配置文件生成API
19
+ * @param configPath 配置文件路径
20
+ */
21
+ export declare function generateFromConfig(configPath?: string): Promise<void>;
22
+ /**
23
+ * 直接使用配置对象生成API
24
+ * @param config 配置对象
25
+ */
26
+ export declare function generate(config: SwaggerConfig): Promise<void>;
27
+ export * from './types';
28
+ export { SwaggerParser } from './core/parser';
29
+ export { CodeGenerator } from './core/generator';
30
+ export * from './utils';
package/dist/index.js ADDED
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
36
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.CodeGenerator = exports.SwaggerParser = exports.Swagger2API = void 0;
40
+ exports.generateFromConfig = generateFromConfig;
41
+ exports.generate = generate;
42
+ const path = __importStar(require("path"));
43
+ const parser_1 = require("./core/parser");
44
+ const generator_1 = require("./core/generator");
45
+ const utils_1 = require("./utils");
46
+ /**
47
+ * Swagger2API 主类
48
+ */
49
+ class Swagger2API {
50
+ constructor(config) {
51
+ this.config = config;
52
+ }
53
+ /**
54
+ * 生成API接口文件
55
+ */
56
+ async generate() {
57
+ try {
58
+ console.log('🚀 开始生成API接口文件...');
59
+ // 1. 加载Swagger文档
60
+ console.log('📖 加载Swagger文档...');
61
+ const document = await (0, utils_1.loadSwaggerDocument)(this.config.input);
62
+ console.log(`✅ 成功加载文档: ${document.info.title} v${document.info.version}`);
63
+ // 2. 解析文档
64
+ console.log('🔍 解析API接口...');
65
+ const parser = new parser_1.SwaggerParser(document, this.config);
66
+ const apis = parser.parseApis();
67
+ const types = parser.parseTypes();
68
+ const groupedApis = parser.groupApisByTags(apis);
69
+ console.log(`✅ 解析完成: ${apis.length} 个接口, ${types.length} 个类型`);
70
+ if (this.config.groupByTags) {
71
+ console.log(`📁 按标签分组: ${groupedApis.size} 个分组`);
72
+ for (const [tag, tagApis] of groupedApis) {
73
+ console.log(` - ${tag}: ${tagApis.length} 个接口`);
74
+ }
75
+ }
76
+ // 3. 生成代码
77
+ console.log('⚡ 生成代码文件...');
78
+ const generator = new generator_1.CodeGenerator(this.config);
79
+ await generator.generateAll(apis, types, groupedApis);
80
+ console.log(`✅ 代码生成完成,输出目录: ${this.config.output}`);
81
+ }
82
+ catch (error) {
83
+ console.error('❌ 生成失败:', error);
84
+ throw error;
85
+ }
86
+ }
87
+ /**
88
+ * 验证配置
89
+ */
90
+ validateConfig() {
91
+ const errors = [];
92
+ if (!this.config.input) {
93
+ errors.push('input 配置项不能为空');
94
+ }
95
+ if (!this.config.output) {
96
+ errors.push('output 配置项不能为空');
97
+ }
98
+ if (this.config.generator !== 'typescript') {
99
+ errors.push('目前只支持 typescript 生成器');
100
+ }
101
+ if (errors.length > 0) {
102
+ console.error('❌ 配置验证失败:');
103
+ errors.forEach(error => console.error(` - ${error}`));
104
+ return false;
105
+ }
106
+ return true;
107
+ }
108
+ }
109
+ exports.Swagger2API = Swagger2API;
110
+ /**
111
+ * 从配置文件生成API
112
+ * @param configPath 配置文件路径
113
+ */
114
+ async function generateFromConfig(configPath) {
115
+ const configFile = configPath || '.swagger.config.ts';
116
+ const fullPath = path.resolve(process.cwd(), configFile);
117
+ try {
118
+ // 动态导入配置文件
119
+ const configModule = await Promise.resolve(`${fullPath}`).then(s => __importStar(require(s)));
120
+ const config = configModule.default || configModule;
121
+ const swagger2api = new Swagger2API(config);
122
+ if (!swagger2api.validateConfig()) {
123
+ process.exit(1);
124
+ }
125
+ await swagger2api.generate();
126
+ }
127
+ catch (error) {
128
+ if (error instanceof Error && error.message.includes('Cannot resolve module')) {
129
+ console.error(`❌ 找不到配置文件: ${fullPath}`);
130
+ console.error('请确保配置文件存在并且路径正确');
131
+ }
132
+ else {
133
+ console.error('❌ 加载配置文件失败:', error);
134
+ }
135
+ process.exit(1);
136
+ }
137
+ }
138
+ /**
139
+ * 直接使用配置对象生成API
140
+ * @param config 配置对象
141
+ */
142
+ async function generate(config) {
143
+ const swagger2api = new Swagger2API(config);
144
+ if (!swagger2api.validateConfig()) {
145
+ throw new Error('配置验证失败');
146
+ }
147
+ await swagger2api.generate();
148
+ }
149
+ // 导出类型和工具
150
+ __exportStar(require("./types"), exports);
151
+ var parser_2 = require("./core/parser");
152
+ Object.defineProperty(exports, "SwaggerParser", { enumerable: true, get: function () { return parser_2.SwaggerParser; } });
153
+ var generator_2 = require("./core/generator");
154
+ Object.defineProperty(exports, "CodeGenerator", { enumerable: true, get: function () { return generator_2.CodeGenerator; } });
155
+ __exportStar(require("./utils"), exports);
@@ -0,0 +1,363 @@
1
+ /**
2
+ * Swagger2API 类型定义
3
+ */
4
+ /**
5
+ * Swagger配置接口
6
+ */
7
+ export interface SwaggerConfig {
8
+ /** Swagger JSON 文件路径或 URL */
9
+ input: string;
10
+ /** 输出目录 */
11
+ output: string;
12
+ /** 生成器类型 */
13
+ generator: 'typescript';
14
+ /** 按 tags 分组生成文件 */
15
+ groupByTags: boolean;
16
+ /** 是否覆盖更新,默认为true。为true时会先删除输出目录下的所有文件 */
17
+ overwrite?: boolean;
18
+ /** 接口路径公共前缀,默认为空字符串 */
19
+ prefix?: string;
20
+ /** 标签分组配置 */
21
+ tagGrouping?: TagGroupingConfig;
22
+ /** 生成选项 */
23
+ options?: GenerationOptions;
24
+ /** 接口注释配置 */
25
+ comments?: CommentConfig;
26
+ /** request 导入路径模板 */
27
+ importTemplate?: string;
28
+ /** 格式化代码命令 */
29
+ lint?: string;
30
+ }
31
+ /**
32
+ * 标签分组配置
33
+ */
34
+ export interface TagGroupingConfig {
35
+ /** 启用标签分组 */
36
+ enabled: boolean;
37
+ /** 为每个标签创建子目录 */
38
+ createSubDirectories: boolean;
39
+ /** 文件命名方式 */
40
+ fileNaming: 'tag' | 'kebab-case' | 'camelCase';
41
+ }
42
+ /**
43
+ * 生成选项
44
+ */
45
+ export interface GenerationOptions {
46
+ /** 是否生成数据模型 */
47
+ generateModels: boolean;
48
+ /** 是否生成 API 接口 */
49
+ generateApis: boolean;
50
+ /** 是否生成入口文件 */
51
+ generateIndex: boolean;
52
+ /** 是否使用 Axios */
53
+ useAxios: boolean;
54
+ /** 是否添加详细注释 */
55
+ addComments: boolean;
56
+ /** 是否格式化代码 */
57
+ prettify: boolean;
58
+ }
59
+ /**
60
+ * 注释配置
61
+ */
62
+ export interface CommentConfig {
63
+ /** 包含接口描述 */
64
+ includeDescription: boolean;
65
+ /** 包含参数信息 */
66
+ includeParameters: boolean;
67
+ /** 包含返回值信息 */
68
+ includeResponses: boolean;
69
+ /** 包含示例 */
70
+ includeExamples: boolean;
71
+ }
72
+ /**
73
+ * Swagger文档结构
74
+ */
75
+ export interface SwaggerDocument {
76
+ swagger?: string;
77
+ openapi?: string;
78
+ info: SwaggerInfo;
79
+ host?: string;
80
+ basePath?: string;
81
+ schemes?: string[];
82
+ consumes?: string[];
83
+ produces?: string[];
84
+ paths: SwaggerPaths;
85
+ definitions?: SwaggerDefinitions;
86
+ components?: SwaggerComponents;
87
+ tags?: SwaggerTag[];
88
+ }
89
+ /**
90
+ * Swagger信息
91
+ */
92
+ export interface SwaggerInfo {
93
+ title: string;
94
+ description?: string;
95
+ version: string;
96
+ termsOfService?: string;
97
+ contact?: SwaggerContact;
98
+ license?: SwaggerLicense;
99
+ }
100
+ /**
101
+ * Swagger联系信息
102
+ */
103
+ export interface SwaggerContact {
104
+ name?: string;
105
+ url?: string;
106
+ email?: string;
107
+ }
108
+ /**
109
+ * Swagger许可证信息
110
+ */
111
+ export interface SwaggerLicense {
112
+ name: string;
113
+ url?: string;
114
+ }
115
+ /**
116
+ * Swagger路径定义
117
+ */
118
+ export interface SwaggerPaths {
119
+ [path: string]: SwaggerPathItem;
120
+ }
121
+ /**
122
+ * Swagger路径项
123
+ */
124
+ export interface SwaggerPathItem {
125
+ get?: SwaggerOperation;
126
+ post?: SwaggerOperation;
127
+ put?: SwaggerOperation;
128
+ delete?: SwaggerOperation;
129
+ patch?: SwaggerOperation;
130
+ head?: SwaggerOperation;
131
+ options?: SwaggerOperation;
132
+ parameters?: SwaggerParameter[];
133
+ }
134
+ /**
135
+ * Swagger操作
136
+ */
137
+ export interface SwaggerOperation {
138
+ tags?: string[];
139
+ summary?: string;
140
+ description?: string;
141
+ operationId?: string;
142
+ consumes?: string[];
143
+ produces?: string[];
144
+ parameters?: SwaggerParameter[];
145
+ requestBody?: SwaggerRequestBody;
146
+ responses: SwaggerResponses;
147
+ deprecated?: boolean;
148
+ }
149
+ /**
150
+ * Swagger请求体 (OpenAPI 3.0)
151
+ */
152
+ export interface SwaggerRequestBody {
153
+ description?: string;
154
+ content: {
155
+ [mediaType: string]: {
156
+ schema?: SwaggerSchema;
157
+ example?: any;
158
+ examples?: {
159
+ [name: string]: any;
160
+ };
161
+ };
162
+ };
163
+ required?: boolean;
164
+ }
165
+ /**
166
+ * Swagger参数
167
+ */
168
+ export interface SwaggerParameter {
169
+ name: string;
170
+ in: 'query' | 'header' | 'path' | 'formData' | 'body';
171
+ description?: string;
172
+ required?: boolean;
173
+ type?: string;
174
+ format?: string;
175
+ schema?: SwaggerSchema;
176
+ items?: SwaggerItems;
177
+ enum?: any[];
178
+ default?: any;
179
+ }
180
+ /**
181
+ * Swagger响应
182
+ */
183
+ export interface SwaggerResponses {
184
+ [statusCode: string]: SwaggerResponse;
185
+ }
186
+ /**
187
+ * Swagger响应项
188
+ */
189
+ export interface SwaggerResponse {
190
+ description: string;
191
+ schema?: SwaggerSchema;
192
+ headers?: {
193
+ [name: string]: SwaggerHeader;
194
+ };
195
+ examples?: {
196
+ [mediaType: string]: any;
197
+ };
198
+ }
199
+ /**
200
+ * Swagger头部
201
+ */
202
+ export interface SwaggerHeader {
203
+ description?: string;
204
+ type: string;
205
+ format?: string;
206
+ items?: SwaggerItems;
207
+ enum?: any[];
208
+ default?: any;
209
+ }
210
+ /**
211
+ * Swagger模式
212
+ */
213
+ export interface SwaggerSchema {
214
+ type?: string;
215
+ format?: string;
216
+ title?: string;
217
+ description?: string;
218
+ default?: any;
219
+ enum?: any[];
220
+ items?: SwaggerSchema;
221
+ properties?: {
222
+ [name: string]: SwaggerSchema;
223
+ };
224
+ additionalProperties?: boolean | SwaggerSchema;
225
+ required?: string[];
226
+ allOf?: SwaggerSchema[];
227
+ oneOf?: SwaggerSchema[];
228
+ anyOf?: SwaggerSchema[];
229
+ not?: SwaggerSchema;
230
+ $ref?: string;
231
+ example?: any;
232
+ examples?: any[];
233
+ discriminator?: string;
234
+ readOnly?: boolean;
235
+ writeOnly?: boolean;
236
+ xml?: SwaggerXml;
237
+ externalDocs?: SwaggerExternalDocs;
238
+ nullable?: boolean;
239
+ deprecated?: boolean;
240
+ }
241
+ /**
242
+ * Swagger项目
243
+ */
244
+ export interface SwaggerItems {
245
+ type?: string;
246
+ format?: string;
247
+ items?: SwaggerItems;
248
+ enum?: any[];
249
+ default?: any;
250
+ $ref?: string;
251
+ }
252
+ /**
253
+ * Swagger定义
254
+ */
255
+ export interface SwaggerDefinitions {
256
+ [name: string]: SwaggerSchema;
257
+ }
258
+ /**
259
+ * Swagger组件 (OpenAPI 3.0)
260
+ */
261
+ export interface SwaggerComponents {
262
+ schemas?: {
263
+ [name: string]: SwaggerSchema;
264
+ };
265
+ responses?: {
266
+ [name: string]: SwaggerResponse;
267
+ };
268
+ parameters?: {
269
+ [name: string]: SwaggerParameter;
270
+ };
271
+ examples?: {
272
+ [name: string]: any;
273
+ };
274
+ requestBodies?: {
275
+ [name: string]: any;
276
+ };
277
+ headers?: {
278
+ [name: string]: SwaggerHeader;
279
+ };
280
+ securitySchemes?: {
281
+ [name: string]: any;
282
+ };
283
+ links?: {
284
+ [name: string]: any;
285
+ };
286
+ callbacks?: {
287
+ [name: string]: any;
288
+ };
289
+ }
290
+ /**
291
+ * Swagger标签
292
+ */
293
+ export interface SwaggerTag {
294
+ name: string;
295
+ description?: string;
296
+ externalDocs?: SwaggerExternalDocs;
297
+ }
298
+ /**
299
+ * Swagger外部文档
300
+ */
301
+ export interface SwaggerExternalDocs {
302
+ description?: string;
303
+ url: string;
304
+ }
305
+ /**
306
+ * Swagger XML
307
+ */
308
+ export interface SwaggerXml {
309
+ name?: string;
310
+ namespace?: string;
311
+ prefix?: string;
312
+ attribute?: boolean;
313
+ wrapped?: boolean;
314
+ }
315
+ /**
316
+ * 生成的API接口信息
317
+ */
318
+ export interface ApiInfo {
319
+ /** 接口名称 */
320
+ name: string;
321
+ /** HTTP方法 */
322
+ method: string;
323
+ /** 接口路径 */
324
+ path: string;
325
+ /** 接口描述 */
326
+ description?: string;
327
+ /** 标签 */
328
+ tags: string[];
329
+ /** 参数 */
330
+ parameters: ParameterInfo[];
331
+ /** 响应类型 */
332
+ responseType: string;
333
+ /** 请求体类型 */
334
+ requestBodyType?: string;
335
+ }
336
+ /**
337
+ * 参数信息
338
+ */
339
+ export interface ParameterInfo {
340
+ /** 参数名 */
341
+ name: string;
342
+ /** 参数类型 */
343
+ type: string;
344
+ /** 参数位置 */
345
+ in: 'query' | 'header' | 'path' | 'formData' | 'body';
346
+ /** 是否必需 */
347
+ required: boolean;
348
+ /** 参数描述 */
349
+ description?: string;
350
+ /** 参数模式 */
351
+ schema?: SwaggerSchema;
352
+ }
353
+ /**
354
+ * 生成的类型信息
355
+ */
356
+ export interface TypeInfo {
357
+ /** 类型名称 */
358
+ name: string;
359
+ /** 类型定义 */
360
+ definition: string;
361
+ /** 类型描述 */
362
+ description?: string;
363
+ }
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * Swagger2API 类型定义
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,82 @@
1
+ import { SwaggerDocument, SwaggerSchema, SwaggerParameter } from '../types';
2
+ /**
3
+ * 工具函数集合
4
+ */
5
+ /**
6
+ * 将路径转换为小驼峰命名的函数名
7
+ * @param method HTTP方法
8
+ * @param path 接口路径
9
+ * @returns 小驼峰命名的函数名
10
+ */
11
+ export declare function pathToFunctionName(method: string, path: string): string;
12
+ /**
13
+ * 将字符串转换为kebab-case
14
+ * @param str 输入字符串
15
+ * @returns kebab-case字符串
16
+ */
17
+ export declare function toKebabCase(str: string): string;
18
+ /**
19
+ * 将字符串转换为PascalCase
20
+ * @param str 输入字符串
21
+ * @returns PascalCase字符串
22
+ */
23
+ export declare function toPascalCase(str: string): string;
24
+ /**
25
+ * 将字符串转换为camelCase
26
+ * @param str 输入字符串
27
+ * @returns camelCase字符串
28
+ */
29
+ export declare function toCamelCase(str: string): string;
30
+ /**
31
+ * 将Swagger类型转换为TypeScript类型
32
+ * @param schema Swagger模式
33
+ * @returns TypeScript类型字符串
34
+ */
35
+ export declare function swaggerTypeToTsType(schema?: SwaggerSchema): string;
36
+ /**
37
+ * 从Swagger参数生成TypeScript参数类型
38
+ * @param parameters Swagger参数数组
39
+ * @returns TypeScript参数类型定义
40
+ */
41
+ export declare function generateParameterTypes(parameters: SwaggerParameter[]): string;
42
+ /**
43
+ * 确保目录存在,如果不存在则创建
44
+ * @param dirPath 目录路径
45
+ */
46
+ export declare function ensureDirectoryExists(dirPath: string): void;
47
+ /**
48
+ * 删除目录及其所有内容
49
+ * @param dirPath 目录路径
50
+ */
51
+ export declare function removeDirectory(dirPath: string): void;
52
+ /**
53
+ * 读取Swagger文档
54
+ * @param input 文件路径或URL
55
+ * @returns Swagger文档对象
56
+ */
57
+ export declare function loadSwaggerDocument(input: string): Promise<SwaggerDocument>;
58
+ /**
59
+ * 写入文件
60
+ * @param filePath 文件路径
61
+ * @param content 文件内容
62
+ */
63
+ export declare function writeFile(filePath: string, content: string): void;
64
+ /**
65
+ * 生成接口注释
66
+ * @param operation Swagger操作对象
67
+ * @param parameters 参数列表
68
+ * @returns 注释字符串
69
+ */
70
+ export declare function generateApiComment(operation: any, parameters: SwaggerParameter[]): string;
71
+ /**
72
+ * 清理文件名,移除非法字符
73
+ * @param filename 文件名
74
+ * @returns 清理后的文件名
75
+ */
76
+ export declare function sanitizeFilename(filename: string): string;
77
+ /**
78
+ * 获取响应类型
79
+ * @param responses Swagger响应对象
80
+ * @returns TypeScript类型字符串
81
+ */
82
+ export declare function getResponseType(responses: any): string;