@jayfong/x-server 2.30.2 → 2.31.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/lib/_cjs/cli/api_generator.js +190 -151
- package/lib/_cjs/cli/api_generator1.js +286 -0
- package/lib/_cjs/cli/cli.js +5 -2
- package/lib/cli/api_generator.d.ts +31 -23
- package/lib/cli/api_generator.js +191 -151
- package/lib/cli/api_generator1.d.ts +44 -0
- package/lib/cli/api_generator1.js +279 -0
- package/lib/cli/cli.js +5 -2
- package/lib/core/types.d.ts +2 -0
- package/lib/services/jwt.d.ts +2 -0
- package/package.json +10 -6
|
@@ -1,129 +1,227 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
|
4
3
|
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
|
|
4
|
+
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
|
5
5
|
exports.__esModule = true;
|
|
6
6
|
exports.ApiGenerator = void 0;
|
|
7
|
-
var
|
|
8
|
-
var ts = _interopRequireWildcard(require("ts-morph"));
|
|
7
|
+
var _path = _interopRequireDefault(require("path"));
|
|
9
8
|
var _debug = _interopRequireDefault(require("debug"));
|
|
10
9
|
var _fsExtra = _interopRequireDefault(require("fs-extra"));
|
|
11
|
-
var
|
|
12
|
-
var _http_method = require("../core/http_method");
|
|
10
|
+
var _tsMorph = _interopRequireWildcard(require("ts-morph"));
|
|
13
11
|
var _vtils = require("vtils");
|
|
12
|
+
var _http_method = require("../core/http_method");
|
|
13
|
+
/** 注释 */
|
|
14
|
+
|
|
15
|
+
/** 接口传输数据 */
|
|
16
|
+
|
|
17
|
+
/** 接口数据 */
|
|
18
|
+
|
|
14
19
|
class ApiGenerator {
|
|
15
|
-
constructor() {
|
|
20
|
+
constructor(cwd = process.cwd()) {
|
|
21
|
+
this.cwd = cwd;
|
|
16
22
|
this.debug = (0, _debug.default)('api');
|
|
17
|
-
|
|
18
|
-
//
|
|
19
|
-
|
|
23
|
+
// 几种情况:
|
|
24
|
+
// /index.ts
|
|
25
|
+
// /user/index.ts
|
|
26
|
+
// /post.ts
|
|
27
|
+
// /user/list.ts
|
|
28
|
+
this.categoryUrlRe = /^.+\/src\/handlers\/(?:index\.ts|(.*)\/index\.ts|(.*)\.ts)$/;
|
|
29
|
+
this.checker = void 0;
|
|
20
30
|
}
|
|
21
|
-
|
|
22
|
-
|
|
31
|
+
async start() {
|
|
32
|
+
this.debug('启动项目...');
|
|
33
|
+
const tsConfigPath = _path.default.join(this.cwd, 'tsconfig.json');
|
|
34
|
+
const handlersPath = _path.default.join(this.cwd, 'node_modules/.x/handlers.ts');
|
|
35
|
+
const entryFile = _path.default.join(this.cwd, 'src/generated/handlers.ts');
|
|
36
|
+
|
|
37
|
+
// 仅使用 ts-morph 初始化项目
|
|
38
|
+
const moProject = new _tsMorph.default.Project({
|
|
39
|
+
tsConfigFilePath: tsConfigPath
|
|
40
|
+
});
|
|
41
|
+
moProject.createSourceFile(entryFile, await _fsExtra.default.readFile(handlersPath, 'utf-8'));
|
|
42
|
+
const program = moProject.getProgram().compilerObject;
|
|
43
|
+
const checker = program.getTypeChecker();
|
|
44
|
+
this.checker = checker;
|
|
45
|
+
const moduleSymbol = checker.getSymbolAtLocation(program.getSourceFile(entryFile));
|
|
46
|
+
const categorySymbols = checker.getExportsOfModule(moduleSymbol);
|
|
47
|
+
const apiData = [];
|
|
48
|
+
for (const categorySymbol of categorySymbols) {
|
|
49
|
+
var _ref, _categoryUrlMatch$;
|
|
50
|
+
// 分类的类型
|
|
51
|
+
const categoryType = checker.getTypeOfSymbolAtLocation(categorySymbol, categorySymbol.getDeclarations()[0]);
|
|
52
|
+
|
|
53
|
+
// 处理器列表
|
|
54
|
+
const handlerSymbols = categoryType.getProperties();
|
|
55
|
+
|
|
56
|
+
// 分类源文件
|
|
57
|
+
const categorySourceFile = handlerSymbols[0].getDeclarations()[0].getSourceFile();
|
|
58
|
+
|
|
59
|
+
// 分类源文件路径
|
|
60
|
+
const categorySourceFilePath = categorySourceFile.fileName;
|
|
61
|
+
|
|
62
|
+
// 分类 URL
|
|
63
|
+
const categoryUrlMatch = categorySourceFilePath.match(this.categoryUrlRe);
|
|
64
|
+
let categoryUrl = (_ref = (_categoryUrlMatch$ = categoryUrlMatch[1]) != null ? _categoryUrlMatch$ : categoryUrlMatch[2]) != null ? _ref : '';
|
|
65
|
+
categoryUrl = categoryUrl === '' ? '/' : `/${categoryUrl}/`;
|
|
66
|
+
for (const handlerSymbol of handlerSymbols) {
|
|
67
|
+
// 处理器名称
|
|
68
|
+
const handlerName = handlerSymbol.getName();
|
|
69
|
+
|
|
70
|
+
// 处理器 URL
|
|
71
|
+
const handlerUrl = `${categoryUrl}${handlerName}`;
|
|
72
|
+
|
|
73
|
+
// 处理器注释
|
|
74
|
+
const handlerComment = this.getComment(handlerSymbol);
|
|
75
|
+
if (handlerComment.tags.has('private')) {
|
|
76
|
+
this.debug('跳过生成接口: %s', `${handlerUrl}`);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
this.debug('生成接口: %s ...', handlerUrl);
|
|
80
|
+
const handlerNode = handlerSymbol.getDeclarations()[0];
|
|
81
|
+
const handlerType = checker.getTypeAtLocation(handlerNode);
|
|
82
|
+
const [requestType, responseType, methodType] = checker.getTypeArguments(handlerType);
|
|
83
|
+
const handlerCategory = (0, _vtils.pascalCase)(categoryUrl) || 'Index';
|
|
84
|
+
const handlerDescription = handlerComment.description || handlerUrl;
|
|
85
|
+
const handlerMethod = methodType.value;
|
|
86
|
+
const httpMethod = _http_method.HandlerMethodToHttpMethod[handlerMethod];
|
|
87
|
+
const requestData = this.getApiDto({
|
|
88
|
+
type: requestType
|
|
89
|
+
});
|
|
90
|
+
const responseData = this.getApiDto({
|
|
91
|
+
type: responseType
|
|
92
|
+
});
|
|
93
|
+
const requestDataJsonSchema = this.apiDataToJsonSchema(requestData);
|
|
94
|
+
const responseDataJsonSchema = this.apiDataToJsonSchema(responseData);
|
|
95
|
+
apiData.push({
|
|
96
|
+
category: handlerCategory,
|
|
97
|
+
name: handlerDescription,
|
|
98
|
+
path: handlerUrl,
|
|
99
|
+
handlerMethod: handlerMethod,
|
|
100
|
+
method: httpMethod,
|
|
101
|
+
requestData: requestData,
|
|
102
|
+
responseData: responseData,
|
|
103
|
+
requestDataJsonSchema: requestDataJsonSchema,
|
|
104
|
+
responseDataJsonSchema: responseDataJsonSchema
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
this.debug('写入文件...');
|
|
109
|
+
await Promise.all([_fsExtra.default.outputJSON(_path.default.join(this.cwd, 'temp/api.json'), apiData, {
|
|
110
|
+
spaces: 2
|
|
111
|
+
}), _fsExtra.default.outputJSON(_path.default.join(this.cwd, 'temp/yapi.json'), this.genYApiData(apiData), {
|
|
112
|
+
spaces: 2
|
|
113
|
+
})]);
|
|
23
114
|
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
115
|
+
|
|
116
|
+
// ref: https://github.com/styleguidist/react-docgen-typescript/blob/master/src/parser.ts#L777
|
|
117
|
+
getComment(symbol) {
|
|
118
|
+
if (!symbol) {
|
|
119
|
+
return {
|
|
120
|
+
existing: false,
|
|
121
|
+
description: '',
|
|
122
|
+
tags: new Map()
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
const description = _tsMorph.ts.displayPartsToString(symbol.getDocumentationComment(this.checker)).trim();
|
|
126
|
+
const tags = symbol.getJsDocTags().map(item => {
|
|
127
|
+
return {
|
|
128
|
+
label: item.name,
|
|
129
|
+
value: _tsMorph.ts.displayPartsToString(item.text).trim()
|
|
130
|
+
};
|
|
32
131
|
});
|
|
33
132
|
return {
|
|
34
|
-
existing: !!
|
|
133
|
+
existing: !!description,
|
|
35
134
|
description: description,
|
|
36
|
-
tags: tags
|
|
135
|
+
tags: tags.reduce((res, item) => {
|
|
136
|
+
res.set(item.label, item.value);
|
|
137
|
+
return res;
|
|
138
|
+
}, new Map())
|
|
37
139
|
};
|
|
38
140
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
141
|
+
getApiDto({
|
|
142
|
+
type,
|
|
143
|
+
keySymbol = type.symbol || type.aliasSymbol
|
|
144
|
+
}) {
|
|
145
|
+
var _valueSymbol;
|
|
146
|
+
const hasTypeFlag = (flag, _type = type) => (_type.flags & flag) === flag;
|
|
147
|
+
let valueSymbol = type.symbol || type.aliasSymbol;
|
|
148
|
+
const keySymbolName = (keySymbol == null ? void 0 : keySymbol.getName()) || '';
|
|
149
|
+
let valueSymbolName = ((_valueSymbol = valueSymbol) == null ? void 0 : _valueSymbol.getName()) || '';
|
|
150
|
+
const comment = this.getComment(keySymbol);
|
|
151
|
+
let isRequired = keySymbol ? !(keySymbol.getFlags() & _tsMorph.ts.SymbolFlags.Optional) : false;
|
|
152
|
+
|
|
153
|
+
// WS
|
|
154
|
+
if (valueSymbolName === 'SocketStream') {
|
|
47
155
|
return {
|
|
48
156
|
name: 'ws',
|
|
49
|
-
desc:
|
|
50
|
-
required:
|
|
157
|
+
desc: comment.description,
|
|
158
|
+
required: isRequired,
|
|
51
159
|
type: 'object',
|
|
52
|
-
|
|
53
|
-
|
|
160
|
+
enum: [],
|
|
161
|
+
children: []
|
|
54
162
|
};
|
|
55
163
|
}
|
|
56
164
|
|
|
57
|
-
//
|
|
58
|
-
if (
|
|
59
|
-
const symbol = _symbol || type.getSymbol();
|
|
165
|
+
// 文件
|
|
166
|
+
if (valueSymbolName === 'MultipartFile') {
|
|
60
167
|
return {
|
|
61
168
|
name: 'file',
|
|
62
|
-
desc:
|
|
63
|
-
required:
|
|
169
|
+
desc: comment.description,
|
|
170
|
+
required: isRequired,
|
|
64
171
|
type: 'file',
|
|
65
|
-
|
|
66
|
-
|
|
172
|
+
enum: [],
|
|
173
|
+
children: []
|
|
67
174
|
};
|
|
68
175
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
176
|
+
|
|
177
|
+
// 联合类型
|
|
178
|
+
// 布尔、枚举也会用这表示
|
|
179
|
+
const rawUnionTypes = type.isUnion() && type.types || [];
|
|
180
|
+
const unionTypes = rawUnionTypes.filter(item => !hasTypeFlag(_tsMorph.ts.TypeFlags.Null, item) && !hasTypeFlag(_tsMorph.ts.TypeFlags.Undefined, item));
|
|
181
|
+
const isUnion = !!unionTypes.length;
|
|
73
182
|
if (isUnion) {
|
|
74
|
-
|
|
75
|
-
|
|
183
|
+
var _this$checker$getBase;
|
|
184
|
+
if (unionTypes.length !== rawUnionTypes.length) {
|
|
185
|
+
isRequired = false;
|
|
76
186
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
type = unionTypes[0].getBaseTypeOfLiteralType();
|
|
187
|
+
type = unionTypes[0];
|
|
188
|
+
valueSymbol = type.symbol || type.aliasSymbol;
|
|
189
|
+
valueSymbolName = ((_this$checker$getBase = this.checker.getBaseTypeOfLiteralType(type).getSymbol()) == null ? void 0 : _this$checker$getBase.getName()) || '';
|
|
81
190
|
}
|
|
82
|
-
const isEnum = type.isEnum();
|
|
83
|
-
const enumData = isEnum ?
|
|
84
|
-
// @ts-ignore
|
|
85
|
-
type.compilerType.types.reduce((res, item) => {
|
|
86
|
-
res[item.getSymbol().getName()] = item.value;
|
|
87
|
-
return res;
|
|
88
|
-
}, {}) : {};
|
|
89
|
-
const enumKeys = Object.keys(enumData);
|
|
90
|
-
const enumValues = Object.values(enumData);
|
|
91
191
|
const isIntersection = type.isIntersection();
|
|
92
|
-
const intersectionTypes = isIntersection && type.
|
|
93
|
-
const
|
|
94
|
-
const
|
|
95
|
-
const
|
|
96
|
-
const
|
|
97
|
-
const
|
|
98
|
-
|
|
192
|
+
const intersectionTypes = isIntersection && type.types || [];
|
|
193
|
+
const isDate = valueSymbolName === 'Date';
|
|
194
|
+
const isBigIntLiteral = hasTypeFlag(_tsMorph.ts.TypeFlags.BigIntLiteral);
|
|
195
|
+
const isBigInt = hasTypeFlag(_tsMorph.ts.TypeFlags.BigInt) || isBigIntLiteral;
|
|
196
|
+
const isArray = valueSymbolName === 'Array' || valueSymbolName === 'ReadonlyArray';
|
|
197
|
+
const isStringLiteral = hasTypeFlag(_tsMorph.ts.TypeFlags.StringLiteral);
|
|
198
|
+
const isString = hasTypeFlag(_tsMorph.ts.TypeFlags.String) || isStringLiteral ||
|
|
199
|
+
// BigInt 类型视为字符串
|
|
200
|
+
isBigInt ||
|
|
201
|
+
// Date 类型视为字符串
|
|
202
|
+
isDate;
|
|
203
|
+
const isNumberLiteral = hasTypeFlag(_tsMorph.ts.TypeFlags.NumberLiteral);
|
|
204
|
+
const isNumber = hasTypeFlag(_tsMorph.ts.TypeFlags.Number) || isNumberLiteral;
|
|
205
|
+
const isBoolean = hasTypeFlag(_tsMorph.ts.TypeFlags.Boolean) || hasTypeFlag(_tsMorph.ts.TypeFlags.BooleanLiteral);
|
|
206
|
+
const isLiteral = isStringLiteral || isNumberLiteral || isBigIntLiteral;
|
|
207
|
+
const isObject = !isArray && !isString && !isNumber && !isBoolean && hasTypeFlag(_tsMorph.ts.TypeFlags.Object) ||
|
|
208
|
+
// 交集类型视为对象
|
|
99
209
|
isIntersection;
|
|
100
|
-
const
|
|
101
|
-
const
|
|
102
|
-
const
|
|
103
|
-
const apiEnum = isUnion ? unionTypes.map(t => t.getLiteralValue()) : isEnum ? enumValues : [];
|
|
210
|
+
const apiName = keySymbolName || '__type';
|
|
211
|
+
const apiDesc = keySymbol && this.getComment(keySymbol).description || '';
|
|
212
|
+
const apiEnum = (isUnion ? unionTypes.map(item => item.value) : isLiteral ? [type.value] : []).filter(v => v != null);
|
|
104
213
|
const apiType = isArray ? 'array' : isString ? 'string' : isNumber ? 'number' : isBoolean ? 'boolean' : 'object';
|
|
105
|
-
const apiRequired = isRequired
|
|
106
|
-
const apiChildren = isArray ? [this.
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
} else {
|
|
117
|
-
// symbols = type.getApparentProperties()
|
|
118
|
-
// https://github.com/microsoft/TypeScript/issues/38184
|
|
119
|
-
symbols = rawChecker.getAllPossiblePropertiesOfTypes([type.compilerType])
|
|
120
|
-
// https://github.com/dsherret/ts-morph/blob/a7072fcf6f9babb784b40f0326c80dea4563a4aa/packages/ts-morph/src/compiler/types/Type.ts#L296
|
|
121
|
-
.map(symbol => compilerFactory.getSymbol(symbol));
|
|
122
|
-
}
|
|
123
|
-
return symbols.map(symbol => {
|
|
124
|
-
return this.typeToApiData(!symbol.compilerSymbol.declarations ?
|
|
125
|
-
// 对于复杂对象,没有定义的,通过 type 直接获取(在前面通过 getText 预处理得到)
|
|
126
|
-
compilerFactory.getType(symbol.compilerSymbol.type) : this.getTypeBySymbol(symbol), symbol);
|
|
214
|
+
const apiRequired = isRequired;
|
|
215
|
+
const apiChildren = isArray ? [this.getApiDto({
|
|
216
|
+
type: this.checker.getTypeArguments(type)[0]
|
|
217
|
+
})] : isObject ? (0, _vtils.ii)(() => {
|
|
218
|
+
const childSymbols = this.checker.getAllPossiblePropertiesOfTypes(intersectionTypes.length ? intersectionTypes : [type]);
|
|
219
|
+
return childSymbols.map(childSymbol => {
|
|
220
|
+
const childType = this.checker.getTypeOfSymbol(childSymbol);
|
|
221
|
+
return this.getApiDto({
|
|
222
|
+
type: childType,
|
|
223
|
+
keySymbol: childSymbol
|
|
224
|
+
});
|
|
127
225
|
});
|
|
128
226
|
}) : [];
|
|
129
227
|
return {
|
|
@@ -140,7 +238,6 @@ class ApiGenerator {
|
|
|
140
238
|
if (apiData.type === 'object') {
|
|
141
239
|
jsonSchema.type = 'object';
|
|
142
240
|
jsonSchema.properties = apiData.children.reduce((res, item) => {
|
|
143
|
-
;
|
|
144
241
|
res[item.name] = this.apiDataToJsonSchema(item);
|
|
145
242
|
return res;
|
|
146
243
|
}, {});
|
|
@@ -217,63 +314,5 @@ class ApiGenerator {
|
|
|
217
314
|
list: data[cat]
|
|
218
315
|
}));
|
|
219
316
|
}
|
|
220
|
-
async generate() {
|
|
221
|
-
this.debug('启动项目...');
|
|
222
|
-
this.project = new ts.Project({
|
|
223
|
-
tsConfigFilePath: _nodePath.default.join(this.cwd, 'tsconfig.json')
|
|
224
|
-
});
|
|
225
|
-
this.debug('加载文件...');
|
|
226
|
-
const sourceFile = this.project.createSourceFile(_nodePath.default.join(this.cwd, 'src/generated/handlers.ts'), await _fsExtra.default.readFile(_nodePath.default.join(this.cwd, 'node_modules/.x/handlers.ts'), 'utf-8'));
|
|
227
|
-
this.debug('导出处理器...');
|
|
228
|
-
const handlerGroup = sourceFile.getExportSymbols();
|
|
229
|
-
const handles = [];
|
|
230
|
-
this.debug('生成API文档...');
|
|
231
|
-
for (const handlerList of handlerGroup) {
|
|
232
|
-
const handlerListSourceFile = this.getTypeBySymbol(handlerList).getProperties()[0].getDeclarations()[0].getSourceFile();
|
|
233
|
-
const basePath = `/${handlerListSourceFile.getFilePath().replace('.ts', '').split('/src/handlers/')[1].replace(/(^|\/)index$/, '/').split('/').map(v => (0, _vtils.snakeCase)(v)).join('/')}/`.replace(/\/{2,}/g, '/');
|
|
234
|
-
for (const handler of handlerListSourceFile.getVariableStatements().filter(item => item.isExported())) {
|
|
235
|
-
// 重要:这一步必须,先调一遍 getText 获取看到的对象,后续对于复杂定义才不会报错
|
|
236
|
-
handler.getDeclarations().forEach(exp => {
|
|
237
|
-
exp.getType().getText();
|
|
238
|
-
});
|
|
239
|
-
const handlerExp = handler.getDeclarations()[0];
|
|
240
|
-
const handlerPath = `${basePath}${handlerExp.getName()}`;
|
|
241
|
-
this.debug('生成接口: %s ...', handlerPath);
|
|
242
|
-
const [requestType, responseType, methodType] = handlerExp.getType().getTypeArguments();
|
|
243
|
-
const handlerComment = this.getComment(handlerExp.getParent().getParent());
|
|
244
|
-
if (handlerComment.tags.has('private')) {
|
|
245
|
-
this.debug('跳过生成接口: %s', `${handlerPath}`);
|
|
246
|
-
continue;
|
|
247
|
-
}
|
|
248
|
-
const handlerCategory = (0, _vtils.pascalCase)(basePath) || 'Index';
|
|
249
|
-
const handlerName = handlerComment.description || handlerPath;
|
|
250
|
-
const handlerMethod = methodType.getLiteralValueOrThrow();
|
|
251
|
-
const serverMethod = _http_method.HandlerMethodToHttpMethod[handlerMethod];
|
|
252
|
-
const requestData = this.typeToApiData(requestType);
|
|
253
|
-
const responseData = this.typeToApiData(responseType);
|
|
254
|
-
const requestDataJsonSchema = this.apiDataToJsonSchema(requestData);
|
|
255
|
-
const responseDataJsonSchema = this.apiDataToJsonSchema(responseData);
|
|
256
|
-
handles.push({
|
|
257
|
-
category: handlerCategory,
|
|
258
|
-
name: handlerName,
|
|
259
|
-
path: handlerPath,
|
|
260
|
-
handlerMethod: handlerMethod,
|
|
261
|
-
method: serverMethod,
|
|
262
|
-
requestData: requestData,
|
|
263
|
-
responseData: responseData,
|
|
264
|
-
requestDataJsonSchema: requestDataJsonSchema,
|
|
265
|
-
responseDataJsonSchema: responseDataJsonSchema
|
|
266
|
-
});
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
this.debug('写入文件...');
|
|
270
|
-
await Promise.all([_fsExtra.default.outputJSON(_nodePath.default.join(this.cwd, 'temp/api.json'), handles, {
|
|
271
|
-
spaces: 2
|
|
272
|
-
}), _fsExtra.default.outputJSON(_nodePath.default.join(this.cwd, 'temp/yapi.json'), this.genYApiData(handles), {
|
|
273
|
-
spaces: 2
|
|
274
|
-
})]);
|
|
275
|
-
}
|
|
276
317
|
}
|
|
277
|
-
|
|
278
|
-
// new ApiGenerator().generate()
|
|
279
318
|
exports.ApiGenerator = ApiGenerator;
|