gen-api-types 1.0.16 → 1.0.18
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/README.en.md +47 -21
- package/README.md +47 -21
- package/bin/index.js +0 -0
- package/package.json +6 -3
- package/src/argv/index.ts +1 -1
- package/src/cli/index.ts +20 -171
- package/src/constant/index.ts +5 -2
- package/src/decotators/index.ts +24 -22
- package/src/generation/index.ts +11 -0
- package/src/generation/moduleLoader.ts +13 -0
- package/src/generation/registry.ts +25 -0
- package/src/generation/runner.ts +25 -0
- package/src/generation/scanner.ts +52 -0
- package/src/generation/types.ts +11 -0
- package/src/index.ts +3 -2
- package/src/plugins/index.ts +1 -0
- package/src/plugins/vite/index.ts +46 -0
- package/src/transformer/index.ts +14 -59
- package/src/transformer/typeTransformer.ts +62 -0
- package/src/utils/decoratorHelper.ts +38 -0
- package/src/utils/index.ts +64 -0
- package/tsconfig.json +3 -3
package/README.en.md
CHANGED
|
@@ -10,8 +10,9 @@ With this tool, we can mark request interface classes and methods through TypeSc
|
|
|
10
10
|
|
|
11
11
|
> Note:
|
|
12
12
|
>
|
|
13
|
-
> 1. Because this tool uses TypeScript
|
|
14
|
-
> 2.
|
|
13
|
+
> 1. Because this tool uses TypeScript method decorators, APIs must be written as **API classes + API methods**.
|
|
14
|
+
> 2. The CLI dynamically imports modules containing marked methods. Module-level code runs during import; decorators only register tasks, and the CLI calls the registered API methods afterward.
|
|
15
|
+
> 3. API methods are executed for real in the CLI process. Make sure required environment variables, network access, and authentication are available.
|
|
15
16
|
|
|
16
17
|
#### Installation
|
|
17
18
|
|
|
@@ -23,14 +24,17 @@ npm install gen-api-types -D
|
|
|
23
24
|
|
|
24
25
|
#### Usage
|
|
25
26
|
|
|
26
|
-
##### 1. Mark
|
|
27
|
+
##### 1. Mark API classes and methods
|
|
27
28
|
|
|
28
29
|
```ts
|
|
29
30
|
import { gen_type_c, gen_type_m } from 'gen-api-types'
|
|
30
31
|
|
|
31
32
|
@gen_type_c()
|
|
32
33
|
export class TestApi {
|
|
33
|
-
@gen_type_m({
|
|
34
|
+
@gen_type_m({
|
|
35
|
+
args: [100],
|
|
36
|
+
typeName: 'XXX',
|
|
37
|
+
})
|
|
34
38
|
static async getList(id: number): Promise<XXX> {
|
|
35
39
|
return asleep(1000).then(() => {
|
|
36
40
|
return { name: 'zs', id }
|
|
@@ -38,7 +42,7 @@ export class TestApi {
|
|
|
38
42
|
}
|
|
39
43
|
|
|
40
44
|
@gen_type_m()
|
|
41
|
-
|
|
45
|
+
getWeather(): Promise<Response_TestApi_getWeather> {
|
|
42
46
|
return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
|
|
43
47
|
}
|
|
44
48
|
}
|
|
@@ -46,14 +50,26 @@ export class TestApi {
|
|
|
46
50
|
|
|
47
51
|
As shown in the code above:
|
|
48
52
|
|
|
49
|
-
- `@gen_type_c`
|
|
50
|
-
- `@gen_type_m`
|
|
51
|
-
|
|
52
|
-
|
|
53
|
+
- `@gen_type_c()` marks an API class.
|
|
54
|
+
- `@gen_type_m()` marks a method to execute and convert. The decorator registers the task; the Runner invokes the API method after the CLI has loaded the modules.
|
|
55
|
+
- `args: any[]` contains the arguments passed to the method. Both static and non-static methods are supported.
|
|
56
|
+
- `typeName: string` is the generated type name. If omitted, it defaults to `Response_${ClassName}_${MethodName}`.
|
|
57
|
+
- The marked class is only a decorator carrier; the Runner does not instantiate it. Non-static methods must not depend on `this` or instance fields.
|
|
58
|
+
|
|
59
|
+
Decorator options may span multiple lines:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
@gen_type_m({
|
|
63
|
+
args: [100],
|
|
64
|
+
typeName: 'XXX'
|
|
65
|
+
})
|
|
66
|
+
```
|
|
53
67
|
|
|
54
68
|
> Note:
|
|
55
69
|
|
|
56
|
-
If TypeScript reports the decorator error
|
|
70
|
+
If TypeScript reports the decorator error "The runtime will invoke the decorator with 2 arguments, but the decorator expects 3", set `compilerOptions.experimentalDecorators` to `true` in `tsconfig.json`.
|
|
71
|
+
|
|
72
|
+
The CLI currently applies a 3-second execution timeout to each API method. Timeouts, synchronous exceptions, and rejected promises are reported as execution failures. A timeout stops waiting for the result but cannot cancel an underlying request that has already started.
|
|
57
73
|
|
|
58
74
|
##### 2. Execute command
|
|
59
75
|
|
|
@@ -85,21 +101,13 @@ You can also use it by configuring scripts in package.json:
|
|
|
85
101
|
}
|
|
86
102
|
```
|
|
87
103
|
|
|
104
|
+
The CLI scans `.ts` files in the input directories to find marked classes, methods, and their modules. It then imports those modules so decorators can register tasks. After all modules have loaded, the Runner invokes the registered API methods and converts successful results into a declaration file. Each API method has a default execution timeout of 5 seconds; registered methods run concurrently.
|
|
105
|
+
|
|
88
106
|
Command output:
|
|
89
107
|
|
|
90
108
|
```shell
|
|
91
|
-
🚀 Start generating API types...
|
|
92
109
|
sourceFilesGlob [ 'src\\**\\*.ts' ]
|
|
93
|
-
|
|
94
|
-
📋 Processing TestApi.getWeather ...
|
|
95
|
-
Request results:
|
|
96
|
-
┌────────────────┬──────────────────────────────────────┐
|
|
97
|
-
│ (index) │ Values │
|
|
98
|
-
├────────────────┼──────────────────────────────────────┤
|
|
99
|
-
│ ✔️ successList │ 'TestApi.getList TestApi.getWeather' │
|
|
100
|
-
│ ❌ errorList │ '' │
|
|
101
|
-
└────────────────┴──────────────────────────────────────┘
|
|
102
|
-
✅ API type generation completed
|
|
110
|
+
✅ API type generation completed: /path/to/api-types.d.ts
|
|
103
111
|
```
|
|
104
112
|
|
|
105
113
|
##### 3. Using the types
|
|
@@ -148,6 +156,24 @@ export type XXX = { name: string };
|
|
|
148
156
|
export type Response_TestApi_getWeather = {...}
|
|
149
157
|
```
|
|
150
158
|
|
|
159
|
+
##### 4. Vite plugin
|
|
160
|
+
|
|
161
|
+
Decorators are needed for type generation, but they normally should not execute when the business application runs or builds. In a Vite project, use the plugin to remove `gen_type_c` and `gen_type_m` from the transformed business code:
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
// vite.config.ts
|
|
165
|
+
import { defineConfig } from 'vite'
|
|
166
|
+
import { removeGatDecorators } from 'gen-api-types'
|
|
167
|
+
|
|
168
|
+
export default defineConfig({
|
|
169
|
+
plugins: [removeGatDecorators()],
|
|
170
|
+
})
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The plugin processes `.ts` and `.tsx` files and supports single-line and multi-line decorator options. It removes decorators by the names `gen_type_c` and `gen_type_m`.
|
|
174
|
+
|
|
175
|
+
The Vite plugin only affects Vite's transform pipeline. It is not involved when the CLI imports and executes API modules.
|
|
176
|
+
|
|
151
177
|
#### VS Code Extension
|
|
152
178
|
|
|
153
179
|
If you use `gen-api-types` in VS Code, you can install the companion extension [gen-api-types-vsce](https://github.com/xuejiangping/gen-api-types-vsce) to generate API return types from the context menu.
|
package/README.md
CHANGED
|
@@ -10,8 +10,9 @@
|
|
|
10
10
|
|
|
11
11
|
> 注意:
|
|
12
12
|
>
|
|
13
|
-
> 1.
|
|
14
|
-
> 2.
|
|
13
|
+
> 1. 由于需要使用 TypeScript 方法装饰器,接口需要以 **API 类 + API 方法** 的形式书写。
|
|
14
|
+
> 2. CLI 会动态导入包含标记方法的模块。模块顶层代码会在导入时执行;装饰器只登记任务,CLI 随后才调用已登记的 API 方法。
|
|
15
|
+
> 3. API 方法会在 CLI 进程中真实执行,请确保运行所需的环境变量、网络权限和鉴权配置已经准备好。
|
|
15
16
|
|
|
16
17
|
#### 安装教程
|
|
17
18
|
|
|
@@ -23,14 +24,17 @@ npm install gen-api-types -D
|
|
|
23
24
|
|
|
24
25
|
#### 使用说明
|
|
25
26
|
|
|
26
|
-
##### 1.
|
|
27
|
+
##### 1. 标记 API 类和方法
|
|
27
28
|
|
|
28
29
|
```ts
|
|
29
30
|
import { gen_type_c, gen_type_m } from 'gen-api-types'
|
|
30
31
|
|
|
31
32
|
@gen_type_c()
|
|
32
33
|
export class TestApi {
|
|
33
|
-
@gen_type_m({
|
|
34
|
+
@gen_type_m({
|
|
35
|
+
args: [100],
|
|
36
|
+
typeName: 'XXX',
|
|
37
|
+
})
|
|
34
38
|
static async getList(id: number): Promise<XXX> {
|
|
35
39
|
return asleep(1000).then(() => {
|
|
36
40
|
return { name: 'zs', id }
|
|
@@ -38,7 +42,7 @@ export class TestApi {
|
|
|
38
42
|
}
|
|
39
43
|
|
|
40
44
|
@gen_type_m()
|
|
41
|
-
|
|
45
|
+
getWeather(): Promise<Response_TestApi_getWeather> {
|
|
42
46
|
return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
|
|
43
47
|
}
|
|
44
48
|
}
|
|
@@ -46,14 +50,26 @@ export class TestApi {
|
|
|
46
50
|
|
|
47
51
|
如上面代码所示:
|
|
48
52
|
|
|
49
|
-
- `@gen_type_c
|
|
50
|
-
- `@gen_type_m
|
|
51
|
-
|
|
52
|
-
|
|
53
|
+
- `@gen_type_c()` 标记 API 类。
|
|
54
|
+
- `@gen_type_m()` 标记需要执行并生成类型的方法;装饰器负责登记任务,API 方法会在 CLI 加载完模块后由 Runner 调用。
|
|
55
|
+
- `args: any[]` 是调用方法时传入的参数,支持静态方法和非静态方法。
|
|
56
|
+
- `typeName: string` 是生成的类型名称;不指定时默认为 `Response_${类名}_${方法名}`。
|
|
57
|
+
- 标记类仅用于承载装饰器;Runner 不会创建类实例。普通方法不要依赖 `this` 或实例字段。
|
|
58
|
+
|
|
59
|
+
装饰器参数可以跨多行书写:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
@gen_type_m({
|
|
63
|
+
args: [100],
|
|
64
|
+
typeName: 'XXX'
|
|
65
|
+
})
|
|
66
|
+
```
|
|
53
67
|
|
|
54
68
|
> 注意:
|
|
55
69
|
|
|
56
|
-
若使用装饰器时
|
|
70
|
+
若使用装饰器时 TypeScript 报错“运行时将使用 2 个自变量调用修饰器,但修饰器需要 3 个”,请将 `tsconfig.json` 中的 `compilerOptions.experimentalDecorators` 设置为 `true`。
|
|
71
|
+
|
|
72
|
+
CLI 默认会为单个 API 方法设置 5 秒执行超时。超时、同步异常或 Promise rejection 都会被记录为该方法的执行失败;超时只能停止等待,不能取消已经发出的底层请求。
|
|
57
73
|
|
|
58
74
|
##### 2. 执行命令
|
|
59
75
|
|
|
@@ -85,21 +101,13 @@ Options:
|
|
|
85
101
|
}
|
|
86
102
|
```
|
|
87
103
|
|
|
104
|
+
CLI 会扫描输入目录中的 `.ts` 文件,找到标记的类和方法及其所属模块。随后动态导入这些模块,使装饰器登记任务;全部模块加载完成后,Runner 才调用登记的 API 方法,并将成功结果转换为声明文件。每个 API 方法的默认执行超时为 5 秒;多个已登记方法会并发执行。
|
|
105
|
+
|
|
88
106
|
命令输出:
|
|
89
107
|
|
|
90
108
|
```shell
|
|
91
|
-
🚀 开始生成API类型...
|
|
92
109
|
sourceFilesGlob [ 'src\\**\\*.ts' ]
|
|
93
|
-
|
|
94
|
-
📋 处理 TestApi.getWeather ...
|
|
95
|
-
请求结果:
|
|
96
|
-
┌────────────────┬──────────────────────────────────────┐
|
|
97
|
-
│ (index) │ Values │
|
|
98
|
-
├────────────────┼──────────────────────────────────────┤
|
|
99
|
-
│ ✔️ successList │ 'TestApi.getList TestApi.getWeather' │
|
|
100
|
-
│ ❌ errorList │ '' │
|
|
101
|
-
└────────────────┴──────────────────────────────────────┘
|
|
102
|
-
✅ API 类型生成完成
|
|
110
|
+
✅ API 类型生成完成: /path/to/api-types.d.ts
|
|
103
111
|
```
|
|
104
112
|
|
|
105
113
|
##### 3. 使用类型
|
|
@@ -148,6 +156,24 @@ export type XXX = { name: string };
|
|
|
148
156
|
export type Response_TestApi_getWeather = {...}
|
|
149
157
|
```
|
|
150
158
|
|
|
159
|
+
##### 4. Vite 插件
|
|
160
|
+
|
|
161
|
+
装饰器只用于生成类型,业务项目正常运行或构建时通常不需要执行这些装饰器。Vite 项目可以使用插件移除 `gen_type_c` 和 `gen_type_m`,避免装饰器在业务运行时产生副作用:
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
// vite.config.ts
|
|
165
|
+
import { defineConfig } from 'vite'
|
|
166
|
+
import { removeGatDecorators } from 'gen-api-types'
|
|
167
|
+
|
|
168
|
+
export default defineConfig({
|
|
169
|
+
plugins: [removeGatDecorators()],
|
|
170
|
+
})
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
插件只处理 `.ts` 文件,并支持单行或多行装饰器参数。插件按 `gen_type_c`、`gen_type_m` 这两个装饰器名称移除装饰器。
|
|
174
|
+
|
|
175
|
+
Vite 插件只影响 Vite 的转换流程,不参与 CLI 的 API 执行流程。
|
|
176
|
+
|
|
151
177
|
#### VS Code 插件
|
|
152
178
|
|
|
153
179
|
如果你在 VS Code 中使用 `gen-api-types` ,可以安装配套插件 [gen-api-types-vsce](https://github.com/xuejiangping/gen-api-types-vsce),通过右键菜单生成 API 返回类型。
|
package/bin/index.js
CHANGED
|
File without changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gen-api-types",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.18",
|
|
4
4
|
"description": "一个自动生成请求接口返回类型的 cli 小工具",
|
|
5
5
|
"main": "./src/index.ts",
|
|
6
6
|
"exports": {
|
|
@@ -19,13 +19,15 @@
|
|
|
19
19
|
"test": "vitest",
|
|
20
20
|
"publish:patch": "npm version patch && git push --tags && npm publish",
|
|
21
21
|
"preinstall": "echo preinstall 。。。",
|
|
22
|
-
"postinstall": "echo postinstall 。。。"
|
|
22
|
+
"postinstall": "echo postinstall 。。。",
|
|
23
|
+
"gat": "gat -o test/output test/api "
|
|
23
24
|
},
|
|
24
25
|
"keywords": [
|
|
25
26
|
"generate types",
|
|
26
27
|
"TypeScript",
|
|
27
28
|
"Cli",
|
|
28
|
-
"API"
|
|
29
|
+
"API",
|
|
30
|
+
"gat"
|
|
29
31
|
],
|
|
30
32
|
"files": [
|
|
31
33
|
"bin",
|
|
@@ -43,6 +45,7 @@
|
|
|
43
45
|
},
|
|
44
46
|
"devDependencies": {
|
|
45
47
|
"@types/node": "^24.3.1",
|
|
48
|
+
"vite": "^8.2.2",
|
|
46
49
|
"vitest": "^3.2.4"
|
|
47
50
|
}
|
|
48
51
|
}
|
package/src/argv/index.ts
CHANGED
package/src/cli/index.ts
CHANGED
|
@@ -2,196 +2,45 @@
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
import * as path from 'path';
|
|
5
|
-
import { Decorator, Project } from 'ts-morph';
|
|
6
|
-
import { pathToFileURL } from 'url';
|
|
7
5
|
import { isExported, output_dir, output_file, positionals } from '../argv';
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { formatResultList } from '../utils';
|
|
12
|
-
|
|
13
|
-
// console.log('positionals', positionals)
|
|
14
|
-
|
|
15
|
-
const sourceFilesGlob = positionals.map(dir => path.normalize(`${dir}/**/*.ts`))
|
|
16
|
-
const out_put_target = path.resolve(output_dir, output_file)
|
|
17
|
-
|
|
18
|
-
// console.log('arg', _arg)
|
|
19
|
-
// console.log('sourceFilesGlob', sourceFilesGlob)
|
|
20
|
-
// debugger
|
|
21
|
-
|
|
22
|
-
type ApiMethodInfo = {
|
|
23
|
-
className: string,
|
|
24
|
-
methodName: string,
|
|
25
|
-
fullMethodName: string,
|
|
26
|
-
modulePath: string,
|
|
27
|
-
args: any[],
|
|
28
|
-
typeName: string,
|
|
29
|
-
isStatic: boolean
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function parserDecoArgs(deco: Decorator): GenTypeOptions {
|
|
33
|
-
const errMsg = `装饰器参数错误`
|
|
34
|
-
try {
|
|
35
|
-
const optionStr = deco.getArguments()[0]?.getText()
|
|
36
|
-
if (!optionStr) return {}
|
|
37
|
-
const option = eval(`(()=>(${optionStr}))()`)
|
|
38
|
-
if (typeof option === 'object') return option
|
|
39
|
-
else throw new Error(errMsg)
|
|
40
|
-
} catch (error) {
|
|
41
|
-
console.warn('parserDecoArgs error', error)
|
|
42
|
-
return {}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
function getApiMethodsInfo() {
|
|
47
|
-
console.log('sourceFilesGlob', sourceFilesGlob)
|
|
48
|
-
const apiMethodsInfo: ApiMethodInfo[] = []
|
|
49
|
-
// 2. 使用ts-morph创建项目,便于解析源码
|
|
50
|
-
// const project = new Project({ tsConfigFilePath: ts_config_path });
|
|
51
|
-
const project = new Project({});
|
|
52
|
-
|
|
53
|
-
project.addSourceFilesAtPaths(sourceFilesGlob);
|
|
54
|
-
// console.log('project.getSourceFiles().length', project.getSourceFiles().length)
|
|
55
|
-
// debugger
|
|
56
|
-
// 3. 遍历所有源文件
|
|
57
|
-
for (const sourceFile of project.getSourceFiles()) {
|
|
58
|
-
|
|
59
|
-
const classes = sourceFile.getClasses();
|
|
60
|
-
for (const classDeclaration of classes) {
|
|
61
|
-
const c_deco = classDeclaration.getDecorator(C_DECO_NAME)
|
|
62
|
-
if (!c_deco) continue
|
|
63
|
-
const methods = classDeclaration.getMethods();
|
|
64
|
-
for (const method of methods) {
|
|
65
|
-
const className = classDeclaration.getName()!;
|
|
66
|
-
const methodName = method.getName();
|
|
67
|
-
const fullMethodName = `${className}.${methodName}`;
|
|
68
|
-
|
|
69
|
-
// if (!method.isStatic()) {
|
|
70
|
-
// console.warn(`⚠️ ${fullMethodName} is not static method,only static method can be transformed`)
|
|
71
|
-
// continue
|
|
72
|
-
// }
|
|
73
|
-
// 4. 检查方法是否被我们的装饰器标记
|
|
74
|
-
const m_deco = method.getDecorator(M_DECO_NAME)
|
|
75
|
-
if (!m_deco) continue
|
|
76
|
-
|
|
77
|
-
const { args = [], typeName = `Response_${className}_${methodName}` } = parserDecoArgs(m_deco)
|
|
78
|
-
apiMethodsInfo.push({
|
|
79
|
-
className, methodName, fullMethodName, modulePath: sourceFile.getFilePath(),
|
|
80
|
-
typeName, args, isStatic: method.isStatic()
|
|
81
|
-
})
|
|
82
|
-
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
return apiMethodsInfo
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
type ExecuteApiMethodResult = {
|
|
90
|
-
data?: any, typeName: string, fullMethodName: string, error?: any
|
|
91
|
-
}
|
|
92
|
-
async function executeApiMethods(apiMethodsInfo: ApiMethodInfo[]): Promise<ExecuteApiMethodResult[]> {
|
|
93
|
-
const apiModuleMap = new Map<string, any>();
|
|
94
|
-
// debugger
|
|
95
|
-
const taskList: ExecuteApiMethodResult[] = []
|
|
96
|
-
for (const apiMethodInfo of apiMethodsInfo) {
|
|
97
|
-
const { className, methodName, fullMethodName, modulePath, args, typeName, isStatic } = apiMethodInfo
|
|
98
|
-
console.log(`📋 处理 ${fullMethodName} ...`);
|
|
99
|
-
let apiModule = null
|
|
100
|
-
// debugger
|
|
101
|
-
if (apiModuleMap.has(modulePath)) apiModule = apiModuleMap.get(modulePath)
|
|
102
|
-
else {
|
|
103
|
-
// apiModule = await import(modulePath)
|
|
104
|
-
// debugger
|
|
105
|
-
// console.log('modulePath', modulePath)
|
|
106
|
-
// console.log('pathToFileURL(modulePath).href', pathToFileURL(modulePath).href)
|
|
107
|
-
|
|
108
|
-
try {
|
|
109
|
-
apiModule = await import(pathToFileURL(modulePath).href)
|
|
110
|
-
// console.log('apiMethod', apiModule)
|
|
111
|
-
if (apiModule) apiModuleMap.set(modulePath, apiModule)
|
|
112
|
-
} catch (error) {
|
|
113
|
-
console.log(`import ${modulePath} error \r\n`, error)
|
|
114
|
-
taskList.push({ error: `module error`, fullMethodName, typeName })
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
const apiMethod = isStatic ?
|
|
119
|
-
apiModule?.[className][methodName]
|
|
120
|
-
: apiModule?.[className].prototype[methodName]
|
|
121
|
-
if (apiMethod && typeof apiMethod === 'function') {
|
|
122
|
-
try {
|
|
123
|
-
// console.log(`🔍 Calling ${fullMethodName} with args:`, args);
|
|
124
|
-
const result = apiMethod.apply(apiModule, args)
|
|
125
|
-
const data = await Promise.resolve(result)
|
|
126
|
-
taskList.push({ data, typeName, fullMethodName })
|
|
127
|
-
} catch (error) {
|
|
128
|
-
console.error(`❌ ${fullMethodName} execute error:`, error)
|
|
129
|
-
taskList.push({ error, fullMethodName, typeName })
|
|
130
|
-
}
|
|
131
|
-
} else {
|
|
132
|
-
console.error(`❌ 无法获取 ${fullMethodName} 方法, 或不是可调用方法 `)
|
|
133
|
-
taskList.push({
|
|
134
|
-
error: `method error`, fullMethodName, typeName
|
|
135
|
-
})
|
|
136
|
-
}
|
|
137
|
-
}
|
|
6
|
+
import { runner, scanner } from '../generation';
|
|
7
|
+
import { importApiModule } from '../generation/moduleLoader';
|
|
8
|
+
import { createDeclarationFile } from '../transformer';
|
|
9
|
+
import { formatResultList, getSourceFilesGlobFromEntrances, logResultList } from '../utils';
|
|
138
10
|
|
|
139
11
|
|
|
140
12
|
|
|
13
|
+
async function main() {
|
|
141
14
|
|
|
142
|
-
return taskList
|
|
143
15
|
|
|
144
|
-
|
|
16
|
+
try {
|
|
145
17
|
|
|
18
|
+
const sourceFilesGlob = getSourceFilesGlobFromEntrances(positionals)
|
|
19
|
+
console.log('sourceFilesGlob', sourceFilesGlob,)
|
|
146
20
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
await ttf.transform(data, typeName)
|
|
152
|
-
return { fullMethodName }
|
|
153
|
-
} catch (error) {
|
|
154
|
-
console.error('transform error', error)
|
|
155
|
-
return { fullMethodName, error }
|
|
21
|
+
const modules = scanner.scan(sourceFilesGlob)
|
|
22
|
+
if (modules.size === 0) {
|
|
23
|
+
console.warn('⚠️ 未找到需要转换的API,请检查api_dir 和 gen_type装饰器标注是否正确!')
|
|
24
|
+
process.exit(0)
|
|
156
25
|
}
|
|
157
|
-
})
|
|
158
|
-
return Promise.all(tasks)
|
|
159
|
-
}
|
|
160
26
|
|
|
27
|
+
await importApiModule(Array.from(modules.keys()))
|
|
161
28
|
|
|
29
|
+
const executeResultList = await runner.run()
|
|
162
30
|
|
|
31
|
+
const { successList: executeSuccessList, errorList: executeErrorList } = formatResultList(executeResultList)
|
|
32
|
+
if (executeErrorList.length) logResultList('请求结果:', executeSuccessList, executeErrorList)
|
|
163
33
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
console.log('🚀 开始生成API类型...');
|
|
167
|
-
const apiMethodsInfo = getApiMethodsInfo();
|
|
168
|
-
if (apiMethodsInfo.length == 0) return console.warn('⚠️ 未找到需要转换的API,请检查api_dir 和 get_type装饰器标注是否正确!')
|
|
169
|
-
const executeList = await executeApiMethods(apiMethodsInfo);
|
|
170
|
-
|
|
171
|
-
const { successList: executeSuccessList, errorList: executeErrorList } = formatResultList(executeList)
|
|
172
|
-
if (executeErrorList.length) {
|
|
173
|
-
console.group('请求结果:')
|
|
174
|
-
console.table({
|
|
175
|
-
"✔️ executeSuccessList": executeSuccessList.map(item => item.fullMethodName).join(' '),
|
|
176
|
-
"❌ executeErrorList": executeErrorList.map(item => item.fullMethodName).join(' ')
|
|
177
|
-
})
|
|
178
|
-
console.groupEnd()
|
|
179
|
-
}
|
|
180
|
-
const transformList = await createDeclarationFile(executeSuccessList)
|
|
34
|
+
const out_put_target = path.resolve(output_dir, output_file)
|
|
35
|
+
const transformList = await createDeclarationFile(executeSuccessList, out_put_target, isExported)
|
|
181
36
|
const { successList: transformSuccessList, errorList: transformErrorList } = formatResultList(transformList)
|
|
182
37
|
|
|
183
|
-
if (transformErrorList.length)
|
|
184
|
-
console.group('转换结果:')
|
|
185
|
-
console.table({
|
|
186
|
-
"✔️ transformSuccessList": transformSuccessList.map(item => item.fullMethodName).join(' '),
|
|
187
|
-
"❌ transformErrorList": transformErrorList.map(item => item.fullMethodName).join(' ')
|
|
188
|
-
})
|
|
189
|
-
console.groupEnd()
|
|
38
|
+
if (transformErrorList.length) logResultList('转换结果:', transformSuccessList, transformErrorList)
|
|
190
39
|
|
|
191
|
-
}
|
|
192
40
|
if (transformSuccessList.length) console.log('✅ API 类型生成完成:', out_put_target);
|
|
193
41
|
} catch (error) {
|
|
194
42
|
console.error('❌ 出错了', error)
|
|
43
|
+
process.exitCode = 1
|
|
195
44
|
}
|
|
196
45
|
|
|
197
46
|
}
|
package/src/constant/index.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
export const GEN_TYPE_METADATA_KEY = Symbol('gen:type:metadata');
|
|
2
2
|
/** 标记方法的装饰器名称 */
|
|
3
|
-
export const
|
|
3
|
+
export const DECO_NAME_M = 'gen_type_m';
|
|
4
4
|
/** 标记类的装饰器名称 */
|
|
5
|
-
export const
|
|
5
|
+
export const DECO_NAME_C = 'gen_type_c';
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
export const EXEC_TIMEOUT = 5_000
|
package/src/decotators/index.ts
CHANGED
|
@@ -1,32 +1,34 @@
|
|
|
1
1
|
// import 'reflect-metadata';
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
import { registry } from "../generation/index.ts";
|
|
4
|
+
import { createClassDecorator, createMethodDecorator } from "../utils/decoratorHelper.ts";
|
|
5
|
+
|
|
4
6
|
|
|
5
7
|
|
|
6
8
|
export interface GenTypeOptions {
|
|
7
9
|
args?: any[];
|
|
8
10
|
typeName?: string;
|
|
9
11
|
}
|
|
10
|
-
/**
|
|
11
|
-
* 标记方法
|
|
12
|
-
*/
|
|
13
|
-
export function gen_type_m({ args = [], typeName }: GenTypeOptions = {}) {
|
|
14
|
-
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
|
15
|
-
// 只存储元数据,不执行任何逻辑
|
|
16
|
-
// Reflect.defineMetadata(
|
|
17
|
-
// GEN_TYPE_METADATA_KEY,
|
|
18
|
-
// { args, typeName },
|
|
19
|
-
// target,
|
|
20
|
-
// propertyKey
|
|
21
|
-
// );
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
12
|
|
|
25
13
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
export const gen_type_c = createClassDecorator((ctx, options) => {
|
|
19
|
+
|
|
20
|
+
})
|
|
21
|
+
export const gen_type_m = createMethodDecorator(async (
|
|
22
|
+
{ target, propertyKey, descriptor },
|
|
23
|
+
{ typeName, args }: GenTypeOptions = { args: [] }
|
|
24
|
+
) => {
|
|
25
|
+
const className = typeof target == 'function' ? target.name : target.constructor.name
|
|
26
|
+
const fullMethodName = `${className}.${propertyKey}`
|
|
27
|
+
typeName ??= `Response_${className}_${propertyKey}`
|
|
28
|
+
const handler = () => (descriptor.value).apply(target, args)
|
|
29
|
+
registry.register({
|
|
30
|
+
key: descriptor.value,
|
|
31
|
+
meta: { typeName, name: fullMethodName, handler }
|
|
32
|
+
})
|
|
33
|
+
})
|
|
34
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { pathToFileURL } from "node:url";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 引入包含标记的方法的模块,触发装饰器执行
|
|
5
|
+
* @param modulePathSet
|
|
6
|
+
* @returns
|
|
7
|
+
*/
|
|
8
|
+
export function importApiModule(modulePathSet: string[]) {
|
|
9
|
+
return Promise.all(
|
|
10
|
+
Array.from(modulePathSet).map(modulePath => import(pathToFileURL(modulePath).href))
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ApiMethod } from "./types"
|
|
2
|
+
|
|
3
|
+
type Task = {
|
|
4
|
+
key: string | symbol | object
|
|
5
|
+
meta: {
|
|
6
|
+
name: string
|
|
7
|
+
handler: ApiMethod
|
|
8
|
+
typeName: string
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class Registry {
|
|
13
|
+
private _taskMap: Map<Task['key'], Task['meta']> = new Map()
|
|
14
|
+
get taskMetas() {
|
|
15
|
+
return Array.from(this._taskMap.values())
|
|
16
|
+
}
|
|
17
|
+
get taskeys() {
|
|
18
|
+
return Array.from(this._taskMap.keys())
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
register(task: Task) {
|
|
22
|
+
this._taskMap.set(task.key, task.meta)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { EXEC_TIMEOUT } from "../constant"
|
|
2
|
+
import { executeApiMethod } from "../utils"
|
|
3
|
+
import { Registry } from "./registry"
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
export class Runner {
|
|
7
|
+
constructor(private registry: Registry) {
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
run() {
|
|
11
|
+
return Promise.all(
|
|
12
|
+
this.registry.taskMetas.map(async ({ name: fullMethodName, handler, typeName }) => {
|
|
13
|
+
try {
|
|
14
|
+
const data = await executeApiMethod({ timeout: EXEC_TIMEOUT, method: handler })
|
|
15
|
+
return { data, typeName, fullMethodName }
|
|
16
|
+
} catch (error) {
|
|
17
|
+
console.error(`❌ ${fullMethodName} execute error:`, error)
|
|
18
|
+
return { error, fullMethodName, typeName }
|
|
19
|
+
} finally {
|
|
20
|
+
}
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { Project } from "ts-morph";
|
|
2
|
+
import { DECO_NAME_C, DECO_NAME_M } from "../constant";
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
type ScanResult = Map<string, Set<string>>
|
|
6
|
+
|
|
7
|
+
export class Scanner {
|
|
8
|
+
constructor(public ts_config_path?: string) { }
|
|
9
|
+
public cacheResult: ScanResult | null = null
|
|
10
|
+
/**
|
|
11
|
+
* 扫描指定的源文件路径,查找被装饰器标记的类和方法,并返回一个映射,键为模块路径,值为该模块中被标记的方法集合。
|
|
12
|
+
* @param sourceFilesGlob
|
|
13
|
+
* @returns modulepath -> methods
|
|
14
|
+
*/
|
|
15
|
+
scan(sourceFilesGlob: string[]) {
|
|
16
|
+
const moduleMap: ScanResult = new Map()
|
|
17
|
+
const project = new Project({ tsConfigFilePath: this.ts_config_path, });
|
|
18
|
+
project.addSourceFilesAtPaths(sourceFilesGlob);
|
|
19
|
+
for (const sourceFile of project.getSourceFiles()) {
|
|
20
|
+
|
|
21
|
+
const classes = sourceFile.getClasses();
|
|
22
|
+
for (const classDeclaration of classes) {
|
|
23
|
+
const c_deco = classDeclaration.getDecorator(DECO_NAME_C)
|
|
24
|
+
if (!c_deco) continue
|
|
25
|
+
const methods = classDeclaration.getMethods();
|
|
26
|
+
for (const method of methods) {
|
|
27
|
+
const className = classDeclaration.getName()!;
|
|
28
|
+
const methodName = method.getName();
|
|
29
|
+
const fullMethodName = `${className}.${methodName}`;
|
|
30
|
+
|
|
31
|
+
const m_deco = method.getDecorator(DECO_NAME_M)
|
|
32
|
+
if (!m_deco) continue
|
|
33
|
+
const modulePath = sourceFile.getFilePath()
|
|
34
|
+
|
|
35
|
+
const methods = moduleMap.get(modulePath) ?? new Set()
|
|
36
|
+
methods.add(fullMethodName)
|
|
37
|
+
moduleMap.set(modulePath, methods)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
this.cacheResult = moduleMap
|
|
42
|
+
return moduleMap
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
get methods() {
|
|
46
|
+
return Array.from(this.cacheResult?.values()!).flatMap(item => [...item])
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './vite/index.ts';
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
import { DECO_NAME_C, DECO_NAME_M } from '../../constant/index.ts';
|
|
3
|
+
|
|
4
|
+
function escapeRegExp(value: string) {
|
|
5
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* 去掉装饰器,用于在项目运行/构建时,gen-api-types的装饰器不会有任何副作用,影响到原来项目代码
|
|
9
|
+
* @param decorators
|
|
10
|
+
* @returns
|
|
11
|
+
*/
|
|
12
|
+
export function removeDecorators(decorators: string[]): Plugin {
|
|
13
|
+
const names = decorators.map(escapeRegExp).join('|');
|
|
14
|
+
|
|
15
|
+
const decoratorRegex = new RegExp(
|
|
16
|
+
`^[ \\t]*@(?:${names})(?:\\s*\\([\\s\\S]*?\\))?[ \\t]*\\r?\\n?`,
|
|
17
|
+
'gm'
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
return {
|
|
21
|
+
name: 'removeDecorators',
|
|
22
|
+
enforce: 'pre',
|
|
23
|
+
|
|
24
|
+
transform(code, id) {
|
|
25
|
+
if (!/\.(ts|tsx)(\?.*)?$/.test(id)) {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const transformedCode = code.replace(decoratorRegex, '');
|
|
30
|
+
|
|
31
|
+
if (transformedCode === code) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
code: transformedCode,
|
|
37
|
+
map: null
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function removeGatDecorators() {
|
|
44
|
+
const decorators = [DECO_NAME_M, DECO_NAME_C]
|
|
45
|
+
return removeDecorators(decorators)
|
|
46
|
+
}
|
package/src/transformer/index.ts
CHANGED
|
@@ -1,62 +1,17 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ExecuteApiMethodResult } from "../generation/types"
|
|
2
|
+
import { TypeTransformer } from "./typeTransformer"
|
|
2
3
|
|
|
3
|
-
function
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
} else if (typeof value === "boolean") {
|
|
16
|
-
return "boolean";
|
|
17
|
-
} else if (value === null) {
|
|
18
|
-
return "null";
|
|
19
|
-
} else if (!value) {
|
|
20
|
-
return "undefined";
|
|
21
|
-
} else {
|
|
22
|
-
return "any";
|
|
23
|
-
}
|
|
4
|
+
export function createDeclarationFile(executeList: ExecuteApiMethodResult[], out_put_target: string, isExported: boolean) {
|
|
5
|
+
const ttf = new TypeTransformer({ filePath: out_put_target, isExported })
|
|
6
|
+
const tasks = executeList.map(async ({ data, typeName, fullMethodName }) => {
|
|
7
|
+
try {
|
|
8
|
+
await ttf.transform(data, typeName)
|
|
9
|
+
return { fullMethodName }
|
|
10
|
+
} catch (error) {
|
|
11
|
+
console.error('transform error', error)
|
|
12
|
+
return { fullMethodName, error }
|
|
13
|
+
}
|
|
14
|
+
})
|
|
15
|
+
return Promise.all(tasks)
|
|
24
16
|
}
|
|
25
17
|
|
|
26
|
-
|
|
27
|
-
export class TypeTransformer {
|
|
28
|
-
project: Project;
|
|
29
|
-
sourceFile: SourceFile;
|
|
30
|
-
isExported: boolean
|
|
31
|
-
constructor({ projectOptions = {}, filePath = "types.d.ts", isExported = false } = {}) {
|
|
32
|
-
this.project = new Project(projectOptions);
|
|
33
|
-
this.sourceFile = this.createSourceFile(filePath);
|
|
34
|
-
this.isExported = isExported
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
createSourceFile(filePath: string) {
|
|
38
|
-
// try {
|
|
39
|
-
// return project.addSourceFileAtPath(filePath);
|
|
40
|
-
// } catch (error) {
|
|
41
|
-
// return project.createSourceFile(filePath);
|
|
42
|
-
// }
|
|
43
|
-
return this.project.createSourceFile(filePath, '', { overwrite: true });
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// 根据运行时对象生成类型定义
|
|
47
|
-
|
|
48
|
-
generateTypeFromObject(val: any, typeName: string) {
|
|
49
|
-
// 4. 添加类型别名
|
|
50
|
-
this.sourceFile.addTypeAlias({
|
|
51
|
-
name: typeName,
|
|
52
|
-
isExported: this.isExported,
|
|
53
|
-
type: inferType(val)
|
|
54
|
-
});
|
|
55
|
-
// if (typeName == 'Res_Weather') throw Error('res_weather test error')
|
|
56
|
-
}
|
|
57
|
-
async transform(res: any, typeName: string, isAsync = true) {
|
|
58
|
-
this.generateTypeFromObject(res, typeName)
|
|
59
|
-
await this.sourceFile.save();
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { Project, SourceFile } from "ts-morph";
|
|
2
|
+
|
|
3
|
+
function inferType(value: any): string {
|
|
4
|
+
if (Array.isArray(value)) {
|
|
5
|
+
if (value.length === 0) return "any[]";
|
|
6
|
+
// 取第一个元素类型,假设数组元素类型一致
|
|
7
|
+
return `${inferType(value[0])}[]`;
|
|
8
|
+
} else if (typeof value === "object" && value !== null) {
|
|
9
|
+
const props = Object.entries(value).map(([k, v]) => `${k}: ${inferType(v)}`).join(";\n");
|
|
10
|
+
return `{${props}}`;
|
|
11
|
+
} else if (typeof value === "string") {
|
|
12
|
+
return "string";
|
|
13
|
+
} else if (typeof value === "number") {
|
|
14
|
+
return "number";
|
|
15
|
+
} else if (typeof value === "boolean") {
|
|
16
|
+
return "boolean";
|
|
17
|
+
} else if (value === null) {
|
|
18
|
+
return "null";
|
|
19
|
+
} else if (!value) {
|
|
20
|
+
return "undefined";
|
|
21
|
+
} else {
|
|
22
|
+
return "any";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
export class TypeTransformer {
|
|
28
|
+
project: Project;
|
|
29
|
+
sourceFile: SourceFile;
|
|
30
|
+
isExported: boolean
|
|
31
|
+
constructor({ projectOptions = {}, filePath = "types.d.ts", isExported = false } = {}) {
|
|
32
|
+
this.project = new Project(projectOptions);
|
|
33
|
+
this.sourceFile = this.createSourceFile(filePath);
|
|
34
|
+
this.isExported = isExported
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
createSourceFile(filePath: string) {
|
|
38
|
+
// try {
|
|
39
|
+
// return project.addSourceFileAtPath(filePath);
|
|
40
|
+
// } catch (error) {
|
|
41
|
+
// return project.createSourceFile(filePath);
|
|
42
|
+
// }
|
|
43
|
+
return this.project.createSourceFile(filePath, '', { overwrite: true });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// 根据运行时对象生成类型定义
|
|
47
|
+
|
|
48
|
+
generateTypeFromObject(val: any, typeName: string) {
|
|
49
|
+
// 4. 添加类型别名
|
|
50
|
+
this.sourceFile.addTypeAlias({
|
|
51
|
+
name: typeName,
|
|
52
|
+
isExported: this.isExported,
|
|
53
|
+
type: inferType(val)
|
|
54
|
+
});
|
|
55
|
+
// if (typeName == 'Res_Weather') throw Error('res_weather test error')
|
|
56
|
+
}
|
|
57
|
+
async transform(res: any, typeName: string, isAsync = true) {
|
|
58
|
+
this.generateTypeFromObject(res, typeName)
|
|
59
|
+
await this.sourceFile.save();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
interface MethodContext {
|
|
6
|
+
target: any,
|
|
7
|
+
propertyKey: string,
|
|
8
|
+
descriptor: PropertyDescriptor
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
export function createMethodDecorator<Options>(
|
|
13
|
+
handler: (ctx: MethodContext, options?: Options) => any,
|
|
14
|
+
defaultOptions?: Options
|
|
15
|
+
) {
|
|
16
|
+
|
|
17
|
+
return (options?: Options) =>
|
|
18
|
+
(target: any, propertyKey: string, descriptor: PropertyDescriptor) =>
|
|
19
|
+
handler({ target, propertyKey, descriptor }, options ?? defaultOptions)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
interface ClassContext {
|
|
24
|
+
target: any
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
export function createClassDecorator<Options>(
|
|
29
|
+
handler: (ctx: ClassContext, options?: Options,) => any,
|
|
30
|
+
defaultOptions?: Options
|
|
31
|
+
) {
|
|
32
|
+
|
|
33
|
+
return (options?: Options) => (target: any) => handler({ target }, options ?? defaultOptions)
|
|
34
|
+
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
package/src/utils/index.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import path from "path"
|
|
2
|
+
import { ApiMethod } from "../generation/types"
|
|
3
|
+
|
|
1
4
|
type ResultInfoBase = { error?: any }
|
|
2
5
|
export function formatResultList<T extends ResultInfoBase>(list: T[]) {
|
|
3
6
|
return list.reduce((acc, item) => {
|
|
@@ -6,3 +9,64 @@ export function formatResultList<T extends ResultInfoBase>(list: T[]) {
|
|
|
6
9
|
return acc
|
|
7
10
|
}, { successList: [] as Omit<T, 'error'>[], errorList: [] as T[] })
|
|
8
11
|
}
|
|
12
|
+
|
|
13
|
+
export function promiseWithResolvers<T>() {
|
|
14
|
+
let promise!: Promise<T>
|
|
15
|
+
let resolve!: (value: T | PromiseLike<T>) => void
|
|
16
|
+
let reject!: (reason?: any) => void
|
|
17
|
+
promise = new Promise((res, rej) => {
|
|
18
|
+
resolve = res
|
|
19
|
+
reject = rej
|
|
20
|
+
})
|
|
21
|
+
return {
|
|
22
|
+
promise, resolve, reject
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
export async function executeApiMethod<T>({
|
|
31
|
+
method,
|
|
32
|
+
timeout = 10 * 1000
|
|
33
|
+
}: {
|
|
34
|
+
method: ApiMethod<T>
|
|
35
|
+
timeout?: number
|
|
36
|
+
}): Promise<T> {
|
|
37
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
38
|
+
|
|
39
|
+
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
40
|
+
timer = setTimeout(() => {
|
|
41
|
+
reject(new Error(`API execution timed out after ${timeout}ms`))
|
|
42
|
+
}, timeout)
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
return await Promise.race([
|
|
47
|
+
Promise.resolve().then(method),
|
|
48
|
+
timeoutPromise
|
|
49
|
+
])
|
|
50
|
+
} finally {
|
|
51
|
+
if (timer) clearTimeout(timer)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
export function getSourceFilesGlobFromEntrances(entrances: string[]): string[] {
|
|
61
|
+
return entrances.map(dir => path.normalize(`${dir}/**/*.ts`))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
export function logResultList(title: string, successLis: any[], errorList: any[]) {
|
|
66
|
+
console.group(`\r\n${title}`)
|
|
67
|
+
console.table({
|
|
68
|
+
"✔️ Success": successLis.map(item => item.fullMethodName).join(' '),
|
|
69
|
+
"❌ Error": errorList.map(item => item.fullMethodName).join(' ')
|
|
70
|
+
})
|
|
71
|
+
console.groupEnd()
|
|
72
|
+
}
|
package/tsconfig.json
CHANGED
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
/* Modules */
|
|
31
31
|
"module": "esnext" /* Specify what module code is generated. */,
|
|
32
32
|
// "rootDir": "./", /* Specify the root folder within your source files. */
|
|
33
|
-
"moduleResolution": "
|
|
33
|
+
"moduleResolution": "bundler" /* Specify how TypeScript looks up a file from a given module specifier. */,
|
|
34
34
|
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
|
35
35
|
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
|
36
36
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
|
39
39
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
40
40
|
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
|
41
|
-
|
|
41
|
+
"allowImportingTsExtensions": true /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */,
|
|
42
42
|
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
|
|
43
43
|
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
|
44
44
|
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
|
60
60
|
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
|
61
61
|
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
|
62
|
-
|
|
62
|
+
"noEmit": true /* Disable emitting files from a compilation. */,
|
|
63
63
|
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
|
64
64
|
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
|
65
65
|
// "removeComments": true, /* Disable emitting comments. */
|