gen-api-types 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/README.en.md +36 -0
- package/README.md +109 -0
- package/package.json +34 -0
- package/src/argv/index.ts +70 -0
- package/src/cli/index.ts +175 -0
- package/src/constant/index.ts +3 -0
- package/src/decotators/index.ts +28 -0
- package/src/index.ts +2 -0
- package/src/transformer/index.ts +58 -0
- package/src/utils/index.ts +12 -0
- package/tsconfig.json +115 -0
package/README.en.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# get-api-types
|
|
2
|
+
|
|
3
|
+
#### Description
|
|
4
|
+
一个自动生成请求接口返回类型的cli工具
|
|
5
|
+
|
|
6
|
+
#### Software Architecture
|
|
7
|
+
Software architecture description
|
|
8
|
+
|
|
9
|
+
#### Installation
|
|
10
|
+
|
|
11
|
+
1. xxxx
|
|
12
|
+
2. xxxx
|
|
13
|
+
3. xxxx
|
|
14
|
+
|
|
15
|
+
#### Instructions
|
|
16
|
+
|
|
17
|
+
1. xxxx
|
|
18
|
+
2. xxxx
|
|
19
|
+
3. xxxx
|
|
20
|
+
|
|
21
|
+
#### Contribution
|
|
22
|
+
|
|
23
|
+
1. Fork the repository
|
|
24
|
+
2. Create Feat_xxx branch
|
|
25
|
+
3. Commit your code
|
|
26
|
+
4. Create Pull Request
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
#### Gitee Feature
|
|
30
|
+
|
|
31
|
+
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
|
|
32
|
+
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
|
|
33
|
+
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
|
|
34
|
+
4. The most valuable open source project [GVP](https://gitee.com/gvp)
|
|
35
|
+
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
|
|
36
|
+
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
package/README.md
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# gen-api-types
|
|
2
|
+
|
|
3
|
+
#### 介绍
|
|
4
|
+
|
|
5
|
+
🚀 一个自动生成请求接口返回类型的 cli 工具
|
|
6
|
+
|
|
7
|
+
在 ts 项目中,经常需要编写接口返回类型。但是每次都要查看接口文档,手动编写非常麻烦。如果遇到一些第三方接口或者接口文档不全的情况,还需要先调试接口后,再编写接口返回类型,很令人头疼
|
|
8
|
+
|
|
9
|
+
借助这个工具,我们可以通过 ts 装饰器来标记请求接口的类和方法,然后动态调用这些接口,并将接口返回的数据转换成 ts 类型文件,这样我们就可以在项目中直接使用了
|
|
10
|
+
|
|
11
|
+
> 注意:
|
|
12
|
+
> 该工具需要动态执行 ts 代码(调用项目中的接口模块),必须依赖 `tsx` 执行工具,请务必先全局安装 `tsx`,确保`tsx`命令可用。
|
|
13
|
+
|
|
14
|
+
#### 安装教程
|
|
15
|
+
|
|
16
|
+
1.npm 安装
|
|
17
|
+
|
|
18
|
+
```shell
|
|
19
|
+
npm install tsx -g
|
|
20
|
+
npm install gen-api-types -D
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
#### 使用说明
|
|
25
|
+
|
|
26
|
+
##### 1. 标记接口类名和方法
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { gen_type_c, gen_type_m } from 'gen-api-types'
|
|
30
|
+
|
|
31
|
+
@gen_type_c()
|
|
32
|
+
export class TestApi {
|
|
33
|
+
@gen_type_m({ args: [100], typeName: 'XXX' })
|
|
34
|
+
static async getList(id: number): Promise<XXX> {
|
|
35
|
+
return asleep(1000).then(() => {
|
|
36
|
+
return { name: 'zs', id }
|
|
37
|
+
})
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
@gen_type_m()
|
|
41
|
+
static getWeather(): Promise<Res_TestApi_getWeather> {
|
|
42
|
+
return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
如上面代码所示:
|
|
48
|
+
|
|
49
|
+
- `@gen_type_c`装饰器函数,用来标记接口类。因为工具会动态分析指定目录下的所有 ts 文件,标记接口类,可以帮助我们快速定位接口类
|
|
50
|
+
- `@gen_type_m`装饰器函数标记需要转换的请求方法。它可以接收一个配置对象,包含两个字段。
|
|
51
|
+
1. `typeName: string` 接口返回类型名称,若不指定该字段,默认生成名称为: `Response_${类名}_${方法名}`
|
|
52
|
+
2. `args:any[] ` 方法参数列表,工具调用请求方法时,会将参数列表传入
|
|
53
|
+
|
|
54
|
+
##### 2. 执行命令
|
|
55
|
+
|
|
56
|
+
```shell
|
|
57
|
+
npx gen-api-types -o output_dir -O output_file_name ./api_dir1 ./api_dir2
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
参数说明:
|
|
61
|
+
|
|
62
|
+
```shell
|
|
63
|
+
Usage: npx gen-api-types [options] [api_dirs...]
|
|
64
|
+
|
|
65
|
+
Options:
|
|
66
|
+
-h, --help 输出帮助信息
|
|
67
|
+
-r, --project_root <path> 项目根目录
|
|
68
|
+
-o, --output_file <path> 输出文件,默认index.d.ts
|
|
69
|
+
-d, --output_dir <path> 输出目录,默认当前根目录
|
|
70
|
+
-t, --ts_config_path <path> tsconfig.json 文件路径
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
当然,也可以通过配置 package.json 中的 scripts 来使用
|
|
74
|
+
|
|
75
|
+
```json
|
|
76
|
+
{
|
|
77
|
+
"scripts": {
|
|
78
|
+
"gen_types": "gen-api-types -o output_dir -O output_file_name ./api_dir1 ./api_dir2"
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
命令输出:
|
|
84
|
+
|
|
85
|
+
```shell
|
|
86
|
+
🚀 开始生成API类型...
|
|
87
|
+
sourceFilesGlob [ 'src\\**\\*.ts' ]
|
|
88
|
+
📋 处理 UserApi.getList ...
|
|
89
|
+
📋 处理 UserApi.getWeather ...
|
|
90
|
+
请求结果:
|
|
91
|
+
┌────────────────┬──────────────────────────────────────┐
|
|
92
|
+
│ (index) │ Values │
|
|
93
|
+
├────────────────┼──────────────────────────────────────┤
|
|
94
|
+
│ ✔️ successList │ 'UserApi.getList UserApi.getWeather' │
|
|
95
|
+
│ ❌ errorList │ '' │
|
|
96
|
+
└────────────────┴──────────────────────────────────────┘
|
|
97
|
+
✅ API 类型生成完成
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
##### 3. 使用类型
|
|
101
|
+
|
|
102
|
+
默认生成类型文件 index.d.ts,且没有导出
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
type XXX = { name: string };
|
|
106
|
+
type Response_UserApi_getWeather = {...}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
可在`tsconfig.json`中配置`include`引用文件,或者直接在接口模块文件顶部通过`/// <reference path="./index.d.ts" />`引用
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "gen-api-types",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "",
|
|
5
|
+
"main": "./src/index.ts",
|
|
6
|
+
"bin": {
|
|
7
|
+
"gen-api-types-2": "src/cli/index.ts"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"test": "echo \"Error: no test specified\" && exit 1",
|
|
11
|
+
"build": "webpack",
|
|
12
|
+
"publish:patch": "npm version patch && npm publish"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [],
|
|
15
|
+
"files": [
|
|
16
|
+
"src",
|
|
17
|
+
"tsconfig.json",
|
|
18
|
+
"package.json"
|
|
19
|
+
],
|
|
20
|
+
"author": "",
|
|
21
|
+
"license": "ISC",
|
|
22
|
+
"packageManager": "pnpm@10.7.1",
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"reflect-metadata": "^0.2.2",
|
|
25
|
+
"ts-morph": "^27.0.0",
|
|
26
|
+
"tsx": "^4.20.5"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^24.3.1",
|
|
30
|
+
"ts-loader": "^9.5.4",
|
|
31
|
+
"webpack": "^5.101.0",
|
|
32
|
+
"webpack-cli": "^6.0.1"
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
import { parseArgs } from "util";
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
// 1. 配置
|
|
6
|
+
const PROJECT_ROOT = path.resolve();
|
|
7
|
+
const OUTPUT_FILE = 'index.d.ts';
|
|
8
|
+
const OUTPUT_DIR = PROJECT_ROOT
|
|
9
|
+
const TS_CONFIG_PATH = path.join(PROJECT_ROOT, 'tsconfig.json');
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
const _arg = parseArgs({
|
|
14
|
+
allowPositionals: true,
|
|
15
|
+
args: process.argv.slice(2),
|
|
16
|
+
options: {
|
|
17
|
+
output_dir: {
|
|
18
|
+
type: 'string',
|
|
19
|
+
short: 'o',
|
|
20
|
+
default: OUTPUT_DIR,
|
|
21
|
+
},
|
|
22
|
+
output_file: {
|
|
23
|
+
type: 'string',
|
|
24
|
+
short: 'O',
|
|
25
|
+
default: OUTPUT_FILE,
|
|
26
|
+
},
|
|
27
|
+
project_root: {
|
|
28
|
+
type: 'string',
|
|
29
|
+
short: 'r',
|
|
30
|
+
default: PROJECT_ROOT,
|
|
31
|
+
},
|
|
32
|
+
ts_config_path: {
|
|
33
|
+
type: 'string',
|
|
34
|
+
short: 't',
|
|
35
|
+
default: TS_CONFIG_PATH,
|
|
36
|
+
},
|
|
37
|
+
help: {
|
|
38
|
+
type: 'boolean',
|
|
39
|
+
short: 'h'
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
export const { positionals, values: { project_root, output_file, output_dir, ts_config_path, help } } = _arg
|
|
46
|
+
|
|
47
|
+
if (help) {
|
|
48
|
+
console.log(`
|
|
49
|
+
Usage: tsx cli.js [options] [positionals]
|
|
50
|
+
|
|
51
|
+
Options:
|
|
52
|
+
-h, --help 输出帮助信息
|
|
53
|
+
-r, --project_root <path> 项目根目录
|
|
54
|
+
-o, --output_file <path> 输出文件
|
|
55
|
+
-d, --output_dir <path> 输出目录
|
|
56
|
+
-t, --ts_config_path <path> tsconfig.json 文件路径
|
|
57
|
+
`
|
|
58
|
+
)
|
|
59
|
+
process.exit(0)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
if (positionals.length == 0) {
|
|
67
|
+
console.error('❌ 错误: 必须指定 API 目录');
|
|
68
|
+
console.log('💡 用法示例: node cli.js ./api-directory');
|
|
69
|
+
process.exit(1)
|
|
70
|
+
}
|
package/src/cli/index.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
#!/usr/bin/env tsx
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
// scripts/generate-api-types.ts
|
|
5
|
+
import * as path from 'path';
|
|
6
|
+
import { Decorator, Project } from 'ts-morph';
|
|
7
|
+
import { pathToFileURL } from 'url';
|
|
8
|
+
import { output_dir, output_file, positionals } from '../argv';
|
|
9
|
+
import { C_DECO_NAME, M_DECO_NAME } from '../constant';
|
|
10
|
+
import { GenTypeOptions } from '../decotators';
|
|
11
|
+
import { TypeTransformer } from '../transformer';
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
const sourceFilesGlob = positionals.map(dir => path.normalize(`${dir}/**/*.ts`))
|
|
16
|
+
|
|
17
|
+
// console.log('arg', _arg)
|
|
18
|
+
// console.log('sourceFilesGlob', sourceFilesGlob)
|
|
19
|
+
// debugger
|
|
20
|
+
|
|
21
|
+
type ApiMethodInfo = {
|
|
22
|
+
className: string,
|
|
23
|
+
methodName: string,
|
|
24
|
+
fullMethodName: string,
|
|
25
|
+
modulePath: string,
|
|
26
|
+
args: any[],
|
|
27
|
+
typeName: string,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function parserDecoArgs(deco: Decorator): GenTypeOptions {
|
|
31
|
+
const errMsg = `装饰器参数错误`
|
|
32
|
+
try {
|
|
33
|
+
const optionStr = deco.getArguments()[0]?.getText()
|
|
34
|
+
if (!optionStr) return {}
|
|
35
|
+
const option = eval(`(()=>(${optionStr}))()`)
|
|
36
|
+
if (typeof option === 'object') return option
|
|
37
|
+
else throw new Error(errMsg)
|
|
38
|
+
} catch (error) {
|
|
39
|
+
console.warn('parserDecoArgs error', error)
|
|
40
|
+
return {}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
}
|
|
44
|
+
function getApiMethodsInfo() {
|
|
45
|
+
console.log('sourceFilesGlob', sourceFilesGlob)
|
|
46
|
+
const apiMethodsInfo: ApiMethodInfo[] = []
|
|
47
|
+
// 2. 使用ts-morph创建项目,便于解析源码
|
|
48
|
+
// const project = new Project({ tsConfigFilePath: ts_config_path });
|
|
49
|
+
const project = new Project({});
|
|
50
|
+
|
|
51
|
+
project.addSourceFilesAtPaths(sourceFilesGlob);
|
|
52
|
+
// debugger
|
|
53
|
+
// 3. 遍历所有源文件
|
|
54
|
+
for (const sourceFile of project.getSourceFiles()) {
|
|
55
|
+
|
|
56
|
+
const classes = sourceFile.getClasses();
|
|
57
|
+
for (const classDeclaration of classes) {
|
|
58
|
+
const c_deco = classDeclaration.getDecorator(C_DECO_NAME)
|
|
59
|
+
if (!c_deco) continue
|
|
60
|
+
const methods = classDeclaration.getMethods();
|
|
61
|
+
for (const method of methods) {
|
|
62
|
+
|
|
63
|
+
const className = classDeclaration.getName()!;
|
|
64
|
+
const methodName = method.getName();
|
|
65
|
+
const fullMethodName = `${className}.${methodName}`;
|
|
66
|
+
|
|
67
|
+
if (!method.isStatic()) {
|
|
68
|
+
console.warn(`⚠️ ${fullMethodName} is not static method,only static method can be transformed`)
|
|
69
|
+
continue
|
|
70
|
+
}
|
|
71
|
+
// 4. 检查方法是否被我们的装饰器标记
|
|
72
|
+
const m_deco = method.getDecorator(M_DECO_NAME)
|
|
73
|
+
if (!m_deco) continue
|
|
74
|
+
|
|
75
|
+
const { args = [], typeName = `Response_${className}_${methodName}` } = parserDecoArgs(m_deco)
|
|
76
|
+
apiMethodsInfo.push({
|
|
77
|
+
className, methodName, fullMethodName, modulePath: sourceFile.getFilePath(),
|
|
78
|
+
typeName, args
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return apiMethodsInfo
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
type ExcuteApiMethodsResult = {
|
|
88
|
+
successList: { data: any, typeName: string, fullMethodName: string }[],
|
|
89
|
+
errorList: { fullMethodName: string, error: any }[]
|
|
90
|
+
}
|
|
91
|
+
async function excuteApiMethods(apiMethodsInfo: ApiMethodInfo[]): Promise<ExcuteApiMethodsResult> {
|
|
92
|
+
const apiModuleMap = new Map<string, any>();
|
|
93
|
+
const taskList = apiMethodsInfo.map(async (apiMethodInfo) => {
|
|
94
|
+
const { className, methodName, fullMethodName, modulePath, args, typeName } = apiMethodInfo
|
|
95
|
+
console.log(`📋 处理 ${fullMethodName} ...`);
|
|
96
|
+
let apiModule = null
|
|
97
|
+
if (apiModuleMap.has(modulePath)) apiModule = apiModuleMap.get(modulePath)
|
|
98
|
+
else {
|
|
99
|
+
// apiModule = await import(modulePath)
|
|
100
|
+
// debugger
|
|
101
|
+
// console.log('modulePath', modulePath)
|
|
102
|
+
// console.log('pathToFileURL(modulePath).href', pathToFileURL(modulePath).href)
|
|
103
|
+
|
|
104
|
+
try {
|
|
105
|
+
apiModule = await import(pathToFileURL(modulePath).href)
|
|
106
|
+
console.log('apiMethod', apiModule)
|
|
107
|
+
if (apiModule) apiModuleMap.set(modulePath, apiModule)
|
|
108
|
+
} catch (error) {
|
|
109
|
+
console.log('import modulePath error', error)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
}
|
|
113
|
+
const apiMethod = apiModule?.[className]?.[methodName]
|
|
114
|
+
if (apiMethod && typeof apiMethod === 'function') {
|
|
115
|
+
try {
|
|
116
|
+
console.log(`🔍 Calling ${fullMethodName} with args:`, args);
|
|
117
|
+
const result = apiMethod.apply(apiModule, args)
|
|
118
|
+
if (result instanceof Promise) {
|
|
119
|
+
const data = await result
|
|
120
|
+
// console.log(`${fullMethodName} result`)
|
|
121
|
+
return { data, typeName, fullMethodName }
|
|
122
|
+
}
|
|
123
|
+
return { error: 'not Promise method', fullMethodName }
|
|
124
|
+
} catch (error) {
|
|
125
|
+
console.error(`❌ ${fullMethodName} execute error:`, error)
|
|
126
|
+
return { error, fullMethodName }
|
|
127
|
+
}
|
|
128
|
+
} else {
|
|
129
|
+
console.error(`❌ 无法获取 ${fullMethodName}或 非 可调用方法 `)
|
|
130
|
+
return {
|
|
131
|
+
error: `method error`, fullMethodName
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
const resultList = await Promise.all(taskList)
|
|
137
|
+
return {
|
|
138
|
+
successList: resultList.filter(item => !item.error) as ExcuteApiMethodsResult['successList'],
|
|
139
|
+
errorList: resultList.filter(item => item.error) as ExcuteApiMethodsResult['errorList'],
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function createDeclarationFile(successList: ExcuteApiMethodsResult['successList']) {
|
|
144
|
+
const out_put_target = path.resolve(output_dir, output_file)
|
|
145
|
+
// console.log('out_put_target', out_put_target)
|
|
146
|
+
const ttf = new TypeTransformer({ filePath: out_put_target })
|
|
147
|
+
const tasks = successList.map(item => ttf.transform(item.data, item.typeName))
|
|
148
|
+
return Promise.all(tasks)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function main() {
|
|
152
|
+
try {
|
|
153
|
+
console.log('🚀 开始生成API类型...');
|
|
154
|
+
const apiMethodsInfo = getApiMethodsInfo();
|
|
155
|
+
const { successList, errorList } = await excuteApiMethods(apiMethodsInfo);
|
|
156
|
+
|
|
157
|
+
console.group('请求结果:')
|
|
158
|
+
console.table({
|
|
159
|
+
"✔️ successList": successList.map(item => item.fullMethodName).join(' '),
|
|
160
|
+
"❌ errorList": errorList.map(item => item.fullMethodName).join(' ')
|
|
161
|
+
})
|
|
162
|
+
console.groupEnd()
|
|
163
|
+
await createDeclarationFile(successList)
|
|
164
|
+
|
|
165
|
+
console.log('✅ API 类型生成完成');
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
} catch (error) {
|
|
170
|
+
console.error('❌ 出错了', error)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
main()
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// import 'reflect-metadata';
|
|
2
|
+
|
|
3
|
+
// 定义一个唯一的metadata key
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
export interface GenTypeOptions {
|
|
7
|
+
args?: any[];
|
|
8
|
+
typeName?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function gen_type_m({ args = [], typeName }: GenTypeOptions = {}) {
|
|
12
|
+
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
|
13
|
+
// 只存储元数据,不执行任何逻辑
|
|
14
|
+
// Reflect.defineMetadata(
|
|
15
|
+
// GEN_TYPE_METADATA_KEY,
|
|
16
|
+
// { args, typeName },
|
|
17
|
+
// target,
|
|
18
|
+
// propertyKey
|
|
19
|
+
// );
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
export function gen_type_c() {
|
|
26
|
+
return function <T>(target: T) {
|
|
27
|
+
};
|
|
28
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
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("; ");
|
|
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) {
|
|
18
|
+
return "null";
|
|
19
|
+
} else {
|
|
20
|
+
return "any";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
export class TypeTransformer {
|
|
26
|
+
project: Project;
|
|
27
|
+
sourceFile: SourceFile;
|
|
28
|
+
constructor({ projectOptions = {}, filePath = "types.d.ts" } = {}) {
|
|
29
|
+
this.project = new Project(projectOptions);
|
|
30
|
+
this.sourceFile = this.createSourceFile(filePath);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
createSourceFile(filePath: string) {
|
|
34
|
+
// try {
|
|
35
|
+
// return project.addSourceFileAtPath(filePath);
|
|
36
|
+
// } catch (error) {
|
|
37
|
+
// return project.createSourceFile(filePath);
|
|
38
|
+
// }
|
|
39
|
+
return this.project.createSourceFile(filePath, '', { overwrite: true });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// 根据运行时对象生成类型定义
|
|
43
|
+
|
|
44
|
+
generateTypeFromObject(val: any, typeName: string) {
|
|
45
|
+
// 4. 添加类型别名
|
|
46
|
+
this.sourceFile.addTypeAlias({
|
|
47
|
+
name: typeName,
|
|
48
|
+
// isExported: true,
|
|
49
|
+
type: inferType(val)
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
transform(res: any, typeName: string, isAsync = true) {
|
|
53
|
+
|
|
54
|
+
this.generateTypeFromObject(res, typeName)
|
|
55
|
+
return this.sourceFile.save();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
{
|
|
2
|
+
"exclude": [],
|
|
3
|
+
"include": ["src", "test", "test2/"],
|
|
4
|
+
"compilerOptions": {
|
|
5
|
+
/* Visit https://aka.ms/tsconfig to read more about this file */
|
|
6
|
+
|
|
7
|
+
/* Projects */
|
|
8
|
+
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
|
9
|
+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
|
10
|
+
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
|
11
|
+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
|
12
|
+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
|
13
|
+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
|
14
|
+
|
|
15
|
+
/* Language and Environment */
|
|
16
|
+
"target": "es2022" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
|
17
|
+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
|
18
|
+
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
|
19
|
+
// "libReplacement": true, /* Enable lib replacement. */
|
|
20
|
+
"experimentalDecorators": true /* Enable experimental support for legacy experimental decorators. */,
|
|
21
|
+
"emitDecoratorMetadata": true /* Emit design-type metadata for decorated declarations in source files. */,
|
|
22
|
+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
|
23
|
+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
|
24
|
+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
|
25
|
+
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
|
26
|
+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
|
27
|
+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
|
28
|
+
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
|
29
|
+
|
|
30
|
+
/* Modules */
|
|
31
|
+
"module": "esnext" /* Specify what module code is generated. */,
|
|
32
|
+
// "rootDir": "./", /* Specify the root folder within your source files. */
|
|
33
|
+
"moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
|
|
34
|
+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
|
35
|
+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
|
36
|
+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
37
|
+
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
|
38
|
+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
|
39
|
+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
40
|
+
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
|
41
|
+
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
|
42
|
+
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
|
|
43
|
+
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
|
44
|
+
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
|
45
|
+
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
|
46
|
+
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
|
|
47
|
+
// "resolveJsonModule": true, /* Enable importing .json files. */
|
|
48
|
+
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
|
49
|
+
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
|
50
|
+
|
|
51
|
+
/* JavaScript Support */
|
|
52
|
+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
|
53
|
+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
|
54
|
+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
|
55
|
+
|
|
56
|
+
/* Emit */
|
|
57
|
+
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
|
58
|
+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
|
59
|
+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
|
60
|
+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
|
61
|
+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
|
62
|
+
// "noEmit": true, /* Disable emitting files from a compilation. */
|
|
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
|
+
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
|
65
|
+
// "removeComments": true, /* Disable emitting comments. */
|
|
66
|
+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
|
67
|
+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
|
68
|
+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
|
69
|
+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
70
|
+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
|
71
|
+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
|
72
|
+
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
|
73
|
+
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
|
74
|
+
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
|
75
|
+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
|
76
|
+
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
|
77
|
+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
|
78
|
+
|
|
79
|
+
/* Interop Constraints */
|
|
80
|
+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
|
81
|
+
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
|
82
|
+
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
|
|
83
|
+
// "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */
|
|
84
|
+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
|
85
|
+
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
|
|
86
|
+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
|
87
|
+
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
|
|
88
|
+
|
|
89
|
+
/* Type Checking */
|
|
90
|
+
"strict": true /* Enable all strict type-checking options. */,
|
|
91
|
+
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
|
92
|
+
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
|
93
|
+
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
|
94
|
+
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
|
95
|
+
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
|
96
|
+
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
|
|
97
|
+
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
|
98
|
+
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
|
99
|
+
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
|
100
|
+
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
|
101
|
+
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
|
102
|
+
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
|
103
|
+
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
|
104
|
+
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
|
105
|
+
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
|
106
|
+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
|
107
|
+
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
|
108
|
+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
|
109
|
+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
|
110
|
+
|
|
111
|
+
/* Completeness */
|
|
112
|
+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
|
113
|
+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
|
114
|
+
}
|
|
115
|
+
}
|