gen-api-types 1.0.4 → 1.0.8

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 xuejiangping
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.en.md CHANGED
@@ -1,36 +1,145 @@
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/)
1
+ # gen-api-types
2
+
3
+ #### Introduction
4
+
5
+ 🚀 A CLI tool for automatically generating request interface return types
6
+
7
+ In TypeScript projects, you often need to write interface return types. However, it's troublesome to manually write them every time by referring to the API documentation. If you encounter third-party interfaces or incomplete documentation, you need to debug the interface first before writing the return types, which is quite a headache.
8
+
9
+ With this tool, we can mark request interface classes and methods through TypeScript decorators, then dynamically call these interfaces and convert the returned data into TypeScript type definition files, which can be directly used in projects.
10
+
11
+ > Note:
12
+ >
13
+ > 1. Because this tool uses TypeScript decorators, and decorators currently (TypeScript 5.0) do not support decorating plain functions directly, APIs must be written as **API classes + static API methods**.
14
+ > 2. This tool needs to dynamically execute TypeScript code (importing API classes and calling the marked static API methods), so it runs through the bundled `tsx` dependency. No global `tsx` installation is required.
15
+
16
+ #### Installation
17
+
18
+ 1. npm installation
19
+
20
+ ```shell
21
+ npm install gen-api-types -D
22
+ ```
23
+
24
+ #### Usage
25
+
26
+ ##### 1. Mark interface class names and methods
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<Response_TestApi_getWeather> {
42
+ return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
43
+ }
44
+ }
45
+ ```
46
+
47
+ As shown in the code above:
48
+
49
+ - `@gen_type_c` decorator function is used to mark interface classes. Since the tool dynamically analyzes all ts files in the specified directory, marking interface classes helps quickly locate them.
50
+ - `@gen_type_m` decorator function marks the request methods that need to be converted. It can accept a configuration object with two fields:
51
+ 1. `typeName: string` Interface return type name. If not specified, the default name will be: `Response_${ClassName}_${MethodName}`
52
+ 2. `args: any[]` Method parameter list. The tool will pass this list when calling the request method.
53
+
54
+ ##### 2. Execute command
55
+
56
+ ```shell
57
+ npx gen-api-types -o output_dir -O output_file_name ./api_dir1 ./api_dir2
58
+ ```
59
+
60
+ Parameter description:
61
+
62
+ ```shell
63
+ Usage: npx gen-api-types [options] [api_dirs...]
64
+
65
+ Options:
66
+ -h, --help Output help information
67
+ -r, --project_root <path> Project root directory
68
+ -O, --output_file <path> Output file name
69
+ -o, --output_dir <path> Output directory
70
+ -t, --ts_config_path <path> Path to tsconfig.json file
71
+ --isExported Generate exported type declarations
72
+ ```
73
+
74
+ You can also use it by configuring scripts in package.json:
75
+
76
+ ```json
77
+ {
78
+ "scripts": {
79
+ "gen_types": "gen-api-types -o output_dir -O output_file_name ./api_dir1 ./api_dir2"
80
+ }
81
+ }
82
+ ```
83
+
84
+ Command output:
85
+
86
+ ```shell
87
+ 🚀 Start generating API types...
88
+ sourceFilesGlob [ 'src\\**\\*.ts' ]
89
+ 📋 Processing UserApi.getList ...
90
+ 📋 Processing UserApi.getWeather ...
91
+ Request results:
92
+ ┌────────────────┬──────────────────────────────────────┐
93
+ │ (index) │ Values │
94
+ ├────────────────┼──────────────────────────────────────┤
95
+ │ ✔️ successList │ 'UserApi.getList UserApi.getWeather' │
96
+ │ ❌ errorList │ '' │
97
+ └────────────────┴──────────────────────────────────────┘
98
+ ✅ API type generation completed
99
+ ```
100
+
101
+ ##### 3. Using the types
102
+
103
+ By default, a type definition file index.d.ts is generated, and the type declarations are not exported:
104
+
105
+ ```ts
106
+ type XXX = { name: string };
107
+ type Response_TestApi_getWeather = {...}
108
+ ```
109
+
110
+ You can configure `include` in tsconfig.json to reference the file:
111
+
112
+ ```json
113
+ // tsconfig.json
114
+ {
115
+ "include": ["index.d.ts"]
116
+ }
117
+ ```
118
+
119
+ Or reference it directly at the top of the interface module file:
120
+
121
+ ```ts
122
+ /// <reference path="./index.d.ts" />
123
+ export class TestApi {
124
+ @gen_type_m()
125
+ static getWeather(): Promise<Response_TestApi_getWeather> {
126
+ return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
127
+ }
128
+ }
129
+
130
+ // data is now typed as Response_TestApi_getWeather
131
+ const data = await TestApi.getWeather()
132
+ ```
133
+
134
+ If you want to generate exported type declarations, add `--isExported` when running the command:
135
+
136
+ ```shell
137
+ npx gen-api-types --isExported -o output_dir -O output_file_name ./api_dir1 ./api_dir2
138
+ ```
139
+
140
+ Generated output example:
141
+
142
+ ```ts
143
+ export type XXX = { name: string };
144
+ export type Response_TestApi_getWeather = {...}
145
+ ```
package/README.md CHANGED
@@ -1,109 +1,146 @@
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<Response__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> 输出文件名
69
- -o, --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" />`引用
1
+ # gen-api-types
2
+
3
+ #### 介绍
4
+
5
+ 🚀 一个自动生成请求接口返回类型的 cli 小工具
6
+
7
+ 在 ts 项目中,经常需要编写接口返回类型。但是每次都要查看接口文档,手动编写非常麻烦。如果遇到一些第三方接口或者接口文档不全的情况,还需要先调试接口后,再编写接口返回类型,很令人头疼
8
+
9
+ 借助这个工具,我们可以通过 ts 装饰器来标记请求接口的类和方法,然后动态调用这些接口,并将接口返回的数据转换成 ts 类型文件,这样我们就可以在项目中直接使用了
10
+
11
+ > 注意:
12
+ >
13
+ > 1. 由于需要使用到ts装饰器特性,而装饰器目前(ts 5.0)不支持直接标记普通函数,所以我们的接口必须以 **接口类+静态api方法** 的形式书写
14
+ > 2. 该工具需要动态执行 ts 代码(import接口类,然后调用标记的静态api方法),因此会通过内置依赖的 `tsx` 执行工具运行,无需额外全局安装 `tsx`。
15
+
16
+ #### 安装教程
17
+
18
+ 1.npm 安装
19
+
20
+ ```shell
21
+ npm install gen-api-types -D
22
+
23
+ ```
24
+
25
+ #### 使用说明
26
+
27
+ ##### 1. 标记接口类名和方法
28
+
29
+ ```ts
30
+ import { gen_type_c, gen_type_m } from 'gen-api-types'
31
+
32
+ @gen_type_c()
33
+ export class TestApi {
34
+ @gen_type_m({ args: [100], typeName: 'XXX' })
35
+ static async getList(id: number): Promise<XXX> {
36
+ return asleep(1000).then(() => {
37
+ return { name: 'zs', id }
38
+ })
39
+ }
40
+
41
+ @gen_type_m()
42
+ static getWeather(): Promise<Response_TestApi_getWeather> {
43
+ return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
44
+ }
45
+ }
46
+ ```
47
+
48
+ 如上面代码所示:
49
+
50
+ - `@gen_type_c`装饰器函数,用来标记接口类。因为工具会动态分析指定目录下的所有 ts 文件,标记接口类,可以帮助我们快速定位接口类
51
+ - `@gen_type_m`装饰器函数标记需要转换的请求方法。它可以接收一个配置对象,包含两个字段。
52
+ 1. `typeName: string` 接口返回类型名称,若不指定该字段,默认生成名称为: `Response_${类名}_${方法名}`
53
+ 2. `args:any[] ` 方法参数列表,工具调用请求方法时,会将参数列表传入
54
+
55
+ ##### 2. 执行命令
56
+
57
+ ```shell
58
+ npx gen-api-types -o output_dir -O output_file_name ./api_dir1 ./api_dir2
59
+ ```
60
+
61
+ 参数说明:
62
+
63
+ ```shell
64
+ Usage: npx gen-api-types [options] [api_dirs...]
65
+
66
+ Options:
67
+ -h, --help 输出帮助信息
68
+ -r, --project_root <path> 项目根目录
69
+ -O, --output_file <path> 输出文件名
70
+ -o, --output_dir <path> 输出目录
71
+ -t, --ts_config_path <path> tsconfig.json 文件路径
72
+ --isExported 生成导出的类型声明
73
+ ```
74
+
75
+ 当然,也可以通过配置 package.json 中的 scripts 来使用
76
+
77
+ ```json
78
+ {
79
+ "scripts": {
80
+ "gen_types": "gen-api-types -o output_dir -O output_file_name ./api_dir1 ./api_dir2"
81
+ }
82
+ }
83
+ ```
84
+
85
+ 命令输出:
86
+
87
+ ```shell
88
+ 🚀 开始生成API类型...
89
+ sourceFilesGlob [ 'src\\**\\*.ts' ]
90
+ 📋 处理 TestApi.getList ...
91
+ 📋 处理 TestApi.getWeather ...
92
+ 请求结果:
93
+ ┌────────────────┬──────────────────────────────────────┐
94
+ (index) Values
95
+ ├────────────────┼──────────────────────────────────────┤
96
+ │ ✔️ successList │ 'TestApi.getList TestApi.getWeather' │
97
+ errorList │ '' │
98
+ └────────────────┴──────────────────────────────────────┘
99
+ ✅ API 类型生成完成
100
+ ```
101
+
102
+ ##### 3. 使用类型
103
+
104
+ 默认生成类型文件 index.d.ts,且类型声明没有导出
105
+
106
+ ```ts
107
+ type XXX = { name: string };
108
+ type Response_TestApi_getWeather = {...}
109
+ ```
110
+
111
+ 可在`tsconfig.json`中配置`include`引用文件
112
+
113
+ ```json
114
+ // tsconfig.json
115
+ {
116
+ "include": ["index.d.ts"]
117
+ }
118
+ ```
119
+
120
+ 或者直接在接口模块文件顶部通过 reference 引用:
121
+
122
+ ```ts
123
+ /// <reference path="./index.d.ts" />
124
+ export class TestApi {
125
+ @gen_type_m()
126
+ static getWeather(): Promise<Response_TestApi_getWeather> {
127
+ return fetch('http://t.weather.sojson.com/api/weather/city/101030100').then(r => r.json())
128
+ }
129
+ }
130
+
131
+ //此时data的类型为Response_TestApi_getWeather
132
+ const data = await TestApi.getWeather()
133
+ ```
134
+
135
+ 如果希望生成可导出的类型声明,可以在执行命令时添加 `--isExported`:
136
+
137
+ ```shell
138
+ npx gen-api-types --isExported -o output_dir -O output_file_name ./api_dir1 ./api_dir2
139
+ ```
140
+
141
+ 生成结果示例:
142
+
143
+ ```ts
144
+ export type XXX = { name: string };
145
+ export type Response_TestApi_getWeather = {...}
146
+ ```
package/bin/index.js CHANGED
@@ -1,33 +1,21 @@
1
- #!/usr/bin/env node
2
- // 强制使用 tsx 执行当前目录下的 TypeScript 文件
3
-
4
-
5
- const { exec,execFile,spawn } = require('child_process');
6
- const path = require('path');
7
- const { promisify } = require('util')
8
- const p_exec = promisify(exec);
9
- const args = process.argv.slice(2);
10
- ; (async function () {
11
-
12
- try {
13
- await p_exec('tsx -v')
14
- try {
15
- const cli_path = path.resolve(__dirname,'../src/cli/index.ts')
16
- // const cli_path = path.resolve(__dirname,'../dist/gen_api_types.cli.min.js')
17
-
18
- const cp = spawn('tsx',[cli_path,...args],{ stdio: 'inherit',shell: true })
19
- cp.on('error',err => console.error('执行 tsx 命令失败',err))
20
-
21
-
22
-
23
- } catch (error) {
24
- // console.error('执行 tsx 命令失败',error)
25
- }
26
-
27
-
28
- } catch (error) {
29
- console.error('请安装 tsx',error)
30
- }
31
-
32
- })();
33
-
1
+ #!/usr/bin/env node
2
+
3
+ const { spawn } = require('child_process');
4
+ const path = require('path');
5
+
6
+ const args = process.argv.slice(2);
7
+ const cliPath = path.resolve(__dirname, '../src/cli/index.ts');
8
+ const tsxCliPath = require.resolve('tsx/cli');
9
+
10
+ const cp = spawn(process.execPath, [tsxCliPath, cliPath, ...args], {
11
+ stdio: 'inherit',
12
+ });
13
+
14
+ cp.on('exit', code => {
15
+ process.exit(code ?? 1);
16
+ });
17
+
18
+ cp.on('error', err => {
19
+ console.error('执行 gen-api-types 失败', err);
20
+ process.exit(1);
21
+ });
package/package.json CHANGED
@@ -1,16 +1,22 @@
1
1
  {
2
2
  "name": "gen-api-types",
3
- "version": "1.0.4",
4
- "description": "",
3
+ "version": "1.0.8",
4
+ "description": "一个自动生成请求接口返回类型的 cli 小工具",
5
5
  "main": "./src/index.ts",
6
6
  "bin": {
7
- "gen-api-types": "src/cli/index.ts",
7
+ "gen-api-types": "bin/index.js",
8
8
  "gat": "bin/index.js"
9
9
  },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/xuejiangping/gen-api-types.git"
13
+ },
10
14
  "scripts": {
11
15
  "test": "vitest",
12
16
  "build": "webpack",
13
- "publish:patch": "npm version patch && npm publish"
17
+ "publish:patch": "npm version patch && git push --tags && npm publish",
18
+ "preinstall": "echo preinstall 。。。",
19
+ "postinstall": "echo postinstall 。。。"
14
20
  },
15
21
  "keywords": [
16
22
  "generate types",
@@ -19,13 +25,13 @@
19
25
  "API"
20
26
  ],
21
27
  "files": [
28
+ "bin",
22
29
  "src",
23
30
  "tsconfig.json",
24
31
  "package.json"
25
32
  ],
26
33
  "author": "",
27
34
  "license": "ISC",
28
- "packageManager": "pnpm@10.7.1",
29
35
  "dependencies": {
30
36
  "reflect-metadata": "^0.2.2",
31
37
  "ts-morph": "^27.0.0",