ai-worktool 1.0.7

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.
@@ -0,0 +1,376 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.initProject = initProject;
7
+ exports.installDependencies = installDependencies;
8
+ exports.addScript = addScript;
9
+ exports.runTest = runTest;
10
+ exports.setupTestEnvironment = setupTestEnvironment;
11
+ const child_process_1 = require("child_process");
12
+ const promises_1 = __importDefault(require("fs/promises"));
13
+ const path_1 = __importDefault(require("path"));
14
+ const util_1 = require("util");
15
+ // 将exec转换为返回Promise的函数
16
+ const execAsync = (0, util_1.promisify)(child_process_1.exec);
17
+ /**
18
+ * 检查指定路径下是否存在package.json文件
19
+ *
20
+ * @param projectPath 项目路径
21
+ * @returns Promise<boolean> 存在返回true,否则返回false
22
+ */
23
+ async function hasPackageJson(projectPath) {
24
+ try {
25
+ await promises_1.default.access(path_1.default.join(projectPath, 'package.json'));
26
+ return true;
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ /**
33
+ * 获取包管理器对应的命令字符串
34
+ *
35
+ * @param manager 包管理器类型,默认为'yarn'
36
+ * @returns string 包管理器命令(如'yarn'或'npm')
37
+ */
38
+ function getPackageManagerCommand(manager = 'yarn') {
39
+ return manager;
40
+ }
41
+ /**
42
+ * 生成安装依赖的命令字符串
43
+ *
44
+ * @param dependencies 依赖包列表
45
+ * @param isDev 是否为开发依赖(devDependencies)
46
+ * @param manager 包管理器类型,默认为'yarn'
47
+ * @returns string 安装依赖的命令字符串,依赖为空时返回空字符串
48
+ */
49
+ function getInstallCommand(dependencies, isDev, manager = 'yarn') {
50
+ if (!dependencies.length) {
51
+ return '';
52
+ }
53
+ if (manager === 'yarn') {
54
+ return isDev ? `yarn add ${dependencies.join(' ')} --dev` : `yarn add ${dependencies.join(' ')}`;
55
+ }
56
+ else {
57
+ return isDev ? `npm install --save-dev ${dependencies.join(' ')}` : `npm install --save ${dependencies.join(' ')}`;
58
+ }
59
+ }
60
+ /**
61
+ * 生成运行npm/yarn脚本的命令字符串
62
+ *
63
+ * @param scriptName 脚本名称(如'test'、'build')
64
+ * @param args 传递给脚本的参数列表,默认为空数组
65
+ * @param manager 包管理器类型,默认为'yarn'
66
+ * @returns string 运行脚本的命令字符串
67
+ */
68
+ function getRunScriptCommand(scriptName, args = [], manager = 'yarn') {
69
+ if (manager === 'yarn') {
70
+ return `yarn ${scriptName} ${args.join(' ')}`.trim();
71
+ }
72
+ else {
73
+ return `npm run ${scriptName} -- ${args.join(' ')}`.trim();
74
+ }
75
+ }
76
+ /**
77
+ * 初始化项目(生成package.json文件)
78
+ *
79
+ * @export
80
+ * @param projectPath 项目路径
81
+ * @param manager 包管理器类型,默认为'yarn'
82
+ * @returns Promise<void> 初始化成功时resolve,失败时reject
83
+ * @description 静默执行(无弹窗),若package.json已存在则跳过初始化
84
+ */
85
+ async function initProject(projectPath, manager = 'yarn') {
86
+ try {
87
+ projectPath = projectPath;
88
+ const resolvedPath = path_1.default.resolve(projectPath);
89
+ if (!(await hasPackageJson(resolvedPath))) {
90
+ const cmd = getPackageManagerCommand(manager);
91
+ const initCmd = cmd === 'yarn' ? 'yarn init -y' : 'npm init -y';
92
+ // 静默执行:不显示弹窗,不输出到控制台
93
+ await executeCommand(resolvedPath, initCmd, '初始化项目');
94
+ console.log(`成功使用${cmd}初始化项目`);
95
+ }
96
+ else {
97
+ console.log('package.json已存在,跳过初始化');
98
+ // 检查node_modules目录是否存在(判断是否已安装依赖)
99
+ const nodeModulesPath = path_1.default.join(resolvedPath, 'node_modules');
100
+ try {
101
+ await promises_1.default.access(nodeModulesPath);
102
+ console.log('依赖已安装,无需操作');
103
+ }
104
+ catch {
105
+ console.log('检测到未安装依赖,开始安装...');
106
+ // 安装所有依赖(生产+开发)
107
+ const installCmd = manager === 'yarn' ? 'yarn install' : 'npm install';
108
+ await executeCommand(resolvedPath, installCmd, '安装项目依赖');
109
+ console.log('依赖安装完成');
110
+ }
111
+ }
112
+ }
113
+ catch (error) {
114
+ console.error('初始化项目失败:', error);
115
+ throw error;
116
+ }
117
+ }
118
+ /**
119
+ * 安装项目依赖
120
+ *
121
+ * @export
122
+ * @param projectPath 项目路径
123
+ * @param dependencies 依赖包列表(数组或逗号分隔的字符串)
124
+ * @param isDev 是否安装为开发依赖,默认为false
125
+ * @param manager 包管理器类型,默认为'yarn'
126
+ * @returns Promise<void> 安装成功时resolve,失败时reject
127
+ * @description 静默执行(无弹窗),支持批量安装依赖
128
+ */
129
+ async function installDependencies(projectPath, dependencies, isDev = false, manager = 'yarn') {
130
+ try {
131
+ // 处理字符串类型的依赖(逗号分隔)
132
+ if (typeof dependencies === 'string') {
133
+ dependencies = dependencies.split(',').map((dep) => dep.trim());
134
+ }
135
+ const resolvedPath = path_1.default.resolve(projectPath);
136
+ const installCmd = getInstallCommand(dependencies, isDev, manager);
137
+ if (!installCmd) {
138
+ console.log('没有需要安装的依赖');
139
+ return;
140
+ }
141
+ console.log(`正在安装依赖: ${dependencies.join(', ')}`);
142
+ // 静默执行:不显示弹窗,不输出安装过程
143
+ await executeCommand(resolvedPath, installCmd, '正在安装依赖');
144
+ console.log('依赖安装完成');
145
+ }
146
+ catch (error) {
147
+ console.error('安装依赖失败:', error);
148
+ throw error;
149
+ }
150
+ }
151
+ /**
152
+ * 向package.json的scripts字段添加自定义脚本
153
+ *
154
+ * @export
155
+ * @param projectPath 项目路径
156
+ * @param scriptName 脚本名称(如'start'、'build')
157
+ * @param scriptCommand 脚本执行的命令(如'node index.js')
158
+ * @returns Promise<void> 添加成功时resolve,失败时reject
159
+ */
160
+ async function addScript(projectPath, scriptName, scriptCommand) {
161
+ try {
162
+ const resolvedPath = path_1.default.resolve(projectPath);
163
+ const pkgPath = path_1.default.join(resolvedPath, 'package.json');
164
+ const pkgContent = await promises_1.default.readFile(pkgPath, 'utf8');
165
+ const pkg = JSON.parse(pkgContent);
166
+ pkg.scripts = pkg.scripts || {};
167
+ pkg.scripts[scriptName] = scriptCommand;
168
+ await promises_1.default.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
169
+ console.log(`已添加脚本: ${scriptName}="${scriptCommand}"`);
170
+ }
171
+ catch (error) {
172
+ console.error('添加脚本失败:', error);
173
+ throw error;
174
+ }
175
+ }
176
+ /**
177
+ * 运行项目中的测试脚本(package.json中定义的'test'脚本)
178
+ *
179
+ * @export
180
+ * @param projectPath 项目路径
181
+ * @param args 传递给测试脚本的参数列表,默认为空数组
182
+ * @param manager 包管理器类型,默认为'yarn'
183
+ * @returns Promise<void> 测试成功时resolve,失败时reject
184
+ * @description 静默执行(无弹窗),通过Promise返回测试结果
185
+ */
186
+ async function runTest(projectPath, args = [], manager = 'yarn') {
187
+ try {
188
+ const resolvedPath = path_1.default.resolve(projectPath);
189
+ const runCmd = getRunScriptCommand('test', args, manager);
190
+ const [cmd, ...cmdArgs] = runCmd.split(' ').filter(Boolean);
191
+ console.log(`正在运行测试: ${runCmd}`);
192
+ // 静默执行测试(无弹窗)
193
+ await executeCommand(resolvedPath, `${cmd} ${cmdArgs.join(' ')}`, '运行测试');
194
+ }
195
+ catch (error) {
196
+ console.error('启动测试失败:', error);
197
+ throw error;
198
+ }
199
+ }
200
+ /**
201
+ * 验证输入参数是否有效
202
+ * @param packageManager 包管理器
203
+ * @param devLanguage 开发语言
204
+ * @param testFramework 测试框架
205
+ * @throws {Error} 当参数无效时抛出错误
206
+ */
207
+ function validateParameters(packageManager, devLanguage, testFramework) {
208
+ const validPackageManagers = ['npm', 'yarn', 'pnpm'];
209
+ const validLanguages = ['typescript', 'javascript'];
210
+ const validTestFrameworks = ['jest', 'mocha', 'vitest'];
211
+ if (!validPackageManagers.includes(packageManager) || !packageManager || packageManager === 'unknown') {
212
+ throw new Error(`无效的包管理器: ${packageManager}。有效值: ${validPackageManagers.join(', ')}`);
213
+ }
214
+ if (!validLanguages.includes(devLanguage) || !devLanguage || devLanguage === 'unknown') {
215
+ throw new Error(`无效的开发语言: ${devLanguage}。有效值: ${validLanguages.join(', ')}`);
216
+ }
217
+ if (!validTestFrameworks.includes(testFramework) || !testFramework || testFramework === 'unknown') {
218
+ throw new Error(`无效的测试框架: ${testFramework}。有效值: ${validTestFrameworks.join(', ')}`);
219
+ }
220
+ }
221
+ /**
222
+ * 执行命令并输出结果
223
+ * @param command 要执行的命令
224
+ * @param description 命令描述,用于日志输出
225
+ */
226
+ async function executeCommand(resolvedPath, command, description) {
227
+ console.log(`正在${description}...`);
228
+ try {
229
+ const { stdout } = await execAsync(command, {
230
+ cwd: resolvedPath,
231
+ windowsHide: true
232
+ // stdio: 'ignore'
233
+ });
234
+ if (stdout) {
235
+ console.log(stdout);
236
+ }
237
+ console.log(`${description}完成`);
238
+ }
239
+ catch (error) {
240
+ console.error(`执行命令失败: ${command}`);
241
+ throw error;
242
+ }
243
+ }
244
+ /**
245
+ * 检查依赖是否已安装
246
+ * @param packageName 包名
247
+ * @param isDev 是否是开发依赖
248
+ * @returns 是否已安装
249
+ */
250
+ async function checkDependency(projectRoot, packageName, isDev = false) {
251
+ try {
252
+ const packageJsonPath = path_1.default.join(projectRoot, 'package.json');
253
+ // 异步检查文件是否存在
254
+ try {
255
+ await promises_1.default.access(packageJsonPath);
256
+ }
257
+ catch {
258
+ return false;
259
+ }
260
+ // 异步读取并解析package.json
261
+ const packageJsonContent = await promises_1.default.readFile(packageJsonPath, 'utf8');
262
+ const packageJson = JSON.parse(packageJsonContent);
263
+ const dependencies = isDev ? packageJson.devDependencies : packageJson.dependencies;
264
+ return dependencies && typeof dependencies[packageName] === 'string';
265
+ }
266
+ catch (error) {
267
+ console.error(`检查${packageName}时出错:`, error);
268
+ return false;
269
+ }
270
+ }
271
+ /**
272
+ * 检查并搭建测试环境
273
+ * @param options 配置选项
274
+ * @param options.packageManager 包管理器 (npm, yarn, pnpm)
275
+ * @param options.devLanguage 开发语言 (typescript, javascript)
276
+ * @param options.testFramework 测试框架 (jest, mocha, vitest)
277
+ * @returns 是否成功搭建测试环境
278
+ */
279
+ async function setupTestEnvironment(projectRoot, packageManager, devLanguage, testFramework) {
280
+ // 验证参数
281
+ validateParameters(packageManager, devLanguage, testFramework);
282
+ const packageJsonPath = path_1.default.join(projectRoot, 'package.json');
283
+ // 异步检查并初始化package.json
284
+ try {
285
+ await promises_1.default.access(packageJsonPath);
286
+ }
287
+ catch {
288
+ console.log('未找到package.json,初始化项目...');
289
+ const initCommand = packageManager === 'yarn' ? 'yarn init -y' : `${packageManager} init -y`;
290
+ await executeCommand(projectRoot, initCommand, '初始化项目');
291
+ }
292
+ // 如果是TypeScript项目,检查并安装TypeScript
293
+ if (devLanguage === 'typescript') {
294
+ console.log('检查TypeScript是否安装...');
295
+ const hasTypeScript = await checkDependency(projectRoot, 'typescript', true);
296
+ if (!hasTypeScript) {
297
+ const installCmd = getInstallCommand(['typescript', '@types/node'], true, packageManager);
298
+ await executeCommand(projectRoot, installCmd, '安装TypeScript及类型定义');
299
+ // 异步检查并创建tsconfig.json
300
+ const tsconfigPath = path_1.default.join(projectRoot, 'tsconfig.json');
301
+ try {
302
+ await promises_1.default.access(tsconfigPath);
303
+ }
304
+ catch {
305
+ await executeCommand(projectRoot, 'npx tsc --init', '创建tsconfig.json');
306
+ }
307
+ }
308
+ }
309
+ // 检查并安装测试框架
310
+ console.log(`检查${testFramework}是否安装...`);
311
+ const hasTestFramework = await checkDependency(projectRoot, testFramework, true);
312
+ const hasTestTypes = devLanguage === 'typescript' ? await checkDependency(projectRoot, `@types/${testFramework}`, true) : true;
313
+ const packagesToInstall = [];
314
+ if (!hasTestFramework) {
315
+ packagesToInstall.push(testFramework);
316
+ }
317
+ if (devLanguage === 'typescript' && !hasTestTypes) {
318
+ packagesToInstall.push(`@types/${testFramework}`);
319
+ }
320
+ // 框架特定的依赖
321
+ if (testFramework === 'jest' && devLanguage === 'typescript' && !hasTestFramework) {
322
+ if (await checkDependency(projectRoot, 'ts-jest', true)) {
323
+ packagesToInstall.push('ts-jest');
324
+ }
325
+ if (await checkDependency(projectRoot, '@types/jest', true)) {
326
+ packagesToInstall.push('ts-jest', '@types/jest');
327
+ }
328
+ }
329
+ if (testFramework === 'mocha' && !hasTestFramework) {
330
+ if (await checkDependency(projectRoot, 'chai', true)) {
331
+ packagesToInstall.push('chai');
332
+ } // 通常与mocha一起使用的断言库
333
+ if (devLanguage === 'typescript') {
334
+ if (await checkDependency(projectRoot, '@types/chai', true)) {
335
+ packagesToInstall.push('@types/chai');
336
+ }
337
+ if (await checkDependency(projectRoot, 'ts-node', true)) {
338
+ packagesToInstall.push('ts-node');
339
+ }
340
+ }
341
+ }
342
+ if (packagesToInstall.length > 0) {
343
+ const installCmd = getInstallCommand(packagesToInstall, true, packageManager);
344
+ await executeCommand(projectRoot, installCmd, `安装${testFramework}及相关依赖`);
345
+ // 框架特定的配置
346
+ let exists = false;
347
+ try {
348
+ await promises_1.default.access(path_1.default.join(projectRoot, 'jest.config.js'));
349
+ exists = true;
350
+ }
351
+ catch { }
352
+ if (testFramework === 'jest' && !exists) {
353
+ await executeCommand(projectRoot, 'npx ts-jest config:init', '配置Jest TypeScript支持');
354
+ }
355
+ console.log('✅ 测试环境搭建完成!');
356
+ }
357
+ // 检查并添加test脚本
358
+ console.log('检查测试脚本是否配置...');
359
+ // 异步读取package.json
360
+ const packageJsonContent = await promises_1.default.readFile(packageJsonPath, 'utf8');
361
+ const packageJson = JSON.parse(packageJsonContent);
362
+ packageJson.scripts = packageJson.scripts || {};
363
+ if (!packageJson.scripts.test) {
364
+ console.log('添加测试脚本到package.json...');
365
+ let testCommand = testFramework;
366
+ if (testFramework === 'mocha' && devLanguage === 'typescript') {
367
+ testCommand = 'mocha --require ts-node/register "test/**/*.ts"';
368
+ }
369
+ packageJson.scripts.test = testCommand;
370
+ // 异步写入package.json
371
+ await promises_1.default.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));
372
+ console.log(`可以使用 ${packageManager} test 命令运行测试`);
373
+ }
374
+ return true;
375
+ }
376
+ //# sourceMappingURL=package.js.map