@cybedefend/vibedefend 1.8.2 → 1.9.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 (328) hide show
  1. package/README.md +185 -17
  2. package/dist/auth/auth-store.js +16 -0
  3. package/dist/auth/auth-store.js.map +1 -1
  4. package/dist/clients/antigravity.js +30 -6
  5. package/dist/clients/antigravity.js.map +1 -1
  6. package/dist/clients/claude-code.js +209 -17
  7. package/dist/clients/claude-code.js.map +1 -1
  8. package/dist/clients/codex.js +171 -11
  9. package/dist/clients/codex.js.map +1 -1
  10. package/dist/clients/cursor.js +149 -9
  11. package/dist/clients/cursor.js.map +1 -1
  12. package/dist/clients/dependency-check-wiring.js +24 -0
  13. package/dist/clients/dependency-check-wiring.js.map +1 -0
  14. package/dist/clients/opencode-plugin.js +905 -0
  15. package/dist/clients/opencode-plugin.js.map +1 -0
  16. package/dist/clients/opencode.js +653 -0
  17. package/dist/clients/opencode.js.map +1 -0
  18. package/dist/clients/registry.js +2 -0
  19. package/dist/clients/registry.js.map +1 -1
  20. package/dist/clients/vscode.js +106 -12
  21. package/dist/clients/vscode.js.map +1 -1
  22. package/dist/clients/windsurf.js +9 -1
  23. package/dist/clients/windsurf.js.map +1 -1
  24. package/dist/commands/mcp/index.js +11 -0
  25. package/dist/commands/mcp/index.js.map +1 -1
  26. package/dist/config.js +4 -1
  27. package/dist/config.js.map +1 -1
  28. package/dist/diagnostics.js +22 -3
  29. package/dist/diagnostics.js.map +1 -1
  30. package/dist/doctor.js +26 -1
  31. package/dist/doctor.js.map +1 -1
  32. package/dist/guards-evaluator/command-analysis.js +347 -86
  33. package/dist/guards-evaluator/command-analysis.js.map +1 -1
  34. package/dist/guards-evaluator/command-view.js +116 -16
  35. package/dist/guards-evaluator/command-view.js.map +1 -1
  36. package/dist/guards-evaluator/evaluate.js +185 -41
  37. package/dist/guards-evaluator/evaluate.js.map +1 -1
  38. package/dist/guards-evaluator/file-reads.js +202 -0
  39. package/dist/guards-evaluator/file-reads.js.map +1 -0
  40. package/dist/guards-evaluator/index.js +1 -1
  41. package/dist/guards-evaluator/index.js.map +1 -1
  42. package/dist/guards-evaluator/inline-danger.js +299 -0
  43. package/dist/guards-evaluator/inline-danger.js.map +1 -0
  44. package/dist/guards-evaluator/normalize.js +1186 -55
  45. package/dist/guards-evaluator/normalize.js.map +1 -1
  46. package/dist/guards-evaluator/regex.js +91 -4
  47. package/dist/guards-evaluator/regex.js.map +1 -1
  48. package/dist/guards-evaluator/shell-files.js +587 -0
  49. package/dist/guards-evaluator/shell-files.js.map +1 -0
  50. package/dist/guards-evaluator/triage.js +32 -2
  51. package/dist/guards-evaluator/triage.js.map +1 -1
  52. package/dist/hook-runner.js +25601 -5423
  53. package/dist/hooks/install.js +8 -3
  54. package/dist/hooks/install.js.map +1 -1
  55. package/dist/hooks/runtime/antigravity-session.js +109 -50
  56. package/dist/hooks/runtime/antigravity-session.js.map +1 -1
  57. package/dist/hooks/runtime/apply-patch.js +92 -0
  58. package/dist/hooks/runtime/apply-patch.js.map +1 -0
  59. package/dist/hooks/runtime/caller-gate.js +27 -0
  60. package/dist/hooks/runtime/caller-gate.js.map +1 -0
  61. package/dist/hooks/runtime/code-mode.js +259 -0
  62. package/dist/hooks/runtime/code-mode.js.map +1 -0
  63. package/dist/hooks/runtime/dependency-check/api.js +179 -0
  64. package/dist/hooks/runtime/dependency-check/api.js.map +1 -0
  65. package/dist/hooks/runtime/dependency-check/capabilities.js +99 -0
  66. package/dist/hooks/runtime/dependency-check/capabilities.js.map +1 -0
  67. package/dist/hooks/runtime/dependency-check/checked-packages.js +48 -0
  68. package/dist/hooks/runtime/dependency-check/checked-packages.js.map +1 -0
  69. package/dist/hooks/runtime/dependency-check/commands/cwd.js +154 -0
  70. package/dist/hooks/runtime/dependency-check/commands/cwd.js.map +1 -0
  71. package/dist/hooks/runtime/dependency-check/commands/env.js +99 -0
  72. package/dist/hooks/runtime/dependency-check/commands/env.js.map +1 -0
  73. package/dist/hooks/runtime/dependency-check/commands/flags.js +164 -0
  74. package/dist/hooks/runtime/dependency-check/commands/flags.js.map +1 -0
  75. package/dist/hooks/runtime/dependency-check/commands/managers.js +418 -0
  76. package/dist/hooks/runtime/dependency-check/commands/managers.js.map +1 -0
  77. package/dist/hooks/runtime/dependency-check/commands/peel.js +111 -0
  78. package/dist/hooks/runtime/dependency-check/commands/peel.js.map +1 -0
  79. package/dist/hooks/runtime/dependency-check/commands/shell.js +217 -0
  80. package/dist/hooks/runtime/dependency-check/commands/shell.js.map +1 -0
  81. package/dist/hooks/runtime/dependency-check/commands/types.js +4 -0
  82. package/dist/hooks/runtime/dependency-check/commands/types.js.map +1 -0
  83. package/dist/hooks/runtime/dependency-check/commands.js +34 -0
  84. package/dist/hooks/runtime/dependency-check/commands.js.map +1 -0
  85. package/dist/hooks/runtime/dependency-check/deadlines.js +69 -0
  86. package/dist/hooks/runtime/dependency-check/deadlines.js.map +1 -0
  87. package/dist/hooks/runtime/dependency-check/dispatch.js +344 -0
  88. package/dist/hooks/runtime/dependency-check/dispatch.js.map +1 -0
  89. package/dist/hooks/runtime/dependency-check/entering.js +63 -0
  90. package/dist/hooks/runtime/dependency-check/entering.js.map +1 -0
  91. package/dist/hooks/runtime/dependency-check/exec-cache.js +36 -0
  92. package/dist/hooks/runtime/dependency-check/exec-cache.js.map +1 -0
  93. package/dist/hooks/runtime/dependency-check/git-blob.js +116 -0
  94. package/dist/hooks/runtime/dependency-check/git-blob.js.map +1 -0
  95. package/dist/hooks/runtime/dependency-check/hook.js +418 -0
  96. package/dist/hooks/runtime/dependency-check/hook.js.map +1 -0
  97. package/dist/hooks/runtime/dependency-check/local-store.js +74 -0
  98. package/dist/hooks/runtime/dependency-check/local-store.js.map +1 -0
  99. package/dist/hooks/runtime/dependency-check/lockfile-walk.js +89 -0
  100. package/dist/hooks/runtime/dependency-check/lockfile-walk.js.map +1 -0
  101. package/dist/hooks/runtime/dependency-check/lockfiles/bun.js +153 -0
  102. package/dist/hooks/runtime/dependency-check/lockfiles/bun.js.map +1 -0
  103. package/dist/hooks/runtime/dependency-check/lockfiles/by-name.js +46 -0
  104. package/dist/hooks/runtime/dependency-check/lockfiles/by-name.js.map +1 -0
  105. package/dist/hooks/runtime/dependency-check/lockfiles/cargo.js +91 -0
  106. package/dist/hooks/runtime/dependency-check/lockfiles/cargo.js.map +1 -0
  107. package/dist/hooks/runtime/dependency-check/lockfiles/composer.js +98 -0
  108. package/dist/hooks/runtime/dependency-check/lockfiles/composer.js.map +1 -0
  109. package/dist/hooks/runtime/dependency-check/lockfiles/gemfile.js +88 -0
  110. package/dist/hooks/runtime/dependency-check/lockfiles/gemfile.js.map +1 -0
  111. package/dist/hooks/runtime/dependency-check/lockfiles/go-mod.js +154 -0
  112. package/dist/hooks/runtime/dependency-check/lockfiles/go-mod.js.map +1 -0
  113. package/dist/hooks/runtime/dependency-check/lockfiles/gradle-lockfile.js +27 -0
  114. package/dist/hooks/runtime/dependency-check/lockfiles/gradle-lockfile.js.map +1 -0
  115. package/dist/hooks/runtime/dependency-check/lockfiles/graph.js +131 -0
  116. package/dist/hooks/runtime/dependency-check/lockfiles/graph.js.map +1 -0
  117. package/dist/hooks/runtime/dependency-check/lockfiles/npm.js +107 -0
  118. package/dist/hooks/runtime/dependency-check/lockfiles/npm.js.map +1 -0
  119. package/dist/hooks/runtime/dependency-check/lockfiles/nuget-packages-lock.js +60 -0
  120. package/dist/hooks/runtime/dependency-check/lockfiles/nuget-packages-lock.js.map +1 -0
  121. package/dist/hooks/runtime/dependency-check/lockfiles/pins.js +105 -0
  122. package/dist/hooks/runtime/dependency-check/lockfiles/pins.js.map +1 -0
  123. package/dist/hooks/runtime/dependency-check/lockfiles/pip-report.js +34 -0
  124. package/dist/hooks/runtime/dependency-check/lockfiles/pip-report.js.map +1 -0
  125. package/dist/hooks/runtime/dependency-check/lockfiles/pnpm.js +109 -0
  126. package/dist/hooks/runtime/dependency-check/lockfiles/pnpm.js.map +1 -0
  127. package/dist/hooks/runtime/dependency-check/lockfiles/poetry.js +105 -0
  128. package/dist/hooks/runtime/dependency-check/lockfiles/poetry.js.map +1 -0
  129. package/dist/hooks/runtime/dependency-check/lockfiles/uv.js +181 -0
  130. package/dist/hooks/runtime/dependency-check/lockfiles/uv.js.map +1 -0
  131. package/dist/hooks/runtime/dependency-check/lockfiles/yaml.js +319 -0
  132. package/dist/hooks/runtime/dependency-check/lockfiles/yaml.js.map +1 -0
  133. package/dist/hooks/runtime/dependency-check/lockfiles/yarn-berry.js +71 -0
  134. package/dist/hooks/runtime/dependency-check/lockfiles/yarn-berry.js.map +1 -0
  135. package/dist/hooks/runtime/dependency-check/lockfiles/yarn1.js +144 -0
  136. package/dist/hooks/runtime/dependency-check/lockfiles/yarn1.js.map +1 -0
  137. package/dist/hooks/runtime/dependency-check/manifests/apply.js +110 -0
  138. package/dist/hooks/runtime/dependency-check/manifests/apply.js.map +1 -0
  139. package/dist/hooks/runtime/dependency-check/manifests/diff.js +127 -0
  140. package/dist/hooks/runtime/dependency-check/manifests/diff.js.map +1 -0
  141. package/dist/hooks/runtime/dependency-check/manifests/edit.js +259 -0
  142. package/dist/hooks/runtime/dependency-check/manifests/edit.js.map +1 -0
  143. package/dist/hooks/runtime/dependency-check/manifests/json.js +109 -0
  144. package/dist/hooks/runtime/dependency-check/manifests/json.js.map +1 -0
  145. package/dist/hooks/runtime/dependency-check/manifests/kind.js +40 -0
  146. package/dist/hooks/runtime/dependency-check/manifests/kind.js.map +1 -0
  147. package/dist/hooks/runtime/dependency-check/manifests/patch.js +179 -0
  148. package/dist/hooks/runtime/dependency-check/manifests/patch.js.map +1 -0
  149. package/dist/hooks/runtime/dependency-check/manifests/text.js +665 -0
  150. package/dist/hooks/runtime/dependency-check/manifests/text.js.map +1 -0
  151. package/dist/hooks/runtime/dependency-check/manifests/toml.js +350 -0
  152. package/dist/hooks/runtime/dependency-check/manifests/toml.js.map +1 -0
  153. package/dist/hooks/runtime/dependency-check/manifests.js +14 -0
  154. package/dist/hooks/runtime/dependency-check/manifests.js.map +1 -0
  155. package/dist/hooks/runtime/dependency-check/messages.js +270 -0
  156. package/dist/hooks/runtime/dependency-check/messages.js.map +1 -0
  157. package/dist/hooks/runtime/dependency-check/net-baseline.js +157 -0
  158. package/dist/hooks/runtime/dependency-check/net-baseline.js.map +1 -0
  159. package/dist/hooks/runtime/dependency-check/net-state.js +70 -0
  160. package/dist/hooks/runtime/dependency-check/net-state.js.map +1 -0
  161. package/dist/hooks/runtime/dependency-check/pending-forces.js +54 -0
  162. package/dist/hooks/runtime/dependency-check/pending-forces.js.map +1 -0
  163. package/dist/hooks/runtime/dependency-check/post-tool-use.js +108 -0
  164. package/dist/hooks/runtime/dependency-check/post-tool-use.js.map +1 -0
  165. package/dist/hooks/runtime/dependency-check/ranges.js +369 -0
  166. package/dist/hooks/runtime/dependency-check/ranges.js.map +1 -0
  167. package/dist/hooks/runtime/dependency-check/requirement-files.js +144 -0
  168. package/dist/hooks/runtime/dependency-check/requirement-files.js.map +1 -0
  169. package/dist/hooks/runtime/dependency-check/resolvers/bun.js +38 -0
  170. package/dist/hooks/runtime/dependency-check/resolvers/bun.js.map +1 -0
  171. package/dist/hooks/runtime/dependency-check/resolvers/bundler.js +218 -0
  172. package/dist/hooks/runtime/dependency-check/resolvers/bundler.js.map +1 -0
  173. package/dist/hooks/runtime/dependency-check/resolvers/cargo.js +303 -0
  174. package/dist/hooks/runtime/dependency-check/resolvers/cargo.js.map +1 -0
  175. package/dist/hooks/runtime/dependency-check/resolvers/composer.js +250 -0
  176. package/dist/hooks/runtime/dependency-check/resolvers/composer.js.map +1 -0
  177. package/dist/hooks/runtime/dependency-check/resolvers/config-files.js +27 -0
  178. package/dist/hooks/runtime/dependency-check/resolvers/config-files.js.map +1 -0
  179. package/dist/hooks/runtime/dependency-check/resolvers/direct-only-registry.js +409 -0
  180. package/dist/hooks/runtime/dependency-check/resolvers/direct-only-registry.js.map +1 -0
  181. package/dist/hooks/runtime/dependency-check/resolvers/direct-only.js +290 -0
  182. package/dist/hooks/runtime/dependency-check/resolvers/direct-only.js.map +1 -0
  183. package/dist/hooks/runtime/dependency-check/resolvers/gem.js +89 -0
  184. package/dist/hooks/runtime/dependency-check/resolvers/gem.js.map +1 -0
  185. package/dist/hooks/runtime/dependency-check/resolvers/go.js +313 -0
  186. package/dist/hooks/runtime/dependency-check/resolvers/go.js.map +1 -0
  187. package/dist/hooks/runtime/dependency-check/resolvers/npm.js +81 -0
  188. package/dist/hooks/runtime/dependency-check/resolvers/npm.js.map +1 -0
  189. package/dist/hooks/runtime/dependency-check/resolvers/pip.js +229 -0
  190. package/dist/hooks/runtime/dependency-check/resolvers/pip.js.map +1 -0
  191. package/dist/hooks/runtime/dependency-check/resolvers/pipx.js +8 -0
  192. package/dist/hooks/runtime/dependency-check/resolvers/pipx.js.map +1 -0
  193. package/dist/hooks/runtime/dependency-check/resolvers/pnpm.js +68 -0
  194. package/dist/hooks/runtime/dependency-check/resolvers/pnpm.js.map +1 -0
  195. package/dist/hooks/runtime/dependency-check/resolvers/poetry.js +70 -0
  196. package/dist/hooks/runtime/dependency-check/resolvers/poetry.js.map +1 -0
  197. package/dist/hooks/runtime/dependency-check/resolvers/project.js +208 -0
  198. package/dist/hooks/runtime/dependency-check/resolvers/project.js.map +1 -0
  199. package/dist/hooks/runtime/dependency-check/resolvers/python-index.js +270 -0
  200. package/dist/hooks/runtime/dependency-check/resolvers/python-index.js.map +1 -0
  201. package/dist/hooks/runtime/dependency-check/resolvers/python.js +229 -0
  202. package/dist/hooks/runtime/dependency-check/resolvers/python.js.map +1 -0
  203. package/dist/hooks/runtime/dependency-check/resolvers/registry.js +221 -0
  204. package/dist/hooks/runtime/dependency-check/resolvers/registry.js.map +1 -0
  205. package/dist/hooks/runtime/dependency-check/resolvers/shared.js +440 -0
  206. package/dist/hooks/runtime/dependency-check/resolvers/shared.js.map +1 -0
  207. package/dist/hooks/runtime/dependency-check/resolvers/tree.js +131 -0
  208. package/dist/hooks/runtime/dependency-check/resolvers/tree.js.map +1 -0
  209. package/dist/hooks/runtime/dependency-check/resolvers/uv.js +433 -0
  210. package/dist/hooks/runtime/dependency-check/resolvers/uv.js.map +1 -0
  211. package/dist/hooks/runtime/dependency-check/resolvers/xml-lite.js +132 -0
  212. package/dist/hooks/runtime/dependency-check/resolvers/xml-lite.js.map +1 -0
  213. package/dist/hooks/runtime/dependency-check/resolvers/yarn-berry.js +106 -0
  214. package/dist/hooks/runtime/dependency-check/resolvers/yarn-berry.js.map +1 -0
  215. package/dist/hooks/runtime/dependency-check/sandbox.js +328 -0
  216. package/dist/hooks/runtime/dependency-check/sandbox.js.map +1 -0
  217. package/dist/hooks/runtime/dependency-check/specs.js +171 -0
  218. package/dist/hooks/runtime/dependency-check/specs.js.map +1 -0
  219. package/dist/hooks/runtime/dependency-check/static-view.js +90 -0
  220. package/dist/hooks/runtime/dependency-check/static-view.js.map +1 -0
  221. package/dist/hooks/runtime/dependency-check/stop-net.js +278 -0
  222. package/dist/hooks/runtime/dependency-check/stop-net.js.map +1 -0
  223. package/dist/hooks/runtime/dependency-check/stop-wiring.js +94 -0
  224. package/dist/hooks/runtime/dependency-check/stop-wiring.js.map +1 -0
  225. package/dist/hooks/runtime/dependency-check/tool-call.js +130 -0
  226. package/dist/hooks/runtime/dependency-check/tool-call.js.map +1 -0
  227. package/dist/hooks/runtime/dependency-check/types.js +96 -0
  228. package/dist/hooks/runtime/dependency-check/types.js.map +1 -0
  229. package/dist/hooks/runtime/emit.js +240 -52
  230. package/dist/hooks/runtime/emit.js.map +1 -1
  231. package/dist/hooks/runtime/exit-deadlock-guard.js +24 -8
  232. package/dist/hooks/runtime/exit-deadlock-guard.js.map +1 -1
  233. package/dist/hooks/runtime/fetch-rules.js +78 -29
  234. package/dist/hooks/runtime/fetch-rules.js.map +1 -1
  235. package/dist/hooks/runtime/grep-include.js +228 -0
  236. package/dist/hooks/runtime/grep-include.js.map +1 -0
  237. package/dist/hooks/runtime/pre-compact.js +1 -1
  238. package/dist/hooks/runtime/pre-compact.js.map +1 -1
  239. package/dist/hooks/runtime/pre-invocation.js +3 -3
  240. package/dist/hooks/runtime/pre-invocation.js.map +1 -1
  241. package/dist/hooks/runtime/repo-registry.js +72 -0
  242. package/dist/hooks/runtime/repo-registry.js.map +1 -0
  243. package/dist/hooks/runtime/repo-scope.js +75 -0
  244. package/dist/hooks/runtime/repo-scope.js.map +1 -0
  245. package/dist/hooks/runtime/resolve.js +11 -2
  246. package/dist/hooks/runtime/resolve.js.map +1 -1
  247. package/dist/hooks/runtime/runner-args.js +17 -2
  248. package/dist/hooks/runtime/runner-args.js.map +1 -1
  249. package/dist/hooks/runtime/script-resolve.js +21 -5
  250. package/dist/hooks/runtime/script-resolve.js.map +1 -1
  251. package/dist/hooks/runtime/session-activation.js +71 -18
  252. package/dist/hooks/runtime/session-activation.js.map +1 -1
  253. package/dist/hooks/runtime/session-review.js +184 -88
  254. package/dist/hooks/runtime/session-review.js.map +1 -1
  255. package/dist/hooks/runtime/session-start.js +68 -13
  256. package/dist/hooks/runtime/session-start.js.map +1 -1
  257. package/dist/hooks/runtime/session-writes.js +11 -5
  258. package/dist/hooks/runtime/session-writes.js.map +1 -1
  259. package/dist/hooks/runtime/shell-writes.js +7 -88
  260. package/dist/hooks/runtime/shell-writes.js.map +1 -1
  261. package/dist/hooks/runtime/sniff.js +227 -2
  262. package/dist/hooks/runtime/sniff.js.map +1 -1
  263. package/dist/hooks/runtime/target-resolve.js +32 -17
  264. package/dist/hooks/runtime/target-resolve.js.map +1 -1
  265. package/dist/hooks/runtime/unmapped-tools.js +77 -1
  266. package/dist/hooks/runtime/unmapped-tools.js.map +1 -1
  267. package/dist/hooks/runtime/user-prompt-submit.js +1 -1
  268. package/dist/hooks/runtime/user-prompt-submit.js.map +1 -1
  269. package/dist/hooks/runtime/work-dir.js +3 -0
  270. package/dist/hooks/runtime/work-dir.js.map +1 -1
  271. package/dist/hooks/shim.js +27 -20
  272. package/dist/hooks/shim.js.map +1 -1
  273. package/dist/index.js +46 -10
  274. package/dist/index.js.map +1 -1
  275. package/dist/install-scope.js +12 -0
  276. package/dist/install-scope.js.map +1 -0
  277. package/dist/install.js +188 -78
  278. package/dist/install.js.map +1 -1
  279. package/dist/link.js +55 -5
  280. package/dist/link.js.map +1 -1
  281. package/dist/mcp/config/hook.js +25 -0
  282. package/dist/mcp/config/hook.js.map +1 -1
  283. package/dist/org.js +3 -1
  284. package/dist/org.js.map +1 -1
  285. package/dist/prompts.js +97 -13
  286. package/dist/prompts.js.map +1 -1
  287. package/dist/refresh-hooks.js +67 -15
  288. package/dist/refresh-hooks.js.map +1 -1
  289. package/dist/repo/exclude-block.js +112 -0
  290. package/dist/repo/exclude-block.js.map +1 -0
  291. package/dist/repo/footer.js +93 -0
  292. package/dist/repo/footer.js.map +1 -0
  293. package/dist/repo/git-repo.js +77 -0
  294. package/dist/repo/git-repo.js.map +1 -0
  295. package/dist/repo/guarded-write.js +45 -0
  296. package/dist/repo/guarded-write.js.map +1 -0
  297. package/dist/repo/install-repo.js +508 -0
  298. package/dist/repo/install-repo.js.map +1 -0
  299. package/dist/repo/machine-wiring.js +122 -0
  300. package/dist/repo/machine-wiring.js.map +1 -0
  301. package/dist/repo/mcp-json.js +57 -0
  302. package/dist/repo/mcp-json.js.map +1 -0
  303. package/dist/repo/registry.js +53 -0
  304. package/dist/repo/registry.js.map +1 -0
  305. package/dist/repo/repo-mode-guard.js +83 -0
  306. package/dist/repo/repo-mode-guard.js.map +1 -0
  307. package/dist/repo/repo-setups.js +123 -0
  308. package/dist/repo/repo-setups.js.map +1 -0
  309. package/dist/repo/repo-status.js +283 -0
  310. package/dist/repo/repo-status.js.map +1 -0
  311. package/dist/repo/uninstall-repo.js +56 -0
  312. package/dist/repo/uninstall-repo.js.map +1 -0
  313. package/dist/repo/unsupported.js +14 -0
  314. package/dist/repo/unsupported.js.map +1 -0
  315. package/dist/scan-diff.js +526 -0
  316. package/dist/scan-diff.js.map +1 -0
  317. package/dist/shim.js +9 -7
  318. package/dist/status.js +53 -11
  319. package/dist/status.js.map +1 -1
  320. package/dist/uninstall.js +51 -3
  321. package/dist/uninstall.js.map +1 -1
  322. package/dist/update-check-gate.js +17 -0
  323. package/dist/update-check-gate.js.map +1 -0
  324. package/dist/update.js +6 -1
  325. package/dist/update.js.map +1 -1
  326. package/dist/zip.js +95 -0
  327. package/dist/zip.js.map +1 -0
  328. package/package.json +6 -3
@@ -9,6 +9,14 @@
9
9
  * rewrites so a downstream triage pass (triage.ts) can reason about what runs,
10
10
  * not about how it was spelled.
11
11
  *
12
+ * It also follows what the command says about ITSELF:
13
+ * - a shell keyword in front of a command (`then rm …`, `do cat …`);
14
+ * - a variable assigned earlier in the same command (`X=rm; $X -rf ~`, the
15
+ * values of `for f in a b`), never one that comes from the environment;
16
+ * - text piped to a shell (`echo "rm -rf ~" | bash`) and words piped to
17
+ * xargs (`echo .env | xargs cat`);
18
+ * - a here-string fed to a shell (`bash <<< "…"`).
19
+ *
12
20
  * Design contract (see analysis-types.ts):
13
21
  * - PURE: no I/O, no network, no clock. Disk resolution lives elsewhere.
14
22
  * - NEVER THROWS: any blindness (unbalanced quotes, an indirect executable,
@@ -31,6 +39,8 @@ const MAX_DEPTH = 3;
31
39
  const MAX_COMMANDS = 256;
32
40
  /** Hard ceiling on substitutions pulled from one command. */
33
41
  const MAX_SUBST = 64;
42
+ /** Hard ceiling on the substitution texts kept (for the script reader and the inline code), all depths together. */
43
+ const MAX_SUBST_KEPT = 64;
34
44
  /** The stored `raw` field is bounded; the tokenizer still sees the full text. */
35
45
  const RAW_CLIP = 2000;
36
46
  /** env function for shell-quote: keep `$VAR` as the literal `$VAR`. */
@@ -68,6 +78,19 @@ const TRANSPARENT_PREFIXES = new Set([
68
78
  'setsid',
69
79
  'env',
70
80
  ]);
81
+ /**
82
+ * Shell keywords that stand in front of the command they run: `then rm …`,
83
+ * `do cat …`, `if ! curl …`, `{ rm …; }`.
84
+ */
85
+ const KEYWORD_PREFIXES = new Set(['then', 'do', 'else', 'elif', 'if', 'while', 'until', '!', '{']);
86
+ /** Builtins that declare variables: `export X=1`, `local X=1`. */
87
+ const DECLARATION_BUILTINS = new Set(['export', 'local', 'readonly', 'declare', 'typeset']);
88
+ /** Commands whose arguments are the text they write to a pipe. */
89
+ const TEXT_WRITERS = new Set(['echo', 'printf']);
90
+ /** Shells that run what they read on stdin when given no script. */
91
+ const STDIN_SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'ash', 'fish']);
92
+ /** At most this many values of one `for` loop are followed. */
93
+ const MAX_LOOP_VALUES = 8;
71
94
  /**
72
95
  * Per-prefix options that CONSUME the following token as their value, so the
73
96
  * peeler does not mistake that value for the wrapped command. e.g. in
@@ -88,6 +111,39 @@ const PREFIX_VALUE_OPTS = {
88
111
  nohup: new Set(),
89
112
  setsid: new Set(),
90
113
  };
114
+ /**
115
+ * `wsl [options] [--] <command>` runs the command in a WSL distribution, as
116
+ * `sudo` runs one as root. These options take a value; `-e`, `--exec` and
117
+ * `--system` take none. Any other option (`--unregister`, `--list`,
118
+ * `--shutdown`, `--export`…) manages the distributions: `wsl` is then the
119
+ * command itself.
120
+ */
121
+ const WSL_VALUE_OPTS = new Set(['-d', '--distribution', '-u', '--user', '--cd', '--shell-type', '--distribution-id']);
122
+ const WSL_FLAG_OPTS = new Set(['-e', '--exec', '--system']);
123
+ /**
124
+ * Where the command `wsl` runs starts in `argv` (at `at`), or -1 when `wsl`
125
+ * runs no command: a management option, or nothing after the options.
126
+ */
127
+ function wslCommandStart(argv, at) {
128
+ let i = at + 1;
129
+ while (i < argv.length) {
130
+ const a = argv[i];
131
+ if (a === '--')
132
+ return i + 1 < argv.length ? i + 1 : -1;
133
+ if (WSL_VALUE_OPTS.has(a)) {
134
+ i += 2;
135
+ continue;
136
+ }
137
+ if (WSL_FLAG_OPTS.has(a)) {
138
+ i++;
139
+ continue;
140
+ }
141
+ if (a.startsWith('-'))
142
+ return -1;
143
+ return i;
144
+ }
145
+ return -1;
146
+ }
91
147
  /** `xargs` options that consume the following token as their value. */
92
148
  const XARGS_VALUE_OPTS = new Set([
93
149
  '-I', '--replace', '-n', '--max-args', '-L', '--max-lines', '-P',
@@ -143,6 +199,33 @@ function tokenText(t) {
143
199
  return t.pattern;
144
200
  return null;
145
201
  }
202
+ /** Whether a segment holds a subshell parenthesis and/or a `$( … )` substitution. */
203
+ function parenKinds(tokens) {
204
+ let subshell = false;
205
+ let substitution = false;
206
+ let depth = 0;
207
+ for (let i = 0; i < tokens.length; i++) {
208
+ const tok = tokens[i];
209
+ if (!isOperator(tok))
210
+ continue;
211
+ if (tok.op === '(') {
212
+ const prev = tokens[i - 1];
213
+ if (prev === '$' || (typeof prev === 'string' && prev.endsWith('$'))) {
214
+ substitution = true; // `$(`, or `X=$(`
215
+ depth++;
216
+ }
217
+ else if (depth === 0)
218
+ subshell = true;
219
+ }
220
+ else if (tok.op === ')') {
221
+ if (depth > 0)
222
+ depth--;
223
+ else
224
+ subshell = true;
225
+ }
226
+ }
227
+ return { subshell, substitution };
228
+ }
146
229
  function clip(s, n) {
147
230
  return s.length > n ? s.slice(0, n) : s;
148
231
  }
@@ -162,16 +245,18 @@ function emit(acc, cmd) {
162
245
  function isIndirect(tok) {
163
246
  return /^\$/.test(tok) || tok.includes('`');
164
247
  }
248
+ /** Extensions Windows runs a program by without naming them (PATHEXT). */
249
+ const WINDOWS_PROGRAM_EXT = /\.(?:exe|cmd|bat|com)$/;
165
250
  /**
166
- * Canonical executable name: strip the directory, strip a single leading
167
- * backslash, lower-case the basename. `/usr/bin/rm` → `rm`, `\rm` → `rm`,
168
- * `RM` → `rm`.
251
+ * Canonical executable name: strip the directory (`/` or `\`), lower-case the
252
+ * basename, drop a Windows program extension. `/usr/bin/rm` → `rm`, `\rm` →
253
+ * `rm`, `RM` → `rm`, `C:\Program Files\Git\cmd\git.exe` → `git`, `npm.cmd` →
254
+ * `npm`. Every module that compares an executable name uses this one.
169
255
  */
170
- function canonicalExec(raw) {
171
- let base = raw.split('/').pop() ?? raw;
172
- if (base.startsWith('\\'))
173
- base = base.slice(1);
174
- return base.toLowerCase();
256
+ export function canonicalExec(raw) {
257
+ const base = (raw.split(/[\\/]/).pop() ?? raw).toLowerCase();
258
+ const stripped = base.replace(WINDOWS_PROGRAM_EXT, '');
259
+ return stripped === '' ? base : stripped;
175
260
  }
176
261
  /**
177
262
  * Peel leading `VAR=value` assignments and transparent wrappers (`sudo`,
@@ -187,6 +272,17 @@ function peelPrefixes(argv) {
187
272
  i++; // leading VAR=value assignment
188
273
  continue;
189
274
  }
275
+ if (KEYWORD_PREFIXES.has(tok)) {
276
+ i++; // `then cmd`, `do cmd`, `! cmd`
277
+ continue;
278
+ }
279
+ if (canonicalExec(tok) === 'wsl') {
280
+ const start = wslCommandStart(argv, i);
281
+ if (start < 0)
282
+ break; // `wsl --unregister …`: wsl is the command
283
+ i = start;
284
+ continue;
285
+ }
190
286
  if (TRANSPARENT_PREFIXES.has(tok)) {
191
287
  const prefix = tok;
192
288
  i++;
@@ -213,18 +309,30 @@ function peelPrefixes(argv) {
213
309
  }
214
310
  return argv.slice(i);
215
311
  }
216
- // ---------------------------------------------------------------------------
217
- // Segment splitting & argv collection (token level)
218
- // ---------------------------------------------------------------------------
219
- /**
220
- * Split a line's tokens into segments on `;`, `&&`, `||`, `|`, `|&`, `&`.
221
- * `&` is a separator UNLESS it is the `&>` redirect spelled as two ops.
222
- */
223
312
  function splitSegments(tokens) {
224
- const segs = [];
313
+ const all = [];
225
314
  let cur = [];
315
+ let curPiped = false;
316
+ let depth = 0;
317
+ let curInSubst = false;
318
+ const close = (sep) => {
319
+ const pipeRight = sep === '|' || sep === '|&';
320
+ all.push({ tokens: cur, sep, pipeLeft: curPiped, pipeRight, inSubst: curInSubst });
321
+ cur = [];
322
+ curPiped = pipeRight;
323
+ curInSubst = depth > 0;
324
+ };
226
325
  for (let i = 0; i < tokens.length; i++) {
227
326
  const tok = tokens[i];
327
+ if (isOperator(tok)) {
328
+ if (tok.op === '(') {
329
+ const prev = tokens[i - 1];
330
+ if (depth > 0 || prev === '$' || (typeof prev === 'string' && prev.endsWith('$')))
331
+ depth++;
332
+ }
333
+ else if (tok.op === ')' && depth > 0)
334
+ depth--;
335
+ }
228
336
  if (isOperator(tok)) {
229
337
  const op = tok.op;
230
338
  if (op === '&') {
@@ -233,13 +341,11 @@ function splitSegments(tokens) {
233
341
  cur.push(tok); // part of `&>` / `&>>`
234
342
  continue;
235
343
  }
236
- segs.push(cur);
237
- cur = [];
344
+ close(op);
238
345
  continue;
239
346
  }
240
347
  if (SEPARATOR_OPS.has(op)) {
241
- segs.push(cur);
242
- cur = [];
348
+ close(op);
243
349
  continue;
244
350
  }
245
351
  cur.push(tok);
@@ -247,8 +353,182 @@ function splitSegments(tokens) {
247
353
  }
248
354
  cur.push(tok);
249
355
  }
250
- segs.push(cur);
251
- return segs.filter((s) => s.length > 0);
356
+ close(null);
357
+ return all.filter((x) => x.tokens.length > 0);
358
+ }
359
+ // ---------------------------------------------------------------------------
360
+ // Variables the command assigns itself
361
+ // ---------------------------------------------------------------------------
362
+ const ASSIGNMENT_RE = /^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/;
363
+ const VAR_REF_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
364
+ /**
365
+ * Record what a segment assigns: `X=rm`, `export D=/etc`, `for f in a b`.
366
+ * Only a value the command itself spells out counts. A value computed at run
367
+ * time (`X=$(…)`), or one that depends on a variable we do not know, FORGETS
368
+ * the name: a stale value would be worse than none.
369
+ *
370
+ * `F=.env cat $F` records nothing: there the assignment belongs to `cat`'s
371
+ * environment, and the shell expands `$F` before it takes effect.
372
+ */
373
+ function recordAssignments(seg, vars) {
374
+ const words = [];
375
+ let computed = false;
376
+ for (const tok of seg) {
377
+ if (isOperator(tok)) {
378
+ if (tok.op === '(' || tok.op === ')')
379
+ computed = true;
380
+ continue;
381
+ }
382
+ const text = tokenText(tok);
383
+ if (text !== null)
384
+ words.push(text);
385
+ }
386
+ if (words.length === 0)
387
+ return;
388
+ if (words[0] === 'for' && words[2] === 'in' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(words[1] ?? '')) {
389
+ const values = words.slice(3, 3 + MAX_LOOP_VALUES);
390
+ if (values.length > 0 && !values.some((v) => v.includes('$') || v.includes('`'))) {
391
+ vars.set(words[1], values);
392
+ }
393
+ else {
394
+ vars.delete(words[1]);
395
+ }
396
+ return;
397
+ }
398
+ let i = 0;
399
+ if (DECLARATION_BUILTINS.has(words[0])) {
400
+ i = 1;
401
+ while (i < words.length && words[i].startsWith('-'))
402
+ i++;
403
+ }
404
+ const assignments = words.slice(i);
405
+ if (assignments.length === 0 || !assignments.every((w) => ASSIGNMENT_RE.test(w)))
406
+ return;
407
+ for (const w of assignments) {
408
+ const m = ASSIGNMENT_RE.exec(w);
409
+ const value = expandText(m[2], vars);
410
+ if (computed || value.includes('$') || value.includes('`'))
411
+ vars.delete(m[1]);
412
+ else
413
+ vars.set(m[1], [value]);
414
+ }
415
+ }
416
+ /** `text` with every known single-valued variable replaced. */
417
+ function expandText(text, vars) {
418
+ if (vars.size === 0 || !text.includes('$'))
419
+ return text;
420
+ return text.replace(VAR_REF_RE, (whole, name) => {
421
+ const values = vars.get(name);
422
+ return values && values.length === 1 ? values[0] : whole;
423
+ });
424
+ }
425
+ /**
426
+ * The words of an unquoted expansion: cut on blanks, and on the separators
427
+ * the command itself put in `IFS` (`IFS=,; cmd="rm,-rf,/"; $cmd`).
428
+ */
429
+ function splitExpansion(value, ifs) {
430
+ const separators = new Set([' ', '\t', '\n', ...ifs]);
431
+ const words = [];
432
+ let cur = '';
433
+ for (const ch of value) {
434
+ if (separators.has(ch)) {
435
+ if (cur.length > 0)
436
+ words.push(cur);
437
+ cur = '';
438
+ }
439
+ else {
440
+ cur += ch;
441
+ }
442
+ }
443
+ if (cur.length > 0)
444
+ words.push(cur);
445
+ return words;
446
+ }
447
+ /**
448
+ * The segment with the variables it uses replaced by what the command
449
+ * assigned to them. A `for` variable gives one segment per value. A word that
450
+ * is exactly `$X` is split as the shell splits an unquoted expansion
451
+ * (`X="rm -rf"; $X ~`).
452
+ */
453
+ function expandSegment(seg, vars) {
454
+ if (vars.size === 0)
455
+ return [seg];
456
+ let loopVar = null;
457
+ let uses = false;
458
+ for (const tok of seg) {
459
+ const text = tokenText(tok);
460
+ if (text === null || !text.includes('$'))
461
+ continue;
462
+ for (const m of text.matchAll(VAR_REF_RE)) {
463
+ const values = vars.get(m[1]);
464
+ if (!values)
465
+ continue;
466
+ uses = true;
467
+ if (values.length > 1 && loopVar === null)
468
+ loopVar = m[1];
469
+ }
470
+ }
471
+ if (!uses)
472
+ return [seg];
473
+ const variants = loopVar === null
474
+ ? [vars]
475
+ : vars.get(loopVar).map((v) => new Map(vars).set(loopVar, [v]));
476
+ return variants.map((scope) => {
477
+ const out = [];
478
+ for (const tok of seg) {
479
+ if (typeof tok !== 'string') {
480
+ out.push(tok);
481
+ continue;
482
+ }
483
+ const exact = /^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(tok);
484
+ const values = exact ? scope.get(exact[1]) : undefined;
485
+ if (values && values.length === 1) {
486
+ const ifs = scope.get('IFS');
487
+ out.push(...splitExpansion(values[0], ifs && ifs.length === 1 ? ifs[0] : ''));
488
+ }
489
+ else {
490
+ out.push(expandText(tok, scope));
491
+ }
492
+ }
493
+ return out;
494
+ });
495
+ }
496
+ /** `word` as one shell word: quoted when a blank or an operator would split it. */
497
+ function shellWord(word) {
498
+ return /^[A-Za-z0-9_./=:@%+,~-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
499
+ }
500
+ /**
501
+ * The text a segment writes to its pipe, when its arguments spell it out
502
+ * (`echo "rm -rf ~"`, `printf 'rm -rf ~'`). `words` are that text split as
503
+ * xargs would read it; `text` is the same as one script.
504
+ */
505
+ function pipedText(seg) {
506
+ const argv = collectArgv(seg);
507
+ const eff = peelPrefixes(argv);
508
+ if (eff.length < 2 || !TEXT_WRITERS.has(canonicalExec(eff[0])))
509
+ return null;
510
+ const args = eff.slice(1).filter((a) => !/^-[neE]+$/.test(a));
511
+ if (args.length === 0 || args.some((a) => a.includes('$(') || a.includes('`')))
512
+ return null;
513
+ const text = args.join(' ');
514
+ return { text, words: text.split(/\s+/).filter(Boolean) };
515
+ }
516
+ /** A redirect target that is a descriptor or a device, not a file. */
517
+ function isRedirectNoise(target) {
518
+ return target === '' || target === '-' || /^&?\d+$/.test(target) || target.startsWith('/dev/');
519
+ }
520
+ /**
521
+ * Remember the file a redirect reads or writes. `<<<` and `<<` carry text,
522
+ * `<&` duplicates a descriptor: none of them names a file.
523
+ */
524
+ function recordRedirect(op, target, into) {
525
+ if (isRedirectNoise(target))
526
+ return;
527
+ if (op === '<' || op === '<>')
528
+ into.inputs.push(target);
529
+ if (op === '>' || op === '>>' || op === '>|' || op === '&>' || op === '&>>' || op === '>&' || op === '<>') {
530
+ into.outputs.push(target);
531
+ }
252
532
  }
253
533
  /**
254
534
  * Collect the argv of one segment: the string/glob tokens that are the
@@ -257,7 +537,7 @@ function splitSegments(tokens) {
257
537
  * substitution standing in the executable position leaves a `$(` marker so
258
538
  * the command is flagged indirect, and redirect targets are dropped.
259
539
  */
260
- function collectArgv(tokens) {
540
+ function collectArgv(tokens, redirects) {
261
541
  const argv = [];
262
542
  let substDepth = 0;
263
543
  let skipTarget = false;
@@ -286,6 +566,12 @@ function collectArgv(tokens) {
286
566
  if (argv.length > 0 && /^\d+$/.test(argv[argv.length - 1]))
287
567
  argv.pop();
288
568
  skipTarget = true;
569
+ if (redirects) {
570
+ const after = tokens[i + 1];
571
+ const target = after === undefined ? null : tokenText(after);
572
+ if (target !== null)
573
+ recordRedirect(op, target, redirects);
574
+ }
289
575
  continue;
290
576
  }
291
577
  continue; // any other op inside a segment is structural, ignore
@@ -307,10 +593,432 @@ function collectArgv(tokens) {
307
593
  }
308
594
  return argv;
309
595
  }
596
+ /**
597
+ * As `collectArgv`, but the text of every `$( … )` is dropped, also when it is
598
+ * glued to a word (`X=$(cmd)`, `a$(b)`). The token stream does not say where
599
+ * a word ends, so a word glued after a substitution reads as a word of its
600
+ * own: `wordLevelArgv` reads such a command from its words instead.
601
+ */
602
+ function plainArgv(tokens) {
603
+ const argv = [];
604
+ let substDepth = 0;
605
+ let skipTarget = false;
606
+ for (let i = 0; i < tokens.length; i++) {
607
+ const tok = tokens[i];
608
+ if (isOperator(tok)) {
609
+ const op = tok.op;
610
+ if (op === '(') {
611
+ const prev = tokens[i - 1];
612
+ if (substDepth > 0)
613
+ substDepth++;
614
+ else if (prev === '$' || (typeof prev === 'string' && prev.endsWith('$')))
615
+ substDepth = 1;
616
+ continue;
617
+ }
618
+ if (op === ')') {
619
+ if (substDepth > 0)
620
+ substDepth--;
621
+ continue;
622
+ }
623
+ if (substDepth > 0)
624
+ continue;
625
+ if (REDIRECT_OPS.has(op)) {
626
+ if (argv.length > 0 && /^\d+$/.test(argv[argv.length - 1]))
627
+ argv.pop();
628
+ skipTarget = true;
629
+ }
630
+ continue;
631
+ }
632
+ if (substDepth > 0)
633
+ continue;
634
+ const text = tokenText(tok);
635
+ if (text === null)
636
+ continue;
637
+ const next = tokens[i + 1];
638
+ if (text === '$' && isOperator(next) && next.op === '(')
639
+ continue;
640
+ if (skipTarget) {
641
+ skipTarget = false;
642
+ continue;
643
+ }
644
+ argv.push(text);
645
+ }
646
+ // An assignment of a backtick substitution is split on its spaces: join it back.
647
+ const odd = (t) => (t.split('`').length - 1) % 2 === 1;
648
+ const out = [];
649
+ for (let k = 0; k < argv.length; k++) {
650
+ out.push(argv[k]);
651
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[k]) && odd(argv[k])) {
652
+ let m = k + 1;
653
+ while (m < argv.length && !odd(argv[m]))
654
+ m++;
655
+ k = m;
656
+ }
657
+ }
658
+ return out;
659
+ }
660
+ // ---------------------------------------------------------------------------
661
+ // Words: an assignment and everything glued to it is one word
662
+ // ---------------------------------------------------------------------------
663
+ //
664
+ // shell-quote turns `$(` into operators and drops the spaces, so `X=$(a)b npm`
665
+ // and `X=$(a) b npm` give the same tokens, a `;` inside `$( … )` or backticks
666
+ // cuts the segment, and a backtick word is cut at its spaces. Bash reads an
667
+ // assignment word whole, whatever it holds: the command is the first word that
668
+ // is not one. Any other word holding a bare substitution (`npm i $(cat list)`)
669
+ // is one argument whose value is unknown: it is kept as written. The few lines
670
+ // that hold such words are read here, from the text.
671
+ /** An assignment word: `NAME=…` or `NAME+=…`, the name unquoted. */
672
+ const ASSIGNMENT_WORD = /^[A-Za-z_][A-Za-z0-9_]*\+?=/;
673
+ /** What stands before the `(` of an array assignment (`X=(a b)`). */
674
+ const ARRAY_HEAD = /^[A-Za-z_][A-Za-z0-9_]*\+?=$/;
675
+ /** Characters that end an unquoted word. */
676
+ const WORD_END = new Set([' ', '\t', '|', '&', ';', '(', ')', '<', '>']);
677
+ /** Index just past the `'` that closes a single-quoted string opened before `from`. */
678
+ function closeSingle(text, from) {
679
+ const end = text.indexOf("'", from);
680
+ return end < 0 ? text.length : end + 1;
681
+ }
682
+ /** Index just past the backtick that closes one opened before `from`. */
683
+ function closeBacktick(text, from) {
684
+ const end = findUnescapedBacktick(text, from);
685
+ return end < 0 ? text.length : end + 1;
686
+ }
687
+ /** Index just past the `"` that closes a double-quoted string opened before `from`. */
688
+ function closeDouble(text, from) {
689
+ let i = from;
690
+ while (i < text.length) {
691
+ const c = text[i];
692
+ if (c === '\\')
693
+ i += 2;
694
+ else if (c === '"')
695
+ return i + 1;
696
+ else if (c === '$' && text[i + 1] === '(')
697
+ i = closeGroup(text, i + 2, '(', ')');
698
+ else if (c === '`')
699
+ i = closeBacktick(text, i + 1);
700
+ else
701
+ i++;
702
+ }
703
+ return text.length;
704
+ }
705
+ /** Index just past the `)` / `}` that closes a `$(`, `<(` or `${` opened before `from`, quotes honoured. */
706
+ function closeGroup(text, from, open, close) {
707
+ let depth = 1;
708
+ let i = from;
709
+ while (i < text.length) {
710
+ const c = text[i];
711
+ if (c === '\\')
712
+ i += 2;
713
+ else if (c === "'")
714
+ i = closeSingle(text, i + 1);
715
+ else if (c === '"')
716
+ i = closeDouble(text, i + 1);
717
+ else if (c === '`')
718
+ i = closeBacktick(text, i + 1);
719
+ else {
720
+ if (c === open)
721
+ depth++;
722
+ else if (c === close && --depth === 0)
723
+ return i + 1;
724
+ i++;
725
+ }
726
+ }
727
+ return text.length;
728
+ }
729
+ /** Index just past the word that starts at `from`. */
730
+ function wordEnd(text, from) {
731
+ let i = from;
732
+ while (i < text.length) {
733
+ const c = text[i];
734
+ if (c === '(' && ARRAY_HEAD.test(text.slice(from, i))) {
735
+ i = closeGroup(text, i + 1, '(', ')'); // `X=(a b)`: the array is the value
736
+ continue;
737
+ }
738
+ if (WORD_END.has(c))
739
+ return i;
740
+ if (c === '\\')
741
+ i += 2;
742
+ else if (c === "'")
743
+ i = closeSingle(text, i + 1);
744
+ else if (c === '"')
745
+ i = closeDouble(text, i + 1);
746
+ else if (c === '`')
747
+ i = closeBacktick(text, i + 1);
748
+ else if (c === '$' && text[i + 1] === '(')
749
+ i = closeGroup(text, i + 2, '(', ')');
750
+ else if (c === '$' && text[i + 1] === '{')
751
+ i = closeGroup(text, i + 2, '{', '}');
752
+ else
753
+ i++;
754
+ }
755
+ return Math.min(i, text.length);
756
+ }
757
+ /** Whether a word holds a `$( … )` or backtick substitution outside quotes (the tokenizer splits it). */
758
+ function hasBareSubstitution(word) {
759
+ let i = 0;
760
+ while (i < word.length) {
761
+ const c = word[i];
762
+ if (c === '`' || (c === '$' && word[i + 1] === '('))
763
+ return true;
764
+ if (c === '\\')
765
+ i += 2;
766
+ else if (c === "'")
767
+ i = closeSingle(word, i + 1);
768
+ else if (c === '"')
769
+ i = closeDouble(word, i + 1);
770
+ else
771
+ i++;
772
+ }
773
+ return false;
774
+ }
775
+ /** A word as one entry: quotes removed, every substitution kept as written (`'a'$(b c)` → `a$(b c)`). */
776
+ function wordAsWritten(word) {
777
+ let out = '';
778
+ let i = 0;
779
+ while (i < word.length) {
780
+ const c = word[i];
781
+ let end;
782
+ if (c === '\\') {
783
+ out += word[i + 1] ?? '';
784
+ i += 2;
785
+ continue;
786
+ }
787
+ if (c === "'" || c === '"') {
788
+ end = c === "'" ? closeSingle(word, i + 1) : closeDouble(word, i + 1);
789
+ out += word.slice(i + 1, word[end - 1] === c && end - 1 > i ? end - 1 : end);
790
+ }
791
+ else if (c === '`') {
792
+ end = closeBacktick(word, i + 1);
793
+ out += word.slice(i, end);
794
+ }
795
+ else if (c === '$' && (word[i + 1] === '(' || word[i + 1] === '{')) {
796
+ end = word[i + 1] === '(' ? closeGroup(word, i + 2, '(', ')') : closeGroup(word, i + 2, '{', '}');
797
+ out += word.slice(i, end);
798
+ }
799
+ else {
800
+ out += c;
801
+ end = i + 1;
802
+ }
803
+ i = end;
804
+ }
805
+ return out;
806
+ }
807
+ /** The commands of one line, cut at `;`, `&&`, `||`, `|`, `|&`, `&` outside every word. */
808
+ function lineCommands(line) {
809
+ const out = [];
810
+ let start = 0;
811
+ let words = [];
812
+ const finish = (end, next) => {
813
+ const text = line.slice(start, end);
814
+ if (text.trim() !== '') {
815
+ out.push({ text, words: words.map((w) => ({ ...w, start: w.start - start, end: w.end - start })) });
816
+ }
817
+ words = [];
818
+ start = next;
819
+ };
820
+ let i = 0;
821
+ while (i < line.length) {
822
+ const c = line[i];
823
+ const n = line[i + 1];
824
+ if (c === ' ' || c === '\t' || c === '(' || c === ')')
825
+ i++;
826
+ else if (c === '#')
827
+ break; // a comment runs to the end of the line
828
+ else if (c === ';') {
829
+ if (n === ';' || n === '&')
830
+ i += line.startsWith(';;&', i) ? 3 : 2; // a `case` arm ends
831
+ else {
832
+ finish(i, i + 1);
833
+ i++;
834
+ }
835
+ }
836
+ else if (c === '&') {
837
+ if (n === '>')
838
+ i += line[i + 2] === '>' ? 3 : 2; // `&>`, `&>>`
839
+ else {
840
+ const len = n === '&' ? 2 : 1;
841
+ finish(i, i + len);
842
+ i += len;
843
+ }
844
+ }
845
+ else if (c === '|') {
846
+ const len = n === '|' || n === '&' ? 2 : 1;
847
+ finish(i, i + len);
848
+ i += len;
849
+ }
850
+ else if (c === '<' || c === '>') {
851
+ if (n === '(')
852
+ i = closeGroup(line, i + 2, '(', ')'); // a process substitution
853
+ else
854
+ i += n === '&' || n === '|' || n === '>' || n === '<' ? 2 : 1;
855
+ }
856
+ else {
857
+ const end = wordEnd(line, i);
858
+ const word = line.slice(i, end);
859
+ if (ASSIGNMENT_WORD.test(word) && (word.includes('$(') || word.includes('`') || word.includes('=('))) {
860
+ words.push({ start: i, end, kind: 'assignment' });
861
+ }
862
+ else if (hasBareSubstitution(word)) {
863
+ words.push({ start: i, end, kind: 'substituted' });
864
+ }
865
+ i = end > i ? end : i + 1;
866
+ }
867
+ }
868
+ finish(line.length, line.length);
869
+ return out;
870
+ }
871
+ /** An assignment word as one entry: its text, every substitution's text removed (`X=$(a)/b` → `X=$/b`). */
872
+ function collapseAssignment(word) {
873
+ let tokens;
874
+ try {
875
+ tokens = shellParse(word, SQ_ENV);
876
+ }
877
+ catch {
878
+ return word;
879
+ }
880
+ let depth = 0;
881
+ let out = '';
882
+ for (const tok of tokens) {
883
+ if (isOperator(tok)) {
884
+ if (tok.op === ')')
885
+ depth = Math.max(0, depth - 1);
886
+ else if (tok.op.endsWith('('))
887
+ depth++;
888
+ continue;
889
+ }
890
+ const text = tokenText(tok);
891
+ if (depth === 0 && text !== null)
892
+ out += text;
893
+ }
894
+ return out;
895
+ }
896
+ /** Stands for a split word while the rest of its command is tokenized. */
897
+ const placeholder = (k) => `\u0001${k}\u0001`;
898
+ const PLACEHOLDER_RE = /^\u0001(\d+)\u0001$/;
899
+ /** The argv of a command read from its words. `null` when it cannot be. */
900
+ function commandWords(cmd) {
901
+ let text = '';
902
+ let last = 0;
903
+ const words = [];
904
+ cmd.words.forEach(({ start, end, kind }, k) => {
905
+ text += cmd.text.slice(last, start) + placeholder(k);
906
+ const word = cmd.text.slice(start, end);
907
+ words.push(kind === 'assignment' ? collapseAssignment(word) : wordAsWritten(word));
908
+ last = end;
909
+ });
910
+ text += cmd.text.slice(last);
911
+ let tokens;
912
+ try {
913
+ tokens = shellParse(text, SQ_ENV);
914
+ }
915
+ catch {
916
+ return null;
917
+ }
918
+ const out = [];
919
+ for (const w of plainArgv(tokens)) {
920
+ const m = PLACEHOLDER_RE.exec(w);
921
+ if (m)
922
+ out.push(words[Number(m[1])]);
923
+ else if (w.includes('\u0001'))
924
+ return null;
925
+ else
926
+ out.push(w);
927
+ }
928
+ return out;
929
+ }
930
+ /**
931
+ * For each command of the line that holds a word the tokenizer splits (an
932
+ * assignment word with a substitution or an array, a word with a bare
933
+ * substitution), its argv read from its words, put on the first of its
934
+ * segments. Each command's text is tokenized again to learn how many segments
935
+ * it makes; `null` when that does not add up to the line's own segments (then
936
+ * nothing is put).
937
+ */
938
+ function wordLevelArgv(line, segCount) {
939
+ if (!line.includes('$(') && !line.includes('`') && !line.includes('=('))
940
+ return null;
941
+ const cmds = lineCommands(line);
942
+ if (!cmds.some((c) => c.words.length > 0))
943
+ return null;
944
+ const level = { argv: new Map(), spans: new Map() };
945
+ let k = 0;
946
+ for (const cmd of cmds) {
947
+ let segs;
948
+ try {
949
+ segs = splitSegments(shellParse(cmd.text, SQ_ENV)).length;
950
+ }
951
+ catch {
952
+ return null;
953
+ }
954
+ if (cmd.words.length > 0 && segs > 0) {
955
+ const argv = commandWords(cmd);
956
+ if (argv === null)
957
+ return null;
958
+ level.argv.set(k, argv);
959
+ level.spans.set(k, segs);
960
+ }
961
+ k += segs;
962
+ }
963
+ return k === segCount ? level : null;
964
+ }
965
+ const ARM_ENDS = new Set([';;', ';&', ';;&']);
966
+ /** Words after which the next word is in command position. */
967
+ const COMMAND_KEYWORDS = new Set(['then', 'do', 'else', 'elif', 'if', 'while', 'until', '!', '{', 'time']);
968
+ /** The grouping parentheses of one segment; `st` carries across segments and lines. */
969
+ function groupingParens(tokens, st) {
970
+ let open = 0;
971
+ let close = 0;
972
+ for (let i = 0; i < tokens.length; i++) {
973
+ const tok = tokens[i];
974
+ const prev = tokens[i - 1];
975
+ if (isOperator(tok)) {
976
+ const op = tok.op;
977
+ if (op === '<(' || op === '>(')
978
+ st.depth++;
979
+ else if (op === '(') {
980
+ const glued = typeof prev === 'string' && (prev.endsWith('$') || ARRAY_HEAD.test(prev)); // `X=$(`, `X=(`
981
+ if (st.depth > 0 || prev === '$' || glued)
982
+ st.depth++;
983
+ else if (!st.pattern)
984
+ open++; // in a pattern, the optional `(` of `(a)`
985
+ }
986
+ else if (op === ')') {
987
+ if (st.depth > 0)
988
+ st.depth--;
989
+ else if (st.pattern)
990
+ st.pattern = false;
991
+ else
992
+ close++;
993
+ }
994
+ else if (st.depth === 0 && ARM_ENDS.has(op))
995
+ st.pattern = true;
996
+ continue;
997
+ }
998
+ if (st.depth > 0)
999
+ continue;
1000
+ const text = tokenText(tok);
1001
+ if (text === null)
1002
+ continue;
1003
+ if (st.caseWords === 1)
1004
+ st.caseWords = 2;
1005
+ else if (st.caseWords === 2) {
1006
+ st.caseWords = 0;
1007
+ st.pattern = text === 'in';
1008
+ }
1009
+ else if (text === 'esac')
1010
+ st.pattern = false;
1011
+ else if (text === 'case' &&
1012
+ (prev === undefined || isOperator(prev) || (typeof prev === 'string' && COMMAND_KEYWORDS.has(prev)))) {
1013
+ st.caseWords = 1;
1014
+ }
1015
+ }
1016
+ return { open, close };
1017
+ }
310
1018
  // ---------------------------------------------------------------------------
311
1019
  // Building one EffectiveCommand
312
1020
  // ---------------------------------------------------------------------------
313
- function buildEffectiveCommand(eff, via, depth, rawText, acc) {
1021
+ function buildEffectiveCommand(eff, via, depth, rawText, acc, argv = eff) {
314
1022
  const rawExecutable = eff[0] ?? '';
315
1023
  let executable;
316
1024
  if (isIndirect(rawExecutable)) {
@@ -361,8 +1069,11 @@ function buildEffectiveCommand(eff, via, depth, rawText, acc) {
361
1069
  flagLetters,
362
1070
  longFlags,
363
1071
  raw: clip(rawText, RAW_CLIP),
1072
+ argv,
364
1073
  via,
365
1074
  depth,
1075
+ scope: acc.scope,
1076
+ parentScope: acc.parentScope,
366
1077
  };
367
1078
  }
368
1079
  // ---------------------------------------------------------------------------
@@ -415,6 +1126,131 @@ function findExecCommand(eff) {
415
1126
  return cmdTokens.join(' ');
416
1127
  }
417
1128
  // ---------------------------------------------------------------------------
1129
+ // PowerShell and cmd
1130
+ // ---------------------------------------------------------------------------
1131
+ //
1132
+ // `powershell -Command "…"`, `pwsh -c "…"` and `cmd /c …` hand their script to
1133
+ // another shell, as `bash -c` does: the script is read as commands. PowerShell
1134
+ // takes any unambiguous prefix of a parameter name, in any case.
1135
+ /** PowerShell parameters that take a value, other than the script itself. */
1136
+ const PS_VALUE_PARAMS = [
1137
+ 'executionpolicy', 'windowstyle', 'inputformat', 'outputformat', 'version', 'psconsolefile',
1138
+ 'configurationname', 'configurationfile', 'workingdirectory', 'settingsfile', 'custompipename',
1139
+ 'encodedarguments',
1140
+ ];
1141
+ const PS_VALUE_ALIASES = new Set(['ep', 'ex', 'exec', 'w', 'win', 'if', 'of', 'o', 'v', 'wd', 'ea', 'config']);
1142
+ const isPsCommand = (name) => name === 'c' || (name.length >= 3 && 'command'.startsWith(name));
1143
+ const isPsEncoded = (name) => name === 'e' || name === 'ec' || (name.length >= 2 && 'encodedcommand'.startsWith(name));
1144
+ const isPsFile = (name) => name === 'f' || (name.length >= 2 && 'file'.startsWith(name));
1145
+ const isPsValue = (name) => PS_VALUE_ALIASES.has(name) || PS_VALUE_PARAMS.some((p) => name.length >= 3 && p.startsWith(name));
1146
+ /**
1147
+ * The script of an `-EncodedCommand`: base64 of UTF-16LE text. Null when the
1148
+ * value is not that, so nothing is read into noise.
1149
+ */
1150
+ function decodePowerShell(value) {
1151
+ if (!value || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value))
1152
+ return null;
1153
+ const text = Buffer.from(value, 'base64').toString('utf16le');
1154
+ if (text.trim() === '' || /[\u0000-\u0008\u000e-\u001f\ufffd]/.test(text))
1155
+ return null;
1156
+ return text;
1157
+ }
1158
+ /**
1159
+ * The script `powershell` / `pwsh` runs, or null (a script file, nothing).
1160
+ * The words after `-Command` are the script, joined as PowerShell joins them.
1161
+ * A first word that is not a parameter is the script for Windows PowerShell
1162
+ * and a script FILE for pwsh.
1163
+ */
1164
+ function powershellScript(exe, eff) {
1165
+ for (let i = 1; i < eff.length; i++) {
1166
+ const w = eff[i];
1167
+ if (w.startsWith('-') && w.length > 1) {
1168
+ const name = w.replace(/^--?/, '').toLowerCase();
1169
+ if (isPsCommand(name))
1170
+ return i + 1 < eff.length ? eff.slice(i + 1).join(' ') : null;
1171
+ if (isPsEncoded(name))
1172
+ return decodePowerShell(eff[i + 1]);
1173
+ if (isPsFile(name))
1174
+ return null;
1175
+ if (isPsValue(name))
1176
+ i++;
1177
+ continue; // a switch: -NoProfile, -NonInteractive, -NoLogo…
1178
+ }
1179
+ return exe === 'powershell' ? eff.slice(i).join(' ') : null;
1180
+ }
1181
+ return null;
1182
+ }
1183
+ /** The command `cmd /c` (or `/k`, `/r`) runs, or null when cmd is only started. */
1184
+ function cmdScript(eff) {
1185
+ for (let i = 1; i < eff.length; i++) {
1186
+ const m = /^\/([A-Za-z])(.*)$/.exec(eff[i]);
1187
+ if (!m)
1188
+ return null;
1189
+ if (/[ckr]/i.test(m[1])) {
1190
+ const rest = (m[2] && !m[2].startsWith(':') ? [m[2]] : []).concat(eff.slice(i + 1));
1191
+ return rest.length > 0 ? rest.join(' ') : null;
1192
+ }
1193
+ }
1194
+ return null;
1195
+ }
1196
+ /**
1197
+ * Where a Windows path starts: a drive, a UNC share, or `.\`, `..\`,
1198
+ * `%VAR%\`, `$env:VAR\`, `$HOME\`, `~\` followed by a name. The name is what
1199
+ * tells `~\x` from the `~\"` of a quote escaped inside `bash -c "…"`.
1200
+ */
1201
+ const WINDOWS_PATH_START = /(?:[A-Za-z]:[\\/]|\\\\[A-Za-z0-9_.$-]+\\|(?:\.{1,2}|%[A-Za-z_][A-Za-z0-9_()]*%|\$env:[A-Za-z_][A-Za-z0-9_]*|\$HOME|~)\\(?=[A-Za-z0-9_.$%*-]))/y;
1202
+ const WORD_START_BEFORE = /[\s=(,;|&<>"]/;
1203
+ const PATH_END = /[\s"';|&<>()]/;
1204
+ /**
1205
+ * A command line with the backslashes of its Windows paths doubled, so a
1206
+ * bash reading keeps them: `type C:\Users\dev\.ssh\id_rsa` names that key in
1207
+ * PowerShell and cmd, where a bash reading sees `C:Usersdev.sshid_rsa`. A
1208
+ * single-quoted string already keeps its backslashes; a bash escape that
1209
+ * starts no such path (`\.env`, `a\ b`) is left alone.
1210
+ */
1211
+ function keepWindowsSeparators(line) {
1212
+ if (!line.includes('\\'))
1213
+ return line;
1214
+ let out = '';
1215
+ let quote = null;
1216
+ let i = 0;
1217
+ while (i < line.length) {
1218
+ const c = line[i];
1219
+ if (quote === "'") {
1220
+ out += c;
1221
+ if (c === "'")
1222
+ quote = null;
1223
+ i++;
1224
+ continue;
1225
+ }
1226
+ const atWordStart = i === 0 || WORD_START_BEFORE.test(line[i - 1]);
1227
+ if (atWordStart) {
1228
+ WINDOWS_PATH_START.lastIndex = i;
1229
+ if (WINDOWS_PATH_START.test(line)) {
1230
+ let j = i;
1231
+ while (j < line.length && !PATH_END.test(line[j])) {
1232
+ out += line[j] === '\\' ? '\\\\' : line[j];
1233
+ j++;
1234
+ }
1235
+ i = j;
1236
+ continue;
1237
+ }
1238
+ }
1239
+ if (c === '\\') {
1240
+ out += c + (line[i + 1] ?? ''); // an escape pair: `\"` closes nothing
1241
+ i += 2;
1242
+ continue;
1243
+ }
1244
+ if (c === '"')
1245
+ quote = quote === '"' ? null : '"';
1246
+ else if (c === "'" && quote === null)
1247
+ quote = "'";
1248
+ out += c;
1249
+ i++;
1250
+ }
1251
+ return out;
1252
+ }
1253
+ // ---------------------------------------------------------------------------
418
1254
  // Heredoc extraction
419
1255
  // ---------------------------------------------------------------------------
420
1256
  /** First command word of a line, with prefixes peeled and canonicalized. */
@@ -424,6 +1260,25 @@ function firstCommandWord(line) {
424
1260
  const eff = peeled.length > 0 ? peeled : parts;
425
1261
  return eff.length > 0 && !isIndirect(eff[0]) ? canonicalExec(eff[0]) : '';
426
1262
  }
1263
+ /** Words of one command text, a leading `(` dropped. */
1264
+ function wordsOf(text) {
1265
+ return text.trim().replace(/^\(+\s*/, '').split(/\s+/).filter(Boolean);
1266
+ }
1267
+ /**
1268
+ * The commands a heredoc feeds: the one that owns the `<<` (the last segment
1269
+ * before it) and, when the line pipes on (`cat <<EOF | bash`), the next one.
1270
+ */
1271
+ function heredocConsumers(before, after) {
1272
+ const owner = wordsOf(before.split(/\|\||&&|;|\||&/).pop() ?? '');
1273
+ const out = owner.length > 0 ? [owner] : [];
1274
+ const piped = /^[^|;&]*\|(?!\|)\s*([^|;&]*)/.exec(after);
1275
+ if (piped) {
1276
+ const words = wordsOf(piped[1]);
1277
+ if (words.length > 0)
1278
+ out.push(words);
1279
+ }
1280
+ return out;
1281
+ }
427
1282
  /**
428
1283
  * Pull heredoc BODIES out of the command so their content (which may contain
429
1284
  * shell operators) never corrupts segmentation, and so an interpreter-fed
@@ -458,7 +1313,12 @@ function extractHeredocs(raw) {
458
1313
  }
459
1314
  if (i < lines.length)
460
1315
  i++; // consume the terminator line
461
- heredocs.push({ interpreter, body: body.join('\n') });
1316
+ heredocs.push({
1317
+ interpreter,
1318
+ body: body.join('\n'),
1319
+ quoted: m[1] !== '',
1320
+ consumers: heredocConsumers(line.slice(0, m.index), line.slice(m.index + m[0].length)),
1321
+ });
462
1322
  }
463
1323
  return { scrubbed: out.join('\n'), heredocs };
464
1324
  }
@@ -468,18 +1328,34 @@ function extractHeredocs(raw) {
468
1328
  function captureParen(text, start) {
469
1329
  let depth = 1;
470
1330
  let i = start;
1331
+ let single = false;
1332
+ let double = false;
471
1333
  while (i < text.length) {
472
1334
  const c = text[i];
473
- if (c === '\\') {
1335
+ if (c === '\\' && !single) {
474
1336
  i += 2;
475
1337
  continue;
476
1338
  }
477
- if (c === '(')
478
- depth++;
479
- else if (c === ')') {
480
- depth--;
481
- if (depth === 0)
482
- return { inner: text.slice(start, i), end: i + 1 };
1339
+ if (c === "'" && !double) {
1340
+ single = !single;
1341
+ i++;
1342
+ continue;
1343
+ }
1344
+ if (c === '"' && !single) {
1345
+ double = !double;
1346
+ i++;
1347
+ continue;
1348
+ }
1349
+ // A parenthesis inside quotes is literal (`$(bash a.sh ')')`), so it never
1350
+ // opens or closes the substitution.
1351
+ if (!single && !double) {
1352
+ if (c === '(')
1353
+ depth++;
1354
+ else if (c === ')') {
1355
+ depth--;
1356
+ if (depth === 0)
1357
+ return { inner: text.slice(start, i), end: i + 1 };
1358
+ }
483
1359
  }
484
1360
  i++;
485
1361
  }
@@ -522,7 +1398,7 @@ function findUnescapedBacktick(text, from) {
522
1398
  * one inside DOUBLE quotes does run and is extracted. Arithmetic `$(( … ))`
523
1399
  * is skipped. Pure string scan, no tokenizer.
524
1400
  */
525
- function findSubstitutions(text) {
1401
+ export function findSubstitutions(text) {
526
1402
  const out = [];
527
1403
  let i = 0;
528
1404
  let single = false;
@@ -549,7 +1425,17 @@ function findSubstitutions(text) {
549
1425
  }
550
1426
  if (c === '$' && text[i + 1] === '(') {
551
1427
  if (text[i + 2] === '(') {
552
- i = skipArithmetic(text, i + 1);
1428
+ // `$(( … ))` is arithmetic, not a command — but the shell runs any
1429
+ // command substitution in its body (`$(( $(cmd) + 1 ))`). Skip the
1430
+ // arithmetic itself, scan its body (between `$((` and the closing `))`)
1431
+ // for substitutions, within the same cap.
1432
+ const end = skipArithmetic(text, i + 1);
1433
+ for (const sub of findSubstitutions(text.slice(i + 3, end))) {
1434
+ if (out.length >= MAX_SUBST)
1435
+ break;
1436
+ out.push(sub);
1437
+ }
1438
+ i = end;
553
1439
  continue;
554
1440
  }
555
1441
  const { inner, end } = captureParen(text, i + 2);
@@ -589,6 +1475,8 @@ function recurse(inner, via, depth, acc) {
589
1475
  acc.notes.add('command-cap');
590
1476
  return;
591
1477
  }
1478
+ if (via === 'subst' && acc.substitutions.length < MAX_SUBST_KEPT)
1479
+ acc.substitutions.push(inner);
592
1480
  analyze(inner, via, depth, acc);
593
1481
  }
594
1482
  /** Emit one best-effort command from a naive whitespace split (parse fallback). */
@@ -598,26 +1486,120 @@ function pushNaive(text, via, depth, acc) {
598
1486
  return;
599
1487
  const peeled = peelPrefixes(parts);
600
1488
  const eff = peeled.length > 0 ? peeled : parts;
601
- emit(acc, buildEffectiveCommand(eff, via, depth, text, acc));
1489
+ const cmd = buildEffectiveCommand(eff, via, depth, text, acc);
1490
+ cmd.argvFull = parts.slice();
1491
+ emit(acc, cmd);
602
1492
  }
603
- function processSegment(segTokens, via, depth, acc) {
604
- const argvFull = collectArgv(segTokens);
1493
+ /**
1494
+ * The commands of a segment that holds `case` arms: split at `;;`, the pattern
1495
+ * (up to its `)`) dropped. `null` when the segment holds none.
1496
+ */
1497
+ function caseArms(tokens, first) {
1498
+ const isArmEnd = (t) => isOperator(t) && (t.op === ';;' || t.op === ';&' || t.op === ';;&');
1499
+ if (first !== 'case' && !tokens.some(isArmEnd))
1500
+ return null;
1501
+ const arms = [];
1502
+ let cur = [];
1503
+ for (const t of tokens) {
1504
+ if (isArmEnd(t)) {
1505
+ arms.push(cur);
1506
+ cur = [];
1507
+ }
1508
+ else if (isOperator(t)) {
1509
+ if (t.op === ')')
1510
+ cur = []; // the end of an arm's pattern
1511
+ }
1512
+ else {
1513
+ const text = tokenText(t);
1514
+ if (text !== null)
1515
+ cur.push(text);
1516
+ }
1517
+ }
1518
+ arms.push(cur);
1519
+ return arms.map((a) => a.filter((w) => w !== 'esac')).filter((a) => a.length > 0);
1520
+ }
1521
+ /** The script a here-string hands to the segment (`bash <<< "…"`), or null. */
1522
+ function hereString(segTokens) {
1523
+ for (let i = 0; i < segTokens.length - 1; i++) {
1524
+ const tok = segTokens[i];
1525
+ if (isOperator(tok) && tok.op === '<<<')
1526
+ return tokenText(segTokens[i + 1]);
1527
+ }
1528
+ return null;
1529
+ }
1530
+ /** A shell given no script and no `-c`: what it reads on stdin is its program. */
1531
+ function readsScriptFromStdin(exe, eff) {
1532
+ if (!STDIN_SHELLS.has(exe))
1533
+ return false;
1534
+ for (const a of eff.slice(1)) {
1535
+ if (a === '-' || a === '--')
1536
+ continue;
1537
+ if (!a.startsWith('-'))
1538
+ return false; // a script file
1539
+ if (/^-[A-Za-z]*c[A-Za-z]*$/.test(a))
1540
+ return false; // its own program
1541
+ }
1542
+ return true;
1543
+ }
1544
+ /** The command of one segment, emitted; `undefined` when the segment has no words or the cap is hit. */
1545
+ function processSegment(segTokens, via, depth, acc, extra) {
1546
+ const argvFull = collectArgv(segTokens, acc);
605
1547
  if (argvFull.length === 0)
606
- return;
1548
+ return undefined;
607
1549
  const peeled = peelPrefixes(argvFull);
608
1550
  const eff = peeled.length > 0 ? peeled : argvFull;
609
1551
  const rawText = argvFull.join(' ');
610
- const cmd = buildEffectiveCommand(eff, via, depth, rawText, acc);
1552
+ const cmd = buildEffectiveCommand(eff, via, depth, rawText, acc, argvFull);
1553
+ const kinds = parenKinds(segTokens);
1554
+ if (kinds.subshell)
1555
+ cmd.subshell = true;
1556
+ if (kinds.substitution)
1557
+ cmd.substitution = true;
1558
+ cmd.argvFull = argvFull.slice();
1559
+ cmd.argvPlain = extra.argvPlain ?? plainArgv(segTokens);
1560
+ if (extra.piped)
1561
+ cmd.piped = true;
1562
+ if (extra.substTail)
1563
+ cmd.substTail = true;
1564
+ if (extra.parens.open > 0 || extra.parens.close > 0)
1565
+ cmd.parens = { ...extra.parens };
1566
+ const arms = caseArms(segTokens, argvFull[0]);
1567
+ if (arms)
1568
+ cmd.arms = arms;
611
1569
  if (!emit(acc, cmd))
612
- return;
1570
+ return undefined;
1571
+ recurseInto(cmd, eff, segTokens, extra.pipedInput, depth, acc);
1572
+ return cmd;
1573
+ }
1574
+ /**
1575
+ * Re-reads what the command runs as code: `bash -c`, a here-string or piped
1576
+ * text fed to a shell, `powershell -Command`, `cmd /c`, `eval`, `xargs`,
1577
+ * `find -exec`.
1578
+ */
1579
+ function recurseInto(cmd, eff, segTokens, piped, depth, acc) {
613
1580
  const exe = cmd.executable;
614
1581
  if (exe === '')
615
1582
  return; // indirect executable: nothing concrete to recurse
616
1583
  const nextDepth = depth + 1;
617
- if (SHELL_INTERPRETERS.has(exe)) {
1584
+ if (STDIN_SHELLS.has(exe) || SHELL_INTERPRETERS.has(exe)) {
618
1585
  const body = shellCArg(eff);
619
1586
  if (body !== null && body.trim().length > 0)
620
1587
  recurse(body, 'bash-c', nextDepth, acc);
1588
+ const here = hereString(segTokens);
1589
+ if (here !== null && here.trim().length > 0)
1590
+ recurse(here, 'heredoc', nextDepth, acc);
1591
+ if (piped !== null && readsScriptFromStdin(exe, eff))
1592
+ recurse(piped.text, 'bash-c', nextDepth, acc);
1593
+ }
1594
+ else if (exe === 'powershell' || exe === 'pwsh') {
1595
+ const script = powershellScript(exe, eff);
1596
+ if (script !== null && script.trim().length > 0)
1597
+ recurse(script, 'bash-c', nextDepth, acc);
1598
+ }
1599
+ else if (exe === 'cmd') {
1600
+ const script = cmdScript(eff);
1601
+ if (script !== null && script.trim().length > 0)
1602
+ recurse(script, 'bash-c', nextDepth, acc);
621
1603
  }
622
1604
  else if (exe === 'eval') {
623
1605
  const body = eff.slice(1).join(' ');
@@ -626,8 +1608,10 @@ function processSegment(segTokens, via, depth, acc) {
626
1608
  }
627
1609
  else if (exe === 'xargs') {
628
1610
  const body = xargsCommand(eff);
629
- if (body !== null && body.trim().length > 0)
630
- recurse(body, 'xargs', nextDepth, acc);
1611
+ if (body !== null && body.trim().length > 0) {
1612
+ const words = piped === null ? '' : ' ' + piped.words.map(shellWord).join(' ');
1613
+ recurse(body + words, 'xargs', nextDepth, acc);
1614
+ }
631
1615
  }
632
1616
  else if (exe === 'find') {
633
1617
  const body = findExecCommand(eff);
@@ -635,23 +1619,97 @@ function processSegment(segTokens, via, depth, acc) {
635
1619
  recurse(body, 'exec', nextDepth, acc);
636
1620
  }
637
1621
  }
1622
+ /**
1623
+ * The command lines of a script: a line break ends a command only OUTSIDE
1624
+ * quotes, and a backslash before it continues the line. Cut inside a quoted
1625
+ * string, `psql -c "DELETE FROM t⏎ WHERE id = 3"` became a DELETE without its
1626
+ * WHERE, and each line of a commit message a command of its own. A `#`
1627
+ * comment runs to the end of its line: an apostrophe in it opens nothing.
1628
+ *
1629
+ * When a quote never closes, the text is read line by line as before: what
1630
+ * follows an unbalanced quote must not vanish into one endless word.
1631
+ */
1632
+ function logicalLines(text) {
1633
+ if (!text.includes('\n'))
1634
+ return [text];
1635
+ const lines = [];
1636
+ let cur = '';
1637
+ let quote = null;
1638
+ for (let i = 0; i < text.length; i++) {
1639
+ const c = text[i];
1640
+ if (c === '\\' && quote !== "'") {
1641
+ const next = text[i + 1];
1642
+ if (next === '\n' && quote === null) {
1643
+ i++; // a continued line: the backslash and the break are dropped
1644
+ continue;
1645
+ }
1646
+ cur += c + (next ?? '');
1647
+ i++;
1648
+ continue;
1649
+ }
1650
+ if (quote === null) {
1651
+ if (c === '#' && (cur === '' || /\s$/.test(cur))) {
1652
+ const end = text.indexOf('\n', i);
1653
+ cur += text.slice(i, end < 0 ? text.length : end);
1654
+ i = (end < 0 ? text.length : end) - 1;
1655
+ continue;
1656
+ }
1657
+ if (c === '\n') {
1658
+ lines.push(cur);
1659
+ cur = '';
1660
+ continue;
1661
+ }
1662
+ if (c === '"' || c === "'")
1663
+ quote = c;
1664
+ }
1665
+ else if (c === quote) {
1666
+ quote = null;
1667
+ }
1668
+ cur += c;
1669
+ }
1670
+ lines.push(cur);
1671
+ return quote === null ? lines : text.split('\n');
1672
+ }
638
1673
  function analyze(raw, via, depth, acc) {
639
1674
  if (acc.commands.length >= MAX_COMMANDS) {
640
1675
  acc.incomplete = true;
641
1676
  acc.notes.add('command-cap');
642
1677
  return;
643
1678
  }
1679
+ const outerScope = acc.scope;
1680
+ const outerParent = acc.parentScope;
1681
+ acc.parentScope = outerScope;
1682
+ acc.scope = acc.nextScope ?? 0;
1683
+ acc.nextScope = acc.scope + 1;
1684
+ try {
1685
+ analyzeScope(raw, via, depth, acc);
1686
+ }
1687
+ finally {
1688
+ acc.scope = outerScope;
1689
+ acc.parentScope = outerParent;
1690
+ }
1691
+ }
1692
+ function analyzeScope(raw, via, depth, acc) {
644
1693
  const { scrubbed, heredocs } = extractHeredocs(raw);
1694
+ // Grouping parentheses are counted across the whole chain; those of a segment
1695
+ // without words go to the next command (`(`) or the previous one (`)`).
1696
+ const parenState = { depth: 0, pattern: false, caseWords: 0 };
1697
+ let pendingOpen = 0;
1698
+ let lastCommand;
645
1699
  // Top-level segments, one tokenize per logical line (newline is a boundary
646
- // that shell-quote otherwise flattens away).
647
- for (const line of scrubbed.split('\n')) {
1700
+ // that shell-quote otherwise flattens away). `vars` holds what this command
1701
+ // assigns itself, in the order it does.
1702
+ const vars = new Map();
1703
+ for (const line of logicalLines(scrubbed)) {
648
1704
  if (acc.commands.length >= MAX_COMMANDS)
649
1705
  break;
650
1706
  if (line.trim().length === 0)
651
1707
  continue;
1708
+ // The word-level reading below sees the same text as the tokenizer.
1709
+ const parsed = keepWindowsSeparators(line);
652
1710
  let tokens;
653
1711
  try {
654
- tokens = shellParse(line, SQ_ENV);
1712
+ tokens = shellParse(parsed, SQ_ENV);
655
1713
  }
656
1714
  catch {
657
1715
  acc.incomplete = true;
@@ -659,12 +1717,75 @@ function analyze(raw, via, depth, acc) {
659
1717
  pushNaive(line, via, depth, acc);
660
1718
  continue;
661
1719
  }
662
- for (const seg of splitSegments(tokens))
663
- processSegment(seg, via, depth, acc);
1720
+ const segs = splitSegments(tokens);
1721
+ // A `|` read while a `case` pattern is open (`a|b)`) is not a pipe.
1722
+ const counted = segs.map((seg) => {
1723
+ const patternBefore = parenState.pattern;
1724
+ const parens = groupingParens(seg.tokens, parenState);
1725
+ return { parens, patternBefore, patternAfter: parenState.pattern };
1726
+ });
1727
+ /** Whether the command made of segments `k` to `last` stands in a pipeline. */
1728
+ const pipedOn = (k, last) => (segs[k].pipeLeft && !counted[k].patternBefore) || (segs[last].pipeRight && !counted[last].patternAfter);
1729
+ const words = wordLevelArgv(parsed, segs.length);
1730
+ const tails = new Set();
1731
+ for (const [head, span] of words?.spans ?? [])
1732
+ for (let m = 1; m < span; m++)
1733
+ tails.add(head + m);
1734
+ let pipedInput = null;
1735
+ segs.forEach((seg, k) => {
1736
+ const { parens } = counted[k];
1737
+ const span = words?.spans.get(k) ?? 1;
1738
+ const variants = acc.expand ? expandSegment(seg.tokens, vars) : [seg.tokens];
1739
+ if (variants.length > 1 || variants[0] !== seg.tokens)
1740
+ acc.notes.add('var-expanded');
1741
+ // Every value of a `for` variable gives one command; they share the
1742
+ // segment's grouping parentheses: the first opens them, the last closes them.
1743
+ let first;
1744
+ let last;
1745
+ variants.forEach((variant, v) => {
1746
+ const cmd = processSegment(variant, via, depth, acc, {
1747
+ piped: pipedOn(k, k + span - 1),
1748
+ substTail: seg.inSubst || tails.has(k),
1749
+ argvPlain: words?.argv.get(k),
1750
+ parens: {
1751
+ open: v === 0 ? pendingOpen + parens.open : 0,
1752
+ close: v === variants.length - 1 ? parens.close : 0,
1753
+ },
1754
+ pipedInput,
1755
+ });
1756
+ if (cmd) {
1757
+ first ??= cmd;
1758
+ last = cmd;
1759
+ }
1760
+ });
1761
+ if (acc.expand)
1762
+ recordAssignments(seg.tokens, vars);
1763
+ pipedInput = seg.pipeRight ? pipedText(variants[0]) : null;
1764
+ if (first) {
1765
+ pendingOpen = 0;
1766
+ lastCommand = last;
1767
+ return;
1768
+ }
1769
+ pendingOpen += parens.open;
1770
+ const matched = Math.min(pendingOpen, parens.close);
1771
+ pendingOpen -= matched;
1772
+ const close = parens.close - matched;
1773
+ if (close > 0 && lastCommand) {
1774
+ lastCommand.parens = { open: lastCommand.parens?.open ?? 0, close: (lastCommand.parens?.close ?? 0) + close };
1775
+ }
1776
+ });
664
1777
  }
665
1778
  // Command substitutions anywhere in this (heredoc-stripped) command.
666
1779
  for (const inner of findSubstitutions(scrubbed))
667
1780
  recurse(inner, 'subst', depth + 1, acc);
1781
+ for (const hd of heredocs) {
1782
+ acc.heredocs.push({
1783
+ scope: acc.scope ?? 0,
1784
+ body: hd.body,
1785
+ quoted: hd.quoted,
1786
+ consumers: hd.consumers,
1787
+ });
1788
+ }
668
1789
  // Interpreter-fed heredoc bodies are code; re-normalize them.
669
1790
  for (const hd of heredocs) {
670
1791
  if (HEREDOC_INTERPRETERS.has(hd.interpreter) && hd.body.trim().length > 0) {
@@ -672,22 +1793,28 @@ function analyze(raw, via, depth, acc) {
672
1793
  }
673
1794
  }
674
1795
  }
675
- // ---------------------------------------------------------------------------
676
- // Public entry point
677
- // ---------------------------------------------------------------------------
678
1796
  /**
679
1797
  * Normalize one raw Bash command string into the effective simple commands it
680
1798
  * will run. Pure and never throws: on any failure it returns what it recovered
681
1799
  * with `incomplete: true` and a stable note.
682
1800
  */
683
- export function normalizeCommand(raw) {
684
- const acc = { commands: [], incomplete: false, notes: new Set() };
1801
+ export function normalizeCommand(raw, options = {}) {
1802
+ const acc = {
1803
+ commands: [],
1804
+ incomplete: false,
1805
+ notes: new Set(),
1806
+ heredocs: [],
1807
+ inputs: [],
1808
+ outputs: [],
1809
+ substitutions: [],
1810
+ expand: options.expandVariables !== false,
1811
+ };
685
1812
  try {
686
1813
  if (typeof raw !== 'string') {
687
- return { commands: [], incomplete: true, notes: ['invalid-input'] };
1814
+ return { commands: [], incomplete: true, notes: ['invalid-input'], substitutions: [] };
688
1815
  }
689
1816
  if (raw.trim().length === 0) {
690
- return { commands: [], incomplete: false, notes: [] };
1817
+ return { commands: [], incomplete: false, notes: [], substitutions: [] };
691
1818
  }
692
1819
  analyze(raw, 'top', 0, acc);
693
1820
  if (acc.commands.length === 0) {
@@ -711,6 +1838,10 @@ export function normalizeCommand(raw) {
711
1838
  commands: acc.commands,
712
1839
  incomplete: acc.incomplete,
713
1840
  notes: [...acc.notes],
1841
+ heredocs: acc.heredocs,
1842
+ inputs: [...new Set(acc.inputs)],
1843
+ outputs: [...new Set(acc.outputs)],
1844
+ substitutions: acc.substitutions,
714
1845
  };
715
1846
  }
716
1847
  //# sourceMappingURL=normalize.js.map