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 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 and executes marked API modules through the project's bundled `tsx` runtime. No global `tsx` installation is required.
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 -D
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. Both static and non-static methods are supported.
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
- - Prefer the exported `gen_type_c` and `gen_type_m` aliases. `GatDecorator` is the internal container used for constant-based decorator names and is not required in business code.
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 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.
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
- "gen_types": "gen-api-types -o output_dir -O output_file_name ./api_dir1 ./api_dir2"
99
+ "gat": "gat -o output_dir -O output_file_name ./api_dir1 ./api_dir2"
100
100
  }
101
101
  }
102
102
  ```
103
103
 
104
- The CLI scans `.ts` files in the input directories, finds marked classes and methods, and dynamically imports the modules containing them. The decorators execute the API methods during module import; the declaration file is generated after all marked methods finish.
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
- 🚀 Start generating API types...
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) │ Values │
114
- ├────────────────┾──────────────────────────────────────â”Ī
115
- │ ✔ïļ successList │ 'TestApi.getList TestApi.getWeather' │
116
- │ ❌ errorList │ '' │
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. Use the `gen_type_c` and `gen_type_m` aliases in business code; direct `GatDecorator.gen_type_m()` calls do not match the plugin's current decorator names.
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 侚åŠĻ态åŊžå…Ĩåđķæ‰§čĄŒæ ‡čŪ°įš„ API æĻĄå—因æ­Ī通čŋ‡éĄđį›Ū内į―Ūįš„ `tsx` čŋčĄŒïžŒäļéœ€č́å…Ļåą€åŪ‰čĢ… `tsx`。
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 -D
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
- - æŽĻ荐ä―ŋį”ĻåŊžå‡šįš„ `gen_type_c`、`gen_type_m` åˆŦ名。`GatDecorator` æ˜Ŋ内éƒĻį”Ļ䚎按åļļé‡åį§°æģĻ册čĢ…éĨ°å™Ļįš„åŪđå™Ļäļæ˜ŊäļšåŠĄäŧĢ᠁åŋ…éĄŧä―ŋį”Ļįš„å…ĨåĢ。
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
- "gen_types": "gen-api-types -o output_dir -O output_file_name ./api_dir1 ./api_dir2"
99
+ "gat": "gat -o output_dir -O output_file_name ./api_dir1 ./api_dir2"
100
100
  }
101
101
  }
102
102
  ```
103
103
 
104
- CLI 侚æ‰Ŧ描čū“å…Ĩį›Ūå―•äļ­įš„ `.ts` 文äŧķæ‰ū到标čŪ°įš„įąŧ和æ–đæģ•后åŠĻ态åŊžå…Ĩ包åŦčŋ™ä𛿖đæģ•įš„æĻĄå—。æĻĄå—åŊžå…Ĩæ—ķčĢ…éĨ°å™Ļäžšæ‰§čĄŒ API æ–đæģ•所有æ–đæģ•åŪŒæˆåŽå†į”ŸæˆåĢ°æ˜Žæ–‡äŧķ。
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
- 🚀 åž€å§‹į”ŸæˆAPIįąŧ型...
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) │ Values │
114
- ├────────────────┾──────────────────────────────────────â”Ī
115
- │ ✔ïļ successList │ 'TestApi.getList TestApi.getWeather' │
116
- │ ❌ errorList │ '' │
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` 和 `.tsx` 文äŧķåđķæ”ŊæŒå•čĄŒæˆ–åĪščĄŒčĢ…éĨ°å™Ļ参数。æŽĻ荐åœĻäļšåŠĄäŧĢ᠁äļ­ä―ŋį”Ļ `gen_type_c`、`gen_type_m` åˆŦ名åĶ‚æžœį›īæŽĨä―ŋį”Ļ `GatDecorator.gen_type_m()`äļäžšåŒđ配插äŧķå―“å‰įš„čĢ…éĨ°å™Ļåį§°ã€‚
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.17",
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 { Project } from 'ts-morph';
6
- import { pathToFileURL } from 'url';
7
- import { isExported, output_dir, output_file, positionals, ts_config_path } from '../argv';
8
- import { DECO_NAME_C, DECO_NAME_M } from '../constant';
9
- import { ExecuteApiMethodResult, executeState } from '../state';
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
- function createDeclarationFile(successList: ExecuteApiMethodResult[]) {
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
- async function main() {
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
- console.group('čŊ·æą‚įŧ“果')
109
- console.table({
110
- "✔ïļ executeSuccessList": executeSuccessList.map(item => item.fullMethodName).join(' '),
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()
@@ -3,3 +3,6 @@ export const GEN_TYPE_METADATA_KEY = Symbol('gen:type:metadata');
3
3
  export const DECO_NAME_M = 'gen_type_m';
4
4
  /** 标čŪ°įąŧįš„čĢ…éĨ°å™Ļåį§° */
5
5
  export const DECO_NAME_C = 'gen_type_c';
6
+
7
+
8
+ export const EXEC_TIMEOUT = 5_000
@@ -1,10 +1,8 @@
1
1
  // import 'reflect-metadata';
2
2
 
3
- import { DECO_NAME_C, DECO_NAME_M } from "../constant/index.ts";
4
- import { executeState } from "../state/index.ts";
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
- export const gen_type_c = GatDecorator[DECO_NAME_C]
55
- export const gen_type_m = GatDecorator[DECO_NAME_M]
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,11 @@
1
+ import { Registry } from "./registry";
2
+ import { Runner } from "./runner";
3
+ import { Scanner } from "./scanner";
4
+
5
+
6
+ export const scanner = new Scanner()
7
+ export const registry = new Registry()
8
+ export const runner = new Runner(registry)
9
+
10
+
11
+
@@ -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
+ }
@@ -0,0 +1,11 @@
1
+
2
+
3
+
4
+ export type Task = CallableFunction
5
+
6
+ export type ApiMethod<T = any> = () => (T | PromiseLike<T>)
7
+
8
+
9
+ export type ExecuteApiMethodResult = {
10
+ data?: any, typeName: string, fullMethodName: string, error?: any
11
+ }
@@ -1,62 +1,17 @@
1
- import { Project, SourceFile } from "ts-morph";
1
+ import { ExecuteApiMethodResult } from "../generation/types"
2
+ import { TypeTransformer } from "./typeTransformer"
2
3
 
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
- }
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
+
@@ -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: () => T | PromiseLike<T>
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
+ }
@@ -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()