swagger2api-v3 1.1.10 → 1.1.11

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.
@@ -7,7 +7,7 @@
7
7
  export interface SwaggerConfig {
8
8
  /** 本地 JSON Schema 路径,用于编辑器提示 */
9
9
  $schema?: string;
10
- /** Swagger JSON 文件路径或 URL */
10
+ /** OpenAPI 3.0 JSON/YAML 文件路径或 URL */
11
11
  input: string;
12
12
  /** 输出目录 */
13
13
  output: string;
@@ -110,6 +110,13 @@ export interface SwaggerDocument {
110
110
  components?: SwaggerComponents;
111
111
  tags?: SwaggerTag[];
112
112
  }
113
+ /**
114
+ * OpenAPI 引用对象
115
+ */
116
+ export interface SwaggerReference {
117
+ /** 引用地址 */
118
+ $ref: string;
119
+ }
113
120
  /**
114
121
  * OpenAPI Server 对象
115
122
  */
@@ -163,6 +170,8 @@ export interface SwaggerPaths {
163
170
  * Swagger路径项
164
171
  */
165
172
  export interface SwaggerPathItem {
173
+ /** Path Item 引用 */
174
+ $ref?: string;
166
175
  get?: SwaggerOperation;
167
176
  post?: SwaggerOperation;
168
177
  put?: SwaggerOperation;
@@ -170,6 +179,7 @@ export interface SwaggerPathItem {
170
179
  patch?: SwaggerOperation;
171
180
  head?: SwaggerOperation;
172
181
  options?: SwaggerOperation;
182
+ trace?: SwaggerOperation;
173
183
  parameters?: SwaggerParameter[];
174
184
  }
175
185
  /**
@@ -192,7 +202,7 @@ export interface SwaggerRequestBody {
192
202
  /** 本地引用路径 */
193
203
  $ref?: string;
194
204
  description?: string;
195
- content: {
205
+ content?: {
196
206
  [mediaType: string]: {
197
207
  schema?: SwaggerSchema;
198
208
  example?: any;
@@ -224,13 +234,15 @@ export interface SwaggerParameter {
224
234
  * OpenAPI 响应
225
235
  */
226
236
  export interface SwaggerResponses {
227
- [statusCode: string]: SwaggerResponse;
237
+ [statusCode: string]: SwaggerResponse | SwaggerReference;
228
238
  }
229
239
  /**
230
240
  * OpenAPI 响应项
231
241
  */
232
242
  export interface SwaggerResponse {
233
- description: string;
243
+ /** 本地或已打包的引用路径 */
244
+ $ref?: string;
245
+ description?: string;
234
246
  content?: {
235
247
  [mediaType: string]: {
236
248
  schema?: SwaggerSchema;
@@ -281,7 +293,7 @@ export interface SwaggerSchema {
281
293
  $ref?: string;
282
294
  example?: any;
283
295
  examples?: any[];
284
- discriminator?: string;
296
+ discriminator?: OpenAPIDiscriminator;
285
297
  readOnly?: boolean;
286
298
  writeOnly?: boolean;
287
299
  xml?: SwaggerXml;
@@ -293,6 +305,15 @@ export interface SwaggerSchema {
293
305
  /** OpenAPI 扩展字段:枚举名称 */
294
306
  'x-enumNames'?: string[];
295
307
  }
308
+ /**
309
+ * OpenAPI discriminator 对象
310
+ */
311
+ export interface OpenAPIDiscriminator {
312
+ /** 用作类型判别的属性名 */
313
+ propertyName: string;
314
+ /** 判别值到 Schema 引用的映射 */
315
+ mapping?: Record<string, string>;
316
+ }
296
317
  /**
297
318
  * Swagger项目
298
319
  */
@@ -312,7 +333,7 @@ export interface SwaggerComponents {
312
333
  [name: string]: SwaggerSchema;
313
334
  };
314
335
  responses?: {
315
- [name: string]: SwaggerResponse;
336
+ [name: string]: SwaggerResponse | SwaggerReference;
316
337
  };
317
338
  parameters?: {
318
339
  [name: string]: SwaggerParameter;
@@ -13,7 +13,10 @@ export interface ApiCommentOperation {
13
13
  /**
14
14
  * 注释生成需要的参数信息
15
15
  */
16
- export type ApiCommentParameter = Pick<ParameterInfo, 'in' | 'description'>;
16
+ export type ApiCommentParameter = Pick<ParameterInfo, 'in' | 'description'> & {
17
+ /** 生成后的函数参数名 */
18
+ name?: string;
19
+ };
17
20
  /**
18
21
  * 生成接口注释
19
22
  * @param operation 接口操作信息
@@ -23,8 +23,12 @@ function generateApiComment(operation, parameters) {
23
23
  const hasData = bodyParams.length > 0;
24
24
  if (hasParams || hasData) {
25
25
  comments.push(' *');
26
- if (hasParams) {
27
- const paramDescriptions = [...pathParams, ...queryParams]
26
+ pathParams.forEach((param, index) => {
27
+ const name = param.name || `pathParam${index + 1}`;
28
+ comments.push(` * @param ${name} ${param.description || '路径参数'}`);
29
+ });
30
+ if (queryParams.length > 0) {
31
+ const paramDescriptions = queryParams
28
32
  .map((param) => param.description || '')
29
33
  .filter((description) => description)
30
34
  .join(', ');
@@ -10,9 +10,16 @@ export declare function ensureDirectoryExists(dirPath: string): void;
10
10
  */
11
11
  export declare function removeDirectory(dirPath: string): void;
12
12
  /**
13
- * 读取Swagger文档
14
- * @param input 文件路径或URL
15
- * @returns Swagger文档对象
13
+ * 判断目标路径是否严格位于父路径内部
14
+ * @param parentPath 父路径
15
+ * @param targetPath 目标路径
16
+ * @returns 目标路径是否位于父路径内部
17
+ */
18
+ export declare function isPathInside(parentPath: string, targetPath: string): boolean;
19
+ /**
20
+ * 读取并打包 OpenAPI 3.0 文档
21
+ * @param input 文件路径或 URL
22
+ * @returns OpenAPI 文档对象
16
23
  */
17
24
  export declare function loadSwaggerDocument(input: string): Promise<SwaggerDocument>;
18
25
  /**
@@ -32,17 +32,15 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
35
  Object.defineProperty(exports, "__esModule", { value: true });
39
36
  exports.ensureDirectoryExists = ensureDirectoryExists;
40
37
  exports.removeDirectory = removeDirectory;
38
+ exports.isPathInside = isPathInside;
41
39
  exports.loadSwaggerDocument = loadSwaggerDocument;
42
40
  exports.writeFile = writeFile;
43
41
  const fs = __importStar(require("fs"));
44
42
  const path = __importStar(require("path"));
45
- const axios_1 = __importDefault(require("axios"));
43
+ const OpenAPIParser = require("@apidevtools/swagger-parser");
46
44
  const logger_1 = require("./logger");
47
45
  /**
48
46
  * 确保目录存在,如果不存在则创建
@@ -63,28 +61,59 @@ function removeDirectory(dirPath) {
63
61
  }
64
62
  }
65
63
  /**
66
- * 读取Swagger文档
67
- * @param input 文件路径或URL
68
- * @returns Swagger文档对象
64
+ * 判断目标路径是否严格位于父路径内部
65
+ * @param parentPath 父路径
66
+ * @param targetPath 目标路径
67
+ * @returns 目标路径是否位于父路径内部
68
+ */
69
+ function isPathInside(parentPath, targetPath) {
70
+ const relativePath = path.relative(path.resolve(parentPath), path.resolve(targetPath));
71
+ return (relativePath !== '' &&
72
+ relativePath !== '..' &&
73
+ !relativePath.startsWith(`..${path.sep}`) &&
74
+ !path.isAbsolute(relativePath));
75
+ }
76
+ /**
77
+ * 读取并打包 OpenAPI 3.0 文档
78
+ * @param input 文件路径或 URL
79
+ * @returns OpenAPI 文档对象
69
80
  */
70
81
  async function loadSwaggerDocument(input) {
71
82
  try {
72
- if (input.startsWith('http://') || input.startsWith('https://')) {
73
- const { data } = await axios_1.default.get(input);
74
- logger_1.logger.debug(`从 URL 加载: ${input}`);
75
- if (data.components?.schemas) {
76
- logger_1.logger.debugKV('schemas 数量', Object.keys(data.components.schemas).length);
77
- }
78
- else {
79
- logger_1.logger.debug('加载的数据中未发现 schemas');
83
+ const isRemoteInput = /^https?:\/\//i.test(input);
84
+ const resolveOptions = isRemoteInput
85
+ ? {
86
+ file: false,
87
+ http: {
88
+ timeout: 15000,
89
+ safeUrlResolver: false
90
+ }
80
91
  }
81
- return data;
92
+ : {
93
+ http: {
94
+ timeout: 15000,
95
+ safeUrlResolver: false
96
+ }
97
+ };
98
+ const data = (await OpenAPIParser.bundle(input, {
99
+ resolve: resolveOptions
100
+ }));
101
+ if (isRemoteInput) {
102
+ logger_1.logger.debug(`从 URL 加载: ${input}`);
103
+ }
104
+ else {
105
+ logger_1.logger.debug(`从文件加载: ${path.resolve(input)}`);
106
+ }
107
+ if (data.components?.schemas) {
108
+ logger_1.logger.debugKV('schemas 数量', Object.keys(data.components.schemas).length);
109
+ }
110
+ else {
111
+ logger_1.logger.debug('加载的数据中未发现 schemas');
82
112
  }
83
- const content = fs.readFileSync(input, 'utf-8');
84
- return JSON.parse(content);
113
+ return data;
85
114
  }
86
115
  catch (error) {
87
- throw new Error(`Failed to load Swagger document from ${input}: ${error}`);
116
+ throw new Error(`Failed to load OpenAPI document from ${input}: ${error}`);
88
117
  }
89
118
  }
90
119
  /**
@@ -118,7 +118,8 @@ function sanitizeFilename(filename) {
118
118
  */
119
119
  function sanitizeTypeName(name) {
120
120
  if (!name)
121
- return name;
121
+ return 'AnonymousType';
122
122
  const replaced = name.replace(/[^a-zA-Z0-9_]/g, '_');
123
- return toPascalCase(replaced);
123
+ const typeName = toPascalCase(replaced) || 'AnonymousType';
124
+ return /^\d/.test(typeName) ? `_${typeName}` : typeName;
124
125
  }
@@ -0,0 +1,79 @@
1
+ import { SwaggerSchema } from '../types';
2
+ /** Schema 的使用场景 */
3
+ export type SchemaUsage = 'neutral' | 'request' | 'response';
4
+ /** 对象属性类型覆盖 */
5
+ export type SchemaPropertyOverrides = Record<string, string>;
6
+ /**
7
+ * 判断字符串是否为合法 TypeScript 标识符
8
+ * @param name 属性名
9
+ * @returns 是否为合法标识符
10
+ */
11
+ export declare function isValidIdentifier(name: string): boolean;
12
+ /**
13
+ * 格式化 TypeScript 属性名
14
+ * @param name 属性名
15
+ * @returns 可用于类型声明的属性名
16
+ */
17
+ export declare function formatTsPropertyName(name: string): string;
18
+ /**
19
+ * 转义 JSDoc 文本
20
+ * @param text 原始文本
21
+ * @returns 可安全写入单行 JSDoc 的文本
22
+ */
23
+ export declare function escapeJSDocText(text: string): string;
24
+ /**
25
+ * 移除联合类型中的顶层 null 类型
26
+ * @param typeStr 类型字符串
27
+ * @returns 移除 null 后的类型字符串
28
+ */
29
+ export declare function stripNullFromUnion(typeStr: string): string;
30
+ /**
31
+ * 判断 Schema 是否应按对象处理
32
+ * @param schema OpenAPI Schema
33
+ * @returns 是否为对象 Schema
34
+ */
35
+ export declare function isObjectSchema(schema: SwaggerSchema): boolean;
36
+ /**
37
+ * 判断 Schema 是否为项目约定的泛型响应容器
38
+ * @param schema OpenAPI Schema
39
+ * @returns 是否为泛型响应容器
40
+ */
41
+ export declare function isGenericResponseSchema(schema: SwaggerSchema): boolean;
42
+ /**
43
+ * 获取当前使用场景可见的对象属性
44
+ * @param schema OpenAPI Schema
45
+ * @param usage Schema 使用场景
46
+ * @returns 可见属性数组
47
+ */
48
+ export declare function getVisibleSchemaProperties(schema: SwaggerSchema, usage?: SchemaUsage): Array<[string, SwaggerSchema]>;
49
+ /**
50
+ * 判断 Schema 在指定场景下是否需要独立类型
51
+ * @param schema OpenAPI Schema
52
+ * @param schemas 全部组件 Schema
53
+ * @param usage Schema 使用场景
54
+ * @returns 是否需要独立类型
55
+ */
56
+ export declare function schemaNeedsUsageVariant(schema: SwaggerSchema, schemas: Record<string, SwaggerSchema>, usage: Exclude<SchemaUsage, 'neutral'>): boolean;
57
+ /**
58
+ * 渲染对象类型成员
59
+ * @param schema OpenAPI Schema
60
+ * @param schemas 全部组件 Schema
61
+ * @param usage Schema 使用场景
62
+ * @param overrides 属性类型覆盖
63
+ * @returns 对象成员代码
64
+ */
65
+ export declare function renderObjectMembers(schema: SwaggerSchema, schemas?: Record<string, SwaggerSchema>, usage?: SchemaUsage, overrides?: SchemaPropertyOverrides): string;
66
+ /**
67
+ * 将 OpenAPI Schema 转换为 TypeScript 类型
68
+ * @param schema OpenAPI Schema
69
+ * @param schemas 全部组件 Schema
70
+ * @param usage Schema 使用场景
71
+ * @returns TypeScript 类型字符串
72
+ */
73
+ export declare function swaggerTypeToTsType(schema: SwaggerSchema | undefined | null, schemas?: Record<string, SwaggerSchema>, usage?: SchemaUsage): string;
74
+ /**
75
+ * 从 $ref 字符串中提取并解码引用名称
76
+ * @param ref OpenAPI $ref 字符串
77
+ * @returns 引用名称
78
+ */
79
+ export declare function getRefName(ref: string): string;