@mycodemap/mycodemap 0.1.0 → 0.1.1

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.
Files changed (64) hide show
  1. package/CHANGELOG.md +86 -6
  2. package/README.md +172 -80
  3. package/dist/cli/commands/cycles.d.ts.map +1 -1
  4. package/dist/cli/commands/cycles.js +2 -0
  5. package/dist/cli/commands/cycles.js.map +1 -1
  6. package/dist/cli/commands/init.d.ts.map +1 -1
  7. package/dist/cli/commands/init.js +3 -1
  8. package/dist/cli/commands/init.js.map +1 -1
  9. package/dist/cli/commands/logs.d.ts +5 -0
  10. package/dist/cli/commands/logs.d.ts.map +1 -0
  11. package/dist/cli/commands/logs.js +189 -0
  12. package/dist/cli/commands/logs.js.map +1 -0
  13. package/dist/cli/commands/report.d.ts +12 -0
  14. package/dist/cli/commands/report.d.ts.map +1 -0
  15. package/dist/cli/commands/report.js +158 -0
  16. package/dist/cli/commands/report.js.map +1 -0
  17. package/dist/cli/commands/watch-foreground.d.ts.map +1 -1
  18. package/dist/cli/commands/watch-foreground.js +2 -0
  19. package/dist/cli/commands/watch-foreground.js.map +1 -1
  20. package/dist/cli/commands/watch.d.ts.map +1 -1
  21. package/dist/cli/commands/watch.js +2 -0
  22. package/dist/cli/commands/watch.js.map +1 -1
  23. package/dist/cli/first-run-guide.d.ts +23 -0
  24. package/dist/cli/first-run-guide.d.ts.map +1 -0
  25. package/dist/cli/first-run-guide.js +83 -0
  26. package/dist/cli/first-run-guide.js.map +1 -0
  27. package/dist/cli/index.js +63 -0
  28. package/dist/cli/index.js.map +1 -1
  29. package/dist/cli/platform-check.d.ts +21 -0
  30. package/dist/cli/platform-check.d.ts.map +1 -0
  31. package/dist/cli/platform-check.js +94 -0
  32. package/dist/cli/platform-check.js.map +1 -0
  33. package/dist/cli/tree-sitter-check.d.ts +35 -0
  34. package/dist/cli/tree-sitter-check.d.ts.map +1 -0
  35. package/dist/cli/tree-sitter-check.js +133 -0
  36. package/dist/cli/tree-sitter-check.js.map +1 -0
  37. package/dist/cli/utils/sanitize.d.ts +54 -0
  38. package/dist/cli/utils/sanitize.d.ts.map +1 -0
  39. package/dist/cli/utils/sanitize.js +131 -0
  40. package/dist/cli/utils/sanitize.js.map +1 -0
  41. package/docs/AI_ASSISTANT_SETUP.md +743 -0
  42. package/docs/CI_GATEWAY_DESIGN.md +784 -0
  43. package/docs/OMC_TEAM_DEBUG_REPORT.md +285 -0
  44. package/docs/PUBLISH_NPM_DESIGN_FINAL.md +485 -0
  45. package/docs/REFACTOR_ARCHITECTURE_OVERVIEW.md +552 -0
  46. package/docs/REFACTOR_CONFIDENCE_DESIGN.md +244 -0
  47. package/docs/REFACTOR_GIT_ANALYZER_DESIGN.md +785 -0
  48. package/docs/REFACTOR_ORCHESTRATOR_DESIGN.md +1065 -0
  49. package/docs/REFACTOR_REQUIREMENTS.md +970 -0
  50. package/docs/REFACTOR_RESULT_FUSION_DESIGN.md +315 -0
  51. package/docs/REFACTOR_TEST_LINKER_DESIGN.md +311 -0
  52. package/docs/SETUP_GUIDE.md +407 -0
  53. package/docs/archive/AI_INTEGRATION_GUIDE_ARCHIVED.md +385 -0
  54. package/docs/archive/PUBLISH_NPM_DESIGN_V1.md +1693 -0
  55. package/docs/archive/PUBLISH_NPM_DESIGN_V2.md +390 -0
  56. package/docs/archive/TASK_DESIGN_COVERAGE_REPORT.md +314 -0
  57. package/docs/plans/POST_TASK_PLAN.md +129 -0
  58. package/docs/plans/archive/2026-03-03-deps-path-extension-fix.md +186 -0
  59. package/examples/README.md +61 -0
  60. package/examples/claude/codemap-skill.md +94 -0
  61. package/examples/codex/codemap-agent.md +66 -0
  62. package/examples/copilot/copilot-instructions.md +24 -0
  63. package/examples/kimi/codemap-skill.md +92 -0
  64. package/package.json +5 -3
@@ -0,0 +1,1693 @@
1
+ # MyCodeMap NPM 发布设计方案
2
+
3
+ > 版本: 1.2
4
+ > 日期: 2026-03-04
5
+ > 方案: 完整体验版(方案 1,最终审查版)
6
+
7
+ ---
8
+
9
+ ## 1. 概述
10
+
11
+ ### 1.1 目标
12
+ 将 CodeMap 工具发布到 NPM,使用户可以通过 `npx mycodemap` 方式在其他项目中使用,同时建立完善的日志反馈机制便于问题排查。
13
+
14
+ ### 1.2 核心设计原则
15
+ 1. **开箱即用** - 预编译 binary 覆盖主流平台,无需用户编译
16
+ 2. **友好引导** - 首次使用提供交互式配置向导
17
+ 3. **问题可追踪** - 完整的日志系统 + 一键上报机制(敏感信息脱敏,用户确认后生成)
18
+ 4. **平台透明** - 乐观支持 macOS/Linux/Windows,如实提示风险
19
+ 5. **品牌一致** - 配置文件、CLI 命令、文档统一使用 `mycodemap`
20
+ 6. **按需检测** - tree-sitter 等依赖按需检测,避免不必要的启动开销
21
+ 7. **安全确认** - 涉及敏感数据的操作需用户明确确认
22
+
23
+ ### 1.3 平台支持策略
24
+
25
+ | 平台 | 架构 | 支持级别 | 说明 |
26
+ |------|------|----------|------|
27
+ | Linux | x64 | ⭐ 完全支持 | 主力开发和测试平台 |
28
+ | Linux | ARM64 | ⚠️ 实验性 | node-gyp-build 可能无法找到预编译 binary |
29
+ | macOS | x64/ARM64 | ⭐ 完全支持 | 有预编译 binary (darwin-x64, darwin-arm64) |
30
+ | Windows | x64 | ⭐ 完全支持 | 有预编译 binary (win32-x64) |
31
+ | Windows | ARM64 | ❌ 不支持 | 无预编译 binary,可能编译失败 |
32
+
33
+ **证据**:
34
+ ```bash
35
+ $ ls node_modules/tree-sitter/prebuilds/
36
+ darwin-arm64 darwin-x64 linux-x64 win32-x64
37
+
38
+ $ ls node_modules/tree-sitter-typescript/prebuilds/
39
+ # 类似结构
40
+ ```
41
+
42
+ **注意**: Linux ARM64 (如树莓派、Apple Silicon Linux VM) 和 Windows ARM64 没有预编译 binary,可能需要在安装时编译,这要求用户有 C++ 编译环境。
43
+
44
+ **注意**:非 Linux 平台首次使用时会显示友好提示:
45
+ ```
46
+ ⚠ 当前平台: darwin-arm64
47
+ 如遇问题请运行: mycodemap report
48
+ 反馈地址: https://github.com/yourname/mycodemap/issues
49
+ ```
50
+
51
+ ---
52
+
53
+ ## 2. 包配置改造
54
+
55
+ ### 2.1 tree-sitter 安装失败处理 ⭐ 关键补充
56
+
57
+ **问题**: tree-sitter 的 postinstall 脚本在安装阶段运行,如果预编译 binary 下载失败,npm install 会直接失败,用户无法看到我们的友好提示。
58
+
59
+ **解决方案**: 添加自定义 postinstall 脚本,捕获 tree-sitter 安装失败并提供友好提示。
60
+
61
+ **文件**: `scripts/postinstall.js`
62
+
63
+ ```javascript
64
+ #!/usr/bin/env node
65
+ // [META] since:2026-03 | owner:cli-team | stable:false
66
+ // [WHY] Provide friendly error messages when tree-sitter installation fails
67
+
68
+ const chalk = require('chalk');
69
+
70
+ function checkTreeSitter() {
71
+ try {
72
+ require('tree-sitter');
73
+ require('tree-sitter-typescript');
74
+ return true;
75
+ } catch (error) {
76
+ return false;
77
+ }
78
+ }
79
+
80
+ if (!checkTreeSitter()) {
81
+ console.log();
82
+ console.log(chalk.yellow('⚠'), 'Tree-sitter 依赖安装可能不完整');
83
+ console.log();
84
+ console.log('这可能是由于:');
85
+ console.log(' • 当前平台没有预编译的 binary');
86
+ console.log(' • 网络问题导致下载失败');
87
+ console.log();
88
+ console.log(chalk.cyan('你可以尝试:'));
89
+ console.log(' 1. 安装 C++ 编译环境后重新安装');
90
+ console.log(' 2. 使用 --build-from-source 标志强制编译');
91
+ console.log();
92
+ console.log('详细帮助: https://github.com/yourname/mycodemap/issues');
93
+ console.log();
94
+
95
+ // 不退出错误码,让安装继续完成
96
+ // 用户在使用时会在 CLI 中看到详细错误
97
+ }
98
+ ```
99
+
100
+ **package.json 更新**:
101
+ ```json
102
+ {
103
+ "scripts": {
104
+ "postinstall": "node scripts/postinstall.js"
105
+ }
106
+ }
107
+ ```
108
+
109
+ ### 2.2 LICENSE 文件 ⭐ 关键遗漏(已发现)
110
+
111
+ **问题**: 项目缺少 LICENSE 文件,但 package.json 声明了 MIT 许可。
112
+
113
+ **证据**:
114
+ ```bash
115
+ $ ls -la LICENSE
116
+ # 文件不存在
117
+
118
+ $ cat package.json | jq -r '.license'
119
+ MIT
120
+ ```
121
+
122
+ **解决方案**: 创建 MIT LICENSE 文件
123
+
124
+ **文件**: `LICENSE`
125
+ ```
126
+ MIT License
127
+
128
+ Copyright (c) 2026 [Your Name]
129
+
130
+ Permission is hereby granted, free of charge, to any person obtaining a copy
131
+ of this software and associated documentation files (the "Software"), to deal
132
+ in the Software without restriction, including without limitation the rights
133
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
134
+ copies of the Software, and to permit persons to whom the Software is
135
+ furnished to do so, subject to the following conditions:
136
+
137
+ The above copyright notice and this permission notice shall be included in all
138
+ copies or substantial portions of the Software.
139
+
140
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
141
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
142
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
143
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
144
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
145
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
146
+ SOFTWARE.
147
+ ```
148
+
149
+ ### 2.3 package.json 变更
150
+
151
+ **决策确认**:
152
+ - 版本号: `0.1.0`(早期版本标识)
153
+ - bin 命令: `mycodemap` + `cm` 别名
154
+ - 暂不实现版本更新检测(后续迭代添加)
155
+ - 发布前确保登录官方 npm registry
156
+
157
+ ```json
158
+ {
159
+ "name": "mycodemap",
160
+ "version": "0.1.0",
161
+ "description": "TypeScript 代码地图工具 - 为 AI 辅助开发提供结构化上下文",
162
+ "main": "dist/index.js",
163
+ "type": "module",
164
+ "bin": {
165
+ "mycodemap": "./dist/cli/index.js",
166
+ "cm": "./dist/cli/index.js"
167
+ },
168
+ "files": [
169
+ "dist/",
170
+ "LICENSE",
171
+ "README.md",
172
+ "mycodemap.config.schema.json",
173
+ "CHANGELOG.md"
174
+ ],
175
+ "scripts": {
176
+ "build": "tsc",
177
+ "dev": "tsc --watch",
178
+ "test": "vitest run",
179
+ "lint": "eslint src --ext .ts",
180
+ "typecheck": "tsc --noEmit",
181
+ "benchmark": "bash scripts/run-benchmark.sh",
182
+ "test:all": "npm run test && npm run benchmark",
183
+ "prepublishOnly": "npm run build && npm test",
184
+ "postversion": "npm run changelog && git add CHANGELOG.md && git commit -m \"docs: update changelog for v$(node -p \"require('./package.json').version\")\"",
185
+ "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"
186
+ },
187
+ "keywords": [
188
+ "typescript",
189
+ "codemap",
190
+ "code-analysis",
191
+ "ai",
192
+ "developer-tools",
193
+ "static-analysis",
194
+ "code-visualization"
195
+ ],
196
+ "author": "Your Name <your.email@example.com>",
197
+ "license": "MIT",
198
+ "repository": {
199
+ "type": "git",
200
+ "url": "https://github.com/yourname/mycodemap.git"
201
+ },
202
+ "bugs": {
203
+ "url": "https://github.com/yourname/mycodemap/issues"
204
+ },
205
+ "homepage": "https://github.com/yourname/mycodemap#readme",
206
+ "engines": {
207
+ "node": ">=18.0.0"
208
+ },
209
+ "os": ["darwin", "linux", "win32"],
210
+ "cpu": ["x64", "arm64"],
211
+ "publishConfig": {
212
+ "access": "public",
213
+ "registry": "https://registry.npmjs.org/"
214
+ }
215
+ }
216
+ ```
217
+
218
+ ### 2.2 关键变更说明
219
+
220
+ | 字段 | 变更 | 原因 |
221
+ |------|------|------|
222
+ | `name` | `codemap` → `mycodemap` | 原包名已被占用 |
223
+ | `bin` | 增加 `cm` 别名 | 提供更短更快的命令 |
224
+ | `files` | 新增 `CHANGELOG.md` | 用户需要了解版本变更 |
225
+ | `engines` | Node >= 18.0.0 | tree-sitter 需要现代 Node |
226
+ | `os` | [darwin, linux, win32] | 声明支持的操作系统 |
227
+ | `cpu` | [x64, arm64] | 声明支持的 CPU 架构 |
228
+ | `repository/bugs/homepage` | 新增 | NPM 页面信息完整 |
229
+ | `publishConfig.registry` | 显式指定 | 确保发布到官方 registry,避免镜像源问题 |
230
+
231
+ **⚠️ 重要: npm Registry 检查** ⭐ 新增
232
+
233
+ **问题**: 当前环境配置使用淘宝镜像源,无法直接发布到 npm。
234
+
235
+ **证据**:
236
+ ```bash
237
+ $ npm config get registry
238
+ https://registry.npmmirror.com # 非官方 registry
239
+
240
+ $ npm whoami
241
+ ENEEDAUTH # 未登录
242
+ ```
243
+
244
+ **发布前必须执行**:
245
+ ```bash
246
+ # 1. 临时切换到官方 registry
247
+ npm config set registry https://registry.npmjs.org/
248
+
249
+ # 2. 登录 npm(需要 OTP 验证)
250
+ npm login
251
+
252
+ # 3. 验证登录状态
253
+ npm whoami
254
+
255
+ # 4. 发布
256
+ npm publish --access public
257
+
258
+ # 5. 如需要,恢复镜像源
259
+ npm config set registry https://registry.npmmirror.com/
260
+ ```
261
+
262
+ 或者使用 nrm 管理 registry:
263
+ ```bash
264
+ npx nrm use npm
265
+ npm login
266
+ npm publish --access public
267
+ npx nrm use taobao
268
+ ```
269
+
270
+ ---
271
+
272
+ ## 3. .npmignore 设计
273
+
274
+ ### 3.1 完整配置
275
+
276
+ ```gitignore
277
+ # ============================================
278
+ # 源代码和开发文件
279
+ # ============================================
280
+ src/
281
+ tests/
282
+ refer/
283
+ scripts/
284
+ !scripts/postinstall.js
285
+ coverage/
286
+ .codemap/
287
+ .tasks/
288
+ .tmp/
289
+ .worktrees/
290
+ custom-output/
291
+ archive/
292
+ test-provider.ts
293
+
294
+ # ============================================
295
+ # 构建和配置
296
+ # ============================================
297
+ tsconfig.json
298
+ vitest.config.ts
299
+ vitest.config.js
300
+ vitest.config.d.ts
301
+ vitest.config.d.ts.map
302
+ vitest.benchmark.config.ts
303
+ .eslintrc*
304
+ .prettierrc*
305
+ .gitignore
306
+ .gitattributes
307
+ .github/
308
+ .githooks/
309
+
310
+ # ============================================
311
+ # 文档(选择性保留)
312
+ # ============================================
313
+ docs/
314
+ *.md
315
+ !README.md
316
+ !CHANGELOG.md
317
+
318
+ # ============================================
319
+ # 开发环境配置
320
+ # ============================================
321
+ .kimi/
322
+ .claude/
323
+ .agents/
324
+ .mcp.json
325
+ codemap.config.json
326
+ mycodemap.config.json
327
+ .vscode/
328
+ .idea/
329
+
330
+ # ============================================
331
+ # 其他
332
+ # ============================================
333
+ *.log
334
+ node_modules/
335
+ .prebuilds/
336
+
337
+ # ============================================
338
+ # 注意:保留 source map 文件
339
+ # dist/*.js.map 需要保留,便于用户调试
340
+ # ============================================
341
+ ```
342
+
343
+ **重要决策**: 保留 `dist/*.js.map` 文件
344
+ - 便于用户调试时定位到 TypeScript 源码
345
+ - 增加包大小约 30%,但显著提升调试体验
346
+
347
+ ### 3.2 打包内容分析
348
+
349
+ ```
350
+ mycodemap-0.1.0.tgz
351
+ ├── dist/ # 编译后的代码 (~500KB)
352
+ ├── LICENSE # MIT 许可证
353
+ ├── README.md # 项目说明
354
+ ├── CHANGELOG.md # 版本变更日志
355
+ ├── codemap.config.schema.json # 配置 JSON Schema
356
+ └── package.json # 包配置
357
+
358
+ 预计总大小: ~600KB (压缩后)
359
+ ```
360
+
361
+ ---
362
+
363
+ ## 4. mycodemap.config.schema.json 设计
364
+
365
+ **品牌一致性决策**: 配置文件名从 `codemap.config.json` 改为 `mycodemap.config.json`
366
+
367
+ ### 4.1 完整 Schema
368
+
369
+ **Schema 引用决策**: 使用相对路径 `./node_modules/mycodemap/mycodemap.config.schema.json`,无需部署到 CDN
370
+
371
+ ```json
372
+ {
373
+ "$schema": "http://json-schema.org/draft-07/schema#",
374
+ "$id": "https://mycodemap.dev/schema.json",
375
+ "title": "CodeMap Configuration",
376
+ "description": "Configuration schema for CodeMap - TypeScript code analysis tool",
377
+ "type": "object",
378
+ "additionalProperties": false,
379
+ "properties": {
380
+ "$schema": {
381
+ "type": "string",
382
+ "description": "JSON Schema reference"
383
+ },
384
+ "mode": {
385
+ "type": "string",
386
+ "enum": ["fast", "smart", "hybrid"],
387
+ "default": "hybrid",
388
+ "description": "Analysis mode: fast (regex), smart (AST), or hybrid (auto-select)"
389
+ },
390
+ "include": {
391
+ "type": "array",
392
+ "items": {
393
+ "type": "string"
394
+ },
395
+ "default": ["src/**/*.ts"],
396
+ "description": "Glob patterns for files to include in analysis"
397
+ },
398
+ "exclude": {
399
+ "type": "array",
400
+ "items": {
401
+ "type": "string"
402
+ },
403
+ "default": [
404
+ "node_modules/**",
405
+ "dist/**",
406
+ "build/**",
407
+ "*.test.ts",
408
+ "*.spec.ts"
409
+ ],
410
+ "description": "Glob patterns for files to exclude from analysis"
411
+ },
412
+ "output": {
413
+ "type": "string",
414
+ "default": ".codemap",
415
+ "description": "Output directory for generated code maps"
416
+ },
417
+ "plugins": {
418
+ "type": "array",
419
+ "items": {
420
+ "type": "string"
421
+ },
422
+ "description": "Plugin modules to load"
423
+ },
424
+ "ai": {
425
+ "type": "object",
426
+ "description": "AI context generation settings",
427
+ "properties": {
428
+ "enabled": {
429
+ "type": "boolean",
430
+ "default": true,
431
+ "description": "Enable AI context generation"
432
+ },
433
+ "model": {
434
+ "type": "string",
435
+ "default": "default",
436
+ "description": "AI model to use for descriptions"
437
+ }
438
+ }
439
+ },
440
+ "watch": {
441
+ "type": "object",
442
+ "description": "Watch mode settings",
443
+ "properties": {
444
+ "enabled": {
445
+ "type": "boolean",
446
+ "default": false,
447
+ "description": "Enable watch mode by default"
448
+ },
449
+ "debounce": {
450
+ "type": "number",
451
+ "default": 500,
452
+ "description": "Debounce interval in milliseconds"
453
+ }
454
+ }
455
+ },
456
+ "logging": {
457
+ "type": "object",
458
+ "description": "Logging configuration",
459
+ "properties": {
460
+ "level": {
461
+ "type": "string",
462
+ "enum": ["debug", "info", "warn", "error"],
463
+ "default": "info"
464
+ },
465
+ "enabled": {
466
+ "type": "boolean",
467
+ "default": true
468
+ }
469
+ }
470
+ }
471
+ },
472
+ "examples": [
473
+ {
474
+ "$schema": "https://codemap.dev/schema.json",
475
+ "mode": "hybrid",
476
+ "include": ["src/**/*.ts"],
477
+ "exclude": ["node_modules/**", "**/*.test.ts"],
478
+ "output": ".codemap"
479
+ }
480
+ ]
481
+ }
482
+ ```
483
+
484
+ ### 4.2 使用示例
485
+
486
+ ```json
487
+ {
488
+ "$schema": "./node_modules/mycodemap/mycodemap.config.schema.json",
489
+ "mode": "hybrid",
490
+ "include": ["src/**/*.ts", "lib/**/*.js"],
491
+ "exclude": [
492
+ "node_modules/**",
493
+ "dist/**",
494
+ "**/*.test.ts",
495
+ "**/*.spec.ts"
496
+ ],
497
+ "output": ".codemap",
498
+ "ai": {
499
+ "enabled": true,
500
+ "model": "default"
501
+ },
502
+ "watch": {
503
+ "enabled": false,
504
+ "debounce": 500
505
+ },
506
+ "logging": {
507
+ "level": "info",
508
+ "enabled": true
509
+ }
510
+ }
511
+ ```
512
+
513
+ ---
514
+
515
+ ## 5. 平台检测与引导系统
516
+
517
+ ### 5.1 平台检测模块
518
+
519
+ **文件**: `src/cli/platform-check.ts`
520
+
521
+ ```typescript
522
+ // [META] since:2026-03 | owner:cli-team | stable:false
523
+ // [WHY] Detect platform compatibility and provide user guidance on first run
524
+
525
+ import os from 'node:os';
526
+ import chalk from 'chalk';
527
+
528
+ export interface PlatformInfo {
529
+ platform: NodeJS.Platform;
530
+ arch: string;
531
+ nodeVersion: string;
532
+ isSupported: boolean;
533
+ supportLevel: 'full' | 'experimental' | 'unsupported';
534
+ }
535
+
536
+ const FULLY_SUPPORTED_PLATFORMS: Array<{ platform: NodeJS.Platform; arch: string }> = [
537
+ { platform: 'linux', arch: 'x64' },
538
+ { platform: 'darwin', arch: 'x64' },
539
+ { platform: 'darwin', arch: 'arm64' },
540
+ { platform: 'win32', arch: 'x64' },
541
+ ];
542
+
543
+ export function detectPlatform(): PlatformInfo {
544
+ const platform = os.platform();
545
+ const arch = os.arch();
546
+ const nodeVersion = process.version;
547
+
548
+ const isFullySupported = FULLY_SUPPORTED_PLATFORMS.some(
549
+ p => p.platform === platform && p.arch === arch
550
+ );
551
+
552
+ let supportLevel: PlatformInfo['supportLevel'] = 'unsupported';
553
+ if (isFullySupported) {
554
+ supportLevel = 'full';
555
+ } else if (['linux', 'darwin', 'win32'].includes(platform)) {
556
+ supportLevel = 'experimental';
557
+ }
558
+
559
+ return {
560
+ platform,
561
+ arch,
562
+ nodeVersion,
563
+ isSupported: supportLevel !== 'unsupported',
564
+ supportLevel,
565
+ };
566
+ }
567
+
568
+ export function printPlatformNotice(info: PlatformInfo): void {
569
+ if (info.supportLevel === 'full') {
570
+ if (info.platform === 'linux') {
571
+ console.log(chalk.green('✓'), '已针对 Linux 优化');
572
+ }
573
+ // macOS 和 Windows 完全支持,不显示额外提示
574
+ return;
575
+ }
576
+
577
+ if (info.supportLevel === 'experimental') {
578
+ console.log(
579
+ chalk.yellow('⚠'),
580
+ `当前平台: ${info.platform}-${info.arch}`
581
+ );
582
+ console.log(
583
+ chalk.gray(' '),
584
+ '此平台为实验性支持,如遇问题请运行:',
585
+ chalk.cyan('mycodemap report')
586
+ );
587
+ console.log(
588
+ chalk.gray(' '),
589
+ '反馈地址:',
590
+ chalk.underline('https://github.com/yourname/mycodemap/issues')
591
+ );
592
+ console.log();
593
+ return;
594
+ }
595
+
596
+ // unsupported
597
+ console.log(
598
+ chalk.red('✗'),
599
+ `不支持的的平台: ${info.platform}-${info.arch}`
600
+ );
601
+ console.log(
602
+ chalk.gray(' '),
603
+ '当前支持的平台: Linux/macOS/Windows (x64/arm64)'
604
+ );
605
+ }
606
+
607
+ export function checkNodeVersion(): boolean {
608
+ const version = process.version;
609
+ const major = parseInt(version.slice(1).split('.')[0], 10);
610
+
611
+ if (major < 18) {
612
+ console.log(chalk.red('✗'), `Node.js 版本过低: ${version}`);
613
+ console.log(chalk.gray(' '), '请升级至 Node.js 18.0.0 或更高版本');
614
+ return false;
615
+ }
616
+
617
+ return true;
618
+ }
619
+ ```
620
+
621
+ ### 5.2 CLI 入口集成
622
+
623
+ **修改**: `src/cli/index.ts`
624
+
625
+ ```typescript
626
+ import { detectPlatform, printPlatformNotice, checkNodeVersion } from './platform-check.js';
627
+
628
+ // CLI 启动时执行检查
629
+ const platform = detectPlatform();
630
+ printPlatformNotice(platform);
631
+
632
+ if (!checkNodeVersion()) {
633
+ process.exit(1);
634
+ }
635
+ ```
636
+
637
+ ### 5.3 tree-sitter 兼容性检测
638
+
639
+ **降级方案决策**: 当 tree-sitter 无法加载时,**阻止使用并给出清晰错误提示**,而非静默降级。
640
+
641
+ **性能优化决策**: tree-sitter 检测**按需进行**,非每次 CLI 启动都检测。
642
+ - `init`, `query`, `report` 等命令不需要 tree-sitter,跳过检测
643
+ - `generate`, `watch`, `complexity` 等需要 AST 解析的命令才检测
644
+
645
+ **文件**: `src/cli/tree-sitter-check.ts`
646
+
647
+ ```typescript
648
+ // [META] since:2026-03 | owner:cli-team | stable:false
649
+ // [WHY] Check tree-sitter availability and provide clear error messages
650
+
651
+ import chalk from 'chalk';
652
+
653
+ export function checkTreeSitter(): boolean {
654
+ try {
655
+ // 尝试动态导入 tree-sitter
656
+ const Parser = require('tree-sitter');
657
+ const TypeScript = require('tree-sitter-typescript');
658
+
659
+ // 验证是否能正常实例化
660
+ const parser = new Parser();
661
+ parser.setLanguage(TypeScript.typescript);
662
+
663
+ return true;
664
+ } catch (error) {
665
+ return false;
666
+ }
667
+ }
668
+
669
+ export function printTreeSitterError(): void {
670
+ console.log();
671
+ console.log(chalk.red('✗'), 'Tree-sitter 加载失败');
672
+ console.log();
673
+ console.log(chalk.yellow('可能的原因:'));
674
+ console.log(' 1. 当前平台没有预编译的 binary');
675
+ console.log(' 2. 缺少 C++ 编译环境(如需要源码编译)');
676
+ console.log(' 3. 网络问题导致 binary 下载失败');
677
+ console.log();
678
+ console.log(chalk.yellow('解决方案:'));
679
+ console.log(' • Linux (Ubuntu): 确保安装 build-essential');
680
+ console.log(' ', chalk.gray('sudo apt-get install build-essential'));
681
+ console.log(' • macOS: 安装 Xcode Command Line Tools');
682
+ console.log(' ', chalk.gray('xcode-select --install'));
683
+ console.log(' • Windows: 安装 Visual Studio Build Tools');
684
+ console.log();
685
+ console.log(' 如问题持续,请运行', chalk.cyan('mycodemap report'), '并提交 Issue:');
686
+ console.log(' ', chalk.underline('https://github.com/yourname/mycodemap/issues'));
687
+ console.log();
688
+ }
689
+ ```
690
+
691
+ ### 5.4 首次使用引导
692
+
693
+ **文件**: `src/cli/first-run-guide.ts`
694
+
695
+ ```typescript
696
+ // [META] since:2026-03 | owner:cli-team | stable:false
697
+ // [WHY] Guide new users through initial setup and configuration
698
+
699
+ import fs from 'node:fs';
700
+ import path from 'node:path';
701
+ import chalk from 'chalk';
702
+ import { createRequire } from 'node:module';
703
+
704
+ const require = createRequire(import.meta.url);
705
+
706
+ export function isFirstRun(cwd: string): boolean {
707
+ const configPath = path.join(cwd, 'mycodemap.config.json');
708
+ const hasConfig = fs.existsSync(configPath);
709
+
710
+ const markerPath = path.join(cwd, '.codemap', '.first-run');
711
+ const hasMarker = fs.existsSync(markerPath);
712
+
713
+ return !hasConfig && !hasMarker;
714
+ }
715
+
716
+ export function markFirstRunComplete(cwd: string): void {
717
+ const markerDir = path.join(cwd, '.codemap');
718
+ const markerPath = path.join(markerDir, '.first-run');
719
+
720
+ try {
721
+ fs.mkdirSync(markerDir, { recursive: true });
722
+ fs.writeFileSync(markerPath, new Date().toISOString());
723
+ } catch {
724
+ // ignore
725
+ }
726
+ }
727
+
728
+ export function printWelcomeMessage(): void {
729
+ const pkg = require('../../package.json');
730
+
731
+ console.log();
732
+ console.log(chalk.bold.cyan(`🗺️ Welcome to MyCodeMap v${pkg.version}!`));
733
+ console.log();
734
+ console.log('快速开始:');
735
+ console.log(chalk.gray(' 1.'), '初始化配置:', chalk.cyan('mycodemap init'));
736
+ console.log(chalk.gray(' 2.'), '生成代码地图:', chalk.cyan('mycodemap generate'));
737
+ console.log(chalk.gray(' 3.'), '查看帮助:', chalk.cyan('mycodemap --help'));
738
+ console.log();
739
+ console.log('常用命令:');
740
+ console.log(chalk.gray(' •'), chalk.cyan('mycodemap query -s <symbol>'), ' 查询符号');
741
+ console.log(chalk.gray(' •'), chalk.cyan('mycodemap deps -m <module>'), ' 分析依赖');
742
+ console.log(chalk.gray(' •'), chalk.cyan('mycodemap complexity'), ' 复杂度分析');
743
+ console.log();
744
+ console.log(chalk.gray('需要更多帮助? 访问:'), chalk.underline(pkg.homepage));
745
+ console.log();
746
+ }
747
+ ```
748
+
749
+ ---
750
+
751
+ ## 6. Report 命令设计
752
+
753
+ ### 6.1 功能说明
754
+
755
+ `mycodemap report` 命令用于打包运行环境信息,方便用户提交 Issue 时提供完整的调试信息。
756
+
757
+ **隐私保护决策**: 报告中的敏感信息必须进行脱敏处理。
758
+
759
+ ### 6.2 采集信息清单
760
+
761
+ | 类别 | 内容 | 脱敏处理 |
762
+ |------|------|----------|
763
+ | 日志文件 | 最近 3 天的日志 | 路径中的用户名替换为 `<user>` |
764
+ | 系统信息 | Node 版本、平台、CPU、内存 | 无需脱敏 |
765
+ | 包信息 | mycodemap 版本、依赖版本 | 无需脱敏 |
766
+ | 配置信息 | mycodemap.config.json | 路径脱敏 |
767
+ | 运行时信息 | 环境变量(CODEMAP_*) | 敏感值(API keys 等)替换为 `<redacted>` |
768
+ | 树形信息 | 项目结构概览 | 路径脱敏,仅保留相对结构 |
769
+
770
+ ### 6.3 脱敏实现
771
+
772
+ **文件**: `src/cli/utils/sanitize.ts`
773
+
774
+ ```typescript
775
+ // [META] since:2026-03 | owner:cli-team | stable:false
776
+ // [WHY] Sanitize sensitive information from logs and paths
777
+
778
+ import os from 'node:os';
779
+ import path from 'node:path';
780
+
781
+ export function sanitizePath(input: string): string {
782
+ const homeDir = os.homedir();
783
+ const username = path.basename(homeDir);
784
+
785
+ return input
786
+ .replace(new RegExp(homeDir.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), '~')
787
+ .replace(new RegExp(username, 'g'), '<user>');
788
+ }
789
+
790
+ export function sanitizeEnvValue(key: string, value: string): string {
791
+ // 敏感 key 模式
792
+ const sensitivePatterns = [
793
+ /key/i,
794
+ /token/i,
795
+ /secret/i,
796
+ /password/i,
797
+ /auth/i,
798
+ /credential/i,
799
+ /private/i,
800
+ ];
801
+
802
+ const isSensitive = sensitivePatterns.some(p => p.test(key));
803
+ return isSensitive ? '<redacted>' : value;
804
+ }
805
+
806
+ export function sanitizeLogContent(content: string): string {
807
+ return content
808
+ .split('\n')
809
+ .map(line => {
810
+ // 脱敏路径
811
+ line = sanitizePath(line);
812
+
813
+ // 脱敏环境变量值(格式: KEY=value)
814
+ line = line.replace(/(\w+)=([^\s]+)/g, (match, key, value) => {
815
+ return `${key}=${sanitizeEnvValue(key, value)}`;
816
+ });
817
+
818
+ return line;
819
+ })
820
+ .join('\n');
821
+ }
822
+ ```
823
+
824
+ ### 6.3 实现代码
825
+
826
+ **文件**: `src/cli/commands/report.ts`
827
+
828
+ ```typescript
829
+ // [META] since:2026-03 | owner:cli-team | stable:false
830
+ // [WHY] Collect runtime information for bug reporting and troubleshooting
831
+
832
+ import fs from 'node:fs';
833
+ import path from 'node:path';
834
+ import os from 'node:os';
835
+ import { createRequire } from 'node:module';
836
+ import chalk from 'chalk';
837
+ import { Command } from 'commander';
838
+
839
+ const require = createRequire(import.meta.url);
840
+
841
+ interface ReportData {
842
+ timestamp: string;
843
+ mycodemapVersion: string;
844
+ system: {
845
+ platform: string;
846
+ arch: string;
847
+ nodeVersion: string;
848
+ cpus: number;
849
+ totalMemory: string;
850
+ freeMemory: string;
851
+ };
852
+ environment: Record<string, string | undefined>;
853
+ config: unknown | null;
854
+ logs: string[];
855
+ projectStructure: string;
856
+ }
857
+
858
+ function collectSystemInfo(): ReportData['system'] {
859
+ return {
860
+ platform: os.platform(),
861
+ arch: os.arch(),
862
+ nodeVersion: process.version,
863
+ cpus: os.cpus().length,
864
+ totalMemory: `${Math.round(os.totalmem() / 1024 / 1024)}MB`,
865
+ freeMemory: `${Math.round(os.freemem() / 1024 / 1024)}MB`,
866
+ };
867
+ }
868
+
869
+ function collectEnvironment(): ReportData['environment'] {
870
+ const env: ReportData['environment'] = {};
871
+ for (const [key, value] of Object.entries(process.env)) {
872
+ if (key.startsWith('CODEMAP_')) {
873
+ env[key] = value;
874
+ }
875
+ }
876
+ return env;
877
+ }
878
+
879
+ function collectConfig(cwd: string): unknown | null {
880
+ const configPath = path.join(cwd, 'mycodemap.config.json');
881
+ if (!fs.existsSync(configPath)) {
882
+ return null;
883
+ }
884
+ try {
885
+ const content = fs.readFileSync(configPath, 'utf-8');
886
+ return JSON.parse(content);
887
+ } catch {
888
+ return { error: 'Failed to parse config' };
889
+ }
890
+ }
891
+
892
+ function collectRecentLogs(logDir: string, days: number): string[] {
893
+ if (!fs.existsSync(logDir)) {
894
+ return [];
895
+ }
896
+
897
+ const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
898
+ const logs: string[] = [];
899
+
900
+ for (const file of fs.readdirSync(logDir)) {
901
+ if (!file.startsWith('codemap-') || !file.endsWith('.log')) {
902
+ continue;
903
+ }
904
+
905
+ const filePath = path.join(logDir, file);
906
+ const stat = fs.statSync(filePath);
907
+
908
+ if (stat.mtimeMs < cutoff) {
909
+ continue;
910
+ }
911
+
912
+ try {
913
+ const content = fs.readFileSync(filePath, 'utf-8');
914
+ // 仅保留最近 1000 行,避免过大
915
+ const lines = content.split('\n').slice(-1000);
916
+ logs.push(`=== ${file} ===\n${lines.join('\n')}`);
917
+ } catch {
918
+ // ignore
919
+ }
920
+ }
921
+
922
+ return logs;
923
+ }
924
+
925
+ function collectProjectStructure(cwd: string, maxDepth = 3): string {
926
+ const output: string[] = [];
927
+
928
+ function traverse(dir: string, depth: number, prefix: string): void {
929
+ if (depth > maxDepth) {
930
+ output.push(`${prefix}...`);
931
+ return;
932
+ }
933
+
934
+ const items: string[] = [];
935
+ try {
936
+ for (const item of fs.readdirSync(dir)) {
937
+ // 跳过隐藏文件和常见不需要的目录
938
+ if (item.startsWith('.') ||
939
+ ['node_modules', 'dist', 'build', 'coverage'].includes(item)) {
940
+ continue;
941
+ }
942
+ items.push(item);
943
+ }
944
+ } catch {
945
+ return;
946
+ }
947
+
948
+ items.sort();
949
+
950
+ for (let i = 0; i < items.length; i++) {
951
+ const item = items[i];
952
+ const isLast = i === items.length - 1;
953
+ const itemPath = path.join(dir, item);
954
+ const stat = fs.statSync(itemPath);
955
+
956
+ const line = prefix + (isLast ? '└── ' : '├── ') + item;
957
+ output.push(line);
958
+
959
+ if (stat.isDirectory()) {
960
+ const newPrefix = prefix + (isLast ? ' ' : '│ ');
961
+ traverse(itemPath, depth + 1, newPrefix);
962
+ }
963
+ }
964
+ }
965
+
966
+ output.push(path.basename(cwd) + '/');
967
+ traverse(cwd, 1, '');
968
+
969
+ return output.join('\n');
970
+ }
971
+
972
+ export function generateReport(cwd: string, logDir: string): ReportData {
973
+ const pkg = require('../../../package.json');
974
+
975
+ return {
976
+ timestamp: new Date().toISOString(),
977
+ mycodemapVersion: pkg.version,
978
+ system: collectSystemInfo(),
979
+ environment: collectEnvironment(),
980
+ config: collectConfig(cwd),
981
+ logs: collectRecentLogs(logDir, 3),
982
+ projectStructure: collectProjectStructure(cwd),
983
+ };
984
+ }
985
+
986
+ export function writeReportFile(report: ReportData, outputDir: string): string {
987
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
988
+ const fileName = `mycodemap-report-${timestamp}.json`;
989
+ const filePath = path.join(outputDir, fileName);
990
+
991
+ fs.mkdirSync(outputDir, { recursive: true });
992
+ fs.writeFileSync(filePath, JSON.stringify(report, null, 2), 'utf-8');
993
+
994
+ return filePath;
995
+ }
996
+
997
+ // 报告大小限制: 5MB
998
+ const MAX_REPORT_SIZE_MB = 5;
999
+
1000
+ function getReportSize(report: ReportData): number {
1001
+ const json = JSON.stringify(report, null, 2);
1002
+ return Buffer.byteLength(json, 'utf-8') / 1024 / 1024;
1003
+ }
1004
+
1005
+ function previewReport(report: ReportData): string {
1006
+ const lines: string[] = [];
1007
+ lines.push(chalk.bold('报告预览:'));
1008
+ lines.push(` 时间戳: ${report.timestamp}`);
1009
+ lines.push(` 版本: ${report.mycodemapVersion}`);
1010
+ lines.push(` 平台: ${report.system.platform}-${report.system.arch}`);
1011
+ lines.push(` 日志条数: ${report.logs.length}`);
1012
+ lines.push(` 配置: ${report.config ? '已包含' : '无'}`);
1013
+ return lines.join('\n');
1014
+
1015
+ export function createReportCommand(): Command {
1016
+ return new Command('report')
1017
+ .description('Generate a diagnostic report for bug reporting')
1018
+ .option('-o, --output <dir>', 'Output directory', '.codemap')
1019
+ .option('--days <n>', 'Number of days of logs to include', '3')
1020
+ .option('-y, --yes', 'Skip confirmation', false)
1021
+ .action(async (options) => {
1022
+ const cwd = process.cwd();
1023
+ const logDir = path.join(cwd, '.codemap', 'logs');
1024
+ const outputDir = path.resolve(cwd, options.output);
1025
+
1026
+ // 边界情况 1: 检查日志目录是否存在
1027
+ if (!fs.existsSync(logDir)) {
1028
+ console.log(chalk.yellow('⚠'), '没有找到日志目录');
1029
+ console.log(chalk.gray(' '), logDir);
1030
+ console.log();
1031
+ console.log('请先运行其他 mycodemap 命令生成日志,再生成报告。');
1032
+ return;
1033
+ }
1034
+
1035
+ // 边界情况 2: 检查是否有日志文件
1036
+ const logs = collectRecentLogs(logDir, parseInt(options.days, 10));
1037
+ if (logs.length === 0) {
1038
+ console.log(chalk.yellow('⚠'), '最近几天没有日志文件');
1039
+ console.log();
1040
+ console.log('请先运行其他 mycodemap 命令生成日志,再生成报告。');
1041
+ return;
1042
+ }
1043
+
1044
+ console.log(chalk.blue('📋'), '正在生成诊断报告...');
1045
+
1046
+ const report = generateReport(cwd, logDir);
1047
+
1048
+ // 边界情况 3: 检查报告大小
1049
+ const sizeMB = getReportSize(report);
1050
+ if (sizeMB > MAX_REPORT_SIZE_MB) {
1051
+ console.log(chalk.yellow('⚠'), `报告过大 (${sizeMB.toFixed(2)}MB),建议清理日志后重试`);
1052
+ console.log(chalk.gray(' '), '日志目录:', logDir);
1053
+ return;
1054
+ }
1055
+
1056
+ // 显示预览并请求确认
1057
+ if (!options.yes) {
1058
+ console.log();
1059
+ console.log(previewReport(report));
1060
+ console.log();
1061
+ console.log(chalk.gray('报告将包含以上信息(敏感信息已脱敏)'));
1062
+ console.log();
1063
+
1064
+ // 简单的确认提示
1065
+ process.stdout.write('确认生成报告? [Y/n] ');
1066
+ const response = await new Promise<string>((resolve) => {
1067
+ process.stdin.once('data', (data) => {
1068
+ resolve(data.toString().trim().toLowerCase());
1069
+ });
1070
+ });
1071
+
1072
+ if (response !== '' && response !== 'y' && response !== 'yes') {
1073
+ console.log('已取消');
1074
+ return;
1075
+ }
1076
+ }
1077
+
1078
+ const filePath = writeReportFile(report, outputDir);
1079
+
1080
+ console.log();
1081
+ console.log(chalk.green('✓'), '报告已生成:');
1082
+ console.log(chalk.gray(' '), filePath);
1083
+ console.log();
1084
+ console.log('请将此文件附加到 Issue 中:');
1085
+ console.log(chalk.cyan(' '), chalk.underline('https://github.com/yourname/mycodemap/issues'));
1086
+ console.log();
1087
+ console.log(chalk.gray('说明: 报告包含系统信息和日志,不包含源代码。敏感信息已脱敏。'));
1088
+ });
1089
+ }
1090
+ ```
1091
+
1092
+ ### 6.4 报告示例
1093
+
1094
+ ```json
1095
+ {
1096
+ "timestamp": "2026-03-04T13:30:00.000Z",
1097
+ "mycodemapVersion": "0.1.0",
1098
+ "system": {
1099
+ "platform": "linux",
1100
+ "arch": "x64",
1101
+ "nodeVersion": "v20.11.0",
1102
+ "cpus": 8,
1103
+ "totalMemory": "16384MB",
1104
+ "freeMemory": "8192MB"
1105
+ },
1106
+ "environment": {
1107
+ "CODEMAP_RUNTIME_LOG_ENABLED": "true",
1108
+ "CODEMAP_RUNTIME_LOG_RETENTION_DAYS": "14"
1109
+ },
1110
+ "config": {
1111
+ "mode": "hybrid",
1112
+ "include": ["src/**/*.ts"]
1113
+ },
1114
+ "logs": ["=== codemap-2026-03-04.log ===\n[...]"],
1115
+ "projectStructure": "my-project/\n├── src/\n│ ├── index.ts\n│ └── utils/\n└── package.json"
1116
+ }
1117
+ ```
1118
+
1119
+ ---
1120
+
1121
+ ## 7. CHANGELOG.md 格式
1122
+
1123
+ ### 7.1 文件头模板
1124
+
1125
+ ```markdown
1126
+ # Changelog
1127
+
1128
+ All notable changes to this project will be documented in this file.
1129
+
1130
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
1131
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
1132
+
1133
+ ## [Unreleased]
1134
+
1135
+ ### Added
1136
+ - New features
1137
+
1138
+ ### Changed
1139
+ - Changes in existing functionality
1140
+
1141
+ ### Deprecated
1142
+ - Soon-to-be removed features
1143
+
1144
+ ### Removed
1145
+ - Now removed features
1146
+
1147
+ ### Fixed
1148
+ - Bug fixes
1149
+
1150
+ ### Security
1151
+ - Security improvements
1152
+ ```
1153
+
1154
+ ### 7.2 版本条目示例
1155
+
1156
+ ```markdown
1157
+ ## [0.1.0] - 2026-03-04
1158
+
1159
+ ### Added
1160
+ - Initial release of MyCodeMap
1161
+ - Support for TypeScript/JavaScript code analysis
1162
+ - Dual parsing modes: fast (regex) and smart (AST)
1163
+ - CLI commands: init, generate, query, deps, complexity, cycles, watch, report
1164
+ - Platform support: Linux, macOS, Windows (x64/arm64)
1165
+ - Runtime logging system for troubleshooting
1166
+ - Diagnostic report generation (`mycodemap report`)
1167
+ - JSON Schema for configuration validation
1168
+ - Pre-compiled tree-sitter binaries for faster installation
1169
+
1170
+ ### Notes
1171
+ - Optimized for Linux (Ubuntu) environments
1172
+ - Experimental support for other platforms
1173
+ - Requires Node.js >= 18.0.0
1174
+ ```
1175
+
1176
+ ### 7.3 npm script 集成
1177
+
1178
+ ```json
1179
+ {
1180
+ "scripts": {
1181
+ "postversion": "npm run changelog && git add CHANGELOG.md && git commit -m \"docs: update changelog for v$(node -p \"require('./package.json').version\")\"",
1182
+ "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"
1183
+ }
1184
+ }
1185
+ ```
1186
+
1187
+ ---
1188
+
1189
+ ## 8. README.md 更新要点
1190
+
1191
+ ### 8.1 安装说明更新
1192
+
1193
+ **品牌一致性**: 所有用户-facing 文档中,`codemap` 统一改为 `mycodemap`。
1194
+
1195
+ ```markdown
1196
+ ## 安装
1197
+
1198
+ ### 使用 npx(推荐,无需安装)
1199
+
1200
+ ```bash
1201
+ npx mycodemap init
1202
+ npx mycodemap generate
1203
+ ```
1204
+
1205
+ ### 全局安装
1206
+
1207
+ ```bash
1208
+ npm install -g mycodemap
1209
+ mycodemap init
1210
+ # 或使用短命令
1211
+ cm init
1212
+ ```
1213
+
1214
+ ### 项目本地安装
1215
+
1216
+ ```bash
1217
+ npm install --save-dev mycodemap
1218
+ npx mycodemap init
1219
+ ```
1220
+
1221
+ ### 环境要求
1222
+
1223
+ - **Node.js**: >= 18.0.0
1224
+ - **平台**: Linux (完全支持), macOS (完全支持), Windows (完全支持)
1225
+ - **架构**: x64, ARM64
1226
+
1227
+ > **注意**: 虽然支持多平台,但在 Linux (Ubuntu) 上测试最充分。
1228
+ > 其他平台如遇问题请运行 `mycodemap report` 并提交 Issue。
1229
+
1230
+ ### 命令别名
1231
+
1232
+ 安装后可以使用以下任一命令:
1233
+ - `mycodemap` - 完整命令
1234
+ - `cm` - 短命令(推荐)
1235
+
1236
+ > **注意**: 如果之前安装过其他 `codemap` 包,请确保使用 `mycodemap` 或 `cm`,而非 `codemap`。
1237
+ ```
1238
+
1239
+ ### 8.2 故障排查章节
1240
+
1241
+ ```markdown
1242
+ ## 故障排查
1243
+
1244
+ ### 安装问题
1245
+
1246
+ #### 1. Tree-sitter 加载失败
1247
+
1248
+ 如果遇到以下错误:
1249
+ ```
1250
+ ✗ Tree-sitter 加载失败
1251
+ ```
1252
+
1253
+ **可能的原因**:
1254
+ - 当前平台没有预编译的 binary
1255
+ - 缺少 C++ 编译环境(如需要源码编译)
1256
+ - 网络问题导致 binary 下载失败
1257
+
1258
+ **解决方案**:
1259
+
1260
+ **Linux (Ubuntu)**:
1261
+ ```bash
1262
+ sudo apt-get install build-essential
1263
+ npm rebuild tree-sitter tree-sitter-typescript
1264
+ ```
1265
+
1266
+ **macOS**:
1267
+ ```bash
1268
+ xcode-select --install
1269
+ npm rebuild tree-sitter tree-sitter-typescript
1270
+ ```
1271
+
1272
+ **Windows**:
1273
+ 安装 Visual Studio Build Tools,然后运行:
1274
+ ```bash
1275
+ npm rebuild tree-sitter tree-sitter-typescript
1276
+ ```
1277
+
1278
+ 如问题持续,请运行 `mycodemap report` 并提交 Issue。
1279
+
1280
+ #### 2. 平台不支持错误
1281
+
1282
+ 如果遇到 `Unsupported platform` 错误,请确认:
1283
+ - Node.js 版本 >= 18.0.0 (`node --version`)
1284
+ - 操作系统为 Linux/macOS/Windows
1285
+ - 架构为 x64 或 ARM64
1286
+
1287
+ #### 2. 首次运行较慢
1288
+
1289
+ 首次使用 `npx mycodemap` 时可能需要下载依赖,请耐心等待。
1290
+ 后续运行会使用本地缓存,速度会快很多。
1291
+
1292
+ ### 运行问题
1293
+
1294
+ #### 1. 生成结果为空
1295
+
1296
+ 检查 `codemap.config.json` 中的 `include` 配置是否正确匹配你的源代码路径。
1297
+
1298
+ #### 2. 内存不足
1299
+
1300
+ 对于大型项目,可以增加 Node.js 内存限制:
1301
+ ```bash
1302
+ NODE_OPTIONS="--max-old-space-size=4096" mycodemap generate
1303
+ ```
1304
+
1305
+ ### 提交 Issue
1306
+
1307
+ 如果遇到无法解决的问题,请运行以下命令生成诊断报告:
1308
+
1309
+ ```bash
1310
+ mycodemap report
1311
+ ```
1312
+
1313
+ 然后将生成的 `.codemap/mycodemap-report-*.json` 文件附加到 Issue 中:
1314
+ https://github.com/yourname/mycodemap/issues
1315
+ ```
1316
+
1317
+ ---
1318
+
1319
+ ## 9. 实施步骤
1320
+
1321
+ ### Phase 1: 包配置准备
1322
+
1323
+ 1. **更新 package.json**
1324
+ - 修改 `name` 为 `mycodemap`
1325
+ - 添加 `bin.cm` 别名
1326
+ - 更新 `files` 字段
1327
+ - 添加 `os` 和 `cpu` 限制
1328
+ - 添加 `repository/bugs/homepage`
1329
+
1330
+ 2. **创建 .npmignore**
1331
+ - 排除开发文件和源代码
1332
+ - 保留必要文档
1333
+
1334
+ 3. **创建 codemap.config.schema.json**
1335
+ - 完整的 JSON Schema 定义
1336
+ - 包含所有配置项的验证规则
1337
+
1338
+ ### Phase 2: 功能开发
1339
+
1340
+ 4. **创建 postinstall.js 脚本** ⭐ 新增
1341
+ - 检查 tree-sitter 是否成功安装
1342
+ - 提供友好的错误提示
1343
+ - 添加到 package.json 的 postinstall 钩子
1344
+
1345
+ 5. **创建 platform-check.ts**
1346
+ - 平台检测逻辑
1347
+ - 支持级别判断
1348
+ - 用户提示输出
1349
+
1350
+ 6. **创建 tree-sitter-check.ts**
1351
+ - tree-sitter 可用性检测(按需)
1352
+ - 加载失败时的错误提示
1353
+
1354
+ 7. **创建 first-run-guide.ts**
1355
+ - 首次运行检测
1356
+ - 欢迎信息输出
1357
+ - 快速开始指南
1358
+
1359
+ 8. **创建 sanitize.ts**
1360
+ - 路径脱敏(用户名)
1361
+ - 环境变量值脱敏
1362
+ - 日志内容脱敏
1363
+
1364
+ 9. **创建 report 命令**
1365
+ - 诊断信息收集(使用脱敏工具)
1366
+ - 边界情况处理(无日志、报告过大)
1367
+ - 交互式用户确认
1368
+ - 报告文件生成
1369
+ - CLI 命令集成
1370
+
1371
+ 10. **更新 CLI 入口**
1372
+ - 集成平台检测
1373
+ - 集成按需 tree-sitter 检测
1374
+ - 集成首次运行引导
1375
+ - 注册 report 命令
1376
+
1377
+ 12. **更新 init 命令**
1378
+ - 生成 `mycodemap.config.json`(而非 `codemap.config.json`)
1379
+ - 使用相对路径引用 schema
1380
+ - 检测旧配置 `codemap.config.json` 并提示迁移
1381
+
1382
+ ### Phase 3: 文档准备
1383
+
1384
+ 13. **创建 CHANGELOG.md**
1385
+ - Keep a Changelog 格式
1386
+ - 初始版本条目
1387
+
1388
+ 14. **创建 mycodemap.config.schema.json**
1389
+ - 完整的 JSON Schema 定义
1390
+ - 包含所有配置项的验证规则
1391
+
1392
+ 15. **创建 LICENSE 文件** ⭐ 关键遗漏
1393
+ - MIT 许可证内容
1394
+ - 与 package.json 中的 license 字段一致
1395
+
1396
+ 16. **更新 README.md**
1397
+ - 新的安装说明(品牌名统一)
1398
+ - 平台支持说明
1399
+ - 故障排查章节(含 tree-sitter 错误)
1400
+
1401
+ ### Phase 4: 测试验证
1402
+
1403
+ 17. **本地打包测试**
1404
+ ```bash
1405
+ npm pack
1406
+ tar -tzf mycodemap-0.1.0.tgz
1407
+ ```
1408
+
1409
+ 18. **本地安装测试**
1410
+ ```bash
1411
+ npm link
1412
+ mycodemap --version
1413
+ cm --version
1414
+ mycodemap init
1415
+ mycodemap report
1416
+ ```
1417
+
1418
+ 19. **多平台测试**(如可能)
1419
+ - Linux x64
1420
+ - macOS x64/ARM64
1421
+ - Windows x64
1422
+
1423
+ ### Phase 5: 发布
1424
+
1425
+ 20. **发布到 NPM**
1426
+ ```bash
1427
+ npm config set registry https://registry.npmjs.org/
1428
+ npm login
1429
+ npm publish --access public
1430
+ ```
1431
+
1432
+ 21. **验证安装**
1433
+ ```bash
1434
+ npm uninstall -g mycodemap
1435
+ npx mycodemap --version
1436
+ npx cm --version
1437
+ ```
1438
+
1439
+ ---
1440
+
1441
+ ## 10. 发布流程与 CI/CD 集成 ⭐ 新增
1442
+
1443
+ ### 10.1 版本发布流程
1444
+
1445
+ **手动发布流程**(推荐初期使用):
1446
+ ```bash
1447
+ # 1. 确保所有测试通过
1448
+ npm run test:all
1449
+
1450
+ # 2. 更新版本号(自动更新 CHANGELOG)
1451
+ npm version patch # 或 minor, major
1452
+
1453
+ # 3. 推送标签到远程
1454
+ git push origin main --tags
1455
+
1456
+ # 4. 发布到 NPM
1457
+ npm publish --access public
1458
+ ```
1459
+
1460
+ **版本号策略**:
1461
+ - `0.1.0` - 初始版本
1462
+ - `0.1.1` - bugfix 版本
1463
+ - `0.2.0` - 新功能版本
1464
+ - `1.0.0` - 稳定版本(API 稳定后)
1465
+
1466
+ ### 10.2 Git Tag 与 NPM 版本同步
1467
+
1468
+ **package.json 脚本**:
1469
+ ```json
1470
+ {
1471
+ "scripts": {
1472
+ "version": "npm run changelog && git add CHANGELOG.md",
1473
+ "postversion": "git push origin main --tags"
1474
+ }
1475
+ }
1476
+ ```
1477
+
1478
+ **说明**:
1479
+ - `npm version` 会自动打 git tag
1480
+ - `postversion` 自动推送 tag 到远程
1481
+ - 确保 git 和 npm 版本始终一致
1482
+
1483
+ ### 10.3 GitHub Actions 自动化(可选)
1484
+
1485
+ **文件**: `.github/workflows/publish.yml`
1486
+
1487
+ ```yaml
1488
+ name: Publish to NPM
1489
+
1490
+ on:
1491
+ push:
1492
+ tags:
1493
+ - 'v*'
1494
+
1495
+ jobs:
1496
+ publish:
1497
+ runs-on: ubuntu-latest
1498
+ steps:
1499
+ - uses: actions/checkout@v4
1500
+
1501
+ - name: Setup Node.js
1502
+ uses: actions/setup-node@v4
1503
+ with:
1504
+ node-version: '20'
1505
+ registry-url: 'https://registry.npmjs.org'
1506
+
1507
+ - name: Install dependencies
1508
+ run: npm ci
1509
+
1510
+ - name: Run tests
1511
+ run: npm test
1512
+
1513
+ - name: Build
1514
+ run: npm run build
1515
+
1516
+ - name: Publish to NPM
1517
+ run: npm publish --access public
1518
+ env:
1519
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
1520
+ ```
1521
+
1522
+ **注意**: 需要先在 GitHub Settings 中添加 `NPM_TOKEN` secret。
1523
+
1524
+ ---
1525
+
1526
+ ## 11. 测试策略 ⭐ 新增
1527
+
1528
+ ### 11.1 单元测试
1529
+
1530
+ **已有测试**: `src/**/*.test.ts`
1531
+
1532
+ **需新增测试**:
1533
+ - `src/cli/__tests__/platform-check.test.ts`
1534
+ - `src/cli/__tests__/tree-sitter-check.test.ts`
1535
+ - `src/cli/__tests__/sanitize.test.ts`
1536
+ - `src/cli/commands/__tests__/report.test.ts`
1537
+
1538
+ ### 11.2 集成测试
1539
+
1540
+ **打包测试**:
1541
+ ```bash
1542
+ # 模拟发布
1543
+ npm pack
1544
+
1545
+ # 解压检查内容
1546
+ tar -tzf mycodemap-*.tgz | head -20
1547
+ ```
1548
+
1549
+ **本地安装测试**:
1550
+ ```bash
1551
+ # 链接到全局
1552
+ npm link
1553
+
1554
+ # 测试所有命令
1555
+ mycodemap --version
1556
+ mycodemap init -y
1557
+ mycodemap generate
1558
+ mycodemap report
1559
+
1560
+ # 取消链接
1561
+ npm unlink -g mycodemap
1562
+ ```
1563
+
1564
+ ### 11.3 平台兼容性测试
1565
+
1566
+ **策略**:
1567
+ - **Linux**: 主要开发和测试平台(GitHub Actions Ubuntu Runner)
1568
+ - **macOS**: 本地手动测试(或 GitHub Actions macOS Runner)
1569
+ - **Windows**: 本地手动测试(或 GitHub Actions Windows Runner)
1570
+
1571
+ ** tree-sitter 失败模拟测试**:
1572
+ ```typescript
1573
+ // 模拟 tree-sitter 不可用的情况
1574
+ describe('tree-sitter-check', () => {
1575
+ it('should handle missing tree-sitter gracefully', () => {
1576
+ // 模拟 require 失败
1577
+ jest.mock('tree-sitter', () => {
1578
+ throw new Error('Cannot find module');
1579
+ });
1580
+
1581
+ const result = checkTreeSitter();
1582
+ expect(result).toBe(false);
1583
+ });
1584
+ });
1585
+ ```
1586
+
1587
+ ### 11.4 发布前检查清单
1588
+
1589
+ - [ ] 所有单元测试通过 (`npm test`)
1590
+ - [ ] TypeScript 编译无错误 (`npm run typecheck`)
1591
+ - [ ] ESLint 检查通过 (`npm run lint`)
1592
+ - [ ] `npm pack` 生成的包包含正确文件
1593
+ - [ ] 本地安装测试通过 (`npm link` + 命令测试)
1594
+ - [ ] 版本号已更新 (`package.json`)
1595
+ - [ ] CHANGELOG 已更新
1596
+ - [ ] README 中的示例已验证
1597
+
1598
+ ---
1599
+
1600
+ ## 13. 风险与应对
1601
+
1602
+ | 风险 | 可能性 | 影响 | 应对措施 |
1603
+ |------|--------|------|----------|
1604
+ | tree-sitter 预编译 binary 不兼容 | 低 | 高 | 提供详细的错误提示和 report 命令 |
1605
+ | tree-sitter 在 npm install 阶段失败 | 中 | 高 | postinstall 脚本提供友好提示,不阻断安装 |
1606
+ | 包名 mycodemap 后续被占用 | 极低 | 高 | 发布后立即推广,建立品牌认知 |
1607
+ | Windows 平台问题较多 | 中 | 中 | 文档说明实验性支持,收集反馈迭代 |
1608
+ | 包体积过大 | 低 | 低 | 优化 .npmignore,仅包含必要文件 |
1609
+ | Node.js 版本要求过高 | 低 | 中 | 在 README 显著位置标明要求 |
1610
+ | 报告文件包含未脱敏的敏感信息 | 低 | 高 | 脱敏工具全面审查,报告前用户确认 |
1611
+ | 现有用户迁移困惑(codemap → mycodemap) | 中 | 中 | README 明确说明,保留旧配置检测提示 |
1612
+
1613
+ ---
1614
+
1615
+ ## 12. 成功标准
1616
+
1617
+ - [ ] `npm pack` 生成的包小于 1MB
1618
+ - [ ] `npx mycodemap --version` 正常工作
1619
+ - [ ] `npx cm --version` 正常工作(别名测试)
1620
+ - [ ] `mycodemap init` 在干净环境成功运行
1621
+ - [ ] `mycodemap init` 生成 `mycodemap.config.json`(非旧名)
1622
+ - [ ] `mycodemap report` 生成有效报告文件
1623
+ - [ ] `mycodemap report` 正确脱敏敏感信息
1624
+ - [ ] tree-sitter 检测按需工作(init 不检测,generate 检测)
1625
+ - [ ] Linux 平台完全正常工作
1626
+ - [ ] macOS 平台基本正常工作
1627
+ - [ ] Windows 平台无致命错误
1628
+
1629
+ ---
1630
+
1631
+ ## 附录 A: 文件清单
1632
+
1633
+ ### 新增文件
1634
+ - `docs/PUBLISH_NPM_DESIGN.md` (本文档)
1635
+ - `LICENSE` - MIT 许可证 ⭐ 关键遗漏
1636
+ - `mycodemap.config.schema.json` (原 `codemap.config.schema.json`)
1637
+ - `.npmignore`
1638
+ - `CHANGELOG.md`
1639
+ - `scripts/postinstall.js` - npm 安装后检查 tree-sitter
1640
+ - `src/cli/platform-check.ts`
1641
+ - `src/cli/tree-sitter-check.ts`
1642
+ - `src/cli/first-run-guide.ts`
1643
+ - `src/cli/utils/sanitize.ts`
1644
+ - `src/cli/commands/report.ts`
1645
+
1646
+ ### 修改文件
1647
+ - `package.json` - 包名、bin 配置、engines、os/cpu 限制、postinstall 脚本
1648
+ - `README.md` - 品牌名称、安装说明、故障排查
1649
+ - `src/cli/index.ts` - 集成平台检测、按需 tree-sitter 检测、report 命令
1650
+ - `src/cli/commands/init.ts` - 配置文件名改为 `mycodemap.config.json`,检测旧配置并提示迁移
1651
+
1652
+ ### 已确认事项
1653
+ - ✅ `src/cli/index.ts` 已包含 `#!/usr/bin/env node` shebang
1654
+ - ✅ 编译后的 `dist/cli/index.js` 保留 shebang 和可执行权限
1655
+
1656
+ ---
1657
+
1658
+ ## 附录 B: 现有用户迁移指南 ⭐ 新增
1659
+
1660
+ ### 配置文件迁移
1661
+
1662
+ **init 命令检测旧配置**:
1663
+ ```typescript
1664
+ // 在 init.ts 中添加
1665
+ function checkLegacyConfig(cwd: string): void {
1666
+ const legacyPath = path.join(cwd, 'codemap.config.json');
1667
+ const newPath = path.join(cwd, 'mycodemap.config.json');
1668
+
1669
+ if (fs.existsSync(legacyPath) && !fs.existsSync(newPath)) {
1670
+ console.log(chalk.yellow('⚠'), '检测到旧版配置文件 codemap.config.json');
1671
+ console.log(chalk.gray(' '), '建议重命名为 mycodemap.config.json');
1672
+ console.log();
1673
+ console.log('你可以运行以下命令迁移:');
1674
+ console.log(chalk.cyan(' '), `mv codemap.config.json mycodemap.config.json`);
1675
+ console.log();
1676
+ }
1677
+ }
1678
+ ```
1679
+
1680
+ ### 命令迁移
1681
+
1682
+ | 旧命令 | 新命令 | 说明 |
1683
+ |--------|--------|------|
1684
+ | `codemap init` | `mycodemap init` 或 `cm init` | 使用新的 CLI 名称 |
1685
+ | `codemap generate` | `mycodemap generate` 或 `cm generate` | 同上 |
1686
+
1687
+ ### 环境变量
1688
+
1689
+ 环境变量前缀保持 `CODEMAP_*` 不变,无需修改。
1690
+
1691
+ ---
1692
+
1693
+ *文档结束*