dsh-git-push 0.0.0-stage → 2.8.4

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 (278) hide show
  1. package/.auditignore +30 -0
  2. package/.gitignore +39 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1482 -2
  5. package/cli.mjs +360 -0
  6. package/cordis.patch.yml +14 -0
  7. package/lib/ARCHITECTURE.md +34 -0
  8. package/lib/BUGFIX-NOTES-2026-09-14.md +278 -0
  9. package/lib/app/apply.js +275 -0
  10. package/lib/app/audit-api.js +158 -0
  11. package/lib/app/command-registry.js +262 -0
  12. package/lib/app/constants.js +16 -0
  13. package/lib/app/handlers/account.js +166 -0
  14. package/lib/app/handlers/clone.js +168 -0
  15. package/lib/app/handlers/http-constants.js +9 -0
  16. package/lib/app/handlers/identity-rewrite.js +94 -0
  17. package/lib/app/handlers/meta.js +175 -0
  18. package/lib/app/handlers/npm.js +169 -0
  19. package/lib/app/handlers/repo-actions.js +143 -0
  20. package/lib/app/handlers/repos.js +231 -0
  21. package/lib/app/handlers/settings.js +62 -0
  22. package/lib/app/host-doc-checks.js +25 -0
  23. package/lib/app/http-handlers.js +131 -0
  24. package/lib/app/index.js +30 -0
  25. package/lib/app/inject-text.js +191 -0
  26. package/lib/app/scan-root.js +23 -0
  27. package/lib/app/schema.js +150 -0
  28. package/lib/app/settings-bridge.js +167 -0
  29. package/lib/app/slash-commands.js +395 -0
  30. package/lib/app/slot-stats.js +35 -0
  31. package/lib/app/tool-call.js +662 -0
  32. package/lib/app/tools.js +40 -0
  33. package/lib/ast/brace.js +105 -0
  34. package/lib/ast/callgraph.js +135 -0
  35. package/lib/ast/code-lines.js +114 -0
  36. package/lib/ast/consts.js +12 -0
  37. package/lib/ast/control-flow.js +461 -0
  38. package/lib/ast/credential.js +199 -0
  39. package/lib/ast/dataflow.js +274 -0
  40. package/lib/ast/dup-code.js +165 -0
  41. package/lib/ast/index.js +36 -0
  42. package/lib/ast/io-risk-const.js +95 -0
  43. package/lib/ast/io-risk-fn.js +208 -0
  44. package/lib/ast/io-risk-loop.js +308 -0
  45. package/lib/ast/io-risk.js +314 -0
  46. package/lib/ast/lang.js +156 -0
  47. package/lib/ast/line-count.js +52 -0
  48. package/lib/ast/magic-number.js +272 -0
  49. package/lib/ast/naming.js +284 -0
  50. package/lib/ast/perf.js +472 -0
  51. package/lib/ast/scope.js +241 -0
  52. package/lib/ast/shell.js +131 -0
  53. package/lib/ast/size.js +378 -0
  54. package/lib/ast/symbol-index.js +399 -0
  55. package/lib/ast/tokenizer.js +341 -0
  56. package/lib/audit/analysis-coverage.js +98 -0
  57. package/lib/audit/audit-file.js +182 -0
  58. package/lib/audit/checks.js +17 -0
  59. package/lib/audit/client-entry.js +93 -0
  60. package/lib/audit/collector.js +477 -0
  61. package/lib/audit/ext-runner.js +80 -0
  62. package/lib/audit/file-context.js +138 -0
  63. package/lib/audit/finding.js +50 -0
  64. package/lib/audit/gitignore-match.js +113 -0
  65. package/lib/audit/glob.js +63 -0
  66. package/lib/audit/history-report.js +100 -0
  67. package/lib/audit/history.js +126 -0
  68. package/lib/audit/ignore-blind.js +101 -0
  69. package/lib/audit/index.js +33 -0
  70. package/lib/audit/orchestrate.js +476 -0
  71. package/lib/audit/public.js +24 -0
  72. package/lib/audit/repo-level.js +30 -0
  73. package/lib/audit/report-yaml.js +86 -0
  74. package/lib/audit/slot.js +65 -0
  75. package/lib/audit-defaults.js +18 -0
  76. package/lib/audit-rules/audit-rules-comment.yml +247 -0
  77. package/lib/audit-rules/audit-rules-cpp.yml +22 -0
  78. package/lib/audit-rules/audit-rules-docs.yml +32 -0
  79. package/lib/audit-rules/audit-rules-dsh.yml +162 -0
  80. package/lib/audit-rules/audit-rules-filehealth.yml +42 -0
  81. package/lib/audit-rules/audit-rules-folder.yml +99 -0
  82. package/lib/audit-rules/audit-rules-frontend.yml +335 -0
  83. package/lib/audit-rules/audit-rules-go.yml +22 -0
  84. package/lib/audit-rules/audit-rules-i18n.yml +45 -0
  85. package/lib/audit-rules/audit-rules-java.yml +105 -0
  86. package/lib/audit-rules/audit-rules-nodejs.yml +647 -0
  87. package/lib/audit-rules/audit-rules-npm.yml +187 -0
  88. package/lib/audit-rules/audit-rules-paths.yml +92 -0
  89. package/lib/audit-rules/audit-rules-performance.yml +207 -0
  90. package/lib/audit-rules/audit-rules-php.yml +22 -0
  91. package/lib/audit-rules/audit-rules-private.yml +24 -0
  92. package/lib/audit-rules/audit-rules-python.yml +106 -0
  93. package/lib/audit-rules/audit-rules-robustness.yml +27 -0
  94. package/lib/audit-rules/audit-rules-rust.yml +22 -0
  95. package/lib/audit-rules/audit-rules-structure.yml +159 -0
  96. package/lib/audit-rules/audit-rules-swift.yml +22 -0
  97. package/lib/audit-rules/audit-rules-template.yml +108 -0
  98. package/lib/checks/button-bind.js +276 -0
  99. package/lib/checks/common.js +170 -0
  100. package/lib/checks/credential-file.js +43 -0
  101. package/lib/checks/dataflow.js +40 -0
  102. package/lib/checks/dispatch.js +112 -0
  103. package/lib/checks/dup-code.js +69 -0
  104. package/lib/checks/dup-const.js +232 -0
  105. package/lib/checks/file-health.js +150 -0
  106. package/lib/checks/filter.js +131 -0
  107. package/lib/checks/folder.js +173 -0
  108. package/lib/checks/hardcoded-path.js +98 -0
  109. package/lib/checks/index.js +46 -0
  110. package/lib/checks/io.js +66 -0
  111. package/lib/checks/magic-number.js +42 -0
  112. package/lib/checks/npm-json.js +273 -0
  113. package/lib/checks/private.js +63 -0
  114. package/lib/checks/regex.js +256 -0
  115. package/lib/checks/semantic.js +134 -0
  116. package/lib/checks/structural.js +274 -0
  117. package/lib/cli/commands-account.mjs +107 -0
  118. package/lib/cli/commands-audit.mjs +144 -0
  119. package/lib/cli/commands-doc.mjs +127 -0
  120. package/lib/cli/commands-vcs.mjs +175 -0
  121. package/lib/client/index.js +162 -0
  122. package/lib/client-parts/00-loader.js +33 -0
  123. package/lib/client-parts/01-const.js +207 -0
  124. package/lib/client-parts/02-utils.js +62 -0
  125. package/lib/client-parts/03-icons.js +12 -0
  126. package/lib/client-parts/10-account.js +83 -0
  127. package/lib/client-parts/11-browser.js +95 -0
  128. package/lib/client-parts/20-repo.js +374 -0
  129. package/lib/client-parts/21-audit.js +301 -0
  130. package/lib/client-parts/22-settings.js +146 -0
  131. package/lib/client-parts/23-npm.js +383 -0
  132. package/lib/client-parts/30-page.js +56 -0
  133. package/lib/client-parts/40-controller.js +1092 -0
  134. package/lib/client-parts/41-actions.js +279 -0
  135. package/lib/client-parts/99-apply.js +72 -0
  136. package/lib/client.js +3195 -0
  137. package/lib/commit-push.js +144 -0
  138. package/lib/context/index.js +363 -0
  139. package/lib/core/atomic-json.js +98 -0
  140. package/lib/core/config.js +40 -0
  141. package/lib/core/credentials.js +274 -0
  142. package/lib/core/endpoints.js +109 -0
  143. package/lib/core/exec.js +162 -0
  144. package/lib/exempt/index.js +292 -0
  145. package/lib/fs/edit-after-read.js +103 -0
  146. package/lib/fsx.js +87 -0
  147. package/lib/git/account-status.js +140 -0
  148. package/lib/git/account.js +233 -0
  149. package/lib/git/api.js +136 -0
  150. package/lib/git/atomic-json.js +6 -0
  151. package/lib/git/browse.js +38 -0
  152. package/lib/git/clone-download.js +397 -0
  153. package/lib/git/clone-history-mode.js +143 -0
  154. package/lib/git/clone-history.js +175 -0
  155. package/lib/git/clone-jobs.js +250 -0
  156. package/lib/git/clone-replay-io.js +172 -0
  157. package/lib/git/clone-replay.js +275 -0
  158. package/lib/git/clone.js +445 -0
  159. package/lib/git/cloud.js +46 -0
  160. package/lib/git/commit-message.js +141 -0
  161. package/lib/git/config.js +6 -0
  162. package/lib/git/cred-env.js +88 -0
  163. package/lib/git/credentials.js +6 -0
  164. package/lib/git/endpoints.js +6 -0
  165. package/lib/git/exec.js +6 -0
  166. package/lib/git/identity-rewrite.js +297 -0
  167. package/lib/git/identity.js +150 -0
  168. package/lib/git/ignore.js +69 -0
  169. package/lib/git/index.js +41 -0
  170. package/lib/git/module-splitter.js +47 -0
  171. package/lib/git/post-push.js +101 -0
  172. package/lib/git/push-diagnose.js +142 -0
  173. package/lib/git/push.js +470 -0
  174. package/lib/git/remote-resolve.js +146 -0
  175. package/lib/git/remote.js +128 -0
  176. package/lib/git/repo-index.js +512 -0
  177. package/lib/git/repos.js +235 -0
  178. package/lib/git/scan-runner.js +159 -0
  179. package/lib/git/sensitive.js +134 -0
  180. package/lib/git/transport.js +430 -0
  181. package/lib/git/visibility.js +35 -0
  182. package/lib/git/wrapped-git.js +68 -0
  183. package/lib/http/index.js +170 -0
  184. package/lib/index.js +24 -0
  185. package/lib/link-check/index.js +187 -0
  186. package/lib/npm/account.js +64 -0
  187. package/lib/npm/install.js +211 -0
  188. package/lib/npm/npmrc.js +56 -0
  189. package/lib/npm/publish.js +167 -0
  190. package/lib/npm/registry.js +147 -0
  191. package/lib/plugin/auto-detect.js +92 -0
  192. package/lib/plugin/auto-push.js +154 -0
  193. package/lib/plugin/index.js +250 -0
  194. package/lib/readme-templates/readme.yml +38 -0
  195. package/lib/rule/compilers/credential.js +62 -0
  196. package/lib/rule/compilers/dataflow.js +38 -0
  197. package/lib/rule/compilers/file-health.js +75 -0
  198. package/lib/rule/compilers/frontend.js +86 -0
  199. package/lib/rule/compilers/func.js +35 -0
  200. package/lib/rule/compilers/helpers.js +71 -0
  201. package/lib/rule/compilers/index.js +29 -0
  202. package/lib/rule/compilers/link-semantic.js +45 -0
  203. package/lib/rule/compilers/list-kinds.js +12 -0
  204. package/lib/rule/compilers/numeric-kinds.js +66 -0
  205. package/lib/rule/compilers/regex.js +78 -0
  206. package/lib/rule/compilers/structure.js +80 -0
  207. package/lib/rule/compilers.js +17 -0
  208. package/lib/rule/homoglyph.js +45 -0
  209. package/lib/rule/loader.js +270 -0
  210. package/lib/rule/registry.js +115 -0
  211. package/lib/rule/scope.js +67 -0
  212. package/lib/score/docs-score.js +166 -0
  213. package/lib/score/index.js +140 -0
  214. package/lib/self/index.js +193 -0
  215. package/lib/skip-dirs.js +64 -0
  216. package/lib/tool-probes.json +50 -0
  217. package/lib/user-requirements.json +14 -0
  218. package/lib/vendor/js-yaml/LICENSE +21 -0
  219. package/lib/vendor/js-yaml/js-yaml.mjs +3073 -0
  220. package/package.json +95 -4
  221. package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
  222. package/scripts/audit-ext/_example-readme-present.mjs +34 -0
  223. package/scripts/audit-ext/variable-min-length.mjs +102 -0
  224. package/scripts/audit-runner.mjs +35 -0
  225. package/scripts/audit-runtime-check.mjs +129 -0
  226. package/scripts/browser-page-probe.mjs +271 -0
  227. package/scripts/build-client.mjs +119 -0
  228. package/scripts/check.mjs +88 -0
  229. package/scripts/clean-date-comments.py +102 -0
  230. package/scripts/doc-drift.mjs +200 -0
  231. package/scripts/doc-func.mjs +212 -0
  232. package/scripts/doc-tree.mjs +456 -0
  233. package/scripts/doc-version.mjs +220 -0
  234. package/scripts/frontend-preview-check.mjs +124 -0
  235. package/scripts/hot-path-probe-cjs.cjs +71 -0
  236. package/scripts/hot-path-probe-fs-shim.mjs +28 -0
  237. package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
  238. package/scripts/hot-path-probe.mjs +153 -0
  239. package/scripts/module-splitter.py +800 -0
  240. package/scripts/platform-scan.mjs +168 -0
  241. package/scripts/preview-gen.mjs +489 -0
  242. package/scripts/preview-local-runner.mjs +55 -0
  243. package/scripts/preview-server-direct.mjs +116 -0
  244. package/scripts/preview-server.mjs +305 -0
  245. package/scripts/preview-slot-data.mjs +123 -0
  246. package/scripts/probe-recheck.mjs +47 -0
  247. package/scripts/readme-gen.mjs +268 -0
  248. package/scripts/rename-locator.mjs +97 -0
  249. package/scripts/rule-switch.mjs +97 -0
  250. package/scripts/rules-solo-audit.mjs +173 -0
  251. package/scripts/scan-file-io.mjs +713 -0
  252. package/scripts/scan-hardcoded-paths.mjs +125 -0
  253. package/scripts/scan-repos.mjs +167 -0
  254. package/scripts/scan-version.mjs +122 -0
  255. package/scripts/scrub-user-wording.mjs +420 -0
  256. package/scripts/symbol-index.mjs +85 -0
  257. package/scripts/sync-plugin-install.mjs +223 -0
  258. package/scripts/sync-plugin.mjs +279 -0
  259. package/scripts/verify-prestep.mjs +100 -0
  260. package/skills/dev/audit-rule-authoring.md +58 -0
  261. package/skills/dev/dsh-git-push.md +323 -0
  262. package/skills/dev/git-push-live-fix.md +45 -0
  263. package/skills/dsh-repo-index.md +35 -0
  264. package/skills/guide/guide-audit.md +167 -0
  265. package/skills/guide/guide-cli-scripts.md +104 -0
  266. package/skills/guide/guide-clone-repos.md +173 -0
  267. package/skills/guide/guide-commit-push.md +156 -0
  268. package/skills/guide/guide-inject-ui.md +166 -0
  269. package/skills/guide/guide-slash-completion.md +118 -0
  270. package/skills/workflow/README.md +21 -0
  271. package/skills/workflow/git-commit-discipline.md +68 -0
  272. package/skills/workflow/git-project-startup.md +85 -0
  273. package/skills/workflow/git-rebuild-process.md +57 -0
  274. package/skills/workflow/github-operations.md +91 -0
  275. package/skills/workflow/readme-sync-git-md.md +28 -0
  276. package/skills/workflow/task-completion-report.md +73 -0
  277. package/skills/workflow/tool-json-add-ask.md +35 -0
  278. package/skills/workflow/versioning-rule.md +211 -0
@@ -0,0 +1,341 @@
1
+ // dsh-skip-func-length: tokenizeUncached 为纯线性解析主体(逐字符状态机),拆成多个函数会引入跨函数
2
+ // 共享的可变状态(行号/块注释状态/输出数组),反而更易出错、更难读;故整文件豁免函数长度检查。
3
+ /**
4
+ * AST 实现层 · 分词器
5
+ *
6
+ * 职责:把源码切成 token 流(字符串/模板串/注释感知),并提供按文本内容的 LRU 缓存。
7
+ * 本模块是全部 token 级检查的公共底座——其余 ast/ 模块都通过 tokenize() 取流。
8
+ *
9
+ * 自研 tokenizer 的原因:零第三方依赖;Node 无内置 JS AST,token 级已足够覆盖
10
+ * 「注释/字符串里的内容不算代码」这类判定(逐行正则做不到)。
11
+ */
12
+
13
+ /**
14
+ * tokenize 结果缓存(性能优化)。
15
+ *
16
+ * 动机:审计一个文件时,多条 AST 精筛规则(short-func-name / magic-number /
17
+ * credential-value / small-file-read)会**各自独立**调用 tokenize,同一个文件
18
+ * 被重复切词 5+ 次。实测 1255 行文件单次 tokenize 16ms,重复调用白浪费约 64ms/文件,
19
+ * 在弱 CPU 机器 + 大仓库上直接表现为「提交推送卡住」。
20
+ *
21
+ * tokenize 是纯函数(同输入必得同输出)且调用方只读返回数组(无 push/splice/sort),
22
+ * 因此可按文本内容缓存。用 Map(插入序 LRU)+ 上限淘汰,避免长驻进程内存无界增长。
23
+ */
24
+ const TOKEN_CACHE = new Map();
25
+
26
+ /** 缓存条目数上限(防「海量小文件」把 Map 撑爆)。可用 env 覆盖(不硬编码)。 */
27
+ const TOKEN_CACHE_MAX = Number(process.env.DSH_GIT_PUSH_TOKEN_CACHE_MAX || 512) || 512;
28
+ /**
29
+ * 缓存**字节预算**(按被缓存文本的字符数计)。为什么要有:旧口径只看条数(512 条),
30
+ * 在大文件仓库上命中率低——512 条小文件就能把大文件全挤出去;而大文件恰恰最贵
31
+ * (单次 tokenize 耗时与其长度成正比,且审计里同一文件会被多条规则反复切词)。
32
+ * 改为「条数 + 字节」双上限后,大文件能留在缓存里。
33
+ * 可用 env 覆盖(不硬编码):DSH_GIT_PUSH_TOKEN_CACHE_BYTES(默认 8MiB 文本)。
34
+ */
35
+ const TOKEN_CACHE_MAX_BYTES = Number(process.env.DSH_GIT_PUSH_TOKEN_CACHE_BYTES || 8 * 1024 * 1024) || 8 * 1024 * 1024;
36
+ /** 当前缓存占用(字符数近似字节;仅用于预算判断,不参与任何判定结果)。 */
37
+ let TOKEN_CACHE_BYTES = 0;
38
+
39
+ /**
40
+ * 轻量 tokenizer:把文本切成 token 流,字符串/模板串/注释原样保留但标记类型。
41
+ *
42
+ * 结果按文本内容缓存(见 TOKEN_CACHE):同一文件被多条规则重复切词时只算一次。
43
+ * 返回的是**共享数组**——调用方只读,禁止原地修改(push/splice/sort)。
44
+ *
45
+ * @param {string} text 文件全文
46
+ * @returns {Array<{type:string, value:string, line:number}>}
47
+ * type: ident / punct / str / tmpl / comment / num / ws / other
48
+ */
49
+ export function tokenize(text = '') {
50
+ const key = String(text);
51
+ const cached = TOKEN_CACHE.get(key);
52
+ if (cached) {
53
+ // LRU 触达:删后重插使其移到队尾(Map 保持插入序,队首即最久未用)
54
+ TOKEN_CACHE.delete(key);
55
+ TOKEN_CACHE.set(key, cached);
56
+ return cached;
57
+ }
58
+ const tokens = tokenizeUncached(text);
59
+ TOKEN_CACHE.set(key, tokens);
60
+ TOKEN_CACHE_BYTES += key.length;
61
+ // 双上限(条数 + 字节):任一超限即淘汰最久未用(Map 首个键),直到都回到限内。
62
+ // 保留至少 1 条:单个超大文件也不至于「刚缓存就被自己挤出」。
63
+ while (TOKEN_CACHE.size > TOKEN_CACHE_MAX || (TOKEN_CACHE_BYTES > TOKEN_CACHE_MAX_BYTES && TOKEN_CACHE.size > 1)) {
64
+ const oldest = TOKEN_CACHE.keys().next();
65
+ if (oldest.done) break;
66
+ TOKEN_CACHE_BYTES -= String(oldest.value).length;
67
+ TOKEN_CACHE.delete(oldest.value);
68
+ }
69
+ return tokens;
70
+ }
71
+
72
+ /** 清空 tokenize 缓存(测试/长驻进程内存回收用)。 */
73
+ export function clearTokenCache() {
74
+ TOKEN_CACHE.clear();
75
+ TOKEN_CACHE_BYTES = 0;
76
+ }
77
+
78
+ /**
79
+ * tokenize 的实际实现(不做缓存)。外部一律走 tokenize()。
80
+ * @param {string} text 文件全文
81
+ * @returns {Array<{type:string, value:string, line:number}>} token 流
82
+ */
83
+ function tokenizeUncached(text = '') {
84
+ const tokens = [];
85
+ const lines = String(text).split('\n');
86
+ let line = 1;
87
+ // 块注释跨行状态(修):旧实现在**单行内**找 `*/`,多行块注释
88
+ // (JSDoc `/** ... */`)的续行 ` * 说明 +1` 会被当成代码 → ident/num token 泄漏,
89
+ // 导致注释里的版本号/数字被魔数等规则误报。改为跨行携带 inBlock 状态。
90
+ let inBlock = false;
91
+ // 模板字符串跨行状态:主循环按行 split,多行模板(如 cli.mjs 的 HELP 帮助文本)
92
+ // 此前只把「开引号那一行」当模板,后续行整行被当代码 tokenize ⇒ 正文里的
93
+ // 占位符 `[--depth N]` 产出 type:"ident" 的 `N`,被 readability/variable-min-length
94
+ // 当短变量名误报(实测 3 条)。与三引号/块注释同模式:跨行携带状态直到闭合反引号。
95
+ let inTemplate = false;
96
+ // Python 三引号字符串跨行状态:主循环按行 split,
97
+ // 多行 docstring("""…\n…""")若按行独立 tokenize 会在换行处被切断成两个
98
+ // str + 中间内容被拆碎(数字/文本误报魔数/重复串)。跨行携带 tripleQuote
99
+ // 状态:进入三引号后,后续行整行并入同一 str token,直到闭合三引号。
100
+ let tripleQuote = '';
101
+ let tripleBuf = '';
102
+ for (const raw of lines) {
103
+ const src = raw;
104
+ let i = 0;
105
+ const n = src.length;
106
+ const push = (type, value) => tokens.push({ type, value, line });
107
+ while (i < n) {
108
+ const ch = src[i];
109
+ const next = src[i + 1];
110
+ // 三引号续行:整行剩余内容并入缓冲,直到找到闭合
111
+ if (tripleQuote) {
112
+ const end = src.indexOf(tripleQuote.repeat(3), i);
113
+ if (end === -1) { tripleBuf += src.slice(i) + '\n'; i = n; break; }
114
+ tripleBuf += src.slice(i, end);
115
+ push('str', tripleQuote.repeat(3) + tripleBuf + tripleQuote.repeat(3));
116
+ tripleQuote = ''; tripleBuf = '';
117
+ i = end + 3;
118
+ continue;
119
+ }
120
+ // 模板字符串续行:整行并入 tmpl,直到找到闭合反引号(多行模板不再泄漏为代码)
121
+ if (inTemplate) {
122
+ const end = src.indexOf('`', i);
123
+ if (end === -1) { push('tmpl', src.slice(i)); i = n; break; }
124
+ push('tmpl', src.slice(i, end + 1));
125
+ inTemplate = false;
126
+ i = end + 1;
127
+ continue;
128
+ }
129
+ // 块注释续行:整行剩余内容都是注释(含 ` * xxx` 的星号续行)
130
+ if (inBlock) {
131
+ const end = src.indexOf('*/', i);
132
+ if (end === -1) { push('comment', src.slice(i)); i = n; break; }
133
+ push('comment', src.slice(i, end + 2));
134
+ i = end + 2;
135
+ inBlock = false;
136
+ continue;
137
+ }
138
+ // 空白 / 行注释 / 块注释(跨行:本行找不到 `*/` 则整行剩余为注释并置 inBlock)
139
+ if (/\s/.test(ch)) { i++; continue; }
140
+ if (ch === '/' && next === '/') { push('comment', src.slice(i)); break; }
141
+ // Python `#` 行注释:仅在**行首**(前面只可能有空白)识别——
142
+ // JS 类私有字段 `#foo` 不在行首,CSS 选择器不在此 tokenizer;行首 `#` 是
143
+ // Python 注释的确定形态(shebang `#!/usr/bin/env` 也算注释)。
144
+ if (ch === '#' && /^\s*$/.test(src.slice(0, i))) { push('comment', src.slice(i)); break; }
145
+ if (ch === '/' && next === '*') {
146
+ const end = src.indexOf('*/', i + 2);
147
+ if (end === -1) { push('comment', src.slice(i)); inBlock = true; i = n; break; }
148
+ const seg = src.slice(i, end + 2);
149
+ push('comment', seg);
150
+ i += seg.length;
151
+ continue;
152
+ }
153
+ // 三引号开始(""" 或 ''',):单行内闭合 → 整体消费为 str;
154
+ // 跨行未闭合 → 设 tripleQuote 状态,整行及后续行并入缓冲
155
+ if ((src.startsWith('"""', i) || src.startsWith("'''", i))) {
156
+ const q = ch;
157
+ const q3 = q.repeat(3);
158
+ const end = src.indexOf(q3, i + 3);
159
+ if (end === -1) {
160
+ tripleQuote = q; tripleBuf = src.slice(i + 3) + '\n';
161
+ i = n; break;
162
+ }
163
+ push('str', src.slice(i, end + 3));
164
+ i = end + 3;
165
+ continue;
166
+ }
167
+ // 字符串 / 模板字符串 / 正则 / 数字 / 标识符 / 运算符 —— 抽成独立消费函数
168
+ const res = consumeLexeme(src, i, n, ch, next, tokens, push);
169
+ if (res) {
170
+ // 多行模板字符串:consumeTemplate 遇未闭合反引号只归并到行尾,这里补跨行状态,
171
+ // 否则后续行会被当代码 tokenize(帮助文本里的 `[--depth N]` 曾因此报短变量名误报)
172
+ const lastTok = tokens[tokens.length - 1];
173
+ // 判据:首个反引号之后再无反引号 = 本行内未闭合。不能只看 endsWith——
174
+ // `const css = ` 后面紧跟换行(反引号正好在行尾)时,token 值就是**单个反引号**,
175
+ // endsWith('`') 为真 ⇒ 旧判据漏置跨行状态 ⇒ 模板正文(CSS/帮助文本)整段被当代码,
176
+ // CSS 里的 #141518 / #888 / 1.5 被 readability/magic-number-smart 当魔数误报。
177
+ if (lastTok && lastTok.type === 'tmpl' && String(lastTok.value).indexOf('`', 1) === -1) inTemplate = true;
178
+ i = res; continue;
179
+ }
180
+ // 标点 / 其他(单字符)
181
+ push('punct', ch);
182
+ i++;
183
+ }
184
+ line++;
185
+ }
186
+ return tokens;
187
+ }
188
+
189
+ /** 多字符运算符(最长匹配优先, 修):旧实现逐字符推送标点,导致
190
+ * `?.`(可选链)被切成 `?` + `.`、`??` 切成两个 `?`、`||` 切成两个 `|`
191
+ * → 圈复杂度把每个可选链当三元运算符(严重高估),而 `||`/`&&`/`??` 反而
192
+ * 识别不到(漏报)。这里按长度降序匹配;**可选链 `?.` 与空值合并 `??`
193
+ * 必须切成不同 token**——前者不产生独立执行路径(不是分支),后者是分支。 */
194
+ const MULTI_OPS = ['===', '!==', '**=', '<<=', '>>=', '...', '??=', '&&=', '||=', '?.', '??',
195
+ '=>', '==', '!=', '<=', '>=', '&&', '||', '++', '--', '+=', '-=', '*=', '/=', '%=', '**', '<<', '>>', '::'];
196
+
197
+ /** 多字符运算符**按首字符分桶**(性能,2026-10-09):原实现对每个标点都线性扫 26 个候选(startsWith),
198
+ * 分桶后只扫同首字符的少数几个;**桶内保持 MULTI_OPS 原顺序** ⇒ 最长匹配语义完全不变。 */
199
+ const MULTI_OPS_BY_FIRST = (() => {
200
+ const m = new Map();
201
+ for (const op of MULTI_OPS) {
202
+ const k = op[0];
203
+ if (!m.has(k)) m.set(k, []);
204
+ m.get(k).push(op);
205
+ }
206
+ return m;
207
+ })();
208
+
209
+ /* 词素字符判定:**字符码查表**替代逐字符正则(性能,2026-10-09)。
210
+ * 原实现对每个字符调用正则(/[0-9]/、/[0-9._a-zA-Z]/、/[A-Za-z_$\u4e00-\u9fa5]/ 等),
211
+ * 逐字符建正则/跑正则的开销占 tokenizer 自耗时的大头(温跑 profile:consumeLexeme 9.8%)。
212
+ * 三张 128 项 ASCII 表由**同样的正则**在模块加载时生成一次 ⇒ 判定集合逐字符等价;
213
+ * 非 ASCII 只有 CJK 区间 \u4e00-\u9fa5 属于标识符(数字体集合里没有非 ASCII)。 */
214
+ const ID_START_ASCII = new Uint8Array(128);
215
+ const ID_PART_ASCII = new Uint8Array(128);
216
+ const NUM_PART_ASCII = new Uint8Array(128);
217
+ for (let c = 0; c < 128; c++) {
218
+ const s = String.fromCharCode(c);
219
+ ID_START_ASCII[c] = /[A-Za-z_$]/.test(s) ? 1 : 0;
220
+ ID_PART_ASCII[c] = /[A-Za-z0-9_$]/.test(s) ? 1 : 0;
221
+ NUM_PART_ASCII[c] = /[0-9._a-zA-Z]/.test(s) ? 1 : 0;
222
+ }
223
+ /** CJK 标识符区间(与原正则 \u4e00-\u9fa5 一致)。 */
224
+ const isCjkChar = (c) => c >= 0x4e00 && c <= 0x9fa5;
225
+ /** 是否标识符起始字符(等价于 /[A-Za-z_$\u4e00-\u9fa5]/)。 */
226
+ const isIdentStartCode = (c) => (c < 128 ? ID_START_ASCII[c] === 1 : isCjkChar(c));
227
+ /** 是否标识符后续字符(等价于 /[A-Za-z0-9_$\u4e00-\u9fa5]/)。 */
228
+ const isIdentPartCode = (c) => (c < 128 ? ID_PART_ASCII[c] === 1 : isCjkChar(c));
229
+ /** 是否数字体字符(等价于 /[0-9._a-zA-Z]/;该集合无非 ASCII 成员)。 */
230
+ const isNumPartCode = (c) => c < 128 && NUM_PART_ASCII[c] === 1;
231
+ /** 是否 ASCII 数字(等价于 /[0-9]/)。 */
232
+ const isAsciiDigit = (c) => c >= 48 && c <= 57;
233
+
234
+ /** 正则可接在哪些关键字后(return/typeof/case/in/of/new/delete/void/do/else/yield/await)。 */
235
+ const REGEX_AFTER_KEYWORD = /^(?:return|typeof|case|in|of|new|delete|void|do|else|yield|await|instanceof)$/;
236
+
237
+ /**
238
+ * 消费一个词素(字符串/模板/正则/数字/标识符/运算符)。由 tokenizeUncached 主循环分派。
239
+ * 返回消费后的新 i;不匹配(纯标点)返回 0。
240
+ * 拆出的原因:tokenizeUncached 圈复杂度 61(阈值 15)——逐字符状态机
241
+ * 分支密集,全部内联在 while 里无法维护;按词素类型抽独立函数,主循环只做分派。
242
+ */
243
+ function consumeLexeme(src, i, n, ch, next, tokens, push) { // dsh-skip-complexity: 词素分派器(六类词素分派分支为结构必然,拆分后职责单一)
244
+ // 字符串(' ")——普通单引号字符串;三引号(""" ''')由主循环专门处理
245
+ if (ch === '"' || ch === "'") return consumeString(src, i, n, ch, push);
246
+ // 模板字符串(`)——嵌套 ${} 简化处理:遇未闭合 ` 归并到行尾
247
+ if (ch === '`') return consumeTemplate(src, i, n, push);
248
+ // 正则字面量(/…/flags)——修:旧实现不识别正则,把 `/^\s*(?:x|y)/` 拆成
249
+ // `/` `^` `\` `s` `*` `(` `?` `:` `|` `)` 等标点,其中的 `(` `)` `{` `}` 直接参与
250
+ // 括号平衡,导致 matchBrace 跑飞:单个 12 行函数被算成 242 行(func-lines 误报 blocker)。
251
+ // 判别依据:`/` 出现在「表达式起始位置」才是正则——即上一个有意义 token 不是
252
+ // 标识符/数字/字符串/`)`/`]`/`}`(那些后面跟的 `/` 是除号)。
253
+ if (ch === '/' && next !== '/' && next !== '*') {
254
+ const consumed = consumeRegex(src, i, n, tokens, push);
255
+ if (consumed) return consumed;
256
+ }
257
+ // 数字(字符码判定,等价于原先的 /[0-9]/.test(ch) 与 /[0-9._a-zA-Z]/.test(src[j]))
258
+ const c0 = src.charCodeAt(i);
259
+ if (isAsciiDigit(c0) || (ch === '.' && isAsciiDigit(next ? next.charCodeAt(0) : -1))) {
260
+ let j = i;
261
+ while (j < n && isNumPartCode(src.charCodeAt(j))) j++;
262
+ push('num', src.slice(i, j));
263
+ return j;
264
+ }
265
+ // 标识符(含 $ _ 中文;字符码判定,等价于 /[A-Za-z_$\u4e00-\u9fa5]/ 与 /[A-Za-z0-9_$\u4e00-\u9fa5]/)
266
+ if (isIdentStartCode(c0)) {
267
+ let j = i;
268
+ while (j < n && isIdentPartCode(src.charCodeAt(j))) j++;
269
+ push('ident', src.slice(i, j));
270
+ return j;
271
+ }
272
+ // 多字符运算符(最长匹配优先;按首字符分桶,桶内顺序与原数组一致)
273
+ const cands = MULTI_OPS_BY_FIRST.get(ch);
274
+ if (cands) {
275
+ for (const cand of cands) {
276
+ if (src.startsWith(cand, i)) { push('punct', cand); return i + cand.length; }
277
+ }
278
+ }
279
+ return 0;
280
+ }
281
+
282
+ /** 字符串字面量(' ")——遇转义 \ 跳两字符;未闭合归并到行尾。 */
283
+ function consumeString(src, i, n, ch, push) {
284
+ let j = i + 1;
285
+ let str = ch;
286
+ while (j < n) {
287
+ if (src[j] === '\\') { str += src[j] + (src[j + 1] || ''); j += 2; continue; }
288
+ str += src[j];
289
+ if (src[j] === ch) { j++; break; }
290
+ j++;
291
+ }
292
+ push('str', str);
293
+ return j;
294
+ }
295
+
296
+ /** 模板字符串(`)——遇 \ 跳两字符;未闭合归并到行尾(简单 ${} 处理)。 */
297
+ function consumeTemplate(src, i, n, push) {
298
+ let j = i + 1;
299
+ let str = '`';
300
+ while (j < n && src[j] !== '`') {
301
+ if (src[j] === '\\') { str += src[j] + (src[j + 1] || ''); j += 2; continue; }
302
+ str += src[j];
303
+ j++;
304
+ }
305
+ if (j < n) { str += '`'; j++; }
306
+ push('tmpl', str);
307
+ return j;
308
+ }
309
+
310
+ /** 正则字面量(/…/flags);`/` 前一 token 是值表达式时为除号,返回 0 交给标点处理。 */
311
+ function consumeRegex(src, i, n, tokens, push) { // dsh-skip-complexity: 正则状态机(转义/字符组/闭包三态,天然多分支)
312
+ const prevTok = tokens.length ? tokens[tokens.length - 1] : null;
313
+ const prevIsValue = prevTok && (
314
+ prevTok.type === 'ident' || prevTok.type === 'num' || prevTok.type === 'str'
315
+ || prevTok.type === 'tmpl' || prevTok.type === 'regex'
316
+ || (prevTok.type === 'punct' && [')', ']', '}'].includes(prevTok.value))
317
+ );
318
+ // 关键字后(return/typeof/case/in/of/new/delete/void/do/else/yield/await)可接正则
319
+ const afterKeyword = prevTok && prevTok.type === 'ident' && REGEX_AFTER_KEYWORD.test(prevTok.value);
320
+ if (prevIsValue && !afterKeyword) return 0;
321
+ let j = i + 1;
322
+ let re = '/';
323
+ let inClass = false; // 字符组 [ ] 内的 `/` 不结束正则
324
+ let closed = false;
325
+ while (j < n) {
326
+ const cj = src[j];
327
+ if (cj === '\\') { re += cj + (src[j + 1] || ''); j += 2; continue; }
328
+ if (cj === '\n') break; // 正则不能跨行,未闭合则放弃
329
+ if (cj === '[') inClass = true;
330
+ else if (cj === ']') inClass = false;
331
+ re += cj;
332
+ if (cj === '/' && !inClass) { closed = true; j++; break; }
333
+ j++;
334
+ }
335
+ if (!closed) return 0;
336
+ // 跟随的 flags(g/i/m/s/u/y/d)
337
+ while (j < n && /[gimsuy]/.test(src[j])) { re += src[j]; j++; }
338
+ push('regex', re);
339
+ return j;
340
+ }
341
+
@@ -0,0 +1,98 @@
1
+ /**
2
+ * 分析覆盖率(**信息项,不参与评分**)
3
+ *
4
+ * 【为什么需要】审计可能「规则全过」但其实根本没解析到代码(比如解析器看不懂某种语法、
5
+ * 导入解析不到目标文件)——只看命中数与分数会被这种假绿误导。这里用符号索引给出三个数:
6
+ * ① 覆盖率 = 连边数 / 可解析调用数(成员调用 `x.y()` 不计入,它们本就不经符号索引解析)
7
+ * ② 未解析构成(unknown / ambiguous)与按文件的未解析 top
8
+ * ③ 被排除的成员调用量(说明分母口径,避免"看起来漏了很多"的误解)
9
+ *
10
+ * 【为什么不进评分】覆盖率高低受语言与工程风格影响很大(纯函数库天然高、框架代码天然低),
11
+ * 直接计分会把「语言差异」算成「代码质量问题」。先作为可见性指标输出,口径稳定后再议是否计分。
12
+ *
13
+ * 【口径限制】需要**完整文件集**才能解析跨文件导入;diff 范围只含变动文件时无法给出可信覆盖率,
14
+ * 此时返回 `{ skipped: 原因 }` 而不是给一个失真的数字。
15
+ */
16
+ import { buildSymbolIndex } from '../ast/symbol-index.js';
17
+ import { collectTextFiles, readText } from './collector.js';
18
+ import { relative } from 'node:path';
19
+
20
+ /** 未解析 top 文件默认取前几个。 */
21
+ const DEFAULT_TOP_N = 5;
22
+
23
+ /**
24
+ * 取「相对路径 → 文件内容」的条目集。
25
+ * - 调用方直接给 `files: [{path, full}]`(含内容)时用它(单测/已读入场景,不再碰磁盘);
26
+ * - 否则按**审计同一套采集器**(collectTextFiles:gitignore/.auditignore 感知)从 repoPath 收集并读取,
27
+ * 保证覆盖率与审计看到的是同一批文件。
28
+ * @returns {Promise<Array<{path:string, full:string}>>}
29
+ */
30
+ async function resolveEntries({ repoPath, files }) {
31
+ if (Array.isArray(files) && files.length) {
32
+ return files.map((f) => ({ path: String(f.path || f.rel || ''), full: String(f.full ?? '') })).filter((f) => f.path);
33
+ }
34
+ if (!repoPath) return [];
35
+ const collected = await collectTextFiles(repoPath, { gitIgnoreRoot: repoPath, includeIgnored: false });
36
+ const list = Array.isArray(collected) ? collected : (collected && collected.files) || [];
37
+ return list
38
+ .map((f) => ({ path: relative(repoPath, String(f.full || f.path || '')).replace(/\\/g, '/'), full: readText(String(f.full || '')) || '' }))
39
+ .filter((f) => f.path && f.full);
40
+ }
41
+
42
+ /**
43
+ * 计算分析覆盖率(信息项)。
44
+ * @param {{repoPath?:string, files?:Array<{path?:string, rel?:string, full?:string}>, topN?:number}} [opts]
45
+ * files:已读入的文件(含内容);未给则用 repoPath 按审计采集器现收现读
46
+ * @returns {Promise<object>} 覆盖率信息对象(不参与评分)
47
+ */
48
+ export async function computeAnalysisCoverage({ repoPath = '', files = null, topN = DEFAULT_TOP_N } = {}) {
49
+ const entries = await resolveEntries({ repoPath, files });
50
+ if (!entries.length) return { files: 0, note: '无文件可分析' };
51
+ const byPath = new Map(entries.map((e) => [e.path, e.full]));
52
+ const index = buildSymbolIndex([...byPath.keys()], { readFile: (rel) => byPath.get(rel) || '' });
53
+ const s = index.stats;
54
+ return {
55
+ files: s.files,
56
+ declarations: s.declarations,
57
+ exports: s.exports,
58
+ calls: s.calls,
59
+ edges: s.edges,
60
+ edgesByVia: s.edgesByVia,
61
+ unresolved: s.unresolved,
62
+ unresolvedByReason: countByReason(index.unresolved),
63
+ memberCallsExcluded: s.skippedMemberCalls,
64
+ coverage: s.coverage,
65
+ topUnresolvedFiles: topUnresolvedFiles(index.unresolved, topN),
66
+ note: '信息项,不参与评分;覆盖率 = 连边 / 可解析调用(成员调用 x.y() 已排除并单独计数)',
67
+ };
68
+ }
69
+
70
+ /** 未解析原因计数。 */
71
+ function countByReason(unresolved) {
72
+ const out = {};
73
+ for (const u of unresolved) out[u.reason] = (out[u.reason] || 0) + 1;
74
+ return out;
75
+ }
76
+
77
+ /** 按文件统计未解析调用数,取前 N(降序)。 */
78
+ function topUnresolvedFiles(unresolved, topN) {
79
+ const counts = new Map();
80
+ for (const u of unresolved) counts.set(u.file, (counts.get(u.file) || 0) + 1);
81
+ return [...counts.entries()]
82
+ .map(([file, count]) => ({ file, count }))
83
+ .sort((a, b) => b.count - a.count)
84
+ .slice(0, Math.max(0, topN));
85
+ }
86
+
87
+ /**
88
+ * 覆盖率一行文本(审计输出里附在 apiGuide 后面)。
89
+ * @param {object} cov computeAnalysisCoverage 的结果(或 `{skipped}`)
90
+ * @returns {string}
91
+ */
92
+ export function formatAnalysisCoverageLine(cov = {}) {
93
+ if (!cov || cov.skipped) return `分析覆盖率:跳过(${(cov && cov.skipped) || '未计算'})`;
94
+ if (!cov.files) return `分析覆盖率:${cov.note || '无文件'}`;
95
+ const reasons = Object.entries(cov.unresolvedByReason || {}).map(([k, v]) => `${k} ${v}`).join(' / ');
96
+ return `分析覆盖率 ${cov.coverage}%(连边 ${cov.edges} / 可解析调用 ${cov.calls};未解析 ${cov.unresolved}${reasons ? `:${reasons}` : ''};`
97
+ + `已排除成员调用 ${cov.memberCallsExcluded})——信息项,不参与评分`;
98
+ }
@@ -0,0 +1,182 @@
1
+ import { runChecks } from './checks.js';
2
+ import { exemptForFinding } from '../exempt/index.js';
3
+ import { hasExternalCallTimeout, hasMkdirInSameFunction } from './file-context.js';
4
+ import { CODE_EXTS } from './finding.js';
5
+
6
+ /**
7
+ * 单文件审计:读文件 → 跑检查 → 豁免过滤(注册表驱动,7 标记全消费)。
8
+ * 豁免判定:exemptForFinding 统一处理「文件头整文件 / 行内单点」两种位置语义;
9
+ * 外加两类语义豁免:
10
+ * 1) residue/style 检查只对代码文件生效(md/yml 文档里出现 debugger 字样是写作/定义,非残留)
11
+ * 2) 规则定义文件(audit-rules-*.yml)自动豁免规则驱动命中(pattern 字符串被自家 regex 自举命中)
12
+ */
13
+ /**
14
+ * 构建/混淆产物判定(抽导出——审计扩展脚本复用,避免复制判定漂移):
15
+ * ①单行混淆(任一行 >5000 字符——压缩产物);②hash 文件名(Vite/webpack assets
16
+ * *-<HASH>.js 连字符形态 与 *.<HASH>.js / *.<HASH>.chunk.js 点分隔形态(webpack/CRA
17
+ * 标准产物如 runtime-main.d37830b0.js / main.83b810ac.chunk.js)——hash 段 ≥6 字符
18
+ * 大小写混合;纯小写连字符词如 env-compat 非产物);③html 产物(引用 hash 命名
19
+ * 静态资源——<script src="*.HASH.js"> / <link href="*.HASH.css">,docusaurus/CRA
20
+ * 生成的 index.html)。
21
+ * 产物不可改,行级规则(复杂度/魔数/命名/重复)必然爆炸误报——调用方跳过/降级。
22
+ */
23
+ const JS_EXTS = ['js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx'];
24
+
25
+ // DSH 客户端入口推导已迁到**中立模块** lib/audit/client-entry.js(避免
26
+ // dispatch → audit-file → checks → dispatch 的循环依赖);此处**再导出**以保持既有导入路径可用。
27
+ export { resolveDshClientEntries, resolveDshClientFragments } from './client-entry.js';
28
+
29
+ function isMinifiedOneLine(text) {
30
+ let maxLine = 0; let start = 0;
31
+ for (let i = 0; i <= text.length; i++) {
32
+ if (i === text.length || text[i] === '\n') {
33
+ if (i - start > maxLine) maxLine = i - start;
34
+ start = i + 1;
35
+ }
36
+ if (maxLine > 5000) return true;
37
+ }
38
+ return false;
39
+ }
40
+
41
+ /** hash 段判定:≥6 字符且大小写/数字混合([A-Z0-9] 与 [a-z] 都出现——数字算大写侧)。
42
+ * d37830b0 / 83b810ac / CRnoCikG 均通过;纯小写词 env-compat/benchmark 不通过。 */
43
+ function isHashSegment(seg) {
44
+ return Boolean(seg && seg.length >= 6 && /[A-Z0-9]/.test(seg) && /[a-z]/.test(seg));
45
+ }
46
+
47
+ export function isBuildArtifactFile(relPathOrFile = '', text = '') {
48
+ const rel = String(relPathOrFile || '');
49
+ const ext = rel.split('.').pop().toLowerCase();
50
+ if (JS_EXTS.includes(ext) && text && isMinifiedOneLine(text)) return true;
51
+ if (rel.endsWith('.js')) {
52
+ // 连字符形态:*-<HASH>.js 点分隔形态:*.<HASH>.js / *.<HASH>.chunk.js
53
+ const match = rel.match(/(^|[\/])[^\/]+(?:-([A-Za-z0-9]{6,})|\.([A-Za-z0-9]{6,})(?:\.[A-Za-z0-9]+)?)\.js$/);
54
+ if (match && isHashSegment(match[2] || match[3])) return true;
55
+ }
56
+ // html 产物:引用 hash 命名静态资源(docusaurus/CRA 的 index.html——生成物非手写页)。
57
+ // hash 段判定复用 isHashSegment:从引用 URL 末尾提取「主文件名段」(main.83b810ac.chunk.js
58
+ // → 取最后一个 ≥6 混排段 83b810ac;runtime-main.d37830b0.js → d37830b0)。
59
+ if (ext === 'html') {
60
+ // ① 声明了生成器:HTML 标准的 <meta name="generator" content="...">——任何代码生成器
61
+ // (archify / docusaurus / hugo / Sphinx…)都会写它。生成物不可手改,行级规则(内联脚本、
62
+ // 按钮无事件、复杂度…)在它上面必然误报(实测:archify 的自包含产物 813K、内联 <script>
63
+ // 是其**产物形态**,却按「管理界面 XSS」报 error 83 条)。
64
+ // 注意容忍 HTML 允许的写法差异:<meta name="generator"> / <meta name = "generator"> / 单引号。
65
+ if (/<meta\s+[^>]*name\s*=\s*["']generator["']/i.test(String(text || ''))) return true;
66
+ // ② 引用 hash 命名静态资源(docusaurus/CRA 的 index.html——生成物非手写页)。
67
+ // hash 段判定复用 isHashSegment:从引用 URL 末尾提取「主文件名段」(main.83b810ac.chunk.js
68
+ // → 取最后一个 ≥6 混排段 83b810ac;runtime-main.d37830b0.js → d37830b0)。
69
+ const refs = String(text || '').match(/(?:src|href)=["']([^"']+\.(?:js|css))["']/gi) || [];
70
+ if (refs.some((r) => {
71
+ const match = r.match(/([A-Za-z0-9]{6,})(?:\.[A-Za-z0-9]+)*\.(?:js|css)["']?$/);
72
+ if (!match) return false;
73
+ return isHashSegment(match[1]);
74
+ })) return true;
75
+ }
76
+ return false;
77
+ }
78
+
79
+ export function auditFile({ file, relPath, text, grouped }, opts = {}) {
80
+ if (!text) return [];
81
+ const ext = String(relPath || file || '').split('.').pop().toLowerCase();
82
+ const isCode = CODE_EXTS.has(ext);
83
+ // 混淆构建产物识别——Vite/webpack 压缩的 .js 单行可达 10万+ 字符
84
+ // (heroui-kGyYtjDh.js 单行 308K、index-BjhIkylN.js 单行 107K;正常源码最大 ~250)。
85
+ // 这类文件是第三方构建产物(非本项目手写代码),行级规则(复杂度/函数长/魔数/
86
+ // 重复串/命名)在单行 10万字符上必然爆炸误报且无意义(产物不可改)。
87
+ // 处理:跳过行级规则,保留文件级(长度/健康度)与凭据扫描(产物若含真凭据仍报)。
88
+ let isMinified = false;
89
+ if (isCode && (ext === 'js' || ext === 'mjs' || ext === 'cjs' || ext === 'ts' || ext === 'tsx' || ext === 'jsx')) {
90
+ // 判据:任一单行 > 5000 字符(混淆压缩产物)。不要求总大小——41K 的
91
+ // icon-runtime 与 567B 的 rolldown-runtime 都是单行混淆(行长=文件大小);
92
+ // 正常手写代码单行不可能 5000+(实测源码最大 ~250)。
93
+ isMinified = (() => {
94
+ let maxLine = 0; let start = 0;
95
+ for (let i = 0; i <= text.length; i++) {
96
+ if (i === text.length || text[i] === '\n') {
97
+ if (i - start > maxLine) maxLine = i - start;
98
+ start = i + 1;
99
+ }
100
+ if (maxLine > 5000) return true;
101
+ }
102
+ return false;
103
+ })();
104
+ }
105
+ // 构建产物 hash 文件名豁免(Vite/webpack assets:*-<HASH>.js——
106
+ // hash 段大写开头且 ≥6 字符,如 SensitiveMedia-BV5WWa1r.js / AboutPage-fPxR3xhp.js;
107
+ // 不误伤手写文件——env-compat/benchmark 等小写段不匹配)。与单行混淆同层处理:
108
+ // 构建产物非本项目手写代码,行级规则(复杂度/魔数/重复/命名)必然误报且产物不可改。
109
+ const isBuildArtifact = isBuildArtifactFile(relPath || file, text);
110
+ if (isBuildArtifact) {
111
+ // 混淆/构建产物:只保留文件级检查(file-health)+ 凭据/路径安全(产物若含真凭据仍报)。
112
+ // 屏蔽全部行级规则(正则/AST 在单行 10万+ 字符上必然爆炸误报且产物不可改)。
113
+ const scoped = {};
114
+ for (const [kind, rules] of Object.entries(grouped || {})) {
115
+ if (!Array.isArray(rules)) { scoped[kind] = rules; continue; }
116
+ // 保留:凭据类(secret/credential/security 硬编码)+ file-health + max-lines(文件级)
117
+ // empty-catch 屏蔽:混淆单行里 `catch{}` 模式天然密集(压缩产物),不是真实空 catch
118
+ const keep = rules.filter((r) => /^secret-|^cred|security\/no-hardcoded-credentials|security\/no-path-traversal|max-lines|max-file-length/.test(String(r?.id || ''))
119
+ && !/no-empty-catch/.test(String(r?.id || '')));
120
+ if (keep.length) scoped[kind] = keep;
121
+ }
122
+ let findings = runChecks({ file, relPath, text, grouped: scoped }, { level: opts?.level, repoHasJsYamlImport: opts?.repoHasJsYamlImport, repoLevelRules: opts?.repoLevelRules, repoPath: opts?.repoPath });
123
+ // 产物超长是属性非问题;内置行级检查(quality/empty-catch 等)与残余行级规则也屏蔽——
124
+ // 混淆单行 10万+ 字符上 catch{} 等模式天然密集,非真实缺陷。
125
+ const keepRule = /^secret-|^cred|security\/no-hardcoded-credentials|security\/no-path-traversal/; // 构建/混淆产物:健康度(行长/大小)是产物属性非问题,只留凭据/路径安全
126
+ findings = findings.filter((f) => keepRule.test(String(f.rule || '')));
127
+ return findings.filter((f) => exemptForFinding(f, text) === false);
128
+ }
129
+ // 文档/配置(md/yml 等)不做重复串检查:反引号代码段、版本号、路径引用重复属正常书写,
130
+ // 按「硬编码文本」报会造成大面积噪音(maintainability 规则只对代码文件生效)
131
+ // 测试目录同理:fixture 会故意构造重复样本与 mock 值,重复是测试语义的一部分
132
+ const isTestFile = /(^|[/\\])(test|tests|__tests__|spec)[/\\]|\.(test|spec)\.(js|mjs|cjs|ts)$/i.test(String(relPath || file));
133
+ const maintainabilityScoped = !isCode || isTestFile;
134
+ const scopedGrouped = maintainabilityScoped ? { ...grouped, 'repeated-string': undefined, 'min-occurrences': undefined } : grouped;
135
+ let findings = runChecks({ file, relPath, text, grouped: scopedGrouped }, { level: opts?.level, repoHasJsYamlImport: opts?.repoHasJsYamlImport, repoLevelRules: opts?.repoLevelRules, repoPath: opts?.repoPath });
136
+ const isRuleDefFile = /(^|[/\\])audit-rules-[a-z0-9-]+\.ya?ml$/i.test(String(relPath || file));
137
+ const fileLines = String(text || '').split('\n');
138
+ // 语义级豁免:纯 regex 规则看不到的上下文在此兜底——
139
+ // 1) timeout-on-external-api:命中调用内已设 AbortSignal.timeout/AbortController/timeout
140
+ // 2) client-module-loader-id:文件已按 window.__ModuleLoader__ 的 load 契约({id, factory} 模块表)注册
141
+ // (pattern 匹配到的是契约调用本身;规则本意是「缺契约才报」,已用契约即通过)
142
+ const hasLoaderContract = /window\.__ModuleLoader__\.load\s*\(\s*\{\s*id\s*:/.test(text);
143
+ // 豁免过滤(dsh-skip-* 注册表统一消费,覆盖 sensitive/size/func-length/syntax/quality/residue/style)
144
+ findings = findings.filter((f) => {
145
+ // 规则定义文件:规则驱动命中(secret/regex/path-regex/func-lines 等 yml 规则)全豁免
146
+ if (isRuleDefFile && f.rule !== 'quality/empty-catch' && f.rule !== 'robustness/io-risk') return false;
147
+ // 技能/规则文档豁免:skills/ 下的 skill 文档与 rules/ 文档里的
148
+ // 沟通措辞是「触发场景/规则描述」设计文本(如 whenToUse 触发场景描述),非代码残留——comment 规则不拦;
149
+ // version 规则同理:版本规则文档自身描述 0.x 例外(如 versioning-rule §二「内置模块从 0 开始」),
150
+ // 文档里的版本号示例是规则文本而非违规版本标记
151
+ const isSkillDoc = /(^|[/\\])skills([/\\]|$)/.test(String(relPath || file));
152
+ const isRulesDoc = /(^|[/\\])rules([/\\]|$)/.test(String(relPath || file));
153
+ const isCommentRule = f.rule === 'documentation/comment-suspicious-detection' || /^conv-/.test(f.rule || '');
154
+ const isVersionDocRule = /^version\//.test(f.rule || '');
155
+ if ((isSkillDoc || isRulesDoc) && !isCode && (isCommentRule || isVersionDocRule)) return false;
156
+ // residue/style:非代码文件豁免(文档/配置里的 debugger/console/风格字样非残留)
157
+ if (!isCode && (f.kind === 'regex')) {
158
+ const residueLike = /debugger|console|todo/i.test(f.rule);
159
+ if (residueLike) return false;
160
+ }
161
+ // timeout 语义豁免:外部调用已设超时
162
+ if (f.rule === 'robustness/timeout-on-external-api') {
163
+ const idx = Math.max(0, (Number(f.line) || 1) - 1);
164
+ if (hasExternalCallTimeout(fileLines[idx] || '', fileLines, idx)) return false;
165
+ // githubFetch 是唯一网络出口(api.js),内部统一 AbortSignal.timeout(timeout) 默认 60s——
166
+ // 调用处无需重复设置(纯 regex 规则看不到包装内部)
167
+ if (/githubFetch\s*\(/.test(fileLines[idx] || '')) return false;
168
+ }
169
+ // mkdir 语义豁免:写文件前同函数已建目录(ensureDataDir 模式)
170
+ if (f.rule === 'robustness/mkdir-before-write') {
171
+ const idx = Math.max(0, (Number(f.line) || 1) - 1);
172
+ if (hasMkdirInSameFunction(fileLines, idx)) return false;
173
+ }
174
+ // loader 契约语义豁免:已按统一 ModuleLoader 契约注册
175
+ if (f.rule === 'dsh/client-module-loader-id' && hasLoaderContract) return false;
176
+ // DSH 插件语义豁免:name 以 dsh- 开头的插件不发布 npm(工作区/市场安装),
177
+ // private:true 是刻意配置(防误发布),npm/private-true-conflict 不报
178
+ if (f.rule === 'npm/private-true-conflict' && /"name"\s*:\s*"dsh-/.test(text)) return false;
179
+ return !exemptForFinding(f, text);
180
+ });
181
+ return findings;
182
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * 审计检查器入口(纯引用文件)
3
+ *
4
+ * ⚠️ 本文件**只写引用**,不含任何实现——保留它只为两点:
5
+ * ① 调用方(lib/audit/index.js 与各测试)继续 `from './checks.js'` 导入,路径稳定;
6
+ * ② 作为「检查层」的显式入口,一眼看出检查器从哪来。
7
+ *
8
+ * 实现已按职责分到两个目录:
9
+ * lib/ast/* 具体实现(token 级解析:注释/字符串/模板串感知)
10
+ * lib/checks/* 调用包装(把 AST 判定转成统一 finding;调度在 checks/dispatch.js)
11
+ *
12
+ * 加/改检查逻辑请去对应目录,不要在本文件实现(此处已无实现可加)。
13
+ * 三层架构:① 规则声明 lib/audit-rules/*.yml → ② 实现 lib/ast/* → ③ 包装 lib/checks/*;
14
+ * 本文件与 lib/audit/index.js 属编排层。
15
+ */
16
+
17
+ export * from '../checks/index.js';