@zhin.js/cli 1.0.5 → 1.0.6

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.
@@ -1,893 +0,0 @@
1
- import { Command } from 'commander';
2
- import { logger } from '../utils/logger.js';
3
- import fs from 'fs-extra';
4
- import path from 'path';
5
- import inquirer from 'inquirer';
6
-
7
- interface InitOptions {
8
- name?: string;
9
- config?: 'json' | 'yaml' | 'toml' | 'ts' | 'js';
10
- packageManager?: 'npm' | 'yarn' | 'pnpm';
11
- runtime?: 'node' | 'bun';
12
- yes?: boolean;
13
- }
14
-
15
- export const initCommand = new Command('init')
16
- .description('初始化新的Zhin机器人项目')
17
- .argument('[project-name]', '项目名称')
18
- .option('-c, --config <format>', '配置文件格式 (json|yaml|toml|ts|js)', 'js')
19
- .option('-p, --package-manager <manager>', '包管理器 (npm|yarn|pnpm)', 'pnpm')
20
- .option('-r, --runtime <runtime>', '运行时 (node|bun)', 'node')
21
- .option('-y, --yes', '自动回答所有问题')
22
- .action(async (projectName: string, options: InitOptions) => {
23
- if(options.yes) {
24
- options.config = 'js';
25
- options.packageManager = 'pnpm';
26
- options.runtime = 'node';
27
- }
28
- try {
29
- let name = projectName;
30
-
31
- if (!name) {
32
- const {projectName:inputName} = await inquirer.prompt([
33
- {
34
- type: 'input',
35
- name: 'projectName',
36
- message: '请输入项目名称:',
37
- default: 'my-zhin-bot',
38
- validate: (input: string) => {
39
- if (!input.trim()) {
40
- return '项目名称不能为空';
41
- }
42
- if (!/^[a-zA-Z0-9-_]+$/.test(input)) {
43
- return '项目名称只能包含字母、数字、横线和下划线';
44
- }
45
- return true;
46
- }
47
- }
48
- ]);
49
- name = inputName;
50
- }
51
- if(!options.runtime) {
52
- const {runtime:inputRuntime} = await inquirer.prompt([
53
- {
54
- type: 'list',
55
- name: 'runtime',
56
- message: '选择运行时:',
57
- choices: [
58
- { name: 'Node.js (推荐)', value: 'node' },
59
- { name: 'Bun', value: 'bun' }
60
- ],
61
- default: options.runtime || 'node'
62
- },
63
- ])
64
- options.runtime=inputRuntime;
65
- }
66
- if(!options.packageManager) {
67
- const {packageManager:inputPackageManager} = await inquirer.prompt([
68
- {
69
- type: 'list',
70
- name: 'packageManager',
71
- message: '选择包管理器:',
72
- choices: [
73
- { name: 'pnpm (推荐)', value: 'pnpm' },
74
- { name: 'npm', value: 'npm' },
75
- { name: 'yarn', value: 'yarn' }
76
- ],
77
- default: options.packageManager || 'pnpm'
78
- }
79
- ])
80
- options.packageManager=inputPackageManager;
81
- }
82
- if(!options.config) {
83
- const {configFormat:inputConfigFormat} = await inquirer.prompt([
84
- {
85
- type: 'list',
86
- name: 'configFormat',
87
- message: '选择配置文件格式:',
88
- choices: [
89
- { name: 'JavaScript (推荐)', value: 'js' },
90
- { name: 'TypeScript', value: 'ts' },
91
- { name: 'YAML', value: 'yaml' },
92
- { name: 'JSON', value: 'json' },
93
- { name: 'TOML', value: 'toml' }
94
- ],
95
- default: options.config || 'js'
96
- }
97
- ]);
98
- options.config=inputConfigFormat;
99
- }
100
-
101
- const projectPath = path.resolve(process.cwd(), name);
102
- const realName=path.basename(projectPath)
103
- // 检查目录是否已存在
104
- if (fs.existsSync(projectPath)) {
105
- logger.error(`目录 ${realName} 已存在`);
106
- process.exit(1);
107
- }
108
-
109
- logger.info(`正在创建项目 ${realName}...`);
110
-
111
- // 创建项目目录结构
112
- await createProjectStructure(projectPath, realName, options);
113
-
114
- logger.success(`项目 ${realName} 创建成功!`);
115
- logger.log('');
116
- logger.log('🎉 下一步操作:');
117
- logger.log(` cd ${realName}`);
118
-
119
- const installCommand = getInstallCommand(options.packageManager!);
120
- logger.log(` ${installCommand} # 安装依赖`);
121
-
122
- logger.log(` npm run dev # 开发环境启动`);
123
- logger.log(` npm run build # 构建项目`);
124
- logger.log(` npm run start # 生产环境前台启动`);
125
- logger.log(` npm run daemon # 生产环境后台启动`);
126
- logger.log(` npm run stop # 停止机器人`);
127
-
128
- logger.log('');
129
- logger.log('📚 相关文档:');
130
- logger.log(' https://github.com/zhinjs/zhin - 项目主页');
131
- logger.log(' https://zhinjs.github.io - 官方文档');
132
-
133
- } catch (error) {
134
- logger.error(`创建项目失败: ${error}`);
135
- process.exit(1);
136
- }
137
- });
138
-
139
- function getInstallCommand(packageManager: string): string {
140
- switch (packageManager) {
141
- case 'yarn': return 'yarn install';
142
- case 'pnpm': return 'pnpm install';
143
- default: return 'npm install';
144
- }
145
- }
146
-
147
- async function createProjectStructure(projectPath: string, projectName: string, options: InitOptions) {
148
- // 创建目录结构
149
- await fs.ensureDir(projectPath);
150
- await fs.ensureDir(path.join(projectPath, 'src'));
151
- await fs.ensureDir(path.join(projectPath, 'src', 'plugins'));
152
- await fs.ensureDir(path.join(projectPath, 'dist'));
153
- await fs.ensureDir(path.join(projectPath, 'data'));
154
-
155
- // 检查是否在工作区中
156
- const isInWorkspace = await checkIfInWorkspace();
157
- const versionSuffix = isInWorkspace ? 'workspace:*' : 'latest';
158
-
159
- // 创建 package.json
160
- const packageJson = {
161
- name: projectName,
162
- private: true,
163
- version: '0.1.0',
164
- description: `${projectName} 机器人`,
165
- type: 'module',
166
- main: 'src/index.ts',
167
- scripts: {
168
- dev: 'zhin dev',
169
- start: options.runtime === 'bun' ? 'zhin start --bun' : 'zhin start',
170
- daemon: options.runtime === 'bun' ? 'zhin start --bun --daemon' : 'zhin start --daemon',
171
- build: 'zhin build',
172
- stop: 'zhin stop'
173
- },
174
- dependencies: {
175
- 'zhin.js': versionSuffix,
176
- '@zhin.js/adapter-process': versionSuffix,
177
- '@zhin.js/http': versionSuffix,
178
- '@zhin.js/client': versionSuffix,
179
- '@zhin.js/console': versionSuffix
180
- },
181
- devDependencies: {
182
- '@zhin.js/cli': versionSuffix,
183
- '@zhin.js/types': versionSuffix,
184
- "react":"latest",
185
- "react-dom":"latest",
186
- "@types/node": "latest",
187
- 'typescript': 'latest',
188
- ...(options.runtime === 'bun' ? {
189
- 'bun': 'latest'
190
- } : {
191
- 'tsx': 'latest'
192
- })
193
- },
194
- engines: {
195
- node: '>=18.0.0'
196
- }
197
- };
198
-
199
- await fs.writeJson(path.join(projectPath, 'package.json'), packageJson, { spaces: 2 });
200
-
201
- // 创建 tsconfig.json
202
- const tsConfig = {
203
- compilerOptions: {
204
- target: 'ES2022',
205
- module: 'ESNext',
206
- moduleResolution: 'bundler',
207
- outDir: './dist',
208
- strict: true,
209
- esModuleInterop: true,
210
- skipLibCheck: true,
211
- forceConsistentCasingInFileNames: true,
212
- resolveJsonModule: true,
213
- isolatedModules: true,
214
- allowSyntheticDefaultImports: true,
215
- experimentalDecorators: true,
216
- emitDecoratorMetadata: true,
217
- declaration: false,
218
- sourceMap: true,
219
- baseUrl: './src',
220
- jsx: 'react-jsx',
221
- jsxImportSource: 'zhin.js',
222
- types: [
223
- '@types/node',
224
- '@zhin.js/types',
225
- 'zhin.js'
226
- ]
227
- },
228
- include: ['src/**/*'],
229
- exclude: ['dist', 'node_modules']
230
- };
231
-
232
- await fs.writeJson(path.join(projectPath, 'tsconfig.json'), tsConfig, { spaces: 2 });
233
-
234
- // 创建配置文件
235
- await createConfigFile(projectPath, options.config!);
236
-
237
- // 创建主入口文件
238
- const indexContent = `import { createApp } from 'zhin.js';
239
-
240
- // 启动机器人
241
- async function main() {
242
- try {
243
- // 异步创建机器人实例 (自动从配置文件加载)
244
- const app = await createApp();
245
- await app.start();
246
-
247
- // 优雅退出处理
248
- const shutdown = async (signal: string) => {
249
- await app.stop();
250
- process.exit(0);
251
- };
252
-
253
- process.on('SIGINT', () => shutdown('SIGINT'));
254
- process.on('SIGTERM', () => shutdown('SIGTERM'));
255
- } catch (error) {
256
- // console.error 已替换为注释
257
- process.exit(1);
258
- }
259
- }
260
-
261
- // 启动应用
262
- main().catch(console.error);
263
- `;
264
-
265
- await fs.writeFile(path.join(projectPath, 'src', 'index.ts'), indexContent);
266
-
267
- // 创建示例插件
268
- const pluginContent = `import {
269
- useLogger,
270
- onMessage,
271
- addCommand,
272
- addMiddleware,
273
- MessageCommand,
274
- useContext,
275
- onDispose,
276
- } from 'zhin.js';
277
-
278
- const logger = useLogger();
279
-
280
- // 添加命令
281
- addCommand(new MessageCommand('hello')
282
- .action(async (message) => {
283
- logger.info('Hello command called by:', message.$sender.name);
284
- return '你好!欢迎使用 Zhin 机器人框架!';
285
- })
286
- );
287
-
288
- addCommand(new MessageCommand('status')
289
- .action(() => {
290
- const uptime = process.uptime() * 1000;
291
- const memory = process.memoryUsage();
292
- return [
293
- '🤖 机器人状态',
294
- \`⏱️ 运行时间: \${formatTime(uptime)}\`,
295
- \`📊 内存使用: \${(memory.rss / 1024 / 1024).toFixed(2)}MB\`,
296
- \`🔧 Node.js: \${process.version}\`
297
- ].join('\\n');
298
- })
299
- );
300
-
301
- // 添加中间件
302
- addMiddleware(async (message, next) => {
303
- logger.info(\`收到消息: \${message.$raw || 'undefined'}\`);
304
- await next();
305
- });
306
-
307
- // 监听消息
308
- onMessage(async (message) => {
309
- if (message.$raw && message.$raw.includes('帮助')) {
310
- await message.$reply('可用命令:hello, status\\n输入命令即可使用!');
311
- }
312
- });
313
-
314
- // 使用 process 上下文
315
- useContext('process', () => {
316
- logger.info('Process 适配器已就绪,可以在控制台输入消息进行测试');
317
- });
318
-
319
- // 插件销毁时的清理
320
- onDispose(() => {
321
- logger.info('测试插件已销毁');
322
- });
323
-
324
- // 工具函数
325
- function formatTime(ms: number): string {
326
- const seconds = Math.floor(ms / 1000);
327
- const minutes = Math.floor(seconds / 60);
328
- const hours = Math.floor(minutes / 60);
329
- const days = Math.floor(hours / 24);
330
-
331
- if (days > 0) return \`\${days}天 \${hours % 24}小时\`;
332
- if (hours > 0) return \`\${hours}小时 \${minutes % 60}分钟\`;
333
- if (minutes > 0) return \`\${minutes}分钟 \${seconds % 60}秒\`;
334
- return \`\${seconds}秒\`;
335
- }
336
-
337
- logger.info('测试插件已加载');
338
- `;
339
-
340
- await fs.writeFile(path.join(projectPath, 'src', 'plugins', 'test-plugin.ts'), pluginContent);
341
-
342
- // 创建 .gitignore
343
- const gitignoreContent = `# Dependencies
344
- node_modules/
345
-
346
- # Production builds
347
- dist/
348
-
349
- # Environment variables
350
- .env
351
- .env.local
352
- .env.development
353
- .env.production
354
-
355
- # IDE
356
- .vscode/
357
- .idea/
358
-
359
- # OS
360
- .DS_Store
361
- Thumbs.db
362
-
363
- # Logs
364
- *.log
365
- npm-debug.log*
366
- yarn-debug.log*
367
- yarn-error.log*
368
- pnpm-debug.log*
369
-
370
- # PID files
371
- .zhin.pid
372
- .zhin-dev.pid
373
-
374
- # Runtime data
375
- pids
376
- *.pid
377
- *.seed
378
- *.pid.lock
379
-
380
- # Coverage directory used by tools like istanbul
381
- coverage/
382
- *.lcov
383
-
384
- # nyc test coverage
385
- .nyc_output
386
-
387
- # Dependency directories
388
- jspm_packages/
389
-
390
- # Optional npm cache directory
391
- .npm
392
-
393
- # Optional eslint cache
394
- .eslintcache
395
-
396
- # Microbundle cache
397
- .rpt2_cache/
398
- .rts2_cache_cjs/
399
- .rts2_cache_es/
400
- .rts2_cache_umd/
401
-
402
- # Optional REPL history
403
- .node_repl_history
404
-
405
- # Output of 'npm pack'
406
- *.tgz
407
-
408
- # Yarn Integrity file
409
- .yarn-integrity
410
-
411
- # parcel-bundler cache (https://parceljs.org/)
412
- .cache
413
- .parcel-cache
414
-
415
- # Next.js build output
416
- .next
417
-
418
- # Nuxt.js build / generate output
419
- .nuxt
420
- dist
421
-
422
- # Gatsby files
423
- .cache/
424
- public
425
-
426
- # Storybook build outputs
427
- .out
428
- .storybook-out
429
-
430
- # Temporary folders
431
- tmp/
432
- temp/
433
- `;
434
-
435
- await fs.writeFile(path.join(projectPath, '.gitignore'), gitignoreContent);
436
-
437
- // 创建 README.md
438
- const readmeContent = `# ${projectName}
439
-
440
- 使用 Zhin 框架创建的机器人项目。
441
-
442
- ## 🚀 快速开始
443
-
444
- ### 安装依赖
445
-
446
- \`\`\`bash
447
- ${getInstallCommand(options.packageManager!)}
448
- \`\`\`
449
-
450
- ### 开发环境
451
-
452
- \`\`\`bash
453
- npm run dev
454
- \`\`\`
455
-
456
- ### 生产环境
457
-
458
- \`\`\`bash
459
- # 构建项目
460
- npm run build
461
-
462
- # 前台启动
463
- npm run start
464
-
465
- # 后台启动
466
- npm run daemon
467
- \`\`\`
468
-
469
- ### 停止机器人
470
-
471
- \`\`\`bash
472
- npm run stop
473
- \`\`\`
474
-
475
- ## 📁 项目结构
476
-
477
- \`\`\`
478
- ${projectName}/
479
- ├── src/
480
- │ ├── index.ts # 主入口文件
481
- │ └── plugins/ # 插件目录
482
- │ └── test-plugin.ts # 示例插件
483
- ├── dist/ # 构建输出目录
484
- ├── data/ # 数据目录
485
- ├── zhin.config.${options.config} # 配置文件
486
- ├── package.json # 项目配置
487
- └── tsconfig.json # TypeScript配置
488
- \`\`\`
489
-
490
- ## ⚙️ 配置
491
-
492
- ### 机器人配置
493
-
494
- 编辑 \`zhin.config.${options.config}\` 来配置你的机器人:
495
-
496
- ${getConfigExample(options.config!)}
497
-
498
- ## 🔌 插件开发
499
-
500
- 在 \`src/plugins/\` 目录下创建你的插件文件。参考 \`test-plugin.ts\` 了解插件开发方式。
501
-
502
- ### 插件示例
503
-
504
- \`\`\`typescript
505
- import { usePlugin, useLogger, addCommand } from '@zhin.js/core';
506
-
507
- const plugin = usePlugin();
508
- const logger = useLogger();
509
-
510
- // 添加命令
511
- addCommand('hello', (message, args) => {
512
- logger.info('Hello command called:', args);
513
- });
514
- \`\`\`
515
-
516
- ## 📚 相关链接
517
-
518
- - [Zhin 官方文档](https://zhinjs.github.io)
519
- - [插件开发指南](https://zhinjs.github.io/plugins)
520
- - [GitHub 仓库](https://github.com/zhinjs/zhin)
521
-
522
- ## 🤝 贡献
523
-
524
- 欢迎提交 Issue 和 Pull Request!
525
-
526
- ## 📄 许可证
527
-
528
- MIT License
529
- `;
530
-
531
- await fs.writeFile(path.join(projectPath, 'README.md'), readmeContent);
532
-
533
- // 创建 pnpm-workspace.yaml (如果使用 pnpm)
534
- if (options.packageManager === 'pnpm') {
535
- const workspaceContent = `packages:
536
- - '.'
537
- `;
538
- await fs.writeFile(path.join(projectPath, 'pnpm-workspace.yaml'), workspaceContent);
539
- }
540
-
541
- // 创建环境变量示例文件
542
- const envExampleContent = `# Zhin Bot 环境变量配置示例
543
- # 复制为 .env 文件并根据需要修改
544
-
545
- # 调试模式
546
- DEBUG=true
547
-
548
- # 插件目录 (可选)
549
- # PLUGIN_DIR=./src/plugins
550
-
551
- # KOOK 机器人配置 (如果使用 KOOK 适配器)
552
- # KOOK_TOKEN=your-kook-token
553
-
554
- # ICQQ 机器人配置 (如果使用 ICQQ 适配器)
555
- # ICQQ_SCAN_UIN=your-qq-number
556
- # ICQQ_LOGIN_UIN=your-qq-number
557
- # ICQQ_SIGN_ADDR=http://localhost:8080
558
-
559
- # OneBot 机器人配置 (如果使用 OneBot 适配器)
560
- # BOT_URL=ws://localhost:8080
561
- # ACCESS_TOKEN=your-access-token
562
- `;
563
- await fs.writeFile(path.join(projectPath, '.env.example'), envExampleContent);
564
- }
565
-
566
- async function createConfigFile(projectPath: string, format: string) {
567
- const configContent = getConfigContent(format);
568
- let fileName: string;
569
-
570
- switch (format) {
571
- case 'ts':
572
- fileName = 'zhin.config.ts';
573
- break;
574
- case 'js':
575
- fileName = 'zhin.config.ts';
576
- break;
577
- default:
578
- fileName = `zhin.config.${format}`;
579
- }
580
-
581
- await fs.writeFile(path.join(projectPath, fileName), configContent);
582
- }
583
-
584
- function getConfigContent(format: string): string {
585
- switch (format) {
586
- case 'json':
587
- return JSON.stringify({
588
- bots: [
589
- {
590
- name: `${process.pid}`,
591
- context: 'process'
592
- }
593
- ],
594
- plugin_dirs: [
595
- './src/plugins',
596
- 'node_modules',
597
- 'node_modules/@zhin.js'
598
- ],
599
- plugins: [
600
- 'adapter-process',
601
- 'http',
602
- 'console',
603
- 'test-plugin'
604
- ],
605
- debug: false
606
- }, null, 2);
607
-
608
- case 'yaml':
609
- return `# Zhin Bot 配置文件
610
-
611
- # 机器人配置
612
- bots:
613
- - name: \${process.pid}
614
- context: process
615
-
616
- # 插件目录
617
- plugin_dirs:
618
- - ./src/plugins
619
- - node_modules
620
- - node_modules/@zhin.js
621
- # 要加载的插件列表
622
- plugins:
623
- - adapter-process
624
- - http
625
- - console
626
- - test-plugin
627
-
628
- # 调试模式
629
- debug: false
630
- `;
631
-
632
- case 'toml':
633
- return `# Zhin Bot 配置文件
634
-
635
- # 机器人配置
636
- [[bots]]
637
- name = "\${process.pid}"
638
- context = "process"
639
-
640
- # 插件目录
641
- plugin_dirs = ["./src/plugins", "node_modules", "node_modules/@zhin.js"]
642
-
643
- # 要加载的插件列表
644
- plugins = ["adapter-process", "http", "console", "test-plugin"]
645
-
646
- # 调试模式
647
- debug = false
648
- `;
649
-
650
- case 'ts':
651
- return `import { defineConfig } from 'zhin.js';
652
-
653
- export default defineConfig(async (env) => {
654
- return {
655
- // 机器人配置
656
- bots: [
657
- {
658
- name: \`\${process.pid}\`,
659
- context: 'process'
660
- }
661
- ],
662
-
663
- // 插件目录
664
- plugin_dirs: [
665
- env.PLUGIN_DIR || './src/plugins',
666
- 'node_modules',
667
- 'node_modules/@zhin.js'
668
- ],
669
-
670
- // 要加载的插件列表
671
- plugins: [
672
- 'adapter-process',
673
- 'http',
674
- 'console',
675
- 'test-plugin'
676
- ],
677
-
678
- // 调试模式
679
- debug: env.DEBUG === 'true'
680
- };
681
- });
682
- `;
683
-
684
- case 'js':
685
- return `import { defineConfig } from 'zhin.js';
686
-
687
- export default defineConfig(async (env) => {
688
- return {
689
- // 机器人配置
690
- bots: [
691
- {
692
- name: \`\${process.pid}\`,
693
- context: 'process'
694
- }
695
- ],
696
-
697
- // 插件目录
698
- plugin_dirs: [
699
- env.PLUGIN_DIR || './src/plugins',
700
- 'node_modules',
701
- 'node_modules/@zhin.js'
702
- ],
703
-
704
- // 要加载的插件列表
705
- plugins: [
706
- 'adapter-process',
707
- 'http',
708
- 'console',
709
- 'test-plugin'
710
- ],
711
-
712
- // 调试模式
713
- debug: env.DEBUG === 'true'
714
- };
715
- });
716
- `;
717
-
718
- default:
719
- throw new Error(`不支持的配置格式: ${format}`);
720
- }
721
- }
722
-
723
- function getConfigExample(format: string): string {
724
- switch (format) {
725
- case 'json':
726
- return `\`\`\`json
727
- {
728
- "bots": [
729
- {
730
- "name": "\${process.pid}",
731
- "context": "process"
732
- }
733
- ],
734
- "plugin_dirs": [
735
- "./src/plugins",
736
- "node_modules",
737
- "node_modules/@zhin.js"
738
- ],
739
- "plugins": [
740
- "adapter-process",
741
- "http",
742
- "console",
743
- "test-plugin"
744
- ],
745
- "debug": false
746
- }
747
- \`\`\`
748
- `;
749
- case 'yaml':
750
- return `\`\`\`yaml
751
- # Zhin Bot 配置文件
752
-
753
- # 机器人配置
754
- bots:
755
- - name: \${process.pid}
756
- context: process
757
-
758
- # 插件目录
759
- plugin_dirs:
760
- - ./src/plugins
761
- - node_modules
762
-
763
- # 要加载的插件列表
764
- plugins:
765
- - adapter-process
766
- - http
767
- - console
768
- - test-plugin
769
-
770
- # 调试模式
771
- debug: false
772
- \`\`\`
773
- `;
774
- case 'toml':
775
- return `\`\`\`toml
776
- # Zhin Bot 配置文件
777
-
778
- # 机器人配置
779
- [[bots]]
780
- name = "\${process.pid}"
781
- context = "process"
782
-
783
- # 插件目录
784
- plugin_dirs = ["./src/plugins", "node_modules"]
785
-
786
- # 要加载的插件列表
787
- plugins = ["adapter-process", "http", "console", "test-plugin"]
788
-
789
- # 调试模式
790
- debug = false
791
- \`\`\`
792
- `;
793
- case 'ts':
794
- return `\`\`\`typescript
795
- import { defineConfig } from 'zhin.js';
796
-
797
- export default defineConfig(async (env) => {
798
- return {
799
- // 机器人配置
800
- bots: [
801
- {
802
- name: \`\${process.pid}\`,
803
- context: 'process'
804
- }
805
- ],
806
-
807
- // 插件目录
808
- plugin_dirs: [
809
- env.PLUGIN_DIR || './src/plugins',
810
- 'node_modules'
811
- ],
812
-
813
- // 要加载的插件列表
814
- plugins: [
815
- 'adapter-process',
816
- 'http',
817
- 'console',
818
- 'test-plugin'
819
- ],
820
-
821
- // 调试模式
822
- debug: env.DEBUG === 'true'
823
- };
824
- });
825
- \`\`\`
826
- `;
827
- case 'js':
828
- return `\`\`\`javascript
829
- import { defineConfig } from 'zhin.js';
830
-
831
- export default defineConfig(async (env) => {
832
- return {
833
- // 机器人配置
834
- bots: [
835
- {
836
- name: \`\${process.pid}\`,
837
- context: 'process'
838
- }
839
- ],
840
-
841
- // 插件目录
842
- plugin_dirs: [
843
- env.PLUGIN_DIR || './src/plugins',
844
- 'node_modules'
845
- ],
846
-
847
- // 要加载的插件列表
848
- plugins: [
849
- 'adapter-process',
850
- 'http',
851
- 'console',
852
- 'test-plugin'
853
- ],
854
-
855
- // 调试模式
856
- debug: env.DEBUG === 'true'
857
- };
858
- });
859
- \`\`\`
860
- `;
861
- default:
862
- throw new Error(`不支持的配置格式: ${format}`);
863
- }
864
- }
865
-
866
- async function checkIfInWorkspace(): Promise<boolean> {
867
- let currentDir = process.cwd();
868
-
869
- while (currentDir !== path.dirname(currentDir)) {
870
- // 检查 pnpm-workspace.yaml
871
- const pnpmWorkspacePath = path.join(currentDir, 'pnpm-workspace.yaml');
872
- if (fs.existsSync(pnpmWorkspacePath)) {
873
- return true;
874
- }
875
-
876
- // 检查 package.json 中的 workspaces 字段
877
- const packageJsonPath = path.join(currentDir, 'package.json');
878
- if (fs.existsSync(packageJsonPath)) {
879
- try {
880
- const packageJson = fs.readJsonSync(packageJsonPath);
881
- if (packageJson.workspaces) {
882
- return true;
883
- }
884
- } catch {
885
- // 忽略错误,继续向上查找
886
- }
887
- }
888
-
889
- currentDir = path.dirname(currentDir);
890
- }
891
-
892
- return false;
893
- }