gen-api-types 1.0.17 â 1.0.19
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 +33 -18
- package/README.md +34 -17
- package/package.json +3 -2
- package/src/cli/index.ts +21 -111
- package/src/constant/index.ts +3 -0
- package/src/decotators/index.ts +22 -43
- 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/transformer/index.ts +14 -59
- package/src/transformer/typeTransformer.ts +62 -0
- package/src/utils/decoratorHelper.ts +38 -0
- package/src/utils/index.ts +26 -1
- package/src/state/index.ts +0 -45
package/README.en.md
CHANGED
|
@@ -11,7 +11,7 @@ With this tool, we can mark request interface classes and methods through TypeSc
|
|
|
11
11
|
> Note:
|
|
12
12
|
>
|
|
13
13
|
> 1. Because this tool uses TypeScript method decorators, APIs must be written as **API classes + API methods**.
|
|
14
|
-
> 2. The CLI dynamically imports
|
|
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
15
|
> 3. API methods are executed for real in the CLI process. Make sure required environment variables, network access, and authentication are available.
|
|
16
16
|
|
|
17
17
|
#### Installation
|
|
@@ -19,7 +19,7 @@ With this tool, we can mark request interface classes and methods through TypeSc
|
|
|
19
19
|
1. npm installation
|
|
20
20
|
|
|
21
21
|
```shell
|
|
22
|
-
npm install gen-api-types
|
|
22
|
+
npm install gen-api-types
|
|
23
23
|
```
|
|
24
24
|
|
|
25
25
|
#### Usage
|
|
@@ -51,10 +51,10 @@ export class TestApi {
|
|
|
51
51
|
As shown in the code above:
|
|
52
52
|
|
|
53
53
|
- `@gen_type_c()` marks an API class.
|
|
54
|
-
- `@gen_type_m()` marks a method to execute and convert.
|
|
55
|
-
- `args: any[]` contains the arguments passed to the method.
|
|
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. Both static and non-static methods are supported.
|
|
55
|
+
- `args: any[]` contains the arguments passed to the method.
|
|
56
56
|
- `typeName: string` is the generated type name. If omitted, it defaults to `Response_${ClassName}_${MethodName}`.
|
|
57
|
-
-
|
|
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
58
|
|
|
59
59
|
Decorator options may span multiple lines:
|
|
60
60
|
|
|
@@ -69,9 +69,9 @@ Decorator options may span multiple lines:
|
|
|
69
69
|
|
|
70
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
71
|
|
|
72
|
-
The CLI
|
|
72
|
+
The CLI applies a default 5-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.
|
|
73
73
|
|
|
74
|
-
##### 2. Execute command
|
|
74
|
+
##### 2. Execute command (`gen-api-types`, `gat`)
|
|
75
75
|
|
|
76
76
|
```shell
|
|
77
77
|
npx gen-api-types -o output_dir -O output_file_name ./api_dir1 ./api_dir2
|
|
@@ -96,26 +96,41 @@ You can also use it by configuring scripts in package.json:
|
|
|
96
96
|
```json
|
|
97
97
|
{
|
|
98
98
|
"scripts": {
|
|
99
|
-
"
|
|
99
|
+
"gat": "gat -o output_dir -O output_file_name ./api_dir1 ./api_dir2"
|
|
100
100
|
}
|
|
101
101
|
}
|
|
102
102
|
```
|
|
103
103
|
|
|
104
|
-
|
|
104
|
+
Available commands:
|
|
105
|
+
|
|
106
|
+
```json
|
|
107
|
+
"bin": {
|
|
108
|
+
"gen-api-types": "bin/index.js",
|
|
109
|
+
"gat": "bin/index.js"
|
|
110
|
+
},
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
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 type declaration file. Each API method has a default execution timeout of 5 seconds; registered methods run concurrently.
|
|
105
114
|
|
|
106
115
|
Command output:
|
|
107
116
|
|
|
108
117
|
```shell
|
|
109
|
-
|
|
118
|
+
# When there are no errors
|
|
110
119
|
sourceFilesGlob [ 'src\\**\\*.ts' ]
|
|
120
|
+
â
API type generation completed: /path/to/api-types.d.ts
|
|
121
|
+
|
|
122
|
+
# If a request fails, its type is skipped; types are generated only for successful requests.
|
|
123
|
+
sourceFilesGlob [ 'test/api/**/*.ts' ]
|
|
124
|
+
â SampleApi.testError execute error: ReferenceError: arg is not defined
|
|
125
|
+
|
|
111
126
|
Request results:
|
|
112
|
-
|
|
113
|
-
â (index)
|
|
114
|
-
|
|
115
|
-
â âïļ
|
|
116
|
-
â â
|
|
117
|
-
|
|
118
|
-
â
API type generation completed
|
|
127
|
+
âââââââââââââŽâââââââââââââââââââââââââââââââââââââââââââ
|
|
128
|
+
â (index) â Values â
|
|
129
|
+
âââââââââââââžâââââââââââââââââââââââââââââââââââââââââââĪ
|
|
130
|
+
â âïļ Success â 'SampleApi.getWeather SampleApi.getList' â
|
|
131
|
+
â â Error â 'SampleApi.testError' â
|
|
132
|
+
âââââââââââââīâââââââââââââââââââââââââââââââââââââââââââ
|
|
133
|
+
â
API type generation completed: /path/to/api-types.d.ts
|
|
119
134
|
```
|
|
120
135
|
|
|
121
136
|
##### 3. Using the types
|
|
@@ -178,7 +193,7 @@ export default defineConfig({
|
|
|
178
193
|
})
|
|
179
194
|
```
|
|
180
195
|
|
|
181
|
-
The plugin processes `.ts` and `.tsx` files and supports single-line and multi-line decorator options.
|
|
196
|
+
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`.
|
|
182
197
|
|
|
183
198
|
The Vite plugin only affects Vite's transform pipeline. It is not involved when the CLI imports and executes API modules.
|
|
184
199
|
|
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
> æģĻæïž
|
|
12
12
|
>
|
|
13
13
|
> 1. įąäšéčĶä―ŋįĻ TypeScript æđæģčĢ
éĨ°åĻïžæĨåĢéčĶäŧĨ **API įąŧ + API æđæģ** įå―ĒåžäđĶåã
|
|
14
|
-
> 2. CLI
|
|
14
|
+
> 2. CLI äžåĻæåŊžå
Ĩå
åŦæ čŪ°æđæģįæĻĄåãæĻĄåéĄķåąäŧĢį äžåĻåŊžå
Ĩæķæ§čĄïžčĢ
éĨ°åĻåŠįŧčŪ°äŧŧåĄïžCLI éåæč°įĻå·ēįŧčŪ°į API æđæģã
|
|
15
15
|
> 3. API æđæģäžåĻ CLI čŋįĻäļįåŪæ§čĄïžčŊ·įĄŪäŋčŋčĄæéįįŊåĒåéãį―įŧæéåéīæé
į―Ūå·ēįŧååĪåĨ―ã
|
|
16
16
|
|
|
17
17
|
#### åŪčĢ
æįĻ
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
1.npm åŪčĢ
|
|
20
20
|
|
|
21
21
|
```shell
|
|
22
|
-
npm install gen-api-types
|
|
22
|
+
npm install gen-api-types
|
|
23
23
|
```
|
|
24
24
|
|
|
25
25
|
#### ä―ŋįĻčŊīæ
|
|
@@ -51,10 +51,10 @@ export class TestApi {
|
|
|
51
51
|
åĶäļéĒäŧĢį æįĪš:
|
|
52
52
|
|
|
53
53
|
- `@gen_type_c()` æ čŪ° API įąŧã
|
|
54
|
-
- `@gen_type_m()`
|
|
55
|
-
- `args: any[]`
|
|
54
|
+
- `@gen_type_m()` æ čŪ°éčĶæ§čĄåđķįæįąŧåįæđæģïžčĢ
éĨ°åĻčīčīĢįŧčŪ°äŧŧåĄïžAPI æđæģäžåĻ CLI å č――åŪæĻĄååįą Runner č°įĻïžæŊæéææđæģåééææđæģ
|
|
55
|
+
- `args: any[]` č°įĻæđæģæķäž å
Ĩįåæ°
|
|
56
56
|
- `typeName: string` æŊįæįįąŧååį§°ïžäļæåŪæķéŧčŪĪäļš `Response_${įąŧå}_${æđæģå}`ã
|
|
57
|
-
-
|
|
57
|
+
- æ čŪ°įąŧäŧ
įĻäšæŋč――čĢ
éĨ°åĻïžRunner äļäžååŧšįąŧåŪäūãæŪéæđæģäļčĶäūčĩ `this` æåŪäūåæŪĩã
|
|
58
58
|
|
|
59
59
|
čĢ
éĨ°åĻåæ°åŊäŧĨč·ĻåĪčĄäđĶåïž
|
|
60
60
|
|
|
@@ -71,7 +71,7 @@ export class TestApi {
|
|
|
71
71
|
|
|
72
72
|
CLI éŧčŪĪäžäļšåäļŠ API æđæģčŪūį―Ū 5 į§æ§čĄčķ
æķãčķ
æķãåæĨåžåļļæ Promise rejection é―äžčĒŦčŪ°å―äļščŊĨæđæģįæ§čĄåĪąčīĨïžčķ
æķåŠč―åæĒįåū
ïžäļč―åæķå·ēįŧååšįåšåąčŊ·æąã
|
|
73
73
|
|
|
74
|
-
##### 2. æ§čĄå―äŧĪ
|
|
74
|
+
##### 2. æ§čĄå―äŧĪ (`gen-api-types`ã`gat`)
|
|
75
75
|
|
|
76
76
|
```shell
|
|
77
77
|
npx gen-api-types -o output_dir -O output_file_name ./api_dir1 ./api_dir2
|
|
@@ -96,26 +96,43 @@ Options:
|
|
|
96
96
|
```json
|
|
97
97
|
{
|
|
98
98
|
"scripts": {
|
|
99
|
-
"
|
|
99
|
+
"gat": "gat -o output_dir -O output_file_name ./api_dir1 ./api_dir2"
|
|
100
100
|
}
|
|
101
101
|
}
|
|
102
102
|
```
|
|
103
103
|
|
|
104
|
-
|
|
104
|
+
åŊįĻįįå―äŧĪïž
|
|
105
|
+
|
|
106
|
+
```json
|
|
107
|
+
"bin": {
|
|
108
|
+
"gen-api-types": "bin/index.js",
|
|
109
|
+
"gat": "bin/index.js"
|
|
110
|
+
},
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
CLI äžæŦæčūå
ĨįŪå―äļį `.ts` æäŧķïžæūå°æ čŪ°įįąŧåæđæģåå
ķæåąæĻĄåãéååĻæåŊžå
ĨčŋäšæĻĄåïžä―ŋčĢ
éĨ°åĻįŧčŪ°äŧŧåĄïžå
ĻéĻæĻĄåå č――åŪæåïžRunner æč°įĻįŧčŪ°į API æđæģïžåđķå°æåįŧæč―ŽæĒäļšįąŧåå̰ææäŧķãæŊäļŠ API æđæģįéŧčŪĪæ§čĄčķ
æķäļš 5 į§ïžåĪäļŠå·ēįŧčŪ°æđæģäžåđķåæ§čĄã
|
|
105
114
|
|
|
106
115
|
å―äŧĪčūåšïž
|
|
107
116
|
|
|
108
117
|
```shell
|
|
109
|
-
|
|
118
|
+
# æ éčŊŊæķ
|
|
110
119
|
sourceFilesGlob [ 'src\\**\\*.ts' ]
|
|
120
|
+
â
API įąŧåįæåŪæïž /path/to/api-types.d.ts
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# å
åŦčŊ·æąéčŊŊæķïžäžåŋ―įĨčŊĨæĄčŊ·æąįįąŧåïžåŠįæ Success įįąŧå
|
|
124
|
+
|
|
125
|
+
sourceFilesGlob [ 'test/api/**/*.ts' ]
|
|
126
|
+
â SampleApi.testError execute error: ReferenceError: arg is not defined
|
|
127
|
+
|
|
111
128
|
čŊ·æąįŧæïž
|
|
112
|
-
|
|
113
|
-
â (index)
|
|
114
|
-
|
|
115
|
-
â âïļ
|
|
116
|
-
â â
|
|
117
|
-
|
|
118
|
-
â
API
|
|
129
|
+
âââââââââââââŽâââââââââââââââââââââââââââââââââââââââââââ
|
|
130
|
+
â (index) â Values â
|
|
131
|
+
âââââââââââââžâââââââââââââââââââââââââââââââââââââââââââĪ
|
|
132
|
+
â âïļ Success â 'SampleApi.getWeather SampleApi.getList' â
|
|
133
|
+
â â Error â 'SampleApi.testError' â
|
|
134
|
+
âââââââââââââīâââââââââââââââââââââââââââââââââââââââââââ
|
|
135
|
+
â
API įąŧåįæåŪæïž /Users/xuejiangping/Desktop/demo/gen-api-types/test/output/api-types.d.ts
|
|
119
136
|
```
|
|
120
137
|
|
|
121
138
|
##### 3. ä―ŋįĻįąŧå
|
|
@@ -178,7 +195,7 @@ export default defineConfig({
|
|
|
178
195
|
})
|
|
179
196
|
```
|
|
180
197
|
|
|
181
|
-
æäŧķåŠåĪį `.ts`
|
|
198
|
+
æäŧķåŠåĪį `.ts` æäŧķïžåđķæŊæåčĄæåĪčĄčĢ
éĨ°åĻåæ°ãæäŧķæ `gen_type_c`ã`gen_type_m` čŋäļĪäļŠčĢ
éĨ°åĻåį§°į§ŧéĪčĢ
éĨ°åĻã
|
|
182
199
|
|
|
183
200
|
Vite æäŧķåŠå―ąå Vite įč―ŽæĒæĩįĻïžäļåäļ CLI į API æ§čĄæĩįĻã
|
|
184
201
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gen-api-types",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.19",
|
|
4
4
|
"description": "äļäļŠčŠåĻįæčŊ·æąæĨåĢčŋåįąŧåį cli å°å·Ĩå
·",
|
|
5
5
|
"main": "./src/index.ts",
|
|
6
6
|
"exports": {
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
"generate types",
|
|
27
27
|
"TypeScript",
|
|
28
28
|
"Cli",
|
|
29
|
-
"API"
|
|
29
|
+
"API",
|
|
30
|
+
"gat"
|
|
30
31
|
],
|
|
31
32
|
"files": [
|
|
32
33
|
"bin",
|
package/src/cli/index.ts
CHANGED
|
@@ -2,137 +2,47 @@
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
import * as path from 'path';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import { TypeTransformer } from '../transformer';
|
|
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
|
-
|
|
23
|
-
function getModulePathSet() {
|
|
24
|
-
console.log('sourceFilesGlob', sourceFilesGlob)
|
|
25
|
-
const modulePathSet: Set<string> = new Set()
|
|
26
|
-
// 2. ä―ŋįĻts-morphååŧšéĄđįŪïžäūŋäšč§Ģææšį
|
|
27
|
-
// const project = new Project({ tsConfigFilePath: ts_config_path });
|
|
28
|
-
const project = new Project({
|
|
29
|
-
tsConfigFilePath: ts_config_path
|
|
30
|
-
});
|
|
31
|
-
project.addSourceFilesAtPaths(sourceFilesGlob);
|
|
32
|
-
// console.log('project.getSourceFiles().length', project.getSourceFiles().length)
|
|
33
|
-
// debugger
|
|
34
|
-
// 3. éåæææšæäŧķ
|
|
35
|
-
for (const sourceFile of project.getSourceFiles()) {
|
|
36
|
-
|
|
37
|
-
const classes = sourceFile.getClasses();
|
|
38
|
-
for (const classDeclaration of classes) {
|
|
39
|
-
const c_deco = classDeclaration.getDecorator(DECO_NAME_C)
|
|
40
|
-
if (!c_deco) continue
|
|
41
|
-
const methods = classDeclaration.getMethods();
|
|
42
|
-
for (const method of methods) {
|
|
43
|
-
const className = classDeclaration.getName()!;
|
|
44
|
-
const methodName = method.getName();
|
|
45
|
-
const fullMethodName = `${className}.${methodName}`;
|
|
46
|
-
|
|
47
|
-
// 4. æĢæĨæđæģæŊåĶčĒŦæäŧŽįčĢ
éĨ°åĻæ čŪ°
|
|
48
|
-
const m_deco = method.getDecorator(DECO_NAME_M)
|
|
49
|
-
if (!m_deco) continue
|
|
50
|
-
executeState.emit(executeState.ADD_TASK, fullMethodName)
|
|
51
|
-
const modulePath = sourceFile.getFilePath()
|
|
52
|
-
if (!modulePathSet.has(modulePath)) modulePathSet.add(modulePath)
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
return modulePathSet
|
|
59
|
-
}
|
|
5
|
+
import { isExported, output_dir, output_file, positionals } from '../argv';
|
|
6
|
+
import { runner, scanner } from '../generation';
|
|
7
|
+
import { importApiModule } from '../generation/moduleLoader';
|
|
8
|
+
import { createDeclarationFile } from '../transformer';
|
|
9
|
+
import { formatResultList, getSourceFilesGlobFromEntrances, logResultList } from '../utils';
|
|
60
10
|
|
|
61
11
|
|
|
62
|
-
/**
|
|
63
|
-
* åžå
Ĩå
åŦæ čŪ°įæđæģįæĻĄåïžč§ĶåčĢ
éĨ°åĻæ§čĄïžčŪ°å―æ§čĄįŧæ
|
|
64
|
-
* @param modulePathSet
|
|
65
|
-
* @returns
|
|
66
|
-
*/
|
|
67
|
-
async function importApiModule<T extends string>(modulePathSet: Set<T>) {
|
|
68
|
-
return Promise.all(
|
|
69
|
-
Array.from(modulePathSet).map(modulePath => import(pathToFileURL(modulePath).href))
|
|
70
|
-
)
|
|
71
12
|
|
|
72
|
-
|
|
13
|
+
async function main() {
|
|
73
14
|
|
|
74
15
|
|
|
75
|
-
|
|
76
|
-
const ttf = new TypeTransformer({ filePath: out_put_target, isExported })
|
|
77
|
-
const tasks = successList.map(async ({ data, typeName, fullMethodName }) => {
|
|
78
|
-
try {
|
|
79
|
-
await ttf.transform(data, typeName)
|
|
80
|
-
return { fullMethodName }
|
|
81
|
-
} catch (error) {
|
|
82
|
-
console.error('transform error', error)
|
|
83
|
-
return { fullMethodName, error }
|
|
84
|
-
}
|
|
85
|
-
})
|
|
86
|
-
return Promise.all(tasks)
|
|
87
|
-
}
|
|
16
|
+
try {
|
|
88
17
|
|
|
18
|
+
const sourceFilesGlob = getSourceFilesGlobFromEntrances(positionals)
|
|
19
|
+
console.log('sourceFilesGlob', sourceFilesGlob,)
|
|
89
20
|
|
|
21
|
+
const modules = scanner.scan(sourceFilesGlob)
|
|
22
|
+
if (modules.size === 0) {
|
|
23
|
+
console.warn('â ïļ æŠæūå°éčĶč―ŽæĒįAPI,čŊ·æĢæĨapi_dir å gen_typečĢ
éĨ°åĻæ æģĻæŊåĶæĢįĄŪ!')
|
|
24
|
+
process.exit(0)
|
|
25
|
+
}
|
|
90
26
|
|
|
27
|
+
await importApiModule(Array.from(modules.keys()))
|
|
91
28
|
|
|
92
|
-
|
|
93
|
-
console.log('ð åžå§įæAPIįąŧå...');
|
|
94
|
-
const modulePathSet = getModulePathSet();
|
|
95
|
-
if (modulePathSet.size == 0) {
|
|
29
|
+
const executeResultList = await runner.run()
|
|
96
30
|
|
|
97
|
-
console.error('â ïļ æŠæūå°éčĶč―ŽæĒįAPI,čŊ·æĢæĨapi_dir å gen_typečĢ
éĨ°åĻæ æģĻæŊåĶæĢįĄŪ!')
|
|
98
|
-
process.exit(1)
|
|
99
|
-
}
|
|
100
|
-
try {
|
|
101
|
-
await importApiModule(modulePathSet);
|
|
102
|
-
// executeState.addListener(executeState.TASKLIST_CLEAR, executeResultList=>{
|
|
103
|
-
// })
|
|
104
|
-
|
|
105
|
-
const executeResultList = await executeState.promise
|
|
106
31
|
const { successList: executeSuccessList, errorList: executeErrorList } = formatResultList(executeResultList)
|
|
107
|
-
if (executeErrorList.length)
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
"â executeErrorList": executeErrorList.map(item => item.fullMethodName).join(' ')
|
|
112
|
-
})
|
|
113
|
-
console.groupEnd()
|
|
114
|
-
}
|
|
115
|
-
const transformList = await createDeclarationFile(executeSuccessList)
|
|
32
|
+
if (executeErrorList.length) logResultList('čŊ·æąįŧæïž', executeSuccessList, executeErrorList)
|
|
33
|
+
|
|
34
|
+
const out_put_target = path.resolve(output_dir, output_file)
|
|
35
|
+
const transformList = await createDeclarationFile(executeSuccessList, out_put_target, isExported)
|
|
116
36
|
const { successList: transformSuccessList, errorList: transformErrorList } = formatResultList(transformList)
|
|
117
37
|
|
|
118
|
-
if (transformErrorList.length)
|
|
119
|
-
console.group('č―ŽæĒįŧæïž')
|
|
120
|
-
console.table({
|
|
121
|
-
"âïļ transformSuccessList": transformSuccessList.map(item => item.fullMethodName).join(' '),
|
|
122
|
-
"â transformErrorList": transformErrorList.map(item => item.fullMethodName).join(' ')
|
|
123
|
-
})
|
|
124
|
-
console.groupEnd()
|
|
38
|
+
if (transformErrorList.length) logResultList('č―ŽæĒįŧæïž', transformSuccessList, transformErrorList)
|
|
125
39
|
|
|
126
|
-
}
|
|
127
40
|
if (transformSuccessList.length) console.log('â
API įąŧåįæåŪæïž', out_put_target);
|
|
128
41
|
} catch (error) {
|
|
129
42
|
console.error('â åšéäš', error)
|
|
130
43
|
process.exitCode = 1
|
|
131
44
|
}
|
|
132
45
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
46
|
}
|
|
137
47
|
|
|
138
48
|
main()
|
package/src/constant/index.ts
CHANGED
package/src/decotators/index.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
// import 'reflect-metadata';
|
|
2
2
|
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { executeApiMethod } from "../utils/index.ts";
|
|
3
|
+
import { registry } from "../generation/index.ts";
|
|
4
|
+
import { createClassDecorator, createMethodDecorator } from "../utils/decoratorHelper.ts";
|
|
6
5
|
|
|
7
|
-
// åŪäđäļäļŠåŊäļįmetadata key
|
|
8
6
|
|
|
9
7
|
|
|
10
8
|
export interface GenTypeOptions {
|
|
@@ -13,43 +11,24 @@ export interface GenTypeOptions {
|
|
|
13
11
|
}
|
|
14
12
|
|
|
15
13
|
|
|
16
|
-
const EXEC_TIMEOUT = 5_000
|
|
17
|
-
export class GatDecorator {
|
|
18
|
-
static [DECO_NAME_C]() {
|
|
19
|
-
return function <T>(target: T) {
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
static [DECO_NAME_M]({ args = [], typeName }: GenTypeOptions = {}) {
|
|
23
|
-
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
(async () => {
|
|
27
|
-
const className = typeof target == 'function' ? target.name : target.constructor.name
|
|
28
|
-
const fullMethodName = `${className}.${propertyKey}`
|
|
29
|
-
console.log('fullMethodName', fullMethodName)
|
|
30
|
-
typeName ??= `Response_${className}_${propertyKey}`
|
|
31
|
-
let resultInfo = null
|
|
32
|
-
try {
|
|
33
|
-
const apiMethod = descriptor.value as Function
|
|
34
|
-
// console.log(`ð Calling ${fullMethodName} with args:`, args);
|
|
35
|
-
|
|
36
|
-
const data = await executeApiMethod({
|
|
37
|
-
timeout: EXEC_TIMEOUT,
|
|
38
|
-
method: () => apiMethod.apply(target, args)
|
|
39
|
-
})
|
|
40
|
-
|
|
41
|
-
resultInfo = { data, typeName, fullMethodName }
|
|
42
|
-
} catch (error) {
|
|
43
|
-
console.error(`â ${fullMethodName} execute error:`, error)
|
|
44
|
-
resultInfo = { error, fullMethodName, typeName }
|
|
45
|
-
} finally {
|
|
46
|
-
executeState.emit(executeState.EXECUTE_END, resultInfo)
|
|
47
|
-
}
|
|
48
|
-
})();
|
|
49
|
-
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
14
|
|
|
54
|
-
|
|
55
|
-
|
|
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/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) => {
|
|
@@ -20,11 +23,15 @@ export function promiseWithResolvers<T>() {
|
|
|
20
23
|
}
|
|
21
24
|
}
|
|
22
25
|
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
23
30
|
export async function executeApiMethod<T>({
|
|
24
31
|
method,
|
|
25
32
|
timeout = 10 * 1000
|
|
26
33
|
}: {
|
|
27
|
-
method:
|
|
34
|
+
method: ApiMethod<T>
|
|
28
35
|
timeout?: number
|
|
29
36
|
}): Promise<T> {
|
|
30
37
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
@@ -45,3 +52,21 @@ export async function executeApiMethod<T>({
|
|
|
45
52
|
}
|
|
46
53
|
}
|
|
47
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/src/state/index.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import EventEmitter from "events"
|
|
2
|
-
import { promiseWithResolvers } from "../utils/index.ts"
|
|
3
|
-
|
|
4
|
-
export type ExecuteApiMethodResult = {
|
|
5
|
-
data?: any, typeName: string, fullMethodName: string, error?: any
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
export class ExecuteState extends EventEmitter {
|
|
14
|
-
|
|
15
|
-
EXECUTE_END = 'executeEnd'
|
|
16
|
-
TASKLIST_CLEAR = 'taskClear'
|
|
17
|
-
ADD_TASK = 'addTask'
|
|
18
|
-
private resultList: ExecuteApiMethodResult[] = []
|
|
19
|
-
private taskList: string[] = []
|
|
20
|
-
promiseWithResolvers = promiseWithResolvers<ExecuteApiMethodResult[]>()
|
|
21
|
-
constructor() {
|
|
22
|
-
super()
|
|
23
|
-
this.init()
|
|
24
|
-
}
|
|
25
|
-
init() {
|
|
26
|
-
this.addListener(this.EXECUTE_END, (result: ExecuteApiMethodResult) => {
|
|
27
|
-
this.resultList.push(result)
|
|
28
|
-
if (this.resultList.length === this.taskList.length) {
|
|
29
|
-
this.emit(this.TASKLIST_CLEAR, this.resultList)
|
|
30
|
-
this.promiseWithResolvers?.resolve(this.resultList)
|
|
31
|
-
}
|
|
32
|
-
})
|
|
33
|
-
|
|
34
|
-
this.addListener(this.ADD_TASK, (taskName) => {
|
|
35
|
-
this.taskList.push(taskName)
|
|
36
|
-
})
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
get promise() {
|
|
40
|
-
return this.promiseWithResolvers?.promise
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export const executeState = new ExecuteState()
|