@mycodemap/mycodemap 0.1.0 → 0.2.0

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